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
|
---|---|---|---|---|---|---|
231,198 |
<p>The following code compiles correctly under VC++ 8 on XPSP3, but running it causes a runtime error. </p>
<p>My header looks like:</p>
<pre><code>#include <stdexcept>
#include <iterator>
#include <list>
template<typename T>
class test_generator
{
public:
typedef T result_type;
//constructor
test_generator()
{
std::generate_n( std::back_inserter( tests ), 100, rand );
value = tests.begin();
}
result_type operator()( void )
{
if( value == tests.end() )
{
throw std::logic_error( "" );
}
return *value++;
}
private:
std::list<T> tests;
typename std::list<T>::iterator value;
};
</code></pre>
<p>My implementation looks like:</p>
<pre><code>#include <functional>
#include <algorithm>
#include <iostream>
#include <deque>
#include "test.h"
int main()
{
test_generator<double> test;
std::deque<double> tests;
std::generate_n( std::back_inserter( tests ), 10, test );
return 0;
}
</code></pre>
<p>This compiles fine, it generates an exception (not the logic_error exception defined in the header).</p>
<p>If I change the implementation to use a function instead of a functor, it works:</p>
<pre><code>int main()
{
std::deque<int> tests;
std::generate_n( std::back_inserter( tests ), 10, rand );
return 0;
}
</code></pre>
<p>What's wrong with using a functor here?</p>
|
[
{
"answer_id": 231270,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 0,
"selected": false,
"text": "<p>I haven't figured out what's causing the exception so far, but you may wish to have <code>return *value++</code> in your <code>operator()</code>. :-)</p>\n"
},
{
"answer_id": 231319,
"author": "ChrisN",
"author_id": 3853,
"author_profile": "https://Stackoverflow.com/users/3853",
"pm_score": 3,
"selected": true,
"text": "<p>The <code>test_generator</code> constructor initialises the <code>value</code> iterator to reference the first element in the <code>tests</code> list (which is a member of <code>test_generator</code>).</p>\n\n<p>When you call <code>std::generate_n</code>, a copy of the <code>test</code> is made (because the object is passed by value). In the copied object, the <code>value</code> iterator refers to the <code>tests</code> list in the original object, not the copy.</p>\n\n<p>Because of the iterator debugging checks performed in the Visual Studio STL implementation, this triggers an assertion, because an iterator obtained from one container should not be compared against an iterator from another container.</p>\n\n<p>To fix the problem, you could either implement a copy constructor for your <code>test_generator</code> class, or defer initialisation of <code>value</code> until the first time <code>operator()</code> is invoked.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14069/"
] |
The following code compiles correctly under VC++ 8 on XPSP3, but running it causes a runtime error.
My header looks like:
```
#include <stdexcept>
#include <iterator>
#include <list>
template<typename T>
class test_generator
{
public:
typedef T result_type;
//constructor
test_generator()
{
std::generate_n( std::back_inserter( tests ), 100, rand );
value = tests.begin();
}
result_type operator()( void )
{
if( value == tests.end() )
{
throw std::logic_error( "" );
}
return *value++;
}
private:
std::list<T> tests;
typename std::list<T>::iterator value;
};
```
My implementation looks like:
```
#include <functional>
#include <algorithm>
#include <iostream>
#include <deque>
#include "test.h"
int main()
{
test_generator<double> test;
std::deque<double> tests;
std::generate_n( std::back_inserter( tests ), 10, test );
return 0;
}
```
This compiles fine, it generates an exception (not the logic\_error exception defined in the header).
If I change the implementation to use a function instead of a functor, it works:
```
int main()
{
std::deque<int> tests;
std::generate_n( std::back_inserter( tests ), 10, rand );
return 0;
}
```
What's wrong with using a functor here?
|
The `test_generator` constructor initialises the `value` iterator to reference the first element in the `tests` list (which is a member of `test_generator`).
When you call `std::generate_n`, a copy of the `test` is made (because the object is passed by value). In the copied object, the `value` iterator refers to the `tests` list in the original object, not the copy.
Because of the iterator debugging checks performed in the Visual Studio STL implementation, this triggers an assertion, because an iterator obtained from one container should not be compared against an iterator from another container.
To fix the problem, you could either implement a copy constructor for your `test_generator` class, or defer initialisation of `value` until the first time `operator()` is invoked.
|
231,204 |
<p>I'm working on updating a classic ASP web page used by a number of sub-sites maintained at the company I work for.</p>
<p>The purpose of the page is to notify the user that they are leaving "our" site and going to another site. It's basically a disclaimer, but due to resource limitations and time limitations I can't add the disclaimer to every site we manage.</p>
<p>This is the crux of the problem. The current code pulls a variable from the query string to create the "continue" link in the new window. This obviously creates many problems in the form of cross site scripting.</p>
<p>How do I approach this update to eliminate most (if not all) of the cross site scripting issues using vbScript/ASP.</p>
<p>The code I'm using is below.</p>
<pre><code><%@ Language = vbScript %>
<% Option Explicit %>
<%
Dim strLink
strLink = Request.QueryString("site")
strLink = Replace(strLink, "<", "&lt")
strLink = Replace(strLink, ">", "&gt;")
strLink = Replace(strLink, chr(34), "")
strLink = Replace(strLink, "script", "", 1, -1, 1)
strLink = Replace(strLink, "onclick", "", 1, -1, 1)
strLink = Replace(strLink, "ondblclick", "", 1, -1, 1)
strLink = Replace(strLink, "onmousedown", "", 1, -1, 1)
strLink = Replace(strLink, "onmouseover", "", 1, -1, 1)
strLink = Replace(strLink, "onmousemove", "", 1, -1, 1)
strLink = Replace(strLink, "onmouseout", "", 1, -1, 1)
strLink = Replace(strLink, "onkeypress", "", 1, -1, 1)
strLink = Replace(strLink, "onkeydown", "", 1, -1, 1)
strLink = Replace(strLink, "onkeyup", "", 1, -1, 1)
strLink = Replace(strLink, "onfocus", "", 1, -1, 1)
strLink = Replace(strLink, "onblur", "", 1, -1, 1)
strLink = Replace(strLink, "&&", "")
strLink = Replace(strLink, "##", "")
strLink = Replace(strLink, "&#", "")
%>
<a href="<%= strLink %>">Continue</a>
</code></pre>
|
[
{
"answer_id": 231606,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": true,
"text": "<p>This is what I recommend for HTML sanitizing -</p>\n\n<p>HTML Whitelist is the latest in the \"cool little Python Web service thrown up on App Engine\" by my good colleague DeWitt Clinton.</p>\n\n<p>It does one thing, and it does it well. You can pass the service HTML and it will return a sanitized version.</p>\n\n<p><a href=\"http://html-whitelist.appspot.com/\" rel=\"nofollow noreferrer\">http://html-whitelist.appspot.com/</a></p>\n"
},
{
"answer_id": 235813,
"author": "Bryan Batchelder",
"author_id": 29786,
"author_profile": "https://Stackoverflow.com/users/29786",
"pm_score": 2,
"selected": false,
"text": "<p>You need to implement an approach that follows the concept of \"Positive Security Model\". You should parse the \"site\" variable and make sure it conforms explicitly to what is allowed, rather than write something that looks for what should be disallowed. This will make your approach much more resilient to attacks, especially unanticipated ones.</p>\n\n<p>I suggest writing a regex (or ask how to write such a regex on stackoverflow).</p>\n\n<p>Also, while the web service posted by Michael is pretty cool, you should evaluate if it is acceptable or not to take a dependency on such a thing.</p>\n"
},
{
"answer_id": 238316,
"author": "Toby Mills",
"author_id": 12377,
"author_profile": "https://Stackoverflow.com/users/12377",
"pm_score": 0,
"selected": false,
"text": "<p>You could add logic to continue page to ensure that it is only called by a page on one of your sites either based on url or IP address. You could also pass a time and hashed code through for added security.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3349/"
] |
I'm working on updating a classic ASP web page used by a number of sub-sites maintained at the company I work for.
The purpose of the page is to notify the user that they are leaving "our" site and going to another site. It's basically a disclaimer, but due to resource limitations and time limitations I can't add the disclaimer to every site we manage.
This is the crux of the problem. The current code pulls a variable from the query string to create the "continue" link in the new window. This obviously creates many problems in the form of cross site scripting.
How do I approach this update to eliminate most (if not all) of the cross site scripting issues using vbScript/ASP.
The code I'm using is below.
```
<%@ Language = vbScript %>
<% Option Explicit %>
<%
Dim strLink
strLink = Request.QueryString("site")
strLink = Replace(strLink, "<", "<")
strLink = Replace(strLink, ">", ">")
strLink = Replace(strLink, chr(34), "")
strLink = Replace(strLink, "script", "", 1, -1, 1)
strLink = Replace(strLink, "onclick", "", 1, -1, 1)
strLink = Replace(strLink, "ondblclick", "", 1, -1, 1)
strLink = Replace(strLink, "onmousedown", "", 1, -1, 1)
strLink = Replace(strLink, "onmouseover", "", 1, -1, 1)
strLink = Replace(strLink, "onmousemove", "", 1, -1, 1)
strLink = Replace(strLink, "onmouseout", "", 1, -1, 1)
strLink = Replace(strLink, "onkeypress", "", 1, -1, 1)
strLink = Replace(strLink, "onkeydown", "", 1, -1, 1)
strLink = Replace(strLink, "onkeyup", "", 1, -1, 1)
strLink = Replace(strLink, "onfocus", "", 1, -1, 1)
strLink = Replace(strLink, "onblur", "", 1, -1, 1)
strLink = Replace(strLink, "&&", "")
strLink = Replace(strLink, "##", "")
strLink = Replace(strLink, "&#", "")
%>
<a href="<%= strLink %>">Continue</a>
```
|
This is what I recommend for HTML sanitizing -
HTML Whitelist is the latest in the "cool little Python Web service thrown up on App Engine" by my good colleague DeWitt Clinton.
It does one thing, and it does it well. You can pass the service HTML and it will return a sanitized version.
<http://html-whitelist.appspot.com/>
|
231,226 |
<pre><code> include('adodb5/adodb.inc.php');
$myServer = "localhost";
$myUser = "root";
$myPass = "root";
$myDB = "database";
//create an instance of the ADO connection object
$conn = new COM("ADODB.Connection") or die("Cannot start ADO");
//define connection string, specify database driver
$connStr = "PROVIDER=SQLOLEDB;SERVER=".$myServer.";UID=".$myUser.";PWD=".$myPass.";DATABASE=".$myDB;
$conn->open($connStr); //Open the connection to the database
</code></pre>
<p>This is the first time I have come across the ADODB library and it supposedly is going to help me switch over from MySQL to Microsoft SQL Server. Does anyone know why i am getting this error or if there is a simpler way that does not involve playing around with the php.ini file?</p>
|
[
{
"answer_id": 231301,
"author": "Toby Allen",
"author_id": 6244,
"author_profile": "https://Stackoverflow.com/users/6244",
"pm_score": 0,
"selected": false,
"text": "<p>The most likely cause is that ADO is not correctly installed on the server. Try running the latest version of MDAC and insure it install correctly then try agin. Update your question with more information for further details. I assume you are on a Windows Server?</p>\n"
},
{
"answer_id": 234072,
"author": "Tom Haigh",
"author_id": 22224,
"author_profile": "https://Stackoverflow.com/users/22224",
"pm_score": 1,
"selected": false,
"text": "<p>It seems that you are including the PHP adodb library, but then not actually using it - instead trying to instanciate a (microsoft) ADO COM object.</p>\n\n<p>If you don't have ADO installed / working from PHP you could try using an ODBC DSN-less connection like:</p>\n\n<pre><code>include('adodb5/adodb.inc.php');\n\n$myServer = \"localhost\";\n$myUser = \"root\";\n$myPass = \"root\";\n$myDB = \"database\";\n\n\n$db = ADONewConnection('odbc_mssql');\n$dsn = \"Driver={SQL Server};Server={{$myServer}};Database={{$myDB}};\";\n$db->Connect($dsn,$myUser,$myPass) or die($db->ErrorMsg()); \n\nif (!$rs = $db->Execute('select * from table')) die($db->ErrorMsg());\n\nwhile (!$rs->EOF) {\n print_r($rs->fields);\n $rs->MoveNext();\n}\n\n$rs->Close(); \n</code></pre>\n\n<p>Also see other connection examples at <a href=\"http://phplens.com/adodb/code.initialization.html#connect_ex\" rel=\"nofollow noreferrer\">http://phplens.com/adodb/code.initialization.html#connect_ex</a></p>\n"
},
{
"answer_id": 24908244,
"author": "snowflake",
"author_id": 223073,
"author_profile": "https://Stackoverflow.com/users/223073",
"pm_score": 2,
"selected": false,
"text": "<p>If you want to use following code:</p>\n\n<pre><code>new COM(\"ADODB.Connection\") \n</code></pre>\n\n<p>you need to enable \"COM support\" in PHP, such using the com_dotnet extension (php_com_dotnet.dll) <a href=\"http://php.net//manual/fr/com.installation.php\" rel=\"nofollow\">How to install COM extension</a></p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231226",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
```
include('adodb5/adodb.inc.php');
$myServer = "localhost";
$myUser = "root";
$myPass = "root";
$myDB = "database";
//create an instance of the ADO connection object
$conn = new COM("ADODB.Connection") or die("Cannot start ADO");
//define connection string, specify database driver
$connStr = "PROVIDER=SQLOLEDB;SERVER=".$myServer.";UID=".$myUser.";PWD=".$myPass.";DATABASE=".$myDB;
$conn->open($connStr); //Open the connection to the database
```
This is the first time I have come across the ADODB library and it supposedly is going to help me switch over from MySQL to Microsoft SQL Server. Does anyone know why i am getting this error or if there is a simpler way that does not involve playing around with the php.ini file?
|
If you want to use following code:
```
new COM("ADODB.Connection")
```
you need to enable "COM support" in PHP, such using the com\_dotnet extension (php\_com\_dotnet.dll) [How to install COM extension](http://php.net//manual/fr/com.installation.php)
|
231,229 |
<p>I have source in a bunch of subdirectories like:</p>
<pre><code>src/widgets/apple.cpp
src/widgets/knob.cpp
src/tests/blend.cpp
src/ui/flash.cpp
</code></pre>
<p>In the root of the project I want to generate a single Makefile using a rule like:</p>
<pre><code>%.o: %.cpp
$(CC) -c $<
build/test.exe: build/widgets/apple.o build/widgets/knob.o build/tests/blend.o src/ui/flash.o
$(LD) build/widgets/apple.o .... build/ui/flash.o -o build/test.exe
</code></pre>
<p>When I try this it does not find a rule for build/widgets/apple.o. Can I change something so that the %.o: %.cpp is used when it needs to make build/widgets/apple.o ?</p>
|
[
{
"answer_id": 231251,
"author": "stephanea",
"author_id": 8776,
"author_profile": "https://Stackoverflow.com/users/8776",
"pm_score": 0,
"selected": false,
"text": "<p>Usually, you create a Makefile in each subdirectory, and write in the top-level Makefile to call make in the subdirectories. </p>\n\n<p>This page may help: <a href=\"http://www.gnu.org/software/make/\" rel=\"nofollow noreferrer\">http://www.gnu.org/software/make/</a></p>\n"
},
{
"answer_id": 231418,
"author": "JesperE",
"author_id": 13051,
"author_profile": "https://Stackoverflow.com/users/13051",
"pm_score": 7,
"selected": true,
"text": "<p>The reason is that your rule</p>\n\n<pre><code>%.o: %.cpp\n ...\n</code></pre>\n\n<p>expects the .cpp file to reside in the same directory as the .o your building. Since test.exe in your case depends on build/widgets/apple.o (etc), make is expecting apple.cpp to be build/widgets/apple.cpp.</p>\n\n<p>You can use VPATH to resolve this:</p>\n\n<pre><code>VPATH = src/widgets\n\nBUILDDIR = build/widgets\n\n$(BUILDDIR)/%.o: %.cpp\n ...\n</code></pre>\n\n<p>When attempting to build \"build/widgets/apple.o\", make will search for apple.cpp <strong>in VPATH</strong>. Note that the build rule has to use special variables in order to access the actual filename make finds:</p>\n\n<pre><code>$(BUILDDIR)/%.o: %.cpp\n $(CC) $< -o $@\n</code></pre>\n\n<p>Where \"$<\" expands to the path where make located the first dependency.</p>\n\n<p>Also note that this will build all the .o files in build/widgets. If you want to build the binaries in different directories, you can do something like</p>\n\n<pre><code>build/widgets/%.o: %.cpp\n ....\n\nbuild/ui/%.o: %.cpp\n ....\n\nbuild/tests/%.o: %.cpp\n ....\n</code></pre>\n\n<p>I would recommend that you use \"<a href=\"http://www.gnu.org/software/make/manual/make.html#Canned-Recipes\" rel=\"noreferrer\">canned command sequences</a>\" in order to avoid repeating the actual compiler build rule:</p>\n\n<pre><code>define cc-command\n$(CC) $(CFLAGS) $< -o $@\nendef\n</code></pre>\n\n<p>You can then have multiple rules like this:</p>\n\n<pre><code>build1/foo.o build1/bar.o: %.o: %.cpp\n $(cc-command)\n\nbuild2/frotz.o build2/fie.o: %.o: %.cpp\n $(cc-command)\n</code></pre>\n"
},
{
"answer_id": 1427198,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Thing is <code>$@</code> will include the entire (relative) path to the source file which is in turn used to construct the object name (and thus its relative path)</p>\n\n<p>We use:</p>\n\n<pre><code>#####################\n# rules to build the object files\n$(OBJDIR_1)/%.o: %.c\n @$(ECHO) \"$< -> $@\"\n @test -d $(OBJDIR_1) || mkdir -pm 775 $(OBJDIR_1)\n @test -d $(@D) || mkdir -pm 775 $(@D)\n @-$(RM) $@\n $(CC) $(CFLAGS) $(CFLAGS_1) $(ALL_FLAGS) $(ALL_DEFINES) $(ALL_INCLUDEDIRS:%=-I%) -c $< -o $@\n</code></pre>\n\n<p>This creates an object directory with name specified in <code>$(OBJDIR_1)</code>\nand subdirectories according to subdirectories in source.</p>\n\n<p>For example (assume objs as toplevel object directory), in Makefile:</p>\n\n<pre><code>widget/apple.cpp\ntests/blend.cpp\n</code></pre>\n\n<p>results in following object directory:</p>\n\n<pre><code>objs/widget/apple.o\nobjs/tests/blend.o\n</code></pre>\n"
},
{
"answer_id": 1430336,
"author": "Beta",
"author_id": 128940,
"author_profile": "https://Stackoverflow.com/users/128940",
"pm_score": 2,
"selected": false,
"text": "<p>This will do it without painful manipulation or multiple command sequences:</p>\n\n<pre>\nbuild/%.o: src/%.cpp\nsrc/%.o: src/%.cpp\n%.o:\n $(CC) -c $< -o $@\n\nbuild/test.exe: build/widgets/apple.o build/widgets/knob.o build/tests/blend.o src/ui/flash.o\n $(LD) $^ -o $@\n</pre>\n\n<p>JasperE has explained why \"%.o: %.cpp\" won't work; this version has one pattern rule (%.o:) with commands and no prereqs, and two pattern rules (build/%.o: and src/%.o:) with prereqs and no commands. (Note that I put in the src/%.o rule to deal with src/ui/flash.o, assuming that wasn't a typo for build/ui/flash.o, so if you don't need it you can leave it out.)</p>\n\n<p>build/test.exe needs build/widgets/apple.o,<br>\nbuild/widgets/apple.o looks like build/%.o, so it needs src/%.cpp (in this case src/widgets/apple.cpp),<br>\nbuild/widgets/apple.o also looks like %.o, so it executes the CC command and uses the prereqs it just found (namely src/widgets/apple.cpp) to build the target (build/widgets/apple.o)</p>\n"
},
{
"answer_id": 2484343,
"author": "Manzill0",
"author_id": 298128,
"author_profile": "https://Stackoverflow.com/users/298128",
"pm_score": 6,
"selected": false,
"text": "<p>This does the trick:</p>\n\n<pre><code>CC := g++\nLD := g++\n\nMODULES := widgets test ui\nSRC_DIR := $(addprefix src/,$(MODULES))\nBUILD_DIR := $(addprefix build/,$(MODULES))\n\nSRC := $(foreach sdir,$(SRC_DIR),$(wildcard $(sdir)/*.cpp))\nOBJ := $(patsubst src/%.cpp,build/%.o,$(SRC))\nINCLUDES := $(addprefix -I,$(SRC_DIR))\n\nvpath %.cpp $(SRC_DIR)\n\ndefine make-goal\n$1/%.o: %.cpp\n $(CC) $(INCLUDES) -c $$< -o $$@\nendef\n\n.PHONY: all checkdirs clean\n\nall: checkdirs build/test.exe\n\nbuild/test.exe: $(OBJ)\n $(LD) $^ -o $@\n\n\ncheckdirs: $(BUILD_DIR)\n\n$(BUILD_DIR):\n @mkdir -p $@\n\nclean:\n @rm -rf $(BUILD_DIR)\n\n$(foreach bdir,$(BUILD_DIR),$(eval $(call make-goal,$(bdir))))\n</code></pre>\n\n<p>This Makefile assumes you have your include files in the source directories. Also it checks if the build directories exist, and creates them if they do not exist.</p>\n\n<p>The last line is the most important. It creates the implicit rules for each build using the function <code>make-goal</code>, and it is not necessary write them one by one</p>\n\n<p>You can also add automatic dependency generation, using <a href=\"http://make.paulandlesley.org/autodep.html\" rel=\"noreferrer\">Tromey's way</a></p>\n"
},
{
"answer_id": 17783161,
"author": "iLya",
"author_id": 2594223,
"author_profile": "https://Stackoverflow.com/users/2594223",
"pm_score": 3,
"selected": false,
"text": "<p>This is another trick.</p>\n\n<p>In main 'Makefile' define SRCDIR for each source dir and include 'makef.mk' for each value of SRCDIR. In each source dir put file 'files.mk' with list of source files and compile options for some of them. In main 'Makefile' one can define compile options and exclude files for each value of SRCDIR.</p>\n\n<p>Makefile:</p>\n\n<pre><code>PRG := prog-name\n\nOPTIMIZE := -O2 -fomit-frame-pointer\n\nCFLAGS += -finline-functions-called-once\nLDFLAGS += -Wl,--gc-section,--reduce-memory-overheads,--relax\n\n\n.DEFAULT_GOAL := hex\n\nOBJDIR := obj\n\nMK_DIRS := $(OBJDIR)\n\n\nSRCDIR := .\ninclude makef.mk\n\nSRCDIR := crc\nCFLAGS_crc := -DCRC8_BY_TABLE -DMODBUS_CRC_BY_TABLE\nASFLAGS_crc := -DCRC8_BY_TABLE -DMODBUS_CRC_BY_TABLE\ninclude makef.mk\n\n################################################################\n\nCC := avr-gcc -mmcu=$(MCU_TARGET) -I.\nOBJCOPY := avr-objcopy\nOBJDUMP := avr-objdump\n\nC_FLAGS := $(CFLAGS) $(REGS) $(OPTIMIZE)\nCPP_FLAGS := $(CPPFLAGS) $(REGS) $(OPTIMIZE)\nAS_FLAGS := $(ASFLAGS)\nLD_FLAGS := $(LDFLAGS) -Wl,-Map,$(OBJDIR)/$(PRG).map\n\n\nC_OBJS := $(C_SRC:%.c=$(OBJDIR)/%.o)\nCPP_OBJS := $(CPP_SRC:%.cpp=$(OBJDIR)/%.o)\nAS_OBJS := $(AS_SRC:%.S=$(OBJDIR)/%.o)\n\nC_DEPS := $(C_OBJS:%=%.d)\nCPP_DEPS := $(CPP_OBJS:%=%.d)\nAS_DEPS := $(AS_OBJS:%=%.d)\n\nOBJS := $(C_OBJS) $(CPP_OBJS) $(AS_OBJS)\nDEPS := $(C_DEPS) $(CPP_DEPS) $(AS_DEPS)\n\n\nhex: $(PRG).hex\nlst: $(PRG).lst\n\n\n$(OBJDIR)/$(PRG).elf : $(OBJS)\n $(CC) $(C_FLAGS) $(LD_FLAGS) $^ -o $@\n\n%.lst: $(OBJDIR)/%.elf\n -@rm $@ 2> /dev/nul\n $(OBJDUMP) -h -s -S $< > $@\n\n%.hex: $(OBJDIR)/%.elf\n -@rm $@ 2> /dev/nul\n $(OBJCOPY) -j .text -j .data -O ihex $< $@\n\n\n$(C_OBJS) : $(OBJDIR)/%.o : %.c Makefile\n $(CC) -MMD -MF [email protected] -c $(C_FLAGS) $(C_FLAGS_$(call clear_name,$<)) $< -o $@\n @sed -e 's,.*:,SRC_FILES += ,g' < [email protected] > [email protected]\n @sed -e \"\\$$s/$$/ $(subst /,\\/,$(dir $<))files.mk\\n/\" < [email protected] >> [email protected]\n @sed -e 's,^[^:]*: *,,' -e 's,^[ \\t]*,,' -e 's, \\\\$$,,' -e 's,$$, :,' < [email protected] >> [email protected]\n -@rm -f [email protected]\n\n$(CPP_OBJS) : $(OBJDIR)/%.o : %.cpp Makefile\n $(CC) -MMD -MF [email protected] -c $(CPP_FLAGS) $(CPP_FLAGS_$(call clear_name,$<)) $< -o $@\n @sed -e 's,.*:,SRC_FILES += ,g' < [email protected] > [email protected]\n @sed -e \"\\$$s/$$/ $(subst /,\\/,$(dir $<))files.mk\\n/\" < [email protected] >> [email protected]\n @sed -e 's,^[^:]*: *,,' -e 's,^[ \\t]*,,' -e 's, \\\\$$,,' -e 's,$$, :,' < [email protected] >> [email protected]\n -@rm -f [email protected]\n\n$(AS_OBJS) : $(OBJDIR)/%.o : %.S Makefile\n $(CC) -MMD -MF [email protected] -c $(AS_FLAGS) $(AS_FLAGS_$(call clear_name,$<)) $< -o $@\n @sed -e 's,.*:,SRC_FILES += ,g' < [email protected] > [email protected]\n @sed -e \"\\$$s/$$/ $(subst /,\\/,$(dir $<))files.mk\\n/\" < [email protected] >> [email protected]\n @sed -e 's,^[^:]*: *,,' -e 's,^[ \\t]*,,' -e 's, \\\\$$,,' -e 's,$$, :,' < [email protected] >> [email protected]\n -@rm -f [email protected]\n\n\nclean:\n -@rm -rf $(OBJDIR)/$(PRG).elf\n -@rm -rf $(PRG).lst $(OBJDIR)/$(PRG).map\n -@rm -rf $(PRG).hex $(PRG).bin $(PRG).srec\n -@rm -rf $(PRG)_eeprom.hex $(PRG)_eeprom.bin $(PRG)_eeprom.srec\n -@rm -rf $(MK_DIRS:%=%/*.o) $(MK_DIRS:%=%/*.o.d)\n -@rm -f tags cscope.out\n\n# -rm -rf $(OBJDIR)/*\n# -rm -rf $(OBJDIR)\n# -rm $(PRG)\n\n\ntag: tags\ntags: $(SRC_FILES)\n if [ -e tags ] ; then ctags -u $? ; else ctags $^ ; fi\n cscope -U -b $^\n\n\n# include dep. files\nifneq \"$(MAKECMDGOALS)\" \"clean\"\n-include $(DEPS)\nendif\n\n\n# Create directory\n$(shell mkdir $(MK_DIRS) 2>/dev/null)\n</code></pre>\n\n<p>makef.mk</p>\n\n<pre><code>SAVE_C_SRC := $(C_SRC)\nSAVE_CPP_SRC := $(CPP_SRC)\nSAVE_AS_SRC := $(AS_SRC)\n\nC_SRC :=\nCPP_SRC :=\nAS_SRC :=\n\n\ninclude $(SRCDIR)/files.mk\nMK_DIRS += $(OBJDIR)/$(SRCDIR)\n\n\nclear_name = $(subst /,_,$(1))\n\n\ndefine rename_var\n$(2)_$(call clear_name,$(SRCDIR))_$(call clear_name,$(1)) := \\\n $($(subst _,,$(2))_$(call clear_name,$(SRCDIR))) $($(call clear_name,$(1)))\n$(call clear_name,$(1)) :=\nendef\n\n\ndefine proc_lang\n\nORIGIN_SRC_FILES := $($(1)_SRC)\n\nifneq ($(strip $($(1)_ONLY_FILES)),)\n$(1)_SRC := $(filter $($(1)_ONLY_FILES),$($(1)_SRC))\nelse\n\nifneq ($(strip $(ONLY_FILES)),)\n$(1)_SRC := $(filter $(ONLY_FILES),$($(1)_SRC))\nelse\n$(1)_SRC := $(filter-out $(EXCLUDE_FILES),$($(1)_SRC))\nendif\n\nendif\n\n$(1)_ONLY_FILES :=\n$(foreach name,$($(1)_SRC),$(eval $(call rename_var,$(name),$(1)_FLAGS)))\n$(foreach name,$(ORIGIN_SRC_FILES),$(eval $(call clear_name,$(name)) :=))\n\nendef\n\n\n$(foreach lang,C CPP AS, $(eval $(call proc_lang,$(lang))))\n\n\nEXCLUDE_FILES :=\nONLY_FILES :=\n\n\nSAVE_C_SRC += $(C_SRC:%=$(SRCDIR)/%)\nSAVE_CPP_SRC += $(CPP_SRC:%=$(SRCDIR)/%)\nSAVE_AS_SRC += $(AS_SRC:%=$(SRCDIR)/%)\n\nC_SRC := $(SAVE_C_SRC)\nCPP_SRC := $(SAVE_CPP_SRC)\nAS_SRC := $(SAVE_AS_SRC)\n</code></pre>\n\n<p>./files.mk</p>\n\n<pre><code>C_SRC := main.c\nCPP_SRC :=\nAS_SRC := timer.S\n\nmain.c += -DDEBUG\n</code></pre>\n\n<p>./crc/files.mk</p>\n\n<pre><code>C_SRC := byte-modbus-crc.c byte-crc8.c\nAS_SRC := modbus-crc.S crc8.S modbus-crc-table.S crc8-table.S\n\nbyte-modbus-crc.c += --std=gnu99\nbyte-crc8.c += --std=gnu99\n</code></pre>\n"
},
{
"answer_id": 21355129,
"author": "Amaury Bouchard",
"author_id": 3235911,
"author_profile": "https://Stackoverflow.com/users/3235911",
"pm_score": 2,
"selected": false,
"text": "<p>Here is my solution, inspired from Beta's answer. It's simpler than the other proposed solutions</p>\n\n<p>I have a project with several C files, stored in many subdirectories.\nFor example:</p>\n\n<pre><code>src/lib.c\nsrc/aa/a1.c\nsrc/aa/a2.c\nsrc/bb/b1.c\nsrc/cc/c1.c\n</code></pre>\n\n<p>Here is my Makefile (in the <code>src/</code> directory):</p>\n\n<pre><code># make -> compile the shared library \"libfoo.so\"\n# make clean -> remove the library file and all object files (.o)\n# make all -> clean and compile\nSONAME = libfoo.so\nSRC = lib.c \\\n aa/a1.c \\\n aa/a2.c \\\n bb/b1.c \\\n cc/c1.c\n# compilation options\nCFLAGS = -O2 -g -W -Wall -Wno-unused-parameter -Wbad-function-cast -fPIC\n# linking options\nLDFLAGS = -shared -Wl,-soname,$(SONAME)\n\n# how to compile individual object files\nOBJS = $(SRC:.c=.o)\n.c.o:\n $(CC) $(CFLAGS) -c $< -o $@\n\n.PHONY: all clean\n\n# library compilation\n$(SONAME): $(OBJS) $(SRC)\n $(CC) $(OBJS) $(LDFLAGS) -o $(SONAME)\n\n# cleaning rule\nclean:\n rm -f $(OBJS) $(SONAME) *~\n\n# additional rule\nall: clean lib\n</code></pre>\n\n<p>This example works fine for a shared library, and it should be very easy to adapt for any compilation process.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231229",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7743/"
] |
I have source in a bunch of subdirectories like:
```
src/widgets/apple.cpp
src/widgets/knob.cpp
src/tests/blend.cpp
src/ui/flash.cpp
```
In the root of the project I want to generate a single Makefile using a rule like:
```
%.o: %.cpp
$(CC) -c $<
build/test.exe: build/widgets/apple.o build/widgets/knob.o build/tests/blend.o src/ui/flash.o
$(LD) build/widgets/apple.o .... build/ui/flash.o -o build/test.exe
```
When I try this it does not find a rule for build/widgets/apple.o. Can I change something so that the %.o: %.cpp is used when it needs to make build/widgets/apple.o ?
|
The reason is that your rule
```
%.o: %.cpp
...
```
expects the .cpp file to reside in the same directory as the .o your building. Since test.exe in your case depends on build/widgets/apple.o (etc), make is expecting apple.cpp to be build/widgets/apple.cpp.
You can use VPATH to resolve this:
```
VPATH = src/widgets
BUILDDIR = build/widgets
$(BUILDDIR)/%.o: %.cpp
...
```
When attempting to build "build/widgets/apple.o", make will search for apple.cpp **in VPATH**. Note that the build rule has to use special variables in order to access the actual filename make finds:
```
$(BUILDDIR)/%.o: %.cpp
$(CC) $< -o $@
```
Where "$<" expands to the path where make located the first dependency.
Also note that this will build all the .o files in build/widgets. If you want to build the binaries in different directories, you can do something like
```
build/widgets/%.o: %.cpp
....
build/ui/%.o: %.cpp
....
build/tests/%.o: %.cpp
....
```
I would recommend that you use "[canned command sequences](http://www.gnu.org/software/make/manual/make.html#Canned-Recipes)" in order to avoid repeating the actual compiler build rule:
```
define cc-command
$(CC) $(CFLAGS) $< -o $@
endef
```
You can then have multiple rules like this:
```
build1/foo.o build1/bar.o: %.o: %.cpp
$(cc-command)
build2/frotz.o build2/fie.o: %.o: %.cpp
$(cc-command)
```
|
231,250 |
<p>How would you write a non-recursive algorithm to compute <code>n!</code>?</p>
|
[
{
"answer_id": 231254,
"author": "JohnMcG",
"author_id": 1674,
"author_profile": "https://Stackoverflow.com/users/1674",
"pm_score": 3,
"selected": false,
"text": "<p>Rewrite the recursive solution as a loop.</p>\n"
},
{
"answer_id": 231255,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 3,
"selected": false,
"text": "<pre><code>public double factorial(int n) {\n double result = 1;\n for(double i = 2; i<=n; ++i) {\n result *= i;\n }\n return result;\n}\n</code></pre>\n"
},
{
"answer_id": 231263,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 2,
"selected": false,
"text": "<pre><code>long fact(int n) {\n long x = 1;\n for(int i = 1; i <= n; i++) {\n x *= i;\n }\n return x;\n}\n</code></pre>\n"
},
{
"answer_id": 231264,
"author": "MrDatabase",
"author_id": 22471,
"author_profile": "https://Stackoverflow.com/users/22471",
"pm_score": -1,
"selected": false,
"text": "<pre><code>int fact(int n){\n int r = 1;\n for(int i = 1; i <= n; i++) r *= i;\n return r;\n}\n</code></pre>\n"
},
{
"answer_id": 231268,
"author": "EBGreen",
"author_id": 1358,
"author_profile": "https://Stackoverflow.com/users/1358",
"pm_score": 0,
"selected": false,
"text": "<p>Pseudo code</p>\n\n<pre><code>total = 1\nFor i = 1 To n\n total *= i\nNext\n</code></pre>\n"
},
{
"answer_id": 231269,
"author": "stephanea",
"author_id": 8776,
"author_profile": "https://Stackoverflow.com/users/8776",
"pm_score": 1,
"selected": false,
"text": "<pre><code>fac = 1 ; \nfor( i = 1 ; i <= n ; i++){\n fac = fac * i ;\n}\n</code></pre>\n"
},
{
"answer_id": 231272,
"author": "Elie",
"author_id": 23249,
"author_profile": "https://Stackoverflow.com/users/23249",
"pm_score": 2,
"selected": false,
"text": "<pre><code>int total = 1\nloop while n > 1\n total = total * n\n n--\nend while\n</code></pre>\n"
},
{
"answer_id": 231273,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 4,
"selected": false,
"text": "<p>in pseudocode</p>\n\n<pre><code>ans = 1\nfor i = n down to 2\n ans = ans * i\nnext\n</code></pre>\n"
},
{
"answer_id": 231276,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": 1,
"selected": false,
"text": "<pre><code>public int factorialNonRecurse(int n) {\n int product = 1;\n\n for (int i = 2; i <= n; i++) {\n product *= i;\n }\n\n return product;\n}\n</code></pre>\n"
},
{
"answer_id": 231300,
"author": "Federico A. Ramponi",
"author_id": 18770,
"author_profile": "https://Stackoverflow.com/users/18770",
"pm_score": 3,
"selected": false,
"text": "<p>Unless you have arbitrary-length integers like in Python, I would store the precomputed values of factorial() in an array of about 20 longs, and use the argument n as the index. The rate of growth of n! is rather high, and computing 20! or 21! you'll get an overflow anyway, even on 64-bit machines.</p>\n"
},
{
"answer_id": 231331,
"author": "BradC",
"author_id": 21398,
"author_profile": "https://Stackoverflow.com/users/21398",
"pm_score": 5,
"selected": false,
"text": "<p>Since an Int32 is going to overflow on anything bigger than 12! anyway, just do:</p>\n\n<pre><code>public int factorial(int n) {\n int[] fact = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, \n 362880, 3628800, 39916800, 479001600};\n return fact[n];\n}\n</code></pre>\n"
},
{
"answer_id": 231458,
"author": "David Frenkel",
"author_id": 28747,
"author_profile": "https://Stackoverflow.com/users/28747",
"pm_score": 0,
"selected": false,
"text": "<p>assuming you wanted to be able to deal with some really huge numbers, I would code it as follows. This implementation would be for if you wanted a decent amount of speed for common cases (low numbers), but wanted to be able to handle some super hefty calculations. I would consider this the most complete answer in theory. In practice I doubt you would need to compute such large factorials for anything other than a homework problem</p>\n\n<pre><code>#define int MAX_PRECALCFACTORIAL = 13;\n\npublic double factorial(int n) {\n ASSERT(n>0);\n int[MAX_PRECALCFACTORIAL] fact = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, \n 362880, 3628800, 39916800, 479001600};\n if(n < MAX_PRECALCFACTORIAL)\n return (double)fact[n];\n\n //else we are at least n big\n double total = (float)fact[MAX_PRECALCFACTORIAL-1]\n for(int i = MAX_PRECALCFACTORIAL; i <= n; i++)\n {\n total *= (double)i; //cost of incrimenting a double often equal or more than casting\n }\n return total;\n\n}\n</code></pre>\n"
},
{
"answer_id": 231569,
"author": "PhirePhly",
"author_id": 20082,
"author_profile": "https://Stackoverflow.com/users/20082",
"pm_score": 2,
"selected": false,
"text": "<p>Here's the precomputed function, except actually correct. As been said, 13! overflows, so there is no point in calculating such a small range of values. 64 bit is larger, but I would expect the range to still be rather reasonable.</p>\n\n<pre><code>int factorial(int i) {\n static int factorials[] = {1, 1, 2, 6, 24, 120, 720, \n 5040, 40320, 362880, 3628800, 39916800, 479001600};\n if (i<0 || i>12) {\n fprintf(stderr, \"Factorial input out of range\\n\");\n exit(EXIT_FAILURE); // You could also return an error code here\n }\n return factorials[i];\n} \n</code></pre>\n\n<p>Source: <a href=\"http://ctips.pbwiki.com/Factorial\" rel=\"nofollow noreferrer\">http://ctips.pbwiki.com/Factorial</a></p>\n"
},
{
"answer_id": 232070,
"author": "Wedge",
"author_id": 332,
"author_profile": "https://Stackoverflow.com/users/332",
"pm_score": 3,
"selected": false,
"text": "<p>In the interests of science I ran some profiling on various implementations of algorithms to compute factorials. I created iterative, look up table, and recursive implementations of each in C# and C++. I limited the maximum input value to 12 or less, since 13! is greater than 2^32 (the maximum value capable of being held in a 32-bit int). Then, I ran each function 10 million times, cycling through the possible input values (i.e. incrementing i from 0 to 10 million, using i modulo 13 as the input parameter).</p>\n\n<p>Here are the relative run-times for different implementations normalized to the iterative C++ figures:</p>\n\n<pre><code> C++ C#\n---------------------\nIterative 1.0 1.6\nLookup .28 1.1\nRecursive 2.4 2.6\n</code></pre>\n\n<p>And, for completeness, here are the relative run-times for implementations using 64-bit integers and allowing input values up to 20:</p>\n\n<pre><code> C++ C#\n---------------------\nIterative 1.0 2.9\nLookup .16 .53\nRecursive 1.9 3.9\n</code></pre>\n"
},
{
"answer_id": 236930,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 0,
"selected": false,
"text": "<p>I would use memoization. That way you can write the method as a recursive call, and still get most of the benefits of a linear implementation.</p>\n"
},
{
"answer_id": 297903,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<pre><code>long fact(int n)\n{\n long fact=1;\n while(n>1)\n fact*=n--;\n return fact;\n}\n\nlong fact(int n)\n{\n for(long fact=1;n>1;n--)\n fact*=n;\n return fact;\n}\n</code></pre>\n"
},
{
"answer_id": 480011,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>At run time this is non-recursive. At compile time it is recursive. Run-time performance should be O(1).</p>\n\n<pre><code>//Note: many compilers have an upper limit on the number of recursive templates allowed.\n\ntemplate <int N>\nstruct Factorial \n{\n enum { value = N * Factorial<N - 1>::value };\n};\n\ntemplate <>\nstruct Factorial<0> \n{\n enum { value = 1 };\n};\n\n// Factorial<4>::value == 24\n// Factorial<0>::value == 1\nvoid foo()\n{\n int x = Factorial<4>::value; // == 24\n int y = Factorial<0>::value; // == 1\n}\n</code></pre>\n"
},
{
"answer_id": 481729,
"author": "dangerouslyfacetious",
"author_id": 56815,
"author_profile": "https://Stackoverflow.com/users/56815",
"pm_score": 2,
"selected": false,
"text": "<p>I love the pythonic solution to this:</p>\n\n<pre><code>def fact(n): return (reduce(lambda x, y: x * y, xrange(1, n+1)))\n</code></pre>\n"
},
{
"answer_id": 11887670,
"author": "nyanshak",
"author_id": 1587737,
"author_profile": "https://Stackoverflow.com/users/1587737",
"pm_score": 0,
"selected": false,
"text": "<p>Iterative:</p>\n\n<pre><code>int answer = 1;\nfor (int i = 1; i <= n; i++){\n answer *= i;\n}\n</code></pre>\n\n<p>Or... using tail recursion in Haskell:</p>\n\n<pre><code>factorial x =\n tailFact x 1\n where tailFact 0 a = a\n tailFact n a = tailFact (n - 1) (n * a)\n</code></pre>\n\n<p>What tail recursion does in this case is uses an accumulator to avoid piling on stack calls. </p>\n\n<p>Reference: <a href=\"http://jxs.me/2010/06/28/tail-recursion-haskell/\" rel=\"nofollow\">Tail Recursion in Haskell</a> </p>\n"
},
{
"answer_id": 13034901,
"author": "Matt",
"author_id": 833083,
"author_profile": "https://Stackoverflow.com/users/833083",
"pm_score": -1,
"selected": false,
"text": "<p>Recursively using JavaScript with caching.</p>\n\n<pre><code>var fc = []\nfunction factorial( n ) {\n return fc[ n ] || ( ( n - 1 && n != 0 ) && \n ( fc[ n ] = n * factorial( n - 1 ) ) ) || 1;\n}\n</code></pre>\n"
},
{
"answer_id": 35744745,
"author": "Developer Marius Žilėnas",
"author_id": 1737819,
"author_profile": "https://Stackoverflow.com/users/1737819",
"pm_score": 0,
"selected": false,
"text": "<p>Non recursive factorial in Java. This solution is with custom iterator (to demonstrate iterator use :) ). </p>\n\n<pre><code>/** \n * Non recursive factorial. Iterator version,\n */\npackage factiterator;\n\nimport java.math.BigInteger;\nimport java.util.Iterator;\n\npublic class FactIterator\n{ \n public static void main(String[] args)\n {\n Iterable<BigInteger> fact = new Iterable<BigInteger>()\n {\n @Override\n public Iterator<BigInteger> iterator()\n {\n return new Iterator<BigInteger>()\n {\n BigInteger i = BigInteger.ONE;\n BigInteger total = BigInteger.ONE;\n\n @Override\n public boolean hasNext()\n {\n return true;\n }\n\n @Override\n public BigInteger next()\n { \n total = total.multiply(i);\n i = i.add(BigInteger.ONE);\n return total;\n }\n\n @Override\n public void remove()\n {\n throw new UnsupportedOperationException();\n }\n };\n }\n };\n int i = 1;\n for (BigInteger f : fact)\n {\n System.out.format(\"%d! is %s%n\", i++, f);\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 56945554,
"author": "Wael Assaf",
"author_id": 6241797,
"author_profile": "https://Stackoverflow.com/users/6241797",
"pm_score": 1,
"selected": false,
"text": "<p>For a non-recursive approach, it can't get simpler than this</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>int fac(int num) {\n int f = 1;\n for (int i = num; i > 0; i--)\n f *= i;\n return f;\n}\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
How would you write a non-recursive algorithm to compute `n!`?
|
Since an Int32 is going to overflow on anything bigger than 12! anyway, just do:
```
public int factorial(int n) {
int[] fact = {1, 1, 2, 6, 24, 120, 720, 5040, 40320,
362880, 3628800, 39916800, 479001600};
return fact[n];
}
```
|
231,259 |
<p>I'm trying to delete a directory that contains XML files from a remote computer. My code compiles and runs fine, but when I go to get a list of XML files in the path I specify, it is not returning anything. Am I missing something permission wise? </p>
<p>I have ran it from my computer logged on as myself and from another computer logged on as a different user. Both accounts have full control over the directory that contains the XML files.</p>
<p>I'm using .NET 2.0.</p>
<pre><code> static void Main(string[] args) {
string directory, ext = ".xml"; // have tried xml and .xml
if (args.Length != 1) {
// do absolutely nothing if we do not exactly 1 argument
} else {
Console.WriteLine("Argument accepted.");
directory = args[0];
// make sure the directory passed is valid
if (ValidateDirectory(directory)) {
Console.WriteLine("Directory is valid.");
DeleteFiles(directory, ext);
}
}
Console.WriteLine("Done.");
}
static bool ValidateDirectory(string d) {
return Regex.IsMatch(d, @""); // I removed my regex - it validates properly
}
static void DeleteFiles(string d, string ext) {
DirectoryInfo di;
FileInfo[] fi;
di = new DirectoryInfo(d);
fi = di.GetFiles(ext);
Console.WriteLine("Number of files = " + fi.Length + ".");
foreach (FileInfo f in fi) {
try {
Console.WriteLine(f.FullName);
f.Delete();
} catch (Exception ex) {
// do nothing when there is an exception
// just do not want it to quit
Console.WriteLine(ex.ToString());
}
}
}
</code></pre>
|
[
{
"answer_id": 231294,
"author": "Ely",
"author_id": 30488,
"author_profile": "https://Stackoverflow.com/users/30488",
"pm_score": 0,
"selected": false,
"text": "<p>I assume you are passing in a network path?\nDoes it fail when you run the program on a local path?\nDoes this line:\nfi = di.GetFiles(ext);\nReturn any fileInfo objects?</p>\n\n<p>You probably just have something small wrong that can be fixed by some debugging.</p>\n"
},
{
"answer_id": 231296,
"author": "Travis Collins",
"author_id": 30460,
"author_profile": "https://Stackoverflow.com/users/30460",
"pm_score": 3,
"selected": true,
"text": "<p>I think you should be using *.xml instead of simply .xml. But I also concur with Kyralessa, test on your local machine first, then add in the complexity of going across a network.</p>\n"
},
{
"answer_id": 231297,
"author": "Brett McCann",
"author_id": 9293,
"author_profile": "https://Stackoverflow.com/users/9293",
"pm_score": 2,
"selected": false,
"text": "<p>in DeleteFiles, you have the following line:</p>\n\n<p>fi = di.GetFiles(ext);</p>\n\n<p>where ext is the extension you pass in, which I believe is just '.xml'. Get files is looking for any files called '.xml'. GetFiles takes wildcards, which I believe is what you are intending to do. Put an asterisk (*) at the front and give that a try.</p>\n\n<p>-Brett</p>\n"
},
{
"answer_id": 231309,
"author": "Ryan Abbott",
"author_id": 27908,
"author_profile": "https://Stackoverflow.com/users/27908",
"pm_score": 0,
"selected": false,
"text": "<p>What are you passing in as the argument? Are you using a Mapped Drive or the direct reference (i.e. //server/folder)?</p>\n\n<p>Instead of your ValidateDirectory, you should use Directory.Exists(directory) just to see if it can see the directory at all.</p>\n"
},
{
"answer_id": 231320,
"author": "Ryan Rodemoyer",
"author_id": 1444511,
"author_profile": "https://Stackoverflow.com/users/1444511",
"pm_score": 1,
"selected": false,
"text": "<p><strong>Follow up:</strong></p>\n\n<p>I needed to use *.xml (should have known that!) and now it works.</p>\n\n<p>This site is great!</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1444511/"
] |
I'm trying to delete a directory that contains XML files from a remote computer. My code compiles and runs fine, but when I go to get a list of XML files in the path I specify, it is not returning anything. Am I missing something permission wise?
I have ran it from my computer logged on as myself and from another computer logged on as a different user. Both accounts have full control over the directory that contains the XML files.
I'm using .NET 2.0.
```
static void Main(string[] args) {
string directory, ext = ".xml"; // have tried xml and .xml
if (args.Length != 1) {
// do absolutely nothing if we do not exactly 1 argument
} else {
Console.WriteLine("Argument accepted.");
directory = args[0];
// make sure the directory passed is valid
if (ValidateDirectory(directory)) {
Console.WriteLine("Directory is valid.");
DeleteFiles(directory, ext);
}
}
Console.WriteLine("Done.");
}
static bool ValidateDirectory(string d) {
return Regex.IsMatch(d, @""); // I removed my regex - it validates properly
}
static void DeleteFiles(string d, string ext) {
DirectoryInfo di;
FileInfo[] fi;
di = new DirectoryInfo(d);
fi = di.GetFiles(ext);
Console.WriteLine("Number of files = " + fi.Length + ".");
foreach (FileInfo f in fi) {
try {
Console.WriteLine(f.FullName);
f.Delete();
} catch (Exception ex) {
// do nothing when there is an exception
// just do not want it to quit
Console.WriteLine(ex.ToString());
}
}
}
```
|
I think you should be using \*.xml instead of simply .xml. But I also concur with Kyralessa, test on your local machine first, then add in the complexity of going across a network.
|
231,288 |
<p>I have started using Jython as it seems to be a excellent language, and has proved to be so far.</p>
<p>I am using dom4j to manipulate and retrieve data from the DOM of a bunch of HTML files I have on disk. I have wrote the below script to check threw the DOM using Xpath for <strong>H1</strong> tags and grab text, if a <strong>H1</strong> tag is not present in the DOM it then searches for the <strong>title</strong> tag and grabs the text from that.</p>
<p>I am very new to Jython but I am sure there is way to perform the required task a lot more graceful than the below method, If I am right in thinking this, is there someone that can show me a better way to do it?</p>
<pre><code>elemHolder = dom.createXPath('//xhtml:h1')
elemHolder.setNamespaceURIs(map)
elem = elemHolder.selectSingleNode(dom)
if elem != None:
h1 = elem.getText()
else:
elemHolder = dom.createXPath('//xhtml:title')
elemHolder.setNamespaceURIs(map)
elem = elemHolder.selectSingleNode(dom)
if elem != None:
title = elem.getText()
else:
title = "Page does not contain a H1 or title tag"
</code></pre>
<p>If anyone could help it would be great. Cheers</p>
|
[
{
"answer_id": 231335,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 3,
"selected": true,
"text": "<p>How about this (I don't claim to know much about Python, by the way, but this looks like an obvious first step):</p>\n\n<pre><code>for path in ('//xhtml:h1', '//xhtml:title'):\n elemHolder = dom.createXPath(path)\n elemHolder.namespaceURIs = map\n elem = elemHolder.selectSingleNode(dom)\n if elem is not None:\n return (elem.localName, elem.text)\n\nreturn (None, \"Page does not contain h1 or title tag\")\n</code></pre>\n"
},
{
"answer_id": 231395,
"author": "RailsSon",
"author_id": 30786,
"author_profile": "https://Stackoverflow.com/users/30786",
"pm_score": 0,
"selected": false,
"text": "<p>That looks like it would work perfectly, only other thing is. I will be passing the value to a database and depending what was found its put in the appropriate column.</p>\n\n<p>If its a H1 tag it will put it in the H1 column and if its a title tag it will get put in the title column.</p>\n\n<p>Is there a way to detemine what tag was found also? Does this make sense?</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30786/"
] |
I have started using Jython as it seems to be a excellent language, and has proved to be so far.
I am using dom4j to manipulate and retrieve data from the DOM of a bunch of HTML files I have on disk. I have wrote the below script to check threw the DOM using Xpath for **H1** tags and grab text, if a **H1** tag is not present in the DOM it then searches for the **title** tag and grabs the text from that.
I am very new to Jython but I am sure there is way to perform the required task a lot more graceful than the below method, If I am right in thinking this, is there someone that can show me a better way to do it?
```
elemHolder = dom.createXPath('//xhtml:h1')
elemHolder.setNamespaceURIs(map)
elem = elemHolder.selectSingleNode(dom)
if elem != None:
h1 = elem.getText()
else:
elemHolder = dom.createXPath('//xhtml:title')
elemHolder.setNamespaceURIs(map)
elem = elemHolder.selectSingleNode(dom)
if elem != None:
title = elem.getText()
else:
title = "Page does not contain a H1 or title tag"
```
If anyone could help it would be great. Cheers
|
How about this (I don't claim to know much about Python, by the way, but this looks like an obvious first step):
```
for path in ('//xhtml:h1', '//xhtml:title'):
elemHolder = dom.createXPath(path)
elemHolder.namespaceURIs = map
elem = elemHolder.selectSingleNode(dom)
if elem is not None:
return (elem.localName, elem.text)
return (None, "Page does not contain h1 or title tag")
```
|
231,318 |
<p>When I first discovered the Strategy pattern, I was amazed of the seemingly endless possibilities it offered to me and my programs. I could better encapsulate my models' behaviour and even exchange this behaviour on the fly. But the strategy could also be used to to provide traits and payload to the containing object - data that was declared in a superclass. Life was fine.</p>
<pre><code>class MyMonsterAI { float const see_radius_; virtual void attack () = 0; /* .. */ };
class ElveAI { ElveAI() : see_radius_(150.0f) {} /* ... */ };
class CycloneAI { CycloneAI() : see_radius_(50.0f) {} /* ... */ };
class Monster { MyMonsterAI* ai_; };
</code></pre>
<p>And along came the Policy pattern and it would allow me even greater flexibility in supplying parameters to a containing class - whole classes, outfitted however I liked, albeit dynamically exchanging the behaviour... that was not too easy (unless part of the policy was to have a strategy!).</p>
<pre><code>class MyMonsterTrait { typedef typename ElveAI AI; };
template< class MonsterTrait >
class Monster : public MonsterTrait::AI
{
void idle (void) { attack(); }
};
</code></pre>
<p>Both patterns seem to be very powerful to me and I like to use both, in different circumstances. But I'm not sure if there are particular/typical/more-practical applications for either at some situations.</p>
<p><strong>I am wondering: where do you use strategies and where policies? Where are either better suited?</strong> </p>
|
[
{
"answer_id": 231343,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 3,
"selected": false,
"text": "<p>I thought they were the <a href=\"http://en.wikipedia.org/wiki/Strategy_pattern\" rel=\"noreferrer\">same thing</a>.</p>\n"
},
{
"answer_id": 231392,
"author": "Adam Davis",
"author_id": 2915,
"author_profile": "https://Stackoverflow.com/users/2915",
"pm_score": 6,
"selected": true,
"text": "<p>Policies are largely set at compile time, while strategies are set at runtime. Further, policies are generally a C++ concept, and apply only to a minority of other languages(for example D), while strategy pattern is available to many (most?) object oriented languages, and languages that treat functions as first class citizens like python.</p>\n\n<p>That being said:</p>\n\n<ul>\n<li><p>A policy, being determined at compile time, is generally only useful for special situations where you want different application logic on a per-binary basis. For instance you might develop software that is slightly customized for each customer, whether via a web interface, or by hand, this would be a policy-based pattern.</p></li>\n<li><p>A strategy is determined at runtime, and in fact can be changed on the fly. For instance you might have software which implements a different user interface and logic for the salesforce than for the support group, but they all have to deal with the same customer and licensing info so rather than having two separately maintained apps you simply have one app whose interface changes as needed.</p></li>\n</ul>\n\n<p>-Adam</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25965/"
] |
When I first discovered the Strategy pattern, I was amazed of the seemingly endless possibilities it offered to me and my programs. I could better encapsulate my models' behaviour and even exchange this behaviour on the fly. But the strategy could also be used to to provide traits and payload to the containing object - data that was declared in a superclass. Life was fine.
```
class MyMonsterAI { float const see_radius_; virtual void attack () = 0; /* .. */ };
class ElveAI { ElveAI() : see_radius_(150.0f) {} /* ... */ };
class CycloneAI { CycloneAI() : see_radius_(50.0f) {} /* ... */ };
class Monster { MyMonsterAI* ai_; };
```
And along came the Policy pattern and it would allow me even greater flexibility in supplying parameters to a containing class - whole classes, outfitted however I liked, albeit dynamically exchanging the behaviour... that was not too easy (unless part of the policy was to have a strategy!).
```
class MyMonsterTrait { typedef typename ElveAI AI; };
template< class MonsterTrait >
class Monster : public MonsterTrait::AI
{
void idle (void) { attack(); }
};
```
Both patterns seem to be very powerful to me and I like to use both, in different circumstances. But I'm not sure if there are particular/typical/more-practical applications for either at some situations.
**I am wondering: where do you use strategies and where policies? Where are either better suited?**
|
Policies are largely set at compile time, while strategies are set at runtime. Further, policies are generally a C++ concept, and apply only to a minority of other languages(for example D), while strategy pattern is available to many (most?) object oriented languages, and languages that treat functions as first class citizens like python.
That being said:
* A policy, being determined at compile time, is generally only useful for special situations where you want different application logic on a per-binary basis. For instance you might develop software that is slightly customized for each customer, whether via a web interface, or by hand, this would be a policy-based pattern.
* A strategy is determined at runtime, and in fact can be changed on the fly. For instance you might have software which implements a different user interface and logic for the salesforce than for the support group, but they all have to deal with the same customer and licensing info so rather than having two separately maintained apps you simply have one app whose interface changes as needed.
-Adam
|
231,321 |
<p>I cant' figure out how to reference the current instance object defined by the XAML file in the XAML file.</p>
<p>I have a converter that I want to send in the current instance as the parameter object.</p>
<pre><code>{Binding Path=<bindingObject>, Converter={x:Static namespace:Converter.Instance}, ConverterParameter=this}
</code></pre>
<p>In this code this is converted to a string instead of a reference to the current instance object.</p>
<p>Thanks</p>
<p>John</p>
|
[
{
"answer_id": 231446,
"author": "Omer van Kloeten",
"author_id": 4979,
"author_profile": "https://Stackoverflow.com/users/4979",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried using the <a href=\"http://msdn.microsoft.com/en-us/library/ms743599.aspx\" rel=\"nofollow noreferrer\"><code>RelativeSource</code> markup extension</a>? You can use <code>Self</code> there.</p>\n"
},
{
"answer_id": 231500,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": 2,
"selected": false,
"text": "<p>According to the <a href=\"http://msdn.microsoft.com/en-us/library/ms752347.aspx#current_record_pointers\" rel=\"nofollow noreferrer\">Data Binding Overview</a>, you can use the \"/\" to indicate the current item. You can then navigate up and down the tree as needs be using the following type syntaxes:</p>\n\n<pre><code><Button Content=\"{Binding }\" />\n<Button Content=\"{Binding Path=/}\" />\n<Button Content=\"{Binding Path=/Description}\" /> \n</code></pre>\n"
},
{
"answer_id": 232095,
"author": "decasteljau",
"author_id": 12082,
"author_profile": "https://Stackoverflow.com/users/12082",
"pm_score": 2,
"selected": false,
"text": "<p>Technically, the ConverterParameter is not a DependencyProperty, so you can't bind to it. It would be nice to do a ConverterParameter={Binding ElementName=this}, but you can't bind to a non-dependency property.</p>\n\n<p>But, someone figure it out how to do it <a href=\"http://rauscheronline.de/item/2008/08/using-databinding-in-a-converterparameter\" rel=\"nofollow noreferrer\">here</a>. This is however a bit complicated.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231321",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9331/"
] |
I cant' figure out how to reference the current instance object defined by the XAML file in the XAML file.
I have a converter that I want to send in the current instance as the parameter object.
```
{Binding Path=<bindingObject>, Converter={x:Static namespace:Converter.Instance}, ConverterParameter=this}
```
In this code this is converted to a string instead of a reference to the current instance object.
Thanks
John
|
According to the [Data Binding Overview](http://msdn.microsoft.com/en-us/library/ms752347.aspx#current_record_pointers), you can use the "/" to indicate the current item. You can then navigate up and down the tree as needs be using the following type syntaxes:
```
<Button Content="{Binding }" />
<Button Content="{Binding Path=/}" />
<Button Content="{Binding Path=/Description}" />
```
|
231,323 |
<p>Anyone know off the top of their heads how to convert a System.Xml.XmlNode to System.Xml.Linq.XNode?</p>
|
[
{
"answer_id": 231353,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 0,
"selected": false,
"text": "<p>I don't think there is, but why would you need to? Each is the lowest 'leaf' of the Xml structure for different ways of reading the document.</p>\n\n<p>If you use Linq to Xml and XDocument you'll have all the linq-style syntax and new functionality, but really all that's about selecting a node.</p>\n\n<p>Once you have the element that you're dealing with, why do you need to switch?</p>\n"
},
{
"answer_id": 231412,
"author": "Chris Shaffer",
"author_id": 6744,
"author_profile": "https://Stackoverflow.com/users/6744",
"pm_score": 5,
"selected": true,
"text": "<p>I've never tried, but my first thought would be something like:</p>\n\n<pre><code>XmlNode myNode;\nXNode translatedNode = XDocument.Parse(myNode.OuterXml);\n</code></pre>\n"
},
{
"answer_id": 828179,
"author": "RandomNickName42",
"author_id": 67819,
"author_profile": "https://Stackoverflow.com/users/67819",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"http://blogs.msdn.com/ericwhite/archive/2008/12/22/convert-xelement-to-xmlnode-and-convert-xmlnode-to-xelement.aspx\" rel=\"noreferrer\">Eric White's blog</a> is the place to be for cool XML/XLINQ conversions and such. I know this question pre-date's the post but I found it while looking at some other Q, so maybe people still come across this a fair amount. His blog has plenty of optimized LINQ, like I suspect the .Parse() call for the origional responce is non-optimal, well in-fact I know it is not. </p>\n\n<p>Parse is going to require that the XML be loaded up in one shot, Eric used extension methods which process the XML conversion with XmlReader/Writer's. Those methods are able to stream the input, so if your XML is of any substantional size, you have to use them. </p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21909/"
] |
Anyone know off the top of their heads how to convert a System.Xml.XmlNode to System.Xml.Linq.XNode?
|
I've never tried, but my first thought would be something like:
```
XmlNode myNode;
XNode translatedNode = XDocument.Parse(myNode.OuterXml);
```
|
231,327 |
<p>I want to use the <a href="http://simplehtmldom.sourceforge.net/manual_api.htm" rel="noreferrer">php simple HTML DOM parser</a> to grab the image, title, date, and description from each article on a page full of articles. When looking at the API I notice it has a set_callback which Sets a callback function. However im not sure what this does or how I would use it? In one of the examples its used to call a function which strips out some stuff, im wondering if you have to use this to call all functions?</p>
<p>I guess im wondering why I use this, and what does it do as I have never come across a callback function before!</p>
|
[
{
"answer_id": 231339,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 6,
"selected": true,
"text": "<p>Here's a basic callback function example:</p>\n\n<pre><code><?php\n\nfunction thisFuncTakesACallback($callbackFunc)\n{\n echo \"I'm going to call $callbackFunc!<br />\";\n $callbackFunc();\n}\n\nfunction thisFuncGetsCalled()\n{\n echo \"I'm a callback function!<br />\";\n}\n\nthisFuncTakesACallback( 'thisFuncGetsCalled' );\n?>\n</code></pre>\n\n<p>You can call a function that has its name stored in a variable like this: <strong>$variable()</strong>.</p>\n\n<p>So, in the above example, we pass the name of the <strong>thisFuncGetsCalled</strong> function to <strong>thisFuncTakesACallback()</strong> which then calls the function passed in.</p>\n"
},
{
"answer_id": 231347,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 2,
"selected": false,
"text": "<p>A callback function will use that function on whatever data is returned by a particular method.</p>\n\n<p>I'm not sure how this particular library works, but it could be something as simple as:</p>\n\n<pre><code>$html = file_get_html('http://example.com');\n$html->set_callback('make_bold');\n$html->find('#title'); // returns an array\n\nfunction make_bold($results) {\n// make the first result bold\n return '<b>'.$results[0].'</b>';\n}\n</code></pre>\n\n<p>ie, The function \"<code>make_bold()</code>\" will be run on any data found. Again, I'm not sure how this particular library works (ie, what methods the callback function will get called on)</p>\n"
},
{
"answer_id": 231874,
"author": "troelskn",
"author_id": 18180,
"author_profile": "https://Stackoverflow.com/users/18180",
"pm_score": 2,
"selected": false,
"text": "<p>A callback is either a function, an object instance' method, or a static method on a class. Either way, it's kind of a function pointer. In some languages, functions are a specific type. So you could assign a function to a variable. These are generally called function oriented languages. A good example is Javascript.</p>\n\n<p>In PHP, a callback can be any of:</p>\n\n<pre><code>$fn = 'foo'; // => foo()\n$fn = array($obj, 'foo'); // => $obj->foo()\n$fn = array('Foo', 'bar'); // => Foo::bar()\n</code></pre>\n\n<p>See the manual entry for <a href=\"http://docs.php.net/is_callable\" rel=\"nofollow noreferrer\"><code>is_callable</code></a>.</p>\n\n<p>You can invoke a callback with the rather verbose function <a href=\"http://docs.php.net/manual/en/function.call-user-func.php\" rel=\"nofollow noreferrer\"><code>call_user_func</code></a>.</p>\n"
},
{
"answer_id": 45677437,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Defination</strong></p>\n\n<p>A callbacks/callable is a simple function(either it is anonymous or named function) that we pass to another function as function parameter which in the result returns that passed function.</p>\n\n<p><strong>Example</strong></p>\n\n<pre><code>function iWillReturnCallback($callBackHere){\n return $callBackHere;\n}\n\nfunction iAmCallBack(){\n echo \"I am returned with the help of another function\";\n}\n\niWillReturnCallback(iAmCallBack());\n\n//--Output -> I am returned with the help of another function\n</code></pre>\n\n<p><strong>Don't be confused</strong></p>\n\n<p>There are some default functions in php that accepts the name of the callback function as a string in their parameter because of avoiding conflicting between the constant name and function name. So don't be confused in these kind of things.</p>\n"
},
{
"answer_id": 47279271,
"author": "Deepak Bawa",
"author_id": 4520304,
"author_profile": "https://Stackoverflow.com/users/4520304",
"pm_score": 0,
"selected": false,
"text": "<p>With <code>PHP 5.3</code>, you can now do this:</p>\n\n<pre><code>function doIt($callback) { $callback(); }\n\ndoIt(function() {\n // this will be done\n});\n</code></pre>\n\n<p>Finally, a nice way to do it. A great addition to <code>PHP</code>, because callbacks are awesome.</p>\n"
},
{
"answer_id": 70610212,
"author": "MaXi32",
"author_id": 841677,
"author_profile": "https://Stackoverflow.com/users/841677",
"pm_score": 0,
"selected": false,
"text": "<p>The aim is to call a function that we want eg: <code>secretCode()</code> but we want to use another function as a <code>helper</code> or <code>service</code> to call it for us:</p>\n<pre><code><?php\n \n // $call parameter can be anything\n function callBackServiceCenter($call)\n {\n echo "[callBackServiceCenter]: Hey, this is callBackServiceCenter function <br>We have received your command to call your requested function and we are now calling it for you! <br />";\n // Below is the part where it will call our secretCode()'s function\n $call();\n // And we can print other things after the secretCode()'s function has been executed:\n echo "[callBackServiceCenter]: Thank you for using our service at callBackServiceCenter. Have a nice day!<br />";\n }\n \n function secretCode()\n {\n echo "[secretCode]: Hey, this is secretCode function. Your secret code is 12345<br />";\n }\n \n callBackServiceCenter( 'secretCode' );\n?>\n</code></pre>\n<p>Output:</p>\n<pre><code>[callBackServiceCenter]: Hey, this is callBackServiceCenter function\nWe have received your command to call your requested function and we are now calling it for you!\n[secretCode]: Hey, this is secretCode function. Your secret code is 12345\n[callBackServiceCenter]: Thank you for using our service at callBackServiceCenter. Have a nice day!\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231327",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28241/"
] |
I want to use the [php simple HTML DOM parser](http://simplehtmldom.sourceforge.net/manual_api.htm) to grab the image, title, date, and description from each article on a page full of articles. When looking at the API I notice it has a set\_callback which Sets a callback function. However im not sure what this does or how I would use it? In one of the examples its used to call a function which strips out some stuff, im wondering if you have to use this to call all functions?
I guess im wondering why I use this, and what does it do as I have never come across a callback function before!
|
Here's a basic callback function example:
```
<?php
function thisFuncTakesACallback($callbackFunc)
{
echo "I'm going to call $callbackFunc!<br />";
$callbackFunc();
}
function thisFuncGetsCalled()
{
echo "I'm a callback function!<br />";
}
thisFuncTakesACallback( 'thisFuncGetsCalled' );
?>
```
You can call a function that has its name stored in a variable like this: **$variable()**.
So, in the above example, we pass the name of the **thisFuncGetsCalled** function to **thisFuncTakesACallback()** which then calls the function passed in.
|
231,340 |
<p>In a project I am working on, Apache is set up to only forward requests that come in as /prefix/* to mongrel. How can I tell ruby on rails to generate all URLs with that prefix? </p>
<p>I have the routes set up for forward to the correct controller action by doing this:</p>
<pre><code>map.connect 'sfc/:controller/:action'
</code></pre>
<p>but that doesn't seem to affect the way that the url writer generates the URLs.</p>
<p>Any ideas?</p>
|
[
{
"answer_id": 231417,
"author": "Can Berk Güder",
"author_id": 2119,
"author_profile": "https://Stackoverflow.com/users/2119",
"pm_score": 2,
"selected": false,
"text": "<p>The <code>RAILS_RELATIVE_URL_ROOT</code> environment variable should do the trick, though I haven't tried it myself.</p>\n"
},
{
"answer_id": 231752,
"author": "Mike Breen",
"author_id": 22346,
"author_profile": "https://Stackoverflow.com/users/22346",
"pm_score": 1,
"selected": false,
"text": "<p>What about using the :path_prefix option:</p>\n\n<pre><code>map.connect ':controller/:action', :path_prefix => 'sfc'\n</code></pre>\n"
},
{
"answer_id": 235311,
"author": "Matt Burke",
"author_id": 29691,
"author_profile": "https://Stackoverflow.com/users/29691",
"pm_score": 2,
"selected": false,
"text": "<p>You probably have another route (probably one of the default routes at the bottom of routes.rb) that URL generation is using in preference to the sfc-prefixed match. For example, if you have</p>\n\n<pre><code>map.connect \"sfc/:controller/:action\"\nmap.connect \":controller/:action/:id\"\n</code></pre>\n\n<p>then <code>url_for(:controller => 'x', :action => 'y', :id => 3)</code> will return <code>\"/x/y/3\"</code>. If you change it to</p>\n\n<pre><code>map.connect \"sfc/:controller/:action\"\nmap.connect \"sfc/:controller/:action/:id\"\n</code></pre>\n\n<p>you should get <code>\"/sfc/x/y/3\"</code>.</p>\n"
},
{
"answer_id": 807904,
"author": "Kyle Boon",
"author_id": 1486,
"author_profile": "https://Stackoverflow.com/users/1486",
"pm_score": 2,
"selected": true,
"text": "<p>Mongrel accepts a --prefix option that will then be prepended to all generated URLs. This is the only way I know of to be able to run multiple instances of the same application on one server. </p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1486/"
] |
In a project I am working on, Apache is set up to only forward requests that come in as /prefix/\* to mongrel. How can I tell ruby on rails to generate all URLs with that prefix?
I have the routes set up for forward to the correct controller action by doing this:
```
map.connect 'sfc/:controller/:action'
```
but that doesn't seem to affect the way that the url writer generates the URLs.
Any ideas?
|
Mongrel accepts a --prefix option that will then be prepended to all generated URLs. This is the only way I know of to be able to run multiple instances of the same application on one server.
|
231,355 |
<p>Hi guys I wrote this code and i have two errors.</p>
<ol>
<li>Invalid rank specifier: expected ',' or ']' </li>
<li>Cannot apply indexing with [] to an expression of type 'int'</li>
</ol>
<p>Can you help please?</p>
<pre><code> static void Main(string[] args)
{
ArrayList numbers = new ArrayList();
foreach (int number in new int[12] {10,9,8,7,6,5,4,3,2,1}) //error No.1
{
numbers.Add(number);
}
numbers.Insert(numbers.Count - 1, 75);
numbers.Remove(7);
numbers.RemoveAt(6);
for(int i=0; i<numbers.Count; i++)
{
int number = (int) number[i]; // error No.2
Console.WriteLine(number);
}
}
</code></pre>
|
[
{
"answer_id": 231365,
"author": "Aaron Smith",
"author_id": 12969,
"author_profile": "https://Stackoverflow.com/users/12969",
"pm_score": 3,
"selected": false,
"text": "<p>1 - You don't have to specify the length of the array just say new int[]</p>\n\n<p>2 - number is just an integer, I think you're trying to access numbers[i]</p>\n"
},
{
"answer_id": 231380,
"author": "Drew Noakes",
"author_id": 24874,
"author_profile": "https://Stackoverflow.com/users/24874",
"pm_score": 2,
"selected": false,
"text": "<p>For 1:</p>\n\n<pre><code>foreach (int number in new int[] {10,9,8,7,6,5,4,3,2,1})\n</code></pre>\n\n<p>For 2:</p>\n\n<pre><code>int number = (int)numbers[i];\n</code></pre>\n\n<p>You are using <code>number</code> where you should have <code>numbers</code> (plural).</p>\n"
},
{
"answer_id": 231385,
"author": "Adam Lassek",
"author_id": 1249,
"author_profile": "https://Stackoverflow.com/users/1249",
"pm_score": 0,
"selected": false,
"text": "<p>You should be initializing the array as </p>\n\n<pre><code>new int[] { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };\n</code></pre>\n\n<p>the compiler will set the size for you. But you're doing it the hard way. Try this:</p>\n\n<pre><code>for (int i = 10; i > 0; i-- )\n{\n numbers.Add(i);\n}\n</code></pre>\n\n<p>If you are using .Net 3.5, you can also use System.Linq.Enumerable to create a range:</p>\n\n<pre><code>IEnumerable<int> numbers = Enumerable.Range(1, 10).Reverse();\n</code></pre>\n\n<p>This would take the place of the ArrayList, which is pretty pointless in 3.5. Since you're just starting, the ArrayList will probably be easier to grasp at first, but keep things like Generics and IEnumerables in mind, they are very important.</p>\n"
},
{
"answer_id": 231399,
"author": "Gulzar Nazim",
"author_id": 4337,
"author_profile": "https://Stackoverflow.com/users/4337",
"pm_score": 3,
"selected": true,
"text": "<pre><code>using System;\nusing System.Collections;\n\nnamespace ConsoleApplication3\n{\n class Program\n {\n static void Main(string[] args)\n {\n ArrayList numbers = new ArrayList();\n foreach (int number in new int[] { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 })\n {\n numbers.Add(number);\n }\n numbers.Insert(numbers.Count - 1, 75);\n numbers.Remove(7);\n numbers.RemoveAt(6);\n for (int i = 0; i < numbers.Count; i++)\n {\n int number = (int)numbers[i];\n Console.WriteLine(number);\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 231405,
"author": "John Rudy",
"author_id": 14048,
"author_profile": "https://Stackoverflow.com/users/14048",
"pm_score": 0,
"selected": false,
"text": "<p>Why not the following for #1?</p>\n\n<pre><code> for (int x = 10; x > 0; --x)\n {\n numbers.Add(number);\n }\n</code></pre>\n\n<p>Despite declaring this as an int[12] (as the apparent intent?), it seems like we're only using the values from 10 to 1, inclusive. Why use a <code>foreach</code> in this scenario, when a <code>for</code> is much more clear in its intent?</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30858/"
] |
Hi guys I wrote this code and i have two errors.
1. Invalid rank specifier: expected ',' or ']'
2. Cannot apply indexing with [] to an expression of type 'int'
Can you help please?
```
static void Main(string[] args)
{
ArrayList numbers = new ArrayList();
foreach (int number in new int[12] {10,9,8,7,6,5,4,3,2,1}) //error No.1
{
numbers.Add(number);
}
numbers.Insert(numbers.Count - 1, 75);
numbers.Remove(7);
numbers.RemoveAt(6);
for(int i=0; i<numbers.Count; i++)
{
int number = (int) number[i]; // error No.2
Console.WriteLine(number);
}
}
```
|
```
using System;
using System.Collections;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
ArrayList numbers = new ArrayList();
foreach (int number in new int[] { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 })
{
numbers.Add(number);
}
numbers.Insert(numbers.Count - 1, 75);
numbers.Remove(7);
numbers.RemoveAt(6);
for (int i = 0; i < numbers.Count; i++)
{
int number = (int)numbers[i];
Console.WriteLine(number);
}
}
}
}
```
|
231,358 |
<p>I'm using NuSOAP on PHP 5.2.6 and I'm seeing that the max message size is only 1000 bytes (which makes it tough to do anything meaningful). Is this set in the endpoint's WSDL or is this something I can configure in NuSOAP?</p>
|
[
{
"answer_id": 232448,
"author": "rjray",
"author_id": 6421,
"author_profile": "https://Stackoverflow.com/users/6421",
"pm_score": 2,
"selected": false,
"text": "<p>I am only passingly-familiar with PHP, and have never used the NuSOAP package at all. However, a SOAP message's size should only be limited by the transport medium. In the case of HTTP, it should be pretty much unbounded (the limitation of 16384 bytes in form POST requests isn't due to SOAP, it's from browser limitations (which may actually not exist anymore, but I don't know for certain)).</p>\n\n<p>I would recommend finding a contact address for the authors/maintainers of NuSOAP and ask them directly. Unless there's something in the WSDL (and I don't recall anything in the WSDL spec that would limit a whole message-body-size... individual parameters (via XML Schema facets), but not the overall body), then the limitation would seem to be in the toolkit.</p>\n"
},
{
"answer_id": 232885,
"author": "Dan Soap",
"author_id": 25253,
"author_profile": "https://Stackoverflow.com/users/25253",
"pm_score": 2,
"selected": false,
"text": "<p>On a production box we use the PHP 5.2.5 built-in Soap-functions as server and NuSoap on PHP 4 and have successfully transferred messages larger than 1 MB.</p>\n\n<p>I don't think that there is a limitation in either product, but you should check your settings in php.ini for </p>\n\n<pre><code>max_input_time (defaults to 60)\n</code></pre>\n\n<p>This is the time each script is allowed to parse input. If the time is up before parsing is complete, the script will not even run.</p>\n\n<p>A sidenote: If possible, I suggest migrating to the SoapClient/SoapServer PHP extension classes. NuSoap has proved itself not very reliable in heavy-load situations, especially when it comes to the cache. Sometimes we saw NuSoap simply \"forgetting\" wsdl definitions and working in none-wsdl-mode. Weird...</p>\n"
},
{
"answer_id": 257661,
"author": "staticsan",
"author_id": 28832,
"author_profile": "https://Stackoverflow.com/users/28832",
"pm_score": 1,
"selected": false,
"text": "<p>You haven't said if you're sending or receiving SOAP messages. If you're sending, I'd be checking to see that NuSOAP is sending via POST rather than GET (you'll probably have to dig into the code to see; I've found the documentation sparse). If you're receiving, check your PHP.INI settings for things like memory and data size. Actually, check your memory limits, anyway -- NuSOAP is quite a memory hog, IIRC.</p>\n"
},
{
"answer_id": 3926436,
"author": "Daniel Alvarez Arribas",
"author_id": 474829,
"author_profile": "https://Stackoverflow.com/users/474829",
"pm_score": 4,
"selected": true,
"text": "<p>Regarding the FUD about a \"1000 bytes limit\"... I looked up the nusoap_client sourcecode and found that the limit is only effective for <strong>debug output</strong>.</p>\n\n<p>This means all data is processed and passed on to the webservice (regardless of its size), but only the first 1000 bytes (or more precisely: characters) are shown in the debug log.</p>\n\n<p>Here's the code:</p>\n\n<pre><code>$this->debug('SOAP message length=' . strlen($soapmsg) . ' contents (max 1000 bytes)=' . substr($soapmsg, 0, 1000));\n\n// send\n$return = $this->send($this->getHTTPBody($soapmsg),$soapAction,$this->timeout,$this->response_timeout);\n</code></pre>\n\n<p>As you can clearly see, the <code>getHTTPBody()</code> call uses the whole <code>$soapmsg</code>, and only the debug output is limited to the first 1000 characters. If you'd like to change this, just change the <code>substr()</code> call to fit your needs, or simply replace it by <code>$soapmsg</code> (so everything is shown in the debug output, too).</p>\n\n<p>This should have absolutely nothing to do with any real limit on the data actually sent. There could of course be other factors actually limiting the size of what you can send (e. g. the RAM limit set for your PHP script, limitations of your HTTP implementation, or running out of available virtual memory), but take it for granted there is no such thing as a \"1000 bytes limit\" for the data you can send with NuSOAP.</p>\n"
},
{
"answer_id": 15677049,
"author": "nightcoder",
"author_id": 94990,
"author_profile": "https://Stackoverflow.com/users/94990",
"pm_score": 0,
"selected": false,
"text": "<p>I think message size will be limited rather by a PHP memory limit, than by some hardcoded value. At least I could send a 6.5MB string without any problems. When I tried to send a 8MB string I got an out of memory exception inside nusoap.php (my server has 64MB limit for PHP).</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231358",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11577/"
] |
I'm using NuSOAP on PHP 5.2.6 and I'm seeing that the max message size is only 1000 bytes (which makes it tough to do anything meaningful). Is this set in the endpoint's WSDL or is this something I can configure in NuSOAP?
|
Regarding the FUD about a "1000 bytes limit"... I looked up the nusoap\_client sourcecode and found that the limit is only effective for **debug output**.
This means all data is processed and passed on to the webservice (regardless of its size), but only the first 1000 bytes (or more precisely: characters) are shown in the debug log.
Here's the code:
```
$this->debug('SOAP message length=' . strlen($soapmsg) . ' contents (max 1000 bytes)=' . substr($soapmsg, 0, 1000));
// send
$return = $this->send($this->getHTTPBody($soapmsg),$soapAction,$this->timeout,$this->response_timeout);
```
As you can clearly see, the `getHTTPBody()` call uses the whole `$soapmsg`, and only the debug output is limited to the first 1000 characters. If you'd like to change this, just change the `substr()` call to fit your needs, or simply replace it by `$soapmsg` (so everything is shown in the debug output, too).
This should have absolutely nothing to do with any real limit on the data actually sent. There could of course be other factors actually limiting the size of what you can send (e. g. the RAM limit set for your PHP script, limitations of your HTTP implementation, or running out of available virtual memory), but take it for granted there is no such thing as a "1000 bytes limit" for the data you can send with NuSOAP.
|
231,362 |
<p>For some weeks now I simply can't run gem install in windows.
It sticks on this line:</p>
<pre><code>C:\Windows\System32>gem install rails --version 2.1.2
Bulk updating Gem source index for: http://gems.rubyforge.org/
</code></pre>
<p>Any ideas what it could be?</p>
|
[
{
"answer_id": 231603,
"author": "hectorsq",
"author_id": 14755,
"author_profile": "https://Stackoverflow.com/users/14755",
"pm_score": 1,
"selected": false,
"text": "<p>It worked fine on my Windows Server 2003 machine. I am using gem version 1.3.0.</p>\n"
},
{
"answer_id": 231670,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 1,
"selected": true,
"text": "<p>Have you been able to install stuff previously?</p>\n\n<p>The gem index is pretty big, about 26MB it seems - what sort of connection do you have? If you have dialup (or 512kbit \"broadband\" etc), it <em>will</em> take quite a while to update.</p>\n\n<p>You could just grab the rails gem file and install it with <code>gem install rails.gem</code> - <a href=\"http://rubyforge.org/frs/?group_id=307\" rel=\"nofollow noreferrer\">http://rubyforge.org/frs/?group_id=307</a></p>\n\n<p>Alternatively you could use one of the prepackage-rails installers, for example <a href=\"http://instantrails.rubyforge.org/wiki/wiki.pl\" rel=\"nofollow noreferrer\">InstantRails</a></p>\n"
},
{
"answer_id": 232798,
"author": "Cameron McCloud",
"author_id": 25484,
"author_profile": "https://Stackoverflow.com/users/25484",
"pm_score": 2,
"selected": false,
"text": "<p>I had this same problem with gem version < 1.2. Upgrading to 1.2 fixed it.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19224/"
] |
For some weeks now I simply can't run gem install in windows.
It sticks on this line:
```
C:\Windows\System32>gem install rails --version 2.1.2
Bulk updating Gem source index for: http://gems.rubyforge.org/
```
Any ideas what it could be?
|
Have you been able to install stuff previously?
The gem index is pretty big, about 26MB it seems - what sort of connection do you have? If you have dialup (or 512kbit "broadband" etc), it *will* take quite a while to update.
You could just grab the rails gem file and install it with `gem install rails.gem` - <http://rubyforge.org/frs/?group_id=307>
Alternatively you could use one of the prepackage-rails installers, for example [InstantRails](http://instantrails.rubyforge.org/wiki/wiki.pl)
|
231,364 |
<p>I am currently building a small website where the content of the main div is being filled through an Ajax call. I basically have a php script that returns the content like this:</p>
<p>(simplified php script...)</p>
<pre><code>
if(isset($_POST["id_tuto"])){
PrintHtml($_POST["id_tuto"]);
}
function PrintHtml($id)
{
switch($id)
{
case [...]:
echo "THIS IS MY HTML CONTENT";
break;
[...]
}
}
</code></pre>
<p>The web page then gets the text from that echo command and replaces the inner html of the content div.</p>
<p>My question is this : What is the best way to echo that html content? there is a lot of content each time since it's a step by step tutorial. Each string will be about 50-80 lines of HTML code. Is there a way to put that html content in a separate html file and echo that file or...?</p>
<p>Thanks a lot!!</p>
|
[
{
"answer_id": 231394,
"author": "Diodeus - James MacFarlane",
"author_id": 12579,
"author_profile": "https://Stackoverflow.com/users/12579",
"pm_score": 0,
"selected": false,
"text": "<p>You just do it the way you'd normally generate an HTML page, except it is not wrapped in HTML HEAD or BODY tags. It's just the HTML fragment that will be added to your page.</p>\n\n<p>Everything you \"echo\" becomes part of the output. You can do it is pieces or all on one go, it doesn't matter because it call gets sent to the browser as \"the response\" as one chunk anyways.</p>\n"
},
{
"answer_id": 231430,
"author": "defrex",
"author_id": 6007,
"author_profile": "https://Stackoverflow.com/users/6007",
"pm_score": 3,
"selected": true,
"text": "<p>You could do it like so:</p>\n\n<pre><code><?php\n function PrintHtml($id) {\n switch($id) {\n case [...]:\n?>\n <h1>Tut page 1</h1>\n <p>this is html content.</p>\n<?php\n break;\n [...]\n }\n }\n?>\n</code></pre>\n\n<p>Or perhaps:</p>\n\n<pre><code><?php\n function PrintHtml($id) {\n switch($id) {\n case [...]:\n include 'section1.php';\n break;\n [...]\n }\n }\n?>\n</code></pre>\n"
},
{
"answer_id": 231470,
"author": "pkaeding",
"author_id": 4257,
"author_profile": "https://Stackoverflow.com/users/4257",
"pm_score": 0,
"selected": false,
"text": "<p>You should use a templating system, such as <a href=\"http://www.smarty.net/\" rel=\"nofollow noreferrer\">Smarty</a>. This will allow you to keep your html separate from your code logic.</p>\n"
},
{
"answer_id": 231471,
"author": "Clutch",
"author_id": 25143,
"author_profile": "https://Stackoverflow.com/users/25143",
"pm_score": 0,
"selected": false,
"text": "<p>Try separating your data (Human readable text) from your formatting (HTML) I suspect that 50 - 80 lines of HTML could be separated. You could create several HTML templates and then add your data into the template as needed. I would definitely use Prototype or some JavaScript library to handle receiving the JSON formated data on the client side. You can have your data in flat files but I think a database would be faster and less prone to errors. MVC pattern would definitely help here.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231364",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25152/"
] |
I am currently building a small website where the content of the main div is being filled through an Ajax call. I basically have a php script that returns the content like this:
(simplified php script...)
```
if(isset($_POST["id_tuto"])){
PrintHtml($_POST["id_tuto"]);
}
function PrintHtml($id)
{
switch($id)
{
case [...]:
echo "THIS IS MY HTML CONTENT";
break;
[...]
}
}
```
The web page then gets the text from that echo command and replaces the inner html of the content div.
My question is this : What is the best way to echo that html content? there is a lot of content each time since it's a step by step tutorial. Each string will be about 50-80 lines of HTML code. Is there a way to put that html content in a separate html file and echo that file or...?
Thanks a lot!!
|
You could do it like so:
```
<?php
function PrintHtml($id) {
switch($id) {
case [...]:
?>
<h1>Tut page 1</h1>
<p>this is html content.</p>
<?php
break;
[...]
}
}
?>
```
Or perhaps:
```
<?php
function PrintHtml($id) {
switch($id) {
case [...]:
include 'section1.php';
break;
[...]
}
}
?>
```
|
231,377 |
<p>I would like to use JavaScript to manipulate hidden input fields in a JSF/Facelets page. When the page loads, I need to set a hidden field to the color depth of the client.</p>
<p>From my Facelet:</p>
<pre><code><body onload="setColorDepth(document.getElementById(?????);">
<h:form>
<h:inputHidden value="#{login.colorDepth}" id="colorDepth" />
</h:form>
</code></pre>
<p>When JSF processes the page, it is of course changing the IDs of the elements. What's the best way to reference these elements from my JavaScript code?</p>
|
[
{
"answer_id": 231393,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 3,
"selected": true,
"text": "<p>You'll want to set the ID of the form so you'll know what it is. Then you'll be able to construct the actual element ID.</p>\n\n<pre><code><body onload=\"setColorDepth(document.getElementById('myForm:colorDepth');\">\n\n<h:form id=\"myForm\">\n <h:inputHidden value=\"#{login.colorDepth}\" id=\"colorDepth\" />\n</h:form>\n</code></pre>\n\n<p>If you don't want to set the form's ID field, you could find it at runtime, like so:</p>\n\n<pre><code><body onload=\"setColorDepth(document.getElementById(document.forms[0].id + ':colorDepth');\">\n</code></pre>\n"
},
{
"answer_id": 231397,
"author": "branchgabriel",
"author_id": 30807,
"author_profile": "https://Stackoverflow.com/users/30807",
"pm_score": 0,
"selected": false,
"text": "<p>View the generated html source and look at what the jsf named the id attribute of the tag.</p>\n\n<p>You will soon see how the naming convention works. Its usually like FORMNAME:FIELDNAME</p>\n"
},
{
"answer_id": 266009,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 0,
"selected": false,
"text": "<p>You can use the control's <em>clientId</em> as returned by <a href=\"http://java.sun.com/javaee/javaserverfaces/1.1_01/docs/api/javax/faces/component/UIComponent.html#getClientId(javax.faces.context.FacesContext)\" rel=\"nofollow noreferrer\">UIComponent.getClientId(FacesContext)</a>. See <a href=\"https://stackoverflow.com/questions/265175/how-does-jsf-generate-the-name-of-the-form-input-field#265561\">here</a> for sample code.</p>\n"
},
{
"answer_id": 266112,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Define a function findElement globally and use it everywhere </p>\n\n<pre><code>function findElement(elementId) {\n if(document.getElementById(elementId)) return elementId;\n for(var i = 0; i < document.forms.length; i++) {\n if(document.getElementById(document.forms[i].id + ':' + elementId)) {\n return document.forms[i].id + ':' + elementId;\n }\n }\n return null;\n }\n\n\n <body onload=\"setColorDepth(findElement('colorDepth'));\">\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27515/"
] |
I would like to use JavaScript to manipulate hidden input fields in a JSF/Facelets page. When the page loads, I need to set a hidden field to the color depth of the client.
From my Facelet:
```
<body onload="setColorDepth(document.getElementById(?????);">
<h:form>
<h:inputHidden value="#{login.colorDepth}" id="colorDepth" />
</h:form>
```
When JSF processes the page, it is of course changing the IDs of the elements. What's the best way to reference these elements from my JavaScript code?
|
You'll want to set the ID of the form so you'll know what it is. Then you'll be able to construct the actual element ID.
```
<body onload="setColorDepth(document.getElementById('myForm:colorDepth');">
<h:form id="myForm">
<h:inputHidden value="#{login.colorDepth}" id="colorDepth" />
</h:form>
```
If you don't want to set the form's ID field, you could find it at runtime, like so:
```
<body onload="setColorDepth(document.getElementById(document.forms[0].id + ':colorDepth');">
```
|
231,381 |
<p>Is this seen as an in efficient prime number generator. It seems to me that this is pretty efficient. Is it the use of the stream that makes the program run slower?</p>
<p>I am trying to submit this to <a href="http://www.spoj.pl/" rel="nofollow noreferrer">SPOJ</a> and it tells me that my time limit exceeded... </p>
<pre><code>#include <iostream>
#include <sstream>
using namespace std;
int main() {
int testCases, first, second, counter = 0;
bool isPrime = true;
stringstream out;
cin >> testCases;
for (int i = 0; i < testCases; i++) {
// get the next two numbers
cin >> first >> second;
if (first%2 == 0)
first++;
// find the prime numbers between the two given numbers
for (int j = first; j <= second; j+=2) {
// go through and check if j is prime
for (int k = 2; k < j; k++) {
if (j%k == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
out << j << "\n";
}
isPrime = true;
}
out << "\n";
}
cout << out.str();
return 0;
}
</code></pre>
<p>EDIT: The program is supposed to generate prime numbers between the numbers specified in the input. (See here for more details: <a href="http://www.spoj.pl/problems/PRIME1/" rel="nofollow noreferrer">Prime Generator Problem</a> )</p>
<p>-Tomek</p>
|
[
{
"answer_id": 231398,
"author": "Matt J",
"author_id": 18528,
"author_profile": "https://Stackoverflow.com/users/18528",
"pm_score": 5,
"selected": true,
"text": "<p>This is one step (skipping even numbers) above the naive algorithm. I would suggest the <a href=\"http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow noreferrer\">Sieve Of Eratosthenes</a> as a more efficient algorithm. From the above link:</p>\n\n<blockquote>\n <p>The complexity of the algorithm is\n O((nlogn)(loglogn)) with a memory\n requirement of O(n). The segmented\n version of the sieve of Eratosthenes,\n with basic optimizations such as wheel\n factorization, uses O(n) operations\n and O(n1 / 2loglogn / logn) bits of\n memory.</p>\n</blockquote>\n\n<p>The algorithm you give is somewhere near O(n^2). The speedup you get by skipping evens isn't that great because you would find an even number not to be prime on the first test. The sieve has a much greater memory requirement, but the runtime complexity is far superior for large <em>N</em>.</p>\n"
},
{
"answer_id": 231400,
"author": "warren",
"author_id": 4418,
"author_profile": "https://Stackoverflow.com/users/4418",
"pm_score": 3,
"selected": false,
"text": "<p>You're searching a <em>lot</em> more numbers than you have to - at most you only need to go to <code><= (sqrt(num))</code>.</p>\n"
},
{
"answer_id": 231408,
"author": "jsl4980",
"author_id": 21756,
"author_profile": "https://Stackoverflow.com/users/21756",
"pm_score": 0,
"selected": false,
"text": "<p>It can be made slightly more efficient. You don't need to start k at 2, you're already making sure not to test even numbers. So start k at 3.<br>\nThen increment k by 2 every time because you don't need to test other even numbers. \nThe most efficient way that I can think of is to only test if a number is divisible by known prime numbers (then when you find another one add that to the list you test with).</p>\n"
},
{
"answer_id": 231421,
"author": "Austin Salonen",
"author_id": 4068,
"author_profile": "https://Stackoverflow.com/users/4068",
"pm_score": 0,
"selected": false,
"text": "<pre><code>for (int k = 2; k < j; k++) {\n if (j%k == 0) {\n isPrime = false;\n break;\n }\n}\n</code></pre>\n\n<p>should be:</p>\n\n<pre><code>for(int k = 3; k <= j/2; k+=2 )\n{\n if( j % k == 0 )\n break;\n}\n</code></pre>\n\n<p>j/2 really should be sqrt(j) but it is typically a good enough estimation.</p>\n"
},
{
"answer_id": 235517,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 2,
"selected": false,
"text": "<p>Here's a simple Sieve of Eratosthenes. It doesn't require predeclaring a big boolean array, but it's still >>O(n) in time and space. As long as you have enough memory, though, it ought to be noticeably faster than what your present naïve method.</p>\n\n<pre><code>#include <iostream>\n#include <map>\n\nusing namespace std;\n\ntemplate<typename T = int, typename M = map<T, T> >\nclass prime_iterator {\n public:\n prime_iterator() : current(2), skips() { skips[4] = 2; }\n T operator*() { return current; }\n prime_iterator &operator++() {\n typename M::iterator i;\n while ((i = skips.find(++current)) != skips.end()) {\n T skip = i->second, next = current + skip;\n skips.erase(i);\n for (typename M::iterator j = skips.find(next);\n j != skips.end(); j = skips.find(next += skip)) {}\n skips[next] = skip;\n }\n skips[current * current] = current;\n return *this;\n }\n private:\n T current;\n M skips;\n};\n\nint main() {\n prime_iterator<int> primes;\n for (; *primes < 1000; ++primes)\n cout << *primes << endl;\n return 0;\n}\n</code></pre>\n\n<p>If this is still too slow for you, you may want to pursue the <a href=\"http://en.wikipedia.org/wiki/Sieve_of_Atkin\" rel=\"nofollow noreferrer\">Sieve of Atkin</a>, an optimized Sieve of Eratosthenes.</p>\n\n<p>Actually, these are only relatively efficient if the range of primes to generate starts low. If the lower bound is already fairly large and the upper bound is not much larger than the lower, then the sieving methods are wasteful work and you'd be better off running a <a href=\"http://en.wikipedia.org/wiki/Primality_test\" rel=\"nofollow noreferrer\">primality test</a>.</p>\n"
},
{
"answer_id": 1081800,
"author": "dpetek",
"author_id": 80204,
"author_profile": "https://Stackoverflow.com/users/80204",
"pm_score": 2,
"selected": false,
"text": "<p>And one more thing, don't use sqrt(n) in a loop:</p>\n\n<pre><code>for(int k=1;k<sqrt(n);++k)\n</code></pre>\n\n<p>If there's no good optimization , sqrt will be calculated in every iteration.</p>\n\n<p>Use</p>\n\n<pre><code>for (int k=1;k*k < n;++k)\n</code></pre>\n\n<p>Or simply</p>\n\n<pre><code>int sq = sqrt ( n );\nfor (int k=1;k<sq;++k)\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231381",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29326/"
] |
Is this seen as an in efficient prime number generator. It seems to me that this is pretty efficient. Is it the use of the stream that makes the program run slower?
I am trying to submit this to [SPOJ](http://www.spoj.pl/) and it tells me that my time limit exceeded...
```
#include <iostream>
#include <sstream>
using namespace std;
int main() {
int testCases, first, second, counter = 0;
bool isPrime = true;
stringstream out;
cin >> testCases;
for (int i = 0; i < testCases; i++) {
// get the next two numbers
cin >> first >> second;
if (first%2 == 0)
first++;
// find the prime numbers between the two given numbers
for (int j = first; j <= second; j+=2) {
// go through and check if j is prime
for (int k = 2; k < j; k++) {
if (j%k == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
out << j << "\n";
}
isPrime = true;
}
out << "\n";
}
cout << out.str();
return 0;
}
```
EDIT: The program is supposed to generate prime numbers between the numbers specified in the input. (See here for more details: [Prime Generator Problem](http://www.spoj.pl/problems/PRIME1/) )
-Tomek
|
This is one step (skipping even numbers) above the naive algorithm. I would suggest the [Sieve Of Eratosthenes](http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) as a more efficient algorithm. From the above link:
>
> The complexity of the algorithm is
> O((nlogn)(loglogn)) with a memory
> requirement of O(n). The segmented
> version of the sieve of Eratosthenes,
> with basic optimizations such as wheel
> factorization, uses O(n) operations
> and O(n1 / 2loglogn / logn) bits of
> memory.
>
>
>
The algorithm you give is somewhere near O(n^2). The speedup you get by skipping evens isn't that great because you would find an even number not to be prime on the first test. The sieve has a much greater memory requirement, but the runtime complexity is far superior for large *N*.
|
231,390 |
<p>I've been trying to install <a href="http://thoughtbot.com/projects/shoulda" rel="nofollow noreferrer">Shoulda</a></p>
<pre><code>script/plugin install git://github.com/thoughtbot/shoulda.git
</code></pre>
<p>but all I get is:</p>
<pre><code>removing: C:/Documents and Settings/Danny/My Documents/Projects/Ruby On Rails/_ProjectName_/vendor/plugins/shoulda/.git
>
</code></pre>
<p>And the <code>vender/plugins</code> directory is empty. I have Rails 2.1.1 installed as a gem and have verified that 2.1.1 is loaded (using a puts inserted into config/boot.rb). Any ideas about what's going on?</p>
<p>(this is on a windows box)</p>
|
[
{
"answer_id": 231396,
"author": "Jordi Bunster",
"author_id": 4272,
"author_profile": "https://Stackoverflow.com/users/4272",
"pm_score": 4,
"selected": true,
"text": "<p>Do you have git installed? If you don't, it will just not work. Rails assumes git is installed and can be found in your PATH.</p>\n\n<p>You can get Git for Windows <a href=\"http://code.google.com/p/msysgit/downloads/list\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 3067200,
"author": "Chris Charabaruk",
"author_id": 5697,
"author_profile": "https://Stackoverflow.com/users/5697",
"pm_score": 0,
"selected": false,
"text": "<p>For folks still having this problem, as of Rails 2.3.5 you are likely to get an error still, as recent Ruby/Win32 builds are done with MinGW. However, the problem's been patched between there and 2.3.8, and so long as you have msysgit installed at this point, it should Just Work.</p>\n\n<p>If you're not comfortable with upgrading (c'mon, it's just a little point release) the following patch will handle things:</p>\n\n<pre><code>--- reporting.rb.orig 2010-06-11 01:00:24.739991600 -0400\n+++ reporting.rb 2010-06-18 00:16:39.517649400 -0400\n@@ -35,7 +35,7 @@\n # puts 'But this will'\n def silence_stream(stream)\n old_stream = stream.dup\n- stream.reopen(RUBY_PLATFORM =~ /mswin/ ? 'NUL:' : '/dev/null')\n+ stream.reopen(RUBY_PLATFORM =~ /(:?mswin|mingw)/ ? 'NUL:' : '/dev/null')\n stream.sync = true\n yield\n ensure\n@@ -56,4 +56,4 @@\n raise unless exception_classes.any? { |cls| e.kind_of?(cls) }\n end\n end\n-end\n\\ No newline at end of file\n+end\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13216/"
] |
I've been trying to install [Shoulda](http://thoughtbot.com/projects/shoulda)
```
script/plugin install git://github.com/thoughtbot/shoulda.git
```
but all I get is:
```
removing: C:/Documents and Settings/Danny/My Documents/Projects/Ruby On Rails/_ProjectName_/vendor/plugins/shoulda/.git
>
```
And the `vender/plugins` directory is empty. I have Rails 2.1.1 installed as a gem and have verified that 2.1.1 is loaded (using a puts inserted into config/boot.rb). Any ideas about what's going on?
(this is on a windows box)
|
Do you have git installed? If you don't, it will just not work. Rails assumes git is installed and can be found in your PATH.
You can get Git for Windows [here](http://code.google.com/p/msysgit/downloads/list).
|
231,439 |
<p>Is there any easy way to create an acronym from a string?</p>
<pre><code>First_name Middle_name Last_name => FML
first_name middle_name last_name => FML
First_name-Middle_name Last_name => F-ML
first_name-middle_name last_name => F-ML
</code></pre>
|
[
{
"answer_id": 231459,
"author": "Totty",
"author_id": 30838,
"author_profile": "https://Stackoverflow.com/users/30838",
"pm_score": 0,
"selected": false,
"text": "<p>I don't know about language agnostic, but I would make a function that accepts an args[] parameter to bring in all of your strings then loop through those and concatenate the first char of each onto another string which is returned.</p>\n\n<p>Edit: Strike that. Didn't realize it was a single string. You would have to loop through all characters looking for special character types. Any letters after the first would be ignored until you get to a space or special character.</p>\n"
},
{
"answer_id": 231473,
"author": "Franci Penov",
"author_id": 17028,
"author_profile": "https://Stackoverflow.com/users/17028",
"pm_score": 2,
"selected": false,
"text": "<pre><code>Tokenize the string on whitespace.\nFor each token1,\n Tokenize on dash.\n For each token2\n Take token2[0] and capitalize\n if not first token2, prepend with dash\n Concatenate to result2\n Concatenate to result\n</code></pre>\n"
},
{
"answer_id": 231566,
"author": "Jordi Bunster",
"author_id": 4272,
"author_profile": "https://Stackoverflow.com/users/4272",
"pm_score": 2,
"selected": true,
"text": "<p>Does language-agnostic means you have to use pseudocode? If not, then in Ruby:</p>\n\n<p><code>\"First_name-Middle_nameLast_name\".gsub('-', ' - ').gsub(/\\B[A-Z]+/, ' \\&').split(' ').map { |s| s[0..0] }.join.upcase => \"F-ML\"</code></p>\n\n<p>If it turns out the lack of space in the third example is a typo, you can skip the second call to <code>gsub</code> (with the ugly regexp.)</p>\n"
},
{
"answer_id": 231572,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 1,
"selected": false,
"text": "<p>Example in JavaScript, supposing the lack of space before Last in 3rd example is a typo:</p>\n\n<pre><code>var testStrings = [\n'First_name Middle_name Last_name',\n'first_name middle_name last_name',\n'First_name-Middle_name Last_name',\n'first_name-middle_name last_name'\n];\nvar re = /\\b(\\w)\\w*\\b(-?)\\s*/g;\nvar mr;\nfor (var i = 0, l = testStrings.length; i < l; i++)\n{\n var name = testStrings[i];\n var abbr = name.replace(re, function (match, ini, dash)\n {\n return ini.toUpperCase() + dash;\n });\n alert(abbr);\n}\n</code></pre>\n\n<p>Should be easy (?) to adapt to other languages.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3718/"
] |
Is there any easy way to create an acronym from a string?
```
First_name Middle_name Last_name => FML
first_name middle_name last_name => FML
First_name-Middle_name Last_name => F-ML
first_name-middle_name last_name => F-ML
```
|
Does language-agnostic means you have to use pseudocode? If not, then in Ruby:
`"First_name-Middle_nameLast_name".gsub('-', ' - ').gsub(/\B[A-Z]+/, ' \&').split(' ').map { |s| s[0..0] }.join.upcase => "F-ML"`
If it turns out the lack of space in the third example is a typo, you can skip the second call to `gsub` (with the ugly regexp.)
|
231,491 |
<p>Is there an elegant way to create and initialize a <code>const std::vector<const T></code> like <code>const T a[] = { ... }</code> to a fixed (and small) number of values?<br>
I need to call a function frequently which expects a <code>vector<T></code>, but these values will never change in my case.</p>
<p>In principle I thought of something like</p>
<pre><code>namespace {
const std::vector<const T> v(??);
}
</code></pre>
<p>since v won't be used outside of this compilation unit.</p>
|
[
{
"answer_id": 231495,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 7,
"selected": true,
"text": "<p>For C++11:</p>\n<pre><code>vector<int> luggage_combo = { 1, 2, 3, 4, 5 };\n</code></pre>\n<p><strong>Original answer:</strong></p>\n<p>You would either have to wait for C++0x or use something like <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/assign/doc/index.html\" rel=\"nofollow noreferrer\">Boost.Assign</a> to do that.</p>\n<p>e.g.:</p>\n<pre><code>#include <boost/assign/std/vector.hpp>\nusing namespace boost::assign; // bring 'operator+=()' into scope\n\nvector<int> v;\nv += 1,2,3,4,5;\n</code></pre>\n"
},
{
"answer_id": 231524,
"author": "Steve Jessop",
"author_id": 13005,
"author_profile": "https://Stackoverflow.com/users/13005",
"pm_score": 5,
"selected": false,
"text": "<p>If you're asking how to initialise a const vector so that it has interesting contents, then the answer is probably to use the copy constructor. First you laboriously fill in a vector, then you create your new const vector from it. Or you can use the <code>vector<InputIterator>(InputIterator, InputIterator)</code> constructor template to initialise from some other kind of container or an array. If an array, then that could have been defined with an initialisation list.</p>\n<p>Something like this is hopefully close to what you want:</p>\n<pre><code>const T ra[3] = {t1, t2, t3};\nconst vector<const T> v(ra, ra+3);\n</code></pre>\n<p>If you're asking how to pass a const vector into a function which takes a vector then the answer is either:</p>\n<ul>\n<li>you can't, because the function might alter the vector and your object/reference is const. Make a non-const copy of the original, and pass that in.</li>\n</ul>\n<p>or</p>\n<ul>\n<li>use <code>const_cast</code> to remove the constness in order to pass it into a function which takes a non-const vector but which you just so happen to know will not modify the vector.</li>\n</ul>\n<p>The latter is one of those things which will, quite rightly, cause anyone who sees it to make comments about goggles, and the fact that they do nothing. It's exactly what <code>const_cast</code> is for, but there's a reasonably strong argument that says if you need <code>const_cast</code>, you have already lost.</p>\n<p>Doing both of those things (creating a const vector from a non-const one with the copy constructor, and then casting away constness) is definitely wrong - you should have just used a non-const vector. So pick at most one of these to do...</p>\n<p>[<strong>Edit:</strong> just noticed that you're talking about a difference between <code>vector<T></code> and <code>const vector<const T></code>. Unfortunately in the STL, <code>vector<const T></code> and <code>vector<T></code> are completely unrelated types, and the only way to convert between them is by copying. This is a difference between vectors and arrays - a <code>T**</code> can be silently and safely converted to <code>const T *const *</code>]</p>\n"
},
{
"answer_id": 231531,
"author": "John Dibling",
"author_id": 241536,
"author_profile": "https://Stackoverflow.com/users/241536",
"pm_score": 4,
"selected": false,
"text": "<p>As others have said, you can't init a vector the same way you can init a C-style array, unless you give it pointers to a source array. But in that case, if your vector is a global const, why not just use an old C-style array instead?</p>\n\n<pre><code>const int MyInts[] = {\n1, 2, 3, 4, 5};\n\nconst size_t NumMyInts = sizeof(MyInts)/sizeof(MyInts[0]);\n</code></pre>\n\n<p>You can even use STL algorithms against this array, the same way you would use algorithms against a const vector...</p>\n\n<pre><code>const int* myInt = std::find( &MyInts[0], &MyInts[NumMyInts], 3);\n</code></pre>\n"
},
{
"answer_id": 231546,
"author": "mstrobl",
"author_id": 25965,
"author_profile": "https://Stackoverflow.com/users/25965",
"pm_score": 0,
"selected": false,
"text": "<p>Not sure if I understood you right. I understand your question like this: you want to initialize a vector to a large number of elements. What's wrong with using <code>push_back()</code> on the vector? :-)</p>\n<p>If you know the number of elements to be stored (or are sure that it will store less than the next power of 2) you can do this, if you have a vector of pointers of type X (works only with pointers):</p>\n<pre><code>std::vector< X* > v;\nv.reserve(num_elems);\nX* p = v.begin();\nfor (int count = 0; count < num_elems; count++)\n p[count] = some_source[count];\n</code></pre>\n<p>Beware of adding more than the next power of 2 elements, even if using <code>push_back()</code>. Pointers to <code>v.begin()</code> will then be invalid.</p>\n"
},
{
"answer_id": 231584,
"author": "janm",
"author_id": 7256,
"author_profile": "https://Stackoverflow.com/users/7256",
"pm_score": 3,
"selected": false,
"text": "<p>You can do it in two steps:</p>\n\n<pre><code>namespace {\n const T s_actual_array[] = { ... };\n const std::vector<const T> s_blah(s_actual_array,\n s_actual_array + (sizeof(s_actual_array) / sizeof(s_actual_array[0])));\n}\n</code></pre>\n\n<p>Perhaps not as beautiful as you might like, but functional.</p>\n"
},
{
"answer_id": 231619,
"author": "Peter",
"author_id": 22517,
"author_profile": "https://Stackoverflow.com/users/22517",
"pm_score": 0,
"selected": false,
"text": "<p>If they're all the same you can just do</p>\n\n<pre><code>vector<T> vec(num_items, item);\n</code></pre>\n\n<p>but I assume they're not - in which case the neatest way is probably:</p>\n\n<pre><code>vector<T> vec(num_items);\nvec[0] = 15;\nvec[1] = 5;\n...\n</code></pre>\n\n<p>C++0x will let you use an initialiser list in exactly the way you're thinking of, but that's\nnot a lot of good right now, unfortunately.</p>\n"
},
{
"answer_id": 254143,
"author": "Shadow2531",
"author_id": 1697,
"author_profile": "https://Stackoverflow.com/users/1697",
"pm_score": 4,
"selected": false,
"text": "<p>Short and dirty way (similar to Boost's <code>list_of()</code>)</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include <iostream>\n#include <vector>\n#include <iterator>\n#include <algorithm>\nusing namespace std;\n\ntemplate <typename T>\nstruct vlist_of : public vector<T> {\n vlist_of(const T& t) {\n (*this)(t);\n }\n vlist_of& operator()(const T& t) {\n this->push_back(t);\n return *this;\n }\n};\n\nint main() {\n const vector<int> v = vlist_of<int>(1)(2)(3)(4)(5);\n copy(v.begin(), v.end(), ostream_iterator<int>(cout, "\\n"));\n}\n</code></pre>\n<p>Now, C++11 has initializer lists, so you don't need to do it that way or even use Boost. But, as an example, you can do the above in C++11 more efficiently like this:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code> #include <iostream>\n #include <vector>\n #include <utility>\n #include <ostream>\n using namespace std;\n\n template <typename T>\n struct vlist_of : public vector<T> {\n vlist_of(T&& t) {\n (*this)(move(t));\n }\n vlist_of& operator()(T&& t) {\n this->push_back(move(t));\n return *this;\n }\n };\n\n int main() {\n const vector<int> v = vlist_of<int>(1)(2)(3)(4)(5);\n for (const auto& i: v) {\n cout << i << endl;\n }\n }\n</code></pre>\n<p>But, it's still not as efficient as using a C++11 initializer list because there's no <code>operator=(vlist_of&&)</code> defined for vector.</p>\n<p>tjohns20's way modified like the following might be a better c++11 <code>vlist_of</code>:</p>\n<pre><code>#include <iostream>\n#include <vector>\n#include <utility>\nusing namespace std;\n\ntemplate <typename T>\nclass vlist_of {\n public:\n vlist_of(T&& r) {\n (*this)(move(r));\n }\n vlist_of& operator()(T&& r) {\n v.push_back(move(r));\n return *this;\n }\n vector<T>&& operator()() {\n return move(v);\n }\n private:\n vector<T> v;\n \n};\n\nint main() {\n const auto v = vlist_of<int>(1)(2)(3)(4)(5)();\n for (const auto& i : v) {\n cout << i << endl;\n }\n \n}\n</code></pre>\n"
},
{
"answer_id": 5939934,
"author": "tjohns20",
"author_id": 223380,
"author_profile": "https://Stackoverflow.com/users/223380",
"pm_score": 0,
"selected": false,
"text": "<p>Based on Shadow2531's response, I'm using this class to initialise vectors, without actually inheriting from std::vector like Shadow's solution did</p>\n\n<pre><code>template <typename T>\nclass vector_init\n{\npublic:\n vector_init(const T& val)\n {\n vec.push_back(val);\n }\n inline vector_init& operator()(T val)\n {\n vec.push_back(val);\n return *this;\n }\n inline std::vector<T> end()\n {\n return vec;\n }\nprivate:\n std::vector<T> vec;\n};\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>std::vector<int> testVec = vector_init<int>(1)(2)(3)(4)(5).end();\n</code></pre>\n\n<p>Compared to Steve Jessop's solution it creates a lot more code, but if the array creation isn't performance critical I find it a nice way to initialise an array in a single line</p>\n"
},
{
"answer_id": 10446388,
"author": "opal",
"author_id": 267118,
"author_profile": "https://Stackoverflow.com/users/267118",
"pm_score": 3,
"selected": false,
"text": "<p>How about:</p>\n\n<pre><code>int ar[]={1,2,3,4,5,6};\nconst int TotalItems = sizeof(ar)/sizeof(ar[0]);\nstd::vector<int> v(ar, ar+TotalItems);\n</code></pre>\n"
},
{
"answer_id": 21124823,
"author": "Kevin",
"author_id": 3195914,
"author_profile": "https://Stackoverflow.com/users/3195914",
"pm_score": 2,
"selected": false,
"text": "<p>Old question, but I ran into the same issue today, here's the approach that was most acceptable for my purposes:</p>\n\n<pre><code>vector<int> initVector(void)\n{\n vector<int> initializer;\n initializer.push_back(10);\n initializer.push_back(13);\n initializer.push_back(3);\n return intializer;\n}\n\nint main()\n{\n const vector<int> a = initVector();\n return 0;\n}\n</code></pre>\n\n<p>Example to avoid excessive copying:</p>\n\n<pre><code>vector<int> & initVector(void)\n{\n static vector<int> initializer;\n if(initializer.empty())\n {\n initializer.push_back(10);\n initializer.push_back(13);\n initializer.push_back(3);\n }\n return intializer;\n}\n\nint main()\n{\n const vector<int> & a = initVector();\n return 0;\n}\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26613/"
] |
Is there an elegant way to create and initialize a `const std::vector<const T>` like `const T a[] = { ... }` to a fixed (and small) number of values?
I need to call a function frequently which expects a `vector<T>`, but these values will never change in my case.
In principle I thought of something like
```
namespace {
const std::vector<const T> v(??);
}
```
since v won't be used outside of this compilation unit.
|
For C++11:
```
vector<int> luggage_combo = { 1, 2, 3, 4, 5 };
```
**Original answer:**
You would either have to wait for C++0x or use something like [Boost.Assign](http://www.boost.org/doc/libs/1_36_0/libs/assign/doc/index.html) to do that.
e.g.:
```
#include <boost/assign/std/vector.hpp>
using namespace boost::assign; // bring 'operator+=()' into scope
vector<int> v;
v += 1,2,3,4,5;
```
|
231,512 |
<p>I am using RedCloth with Rails 2.1.1. The Textile <code><del></code> tag markup format (i.e. -delete-) was not translating at all. Tried a few choice options.</p>
<pre><code>> x=RedCloth.new('foobar -blah-')
=> "foobar -blah-"
> x.to_html
=> "<p>foobar <del>blah</del></p>" # WORKED!
> x=RedCloth.new('foobar * -blah-')
=> "foobar * -blah-"
> x.to_html
=> "<p>foobar * <del>blah</del></p>" # WORKED!
> x=RedCloth.new("foobar\n* -blah-")
=> "foobar\n* -blah-"
> x.to_html
=> "<p>foobar</p>\n<ul>\n\t<li>-blah-</li>\n</ul>" # DID NOT WORK!
</code></pre>
<p>It appears to me that newlines are the culprit in throwing RedCloth up-in-arms. Any solutions to getting RedCloth to properly recognize '-delete-'? I have tried RedCloth 4.0.1, 4.0.3, and 4.0.4.</p>
|
[
{
"answer_id": 231660,
"author": "Michael Sepcot",
"author_id": 6033,
"author_profile": "https://Stackoverflow.com/users/6033",
"pm_score": 2,
"selected": false,
"text": "<p>Looks like RedCloth needs a little more syntax to interpret the delete tag as the first element after a list item...</p>\n\n<pre><code>>> RedCloth.new(\"foobar\\n* [-blah-]\").to_html\n=> \"<p>foobar</p>\\n<ul>\\n\\t<li><del>blah</del></li>\\n</ul>\"\n</code></pre>\n"
},
{
"answer_id": 253930,
"author": "Ian Terrell",
"author_id": 9269,
"author_profile": "https://Stackoverflow.com/users/9269",
"pm_score": 0,
"selected": false,
"text": "<p>This is because <strong>a star on a new line represents a list item</strong>, and it is ignoring delete markers without explicitly telling it to render them as Michael points out.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14895/"
] |
I am using RedCloth with Rails 2.1.1. The Textile `<del>` tag markup format (i.e. -delete-) was not translating at all. Tried a few choice options.
```
> x=RedCloth.new('foobar -blah-')
=> "foobar -blah-"
> x.to_html
=> "<p>foobar <del>blah</del></p>" # WORKED!
> x=RedCloth.new('foobar * -blah-')
=> "foobar * -blah-"
> x.to_html
=> "<p>foobar * <del>blah</del></p>" # WORKED!
> x=RedCloth.new("foobar\n* -blah-")
=> "foobar\n* -blah-"
> x.to_html
=> "<p>foobar</p>\n<ul>\n\t<li>-blah-</li>\n</ul>" # DID NOT WORK!
```
It appears to me that newlines are the culprit in throwing RedCloth up-in-arms. Any solutions to getting RedCloth to properly recognize '-delete-'? I have tried RedCloth 4.0.1, 4.0.3, and 4.0.4.
|
Looks like RedCloth needs a little more syntax to interpret the delete tag as the first element after a list item...
```
>> RedCloth.new("foobar\n* [-blah-]").to_html
=> "<p>foobar</p>\n<ul>\n\t<li><del>blah</del></li>\n</ul>"
```
|
231,525 |
<p>We're all familiar with the horror that is C# event declaration. To ensure thread-safety, <a href="http://blogs.msdn.com/brada/archive/2005/01/14/353132.aspx" rel="noreferrer">the standard is to write something like this</a>:</p>
<pre><code>public event EventHandler SomethingHappened;
protected virtual void OnSomethingHappened(EventArgs e)
{
var handler = SomethingHappened;
if (handler != null)
handler(this, e);
}
</code></pre>
<p>Recently in some other question on this board (which I can't find now), someone pointed out that extension methods could be used nicely in this scenario. Here's one way to do it:</p>
<pre><code>static public class EventExtensions
{
static public void RaiseEvent(this EventHandler @event, object sender, EventArgs e)
{
var handler = @event;
if (handler != null)
handler(sender, e);
}
static public void RaiseEvent<T>(this EventHandler<T> @event, object sender, T e)
where T : EventArgs
{
var handler = @event;
if (handler != null)
handler(sender, e);
}
}
</code></pre>
<p>With these extension methods in place, all you need to declare and raise an event is something like this:</p>
<pre><code>public event EventHandler SomethingHappened;
void SomeMethod()
{
this.SomethingHappened.RaiseEvent(this, EventArgs.Empty);
}
</code></pre>
<p>My question: Is this a good idea? Are we missing anything by not having the standard On method? (One thing I notice is that it doesn't work with events that have explicit add/remove code.)</p>
|
[
{
"answer_id": 231536,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 7,
"selected": true,
"text": "<p>It will still work with events that have an explicit add/remove - you just need to use the delegate variable (or however you've stored the delegate) instead of the event name.</p>\n\n<p>However, there's an easier way to make it thread-safe - initialize it with a no-op handler:</p>\n\n<pre><code>public event EventHandler SomethingHappened = delegate {};\n</code></pre>\n\n<p>The performance hit of calling an extra delegate will be negligible, and it sure makes the code easier.</p>\n\n<p>By the way, in your extension method you don't need an extra local variable - you could just do:</p>\n\n<pre><code>static public void RaiseEvent(this EventHandler @event, object sender, EventArgs e)\n{\n if (@event != null)\n @event(sender, e);\n}\n\nstatic public void RaiseEvent<T>(this EventHandler<T> @event, object sender, T e)\n where T : EventArgs\n{\n if (@event != null)\n @event(sender, e);\n}\n</code></pre>\n\n<p>Personally I wouldn't use a keyword as a parameter name, but it doesn't really change the calling side at all, so do what you want :)</p>\n\n<p>EDIT: As for the \"OnXXX\" method: are you planning on your classes being derived from? In my view, most classes should be sealed. If you <em>do</em>, do you want those derived classes to be able to raise the event? If the answer to either of these questions is \"no\" then don't bother. If the answer to both is \"yes\" then do :)</p>\n"
},
{
"answer_id": 231548,
"author": "Cristian Libardo",
"author_id": 16526,
"author_profile": "https://Stackoverflow.com/users/16526",
"pm_score": 2,
"selected": false,
"text": "<p>Less code, more readable. Me like.</p>\n\n<p>If you're not interested in performance you can declare your event like this to avoid the null check:</p>\n\n<pre><code>public event EventHandler SomethingHappened = delegate{};\n</code></pre>\n"
},
{
"answer_id": 231568,
"author": "Isak Savo",
"author_id": 8521,
"author_profile": "https://Stackoverflow.com/users/8521",
"pm_score": 1,
"selected": false,
"text": "<p>You're not <em>\"ensuring\"</em> thread safety by assigning the handler to a local variable. Your method could still be interrupted after the assignment. If for example the class that used to listen for the event gets disposed during the interruption, you're calling a method in a disposed class.</p>\n\n<p>You're saving yourself from a null reference exception, but there are easier ways to do that, as Jon Skeet and cristianlibardo pointed out in their answers.</p>\n\n<p>Another thing is that for non-sealed classes, the OnFoo method should be virtual which I don't think is possible with extension methods.</p>\n"
},
{
"answer_id": 231673,
"author": "Robert Paulson",
"author_id": 14033,
"author_profile": "https://Stackoverflow.com/users/14033",
"pm_score": 3,
"selected": false,
"text": "<p>[Here's a thought] </p>\n\n<p>Just write the code once in the recommended way and be done with it. Then you won't confuse your colleagues looking over the code thinking you did something wrong? </p>\n\n<p>[I read more posts trying to find ways around writing an event handler than I ever spend writing an event handler.]</p>\n"
},
{
"answer_id": 32015254,
"author": "Bob Sammers",
"author_id": 305237,
"author_profile": "https://Stackoverflow.com/users/305237",
"pm_score": 4,
"selected": false,
"text": "<p>Now C# 6 is here, there is a more compact, thread-safe way to fire an event:</p>\n\n<pre><code>SomethingHappened?.Invoke(this, e);\n</code></pre>\n\n<p><code>Invoke()</code> is only called if delegates are registered for the event (i.e. it's not null), thanks to the null-conditional operator, \"?\".</p>\n\n<p>The threading problem the \"handler\" code in the question sets out to solve is sidestepped here because, like in that code, <code>SomethingHappened</code> is only accessed once, so there is no possibility of it being set to null between test and invocation.</p>\n\n<p>This answer is perhaps tangential to the original question, but very relevent for those looking for a simpler method to raise events.</p>\n"
},
{
"answer_id": 57095184,
"author": "Bill Tarbell",
"author_id": 1721136,
"author_profile": "https://Stackoverflow.com/users/1721136",
"pm_score": 0,
"selected": false,
"text": "<p>To take the above answers a step further you could protect yourself against one of your handlers throwing an exception. If this were to happen then the subsequent handlers wouldn't be called.</p>\n\n<p>Likewise, you could taskify the handlers to prevent a long-running handler from causing an excessive delay for the latter handlers to be informed. This can also protect the source thread from being hijacked by a long-running handler.</p>\n\n<pre><code> public static class EventHandlerExtensions\n {\n private static readonly log4net.ILog _log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);\n\n public static void Taskify(this EventHandler theEvent, object sender, EventArgs args)\n {\n Invoke(theEvent, sender, args, true);\n }\n\n public static void Taskify<T>(this EventHandler<T> theEvent, object sender, T args)\n {\n Invoke(theEvent, sender, args, true);\n }\n\n public static void InvokeSafely(this EventHandler theEvent, object sender, EventArgs args)\n {\n Invoke(theEvent, sender, args, false);\n }\n\n public static void InvokeSafely<T>(this EventHandler<T> theEvent, object sender, T args)\n {\n Invoke(theEvent, sender, args, false);\n }\n\n private static void Invoke(this EventHandler theEvent, object sender, EventArgs args, bool taskify)\n {\n if (theEvent == null)\n return;\n\n foreach (EventHandler handler in theEvent.GetInvocationList())\n {\n var action = new Action(() =>\n {\n try\n {\n handler(sender, args);\n }\n catch (Exception ex)\n {\n _log.Error(ex);\n }\n });\n\n if (taskify)\n Task.Run(action);\n else\n action();\n }\n }\n\n private static void Invoke<T>(this EventHandler<T> theEvent, object sender, T args, bool taskify)\n {\n if (theEvent == null)\n return;\n\n foreach (EventHandler<T> handler in theEvent.GetInvocationList())\n {\n var action = new Action(() =>\n {\n try\n {\n handler(sender, args);\n }\n catch (Exception ex)\n {\n _log.Error(ex);\n }\n });\n\n if (taskify)\n Task.Run(action);\n else\n action();\n }\n }\n }\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5486/"
] |
We're all familiar with the horror that is C# event declaration. To ensure thread-safety, [the standard is to write something like this](http://blogs.msdn.com/brada/archive/2005/01/14/353132.aspx):
```
public event EventHandler SomethingHappened;
protected virtual void OnSomethingHappened(EventArgs e)
{
var handler = SomethingHappened;
if (handler != null)
handler(this, e);
}
```
Recently in some other question on this board (which I can't find now), someone pointed out that extension methods could be used nicely in this scenario. Here's one way to do it:
```
static public class EventExtensions
{
static public void RaiseEvent(this EventHandler @event, object sender, EventArgs e)
{
var handler = @event;
if (handler != null)
handler(sender, e);
}
static public void RaiseEvent<T>(this EventHandler<T> @event, object sender, T e)
where T : EventArgs
{
var handler = @event;
if (handler != null)
handler(sender, e);
}
}
```
With these extension methods in place, all you need to declare and raise an event is something like this:
```
public event EventHandler SomethingHappened;
void SomeMethod()
{
this.SomethingHappened.RaiseEvent(this, EventArgs.Empty);
}
```
My question: Is this a good idea? Are we missing anything by not having the standard On method? (One thing I notice is that it doesn't work with events that have explicit add/remove code.)
|
It will still work with events that have an explicit add/remove - you just need to use the delegate variable (or however you've stored the delegate) instead of the event name.
However, there's an easier way to make it thread-safe - initialize it with a no-op handler:
```
public event EventHandler SomethingHappened = delegate {};
```
The performance hit of calling an extra delegate will be negligible, and it sure makes the code easier.
By the way, in your extension method you don't need an extra local variable - you could just do:
```
static public void RaiseEvent(this EventHandler @event, object sender, EventArgs e)
{
if (@event != null)
@event(sender, e);
}
static public void RaiseEvent<T>(this EventHandler<T> @event, object sender, T e)
where T : EventArgs
{
if (@event != null)
@event(sender, e);
}
```
Personally I wouldn't use a keyword as a parameter name, but it doesn't really change the calling side at all, so do what you want :)
EDIT: As for the "OnXXX" method: are you planning on your classes being derived from? In my view, most classes should be sealed. If you *do*, do you want those derived classes to be able to raise the event? If the answer to either of these questions is "no" then don't bother. If the answer to both is "yes" then do :)
|
231,538 |
<p>So I have a snazzy custom route for login</p>
<pre><code># routes.rb
map.login '/login', :controller => 'sessions', :action => 'new'
</code></pre>
<p>Visit www.asite.com/login and you're there. As is custom with failed login, however, we'll do the following in our action. Note what happens on failed login.</p>
<pre><code> # sessions_controller.rb
def create
self.current_user = User.authenticate(params[:email], params[:password])
if logged_in?
# some work and redirect the user
else
flash.now[:warning] = "The email and/or password you entered is invalid."
render :action => 'new'
end
end
</code></pre>
<p>This is very typical. Simply render the new action and prompt for login again. Unfortunately you also get with it an ugly URL: www.asite.com/session. Ick! Is it possible to get rendering to respect the original URL?</p>
|
[
{
"answer_id": 231625,
"author": "Michael Sepcot",
"author_id": 6033,
"author_profile": "https://Stackoverflow.com/users/6033",
"pm_score": 0,
"selected": false,
"text": "<p>Change <code>render :action => 'new'</code> to <code>redirect_to login_path</code></p>\n"
},
{
"answer_id": 232888,
"author": "tomafro",
"author_id": 7126,
"author_profile": "https://Stackoverflow.com/users/7126",
"pm_score": 3,
"selected": false,
"text": "<p>Your problem is this: the user first visits <code>/login</code> and fills in the form. When they submit the form, they POST to <code>/sessions</code>, which is why the browser URL changes. To get around this you can do two things:</p>\n\n<p>As Michael mentioned, you can redirect back to the :new action, changing the else to:</p>\n\n<pre><code> else\n flash[:warning] = \"The email and/or password you entered is invalid.\"\n redirect_to login_path\n end\n</code></pre>\n\n<p>Note that you'll need to change the flash so the message is available in the next request (following the redirect).</p>\n\n<p>The second method is slightly hackier, but maybe worth mentioning. By using conditions on your routes, you can map both the login form (which is a GET) and the form submit (which is a POST) to the same path. Something like:</p>\n\n<pre><code>map.login '/login',\n :controller => 'sessions', :action => 'new', \n :conditions => {:method => :get}\n\nmap.login_submit '/login',\n :controller => 'sessions', :action => 'create', \n :conditions => {:method => :post}\n</code></pre>\n\n<p>Then if your form action is login submit path, things should work as you expect.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14895/"
] |
So I have a snazzy custom route for login
```
# routes.rb
map.login '/login', :controller => 'sessions', :action => 'new'
```
Visit www.asite.com/login and you're there. As is custom with failed login, however, we'll do the following in our action. Note what happens on failed login.
```
# sessions_controller.rb
def create
self.current_user = User.authenticate(params[:email], params[:password])
if logged_in?
# some work and redirect the user
else
flash.now[:warning] = "The email and/or password you entered is invalid."
render :action => 'new'
end
end
```
This is very typical. Simply render the new action and prompt for login again. Unfortunately you also get with it an ugly URL: www.asite.com/session. Ick! Is it possible to get rendering to respect the original URL?
|
Your problem is this: the user first visits `/login` and fills in the form. When they submit the form, they POST to `/sessions`, which is why the browser URL changes. To get around this you can do two things:
As Michael mentioned, you can redirect back to the :new action, changing the else to:
```
else
flash[:warning] = "The email and/or password you entered is invalid."
redirect_to login_path
end
```
Note that you'll need to change the flash so the message is available in the next request (following the redirect).
The second method is slightly hackier, but maybe worth mentioning. By using conditions on your routes, you can map both the login form (which is a GET) and the form submit (which is a POST) to the same path. Something like:
```
map.login '/login',
:controller => 'sessions', :action => 'new',
:conditions => {:method => :get}
map.login_submit '/login',
:controller => 'sessions', :action => 'create',
:conditions => {:method => :post}
```
Then if your form action is login submit path, things should work as you expect.
|
231,550 |
<p>I'd like to use the <a href="https://developer.mozilla.org/en/Rhino_JavaScript_Compiler" rel="nofollow noreferrer">Rhino JavaScript</a> compiler to compile some JavaScript to .class bytecode files for use in a project. It seems like this should already exist, since there are groovyc, netrexxc, and jythonc tasks for Groovy, NetREXX(!) and Jython, respectively. Has anyone used or written such an Ant task, or can anyone provide some tips on how to write one?</p>
<p>Ideally it would have some way to resolve dependencies among JavaScript or Java classes.</p>
|
[
{
"answer_id": 231750,
"author": "Vladimir Dyuzhev",
"author_id": 1163802,
"author_profile": "https://Stackoverflow.com/users/1163802",
"pm_score": 4,
"selected": true,
"text": "<p>Why not simply use java task?</p>\n\n<pre><code><java fork=\"yes\" \n classpathref=\"build.path\" \n classname=\"org.mozilla.javascript.tools.jsc.Main\" \n failonerror=\"true\">\n <arg value=\"-debug\"/>\n ...\n <arg value=\"file.js\"/> \n</java>\n</code></pre>\n\n<p>Any objections?</p>\n"
},
{
"answer_id": 1140411,
"author": "Joseph Montanez",
"author_id": 134617,
"author_profile": "https://Stackoverflow.com/users/134617",
"pm_score": 3,
"selected": false,
"text": "<p>Here is a sample build.xml I use for my rhino applications. If you have lots of javascript files you just need to keep adding more tags<br />\n~:ant compile jar run</p>\n\n<pre><code><project>\n<target name=\"compile\">\n <mkdir dir=\"build/classes\"/>\n <java fork=\"yes\" \n classpath=\"js.jar\" \n classname=\"org.mozilla.javascript.tools.jsc.Main\" \n failonerror=\"true\">\n <arg value=\"-nosource\"/>\n <arg value=\"-opt\"/>\n <arg value=\"9\"/>\n <arg value=\"-version\"/>\n <arg value=\"170\"/>\n <arg value=\"src/SwingApplication.js\"/>\n </java>\n <move todir=\"build/classes\">\n <fileset dir=\"src\">\n <include name=\"**/*.class\"/>\n </fileset>\n </move>\n</target>\n<target name=\"jar\">\n <mkdir dir=\"build/jar\"/>\n <jar destfile=\"build/jar/SwingApplication.jar\" basedir=\"build/classes\">\n <zipfileset src=\"js.jar\" includes=\"**/*.class\"/>\n <manifest>\n <attribute name=\"Main-Class\" value=\"SwingApplication\"/>\n </manifest>\n </jar>\n</target>\n<target name=\"run\">\n <exec executable=\"java\">\n <arg valUe=\"-jar\"/>\n <arg value=\"build/jar/SwingApplication.jar\"/>\n </exec>\n</target>\n</project>\n</code></pre>\n\n<p>~ </p>\n"
},
{
"answer_id": 3567406,
"author": "jbeard4",
"author_id": 366856,
"author_profile": "https://Stackoverflow.com/users/366856",
"pm_score": 3,
"selected": false,
"text": "<p>I'm using <a href=\"http://requirejs.org/\" rel=\"noreferrer\">RequireJS</a> in my project, which includes a script that traces out dependencies between modules, and combines them into a single JavaScript file. Optionally, it can also minify the combined js file with the Google Closure compiler. Once it's in this form, where all dependencies are included in a single js file, the file can be easily compiled using jsc. </p>\n\n<p>Here's a segment of my ant script which I use to create the single combined js file, compile it to a class file, and then create an executable JAR:</p>\n\n<pre><code><target name=\"compile-single-js\">\n <mkdir dir=\"${build-js}\"/>\n\n <java classname=\"org.mozilla.javascript.tools.shell.Main\">\n <classpath>\n <path refid=\"rhino-classpath\"/>\n <path refid=\"closure-classpath\"/>\n </classpath>\n <arg value=\"${js-build-script}\"/>\n <arg value=\"${js-build-dir}\"/>\n <arg value=\"name=${build-js-main-rhino-frontend-module}\"/> \n <arg value=\"out=${build-js-main}\"/>\n <arg value=\"baseUrl=.\"/>\n <arg value=\"includeRequire=true\"/>\n <arg value=\"inlineText=true\"/> \n <arg value=\"optimize=none\"/>\n </java>\n</target>\n\n<target name=\"compile-single-class\" depends=\"compile-single-js\">\n <mkdir dir=\"${build-class}\"/>\n\n <!-- TODO: set -opt -->\n <java classname=\"org.mozilla.javascript.tools.jsc.Main\">\n <classpath>\n <path refid=\"rhino-classpath\"/>\n </classpath>\n <arg value=\"-o\"/>\n <arg value=\"${build-class-main-name}.class\"/>\n <arg value=\"${build-js-main}\"/>\n </java>\n <move file=\"${build-js}/${build-class-main-name}.class\" todir=\"${build-class}\"/>\n</target>\n\n<target name=\"jar-single-class\" depends=\"compile-single-class\">\n <mkdir dir=\"${build-jar}\"/>\n\n <jar destfile=\"${build-jar-main}\"\n basedir=\"${build-class}\"\n includes=\"${build-class-main-name}.class\">\n <manifest>\n <attribute name=\"Main-Class\" value=\"${build-class-main-name}\" />\n </manifest>\n </jar>\n</target>\n</code></pre>\n\n<p>The complete build script can be found <a href=\"https://svn.apache.org/repos/asf/commons/sandbox/gsoc/2010/scxml-js/trunk/build.xml\" rel=\"noreferrer\">here</a>.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28604/"
] |
I'd like to use the [Rhino JavaScript](https://developer.mozilla.org/en/Rhino_JavaScript_Compiler) compiler to compile some JavaScript to .class bytecode files for use in a project. It seems like this should already exist, since there are groovyc, netrexxc, and jythonc tasks for Groovy, NetREXX(!) and Jython, respectively. Has anyone used or written such an Ant task, or can anyone provide some tips on how to write one?
Ideally it would have some way to resolve dependencies among JavaScript or Java classes.
|
Why not simply use java task?
```
<java fork="yes"
classpathref="build.path"
classname="org.mozilla.javascript.tools.jsc.Main"
failonerror="true">
<arg value="-debug"/>
...
<arg value="file.js"/>
</java>
```
Any objections?
|
231,553 |
<p>As an amateur software developer (I'm still in academia) I've written a few schemas for XML documents. I routinely run into design flubs that cause ugly-looking XML documents because I'm not entirely certain what the semantics of XML exactly are.</p>
<p>My assumptions:</p>
<pre><code><property> value </property>
</code></pre>
<p>property = value</p>
<pre><code><property attribute="attval"> value </property>
</code></pre>
<p>A property with a special descriptor, the attribute.</p>
<pre><code><parent>
<child> value </child>
</parent>
</code></pre>
<p>The parent has a characteristic "child" which has the value "value."</p>
<pre><code><tag />
</code></pre>
<p>"Tag" is a flag or it directly translates to text. I'm not sure on this one.</p>
<pre><code><parent>
<child />
</parent>
</code></pre>
<p>"child" describes "parent." "child" is a flag or boolean. I'm not sure on this one, either.</p>
<p>Ambiguity arises if you want to do something like representing cartesian coordinates:</p>
<pre><code><coordinate x="0" y="1" />
<coordinate> 0,1 </coordinate>
<coordinate> <x> 0 </x> <y> 1 </y> </coordinate>
</code></pre>
<p>Which one of these options is most correct? I would lean towards the third based upon my current conception of XML schema design, but I really don't know.</p>
<p>What are some resources that succinctly describe how to effectively design xml schemas?</p>
|
[
{
"answer_id": 231578,
"author": "Rob Wells",
"author_id": 2974,
"author_profile": "https://Stackoverflow.com/users/2974",
"pm_score": 0,
"selected": false,
"text": "<p>Look at the relationships of the data you are trying to represent is the best approach that I've found.</p>\n"
},
{
"answer_id": 231586,
"author": "Greg Beech",
"author_id": 13552,
"author_profile": "https://Stackoverflow.com/users/13552",
"pm_score": 2,
"selected": false,
"text": "<p>XML is somewhat subjective in terms of design - I don't think there are exact guidelines for how the elements and attributes should be laid out, but I tend to go with using elements to represent 'things' and attributes to represent singular attributes/properties of them. </p>\n\n<p>In terms of the coordinates example either would be perfectly acceptable, but my inclination would be to go with <code><coordinate x=\"\" y=\"\"/></code> because it is somewhat more terse, and makes the document a little more readable if you have many of them.</p>\n\n<p>The most important thing, though, is the namespace of the schema. Make sure that (a) you have one, and (b) you have a version in there so you can change things in the future and issue a new version. Versions may be either dates or numbers, e.g.</p>\n\n<pre><code>http://company.com/2008/12/something/somethingelse/\nurn:company-com:2008-12:something:somethingelse\n\nhttp://company.com/v1/something/somethingelse/\nurn:company-com:v1:something:somethingelse\n</code></pre>\n"
},
{
"answer_id": 231595,
"author": "Kris",
"author_id": 18565,
"author_profile": "https://Stackoverflow.com/users/18565",
"pm_score": 0,
"selected": false,
"text": "<p>I often find myself struggling with the same issue but I find that in practice it doesn't really matter, xml is just data.</p>\n\n<p>That said, I usually prefer the \"if it says something about the node it's an attribute, otherwise it's a childnode\" approach.</p>\n\n<p>In your example i'd go for:</p>\n\n<pre><code><coordinate>\n <x>0</x>\n <y>1</y>\n</coordinate>\n</code></pre>\n\n<p>because the x and y are properties of a coordinate, not actually saying anything about the xml, but about the object represented by it.</p>\n"
},
{
"answer_id": 231629,
"author": "Jeff Yates",
"author_id": 23234,
"author_profile": "https://Stackoverflow.com/users/23234",
"pm_score": 1,
"selected": false,
"text": "<p>When designing an XML-based format, it's often good to think about what you're representing. Try mocking some XML data that fits the purpose you intend. Once you've got something you're satisfied with that meets your requirements, develop the schema to validate it.</p>\n\n<p>When desiging a format, I tend to use elements for holding data content and attributes for applying characteristics to the data like an id, a name, a type, or some other metadata about the data an element contains.</p>\n\n<p>In that regard, an XML representation for coordinates might be:</p>\n\n<pre><code><coordinate type=\"cartesian\">\n <ordinate name=\"x\">0</ordinate>\n <ordinate name=\"y\">1</ordinate>\n</coordinate>\n</code></pre>\n\n<p>This caters for different coordinate systems. If you knew they'd always be cartesian, a better implementation might be:</p>\n\n<pre><code><coordinate>\n <x>0</x>\n <y>1</y>\n</coordinate>\n</code></pre>\n\n<p>Of course, the latter could lead to a more verbose schema as each element type would need declaring (though I'd hope a complex type was defined to actually do the hard work for these elements).</p>\n\n<p>Just as in programming, there are often multiple ways of achieving the same ends, but there is no right and wrong in many situations, just better and worse. The important thing is to remain consistent and try to be intuitive so that when others look at your schema, they can understand what you were trying to achieve.</p>\n\n<p>You should always version your schemas and ensure that XML written against your schema indicates it as such. If you don't properly version the XML then making addendums to the schema while supporting XML written to the older schema will be much more difficult.</p>\n"
},
{
"answer_id": 231631,
"author": "shahkalpesh",
"author_id": 23574,
"author_profile": "https://Stackoverflow.com/users/23574",
"pm_score": 0,
"selected": false,
"text": "<p>I guess, it depends on how complex or simple the structure is.<br>\nI will make x and y as attribute, unless x and y have their own details</p>\n\n<p>You can look at HTML or any other form of markup, which is used to define things (XAML in case of WPF, MXML in case of flash) to understand, why something is chosen as attribute as against a child node)</p>\n\n<p>if x and y are not to be repeated, they can be attributes.</p>\n\n<p>Lets say co-ordinates has multiple x and y, I guess xml doesnt allow multiple attributes with same name for a node. In that case, you will have to use child nodes.</p>\n"
},
{
"answer_id": 231633,
"author": "BQ.",
"author_id": 4632,
"author_profile": "https://Stackoverflow.com/users/4632",
"pm_score": 0,
"selected": false,
"text": "<p>There's nothing inherently wrong with using an element or sub-element for every value you'd like to represent.</p>\n\n<p>The main consideration is that sometimes it's cleaner to use an attribute. Since an element can only have one attribute of a given name, you're stuck with a 1:1 cardinality. If you're representing the data as a child element, you can use whatever cardinality you'd like (or be open to extending it later).</p>\n\n<p>Rob Wells' response above is right: it depends on the relationships you're trying to model.</p>\n\n<p>Any time there's clearly never going to be anything but a 1:1 relationship, an attribute may be cleaner.</p>\n"
},
{
"answer_id": 231654,
"author": "ddaa",
"author_id": 11549,
"author_profile": "https://Stackoverflow.com/users/11549",
"pm_score": 2,
"selected": false,
"text": "<p>I do not know any good learning resource about how to design XML document models (schemas are just a formal way of specifying document models).</p>\n\n<p>In my opinion, one crucial insight to XML is that it is not a language: it is a syntax. And each document model is a separate language.</p>\n\n<p>Different cultures will each use XML in their own special way. Even within W3C specifications you can smell Lisp in dash-separated-names of XSLT, and Java in the camelCaseNames of XML Schema. Similarly, different application domains will call for different XML idioms.</p>\n\n<p>Narrative document models such as <a href=\"http://www.w3.org/TR/REC-html40/\" rel=\"nofollow noreferrer\">HTML</a> or <a href=\"http://www.docbook.org/\" rel=\"nofollow noreferrer\">DocBook</a> tend to put printable text in text nodes and metadata in element names and attributes.</p>\n\n<p>More object-oriented document models such as <a href=\"http://www.w3.org/TR/SVG11/\" rel=\"nofollow noreferrer\">SVG</a> make little or no use of text nodes and instead only use elements and attributes.</p>\n\n<p>My personal rules of thumb for document model design go something like this:</p>\n\n<ul>\n<li>If it is the sort of the free-from tag soup that requires <a href=\"http://www.w3.org/TR/REC-xml/#sec-mixed-content\" rel=\"nofollow noreferrer\">mixed content</a>, use HTML and DocBook as sources of inspiration. The other rules are only relevant otherwise.</li>\n<li>If a value is going to be composite or hierarchical, use elements. XML data should require no further parsing, except for established idioms such as IDREFS which are simple space-separated sequences.</li>\n<li>If a value may need to occur more than once, use elements.</li>\n<li>If a value may need to be refined further, or enriched later, use elements.</li>\n<li>If a value is clearly atomic (boolean, number, date, identifier, simple label), and may occur at most once, then use an attribute.</li>\n</ul>\n\n<p>Another way to say it could be:</p>\n\n<ul>\n<li>If it's narrative, it's not object oriented.</li>\n<li>If it's object oriented, model objects as elements and atomic attributes as attributes.</li>\n</ul>\n\n<p>EDIT: Some people seem to like to entirely forgo attributes. There's nothing <em>wrong</em> with it, but I dislike it as it bloats documents and make them unnecessary hard to read and write by hand.</p>\n"
},
{
"answer_id": 231684,
"author": "C. Dragon 76",
"author_id": 5682,
"author_profile": "https://Stackoverflow.com/users/5682",
"pm_score": 5,
"selected": false,
"text": "<p>One general (but important!) recommendation is never to store multiple logical pieces of data in a single node (be it a text node or an attribute node). Otherwise, you end up needing your own parsing logic <strong>on top of</strong> the XML parsing logic you normally get for free from your framework.</p>\n\n<p>So in your coordinate example,\n<code><coordinate x=\"0\" y=\"1\" /></code>\nand\n<code><coordinate> <x>0</x> <y>1</y> </coordinate></code>\nare both reasonable to me.</p>\n\n<p>But <code><coordinate> 0,1 </coordinate></code> isn’t very good, because it’s storing two logical pieces of data (the X-coordinate and the Y-coordinate) in a single XML node—forcing the consumer to parse the data <strong>outside</strong> of their XML parser. And while splitting a string by a comma is pretty simple, there are still some ambiguities like what happens if there's an extra comma at the end.</p>\n"
},
{
"answer_id": 232314,
"author": "6eorge Jetson",
"author_id": 23422,
"author_profile": "https://Stackoverflow.com/users/23422",
"pm_score": 4,
"selected": false,
"text": "<p>I agree w/ cdragon's advice below to avoid option #2. The choice between #1 & #3 is largely a matter of style. I like to use attributes for what I consider to be attributes of the entity, and elements for what I consider to be data. Sometimes, it's hard to classify. Nonetheless, neither are \"wrong\".</p>\n\n<p>And while we're on the topic of schema design, I'll add my two cents regarding my preferred level of (maximum) reuse (of both elements and types), which can also facilitate external \"logical\" referencing of these entities in, say, a data dictionary stored in a database. </p>\n\n<p>Note that while the \"Garden of Eden\" schema pattern offers the maximum reuse, it also involves the most work. At the bottom of this post, I've provided links to the other patterns covered in the blog series.</p>\n\n<p>• <b>The Garden of Eden approach </b> <a href=\"http://blogs.msdn.com/skaufman/archive/2005/05/10/416269.aspx\" rel=\"noreferrer\">http://blogs.msdn.com/skaufman/archive/2005/05/10/416269.aspx</a> <blockquote>\nUses a modular approach by defining all elements globally and like the Venetian Blind approach all type definitions are declared globally. Each element is globally defined as an immediate child of the node and its type attribute can be set to one of the named complex types. \n</blockquote></p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"UTF-8\"?> \n<xs:schema targetNamespace=\"TargetNamespace\" xmlns:TN=\"TargetNamespace\" \n xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" \n elementFormDefault=\"qualified\" attributeFormDefault=\"unqualified\"/> \n<xs:element name=\"BookInformation\" type=\"BookInformationType\"/> \n <xs:complexType name=\"BookInformationType\"/> \n <xs:sequence> \n <xs:element ref=\"Title\"/> \n <xs:element ref=\"ISBN\"/> \n <xs:element ref=\"Publisher\"/> \n <xs:element ref=\"PeopleInvolved\" maxOccurs=\"unbounded\"/> \n </xs:sequence> \n </xs:complexType> \n <xs:complexType name=\"PeopleInvolvedType\"> \n <xs:sequence> \n <xs:element name=\"Author\"/> \n </xs:sequence> \n </xs:complexType> \n <xs:element name=\"Title\"/> \n <xs:element name=\"ISBN\"/> \n <xs:element name=\"Publisher\"/> \n <xs:element name=\"PeopleInvolved\" type=\"PeopleInvolvedType\"/> \n</xs:schema>\n</code></pre>\n\n<blockquote>The advantage of this approach is that the schemas are reusable. Since both the elements and types are defined globally both are available for reuse. This approach offers the maximum amount of reusable content.\n\nThe disadvantages are the that the schema is verbose.\n\nThis would be an appropriate design when you are creating general libraries in which you can afford to make no assumptions about the scope of the schema elements and types and their use in other schemas particularly in reference to extensibility and modularity.</blockquote> \n\n<p><br/>Since every distinct type and element has a single global definition, these canonical particles/components can be related one-to-one to identifiers in a database. And while it may at first glance seem like a tiresome ongoing manual task to maintain the associations between the textual XSD particles/components and the database, SQL Server 2005 can in fact generate canonical schema component identifiers via the statement </p>\n\n<pre><code>CREATE XML SCHEMA COLLECTION\n</code></pre>\n\n<p><a href=\"http://technet.microsoft.com/en-us/library/ms179457.aspx\" rel=\"noreferrer\">http://technet.microsoft.com/en-us/library/ms179457.aspx</a></p>\n\n<p>Conversely, to construct a schema from the canonical particles, SQL Server 2005 provides the </p>\n\n<pre><code>SELECT xml_schema_namespace function\n</code></pre>\n\n<p><a href=\"http://technet.microsoft.com/en-us/library/ms191170.aspx\" rel=\"noreferrer\">http://technet.microsoft.com/en-us/library/ms191170.aspx</a></p>\n\n<p>ca·non·i·cal\n Related to Mathematics. (of an equation, coordinate, etc.) \n \"in simplest or standard form\"\n <a href=\"http://dictionary.reference.com/browse/canonical\" rel=\"noreferrer\">http://dictionary.reference.com/browse/canonical</a></p>\n\n<p>Other, easier to construct, but less resuable/more \"denormalized/redundant\" schema patterns include</p>\n\n<p>• <b>The Russian Doll approach </b><a href=\"http://blogs.msdn.com/skaufman/archive/2005/04/21/410486.aspx\" rel=\"noreferrer\">http://blogs.msdn.com/skaufman/archive/2005/04/21/410486.aspx</a> <blockquote>\nThe schema has one single global element - the root element. All other elements and types are nested progressively deeper giving it the name due to each type fitting into the one above it. Since the elements in this design are declared locally they will not be reusable through the import or include statements.</blockquote></p>\n\n<p>• <b>The the Salami Slice approach </b> <a href=\"http://blogs.msdn.com/skaufman/archive/2005/04/25/411809.aspx\" rel=\"noreferrer\">http://blogs.msdn.com/skaufman/archive/2005/04/25/411809.aspx</a> <blockquote>\nAll elements are defined globally but the type definitions are defined locally. This way other schemas may reuse the elements. With this approach, a global element with its locally defined type provide a complete description of the elements content. This information 'slice' is declared individually and then aggregated back together and may also be pieced together to construct other schemas.</blockquote></p>\n\n<p>• <b>The Venetian Blind approach </b> <a href=\"http://blogs.msdn.com/skaufman/archive/2005/04/29/413491.aspx\" rel=\"noreferrer\">http://blogs.msdn.com/skaufman/archive/2005/04/29/413491.aspx</a> <blockquote>\nSimilar to the Russian Doll approach in that they both use a single global element. The Venetian Blind approach describes a modular approach by naming and defining all type definitions globally (as opposed to the Salami Slice approach which declares elements globally and types locally). Each globally defined type describes an individual \"slat\" and can be reused by other components. In addition, all the locally declared elements can be namespace qualified or namespace unqualified (the slats can be \"opened\" or \"closed\") depending on the elementFormDefault attribute setting at the top of the schema.</blockquote></p>\n"
},
{
"answer_id": 292815,
"author": "Hans-Peter Störr",
"author_id": 21499,
"author_profile": "https://Stackoverflow.com/users/21499",
"pm_score": 1,
"selected": false,
"text": "<p>In our Java-projects we are often using <a href=\"http://en.wikipedia.org/wiki/JAXB\" rel=\"nofollow noreferrer\">JAXB</a> to automatically parse XML and transform it into an object structure. I guess for other languagues you'll have something similar. A suitable generator can create automatically the object structure in your chosen programming language. This makes processing of XML often much easier, while still having a portable XML representation for the communication between systems.</p>\n\n<p>If you do use such an automatic mapping, you will find this constrains the schema much - <code><coordinate> <x> 0 </x> <y> 1 </y> </coordinate></code> is the way to go unless you want to do special magic in the translation. You will end up with a Class <code>Coordinate</code> with two attributes <code>x</code> and <code>y</code> with the appropriate type as declared in the schema.</p>\n"
},
{
"answer_id": 297833,
"author": "Dimitre Novatchev",
"author_id": 36305,
"author_profile": "https://Stackoverflow.com/users/36305",
"pm_score": 5,
"selected": true,
"text": "<p>See the tutorial: </p>\n\n<ul>\n<li>\"<a href=\"http://www.xfront.com/BestPracticesHomepage.html\" rel=\"noreferrer\"><strong>XML Schemas: Best Practices</strong></a>\" by <a href=\"http://www.xfront.com/\" rel=\"noreferrer\"><strong>Roger Costello</strong></a>.</li>\n</ul>\n\n<p>I also recommend:</p>\n\n<ul>\n<li><p><a href=\"http://www.datypic.com/about.html\" rel=\"noreferrer\"><strong>Priscilla Walmsley</strong></a>'s book \"<a href=\"https://rads.stackoverflow.com/amzn/click/com/0130655678\" rel=\"noreferrer\" rel=\"nofollow noreferrer\"><strong>Definitive XML Schema</strong></a>\".</p></li>\n<li><p><a href=\"http://www.jenitennison.com/\" rel=\"noreferrer\"><strong>Jeni Tennison</strong></a>'s <a href=\"http://www.jenitennison.com/schema/index.html\" rel=\"noreferrer\"><strong>XML Schema pages</strong></a></p></li>\n</ul>\n"
},
{
"answer_id": 1486590,
"author": "Zearin",
"author_id": 180290,
"author_profile": "https://Stackoverflow.com/users/180290",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://www.xmlpatterns.com\" rel=\"nofollow noreferrer\">Here</a> is a great list of methods for designing an XML grammar. </p>\n\n<p>As stated above it is a subjective practice, but this site gives some useful directions, such as “use this pattern to solve problem X”…or “advantages and disadvantages are…”.</p>\n"
},
{
"answer_id": 8947380,
"author": "Caleb",
"author_id": 630918,
"author_profile": "https://Stackoverflow.com/users/630918",
"pm_score": 0,
"selected": false,
"text": "<p>I've found the attribute form more manageable when dealing with Cartesian coordinates. My projects tend to require multiple namespaces, and sharing the coordinate type definition between namespaces gets ugly in the sub-element form. In the sub-element form, you have to either qualify the sub-elements, juggle namespaces on the base or root element, or default to unqualified element names (i.e. <a href=\"http://www.xfront.com/HideVersusExpose.pdf\" rel=\"nofollow\">namespace hiding</a>)</p>\n"
},
{
"answer_id": 42818192,
"author": "neves",
"author_id": 10335,
"author_profile": "https://Stackoverflow.com/users/10335",
"pm_score": 1,
"selected": false,
"text": "<p>I was designated to write a bunch of XML schemas to integrate my company systems with our clients. I've designed a dozen of them more than 10 years ago and saw that a lot of extension features in the specification didn't work well in practice. Before designing the new ones, I've searched for the current best practices (and arrived here!). </p>\n\n<p>Some of the tips above are useful, but I didn't like almost all references. The best place with design recommendations that I found were from Microsoft. </p>\n\n<p>The best reference is <a href=\"https://msdn.microsoft.com/en-us/library/aa468564.aspx\" rel=\"nofollow noreferrer\">XML Schema Design Patterns: Avoiding Complexity</a>. Here you will find this sane advice:</p>\n\n<blockquote>\n <p>it seems that many schema authors would be best served by\n understanding and utilizing an effective subset of the features\n provided by W3C XML Schema instead of attempting to comprehend all of\n the esoteric and minutiae of the language.</p>\n</blockquote>\n\n<p>and give detailed explanations of the following guidelines:</p>\n\n<ul>\n<li>Why you should use global and local element declarations</li>\n<li>Why you should use global and local attribute declarations</li>\n<li>Why you should understand how XML namespaces affect the W3C XML Schema</li>\n<li>Why you should always set elementFormDefault to \"qualified\"</li>\n<li>Why you should use attribute groups</li>\n<li>Why you should use model groups</li>\n<li>Why you should use the built-in simple types</li>\n<li>Why you should use complex types</li>\n<li>Why you should not use notation declarations</li>\n<li>Why you should use substitution groups carefully</li>\n<li>Why you should favor key/keyref/unique over ID/IDREF for identity constraints</li>\n<li>Why you should use chameleon schemas carefully</li>\n<li>Why you should not use default or fixed values especially for types of xs:QName</li>\n<li>Why you should use restriction and extension of simple types</li>\n<li>Why you should use extension of complex types</li>\n<li>Why you should use restriction of complex types carefully</li>\n<li>Why you should use abstract types carefully</li>\n<li>Do use wildcards to provide well-defined points of extensibility</li>\n<li>Do not use group or type redefinition</li>\n</ul>\n\n<p>My advice about their advice is that when they say <em>\"use carefully\"</em>, you should simply avoid it. My impression is that the Schema specification were not written by software developers. They tried to use some Object Orientation concepts but did a mess of it. A lot of the extension mechanisms are useless or extremely verbose. I don't really understand how someone could have invented the restriction of complex types.</p>\n\n<p>Two more nice articles in this site are:</p>\n\n<ul>\n<li><a href=\"https://msdn.microsoft.com/en-us/library/aa468563.aspx\" rel=\"nofollow noreferrer\">Schema Design Patterns: Dealing With Change</a></li>\n<li><a href=\"https://msdn.microsoft.com/en-us/library/aa468548.aspx\" rel=\"nofollow noreferrer\">XML Schema Design Patterns: Is Complex Type Derivation Unnecessary?</a></li>\n</ul>\n\n<p>And one tip that is pervasive is to specify your schemas with something different than the official specification. Relax NG looks the most favored specification language. Unfortunately you will loose one of the best features of it that is the standardization. </p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29119/"
] |
As an amateur software developer (I'm still in academia) I've written a few schemas for XML documents. I routinely run into design flubs that cause ugly-looking XML documents because I'm not entirely certain what the semantics of XML exactly are.
My assumptions:
```
<property> value </property>
```
property = value
```
<property attribute="attval"> value </property>
```
A property with a special descriptor, the attribute.
```
<parent>
<child> value </child>
</parent>
```
The parent has a characteristic "child" which has the value "value."
```
<tag />
```
"Tag" is a flag or it directly translates to text. I'm not sure on this one.
```
<parent>
<child />
</parent>
```
"child" describes "parent." "child" is a flag or boolean. I'm not sure on this one, either.
Ambiguity arises if you want to do something like representing cartesian coordinates:
```
<coordinate x="0" y="1" />
<coordinate> 0,1 </coordinate>
<coordinate> <x> 0 </x> <y> 1 </y> </coordinate>
```
Which one of these options is most correct? I would lean towards the third based upon my current conception of XML schema design, but I really don't know.
What are some resources that succinctly describe how to effectively design xml schemas?
|
See the tutorial:
* "[**XML Schemas: Best Practices**](http://www.xfront.com/BestPracticesHomepage.html)" by [**Roger Costello**](http://www.xfront.com/).
I also recommend:
* [**Priscilla Walmsley**](http://www.datypic.com/about.html)'s book "[**Definitive XML Schema**](https://rads.stackoverflow.com/amzn/click/com/0130655678)".
* [**Jeni Tennison**](http://www.jenitennison.com/)'s [**XML Schema pages**](http://www.jenitennison.com/schema/index.html)
|
231,592 |
<p>I have some char() fields in a DBF table that were left encrypted by a past developer in the project. </p>
<p>However, I know the plaintext result of the decryption of several records. How can I determine the function/algorithm/scheme to decrypt the original data?
These are some sample fields:</p>
<p>For cryptext:</p>
<pre><code>b5 01 02 c1 e3 0d 0a
</code></pre>
<p>plaintext should be:</p>
<pre><code>3543921 or 3.543.921
</code></pre>
<p>And for cryptext:</p>
<pre><code>41 c3 c5 07 17 0d 0a
</code></pre>
<p>plaintext should be</p>
<pre><code>1851154 or 1.851.154
</code></pre>
<p>I believe <code>0d 0a</code> is just padding. Was from data gathered in win-1252 encoding (dunno if matters)</p>
<p><strong>EDIT:</strong> It's for the sake of curiosity and learning. I want to be able to undestand the encryption used(seems a simple one, although is binary data) to recover the value of the fields for the tuples whose plaintext I don't know.</p>
<p><strong>EDIT 2:</strong> Added a couple samples.</p>
|
[
{
"answer_id": 231597,
"author": "warren",
"author_id": 4418,
"author_profile": "https://Stackoverflow.com/users/4418",
"pm_score": 1,
"selected": false,
"text": "<p>Determining the algorithm used without the corresponding key may not be entirely useful.</p>\n\n<p>If the text is small enough, and you have the plaintext, why would you ant to figure it out? Other than, of course, for curiosity sake?</p>\n"
},
{
"answer_id": 231602,
"author": "Douglas Mayle",
"author_id": 8458,
"author_profile": "https://Stackoverflow.com/users/8458",
"pm_score": 1,
"selected": false,
"text": "<p>There's no deterministic way to tell, but often there are hints in the ciphertext. Is it really encrypted (with some sort of key)? Or is it just hashed and (possibly) salted.</p>\n\n<p>If it's hashed, you could get lucky and just google for a matching pair (assuming you have any that are dictionary words) because there are pre-hashed dictionaries already online.</p>\n\n<p>If you have an example of the ciphertext, you could post it, someone might recognize the cipher format...</p>\n"
},
{
"answer_id": 231611,
"author": "Sergey",
"author_id": 29363,
"author_profile": "https://Stackoverflow.com/users/29363",
"pm_score": 3,
"selected": true,
"text": "<p>There is no easy way in general case. This question is too general. Try posting these plain + encrypted strings.</p>\n\n<p>EDIT: </p>\n\n<ul>\n<li>for the sake of learning you can read this article : <a href=\"http://en.wikipedia.org/wiki/Cryptography\" rel=\"nofollow noreferrer\">Cryptography on Wikipedia</a></li>\n<li><p>if you really beleive the encryption is simple - check if it's a byte (or word) level XOR - see the following pseudocode</p>\n\n<pre><code>for (i in originalString) {\nnewString[i] = originalString[i] ^ CRYPT_BYTE;\n}\n</code></pre></li>\n</ul>\n"
},
{
"answer_id": 231729,
"author": "Alexander",
"author_id": 16724,
"author_profile": "https://Stackoverflow.com/users/16724",
"pm_score": 2,
"selected": false,
"text": "<p>Assuming it's not something as simple as a substitution cipher (try frequency analysis) or a poorly applied XOR (e.g., reusing the key; try XORing two ciphertexts with known plaintexts and then see whether the result is the XOR of the plaintexts; or try XORing the ciphertext with itself shifted by some number of bytes), you should probably assume it's well-known stream/block cipher with an unknown key (which most likely consists of ASCII characters). If you have a big enough sample of ciphertext-plaintext pairs, you could start by checking whether plaintexts with the same first few characters/bytes have ciphertexts with the same first characters/bytes. There you might also see whether it's a block or a stream cipher and whether there is any feedback mechanism involved. Padding, if present, might also suggest that it's a block cipher rather than a stream cipher.</p>\n"
},
{
"answer_id": 231755,
"author": "TimB",
"author_id": 4193,
"author_profile": "https://Stackoverflow.com/users/4193",
"pm_score": 2,
"selected": false,
"text": "<p>Depending on how much effort you want to put into it, you should be able to get somewhere. Start by reading up on <a href=\"http://en.wikipedia.org/wiki/Cryptanalysis\" rel=\"nofollow noreferrer\">cryptanalysis</a>, in particular the <a href=\"http://en.wikipedia.org/wiki/Cryptanalysis#Methods_of_cryptanalysis\" rel=\"nofollow noreferrer\">methods of cryptanalysis</a>.</p>\n\n<p>The things that will determine how easy this task will be are:</p>\n\n<ul>\n<li>how good the encryption method used is; if it's a recent, well-regarded method such as RSA or AES, you're probably out of luck</li>\n<li>how much ciphertext and plaintext you have -- the more the better</li>\n<li>what kind of data it is -- simple text is the easiest, while random data would be the hardest</li>\n<li>whether the data is all encrypted with the same key, or whether multiple keys have been used.</li>\n</ul>\n\n<p>The key to success is don't be disheartened; the history of cryptanalysis is filled with stories of supposedly unbreakable codes being cracked; perhaps the most famous is the Enigma machine from World War II, the cracking of which contributed to the development of modern computers.</p>\n"
},
{
"answer_id": 232964,
"author": "Nick Johnson",
"author_id": 12030,
"author_profile": "https://Stackoverflow.com/users/12030",
"pm_score": 2,
"selected": false,
"text": "<p>We can tell a few things from what you've provided:</p>\n\n<ul>\n<li>With a ciphertext length of 7 bytes in each case, it's unlikely to be a block cipher (since block ciphers encrypt a block at a time, their length will be a multiple of the blocksize, and a blocksize of 56 bits is pretty unlikely*).</li>\n<li>The length of the ciphertext and the number of characters in the plaintext is the same in each case, so it could be straightforward encoding of numbers as ascii with a stream cipher applied.</li>\n<li>XORing the plaintext (as ascii) and the ciphertext together gives neither a single repeated octet nor the same cryptostream for each, so it's not a trivial cipher. It's also not a simple stream cipher using the same key for both, unless some of the ciphertext bytes are an IV.</li>\n<li>The last two bytes are identical in ciphertext but not in plaintext. This could be a coincidence but also could be indicative of padding as you suggest. If they are padding, some other encoding mechanism must be used.</li>\n</ul>\n\n<p>Do you know if all the encrypted values are integers, or are other values also possible?</p>\n"
},
{
"answer_id": 234383,
"author": "Ying Xiao",
"author_id": 30202,
"author_profile": "https://Stackoverflow.com/users/30202",
"pm_score": 0,
"selected": false,
"text": "<p>I think it's a misconception that XOR is an easily decryptable scheme. The theoretically strongest form of encryption is a one-time pad: simply a string of predetermined bits which you xor your plaintext with...</p>\n\n<p>Finite XORs, on the other hand...</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/861/"
] |
I have some char() fields in a DBF table that were left encrypted by a past developer in the project.
However, I know the plaintext result of the decryption of several records. How can I determine the function/algorithm/scheme to decrypt the original data?
These are some sample fields:
For cryptext:
```
b5 01 02 c1 e3 0d 0a
```
plaintext should be:
```
3543921 or 3.543.921
```
And for cryptext:
```
41 c3 c5 07 17 0d 0a
```
plaintext should be
```
1851154 or 1.851.154
```
I believe `0d 0a` is just padding. Was from data gathered in win-1252 encoding (dunno if matters)
**EDIT:** It's for the sake of curiosity and learning. I want to be able to undestand the encryption used(seems a simple one, although is binary data) to recover the value of the fields for the tuples whose plaintext I don't know.
**EDIT 2:** Added a couple samples.
|
There is no easy way in general case. This question is too general. Try posting these plain + encrypted strings.
EDIT:
* for the sake of learning you can read this article : [Cryptography on Wikipedia](http://en.wikipedia.org/wiki/Cryptography)
* if you really beleive the encryption is simple - check if it's a byte (or word) level XOR - see the following pseudocode
```
for (i in originalString) {
newString[i] = originalString[i] ^ CRYPT_BYTE;
}
```
|
231,630 |
<p>I want to override the default CreateObject() function in VBScript with my own.</p>
<p>Basically this example in VB6:</p>
<p><a href="http://www.darinhiggins.com/the-vb6-createobject-function/" rel="nofollow noreferrer">http://www.darinhiggins.com/the-vb6-createobject-function/</a></p>
<p>I cannot figure out is this line:</p>
<pre><code> Set CreateObject = VBA.CreateObject(Class$, ServerName$)
</code></pre>
<p>How do I refer to "VBA" in VBSript?</p>
|
[
{
"answer_id": 231657,
"author": "chadmyers",
"author_id": 10862,
"author_profile": "https://Stackoverflow.com/users/10862",
"pm_score": 0,
"selected": false,
"text": "<p>I don't think you can override it so that all code will use it, only YOUR code.</p>\n\n<p>In which case, it doesn't matter what it's called (unless you have tons of existing code you can't change). Can you call it CreateObjectEx() or ExCreateObject() or something like that? Have this function add all your error handling and such and then turn around and call the main/core CreateObject() method</p>\n"
},
{
"answer_id": 231701,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 2,
"selected": false,
"text": "<p>This quick test seems to work...</p>\n\n<pre><code>Function CreateObject(className, serverName)\n '---- override the CreateObject\n ' function in order to register what\n ' object is being created in any error message\n ' that's generated\n Dim source, descr, errNum\n\n WScript.echo \"In custom CreateObject\"\n If Len(serverName) > 0 Then\n Set CreateObject = WScript.CreateObject(className, serverName)\n Else\n Set CreateObject = WScript.CreateObject(className)\n End If\n\nEnd Function\n\nDim fso\nSet fso = CreateObject(\"Scripting.FileSystemObject\", \"\")\npath = fso.GetAbsolutePathName(\".\")\n\nWScript.echo path\n</code></pre>\n\n<p>No guarantees! ;-)</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I want to override the default CreateObject() function in VBScript with my own.
Basically this example in VB6:
<http://www.darinhiggins.com/the-vb6-createobject-function/>
I cannot figure out is this line:
```
Set CreateObject = VBA.CreateObject(Class$, ServerName$)
```
How do I refer to "VBA" in VBSript?
|
This quick test seems to work...
```
Function CreateObject(className, serverName)
'---- override the CreateObject
' function in order to register what
' object is being created in any error message
' that's generated
Dim source, descr, errNum
WScript.echo "In custom CreateObject"
If Len(serverName) > 0 Then
Set CreateObject = WScript.CreateObject(className, serverName)
Else
Set CreateObject = WScript.CreateObject(className)
End If
End Function
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject", "")
path = fso.GetAbsolutePathName(".")
WScript.echo path
```
No guarantees! ;-)
|
231,637 |
<p>I need to match (case insensitive) "abcd" and an optional trademark symbol</p>
<p>Regex: <code>/abcd(™)?/gi</code></p>
<p>See example:</p>
<pre><code>preg_match("/abcd(™)?/gi","AbCd™ U9+",$matches);
print_r($matches);
</code></pre>
<p>When I run this, <code>$matches</code> isn't populated with anything... Not even created as an empty array. Any ideas?</p>
|
[
{
"answer_id": 231648,
"author": "theraccoonbear",
"author_id": 7210,
"author_profile": "https://Stackoverflow.com/users/7210",
"pm_score": 2,
"selected": false,
"text": "<p>I suspect it has something to do with the literal trademark symbol.</p>\n\n<p>You'll probably want to check out how to use <a href=\"http://www.regular-expressions.info/unicode.html\" rel=\"nofollow noreferrer\">Unicode with your regular expressions</a>, and then embed the escape sequence for the <a href=\"http://www.fileformat.info/info/unicode/char/2122/index.htm\" rel=\"nofollow noreferrer\">trademark symbol</a>.</p>\n"
},
{
"answer_id": 231656,
"author": "Douglas Mayle",
"author_id": 8458,
"author_profile": "https://Stackoverflow.com/users/8458",
"pm_score": 4,
"selected": true,
"text": "<p>How is your file encoded? PHP has got issues when it comes to unicode. In your case, try using the escape sequence <code>\\x99</code> instead of directly embedding the TM symbol.</p>\n"
},
{
"answer_id": 231659,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Note:</strong> I'm not a PHP guru. However, this seems to be an issue about character encodings. For example, your PHP file could be encoded as win-1252 (where ™ is encoded as <code>\\x99</code>), and the data you are trying to match could be encoded as UTF-8 (where ™ is encoded as <code>\\xe2\\x84\\xa2</code>), or vice versa (i.e. your file is UTF-8 and your data is win-1252). Try looking in this direction, and give us more information about what you are doing.</p>\n"
},
{
"answer_id": 231697,
"author": "Ken Sykora",
"author_id": 53001,
"author_profile": "https://Stackoverflow.com/users/53001",
"pm_score": 2,
"selected": false,
"text": "<p>It was a combination of things... this was the regex that finally worked:</p>\n\n<pre><code>/abcd(\\xe2\\x84\\xa2)?/i\n</code></pre>\n\n<p>I had to remove <code>/g</code> modifier and change the tm symbol to <code>\\xe2\\x84\\xa2</code>.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/53001/"
] |
I need to match (case insensitive) "abcd" and an optional trademark symbol
Regex: `/abcd(™)?/gi`
See example:
```
preg_match("/abcd(™)?/gi","AbCd™ U9+",$matches);
print_r($matches);
```
When I run this, `$matches` isn't populated with anything... Not even created as an empty array. Any ideas?
|
How is your file encoded? PHP has got issues when it comes to unicode. In your case, try using the escape sequence `\x99` instead of directly embedding the TM symbol.
|
231,638 |
<p>I've downloaded the source for SubSonic via SVN. When I try to open the project in Visual Studio 2008, it converts the solution, loads all the projects then disappears without an error message. Subsequent loads of the solution do the same. If I run devenv /safemode and then open the project it works fine, but I can't use any add-ins.</p>
<p>Any ideas for tracking down the crash?</p>
<p>Edit: In event viewer: </p>
<pre>
Event Type: Error
Event Source: .NET Runtime Event
Category: None
Event ID: 1023
Date: 10/23/2008
Time: 4:45:05 PM
User: N/A
Computer: Foo
Description: .NET Runtime version 2.0.50727.3053 - Fatal Execution Engine Error (7A035E00) (80131506)
</pre>
|
[
{
"answer_id": 231687,
"author": "John Sheehan",
"author_id": 1786,
"author_profile": "https://Stackoverflow.com/users/1786",
"pm_score": 2,
"selected": false,
"text": "<p>This was a conflict with PowerCommands (see <a href=\"https://stackoverflow.com/questions/134131/aspnet-mvc-ctp5-crashing-ide\">ASP.NET MVC CTP5 Crashing IDE</a>)</p>\n"
},
{
"answer_id": 231698,
"author": "Gulzar Nazim",
"author_id": 4337,
"author_profile": "https://Stackoverflow.com/users/4337",
"pm_score": 2,
"selected": true,
"text": "<p>looks like this issue is reported:</p>\n\n<p><a href=\"http://code.msdn.microsoft.com/PowerCommands/WorkItem/View.aspx?WorkItemId=34\" rel=\"nofollow noreferrer\">http://code.msdn.microsoft.com/PowerCommands/WorkItem/View.aspx?WorkItemId=34</a></p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1786/"
] |
I've downloaded the source for SubSonic via SVN. When I try to open the project in Visual Studio 2008, it converts the solution, loads all the projects then disappears without an error message. Subsequent loads of the solution do the same. If I run devenv /safemode and then open the project it works fine, but I can't use any add-ins.
Any ideas for tracking down the crash?
Edit: In event viewer:
```
Event Type: Error
Event Source: .NET Runtime Event
Category: None
Event ID: 1023
Date: 10/23/2008
Time: 4:45:05 PM
User: N/A
Computer: Foo
Description: .NET Runtime version 2.0.50727.3053 - Fatal Execution Engine Error (7A035E00) (80131506)
```
|
looks like this issue is reported:
<http://code.msdn.microsoft.com/PowerCommands/WorkItem/View.aspx?WorkItemId=34>
|
231,647 |
<p>How do you set the timeout for blocking operations on a Ruby socket?</p>
|
[
{
"answer_id": 231662,
"author": "readonly",
"author_id": 4883,
"author_profile": "https://Stackoverflow.com/users/4883",
"pm_score": 5,
"selected": true,
"text": "<p>The solution I found which appears to work is to use <a href=\"http://www.ruby-doc.org/stdlib/libdoc/timeout/rdoc/index.html\" rel=\"noreferrer\">Timeout::timeout</a>:</p>\n\n<pre><code>require 'timeout'\n ...\nbegin \n timeout(5) do\n message, client_address = some_socket.recvfrom(1024)\n end\nrescue Timeout::Error\n puts \"Timed out!\"\nend\n</code></pre>\n"
},
{
"answer_id": 232761,
"author": "Jonke",
"author_id": 15638,
"author_profile": "https://Stackoverflow.com/users/15638",
"pm_score": 4,
"selected": false,
"text": "<p>The timeout object is a good solution.</p>\n\n<p>This is an example of asynchronous I/O (non-blocking in nature and occurs asynchronously to\nthe flow of the application.)</p>\n\n<pre><code>IO.select(read_array\n[, write_array\n[, error_array\n[, timeout]]] ) => array or nil\n</code></pre>\n\n<p>Can be used to get the same effect.</p>\n\n<pre><code>require 'socket'\n\nstrmSock1 = TCPSocket::new( \"www.dn.se\", 80 )\nstrmSock2 = TCPSocket::new( \"www.svd.se\", 80 )\n# Block until one or more events are received\n#result = select( [strmSock1, strmSock2, STDIN], nil, nil )\ntimeout=5\n\ntimeout=100\nresult = select( [strmSock1, strmSock2], nil, nil,timeout )\nputs result.inspect\nif result\n\n for inp in result[0]\n if inp == strmSock1 then\n # data avail on strmSock1\n puts \"data avail on strmSock1\"\n elsif inp == strmSock2 then\n # data avail on strmSock2\n puts \"data avail on strmSock2\"\n elsif inp == STDIN\n # data avail on STDIN\n puts \"data avail on STDIN\"\n end\n end\nend\n</code></pre>\n"
},
{
"answer_id": 2791280,
"author": "Pete Brumm",
"author_id": 335770,
"author_profile": "https://Stackoverflow.com/users/335770",
"pm_score": 3,
"selected": false,
"text": "<p>I think the non blocking approach is the way to go.<br>\nI tried the mentioned above article and could still get it to hang.<br>\nthis article <a href=\"http://peasleer.wordpress.com/2006/11/14/non-blocking-networking-in-ruby/\" rel=\"noreferrer\">non blocking networking</a> and the jonke's approach above got me on the right path. My server was blocking on the initial connect so I needed it to be a little lower level.<br>\nthe socket rdoc can give more details into the connect_nonblock</p>\n\n<pre><code>def self.open(host, port, timeout=10)\n addr = Socket.getaddrinfo(host, nil)\n sock = Socket.new(Socket.const_get(addr[0][0]), Socket::SOCK_STREAM, 0)\n\n begin\n sock.connect_nonblock(Socket.pack_sockaddr_in(port, addr[0][3]))\n rescue Errno::EINPROGRESS\n resp = IO.select([sock],nil, nil, timeout.to_i)\n if resp.nil?\n raise Errno::ECONNREFUSED\n end\n begin\n sock.connect_nonblock(Socket.pack_sockaddr_in(port, addr[0][3]))\n rescue Errno::EISCONN\n end\n end\n sock\nend\n</code></pre>\n\n<p>to get a good test. startup a simple socket server and then do a ctrl-z to background it</p>\n\n<p>the IO.select is expecting data to come in on the input stream within 10 seconds. this may not work if that is not the case. </p>\n\n<p>It should be a good replacement for the TCPSocket's open method. </p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
] |
How do you set the timeout for blocking operations on a Ruby socket?
|
The solution I found which appears to work is to use [Timeout::timeout](http://www.ruby-doc.org/stdlib/libdoc/timeout/rdoc/index.html):
```
require 'timeout'
...
begin
timeout(5) do
message, client_address = some_socket.recvfrom(1024)
end
rescue Timeout::Error
puts "Timed out!"
end
```
|
231,649 |
<p>With common lisp and I am assuming the introspection properties. How can I add code to common lisp code that will tell me when a function is called and when has finished executing. I want to take any lisp code and this particular modification to the code. I figure with lisp's AST analysis, this should be possible.</p>
|
[
{
"answer_id": 231796,
"author": "Godeke",
"author_id": 28006,
"author_profile": "https://Stackoverflow.com/users/28006",
"pm_score": 2,
"selected": false,
"text": "<p>Common lisp has a TRACE function that reports the function, arguments and resulting value of each call specified. Here is the doc page for Steel Bank's version, but you should find something similar in most implementations:</p>\n\n<p><a href=\"http://www.sbcl.org/manual/Function-Tracing.html\" rel=\"nofollow noreferrer\">http://www.sbcl.org/manual/Function-Tracing.html</a></p>\n\n<p>The system also includes a profiler: </p>\n\n<p><a href=\"http://www.sbcl.org/manual/Deterministic-Profiler.html\" rel=\"nofollow noreferrer\">http://www.sbcl.org/manual/Deterministic-Profiler.html</a></p>\n"
},
{
"answer_id": 232638,
"author": "dsm",
"author_id": 7780,
"author_profile": "https://Stackoverflow.com/users/7780",
"pm_score": 4,
"selected": true,
"text": "<p>You can use <a href=\"http://www.sbcl.org/manual/Function-Tracing.html\" rel=\"nofollow noreferrer\"><code>(trace function)</code></a> for a simple mechanism. For something more involved, here is a good discussion from <a href=\"http://groups.google.com/group/comp.lang.lisp/browse_thread/thread/75ddcdcc160508b0?pli=1\" rel=\"nofollow noreferrer\">comp.lang.lisp</a>.</p>\n\n<pre><code>[CL_USER]>\n(defun fac (n)\n \"Naïve factorial implementation\"\n (if (< 1 n)\n (* n (fac (- n 1)))\n 1))\nFAC\n[CL_USER]> (trace fac)\n;; Tracing function FAC.\n(FAC)\n[CL_USER]> (fac 5)\n1. Trace: (FAC '5)\n2. Trace: (FAC '4)\n3. Trace: (FAC '3)\n4. Trace: (FAC '2)\n5. Trace: (FAC '1)\n5. Trace: FAC ==> 1\n4. Trace: FAC ==> 2\n3. Trace: FAC ==> 6\n2. Trace: FAC ==> 24\n1. Trace: FAC ==> 120\n120\n[CL_USER]> \n</code></pre>\n"
},
{
"answer_id": 242180,
"author": "Tim Stewart",
"author_id": 26002,
"author_profile": "https://Stackoverflow.com/users/26002",
"pm_score": 2,
"selected": false,
"text": "<p>If <a href=\"http://en.wikipedia.org/wiki/Common_Lisp_Object_System\" rel=\"nofollow noreferrer\">CLOS</a> is an option, it has <a href=\"http://www.ravenbrook.com/doc/2003/07/15/clos-fundamentals/\" rel=\"nofollow noreferrer\">before, after, and around methods</a> that run before, after and around other methods.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10522/"
] |
With common lisp and I am assuming the introspection properties. How can I add code to common lisp code that will tell me when a function is called and when has finished executing. I want to take any lisp code and this particular modification to the code. I figure with lisp's AST analysis, this should be possible.
|
You can use [`(trace function)`](http://www.sbcl.org/manual/Function-Tracing.html) for a simple mechanism. For something more involved, here is a good discussion from [comp.lang.lisp](http://groups.google.com/group/comp.lang.lisp/browse_thread/thread/75ddcdcc160508b0?pli=1).
```
[CL_USER]>
(defun fac (n)
"Naïve factorial implementation"
(if (< 1 n)
(* n (fac (- n 1)))
1))
FAC
[CL_USER]> (trace fac)
;; Tracing function FAC.
(FAC)
[CL_USER]> (fac 5)
1. Trace: (FAC '5)
2. Trace: (FAC '4)
3. Trace: (FAC '3)
4. Trace: (FAC '2)
5. Trace: (FAC '1)
5. Trace: FAC ==> 1
4. Trace: FAC ==> 2
3. Trace: FAC ==> 6
2. Trace: FAC ==> 24
1. Trace: FAC ==> 120
120
[CL_USER]>
```
|
231,666 |
<p>I wonder if anyone could suggest the best way of looping through all the <code><option></code> s in a <code><select></code> element with jQuery, and building an array.</p>
<p>Eg.</p>
<p>Instead of the following, whereby a string ins passed to the autoCompleteArray(),</p>
<pre><code>$("#CityLocal").autocompleteArray(
[
"Aberdeen", "Ada", "Adamsville", "Zoar" //and a million other cities...
],
{
delay:10,
minChars:1,
matchSubset:1,
onItemSelect:selectItem,
onFindValue:findValue,
autoFill:true,
maxItemsToShow:10
}
);
</code></pre>
<p>...I need to loop through all the <code><options></code> in a <code><select></code> and push them into an array, and just pass that array variable to the function instead of a long string.</p>
<p>Eg,</p>
<pre><code>$("#CityLocal").autocompleteArray(
[
MyBigArrayOfOptions
],
{
delay:10,
minChars:1,
matchSubset:1,
onItemSelect:selectItem,
onFindValue:findValue,
autoFill:true,
maxItemsToShow:10
}
);
</code></pre>
<p>I'd be grateful if you could suggest how to push stuff into an array in the correct format. I've pretty much sussed the looping part from another post on this site.</p>
<p>Thanks.</p>
|
[
{
"answer_id": 231699,
"author": "Damir Zekić",
"author_id": 401510,
"author_profile": "https://Stackoverflow.com/users/401510",
"pm_score": 4,
"selected": true,
"text": "<p>This should work:</p>\n\n<pre><code>$(document).ready(function(){\n // array of option elements' values\n var optionValues = [];\n // array of option elements' text\n var optionTexts = [];\n\n // iterate through all option elements\n $('#sel > option').each(function() {\n // get value/text and push it into respective array\n optionValues.push($(this).val());\n optionTexts.push($(this).text());\n });\n\n // test with alert\n alert(optionValues);\n alert(optionTexts);\n});\n</code></pre>\n\n<p>Given that your <code>select</code> element has ID <em>sel</em>.</p>\n"
},
{
"answer_id": 231772,
"author": "Matt Ephraim",
"author_id": 22291,
"author_profile": "https://Stackoverflow.com/users/22291",
"pm_score": 3,
"selected": false,
"text": "<p>The <a href=\"http://docs.jquery.com/Utilities/jQuery.map#arraycallback\" rel=\"nofollow noreferrer\">jQuery.map</a> function might be what you're looking for. The code below will create an array that contains all of the values or text values for the <code><select></code> options.</p>\n\n<pre><code>var values = jQuery.map(jQuery(\"#select\")[0].options, function(option)\n {\n return option.value;\n });\n\nvar texts = jQuery.map(jQuery(\"#select\")[0].options, function(option)\n {\n return option.innerHTML;\n });\n</code></pre>\n"
},
{
"answer_id": 232195,
"author": "jcampbell1",
"author_id": 20512,
"author_profile": "https://Stackoverflow.com/users/20512",
"pm_score": 2,
"selected": false,
"text": "<p>All you need to do is pass the array as the first parameter without the brackets. Brackets create a new array, but you don't need to do that because you are already passing an array. Just do:</p>\n\n<pre><code>$(\"#CityLocal\").autocompleteArray(\n MyBigArrayOfOptions,\n {\n delay:10,\n minChars:1,\n matchSubset:1,\n onItemSelect:selectItem,\n onFindValue:findValue,\n autoFill:true,\n maxItemsToShow:10\n }\n );\n</code></pre>\n"
},
{
"answer_id": 232259,
"author": "Leo",
"author_id": 20689,
"author_profile": "https://Stackoverflow.com/users/20689",
"pm_score": 2,
"selected": false,
"text": "<p>If I understand your question corrently, the following code should do what you need:</p>\n\n<pre><code>myFunction($(\"#my-select option\"));\n</code></pre>\n\n<p>The output of the query is already an array of options that are descendants of the select, so you don't need to push them into another array. Alternatively, if your select doesn't have an id, but you have the DOM element:</p>\n\n<pre><code>myFunction($(\"option\", theSelect));\n</code></pre>\n\n<p>Plugging this idea back into your code:</p>\n\n<pre><code>$(\"#CityLocal\").autocompleteArray(\n $(\"option\", theSelect),\n {\n delay:10,\n minChars:1,\n matchSubset:1,\n onItemSelect:selectItem,\n onFindValue:findValue,\n autoFill:true,\n maxItemsToShow:10\n }\n);\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26107/"
] |
I wonder if anyone could suggest the best way of looping through all the `<option>` s in a `<select>` element with jQuery, and building an array.
Eg.
Instead of the following, whereby a string ins passed to the autoCompleteArray(),
```
$("#CityLocal").autocompleteArray(
[
"Aberdeen", "Ada", "Adamsville", "Zoar" //and a million other cities...
],
{
delay:10,
minChars:1,
matchSubset:1,
onItemSelect:selectItem,
onFindValue:findValue,
autoFill:true,
maxItemsToShow:10
}
);
```
...I need to loop through all the `<options>` in a `<select>` and push them into an array, and just pass that array variable to the function instead of a long string.
Eg,
```
$("#CityLocal").autocompleteArray(
[
MyBigArrayOfOptions
],
{
delay:10,
minChars:1,
matchSubset:1,
onItemSelect:selectItem,
onFindValue:findValue,
autoFill:true,
maxItemsToShow:10
}
);
```
I'd be grateful if you could suggest how to push stuff into an array in the correct format. I've pretty much sussed the looping part from another post on this site.
Thanks.
|
This should work:
```
$(document).ready(function(){
// array of option elements' values
var optionValues = [];
// array of option elements' text
var optionTexts = [];
// iterate through all option elements
$('#sel > option').each(function() {
// get value/text and push it into respective array
optionValues.push($(this).val());
optionTexts.push($(this).text());
});
// test with alert
alert(optionValues);
alert(optionTexts);
});
```
Given that your `select` element has ID *sel*.
|
231,677 |
<p>Given this in a grails action:</p>
<pre><code>def xml = {
rss(version: '2.0') {
...
}
}
render(contentType: 'application/rss+xml', xml)
</code></pre>
<p>I see this:</p>
<pre><code><rss><channel><title></title><description></description><link></link><item></item></channel></rss>
</code></pre>
<p>Is there an easy way to pretty print the XML? Something built into the render method, perhaps?</p>
|
[
{
"answer_id": 232101,
"author": "seansand",
"author_id": 9452,
"author_profile": "https://Stackoverflow.com/users/9452",
"pm_score": 4,
"selected": false,
"text": "<p>This is a simple way to pretty-print XML, using Groovy code only:</p>\n\n<pre><code>def xml = \"<rss><channel><title></title><description>\" +\n \"</description><link></link><item></item></channel></rss>\"\n\ndef stringWriter = new StringWriter()\ndef node = new XmlParser().parseText(xml);\nnew XmlNodePrinter(new PrintWriter(stringWriter)).print(node)\n\nprintln stringWriter.toString()\n</code></pre>\n\n<p>results in:</p>\n\n<pre><code><rss>\n <channel>\n <title/>\n <description/>\n <link/>\n <item/>\n </channel>\n</rss>\n</code></pre>\n"
},
{
"answer_id": 3459944,
"author": "Eric Levine",
"author_id": 3767,
"author_profile": "https://Stackoverflow.com/users/3767",
"pm_score": 3,
"selected": true,
"text": "<p>According to the <a href=\"http://grails.org/Converters+Reference\" rel=\"nofollow noreferrer\">reference docs</a>, you can use the following configuration option to enable pretty printing:</p>\n\n<pre><code> grails.converters.default.pretty.print (Boolean)\n //Whether the default output of the Converters is pretty-printed ( default: false )\n</code></pre>\n"
},
{
"answer_id": 6326835,
"author": "Captian Trips",
"author_id": 2133630,
"author_profile": "https://Stackoverflow.com/users/2133630",
"pm_score": 2,
"selected": false,
"text": "<p>Use MarkupBuilder to pretty-print your Groovy xml</p>\n\n<pre><code>def writer = new StringWriter()\ndef xml = new MarkupBuilder (writer)\n\nxml.rss(version: '2.0') {\n ...\n }\n}\n\nrender(contentType: 'application/rss+xml', writer.toString())\n</code></pre>\n"
},
{
"answer_id": 9507445,
"author": "Fabien Barbier",
"author_id": 103832,
"author_profile": "https://Stackoverflow.com/users/103832",
"pm_score": 2,
"selected": false,
"text": "<p>Use XmlUtil :</p>\n\n<pre><code>def xml = \"<rss><channel><title></title><description>\" +\n \"</description><link></link><item></item></channel></rss>\"\n\nprintln XmlUtil.serialize(xml)\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2031/"
] |
Given this in a grails action:
```
def xml = {
rss(version: '2.0') {
...
}
}
render(contentType: 'application/rss+xml', xml)
```
I see this:
```
<rss><channel><title></title><description></description><link></link><item></item></channel></rss>
```
Is there an easy way to pretty print the XML? Something built into the render method, perhaps?
|
According to the [reference docs](http://grails.org/Converters+Reference), you can use the following configuration option to enable pretty printing:
```
grails.converters.default.pretty.print (Boolean)
//Whether the default output of the Converters is pretty-printed ( default: false )
```
|
231,679 |
<p>To add a svg graphics in html page, it is common to use object tag to wrap it like this:</p>
<pre><code><object id="svgid" data="mysvg.svg" type="image/svg+xml"
wmode="transparent" width="100" height="100">
this browser is not able to show SVG: <a linkindex="3"
href="http://getfirefox.com">http://getfirefox.com</a>
is free and does it!
If you use Internet Explorer, you can also get a plugin:
<a linkindex="4" href="http://www.adobe.com/svg/viewer/install/main.html">
http://www.adobe.com/svg/viewer/install/main.html</a>
</object>
</code></pre>
<p>If you do not use width and height attributes in the object tag, the svg will be displayed in full size. Normally I get svg files from Open Graphics Library for testing. Is there any way to get svg's size by using JavaScript? Or maybe I should just look at the svg xml file to find out the size from the top svg tag?</p>
|
[
{
"answer_id": 233819,
"author": "Jon Cram",
"author_id": 5343,
"author_profile": "https://Stackoverflow.com/users/5343",
"pm_score": 3,
"selected": false,
"text": "<p><strong>> Is there any way to get svg's size by using JavaScript?</strong></p>\n\n<p>No and yes.</p>\n\n<p><strong>No:</strong></p>\n\n<p>JavaScript won't be able to access the SVG file contents that are sitting in the browser.</p>\n\n<p>So it wouldn't be possible to have a page containing an arbitrary SVG image and then have JavaScript determine anything from the SVG file itself.</p>\n\n<p>The only data JS can access it that contained within the page's DOM: the original markup plus any JS-related modifications to the DOM. You could access the <code>object</code> element's attributes and descendant nodes, but that won't give you visibility of anything more than what you can see if you look at the page markup yourself.</p>\n\n<p><strong>Yes:</strong></p>\n\n<p>JS (in modern browsers) can parse any XML string into a DOM and then access the content using DOM-based methods.</p>\n\n<p>You could get the SVG file contents by issuing an xmlHttpRequest-style request (i.e. JS performs an HTTP GET on the SVG file's URL). JS would then have the SVG file's full XML string and you can then access anything you like.</p>\n\n<p><strong>> Or maybe I should just look at the svg xml file to find out the size from the top svg tag?</strong></p>\n\n<p>This would be more feasible by far.</p>\n\n<p>The only JS-based solution would require JS to perform a GET request on the SVG file's URL (as above), which is unlikely to be feasible - each page load might result in double-downloading each SVG file, and the parsing of the SVG's XML into a DOM by JS might be too resource intensive.</p>\n\n<p>Having JS retrieve the SVG's XML content and parse it into a DOM to retrieve only the image dimensions is a bit overkill. It's perfectly possible, but generally not practical.</p>\n\n<p>Querying the SVG's XML content server-side, determining a suitable width and height and then dynamically adding the <code>width</code> and <code>height</code> attributes prior to returning markup to the browser would be your best bet.</p>\n"
},
{
"answer_id": 1577890,
"author": "codedread",
"author_id": 67838,
"author_profile": "https://Stackoverflow.com/users/67838",
"pm_score": 3,
"selected": false,
"text": "<p>See <a href=\"http://dev.opera.com/articles/view/svg-evolution-not-revolution/?page=2\" rel=\"noreferrer\">http://dev.opera.com/articles/view/svg-evolution-not-revolution/?page=2</a></p>\n\n<p>It is possible to get access to the SVG DOM referenced by an HTML:object as long as the SVG file is on the same domain (otherwise this would be a security vulnerability. If your object tag has id=\"myobj\" you would do:</p>\n\n<pre><code>var obj = document.getElementById(\"myobj\"); // reference to the object tag\nvar svgdoc = obj.contentDocument; // reference to the SVG document\nvar svgelem = svgdoc.documentElement; // reference to the SVG element\n</code></pre>\n\n<p>Then you can get access to the svg element's width/height by:</p>\n\n<pre><code>svgelem.getAttribute(\"width\")\nsvgelem.getAttribute(\"height\")\n</code></pre>\n\n<p>Note that these attributes may be things like \"100px\", \"300\", \"200em\", \"40mm\", \"100%\" so you need to carefully parse it.</p>\n"
},
{
"answer_id": 3951992,
"author": "Xaxis",
"author_id": 441047,
"author_profile": "https://Stackoverflow.com/users/441047",
"pm_score": -1,
"selected": false,
"text": "<blockquote>\n <p>Is there any way to get svg's size by\n using JavaScript?</p>\n</blockquote>\n\n<p><strong>YES</strong></p>\n\n<pre><code>var filesize = function(url, requestHandler) {\n var requestObj = new XMLHttpRequest(); \n requestObj.open('head', address, true); \n requestObj.onreadystatechange = callback;\n requestObj.send(null); \n};\n</code></pre>\n\n<p>Now a handling function:</p>\n\n<pre><code>var requestHandler = function(result) {\n if (this.readyState === 1) {\n this.abort();\n }\n return this.getResponseHeader(\"Content-length\");\n};\n\nvar size = fileSize(\"http://whatever.org/someSVGFile.svg\", requestHandler);\nalert(size); \n</code></pre>\n\n<p>That should return the filesize of your svg or any other file without a hitch. Server configuration is the only thing that might interfere.</p>\n"
},
{
"answer_id": 52411649,
"author": "Kamil Kiełczewski",
"author_id": 860099,
"author_profile": "https://Stackoverflow.com/users/860099",
"pm_score": 1,
"selected": false,
"text": "<p><strong>ES6</strong>: Using <code>async/await</code> you can do this in sequence-like way</p>\n\n<pre><code>async function getImage(url) {\n return new Promise((resolve, reject) => {\n let img = new Image();\n img.onload = () => resolve(img);\n img.onerror = reject;\n img.src = url;\n });\n}\n</code></pre>\n\n<p>and use above function</p>\n\n<pre><code>let img = await getImage(\"yourimage.svg\");\nlet w = img.width;\nlet h = img.height; \n</code></pre>\n\n<p>You can use it as long as the SVG file is on the same domain (details <a href=\"https://stackoverflow.com/a/43001137/860099\">here</a>). Working example</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>async function getImage(url) {\r\n return new Promise((resolve, reject) => {\r\n let img = new Image();\r\n img.onload = () => resolve(img);\r\n img.onerror = reject;\r\n img.src = url;\r\n });\r\n}\r\n\r\nasync function start() {\r\n // here is example url with embeded svg but you can use any url\r\n let svgURL = \"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' height='120' width='220'%3E%3Cellipse cx='110' cy='60' rx='100' ry='50' stroke='black' stroke-width='3' fill='red' /%3E%3C/svg%3E\";\r\n \r\n let img = await getImage(svgURL);\r\n let w = img.width;\r\n let h = img.height; \r\n \r\n // print\r\n console.log({w,h});\r\n pic.src = svgURL;\r\n}\r\n\r\nstart();</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><img id=\"pic\"></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231679",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/62776/"
] |
To add a svg graphics in html page, it is common to use object tag to wrap it like this:
```
<object id="svgid" data="mysvg.svg" type="image/svg+xml"
wmode="transparent" width="100" height="100">
this browser is not able to show SVG: <a linkindex="3"
href="http://getfirefox.com">http://getfirefox.com</a>
is free and does it!
If you use Internet Explorer, you can also get a plugin:
<a linkindex="4" href="http://www.adobe.com/svg/viewer/install/main.html">
http://www.adobe.com/svg/viewer/install/main.html</a>
</object>
```
If you do not use width and height attributes in the object tag, the svg will be displayed in full size. Normally I get svg files from Open Graphics Library for testing. Is there any way to get svg's size by using JavaScript? Or maybe I should just look at the svg xml file to find out the size from the top svg tag?
|
**> Is there any way to get svg's size by using JavaScript?**
No and yes.
**No:**
JavaScript won't be able to access the SVG file contents that are sitting in the browser.
So it wouldn't be possible to have a page containing an arbitrary SVG image and then have JavaScript determine anything from the SVG file itself.
The only data JS can access it that contained within the page's DOM: the original markup plus any JS-related modifications to the DOM. You could access the `object` element's attributes and descendant nodes, but that won't give you visibility of anything more than what you can see if you look at the page markup yourself.
**Yes:**
JS (in modern browsers) can parse any XML string into a DOM and then access the content using DOM-based methods.
You could get the SVG file contents by issuing an xmlHttpRequest-style request (i.e. JS performs an HTTP GET on the SVG file's URL). JS would then have the SVG file's full XML string and you can then access anything you like.
**> Or maybe I should just look at the svg xml file to find out the size from the top svg tag?**
This would be more feasible by far.
The only JS-based solution would require JS to perform a GET request on the SVG file's URL (as above), which is unlikely to be feasible - each page load might result in double-downloading each SVG file, and the parsing of the SVG's XML into a DOM by JS might be too resource intensive.
Having JS retrieve the SVG's XML content and parse it into a DOM to retrieve only the image dimensions is a bit overkill. It's perfectly possible, but generally not practical.
Querying the SVG's XML content server-side, determining a suitable width and height and then dynamically adding the `width` and `height` attributes prior to returning markup to the browser would be your best bet.
|
231,693 |
<p>I have created a pretty basic Flash website for a client and am having an issue programming a Client Login feature that he would like. Currently, if I navigate to the site and click Client Login, it takes me to a login page. The way I need this to work is -- within the Flash, using ActionScript 2.0 -- have the user enter their UserID and Password and click to login, which submits POST vars to the form action of the Client Login website.</p>
<p>Is this possible/legal to do from a different domain? How would I go about doing this, assuming it's possible?</p>
|
[
{
"answer_id": 231779,
"author": "Diodeus - James MacFarlane",
"author_id": 12579,
"author_profile": "https://Stackoverflow.com/users/12579",
"pm_score": 3,
"selected": true,
"text": "<p>Try this:</p>\n\n<pre><code>myVars = new LoadVars();\nmyVars.username = username.text;\nmyVars.password = pwd.text;\nmyVars.onLoad = function(success) {\n trace(\"yay!\");\n else {\n trace(\"try again\"); \n }\n}\nmyVars.sendAndLoad(\"login.php\", myVars, \"POST\");\n</code></pre>\n"
},
{
"answer_id": 231830,
"author": "Jeremy White",
"author_id": 2715,
"author_profile": "https://Stackoverflow.com/users/2715",
"pm_score": 1,
"selected": false,
"text": "<p>So, I get \"yay!\" with the code provided below (yours had an error in it). However, I need to be redirected to the resulting \"logged-in\" page. How do I do that?</p>\n\n<pre>\nmyVars = new LoadVars();\nmyVars.txtUserID = \"some_user\";\nmyVars.txtPassword = \"some_password\";\nmyVars.__VIEWSTATE = \"dDw3MTcxMTg3ODM7dDw7bDxpPDM+O2k8NT47PjtsPHQ8cDxsPFRleHQ7PjtsPGRlbW87Pj47Oz47dDw7bDxpPDE+O2k8Mz47aTw1Pjs+O2w8dDxwPGw8VGV4dDs+O2w8YmFja2dyb3VuZC1jb2xvcjojZjZmNmY2XDtjb2xvcjojMzMzMzMzXDs7Pj47Oz47dDxwPDtwPGw8c3R5bGU7PjtsPHdpZHRoOjEwMHB4XDs7Pj4+Ozs+O3Q8cDw7cDxsPHN0eWxlOz47bDx3aWR0aDoxMDBweFw7Oz4+Pjs7Pjs+Pjs+Pjs+56k0UDxn5ED61lGLjP0fIkStm6o=\";\nmyVars.onLoad = function(success) {\n if (success)\n {\n trace(\"yay!\");\n } else {\n trace(\"try again\"); \n }\n}\nmyVars.sendAndLoad(\"http://www.buildertrend.net/loginFrame.aspx?builderID=35&bgcolor=%23f6f6f6&fcolor=%23333333&uwidth=100&pwidth=100\", myVars, \"POST\");\n</pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2715/"
] |
I have created a pretty basic Flash website for a client and am having an issue programming a Client Login feature that he would like. Currently, if I navigate to the site and click Client Login, it takes me to a login page. The way I need this to work is -- within the Flash, using ActionScript 2.0 -- have the user enter their UserID and Password and click to login, which submits POST vars to the form action of the Client Login website.
Is this possible/legal to do from a different domain? How would I go about doing this, assuming it's possible?
|
Try this:
```
myVars = new LoadVars();
myVars.username = username.text;
myVars.password = pwd.text;
myVars.onLoad = function(success) {
trace("yay!");
else {
trace("try again");
}
}
myVars.sendAndLoad("login.php", myVars, "POST");
```
|
231,695 |
<p>I need to store several date values in a database field. These values will be tied to a "User" such that each user will have their own unique set of these several date values.</p>
<p>I could use a one-to-many relationship here but each user will have exactly 4 date values tied to them so I feel that a one-to-many table would be overkill (in many ways e.g. speed) but if I needed to query against them I would need those 4 values to be in different fields e.g. MyDate1 MyDate2 ... etc. but then the SQL command to fetch it out would have to check for 4 values each time.</p>
<p>So the one-to-many relationship would probably be the best solution, but is there a better/cleaner/faster/whatever another way around? Am I designing it correctly?</p>
<p>The platform is MS SQL 2005 but solution on any platform will do, I'm mostly looking for proper db designing techniques.</p>
<p><strong>EDIT:</strong> The 4 fields represent 4 instances of the same thing.</p>
|
[
{
"answer_id": 231708,
"author": "shahkalpesh",
"author_id": 23574,
"author_profile": "https://Stackoverflow.com/users/23574",
"pm_score": 0,
"selected": false,
"text": "<p>How about having 4 fields alongwith User ID (if you are sure, it wont exceed that)?</p>\n"
},
{
"answer_id": 231711,
"author": "Douglas Mayle",
"author_id": 8458,
"author_profile": "https://Stackoverflow.com/users/8458",
"pm_score": 3,
"selected": true,
"text": "<p>If you do it as four separate fields, then you don't have to join. To Save the query syntax from being too horrible, you could write:</p>\n\n<pre><code>SELECT * FROM MyTable WHERE 'DateLiteral' IN (MyDate1, MyDate2, MyDate3, MyDate4);\n</code></pre>\n\n<p>As mentioned in comments, the IN operator is pretty specific when it comes to date fields (down to the last (milli)second). You can always use date time functions on the subquery, but BETWEEN is unusable:</p>\n\n<pre><code>SELECT * FROM MyTable WHERE date_trunc('hour', 'DateLiteral') \nIN (date_trunc('hour', MyDate1), date_trunc('hour', MyDate2), date_trunc('hour', MyDate3), date_trunc('hour', MyDate4));\n</code></pre>\n"
},
{
"answer_id": 231727,
"author": "twblamer",
"author_id": 25005,
"author_profile": "https://Stackoverflow.com/users/25005",
"pm_score": -1,
"selected": false,
"text": "<p>Create four date fields and store the dates in the fields. The date fields might be part of your user table, or they might be in some other table joined to the user table in a one-to-one relationship. It's your call.</p>\n"
},
{
"answer_id": 231828,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 1,
"selected": false,
"text": "<p>For what it's worth, the normalized design would be to store the dates as rows in a dependent table.</p>\n\n<p>Storing multiple values in a single column is not a normalized design; normalization explicitly means each column has exactly one value.</p>\n\n<p>You can make sure no more than four rows are inserted into the dependent table this way:</p>\n\n<pre><code> CREATE TABLE ThisManyDates (n INT PRIMARY KEY);\n INSERT INTO ThisManyDates VALUES (1), (2), (3), (4);\n\n CREATE TABLE UserDates (\n User_ID INT REFERENCES Users,\n n INT REFERENCES ThisManyDates,\n Date_Value DATE NOT NULL,\n PRIMARY KEY (User_ID, n)\n );\n</code></pre>\n\n<p>However, this design doesn't allow you make the date values mandatory.</p>\n"
},
{
"answer_id": 232007,
"author": "Milan Babuškov",
"author_id": 14690,
"author_profile": "https://Stackoverflow.com/users/14690",
"pm_score": 2,
"selected": false,
"text": "<p>Some databases like <a href=\"http://www.firebirdsql.org\" rel=\"nofollow noreferrer\">Firebird</a> have array datatype, which does exactly what you described. It is declared something like this:</p>\n\n<pre><code>alter table t1 add MyDate[4] date;\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3055/"
] |
I need to store several date values in a database field. These values will be tied to a "User" such that each user will have their own unique set of these several date values.
I could use a one-to-many relationship here but each user will have exactly 4 date values tied to them so I feel that a one-to-many table would be overkill (in many ways e.g. speed) but if I needed to query against them I would need those 4 values to be in different fields e.g. MyDate1 MyDate2 ... etc. but then the SQL command to fetch it out would have to check for 4 values each time.
So the one-to-many relationship would probably be the best solution, but is there a better/cleaner/faster/whatever another way around? Am I designing it correctly?
The platform is MS SQL 2005 but solution on any platform will do, I'm mostly looking for proper db designing techniques.
**EDIT:** The 4 fields represent 4 instances of the same thing.
|
If you do it as four separate fields, then you don't have to join. To Save the query syntax from being too horrible, you could write:
```
SELECT * FROM MyTable WHERE 'DateLiteral' IN (MyDate1, MyDate2, MyDate3, MyDate4);
```
As mentioned in comments, the IN operator is pretty specific when it comes to date fields (down to the last (milli)second). You can always use date time functions on the subquery, but BETWEEN is unusable:
```
SELECT * FROM MyTable WHERE date_trunc('hour', 'DateLiteral')
IN (date_trunc('hour', MyDate1), date_trunc('hour', MyDate2), date_trunc('hour', MyDate3), date_trunc('hour', MyDate4));
```
|
231,740 |
<p>Scott Hanselman recently posted a <a href="http://www.hanselman.com/blog/TheWeeklySourceCode35ZipCompressingASPNETSessionAndCacheState.aspx" rel="nofollow noreferrer">blog article</a> describing how to compress strings stored in the session / cache. This looks fairly promising, but the majority of data that I am storing in the session / cache are not strings but custom classes. How would you go about compressing these?</p>
<p>My initial thought would be to utilize the BinaryFormatter to serialize the object first (just like the ASP.NET framework would do normally when storing custom class objects into the session / cache), then compress the resulting byte array. However, this has the adverse side effect that the retrieved data from the session / cache would be readonly (since decompressing and deserializing would create a new in-memory object).</p>
<p>In other words, if my code currently looks like the following, is there a way to compress its storage into the session?</p>
<pre><code>MyClass foo = new MyClass();
Session["foo"] = foo;
MyClass retrievedFoo1 = (MyClass) Session["foo"];
retrievedFoo1.Property1 = "property 1";
// retrievedFoo2.Property1 should equal "property 1"!
MyClass retrievedFoo2 = (MyClass) Session["foo"];
</code></pre>
|
[
{
"answer_id": 233708,
"author": "Toby Mills",
"author_id": 12377,
"author_profile": "https://Stackoverflow.com/users/12377",
"pm_score": 0,
"selected": false,
"text": "<p>Could you use an XML Serializer to transformed it into an XML format?</p>\n"
},
{
"answer_id": 236018,
"author": "sliderhouserules",
"author_id": 31385,
"author_profile": "https://Stackoverflow.com/users/31385",
"pm_score": 0,
"selected": false,
"text": "<p>It is my understanding that the performance degradation you get from (overloading) the Session is due to the overhead of serialization/deserialization, not storage size. If you are looking at compression to help with performance issues I think you're going down the wrong road. (De)Compression will just add more overhead.</p>\n\n<p>Now if you're talking about the Cache, then things are a bit different. But you specifically mention Session...</p>\n\n<hr>\n\n<p>I'm confused by your question having just read your comment on Scott's article. It seems you don't really understand you're getting data persistence by putting something in Session/Cache the same as if you put it into a database or wrote it to file. Compression isn't going to solve what you're asking about.</p>\n"
},
{
"answer_id": 236036,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Firstly I'd look at why you need to compress the data in your session / cache. Compression should be an act of last resort, better programming should be the first. </p>\n\n<p>Are you running out of memory, and if so, which objects are consuming the most? This should point you in the direction for code improvement to reduce the amount of memory used.</p>\n\n<p>If your app is optimised the best it can with the objects it needs, you may want to look at out of memory storage such as a database or file system to cache larger objects (which is where serialisation comes in handy).</p>\n\n<p>You could also place InProc sessions on a different server to the webserver to improve scalability and distribute the site over a web farm.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1574/"
] |
Scott Hanselman recently posted a [blog article](http://www.hanselman.com/blog/TheWeeklySourceCode35ZipCompressingASPNETSessionAndCacheState.aspx) describing how to compress strings stored in the session / cache. This looks fairly promising, but the majority of data that I am storing in the session / cache are not strings but custom classes. How would you go about compressing these?
My initial thought would be to utilize the BinaryFormatter to serialize the object first (just like the ASP.NET framework would do normally when storing custom class objects into the session / cache), then compress the resulting byte array. However, this has the adverse side effect that the retrieved data from the session / cache would be readonly (since decompressing and deserializing would create a new in-memory object).
In other words, if my code currently looks like the following, is there a way to compress its storage into the session?
```
MyClass foo = new MyClass();
Session["foo"] = foo;
MyClass retrievedFoo1 = (MyClass) Session["foo"];
retrievedFoo1.Property1 = "property 1";
// retrievedFoo2.Property1 should equal "property 1"!
MyClass retrievedFoo2 = (MyClass) Session["foo"];
```
|
Firstly I'd look at why you need to compress the data in your session / cache. Compression should be an act of last resort, better programming should be the first.
Are you running out of memory, and if so, which objects are consuming the most? This should point you in the direction for code improvement to reduce the amount of memory used.
If your app is optimised the best it can with the objects it needs, you may want to look at out of memory storage such as a database or file system to cache larger objects (which is where serialisation comes in handy).
You could also place InProc sessions on a different server to the webserver to improve scalability and distribute the site over a web farm.
|
231,760 |
<p>This seems like a simple question, but I can't find it with the Stack Overflow search or Google. What does a type followed by a <code>_t</code> mean? Such as</p>
<pre><code>int_t anInt;
</code></pre>
<p>I see it a lot in C code meant to deal closely with hardware—I can't help but think that they're related.</p>
|
[
{
"answer_id": 231765,
"author": "Douglas Mayle",
"author_id": 8458,
"author_profile": "https://Stackoverflow.com/users/8458",
"pm_score": 4,
"selected": false,
"text": "<p>It means type. <code>size_t</code> is the size type.</p>\n"
},
{
"answer_id": 231776,
"author": "Matt Curtis",
"author_id": 17221,
"author_profile": "https://Stackoverflow.com/users/17221",
"pm_score": 4,
"selected": false,
"text": "<p>It's just a convention which means \"type\". It means nothing special to the compiler.</p>\n"
},
{
"answer_id": 231789,
"author": "mmacaulay",
"author_id": 22152,
"author_profile": "https://Stackoverflow.com/users/22152",
"pm_score": 6,
"selected": false,
"text": "<p>It's a convention used for naming data types, e.g with <code>typedef</code>:</p>\n\n<pre>\n<code>\ntypedef struct {\n char* model;\n int year;\n...\n} car_t;\n</code>\n</pre>\n"
},
{
"answer_id": 231791,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 3,
"selected": false,
"text": "<p>If you're dealing with hardware interface code, the author of the code you're looking at might have defined <code>int_t</code> to be a specific size integer. The C standard doesn't assign a specific size to the <code>int</code> type (it depends on your compiler and target platform, potentially), and using a specific <code>int_t</code> type would avoid that portability problem.</p>\n\n<p>This is a particularly important consideration for hardware interface code, which may be why you've first noticed the convention there.</p>\n"
},
{
"answer_id": 231807,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 9,
"selected": true,
"text": "<p>As Douglas Mayle noted, it basically denotes a type name. Consequently, you would be ill-advised to end variable or function names with '<code>_t</code>' since it could cause some confusion. As well as <code>size_t</code>, the C89 standard defines <code>wchar_t</code>, <code>off_t</code>, <code>ptrdiff_t</code>, and probably some others I've forgotten. The C99 standard defines a lot of extra types, such as <code>uintptr_t</code>, <code>intmax_t</code>, <code>int8_t</code>, <code>uint_least16_t</code>, <code>uint_fast32_t</code>, and so on. These new types are formally defined in <code><stdint.h></code> but most often you will use <code><inttypes.h></code> which (unusually for standard C headers) includes <code><stdint.h></code>. It (<code><inttypes.h></code>) also defines macros for use with the <code>printf()</code> and <code>scanf()</code>.</p>\n\n<p>As Matt Curtis noted, there is no significance to the compiler in the suffix; it is a human-oriented convention.</p>\n\n<p>However, you should also note that <a href=\"https://en.wikipedia.org/wiki/POSIX\" rel=\"noreferrer\">POSIX</a> defines a lot of extra type names ending in '<code>_t</code>', and <strong>reserves the suffix</strong> for the implementation. That means that if you are working on POSIX-related systems, defining your own type names with the convention is ill-advised. The system I work on has done it (for more than 20 years); we regularly get tripped up by systems defining types with the same name as we define.</p>\n"
},
{
"answer_id": 231815,
"author": "mkClark",
"author_id": 30970,
"author_profile": "https://Stackoverflow.com/users/30970",
"pm_score": 4,
"selected": false,
"text": "<p>It is a standard naming convention for data types, usually defined by typedefs. A lot of C code that deals with hardware registers uses C99-defined standard names for signed and unsigned fixed-size data types. As a convention, these names are in a standard header file (stdint.h), and end with _t.</p>\n"
},
{
"answer_id": 231818,
"author": "Toybuilder",
"author_id": 22329,
"author_profile": "https://Stackoverflow.com/users/22329",
"pm_score": 4,
"selected": false,
"text": "<p>The <code>_t</code> does not inherently have any special meaning. But it has fallen into common use to add the <code>_t</code> suffix to typedef's.</p>\n\n<p>You may be more familiar with common C practices for variable naming... This is similar to how it's common to stick a p at the front for a pointer, and to use an underscore in front of global variables (this is a bit less common), and to use the variable names <code>i</code>, <code>j</code>, and <code>k</code> for temporary loop variables.</p>\n\n<p>In code where word-size and ordering is important, it's very common to use custom defined types that are explicit, such as <code>BYTE</code> <code>WORD</code> (normally 16-bit) <code>DWORD</code> (32-bits). </p>\n\n<p><code>int_t</code> is not so good, because the definition of <code>int</code> varies between platforms -- so whose <code>int</code> are you conforming to? (Although, these days, most PC-centric development treats it as 32 bits, much stuff for non-PC development still treat int's as 16 bits). </p>\n"
},
{
"answer_id": 233105,
"author": "Ilya",
"author_id": 6807,
"author_profile": "https://Stackoverflow.com/users/6807",
"pm_score": 3,
"selected": false,
"text": "<p>There were a few good explanations about the subject. Just to add another reason for re-defining the types:</p>\n\n<p>In many embedded projects, all types are redefined to correctly state the given sizing to the types and to improve portability across different platforms (i.e hardware types compilers).</p>\n\n<p>Another reason will be to make your code portable across different OSs and to avoid collisions with existing types in the OS that you are integrating in your code. For this, usually a unique (as possible) prefix is added.</p>\n\n<p>Example:</p>\n\n<pre><code>typedef unsigned long dc_uint32_t;\n</code></pre>\n"
},
{
"answer_id": 12727104,
"author": "Benoit",
"author_id": 1439701,
"author_profile": "https://Stackoverflow.com/users/1439701",
"pm_score": 6,
"selected": false,
"text": "<p>The <code>_t</code> usually wraps an opaque type definition.</p>\n<p>GCC merely add names that end with <code>_t</code> to the reserved namespace you may not use, to avoid conflicts with future versions of Standard C and POSIX <a href=\"http://www.gnu.org/software/libc/manual/html_node/Reserved-Names.html\" rel=\"noreferrer\">(GNU C library manual)</a>. After some research, I finally found the correct reference inside the POSIX Standard 1003.1: <a href=\"https://pubs.opengroup.org/onlinepubs/9699919799/xrat/V4_xsh_chap02.html#tag_22_02_12\" rel=\"noreferrer\">B.2.12 Data Types</a> (Volume: <a href=\"https://pubs.opengroup.org/onlinepubs/9699919799/idx/xrat.html\" rel=\"noreferrer\">Rationale</a>, Appendix: <a href=\"https://pubs.opengroup.org/onlinepubs/9699919799/xrat/V4_xsh_chap01.html\" rel=\"noreferrer\">B. Rationale for System Interfaces</a>, Chapter: <a href=\"https://pubs.opengroup.org/onlinepubs/9699919799/xrat/V4_xsh_chap02.html\" rel=\"noreferrer\">B.2 General Information</a>):</p>\n<blockquote>\n<p><strong>B.2.12 Data Types</strong><br />\n<em>Defined Types</em><br />\nThe requirement that additional types defined in this section end in "_t" was prompted by the problem of name space pollution. It is difficult to define a type (where that type is not one defined by POSIX.1-2017) in one header file and use it in another without adding symbols to the name space of the program. To allow implementors to provide their own types, all conforming applications are required to avoid symbols ending in "_t", which permits the implementor to provide additional types. Because a major use of types is in the definition of structure members, which can (and in many cases must) be added to the structures defined in POSIX.1-2017, the need for additional types is compelling.</p>\n</blockquote>\n<p>In a nutshell, the Standard says that there are good chances of extending the Standard types' list, therefore the Standard restricts the <code>_t</code> namespace for its own use.</p>\n<p>For instance, your program matches <em>POSIX 1003.1 Issue 7</em> and you defined a type <code>foo_t</code>. <em>POSIX 1003.1 Issue 8</em> is eventually released with a newly defined type <code>foo_t</code>. Your program does not match the new version, which might be a problem. Restricting the <code>_t</code> usage prevents from refactoring the code. Thus, if you aim to a POSIX compliancy, you should definitely avoid the <code>_t</code> as the Standard states it.</p>\n<p><em>Side note: personally, I try to stick to POSIX because I think it gives good basics for clean programming. Moreover, I am pretty fond of <a href=\"https://elixir.bootlin.com/linux/latest/source/Documentation/process/coding-style.rst#L343\" rel=\"noreferrer\">Linux Coding Style (chapter 5)</a> guidelines. There are some good reasons why not using typedef. Hope this help!</em></p>\n"
},
{
"answer_id": 51279858,
"author": "Jayhello",
"author_id": 6329006,
"author_profile": "https://Stackoverflow.com/users/6329006",
"pm_score": 2,
"selected": false,
"text": "<p>For example in C99, /usr/include/stdint.h:</p>\n\n<pre><code>typedef unsigned char uint8_t;\ntypedef unsigned short int uint16_t;\n#ifndef __uint32_t_defined\ntypedef unsigned int uint32_t;\n# define __uint32_t_defined\n#endif\n#if __WORDSIZE == 64\ntypedef unsigned long int uint64_t;\n#else\n__extension__\ntypedef unsigned long long int uint64_t;\n#endif\n</code></pre>\n\n<p><code>_t</code> always means defined by typedef.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26237/"
] |
This seems like a simple question, but I can't find it with the Stack Overflow search or Google. What does a type followed by a `_t` mean? Such as
```
int_t anInt;
```
I see it a lot in C code meant to deal closely with hardware—I can't help but think that they're related.
|
As Douglas Mayle noted, it basically denotes a type name. Consequently, you would be ill-advised to end variable or function names with '`_t`' since it could cause some confusion. As well as `size_t`, the C89 standard defines `wchar_t`, `off_t`, `ptrdiff_t`, and probably some others I've forgotten. The C99 standard defines a lot of extra types, such as `uintptr_t`, `intmax_t`, `int8_t`, `uint_least16_t`, `uint_fast32_t`, and so on. These new types are formally defined in `<stdint.h>` but most often you will use `<inttypes.h>` which (unusually for standard C headers) includes `<stdint.h>`. It (`<inttypes.h>`) also defines macros for use with the `printf()` and `scanf()`.
As Matt Curtis noted, there is no significance to the compiler in the suffix; it is a human-oriented convention.
However, you should also note that [POSIX](https://en.wikipedia.org/wiki/POSIX) defines a lot of extra type names ending in '`_t`', and **reserves the suffix** for the implementation. That means that if you are working on POSIX-related systems, defining your own type names with the convention is ill-advised. The system I work on has done it (for more than 20 years); we regularly get tripped up by systems defining types with the same name as we define.
|
231,767 |
<p>What is the use of the <code>yield</code> keyword in Python? What does it do?</p>
<p>For example, I'm trying to understand this code<sup><strong>1</strong></sup>:</p>
<pre><code>def _get_child_candidates(self, distance, min_dist, max_dist):
if self._leftchild and distance - max_dist < self._median:
yield self._leftchild
if self._rightchild and distance + max_dist >= self._median:
yield self._rightchild
</code></pre>
<p>And this is the caller:</p>
<pre><code>result, candidates = [], [self]
while candidates:
node = candidates.pop()
distance = node._get_dist(obj)
if distance <= max_dist and distance >= min_dist:
result.extend(node._values)
candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))
return result
</code></pre>
<p>What happens when the method <code>_get_child_candidates</code> is called?
Is a list returned? A single element? Is it called again? When will subsequent calls stop?</p>
<hr />
<sub>
1. This piece of code was written by Jochen Schulz (jrschulz), who made a great Python library for metric spaces. This is the link to the complete source: <a href="https://well-adjusted.de/~jrspieker/mspace/" rel="noreferrer">Module mspace</a>.</sub>
|
[
{
"answer_id": 231778,
"author": "Douglas Mayle",
"author_id": 8458,
"author_profile": "https://Stackoverflow.com/users/8458",
"pm_score": 9,
"selected": false,
"text": "<p><code>yield</code> is just like <code>return</code> - it returns whatever you tell it to (as a generator). The difference is that the next time you call the generator, execution starts from the last call to the <code>yield</code> statement. Unlike return, <strong>the stack frame is not cleaned up when a yield occurs, however control is transferred back to the caller, so its state will resume the next time the function is called.</strong></p>\n\n<p>In the case of your code, the function <code>get_child_candidates</code> is acting like an iterator so that when you extend your list, it adds one element at a time to the new list.</p>\n\n<p><code>list.extend</code> calls an iterator until it's exhausted. In the case of the code sample you posted, it would be much clearer to just return a tuple and append that to the list.</p>\n"
},
{
"answer_id": 231788,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 8,
"selected": false,
"text": "<p>It's returning a generator. I'm not particularly familiar with Python, but I believe it's the same kind of thing as <a href=\"http://csharpindepth.com/Articles/Chapter11/StreamingAndIterators.aspx\" rel=\"noreferrer\">C#'s iterator blocks</a> if you're familiar with those.</p>\n\n<p>The key idea is that the compiler/interpreter/whatever does some trickery so that as far as the caller is concerned, they can keep calling next() and it will keep returning values - <em>as if the generator method was paused</em>. Now obviously you can't really \"pause\" a method, so the compiler builds a state machine for you to remember where you currently are and what the local variables etc look like. This is much easier than writing an iterator yourself.</p>\n"
},
{
"answer_id": 231801,
"author": "Jason Baker",
"author_id": 2147,
"author_profile": "https://Stackoverflow.com/users/2147",
"pm_score": 9,
"selected": false,
"text": "<p>Think of it this way:</p>\n\n<p>An iterator is just a fancy sounding term for an object that has a <code>next()</code> method. So a yield-ed function ends up being something like this:</p>\n\n<p>Original version:</p>\n\n<pre><code>def some_function():\n for i in xrange(4):\n yield i\n\nfor i in some_function():\n print i\n</code></pre>\n\n<p>This is basically what the Python interpreter does with the above code:</p>\n\n<pre><code>class it:\n def __init__(self):\n # Start at -1 so that we get 0 when we add 1 below.\n self.count = -1\n\n # The __iter__ method will be called once by the 'for' loop.\n # The rest of the magic happens on the object returned by this method.\n # In this case it is the object itself.\n def __iter__(self):\n return self\n\n # The next method will be called repeatedly by the 'for' loop\n # until it raises StopIteration.\n def next(self):\n self.count += 1\n if self.count < 4:\n return self.count\n else:\n # A StopIteration exception is raised\n # to signal that the iterator is done.\n # This is caught implicitly by the 'for' loop.\n raise StopIteration\n\ndef some_func():\n return it()\n\nfor i in some_func():\n print i\n</code></pre>\n\n<p>For more insight as to what's happening behind the scenes, the <code>for</code> loop can be rewritten to this:</p>\n\n<pre><code>iterator = some_func()\ntry:\n while 1:\n print iterator.next()\nexcept StopIteration:\n pass\n</code></pre>\n\n<p>Does that make more sense or just confuse you more? :)</p>\n\n<p>I should note that this <em>is</em> an oversimplification for illustrative purposes. :)</p>\n"
},
{
"answer_id": 231855,
"author": "e-satis",
"author_id": 9951,
"author_profile": "https://Stackoverflow.com/users/9951",
"pm_score": 15,
"selected": true,
"text": "<p>To understand what <code>yield</code> does, you must understand what <em>generators</em> are. And before you can understand generators, you must understand <em>iterables</em>.</p>\n<h2>Iterables</h2>\n<p>When you create a list, you can read its items one by one. Reading its items one by one is called iteration:</p>\n<pre><code>>>> mylist = [1, 2, 3]\n>>> for i in mylist:\n... print(i)\n1\n2\n3\n</code></pre>\n<p><code>mylist</code> is an <em>iterable</em>. When you use a list comprehension, you create a list, and so an iterable:</p>\n<pre><code>>>> mylist = [x*x for x in range(3)]\n>>> for i in mylist:\n... print(i)\n0\n1\n4\n</code></pre>\n<p>Everything you can use "<code>for... in...</code>" on is an iterable; <code>lists</code>, <code>strings</code>, files...</p>\n<p>These iterables are handy because you can read them as much as you wish, but you store all the values in memory and this is not always what you want when you have a lot of values.</p>\n<h2>Generators</h2>\n<p>Generators are iterators, a kind of iterable <strong>you can only iterate over once</strong>. Generators do not store all the values in memory, <strong>they generate the values on the fly</strong>:</p>\n<pre><code>>>> mygenerator = (x*x for x in range(3))\n>>> for i in mygenerator:\n... print(i)\n0\n1\n4\n</code></pre>\n<p>It is just the same except you used <code>()</code> instead of <code>[]</code>. BUT, you <strong>cannot</strong> perform <code>for i in mygenerator</code> a second time since generators can only be used once: they calculate 0, then forget about it and calculate 1, and end calculating 4, one by one.</p>\n<h2>Yield</h2>\n<p><code>yield</code> is a keyword that is used like <code>return</code>, except the function will return a generator.</p>\n<pre><code>>>> def create_generator():\n... mylist = range(3)\n... for i in mylist:\n... yield i*i\n...\n>>> mygenerator = create_generator() # create a generator\n>>> print(mygenerator) # mygenerator is an object!\n<generator object create_generator at 0xb7555c34>\n>>> for i in mygenerator:\n... print(i)\n0\n1\n4\n</code></pre>\n<p>Here it's a useless example, but it's handy when you know your function will return a huge set of values that you will only need to read once.</p>\n<p>To master <code>yield</code>, you must understand that <strong>when you call the function, the code you have written in the function body does not run.</strong> The function only returns the generator object, this is a bit tricky.</p>\n<p>Then, your code will continue from where it left off each time <code>for</code> uses the generator.</p>\n<p>Now the hard part:</p>\n<p>The first time the <code>for</code> calls the generator object created from your function, it will run the code in your function from the beginning until it hits <code>yield</code>, then it'll return the first value of the loop. Then, each subsequent call will run another iteration of the loop you have written in the function and return the next value. This will continue until the generator is considered empty, which happens when the function runs without hitting <code>yield</code>. That can be because the loop has come to an end, or because you no longer satisfy an <code>"if/else"</code>.</p>\n<hr />\n<h2>Your code explained</h2>\n<p><em>Generator:</em></p>\n<pre><code># Here you create the method of the node object that will return the generator\ndef _get_child_candidates(self, distance, min_dist, max_dist):\n\n # Here is the code that will be called each time you use the generator object:\n\n # If there is still a child of the node object on its left\n # AND if the distance is ok, return the next child\n if self._leftchild and distance - max_dist < self._median:\n yield self._leftchild\n\n # If there is still a child of the node object on its right\n # AND if the distance is ok, return the next child\n if self._rightchild and distance + max_dist >= self._median:\n yield self._rightchild\n\n # If the function arrives here, the generator will be considered empty\n # there are no more than two values: the left and the right children\n</code></pre>\n<p><em>Caller:</em></p>\n<pre><code># Create an empty list and a list with the current object reference\nresult, candidates = list(), [self]\n\n# Loop on candidates (they contain only one element at the beginning)\nwhile candidates:\n\n # Get the last candidate and remove it from the list\n node = candidates.pop()\n\n # Get the distance between obj and the candidate\n distance = node._get_dist(obj)\n\n # If the distance is ok, then you can fill in the result\n if distance <= max_dist and distance >= min_dist:\n result.extend(node._values)\n\n # Add the children of the candidate to the candidate's list\n # so the loop will keep running until it has looked\n # at all the children of the children of the children, etc. of the candidate\n candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))\n\nreturn result\n</code></pre>\n<p>This code contains several smart parts:</p>\n<ul>\n<li><p>The loop iterates on a list, but the list expands while the loop is being iterated. It's a concise way to go through all these nested data even if it's a bit dangerous since you can end up with an infinite loop. In this case, <code>candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))</code> exhausts all the values of the generator, but <code>while</code> keeps creating new generator objects which will produce different values from the previous ones since it's not applied on the same node.</p>\n</li>\n<li><p>The <code>extend()</code> method is a list object method that expects an iterable and adds its values to the list.</p>\n</li>\n</ul>\n<p>Usually, we pass a list to it:</p>\n<pre><code>>>> a = [1, 2]\n>>> b = [3, 4]\n>>> a.extend(b)\n>>> print(a)\n[1, 2, 3, 4]\n</code></pre>\n<p>But in your code, it gets a generator, which is good because:</p>\n<ol>\n<li>You don't need to read the values twice.</li>\n<li>You may have a lot of children and you don't want them all stored in memory.</li>\n</ol>\n<p>And it works because Python does not care if the argument of a method is a list or not. Python expects iterables so it will work with strings, lists, tuples, and generators! This is called duck typing and is one of the reasons why Python is so cool. But this is another story, for another question...</p>\n<p>You can stop here, or read a little bit to see an advanced use of a generator:</p>\n<h2>Controlling a generator exhaustion</h2>\n<pre><code>>>> class Bank(): # Let's create a bank, building ATMs\n... crisis = False\n... def create_atm(self):\n... while not self.crisis:\n... yield "$100"\n>>> hsbc = Bank() # When everything's ok the ATM gives you as much as you want\n>>> corner_street_atm = hsbc.create_atm()\n>>> print(corner_street_atm.next())\n$100\n>>> print(corner_street_atm.next())\n$100\n>>> print([corner_street_atm.next() for cash in range(5)])\n['$100', '$100', '$100', '$100', '$100']\n>>> hsbc.crisis = True # Crisis is coming, no more money!\n>>> print(corner_street_atm.next())\n<type 'exceptions.StopIteration'>\n>>> wall_street_atm = hsbc.create_atm() # It's even true for new ATMs\n>>> print(wall_street_atm.next())\n<type 'exceptions.StopIteration'>\n>>> hsbc.crisis = False # The trouble is, even post-crisis the ATM remains empty\n>>> print(corner_street_atm.next())\n<type 'exceptions.StopIteration'>\n>>> brand_new_atm = hsbc.create_atm() # Build a new one to get back in business\n>>> for cash in brand_new_atm:\n... print cash\n$100\n$100\n$100\n$100\n$100\n$100\n$100\n$100\n$100\n...\n</code></pre>\n<p><strong>Note:</strong> For Python 3, use<code>print(corner_street_atm.__next__())</code> or <code>print(next(corner_street_atm))</code></p>\n<p>It can be useful for various things like controlling access to a resource.</p>\n<h2>Itertools, your best friend</h2>\n<p>The itertools module contains special functions to manipulate iterables. Ever wish to duplicate a generator?\nChain two generators? Group values in a nested list with a one-liner? <code>Map / Zip</code> without creating another list?</p>\n<p>Then just <code>import itertools</code>.</p>\n<p>An example? Let's see the possible orders of arrival for a four-horse race:</p>\n<pre><code>>>> horses = [1, 2, 3, 4]\n>>> races = itertools.permutations(horses)\n>>> print(races)\n<itertools.permutations object at 0xb754f1dc>\n>>> print(list(itertools.permutations(horses)))\n[(1, 2, 3, 4),\n (1, 2, 4, 3),\n (1, 3, 2, 4),\n (1, 3, 4, 2),\n (1, 4, 2, 3),\n (1, 4, 3, 2),\n (2, 1, 3, 4),\n (2, 1, 4, 3),\n (2, 3, 1, 4),\n (2, 3, 4, 1),\n (2, 4, 1, 3),\n (2, 4, 3, 1),\n (3, 1, 2, 4),\n (3, 1, 4, 2),\n (3, 2, 1, 4),\n (3, 2, 4, 1),\n (3, 4, 1, 2),\n (3, 4, 2, 1),\n (4, 1, 2, 3),\n (4, 1, 3, 2),\n (4, 2, 1, 3),\n (4, 2, 3, 1),\n (4, 3, 1, 2),\n (4, 3, 2, 1)]\n</code></pre>\n<h2>Understanding the inner mechanisms of iteration</h2>\n<p>Iteration is a process implying iterables (implementing the <code>__iter__()</code> method) and iterators (implementing the <code>__next__()</code> method).\nIterables are any objects you can get an iterator from. Iterators are objects that let you iterate on iterables.</p>\n<p>There is more about it in this article about <a href=\"https://web.archive.org/web/20201109034340/http://effbot.org/zone/python-for-statement.htm\" rel=\"noreferrer\">how <code>for</code> loops work</a>.</p>\n"
},
{
"answer_id": 232111,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 8,
"selected": false,
"text": "<p>Here is an example in plain language. I will provide a correspondence between high-level human concepts to low-level Python concepts.</p>\n<p>I want to operate on a sequence of numbers, but I don't want to bother my self with the creation of that sequence, I want only to focus on the operation I want to do. So, I do the following:</p>\n<ul>\n<li>I call you and tell you that I want a sequence of numbers which are calculated in a specific way, and I let you know what the algorithm is. <br/>\n<b>This step corresponds to <code>def</code>ining the generator function, i.e. the function containing a <code>yield</code>.</b></li>\n<li>Sometime later, I tell you, "OK, get ready to tell me the sequence of numbers". <br/>\n<b>This step corresponds to calling the generator function which returns a generator object.</b> Note that you don't tell me any numbers yet; you just grab your paper and pencil.</li>\n<li>I ask you, "tell me the next number", and you tell me the first number; after that, you wait for me to ask you for the next number. It's your job to remember where you were, what numbers you have already said, and what is the next number. I don't care about the details. <br/>\n<b>This step corresponds to calling <code>next(generator)</code> on the generator object.</b><br />\n(In Python 2, <code>.next</code> was a method of the generator object; in Python 3, it is named <code>.__next__</code>, but the proper way to call it is using the builtin <code>next()</code> function just like <code>len()</code> and <code>.__len__</code>)</li>\n<li>… repeat previous step, until…</li>\n<li>eventually, you might come to an end. You don't tell me a number; you just shout, "hold your horses! I'm done! No more numbers!" <br/>\n<b>This step corresponds to the generator object ending its job, and raising a <code>StopIteration</code> exception.</b><br />\nThe generator function does not need to raise the exception. It's raised automatically when the function ends or issues a <code>return</code>.</li>\n</ul>\n<p>This is what a generator does (a function that contains a <code>yield</code>); it starts executing on the first <code>next()</code>, pauses whenever it does a <code>yield</code>, and when asked for the <code>next()</code> value it continues from the point it was last. It fits perfectly by design with the iterator protocol of Python, which describes how to sequentially request values.</p>\n<p>The most famous user of the iterator protocol is the <code>for</code> command in Python. So, whenever you do a:</p>\n<pre><code>for item in sequence:\n</code></pre>\n<p>it doesn't matter if <code>sequence</code> is a list, a string, a dictionary or a generator <em>object</em> like described above; the result is the same: you read items off a sequence one by one.</p>\n<p>Note that <code>def</code>ining a function which contains a <code>yield</code> keyword is not the only way to create a generator; it's just the easiest way to create one.</p>\n<p>For more accurate information, read about <a href=\"http://docs.python.org/library/stdtypes.html#iterator-types\" rel=\"noreferrer\">iterator types</a>, the <a href=\"http://docs.python.org/reference/simple_stmts.html#yield\" rel=\"noreferrer\">yield statement</a> and <a href=\"http://docs.python.org/glossary.html#term-generator\" rel=\"noreferrer\">generators</a> in the Python documentation.</p>\n"
},
{
"answer_id": 232853,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 8,
"selected": false,
"text": "<p>There's one extra thing to mention: a function that yields doesn't actually have to terminate. I've written code like this:</p>\n\n<pre><code>def fib():\n last, cur = 0, 1\n while True: \n yield cur\n last, cur = cur, last + cur\n</code></pre>\n\n<p>Then I can use it in other code like this:</p>\n\n<pre><code>for f in fib():\n if some_condition: break\n coolfuncs(f);\n</code></pre>\n\n<p>It really helps simplify some problems, and makes some things easier to work with. </p>\n"
},
{
"answer_id": 237028,
"author": "user28409",
"author_id": 28409,
"author_profile": "https://Stackoverflow.com/users/28409",
"pm_score": 11,
"selected": false,
"text": "<h2>Shortcut to understanding <code>yield</code></h2>\n<p>When you see a function with <code>yield</code> statements, apply this easy trick to understand what will happen:</p>\n<ol>\n<li>Insert a line <code>result = []</code> at the start of the function.</li>\n<li>Replace each <code>yield expr</code> with <code>result.append(expr)</code>.</li>\n<li>Insert a line <code>return result</code> at the bottom of the function.</li>\n<li>Yay - no more <code>yield</code> statements! Read and figure out the code.</li>\n<li>Compare function to the original definition.</li>\n</ol>\n<p>This trick may give you an idea of the logic behind the function, but what actually happens with <code>yield</code> is significantly different than what happens in the list-based approach. In many cases, the yield approach will be a lot more memory efficient and faster too. In other cases, this trick will get you stuck in an infinite loop, even though the original function works just fine. Read on to learn more...</p>\n<h2>Don't confuse your Iterables, Iterators, and Generators</h2>\n<p>First, the <strong>iterator protocol</strong> - when you write</p>\n<pre><code>for x in mylist:\n ...loop body...\n</code></pre>\n<p>Python performs the following two steps:</p>\n<ol>\n<li><p>Gets an iterator for <code>mylist</code>:</p>\n<p>Call <code>iter(mylist)</code> -> this returns an object with a <code>next()</code> method (or <code>__next__()</code> in Python 3).</p>\n<p>[This is the step most people forget to tell you about]</p>\n</li>\n<li><p>Uses the iterator to loop over items:</p>\n<p>Keep calling the <code>next()</code> method on the iterator returned from step 1. The return value from <code>next()</code> is assigned to <code>x</code> and the loop body is executed. If an exception <code>StopIteration</code> is raised from within <code>next()</code>, it means there are no more values in the iterator and the loop is exited.</p>\n</li>\n</ol>\n<p>The truth is Python performs the above two steps anytime it wants to <em>loop over</em> the contents of an object - so it could be a for loop, but it could also be code like <code>otherlist.extend(mylist)</code> (where <code>otherlist</code> is a Python list).</p>\n<p>Here <code>mylist</code> is an <em>iterable</em> because it implements the iterator protocol. In a user-defined class, you can implement the <code>__iter__()</code> method to make instances of your class iterable. This method should return an <em>iterator</em>. An iterator is an object with a <code>next()</code> method. It is possible to implement both <code>__iter__()</code> and <code>next()</code> on the same class, and have <code>__iter__()</code> return <code>self</code>. This will work for simple cases, but not when you want two iterators looping over the same object at the same time.</p>\n<p>So that's the iterator protocol, many objects implement this protocol:</p>\n<ol>\n<li>Built-in lists, dictionaries, tuples, sets, and files.</li>\n<li>User-defined classes that implement <code>__iter__()</code>.</li>\n<li>Generators.</li>\n</ol>\n<p>Note that a <code>for</code> loop doesn't know what kind of object it's dealing with - it just follows the iterator protocol, and is happy to get item after item as it calls <code>next()</code>. Built-in lists return their items one by one, dictionaries return the <em>keys</em> one by one, files return the <em>lines</em> one by one, etc. And generators return... well that's where <code>yield</code> comes in:</p>\n<pre><code>def f123():\n yield 1\n yield 2\n yield 3\n\nfor item in f123():\n print item\n</code></pre>\n<p>Instead of <code>yield</code> statements, if you had three <code>return</code> statements in <code>f123()</code> only the first would get executed, and the function would exit. But <code>f123()</code> is no ordinary function. When <code>f123()</code> is called, it <em>does not</em> return any of the values in the yield statements! It returns a generator object. Also, the function does not really exit - it goes into a suspended state. When the <code>for</code> loop tries to loop over the generator object, the function resumes from its suspended state at the very next line after the <code>yield</code> it previously returned from, executes the next line of code, in this case, a <code>yield</code> statement, and returns that as the next item. This happens until the function exits, at which point the generator raises <code>StopIteration</code>, and the loop exits.</p>\n<p>So the generator object is sort of like an adapter - at one end it exhibits the iterator protocol, by exposing <code>__iter__()</code> and <code>next()</code> methods to keep the <code>for</code> loop happy. At the other end, however, it runs the function just enough to get the next value out of it, and puts it back in suspended mode.</p>\n<h2>Why Use Generators?</h2>\n<p>Usually, you can write code that doesn't use generators but implements the same logic. One option is to use the temporary list 'trick' I mentioned before. That will not work in all cases, for e.g. if you have infinite loops, or it may make inefficient use of memory when you have a really long list. The other approach is to implement a new iterable class SomethingIter that keeps the state in instance members and performs the next logical step in its <code>next()</code> (or <code>__next__()</code> in Python 3) method. Depending on the logic, the code inside the <code>next()</code> method may end up looking very complex and prone to bugs. Here generators provide a clean and easy solution.</p>\n"
},
{
"answer_id": 6400990,
"author": "ninjagecko",
"author_id": 711085,
"author_profile": "https://Stackoverflow.com/users/711085",
"pm_score": 9,
"selected": false,
"text": "\n<p>The <code>yield</code> keyword is reduced to two simple facts:</p>\n<ol>\n<li>If the compiler detects the <code>yield</code> keyword <em>anywhere</em> inside a function, that function no longer returns via the <code>return</code> statement. <em><strong>Instead</strong></em>, it <strong>immediately</strong> returns a <strong>lazy "pending list" object</strong> called a generator</li>\n<li>A generator is iterable. What is an <em>iterable</em>? It's anything like a <code>list</code> or <code>set</code> or <code>range</code> or dict-view, with a <em>built-in protocol for visiting each element in a certain order</em>.</li>\n</ol>\n<p>In a nutshell: Most commonly, <strong>a generator is a lazy, incrementally-pending list</strong>, and <strong><code>yield</code> statements allow you to use function notation to program the list values</strong> the generator should incrementally spit out. <strong>Furthermore, advanced usage lets you use generators as coroutines (see below).</strong></p>\n<pre class=\"lang-py prettyprint-override\"><code>generator = myYieldingFunction(...) # basically a list (but lazy)\nx = list(generator) # evaluate every element into a list\n\n generator\n v\n[x[0], ..., ???]\n\n generator\n v\n[x[0], x[1], ..., ???]\n\n generator\n v\n[x[0], x[1], x[2], ..., ???]\n\n StopIteration exception\n[x[0], x[1], x[2]] done\n</code></pre>\n<p>Basically, whenever the <code>yield</code> statement is encountered, the function pauses and saves its state, then emits "the next return value in the 'list'" according to the python iterator protocol (to some syntactic construct like a for-loop that repeatedly calls <code>next()</code> and catches a <code>StopIteration</code> exception, etc.). You might have encountered generators with <a href=\"https://www.python.org/dev/peps/pep-0289/\" rel=\"noreferrer\">generator expressions</a>; generator functions are more powerful because you can pass arguments back into the paused generator function, using them to implement coroutines. More on that later.</p>\n<hr />\n<h2>Basic Example ('list')</h2>\n<p>Let's define a function <code>makeRange</code> that's just like Python's <code>range</code>. Calling <code>makeRange(n)</code> RETURNS A GENERATOR:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def makeRange(n):\n # return 0,1,2,...,n-1\n i = 0\n while i < n:\n yield i\n i += 1\n\n>>> makeRange(5)\n<generator object makeRange at 0x19e4aa0>\n</code></pre>\n<p>To force the generator to immediately return its pending values, you can pass it into <code>list()</code> (just like you could any iterable):</p>\n<pre class=\"lang-py prettyprint-override\"><code>>>> list(makeRange(5))\n[0, 1, 2, 3, 4]\n</code></pre>\n<hr />\n<h2>Comparing example to "just returning a list"</h2>\n<p>The above example can be thought of as merely creating a list which you append to and return:</p>\n<pre class=\"lang-py prettyprint-override\"><code># return a list # # return a generator\ndef makeRange(n): # def makeRange(n):\n """return [0,1,2,...,n-1]""" # """return 0,1,2,...,n-1"""\n TO_RETURN = [] # \n i = 0 # i = 0\n while i < n: # while i < n:\n TO_RETURN += [i] # yield i\n i += 1 # i += 1\n return TO_RETURN # \n\n>>> makeRange(5)\n[0, 1, 2, 3, 4]\n</code></pre>\n<p>There is one major difference, though; see the last section.</p>\n<hr />\n<h2>How you might use generators</h2>\n<p>An iterable is the last part of a list comprehension, and all generators are iterable, so they're often used like so:</p>\n<pre class=\"lang-py prettyprint-override\"><code># < ITERABLE >\n>>> [x+10 for x in makeRange(5)]\n[10, 11, 12, 13, 14]\n</code></pre>\n<p>To get a better feel for generators, you can play around with the <code>itertools</code> module (be sure to use <code>chain.from_iterable</code> rather than <code>chain</code> when warranted). For example, you might even use generators to implement infinitely-long lazy lists like <code>itertools.count()</code>. You could implement your own <code>def enumerate(iterable): zip(count(), iterable)</code>, or alternatively do so with the <code>yield</code> keyword in a while-loop.</p>\n<p>Please note: generators can actually be used for many more things, such as <a href=\"http://www.dabeaz.com/coroutines/index.html\" rel=\"noreferrer\">implementing coroutines</a> or non-deterministic programming or other elegant things. However, the "lazy lists" viewpoint I present here is the most common use you will find.</p>\n<hr />\n<h2>Behind the scenes</h2>\n<p>This is how the "Python iteration protocol" works. That is, what is going on when you do <code>list(makeRange(5))</code>. This is what I describe earlier as a "lazy, incremental list".</p>\n<pre class=\"lang-py prettyprint-override\"><code>>>> x=iter(range(5))\n>>> next(x) # calls x.__next__(); x.next() is deprecated\n0\n>>> next(x)\n1\n>>> next(x)\n2\n>>> next(x)\n3\n>>> next(x)\n4\n>>> next(x)\nTraceback (most recent call last):\n File "<stdin>", line 1, in <module>\nStopIteration\n</code></pre>\n<p>The built-in function <code>next()</code> just calls the objects <code>.__next__()</code> function, which is a part of the "iteration protocol" and is found on all iterators. You can manually use the <code>next()</code> function (and other parts of the iteration protocol) to implement fancy things, usually at the expense of readability, so try to avoid doing that...</p>\n<hr />\n<h2>Coroutines</h2>\n<p><a href=\"https://www.python.org/dev/peps/pep-0342/\" rel=\"noreferrer\">Coroutine</a> example:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def interactiveProcedure():\n userResponse = yield makeQuestionWebpage()\n print('user response:', userResponse)\n yield 'success'\n\ncoroutine = interactiveProcedure()\nwebFormData = next(coroutine) # same as .send(None)\nuserResponse = serveWebForm(webFormData)\n\n# ...at some point later on web form submit...\n\nsuccessStatus = coroutine.send(userResponse)\n</code></pre>\n<p>A coroutine (generators which generally accept input via the <code>yield</code> keyword e.g. <code>nextInput = yield nextOutput</code>, as a form of two-way communication) is basically a computation which is allowed to pause itself and request input (e.g. to what it should do next). When the coroutine pauses itself (when the running coroutine eventually hits a <code>yield</code> keyword), the computation is paused and control is inverted (yielded) back to the 'calling' function (the frame which requested the <code>next</code> value of the computation). The paused generator/coroutine remains paused until another invoking function (possibly a different function/context) requests the next value to unpause it (usually passing input data to direct the paused logic interior to the coroutine's code).</p>\n<p><strong>You can think of python coroutines as lazy incrementally-pending lists, where the next element doesn't just depend on the previous computation, but also on input you may opt to inject during the generation process.</strong></p>\n<hr />\n<h2>Minutiae</h2>\n<p>Normally, most people would not care about the following distinctions and probably want to stop reading here.</p>\n<p>In Python-speak, an <em>iterable</em> is any object which "understands the concept of a for-loop" like a list <code>[1,2,3]</code>, and an <em>iterator</em> is a specific instance of the requested for-loop like <code>[1,2,3].__iter__()</code>. A <em>generator</em> is exactly the same as any iterator, except for the way it was written (with function syntax).</p>\n<p>When you request an iterator from a list, it creates a new iterator. However, when you request an iterator from an iterator (which you would rarely do), it just gives you a copy of itself.</p>\n<p>Thus, in the unlikely event that you are failing to do something like this...</p>\n<pre class=\"lang-py prettyprint-override\"><code>> x = myRange(5)\n> list(x)\n[0, 1, 2, 3, 4]\n> list(x)\n[]\n</code></pre>\n<p>... then remember that a generator is an <em>iterator</em>; that is, it is one-time-use. If you want to reuse it, you should call <code>myRange(...)</code> again. If you need to use the result twice, convert the result to a list and store it in a variable <code>x = list(myRange(5))</code>. Those who absolutely need to clone a generator (for example, who are doing terrifyingly hackish metaprogramming) can use <a href=\"https://docs.python.org/2/library/itertools.html#itertools.tee\" rel=\"noreferrer\"><code>itertools.tee</code></a> (<a href=\"https://docs.python.org/3/library/itertools.html#itertools.tee\" rel=\"noreferrer\">still works in Python 3</a>) if absolutely necessary, since the <a href=\"https://www.python.org/dev/peps/pep-0323/\" rel=\"noreferrer\">copyable iterator Python PEP standards proposal</a> has been deferred.</p>\n"
},
{
"answer_id": 12716515,
"author": "Dustin Getz",
"author_id": 20003,
"author_profile": "https://Stackoverflow.com/users/20003",
"pm_score": 7,
"selected": false,
"text": "<p>Here are some Python examples of how to actually implement generators as if Python did not provide syntactic sugar for them:</p>\n\n<p><strong>As a Python generator:</strong></p>\n\n<pre><code>from itertools import islice\n\ndef fib_gen():\n a, b = 1, 1\n while True:\n yield a\n a, b = b, a + b\n\nassert [1, 1, 2, 3, 5] == list(islice(fib_gen(), 5))\n</code></pre>\n\n<p><strong>Using lexical closures instead of generators</strong></p>\n\n<pre><code>def ftake(fnext, last):\n return [fnext() for _ in xrange(last)]\n\ndef fib_gen2():\n #funky scope due to python2.x workaround\n #for python 3.x use nonlocal\n def _():\n _.a, _.b = _.b, _.a + _.b\n return _.a\n _.a, _.b = 0, 1\n return _\n\nassert [1,1,2,3,5] == ftake(fib_gen2(), 5)\n</code></pre>\n\n<p><strong>Using object closures instead of generators</strong> (because <a href=\"http://c2.com/cgi/wiki?ClosuresAndObjectsAreEquivalent\" rel=\"noreferrer\">ClosuresAndObjectsAreEquivalent</a>)</p>\n\n<pre><code>class fib_gen3:\n def __init__(self):\n self.a, self.b = 1, 1\n\n def __call__(self):\n r = self.a\n self.a, self.b = self.b, self.a + self.b\n return r\n\nassert [1,1,2,3,5] == ftake(fib_gen3(), 5)\n</code></pre>\n"
},
{
"answer_id": 14352675,
"author": "RBansal",
"author_id": 1776798,
"author_profile": "https://Stackoverflow.com/users/1776798",
"pm_score": 8,
"selected": false,
"text": "<p>Yield gives you a generator. </p>\n\n<pre><code>def get_odd_numbers(i):\n return range(1, i, 2)\ndef yield_odd_numbers(i):\n for x in range(1, i, 2):\n yield x\nfoo = get_odd_numbers(10)\nbar = yield_odd_numbers(10)\nfoo\n[1, 3, 5, 7, 9]\nbar\n<generator object yield_odd_numbers at 0x1029c6f50>\nbar.next()\n1\nbar.next()\n3\nbar.next()\n5\n</code></pre>\n\n<p>As you can see, in the first case <code>foo</code> holds the entire list in memory at once. It's not a big deal for a list with 5 elements, but what if you want a list of 5 million? Not only is this a huge memory eater, it also costs a lot of time to build at the time that the function is called.</p>\n\n<p>In the second case, <code>bar</code> just gives you a generator. A generator is an iterable--which means you can use it in a <code>for</code> loop, etc, but each value can only be accessed once. All the values are also not stored in memory at the same time; the generator object \"remembers\" where it was in the looping the last time you called it--this way, if you're using an iterable to (say) count to 50 billion, you don't have to count to 50 billion all at once and store the 50 billion numbers to count through.</p>\n\n<p>Again, this is a pretty contrived example, you probably would use itertools if you really wanted to count to 50 billion. :)</p>\n\n<p>This is the most simple use case of generators. As you said, it can be used to write efficient permutations, using yield to push things up through the call stack instead of using some sort of stack variable. Generators can also be used for specialized tree traversal, and all manner of other things.</p>\n"
},
{
"answer_id": 14404292,
"author": "Daniel",
"author_id": 1531346,
"author_profile": "https://Stackoverflow.com/users/1531346",
"pm_score": 8,
"selected": false,
"text": "<p>For those who prefer a minimal working example, meditate on this interactive Python session:</p>\n\n<pre><code>>>> def f():\n... yield 1\n... yield 2\n... yield 3\n... \n>>> g = f()\n>>> for i in g:\n... print(i)\n... \n1\n2\n3\n>>> for i in g:\n... print(i)\n... \n>>> # Note that this time nothing was printed\n</code></pre>\n"
},
{
"answer_id": 14554322,
"author": "johnzachary",
"author_id": 479213,
"author_profile": "https://Stackoverflow.com/users/479213",
"pm_score": 7,
"selected": false,
"text": "<p>I was going to post \"read page 19 of Beazley's 'Python: Essential Reference' for a quick description of generators\", but so many others have posted good descriptions already.</p>\n\n<p>Also, note that <code>yield</code> can be used in coroutines as the dual of their use in generator functions. Although it isn't the same use as your code snippet, <code>(yield)</code> can be used as an expression in a function. When a caller sends a value to the method using the <code>send()</code> method, then the coroutine will execute until the next <code>(yield)</code> statement is encountered.</p>\n\n<p>Generators and coroutines are a cool way to set up data-flow type applications. I thought it would be worthwhile knowing about the other use of the <code>yield</code> statement in functions.</p>\n"
},
{
"answer_id": 15814755,
"author": "aestrivex",
"author_id": 2040716,
"author_profile": "https://Stackoverflow.com/users/2040716",
"pm_score": 8,
"selected": false,
"text": "<p>There is one type of answer that I don't feel has been given yet, among the many great answers that describe how to use generators. Here is the programming language theory answer:</p>\n\n<p>The <code>yield</code> statement in Python returns a generator. A generator in Python is a function that returns <i>continuations</i> (and specifically a type of coroutine, but continuations represent the more general mechanism to understand what is going on).</p>\n\n<p>Continuations in programming languages theory are a much more fundamental kind of computation, but they are not often used, because they are extremely hard to reason about and also very difficult to implement. But the idea of what a continuation is, is straightforward: it is the state of a computation that has not yet finished. In this state, the current values of variables, the operations that have yet to be performed, and so on, are saved. Then at some point later in the program the continuation can be invoked, such that the program's variables are reset to that state and the operations that were saved are carried out.</p>\n\n<p>Continuations, in this more general form, can be implemented in two ways. In the <code>call/cc</code> way, the program's stack is literally saved and then when the continuation is invoked, the stack is restored.</p>\n\n<p>In continuation passing style (CPS), continuations are just normal functions (only in languages where functions are first class) which the programmer explicitly manages and passes around to subroutines. In this style, program state is represented by closures (and the variables that happen to be encoded in them) rather than variables that reside somewhere on the stack. Functions that manage control flow accept continuation as arguments (in some variations of CPS, functions may accept multiple continuations) and manipulate control flow by invoking them by simply calling them and returning afterwards. A very simple example of continuation passing style is as follows:</p>\n\n<pre><code>def save_file(filename):\n def write_file_continuation():\n write_stuff_to_file(filename)\n\n check_if_file_exists_and_user_wants_to_overwrite(write_file_continuation)\n</code></pre>\n\n<p>In this (very simplistic) example, the programmer saves the operation of actually writing the file into a continuation (which can potentially be a very complex operation with many details to write out), and then passes that continuation (i.e, as a first-class closure) to another operator which does some more processing, and then calls it if necessary. (I use this design pattern a lot in actual GUI programming, either because it saves me lines of code or, more importantly, to manage control flow after GUI events trigger.)</p>\n\n<p>The rest of this post will, without loss of generality, conceptualize continuations as CPS, because it is a hell of a lot easier to understand and read.</p>\n\n<p><br></p>\n\n<p>Now let's talk about generators in Python. Generators are a specific subtype of continuation. Whereas <strong>continuations are able in general to save the state of a <em>computation</em></strong> (i.e., the program's call stack), <strong>generators are only able to save the state of iteration over an <em>iterator</em></strong>. Although, this definition is slightly misleading for certain use cases of generators. For instance:</p>\n\n<pre><code>def f():\n while True:\n yield 4\n</code></pre>\n\n<p>This is clearly a reasonable iterable whose behavior is well defined -- each time the generator iterates over it, it returns 4 (and does so forever). But it isn't probably the prototypical type of iterable that comes to mind when thinking of iterators (i.e., <code>for x in collection: do_something(x)</code>). This example illustrates the power of generators: if anything is an iterator, a generator can save the state of its iteration.</p>\n\n<p>To reiterate: Continuations can save the state of a program's stack and generators can save the state of iteration. This means that continuations are more a lot powerful than generators, but also that generators are a lot, lot easier. They are easier for the language designer to implement, and they are easier for the programmer to use (if you have some time to burn, try to read and understand <a href=\"http://www.madore.org/~david/computers/callcc.html\" rel=\"noreferrer\">this page about continuations and call/cc</a>).</p>\n\n<p>But you could easily implement (and conceptualize) generators as a simple, specific case of continuation passing style:</p>\n\n<p>Whenever <code>yield</code> is called, it tells the function to return a continuation. When the function is called again, it starts from wherever it left off. So, in pseudo-pseudocode (i.e., not pseudocode, but not code) the generator's <code>next</code> method is basically as follows:</p>\n\n<pre><code>class Generator():\n def __init__(self,iterable,generatorfun):\n self.next_continuation = lambda:generatorfun(iterable)\n\n def next(self):\n value, next_continuation = self.next_continuation()\n self.next_continuation = next_continuation\n return value\n</code></pre>\n\n<p>where the <code>yield</code> keyword is actually syntactic sugar for the real generator function, basically something like:</p>\n\n<pre><code>def generatorfun(iterable):\n if len(iterable) == 0:\n raise StopIteration\n else:\n return (iterable[0], lambda:generatorfun(iterable[1:]))\n</code></pre>\n\n<p>Remember that this is just pseudocode and the actual implementation of generators in Python is more complex. But as an exercise to understand what is going on, try to use continuation passing style to implement generator objects without use of the <code>yield</code> keyword.</p>\n"
},
{
"answer_id": 17113322,
"author": "Evgeni Sergeev",
"author_id": 1143274,
"author_profile": "https://Stackoverflow.com/users/1143274",
"pm_score": 6,
"selected": false,
"text": "<p>Here is a mental image of what <code>yield</code> does.</p>\n\n<p>I like to think of a thread as having a stack (even when it's not implemented that way).</p>\n\n<p>When a normal function is called, it puts its local variables on the stack, does some computation, then clears the stack and returns. The values of its local variables are never seen again.</p>\n\n<p>With a <code>yield</code> function, when its code begins to run (i.e. after the function is called, returning a generator object, whose <code>next()</code> method is then invoked), it similarly puts its local variables onto the stack and computes for a while. But then, when it hits the <code>yield</code> statement, before clearing its part of the stack and returning, it takes a snapshot of its local variables and stores them in the generator object. It also writes down the place where it's currently up to in its code (i.e. the particular <code>yield</code> statement).</p>\n\n<p>So it's a kind of a frozen function that the generator is hanging onto.</p>\n\n<p>When <code>next()</code> is called subsequently, it retrieves the function's belongings onto the stack and re-animates it. The function continues to compute from where it left off, oblivious to the fact that it had just spent an eternity in cold storage.</p>\n\n<p>Compare the following examples:</p>\n\n<pre><code>def normalFunction():\n return\n if False:\n pass\n\ndef yielderFunction():\n return\n if False:\n yield 12\n</code></pre>\n\n<p>When we call the second function, it behaves very differently to the first. The <code>yield</code> statement might be unreachable, but if it's present anywhere, it changes the nature of what we're dealing with.</p>\n\n<pre><code>>>> yielderFunction()\n<generator object yielderFunction at 0x07742D28>\n</code></pre>\n\n<p>Calling <code>yielderFunction()</code> doesn't run its code, but makes a generator out of the code. (Maybe it's a good idea to name such things with the <code>yielder</code> prefix for readability.)</p>\n\n<pre><code>>>> gen = yielderFunction()\n>>> dir(gen)\n['__class__',\n ...\n '__iter__', #Returns gen itself, to make it work uniformly with containers\n ... #when given to a for loop. (Containers return an iterator instead.)\n 'close',\n 'gi_code',\n 'gi_frame',\n 'gi_running',\n 'next', #The method that runs the function's body.\n 'send',\n 'throw']\n</code></pre>\n\n<p>The <code>gi_code</code> and <code>gi_frame</code> fields are where the frozen state is stored. Exploring them with <code>dir(..)</code>, we can confirm that our mental model above is credible.</p>\n"
},
{
"answer_id": 18365578,
"author": "alinsoar",
"author_id": 1419272,
"author_profile": "https://Stackoverflow.com/users/1419272",
"pm_score": 7,
"selected": false,
"text": "<p>From a programming viewpoint, the iterators are implemented as <a href=\"http://en.wikipedia.org/wiki/Thunk_(functional_programming)\" rel=\"noreferrer\">thunks</a>.</p>\n<p>To implement iterators, generators, and thread pools for concurrent execution, etc. as thunks, one uses <a href=\"https://wiki.c2.com/?ClosuresAndObjectsAreEquivalent\" rel=\"noreferrer\">messages sent to a closure object</a>, which has a dispatcher, and the <a href=\"http://en.wikipedia.org/wiki/Message_passing\" rel=\"noreferrer\">dispatcher answers to "messages"</a>.</p>\n<p><a href=\"https://docs.python.org/3/library/functions.html#next\" rel=\"noreferrer\">"<em>next</em>"</a> is a message sent to a closure, created by the "<em>iter</em>" call.</p>\n<p>There are lots of ways to implement this computation. I used mutation, but it is possible to do this kind of computation without mutation, by returning the current value and the next yielder (making it <a href=\"https://en.wikipedia.org/wiki/Referential_transparency\" rel=\"noreferrer\">referential transparent</a>). Racket uses a sequence of transformations of the initial program in some intermediary languages, one of such rewriting making the yield operator to be transformed in some language with simpler operators.</p>\n<p>Here is a demonstration of how yield could be rewritten, which uses the structure of R6RS, but the semantics is identical to Python's. It's the same model of computation, and only a change in syntax is required to rewrite it using yield of Python.</p>\n<blockquote>\n<pre><code>Welcome to Racket v6.5.0.3.\n\n-> (define gen\n (lambda (l)\n (define yield\n (lambda ()\n (if (null? l)\n 'END\n (let ((v (car l)))\n (set! l (cdr l))\n v))))\n (lambda(m)\n (case m\n ('yield (yield))\n ('init (lambda (data)\n (set! l data)\n 'OK))))))\n-> (define stream (gen '(1 2 3)))\n-> (stream 'yield)\n1\n-> (stream 'yield)\n2\n-> (stream 'yield)\n3\n-> (stream 'yield)\n'END\n-> ((stream 'init) '(a b))\n'OK\n-> (stream 'yield)\n'a\n-> (stream 'yield)\n'b\n-> (stream 'yield)\n'END\n-> (stream 'yield)\n'END\n->\n</code></pre>\n</blockquote>\n"
},
{
"answer_id": 20704301,
"author": "Engin OZTURK",
"author_id": 1077381,
"author_profile": "https://Stackoverflow.com/users/1077381",
"pm_score": 7,
"selected": false,
"text": "<p>Here is a simple example:</p>\n\n<pre><code>def isPrimeNumber(n):\n print \"isPrimeNumber({}) call\".format(n)\n if n==1:\n return False\n for x in range(2,n):\n if n % x == 0:\n return False\n return True\n\ndef primes (n=1):\n while(True):\n print \"loop step ---------------- {}\".format(n)\n if isPrimeNumber(n): yield n\n n += 1\n\nfor n in primes():\n if n> 10:break\n print \"wiriting result {}\".format(n)\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>loop step ---------------- 1\nisPrimeNumber(1) call\nloop step ---------------- 2\nisPrimeNumber(2) call\nloop step ---------------- 3\nisPrimeNumber(3) call\nwiriting result 3\nloop step ---------------- 4\nisPrimeNumber(4) call\nloop step ---------------- 5\nisPrimeNumber(5) call\nwiriting result 5\nloop step ---------------- 6\nisPrimeNumber(6) call\nloop step ---------------- 7\nisPrimeNumber(7) call\nwiriting result 7\nloop step ---------------- 8\nisPrimeNumber(8) call\nloop step ---------------- 9\nisPrimeNumber(9) call\nloop step ---------------- 10\nisPrimeNumber(10) call\nloop step ---------------- 11\nisPrimeNumber(11) call\n</code></pre>\n\n<p>I am not a Python developer, but it looks to me <code>yield</code> holds the position of program flow and the next loop start from \"yield\" position. It seems like it is waiting at that position, and just before that, returning a value outside, and next time continues to work.</p>\n\n<p>It seems to be an interesting and nice ability :D</p>\n"
},
{
"answer_id": 21541902,
"author": "Mike McKerns",
"author_id": 2379433,
"author_profile": "https://Stackoverflow.com/users/2379433",
"pm_score": 7,
"selected": false,
"text": "<p>While a lot of answers show why you'd use a <code>yield</code> to create a generator, there are more uses for <code>yield</code>. It's quite easy to make a coroutine, which enables the passing of information between two blocks of code. I won't repeat any of the fine examples that have already been given about using <code>yield</code> to create a generator.</p>\n\n<p>To help understand what a <code>yield</code> does in the following code, you can use your finger to trace the cycle through any code that has a <code>yield</code>. Every time your finger hits the <code>yield</code>, you have to wait for a <code>next</code> or a <code>send</code> to be entered. When a <code>next</code> is called, you trace through the code until you hit the <code>yield</code>… the code on the right of the <code>yield</code> is evaluated and returned to the caller… then you wait. When <code>next</code> is called again, you perform another loop through the code. However, you'll note that in a coroutine, <code>yield</code> can also be used with a <code>send</code>… which will send a value from the caller <em>into</em> the yielding function. If a <code>send</code> is given, then <code>yield</code> receives the value sent, and spits it out the left hand side… then the trace through the code progresses until you hit the <code>yield</code> again (returning the value at the end, as if <code>next</code> was called).</p>\n\n<p>For example:</p>\n\n<pre><code>>>> def coroutine():\n... i = -1\n... while True:\n... i += 1\n... val = (yield i)\n... print(\"Received %s\" % val)\n...\n>>> sequence = coroutine()\n>>> sequence.next()\n0\n>>> sequence.next()\nReceived None\n1\n>>> sequence.send('hello')\nReceived hello\n2\n>>> sequence.close()\n</code></pre>\n"
},
{
"answer_id": 24944096,
"author": "Sławomir Lenart",
"author_id": 1416144,
"author_profile": "https://Stackoverflow.com/users/1416144",
"pm_score": 7,
"selected": false,
"text": "<p>There is another <code>yield</code> use and meaning (since Python 3.3):</p>\n<pre><code>yield from <expr>\n</code></pre>\n<p>From <em><a href=\"http://www.python.org/dev/peps/pep-0380/\" rel=\"noreferrer\">PEP 380 -- Syntax for Delegating to a Subgenerator</a></em>:</p>\n<blockquote>\n<p>A syntax is proposed for a generator to delegate part of its operations to another generator. This allows a section of code containing 'yield' to be factored out and placed in another generator. Additionally, the subgenerator is allowed to return with a value, and the value is made available to the delegating generator.</p>\n<p>The new syntax also opens up some opportunities for optimisation when one generator re-yields values produced by another.</p>\n</blockquote>\n<p>Moreover <a href=\"https://www.python.org/dev/peps/pep-0492/\" rel=\"noreferrer\">this</a> will introduce (since Python 3.5):</p>\n<pre><code>async def new_coroutine(data):\n ...\n await blocking_action()\n</code></pre>\n<p>to avoid coroutines being confused with a regular generator (today <code>yield</code> is used in both).</p>\n"
},
{
"answer_id": 30341713,
"author": "Will Dereham",
"author_id": 4884103,
"author_profile": "https://Stackoverflow.com/users/4884103",
"pm_score": 6,
"selected": false,
"text": "<p><code>yield</code> is like a return element for a function. The difference is, that the <code>yield</code> element turns a function into a generator. A generator behaves just like a function until something is 'yielded'. The generator stops until it is next called, and continues from exactly the same point as it started. You can get a sequence of all the 'yielded' values in one, by calling <code>list(generator())</code>.</p>\n"
},
{
"answer_id": 31042491,
"author": "Russia Must Remove Putin",
"author_id": 541136,
"author_profile": "https://Stackoverflow.com/users/541136",
"pm_score": 9,
"selected": false,
"text": "<blockquote>\n<p><strong>What does the <code>yield</code> keyword do in Python?</strong></p>\n</blockquote>\n<h1>Answer Outline/Summary</h1>\n<ul>\n<li>A function with <a href=\"https://docs.python.org/reference/expressions.html#yieldexpr\" rel=\"noreferrer\"><strong><code>yield</code></strong></a>, when called, <strong>returns a <a href=\"https://docs.python.org/2/tutorial/classes.html#generators\" rel=\"noreferrer\">Generator</a>.</strong></li>\n<li>Generators are iterators because they implement the <a href=\"https://docs.python.org/2/library/stdtypes.html#iterator-types\" rel=\"noreferrer\"><strong>iterator protocol</strong></a>, so you can iterate over them.</li>\n<li>A generator can also be <strong>sent information</strong>, making it conceptually a <strong>coroutine</strong>.</li>\n<li>In Python 3, you can <strong>delegate</strong> from one generator to another in both directions with <strong><code>yield from</code></strong>.</li>\n<li>(Appendix critiques a couple of answers, including the top one, and discusses the use of <code>return</code> in a generator.)</li>\n</ul>\n<h1>Generators:</h1>\n<p><strong><code>yield</code></strong> is only legal inside of a function definition, and <strong>the inclusion of <code>yield</code> in a function definition makes it return a generator.</strong></p>\n<p>The idea for generators comes from other languages (see footnote 1) with varying implementations. In Python's Generators, the execution of the code is <a href=\"https://docs.python.org/3.5/glossary.html#term-generator-iterator\" rel=\"noreferrer\">frozen</a> at the point of the yield. When the generator is called (methods are discussed below) execution resumes and then freezes at the next yield.</p>\n<p><code>yield</code> provides an\neasy way of <a href=\"https://docs.python.org/2/library/stdtypes.html#generator-types\" rel=\"noreferrer\">implementing the iterator protocol</a>, defined by the following two methods:\n<code>__iter__</code> and <code>__next__</code>. Both of those methods\nmake an object an iterator that you could type-check with the <code>Iterator</code> Abstract Base\nClass from the <code>collections</code> module.</p>\n<pre><code>def func():\n yield 'I am'\n yield 'a generator!'\n</code></pre>\n<p>Let's do some introspection:</p>\n<pre><code>>>> type(func) # A function with yield is still a function\n<type 'function'>\n>>> gen = func()\n>>> type(gen) # but it returns a generator\n<type 'generator'>\n>>> hasattr(gen, '__iter__') # that's an iterable\nTrue\n>>> hasattr(gen, '__next__') # and with .__next__\nTrue # implements the iterator protocol.\n</code></pre>\n<p>The generator type is a sub-type of iterator:</p>\n<pre><code>from types import GeneratorType\nfrom collections.abc import Iterator\n\n>>> issubclass(GeneratorType, Iterator)\nTrue\n</code></pre>\n<p>And if necessary, we can type-check like this:</p>\n<pre><code>>>> isinstance(gen, GeneratorType)\nTrue\n>>> isinstance(gen, Iterator)\nTrue\n</code></pre>\n<p>A feature of an <code>Iterator</code> <a href=\"https://docs.python.org/2/glossary.html#term-iterator\" rel=\"noreferrer\">is that once exhausted</a>, you can't reuse or reset it:</p>\n<pre><code>>>> list(gen)\n['I am', 'a generator!']\n>>> list(gen)\n[]\n</code></pre>\n<p>You'll have to make another if you want to use its functionality again (see footnote 2):</p>\n<pre><code>>>> list(func())\n['I am', 'a generator!']\n</code></pre>\n<p>One can yield data programmatically, for example:</p>\n<pre><code>def func(an_iterable):\n for item in an_iterable:\n yield item\n</code></pre>\n<p>The above simple generator is also equivalent to the below - as of Python 3.3 you can use <a href=\"https://www.python.org/dev/peps/pep-0380/\" rel=\"noreferrer\"><code>yield from</code></a>:</p>\n<pre><code>def func(an_iterable):\n yield from an_iterable\n</code></pre>\n<p>However, <code>yield from</code> also allows for delegation to subgenerators,\nwhich will be explained in the following section on cooperative delegation with sub-coroutines.</p>\n<h1>Coroutines:</h1>\n<p><code>yield</code> forms an expression that allows data to be sent into the generator (see footnote 3)</p>\n<p>Here is an example, take note of the <code>received</code> variable, which will point to the data that is sent to the generator:</p>\n<pre><code>def bank_account(deposited, interest_rate):\n while True:\n calculated_interest = interest_rate * deposited \n received = yield calculated_interest\n if received:\n deposited += received\n\n\n>>> my_account = bank_account(1000, .05)\n</code></pre>\n<p>First, we must queue up the generator with the builtin function, <a href=\"https://docs.python.org/2/library/functions.html#next\" rel=\"noreferrer\"><code>next</code></a>. It will\ncall the appropriate <code>next</code> or <code>__next__</code> method, depending on the version of\nPython you are using:</p>\n<pre><code>>>> first_year_interest = next(my_account)\n>>> first_year_interest\n50.0\n</code></pre>\n<p>And now we can send data into the generator. (<a href=\"https://www.python.org/dev/peps/pep-0342/#specification-sending-values-into-generators\" rel=\"noreferrer\">Sending <code>None</code> is\nthe same as calling <code>next</code></a>.) :</p>\n<pre><code>>>> next_year_interest = my_account.send(first_year_interest + 1000)\n>>> next_year_interest\n102.5\n</code></pre>\n<h2>Cooperative Delegation to Sub-Coroutine with <code>yield from</code></h2>\n<p>Now, recall that <code>yield from</code> is available in Python 3. This allows us to delegate coroutines to a subcoroutine:</p>\n<pre class=\"lang-py prettyprint-override\"><code>\ndef money_manager(expected_rate):\n # must receive deposited value from .send():\n under_management = yield # yield None to start.\n while True:\n try:\n additional_investment = yield expected_rate * under_management \n if additional_investment:\n under_management += additional_investment\n except GeneratorExit:\n '''TODO: write function to send unclaimed funds to state'''\n raise\n finally:\n '''TODO: write function to mail tax info to client'''\n \n\ndef investment_account(deposited, manager):\n '''very simple model of an investment account that delegates to a manager'''\n # must queue up manager:\n next(manager) # <- same as manager.send(None)\n # This is where we send the initial deposit to the manager:\n manager.send(deposited)\n try:\n yield from manager\n except GeneratorExit:\n return manager.close() # delegate?\n</code></pre>\n<p>And now we can delegate functionality to a sub-generator and it can be used\nby a generator just as above:</p>\n<pre class=\"lang-py prettyprint-override\"><code>my_manager = money_manager(.06)\nmy_account = investment_account(1000, my_manager)\nfirst_year_return = next(my_account) # -> 60.0\n</code></pre>\n<p>Now simulate adding another 1,000 to the account plus the return on the account (60.0):</p>\n<pre class=\"lang-py prettyprint-override\"><code>next_year_return = my_account.send(first_year_return + 1000)\nnext_year_return # 123.6\n</code></pre>\n<p>You can read more about the precise semantics of <code>yield from</code> in <a href=\"https://www.python.org/dev/peps/pep-0380/#formal-semantics\" rel=\"noreferrer\">PEP 380.</a></p>\n<h2>Other Methods: close and throw</h2>\n<p>The <code>close</code> method raises <code>GeneratorExit</code> at the point the function\nexecution was frozen. This will also be called by <code>__del__</code> so you\ncan put any cleanup code where you handle the <code>GeneratorExit</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>my_account.close()\n</code></pre>\n<p>You can also throw an exception which can be handled in the generator\nor propagated back to the user:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import sys\ntry:\n raise ValueError\nexcept:\n my_manager.throw(*sys.exc_info())\n</code></pre>\n<p>Raises:</p>\n<pre class=\"lang-none prettyprint-override\"><code>Traceback (most recent call last):\n File "<stdin>", line 4, in <module>\n File "<stdin>", line 6, in money_manager\n File "<stdin>", line 2, in <module>\nValueError\n</code></pre>\n<h1>Conclusion</h1>\n<p>I believe I have covered all aspects of the following question:</p>\n<blockquote>\n<p><strong>What does the <code>yield</code> keyword do in Python?</strong></p>\n</blockquote>\n<p>It turns out that <code>yield</code> does a lot. I'm sure I could add even more\nthorough examples to this. If you want more or have some constructive criticism, let me know by commenting\nbelow.</p>\n<hr />\n<h1>Appendix:</h1>\n<h2>Critique of the Top/Accepted Answer**</h2>\n<ul>\n<li>It is confused on what makes an <strong>iterable</strong>, just using a list as an example. See my references above, but in summary: an <strong>iterable</strong> has an <code>__iter__</code> method returning an <strong>iterator</strong>. An <strong>iterator</strong> additionally provides a <code>.__next__</code> method, which is implicitly called by <code>for</code> loops until it raises <code>StopIteration</code>, and once it does raise <code>StopIteration</code>, it will continue to do so.</li>\n<li>It then uses a generator expression to describe what a generator is. Since a generator expression is simply a convenient way to create an <strong>iterator</strong>, it only confuses the matter, and we still have not yet gotten to the <code>yield</code> part.</li>\n<li>In <strong>Controlling a generator exhaustion</strong> he calls the <code>.next</code> method (which only works in Python 2), when instead he should use the builtin function, <code>next</code>. Calling <code>next(obj)</code> would be an appropriate layer of indirection, because his code does not work in Python 3.</li>\n<li>Itertools? This was not relevant to what <code>yield</code> does at all.</li>\n<li>No discussion of the methods that <code>yield</code> provides along with the new functionality <code>yield from</code> in Python 3.</li>\n</ul>\n<p><strong>The top/accepted answer is a very incomplete answer.</strong></p>\n<h2>Critique of answer suggesting <code>yield</code> in a generator expression or comprehension.</h2>\n<p>The grammar currently allows any expression in a list comprehension.</p>\n<pre><code>expr_stmt: testlist_star_expr (annassign | augassign (yield_expr|testlist) |\n ('=' (yield_expr|testlist_star_expr))*)\n...\nyield_expr: 'yield' [yield_arg]\nyield_arg: 'from' test | testlist\n</code></pre>\n<p>Since yield is an expression, it has been touted by some as interesting to use it in comprehensions or generator expression - in spite of citing no particularly good use-case.</p>\n<p>The CPython core developers are <a href=\"https://mail.python.org/pipermail/python-dev/2017-January/147301.html\" rel=\"noreferrer\">discussing deprecating its allowance</a>.\nHere's a relevant post from the mailing list:</p>\n<blockquote>\n<p>On 30 January 2017 at 19:05, Brett Cannon wrote:</p>\n<blockquote>\n<p>On Sun, 29 Jan 2017 at 16:39 Craig Rodrigues wrote:</p>\n<blockquote>\n<p>I'm OK with either approach. Leaving things the way they are in Python 3\nis no good, IMHO.</p>\n</blockquote>\n<p>My vote is it be a SyntaxError since you're not getting what you expect from\nthe syntax.</p>\n</blockquote>\n<p>I'd agree that's a sensible place for us to end up, as any code\nrelying on the current behaviour is really too clever to be\nmaintainable.</p>\n<p>In terms of getting there, we'll likely want:</p>\n<ul>\n<li>SyntaxWarning or DeprecationWarning in 3.7</li>\n<li>Py3k warning in 2.7.x</li>\n<li>SyntaxError in 3.8</li>\n</ul>\n<p>Cheers, Nick.</p>\n<p>-- Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia</p>\n</blockquote>\n<p>Further, there is an <a href=\"http://bugs.python.org/issue10544\" rel=\"noreferrer\">outstanding issue (10544)</a> which seems to be pointing in the direction of this <em>never</em> being a good idea (PyPy, a Python implementation written in Python, is already raising syntax warnings.)</p>\n<p>Bottom line, until the developers of CPython tell us otherwise: <strong>Don't put <code>yield</code> in a generator expression or comprehension.</strong></p>\n<h2>The <code>return</code> statement in a generator</h2>\n<p>In <a href=\"https://docs.python.org/3/reference/simple_stmts.html#the-return-statement\" rel=\"noreferrer\">Python 3</a>:</p>\n<blockquote>\n<p>In a generator function, the <code>return</code> statement indicates that the generator is done and will cause <code>StopIteration</code> to be raised. The returned value (if any) is used as an argument to construct <code>StopIteration</code> and becomes the <code>StopIteration.value</code> attribute.</p>\n</blockquote>\n<p><sub>Historical note, in <a href=\"https://docs.python.org/2/reference/simple_stmts.html#the-return-statement\" rel=\"noreferrer\">Python 2</a>:\n"In a generator function, the <code>return</code> statement is not allowed to include an <code>expression_list</code>. In that context, a bare <code>return</code> indicates that the generator is done and will cause <code>StopIteration</code> to be raised."\nAn <code>expression_list</code> is basically any number of expressions separated by commas - essentially, in Python 2, you can stop the generator with <code>return</code>, but you can't return a value.\n</sub></p>\n<h2>Footnotes</h2>\n<ol>\n<li><p><sub>The languages CLU, Sather, and Icon were referenced in the proposal\nto introduce the concept of generators to Python. The general idea is\nthat a function can maintain internal state and yield intermediate\ndata points on demand by the user. This promised to be <a href=\"https://www.python.org/dev/peps/pep-0255/\" rel=\"noreferrer\">superior in performance\nto other approaches, including Python threading</a>, which isn't even available on some systems.</sub></p>\n</li>\n<li><p><sub> This means, for example, that <code>range</code> objects aren't <code>Iterator</code>s, even though they are iterable, because they can be reused. Like lists, their <code>__iter__</code> methods return iterator objects.</sub></p>\n</li>\n<li><p><sub> <code>yield</code> was originally introduced as a statement, meaning that it\ncould only appear at the beginning of a line in a code block.\nNow <code>yield</code> creates a yield expression.\n<a href=\"https://docs.python.org/2/reference/simple_stmts.html#grammar-token-yield_stmt\" rel=\"noreferrer\">https://docs.python.org/2/reference/simple_stmts.html#grammar-token-yield_stmt</a>\nThis change was <a href=\"https://www.python.org/dev/peps/pep-0342/#specification-sending-values-into-generators\" rel=\"noreferrer\">proposed</a> to allow a user to send data into the generator just as\none might receive it. To send data, one must be able to assign it to something, and\nfor that, a statement just won't work.</sub></p>\n</li>\n</ol>\n"
},
{
"answer_id": 31692481,
"author": "Mangu Singh Rajpurohit",
"author_id": 2393267,
"author_profile": "https://Stackoverflow.com/users/2393267",
"pm_score": 6,
"selected": false,
"text": "<p>Like every answer suggests, <code>yield</code> is used for creating a sequence generator. It's used for generating some sequence dynamically. For example, while reading a file line by line on a network, you can use the <code>yield</code> function as follows:</p>\n\n<pre><code>def getNextLines():\n while con.isOpen():\n yield con.read()\n</code></pre>\n\n<p>You can use it in your code as follows:</p>\n\n<pre><code>for line in getNextLines():\n doSomeThing(line)\n</code></pre>\n\n<p><strong><em>Execution Control Transfer gotcha</em></strong></p>\n\n<p>The execution control will be transferred from getNextLines() to the <code>for</code> loop when yield is executed. Thus, every time getNextLines() is invoked, execution begins from the point where it was paused last time.</p>\n\n<p>Thus in short, a function with the following code</p>\n\n<pre><code>def simpleYield():\n yield \"first time\"\n yield \"second time\"\n yield \"third time\"\n yield \"Now some useful value {}\".format(12)\n\nfor i in simpleYield():\n print i\n</code></pre>\n\n<p>will print</p>\n\n<pre><code>\"first time\"\n\"second time\"\n\"third time\"\n\"Now some useful value 12\"\n</code></pre>\n"
},
{
"answer_id": 32331953,
"author": "Kaleem Ullah",
"author_id": 2046817,
"author_profile": "https://Stackoverflow.com/users/2046817",
"pm_score": 6,
"selected": false,
"text": "<p><strong>Yield is an object</strong></p>\n\n<p>A <code>return</code> in a function will return a single value.</p>\n\n<p>If you want <strong>a function to return a huge set of values</strong>, use <code>yield</code>.</p>\n\n<p>More importantly, <code>yield</code> is a <strong>barrier</strong>.</p>\n\n<blockquote>\n <p>like barrier in the CUDA language, it will not transfer control until it gets\n completed.</p>\n</blockquote>\n\n<p>That is, it will run the code in your function from the beginning until it hits <code>yield</code>. Then, it’ll return the first value of the loop.</p>\n\n<p>Then, every other call will run the loop you have written in the function one more time, returning the next value until there isn't any value to return.</p>\n"
},
{
"answer_id": 33788856,
"author": "Bahtiyar Özdere",
"author_id": 5069117,
"author_profile": "https://Stackoverflow.com/users/5069117",
"pm_score": 6,
"selected": false,
"text": "<p>The <code>yield</code> keyword simply collects returning results. Think of <code>yield</code> like <code>return +=</code></p>\n"
},
{
"answer_id": 35526740,
"author": "Dimitris Fasarakis Hilliard",
"author_id": 4952130,
"author_profile": "https://Stackoverflow.com/users/4952130",
"pm_score": 6,
"selected": false,
"text": "<p>Here's a simple <code>yield</code> based approach, to compute the fibonacci series, explained:</p>\n\n<pre><code>def fib(limit=50):\n a, b = 0, 1\n for i in range(limit):\n yield b\n a, b = b, a+b\n</code></pre>\n\n<p>When you enter this into your REPL and then try and call it, you'll get a mystifying result:</p>\n\n<pre><code>>>> fib()\n<generator object fib at 0x7fa38394e3b8>\n</code></pre>\n\n<p>This is because the presence of <code>yield</code> signaled to Python that you want to create a <em>generator</em>, that is, an object that generates values on demand.</p>\n\n<p>So, how do you generate these values? This can either be done directly by using the built-in function <code>next</code>, or, indirectly by feeding it to a construct that consumes values. </p>\n\n<p>Using the built-in <code>next()</code> function, you directly invoke <code>.next</code>/<code>__next__</code>, forcing the generator to produce a value:</p>\n\n<pre><code>>>> g = fib()\n>>> next(g)\n1\n>>> next(g)\n1\n>>> next(g)\n2\n>>> next(g)\n3\n>>> next(g)\n5\n</code></pre>\n\n<p>Indirectly, if you provide <code>fib</code> to a <code>for</code> loop, a <code>list</code> initializer, a <code>tuple</code> initializer, or anything else that expects an object that generates/produces values, you'll \"consume\" the generator until no more values can be produced by it (and it returns):</p>\n\n<pre><code>results = []\nfor i in fib(30): # consumes fib\n results.append(i) \n# can also be accomplished with\nresults = list(fib(30)) # consumes fib\n</code></pre>\n\n<p>Similarly, with a <code>tuple</code> initializer: </p>\n\n<pre><code>>>> tuple(fib(5)) # consumes fib\n(1, 1, 2, 3, 5)\n</code></pre>\n\n<p>A generator differs from a function in the sense that it is lazy. It accomplishes this by maintaining it's local state and allowing you to resume whenever you need to. </p>\n\n<p>When you first invoke <code>fib</code> by calling it:</p>\n\n<pre><code>f = fib()\n</code></pre>\n\n<p>Python compiles the function, encounters the <code>yield</code> keyword and simply returns a generator object back at you. Not very helpful it seems. </p>\n\n<p>When you then request it generates the first value, directly or indirectly, it executes all statements that it finds, until it encounters a <code>yield</code>, it then yields back the value you supplied to <code>yield</code> and pauses. For an example that better demonstrates this, let's use some <code>print</code> calls (replace with <code>print \"text\"</code> if on Python 2):</p>\n\n<pre><code>def yielder(value):\n \"\"\" This is an infinite generator. Only use next on it \"\"\" \n while 1:\n print(\"I'm going to generate the value for you\")\n print(\"Then I'll pause for a while\")\n yield value\n print(\"Let's go through it again.\")\n</code></pre>\n\n<p>Now, enter in the REPL:</p>\n\n<pre><code>>>> gen = yielder(\"Hello, yield!\")\n</code></pre>\n\n<p>you have a generator object now waiting for a command for it to generate a value. Use <code>next</code> and see what get's printed:</p>\n\n<pre><code>>>> next(gen) # runs until it finds a yield\nI'm going to generate the value for you\nThen I'll pause for a while\n'Hello, yield!'\n</code></pre>\n\n<p>The unquoted results are what's printed. The quoted result is what is returned from <code>yield</code>. Call <code>next</code> again now:</p>\n\n<pre><code>>>> next(gen) # continues from yield and runs again\nLet's go through it again.\nI'm going to generate the value for you\nThen I'll pause for a while\n'Hello, yield!'\n</code></pre>\n\n<p>The generator remembers it was paused at <code>yield value</code> and resumes from there. The next message is printed and the search for the <code>yield</code> statement to pause at it performed again (due to the <code>while</code> loop).</p>\n"
},
{
"answer_id": 36214653,
"author": "smwikipedia",
"author_id": 264052,
"author_profile": "https://Stackoverflow.com/users/264052",
"pm_score": 6,
"selected": false,
"text": "<p>(My below answer only speaks from the perspective of using Python generator, not the <a href=\"https://stackoverflow.com/questions/8389812/how-are-generators-and-coroutines-implemented-in-cpython\">underlying implementation of generator mechanism</a>, which involves some tricks of stack and heap manipulation.)</p>\n\n<p>When <code>yield</code> is used instead of a <code>return</code> in a python function, that function is turned into something special called <code>generator function</code>. That function will return an object of <code>generator</code> type. <strong>The <code>yield</code> keyword is a flag to notify the python compiler to treat such function specially.</strong> Normal functions will terminate once some value is returned from it. But with the help of the compiler, the generator function <strong>can be thought of</strong> as resumable. That is, the execution context will be restored and the execution will continue from last run. Until you explicitly call return, which will raise a <code>StopIteration</code> exception (which is also part of the iterator protocol), or reach the end of the function. I found a lot of references about <code>generator</code> but this <a href=\"https://docs.python.org/dev/howto/functional.html#generators\" rel=\"noreferrer\">one</a> from the <code>functional programming perspective</code> is the most digestable.</p>\n\n<p>(Now I want to talk about the rationale behind <code>generator</code>, and the <code>iterator</code> based on my own understanding. I hope this can help you grasp the <strong><em>essential motivation</em></strong> of iterator and generator. Such concept shows up in other languages as well such as C#.)</p>\n\n<p>As I understand, when we want to process a bunch of data, we usually first store the data somewhere and then process it one by one. But this <em>naive</em> approach is problematic. If the data volume is huge, it's expensive to store them as a whole beforehand. <strong>So instead of storing the <code>data</code> itself directly, why not store some kind of <code>metadata</code> indirectly, i.e. <code>the logic how the data is computed</code></strong>. </p>\n\n<p>There are 2 approaches to wrap such metadata.</p>\n\n<ol>\n<li>The OO approach, we wrap the metadata <code>as a class</code>. This is the so-called <code>iterator</code> who implements the iterator protocol (i.e. the <code>__next__()</code>, and <code>__iter__()</code> methods). This is also the commonly seen <a href=\"https://en.wikipedia.org/wiki/Iterator_pattern#Python\" rel=\"noreferrer\">iterator design pattern</a>.</li>\n<li>The functional approach, we wrap the metadata <code>as a function</code>. This is\nthe so-called <code>generator function</code>. But under the hood, the returned <code>generator object</code> still <code>IS-A</code> iterator because it also implements the iterator protocol.</li>\n</ol>\n\n<p>Either way, an iterator is created, i.e. some object that can give you the data you want. The OO approach may be a bit complex. Anyway, which one to use is up to you.</p>\n"
},
{
"answer_id": 36220775,
"author": "Bob Stein",
"author_id": 673991,
"author_profile": "https://Stackoverflow.com/users/673991",
"pm_score": 8,
"selected": false,
"text": "<p><strong>TL;DR</strong></p>\n\n<h1>Instead of this:</h1>\n\n<pre><code>def square_list(n):\n the_list = [] # Replace\n for x in range(n):\n y = x * x\n the_list.append(y) # these\n return the_list # lines\n</code></pre>\n\n<h1>do this:</h1>\n\n<pre><code>def square_yield(n):\n for x in range(n):\n y = x * x\n yield y # with this one.\n</code></pre>\n\n<p>Whenever you find yourself building a list from scratch, <code>yield</code> each piece instead. </p>\n\n<p>This was my first \"aha\" moment with yield.</p>\n\n<hr>\n\n<p><code>yield</code> is a <a href=\"https://en.wikipedia.org/wiki/Syntactic_sugar\" rel=\"noreferrer\">sugary</a> way to say </p>\n\n<blockquote>\n <p>build a series of stuff</p>\n</blockquote>\n\n<p>Same behavior:</p>\n\n<pre><code>>>> for square in square_list(4):\n... print(square)\n...\n0\n1\n4\n9\n>>> for square in square_yield(4):\n... print(square)\n...\n0\n1\n4\n9\n</code></pre>\n\n<p>Different behavior:</p>\n\n<p>Yield is <strong>single-pass</strong>: you can only iterate through once. When a function has a yield in it we call it a <a href=\"https://stackoverflow.com/a/1756342/673991\">generator function</a>. And an <a href=\"https://stackoverflow.com/a/9884501/673991\">iterator</a> is what it returns. Those terms are revealing. We lose the convenience of a container, but gain the power of a series that's computed as needed, and arbitrarily long.</p>\n\n<p>Yield is <strong>lazy</strong>, it puts off computation. A function with a yield in it <em>doesn't actually execute at all when you call it.</em> It returns an <a href=\"https://docs.python.org/3/reference/expressions.html#yieldexpr\" rel=\"noreferrer\">iterator object</a> that remembers where it left off. Each time you call <code>next()</code> on the iterator (this happens in a for-loop) execution inches forward to the next yield. <code>return</code> raises StopIteration and ends the series (this is the natural end of a for-loop).</p>\n\n<p>Yield is <strong>versatile</strong>. Data doesn't have to be stored all together, it can be made available one at a time. It can be infinite.</p>\n\n<pre><code>>>> def squares_all_of_them():\n... x = 0\n... while True:\n... yield x * x\n... x += 1\n...\n>>> squares = squares_all_of_them()\n>>> for _ in range(4):\n... print(next(squares))\n...\n0\n1\n4\n9\n</code></pre>\n\n<hr>\n\n<p>If you need <strong>multiple passes</strong> and the series isn't too long, just call <code>list()</code> on it:</p>\n\n<pre><code>>>> list(square_yield(4))\n[0, 1, 4, 9]\n</code></pre>\n\n<hr>\n\n<p>Brilliant choice of the word <code>yield</code> because <a href=\"https://www.google.com/search?q=yield+meaning\" rel=\"noreferrer\">both meanings</a> apply:</p>\n\n<blockquote>\n <p><strong>yield</strong> — produce or provide (as in agriculture)</p>\n</blockquote>\n\n<p>...provide the next data in the series.</p>\n\n<blockquote>\n <p><strong>yield</strong> — give way or relinquish (as in political power)</p>\n</blockquote>\n\n<p>...relinquish CPU execution until the iterator advances.</p>\n"
},
{
"answer_id": 37964180,
"author": "Christophe Roussy",
"author_id": 657427,
"author_profile": "https://Stackoverflow.com/users/657427",
"pm_score": 6,
"selected": false,
"text": "<p>Yet another TL;DR</p>\n\n<p><strong>Iterator on list</strong>: <code>next()</code> returns the next element of the list</p>\n\n<p><strong>Iterator generator</strong>: <code>next()</code> will compute the next element on the fly (execute code)</p>\n\n<p>You can see the yield/generator as a way to manually run the <strong>control flow</strong> from outside (like continue loop one step), by calling <code>next</code>, however complex the flow.</p>\n\n<p><strong>Note</strong>: The generator is <strong>NOT</strong> a normal function. It remembers the previous state like local variables (stack). See other answers or articles for detailed explanation. The generator can only be <strong>iterated on once</strong>. You could do without <code>yield</code>, but it would not be as nice, so it can be considered 'very nice' language sugar.</p>\n"
},
{
"answer_id": 39425637,
"author": "Tom Fuller",
"author_id": 5177604,
"author_profile": "https://Stackoverflow.com/users/5177604",
"pm_score": 6,
"selected": false,
"text": "<p>Many people use <code>return</code> rather than <code>yield</code>, but in some cases <code>yield</code> can be more efficient and easier to work with.</p>\n\n<p>Here is an example which <code>yield</code> is definitely best for:</p>\n\n<blockquote>\n <p><strong>return</strong> (in function)</p>\n</blockquote>\n\n<pre><code>import random\n\ndef return_dates():\n dates = [] # With 'return' you need to create a list then return it\n for i in range(5):\n date = random.choice([\"1st\", \"2nd\", \"3rd\", \"4th\", \"5th\", \"6th\", \"7th\", \"8th\", \"9th\", \"10th\"])\n dates.append(date)\n return dates\n</code></pre>\n\n<blockquote>\n <p><strong>yield</strong> (in function)</p>\n</blockquote>\n\n<pre><code>def yield_dates():\n for i in range(5):\n date = random.choice([\"1st\", \"2nd\", \"3rd\", \"4th\", \"5th\", \"6th\", \"7th\", \"8th\", \"9th\", \"10th\"])\n yield date # 'yield' makes a generator automatically which works\n # in a similar way. This is much more efficient.\n</code></pre>\n\n<blockquote>\n <p><strong>Calling functions</strong></p>\n</blockquote>\n\n<pre><code>dates_list = return_dates()\nprint(dates_list)\nfor i in dates_list:\n print(i)\n\ndates_generator = yield_dates()\nprint(dates_generator)\nfor i in dates_generator:\n print(i)\n</code></pre>\n\n<p>Both functions do the same thing, but <code>yield</code> uses three lines instead of five and has one less variable to worry about.</p>\n\n<blockquote>\n <blockquote>\n <p><strong>This is the result from the code:</strong></p>\n </blockquote>\n</blockquote>\n\n<p><a href=\"https://i.stack.imgur.com/iUFNJ.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/iUFNJ.png\" alt=\"Output\"></a></p>\n\n<p>As you can see both functions do the same thing. The only difference is <code>return_dates()</code> gives a list and <code>yield_dates()</code> gives a generator.</p>\n\n<p>A real life example would be something like reading a file line by line or if you just want to make a generator.</p>\n"
},
{
"answer_id": 40022748,
"author": "redbandit",
"author_id": 3104473,
"author_profile": "https://Stackoverflow.com/users/3104473",
"pm_score": 6,
"selected": false,
"text": "<p>In summary, the <code>yield</code> statement transforms your function into a factory that produces a special object called a <code>generator</code> which wraps around the body of your original function. When the <code>generator</code> is iterated, it executes your function until it reaches the next <code>yield</code> then suspends execution and evaluates to the value passed to <code>yield</code>. It repeats this process on each iteration until the path of execution exits the function. For instance,</p>\n\n<pre><code>def simple_generator():\n yield 'one'\n yield 'two'\n yield 'three'\n\nfor i in simple_generator():\n print i\n</code></pre>\n\n<p>simply outputs</p>\n\n<pre><code>one\ntwo\nthree\n</code></pre>\n\n<p>The power comes from using the generator with a loop that calculates a sequence, the generator executes the loop stopping each time to 'yield' the next result of the calculation, in this way it calculates a list on the fly, the benefit being the memory saved for especially large calculations</p>\n\n<p>Say you wanted to create a your own <code>range</code> function that produces an iterable range of numbers, you could do it like so,</p>\n\n<pre><code>def myRangeNaive(i):\n n = 0\n range = []\n while n < i:\n range.append(n)\n n = n + 1\n return range\n</code></pre>\n\n<p>and use it like this;</p>\n\n<pre><code>for i in myRangeNaive(10):\n print i\n</code></pre>\n\n<p>But this is inefficient because</p>\n\n<ul>\n<li>You create an array that you only use once (this wastes memory)</li>\n<li>This code actually loops over that array twice! :(</li>\n</ul>\n\n<p>Luckily Guido and his team were generous enough to develop generators so we could just do this;</p>\n\n<pre><code>def myRangeSmart(i):\n n = 0\n while n < i:\n yield n\n n = n + 1\n return\n\nfor i in myRangeSmart(10):\n print i\n</code></pre>\n\n<p>Now upon each iteration a function on the generator called <code>next()</code> executes the function until it either reaches a 'yield' statement in which it stops and 'yields' the value or reaches the end of the function. In this case on the first call, <code>next()</code> executes up to the yield statement and yield 'n', on the next call it will execute the increment statement, jump back to the 'while', evaluate it, and if true, it will stop and yield 'n' again, it will continue that way until the while condition returns false and the generator jumps to the end of the function.</p>\n"
},
{
"answer_id": 41426583,
"author": "Gavriel Cohen",
"author_id": 5770004,
"author_profile": "https://Stackoverflow.com/users/5770004",
"pm_score": 6,
"selected": false,
"text": "<p>An easy example to understand what it is: <code>yield</code></p>\n\n<pre><code>def f123():\n for _ in range(4):\n yield 1\n yield 2\n\n\nfor i in f123():\n print (i)\n</code></pre>\n\n<p>The output is: </p>\n\n<pre><code>1 2 1 2 1 2 1 2\n</code></pre>\n"
},
{
"answer_id": 43698502,
"author": "Ahmad Ismail",
"author_id": 1772898,
"author_profile": "https://Stackoverflow.com/users/1772898",
"pm_score": 5,
"selected": false,
"text": "<p><strong>yield</strong> is similar to return. The difference is: </p>\n\n<p><strong>yield</strong> makes a function iterable (in the following example <code>primes(n = 1)</code> function becomes iterable).<br>\nWhat it essentially means is the next time the function is called, it will continue from where it left (which is after the line of <code>yield expression</code>).</p>\n\n<pre><code>def isprime(n):\n if n == 1:\n return False\n for x in range(2, n):\n if n % x == 0:\n return False\n else:\n return True\n\ndef primes(n = 1):\n while(True):\n if isprime(n): yield n\n n += 1 \n\nfor n in primes():\n if n > 100: break\n print(n)\n</code></pre>\n\n<p>In the above example if <code>isprime(n)</code> is true it will return the prime number. In the next iteration it will continue from the next line </p>\n\n<pre><code>n += 1 \n</code></pre>\n"
},
{
"answer_id": 46543549,
"author": "Chen A.",
"author_id": 840582,
"author_profile": "https://Stackoverflow.com/users/840582",
"pm_score": 5,
"selected": false,
"text": "<p>All of the answers here are great; but only one of them (the most voted one) relates to <strong>how your code works</strong>. Others are relating to <em>generators</em> in general, and how they work.</p>\n\n<p>So I won't repeat what generators are or what yields do; I think these are covered by great existing answers. However, after spending few hours trying to understand a similar code to yours, I'll break it down how it works.</p>\n\n<p>Your code traverse a binary tree structure. Let's take this tree for example:</p>\n\n<pre><code> 5\n / \\\n 3 6\n / \\ \\\n1 4 8\n</code></pre>\n\n<p>And another simpler implementation of a binary-search tree traversal:</p>\n\n<pre><code>class Node(object):\n..\ndef __iter__(self):\n if self.has_left_child():\n for child in self.left:\n yield child\n\n yield self.val\n\n if self.has_right_child():\n for child in self.right:\n yield child\n</code></pre>\n\n<p>The execution code is on the <code>Tree</code> object, which implements <code>__iter__</code> as this:</p>\n\n<pre><code>def __iter__(self):\n\n class EmptyIter():\n def next(self):\n raise StopIteration\n\n if self.root:\n return self.root.__iter__()\n return EmptyIter()\n</code></pre>\n\n<p>The <code>while candidates</code> statement can be replaced with <code>for element in tree</code>; Python translate this to</p>\n\n<pre><code>it = iter(TreeObj) # returns iter(self.root) which calls self.root.__iter__()\nfor element in it: \n .. process element .. \n</code></pre>\n\n<p>Because <code>Node.__iter__</code> function is a generator, the code <strong>inside it</strong> is executed per iteration. So the execution would look like this:</p>\n\n<ol>\n<li>root element is first; check if it has left childs and <code>for</code> iterate them (let's call it it1 because its the first iterator object)</li>\n<li>it has a child so the <code>for</code> is executed. The <code>for child in self.left</code> creates a <strong>new iterator</strong> from <code>self.left</code>, which is a Node object itself (it2)</li>\n<li>Same logic as 2, and a new <code>iterator</code> is created (it3)</li>\n<li>Now we reached the left end of the tree. <code>it3</code> has no left childs so it continues and <code>yield self.value</code></li>\n<li>On the next call to <code>next(it3)</code> it raises <code>StopIteration</code> and exists since it has no right childs (it reaches to the end of the function without yield anything)</li>\n<li><code>it1</code> and <code>it2</code> are still active - they are not exhausted and calling <code>next(it2)</code> would yield values, not raise <code>StopIteration</code></li>\n<li>Now we are back to <code>it2</code> context, and call <code>next(it2)</code> which continues where it stopped: right after the <code>yield child</code> statement. Since it has no more left childs it continues and yields it's <code>self.val</code>.</li>\n</ol>\n\n<p>The catch here is that every iteration <strong>creates sub-iterators</strong> to traverse the tree, and holds the state of the current iterator. Once it reaches the end it traverse back the stack, and values are returned in the correct order (smallest yields value first).</p>\n\n<p>Your code example did something similar in a different technique: it populated a <strong>one-element list</strong> for every child, then on the next iteration it pops it and run the function code on the current object (hence the <code>self</code>).</p>\n\n<p>I hope this contributed a little to this legendary topic. I spent several good hours drawing this process to understand it.</p>\n"
},
{
"answer_id": 47285378,
"author": "AbstProcDo",
"author_id": 7301792,
"author_profile": "https://Stackoverflow.com/users/7301792",
"pm_score": 7,
"selected": false,
"text": "<p>All great answers, however a bit difficult for newbies.</p>\n\n<p>I assume you have learned the <code>return</code> statement.</p>\n\n<p>As an analogy, <code>return</code> and <code>yield</code> are twins. <code>return</code> means 'return and stop' whereas 'yield` means 'return, but continue'</p>\n\n<blockquote>\n <ol>\n <li>Try to get a num_list with <code>return</code>.</li>\n </ol>\n</blockquote>\n\n<pre><code>def num_list(n):\n for i in range(n):\n return i\n</code></pre>\n\n<p>Run it:</p>\n\n<pre><code>In [5]: num_list(3)\nOut[5]: 0\n</code></pre>\n\n<p>See, you get only a single number rather than a list of them. <code>return</code> never allows you prevail happily, just implements once and quit.</p>\n\n<blockquote>\n <ol start=\"2\">\n <li>There comes <code>yield</code></li>\n </ol>\n</blockquote>\n\n<p>Replace <code>return</code> with <code>yield</code>:</p>\n\n<pre><code>In [10]: def num_list(n):\n ...: for i in range(n):\n ...: yield i\n ...:\n\nIn [11]: num_list(3)\nOut[11]: <generator object num_list at 0x10327c990>\n\nIn [12]: list(num_list(3))\nOut[12]: [0, 1, 2]\n</code></pre>\n\n<p>Now, you win to get all the numbers.</p>\n\n<p>Comparing to <code>return</code> which runs once and stops, <code>yield</code> runs times you planed.\nYou can interpret <code>return</code> as <code>return one of them</code>, and <code>yield</code> as <code>return all of them</code>. This is called <code>iterable</code>.</p>\n\n<blockquote>\n <ol start=\"3\">\n <li>One more step we can rewrite <code>yield</code> statement with <code>return</code></li>\n </ol>\n</blockquote>\n\n<pre><code>In [15]: def num_list(n):\n ...: result = []\n ...: for i in range(n):\n ...: result.append(i)\n ...: return result\n\nIn [16]: num_list(3)\nOut[16]: [0, 1, 2]\n</code></pre>\n\n<p>It's the core about <code>yield</code>.</p>\n\n<p>The difference between a list <code>return</code> outputs and the object <code>yield</code> output is:</p>\n\n<p>You will always get [0, 1, 2] from a list object but only could retrieve them from 'the object <code>yield</code> output' once. So, it has a new name <code>generator</code> object as displayed in <code>Out[11]: <generator object num_list at 0x10327c990></code>.</p>\n\n<p>In conclusion, as a metaphor to grok it:</p>\n\n<ul>\n<li><code>return</code> and <code>yield</code> are twins</li>\n<li><code>list</code> and <code>generator</code> are twins</li>\n</ul>\n"
},
{
"answer_id": 52244968,
"author": "Andy Jazz",
"author_id": 6599590,
"author_profile": "https://Stackoverflow.com/users/6599590",
"pm_score": 5,
"selected": false,
"text": "<p>In Python <code>generators</code> (a special type of <code>iterators</code>) are used to generate series of values and <code>yield</code> keyword is just like the <code>return</code> keyword of generator functions. </p>\n\n<p><strong>The other fascinating thing <code>yield</code> keyword does is saving the <code>state</code> of a generator function</strong>. </p>\n\n<p>So, we can set a <code>number</code> to a different value each time the <code>generator</code> yields. </p>\n\n<p>Here's an instance:</p>\n\n<pre><code>def getPrimes(number):\n while True:\n if isPrime(number):\n number = yield number # a miracle occurs here\n number += 1\n\ndef printSuccessivePrimes(iterations, base=10):\n primeGenerator = getPrimes(base)\n primeGenerator.send(None)\n for power in range(iterations):\n print(primeGenerator.send(base ** power))\n</code></pre>\n"
},
{
"answer_id": 54826880,
"author": "thavan",
"author_id": 323000,
"author_profile": "https://Stackoverflow.com/users/323000",
"pm_score": 5,
"selected": false,
"text": "<p><code>yield</code> yields something. It's like somebody asks you to make 5 cupcakes. If you are done with at least one cupcake, you can give it to them to eat while you make other cakes.</p>\n\n<pre><code>In [4]: def make_cake(numbers):\n ...: for i in range(numbers):\n ...: yield 'Cake {}'.format(i)\n ...:\n\nIn [5]: factory = make_cake(5)\n</code></pre>\n\n<p>Here <code>factory</code> is called a generator, which makes you cakes. If you call <code>make_function</code>, you get a generator instead of running that function. It is because when <code>yield</code> keyword is present in a function, it becomes a generator.</p>\n\n<pre><code>In [7]: next(factory)\nOut[7]: 'Cake 0'\n\nIn [8]: next(factory)\nOut[8]: 'Cake 1'\n\nIn [9]: next(factory)\nOut[9]: 'Cake 2'\n\nIn [10]: next(factory)\nOut[10]: 'Cake 3'\n\nIn [11]: next(factory)\nOut[11]: 'Cake 4'\n</code></pre>\n\n<p>They consumed all the cakes, but they ask for one again.</p>\n\n<pre><code>In [12]: next(factory)\n---------------------------------------------------------------------------\nStopIteration Traceback (most recent call last)\n<ipython-input-12-0f5c45da9774> in <module>\n----> 1 next(factory)\n\nStopIteration:\n</code></pre>\n\n<p>and they are being told to stop asking more. So once you consumed a generator you are done with it. You need to call <code>make_cake</code> again if you want more cakes. It is like placing another order for cupcakes.</p>\n\n<pre><code>In [13]: factory = make_cake(3)\n\nIn [14]: for cake in factory:\n ...: print(cake)\n ...:\nCake 0\nCake 1\nCake 2\n</code></pre>\n\n<p>You can also use for loop with a generator like the one above.</p>\n\n<p>One more example: Lets say you want a random password whenever you ask for it.</p>\n\n<pre><code>In [22]: import random\n\nIn [23]: import string\n\nIn [24]: def random_password_generator():\n ...: while True:\n ...: yield ''.join([random.choice(string.ascii_letters) for _ in range(8)])\n ...:\n\nIn [25]: rpg = random_password_generator()\n\nIn [26]: for i in range(3):\n ...: print(next(rpg))\n ...:\nFXpUBhhH\nDdUDHoHn\ndvtebEqG\n\nIn [27]: next(rpg)\nOut[27]: 'mJbYRMNo'\n</code></pre>\n\n<p>Here <code>rpg</code> is a generator, which can generate an infinite number of random passwords. So we can also say that generators are useful when we don't know the length of the sequence, unlike list which has a finite number of elements.</p>\n"
},
{
"answer_id": 55314423,
"author": "Dr Rafael",
"author_id": 4946896,
"author_profile": "https://Stackoverflow.com/users/4946896",
"pm_score": 6,
"selected": false,
"text": "<img src=\"https://i.stack.imgur.com/AJZlN.png\" width=\"300\" />\n<p>Imagine that you have created a remarkable machine that is capable of generating thousands and thousands of lightbulbs per day. The machine generates these lightbulbs in boxes with a unique serial number. You don't have enough space to store all of these lightbulbs at the same time, so you would like to adjust it to generate lightbulbs on-demand.</p>\n<p>Python generators don't differ much from this concept. Imagine that you have a function called <code>barcode_generator</code> that generates unique serial numbers for the boxes. Obviously, you can have a huge number of such barcodes returned by the function, subject to the hardware (RAM) limitations. A wiser, and space efficient, option is to generate those serial numbers on-demand.</p>\n<p>Machine's code:</p>\n<pre><code>def barcode_generator():\n serial_number = 10000 # Initial barcode\n while True:\n yield serial_number\n serial_number += 1\n\n\nbarcode = barcode_generator()\nwhile True:\n number_of_lightbulbs_to_generate = int(input("How many lightbulbs to generate? "))\n barcodes = [next(barcode) for _ in range(number_of_lightbulbs_to_generate)]\n print(barcodes)\n\n # function_to_create_the_next_batch_of_lightbulbs(barcodes)\n\n produce_more = input("Produce more? [Y/n]: ")\n if produce_more == "n":\n break\n</code></pre>\n<p>Note the <code>next(barcode)</code> bit.</p>\n<p>As you can see, we have a self-contained “function” to generate the next unique serial number each time. This function returns a <em>generator</em>! As you can see, we are not calling the function each time we need a new serial number, but instead we are using <code>next()</code> given the generator to obtain the next serial number.</p>\n<h1>Lazy Iterators</h1>\n<p>To be more precise, this generator is a <em>lazy iterator</em>! An iterator is an object that helps us traverse a sequence of objects. It's called <em>lazy</em> because it does not load all the items of the sequence in memory until they are needed. The use of <code>next</code> in the previous example is the <em>explicit</em> way to obtain the next item from the iterator. The <em>implicit</em> way is using for loops:</p>\n<pre><code>for barcode in barcode_generator():\n print(barcode)\n</code></pre>\n<p>This will print barcodes infinitely, yet you will not run out of memory.</p>\n<p><strong>In other words, a generator <em>looks like</em> a function but <em>behaves like</em> an iterator.</strong></p>\n<h1>Real-world application?</h1>\n<p>Finally, real-world applications? They are usually useful when you work with big sequences. Imagine reading a <em>huge</em> file from disk with billions of records. Reading the entire file in memory, before you can work with its content, will probably be infeasible (i.e., you will run out of memory).</p>\n"
},
{
"answer_id": 59785342,
"author": "Swati Srivastava",
"author_id": 9851541,
"author_profile": "https://Stackoverflow.com/users/9851541",
"pm_score": 4,
"selected": false,
"text": "<p>yield in python is in a way similar to the return statement, except for some differences. If multiple values have to be returned from a function, return statement will return all the values as a list and it has to be stored in the memory in the caller block. But what if we don't want to use extra memory? Instead, we want to get the value from the function when we need it. This is where yield comes in. Consider the following function :-</p>\n\n<pre><code>def fun():\n yield 1\n yield 2\n yield 3\n</code></pre>\n\n<p>And the caller is :-</p>\n\n<pre><code>def caller():\n print ('First value printing')\n print (fun())\n print ('Second value printing')\n print (fun())\n print ('Third value printing')\n print (fun())\n</code></pre>\n\n<p>The above code segment (caller function) when called, outputs :-</p>\n\n<pre><code>First value printing\n1\nSecond value printing\n2\nThird value printing\n3\n</code></pre>\n\n<p>As can be seen from above, yield returns a value to its caller, but when the function is called again, it doesn't start from the first statement, but from the statement right after the yield. In the above example, \"First value printing\" was printed and the function was called. 1 was returned and printed. Then \"Second value printing\" was printed and again fun() was called. Instead of printing 1 (the first statement), it returned 2, i.e., the statement just after yield 1. The same process is repeated further.</p>\n"
},
{
"answer_id": 63533381,
"author": "Aaron_ab",
"author_id": 6221828,
"author_profile": "https://Stackoverflow.com/users/6221828",
"pm_score": 4,
"selected": false,
"text": "<h2>Can also send data back to the generator!</h2>\n<p>Indeed, as many answers here explain, using <code>yield</code> creates a <code>generator</code>.</p>\n<p>You can use the <code>yield</code> keyword to <strong>send data back to a "live" generator</strong>.</p>\n<h3>Example:</h3>\n<p>Let's say we have a method which translates from english to some other language. And in the beginning of it, it does something which is heavy and should be done once. We want this method run forever (don't really know why.. :)), and receive words words to be translated.</p>\n<pre><code>def translator():\n # load all the words in English language and the translation to 'other lang'\n my_words_dict = {'hello': 'hello in other language', 'dog': 'dog in other language'}\n\n while True:\n word = (yield)\n yield my_words_dict.get(word, 'Unknown word...')\n</code></pre>\n<p>Running:</p>\n<pre><code>my_words_translator = translator()\n\nnext(my_words_translator)\nprint(my_words_translator.send('dog'))\n\nnext(my_words_translator)\nprint(my_words_translator.send('cat'))\n</code></pre>\n<p>will print:</p>\n<pre><code>dog in other language\nUnknown word...\n</code></pre>\n<h3>To summarise:</h3>\n<p>use <code>send</code> method inside a generator to send data back to the generator. To allow that, a <code>(yield)</code> is used.</p>\n"
},
{
"answer_id": 67970221,
"author": "Siva Sankar",
"author_id": 11282077,
"author_profile": "https://Stackoverflow.com/users/11282077",
"pm_score": 2,
"selected": false,
"text": "<p>Function - returns.</p>\n<p>Generator - yields (contains one or more yields and zero or more returns).</p>\n<pre><code>names = ['Sam', 'Sarah', 'Thomas', 'James']\n\n\n# Using function\ndef greet(name) :\n return f'Hi, my name is {name}.'\n \nfor each_name in names:\n print(greet(each_name))\n\n# Output: \n>>>Hi, my name is Sam.\n>>>Hi, my name is Sarah.\n>>>Hi, my name is Thomas.\n>>>Hi, my name is James.\n\n\n# using generator\ndef greetings(names) :\n for each_name in names:\n yield f'Hi, my name is {each_name}.'\n \nfor greet_name in greetings(names):\n print (greet_name)\n\n# Output: \n>>>Hi, my name is Sam.\n>>>Hi, my name is Sarah.\n>>>Hi, my name is Thomas.\n>>>Hi, my name is James.\n</code></pre>\n<p>A generator looks like a function but behaves like an iterator.</p>\n<p>A generator continues execution from where it is lefoff (or yielded). When resumed, the function continues the execution immediately after the last yield run. This allows its code to produce a series of values over time rather them computing them all at once and sending them back like a list.</p>\n<pre><code>def function():\n yield 1 # return this first\n yield 2 # start continue from here (yield don't execute above code once executed)\n yield 3 # give this at last (yield don't execute above code once executed)\n\nfor processed_data in function(): \n print(processed_data)\n \n#Output:\n\n>>>1\n>>>2\n>>>3\n</code></pre>\n<p>Note:\nYield should not be in the try ... finally construct.</p>\n"
},
{
"answer_id": 67976136,
"author": "Mayank Maheshwari",
"author_id": 10251555,
"author_profile": "https://Stackoverflow.com/users/10251555",
"pm_score": 3,
"selected": false,
"text": "<p>Usually, it's used to create an iterator out of function.\nThink 'yield' as an append() to your function and your function as an array.\nAnd if certain criteria meet, you can add that value in your function to make it an iterator.</p>\n<pre><code>arr=[]\nif 2>0:\n arr.append(2)\n\ndef func():\n if 2>0:\n yield 2\n</code></pre>\n<p>the output will be the same for both.</p>\n<p>The main advantage of using yield is to creating iterators.\nIterators don’t compute the value of each item when instantiated. They only compute it when you ask for it. This is known as lazy evaluation.</p>\n"
},
{
"answer_id": 69427199,
"author": "ToTamire",
"author_id": 15964568,
"author_profile": "https://Stackoverflow.com/users/15964568",
"pm_score": 3,
"selected": false,
"text": "<h1>Simple answer</h1>\n<p>When function contains at least one <code>yield</code> statement, the function automaticly becomes generator function. When you call generator function, python executes code in the generator function until <code>yield</code> statement occur. <code>yield</code> statement freezes the function with all its internal states. When you call generator function again, python continues execution of code in the generator function from frozen position, until <code>yield</code> statement occur again and again. The generator function executes code until generator function runs out without <code>yield</code> statement.</p>\n<h1>Benchmark</h1>\n<p>Create a list and return it:</p>\n<pre class=\"lang-python prettyprint-override\"><code>def my_range(n):\n my_list = []\n i = 0\n while i < n:\n my_list.append(i)\n i += 1\n return my_list\n\n@profile\ndef function():\n my_sum = 0\n my_values = my_range(1000000)\n for my_value in my_values:\n my_sum += my_value\n\nfunction()\n</code></pre>\n<p>Results with:</p>\n<pre><code>Total time: 1.07901 s\nTimer unit: 1e-06 s\n\nLine # Hits Time Per Hit % Time Line Contents\n==============================================================\n 9 @profile\n 10 def function():\n 11 1 1.1 1.1 0.0 my_sum = 0\n 12 1 494875.0 494875.0 45.9 my_values = my_range(1000000)\n 13 1000001 262842.1 0.3 24.4 for my_value in my_values:\n 14 1000000 321289.8 0.3 29.8 my_sum += my_value\n\n\n\nLine # Mem usage Increment Occurences Line Contents\n============================================================\n 9 40.168 MiB 40.168 MiB 1 @profile\n 10 def function():\n 11 40.168 MiB 0.000 MiB 1 my_sum = 0\n 12 78.914 MiB 38.746 MiB 1 my_values = my_range(1000000)\n 13 78.941 MiB 0.012 MiB 1000001 for my_value in my_values:\n 14 78.941 MiB 0.016 MiB 1000000 my_sum += my_value\n</code></pre>\n<p>Generate values on the fly:</p>\n<pre class=\"lang-python prettyprint-override\"><code>def my_range(n):\n i = 0\n while i < n:\n yield i\n i += 1\n\n@profile\ndef function():\n my_sum = 0\n \n for my_value in my_range(1000000):\n my_sum += my_value\n\nfunction()\n</code></pre>\n<p>Results with:</p>\n<pre><code>Total time: 1.24841 s\nTimer unit: 1e-06 s\n\nLine # Hits Time Per Hit % Time Line Contents\n==============================================================\n 7 @profile\n 8 def function():\n 9 1 1.1 1.1 0.0 my_sum = 0\n 10\n 11 1000001 895617.3 0.9 71.7 for my_value in my_range(1000000):\n 12 1000000 352793.7 0.4 28.3 my_sum += my_value\n\n\n\nLine # Mem usage Increment Occurences Line Contents\n============================================================\n 7 40.168 MiB 40.168 MiB 1 @profile\n 8 def function():\n 9 40.168 MiB 0.000 MiB 1 my_sum = 0\n 10\n 11 40.203 MiB 0.016 MiB 1000001 for my_value in my_range(1000000):\n 12 40.203 MiB 0.020 MiB 1000000 my_sum += my_value\n</code></pre>\n<h1>Summary</h1>\n<p>The generator function needs a little more time to execute, than function which returns a list but it use much less memory.</p>\n"
},
{
"answer_id": 69893671,
"author": "Ted Shaneyfelt",
"author_id": 14751543,
"author_profile": "https://Stackoverflow.com/users/14751543",
"pm_score": 3,
"selected": false,
"text": "<p>A simple use case:</p>\n<pre><code>>>> def foo():\n yield 100\n yield 20\n yield 3\n\n \n>>> for i in foo(): print(i)\n\n100\n20\n3\n>>> \n</code></pre>\n<p>How it works: when called, the function returns an object immediately. The object can be passed to the next() function. Whenever the next() function is called, your function runs up until the next yield and provides the return value for the next() function.</p>\n<p>Under the hood, the for loop recognizes that the object is a generator object and uses next() to get the next value.</p>\n<p>In some languages like ES6 and higher, it's implemented a little differently so next is a member function of the generator object, and you could pass values from the caller every time it gets the next value. So if result is the generator then you could do something like y = result.next(555), and the program yielding values could say something like z = yield 999. The value of y would be 999 that next gets from the yield, and the value of z would be 555 that yield gets from the next. Python get and send methods have a similar effect.</p>\n"
},
{
"answer_id": 70233705,
"author": "michalmonday",
"author_id": 4620679,
"author_profile": "https://Stackoverflow.com/users/4620679",
"pm_score": 2,
"selected": false,
"text": "<p>Generators allow to get individual processed items immediately (without the need to wait for the whole collection to be processed). This is illustrated in the example below.</p>\n<pre class=\"lang-py prettyprint-override\"><code>import time\n\ndef get_gen():\n for i in range(10):\n yield i\n time.sleep(1)\n\ndef get_list():\n ret = []\n for i in range(10):\n ret.append(i)\n time.sleep(1)\n return ret\n\n\nstart_time = time.time()\nprint('get_gen iteration (individual results come immediately)')\nfor i in get_gen():\n print(f'result arrived after: {time.time() - start_time:.0f} seconds')\nprint()\n\nstart_time = time.time()\nprint('get_list iteration (results come all at once)') \nfor i in get_list():\n print(f'result arrived after: {time.time() - start_time:.0f} seconds')\n\n</code></pre>\n<pre><code>get_gen iteration (individual results come immediately)\nresult arrived after: 0 seconds\nresult arrived after: 1 seconds\nresult arrived after: 2 seconds\nresult arrived after: 3 seconds\nresult arrived after: 4 seconds\nresult arrived after: 5 seconds\nresult arrived after: 6 seconds\nresult arrived after: 7 seconds\nresult arrived after: 8 seconds\nresult arrived after: 9 seconds\n\nget_list iteration (results come all at once)\nresult arrived after: 10 seconds\nresult arrived after: 10 seconds\nresult arrived after: 10 seconds\nresult arrived after: 10 seconds\nresult arrived after: 10 seconds\nresult arrived after: 10 seconds\nresult arrived after: 10 seconds\nresult arrived after: 10 seconds\nresult arrived after: 10 seconds\nresult arrived after: 10 seconds\n</code></pre>\n"
},
{
"answer_id": 70516941,
"author": "Conjure.Li",
"author_id": 15642146,
"author_profile": "https://Stackoverflow.com/users/15642146",
"pm_score": 2,
"selected": false,
"text": "<p>To understand its yield function, one must understand what a generator is. Moreover, before understanding generators, you must understand <em>iterables</em>.\nIterable: iterable\nTo create a list, you naturally need to be able to read each element one by one. The process of reading its items one by one is called iteration:</p>\n<pre><code>>>> mylist = [1, 2, 3]\n>>> for i in mylist:\n... print(i)\n1\n2\n3 \n</code></pre>\n<p>mylist is an iterable. When you use list comprehensions, you create a list and therefore iterable:</p>\n<pre><code>>>> mylist = [x*x for x in range(3)]\n>>> for i in mylist:\n... print(i)\n0\n1\n4 \n</code></pre>\n<p>All data structures that can be used for... in... are iterable; lists, strings, files...</p>\n<p>These iterable methods are convenient because you can read them at will, but you store all the values in memory, which is not always desirable when you have many values.\nGenerator: generator\nA generator is also a kind of iterator, a special kind of iteration, which can only be iterated once. The generator does not store all values in memory, but generates values on the fly:</p>\n<p>generator: generator, generator, generator generates electricity but does not store energy;)</p>\n<pre><code>>>> mygenerator = (x*x for x in range(3))\n>>> for i in mygenerator:\n... print(i)\n0\n1\n4 \n</code></pre>\n<p>As long as () is used instead of [], the list comprehension becomes the generator comprehension. However, since the generator can only be used once, you cannot execute for i in mygenerator a second time: the generator calculates 0, then discards it, then calculates 1, and the last time it calculates 4. The typical black blind man breaks corn.</p>\n<p>The yield keyword is used in the same way as return, except that the function will return the generator.</p>\n<pre><code>>>> def createGenerator():\n... mylist = range(3)\n... for i in mylist:\n... yield i*i\n...\n>>> mygenerator = createGenerator() \n>>> print(mygenerator) \n<generator object createGenerator at 0xb7555c34>\n>>> for i in mygenerator:\n... print(i)\n0\n1\n4 \n</code></pre>\n<p>This example itself is useless, but when you need a function to return a large number of values and only need to read it once, using yield becomes convenient.</p>\n<p>To master the yield, one need to be clear is that when a function is called, the code written in the function body will not run. The function only returns the generator object. Beginners are likely to be confused about this.</p>\n<p>Second, understand that the code will continue from where it left off every time for uses the generator.</p>\n<p>The most difficult part now is:</p>\n<p>The first time for calls the generator object created from your function, it will run the code in the function from the beginning until it hits yield, and then it will return the first value of the loop. Then, each subsequent call will run the next iteration of the loop you wrote in the function and return the next value. This will continue until the generator is considered empty, which yields when there is no hit while the function is running. That may be because the loop has ended, or because you are no longer satisfied with "if/else".</p>\n<p>Personal understanding I hope to help you!</p>\n"
},
{
"answer_id": 70521893,
"author": "yash bhangare",
"author_id": 13388767,
"author_profile": "https://Stackoverflow.com/users/13388767",
"pm_score": 4,
"selected": false,
"text": "<p>The <code>yield</code> keyword in Python used to exit from the code without disturbing the state of local variables and when again the function is called the execution starts from the last point where we left the code.</p>\n<p>The below example demonstrates the working of <code>yield</code>:</p>\n<pre><code>def counter():\n x=2\n while x < 5:\n yield x\n x += 1\n \nprint("Initial value of x: ", counter()) \n\nfor y in counter():\n print(y)\n</code></pre>\n<p>The above code generates the Below output:</p>\n<pre><code>Initial value of x: <generator object counter at 0x7f0263020ac0>\n2\n3\n4\n</code></pre>\n"
},
{
"answer_id": 70617027,
"author": "Vinod Srivastav",
"author_id": 3057246,
"author_profile": "https://Stackoverflow.com/users/3057246",
"pm_score": 2,
"selected": false,
"text": "<p>The <code>yield</code> keyword is used in enumeration/iteration where the function is expected to return more then one output. I want to quote this very simple <strong>example A</strong>:</p>\n<pre class=\"lang-py prettyprint-override\"><code># example A\ndef getNumber():\n for r in range(1,10):\n return r\n</code></pre>\n<p>The above function will return only <strong>1</strong> even when it's called multiple times. Now if we replace <code>return</code> with <code>yield</code> as in <strong>example B</strong>:</p>\n<pre class=\"lang-py prettyprint-override\"><code># example B\ndef getNumber():\n for r in range(1,10):\n yield r\n</code></pre>\n<p>It will return <strong>1</strong> when first called <strong>2</strong> when called again then <strong>3</strong>,<strong>4</strong> and it goes to increment till 10.</p>\n<p>Although the <strong>example B</strong> is conceptually true but to call it in <strong>python 3</strong> we have to do the following:</p>\n<pre class=\"lang-py prettyprint-override\"><code>\ng = getNumber() #instance\nprint(next(g)) #will print 1\nprint(next(g)) #will print 2\nprint(next(g)) #will print 3\n\n# so to assign it to a variables\nv = getNumber()\nv1 = next(v) #v1 will have 1\nv2 = next(v) #v2 will have 2\nv3 = next(v) #v3 will have 3\n</code></pre>\n"
},
{
"answer_id": 72334132,
"author": "Raymond Hettinger",
"author_id": 424499,
"author_profile": "https://Stackoverflow.com/users/424499",
"pm_score": 2,
"selected": false,
"text": "<h2>Key points</h2>\n<ul>\n<li><p>The <a href=\"https://docs.python.org/3/reference/grammar.html\" rel=\"nofollow noreferrer\">grammar for Python</a> uses the presence of the <code>yield</code> keyword to make a function that returns a <a href=\"https://docs.python.org/3/glossary.html#term-generator\" rel=\"nofollow noreferrer\">generator</a>.</p>\n</li>\n<li><p>A generator is a kind of <a href=\"https://docs.python.org/3/glossary.html#term-iterator\" rel=\"nofollow noreferrer\">iterator</a>, which is that main way that looping occurs in Python.</p>\n</li>\n<li><p>A generator is essentially a resumable function. Unlike <code>return</code> that returns a value and ends a function, the <code>yield</code> keyword returns a value and suspends a function.</p>\n</li>\n<li><p>When <code>next(g)</code> is called on a generator, the function resumes execution where it left off.</p>\n</li>\n<li><p>Only when the function encounters an explicit or implied <code>return</code> does it actually end.</p>\n</li>\n</ul>\n<h2>Technique for writing and understanding generators</h2>\n<p>An easy way to understand and think about generators is to write a regular function with <code>print()</code> instead of <code>yield</code>:</p>\n<pre><code>def f(n):\n for x in range(n):\n print(x)\n print(x * 10)\n</code></pre>\n<p>Watch what it outputs:</p>\n<pre><code>>>> f(3)\n0\n0\n1\n10\n2\n2\n</code></pre>\n<p>When that function is understood, substitute the <code>yield</code> for <code>print</code> to get a generator that produces the same values:</p>\n<pre><code>def f(n):\n for x in range(n):\n yield x\n yield x * 10\n</code></pre>\n<p>Which gives:</p>\n<pre><code>>>> list(f(3))\n[0, 0, 1, 10, 2, 20]\n</code></pre>\n<h2>Iterator protocol</h2>\n<p>The answer to "what yield does" can be short and simple, but it is part of a larger world, the so-called "iterator protocol".</p>\n<p>On the sender side of iterator protocol, there are two relevant kinds of objects. The <em>iterables</em> are things you can loop over. And the <em>iterators</em> are objects that track the loop state.</p>\n<p>On the consumer side of the iterator protocol, we call <a href=\"https://docs.python.org/3/library/functions.html#iter\" rel=\"nofollow noreferrer\">iter()</a> on the iterable object to get a iterator. Then we call <a href=\"https://docs.python.org/3/library/functions.html#next\" rel=\"nofollow noreferrer\">next()</a> on the iterator to retrieve values from the iterator. When there is no more data, a <a href=\"https://docs.python.org/3/library/exceptions.html#StopIteration\" rel=\"nofollow noreferrer\">StopIteration</a> exception is raised:</p>\n<pre><code>>>> s = [10, 20, 30] # The list is the "iterable"\n>>> it = iter(s) # This is the "iterator"\n>>> next(it) # Gets values out of an iterator\n10\n>>> next(it)\n20\n>>> next(it)\n30\n>>> next(it)\nTraceback (most recent call last):\n ...\nStopIteration\n</code></pre>\n<p>To make this all easier for us, for-loops call iter and next on our behalf:</p>\n<pre><code>>>> for x in s:\n... print(x)\n... \n10\n20\n30\n</code></pre>\n<p>A person could write a book about all this, but these are the key points. When I teach Python courses, I've found that this is a minimal sufficient explanation to build understand and start using it right away. In particular, the trick of writing a function with <code>print</code>, testing it, and then converting to <code>yield</code> seems to work well with all levels of Python programmers.</p>\n"
},
{
"answer_id": 73457837,
"author": "Shisui Otsutsuki",
"author_id": 16360640,
"author_profile": "https://Stackoverflow.com/users/16360640",
"pm_score": 1,
"selected": false,
"text": "<p><code>yield</code> is used to create a <code>generator</code>. Think of generator as an iterator whihc gives you value on each iteration. When you use yield in the loop you get a generator object which you could use to get items from the loop in an iterative manner</p>\n"
},
{
"answer_id": 73924762,
"author": "My Car",
"author_id": 16124033,
"author_profile": "https://Stackoverflow.com/users/16124033",
"pm_score": 2,
"selected": false,
"text": "<p><strong>What Is Yield In Python?</strong></p>\n<p>The Yield keyword in Python is similar to a return statement used for returning values or objects in Python. However, there is a slight difference. The yield statement returns a generator object to the one who calls the function which contains yield, instead of simply returning a value.</p>\n<p>Inside a program, when you call a function that has a yield statement, as soon as a yield is encountered, the execution of the function stops and returns an object of the generator to the function caller. In simpler words, the yield keyword will convert an expression that is specified along with it to a generator object and return it to the caller. Hence, if you want to get the values stored inside the generator object, you need to iterate over it.</p>\n<p>It will not destroy the local variables’ states. Whenever a function is called, the execution will start from the last yield expression. Please note that a function that contains a yield keyword is known as a generator function.</p>\n<p>When you use a function with a return value, every time you call the function, it starts with a new set of variables. In contrast, if you use a generator function instead of a normal function, the execution will start right from where it left last.</p>\n<p>If you want to return multiple values from a function, you can use generator functions with yield keywords. The yield expressions return multiple values. They return one value, then wait, save the local state, and resume again.</p>\n<p>Source: <a href=\"https://www.simplilearn.com/tutorials/python-tutorial/yield-in-python\" rel=\"nofollow noreferrer\">https://www.simplilearn.com/tutorials/python-tutorial/yield-in-python</a></p>\n"
},
{
"answer_id": 74055463,
"author": "Roland",
"author_id": 1845672,
"author_profile": "https://Stackoverflow.com/users/1845672",
"pm_score": 2,
"selected": false,
"text": "<p><code>yield</code> allows you to write smarter <code>for</code>-loops by factoring out the looping part to a separate method for easy reuse.</p>\n<p>Suppose you need to loop over all non-blank rows of a spreadsheet and do something with each row.</p>\n<pre><code>for i, row in df.iterrows(): #from the panda package for reading excel \n if row = blank: # pseudo code, check if row is non-blank...\n continue\n if past_last_row: # pseudo code, check for end of input data\n break\n #### above is boring stuff, below is what we actually want to do with the data ###\n f(row)\n</code></pre>\n<p>If you need to call <code>g(row)</code> in a similar loop, you might find yourself repeating the <code>for</code> statement plus the checks for valid rows, which is boring, complex and error-prone. We don't want to repeat ourselves (DRY principle).</p>\n<p>You want to separate the code for checking each record from the code that actually process the rows, like <code>f(row)</code> and <code>g(row)</code> .</p>\n<p>You could make a function that takes f() as input parameter, but it is much simpler to use <code>yield</code> in a method that does all the boring stuff about checking for valid rows in preparation for calling f():</p>\n<pre><code>def valid_rows():\n for i, row in df.iterrows(): # iterate over each row of spreadsheet\n if row == blank: # pseudo code, check if row is non-blank...\n continue\n if past_last_row: # pseudo code, check for end of input data\n break\n yield i, row\n</code></pre>\n<p>Note that each call of the method will return one next row, except that if all rows are read and the <code>for</code> finishes, the method will <code>return</code> normally. The next call will start a new <code>for</code> loop.</p>\n<p>Now you can write iterations over the data without having to repeat that boring checking for valid rows (which is now factored out to its own method) like:</p>\n<pre><code>for i, row in valid_rows():\n f(row)\n\nfor i, row in valid_rows():\n g(row)\n\nnr_valid_rows = len(list(valid_rows()))\n</code></pre>\n<p>That is all there is. Note that I have not used jargon like iterator, generator, protocol, co-routine. I think that this simple example applies to a lot of our day to day coding.</p>\n"
},
{
"answer_id": 74338534,
"author": "Kai - Kazuya Ito",
"author_id": 8172439,
"author_profile": "https://Stackoverflow.com/users/8172439",
"pm_score": 2,
"selected": false,
"text": "<p><strong><code>yield</code></strong>:</p>\n<ul>\n<li>can return a value multiple times from a function by stopping the function.</li>\n<li>can use <code>from</code> with it like <code>yield from</code>.</li>\n<li>is used when returning big data by dividing it into small pieces of data to prevent the big usage of RAM.</li>\n</ul>\n<p>For example, <code>test()</code> below can return <code>'One'</code>, <code>'Two'</code> and <code>['Three', 'Four']</code> one by one by stopping <code>test()</code> so <code>test()</code> returns 3 times in total by stopping <code>test()</code> 3 times in total:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def test():\n yield 'One' # Stop, return 'One' and resume \n yield 'Two' # Stop, return 'Two' and resume\n yield from ['Three', 'Four'] # Stop and return ['Three', 'Four'] \n</code></pre>\n<p>And, these 3 sets of code below can call <code>test()</code> and print <code>'One'</code>, <code>'Two'</code>, <code>'Three'</code> and <code>'Four'</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>for x in test():\n print(x)\n</code></pre>\n<pre class=\"lang-py prettyprint-override\"><code>x = test()\nprint(next(x))\nprint(next(x))\nprint(next(x))\nprint(next(x))\n</code></pre>\n<pre class=\"lang-py prettyprint-override\"><code>x = test()\nprint(x.__next__())\nprint(x.__next__())\nprint(x.__next__())\nprint(x.__next__())\n</code></pre>\n<p>This is the result:</p>\n<pre class=\"lang-none prettyprint-override\"><code>$ python yield_test.py\nOne\nTwo\nThree\nFour\n</code></pre>\n<p>In addition, when using <code>return</code> with <code>yield</code>, there is no way to get the value from <code>return</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def test():\n yield 'One' \n yield 'Two'\n yield from ['Three', 'Four']\n return 'Five' # 'Five' cannot be got\n\nx = test()\nprint(next(x))\nprint(next(x))\nprint(next(x))\nprint(next(x))\nprint(next(x)) # Here\n</code></pre>\n<p>So, there is the error below when trying to get <code>'Five'</code>:</p>\n<pre class=\"lang-none prettyprint-override\"><code>$ python yield_test.py \nOne\nTwo\nThree\nFour\nTraceback (most recent call last):\n File "C:\\Users\\kai\\yield_test.py", line 12, in <module>\n print(next(x))\n ^^^^^^^\nStopIteration: Five\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18300/"
] |
What is the use of the `yield` keyword in Python? What does it do?
For example, I'm trying to understand this code**1**:
```
def _get_child_candidates(self, distance, min_dist, max_dist):
if self._leftchild and distance - max_dist < self._median:
yield self._leftchild
if self._rightchild and distance + max_dist >= self._median:
yield self._rightchild
```
And this is the caller:
```
result, candidates = [], [self]
while candidates:
node = candidates.pop()
distance = node._get_dist(obj)
if distance <= max_dist and distance >= min_dist:
result.extend(node._values)
candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))
return result
```
What happens when the method `_get_child_candidates` is called?
Is a list returned? A single element? Is it called again? When will subsequent calls stop?
---
1. This piece of code was written by Jochen Schulz (jrschulz), who made a great Python library for metric spaces. This is the link to the complete source: [Module mspace](https://well-adjusted.de/~jrspieker/mspace/).
|
To understand what `yield` does, you must understand what *generators* are. And before you can understand generators, you must understand *iterables*.
Iterables
---------
When you create a list, you can read its items one by one. Reading its items one by one is called iteration:
```
>>> mylist = [1, 2, 3]
>>> for i in mylist:
... print(i)
1
2
3
```
`mylist` is an *iterable*. When you use a list comprehension, you create a list, and so an iterable:
```
>>> mylist = [x*x for x in range(3)]
>>> for i in mylist:
... print(i)
0
1
4
```
Everything you can use "`for... in...`" on is an iterable; `lists`, `strings`, files...
These iterables are handy because you can read them as much as you wish, but you store all the values in memory and this is not always what you want when you have a lot of values.
Generators
----------
Generators are iterators, a kind of iterable **you can only iterate over once**. Generators do not store all the values in memory, **they generate the values on the fly**:
```
>>> mygenerator = (x*x for x in range(3))
>>> for i in mygenerator:
... print(i)
0
1
4
```
It is just the same except you used `()` instead of `[]`. BUT, you **cannot** perform `for i in mygenerator` a second time since generators can only be used once: they calculate 0, then forget about it and calculate 1, and end calculating 4, one by one.
Yield
-----
`yield` is a keyword that is used like `return`, except the function will return a generator.
```
>>> def create_generator():
... mylist = range(3)
... for i in mylist:
... yield i*i
...
>>> mygenerator = create_generator() # create a generator
>>> print(mygenerator) # mygenerator is an object!
<generator object create_generator at 0xb7555c34>
>>> for i in mygenerator:
... print(i)
0
1
4
```
Here it's a useless example, but it's handy when you know your function will return a huge set of values that you will only need to read once.
To master `yield`, you must understand that **when you call the function, the code you have written in the function body does not run.** The function only returns the generator object, this is a bit tricky.
Then, your code will continue from where it left off each time `for` uses the generator.
Now the hard part:
The first time the `for` calls the generator object created from your function, it will run the code in your function from the beginning until it hits `yield`, then it'll return the first value of the loop. Then, each subsequent call will run another iteration of the loop you have written in the function and return the next value. This will continue until the generator is considered empty, which happens when the function runs without hitting `yield`. That can be because the loop has come to an end, or because you no longer satisfy an `"if/else"`.
---
Your code explained
-------------------
*Generator:*
```
# Here you create the method of the node object that will return the generator
def _get_child_candidates(self, distance, min_dist, max_dist):
# Here is the code that will be called each time you use the generator object:
# If there is still a child of the node object on its left
# AND if the distance is ok, return the next child
if self._leftchild and distance - max_dist < self._median:
yield self._leftchild
# If there is still a child of the node object on its right
# AND if the distance is ok, return the next child
if self._rightchild and distance + max_dist >= self._median:
yield self._rightchild
# If the function arrives here, the generator will be considered empty
# there are no more than two values: the left and the right children
```
*Caller:*
```
# Create an empty list and a list with the current object reference
result, candidates = list(), [self]
# Loop on candidates (they contain only one element at the beginning)
while candidates:
# Get the last candidate and remove it from the list
node = candidates.pop()
# Get the distance between obj and the candidate
distance = node._get_dist(obj)
# If the distance is ok, then you can fill in the result
if distance <= max_dist and distance >= min_dist:
result.extend(node._values)
# Add the children of the candidate to the candidate's list
# so the loop will keep running until it has looked
# at all the children of the children of the children, etc. of the candidate
candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))
return result
```
This code contains several smart parts:
* The loop iterates on a list, but the list expands while the loop is being iterated. It's a concise way to go through all these nested data even if it's a bit dangerous since you can end up with an infinite loop. In this case, `candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))` exhausts all the values of the generator, but `while` keeps creating new generator objects which will produce different values from the previous ones since it's not applied on the same node.
* The `extend()` method is a list object method that expects an iterable and adds its values to the list.
Usually, we pass a list to it:
```
>>> a = [1, 2]
>>> b = [3, 4]
>>> a.extend(b)
>>> print(a)
[1, 2, 3, 4]
```
But in your code, it gets a generator, which is good because:
1. You don't need to read the values twice.
2. You may have a lot of children and you don't want them all stored in memory.
And it works because Python does not care if the argument of a method is a list or not. Python expects iterables so it will work with strings, lists, tuples, and generators! This is called duck typing and is one of the reasons why Python is so cool. But this is another story, for another question...
You can stop here, or read a little bit to see an advanced use of a generator:
Controlling a generator exhaustion
----------------------------------
```
>>> class Bank(): # Let's create a bank, building ATMs
... crisis = False
... def create_atm(self):
... while not self.crisis:
... yield "$100"
>>> hsbc = Bank() # When everything's ok the ATM gives you as much as you want
>>> corner_street_atm = hsbc.create_atm()
>>> print(corner_street_atm.next())
$100
>>> print(corner_street_atm.next())
$100
>>> print([corner_street_atm.next() for cash in range(5)])
['$100', '$100', '$100', '$100', '$100']
>>> hsbc.crisis = True # Crisis is coming, no more money!
>>> print(corner_street_atm.next())
<type 'exceptions.StopIteration'>
>>> wall_street_atm = hsbc.create_atm() # It's even true for new ATMs
>>> print(wall_street_atm.next())
<type 'exceptions.StopIteration'>
>>> hsbc.crisis = False # The trouble is, even post-crisis the ATM remains empty
>>> print(corner_street_atm.next())
<type 'exceptions.StopIteration'>
>>> brand_new_atm = hsbc.create_atm() # Build a new one to get back in business
>>> for cash in brand_new_atm:
... print cash
$100
$100
$100
$100
$100
$100
$100
$100
$100
...
```
**Note:** For Python 3, use`print(corner_street_atm.__next__())` or `print(next(corner_street_atm))`
It can be useful for various things like controlling access to a resource.
Itertools, your best friend
---------------------------
The itertools module contains special functions to manipulate iterables. Ever wish to duplicate a generator?
Chain two generators? Group values in a nested list with a one-liner? `Map / Zip` without creating another list?
Then just `import itertools`.
An example? Let's see the possible orders of arrival for a four-horse race:
```
>>> horses = [1, 2, 3, 4]
>>> races = itertools.permutations(horses)
>>> print(races)
<itertools.permutations object at 0xb754f1dc>
>>> print(list(itertools.permutations(horses)))
[(1, 2, 3, 4),
(1, 2, 4, 3),
(1, 3, 2, 4),
(1, 3, 4, 2),
(1, 4, 2, 3),
(1, 4, 3, 2),
(2, 1, 3, 4),
(2, 1, 4, 3),
(2, 3, 1, 4),
(2, 3, 4, 1),
(2, 4, 1, 3),
(2, 4, 3, 1),
(3, 1, 2, 4),
(3, 1, 4, 2),
(3, 2, 1, 4),
(3, 2, 4, 1),
(3, 4, 1, 2),
(3, 4, 2, 1),
(4, 1, 2, 3),
(4, 1, 3, 2),
(4, 2, 1, 3),
(4, 2, 3, 1),
(4, 3, 1, 2),
(4, 3, 2, 1)]
```
Understanding the inner mechanisms of iteration
-----------------------------------------------
Iteration is a process implying iterables (implementing the `__iter__()` method) and iterators (implementing the `__next__()` method).
Iterables are any objects you can get an iterator from. Iterators are objects that let you iterate on iterables.
There is more about it in this article about [how `for` loops work](https://web.archive.org/web/20201109034340/http://effbot.org/zone/python-for-statement.htm).
|
231,827 |
<p>I'm designing a multi-tiered database driven web application – SQL relational database, Java for the middle service tier, web for the UI. The language doesn't really matter.</p>
<p>The middle service tier performs the actual querying of the database. The UI simply asks for certain data and has no concept that it's backed by a database.</p>
<p>The question is how to handle large data sets? The UI asks for data but the results might be huge, possibly too big to fit in memory. For example, a street sign application might have a service layer of:</p>
<pre><code>StreetSign getStreetSign(int identifier)
Collection<StreetSign> getStreetSigns(Street street)
Collection<StreetSign> getStreetSigns(LatLonBox box)
</code></pre>
<p>The UI layer asks to get all street signs meeting some criteria. Depending on the criteria, the result set might be huge. The UI layer might divide the results into separate pages (for a browser) or just present them all (serving up to Goolge Earth). The potentially huge result set could be a performance and resource problem (out of memory).</p>
<p>One solution is not to return fully loaded objects (StreetSign objects). Rather return some sort of result set or iterator that lazily loads each individual object.</p>
<p>Another solution is to change the service API to return a subset of the requested data:</p>
<pre><code>Collection<StreetSign> getStreetSigns(LatLonBox box, int pageNumber, int resultsPerPage)
</code></pre>
<p>Of course the UI can still request a huge result set:</p>
<pre><code>getStreetSigns(box, 1, 1000000000)
</code></pre>
<p>I'm curious what is the standard industry design pattern for this scenario?</p>
|
[
{
"answer_id": 231835,
"author": "Ty.",
"author_id": 16948,
"author_profile": "https://Stackoverflow.com/users/16948",
"pm_score": 0,
"selected": false,
"text": "<p>In ASP.NET I would use server-side paging, where you only retrieve the page of data the user has requested from the data store. This is opposed to retrieving the entire result set, putting it into memory and paging through it on request.</p>\n"
},
{
"answer_id": 231837,
"author": "dacracot",
"author_id": 13930,
"author_profile": "https://Stackoverflow.com/users/13930",
"pm_score": 0,
"selected": false,
"text": "<p>JSF or JavaServerFaces has widgets for chunking large result sets to the browser. It can be parameterized as you suggest. I wouldn't call it a \"standard industry design pattern\" by any means, but it is worth a look to see how someone else solved the problem.</p>\n"
},
{
"answer_id": 231841,
"author": "Brian Schmitt",
"author_id": 30492,
"author_profile": "https://Stackoverflow.com/users/30492",
"pm_score": 1,
"selected": false,
"text": "<p>I would say if the potential exsists for a large set of data, then go the paging route. </p>\n\n<p>You can still set a MAX that you do not want them to go over.</p>\n\n<p>E.G. SO uses page sizes of 15, 30, 50...</p>\n"
},
{
"answer_id": 231860,
"author": "Gunny",
"author_id": 12830,
"author_profile": "https://Stackoverflow.com/users/12830",
"pm_score": 0,
"selected": false,
"text": "<p>When I deal with this type of issue, I usually chunk the data sent to the browser (or thin/thick client, whichever is more appropriate for your situation) as regardless of the actual total size of the data that meets some certain criteria, only a small portion is really usable in any UI at one time.</p>\n\n<p>I live in a Microsoft world, so my primary environment is ASP.Net with SQL Server. Here are two articles about paging (which mention some techniques for paging through result sets) that may be helpful:</p>\n\n<p><a href=\"http://weblogs.asp.net/scottgu/archive/2006/01/01/434314.aspx\" rel=\"nofollow noreferrer\">Paging through lots of data efficiently (and in an Ajax way) with ASP.NET 2.0</a>\n<a href=\"http://weblogs.asp.net/scottgu/archive/2006/01/07/434787.aspx\" rel=\"nofollow noreferrer\">Efficient Data Paging with the ASP.NET 2.0 DataList Control and ObjectDataSource</a></p>\n\n<p>Another mechanism that Microsoft has shipped lately is their idea of \"<a href=\"http://msdn.microsoft.com/en-us/library/cc668159.aspx\" rel=\"nofollow noreferrer\">Dynamic Data</a>\" - you might be able to check out the guts of this for some guidance as to how they're dealing with this issue.</p>\n"
},
{
"answer_id": 231864,
"author": "Niniki",
"author_id": 4155,
"author_profile": "https://Stackoverflow.com/users/4155",
"pm_score": 0,
"selected": false,
"text": "<p>I've done similar things on two different products. In one case the data source is optionally paginated -- for java, implements a Pageable interface similar to:</p>\n\n<pre><code>public interface Pageable\n{\n public void setStartIndex( int index );\n public int getStartIndex();\n public int getRowsPerPage() throws Exception;\n public void setRowsPerPage( int rowsPerPage );\n}\n</code></pre>\n\n<p>The data source implements another method for get() of items, and the implementation of a paginated data source just returns the current page. So you can set your start index, and grab a page in your controller.</p>\n\n<p>One thing to consider will be to cache your cursors server side. For a web app you'll have to expire them, but they'll really help performance wise.</p>\n"
},
{
"answer_id": 231939,
"author": "Matthew Smith",
"author_id": 20889,
"author_profile": "https://Stackoverflow.com/users/20889",
"pm_score": 0,
"selected": false,
"text": "<p>The <a href=\"http://fedora.info/\" rel=\"nofollow noreferrer\">fedora digital repository</a> project returns a maximum number of results with a result-set-id. You then get the rest of the result by asking for the next chunk supplying the result-set-id in the subsequent query. It works ok as long as you don't want to do any searching or sorting outside of the query.</p>\n"
},
{
"answer_id": 231961,
"author": "HTTP 410",
"author_id": 13118,
"author_profile": "https://Stackoverflow.com/users/13118",
"pm_score": 2,
"selected": false,
"text": "<p>The most frequent pattern I've seen for this situation is some sort of paging, usually done server-side to reduce the amount of information sent over the wire. </p>\n\n<p>Here's a SQL Server 2000 example using a table variable (generally faster than a temp table) together with your street signs example:</p>\n\n<pre><code>CREATE PROCEDURE GetPagedStreetSigns\n(\n @Page int = 1,\n @PageSize int = 10\n)\nAS\n SET NOCOUNT ON\n\n -- This memory-variable table will control paging\n DECLARE @TempTable TABLE (RowNumber int identity, StreetSignId int)\n\n INSERT INTO @TempTable\n (\n StreetSignId\n )\n SELECT [Id]\n FROM StreetSign\n ORDER BY [Id]\n\n -- select only those rows belonging to the requested page\n SELECT SS.*\n FROM StreetSign SS\n INNER JOIN @TempTable TT ON TT.StreetSignId = SS.[Id]\n WHERE TT.RowNumber BETWEEN ((@Page - 1) * @PageSize + 1) \n AND (@Page * @PageSize)\n</code></pre>\n\n<p>In SQL Server 2005, you can get more clever with stuff like Common Table Expressions and the new SQL Ranking functions. But the general theme is that you use the server to return only the information belonging to the current page.</p>\n\n<p>Be aware that this approach can get messy if you're allowing the end-user to apply on-the-fly filters to the data that s/he's seeing.</p>\n"
},
{
"answer_id": 231982,
"author": "RogueOne",
"author_id": 31019,
"author_profile": "https://Stackoverflow.com/users/31019",
"pm_score": 3,
"selected": false,
"text": "<p>The very first question should be:</p>\n\n<p>¿The user needs to, or is capable of, manage this amount of data?</p>\n\n<p>Although the result set should be paged, if its potentially size is so huge, the answer will be \"probably not\", so the UI shouldn't try to show it.</p>\n\n<p>I worked on J2EE projects on Health Care Systems, that deal with enormous amount of stored data, literally millions of patients, visits, forms, etc, and the general rule is not to show more than 100 or 200 rows for any user search, advising the user that those set of criteria produces more information that he can understand.</p>\n\n<p>The way to implement this varies from one project to another, it is possible to force the UI to ask the service tier the size of a query before launching it, or it is possible to throw an Exception from the service tier if the result set grows too much (however this way couples the service tier with the limited implementation of an UI).</p>\n\n<p>Be careful! This not means that every method on the service tier must throw an Exception if its result sizes more than 100, this general rule only applies to result sets that are shown to the user directly, that is a better reason to place the control in the UI instead on the service tier.</p>\n"
},
{
"answer_id": 232025,
"author": "MusiGenesis",
"author_id": 14606,
"author_profile": "https://Stackoverflow.com/users/14606",
"pm_score": 1,
"selected": false,
"text": "<p>One thing to be wary of when working with home-grown row-wrapper classes like you (apparently) have, is code that makes additional calls to the database without you (the developer) being aware of it. For example, you might call a method that returns a collection of Person objects and think that the only thing going on under the hood is a single \"SELECT * FROM PERSONS\" call. In actuality, the method you're calling might iterate through the returned collection of Person objects and make additional DB calls to populate each Person's Orders collection.</p>\n\n<p>As you say, one of your solutions is to not return fully-loaded objects, so you're probably aware of this potential problem. One of the reasons I tend to avoid using row wrappers is that they invariably make it difficult to tune your application and minimize the size and frequency of database traffic.</p>\n"
},
{
"answer_id": 235004,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>From the datay retrieval layer, the standard design pattern is to have two method interfaces, one for all and one for a block size.</p>\n\n<p>If you wish, you can layer components that do paging over it.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24396/"
] |
I'm designing a multi-tiered database driven web application – SQL relational database, Java for the middle service tier, web for the UI. The language doesn't really matter.
The middle service tier performs the actual querying of the database. The UI simply asks for certain data and has no concept that it's backed by a database.
The question is how to handle large data sets? The UI asks for data but the results might be huge, possibly too big to fit in memory. For example, a street sign application might have a service layer of:
```
StreetSign getStreetSign(int identifier)
Collection<StreetSign> getStreetSigns(Street street)
Collection<StreetSign> getStreetSigns(LatLonBox box)
```
The UI layer asks to get all street signs meeting some criteria. Depending on the criteria, the result set might be huge. The UI layer might divide the results into separate pages (for a browser) or just present them all (serving up to Goolge Earth). The potentially huge result set could be a performance and resource problem (out of memory).
One solution is not to return fully loaded objects (StreetSign objects). Rather return some sort of result set or iterator that lazily loads each individual object.
Another solution is to change the service API to return a subset of the requested data:
```
Collection<StreetSign> getStreetSigns(LatLonBox box, int pageNumber, int resultsPerPage)
```
Of course the UI can still request a huge result set:
```
getStreetSigns(box, 1, 1000000000)
```
I'm curious what is the standard industry design pattern for this scenario?
|
The very first question should be:
¿The user needs to, or is capable of, manage this amount of data?
Although the result set should be paged, if its potentially size is so huge, the answer will be "probably not", so the UI shouldn't try to show it.
I worked on J2EE projects on Health Care Systems, that deal with enormous amount of stored data, literally millions of patients, visits, forms, etc, and the general rule is not to show more than 100 or 200 rows for any user search, advising the user that those set of criteria produces more information that he can understand.
The way to implement this varies from one project to another, it is possible to force the UI to ask the service tier the size of a query before launching it, or it is possible to throw an Exception from the service tier if the result set grows too much (however this way couples the service tier with the limited implementation of an UI).
Be careful! This not means that every method on the service tier must throw an Exception if its result sizes more than 100, this general rule only applies to result sets that are shown to the user directly, that is a better reason to place the control in the UI instead on the service tier.
|
231,838 |
<p>Alright, so I have a query that looks like this:</p>
<pre><code>SELECT
`orders`.*,
GROUP_CONCAT(
CONCAT(
`menu_items`.`name`,
' ($',
FORMAT(`menu_items`.`price`,2),
')'
) SEPARATOR '<br>'
) as `items`,
SUM(`menu_items`.`price`) as `additional`,
`children`.`first_name`,
`children`.`last_name`,
`organizations`.`base_price`
FROM
`orders`, `order_items`, `menu_items`, `children`, `organizations`
WHERE
`order_items`.`menu_item_id` = `menu_items`.`id` AND
`order_items`.`order_id` = `orders`.`id` AND
`orders`.`added_by` = {$user_id} AND
`orders`.`date` > '{$cutoff}' AND
`children`.`id` = `orders`.`child_id` AND
`organizations`.`id` = `children`.`organization_id`
GROUP BY
`orders`.`id`
</code></pre>
<p>I know it's a monstrosity and that some people will die before not using explicit joins. Ignoring that, however, what I wish to do is to only use the <code>CONCAT</code> inside the <code>GROUP_CONCAT</code> if the <code>menu_items.price</code> is greater than 0, otherwise only return <code>menu_items.name</code>. I have had, however, no success trying to throw an <code>IF</code> in there. I've read the manual but all the ways that I've tried aren't working and I'm pretty sure I'm missing something on the whole conditional statements thing.</p>
|
[
{
"answer_id": 231846,
"author": "Lance Roberts",
"author_id": 13295,
"author_profile": "https://Stackoverflow.com/users/13295",
"pm_score": 4,
"selected": true,
"text": "<p>Have you tried using something like this?</p>\n\n<pre><code>CASE WHEN 'menu_items'.'price' = 0 THEN 'menu.items'.'name' ELSE CONCAT (etc) END \n</code></pre>\n\n<p>Replacing the <code>CONCAT</code> statement of course.</p>\n"
},
{
"answer_id": 231956,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 1,
"selected": false,
"text": "<p>Something like this should work (but I didn't test it, sorry):</p>\n\n<pre><code>GROUP_CONCAT(\n CONCAT(\n `menu_items`.`name`, \n IF(`menu_items`.`price` > 0, -- <condition>\n CONCAT(' ($', FORMAT(`menu_items`.`price`,2), ')'), -- <true-expr>\n '' -- <false-expr>\n )\n )\n SEPARATOR '<br>'\n) as `items`,\n</code></pre>\n\n<p>The <code>IF()</code> function is really simple:</p>\n\n<pre><code>IF( <condition>, <true-expr>, <false-expr> )\n</code></pre>\n\n<p>The function has three arguments: the first is <code><condition></code>. If the condition evaluates to true, the function returns the result of <code><true-expr></code>. Else the function returns the result of <code><false-expr></code>.</p>\n\n<p>Things get harder to get right when you use really long, multi-line expressions that contain parentheses and commas and so on. You just have to do it carefully. I suggest starting with more simple expressions and then build up.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16417/"
] |
Alright, so I have a query that looks like this:
```
SELECT
`orders`.*,
GROUP_CONCAT(
CONCAT(
`menu_items`.`name`,
' ($',
FORMAT(`menu_items`.`price`,2),
')'
) SEPARATOR '<br>'
) as `items`,
SUM(`menu_items`.`price`) as `additional`,
`children`.`first_name`,
`children`.`last_name`,
`organizations`.`base_price`
FROM
`orders`, `order_items`, `menu_items`, `children`, `organizations`
WHERE
`order_items`.`menu_item_id` = `menu_items`.`id` AND
`order_items`.`order_id` = `orders`.`id` AND
`orders`.`added_by` = {$user_id} AND
`orders`.`date` > '{$cutoff}' AND
`children`.`id` = `orders`.`child_id` AND
`organizations`.`id` = `children`.`organization_id`
GROUP BY
`orders`.`id`
```
I know it's a monstrosity and that some people will die before not using explicit joins. Ignoring that, however, what I wish to do is to only use the `CONCAT` inside the `GROUP_CONCAT` if the `menu_items.price` is greater than 0, otherwise only return `menu_items.name`. I have had, however, no success trying to throw an `IF` in there. I've read the manual but all the ways that I've tried aren't working and I'm pretty sure I'm missing something on the whole conditional statements thing.
|
Have you tried using something like this?
```
CASE WHEN 'menu_items'.'price' = 0 THEN 'menu.items'.'name' ELSE CONCAT (etc) END
```
Replacing the `CONCAT` statement of course.
|
231,839 |
<p>In C++ you can disable a function in parent's class by declaring it as private in the child class. How can this be done in Python? I.E. How can I hide parent's function from child's public interface?</p>
|
[
{
"answer_id": 231857,
"author": "Jason Baker",
"author_id": 2147,
"author_profile": "https://Stackoverflow.com/users/2147",
"pm_score": 3,
"selected": false,
"text": "<pre><code>class X(object):\n def some_function(self):\n do_some_stuff()\n\nclass Y(object):\n some_function = None\n</code></pre>\n\n<p>This may lead to some nasty and hard to find exceptions being thrown though, so you might try this:</p>\n\n<pre><code>class X(object):\n def some_function(self):\n do_some_stuff()\n\nclass Y(object):\n def some_function(self):\n raise NotImplementedError(\"function some_function not implemented\")\n</code></pre>\n"
},
{
"answer_id": 231871,
"author": "kurosch",
"author_id": 30153,
"author_profile": "https://Stackoverflow.com/users/30153",
"pm_score": 6,
"selected": true,
"text": "<p>There really aren't any true \"private\" attributes or methods in Python. One thing you can do is simply override the method you don't want in the subclass, and raise an exception:</p>\n\n<pre><code>>>> class Foo( object ):\n... def foo( self ):\n... print 'FOO!'\n... \n>>> class Bar( Foo ):\n... def foo( self ):\n... raise AttributeError( \"'Bar' object has no attribute 'foo'\" )\n... \n>>> b = Bar()\n>>> b.foo()\nTraceback (most recent call last):\n File \"<interactive input>\", line 1, in <module>\n File \"<interactive input>\", line 3, in foo\nAttributeError: 'Bar' object has no attribute 'foo'\n</code></pre>\n"
},
{
"answer_id": 235657,
"author": "cdleary",
"author_id": 3594,
"author_profile": "https://Stackoverflow.com/users/3594",
"pm_score": 4,
"selected": false,
"text": "<p>kurosch's method of solving the problem isn't quite correct, because you can still use <code>b.foo</code> without getting an <code>AttributeError</code>. If you don't invoke the function, no error occurs. Here are two ways that I can think to do this:</p>\n\n<pre><code>import doctest\n\nclass Foo(object):\n \"\"\"\n >>> Foo().foo()\n foo\n \"\"\"\n def foo(self): print 'foo'\n def fu(self): print 'fu'\n\nclass Bar(object):\n \"\"\"\n >>> b = Bar()\n >>> b.foo()\n Traceback (most recent call last):\n ...\n AttributeError\n >>> hasattr(b, 'foo')\n False\n >>> hasattr(b, 'fu')\n True\n \"\"\"\n def __init__(self): self._wrapped = Foo()\n\n def __getattr__(self, attr_name):\n if attr_name == 'foo': raise AttributeError\n return getattr(self._wrapped, attr_name)\n\nclass Baz(Foo):\n \"\"\"\n >>> b = Baz()\n >>> b.foo() # doctest: +ELLIPSIS\n Traceback (most recent call last):\n ...\n AttributeError...\n >>> hasattr(b, 'foo')\n False\n >>> hasattr(b, 'fu')\n True\n \"\"\"\n foo = property()\n\nif __name__ == '__main__':\n doctest.testmod()\n</code></pre>\n\n<p>Bar uses the \"wrap\" pattern to restrict access to the wrapped object. <a href=\"http://www.aleax.it/gdd_pydp.pdf\" rel=\"noreferrer\">Martelli has a good talk</a> dealing with this. Baz uses <a href=\"http://docs.python.org/library/functions.html?highlight=property#property\" rel=\"noreferrer\">the property built-in</a> to implement the descriptor protocol for the attribute to override.</p>\n"
},
{
"answer_id": 23126120,
"author": "Joey Nelson",
"author_id": 2600246,
"author_profile": "https://Stackoverflow.com/users/2600246",
"pm_score": 1,
"selected": false,
"text": "<p>This is the cleanest way I know to do it.</p>\n\n<p>Override the methods and have each of the overridden methods call your disabledmethods() method. Like this:</p>\n\n<pre><code>class Deck(list):\n...\n@staticmethod\n def disabledmethods():\n raise Exception('Function Disabled')\n def pop(self): Deck.disabledmethods()\n def sort(self): Deck.disabledmethods()\n def reverse(self): Deck.disabledmethods()\n def __setitem__(self, loc, val): Deck.disabledmethods()\n</code></pre>\n"
},
{
"answer_id": 23126260,
"author": "John Damen",
"author_id": 2829389,
"author_profile": "https://Stackoverflow.com/users/2829389",
"pm_score": 4,
"selected": false,
"text": "<p>A variation on the answer of kurosch:</p>\n\n<pre><code>class Foo( object ):\n def foo( self ):\n print 'FOO!'\n\nclass Bar( Foo ):\n @property\n def foo( self ):\n raise AttributeError( \"'Bar' object has no attribute 'foo'\" )\n\nb = Bar()\nb.foo\n</code></pre>\n\n<p>This raises an <code>AttributeError</code> on the property instead of when the method is called.</p>\n\n<p>I would have suggested it in a comment but unfortunately do not have the reputation for it yet.</p>\n"
},
{
"answer_id": 56771281,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>That could be even simpler.</p>\n\n<pre><code>@property\ndef private(self):\n raise AttributeError\n\nclass A:\n def __init__(self):\n pass\n def hello(self):\n print(\"Hello World\")\n\nclass B(A):\n hello = private # that short, really\n def hi(self):\n A.hello(self)\n\nobj = A()\nobj.hello()\nobj = B()\nobj.hi() # works\nobj.hello() # raises AttributeError\n</code></pre>\n"
},
{
"answer_id": 63585320,
"author": "Gordon Wrigley",
"author_id": 10471,
"author_profile": "https://Stackoverflow.com/users/10471",
"pm_score": 1,
"selected": false,
"text": "<p>Another approach is define an descriptor that errors on access.</p>\n<pre><code> class NotHereDescriptor:\n def __get__(self, obj, type=None):\n raise AttributeError\n \n class Bar:\n foo = NotHereDescriptor()\n</code></pre>\n<p>This is similar in nature to the property approach a few people have used above. However it has the advantage that <code>hasattr(Bar, 'foo')</code> will return <code>False</code> as one would expect if the function really didn't exist. Which further reduces the chance of weird bugs. Although it does still show up in <code>dir(Bar)</code>.</p>\n<p>If you are interested in what this is doing and why it works check out the descriptor section of the data model page <a href=\"https://docs.python.org/3/reference/datamodel.html#descriptors\" rel=\"nofollow noreferrer\">https://docs.python.org/3/reference/datamodel.html#descriptors</a> and the descriptor how to <a href=\"https://docs.python.org/3/howto/descriptor.html\" rel=\"nofollow noreferrer\">https://docs.python.org/3/howto/descriptor.html</a></p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17523/"
] |
In C++ you can disable a function in parent's class by declaring it as private in the child class. How can this be done in Python? I.E. How can I hide parent's function from child's public interface?
|
There really aren't any true "private" attributes or methods in Python. One thing you can do is simply override the method you don't want in the subclass, and raise an exception:
```
>>> class Foo( object ):
... def foo( self ):
... print 'FOO!'
...
>>> class Bar( Foo ):
... def foo( self ):
... raise AttributeError( "'Bar' object has no attribute 'foo'" )
...
>>> b = Bar()
>>> b.foo()
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
File "<interactive input>", line 3, in foo
AttributeError: 'Bar' object has no attribute 'foo'
```
|
231,848 |
<p>The follow code (running in ASP.Net 2.0) displays the contents of the requested URL <strong>twice</strong>. I only want it to display the contents of the requested URL once. I can't figure out what I'm doing wrong. The URL requested is returning XML and if I visit the URL directly, it works fine.</p>
<pre><code>HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
byte[] postDataBytes = Encoding.UTF8.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/xml";
request.ContentLength = postDataBytes.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(postDataBytes, 0, postDataBytes.Length);
requestStream.Close();
// get response and write to console
response = (HttpWebResponse) request.GetResponse();
StreamReader responseReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
try {
Response.Write(responseReader.ReadToEnd());
}
finally {
responseReader.Close();
}
response.Close();
</code></pre>
|
[
{
"answer_id": 231857,
"author": "Jason Baker",
"author_id": 2147,
"author_profile": "https://Stackoverflow.com/users/2147",
"pm_score": 3,
"selected": false,
"text": "<pre><code>class X(object):\n def some_function(self):\n do_some_stuff()\n\nclass Y(object):\n some_function = None\n</code></pre>\n\n<p>This may lead to some nasty and hard to find exceptions being thrown though, so you might try this:</p>\n\n<pre><code>class X(object):\n def some_function(self):\n do_some_stuff()\n\nclass Y(object):\n def some_function(self):\n raise NotImplementedError(\"function some_function not implemented\")\n</code></pre>\n"
},
{
"answer_id": 231871,
"author": "kurosch",
"author_id": 30153,
"author_profile": "https://Stackoverflow.com/users/30153",
"pm_score": 6,
"selected": true,
"text": "<p>There really aren't any true \"private\" attributes or methods in Python. One thing you can do is simply override the method you don't want in the subclass, and raise an exception:</p>\n\n<pre><code>>>> class Foo( object ):\n... def foo( self ):\n... print 'FOO!'\n... \n>>> class Bar( Foo ):\n... def foo( self ):\n... raise AttributeError( \"'Bar' object has no attribute 'foo'\" )\n... \n>>> b = Bar()\n>>> b.foo()\nTraceback (most recent call last):\n File \"<interactive input>\", line 1, in <module>\n File \"<interactive input>\", line 3, in foo\nAttributeError: 'Bar' object has no attribute 'foo'\n</code></pre>\n"
},
{
"answer_id": 235657,
"author": "cdleary",
"author_id": 3594,
"author_profile": "https://Stackoverflow.com/users/3594",
"pm_score": 4,
"selected": false,
"text": "<p>kurosch's method of solving the problem isn't quite correct, because you can still use <code>b.foo</code> without getting an <code>AttributeError</code>. If you don't invoke the function, no error occurs. Here are two ways that I can think to do this:</p>\n\n<pre><code>import doctest\n\nclass Foo(object):\n \"\"\"\n >>> Foo().foo()\n foo\n \"\"\"\n def foo(self): print 'foo'\n def fu(self): print 'fu'\n\nclass Bar(object):\n \"\"\"\n >>> b = Bar()\n >>> b.foo()\n Traceback (most recent call last):\n ...\n AttributeError\n >>> hasattr(b, 'foo')\n False\n >>> hasattr(b, 'fu')\n True\n \"\"\"\n def __init__(self): self._wrapped = Foo()\n\n def __getattr__(self, attr_name):\n if attr_name == 'foo': raise AttributeError\n return getattr(self._wrapped, attr_name)\n\nclass Baz(Foo):\n \"\"\"\n >>> b = Baz()\n >>> b.foo() # doctest: +ELLIPSIS\n Traceback (most recent call last):\n ...\n AttributeError...\n >>> hasattr(b, 'foo')\n False\n >>> hasattr(b, 'fu')\n True\n \"\"\"\n foo = property()\n\nif __name__ == '__main__':\n doctest.testmod()\n</code></pre>\n\n<p>Bar uses the \"wrap\" pattern to restrict access to the wrapped object. <a href=\"http://www.aleax.it/gdd_pydp.pdf\" rel=\"noreferrer\">Martelli has a good talk</a> dealing with this. Baz uses <a href=\"http://docs.python.org/library/functions.html?highlight=property#property\" rel=\"noreferrer\">the property built-in</a> to implement the descriptor protocol for the attribute to override.</p>\n"
},
{
"answer_id": 23126120,
"author": "Joey Nelson",
"author_id": 2600246,
"author_profile": "https://Stackoverflow.com/users/2600246",
"pm_score": 1,
"selected": false,
"text": "<p>This is the cleanest way I know to do it.</p>\n\n<p>Override the methods and have each of the overridden methods call your disabledmethods() method. Like this:</p>\n\n<pre><code>class Deck(list):\n...\n@staticmethod\n def disabledmethods():\n raise Exception('Function Disabled')\n def pop(self): Deck.disabledmethods()\n def sort(self): Deck.disabledmethods()\n def reverse(self): Deck.disabledmethods()\n def __setitem__(self, loc, val): Deck.disabledmethods()\n</code></pre>\n"
},
{
"answer_id": 23126260,
"author": "John Damen",
"author_id": 2829389,
"author_profile": "https://Stackoverflow.com/users/2829389",
"pm_score": 4,
"selected": false,
"text": "<p>A variation on the answer of kurosch:</p>\n\n<pre><code>class Foo( object ):\n def foo( self ):\n print 'FOO!'\n\nclass Bar( Foo ):\n @property\n def foo( self ):\n raise AttributeError( \"'Bar' object has no attribute 'foo'\" )\n\nb = Bar()\nb.foo\n</code></pre>\n\n<p>This raises an <code>AttributeError</code> on the property instead of when the method is called.</p>\n\n<p>I would have suggested it in a comment but unfortunately do not have the reputation for it yet.</p>\n"
},
{
"answer_id": 56771281,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>That could be even simpler.</p>\n\n<pre><code>@property\ndef private(self):\n raise AttributeError\n\nclass A:\n def __init__(self):\n pass\n def hello(self):\n print(\"Hello World\")\n\nclass B(A):\n hello = private # that short, really\n def hi(self):\n A.hello(self)\n\nobj = A()\nobj.hello()\nobj = B()\nobj.hi() # works\nobj.hello() # raises AttributeError\n</code></pre>\n"
},
{
"answer_id": 63585320,
"author": "Gordon Wrigley",
"author_id": 10471,
"author_profile": "https://Stackoverflow.com/users/10471",
"pm_score": 1,
"selected": false,
"text": "<p>Another approach is define an descriptor that errors on access.</p>\n<pre><code> class NotHereDescriptor:\n def __get__(self, obj, type=None):\n raise AttributeError\n \n class Bar:\n foo = NotHereDescriptor()\n</code></pre>\n<p>This is similar in nature to the property approach a few people have used above. However it has the advantage that <code>hasattr(Bar, 'foo')</code> will return <code>False</code> as one would expect if the function really didn't exist. Which further reduces the chance of weird bugs. Although it does still show up in <code>dir(Bar)</code>.</p>\n<p>If you are interested in what this is doing and why it works check out the descriptor section of the data model page <a href=\"https://docs.python.org/3/reference/datamodel.html#descriptors\" rel=\"nofollow noreferrer\">https://docs.python.org/3/reference/datamodel.html#descriptors</a> and the descriptor how to <a href=\"https://docs.python.org/3/howto/descriptor.html\" rel=\"nofollow noreferrer\">https://docs.python.org/3/howto/descriptor.html</a></p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231848",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30996/"
] |
The follow code (running in ASP.Net 2.0) displays the contents of the requested URL **twice**. I only want it to display the contents of the requested URL once. I can't figure out what I'm doing wrong. The URL requested is returning XML and if I visit the URL directly, it works fine.
```
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
byte[] postDataBytes = Encoding.UTF8.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/xml";
request.ContentLength = postDataBytes.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(postDataBytes, 0, postDataBytes.Length);
requestStream.Close();
// get response and write to console
response = (HttpWebResponse) request.GetResponse();
StreamReader responseReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
try {
Response.Write(responseReader.ReadToEnd());
}
finally {
responseReader.Close();
}
response.Close();
```
|
There really aren't any true "private" attributes or methods in Python. One thing you can do is simply override the method you don't want in the subclass, and raise an exception:
```
>>> class Foo( object ):
... def foo( self ):
... print 'FOO!'
...
>>> class Bar( Foo ):
... def foo( self ):
... raise AttributeError( "'Bar' object has no attribute 'foo'" )
...
>>> b = Bar()
>>> b.foo()
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
File "<interactive input>", line 3, in foo
AttributeError: 'Bar' object has no attribute 'foo'
```
|
231,862 |
<p>I'm working with a MySQL query that writes into an outfile. I run this query once every day or two and so I want to be able to remove the outfile without having to resort to su or sudo. The only way I can think of making that happen is to have the outfile written as owned by someone other than the mysql user. Is this possible?</p>
<p>Edit: I am not redirecting output to a file, I am using the INTO OUTFILE part of a select query to output to a file.</p>
<p>If it helps:<pre>
mysql --version
mysql Ver 14.12 Distrib 5.0.32, for pc-linux-gnu (x86_64) using readline 5.2
</pre></p>
|
[
{
"answer_id": 231876,
"author": "acrosman",
"author_id": 24215,
"author_profile": "https://Stackoverflow.com/users/24215",
"pm_score": 1,
"selected": false,
"text": "<p>If you have another user run the query from cron, it will create the file as that user.</p>\n"
},
{
"answer_id": 232022,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 5,
"selected": true,
"text": "<p>The output file is created by the mysqld process, not by your client process. Therefore the output file must be owned by the uid and gid of the mysqld process.</p>\n\n<p>You can avoid having to sudo to access the file if you access it from a process under a uid or gid that can access the file. In other words, if mysqld creates files owned by uid and gid \"mysql\"/\"mysql\", then add your own account to group \"mysql\". Then you should be able to access the file, provided the file's permission mode includes group access.</p>\n\n<p><strong>Edit:</strong></p>\n\n<p>You are deleting a file in /tmp, with a directory permission mode of rwxrwxrwt. The sticky bit ('t') means you can remove files only if your uid is the same as the owner of the file, regardless of permissions on the file or the directory.</p>\n\n<p>If you save your output file in another directory that doesn't have the sticky bit set, you should be able to remove the file normally.</p>\n\n<p>Read this excerpt from the man page for sticky(8):</p>\n\n<p><strong>STICKY DIRECTORIES</strong></p>\n\n<p>A directory whose `sticky bit' is set becomes an append-only directory, or, more accurately, a directory in which the deletion of files is restricted. A file in a sticky directory may only be removed or renamed by a user if the user has write permission for the directory and the user is the owner of the file, the owner of the directory, or the super-user. This feature is usefully applied to directories such as /tmp which must be publicly writable but should deny users the license to arbitrarily delete or rename each others' files.</p>\n"
},
{
"answer_id": 232254,
"author": "Draemon",
"author_id": 26334,
"author_profile": "https://Stackoverflow.com/users/26334",
"pm_score": 3,
"selected": false,
"text": "<p>Not using the \"SELECT...INTO OUTFILE\" syntax, no.</p>\n\n<p>You need to run the query (ie client) as another user, and redirect the output. For example, edit your crontab to run the following command whenever you want:</p>\n\n<pre><code>mysql db_schema -e 'SELECT col,... FROM table' > /tmp/outfile.txt\n</code></pre>\n\n<p>That will create /tmp/outfile.txt as the user who's crontab you've added the command to.</p>\n"
},
{
"answer_id": 3028580,
"author": "coder5",
"author_id": 365212,
"author_profile": "https://Stackoverflow.com/users/365212",
"pm_score": 1,
"selected": false,
"text": "<p>I just do </p>\n\n<pre><code>sudo gedit /etc/apparmor.d/usr.sbin.mysqld\n</code></pre>\n\n<p>and add </p>\n\n<pre><code> /var/www/codeigniter/assets/download/* w,\n</code></pre>\n\n<p>and</p>\n\n<pre><code>sudo service mysql restart\n</code></pre>\n\n<p>And that's it, I can do easily <code>SELECT INTO OUTFILE</code> any filename</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1447/"
] |
I'm working with a MySQL query that writes into an outfile. I run this query once every day or two and so I want to be able to remove the outfile without having to resort to su or sudo. The only way I can think of making that happen is to have the outfile written as owned by someone other than the mysql user. Is this possible?
Edit: I am not redirecting output to a file, I am using the INTO OUTFILE part of a select query to output to a file.
If it helps:
```
mysql --version
mysql Ver 14.12 Distrib 5.0.32, for pc-linux-gnu (x86_64) using readline 5.2
```
|
The output file is created by the mysqld process, not by your client process. Therefore the output file must be owned by the uid and gid of the mysqld process.
You can avoid having to sudo to access the file if you access it from a process under a uid or gid that can access the file. In other words, if mysqld creates files owned by uid and gid "mysql"/"mysql", then add your own account to group "mysql". Then you should be able to access the file, provided the file's permission mode includes group access.
**Edit:**
You are deleting a file in /tmp, with a directory permission mode of rwxrwxrwt. The sticky bit ('t') means you can remove files only if your uid is the same as the owner of the file, regardless of permissions on the file or the directory.
If you save your output file in another directory that doesn't have the sticky bit set, you should be able to remove the file normally.
Read this excerpt from the man page for sticky(8):
**STICKY DIRECTORIES**
A directory whose `sticky bit' is set becomes an append-only directory, or, more accurately, a directory in which the deletion of files is restricted. A file in a sticky directory may only be removed or renamed by a user if the user has write permission for the directory and the user is the owner of the file, the owner of the directory, or the super-user. This feature is usefully applied to directories such as /tmp which must be publicly writable but should deny users the license to arbitrarily delete or rename each others' files.
|
231,868 |
<p>I'm getting a strange error from <code>g++</code> 3.3 in the following code:</p>
<pre><code>#include <bitset>
#include <string>
using namespace std;
template <int N, int M>
bitset<N> slice_bitset(const bitset<M> &original, size_t start) {
string str = original.to_string<char, char_traits<char>, allocator<char> >();
string newstr = str.substr(start, N);
return bitset<N>(newstr);
}
int main() {
bitset<128> test;
bitset<12> result = slice_bitset<12, 128>(test, 0);
return 0;
}
</code></pre>
<p>The error is as follows:</p>
<pre>
In function `std::bitset slice_bitset(const std::bitset&, unsigned int)':
syntax error before `,' token
`char_traits' specified as declarator-id
two or more data types in declaration of `char_traits'
`allocator' specified as declarator-id
two or more data types in declaration of `allocator'
syntax error before `>' token
</pre>
<p>It has to be something really silly, but I've already told it to my rubber duck and a friend to no avail.</p>
<p>Thanks, Lazyweb.</p>
|
[
{
"answer_id": 231904,
"author": "CAdaker",
"author_id": 30579,
"author_profile": "https://Stackoverflow.com/users/30579",
"pm_score": 3,
"selected": false,
"text": "<p>Use either just</p>\n\n<pre><code>original.to_string();\n</code></pre>\n\n<p>or, if you really need the type specifiers,</p>\n\n<pre><code>original.template to_string<char, char_traits<char>, allocator<char> >();\n</code></pre>\n"
},
{
"answer_id": 231922,
"author": "Tim Stewart",
"author_id": 26002,
"author_profile": "https://Stackoverflow.com/users/26002",
"pm_score": 2,
"selected": false,
"text": "<p>The following compiled for me (using gcc 3.4.4):</p>\n\n<pre><code>#include <bitset>\n#include <string>\n\nusing namespace std;\n\ntemplate <int N, int M> \nbitset<N> slice_bitset(const bitset<M> &original, size_t start) \n{ \n string str = original.to_string();\n string newstr = str.substr(start, N); \n return bitset<N>(newstr);\n}\n\nint main() \n{ \n return 0; \n}\n</code></pre>\n"
},
{
"answer_id": 239654,
"author": "Richard Corden",
"author_id": 11698,
"author_profile": "https://Stackoverflow.com/users/11698",
"pm_score": 4,
"selected": true,
"text": "<p>The selected answer from <a href=\"https://stackoverflow.com/questions/231868/c-two-or-more-data-types-in-declaration#231904\">CAdaker</a> solves the problem, but does not explain <strong>why</strong> it solves the problem.</p>\n<p>When a function template is being parsed, lookup does not take place in dependent types. As a result, constructs such as the following can be parsed:</p>\n<pre><code>template <typename T>\nclass B;\n\ntemplate <typename T>\nvoid foo (B<T> & b) {\n // Use 'b' here, even though 'B' not defined\n}\n\ntemplate <typename T>\nclass B\n{\n // Define 'B' here.\n};\n</code></pre>\n<p>However, this "feature" has a cost, and in this case it is that the definition of 'foo' requires hints on the contents of the template 'B'. If 'foo' uses a nested type of 'B', then the <code>typename</code> keyword is required to tell the compiler that the name is a type:</p>\n<pre><code>template <typename T>\nvoid foo (B<T> & b)\n{\n typename B<T>::X t1; // 'X' is a type - this declares t1\n B<T>::Y * t1; // 'Y' is an object - this is multiplication\n}\n</code></pre>\n<p>Without 'typename' in the above the compiler will assume that <code>X</code> is an object (or function).</p>\n<p>Similarly, if a member function is called and the call has explicit template arguments then the compiler needs to know to treat the <code><</code> as the start of a template argument list and not the less than operator:</p>\n<pre><code>template <typename T>\nvoid foo (B<T> & b)\n{\n b.template bar<int> (0); // 'bar' is a template, '<' is start of arg list\n b.Y < 10; // 'Y' is an object, '<' is less than operator\n}\n</code></pre>\n<p>Without <code>template</code>, the compiler assumes that <code><</code> is the less than operator, and so generates the syntax error when it sees <code>int></code> since that is not an expression.</p>\n<p>These hints are required <em>even</em> when the definition of the template is visible. The reason is that an explicit specialization might later change the definition that is actually chosen:</p>\n<pre><code>template <typename T>\nclass B\n{\n template <typename S>\n void a();\n};\n\ntemplate <typename T>\nvoid foo (B<T> & b)\n{\n b.a < 10; // 'B<int>::a' is a member object\n}\n\ntemplate <>\nclass B<int>\n{\n int a;\n};\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3594/"
] |
I'm getting a strange error from `g++` 3.3 in the following code:
```
#include <bitset>
#include <string>
using namespace std;
template <int N, int M>
bitset<N> slice_bitset(const bitset<M> &original, size_t start) {
string str = original.to_string<char, char_traits<char>, allocator<char> >();
string newstr = str.substr(start, N);
return bitset<N>(newstr);
}
int main() {
bitset<128> test;
bitset<12> result = slice_bitset<12, 128>(test, 0);
return 0;
}
```
The error is as follows:
```
In function `std::bitset slice_bitset(const std::bitset&, unsigned int)':
syntax error before `,' token
`char_traits' specified as declarator-id
two or more data types in declaration of `char_traits'
`allocator' specified as declarator-id
two or more data types in declaration of `allocator'
syntax error before `>' token
```
It has to be something really silly, but I've already told it to my rubber duck and a friend to no avail.
Thanks, Lazyweb.
|
The selected answer from [CAdaker](https://stackoverflow.com/questions/231868/c-two-or-more-data-types-in-declaration#231904) solves the problem, but does not explain **why** it solves the problem.
When a function template is being parsed, lookup does not take place in dependent types. As a result, constructs such as the following can be parsed:
```
template <typename T>
class B;
template <typename T>
void foo (B<T> & b) {
// Use 'b' here, even though 'B' not defined
}
template <typename T>
class B
{
// Define 'B' here.
};
```
However, this "feature" has a cost, and in this case it is that the definition of 'foo' requires hints on the contents of the template 'B'. If 'foo' uses a nested type of 'B', then the `typename` keyword is required to tell the compiler that the name is a type:
```
template <typename T>
void foo (B<T> & b)
{
typename B<T>::X t1; // 'X' is a type - this declares t1
B<T>::Y * t1; // 'Y' is an object - this is multiplication
}
```
Without 'typename' in the above the compiler will assume that `X` is an object (or function).
Similarly, if a member function is called and the call has explicit template arguments then the compiler needs to know to treat the `<` as the start of a template argument list and not the less than operator:
```
template <typename T>
void foo (B<T> & b)
{
b.template bar<int> (0); // 'bar' is a template, '<' is start of arg list
b.Y < 10; // 'Y' is an object, '<' is less than operator
}
```
Without `template`, the compiler assumes that `<` is the less than operator, and so generates the syntax error when it sees `int>` since that is not an expression.
These hints are required *even* when the definition of the template is visible. The reason is that an explicit specialization might later change the definition that is actually chosen:
```
template <typename T>
class B
{
template <typename S>
void a();
};
template <typename T>
void foo (B<T> & b)
{
b.a < 10; // 'B<int>::a' is a member object
}
template <>
class B<int>
{
int a;
};
```
|
231,870 |
<p>I have a separate partition on my disk formatted with FAT32. When I hibernate windows, I want to be able to load another OS, create/modify files that are on that partition, then bring Windows out of hibernation and be able to see the changes that I've made.</p>
<p>I know what you're going to type, "Well, you're not supposed to do that!" and then link me to some specs about how what I'm trying to do is wrong/impossible/going to break EVERYTHING. However, I'm sure there's some way I can get around that. :)</p>
<p>I don't need the FAT32 partition in Windows, except to read the files that were written there, then I'm done - so whatever the solution is, it's acceptable for the disk to be completely inaccessible for a period of time. Unfortunately, I can't take the entire physical disk offline because it is just a partition of the same physical device that windows is installed on -- just the partition.</p>
<p>These are the things I've tried so far...</p>
<ol>
<li>Google it. I got at least one "this is NEVER going to happen" answer. Unacceptable! :)</li>
<li>Unmount the disk before hibernating. Mount after coming out of hibernation. This seems to have no effect. Windows still thinks the FAT is the same as it was before, so whatever data I wrote to disk is lost, and any files I resized are corrupted. If any of the file was cached, it's even worse.</li>
<li>Use DeviceIoControl to call IOCTL_DISK_UPDATE_PROPERTIES to try and refresh the disk (but the partition table hasn't changed, so this doesn't really do anything).</li>
</ol>
<p>Is there any way to invalidate the disk/volume read cache to force windows to go back to the disk? </p>
<p>I thought about opening the partition and reading/writing directly by using libfat and bypassing the cache or something is overkill.</p>
|
[
{
"answer_id": 231981,
"author": "Kluge",
"author_id": 8752,
"author_profile": "https://Stackoverflow.com/users/8752",
"pm_score": 0,
"selected": false,
"text": "<p>My memory is that the FAT table is read during the OS boot and mounting of the volume. Can't you do a shutdown, then modify the FAT, then reboot Windows?</p>\n"
},
{
"answer_id": 231993,
"author": "CesarB",
"author_id": 28258,
"author_profile": "https://Stackoverflow.com/users/28258",
"pm_score": 2,
"selected": false,
"text": "<p>Well, you're not supposed to do that! ;-)</p>\n\n<p>Since the operating system (Windows in this case, but Linux is the same) writes some of its internal filesystem structures in the hibernation image, it is going to be very confused if the disk contents change while it's \"running\" (think of hibernation as just a long pause in the operating system's execution).</p>\n\n<p>What I can suggest is that you completely bypass the issue: format the partition as ext2. There are Windows programs to read an ext2 partition, which you can use to get data out of it, and most modern operating systems should be able to read/write it (since it's a quite common Unix-style filesystem). Avoid ext2 IFS drivers; you want to take the filesystem access out of the kernel and into a program which you can open and close at will.</p>\n"
},
{
"answer_id": 232012,
"author": "Windows programmer",
"author_id": 23705,
"author_profile": "https://Stackoverflow.com/users/23705",
"pm_score": 1,
"selected": false,
"text": "<p>Use Linux to create the partition as a hidden FAT32 partition. Linux will let you mount the partition and write files. Windows will not let you mount the partition and read files, and Windows will not corrupt the partition. But there are third party libraries that will read the partition while Windows is running.</p>\n\n<p>To clarify, hidden means that the partition type is different from an ordinary FAT32 partition type. If your ordinary partition type is 0x0C then the corresponding hidden type is 0x1C.</p>\n"
},
{
"answer_id": 241771,
"author": "Windows programmer",
"author_id": 23705,
"author_profile": "https://Stackoverflow.com/users/23705",
"pm_score": 0,
"selected": false,
"text": "<p>As far as I can tell, Windows does caching at the disk level. However, if a partition has a type that Windows refuses to read or write (ext2, hidden FAT32, etc.) then that partition's contents should never get into Windows caches in the first place.</p>\n"
},
{
"answer_id": 254756,
"author": "Nick",
"author_id": 30425,
"author_profile": "https://Stackoverflow.com/users/30425",
"pm_score": 3,
"selected": false,
"text": "<p>So I finally got a solution to my problem. In my mind, I associated Mount Point with Mount. These are NOT the same thing. Removing all of the volume mount points does not make the volume unmounted. It's still mounted but not in the sense that you have a path you can access in explorer.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/dd143253.aspx\" rel=\"nofollow noreferrer\">This is the article</a> that started it all.\nIt also goes to show that searching for your EXACT problem, as opposed to the perceived problem can help a lot!</p>\n\n<p>So there were a couple of solutions, one was to constantly call NtSetSystemInformation() in a tight loop to set the \"SYSTEMCACHEINFORMATION\" property to essentially empty/clear the cache whenever the system is going to hibernation. Then stop the loop when you come out. This, to me, seemed like it could affect system performance. So I discarded it.</p>\n\n<p>Even better though, is the recommended solution to a slightly different problem presented in this MSDN article, which provides direction to an even better solution to the problem: <a href=\"http://msdn.microsoft.com/en-us/library/dd143253.aspx\" rel=\"nofollow noreferrer\">Dismounting Volumes in a Hibernate Once/Resume Many Configuration</a></p>\n\n<p>Now I have a service which will flush the write caches, then lock and dismount the volume whenever the system goes into hibernation/sleep and release the lock on the volume as soon as it comes out. </p>\n\n<p>Here's a little bit of code.\nOnHibernate></p>\n\n<pre><code>volumeHandle = CreateFile(volumePath,\n GENERIC_READ|GENERIC_WRITE, \n FILE_SHARE_READ|FILE_SHARE_WRITE,\n NULL,\n OPEN_EXISTING, \n FILE_ATTRIBUTE_NORMAL,\n 0 );\nFlushFileBuffers( volumeHandle );\nDeviceIoControl( volumeHandle, FSCTL_LOCK_VOLUME, NULL, 0, NULL, 0, &cbReturned, NULL ) ;\nDeviceIoControl( volumeHandle, FSCTL_DISMOUNT_VOLUME, NULL, 0, NULL, 0, &cbReturned, NULL );\n//Keep the handle open here.\n//System hibernates.\n</code></pre>\n\n<p>OnResume></p>\n\n<pre><code>DeviceIoControl( volumeHandle, FSCTL_UNLOCK_VOLUME, NULL, 0, NULL, 0, &cbReturned, NULL )\nCloseHandle(volumeHandle)\n</code></pre>\n\n<p>Hopefully this helps someone else out in the future :)</p>\n"
},
{
"answer_id": 5894535,
"author": "Raymond",
"author_id": 739462,
"author_profile": "https://Stackoverflow.com/users/739462",
"pm_score": 1,
"selected": false,
"text": "<p>On a related but different problem, I used the following:</p>\n\n<p>Running cmd as administrator (works from batch file)<br>\n<code><br>\nDISKPART<br>\n SELECT G<br>\n REMOVE<br>\n ASSIGN LETTER=G<br>\nEXIT</code></p>\n\n<p>This unmounts the volume (G:) and then remounts it. Any read of the disk (in my case a device pretending to be a USB Mass Storage Device formatted as FAT16) will actually read the device, so the read cache is effectively flushed.</p>\n\n<p>Downside is that starting DISKPART takes about 4 seconds, but that's probably not a problem in a hibernating situation.</p>\n"
},
{
"answer_id": 16381001,
"author": "Papou",
"author_id": 2144456,
"author_profile": "https://Stackoverflow.com/users/2144456",
"pm_score": 0,
"selected": false,
"text": "<p>With DOS, it was typing <kbd>ctrl</kbd>+<kbd>c</kbd>, twice if I recall well.</p>\n\n<p>With Linux, <code>sync; echo 3 > /proc/sys/vm/drop_caches</code> or a script thereof, of course ;-)</p>\n\n<p>With Windows, interpolate ;-) Or install VirtualBox and Ubuntu+Wine to develop compatibly.</p>\n\n<p>Well, I vaguely remember that former Windows used a diskcache program to start a process and that diskcache could be used to send the process a signal to flush and purge the whole cache. If things have evolved gently, you might be able to send such a signal to a Windows process. Sorry I'm no longer using Windows partly because of such obscurity.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30425/"
] |
I have a separate partition on my disk formatted with FAT32. When I hibernate windows, I want to be able to load another OS, create/modify files that are on that partition, then bring Windows out of hibernation and be able to see the changes that I've made.
I know what you're going to type, "Well, you're not supposed to do that!" and then link me to some specs about how what I'm trying to do is wrong/impossible/going to break EVERYTHING. However, I'm sure there's some way I can get around that. :)
I don't need the FAT32 partition in Windows, except to read the files that were written there, then I'm done - so whatever the solution is, it's acceptable for the disk to be completely inaccessible for a period of time. Unfortunately, I can't take the entire physical disk offline because it is just a partition of the same physical device that windows is installed on -- just the partition.
These are the things I've tried so far...
1. Google it. I got at least one "this is NEVER going to happen" answer. Unacceptable! :)
2. Unmount the disk before hibernating. Mount after coming out of hibernation. This seems to have no effect. Windows still thinks the FAT is the same as it was before, so whatever data I wrote to disk is lost, and any files I resized are corrupted. If any of the file was cached, it's even worse.
3. Use DeviceIoControl to call IOCTL\_DISK\_UPDATE\_PROPERTIES to try and refresh the disk (but the partition table hasn't changed, so this doesn't really do anything).
Is there any way to invalidate the disk/volume read cache to force windows to go back to the disk?
I thought about opening the partition and reading/writing directly by using libfat and bypassing the cache or something is overkill.
|
So I finally got a solution to my problem. In my mind, I associated Mount Point with Mount. These are NOT the same thing. Removing all of the volume mount points does not make the volume unmounted. It's still mounted but not in the sense that you have a path you can access in explorer.
[This is the article](http://msdn.microsoft.com/en-us/library/dd143253.aspx) that started it all.
It also goes to show that searching for your EXACT problem, as opposed to the perceived problem can help a lot!
So there were a couple of solutions, one was to constantly call NtSetSystemInformation() in a tight loop to set the "SYSTEMCACHEINFORMATION" property to essentially empty/clear the cache whenever the system is going to hibernation. Then stop the loop when you come out. This, to me, seemed like it could affect system performance. So I discarded it.
Even better though, is the recommended solution to a slightly different problem presented in this MSDN article, which provides direction to an even better solution to the problem: [Dismounting Volumes in a Hibernate Once/Resume Many Configuration](http://msdn.microsoft.com/en-us/library/dd143253.aspx)
Now I have a service which will flush the write caches, then lock and dismount the volume whenever the system goes into hibernation/sleep and release the lock on the volume as soon as it comes out.
Here's a little bit of code.
OnHibernate>
```
volumeHandle = CreateFile(volumePath,
GENERIC_READ|GENERIC_WRITE,
FILE_SHARE_READ|FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
0 );
FlushFileBuffers( volumeHandle );
DeviceIoControl( volumeHandle, FSCTL_LOCK_VOLUME, NULL, 0, NULL, 0, &cbReturned, NULL ) ;
DeviceIoControl( volumeHandle, FSCTL_DISMOUNT_VOLUME, NULL, 0, NULL, 0, &cbReturned, NULL );
//Keep the handle open here.
//System hibernates.
```
OnResume>
```
DeviceIoControl( volumeHandle, FSCTL_UNLOCK_VOLUME, NULL, 0, NULL, 0, &cbReturned, NULL )
CloseHandle(volumeHandle)
```
Hopefully this helps someone else out in the future :)
|
231,885 |
<p>I encountered a problem when running some old code that was handed down to me. It works 99% of the time, but once in a while, I notice it throwing a "Violation reading location" exception. I have a variable number of threads potentially executing this code throughout the lifetime of the process. The low occurrence frequency may be indicative of a race condition, but I don't know why one would cause an exception in this case. Here is the code in question:</p>
<pre><code>MyClass::Dostuff()
{
static map<char, int> mappedChars;
if (mappedChars.empty())
{
for (char c = '0'; c <= '9'; ++c)
{
mappedChars[c] = c - '0';
}
}
// More code here, but mappedChars in not changed.
}
</code></pre>
<p>The exception is thrown in the map's operator[] implementation, on the very first call to the operator[] (Using the VS2005 implementation of STL.)</p>
<pre><code>
mapped_type& operator[](const key_type& _Keyval)
{
iterator _Where = this->lower_bound(_Keyval); //exception thrown on the first line
// More code here
}
</code></pre>
<p>I already tried freezing threads in operator[] and trying to get them to all run through it at the same time, but I was unable to reproduce the exception using that methodology.</p>
<p>Can you think of any reason why that would throw, and only some of the time? </p>
<p>(Yes, I know STL is not thread-safe and I'll need to make changes here. I am mostly curious as to WHY I'm seeing the behavior I described above.)</p>
<p>As requested, here some further details about the exception:<br>
Unhandled exception at 0x00639a1c (app.exe) in app15-51-02-0944_2008-10-23.mdmp: 0xC0000005: Access violation reading location 0x00000004.</p>
<p>Thanks to everyone suggesting solutions to multithreading issues, but this isn't what this question is meant to address. Yes, I understand the presented code is not protected correctly and is overkill in what it's trying to accomplish. I already have the fix for it implemented. I'm just trying to get a better understanding of why this exception was thrown to begin with.</p>
|
[
{
"answer_id": 231895,
"author": "Henk",
"author_id": 4613,
"author_profile": "https://Stackoverflow.com/users/4613",
"pm_score": 2,
"selected": false,
"text": "<p>If multiple threads are invoking the function <code>DoStuff</code> this will mean that the initialization code</p>\n\n<pre><code>if (mappedChars.empty())\n</code></pre>\n\n<p>can enter a race condition. This means thread 1 enters the function, finds the map empty and begins filling it. Thread 2 then enters the function and finds the map non-empty (but not completely initialized) so merrily begins reading it. Because both threads are now in contention, but one is modifying the map structure (i.e inserting nodes), undefined behaviour (a crash) will result.</p>\n\n<p>If you use a synchronization primitive prior to checking the map for <code>empty()</code>, and released after the map is guaranteed to have been completely initialized, all will be well.</p>\n\n<p>I had a look via <a href=\"http://blogs.msdn.com/oldnewthing/archive/2004/03/08/85901.aspx\" rel=\"nofollow noreferrer\">Google</a> and indeed static initialization is <strong>not</strong> thread safe. Thus the declaration <code>static mappedChars</code> is immediately an issue. As others have mentioned it would be best if your initialization was done when only 1 thread is guaranteed to be active for the life time of initialization.</p>\n"
},
{
"answer_id": 231898,
"author": "Tim Stewart",
"author_id": 26002,
"author_profile": "https://Stackoverflow.com/users/26002",
"pm_score": 2,
"selected": false,
"text": "<p>mappedChars is static so it's shared by all the threads that execute DoStuff(). That alone could be your problem.</p>\n\n<p>If you have to use a static map, then you may need to protect it with a mutex or critical section.</p>\n\n<p>Personally, I think using a map for this purpose is overkill. I would write a helper function that takes a char and subtracts '0' from it. You won't have any thread safety issues with a function.</p>\n"
},
{
"answer_id": 231921,
"author": "Tony Lee",
"author_id": 5819,
"author_profile": "https://Stackoverflow.com/users/5819",
"pm_score": 4,
"selected": true,
"text": "<p>Given an address of \"4\", Likely the \"this\" pointer is null or the iterator is bad. You should be able to see this in the debugger. If this is null, then the problem isn't in that function but who ever is calling that function. If the iterator is bad, then it's the race condition you alluded to. Most iterators can't tolerate the list being updated.</p>\n\n<p>Okay wait - No FM here. Static's are initialized on first use. The code that does this is not multi-thread safe. one thread is doing the initialization while the 2nd thinks it's already been done but it's still in progress. The result is that is uses an uninitialized variable. You can see this in the assembly below:</p>\n\n<pre><code>static x y;\n004113ED mov eax,dword ptr [$S1 (418164h)] \n004113F2 and eax,1 \n004113F5 jne wmain+6Ch (41141Ch) \n004113F7 mov eax,dword ptr [$S1 (418164h)] \n004113FC or eax,1 \n004113FF mov dword ptr [$S1 (418164h)],eax \n00411404 mov dword ptr [ebp-4],0 \n0041140B mov ecx,offset y (418160h) \n00411410 call x::x (4111A4h) \n00411415 mov dword ptr [ebp-4],0FFFFFFFFh\n</code></pre>\n\n<p>The $S1 is set to 1 when it init's. If set, (004113F5) it jumps over the init code - freezing the threads in the fnc won't help because this check is done on entry to a function. This isn't null, but one of the members is.</p>\n\n<p>Fix by moving the map out of the method and into the class as static. Then it will initialize on startup. Otherwise, you have to put a CR around the calls do DoStuff(). You can protect from the remaining MT issues by placing a CR around the use of the map itself (e.g. where DoStuff uses operator[]).</p>\n"
},
{
"answer_id": 231944,
"author": "Eclipse",
"author_id": 8701,
"author_profile": "https://Stackoverflow.com/users/8701",
"pm_score": 1,
"selected": false,
"text": "<p>When you get into multi-threading, there's usually too much going on to pinpoint the exact spot where things are going bad, since it will always be changing. There are a ton of spots where using a static map in a multithreaded situation could go bad.</p>\n\n<p>See <a href=\"https://stackoverflow.com/questions/164496/how-can-i-create-a-thread-safe-singleton-pattern-in-windows#164640\">this thread</a> for some of the ways to guard a static variable. Your best bet would probably be to call the function once before starting up multiple threads to initialize it. Either that, or move the static map out, and create a separate initialization method.</p>\n"
},
{
"answer_id": 232491,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 0,
"selected": false,
"text": "<p>Are you ever calling <code>operator[]</code> with an argument that's not in the range <code>0..9</code>? If so, then you are inadvertently modifying the map, which is likely causing badness to happen in other threads. If you call <code>operator[]</code> with an argument not already in the map, it inserts that key into the map with a value equal to the default value of the value type (0 in the case of <code>int</code>).</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231885",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22724/"
] |
I encountered a problem when running some old code that was handed down to me. It works 99% of the time, but once in a while, I notice it throwing a "Violation reading location" exception. I have a variable number of threads potentially executing this code throughout the lifetime of the process. The low occurrence frequency may be indicative of a race condition, but I don't know why one would cause an exception in this case. Here is the code in question:
```
MyClass::Dostuff()
{
static map<char, int> mappedChars;
if (mappedChars.empty())
{
for (char c = '0'; c <= '9'; ++c)
{
mappedChars[c] = c - '0';
}
}
// More code here, but mappedChars in not changed.
}
```
The exception is thrown in the map's operator[] implementation, on the very first call to the operator[] (Using the VS2005 implementation of STL.)
```
mapped_type& operator[](const key_type& _Keyval)
{
iterator _Where = this->lower_bound(_Keyval); //exception thrown on the first line
// More code here
}
```
I already tried freezing threads in operator[] and trying to get them to all run through it at the same time, but I was unable to reproduce the exception using that methodology.
Can you think of any reason why that would throw, and only some of the time?
(Yes, I know STL is not thread-safe and I'll need to make changes here. I am mostly curious as to WHY I'm seeing the behavior I described above.)
As requested, here some further details about the exception:
Unhandled exception at 0x00639a1c (app.exe) in app15-51-02-0944\_2008-10-23.mdmp: 0xC0000005: Access violation reading location 0x00000004.
Thanks to everyone suggesting solutions to multithreading issues, but this isn't what this question is meant to address. Yes, I understand the presented code is not protected correctly and is overkill in what it's trying to accomplish. I already have the fix for it implemented. I'm just trying to get a better understanding of why this exception was thrown to begin with.
|
Given an address of "4", Likely the "this" pointer is null or the iterator is bad. You should be able to see this in the debugger. If this is null, then the problem isn't in that function but who ever is calling that function. If the iterator is bad, then it's the race condition you alluded to. Most iterators can't tolerate the list being updated.
Okay wait - No FM here. Static's are initialized on first use. The code that does this is not multi-thread safe. one thread is doing the initialization while the 2nd thinks it's already been done but it's still in progress. The result is that is uses an uninitialized variable. You can see this in the assembly below:
```
static x y;
004113ED mov eax,dword ptr [$S1 (418164h)]
004113F2 and eax,1
004113F5 jne wmain+6Ch (41141Ch)
004113F7 mov eax,dword ptr [$S1 (418164h)]
004113FC or eax,1
004113FF mov dword ptr [$S1 (418164h)],eax
00411404 mov dword ptr [ebp-4],0
0041140B mov ecx,offset y (418160h)
00411410 call x::x (4111A4h)
00411415 mov dword ptr [ebp-4],0FFFFFFFFh
```
The $S1 is set to 1 when it init's. If set, (004113F5) it jumps over the init code - freezing the threads in the fnc won't help because this check is done on entry to a function. This isn't null, but one of the members is.
Fix by moving the map out of the method and into the class as static. Then it will initialize on startup. Otherwise, you have to put a CR around the calls do DoStuff(). You can protect from the remaining MT issues by placing a CR around the use of the map itself (e.g. where DoStuff uses operator[]).
|
231,886 |
<p>This may seem like a somewhat contrived example, but I'm left scratching my head.</p>
<p>Ok, I have a console app that instantiates a WindowsForm and calls a method called DoSomeWork() on the form.</p>
<pre><code>class Program
{
static void Main(string[] args)
{
Form1 form = new Form1();
form.DoSomeWork();
}
}
</code></pre>
<p>Form1 looks like this...</p>
<pre><code>public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void DoSomeWork()
{
OuterClass outerClass = new OuterClass();
outerClass.DoSomeWork();
}
}
</code></pre>
<p>Outer class, in turn, looks like this...</p>
<pre><code>public class OuterClass
{
public void DoSomeWork()
{
InnerClass innerClass = new InnerClass();
innerClass.DoSomeWork();
}
}
</code></pre>
<p>And finally InnerClass looks like this...</p>
<pre><code>public class InnerClass
{
private BackgroundWorker _backgroundWorker = new BackgroundWorker();
public InnerClass()
{
_backgroundWorker.WorkerReportsProgress = true;
_backgroundWorker.DoWork += new DoWorkEventHandler(BackgroundWorker_DoWork);
_backgroundWorker.ProgressChanged += new ProgressChangedEventHandler(BackgroundWorker_ProgressChanged);
}
void BackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
int i = 0; //I've placed a break point here. But it's never hit
}
void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
worker.ReportProgress(42);
}
public void DoSomeWork()
{
_backgroundWorker.RunWorkerAsync();
}
}
</code></pre>
<p>For a reason unknown (to me), the BacgroundWorker in InnerClass never seems to fire the <strong>ProgressChanged</strong> event. If I replace </p>
<pre><code>Form1 form = new Form1();
</code></pre>
<p>with </p>
<pre><code>OuterClass outerClass = new OuterClass()
</code></pre>
<p>in class Program, it works fine. So why is that my events don't fire when I'm calling the same methods through a Form?</p>
<p>Thanks!</p>
<p>EDIT: I seemed to be throwing people off by leaving the ProgressChanged event handler as throwing a NotImplementedException, so I've removed it for clarity.</p>
|
[
{
"answer_id": 231894,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 2,
"selected": false,
"text": "<p>Did you actually <code>throw NotImplementedException();</code> in the handler? or you're just mocking this up quick and forgot to remove it?</p>\n\n<p>My guess would be that it is related to different thread apartment models being utilized.</p>\n\n<p>From my experience if a single-thread-apartment <em>non-UI</em> thread throws an exception outside of the main UI thread, that thread will simply dies without any warning.</p>\n\n<p>Windows Forms require a different apartment model than Console applications if I remember correctly. That could be the source of the problem.</p>\n\n<p>I could be wrong but that should give some pointers.</p>\n"
},
{
"answer_id": 232073,
"author": "Hans Passant",
"author_id": 17034,
"author_profile": "https://Stackoverflow.com/users/17034",
"pm_score": 4,
"selected": true,
"text": "<p>You forgot to start a message loop, calling Application.Run() is required. Without a message loop, the BackgroundWorker events cannot work. To fix:</p>\n\n<pre><code>static void Main(string[] args)\n{\n Application.Run(new Form1()); \n}\n</code></pre>\n\n<p>Call DoSomeWork() in the form's constructor or it's Load event.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6419/"
] |
This may seem like a somewhat contrived example, but I'm left scratching my head.
Ok, I have a console app that instantiates a WindowsForm and calls a method called DoSomeWork() on the form.
```
class Program
{
static void Main(string[] args)
{
Form1 form = new Form1();
form.DoSomeWork();
}
}
```
Form1 looks like this...
```
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void DoSomeWork()
{
OuterClass outerClass = new OuterClass();
outerClass.DoSomeWork();
}
}
```
Outer class, in turn, looks like this...
```
public class OuterClass
{
public void DoSomeWork()
{
InnerClass innerClass = new InnerClass();
innerClass.DoSomeWork();
}
}
```
And finally InnerClass looks like this...
```
public class InnerClass
{
private BackgroundWorker _backgroundWorker = new BackgroundWorker();
public InnerClass()
{
_backgroundWorker.WorkerReportsProgress = true;
_backgroundWorker.DoWork += new DoWorkEventHandler(BackgroundWorker_DoWork);
_backgroundWorker.ProgressChanged += new ProgressChangedEventHandler(BackgroundWorker_ProgressChanged);
}
void BackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
int i = 0; //I've placed a break point here. But it's never hit
}
void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
worker.ReportProgress(42);
}
public void DoSomeWork()
{
_backgroundWorker.RunWorkerAsync();
}
}
```
For a reason unknown (to me), the BacgroundWorker in InnerClass never seems to fire the **ProgressChanged** event. If I replace
```
Form1 form = new Form1();
```
with
```
OuterClass outerClass = new OuterClass()
```
in class Program, it works fine. So why is that my events don't fire when I'm calling the same methods through a Form?
Thanks!
EDIT: I seemed to be throwing people off by leaving the ProgressChanged event handler as throwing a NotImplementedException, so I've removed it for clarity.
|
You forgot to start a message loop, calling Application.Run() is required. Without a message loop, the BackgroundWorker events cannot work. To fix:
```
static void Main(string[] args)
{
Application.Run(new Form1());
}
```
Call DoSomeWork() in the form's constructor or it's Load event.
|
231,893 |
<p>I have seen this syntax in MSDN: <a href="https://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx" rel="noreferrer"><code>yield break</code></a>, but I don't know what it does. Does anyone know?</p>
|
[
{
"answer_id": 231896,
"author": "Brian",
"author_id": 19299,
"author_profile": "https://Stackoverflow.com/users/19299",
"pm_score": 6,
"selected": false,
"text": "<p>Ends an iterator block (e.g. says there are no more elements in the IEnumerable).</p>\n"
},
{
"answer_id": 231915,
"author": "Trap",
"author_id": 7839,
"author_profile": "https://Stackoverflow.com/users/7839",
"pm_score": 5,
"selected": false,
"text": "<p>Tells the iterator that it's reached the end.</p>\n\n<p>As an example:</p>\n\n<pre><code>public interface INode\n{\n IEnumerable<Node> GetChildren();\n}\n\npublic class NodeWithTenChildren : INode\n{\n private Node[] m_children = new Node[10];\n\n public IEnumerable<Node> GetChildren()\n {\n for( int n = 0; n < 10; ++n )\n {\n yield return m_children[ n ];\n }\n }\n}\n\npublic class NodeWithNoChildren : INode\n{\n public IEnumerable<Node> GetChildren()\n {\n yield break;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 231945,
"author": "Damir Zekić",
"author_id": 401510,
"author_profile": "https://Stackoverflow.com/users/401510",
"pm_score": 10,
"selected": true,
"text": "<p>It specifies that an iterator has come to an end. You can think of <code>yield break</code> as a <code>return</code> statement which does not return a value.</p>\n\n<p>For example, if you define a function as an iterator, the body of the function may look like this:</p>\n\n<pre><code>for (int i = 0; i < 5; i++)\n{\n yield return i;\n}\n\nConsole.Out.WriteLine(\"You will see me\");\n</code></pre>\n\n<p>Note that after the loop has completed all its cycles, the last line gets executed and you will see the message in your console app.</p>\n\n<p>Or like this with <code>yield break</code>:</p>\n\n<pre><code>int i = 0;\nwhile (true)\n{\n if (i < 5)\n {\n yield return i;\n }\n else\n {\n // note that i++ will not be executed after this\n yield break;\n }\n i++;\n}\n\nConsole.Out.WriteLine(\"Won't see me\");\n</code></pre>\n\n<p>In this case the last statement is never executed because we left the function early.</p>\n"
},
{
"answer_id": 1051152,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p><code>yield</code> basically makes an <code>IEnumerable<T></code> method behave similarly to a cooperatively (as opposed to preemptively) scheduled thread.</p>\n\n<p><code>yield return</code> is like a thread calling a \"schedule\" or \"sleep\" function to give up control of the CPU. Just like a thread, the <code>IEnumerable<T></code> method regains controls at the point immediately afterward, with all local variables having the same values as they had before control was given up.</p>\n\n<p><code>yield break</code> is like a thread reaching the end of its function and terminating.</p>\n\n<p>People talk about a \"state machine\", but a state machine is all a \"thread\" really is. A thread has some state (I.e. values of local variables), and each time it is scheduled it takes some action(s) in order to reach a new state. The key point about <code>yield</code> is that, unlike the operating system threads we're used to, the code that uses it is frozen in time until the iteration is manually advanced or terminated.</p>\n"
},
{
"answer_id": 2573970,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Here <a href=\"http://www.alteridem.net/2007/08/22/the-yield-statement-in-c/\" rel=\"noreferrer\">http://www.alteridem.net/2007/08/22/the-yield-statement-in-c/</a> is very good example:</p>\n\n<pre>\npublic static IEnumerable<int> Range( int min, int max )\n{\n while ( true )\n {\n if ( min >= max )\n {\n yield break;\n }\n yield return min++;\n }\n}\n</pre>\n\n<p>and explanation, that if a <code>yield break</code> statement is hit within a method, execution of that method stops with no return. There are some time situations, when you don't want to give any result, then you can use yield break.</p>\n"
},
{
"answer_id": 8771185,
"author": "Eranga Dissanayaka",
"author_id": 1622207,
"author_profile": "https://Stackoverflow.com/users/1622207",
"pm_score": -1,
"selected": false,
"text": "<p>The yield keyword is used together with the return keyword to provide a value to the enumerator object. <strong>yield return</strong> specifies the value, or values, returned. When the yield return statement is reached, the current location is stored. Execution is restarted from this location the next time the iterator is called.</p>\n\n<p>To explain the meaning using an example:</p>\n\n<blockquote>\n<pre><code> public IEnumerable<int> SampleNumbers()\n {\n int counter = 0;\n yield return counter;\n\n counter = counter + 2;\n\n yield return counter;\n\n counter = counter + 3;\n\n yield return counter ;\n }\n</code></pre>\n</blockquote>\n\n<p>Values returned when this is iterated are: 0, 2, 5.</p>\n\n<p><strong>It’s important to note that <em>counter</em> variable in this example is a local variable.</strong> After the second iteration which returns the value of 2, third iteration starts from where it left before, while preserving the previous value of local variable named <em>counter</em> which was 2.</p>\n"
},
{
"answer_id": 40814062,
"author": "Wallace Kelly",
"author_id": 167920,
"author_profile": "https://Stackoverflow.com/users/167920",
"pm_score": 4,
"selected": false,
"text": "<p>The <code>yield break</code> statement causes the enumeration to stop. In effect, <code>yield break</code> completes the enumeration without returning any additional items.</p>\n\n<p>Consider that there are actually two ways that an iterator method could stop iterating. In one case, the logic of the method could naturally exit the method after returning all the items. Here is an example:</p>\n\n<pre><code>IEnumerable<uint> FindPrimes(uint startAt, uint maxCount)\n{\n for (var i = 0UL; i < maxCount; i++)\n {\n startAt = NextPrime(startAt);\n yield return startAt;\n }\n\n Debug.WriteLine(\"All the primes were found.\");\n}\n</code></pre>\n\n<p>In the above example, the iterator method will naturally stop executing once <code>maxCount</code> primes have been found.</p>\n\n<p>The <code>yield break</code> statement is another way for the iterator to cease enumerating. It is a way to break out of the enumeration early. Here is the same method as above. This time, the method has a limit on the amount of time that the method can execute. </p>\n\n<pre><code>IEnumerable<uint> FindPrimes(uint startAt, uint maxCount, int maxMinutes)\n{\n var sw = System.Diagnostics.Stopwatch.StartNew();\n for (var i = 0UL; i < maxCount; i++)\n {\n startAt = NextPrime(startAt);\n yield return startAt;\n\n if (sw.Elapsed.TotalMinutes > maxMinutes)\n yield break;\n }\n\n Debug.WriteLine(\"All the primes were found.\");\n}\n</code></pre>\n\n<p>Notice the call to <code>yield break</code>. In effect, it is exiting the enumeration early.</p>\n\n<p>Notice too that the <code>yield break</code> works differently than just a plain <code>break</code>. In the above example, <code>yield break</code> exits the method without making the call to <code>Debug.WriteLine(..)</code>.</p>\n"
},
{
"answer_id": 51502141,
"author": "John ClearZ",
"author_id": 318041,
"author_profile": "https://Stackoverflow.com/users/318041",
"pm_score": 4,
"selected": false,
"text": "<p>yield break is just a way of saying return for the last time and don't return any value</p>\n\n<p>e.g</p>\n\n<pre><code>// returns 1,2,3,4,5\nIEnumerable<int> CountToFive()\n{\n yield return 1;\n yield return 2;\n yield return 3;\n yield return 4;\n yield return 5;\n yield break;\n yield return 6;\n yield return 7;\n yield return 8;\n yield return 9;\n }\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14101/"
] |
I have seen this syntax in MSDN: [`yield break`](https://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx), but I don't know what it does. Does anyone know?
|
It specifies that an iterator has come to an end. You can think of `yield break` as a `return` statement which does not return a value.
For example, if you define a function as an iterator, the body of the function may look like this:
```
for (int i = 0; i < 5; i++)
{
yield return i;
}
Console.Out.WriteLine("You will see me");
```
Note that after the loop has completed all its cycles, the last line gets executed and you will see the message in your console app.
Or like this with `yield break`:
```
int i = 0;
while (true)
{
if (i < 5)
{
yield return i;
}
else
{
// note that i++ will not be executed after this
yield break;
}
i++;
}
Console.Out.WriteLine("Won't see me");
```
In this case the last statement is never executed because we left the function early.
|
231,903 |
<p>Just wondering how much people log within their applications???</p>
<p>I have seen this:</p>
<blockquote>
<p>"I typically like to use the ERROR log
level to log any exceptions that are
caught by the application. I will use
the INFO log level as a "first level"
debugging scheme to show whenever I
enter or exit a method. From there I
use the DEBUG log level to trace
detailed information. The FATAL log
level is used for any exceptions that
I have failed to catch in my web based
applications."</p>
</blockquote>
<p>Which had this code sample with it:</p>
<pre><code>Public Class LogSample
Private Shared ReadOnly Log As log4net.ILog = log4net.LogManager.GetLogger(GetType(LogSample))
Public Function AddNumbers(ByVal Number1 As Integer, ByVal Number2 As Integer) As Integer
Dim intResults As Integer
Log.Info("Starting AddNumbers Method...")
Log.Debug("Number1 Specified: " & Number1)
Log.Debug("Number2 Specified: " & Number2)
intResults = Number1 + Number2
Try
intResults = Number1 + Number2
Catch ex As Exception
Log.Error("Error Adding Nubmers.", ex)
End Try
Log.Info("AddNumbers Method Complete.")
Return intResults
End Function
End Class
</code></pre>
<p>But this just seems to add so much to the method. For instance a class that would normally be maybe 7 lines of code suddenly becomes 12 lines of code. The method also loses some of its clarity and simplicity.</p>
<p>But in saying that the benefit of having the logging in place can be good. For instance performance monitoring in a production system, chasing down aberrant bugs in production (not that you would have all this logging turned on all the time.</p>
<p>Hence I am wondering what people do?
Cheers
Anthony </p>
|
[
{
"answer_id": 231923,
"author": "SaaS Developer",
"author_id": 7215,
"author_profile": "https://Stackoverflow.com/users/7215",
"pm_score": 2,
"selected": false,
"text": "<p>You are right that this does make the code more difficult to read and maintain. One recommendation is to consider looking into an AOP (Aspect oriented Programming) tool to separate your logging logic from your application logic. Castle Windsor and Spring are two that come to mind within the .Net community that you may want to research.</p>\n"
},
{
"answer_id": 231926,
"author": "Joe Basirico",
"author_id": 20795,
"author_profile": "https://Stackoverflow.com/users/20795",
"pm_score": 0,
"selected": false,
"text": "<p>From a security standpoint logging can be an interesting topic. I wrote a <a href=\"http://blogs.csoonline.com/when_ddos_attacks_become_personal\" rel=\"nofollow noreferrer\">blog entry</a> on CSO Online a while back in the wake of a couple of DDOS attacks. This is the section where I talked about logging, hope it helps a bit:</p>\n\n<blockquote>\n <p>Techniques such as log throttling,\n write only logs, and using log servers\n can strengthen the retroactive\n security of a system. After a possible\n DDoS attack has occurred the company\n will no doubt want to investigate the\n attack. An investigation is only\n possible if the correct level of\n logging has been used. Too much and\n the logs will quickly become filled,\n which could be the reason for the DoS\n in the first place. Too little and the\n logs will be worthless because they\n don’t contain enough information to\n catch the criminal.</p>\n</blockquote>\n"
},
{
"answer_id": 231942,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 2,
"selected": false,
"text": "<p>It's more the <em>art</em> side of programming.</p>\n\n<p>You don't want to log everything. But you will want to log the most crucial parts of the system.</p>\n\n<p>Just think about your program in a broad sense and try to identify which information you will want in case something breaks in production.</p>\n\n<p>For a start, all the core logic modules of your application should have logging functionality. The decorative parts e.g. UI/animation shouldn't need logging.</p>\n\n<p>IMHO, logging every method entry/exits is overkill and will also produce a noise especially since you can just embed a stack trace.</p>\n\n<p>And for performance, use a <em>profiler</em>.</p>\n"
},
{
"answer_id": 231988,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": 2,
"selected": false,
"text": "<p>...hey, do I get a badge for being quoted as the topic in a SO question? 8^D</p>\n\n<p>But seriously though, one thing I want to clarify about the logging comment above is that part of my justification for the \"verbose\" logging is based on the fact that I'm leveraging the features of log4net itself.</p>\n\n<p>In the sample I provided, that method logs on a daily basis in WARN mode. Which means that the only thing that gets logged \"by default\" is if an exception occurs. If I get a call from one of my clients about having an error in the application, they don't have to read me some cryptic message on the screen, I jump in the log and can see what's going on. Most of the time, the answer is right there.</p>\n\n<p>What happens if the answer isn't readily available? Log4net allows me to update my configuration file (no re-compilation necessary, no need to get access to some special system file on the web server with the sysadmin's approval) and go into INFO mode. Now you start seeing a second layer of logging. Maybe the code never made it to a certain loop. Maybe the data retrieval had an empty record set. This second level of debugging is helpful, and the log only gets slightly larger. Once this is done, I can change the config again and go back to the light logging.</p>\n\n<p>Naturally if things are REALLY crazy, then I go to the full debug level, and I want to know what each variable is reporting, what DataRows I'm dealing with, and what is going on in the application. At my current place of work, we don't have the ability to do remote debugging into our web applications, and we can't always tap into the production database without potentially augmenting data, so having this full debug is the next best thing.</p>\n\n<p>I agree with the majority of folks out there that excessive logging can really bring down an application and cause more problems than it is worth. If wouldn't recommend this kind of verbose logging in an application either unless the application warranted it for security reasons. However, being able to leverage verbose logging when needed and without having to recompile my code <strong>IS a HUGE</strong> benefit in my opinion and if you have a framework that can allow for it easily (such as log4net), then I say get nice and verbose and it is easy enough to mentally filter out the log code references if you're having to go back into the code itself.</p>\n\n<p>I apologize if I sound defensive or ranting, I don't mean that in any regard. I just wanted to provide a bit more background into how and why I setup my logging using log4net in the method mentioned. 8^D</p>\n"
},
{
"answer_id": 232189,
"author": "RWendi",
"author_id": 15152,
"author_profile": "https://Stackoverflow.com/users/15152",
"pm_score": 0,
"selected": false,
"text": "<p>At a bare minimum you should log errors and calls to external component... The sample you provide is what I would call TOO much loggings... There is no point of logging that you're in a start of a method, or in the end of a method, or even the params that were passed to the method... Its a waste of disk space, You log file will get very big in no time...</p>\n\n<p><a href=\"http://www.rwendi.com\" rel=\"nofollow noreferrer\" title=\"RWendi\">RWendi</a></p>\n"
},
{
"answer_id": 37355187,
"author": "tranmq",
"author_id": 73820,
"author_profile": "https://Stackoverflow.com/users/73820",
"pm_score": 0,
"selected": false,
"text": "<p>It is not easy to decide how much logging is enough. Too much logging code in a function as in your example buries the actual logic code. Too many log entries makes the log noisy. But too little of logs is not very helpful!!</p>\n\n<p>For .NET, you can use the AOP library, PostSharp, to help log the entering and exiting of a function together with values of the arguments and more.</p>\n\n<p>For help with determining how much to log your application, check out this article <a href=\"http://ranum.com/security/computer_security/archives/logging-notes.pdf\" rel=\"nofollow\">\"System Logging and Log Analysis</a>\" by Marcus Ranum.</p>\n\n<p>Hope this helps.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231903",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30572/"
] |
Just wondering how much people log within their applications???
I have seen this:
>
> "I typically like to use the ERROR log
> level to log any exceptions that are
> caught by the application. I will use
> the INFO log level as a "first level"
> debugging scheme to show whenever I
> enter or exit a method. From there I
> use the DEBUG log level to trace
> detailed information. The FATAL log
> level is used for any exceptions that
> I have failed to catch in my web based
> applications."
>
>
>
Which had this code sample with it:
```
Public Class LogSample
Private Shared ReadOnly Log As log4net.ILog = log4net.LogManager.GetLogger(GetType(LogSample))
Public Function AddNumbers(ByVal Number1 As Integer, ByVal Number2 As Integer) As Integer
Dim intResults As Integer
Log.Info("Starting AddNumbers Method...")
Log.Debug("Number1 Specified: " & Number1)
Log.Debug("Number2 Specified: " & Number2)
intResults = Number1 + Number2
Try
intResults = Number1 + Number2
Catch ex As Exception
Log.Error("Error Adding Nubmers.", ex)
End Try
Log.Info("AddNumbers Method Complete.")
Return intResults
End Function
End Class
```
But this just seems to add so much to the method. For instance a class that would normally be maybe 7 lines of code suddenly becomes 12 lines of code. The method also loses some of its clarity and simplicity.
But in saying that the benefit of having the logging in place can be good. For instance performance monitoring in a production system, chasing down aberrant bugs in production (not that you would have all this logging turned on all the time.
Hence I am wondering what people do?
Cheers
Anthony
|
You are right that this does make the code more difficult to read and maintain. One recommendation is to consider looking into an AOP (Aspect oriented Programming) tool to separate your logging logic from your application logic. Castle Windsor and Spring are two that come to mind within the .Net community that you may want to research.
|
231,917 |
<p>This originally was a problem I ran into at work, but is now something I'm just trying to solve for my own curiosity.</p>
<p>I want to find out if int 'a' contains the int 'b' in the most efficient way possible. I wrote some code, but it seems no matter what I write, parsing it into a string and then using indexOf is twice as fast as doing it mathematically.</p>
<p>Memory is not an issue (within reason), just sheer processing speed.</p>
<p>This is the code I have written to do it mathematically:</p>
<pre><code>private static int[] exponents = {10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 };
private static boolean findMatch(int a, int b) {
if (b > a) return false;
if (a == b) return true;
int needleLength = getLength(b);
int exponent = exponents[needleLength];
int subNum;
while (a >= 1) {
subNum = a % exponent;
if (subNum == b)
return true;
a /= 10;
}
return false;
}
private static int getLength(int b) {
int len = 0;
while (b >= 1) {
len++;
b /= 10;
}
return len;
}
</code></pre>
<p>Here's the string method I'm using, which seems to trump the mathematical method above:</p>
<pre><code>private static boolean findStringMatch(int a, int b) {
return String.valueOf(a).indexOf(String.valueOf(b)) != -1;
}
</code></pre>
<p>So although this isn't really required for me to complete my work, I was just wondering if anyone could think of any way to further optimize my way of doing it mathematically, or an entirely new approach altogether. Again memory is no problem, I am just shooting for sheer speed.</p>
<p>I'm really interested to see or hear anything anyone has to offer on this.</p>
<p><strong>EDIT:</strong> When I say contains I mean can be anywhere, so for example, findMatch(1234, 23) == true</p>
<p><strong>EDIT:</strong> For everyone saying that this crap is unreadable and unnecessary: you're missing the point. The point was to get to geek out on an interesting problem, not come up with an answer to be used in production code.</p>
|
[
{
"answer_id": 231936,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 0,
"selected": false,
"text": "<p>Umm, I'm probably totally misunderstanding the question, but.....</p>\n\n<pre><code>// Check if A is inside B lol\nbool Contains (int a, int b)\n{\n return (a <= b);\n}\n</code></pre>\n\n<p>Unless you want to know if a particular sequence of numbers is within another sequence of numbers.</p>\n\n<p>In that case, converting it to a string WILL be faster than doing the math to figure it out.</p>\n"
},
{
"answer_id": 231950,
"author": "oxbow_lakes",
"author_id": 16853,
"author_profile": "https://Stackoverflow.com/users/16853",
"pm_score": 0,
"selected": false,
"text": "<p>This in no way answers your question, whatsoever, but it's advice anyway :-)</p>\n\n<p>The method name <code>findMatch</code> is not very descriptive. In this case, I'd have a static method <code>ContainerBuilder.number(int)</code>, which returned a <code>ContainerBuilder</code>, which has the method <code>contains</code> on it. In this way your code becomes:</p>\n\n<pre><code>boolean b = number(12345).contains(234);\n</code></pre>\n\n<p>Juts some advice for the long run!</p>\n\n<p>Oh yes, I meant to say also, you should <em>define what you mean by \"contains\"</em></p>\n"
},
{
"answer_id": 231974,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 2,
"selected": false,
"text": "<p>The only optimization that I can think of is to do the conversion to string on your own and compare digits (right to left) as you do the conversion. First convert all the digits of b, then convert from the right on a until you find a match on the first digit of b (from right). Compare until all of b matches or you hit a mismatch. If you hit a mismatch, backtrack to the point where you starting matching the first digit of b, advance in a and start over.</p>\n\n<p>IndexOf will have to do basically the same back tracking algorithm, except from the left. Depending on the actual numbers this may be faster. I think if the numbers are random, it should be since there should be many times when it doesn't have to convert all of a.</p>\n"
},
{
"answer_id": 232011,
"author": "buti-oxa",
"author_id": 2515,
"author_profile": "https://Stackoverflow.com/users/2515",
"pm_score": 3,
"selected": false,
"text": "<p>It <em>should</em> be faster string way, because your problem is textual, not mathematical. Notice that the your \"contains\" relationship says nothing about the numbers, it only says something about their <em>decimal</em> representations.</p>\n\n<p>Notice also that the function you want to write will be unreadable - another developer will never understand what you are doing. (See what trouble you had with that here.) The string version, on the other hand, is perfectly clear.</p>\n"
},
{
"answer_id": 232023,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 0,
"selected": false,
"text": "<p>Is there any way to calculate this in binary? Obviously the binary value of an integer containing the binary integer of another character doesn't mean that the decical does the same. However, is there some kind of binary trickary that could be used? Maybe convert a numer like 12345 to 0001 0010 0011 0100 0101, and then do some bit shifting to figure out if 23 (0010 0011) is contained in there. Because your character set is only 10 characters, you could cut down the computation time by store 2 characters values in a single byte. </p>\n\n<p>EDIT</p>\n\n<p>Expanding on this idea a bit. if you have 2 integers, A and B, and want to know if A contains B, you check 2 things first. if A is less than B, then A cannot contain B. If A = B then A contains B. At this point you can convert them to strings*. If A contains the same number of character numbers as B, then A does not contain B, unless they are equal, but we wouldn't be here if they are equal, so if both strings are the same length, a does not contain b. At this point, the length of A will be longer than B. So, now you can convert the strings to their packed binary values as I noted in the first part of this post. Store these values in an array of integers. Now you do a bitwise AND Of the integer values in your array, and if the result is A, then A contains B. Now you shift the array of integers for B, to the left 4 bits, and do the conparison again. Do this until you start popping bits off the left of B. </p>\n\n<p>*That * in the previous paragraph means you may be able to skip this step. There may be a way to do this without using strings at all. There might be some fancy binary trick you can do to get the packed binary representation I discussed in the first paragraph. There should be some binary trick you can use, or some quick math which will convert an integer to the decimal value I discussed before.</p>\n"
},
{
"answer_id": 232031,
"author": "David Santamaria",
"author_id": 24097,
"author_profile": "https://Stackoverflow.com/users/24097",
"pm_score": 2,
"selected": false,
"text": "<p>Looks like your function is actually doing pretty well, but an small improvement:</p>\n\n<pre><code>private static boolean findMatch(int a, int b) {\n if (b > a) return false;\n\n if (a == b) return true;\n\n int needleLength = getLength(b);\n\n int exponent = exponents[needleLength];\n int subNum;\n while (a > b) {\n subNum = a % exponent;\n\n if (subNum == b)\n return true;\n\n a /= 10;\n }\n return false;\n}\n</code></pre>\n\n<p>Just because once that a is smaller than b, is not worthy keeps looking, isnt it?\nGood luck and post if you find the solution!</p>\n"
},
{
"answer_id": 232036,
"author": "David Santamaria",
"author_id": 24097,
"author_profile": "https://Stackoverflow.com/users/24097",
"pm_score": -1,
"selected": false,
"text": "<p>FYI</p>\n\n<p><a href=\"http://refactormycode.com/\" rel=\"nofollow noreferrer\">http://refactormycode.com/</a></p>\n\n<p>Could work for you.</p>\n"
},
{
"answer_id": 232382,
"author": "Laplie Anderson",
"author_id": 14204,
"author_profile": "https://Stackoverflow.com/users/14204",
"pm_score": 2,
"selected": false,
"text": "<p>This is an interesting problem. Many of String.class's functions are actually native making beating String a difficult proposition. But here's some helpers:</p>\n\n<p><strong>TIP 1:</strong> Different simple integer operations have different speeds.</p>\n\n<p>By quick calculations in sample programs showed:</p>\n\n<pre><code>% ~ T\n* ~ 4T\n/ ~ 7T\n</code></pre>\n\n<p>So you want to use as little division as possible in favor of multiplication or modulo. Not shown are subtraction, addition, and comparison operators cause they blow all of these out of the water. Also, using \"final\" as much as possible allows the JVM to do certain optimizations. Speeding up you \"getLength\" function:</p>\n\n<pre><code>private static int getLength(final int b) { \n int len = 0;\n while (b > exponents[len]) {\n len++;\n }\n return len + 1\n}\n</code></pre>\n\n<p>That gives about a 7x improvement in the function. You get an indexOutOfBounds exception if b > your max in exponents. To solve that, you can have:</p>\n\n<pre><code>private static int getLength(final int b) { \n int len = 0;\n final int maxLen = exponents.length;\n while (len < maxLen && b > exponents[len]) {\n len++;\n }\n return len + 1;\n}\n</code></pre>\n\n<p>That's slightly slower and gives you an incorrect length if b is too big, but it doesn't throw an exception.</p>\n\n<p><strong>TIP 2:</strong> Unnecessary object/primitive creation and method calls add to run time.</p>\n\n<p>I'm guessing that \"getLength\" isn't called anywhere else, so while it might be nice to have a separate function, from a optimization standpoint its an unnecessary method call and creation of the object \"len\". We can put that code right where we use it.</p>\n\n<pre><code>private static boolean findMatch(int a, final int b) {\n if (b > a) return false;\n if (a == b) return true;\n int needleLength = 0;\n while (b > exponents[len]) {\n needleLength ++;\n }\n needleLength++;\n\n final int exponent = exponents[needleLength];\n int subNum;\n while (a >= 1 && a <= b) {\n subNum = a % exponent;\n if (subNum == b)\n return true;\n a /= 10;\n }\n return false;\n}\n</code></pre>\n\n<p>Also, note I changed the bottom while loop to also include \"a <= b\". I haven't tested that and not sure if the per-iteration penalty beats the fact that you don't waste any iterations. I'm sure there's a way to get rid of the division using clever math, but I can't think of it right now.</p>\n"
},
{
"answer_id": 232559,
"author": "Axeman",
"author_id": 11289,
"author_profile": "https://Stackoverflow.com/users/11289",
"pm_score": 3,
"selected": true,
"text": "<p>This is along Kibbee's line, but I got a little intrigued by this before he posted and worked this out: </p>\n\n<pre><code>long mask ( long n ) { \n long m = n % 10;\n long n_d = n;\n long div = 10;\n int shl = 0;\n while ( n_d >= 10 ) { \n n_d /= 10;\n long t = n_d % 10;\n m |= ( t << ( shl += 4 ));\n }\n return m;\n}\n\nboolean findMatch( int a, int b ) { \n if ( b < a ) return false;\n if ( a == b ) return true;\n\n long m_a = mask( a ); // set up mask O(n)\n long m_b = mask( b ); // set up mask O(m)\n\n while ( m_a < m_b ) {\n if (( m_a & m_b ) == m_a ) return true;\n m_a <<= 4; // shift - fast!\n if ( m_a == m_b ) return true;\n } // O(p)\n return false;\n} \n\nvoid testContains( int a, int b ) { \n print( \"findMatch( \" + a + \", \" + b + \" )=\" + findMatch( a, b ));\n}\n\ntestContains( 12, 120 );\ntestContains( 12, 125 );\ntestContains( 123, 551241238 );\ntestContains( 131, 1214124 );\ntestContains( 131, 1314124 );\n</code></pre>\n\n<hr>\n\n<p>Since 300 characters is far too little to make an argument in, I'm editing this main post to respond to Pyrolistical. </p>\n\n<p>Unlike the OP, I wasn't that surprised that a native compiled indexOf was faster than Java code with primitives. So my goal was not to find something I thought was faster than a native method called zillions of times all over Java code. </p>\n\n<p>The OP made it clear that this was not a production problem and more along the lines of an idle curiosity, so my answer solves that curiosity. My guess was that speed was an issue, when he was trying to solve it in production, but as an idle curiosity, \"This method will be called millions and millions of times\" no longer applies. As he had to explain to one poster, it's no longer pursued as production code, so the complexity no longer matters.</p>\n\n<p>Plus it provides the only implementation on the page that manages to find the \"123\" in \"551241238\", so unless correctness is an extraneous concern, it provides that. Also the solution space of \"an algorithm that solves the problem mathematically using Java primitives but beats optimized native code\" might be <em>EMPTY</em>. </p>\n\n<p>Plus, it's not clear from your comment whether or not you compared apples to apples. The functional spec is f( int, int )-> boolean, not f( String, String )-> boolean (which is kind of the domain of <code>indexOf</code>) . So unless you tested something like this (which could still beat mine, and I wouldn't be awfully surprised.) the additional overhead <em>might</em> eat up some of that excess 40%.</p>\n\n<pre><code>boolean findMatch( int a, int b ) { \n String s_a = \"\" + a;\n String s_b = \"\" + b;\n return s_a.indexOf( s_b ) > -1;\n}\n</code></pre>\n\n<p>It does the same basic steps. log<sub>10</sub>( a ) encoding + log<sub>10</sub>( b ) encoding + actually finding the match, which is as well O(<em>n</em>) where <em>n</em> is the largest logarithm. </p>\n"
},
{
"answer_id": 232837,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 0,
"selected": false,
"text": "<p>Can I ask where you're using this function in your code? Maybe there's another way to solve the problem it is currently solving which would be much faster. This could be like when my friend asked me to completely re-tune his guitar, and I did it before realizing I could have just lowered the bottom string by a whole step and gotten an equivalent result.</p>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14007/"
] |
This originally was a problem I ran into at work, but is now something I'm just trying to solve for my own curiosity.
I want to find out if int 'a' contains the int 'b' in the most efficient way possible. I wrote some code, but it seems no matter what I write, parsing it into a string and then using indexOf is twice as fast as doing it mathematically.
Memory is not an issue (within reason), just sheer processing speed.
This is the code I have written to do it mathematically:
```
private static int[] exponents = {10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 };
private static boolean findMatch(int a, int b) {
if (b > a) return false;
if (a == b) return true;
int needleLength = getLength(b);
int exponent = exponents[needleLength];
int subNum;
while (a >= 1) {
subNum = a % exponent;
if (subNum == b)
return true;
a /= 10;
}
return false;
}
private static int getLength(int b) {
int len = 0;
while (b >= 1) {
len++;
b /= 10;
}
return len;
}
```
Here's the string method I'm using, which seems to trump the mathematical method above:
```
private static boolean findStringMatch(int a, int b) {
return String.valueOf(a).indexOf(String.valueOf(b)) != -1;
}
```
So although this isn't really required for me to complete my work, I was just wondering if anyone could think of any way to further optimize my way of doing it mathematically, or an entirely new approach altogether. Again memory is no problem, I am just shooting for sheer speed.
I'm really interested to see or hear anything anyone has to offer on this.
**EDIT:** When I say contains I mean can be anywhere, so for example, findMatch(1234, 23) == true
**EDIT:** For everyone saying that this crap is unreadable and unnecessary: you're missing the point. The point was to get to geek out on an interesting problem, not come up with an answer to be used in production code.
|
This is along Kibbee's line, but I got a little intrigued by this before he posted and worked this out:
```
long mask ( long n ) {
long m = n % 10;
long n_d = n;
long div = 10;
int shl = 0;
while ( n_d >= 10 ) {
n_d /= 10;
long t = n_d % 10;
m |= ( t << ( shl += 4 ));
}
return m;
}
boolean findMatch( int a, int b ) {
if ( b < a ) return false;
if ( a == b ) return true;
long m_a = mask( a ); // set up mask O(n)
long m_b = mask( b ); // set up mask O(m)
while ( m_a < m_b ) {
if (( m_a & m_b ) == m_a ) return true;
m_a <<= 4; // shift - fast!
if ( m_a == m_b ) return true;
} // O(p)
return false;
}
void testContains( int a, int b ) {
print( "findMatch( " + a + ", " + b + " )=" + findMatch( a, b ));
}
testContains( 12, 120 );
testContains( 12, 125 );
testContains( 123, 551241238 );
testContains( 131, 1214124 );
testContains( 131, 1314124 );
```
---
Since 300 characters is far too little to make an argument in, I'm editing this main post to respond to Pyrolistical.
Unlike the OP, I wasn't that surprised that a native compiled indexOf was faster than Java code with primitives. So my goal was not to find something I thought was faster than a native method called zillions of times all over Java code.
The OP made it clear that this was not a production problem and more along the lines of an idle curiosity, so my answer solves that curiosity. My guess was that speed was an issue, when he was trying to solve it in production, but as an idle curiosity, "This method will be called millions and millions of times" no longer applies. As he had to explain to one poster, it's no longer pursued as production code, so the complexity no longer matters.
Plus it provides the only implementation on the page that manages to find the "123" in "551241238", so unless correctness is an extraneous concern, it provides that. Also the solution space of "an algorithm that solves the problem mathematically using Java primitives but beats optimized native code" might be *EMPTY*.
Plus, it's not clear from your comment whether or not you compared apples to apples. The functional spec is f( int, int )-> boolean, not f( String, String )-> boolean (which is kind of the domain of `indexOf`) . So unless you tested something like this (which could still beat mine, and I wouldn't be awfully surprised.) the additional overhead *might* eat up some of that excess 40%.
```
boolean findMatch( int a, int b ) {
String s_a = "" + a;
String s_b = "" + b;
return s_a.indexOf( s_b ) > -1;
}
```
It does the same basic steps. log10( a ) encoding + log10( b ) encoding + actually finding the match, which is as well O(*n*) where *n* is the largest logarithm.
|
231,937 |
<p>I am trying to show and hide an inline element (eg a span) using jQuery.</p>
<p>If I just use toggle(), it works as expected but if I use toggle("slow") to give it an animation, it turns the span into a block element and therefore inserts breaks.</p>
<p>Is animation possible with inline elements? I would prefer a smooth sliding if possible, rather than a fade in.</p>
<pre><code><script type="text/javascript">
$(function(){
$('.toggle').click(function() { $('.hide').toggle("slow") });
});
</script>
<p>Hello <span class="hide">there</span> jquery</p>
<button class="toggle">Toggle</button>
</code></pre>
|
[
{
"answer_id": 232005,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 1,
"selected": false,
"text": "<p>I don't think it is possible like that. The only way I could think to do it would be to animate its opacity between 0 and 1, and, using a callback on the animation, then turn it on or off.</p>\n\n<pre><code>$('.toggle').click(function() {\n $('.hide:visible').animate(\n {opacity : 0},\n function() { $(this).hide(); }\n );\n $('.hide:hidden')\n .show()\n .animate({opacity : 1})\n ;\n});\n</code></pre>\n"
},
{
"answer_id": 232037,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 5,
"selected": true,
"text": "<p><code>toggle()</code> has a bunch of weird things with it, including hiding or transforming odd elements at times. here's a similar solution:</p>\n\n<pre><code>$('.toggle').click(function() {\n $('.hide').animate({\n 'opacity' : 'toggle',\n });\n});\n</code></pre>\n\n<p><strong>edit</strong>: here's a way to add smooth sliding, with minimal extra HTML markup:</p>\n\n<pre><code>var hidepos = $('.hide').offset().left;\nvar slidepos = $('.slide').offset().left;\n\n$('.toggle').click(function() {\n var goto = ($('.slide').offset().left < slidepos) ? slidepos : hidepos;\n\n $('.slide').css({\n 'left' : $('.slide').offset().left,\n 'position' : 'fixed',\n }).animate({\n 'left' : goto,\n }, function() {\n $(this).css('position', 'static');\n });\n\n $('.hide').animate({\n 'opacity' : 'toggle',\n });\n});\n</code></pre>\n\n<p>html:</p>\n\n<pre><code><p>Hello <span class=\"hide\">there</span> <span class=\"slide\">jquery</span></p>\n<button class=\"toggle\">Toggle</button>\n</code></pre>\n"
},
{
"answer_id": 232113,
"author": "defrex",
"author_id": 6007,
"author_profile": "https://Stackoverflow.com/users/6007",
"pm_score": 0,
"selected": false,
"text": "<p>As other answers have shown, fading is possible. However, I don't think \"smooth sliding\" will be. Simply put, a specific property of the element has to be animated. An inline span like you mention has no specific height or width, though it does have an opacity.</p>\n"
},
{
"answer_id": 232227,
"author": "jcampbell1",
"author_id": 20512,
"author_profile": "https://Stackoverflow.com/users/20512",
"pm_score": 0,
"selected": false,
"text": "<p>I don't think what you want to do is possible until display:inline-block is well supported across browsers. For now, I think I would fade the background to red, and then hide the element.</p>\n\n<p>If display:inline-block was well supported, you could change the style to inline-block, and then animate the width or height, but unfortunately that won't work very well these days. Maybe in 2010 :)</p>\n"
},
{
"answer_id": 1146761,
"author": "Simon_Weaver",
"author_id": 16940,
"author_profile": "https://Stackoverflow.com/users/16940",
"pm_score": 0,
"selected": false,
"text": "<p>The fact that 'animate' changes what it is animating to a block element is not an issue if what you are trying to slide left or right is positioned with float:left and whatever is next to it is also positioned with float:left</p>\n\n<pre><code> $('#pnlPopup #btnUpdateButton').assertOne().animate({ width: \"toggle\" });\n</code></pre>\n\n<p>if #btnUpdateButton is styled with the following then it slides quite nicely and pushes the content to the right.</p>\n\n<pre><code>#btnUpdateButton {\n float: left;\n margin-right: 5px;\n}\n</code></pre>\n"
},
{
"answer_id": 2476900,
"author": "Terion",
"author_id": 297319,
"author_profile": "https://Stackoverflow.com/users/297319",
"pm_score": 3,
"selected": false,
"text": "<p>Just one CSS-property will make you happy: <a href=\"http://terion-fallen.livejournal.com/332945.html\" rel=\"nofollow noreferrer\">http://terion-fallen.livejournal.com/332945.html</a></p>\n\n<pre><code>#animated-element { display: inline-block!important }\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31012/"
] |
I am trying to show and hide an inline element (eg a span) using jQuery.
If I just use toggle(), it works as expected but if I use toggle("slow") to give it an animation, it turns the span into a block element and therefore inserts breaks.
Is animation possible with inline elements? I would prefer a smooth sliding if possible, rather than a fade in.
```
<script type="text/javascript">
$(function(){
$('.toggle').click(function() { $('.hide').toggle("slow") });
});
</script>
<p>Hello <span class="hide">there</span> jquery</p>
<button class="toggle">Toggle</button>
```
|
`toggle()` has a bunch of weird things with it, including hiding or transforming odd elements at times. here's a similar solution:
```
$('.toggle').click(function() {
$('.hide').animate({
'opacity' : 'toggle',
});
});
```
**edit**: here's a way to add smooth sliding, with minimal extra HTML markup:
```
var hidepos = $('.hide').offset().left;
var slidepos = $('.slide').offset().left;
$('.toggle').click(function() {
var goto = ($('.slide').offset().left < slidepos) ? slidepos : hidepos;
$('.slide').css({
'left' : $('.slide').offset().left,
'position' : 'fixed',
}).animate({
'left' : goto,
}, function() {
$(this).css('position', 'static');
});
$('.hide').animate({
'opacity' : 'toggle',
});
});
```
html:
```
<p>Hello <span class="hide">there</span> <span class="slide">jquery</span></p>
<button class="toggle">Toggle</button>
```
|
231,947 |
<p>I have a project that is based on the Navigation Based Application template.
In the AppDelegate are the methods <code>-applicationDidFinishLoading:</code> and <code>-applicationWillTerminate:</code>. In those methods, I am loading and saving the application data, and storing it in an instance variable (it is actually an object-graph).</p>
<p>When the application loads, it loads MainWindow.xib, which has a NavigationConroller, which in turn has a RootViewController. The RootViewController <code>nibName</code> property points to RootView (my actual controller class).</p>
<p>In my class, I wish to refer to the object that I created in the <code>-applicationDidFinishLoading:</code> method, so that I can get a reference to it.</p>
<p>Can anyone tell me how to do that? I know how to reference between objects that I have created programmatically, but I can't seem to figure out to thread my way back, given that the middle step was done from within the NIB file.</p>
|
[
{
"answer_id": 232016,
"author": "Ben Gottlieb",
"author_id": 6694,
"author_profile": "https://Stackoverflow.com/users/6694",
"pm_score": 4,
"selected": false,
"text": "<p>If I understand your question, you want to reference member variables/properties in your AppDelegate object? The simplest way is to use [[UIApplication sharedApplication] delegate] to return a reference to your object. </p>\n\n<p>If you've got a property called window, you could do this:</p>\n\n<pre><code>UIWindow *mainWindow = [[[UIApplication sharedApplication] delegate] window];\n//do something with mainWindow\n</code></pre>\n"
},
{
"answer_id": 232372,
"author": "leonho",
"author_id": 30883,
"author_profile": "https://Stackoverflow.com/users/30883",
"pm_score": 8,
"selected": false,
"text": "<p>For variables (usually the model data structure) which I need to access it anywhere in the app, declare them in your AppDelegate class. When you need to reference it:</p>\n\n<pre><code>YourAppDelegate *appDelegate = (YourAppDelegate *)[[UIApplication sharedApplication] delegate];\n//and then access the variable by appDelegate.variable \n</code></pre>\n"
},
{
"answer_id": 5132864,
"author": "Ken",
"author_id": 283311,
"author_profile": "https://Stackoverflow.com/users/283311",
"pm_score": 4,
"selected": false,
"text": "<p>Here's a well defined portable alternative for iOS4.0 and up:</p>\n\n<pre><code>UIApplication *myApplication = [UIApplication sharedApplication];\nUIWindow *mainWindow = [myApplication keyWindow];\nUIViewController *rootViewController = [mainWindow rootViewController];\n</code></pre>\n\n<p>or, in one line,</p>\n\n<pre><code>UIViewController *rootViewController = [[[UIApplication sharedApplication] keyWindow] rootViewController];\n</code></pre>\n\n<p>Don't forget to set the window's <code>rootViewController</code> property (say in IB) or this will do jack.</p>\n"
},
{
"answer_id": 41299691,
"author": "tryKuldeepTanwar",
"author_id": 6330448,
"author_profile": "https://Stackoverflow.com/users/6330448",
"pm_score": 2,
"selected": false,
"text": "<h2>Define a macro and use it anywhere!</h2>\n<pre><code>#define appDelegateShared ((AppDelegate *)[UIApplication sharedApplication].delegate)\n</code></pre>\n<p>In My Code:-</p>\n<pre><code>UIViewController *rootViewController = appDelegateShared.window.rootViewController;\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/231947",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have a project that is based on the Navigation Based Application template.
In the AppDelegate are the methods `-applicationDidFinishLoading:` and `-applicationWillTerminate:`. In those methods, I am loading and saving the application data, and storing it in an instance variable (it is actually an object-graph).
When the application loads, it loads MainWindow.xib, which has a NavigationConroller, which in turn has a RootViewController. The RootViewController `nibName` property points to RootView (my actual controller class).
In my class, I wish to refer to the object that I created in the `-applicationDidFinishLoading:` method, so that I can get a reference to it.
Can anyone tell me how to do that? I know how to reference between objects that I have created programmatically, but I can't seem to figure out to thread my way back, given that the middle step was done from within the NIB file.
|
For variables (usually the model data structure) which I need to access it anywhere in the app, declare them in your AppDelegate class. When you need to reference it:
```
YourAppDelegate *appDelegate = (YourAppDelegate *)[[UIApplication sharedApplication] delegate];
//and then access the variable by appDelegate.variable
```
|
232,004 |
<p>For the moment the best way that I have found to be able to manipulate DOM from a string that contain HTML is:</p>
<pre><code>WebBrowser webControl = new WebBrowser();
webControl.DocumentText = html;
HtmlDocument doc = webControl.Document;
</code></pre>
<p>There are two problems:</p>
<ol>
<li>Requires the <code>WebBrowser</code> object! </li>
<li>This can't be used with multiple threads; I need something that would work on different thread (other than the main thread).</li>
</ol>
<p>Any ideas?</p>
|
[
{
"answer_id": 232021,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 3,
"selected": false,
"text": "<p>Depending on what you are trying to do (maybe you can give us more details?) and depending on whether or not the HTML is well-formed, you <em>could</em> convert this to an <code>XmlDocument</code>:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>System.Xml.XmlDocument x = new System.Xml.XmlDocument();\nx.LoadXml(html); // as long as html is well-formed, i.e. XHTML\n</code></pre>\n<p>Then you could manipulate it easily, without the <code>WebBrowser</code> instance. As for threads, I don't know enough about the implementation of <code>XmlDocument</code> to know the answer to that part.</p>\n<hr />\n<p>If the document isn't in proper form, you could use <a href=\"http://sourceforge.net/projects/ntidy/\" rel=\"nofollow noreferrer\"><strong>NTidy</strong></a> (.NET wrapper for <a href=\"http://tidy.sourceforge.net/\" rel=\"nofollow noreferrer\"><strong>HTML Tidy</strong></a>) to get it in shape first; I had to do this very thing for a project once and it really wasn't too bad.</p>\n"
},
{
"answer_id": 232028,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 6,
"selected": true,
"text": "<p>I did a search to GooglePlex for HTML and I found <a href=\"https://html-agility-pack.net/\" rel=\"noreferrer\">Html Agility Pack</a> I do not know if it's for that or not, I am downloading it right now to give a try.</p>\n"
},
{
"answer_id": 242704,
"author": "Martin Kool",
"author_id": 216896,
"author_profile": "https://Stackoverflow.com/users/216896",
"pm_score": 3,
"selected": false,
"text": "<p>JasonBunting already posted this, but it really works to use a .net wrapper around HTML tidy and load it up in an XmlDocument.</p>\n\n<p>I have used this .net wrapper before :</p>\n\n<p><a href=\"http://www.codeproject.com/KB/cs/ZetaHtmlTidy.aspx\" rel=\"noreferrer\">http://www.codeproject.com/KB/cs/ZetaHtmlTidy.aspx</a></p>\n\n<p>And implemented it somewhat like this:</p>\n\n<pre><code>string input = \"<p>crappy html<br <img src=foo></div>\";\nHtmlTidy tidy = new HtmlTidy()\nstring output = tidy.CleanHtml(input, HtmlTidyOptions.ConvertToXhtml);\nXmlDocument doc = new XmlDocument();\ndoc.LoadXml(output);\n</code></pre>\n\n<p>Sorry if considered a repost :)</p>\n"
},
{
"answer_id": 19014446,
"author": "Ashraf Sabry",
"author_id": 95970,
"author_profile": "https://Stackoverflow.com/users/95970",
"pm_score": 2,
"selected": false,
"text": "<p>This is an old question. Now there are:</p>\n\n<ul>\n<li><a href=\"https://github.com/zzzprojects/html-agility-pack\" rel=\"nofollow noreferrer\">The HTML Agility Pack</a> (You have already found this)</li>\n<li><a href=\"https://github.com/jamietre/CsQuery\" rel=\"nofollow noreferrer\">CsQuery</a>, a .Net jQuery port, which will be great for jQuery developers</li>\n</ul>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/232004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13913/"
] |
For the moment the best way that I have found to be able to manipulate DOM from a string that contain HTML is:
```
WebBrowser webControl = new WebBrowser();
webControl.DocumentText = html;
HtmlDocument doc = webControl.Document;
```
There are two problems:
1. Requires the `WebBrowser` object!
2. This can't be used with multiple threads; I need something that would work on different thread (other than the main thread).
Any ideas?
|
I did a search to GooglePlex for HTML and I found [Html Agility Pack](https://html-agility-pack.net/) I do not know if it's for that or not, I am downloading it right now to give a try.
|
232,030 |
<p>I want a pure virtual parent class to call a child implementation of a function like so:</p>
<pre><code>class parent
{
public:
void Read() { //read stuff }
virtual void Process() = 0;
parent()
{
Read();
Process();
}
}
class child : public parent
{
public:
virtual void Process() { //process stuff }
child() : parent() { }
}
int main()
{
child c;
}
</code></pre>
<p>This should work, but I get an unlinked error :/ This is using VC++ 2k3</p>
<p>Or shouldn't it work, am I wrong?</p>
|
[
{
"answer_id": 232039,
"author": "Nick",
"author_id": 26240,
"author_profile": "https://Stackoverflow.com/users/26240",
"pm_score": 2,
"selected": false,
"text": "<p>Will work in general, but not for calls within the constructor of the pure virtual base class. At the time the base class in constructed, the sub-class override doesn't exist, so you can't call it. As long as you call it once the entire object is constructed, it should work.</p>\n"
},
{
"answer_id": 232042,
"author": "Adam Pierce",
"author_id": 5324,
"author_profile": "https://Stackoverflow.com/users/5324",
"pm_score": 2,
"selected": false,
"text": "<p>It's because your call is in the constructor. The derived class will not be valid until the constructor has completed so you compiler is right in dinging you for this.</p>\n\n<p>There are two solutions:</p>\n\n<ol>\n<li>Make the call to Process() in the derived class's constructor</li>\n<li>define a blank function body for Process as in the following example:</li>\n</ol>\n\n<pre><code>class parent\n{\n public:\n void Read() { //read stuff }\n virtual void Process() { }\n parent() \n {\n Read();\n Process();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 232045,
"author": "Damir Zekić",
"author_id": 401510,
"author_profile": "https://Stackoverflow.com/users/401510",
"pm_score": 5,
"selected": true,
"text": "<p>Title of the following article says it all: <a href=\"http://www.artima.com/cppsource/nevercall.html\" rel=\"noreferrer\">Never Call Virtual Functions during Construction or Destruction</a>.</p>\n"
},
{
"answer_id": 232081,
"author": "Keith Nicholas",
"author_id": 10431,
"author_profile": "https://Stackoverflow.com/users/10431",
"pm_score": 2,
"selected": false,
"text": "<p>Alternatively, make a factory method for creating the objects and make the constructors private, the factory method can then Initialize the object after construction.</p>\n"
},
{
"answer_id": 232092,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 0,
"selected": false,
"text": "<p>You need to wrap in inside an object that calls the virtual method after the object is fully constructed:</p>\n\n<pre><code>class parent\n{\n public:\n void Read() { /*read stuff*/ }\n virtual void Process() = 0;\n parent()\n {\n Read();\n }\n};\n\nclass child: public parent\n{\n public:\n virtual void Process() { /*process stuff*/ }\n child() : parent() { }\n};\n\ntemplate<typename T>\nclass Processor\n{\n public:\n Processor()\n :processorObj() // Pass on any args here\n {\n processorObj.Process();\n }\n private:\n T processorObj;\n\n};\n\n\n\n\nint main()\n{\n Processor<child> c;\n}\n</code></pre>\n"
},
{
"answer_id": 232924,
"author": "Marcin Gil",
"author_id": 5731,
"author_profile": "https://Stackoverflow.com/users/5731",
"pm_score": 2,
"selected": false,
"text": "<p>With one step more you could just introduce some kind of a function like</p>\n\n<pre><code>class parent\n{\n public:\n void initialize() {\n read();\n process();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 232947,
"author": "xtofl",
"author_id": 6610,
"author_profile": "https://Stackoverflow.com/users/6610",
"pm_score": 1,
"selected": false,
"text": "<p>The <strong>superficial</strong> problem is that you call a virtual function that's not known yet (Objects are constructed from Parent to Child, thus so are the vtables). Your compiler warned you about that.</p>\n\n<p>The <strong>essential</strong> problem, as far as I can see, is that you try to reuse functionality by inheritance. This is almost always a bad idea. A design issue, so to speak :)</p>\n\n<p>Essentially, you try instantiating a Template Method pattern, to separate the <em>what</em> from the <em>when</em>: first read some data (in some way), then process it (in some way).</p>\n\n<p>This will probably much better work with aggregation: give the Processing function to the Template method to be called at the right time. Maybe you can even do the same for the Read functionality.</p>\n\n<p>The aggregation can be done in two ways:</p>\n\n<ol>\n<li>Using virtual functions (i.e. Runtime Binding)</li>\n<li>Using templates (i.e. Compile Time Binding)</li>\n</ol>\n\n<p>Example 1: runtime binding</p>\n\n<pre><code>class Data {};\nclass IReader { public: virtual Data read() = 0; };\nclass IProcessor { public: virtual void process( Data& d) = 0; };\n\nclass ReadNProcess {\npublic:\n ReadNProcess( IReader& reader, IProcessor processor ){\n processor.process( reader.read() );\n }\n};\n</code></pre>\n\n<p>Example 2: compiletime binding</p>\n\n<pre><code>template< typename Reader, typename Writer > // definitely could use concepts here :)\nclass ReadNProcess {\npublic:\n ReadNProcess( Reader& r, Processor& p ) {\n p.process( r.read() );\n }\n};\n</code></pre>\n"
}
] |
2008/10/23
|
[
"https://Stackoverflow.com/questions/232030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23829/"
] |
I want a pure virtual parent class to call a child implementation of a function like so:
```
class parent
{
public:
void Read() { //read stuff }
virtual void Process() = 0;
parent()
{
Read();
Process();
}
}
class child : public parent
{
public:
virtual void Process() { //process stuff }
child() : parent() { }
}
int main()
{
child c;
}
```
This should work, but I get an unlinked error :/ This is using VC++ 2k3
Or shouldn't it work, am I wrong?
|
Title of the following article says it all: [Never Call Virtual Functions during Construction or Destruction](http://www.artima.com/cppsource/nevercall.html).
|
232,052 |
<p>I have an MSBuild task to build a specific project in a solution file. It looks something like this:</p>
<pre><code><Target Name="Baz">
<MSBuild Projects="Foo.sln" Targets="bar:$(BuildCmd)" />
</Target>
</code></pre>
<p>From the command line, I can set my <code>BuildCmd</code> to either <code>Rebuild</code> or <code>Clean</code> and it works as expected:</p>
<blockquote>
<p>msbuild /target:Baz /property:BuildCmd=Rebuild MyMsbuildFile.xml
msbuild /target:Baz /property:BuildCmd=Clean MyMsbuildFile.xml</p>
</blockquote>
<p>But what word do I use to set <code>BuildCmd</code> to in order to just build? I've tried <code>Build</code> and <code>Compile</code> and just leaving it blank or undefined, but I always get an error.</p>
<blockquote>
<p>msbuild /target:Baz /property:BuildCmd=Build MyMsbuildFile.xml
Foo.sln : error MSB4057: The target "bar:Build" does not exist in the project.</p>
<p>msbuild /target:Baz /property:BuildCmd=Compile MyMsbuildFile.xml
Foo.sln : error MSB4057: The target "bar:Compile" does not exist in the project.</p>
<p>msbuild /target:Baz MyMsbuildFile.xml
Foo.sln : error MSB4057: The target "bar:" does not exist in the project.</p>
</blockquote>
|
[
{
"answer_id": 232119,
"author": "ripper234",
"author_id": 11236,
"author_profile": "https://Stackoverflow.com/users/11236",
"pm_score": -1,
"selected": false,
"text": "<p>Just edit the sln file yourself and find out - MSBuild is a real easy syntax, just look for targets.</p>\n"
},
{
"answer_id": 232518,
"author": "Tim Stewart",
"author_id": 26002,
"author_profile": "https://Stackoverflow.com/users/26002",
"pm_score": 3,
"selected": false,
"text": "<p>From: <a href=\"http://msdn.microsoft.com/en-us/library/ms164311.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/ms164311.aspx</a></p>\n\n<p>/target:targets</p>\n\n<p>Builds these targets in this project. Use a semicolon or a comma to separate multiple targets, or specify each target separately. /t is also acceptable. For example:\n/target:Resources;Compile</p>\n"
},
{
"answer_id": 233738,
"author": "CheGueVerra",
"author_id": 17787,
"author_profile": "https://Stackoverflow.com/users/17787",
"pm_score": 6,
"selected": true,
"text": "<p>I understood that you want to build a target with a specific command: Build, Clean, etc.</p>\n\n<p>This is how I would do it.</p>\n\n<p>Create a property to receive your build command, when not specified defaults to Build</p>\n\n<pre><code><PropertyGroup>\n <BuildCmd Condition=\" '$(BuildCmd)' == ''\">Build</BuildCmd>\n</PropertyGroup>\n</code></pre>\n\n<p>After, create the target that will start MSBuild with the specified target in the parameter:</p>\n\n<pre><code><Target Name=\"Stackoverflow\">\n <MsBuild Projects=\"Foo.sln\" Targets=\"$(BuildCmd)\" />\n</Target>\n</code></pre>\n\n<p>Then call your MSBuild file with the target and BuildCmd parameter like so:</p>\n\n<pre><code>msbuild msbuild.xml /t:Stackoverflow /p:BuildCmd=Clean\n</code></pre>\n\n<p>Just make sure the target exists in the solution or project file.</p>\n"
},
{
"answer_id": 235257,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Using CheGueVerra's template, I came up with the following solution:</p>\n\n<pre><code><PropertyGroup>\n <ProjBuildCmd Condition=\"'$(BuildCmd)' != 'Build'\">:$(BuildCmd)</ProjBuildCmd>\n <SolnBuildCmd Condition=\"'$(BuildCmd)' != 'Build'\">$(BuildCmd)</SolnBuildCmd>\n</PropertyGroup>\n</code></pre>\n\n<p>And then instead of using <code>$(BuildCmd)</code> directly, I use <code>$(ProjBuildCmd)</code> or <code>$(SolnBuildCmd)</code> like this:</p>\n\n<pre><code><!-- Build the 'bar' project only -->\n<Target Name=\"Baz\">\n <MSBuild Projects=\"Foo.sln\" Targets=\"bar$(ProjBuildCmd)\" />\n</Target>\n\n<!-- Build the whole solution -->\n<Target Name=\"Baz2\">\n <MSBuild Projects=\"Foo.sln\" Targets=\"$(SolnBuildCmd)\" />\n</Target>\n</code></pre>\n"
},
{
"answer_id": 11689059,
"author": "Matt Slagle",
"author_id": 1557745,
"author_profile": "https://Stackoverflow.com/users/1557745",
"pm_score": 2,
"selected": false,
"text": "<p>The key is conditionalize the BuildCmd property. </p>\n\n<pre><code> <Target Name=\"Baz\">\n <PropertyGroup>\n <BuildCmd Condition=\"'$(BuildCmd)' != ''\">:$(BuildCmd)</BuildCmd>\n </PropertyGroup>\n <MSBuild Projects=\"Foo.sln\" Targets=\"bar$(BuildCmd)\" />\n </Target>\n</code></pre>\n\n<p>This way, if Clean or Rebuild are set, the colon is added. If nothing is added, BuildCmd will just be blank, defaulting to the Build target.</p>\n\n<p><em>Note</em> - The property group must reside in the target, or it will be overriden when you specify it on the command line.</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/232052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have an MSBuild task to build a specific project in a solution file. It looks something like this:
```
<Target Name="Baz">
<MSBuild Projects="Foo.sln" Targets="bar:$(BuildCmd)" />
</Target>
```
From the command line, I can set my `BuildCmd` to either `Rebuild` or `Clean` and it works as expected:
>
> msbuild /target:Baz /property:BuildCmd=Rebuild MyMsbuildFile.xml
> msbuild /target:Baz /property:BuildCmd=Clean MyMsbuildFile.xml
>
>
>
But what word do I use to set `BuildCmd` to in order to just build? I've tried `Build` and `Compile` and just leaving it blank or undefined, but I always get an error.
>
> msbuild /target:Baz /property:BuildCmd=Build MyMsbuildFile.xml
> Foo.sln : error MSB4057: The target "bar:Build" does not exist in the project.
>
>
> msbuild /target:Baz /property:BuildCmd=Compile MyMsbuildFile.xml
> Foo.sln : error MSB4057: The target "bar:Compile" does not exist in the project.
>
>
> msbuild /target:Baz MyMsbuildFile.xml
> Foo.sln : error MSB4057: The target "bar:" does not exist in the project.
>
>
>
|
I understood that you want to build a target with a specific command: Build, Clean, etc.
This is how I would do it.
Create a property to receive your build command, when not specified defaults to Build
```
<PropertyGroup>
<BuildCmd Condition=" '$(BuildCmd)' == ''">Build</BuildCmd>
</PropertyGroup>
```
After, create the target that will start MSBuild with the specified target in the parameter:
```
<Target Name="Stackoverflow">
<MsBuild Projects="Foo.sln" Targets="$(BuildCmd)" />
</Target>
```
Then call your MSBuild file with the target and BuildCmd parameter like so:
```
msbuild msbuild.xml /t:Stackoverflow /p:BuildCmd=Clean
```
Just make sure the target exists in the solution or project file.
|
232,078 |
<p>I have three projects. One is a WCF Services Project, one is a WPF Project, and one is a Microsoft Unit Testing Project. I setup the WCF Services project with a data object that looks like this:</p>
<pre><code>[DataContract]
public enum Priority
{
Low,
Medium,
High
}
[DataContract]
public struct TimeInfo
{
[DataMember]
public Int16 EstimatedHours { get; set; }
[DataMember]
public Int16 ActualHours { get; set; }
[DataMember]
public DateTime StartDate { get; set; }
[DataMember]
public DateTime EndDate { get; set; }
[DataMember]
public DateTime CompletionDate { get; set; }
}
[DataContract]
public class Task
{
[DataMember]
public string Title { get; set; }
[DataMember]
public string Description { get; set; }
[DataMember]
public Priority Priority { get; set; }
[DataMember]
public TimeInfo TimeInformation { get; set; }
[DataMember]
public Decimal Cost { get; set; }
}
</code></pre>
<p>My contract looks like this:</p>
<pre><code>[ServiceContract]
public interface ITaskManagement
{
[OperationContract]
List<Task> GetTasks();
[OperationContract]
void CreateTask(Task taskToCreate);
[OperationContract]
void UpdateTask(Task taskToCreate);
[OperationContract]
void DeleteTask(Task taskToDelete);
}
</code></pre>
<p>When I try to use the service in either the WPF Application or the Unit Test Project with this code:</p>
<pre><code>var client = new TaskManagementClient();
textBox1.Text = client.GetTasks().ToString();
client.Close();
</code></pre>
<p>I get the following error: "The underlying connection was closed: The connection was closed unexpectedly."</p>
<p>The app.config for the WPF and Unit Test Projects look like this:</p>
<pre><code><system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="WSHttpBinding_ITaskManagement" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard"
maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"
allowCookies="false">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<reliableSession ordered="true" inactivityTimeout="00:10:00"
enabled="false" />
<security mode="Message">
<transport clientCredentialType="Windows" proxyCredentialType="None"
realm="" />
<message clientCredentialType="Windows" negotiateServiceCredential="true"
algorithmSuite="Default" establishSecurityContext="true" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:9999/TaskManagement.svc"
binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_ITaskManagement"
contract="TaskManagement.ITaskManagement" name="WSHttpBinding_ITaskManagement">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
</client>
</system.serviceModel>
</code></pre>
<p>and the web.config of the WCF Service looks like this:</p>
<pre><code> <system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="InternetBasedWcfServices.TaskManagementBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
<behavior name="InternetBasedWcfServices.ScheduleManagementBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="InternetBasedWcfServices.TaskManagementBehavior"
name="InternetBasedWcfServices.TaskManagement">
<endpoint address="" binding="wsHttpBinding" contract="InternetBasedWcfServices.ITaskManagement">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
<service behaviorConfiguration="InternetBasedWcfServices.ScheduleManagementBehavior"
name="InternetBasedWcfServices.ScheduleManagement">
<endpoint address="" binding="wsHttpBinding" contract="InternetBasedWcfServices.IScheduleManagement">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
</system.serviceModel>
</code></pre>
<p>This is not the first time this has happened, and I'm guessing it is a configuration issue. But each time I've usually just blown away my service and put it back or created a new service project. Then everything works wonderfully. If anyone has any ideas, that would be awesome. Thx.</p>
<p>**</p>
<blockquote>
<p>Updated: I've added comments for more
of my troubleshooting on this problem.
When an answer is available, if the
answer is unpublished, I'll add it as
an official "answer".</p>
</blockquote>
<p>**</p>
|
[
{
"answer_id": 232335,
"author": "Timothy Khouri",
"author_id": 11917,
"author_profile": "https://Stackoverflow.com/users/11917",
"pm_score": 1,
"selected": false,
"text": "<p>I could be way off, but it might be a security thing... I've gotten that error before, and I solved it... but I was up for days trying to get a lot of different bugs worked out.</p>\n\n<p>I have a sample article doing something basic, but I'm using net.tcp (with security set to \"None\") here: <a href=\"http://www.singingeels.com/Articles/Duplex_WCF_Services_Hosted_in_IIS_Using_NetTcp.aspx\" rel=\"nofollow noreferrer\">Duplex WCF Services Hosted in IIS Using Net.Tcp</a></p>\n\n<p>Also, where are you getting the error... is it on the \".Close()\" line, or the \".GetTasks().ToString()\" line?</p>\n\n<p>Another thing you can check is to simply telnet to localhost on port 9999 to see if the service is listening for incomming connections altogether.</p>\n"
},
{
"answer_id": 232412,
"author": "jezell",
"author_id": 27453,
"author_profile": "https://Stackoverflow.com/users/27453",
"pm_score": 2,
"selected": false,
"text": "<p>Make sure that nothing that isn't a FaultException gets thrown and passed back to the client.</p>\n"
},
{
"answer_id": 234584,
"author": "Adron",
"author_id": 29345,
"author_profile": "https://Stackoverflow.com/users/29345",
"pm_score": 5,
"selected": true,
"text": "<p>I Found the Answer</p>\n\n<p>Ok, not sure if it is kewl answering my own question, but here we go. For some reason the enumeration needed to be marked with the [EnumMember] Attributes as below:</p>\n\n<pre><code>[DataContract]\npublic enum Priority\n{\n [EnumMember]\n Low,\n [EnumMember]\n Medium,\n [EnumMember]\n High\n}\n</code></pre>\n\n<p>Once I did that my tests and services could be called without the error occurring. I'm still not sure why that specific error was displayed. The error doesn't seem to align in any correlation with the functional reason the error occurred, but this fix definitely smoothed everything out.</p>\n"
},
{
"answer_id": 419609,
"author": "Sam",
"author_id": 7021,
"author_profile": "https://Stackoverflow.com/users/7021",
"pm_score": 3,
"selected": false,
"text": "<p>As you yourself noted, if you mark the enum as DataContract, you'll have to mark the items, too.</p>\n\n<p>As an alternative you could just remove the [DataContract] before your enum like this:</p>\n\n<pre><code>public enum Priority\n{ \n Low, \n Medium, \n High\n}\n</code></pre>\n\n<p>This would work, too, because in this case WCF handles the enum by itself. If you mark it as [DataContract] you have to mark every item as you noticed yourself.</p>\n"
},
{
"answer_id": 2593256,
"author": "Rohini",
"author_id": 311070,
"author_profile": "https://Stackoverflow.com/users/311070",
"pm_score": 1,
"selected": false,
"text": "<p>Sometimes this error could be very misleading. Common WCF Exception : Connection Unexpectedly Closed can be occurred when the culture is not set correctly or in string formating as well.</p>\n\n<p>Following fails: </p>\n\n<pre><code>new DateTime(adate.Year, adate.Month, firstday).ToString(\"d\", cultureInfo);\n</code></pre>\n\n<p>while this works:</p>\n\n<pre><code>CultureInfo culture = new CultureInfo(this.aculture.Name); \nConvert.ToString(new DateTime(adate.Year, adate.Month, firstday), culture);\n</code></pre>\n"
},
{
"answer_id": 7155025,
"author": "A-Dubb",
"author_id": 389103,
"author_profile": "https://Stackoverflow.com/users/389103",
"pm_score": 2,
"selected": false,
"text": "<p>I've noticed this when using LINQ and calls like Select, Where, etc. without an immediate call to .ToList() or ToArray(). Iterators will get you in trouble. They're not native types that WCF knows how to work with like List, Array, etc. They're of type WhereEnumerable or something. Just keep that in mind when sending back results from NHibernate or Entity Framework. Hope this helps someone. Took me hours to figure out.</p>\n"
},
{
"answer_id": 7817781,
"author": "squig",
"author_id": 32254,
"author_profile": "https://Stackoverflow.com/users/32254",
"pm_score": 3,
"selected": false,
"text": "<p>I was getting this error when returning a large payload, it turned out to be the DataContractSerialiser stopping mid stream as it had hit the default maxItemsInObjectGraph setting, adding the folloing to my endpoint behavour fixed the problem</p>\n\n<pre><code><dataContractSerializer maxItemsInObjectGraph=\"2147483647\" />\n</code></pre>\n"
},
{
"answer_id": 9524172,
"author": "Stewart Anderson",
"author_id": 805922,
"author_profile": "https://Stackoverflow.com/users/805922",
"pm_score": 0,
"selected": false,
"text": "<p>Someone on this thread posted that adding this element to the endpoint behavior fixed the issue.</p>\n\n<pre><code><dataContractSerializer maxItemsInObjectGraph=\"2147483647\" />\n</code></pre>\n\n<p>This worked but it had to be added not only to the endpoint behavior but the service behavior too (which makes sense since that is where the serialization will take place).</p>\n\n<p>If it was added to the service only I got this error \"Maximum number of items that can be serialized or deserialized in an object graph is '65536'. Change the object graph or increase the MaxItemsInObjectGraph quota.\"</p>\n\n<p>If added to the endpoint only I still got the connection unexpectedly closed error.</p>\n"
},
{
"answer_id": 10117740,
"author": "rusty",
"author_id": 332610,
"author_profile": "https://Stackoverflow.com/users/332610",
"pm_score": 2,
"selected": false,
"text": "<p>In case someone else is also doing this, I returning a List of objects that were generated by linq to sql / dbml file. I just had to enable serialization in the dbml file : </p>\n\n<p><a href=\"http://blogs.msdn.com/b/wriju/archive/2007/11/27/linq-to-sql-enabling-dbml-file-for-wcf.aspx\" rel=\"nofollow\">http://blogs.msdn.com/b/wriju/archive/2007/11/27/linq-to-sql-enabling-dbml-file-for-wcf.aspx</a></p>\n\n<p>cheers</p>\n"
},
{
"answer_id": 12473530,
"author": "Arun M",
"author_id": 63709,
"author_profile": "https://Stackoverflow.com/users/63709",
"pm_score": 1,
"selected": false,
"text": "<p>Another reason: This exception comes up if you have <code>DataContract/DataMember</code> attributes on an <code>Interface</code> instead of a concrete type (<a href=\"https://stackoverflow.com/questions/3720474/why-cant-my-operation-contracts-in-my-wcf-client-take-interfaces-as-parameters\">terrible idea</a>, don't do it) and you are trying to serialize the <code>Concrete type</code>.</p>\n"
},
{
"answer_id": 13936160,
"author": "Chuck Herrington",
"author_id": 1498832,
"author_profile": "https://Stackoverflow.com/users/1498832",
"pm_score": 1,
"selected": false,
"text": "<p>in my case i was returning a custom class object, one of the members of which was a data table. and if you dont have a name on the datatable it will throw this error.</p>\n\n<pre><code>Dim oTable As DataTable = New DataTable 'this wont serialize\nDim oTable As DataTable = New DataTable(\"MyTable\") 'this will serialize\n</code></pre>\n"
},
{
"answer_id": 18652629,
"author": "tkerwood",
"author_id": 463425,
"author_profile": "https://Stackoverflow.com/users/463425",
"pm_score": 2,
"selected": false,
"text": "<p>In my case my data contract had a [datamember] property that did not have a set method. I used a WCF trace to get the real error. <a href=\"https://stackoverflow.com/a/4271528/463425\">https://stackoverflow.com/a/4271528/463425</a>. I hope this helps someone.</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/232078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29345/"
] |
I have three projects. One is a WCF Services Project, one is a WPF Project, and one is a Microsoft Unit Testing Project. I setup the WCF Services project with a data object that looks like this:
```
[DataContract]
public enum Priority
{
Low,
Medium,
High
}
[DataContract]
public struct TimeInfo
{
[DataMember]
public Int16 EstimatedHours { get; set; }
[DataMember]
public Int16 ActualHours { get; set; }
[DataMember]
public DateTime StartDate { get; set; }
[DataMember]
public DateTime EndDate { get; set; }
[DataMember]
public DateTime CompletionDate { get; set; }
}
[DataContract]
public class Task
{
[DataMember]
public string Title { get; set; }
[DataMember]
public string Description { get; set; }
[DataMember]
public Priority Priority { get; set; }
[DataMember]
public TimeInfo TimeInformation { get; set; }
[DataMember]
public Decimal Cost { get; set; }
}
```
My contract looks like this:
```
[ServiceContract]
public interface ITaskManagement
{
[OperationContract]
List<Task> GetTasks();
[OperationContract]
void CreateTask(Task taskToCreate);
[OperationContract]
void UpdateTask(Task taskToCreate);
[OperationContract]
void DeleteTask(Task taskToDelete);
}
```
When I try to use the service in either the WPF Application or the Unit Test Project with this code:
```
var client = new TaskManagementClient();
textBox1.Text = client.GetTasks().ToString();
client.Close();
```
I get the following error: "The underlying connection was closed: The connection was closed unexpectedly."
The app.config for the WPF and Unit Test Projects look like this:
```
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="WSHttpBinding_ITaskManagement" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard"
maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"
allowCookies="false">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<reliableSession ordered="true" inactivityTimeout="00:10:00"
enabled="false" />
<security mode="Message">
<transport clientCredentialType="Windows" proxyCredentialType="None"
realm="" />
<message clientCredentialType="Windows" negotiateServiceCredential="true"
algorithmSuite="Default" establishSecurityContext="true" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:9999/TaskManagement.svc"
binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_ITaskManagement"
contract="TaskManagement.ITaskManagement" name="WSHttpBinding_ITaskManagement">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
</client>
</system.serviceModel>
```
and the web.config of the WCF Service looks like this:
```
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="InternetBasedWcfServices.TaskManagementBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
<behavior name="InternetBasedWcfServices.ScheduleManagementBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="InternetBasedWcfServices.TaskManagementBehavior"
name="InternetBasedWcfServices.TaskManagement">
<endpoint address="" binding="wsHttpBinding" contract="InternetBasedWcfServices.ITaskManagement">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
<service behaviorConfiguration="InternetBasedWcfServices.ScheduleManagementBehavior"
name="InternetBasedWcfServices.ScheduleManagement">
<endpoint address="" binding="wsHttpBinding" contract="InternetBasedWcfServices.IScheduleManagement">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
</system.serviceModel>
```
This is not the first time this has happened, and I'm guessing it is a configuration issue. But each time I've usually just blown away my service and put it back or created a new service project. Then everything works wonderfully. If anyone has any ideas, that would be awesome. Thx.
\*\*
>
> Updated: I've added comments for more
> of my troubleshooting on this problem.
> When an answer is available, if the
> answer is unpublished, I'll add it as
> an official "answer".
>
>
>
\*\*
|
I Found the Answer
Ok, not sure if it is kewl answering my own question, but here we go. For some reason the enumeration needed to be marked with the [EnumMember] Attributes as below:
```
[DataContract]
public enum Priority
{
[EnumMember]
Low,
[EnumMember]
Medium,
[EnumMember]
High
}
```
Once I did that my tests and services could be called without the error occurring. I'm still not sure why that specific error was displayed. The error doesn't seem to align in any correlation with the functional reason the error occurred, but this fix definitely smoothed everything out.
|
232,083 |
<p>Is there a way to know which file is being selected in windows explorer? I've been looking at the tutorial posted here <a href="https://stackoverflow.com/questions/140312/tutorial-for-windows-shell-extensions">Idiots guide to ...</a> but the actions described are:</p>
<p>hover</p>
<p>context </p>
<p>menu properties </p>
<p>drag</p>
<p>drag and drop</p>
<p>I wonder if is there a method that get invoked when a file is selected. For instance to create a thumbnail view of the file. </p>
<p>Thanks.</p>
|
[
{
"answer_id": 232335,
"author": "Timothy Khouri",
"author_id": 11917,
"author_profile": "https://Stackoverflow.com/users/11917",
"pm_score": 1,
"selected": false,
"text": "<p>I could be way off, but it might be a security thing... I've gotten that error before, and I solved it... but I was up for days trying to get a lot of different bugs worked out.</p>\n\n<p>I have a sample article doing something basic, but I'm using net.tcp (with security set to \"None\") here: <a href=\"http://www.singingeels.com/Articles/Duplex_WCF_Services_Hosted_in_IIS_Using_NetTcp.aspx\" rel=\"nofollow noreferrer\">Duplex WCF Services Hosted in IIS Using Net.Tcp</a></p>\n\n<p>Also, where are you getting the error... is it on the \".Close()\" line, or the \".GetTasks().ToString()\" line?</p>\n\n<p>Another thing you can check is to simply telnet to localhost on port 9999 to see if the service is listening for incomming connections altogether.</p>\n"
},
{
"answer_id": 232412,
"author": "jezell",
"author_id": 27453,
"author_profile": "https://Stackoverflow.com/users/27453",
"pm_score": 2,
"selected": false,
"text": "<p>Make sure that nothing that isn't a FaultException gets thrown and passed back to the client.</p>\n"
},
{
"answer_id": 234584,
"author": "Adron",
"author_id": 29345,
"author_profile": "https://Stackoverflow.com/users/29345",
"pm_score": 5,
"selected": true,
"text": "<p>I Found the Answer</p>\n\n<p>Ok, not sure if it is kewl answering my own question, but here we go. For some reason the enumeration needed to be marked with the [EnumMember] Attributes as below:</p>\n\n<pre><code>[DataContract]\npublic enum Priority\n{\n [EnumMember]\n Low,\n [EnumMember]\n Medium,\n [EnumMember]\n High\n}\n</code></pre>\n\n<p>Once I did that my tests and services could be called without the error occurring. I'm still not sure why that specific error was displayed. The error doesn't seem to align in any correlation with the functional reason the error occurred, but this fix definitely smoothed everything out.</p>\n"
},
{
"answer_id": 419609,
"author": "Sam",
"author_id": 7021,
"author_profile": "https://Stackoverflow.com/users/7021",
"pm_score": 3,
"selected": false,
"text": "<p>As you yourself noted, if you mark the enum as DataContract, you'll have to mark the items, too.</p>\n\n<p>As an alternative you could just remove the [DataContract] before your enum like this:</p>\n\n<pre><code>public enum Priority\n{ \n Low, \n Medium, \n High\n}\n</code></pre>\n\n<p>This would work, too, because in this case WCF handles the enum by itself. If you mark it as [DataContract] you have to mark every item as you noticed yourself.</p>\n"
},
{
"answer_id": 2593256,
"author": "Rohini",
"author_id": 311070,
"author_profile": "https://Stackoverflow.com/users/311070",
"pm_score": 1,
"selected": false,
"text": "<p>Sometimes this error could be very misleading. Common WCF Exception : Connection Unexpectedly Closed can be occurred when the culture is not set correctly or in string formating as well.</p>\n\n<p>Following fails: </p>\n\n<pre><code>new DateTime(adate.Year, adate.Month, firstday).ToString(\"d\", cultureInfo);\n</code></pre>\n\n<p>while this works:</p>\n\n<pre><code>CultureInfo culture = new CultureInfo(this.aculture.Name); \nConvert.ToString(new DateTime(adate.Year, adate.Month, firstday), culture);\n</code></pre>\n"
},
{
"answer_id": 7155025,
"author": "A-Dubb",
"author_id": 389103,
"author_profile": "https://Stackoverflow.com/users/389103",
"pm_score": 2,
"selected": false,
"text": "<p>I've noticed this when using LINQ and calls like Select, Where, etc. without an immediate call to .ToList() or ToArray(). Iterators will get you in trouble. They're not native types that WCF knows how to work with like List, Array, etc. They're of type WhereEnumerable or something. Just keep that in mind when sending back results from NHibernate or Entity Framework. Hope this helps someone. Took me hours to figure out.</p>\n"
},
{
"answer_id": 7817781,
"author": "squig",
"author_id": 32254,
"author_profile": "https://Stackoverflow.com/users/32254",
"pm_score": 3,
"selected": false,
"text": "<p>I was getting this error when returning a large payload, it turned out to be the DataContractSerialiser stopping mid stream as it had hit the default maxItemsInObjectGraph setting, adding the folloing to my endpoint behavour fixed the problem</p>\n\n<pre><code><dataContractSerializer maxItemsInObjectGraph=\"2147483647\" />\n</code></pre>\n"
},
{
"answer_id": 9524172,
"author": "Stewart Anderson",
"author_id": 805922,
"author_profile": "https://Stackoverflow.com/users/805922",
"pm_score": 0,
"selected": false,
"text": "<p>Someone on this thread posted that adding this element to the endpoint behavior fixed the issue.</p>\n\n<pre><code><dataContractSerializer maxItemsInObjectGraph=\"2147483647\" />\n</code></pre>\n\n<p>This worked but it had to be added not only to the endpoint behavior but the service behavior too (which makes sense since that is where the serialization will take place).</p>\n\n<p>If it was added to the service only I got this error \"Maximum number of items that can be serialized or deserialized in an object graph is '65536'. Change the object graph or increase the MaxItemsInObjectGraph quota.\"</p>\n\n<p>If added to the endpoint only I still got the connection unexpectedly closed error.</p>\n"
},
{
"answer_id": 10117740,
"author": "rusty",
"author_id": 332610,
"author_profile": "https://Stackoverflow.com/users/332610",
"pm_score": 2,
"selected": false,
"text": "<p>In case someone else is also doing this, I returning a List of objects that were generated by linq to sql / dbml file. I just had to enable serialization in the dbml file : </p>\n\n<p><a href=\"http://blogs.msdn.com/b/wriju/archive/2007/11/27/linq-to-sql-enabling-dbml-file-for-wcf.aspx\" rel=\"nofollow\">http://blogs.msdn.com/b/wriju/archive/2007/11/27/linq-to-sql-enabling-dbml-file-for-wcf.aspx</a></p>\n\n<p>cheers</p>\n"
},
{
"answer_id": 12473530,
"author": "Arun M",
"author_id": 63709,
"author_profile": "https://Stackoverflow.com/users/63709",
"pm_score": 1,
"selected": false,
"text": "<p>Another reason: This exception comes up if you have <code>DataContract/DataMember</code> attributes on an <code>Interface</code> instead of a concrete type (<a href=\"https://stackoverflow.com/questions/3720474/why-cant-my-operation-contracts-in-my-wcf-client-take-interfaces-as-parameters\">terrible idea</a>, don't do it) and you are trying to serialize the <code>Concrete type</code>.</p>\n"
},
{
"answer_id": 13936160,
"author": "Chuck Herrington",
"author_id": 1498832,
"author_profile": "https://Stackoverflow.com/users/1498832",
"pm_score": 1,
"selected": false,
"text": "<p>in my case i was returning a custom class object, one of the members of which was a data table. and if you dont have a name on the datatable it will throw this error.</p>\n\n<pre><code>Dim oTable As DataTable = New DataTable 'this wont serialize\nDim oTable As DataTable = New DataTable(\"MyTable\") 'this will serialize\n</code></pre>\n"
},
{
"answer_id": 18652629,
"author": "tkerwood",
"author_id": 463425,
"author_profile": "https://Stackoverflow.com/users/463425",
"pm_score": 2,
"selected": false,
"text": "<p>In my case my data contract had a [datamember] property that did not have a set method. I used a WCF trace to get the real error. <a href=\"https://stackoverflow.com/a/4271528/463425\">https://stackoverflow.com/a/4271528/463425</a>. I hope this helps someone.</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/232083",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20654/"
] |
Is there a way to know which file is being selected in windows explorer? I've been looking at the tutorial posted here [Idiots guide to ...](https://stackoverflow.com/questions/140312/tutorial-for-windows-shell-extensions) but the actions described are:
hover
context
menu properties
drag
drag and drop
I wonder if is there a method that get invoked when a file is selected. For instance to create a thumbnail view of the file.
Thanks.
|
I Found the Answer
Ok, not sure if it is kewl answering my own question, but here we go. For some reason the enumeration needed to be marked with the [EnumMember] Attributes as below:
```
[DataContract]
public enum Priority
{
[EnumMember]
Low,
[EnumMember]
Medium,
[EnumMember]
High
}
```
Once I did that my tests and services could be called without the error occurring. I'm still not sure why that specific error was displayed. The error doesn't seem to align in any correlation with the functional reason the error occurred, but this fix definitely smoothed everything out.
|
232,140 |
<p>My <sub>crappy</sub> web host did some upgrades the other day and some settings have gone awry, because looking at our company's wiki (MediaWiki), every quote is being escaped with a backslashes. It's not even just data which is being posted (i.e.: the articles) which are affected, but also the standard MediaWiki text. For example,</p>
<blockquote>
<p>You\'ve followed a link to a page that doesn\'t exist yet. To create the page, start typing in the box below (see the help page for more info). If you are here by mistake, just click your browser\'s \'\'\'back\'\'\' button.</p>
</blockquote>
<p>The first thing I did was disable <code>magic_quotes_gpc</code> AND <code>magic_quotes_runtime</code> using a <code>.htaccess</code> file, but this is still occurring. My <code>php_info()</code> reports this:</p>
<pre><code>Setting Local Value Master Value
magic_quotes_gpc Off On
magic_quotes_runtime Off On
magic_quotes_sybase Off Off
</code></pre>
<p>Any ideas?</p>
|
[
{
"answer_id": 232149,
"author": "Andy Lester",
"author_id": 8454,
"author_profile": "https://Stackoverflow.com/users/8454",
"pm_score": 0,
"selected": false,
"text": "<p>Perhaps something else is calling set_magic_quotes_runtime().</p>\n"
},
{
"answer_id": 232242,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 1,
"selected": false,
"text": "<p>You'll need to get them to change the master value, or handle it yourself. I don't believe you can set <code>magic_quotes_gpc()</code> at runtime for super globals. (Setting it at runtime will strip things like database/files, but not the globals.)</p>\n\n<pre><code>if (ini_get('magic_quotes_gpc') ) {\n foreach($_GET as $key=>$value) {\n $_GET[$key] = stripslashes($value);\n }\n} // etc...\n</code></pre>\n"
},
{
"answer_id": 232461,
"author": "Lucas Oman",
"author_id": 6726,
"author_profile": "https://Stackoverflow.com/users/6726",
"pm_score": 2,
"selected": false,
"text": "<p>You may want to confirm that the data in your DB hasn't been corrupted. If you were addslash()ing your data when, unbeknownst to you, magic_quotes had been turned on, then you'd be double-slashifying data going into your DB.</p>\n"
},
{
"answer_id": 232789,
"author": "troelskn",
"author_id": 18180,
"author_profile": "https://Stackoverflow.com/users/18180",
"pm_score": 2,
"selected": true,
"text": "<p>If PHP flags are set with <code>php_admin_flag</code>/<code>php_admin_value</code>, you can't change it from a <code>.htaccess</code> file. This has caused me some headache before. Either disable it in <code>php.ini</code> or undo magic quotes in runtime:\n<a href=\"http://talks.php.net/show/php-best-practices/26\" rel=\"nofollow noreferrer\">http://talks.php.net/show/php-best-practices/26</a></p>\n"
},
{
"answer_id": 261196,
"author": "Tim",
"author_id": 33914,
"author_profile": "https://Stackoverflow.com/users/33914",
"pm_score": -1,
"selected": false,
"text": "<p>I use stripslases() to remove slashes when displaying.</p>\n\n<p><a href=\"http://www.php.net/manual/en/function.stripslashes.php\" rel=\"nofollow noreferrer\">http://www.php.net/manual/en/function.stripslashes.php</a></p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/232140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9021/"
] |
My crappy web host did some upgrades the other day and some settings have gone awry, because looking at our company's wiki (MediaWiki), every quote is being escaped with a backslashes. It's not even just data which is being posted (i.e.: the articles) which are affected, but also the standard MediaWiki text. For example,
>
> You\'ve followed a link to a page that doesn\'t exist yet. To create the page, start typing in the box below (see the help page for more info). If you are here by mistake, just click your browser\'s \'\'\'back\'\'\' button.
>
>
>
The first thing I did was disable `magic_quotes_gpc` AND `magic_quotes_runtime` using a `.htaccess` file, but this is still occurring. My `php_info()` reports this:
```
Setting Local Value Master Value
magic_quotes_gpc Off On
magic_quotes_runtime Off On
magic_quotes_sybase Off Off
```
Any ideas?
|
If PHP flags are set with `php_admin_flag`/`php_admin_value`, you can't change it from a `.htaccess` file. This has caused me some headache before. Either disable it in `php.ini` or undo magic quotes in runtime:
<http://talks.php.net/show/php-best-practices/26>
|
232,144 |
<p>I have a volunteers_2009 table that lists all the volunteers and a venues table that lists the venues that a volunteer can be assigned to, they are only assigned to one.</p>
<p>What I want to do, is print out the number of volunteers assigned to each venue.</p>
<p>I want it to print out like this:</p>
<p>Name of Venue: # of volunteers</p>
<p>table: volunteers_2009
columns: id, name, <code>venue_id</code></p>
<p>table: venues
columns: id, venue_name</p>
<p>They relate by <code>volunteers_2009.venue_id = venues.id</code></p>
<p>This is what I have but it is not working properly.</p>
<pre><code>$sql = "SELECT venues.venue_name as 'Venue', COUNT(volunteers_2009.id) as 'Number Of
Volunteers' FROM venues ven JOIN volunteers_2009 vol ON
(venues.id=volunteers_2009.venue_id) GROUP BY venues.venue_name ORDER BY
venues.venue_name ASC";
$result = mysql_query($sql);
while(list($name,$vols) = mysql_fetch_array($result)) {
print '<p>'.$name.': '.$vols.'</p>';
}
</code></pre>
|
[
{
"answer_id": 232159,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 3,
"selected": true,
"text": "<p>Not a MySQL person so this may be really wrong, but when you give your table an alias, don't you then need to refer to it by that name.</p>\n\n<pre><code>$sql = \"SELECT ven.venue_name as 'Venue', COUNT(vol.id) as 'Number Of \nVolunteers' FROM venues ven JOIN volunteers_2009 vol ON \n(ven.id=vol.venue_id) GROUP BY ven.venue_name ORDER BY ven.venue_name ASC\";\n</code></pre>\n"
},
{
"answer_id": 232174,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 0,
"selected": false,
"text": "<pre><code>$query = \"SELECT ven.venue_name AS 'Venue', count(*) AS 'Number of venues'\n FROM volunteers_2009 AS vol, venues AS ven WHERE vol.venue_id = ven.id \n GROUP BY ven.venue_name\";\n</code></pre>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/232144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26130/"
] |
I have a volunteers\_2009 table that lists all the volunteers and a venues table that lists the venues that a volunteer can be assigned to, they are only assigned to one.
What I want to do, is print out the number of volunteers assigned to each venue.
I want it to print out like this:
Name of Venue: # of volunteers
table: volunteers\_2009
columns: id, name, `venue_id`
table: venues
columns: id, venue\_name
They relate by `volunteers_2009.venue_id = venues.id`
This is what I have but it is not working properly.
```
$sql = "SELECT venues.venue_name as 'Venue', COUNT(volunteers_2009.id) as 'Number Of
Volunteers' FROM venues ven JOIN volunteers_2009 vol ON
(venues.id=volunteers_2009.venue_id) GROUP BY venues.venue_name ORDER BY
venues.venue_name ASC";
$result = mysql_query($sql);
while(list($name,$vols) = mysql_fetch_array($result)) {
print '<p>'.$name.': '.$vols.'</p>';
}
```
|
Not a MySQL person so this may be really wrong, but when you give your table an alias, don't you then need to refer to it by that name.
```
$sql = "SELECT ven.venue_name as 'Venue', COUNT(vol.id) as 'Number Of
Volunteers' FROM venues ven JOIN volunteers_2009 vol ON
(ven.id=vol.venue_id) GROUP BY ven.venue_name ORDER BY ven.venue_name ASC";
```
|
232,161 |
<p>I'm currently developing an application that is comprised of five separate executables that communicate via ActiveMQ. I have a Visual Studio Solution that contains the five executable projects. One of the projects (the launcher.exe) launches the other four projects from their local folders as separate processes. As such, the launcher project is set as the "Startup Project" and, as a result, it's the only one I can set break points in and debug due to my limited knowledge of VS2005.</p>
<p>Is there a way to set multiple breakpoints across my five c++ projects in my single VS solution and debug them at the same time if the launcher project is the only project executed from VS? </p>
<p><strong><em>Note:</em></strong> <em>Manually starting new instances of each project via Visual Studio is not an option since their execution needs to be synchronized by the launcher.exe.</em></p>
<p>I apologize if this is convoluted, it's the best I can explain it. Thanks in advance for your help! </p>
|
[
{
"answer_id": 232176,
"author": "Charlie",
"author_id": 18529,
"author_profile": "https://Stackoverflow.com/users/18529",
"pm_score": 4,
"selected": true,
"text": "<p>What you need is in the Tools menu: Attach to Process. This gives you a list of running processes and allows you to attach your debugger to those processes.</p>\n\n<p>For local debugging, Transport and Qualifier should keep their default values. The Attach To value just above the list determines which type of debugging you'll be doing (native or managed are the most common types), and normally the debugger can figure out a good default here as well.</p>\n\n<p>The main interesting part is the list of processes - look in this list for the sub-processes you want to debug. Once you've found and selected the process, click Attach in the lower right corner (or just double-click the process), and the debugger will attach to that process and start debugging it.</p>\n\n<p>You'll probably also want to enable the Debug Location toolbar, which provides a way to change the focus of the debugger to the various processes and threads you're attached to. Multi-process debugging within one Visual Studio instance can be tricky, so you can always consider starting separate instances to debug each different process.</p>\n\n<p>Another tricky aspect of this can be debugging the initial startup of the sub-processes. Often the thing you want to debug happens before you can get the debugger attached, so you need some way to cause the process to wait for you to be ready. An easy way to do this in C++ is to use the IsDebuggerPresent function. Try adding this code to the very beginning of your main() function (or equivalent):</p>\n\n<pre><code>while( !IsDebuggerPresent() )\n Sleep( 500 );\n</code></pre>\n\n<p>Or try this code for C#:</p>\n\n<pre><code>while( !System.Diagnostics.Debugger.IsAttached )\n System.Threading.Thread.Sleep( 500 );\n</code></pre>\n"
},
{
"answer_id": 232180,
"author": "Eclipse",
"author_id": 8701,
"author_profile": "https://Stackoverflow.com/users/8701",
"pm_score": 1,
"selected": false,
"text": "<p>You can pick one at a time by running launcher manually (outside of visual studio, or with <ctrl-f5>) and then attaching to the process you want to debug once it's started. If it's one of the projects in your solution, you can set breakpoints and they'll get picked up when you attach the debugger.</p>\n"
},
{
"answer_id": 232268,
"author": "Joel Lucsy",
"author_id": 645,
"author_profile": "https://Stackoverflow.com/users/645",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://blogs.msdn.com/saraford/archive/2008/07/28/did-you-know-you-can-start-debugging-multiple-projects-268.aspx\" rel=\"nofollow noreferrer\">Did you know… You can start debugging multiple projects? - #268</a></p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/232161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/191808/"
] |
I'm currently developing an application that is comprised of five separate executables that communicate via ActiveMQ. I have a Visual Studio Solution that contains the five executable projects. One of the projects (the launcher.exe) launches the other four projects from their local folders as separate processes. As such, the launcher project is set as the "Startup Project" and, as a result, it's the only one I can set break points in and debug due to my limited knowledge of VS2005.
Is there a way to set multiple breakpoints across my five c++ projects in my single VS solution and debug them at the same time if the launcher project is the only project executed from VS?
***Note:*** *Manually starting new instances of each project via Visual Studio is not an option since their execution needs to be synchronized by the launcher.exe.*
I apologize if this is convoluted, it's the best I can explain it. Thanks in advance for your help!
|
What you need is in the Tools menu: Attach to Process. This gives you a list of running processes and allows you to attach your debugger to those processes.
For local debugging, Transport and Qualifier should keep their default values. The Attach To value just above the list determines which type of debugging you'll be doing (native or managed are the most common types), and normally the debugger can figure out a good default here as well.
The main interesting part is the list of processes - look in this list for the sub-processes you want to debug. Once you've found and selected the process, click Attach in the lower right corner (or just double-click the process), and the debugger will attach to that process and start debugging it.
You'll probably also want to enable the Debug Location toolbar, which provides a way to change the focus of the debugger to the various processes and threads you're attached to. Multi-process debugging within one Visual Studio instance can be tricky, so you can always consider starting separate instances to debug each different process.
Another tricky aspect of this can be debugging the initial startup of the sub-processes. Often the thing you want to debug happens before you can get the debugger attached, so you need some way to cause the process to wait for you to be ready. An easy way to do this in C++ is to use the IsDebuggerPresent function. Try adding this code to the very beginning of your main() function (or equivalent):
```
while( !IsDebuggerPresent() )
Sleep( 500 );
```
Or try this code for C#:
```
while( !System.Diagnostics.Debugger.IsAttached )
System.Threading.Thread.Sleep( 500 );
```
|
232,168 |
<p>I'm trying to get a file with ant, using the get property. I'm running apache 2, and I can get the file from the indicated URL using wget and firefox, but ant gives me the following error:</p>
<pre><code>[get] Error opening connection java.io.IOException:
Server returned HTTP response code: 503 for URL: http://localhost/jars/jai_core.jar
</code></pre>
<p>This is what I'm doing in my build.xml:</p>
<pre><code><get src="http://localhost/jars/jai_core.jar"
dest="${build.dir}/lib/jai_core.jar"
usetimestamp="true"/>
</code></pre>
<p>Any idea what could be going wrong?</p>
<p><strong>EDIT:</strong> On to something. When I provide the full host name of my box instead of localhost, it works.</p>
|
[
{
"answer_id": 232220,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 3,
"selected": true,
"text": "<p>503 is <em>Service Unavailable</em>, which probably means that the <code>src</code> URL isn't getting interpreted properly and sent by the ANT task or perhaps the JRE.</p>\n\n<p>Here are some things to try:</p>\n\n<ul>\n<li><p>As always, with ANT, execute the smallest possible build.xml with <strong>-verbose</strong> to see if that gives any more information, <strong>-debug</strong> for even more information.</p></li>\n<li><p>Try the <code>verbose=\"true\"</code> attribute on the task.</p></li>\n<li><p>use \"<a href=\"http://127.0.0.1/jars/jai_core.jar\" rel=\"nofollow noreferrer\">http://127.0.0.1/jars/jai_core.jar</a>\" - depending on what version of the java runtime ANT is executing under, 'localhost' may not be getting resolved correctly.</p></li>\n<li><p>Drop the <code>usetimestamp</code> attribute just to see if it changes behavior.</p></li>\n<li><p>Use another Java based application to try to perform the GET and compare results.</p></li>\n</ul>\n"
},
{
"answer_id": 232299,
"author": "mhawke",
"author_id": 21945,
"author_profile": "https://Stackoverflow.com/users/21945",
"pm_score": 0,
"selected": false,
"text": "<p>The HTTP request might be going through a proxy which is rejecting the request. Alternatively <code>ant</code> might not be using a proxy where it should.</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/232168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3434/"
] |
I'm trying to get a file with ant, using the get property. I'm running apache 2, and I can get the file from the indicated URL using wget and firefox, but ant gives me the following error:
```
[get] Error opening connection java.io.IOException:
Server returned HTTP response code: 503 for URL: http://localhost/jars/jai_core.jar
```
This is what I'm doing in my build.xml:
```
<get src="http://localhost/jars/jai_core.jar"
dest="${build.dir}/lib/jai_core.jar"
usetimestamp="true"/>
```
Any idea what could be going wrong?
**EDIT:** On to something. When I provide the full host name of my box instead of localhost, it works.
|
503 is *Service Unavailable*, which probably means that the `src` URL isn't getting interpreted properly and sent by the ANT task or perhaps the JRE.
Here are some things to try:
* As always, with ANT, execute the smallest possible build.xml with **-verbose** to see if that gives any more information, **-debug** for even more information.
* Try the `verbose="true"` attribute on the task.
* use "<http://127.0.0.1/jars/jai_core.jar>" - depending on what version of the java runtime ANT is executing under, 'localhost' may not be getting resolved correctly.
* Drop the `usetimestamp` attribute just to see if it changes behavior.
* Use another Java based application to try to perform the GET and compare results.
|
232,171 |
<p>I have an IQueryable and an object of type T.</p>
<p>I want to do IQueryable().Where(o => o.GetProperty(fieldName) == objectOfTypeT.GetProperty(fieldName))</p>
<p>so ...</p>
<pre><code>public IQueryable<T> DoWork<T>(string fieldName)
where T : EntityObject
{
...
T objectOfTypeT = ...;
....
return SomeIQueryable<T>().Where(o => o.GetProperty(fieldName) == objectOfTypeT.GetProperty(fieldName));
}
</code></pre>
<p>Fyi, GetProperty isn't a valid function. I need something which performs this function.</p>
<p>Am I having a Friday afternoon brain melt or is this a complex thing to do?</p>
<hr>
<p>objectOfTypeT I can do the following ...</p>
<pre><code>var matchToValue = Expression.Lambda(ParameterExpression
.Property(ParameterExpression.Constant(item), "CustomerKey"))
.Compile().DynamicInvoke();
</code></pre>
<p>Which works perfectly,now I just need the second part:</p>
<p>return SomeIQueryable().Where(o => <strong>o.GetProperty(fieldName)</strong> == matchValue);</p>
|
[
{
"answer_id": 232304,
"author": "JTew",
"author_id": 25372,
"author_profile": "https://Stackoverflow.com/users/25372",
"pm_score": 0,
"selected": false,
"text": "<p>From what I can see so far it's going to have to be something like ...</p>\n\n<pre><code>IQueryable<T>().Where(t => \nMemberExpression.Property(MemberExpression.Constant(t), fieldName) == \nParameterExpression.Property(ParameterExpression.Constant(item), fieldName));\n</code></pre>\n\n<p>While I can get this to compile it's not quite executing the way it is required.</p>\n"
},
{
"answer_id": 232446,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 3,
"selected": true,
"text": "<p>Like so:</p>\n\n<pre><code> var param = Expression.Parameter(typeof(T), \"o\");\n var fixedItem = Expression.Constant(objectOfTypeT, typeof(T));\n var body = Expression.Equal(\n Expression.PropertyOrField(param, fieldName),\n Expression.PropertyOrField(fixedItem, fieldName));\n var lambda = Expression.Lambda<Func<T,bool>>(body,param);\n return source.Where(lambda);\n</code></pre>\n\n<p>I have started a blog which will cover a number of expression topics, <a href=\"http://marcgravell.blogspot.com/\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>If you get any problems, another option is to extract the value from <code>objectOfTypeT</code> first (using reflection) and then use that value in the <code>Expression.Constant</code>, but I suspect it'll be fine \"as is\".</p>\n"
},
{
"answer_id": 10017752,
"author": "Jeroen van Langen",
"author_id": 1112646,
"author_profile": "https://Stackoverflow.com/users/1112646",
"pm_score": 0,
"selected": false,
"text": "<p>What about:</p>\n\n<pre><code> public class Person\n {\n public string Name { get; set; }\n public int Age { get; set; }\n\n }\n\n public Func<T, TRes> GetPropertyFunc<T, TRes>(string propertyName)\n {\n // get the propertyinfo of that property.\n PropertyInfo propInfo = typeof(T).GetProperty(propertyName);\n\n // reference the propertyinfo to get the value directly.\n return (obj) => { return (TRes)propInfo.GetValue(obj, null); };\n }\n\n public void Run()\n {\n List<Person> personList = new List<Person>();\n\n // fill with some data\n personList.Add(new Person { Name = \"John\", Age = 45 });\n personList.Add(new Person { Name = \"Michael\", Age = 31 });\n personList.Add(new Person { Name = \"Rose\", Age = 63 });\n\n // create a lookup functions (should be executed ones)\n Func<Person, string> GetNameValue = GetPropertyFunc<Person, string>(\"Name\");\n Func<Person, int> GetAgeValue = GetPropertyFunc<Person, int>(\"Age\");\n\n\n // filter the list on name\n IEnumerable<Person> filteredOnName = personList.Where(item => GetNameValue(item) == \"Michael\");\n // filter the list on age > 35\n IEnumerable<Person> filteredOnAge = personList.Where(item => GetAgeValue(item) > 35);\n }\n</code></pre>\n\n<p>This is a way to get values of a properties by string without using of dynamic queries. The downside is al values will be boxed/unboxed.</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/232171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25372/"
] |
I have an IQueryable and an object of type T.
I want to do IQueryable().Where(o => o.GetProperty(fieldName) == objectOfTypeT.GetProperty(fieldName))
so ...
```
public IQueryable<T> DoWork<T>(string fieldName)
where T : EntityObject
{
...
T objectOfTypeT = ...;
....
return SomeIQueryable<T>().Where(o => o.GetProperty(fieldName) == objectOfTypeT.GetProperty(fieldName));
}
```
Fyi, GetProperty isn't a valid function. I need something which performs this function.
Am I having a Friday afternoon brain melt or is this a complex thing to do?
---
objectOfTypeT I can do the following ...
```
var matchToValue = Expression.Lambda(ParameterExpression
.Property(ParameterExpression.Constant(item), "CustomerKey"))
.Compile().DynamicInvoke();
```
Which works perfectly,now I just need the second part:
return SomeIQueryable().Where(o => **o.GetProperty(fieldName)** == matchValue);
|
Like so:
```
var param = Expression.Parameter(typeof(T), "o");
var fixedItem = Expression.Constant(objectOfTypeT, typeof(T));
var body = Expression.Equal(
Expression.PropertyOrField(param, fieldName),
Expression.PropertyOrField(fixedItem, fieldName));
var lambda = Expression.Lambda<Func<T,bool>>(body,param);
return source.Where(lambda);
```
I have started a blog which will cover a number of expression topics, [here](http://marcgravell.blogspot.com/).
If you get any problems, another option is to extract the value from `objectOfTypeT` first (using reflection) and then use that value in the `Expression.Constant`, but I suspect it'll be fine "as is".
|
232,237 |
<p>What's the best way to return a random line in a text file using C? It has to use the standard I/O library (<code><stdio.h></code>) because it's for Nintendo DS homebrew.</p>
<p><strong>Clarifications:</strong></p>
<ul>
<li>Using a header in the file to store the number of lines won't work for what I want to do.</li>
<li>I want it to be as random as possible (the best being if each line has an equal probability of being chosen as every other line.)</li>
<li>The file will never change while the program is being run. (It's the DS, so no multi-tasking.)</li>
</ul>
|
[
{
"answer_id": 232246,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 3,
"selected": false,
"text": "<p><strong>This method is good because:</strong></p>\n\n<p>i) You can keep generating random lines at no big cost</p>\n\n<p>ii) You only have to read the file a total of 1 time + 1 line at a time per random line you want. The excess read data is only equal to the size of the file. </p>\n\n<p>iii) It gives each line a fair chance no matter what its position is in the file.</p>\n\n<p>iv) It gives each line a fair chance no matter what its length is in the file.</p>\n\n<p><strong>The suggestion:</strong></p>\n\n<p>I would suggest a 2 pass algorithm. Well really it's a 1 pass + N lines. Where N is the number of random lines you want.</p>\n\n<p>The first pass you would use to calculate how many lines and the start positions of each line.</p>\n\n<p>You then take a random number from 0 to the number of lines minus 1. Use that random number, which is your line index, get the start position for that line index. Seek to that position.</p>\n\n<p>You then have only 1 more read needed, and you know the exact size. (until the start index of the next line)</p>\n\n<p><strong>How to store the number of lines and the index of each line:</strong></p>\n\n<p>To store the number of lines, you can obviously just use an int. </p>\n\n<p>If you can use a vector then you can add each line index into the vector. If not you can just create an array of ints with the max number of lines you think there will be. Then index into that array. </p>\n\n<p><strong>Other answers:</strong></p>\n\n<p>Another answer mentioned that you can pick a random number from 1 to the size of the file, and then use the closest newline. But this won't work. For example you might have 1 line that is really long and the others that are not that long. In that case you would have an uneven distribution.</p>\n"
},
{
"answer_id": 232248,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 6,
"selected": true,
"text": "<p>Read each line, and use a random number to choose whether to keep that line or ignore it. For the first line, you want odds of 1:1 to keep; for the second, you want odds of 1:2, etc.</p>\n\n<pre><code>count = 0;\nwhile (fgets(line, length, stream) != NULL)\n{\n count++;\n if ((rand() * count) / RAND_MAX == 0)\n strcpy(keptline, line);\n}\n</code></pre>\n\n<p>I haven't verified that this has the proper random qualities, but it seems right at first glance.\n<hr>\nIt has been pointed out that integer overflow would quickly become a problem with the way the comparison is coded, and I had independently reached the same conclusion myself. There are probably many ways to fix it, but this is the first that comes to mind:</p>\n\n<pre><code>if ((rand() / (float)RAND_MAX) <= (1.0 / count)) \n</code></pre>\n"
},
{
"answer_id": 232249,
"author": "Adam Pierce",
"author_id": 5324,
"author_profile": "https://Stackoverflow.com/users/5324",
"pm_score": 2,
"selected": false,
"text": "<ol>\n<li>Get the length of the file.</li>\n<li>Pick a random position in the file.</li>\n<li>Seek to that position.</li>\n<li>Iterate forward until you find a newline character.</li>\n<li>If you don't find a newline character, seek back to the beginning.</li>\n<li>Use gets() to read the line.</li>\n</ol>\n"
},
{
"answer_id": 232287,
"author": "Adam Pierce",
"author_id": 5324,
"author_profile": "https://Stackoverflow.com/users/5324",
"pm_score": 1,
"selected": false,
"text": "<p>I have an alternative solution. Since the platform is the DS, you'd probably not want to try to hold the file in memory. This reads the file twice. Once to count the lines and the 2nd time to find the line it wants. This would run slower than the other solutions suggested so far but it uses hardly any memory. I even wrote it in C for you (I omitted error handling):</p>\n\n<pre><code>main(int argc, char **argv)\n{\n FILE *f;\n int nLines = 0;\n char line[1024];\n int randLine;\n int i;\n\n srand(time(0));\n f = fopen(argv[1], \"r\");\n\n/* 1st pass - count the lines. */\n while(!feof(f))\n {\n fgets(line, 1024, f);\n nLines++;\n }\n\n randLine = rand() % nLines;\n printf(\"Chose %d of %d lines\\n\", randLine, nLines);\n\n/* 2nd pass - find the line we want. */\n fseek(f, 0, SEEK_SET);\n for(i = 0; !feof(f) && i <= randLine; i++)\n fgets(line, 1024, f);\n\n printf(\"%s\", line);\n}\n</code></pre>\n\n<p><strong>UPDATE:</strong> Oops, I should have read Brian R. Bondy's answer before I posted this but I was kinda obsessing over writing the code and didn't notice. This is almost the same except it doesn't store the line positions in an array. You could do it either way depending on how big the file is and whether speed is more important than saving memory.</p>\n"
},
{
"answer_id": 232306,
"author": "Matthew Smith",
"author_id": 20889,
"author_profile": "https://Stackoverflow.com/users/20889",
"pm_score": -1,
"selected": false,
"text": "<p>Use a combination of Adam's random offset into the file approach and Mark's probability approach. Adam's method can get you randomly to a section of the file. Then you use Mark's approach to avoid preferring the larger strings. Mark's algorithm will prefer the first few strings from wherever it starts,</p>\n"
},
{
"answer_id": 255431,
"author": "paperhorse",
"author_id": 4498,
"author_profile": "https://Stackoverflow.com/users/4498",
"pm_score": 0,
"selected": false,
"text": "<p>All you need do is generate one unscaled random number per line, while maintaining the maximum value for all the random numbers you generate. Whenever you update the maximum value, you overwrite the selected line with the current line.<p>\nAt the end you get the line associated with the highest number rand() spat out, which should be equally probable among all your lines.</p>\n"
},
{
"answer_id": 267501,
"author": "chazomaticus",
"author_id": 30497,
"author_profile": "https://Stackoverflow.com/users/30497",
"pm_score": 0,
"selected": false,
"text": "<p>Just a quick note about <a href=\"https://stackoverflow.com/questions/232237/whats-the-best-way-to-return-a-random-line-in-a-text-file-using-c#232248\">Mark Ransom</a>'s way of avoiding integer overflow: the DS has no FPU, so floating point division will be emulated in software and very slow. You'll want to avoid typecasting/promotion to float or double at all costs, if speed is a concern.</p>\n\n<p>Here's a different way of avoiding integer overflow that avoids any floating point math:</p>\n\n<pre><code>if(rand() <= RAND_MAX / count)\n</code></pre>\n\n<p>The probabilities may be slightly skewed due to integer division, but this should certainly run much faster on a DS.</p>\n"
},
{
"answer_id": 2933159,
"author": "Daniel Trebbien",
"author_id": 196844,
"author_profile": "https://Stackoverflow.com/users/196844",
"pm_score": 3,
"selected": false,
"text": "<p>Mark's answer is almost correct except for two issues:</p>\n\n<ol>\n<li>If a line is longer than <code>length - 1</code> characters (including the newline), then the <code>while</code> loop will increment <code>count</code> at least twice for the same line: once for the first <code>length - 1</code> characters, another for the next <code>length - 1</code> characters, etc.</li>\n<li>The calculation of <code>rand() * count</code> can cause an integer overflow.</li>\n</ol>\n\n<p>To solve the first problem, you can call <code>fgets</code> into a trash buffer until it returns <code>NULL</code> (indicating an I/O error or EOF with no data read) or the trash buffer contains a newline:</p>\n\n<pre><code>count = 0;\nwhile (fgets(line, length, stream) != NULL)\n{\n char *p = strchr(line, '\\n');\n if (p != NULL) {\n assert(*p == '\\n');\n *p = '\\0'; // trim the newline\n }\n else { // haven't reached EOL yet. Read & discard the rest of the line.\n#define TRASH_LENGTH 1024\n char trash[TRASH_LENGTH];\n while((p = fgets(trash, TRASH_LENGTH, stream)) != NULL) {\n if ((p = strchr(trash, '\\n')) != NULL) // reached EOL\n break;\n }\n }\n assert(strchr(line, '\\n') == NULL); // `line` does not contain a newline\n count++;\n // ...\n</code></pre>\n\n<p>The second problem can be solved with @tvanfosson's suggestion if floating-point arithmetic is not available:</p>\n\n<pre><code>int one_chance_in(size_t n)\n{\n if (rand() % n == 0) // `rand` returns an integer in [0, `RAND_MAX`]\n return 1;\n else\n return 0;\n}\n</code></pre>\n\n<p>But note that <code>rand() % n</code> is not a <a href=\"http://en.wikipedia.org/wiki/Uniform_distribution_(discrete)\" rel=\"noreferrer\">uniform, discrete random variable</a> even if <code>rand()</code> is assumed to be one because the probability that <code>rand() % n == 0</code> can be as much as 1/<code>RAND_MAX</code> higher than the desired probability 1/<code>n</code>. On my machine, <code>RAND_MAX</code> is 2147483647, so the difference is 4.66 × 10<sup>-10</sup>, but the C standard only requires that <code>RAND_MAX</code> be at least 32767 (3.05 × 10<sup>-5</sup> difference).</p>\n\n<p>Also, for anyone left wondering why this scheme works (as I was), it might be helpful to work through the calculation of the probability that the first line remains in <code>keptline</code> if there are <em>m</em> lines and generalize: In the first iteration of the loop, the probability that the first line is copied to <code>keptline</code> is 1/1. In the second iteration of the loop, the probability that the second line does <em>not</em> overwrite the first line is 1/2. In the third iteration, the probability that the third line does <em>not</em> overwrite the first line is 2/3. Continuing, the probability that the last line does not overwrite the first line is (<em>m</em> - 1)/<em>m</em>. Thus, the probability that the first line remains in <code>keptline</code> after iterating over all lines is:</p>\n\n<blockquote>\n <p>1/1 × 1/2 × 2/3 × 3/4 × ... × (<em>m</em> - 2)/(<em>m</em> - 1) × (<em>m</em> - 1)/<em>m</em> = 1/<em>m</em></p>\n</blockquote>\n\n<p>The probability that the <em>second</em> line remains in <code>keptline</code> is:</p>\n\n<blockquote>\n <p>1/2 × 2/3 × 3/4 × ... × (<em>m</em> - 2)/(<em>m</em> - 1) × (<em>m</em> - 1)/<em>m</em> = 1/<em>m</em></p>\n</blockquote>\n\n<p>The probability that the <em>third</em> line remains in <code>keptline</code> is:</p>\n\n<blockquote>\n <p>1/3 × 3/4 × ... × (<em>m</em> - 2)/(<em>m</em> - 1) × (<em>m</em> - 1)/<em>m</em> = 1/<em>m</em></p>\n</blockquote>\n\n<p>Etc. They're all 1/<em>m</em>.</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/232237",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/813/"
] |
What's the best way to return a random line in a text file using C? It has to use the standard I/O library (`<stdio.h>`) because it's for Nintendo DS homebrew.
**Clarifications:**
* Using a header in the file to store the number of lines won't work for what I want to do.
* I want it to be as random as possible (the best being if each line has an equal probability of being chosen as every other line.)
* The file will never change while the program is being run. (It's the DS, so no multi-tasking.)
|
Read each line, and use a random number to choose whether to keep that line or ignore it. For the first line, you want odds of 1:1 to keep; for the second, you want odds of 1:2, etc.
```
count = 0;
while (fgets(line, length, stream) != NULL)
{
count++;
if ((rand() * count) / RAND_MAX == 0)
strcpy(keptline, line);
}
```
I haven't verified that this has the proper random qualities, but it seems right at first glance.
---
It has been pointed out that integer overflow would quickly become a problem with the way the comparison is coded, and I had independently reached the same conclusion myself. There are probably many ways to fix it, but this is the first that comes to mind:
```
if ((rand() / (float)RAND_MAX) <= (1.0 / count))
```
|
232,274 |
<p>When I browse code in Vim, I need to see opening and closing parenthesis/
brackets, and pressing <kbd>%</kbd> seems unproductive.</p>
<p>I tried <code>:set showmatch</code>, but it makes the cursor jump back and forth
when you type in a bracket. But what to do if I am browsing already written code?</p>
|
[
{
"answer_id": 232278,
"author": "jcoby",
"author_id": 2884,
"author_profile": "https://Stackoverflow.com/users/2884",
"pm_score": 5,
"selected": false,
"text": "<p><code>set showmatch</code> is your best bet. you can also use the <kbd>%</kbd> command to jump between matching parenthesis, braces, brackets, quotes, etc.</p>\n"
},
{
"answer_id": 232289,
"author": "Harley Holcombe",
"author_id": 1057,
"author_profile": "https://Stackoverflow.com/users/1057",
"pm_score": 7,
"selected": true,
"text": "<pre><code>DoMatchParen\n</code></pre>\n\n<p>in your <code>.vimrc</code> file</p>\n\n<p>or</p>\n\n<pre><code>:DoMatchParen\n</code></pre>\n\n<p>within vim itself.</p>\n\n<p>Edit: This comes from the <a href=\"http://vimdoc.sourceforge.net/htmldoc/pi_paren.html\" rel=\"noreferrer\">pi_paren</a> plugin (which is a standard plugin).</p>\n"
},
{
"answer_id": 3377980,
"author": "Grissiom",
"author_id": 297347,
"author_profile": "https://Stackoverflow.com/users/297347",
"pm_score": 0,
"selected": false,
"text": "<p>Maybe what you want is this plugin:</p>\n\n<p><a href=\"http://www.vim.org/scripts/script.php?script_id=350\" rel=\"nofollow noreferrer\">http://www.vim.org/scripts/script.php?script_id=350</a></p>\n"
},
{
"answer_id": 52735311,
"author": "Bruce Zhang",
"author_id": 5705731,
"author_profile": "https://Stackoverflow.com/users/5705731",
"pm_score": 1,
"selected": false,
"text": "<p>An upgrade of vim from version 6.3 to 8.0 might swap/upgrade the code file that manages this MatchParen functionality under <code>/usr/share/vim/vim80/plugin/matchparen.vim</code></p>\n\n<p>The function to begin investigating a vim failure for highlighting matching brackets is called: <code>Highlight_Matching_Pair()</code>. Do an echo and a sleep and step through the code until <code>matchaddpos(...)</code> runs. </p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/232274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29405/"
] |
When I browse code in Vim, I need to see opening and closing parenthesis/
brackets, and pressing `%` seems unproductive.
I tried `:set showmatch`, but it makes the cursor jump back and forth
when you type in a bracket. But what to do if I am browsing already written code?
|
```
DoMatchParen
```
in your `.vimrc` file
or
```
:DoMatchParen
```
within vim itself.
Edit: This comes from the [pi\_paren](http://vimdoc.sourceforge.net/htmldoc/pi_paren.html) plugin (which is a standard plugin).
|
232,280 |
<p>Im having a problem with a final part of my assignment. We get in a stream of bits, etc etc, in the stream is an integer with the number of 1's in the text portion. I get that integer and its 24 which is correct, now i loop through the text data i get and i try to count all the 1's in there. But my proc is always returning zero.</p>
<p>I was able to make sure it was looping properly and it is.</p>
<p>The text = Hello
which is 16 1's, here is my proc for looping through that text to count the number of ones in it.</p>
<pre><code>sub AX,AX
sub SI,SI
mov bx,[bp+6] ;get message offset
@@mainLoop:
mov cx,8
mov dh,80h
cmp byte ptr [bx + si],0
je @@endChecker
@@innerLoop:
test byte ptr [bx + si],dh
jz @@zeroFound
inc AX
@@zeroFound:
shr bh,1
loop @@innerLoop
@@continue:
inc si
jmp @@mainLoop
</code></pre>
<p>the rest of the proc is just push/pops. What im wanting this to actually do is use TEST to compare 100000000 to a byte, if its a 1 inc AX else shift right the mask by 1 and loop a whole byte, than inc to next byte and do again.</p>
|
[
{
"answer_id": 232291,
"author": "Menkboy",
"author_id": 29539,
"author_profile": "https://Stackoverflow.com/users/29539",
"pm_score": 3,
"selected": true,
"text": "<p>'shr bh,1' should probably be 'shr dh,1', no?</p>\n"
},
{
"answer_id": 232860,
"author": "Nils Pipenbrinck",
"author_id": 15955,
"author_profile": "https://Stackoverflow.com/users/15955",
"pm_score": 1,
"selected": false,
"text": "<p>Just to give you an alternative and shorter implementation of your inner-loop:</p>\n\n<pre><code> mov cx, 8\n mov dh, byte ptr [bx+si] \n@@innerLoop:\n add dh, dh \n adc ax, 0\n loop @@innerLoop \n</code></pre>\n\n<p>Here we don't test the bits at all. Instead the add dh, dh shifts the topmost bit into the carry and also does the same as shl dh,1 in one instruction.</p>\n\n<p>The addc ax,0 just adds the carry to AX.</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/232280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18431/"
] |
Im having a problem with a final part of my assignment. We get in a stream of bits, etc etc, in the stream is an integer with the number of 1's in the text portion. I get that integer and its 24 which is correct, now i loop through the text data i get and i try to count all the 1's in there. But my proc is always returning zero.
I was able to make sure it was looping properly and it is.
The text = Hello
which is 16 1's, here is my proc for looping through that text to count the number of ones in it.
```
sub AX,AX
sub SI,SI
mov bx,[bp+6] ;get message offset
@@mainLoop:
mov cx,8
mov dh,80h
cmp byte ptr [bx + si],0
je @@endChecker
@@innerLoop:
test byte ptr [bx + si],dh
jz @@zeroFound
inc AX
@@zeroFound:
shr bh,1
loop @@innerLoop
@@continue:
inc si
jmp @@mainLoop
```
the rest of the proc is just push/pops. What im wanting this to actually do is use TEST to compare 100000000 to a byte, if its a 1 inc AX else shift right the mask by 1 and loop a whole byte, than inc to next byte and do again.
|
'shr bh,1' should probably be 'shr dh,1', no?
|
232,316 |
<p>I'm tinkering with Silverlight 2.0.</p>
<p>I have some images, which I currently have a static URL for the image source.
Is there a way to dynamically load the image from a URL path for the site that is hosting the control?</p>
<p>Alternatively, a configuration setting, stored in a single place, that holds the base path for the URL, so that each image only holds the filename?</p>
|
[
{
"answer_id": 232414,
"author": "Aaron Fischer",
"author_id": 5618,
"author_profile": "https://Stackoverflow.com/users/5618",
"pm_score": 5,
"selected": true,
"text": "<p>In the code behind or a value converter you can do </p>\n\n<pre><code> Uri uri = new Uri(\"http://testsvr.com/hello.jpg\");\n YourImage.Source = new BitmapImage(uri);\n</code></pre>\n"
},
{
"answer_id": 232429,
"author": "Aaron Weiker",
"author_id": 30664,
"author_profile": "https://Stackoverflow.com/users/30664",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/system.windows.interop.silverlighthost.source(VS.95).aspx\" rel=\"nofollow noreferrer\">SilverlightHost.Source</a> will provide you the URL that was used to load the XAP file. You can use this to then construct a relative URL for your images.</p>\n\n<p>So if for example your XAP is hosted on <a href=\"http://foo.bar/ClientBin/bas.xap\" rel=\"nofollow noreferrer\">http://foo.bar/ClientBin/bas.xap</a> and your images were stored in <a href=\"http://foo.bar/Images/\" rel=\"nofollow noreferrer\">http://foo.bar/Images/</a> you can simply use the Source to grab the host name and protocol to construct the new URI.</p>\n"
},
{
"answer_id": 236365,
"author": "Craig Nicholson",
"author_id": 28305,
"author_profile": "https://Stackoverflow.com/users/28305",
"pm_score": 4,
"selected": false,
"text": "<p>From what I gather you aren't trying to change the image itself dynamically, but rather to correctly determine the location of the image at runtime.</p>\n\n<p>I believe simply prefixing the image relative URL with \"../\" should get you to the root of your application, not necessarily the site as the application might not be hosted in the root of a site.</p>\n\n<p>If your XAP file is located as follows:</p>\n\n<blockquote>\n <p><a href=\"http://somesite.foo/app1/somethingelse/clientbin/MyFoo.xap\" rel=\"noreferrer\">http://somesite.foo/app1/somethingelse/clientbin/MyFoo.xap</a></p>\n</blockquote>\n\n<p>And you where trying to link the following image:</p>\n\n<blockquote>\n <p><a href=\"http://somesite.foo/app1/somethingelse/images/a/boo.png\" rel=\"noreferrer\">http://somesite.foo/app1/somethingelse/images/a/boo.png</a></p>\n</blockquote>\n\n<p>Apparently all relative URI's are relative to where the XAP file is located (ClientBin folder typically) and Silverlight appends the current Silverlight client namespace. So if you Silverlight control is in the namespace Whoppa you would need to put all your images in the clientbin/Whoppa/ directory. Not exactly convenient.</p>\n\n<p>The workaround is to use absolute URIs as follows:</p>\n\n<blockquote>\n <p>new Uri(App.Current.Host.Source, \"../images/a/boo.png\");</p>\n</blockquote>\n"
},
{
"answer_id": 657410,
"author": "NinethSense",
"author_id": 73722,
"author_profile": "https://Stackoverflow.com/users/73722",
"pm_score": 2,
"selected": false,
"text": "<p>img.Source = new BitmapImage(image uri) must work.</p>\n"
},
{
"answer_id": 735677,
"author": "mknopf",
"author_id": 87680,
"author_profile": "https://Stackoverflow.com/users/87680",
"pm_score": 2,
"selected": false,
"text": "<p><code>img.Source = new BitmapImage(new Uri(\"/images/my-image.jpg\", UriKind.Relative));</code> will properly resolve to the root of the Silverlight application where as \"../images/my-image.jpg\" will not. </p>\n\n<p>This is only true in the code-behind when dynamically setting the source of the image. You cannot use this notation (the \"/\" to designate the root) in the XAML (go fiquire, hope they fix that)</p>\n"
},
{
"answer_id": 1129711,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>The below code worked for me only when the image is included in the project as a resource file:</p>\n\n<pre><code>img.Source = new BitmapImage(new Uri(\"/images/my-image.jpg\", UriKind.Relative)); \n</code></pre>\n\n<p>I am unable to access URL from absolute URLs. Not even Flickr's farm URL for images.</p>\n"
},
{
"answer_id": 2828321,
"author": "Dan Wygant",
"author_id": 340460,
"author_profile": "https://Stackoverflow.com/users/340460",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://www.silverlightexamples.net/post/How-to-Get-Files-From-Resources-in-Silverlight-20.aspx\" rel=\"nofollow noreferrer\">http://www.silverlightexamples.net/post/How-to-Get-Files-From-Resources-in-Silverlight-20.aspx</a></p>\n\n<pre><code>using System.Windows.Resources; // StreamResourceInfo\nusing System.Windows.Media.Imaging; // BitmapImage\n....\n\nStreamResourceInfo sr = Application.GetResourceStream(new Uri(\"SilverlightApplication1;component/MyImage.png\", UriKind.Relative));\nBitmapImage bmp = new BitmapImage();\nbmp.SetSource(sr.Stream);\n</code></pre>\n"
},
{
"answer_id": 3853545,
"author": "Malcolm Swaine",
"author_id": 431246,
"author_profile": "https://Stackoverflow.com/users/431246",
"pm_score": 3,
"selected": false,
"text": "<pre><code>// create a new image\nImage image = new Image();\n\n// better to keep this in a global config singleton\nstring hostName = Application.Current.Host.Source.Host; \nif (Application.Current.Host.Source.Port != 80)\n hostName += \":\" + Application.Current.Host.Source.Port;\n\n// set the image source\nimage.Source = new BitmapImage(new Uri(\"http://\" + hostName + \"/cute_kitten112.jpg\", UriKind.Absolute)); \n</code></pre>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/232316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24126/"
] |
I'm tinkering with Silverlight 2.0.
I have some images, which I currently have a static URL for the image source.
Is there a way to dynamically load the image from a URL path for the site that is hosting the control?
Alternatively, a configuration setting, stored in a single place, that holds the base path for the URL, so that each image only holds the filename?
|
In the code behind or a value converter you can do
```
Uri uri = new Uri("http://testsvr.com/hello.jpg");
YourImage.Source = new BitmapImage(uri);
```
|
232,333 |
<p>How long should it take to run </p>
<pre><code>ALTER DATABASE [MySite] SET READ_COMMITTED_SNAPSHOT ON
</code></pre>
<p>I just ran it and it's taken 10 minutes.</p>
<p>How can I check if it is applied?</p>
|
[
{
"answer_id": 232358,
"author": "Rick",
"author_id": 14138,
"author_profile": "https://Stackoverflow.com/users/14138",
"pm_score": 7,
"selected": true,
"text": "<p>You can check the status of the READ_COMMITTED_SNAPSHOT setting using the <strong><code>sys.databases</code></strong> view. Check the value of the <strong><code>is_read_committed_snapshot_on</code></strong> column. Already <a href=\"https://stackoverflow.com/questions/51969/how-to-detect-readcommittedsnapshot-is-enabled\">asked and answered</a>.</p>\n\n<p>As for the duration, Books Online states that there can't be any other connections to the database when this takes place, but it doesn't require single-user mode. So you may be blocked by other active connections. Run <strong><code>sp_who</code></strong> (or <strong><code>sp_who2</code></strong>) to see what else is connected to that database.</p>\n"
},
{
"answer_id": 1253452,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>ALTER DATABASE generic SET READ_COMMITTED_SNAPSHOT ON WITH ROLLBACK IMMEDIATE\n</code></pre>\n"
},
{
"answer_id": 2058352,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 3,
"selected": false,
"text": "<p>Try this code:</p>\n\n<pre><code>if(charindex('Microsoft SQL Server 2005',@@version) > 0)\nbegin\n declare @sql varchar(8000)\n select @sql = '\n ALTER DATABASE ' + DB_NAME() + ' SET SINGLE_USER WITH ROLLBACK IMMEDIATE ;\n ALTER DATABASE ' + DB_NAME() + ' SET READ_COMMITTED_SNAPSHOT ON;\n ALTER DATABASE ' + DB_NAME() + ' SET MULTI_USER;'\n\n Exec(@sql)\nend\n</code></pre>\n"
},
{
"answer_id": 10534269,
"author": "eLVik",
"author_id": 1317263,
"author_profile": "https://Stackoverflow.com/users/1317263",
"pm_score": 2,
"selected": false,
"text": "<p>Try use master database before altering current database.</p>\n\n<pre><code>USE Master\nGO\n\nALTER DATABASE [YourDatabase] SET READ_COMMITTED_SNAPSHOT ON\nGO\n</code></pre>\n"
},
{
"answer_id": 13343078,
"author": "Yasin Kilicdere",
"author_id": 410448,
"author_profile": "https://Stackoverflow.com/users/410448",
"pm_score": 2,
"selected": false,
"text": "<p>I didn't take a second for me when i changed my DB to single user</p>\n"
},
{
"answer_id": 13731964,
"author": "Simon_Weaver",
"author_id": 16940,
"author_profile": "https://Stackoverflow.com/users/16940",
"pm_score": 5,
"selected": false,
"text": "<p>OK (I am the original questioner) so it turns out this whole time I didn't even have the darn thing enabled.</p>\n\n<p>Here's the <a href=\"http://support.purecm.com/index.php?pg=kb.page&id=348\" rel=\"noreferrer\">ultimate code</a> to run to enable snapshot mode and make sure it is enabled. </p>\n\n<pre><code>SELECT is_read_committed_snapshot_on, snapshot_isolation_state_desc,snapshot_isolation_state FROM sys.databases WHERE name='shipperdb'\n\nALTER DATABASE shipperdb SET allow_snapshot_isolation ON\nALTER DATABASE shipperdb SET SINGLE_USER WITH ROLLBACK IMMEDIATE\nALTER DATABASE shipperdb SET read_committed_snapshot ON\nALTER DATABASE shipperdb SET MULTI_USER\n\nSELECT is_read_committed_snapshot_on, snapshot_isolation_state_desc,snapshot_isolation_state FROM sys.databases WHERE name='shipperdb'\n</code></pre>\n\n<p>This works even with connections active (presumably you're fine with them getting kicked out).</p>\n\n<p>You can see the before and after state and this should run almost immediately.</p>\n\n<hr>\n\n<p>IMPORTANT: </p>\n\n<p>The option READ_COMMITTED_SNAPSHOT above corresponds to IsolationLevel.ReadCommitted in .NET<br/>\nThe option ALLOW_SNAPSHOT_ISOLATION above corresponds to IsolationLevel.Snapshot in .NET</p>\n\n<p><a href=\"https://stackoverflow.com/questions/2741016/read-committed-snapshot-vs-snapshot-isolation-level\">Great article about different versioning</a></p>\n\n<hr>\n\n<p><strong>.NET Tips:</strong></p>\n\n<p>Looks like <code>Isolationlevel.ReadCommitted</code> is allowed in code even if not enabled by the database. No warning is thrown. So do yourself a favor and be sure it is turned on before you assume it is for 3 years like I did!!!</p>\n\n<p>If you're using C# you probably want the <code>ReadCommitted</code> IsolationLevel and not <code>Snapshot</code> - unless you are doing writes in this transaction.</p>\n\n<p><code>READ COMMITTED SNAPSHOT</code> does optimistic reads and pessimistic writes. In contrast, <code>SNAPSHOT</code> does optimistic reads and optimistic writes. <a href=\"https://stackoverflow.com/questions/2741016/read-committed-snapshot-vs-snapshot-isolation-level\">(from here)</a></p>\n\n<pre><code>bool snapshotEnabled = true;\n\nusing (var t = new TransactionScope(TransactionScopeOption.Required,\n new TransactionOptions\n{\n IsolationLevel = IsolationLevel.ReadCommitted\n}))\n{\n using (var shipDB = new ShipperDBDataContext())\n {\n\n }\n}\n</code></pre>\n\n<p>In additional you may get an error about being 'unable to promote' a transaction. Search for 'promotion' in <a href=\"http://msdn.microsoft.com/en-us/library/ms973865.aspx\" rel=\"noreferrer\">Introducing System.Transactions in the .NET Framework 2.0</a>.</p>\n\n<p>Unless you're doing something special like connecting to an external database (or second database) then something as simple as creating a new DataContext can cause this. I had a cache that 'spun up' its own datacontext at initialization and this was trying to escalate the transaction to a full distributed one.</p>\n\n<p>The solution was simple :</p>\n\n<pre><code> using (var tran = new TransactionScope(TransactionScopeOption.Suppress))\n {\n using (var shipDB = new ShipperDBDataContext())\n { \n // initialize cache\n }\n }\n</code></pre>\n\n<p>See also <a href=\"http://www.codinghorror.com/blog/2008/08/deadlocked.html\" rel=\"noreferrer\"><code>Deadlocked</code> article by @CodingHorror</a> </p>\n"
},
{
"answer_id": 43077754,
"author": "Jeff",
"author_id": 7781863,
"author_profile": "https://Stackoverflow.com/users/7781863",
"pm_score": 0,
"selected": false,
"text": "<p>Try Shut off the other SQL services so that only the SQL server service is running. </p>\n\n<p>Mine ran for 5 minutes then I cancelled it because it was obvious nothing was happening. Its a brand new server so there are no other users connected. I shut off the SQL Reporting Services and then ran it again.. took less than a second to complete. </p>\n"
},
{
"answer_id": 45599399,
"author": "Jeff Mergler",
"author_id": 1129926,
"author_profile": "https://Stackoverflow.com/users/1129926",
"pm_score": 3,
"selected": false,
"text": "<p>I tried the command:</p>\n\n<pre><code>ALTER DATABASE MyDB SET READ_COMMITTED_SNAPSHOT ON\nGO\n</code></pre>\n\n<p>against a dev box but the it took 10+ minutes and so I killed it. </p>\n\n<p>I then found this: </p>\n\n<p><a href=\"https://willwarren.com/2015/10/12/sql-server-read-committed-snapshot/\" rel=\"noreferrer\">https://willwarren.com/2015/10/12/sql-server-read-committed-snapshot/</a> </p>\n\n<p>and used his code block (which took about 1:26 to run):</p>\n\n<pre><code>USE master\nGO\n\n/** \n * Cut off live connections\n * This will roll back any open transactions after 30 seconds and\n * restricts access to the DB to logins with sysadmin, dbcreator or\n * db_owner roles\n */\nALTER DATABASE MyDB SET RESTRICTED_USER WITH ROLLBACK AFTER 30 SECONDS\nGO\n\n-- Enable RCSI for MyDB\nALTER DATABASE MyDB SET READ_COMMITTED_SNAPSHOT ON\nGO\n\n-- Allow connections to be established once again\nALTER DATABASE MyDB SET MULTI_USER\nGO\n\n-- Check the status afterwards to make sure it worked\nSELECT is_read_committed_snapshot_on\nFROM sys.databases\nWHERE [name] = 'MyDB '\n</code></pre>\n"
},
{
"answer_id": 69104253,
"author": "Wix",
"author_id": 7052931,
"author_profile": "https://Stackoverflow.com/users/7052931",
"pm_score": 1,
"selected": false,
"text": "<p>All you need to do is this:\nALTER DATABASE xyz SET READ_COMMITTED_SNAPSHOT ON WITH ROLLBACK IMMEDIATE;</p>\n<p>No need to put the database into single user mode.\nYou will rollback uncommitted transactions though.</p>\n"
},
{
"answer_id": 72993041,
"author": "Salim",
"author_id": 1306836,
"author_profile": "https://Stackoverflow.com/users/1306836",
"pm_score": 0,
"selected": false,
"text": "<p>With "ROLLBACK IMMEDIATE" it took about 20-30 seconds on my db which is 300GB.</p>\n<pre><code>ALTER DATABASE DBNAME SET READ_COMMITTED_SNAPSHOT ON WITH ROLLBACK IMMEDIATE\n</code></pre>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/232333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16940/"
] |
How long should it take to run
```
ALTER DATABASE [MySite] SET READ_COMMITTED_SNAPSHOT ON
```
I just ran it and it's taken 10 minutes.
How can I check if it is applied?
|
You can check the status of the READ\_COMMITTED\_SNAPSHOT setting using the **`sys.databases`** view. Check the value of the **`is_read_committed_snapshot_on`** column. Already [asked and answered](https://stackoverflow.com/questions/51969/how-to-detect-readcommittedsnapshot-is-enabled).
As for the duration, Books Online states that there can't be any other connections to the database when this takes place, but it doesn't require single-user mode. So you may be blocked by other active connections. Run **`sp_who`** (or **`sp_who2`**) to see what else is connected to that database.
|
232,344 |
<p>I have some code which ignores a specific exception. </p>
<pre><code>try
{
foreach (FileInfo fi in di.GetFiles())
{
collection.Add(fi.Name);
}
foreach (DirectoryInfo d in di.GetDirectories())
{
populateItems(collection, d);
}
}
catch (UnauthorizedAccessException ex)
{
//ignore and move onto next directory
}
</code></pre>
<p>of course this results in a compile time warning as ex is unused. Is there some standard accept noop which should be used to remove this warning? </p>
|
[
{
"answer_id": 232350,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 5,
"selected": true,
"text": "<p>Just rewrite it as</p>\n\n<pre><code>catch (UnauthorizedAccessException) {}\n</code></pre>\n"
},
{
"answer_id": 232363,
"author": "Booji Boy",
"author_id": 1433,
"author_profile": "https://Stackoverflow.com/users/1433",
"pm_score": 1,
"selected": false,
"text": "<p>I usually do</p>\n\n<pre><code>Debug.WriteLine(ex.message)\n</code></pre>\n\n<p>(that way I can just set a breakpoint in the exception, if needed, too)</p>\n"
},
{
"answer_id": 232367,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 2,
"selected": false,
"text": "<p>As Dave M. and tvanfosson said, you want to rewrite it as</p>\n\n<pre><code>catch (UnauthorizedAccessException) {}\n</code></pre>\n\n<p>The bigger question that should be asked, however, is why you are catching an exception on ignoring it (commonly called swallowing the exception)? This is generally a bad idea as it can (and usually does) hide problems in the application at runtime that can lead to very strange results and a difficult time debugging them.</p>\n"
},
{
"answer_id": 232443,
"author": "Alan",
"author_id": 17205,
"author_profile": "https://Stackoverflow.com/users/17205",
"pm_score": -1,
"selected": false,
"text": "<p>Even though I'm a Java developer (not C#), @Scott Dorman is absolutely right. Why are you \"swallowing the exception\"? Better yet, what <em>could</em> throw the UnauthorizedAccessException? Here are common-sense possibilities:</p>\n\n<ol>\n<li>The file doesn't exist</li>\n<li>The directory doesn't exist</li>\n<li>The current thread of control does not have the correct security privileges. In the *nix world, the current thread may be in the wrong group or the wrong user.</li>\n<li>The disk crashed</li>\n<li>The file's ACL is set to write only but not read. Likewise, for the directory.</li>\n</ol>\n\n<p>The above of course is an incomplete list.</p>\n"
},
{
"answer_id": 232745,
"author": "Robert Rossney",
"author_id": 19403,
"author_profile": "https://Stackoverflow.com/users/19403",
"pm_score": 1,
"selected": false,
"text": "<p>Assuming the comment in your original code is an accurate description of what you're trying to do, I think you want to write it like this:</p>\n\n<pre><code>foreach (FileInfo fi in di.GetFiles())\n{\n //TODO: what exceptions should be handled here?\n collection.Add(fi.Name);\n}\n\n// populate collection for each directory we have authorized access to\nforeach (DirectoryInfo d in di.GetDirectories())\n{\n try\n {\n populateItems(collection, d);\n }\n catch (UnauthorizedAccessException)\n {\n //ignore and move onto next directory\n }\n}\n</code></pre>\n\n<p>And then you need to work on that TODO item.</p>\n"
},
{
"answer_id": 937550,
"author": "Matthew",
"author_id": 115204,
"author_profile": "https://Stackoverflow.com/users/115204",
"pm_score": 1,
"selected": false,
"text": "<p>I agree with the people who say it's probably a bad idea to simply ignore the exception. If you're not going to re-throw it then at the very least log it somewhere. I've written small tools that process a list of files where I didn't want errors on individual files to crash the whole program, and in such cases I would print a warning message so I could see which files were skipped.</p>\n\n<p>The only time I personally ever catch an exception without naming it, as in catch(xxxException), is if I'm going to react to it in some way and then re-throw it so that I can catch it in some outer routine. E.g.:</p>\n\n<pre><code>try\n{\n // do something\n // ...\n}\ncatch(UnauthorizedAccessException)\n{\n // react to this exception in some way\n // ...\n\n // let _someone_ know the exception happened\n throw;\n}\n</code></pre>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/232344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/361/"
] |
I have some code which ignores a specific exception.
```
try
{
foreach (FileInfo fi in di.GetFiles())
{
collection.Add(fi.Name);
}
foreach (DirectoryInfo d in di.GetDirectories())
{
populateItems(collection, d);
}
}
catch (UnauthorizedAccessException ex)
{
//ignore and move onto next directory
}
```
of course this results in a compile time warning as ex is unused. Is there some standard accept noop which should be used to remove this warning?
|
Just rewrite it as
```
catch (UnauthorizedAccessException) {}
```
|
232,386 |
<p>I'm trying to make an item on ToolBar (specifically a Label, TextBlock, or a TextBox) That will fill all available horizontal space. I've gotten the ToolBar itself to stretch out by taking it out of its ToolBarTray, but I can't figure out how to make items stretch.</p>
<p>I tried setting Width to Percenatage or Star values, but it doesn't accept that. Setting Horizontal(Content)Alignment to Stretch in various places seems to have no effect either.</p>
|
[
{
"answer_id": 232407,
"author": "Anthony Potts",
"author_id": 22777,
"author_profile": "https://Stackoverflow.com/users/22777",
"pm_score": 0,
"selected": false,
"text": "<p>Try putting a horizontal StackPanel in the ToolBar and then the element you want inside of that StackPanel.</p>\n"
},
{
"answer_id": 232499,
"author": "Jobi Joy",
"author_id": 8091,
"author_profile": "https://Stackoverflow.com/users/8091",
"pm_score": 0,
"selected": false,
"text": "<p>You need a special custom panel like <strong>auto stretched stack panel</strong>, and replace the toolbarpanel. Check this out you can find one panel there \n<a href=\"http://blendables.com/products/productsLayoutmix.aspx\" rel=\"nofollow noreferrer\">http://blendables.com/products/productsLayoutmix.aspx</a></p>\n"
},
{
"answer_id": 299786,
"author": "Robert Macnee",
"author_id": 19273,
"author_profile": "https://Stackoverflow.com/users/19273",
"pm_score": 4,
"selected": false,
"text": "<p>Unfortunately it looks like the default ControlTemplate for ToolBar doesn't use an ItemsPresenter, it uses a ToolBarPanel, so setting ToolBar.ItemsPanel won't have any effect.</p>\n\n<p>ToolBarPanel inherits from StackPanel. By default its Orientation is bound to the parent ToolBar.Orientation, but you can override this and set its Orientation to Vertical with a Style and this will allow items to stretch horizontally:</p>\n\n<pre><code><DockPanel>\n <ToolBar DockPanel.Dock=\"Top\">\n <ToolBar.Resources>\n <Style TargetType=\"{x:Type ToolBarPanel}\">\n <Setter Property=\"Orientation\" Value=\"Vertical\"/>\n </Style>\n </ToolBar.Resources>\n <ComboBox HorizontalAlignment=\"Stretch\" SelectedIndex=\"0\">\n <ComboBoxItem>A B C</ComboBoxItem>\n <ComboBoxItem>1 2 3</ComboBoxItem>\n <ComboBoxItem>Do Re Mi</ComboBoxItem>\n </ComboBox>\n </ToolBar>\n <Border Margin=\"10\" BorderBrush=\"Yellow\" BorderThickness=\"3\"/>\n</DockPanel>\n</code></pre>\n\n<p>You can then use a Grid or something in place of the ComboBox above if you want multiple items on a line.</p>\n"
},
{
"answer_id": 348917,
"author": "Kirill Osenkov",
"author_id": 37899,
"author_profile": "https://Stackoverflow.com/users/37899",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried wrapping your item in a Grid, not in a StackPanel?</p>\n"
},
{
"answer_id": 398578,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I've had this same problem for a while, and there is very little help available online.</p>\n\n<p>Since it doesn't sound like you need all the extra functionality of a Toolbar (collapsible/movable trays), why not just use a Top-docked Grid, and tweak the background a little to make it look like a standard toolbar?</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/232386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7649/"
] |
I'm trying to make an item on ToolBar (specifically a Label, TextBlock, or a TextBox) That will fill all available horizontal space. I've gotten the ToolBar itself to stretch out by taking it out of its ToolBarTray, but I can't figure out how to make items stretch.
I tried setting Width to Percenatage or Star values, but it doesn't accept that. Setting Horizontal(Content)Alignment to Stretch in various places seems to have no effect either.
|
Unfortunately it looks like the default ControlTemplate for ToolBar doesn't use an ItemsPresenter, it uses a ToolBarPanel, so setting ToolBar.ItemsPanel won't have any effect.
ToolBarPanel inherits from StackPanel. By default its Orientation is bound to the parent ToolBar.Orientation, but you can override this and set its Orientation to Vertical with a Style and this will allow items to stretch horizontally:
```
<DockPanel>
<ToolBar DockPanel.Dock="Top">
<ToolBar.Resources>
<Style TargetType="{x:Type ToolBarPanel}">
<Setter Property="Orientation" Value="Vertical"/>
</Style>
</ToolBar.Resources>
<ComboBox HorizontalAlignment="Stretch" SelectedIndex="0">
<ComboBoxItem>A B C</ComboBoxItem>
<ComboBoxItem>1 2 3</ComboBoxItem>
<ComboBoxItem>Do Re Mi</ComboBoxItem>
</ComboBox>
</ToolBar>
<Border Margin="10" BorderBrush="Yellow" BorderThickness="3"/>
</DockPanel>
```
You can then use a Grid or something in place of the ComboBox above if you want multiple items on a line.
|
232,387 |
<p>Suppose I have a table with a numeric column (lets call it "score").</p>
<p>I'd like to generate a table of counts, that shows how many times scores appeared in each range.</p>
<p>For example:</p>
<pre>
score range | number of occurrences
-------------------------------------
0-9 | 11
10-19 | 14
20-29 | 3
... | ...
</pre>
<p>In this example there were 11 rows with scores in the range of 0 to 9, 14 rows with scores in the range of 10 to 19, and 3 rows with scores in the range 20-29.</p>
<p>Is there an easy way to set this up? What do you recommend?</p>
|
[
{
"answer_id": 232405,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 3,
"selected": false,
"text": "<pre><code>create table scores (\n user_id int,\n score int\n)\n\nselect t.range as [score range], count(*) as [number of occurences]\nfrom (\n select user_id,\n case when score >= 0 and score < 10 then '0-9'\n case when score >= 10 and score < 20 then '10-19'\n ...\n else '90-99' as range\n from scores) t\ngroup by t.range\n</code></pre>\n"
},
{
"answer_id": 232406,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 3,
"selected": false,
"text": "<pre><code>select cast(score/10 as varchar) + '-' + cast(score/10+9 as varchar), \n count(*)\nfrom scores\ngroup by score/10\n</code></pre>\n"
},
{
"answer_id": 232420,
"author": "mhawke",
"author_id": 21945,
"author_profile": "https://Stackoverflow.com/users/21945",
"pm_score": 5,
"selected": false,
"text": "<p>In postgres (where <code>||</code> is the string concatenation operator):</p>\n\n<pre><code>select (score/10)*10 || '-' || (score/10)*10+9 as scorerange, count(*)\nfrom scores\ngroup by score/10\norder by 1\n</code></pre>\n\n<p>gives:</p>\n\n<pre><code> scorerange | count \n------------+-------\n 0-9 | 11\n 10-19 | 14\n 20-29 | 3\n 30-39 | 2\n</code></pre>\n"
},
{
"answer_id": 232433,
"author": "Richard T",
"author_id": 26976,
"author_profile": "https://Stackoverflow.com/users/26976",
"pm_score": -1,
"selected": false,
"text": "<p>Perhaps you're asking about keeping such things going...</p>\n\n<p>Of course you'll invoke a full table scan for the queries and if the table containing the scores that need to be tallied (aggregations) is large you might want a better performing solution, you can create a secondary table and use rules, such as <code>on insert</code> - you might look into it.</p>\n\n<p>Not all RDBMS engines have rules, though! </p>\n"
},
{
"answer_id": 232449,
"author": "Aheho",
"author_id": 21155,
"author_profile": "https://Stackoverflow.com/users/21155",
"pm_score": 2,
"selected": false,
"text": "<pre><code>declare @RangeWidth int\n\nset @RangeWidth = 10\n\nselect\n Floor(Score/@RangeWidth) as LowerBound,\n Floor(Score/@RangeWidth)+@RangeWidth as UpperBound,\n Count(*)\nFrom\n ScoreTable\ngroup by\n Floor(Score/@RangeWidth)\n</code></pre>\n"
},
{
"answer_id": 232463,
"author": "Ken Paul",
"author_id": 26671,
"author_profile": "https://Stackoverflow.com/users/26671",
"pm_score": 5,
"selected": false,
"text": "<p>I see answers here that won't work in SQL Server's syntax. I would use:</p>\n\n<pre><code>select t.range as [score range], count(*) as [number of occurences]\nfrom (\n select case \n when score between 0 and 9 then ' 0-9 '\n when score between 10 and 19 then '10-19'\n when score between 20 and 29 then '20-29'\n ...\n else '90-99' end as range\n from scores) t\ngroup by t.range\n</code></pre>\n\n<p>EDIT: see comments</p>\n"
},
{
"answer_id": 232598,
"author": "Timothy Walters",
"author_id": 14454,
"author_profile": "https://Stackoverflow.com/users/14454",
"pm_score": 4,
"selected": false,
"text": "<p>James Curran's answer was the most concise in my opinion, but the output wasn't correct. For SQL Server the simplest statement is as follows:</p>\n\n<pre><code>SELECT \n [score range] = CAST((Score/10)*10 AS VARCHAR) + ' - ' + CAST((Score/10)*10+9 AS VARCHAR), \n [number of occurrences] = COUNT(*)\nFROM #Scores\nGROUP BY Score/10\nORDER BY Score/10\n</code></pre>\n\n<p>This assumes a #Scores temporary table I used to test it, I just populated 100 rows with random number between 0 and 99.</p>\n"
},
{
"answer_id": 233223,
"author": "Ron Tuffin",
"author_id": 939,
"author_profile": "https://Stackoverflow.com/users/939",
"pm_score": 8,
"selected": true,
"text": "<p>Neither of the highest voted answers are correct on SQL Server 2000. Perhaps they were using a different version.</p>\n<p>Here are the correct versions of both of them on SQL Server 2000.</p>\n<pre><code>select t.range as [score range], count(*) as [number of occurences]\nfrom (\n select case \n when score between 0 and 9 then ' 0- 9'\n when score between 10 and 19 then '10-19'\n else '20-99' end as range\n from scores) t\ngroup by t.range\n</code></pre>\n<p>or</p>\n<pre><code>select t.range as [score range], count(*) as [number of occurrences]\nfrom (\n select user_id,\n case when score >= 0 and score< 10 then '0-9'\n when score >= 10 and score< 20 then '10-19'\n else '20-99' end as range\n from scores) t\ngroup by t.range\n</code></pre>\n"
},
{
"answer_id": 236314,
"author": "Walter Mitty",
"author_id": 19937,
"author_profile": "https://Stackoverflow.com/users/19937",
"pm_score": 5,
"selected": false,
"text": "<p>An alternative approach would involve storing the ranges in a table, instead of embedding them in the query. You would end up with a table, call it Ranges, that looks like this:</p>\n\n<pre><code>LowerLimit UpperLimit Range \n0 9 '0-9'\n10 19 '10-19'\n20 29 '20-29'\n30 39 '30-39'\n</code></pre>\n\n<p>And a query that looks like this:</p>\n\n<pre><code>Select\n Range as [Score Range],\n Count(*) as [Number of Occurences]\nfrom\n Ranges r inner join Scores s on s.Score between r.LowerLimit and r.UpperLimit\ngroup by Range\n</code></pre>\n\n<p>This does mean setting up a table, but it would be easy to maintain when the desired ranges change. No code changes necessary!</p>\n"
},
{
"answer_id": 15715413,
"author": "Danny Hui",
"author_id": 2226449,
"author_profile": "https://Stackoverflow.com/users/2226449",
"pm_score": 1,
"selected": false,
"text": "<pre><code>select t.blah as [score range], count(*) as [number of occurences]\nfrom (\n select case \n when score between 0 and 9 then ' 0-9 '\n when score between 10 and 19 then '10-19'\n when score between 20 and 29 then '20-29'\n ...\n else '90-99' end as blah\n from scores) t\ngroup by t.blah\n</code></pre>\n\n<p>Make sure you use a word other than 'range' if you are in MySQL, or you will get an error for running the above example.</p>\n"
},
{
"answer_id": 24758052,
"author": "Kevin Hogg",
"author_id": 687441,
"author_profile": "https://Stackoverflow.com/users/687441",
"pm_score": 1,
"selected": false,
"text": "<p>Because the column being sorted on (<code>Range</code>) is a string, string/word sorting is used instead of numeric sorting.</p>\n\n<p>As long as the strings have zeros to pad out the number lengths the sorting should still be semantically correct:</p>\n\n<pre><code>SELECT t.range AS ScoreRange,\n COUNT(*) AS NumberOfOccurrences\n FROM (SELECT CASE\n WHEN score BETWEEN 0 AND 9 THEN '00-09'\n WHEN score BETWEEN 10 AND 19 THEN '10-19'\n ELSE '20-99'\n END AS Range\n FROM Scores) t\n GROUP BY t.Range\n</code></pre>\n\n<p>If the range is mixed, simply pad an extra zero:</p>\n\n<pre><code>SELECT t.range AS ScoreRange,\n COUNT(*) AS NumberOfOccurrences\n FROM (SELECT CASE\n WHEN score BETWEEN 0 AND 9 THEN '000-009'\n WHEN score BETWEEN 10 AND 19 THEN '010-019'\n WHEN score BETWEEN 20 AND 99 THEN '020-099'\n ELSE '100-999'\n END AS Range\n FROM Scores) t\n GROUP BY t.Range\n</code></pre>\n"
},
{
"answer_id": 27131866,
"author": "JoshNaro",
"author_id": 7423,
"author_profile": "https://Stackoverflow.com/users/7423",
"pm_score": 2,
"selected": false,
"text": "<p>I would do this a little differently so that it scales without having to define every case:</p>\n\n<pre><code>select t.range as [score range], count(*) as [number of occurences]\nfrom (\n select FLOOR(score/10) as range\n from scores) t\ngroup by t.range\n</code></pre>\n\n<p>Not tested, but you get the idea...</p>\n"
},
{
"answer_id": 33000669,
"author": "trevorgrayson",
"author_id": 965161,
"author_profile": "https://Stackoverflow.com/users/965161",
"pm_score": 3,
"selected": false,
"text": "<p>This will allow you to not have to specify ranges, and should be SQL server agnostic. Math FTW! </p>\n\n<pre><code>SELECT CONCAT(range,'-',range+9), COUNT(range)\nFROM (\n SELECT \n score - (score % 10) as range\n FROM scores\n)\n</code></pre>\n"
},
{
"answer_id": 33830966,
"author": "Stubo",
"author_id": 5586547,
"author_profile": "https://Stackoverflow.com/users/5586547",
"pm_score": 1,
"selected": false,
"text": "<p>Try</p>\n\n<pre><code>SELECT (str(range) + \"-\" + str(range + 9) ) AS [Score range], COUNT(score) AS [number of occurances]\nFROM (SELECT score, int(score / 10 ) * 10 AS range FROM scoredata ) \nGROUP BY range;\n</code></pre>\n"
},
{
"answer_id": 63391773,
"author": "user8494871",
"author_id": 8494871,
"author_profile": "https://Stackoverflow.com/users/8494871",
"pm_score": 0,
"selected": false,
"text": "<pre><code>select t.range as score, count(*) as Count \nfrom (\n select UserId,\n case when isnull(score ,0) >= 0 and isnull(score ,0)< 5 then '0-5'\n when isnull(score ,0) >= 5 and isnull(score ,0)< 10 then '5-10'\n when isnull(score ,0) >= 10 and isnull(score ,0)< 15 then '10-15'\n when isnull(score ,0) >= 15 and isnull(score ,0)< 20 then '15-20' \n else ' 20+' end as range\n ,case when isnull(score ,0) >= 0 and isnull(score ,0)< 5 then 1\n when isnull(score ,0) >= 5 and isnull(score ,0)< 10 then 2\n when isnull(score ,0) >= 10 and isnull(score ,0)< 15 then 3\n when isnull(score ,0) >= 15 and isnull(score ,0)< 20 then 4 \n else 5 end as pd\n from score table\n ) t\n\ngroup by t.range,pd order by pd\n</code></pre>\n"
},
{
"answer_id": 65428925,
"author": "April Rose Garcia",
"author_id": 12310251,
"author_profile": "https://Stackoverflow.com/users/12310251",
"pm_score": 0,
"selected": false,
"text": "<p>I'm here because i have similar question but i find the short answers wrong and the one with the continuous "case when" is to much work and seeing anything repetitive in my code hurts my eyes. So here is the solution</p>\n<pre><code>SELECT --MIN(score), MAX(score),\n [score range] = CAST(ROUND(score-5,-1)AS VARCHAR) + ' - ' + CAST((ROUND(score-5,-1)+10)AS VARCHAR),\n [number of occurrences] = COUNT(*)\nFROM order\nGROUP BY CAST(ROUND(score-5,-1)AS VARCHAR) + ' - ' + CAST((ROUND(score-5,-1)+10)AS VARCHAR)\nORDER BY MIN(score)\n\n\n</code></pre>\n"
},
{
"answer_id": 72761784,
"author": "Alex Punnen",
"author_id": 429476,
"author_profile": "https://Stackoverflow.com/users/429476",
"pm_score": 0,
"selected": false,
"text": "<p>For PrestoSQL/Trino applying answer from Ken <a href=\"https://stackoverflow.com/a/232463/429476\">https://stackoverflow.com/a/232463/429476</a></p>\n<pre><code>select t.range, count(*) as "Number of Occurance", ROUND(AVG(fare_amount),2) as "Avg",\n ROUND(MAX(fare_amount),2) as "Max" ,ROUND(MIN(fare_amount),2) as "Min" \nfrom (\n select \n case \n when trip_distance between 0 and 9 then ' 0-9 '\n when trip_distance between 10 and 19 then '10-19'\n when trip_distance between 20 and 29 then '20-29'\n when trip_distance between 30 and 39 then '30-39'\n else '> 39' \n end as range ,fare_amount \n from nyc_in_parquet.tlc_yellow_trip_2022) t\n where fare_amount > 1 and fare_amount < 401092\ngroup by t.range;\n\n range | Number of Occurance | Avg | Max | Min \n-------+---------------------+--------+-------+------\n 0-9 | 2260865 | 10.28 | 720.0 | 1.11 \n 30-39 | 1107 | 104.28 | 280.0 | 5.0 \n 10-19 | 126136 | 43.8 | 413.5 | 2.0 \n > 39 | 42556 | 39.11 | 668.0 | 1.99 \n 20-29 | 19133 | 58.62 | 250.0 | 2.5 \n</code></pre>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/232387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31060/"
] |
Suppose I have a table with a numeric column (lets call it "score").
I'd like to generate a table of counts, that shows how many times scores appeared in each range.
For example:
```
score range | number of occurrences
-------------------------------------
0-9 | 11
10-19 | 14
20-29 | 3
... | ...
```
In this example there were 11 rows with scores in the range of 0 to 9, 14 rows with scores in the range of 10 to 19, and 3 rows with scores in the range 20-29.
Is there an easy way to set this up? What do you recommend?
|
Neither of the highest voted answers are correct on SQL Server 2000. Perhaps they were using a different version.
Here are the correct versions of both of them on SQL Server 2000.
```
select t.range as [score range], count(*) as [number of occurences]
from (
select case
when score between 0 and 9 then ' 0- 9'
when score between 10 and 19 then '10-19'
else '20-99' end as range
from scores) t
group by t.range
```
or
```
select t.range as [score range], count(*) as [number of occurrences]
from (
select user_id,
case when score >= 0 and score< 10 then '0-9'
when score >= 10 and score< 20 then '10-19'
else '20-99' end as range
from scores) t
group by t.range
```
|
232,395 |
<p>I have a two-dimensional array (of Strings) which make up my data table (of rows and columns). I want to sort this array by any column. I tried to find an algorithm for doing this in C#, but have not been successful.</p>
<p>Any help is appreciated.</p>
|
[
{
"answer_id": 232413,
"author": "Doug L.",
"author_id": 19179,
"author_profile": "https://Stackoverflow.com/users/19179",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"https://web.archive.org/web/20160819174858/http://www.informit.com/guides/content.aspx?g=dotnet&seqNum=151\" rel=\"nofollow noreferrer\">Here</a> is an archived article from Jim Mischel at InformIt that handles sorting for both rectangular and jagged multi-dimensional arrays. </p>\n"
},
{
"answer_id": 232444,
"author": "MusiGenesis",
"author_id": 14606,
"author_profile": "https://Stackoverflow.com/users/14606",
"pm_score": 6,
"selected": true,
"text": "<p>Load your two-dimensional string array into an actual DataTable (System.Data.DataTable), and then use the DataTable object's Select() method to generate a sorted array of DataRow objects (or use a DataView for a similar effect).</p>\n\n<pre><code>// assumes stringdata[row, col] is your 2D string array\nDataTable dt = new DataTable();\n// assumes first row contains column names:\nfor (int col = 0; col < stringdata.GetLength(1); col++)\n{\n dt.Columns.Add(stringdata[0, col]);\n}\n// load data from string array to data table:\nfor (rowindex = 1; rowindex < stringdata.GetLength(0); rowindex++)\n{\n DataRow row = dt.NewRow();\n for (int col = 0; col < stringdata.GetLength(1); col++)\n {\n row[col] = stringdata[rowindex, col];\n }\n dt.Rows.Add(row);\n}\n// sort by third column:\nDataRow[] sortedrows = dt.Select(\"\", \"3\");\n// sort by column name, descending:\nsortedrows = dt.Select(\"\", \"COLUMN3 DESC\");\n</code></pre>\n\n<p>You could also write your own method to sort a two-dimensional array. Both approaches would be useful learning experiences, but the DataTable approach would get you started on learning a better way of handling tables of data in a C# application.</p>\n"
},
{
"answer_id": 232452,
"author": "Moishe Lettvin",
"author_id": 23786,
"author_profile": "https://Stackoverflow.com/users/23786",
"pm_score": 0,
"selected": false,
"text": "<p>So your array is structured like this (I'm gonna talk in pseudocode because my C#-fu is weak, but I hope you get the gist of what I'm saying)</p>\n\n<pre><code>string values[rows][columns]\n</code></pre>\n\n<p>So <code>value[1][3]</code> is the value at row 1, column 3.</p>\n\n<p>You want to sort by column, so the problem is that your array is off by 90 degrees.</p>\n\n<p>As a first cut, could you just rotate it?</p>\n\n<pre><code>std::string values_by_column[columns][rows];\n\nfor (int i = 0; i < rows; i++)\n for (int j = 0; j < columns; j++)\n values_by_column[column][row] = values[row][column]\n\nsort_array(values_by_column[column])\n\nfor (int i = 0; i < rows; i++)\n for (int j = 0; j < columns; j++)\n values[row][column] = values_by_column[column][row]\n</code></pre>\n\n<p>If you know you only want to sort one column at a time, you could optimize this a lot by just extracting the data you want to sort:</p>\n\n<pre><code> string values_to_sort[rows]\n for (int i = 0; i < rows; i++)\n values_to_sort[i] = values[i][column_to_sort]\n\n sort_array(values_to_sort)\n\n for (int i = 0; i < rows; i++)\n values[i][column_to_sort] = values_to_sort[i]\n</code></pre>\n\n<p>In C++ you could play tricks with how to calculate offsets into the array (since you could treat your two-dimensional array as a one-d array) but I'm not sure how to do that in c#.</p>\n"
},
{
"answer_id": 232464,
"author": "David Hall",
"author_id": 2660,
"author_profile": "https://Stackoverflow.com/users/2660",
"pm_score": 1,
"selected": false,
"text": "<p>This code should do what you are after, I haven't generalised it for n by n, but that is straight forward. That said - I agree with MusiGenesis, using another object that is a little better suited to this (especially if you intend to do any sort of binding)</p>\n\n<p>(I found the code <a href=\"http://channel9.msdn.com/forums/Coffeehouse/189171-Sorting-Two-Dimensional-Arrays-in-C/\" rel=\"nofollow noreferrer\">here</a>)</p>\n\n<pre><code>string[][] array = new string[3][];\n\narray[0] = new string[3] { \"apple\", \"apple\", \"apple\" };\narray[1] = new string[3] { \"banana\", \"banana\", \"dog\" };\narray[2] = new string[3] { \"cat\", \"hippo\", \"cat\" }; \n\nfor (int i = 0; i < 3; i++)\n{\n Console.WriteLine(String.Format(\"{0} {1} {2}\", array[i][0], array[i][1], array[i][2]));\n}\n\nint j = 2;\n\nArray.Sort(array, delegate(object[] x, object[] y)\n {\n return (x[j] as IComparable).CompareTo(y[ j ]);\n }\n);\n\nfor (int i = 0; i < 3; i++)\n{\n Console.WriteLine(String.Format(\"{0} {1} {2}\", array[i][0], array[i][1], array[i][2]));\n}\n</code></pre>\n"
},
{
"answer_id": 232465,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 6,
"selected": false,
"text": "<p>Can I check - do you mean a rectangular array (<code>[,]</code>)or a jagged array (<code>[][]</code>)?</p>\n\n<p>It is quite easy to sort a jagged array; I have a discussion on that <a href=\"http://groups.google.co.uk/group/microsoft.public.dotnet.languages.csharp/browse_thread/thread/1e1a4bd58144bf73/364f22121b566a3c#23b3e4487e91cd02\" rel=\"noreferrer\">here</a>. Obviously in this case the <code>Comparison<T></code> would involve a column instead of sorting by ordinal - but very similar.</p>\n\n<p>Sorting a rectangular array is trickier... I'd probably be tempted to copy the data out into either a rectangular array or a <code>List<T[]></code>, and sort <em>there</em>, then copy back.</p>\n\n<p>Here's an example using a jagged array:</p>\n\n<pre><code>static void Main()\n{ // could just as easily be string...\n int[][] data = new int[][] { \n new int[] {1,2,3}, \n new int[] {2,3,4}, \n new int[] {2,4,1} \n }; \n Sort<int>(data, 2); \n} \nprivate static void Sort<T>(T[][] data, int col) \n{ \n Comparer<T> comparer = Comparer<T>.Default;\n Array.Sort<T[]>(data, (x,y) => comparer.Compare(x[col],y[col])); \n} \n</code></pre>\n\n<p>For working with a rectangular array... well, here is some code to swap between the two on the fly...</p>\n\n<pre><code>static T[][] ToJagged<T>(this T[,] array) {\n int height = array.GetLength(0), width = array.GetLength(1);\n T[][] jagged = new T[height][];\n\n for (int i = 0; i < height; i++)\n {\n T[] row = new T[width];\n for (int j = 0; j < width; j++)\n {\n row[j] = array[i, j];\n }\n jagged[i] = row;\n }\n return jagged;\n}\nstatic T[,] ToRectangular<T>(this T[][] array)\n{\n int height = array.Length, width = array[0].Length;\n T[,] rect = new T[height, width];\n for (int i = 0; i < height; i++)\n {\n T[] row = array[i];\n for (int j = 0; j < width; j++)\n {\n rect[i, j] = row[j];\n }\n }\n return rect;\n}\n// fill an existing rectangular array from a jagged array\nstatic void WriteRows<T>(this T[,] array, params T[][] rows)\n{\n for (int i = 0; i < rows.Length; i++)\n {\n T[] row = rows[i];\n for (int j = 0; j < row.Length; j++)\n {\n array[i, j] = row[j];\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 232530,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 0,
"selected": false,
"text": "<p>Try this out. The basic strategy is to sort the particular column independently and remember the original row of the entry. The rest of the code will cycle through the sorted column data and swap out the rows in the array. The tricky part is remembing to update the original column as the swap portion will effectively alter the original column. </p>\n\n<pre><code>\n public class Pair<T> {\n public int Index;\n public T Value;\n public Pair(int i, T v) {\n Index = i;\n Value = v;\n }\n }\n static IEnumerable<Pair<T>> Iterate<T>(this IEnumerable<T> source) {\n int index = 0;\n foreach ( var cur in source) {\n yield return new Pair<T>(index,cur);\n index++;\n }\n }\n static void Sort2d(string[][] source, IComparer comp, int col) {\n var colValues = source.Iterate()\n .Select(x => new Pair<string>(x.Index,source[x.Index][col])).ToList();\n colValues.Sort((l,r) => comp.Compare(l.Value, r.Value));\n var temp = new string[source[0].Length];\n var rest = colValues.Iterate();\n while ( rest.Any() ) {\n var pair = rest.First();\n var cur = pair.Value;\n var i = pair.Index;\n if (i == cur.Index ) {\n rest = rest.Skip(1);\n continue;\n }\n\n Array.Copy(source[i], temp, temp.Length);\n Array.Copy(source[cur.Index], source[i], temp.Length);\n Array.Copy(temp, source[cur.Index], temp.Length);\n rest = rest.Skip(1);\n rest.Where(x => x.Value.Index == i).First().Value.Index = cur.Index;\n }\n }\n\n public static void Test1() {\n var source = new string[][] \n {\n new string[]{ \"foo\", \"bar\", \"4\" },\n new string[] { \"jack\", \"dog\", \"1\" },\n new string[]{ \"boy\", \"ball\", \"2\" },\n new string[]{ \"yellow\", \"green\", \"3\" }\n };\n Sort2d(source, StringComparer.Ordinal, 2);\n }\n</code></pre>\n"
},
{
"answer_id": 237702,
"author": "Raindog",
"author_id": 29049,
"author_profile": "https://Stackoverflow.com/users/29049",
"pm_score": 0,
"selected": false,
"text": "<p>If you could get the data as a generic tuple when you read it in or retrieved it, it would be a lot easier; then you would just have to write a Sort function that compares the desired column of the tuple, and you have a single dimension array of tuples.</p>\n"
},
{
"answer_id": 3161080,
"author": "Jeffrey Roughgarden",
"author_id": 381465,
"author_profile": "https://Stackoverflow.com/users/381465",
"pm_score": 0,
"selected": false,
"text": "<p>I like the DataTable approach proposed by MusiGenesis above. The nice thing about it is that you can sort by any valid SQL 'order by' string that uses column names, e.g. \"x, y desc, z\" for 'order by x, y desc, z'. (FWIW, I could not get it to work using column ordinals, e.g. \"3,2,1 \" for 'order by 3,2,1') I used only integers, but clearly you could add mixed type data into the DataTable and sort it any which way.</p>\n\n<p>In the example below, I first loaded some unsorted integer data into a tblToBeSorted in Sandbox (not shown). With the table and its data already existing, I load it (unsorted) into a 2D integer array, then to a DataTable. The array of DataRows is the sorted version of DataTable. The example is a little odd in that I load my array from the DB and could have sorted it then, but I just wanted to get an unsorted array into C# to use with the DataTable object.</p>\n\n<pre><code>static void Main(string[] args)\n{\n SqlConnection cnnX = new SqlConnection(\"Data Source=r90jroughgarden\\\\;Initial Catalog=Sandbox;Integrated Security=True\");\n SqlCommand cmdX = new SqlCommand(\"select * from tblToBeSorted\", cnnX);\n cmdX.CommandType = CommandType.Text;\n SqlDataReader rdrX = null;\n if (cnnX.State == ConnectionState.Closed) cnnX.Open();\n\n int[,] aintSortingArray = new int[100, 4]; //i, elementid, planid, timeid\n\n try\n {\n //Load unsorted table data from DB to array\n rdrX = cmdX.ExecuteReader();\n if (!rdrX.HasRows) return;\n\n int i = -1;\n while (rdrX.Read() && i < 100)\n {\n i++;\n aintSortingArray[i, 0] = rdrX.GetInt32(0);\n aintSortingArray[i, 1] = rdrX.GetInt32(1);\n aintSortingArray[i, 2] = rdrX.GetInt32(2);\n aintSortingArray[i, 3] = rdrX.GetInt32(3);\n }\n rdrX.Close();\n\n DataTable dtblX = new DataTable();\n dtblX.Columns.Add(\"ChangeID\");\n dtblX.Columns.Add(\"ElementID\");\n dtblX.Columns.Add(\"PlanID\");\n dtblX.Columns.Add(\"TimeID\");\n for (int j = 0; j < i; j++)\n {\n DataRow drowX = dtblX.NewRow();\n for (int k = 0; k < 4; k++)\n {\n drowX[k] = aintSortingArray[j, k];\n }\n dtblX.Rows.Add(drowX);\n }\n\n DataRow[] adrowX = dtblX.Select(\"\", \"ElementID, PlanID, TimeID\");\n adrowX = dtblX.Select(\"\", \"ElementID desc, PlanID asc, TimeID desc\");\n\n }\n catch (Exception ex)\n {\n string strErrMsg = ex.Message;\n }\n finally\n {\n if (cnnX.State == ConnectionState.Open) cnnX.Close();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 6483498,
"author": "Gregory Massov",
"author_id": 816058,
"author_profile": "https://Stackoverflow.com/users/816058",
"pm_score": 1,
"selected": false,
"text": "<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ConsoleApplication1\n{\n class Program\n {\n static void Main(string[] args)\n {\n int[,] arr = { { 20, 9, 11 }, { 30, 5, 6 } };\n Console.WriteLine(\"before\");\n for (int i = 0; i < arr.GetLength(0); i++)\n {\n for (int j = 0; j < arr.GetLength(1); j++)\n {\n Console.Write(\"{0,3}\", arr[i, j]);\n }\n Console.WriteLine();\n }\n Console.WriteLine(\"After\");\n\n for (int i = 0; i < arr.GetLength(0); i++) // Array Sorting\n {\n for (int j = arr.GetLength(1) - 1; j > 0; j--)\n {\n\n for (int k = 0; k < j; k++)\n {\n if (arr[i, k] > arr[i, k + 1])\n {\n int temp = arr[i, k];\n arr[i, k] = arr[i, k + 1];\n arr[i, k + 1] = temp;\n }\n }\n }\n Console.WriteLine();\n }\n\n for (int i = 0; i < arr.GetLength(0); i++)\n {\n for (int j = 0; j < arr.GetLength(1); j++)\n {\n Console.Write(\"{0,3}\", arr[i, j]);\n }\n Console.WriteLine();\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 14438117,
"author": "No_Nick777",
"author_id": 1915670,
"author_profile": "https://Stackoverflow.com/users/1915670",
"pm_score": 1,
"selected": false,
"text": "<p>Can allso look at Array.Sort Method <a href=\"http://msdn.microsoft.com/en-us/library/aa311213(v=vs.71).aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/aa311213(v=vs.71).aspx</a> </p>\n\n<p>e.g. Array.Sort(array, delegate(object[] x, object[] y){ return (x[ i ] as IComparable).CompareTo(y[ i ]);}); </p>\n\n<p>from <a href=\"http://channel9.msdn.com/forums/Coffeehouse/189171-Sorting-Two-Dimensional-Arrays-in-C/\" rel=\"nofollow\">http://channel9.msdn.com/forums/Coffeehouse/189171-Sorting-Two-Dimensional-Arrays-in-C/</a></p>\n"
},
{
"answer_id": 18260685,
"author": "Chuck Wilbur",
"author_id": 99640,
"author_profile": "https://Stackoverflow.com/users/99640",
"pm_score": 0,
"selected": false,
"text": "<p>This is an old question, but here's a class I just built based on <a href=\"http://www.informit.com/guides/content.aspx?g=dotnet&seqNum=151\" rel=\"nofollow noreferrer\">the article from Jim Mischel at InformIt</a> linked by <a href=\"https://stackoverflow.com/users/19179/doug-l\">Doug L.</a></p>\n\n<pre><code>class Array2DSort : IComparer<int>\n{\n // maintain a reference to the 2-dimensional array being sorted\n string[,] _sortArray;\n int[] _tagArray;\n int _sortIndex;\n\n protected string[,] SortArray { get { return _sortArray; } }\n\n // constructor initializes the sortArray reference\n public Array2DSort(string[,] theArray, int sortIndex)\n {\n _sortArray = theArray;\n _tagArray = new int[_sortArray.GetLength(0)];\n for (int i = 0; i < _sortArray.GetLength(0); ++i) _tagArray[i] = i;\n _sortIndex = sortIndex;\n }\n\n public string[,] ToSortedArray()\n {\n Array.Sort(_tagArray, this);\n string[,] result = new string[\n _sortArray.GetLength(0), _sortArray.GetLength(1)];\n for (int i = 0; i < _sortArray.GetLength(0); i++)\n {\n for (int j = 0; j < _sortArray.GetLength(1); j++)\n {\n result[i, j] = _sortArray[_tagArray[i], j];\n }\n }\n return result;\n }\n\n // x and y are integer row numbers into the sortArray\n public virtual int Compare(int x, int y)\n {\n if (_sortIndex < 0) return 0;\n return CompareStrings(x, y, _sortIndex);\n }\n\n protected int CompareStrings(int x, int y, int col)\n {\n return _sortArray[x, col].CompareTo(_sortArray[y, col]);\n }\n}\n</code></pre>\n\n<p>Given an unsorted 2D array <code>data</code> of arbitrary size that you want to sort on column 5 you just do this:</p>\n\n<pre><code> Array2DSort comparer = new Array2DSort(data, 5);\n string[,] sortedData = comparer.ToSortedArray();\n</code></pre>\n\n<p>Note the virtual <code>Compare</code> method and protected <code>SortArray</code> so you can create specialized subclasses that always sort on a particular column or do specialized sorting on multiple columns or whatever you want to do. That's also why <code>CompareStrings</code> is broken out and protected - any subclasses can use it for simple comparisons instead of typing out the full <code>SortArray[x, col].CompareTo(SortArray[y, col])</code> syntax.</p>\n"
},
{
"answer_id": 38155641,
"author": "Mamoon Ahmed",
"author_id": 5647662,
"author_profile": "https://Stackoverflow.com/users/5647662",
"pm_score": 0,
"selected": false,
"text": "<p>I know its late but here is my thought you might wanna consider.</p>\n\n<p>for example this is array</p>\n\n<pre><code>{\nm,m,m\na,a,a\nb,b,b\nj,j,j\nk,l,m\n}\n</code></pre>\n\n<p>and you want to convert it by column number 2, then </p>\n\n<pre><code>string[] newArr = new string[arr.length]\nfor(int a=0;a<arr.length;a++)\n newArr[a] = arr[a][1] + a;\n\n// create new array that contains index number at the end and also the column values\nArray.Sort(newArr);\nfor(int a=0;a<newArr.length;a++)\n{\n int index = Convert.ToInt32(newArr[a][newArr[a].Length -1]);\n //swap whole row with tow at current index\n if(index != a)\n {\n string[] arr2 = arr[a];\n arr[a] = arr[index];\n arr[index] = arr2;\n }\n}\n</code></pre>\n\n<p>Congratulations you have sorted the array by desired column. You can edit this to make it work with other data types</p>\n"
},
{
"answer_id": 59003014,
"author": "AllenJolley",
"author_id": 12418768,
"author_profile": "https://Stackoverflow.com/users/12418768",
"pm_score": 3,
"selected": false,
"text": "<pre><code>Array.Sort(array, (a, b) => { return a[0] - b[0]; });\n</code></pre>\n"
},
{
"answer_id": 70630809,
"author": "Shubham Sharma",
"author_id": 4446810,
"author_profile": "https://Stackoverflow.com/users/4446810",
"pm_score": -1,
"selected": false,
"text": "<p>Assuming it is a jagged array, you can use LINQ or Array.Sort() method to sort it.</p>\n<p><strong>Method 1: Using LINQ</strong></p>\n<pre><code>var myOrderedRows = myArray.OrderBy(row => row[columnIndex]).ToArray();\n</code></pre>\n<p>Here, LINQ creates a new IEnumerable which needs to be converted to array (using <code>ToArray()</code>) myOrderedRows. Your original array is still unsorted. More details can be found in docs <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.orderby?view=net-6.0\" rel=\"nofollow noreferrer\">here</a>.</p>\n<p><strong>Method 2: Using Array.Sort()</strong></p>\n<pre><code>Array.Sort(myArray, (p, q) => p[columnIndex].CompareTo(q[columnIndex]));\n</code></pre>\n<p>In this case your original array is sorted in place. You can also provide custom Comparer for more comparison rules. More details can be found in docs <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.array.sort?view=net-6.0\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 73190340,
"author": "Jan Lacina",
"author_id": 14104519,
"author_profile": "https://Stackoverflow.com/users/14104519",
"pm_score": 0,
"selected": false,
"text": "<p>Short way, but be careful of performance in big arrays and must have n-count of columns:</p>\n<p>This will order it from the last number to the first. In case of need reverse it from 0 to "hero":</p>\n<pre class=\"lang-cs prettyprint-override\"><code>for (int i = n-1; i >= 0; i--)\n{\n resultsAsArray = resultsAsArray.OrderBy(x => x[i]).ToArray();\n}\n\n</code></pre>\n<p><strong>Example <em>(do not be surprised, that 3 is first, 2 after that - those are negative, so -3 is lesser than -2)</em></strong></p>\n<pre class=\"lang-cs prettyprint-override\"><code>var original = new int[][] { new int[] { -3, 1, 2 }, new int[] { -2, -1, 3 }, new int[] { -3, -1, 4 }, new int[] { -3, -2, 5 } };\n\n*var processed = new int[][] { new int[] { -3, -2, 5 }, new int[] { -3, -1, 4 }, new int[] { -3, 1, 2 }, new int[] { -2, -1, 3 } };\n</code></pre>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/232395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15052/"
] |
I have a two-dimensional array (of Strings) which make up my data table (of rows and columns). I want to sort this array by any column. I tried to find an algorithm for doing this in C#, but have not been successful.
Any help is appreciated.
|
Load your two-dimensional string array into an actual DataTable (System.Data.DataTable), and then use the DataTable object's Select() method to generate a sorted array of DataRow objects (or use a DataView for a similar effect).
```
// assumes stringdata[row, col] is your 2D string array
DataTable dt = new DataTable();
// assumes first row contains column names:
for (int col = 0; col < stringdata.GetLength(1); col++)
{
dt.Columns.Add(stringdata[0, col]);
}
// load data from string array to data table:
for (rowindex = 1; rowindex < stringdata.GetLength(0); rowindex++)
{
DataRow row = dt.NewRow();
for (int col = 0; col < stringdata.GetLength(1); col++)
{
row[col] = stringdata[rowindex, col];
}
dt.Rows.Add(row);
}
// sort by third column:
DataRow[] sortedrows = dt.Select("", "3");
// sort by column name, descending:
sortedrows = dt.Select("", "COLUMN3 DESC");
```
You could also write your own method to sort a two-dimensional array. Both approaches would be useful learning experiences, but the DataTable approach would get you started on learning a better way of handling tables of data in a C# application.
|
232,435 |
<p>I have a two way foreign relation similar to the following</p>
<pre><code>class Parent(models.Model):
name = models.CharField(max_length=255)
favoritechild = models.ForeignKey("Child", blank=True, null=True)
class Child(models.Model):
name = models.CharField(max_length=255)
myparent = models.ForeignKey(Parent)
</code></pre>
<p>How do I restrict the choices for Parent.favoritechild to only children whose parent is itself? I tried</p>
<pre><code>class Parent(models.Model):
name = models.CharField(max_length=255)
favoritechild = models.ForeignKey("Child", blank=True, null=True, limit_choices_to = {"myparent": "self"})
</code></pre>
<p>but that causes the admin interface to not list any children.</p>
|
[
{
"answer_id": 232644,
"author": "Eric Holscher",
"author_id": 4169,
"author_profile": "https://Stackoverflow.com/users/4169",
"pm_score": 4,
"selected": false,
"text": "<p>This isn't how django works. You would only create the relation going one way.</p>\n\n<pre><code>class Parent(models.Model):\n name = models.CharField(max_length=255)\n\nclass Child(models.Model):\n name = models.CharField(max_length=255)\n myparent = models.ForeignKey(Parent)\n</code></pre>\n\n<p>And if you were trying to access the children from the parent you would do\n<code>parent_object.child_set.all()</code>. If you set a related_name in the myparent field, then that is what you would refer to it as. Ex: <code>related_name='children'</code>, then you would do <code>parent_object.children.all()</code></p>\n\n<p>Read the <a href=\"http://docs.djangoproject.com/en/dev/topics/db/models/#many-to-one-relationships\" rel=\"noreferrer\">docs</a> <a href=\"http://docs.djangoproject.com/en/dev/topics/db/models/#many-to-one-relationships\" rel=\"noreferrer\">http://docs.djangoproject.com/en/dev/topics/db/models/#many-to-one-relationships</a> for more.</p>\n"
},
{
"answer_id": 232969,
"author": "Ber",
"author_id": 11527,
"author_profile": "https://Stackoverflow.com/users/11527",
"pm_score": 2,
"selected": false,
"text": "<p>Do you want to restrict the choices available in the admin interface when creating/editing a model instance?</p>\n\n<p>One way to do this is validation of the model. This lets you raise an error in the admin interface if the foreign field is not the right choice.</p>\n\n<p>Of course, Eric's answer is correct: You only really need one foreign key, from child to parent here.</p>\n"
},
{
"answer_id": 234325,
"author": "Jeff Mc",
"author_id": 25521,
"author_profile": "https://Stackoverflow.com/users/25521",
"pm_score": 2,
"selected": false,
"text": "<p>@Ber: I have added validation to the model similar to this</p>\n\n<pre><code>class Parent(models.Model):\n name = models.CharField(max_length=255)\n favoritechild = models.ForeignKey(\"Child\", blank=True, null=True)\n def save(self, force_insert=False, force_update=False):\n if self.favoritechild is not None and self.favoritechild.myparent.id != self.id:\n raise Exception(\"You must select one of your own children as your favorite\")\n super(Parent, self).save(force_insert, force_update)\n</code></pre>\n\n<p>which works exactly how I want, but it would be really nice if this validation could restrict choices in the dropdown in the admin interface rather than validating after the choice.</p>\n"
},
{
"answer_id": 252087,
"author": "Ber",
"author_id": 11527,
"author_profile": "https://Stackoverflow.com/users/11527",
"pm_score": 7,
"selected": true,
"text": "<p>I just came across <a href=\"http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.limit_choices_to\" rel=\"noreferrer\">ForeignKey.limit_choices_to</a> in the Django docs.\nNot sure yet how this works, but it might just be the right thing here.</p>\n\n<p><strong>Update:</strong> ForeignKey.limit_choices_to allows to specify either a constant, a callable or a Q object to restrict the allowable choices for the key. A constant obviously is of no use here, since it knows nothing about the objects involved.</p>\n\n<p>Using a callable (function or class method or any callable object) seems more promising. However, the problem of how to access the necessary information from the HttpRequest object remains. Using <a href=\"https://stackoverflow.com/questions/160009/django-model-limitchoicestouser-user\">thread local storage</a> may be a solution.</p>\n\n<p><strong>2. Update:</strong> Here is what has worked for me:</p>\n\n<p>I created a middleware as described in the link above. It extracts one or more arguments from the request's GET part, such as \"product=1\", and stores this information in the thread locals.</p>\n\n<p>Next there is a class method in the model that reads the thread local variable and returns a list of ids to limit the choice of a foreign key field.</p>\n\n<pre><code>@classmethod\ndef _product_list(cls):\n \"\"\"\n return a list containing the one product_id contained in the request URL,\n or a query containing all valid product_ids if not id present in URL\n\n used to limit the choice of foreign key object to those related to the current product\n \"\"\"\n id = threadlocals.get_current_product()\n if id is not None:\n return [id]\n else:\n return Product.objects.all().values('pk').query\n</code></pre>\n\n<p>It is important to return a query containing all possible ids if none was selected so that the normal admin pages work ok.</p>\n\n<p>The foreign key field is then declared as:</p>\n\n<pre><code>product = models.ForeignKey(\n Product,\n limit_choices_to={\n id__in=BaseModel._product_list,\n },\n)\n</code></pre>\n\n<p>The catch is that you have to provide the information to restrict the choices via the request. I don't see a way to access \"self\" here.</p>\n"
},
{
"answer_id": 1749330,
"author": "Anentropic",
"author_id": 202168,
"author_profile": "https://Stackoverflow.com/users/202168",
"pm_score": 2,
"selected": false,
"text": "<p>I'm trying to do something similar. It seems like everyone saying 'you should only have a foreign key one way' has maybe misunderstood what you're trying do.</p>\n\n<p>It's a shame the limit_choices_to={\"myparent\": \"self\"} you wanted to do doesn't work... that would have been clean and simple. Unfortunately the 'self' doesn't get evaluated and goes through as a plain string.</p>\n\n<p>I thought maybe I could do:</p>\n\n<pre><code>class MyModel(models.Model):\n def _get_self_pk(self):\n return self.pk\n favourite = models.ForeignKey(limit_choices_to={'myparent__pk':_get_self_pk})\n</code></pre>\n\n<p>But alas that gives an error because the function doesn't get passed a self arg :(</p>\n\n<p>It seems like the only way is to put the logic into all the forms that use this model (ie pass a queryset in to the choices for your formfield). Which is easily done, but it'd be more DRY to have this at the model level. Your overriding the save method of the model seems a good way to prevent invalid choices getting through.</p>\n\n<p><strong>Update</strong><br>\nSee my later answer for another way <a href=\"https://stackoverflow.com/a/3753916/202168\">https://stackoverflow.com/a/3753916/202168</a></p>\n"
},
{
"answer_id": 3753916,
"author": "Anentropic",
"author_id": 202168,
"author_profile": "https://Stackoverflow.com/users/202168",
"pm_score": 2,
"selected": false,
"text": "<p>An alternative approach would be not to have 'favouritechild' fk as a field on the Parent model.</p>\n\n<p>Instead you could have an is_favourite boolean field on the Child.</p>\n\n<p>This may help:\n<a href=\"https://github.com/anentropic/django-exclusivebooleanfield\" rel=\"nofollow noreferrer\">https://github.com/anentropic/django-exclusivebooleanfield</a></p>\n\n<p>That way you'd sidestep the whole problem of ensuring Children could only be made the favourite of the Parent they belong to.</p>\n\n<p>The view code would be slightly different but the filtering logic would be straightforward.</p>\n\n<p>In the admin you could even have an inline for Child models that exposed the is_favourite checkbox (if you only have a few children per parent) otherwise the admin would have to be done from the Child's side.</p>\n"
},
{
"answer_id": 4653418,
"author": "White Box Dev",
"author_id": 105792,
"author_profile": "https://Stackoverflow.com/users/105792",
"pm_score": 4,
"selected": false,
"text": "<p>The new \"right\" way of doing this, at least since Django 1.1 is by overriding the AdminModel.formfield_for_foreignkey(self, db_field, request, **kwargs). </p>\n\n<p>See <a href=\"http://docs.djangoproject.com/en/1.2/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_for_foreignkey\" rel=\"noreferrer\">http://docs.djangoproject.com/en/1.2/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_for_foreignkey</a></p>\n\n<p>For those who don't want to follow the link below is an example function that is close for the above questions models.</p>\n\n<pre><code>class MyModelAdmin(admin.ModelAdmin):\n def formfield_for_foreignkey(self, db_field, request, **kwargs):\n if db_field.name == \"favoritechild\":\n kwargs[\"queryset\"] = Child.objects.filter(myparent=request.object_id)\n return super(MyModelAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)\n</code></pre>\n\n<p>I'm only not sure about how to get the current object that is being edited. I expect it is actually on the self somewhere but I'm not sure.</p>\n"
},
{
"answer_id": 19556353,
"author": "s29",
"author_id": 489638,
"author_profile": "https://Stackoverflow.com/users/489638",
"pm_score": 5,
"selected": false,
"text": "<p>The 'right' way to do it is to use a custom form. From there, you can access self.instance, which is the current object. Example --</p>\n\n<pre><code>from django import forms\nfrom django.contrib import admin \nfrom models import *\n\nclass SupplierAdminForm(forms.ModelForm):\n class Meta:\n model = Supplier\n fields = \"__all__\" # for Django 1.8+\n\n\n def __init__(self, *args, **kwargs):\n super(SupplierAdminForm, self).__init__(*args, **kwargs)\n if self.instance:\n self.fields['cat'].queryset = Cat.objects.filter(supplier=self.instance)\n\nclass SupplierAdmin(admin.ModelAdmin):\n form = SupplierAdminForm\n</code></pre>\n"
},
{
"answer_id": 29455444,
"author": "wasabigeek",
"author_id": 1839532,
"author_profile": "https://Stackoverflow.com/users/1839532",
"pm_score": 4,
"selected": false,
"text": "<p>If you only need the limitations in the Django admin interface, this might work. I based it on <a href=\"http://w3facility.org/question/django-limit-manytomany-queryset-based-on-selected-fk/#answer-13147522\" rel=\"noreferrer\">this answer</a> from another forum - although it's for ManyToMany relationships, you should be able to replace <code>formfield_for_foreignkey</code> for it to work. In <code>admin.py</code>:</p>\n\n<pre><code>class ParentAdmin(admin.ModelAdmin):\n def get_form(self, request, obj=None, **kwargs):\n self.instance = obj\n return super(ParentAdmin, self).get_form(request, obj=obj, **kwargs)\n\n def formfield_for_foreignkey(self, db_field, request=None, **kwargs):\n if db_field.name == 'favoritechild' and self.instance: \n kwargs['queryset'] = Child.objects.filter(myparent=self.instance.pk)\n return super(ChildAdmin, self).formfield_for_foreignkey(db_field, request=request, **kwargs)\n</code></pre>\n"
},
{
"answer_id": 35395212,
"author": "Øyvind Saltvik",
"author_id": 5925860,
"author_profile": "https://Stackoverflow.com/users/5925860",
"pm_score": -1,
"selected": false,
"text": "<pre><code>from django.contrib import admin\nfrom sopin.menus.models import Restaurant, DishType\n\nclass ObjInline(admin.TabularInline):\n def __init__(self, parent_model, admin_site, obj=None):\n self.obj = obj\n super(ObjInline, self).__init__(parent_model, admin_site)\n\nclass ObjAdmin(admin.ModelAdmin):\n\n def get_inline_instances(self, request, obj=None):\n inline_instances = []\n for inline_class in self.inlines:\n inline = inline_class(self.model, self.admin_site, obj)\n if request:\n if not (inline.has_add_permission(request) or\n inline.has_change_permission(request, obj) or\n inline.has_delete_permission(request, obj)):\n continue\n if not inline.has_add_permission(request):\n inline.max_num = 0\n inline_instances.append(inline)\n\n return inline_instances\n\n\n\nclass DishTypeInline(ObjInline):\n model = DishType\n\n def formfield_for_foreignkey(self, db_field, request=None, **kwargs):\n field = super(DishTypeInline, self).formfield_for_foreignkey(db_field, request, **kwargs)\n if db_field.name == 'dishtype':\n if self.obj is not None:\n field.queryset = field.queryset.filter(restaurant__exact = self.obj) \n else:\n field.queryset = field.queryset.none()\n\n return field\n\nclass RestaurantAdmin(ObjAdmin):\n inlines = [\n DishTypeInline\n ]\n</code></pre>\n"
},
{
"answer_id": 64581746,
"author": "Dcode22",
"author_id": 14100714,
"author_profile": "https://Stackoverflow.com/users/14100714",
"pm_score": 1,
"selected": false,
"text": "<p>A much simpler variation of @s29's answer:</p>\n<p>Instead of customising the form,\n<strong>You can simply restrict the choices available in form field from your view:</strong></p>\n<p>what worked for me was:\nin forms.py:</p>\n<pre><code>class AddIncomingPaymentForm(forms.ModelForm):\n class Meta: \n model = IncomingPayment\n fields = ('description', 'amount', 'income_source', 'income_category', 'bank_account')\n</code></pre>\n<p>in views.py:</p>\n<pre><code>def addIncomingPayment(request):\n form = AddIncomingPaymentForm()\n form.fields['bank_account'].queryset = BankAccount.objects.filter(profile=request.user.profile)\n</code></pre>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/232435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25521/"
] |
I have a two way foreign relation similar to the following
```
class Parent(models.Model):
name = models.CharField(max_length=255)
favoritechild = models.ForeignKey("Child", blank=True, null=True)
class Child(models.Model):
name = models.CharField(max_length=255)
myparent = models.ForeignKey(Parent)
```
How do I restrict the choices for Parent.favoritechild to only children whose parent is itself? I tried
```
class Parent(models.Model):
name = models.CharField(max_length=255)
favoritechild = models.ForeignKey("Child", blank=True, null=True, limit_choices_to = {"myparent": "self"})
```
but that causes the admin interface to not list any children.
|
I just came across [ForeignKey.limit\_choices\_to](http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.limit_choices_to) in the Django docs.
Not sure yet how this works, but it might just be the right thing here.
**Update:** ForeignKey.limit\_choices\_to allows to specify either a constant, a callable or a Q object to restrict the allowable choices for the key. A constant obviously is of no use here, since it knows nothing about the objects involved.
Using a callable (function or class method or any callable object) seems more promising. However, the problem of how to access the necessary information from the HttpRequest object remains. Using [thread local storage](https://stackoverflow.com/questions/160009/django-model-limitchoicestouser-user) may be a solution.
**2. Update:** Here is what has worked for me:
I created a middleware as described in the link above. It extracts one or more arguments from the request's GET part, such as "product=1", and stores this information in the thread locals.
Next there is a class method in the model that reads the thread local variable and returns a list of ids to limit the choice of a foreign key field.
```
@classmethod
def _product_list(cls):
"""
return a list containing the one product_id contained in the request URL,
or a query containing all valid product_ids if not id present in URL
used to limit the choice of foreign key object to those related to the current product
"""
id = threadlocals.get_current_product()
if id is not None:
return [id]
else:
return Product.objects.all().values('pk').query
```
It is important to return a query containing all possible ids if none was selected so that the normal admin pages work ok.
The foreign key field is then declared as:
```
product = models.ForeignKey(
Product,
limit_choices_to={
id__in=BaseModel._product_list,
},
)
```
The catch is that you have to provide the information to restrict the choices via the request. I don't see a way to access "self" here.
|
232,445 |
<p>I'm just starting to learn C++ so excuse me for this simple question. What I'm doing is reading in numbers from a file and then trying to add them to an array. My problem is how do you increase the size of the array? For example I thought might be able to just do:</p>
<pre><code>#include <iostream>
using namespace std;
int main() {
double *x;
x = new double[1];
x[0]=5;
x = new double[1];
x[1]=6;
cout << x[0] << "," << x[1] << endl;
return 0;
}
</code></pre>
<p>But this obviously just overwrites the value, 5, that I initially set to x[0] and so outputs 0,6. How would I make it so that it would output 5,6?<br /><br />Please realize that for the example I've included I didn't want to clutter it up with the code reading from a file or code to get numbers from a user. In the actual application I won't know how big of an array I need at compile time so please don't tell me to just make an array with two elements and set them equal to 5 and 6 respectively.<br /><br />Thanks for your help.</p>
|
[
{
"answer_id": 232454,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 5,
"selected": true,
"text": "<p>You don't want to work with arrays directly. Consider using a <code>vector</code>, instead. Then, you can call the <code>push_back</code> function to add things to the end, and it will automatically resize the vector for you.</p>\n\n<pre><code>#include <iostream>\n#include <vector>\n\nint\nmain() {\n double value;\n std::vector<double> values;\n\n // Read in values\n while (std::cin >> value) {\n values.push_back(value);\n }\n\n // Print them back out\n for (std::size_t i(0), len(values.size()); i != len; ++i) {\n std::cout << values[i];\n }\n}\n</code></pre>\n"
},
{
"answer_id": 232455,
"author": "Ty.",
"author_id": 16948,
"author_profile": "https://Stackoverflow.com/users/16948",
"pm_score": 2,
"selected": false,
"text": "<p>You should use a collection class to do this for you rather than managing it yourself. Have a look at the \"vector\" class. It's essentially a dynamic array that resizes automatically as required.</p>\n\n<p>In your situation you would use \"vector\" with the \"double\" type. You may also need to read up on templates in C++.</p>\n\n<p><a href=\"http://www.cplusplus.com/reference/stl/vector/\" rel=\"nofollow noreferrer\">http://www.cplusplus.com/reference/stl/vector/</a></p>\n"
},
{
"answer_id": 232462,
"author": "markets",
"author_id": 4662,
"author_profile": "https://Stackoverflow.com/users/4662",
"pm_score": 2,
"selected": false,
"text": "<p>Or, if you don't want to use STL or another dynamic thing, you can just create the array with the correct size from the beginning: x = new double[2];</p>\n\n<p>Of course the problem there is how big to make it. If you don't know, then you'll need to just create it \"big enough\" (like a hundred, or a thousand)... which, at some point, won't be big enough and it will fail in some random looking way. So then you'll need to resize it. And once you get to that point, you'll wish you'd used the STL from the start, like the other answers are telling you to do.</p>\n\n<pre><code>#include <iostream>\nusing namespace std;\nint main() {\n double *x = new double[2];\n x[0]=5;\n x[1]=6;\n cout << x[0] << \",\" << x[1] << endl;\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 232468,
"author": "Moishe Lettvin",
"author_id": 23786,
"author_profile": "https://Stackoverflow.com/users/23786",
"pm_score": 2,
"selected": false,
"text": "<p>If for some reason you don't have access to STL -- or want to learn how to do this yourself -- you could use an algorithm like this:</p>\n\n<p>Allocate your array as some arbitrary size, and remember how many elements are in it and how big it is:</p>\n\n<pre><code>int *a = malloc(int * ARBITRARY_SIZE);\nint size = 0;\nint allocated = ARBITRARY_SIZE;\n</code></pre>\n\n<p>each time you add a new element, increase \"size\". If size equals ARBITRARY_SIZE, multiply 'allocated' by 2, and reallocate the array. Either way, assign the new value to a[size].</p>\n\n<pre><code>void addElement(int value) {\n ++size;\n\n if (size == allocated) {\n allocated *= 2;\n a = realloc(sizeof(int) * allocated);\n a = new_a;\n }\n\n a[size] = value;\n}\n</code></pre>\n\n<p>Note that your code above has at least one bug -- you aren't allocating enough space for x[1] in either case.</p>\n\n<p>Also obviously in real code you'd check that the return from malloc & realloc isn't null.</p>\n"
},
{
"answer_id": 232497,
"author": "Shadow2531",
"author_id": 1697,
"author_profile": "https://Stackoverflow.com/users/1697",
"pm_score": 2,
"selected": false,
"text": "<p>Here's an example though for good measure, so you can see the pattern:</p>\n\n<pre><code>#include <iostream>\nusing namespace std;\n\nint main() {\n // Allocate some memory for a double array of size 1 and store\n // an address to the beginning of the memory in mem_address.\n double* mem_address = new double[1];\n\n // Assign 5 to the first element in the array.\n mem_address[0] = 5;\n\n // Save the address of the memory mem_address is currently\n // referencing.\n double* saved_address = mem_address;\n\n // Allocate some memory for a double array of size 2 and store\n // an address to the beginning of the memory in mem_address.\n mem_address = new double[2];\n\n // Copy over the 1 element from the first memory block\n // to the new one.\n mem_address[0] = saved_address[0];\n\n // Done with the old memory, so clean it up.\n delete [] saved_address;\n\n // Assign 6 to the second element in the new array.\n mem_address[1] = 6;\n\n // Print out the 2 elements in the new array.\n cout << mem_address[0] << \"\\n\";\n cout << mem_address[1] << \"\\n\";\n\n // Done with the new array memory now, so clean it up.\n delete [] mem_address;\n}\n</code></pre>\n"
},
{
"answer_id": 232536,
"author": "Abhishek Yadav",
"author_id": 30252,
"author_profile": "https://Stackoverflow.com/users/30252",
"pm_score": 0,
"selected": false,
"text": "<p>An array always needs a contiguous block of memory. In a situation where you might need to resize the array later on, reallocation is probably the only solution. This is what Moishe and Shadow2531 do above. </p>\n\n<p>The problem with reallocation is that it can be a costly operation. So if you need adding 5 more elements to a 5000 element array, you might end up copying all the 5000 elements across memory.</p>\n\n<p>Using a linked list instead can be considered for such a scenario.</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/232445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38/"
] |
I'm just starting to learn C++ so excuse me for this simple question. What I'm doing is reading in numbers from a file and then trying to add them to an array. My problem is how do you increase the size of the array? For example I thought might be able to just do:
```
#include <iostream>
using namespace std;
int main() {
double *x;
x = new double[1];
x[0]=5;
x = new double[1];
x[1]=6;
cout << x[0] << "," << x[1] << endl;
return 0;
}
```
But this obviously just overwrites the value, 5, that I initially set to x[0] and so outputs 0,6. How would I make it so that it would output 5,6?
Please realize that for the example I've included I didn't want to clutter it up with the code reading from a file or code to get numbers from a user. In the actual application I won't know how big of an array I need at compile time so please don't tell me to just make an array with two elements and set them equal to 5 and 6 respectively.
Thanks for your help.
|
You don't want to work with arrays directly. Consider using a `vector`, instead. Then, you can call the `push_back` function to add things to the end, and it will automatically resize the vector for you.
```
#include <iostream>
#include <vector>
int
main() {
double value;
std::vector<double> values;
// Read in values
while (std::cin >> value) {
values.push_back(value);
}
// Print them back out
for (std::size_t i(0), len(values.size()); i != len; ++i) {
std::cout << values[i];
}
}
```
|
232,472 |
<p>In C and C++ what do the following declarations do?</p>
<pre><code>const int * i;
int * const i;
const volatile int ip;
const int *i;
</code></pre>
<p>Are any of the above declarations wrong?</p>
<p>If not what is the meaning and differences between them?</p>
<p>What are the useful uses of above declarations (I mean in which situation we have to use them in C/C++/embedded C)?</p>
|
[
{
"answer_id": 232479,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 5,
"selected": false,
"text": "<p><code>const int * i;</code></p>\n\n<p><code>i</code> is a pointer to constant integer. <code>i</code> can be changed to point to a different value, but the value being pointed to by <code>i</code> can not be changed.</p>\n\n<p><code>int * const i;</code></p>\n\n<p><code>i</code> is a constant pointer to a non-constant integer. The value pointed to by <code>i</code> can be changed, but <code>i</code> cannot be changed to point to a different value.</p>\n\n<p><code>const volatile int ip;</code></p>\n\n<p>This one is kind of tricky. The fact that <code>ip</code> is <code>const</code> means that the compiler will not let you change the value of <code>ip</code>. However, it could still be modified in theory, e.g. by taking its address and using the <code>const_cast</code> operator. This is very dangerous and not a good idea, but it is allowed. The <code>volatile</code> qualifier indicates that any time <code>ip</code> is accessed, it should always be reloaded from memory, i.e. it should NOT be cached in a register. This prevents the compiler from making certain optimizations. You want to use the <code>volatile</code> qualifier when you have a variable which might be modified by another thread, or if you're using memory-mapped I/O, or other similar situations which could cause behavior the compiler might not be expecting. Using <code>const</code> and <code>volatile</code> on the same variable is rather unusual (but legal) -- you'll usually see one but not the other.</p>\n\n<p><code>const int *i;</code></p>\n\n<p>This is the same as the first declaration.</p>\n"
},
{
"answer_id": 232480,
"author": "Ty.",
"author_id": 16948,
"author_profile": "https://Stackoverflow.com/users/16948",
"pm_score": 2,
"selected": false,
"text": "<p>You read variables declarations in C/C++ right-to-left, so to speak.</p>\n\n<pre><code>const int *i; // pointer to a constant int (the integer value doesn't change)\n\nint *const i; // constant pointer to an int (what i points to doesn't change)\n\nconst volatile int ip; // a constant integer whose value will never be cached by the system\n</code></pre>\n\n<p>They each have their own purposes. Any C++ textbook or half decent resource will have explanations of each.</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/232472",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
In C and C++ what do the following declarations do?
```
const int * i;
int * const i;
const volatile int ip;
const int *i;
```
Are any of the above declarations wrong?
If not what is the meaning and differences between them?
What are the useful uses of above declarations (I mean in which situation we have to use them in C/C++/embedded C)?
|
`const int * i;`
`i` is a pointer to constant integer. `i` can be changed to point to a different value, but the value being pointed to by `i` can not be changed.
`int * const i;`
`i` is a constant pointer to a non-constant integer. The value pointed to by `i` can be changed, but `i` cannot be changed to point to a different value.
`const volatile int ip;`
This one is kind of tricky. The fact that `ip` is `const` means that the compiler will not let you change the value of `ip`. However, it could still be modified in theory, e.g. by taking its address and using the `const_cast` operator. This is very dangerous and not a good idea, but it is allowed. The `volatile` qualifier indicates that any time `ip` is accessed, it should always be reloaded from memory, i.e. it should NOT be cached in a register. This prevents the compiler from making certain optimizations. You want to use the `volatile` qualifier when you have a variable which might be modified by another thread, or if you're using memory-mapped I/O, or other similar situations which could cause behavior the compiler might not be expecting. Using `const` and `volatile` on the same variable is rather unusual (but legal) -- you'll usually see one but not the other.
`const int *i;`
This is the same as the first declaration.
|
232,475 |
<p>I need to add unit testing to some old scripts, the scripts are all basically in the following form:</p>
<pre><code>#!/usr/bin/perl
# Main code
foo();
bar();
# subs
sub foo {
}
sub bar {
}
</code></pre>
<p>If I try to 'require' this code in a unit test, the main section of the code will run, where as I want to be able to just test "foo" in isolation.</p>
<p>Is there any way to do this without moving foo,bar into a seperate .pm file?</p>
|
[
{
"answer_id": 232552,
"author": "ysth",
"author_id": 17389,
"author_profile": "https://Stackoverflow.com/users/17389",
"pm_score": 4,
"selected": false,
"text": "<p>Assuming you have no security concerns, wrap it in a sub { ... } and eval it:</p>\n\n<pre><code>use File::Slurp \"read_file\";\neval \"package Script; sub {\" . read_file(\"script\") . \"}\";\n\nis(Script::foo(), \"foo\");\n</code></pre>\n\n<p>(taking care that the eval isn't in scope of any lexicals that would be closed over by the script).</p>\n"
},
{
"answer_id": 232723,
"author": "Ovid",
"author_id": 8003,
"author_profile": "https://Stackoverflow.com/users/8003",
"pm_score": 5,
"selected": true,
"text": "<p>Another common trick for unit testing scripts is to wrap the body of their code into a 'caller' block:</p>\n\n<pre><code>#!/usr/bin/perl\n\nuse strict;\nuse warnings;\n\nunless (caller) {\n # startup code\n}\n\nsub foo { ... }\n</code></pre>\n\n<p>When run from the command line, cron, a bash script, etc., it runs normally. However, if you load it from another Perl program, the \"unless (caller) {...}\" code does not run. Then in your test program, declare a namespace (since the script is probably running code in package main::) and 'do' the script.</p>\n\n<pre><code>#!/usr/bin/perl\n\npackage Tests::Script; # avoid the Test:: namespace to avoid conflicts\n # with testing modules\nuse strict;\nuse warnings;\n\ndo 'some_script' or die \"Cannot (do 'some_script'): $!\";\n\n# write your tests\n</code></pre>\n\n<p>'do' is more efficient than eval and fairly clean for this.</p>\n\n<p>Another trick for testing scripts is to use <a href=\"http://search.cpan.org/dist/Expect/\" rel=\"noreferrer\">Expect</a>. This is cleaner, but is also harder to use and it won't let you override anything within the script if you need to mock anything up.</p>\n"
},
{
"answer_id": 232787,
"author": "Schwern",
"author_id": 14660,
"author_profile": "https://Stackoverflow.com/users/14660",
"pm_score": 4,
"selected": false,
"text": "<p>Ahh, the old \"how do I unit test a program\" question. The simplest trick is to put this in your program before it starts doing things:</p>\n\n<pre><code>return 1 unless $0 eq __FILE__;\n</code></pre>\n\n<p><code>__FILE__</code> is the current source file. <code>$0</code> is the name of the program being run. If they are the same, your code is being executed as a program. If they're different, it's being loaded as a library.</p>\n\n<p>That's enough to let you start unit testing the subroutines inside your program.</p>\n\n<pre><code>require \"some/program\";\n...and test...\n</code></pre>\n\n<p>Next step is to move all the code outside a subroutine into <code>main</code>, then you can do this:</p>\n\n<pre><code>main() if $0 eq __FILE__;\n</code></pre>\n\n<p>and now you can test main() just like any other subroutine.</p>\n\n<p>Once that's done you can start contemplating moving the program's subroutines out into their own real libraries.</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/232475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3839/"
] |
I need to add unit testing to some old scripts, the scripts are all basically in the following form:
```
#!/usr/bin/perl
# Main code
foo();
bar();
# subs
sub foo {
}
sub bar {
}
```
If I try to 'require' this code in a unit test, the main section of the code will run, where as I want to be able to just test "foo" in isolation.
Is there any way to do this without moving foo,bar into a seperate .pm file?
|
Another common trick for unit testing scripts is to wrap the body of their code into a 'caller' block:
```
#!/usr/bin/perl
use strict;
use warnings;
unless (caller) {
# startup code
}
sub foo { ... }
```
When run from the command line, cron, a bash script, etc., it runs normally. However, if you load it from another Perl program, the "unless (caller) {...}" code does not run. Then in your test program, declare a namespace (since the script is probably running code in package main::) and 'do' the script.
```
#!/usr/bin/perl
package Tests::Script; # avoid the Test:: namespace to avoid conflicts
# with testing modules
use strict;
use warnings;
do 'some_script' or die "Cannot (do 'some_script'): $!";
# write your tests
```
'do' is more efficient than eval and fairly clean for this.
Another trick for testing scripts is to use [Expect](http://search.cpan.org/dist/Expect/). This is cleaner, but is also harder to use and it won't let you override anything within the script if you need to mock anything up.
|
232,535 |
<p>What's the best way to call a generic method when the type parameter isn't known at compile time, but instead is obtained dynamically at runtime?</p>
<p>Consider the following sample code - inside the <code>Example()</code> method, what's the most concise way to invoke <code>GenericMethod<T>()</code> using the <code>Type</code> stored in the <code>myType</code> variable?</p>
<pre><code>public class Sample
{
public void Example(string typeName)
{
Type myType = FindType(typeName);
// What goes here to call GenericMethod<T>()?
GenericMethod<myType>(); // This doesn't work
// What changes to call StaticMethod<T>()?
Sample.StaticMethod<myType>(); // This also doesn't work
}
public void GenericMethod<T>()
{
// ...
}
public static void StaticMethod<T>()
{
//...
}
}
</code></pre>
|
[
{
"answer_id": 232621,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 11,
"selected": true,
"text": "<p>You need to use reflection to get the method to start with, then \"construct\" it by supplying type arguments with <a href=\"http://msdn.microsoft.com/en-us/library/system.reflection.methodinfo.makegenericmethod.aspx\" rel=\"noreferrer\">MakeGenericMethod</a>:</p>\n\n<pre><code>MethodInfo method = typeof(Sample).GetMethod(nameof(Sample.GenericMethod));\nMethodInfo generic = method.MakeGenericMethod(myType);\ngeneric.Invoke(this, null);\n</code></pre>\n\n<p>For a static method, pass <code>null</code> as the first argument to <code>Invoke</code>. That's nothing to do with generic methods - it's just normal reflection.</p>\n\n<p>As noted, a lot of this is simpler as of C# 4 using <code>dynamic</code> - if you can use type inference, of course. It doesn't help in cases where type inference isn't available, such as the exact example in the question.</p>\n"
},
{
"answer_id": 5134251,
"author": "Adrian Gallero",
"author_id": 636604,
"author_profile": "https://Stackoverflow.com/users/636604",
"pm_score": 8,
"selected": false,
"text": "<p>Just an addition to the original answer. While this will work:</p>\n\n<pre><code>MethodInfo method = typeof(Sample).GetMethod(\"GenericMethod\");\nMethodInfo generic = method.MakeGenericMethod(myType);\ngeneric.Invoke(this, null);\n</code></pre>\n\n<p>It is also a little dangerous in that you lose compile-time check for <code>GenericMethod</code>. If you later do a refactoring and rename <code>GenericMethod</code>, this code won't notice and will fail at run time. Also, if there is any post-processing of the assembly (for example obfuscating or removing unused methods/classes) this code might break too.</p>\n\n<p>So, if you know the method you are linking to at compile time, and this isn't called millions of times so overhead doesn't matter, I would change this code to be:</p>\n\n<pre><code>Action<> GenMethod = GenericMethod<int>; //change int by any base type \n //accepted by GenericMethod\nMethodInfo method = this.GetType().GetMethod(GenMethod.Method.Name);\nMethodInfo generic = method.MakeGenericMethod(myType);\ngeneric.Invoke(this, null);\n</code></pre>\n\n<p>While not very pretty, you have a compile time reference to <code>GenericMethod</code> here, and if you refactor, delete or do anything with <code>GenericMethod</code>, this code will keep working, or at least break at compile time (if for example you remove <code>GenericMethod</code>). </p>\n\n<p>Other way to do the same would be to create a new wrapper class, and create it through <code>Activator</code>. I don't know if there is a better way.</p>\n"
},
{
"answer_id": 6583578,
"author": "jbtule",
"author_id": 637783,
"author_profile": "https://Stackoverflow.com/users/637783",
"pm_score": 4,
"selected": false,
"text": "<p>With C# 4.0, reflection isn't necessary as the DLR can call it using runtime types. Since using the DLR library is kind of a pain dynamically (instead of the C# compiler generating code for you), the open source framework <a href=\"https://github.com/ekonbenefits/dynamitey\" rel=\"noreferrer\">Dynamitey</a> (.net standard 1.5) gives you easy cached run-time access to the same calls the compiler would generate for you.</p>\n\n<pre><code>var name = InvokeMemberName.Create;\nDynamic.InvokeMemberAction(this, name(\"GenericMethod\", new[]{myType}));\n\n\nvar staticContext = InvokeContext.CreateStatic;\nDynamic.InvokeMemberAction(staticContext(typeof(Sample)), name(\"StaticMethod\", new[]{myType}));\n</code></pre>\n"
},
{
"answer_id": 22441650,
"author": "Mariusz Pawelski",
"author_id": 350384,
"author_profile": "https://Stackoverflow.com/users/350384",
"pm_score": 7,
"selected": false,
"text": "<p>Calling a generic method with a type parameter known only at runtime can be greatly simplified by using a <a href=\"http://msdn.microsoft.com/en-us/library/dd264741.aspx\" rel=\"noreferrer\"><code>dynamic</code></a> type instead of the reflection API.</p>\n<p>To use this technique the type must be known from the actual object (not just an instance of the <code>Type</code> class). Otherwise, you have to create an object of that type or use the standard reflection API <a href=\"https://stackoverflow.com/a/232621/350384\">solution</a>. You can create an object by using the <a href=\"http://msdn.microsoft.com/en-us/library/wccyzw83%28v=vs.110%29.aspx\" rel=\"noreferrer\">Activator.CreateInstance</a> method.</p>\n<p>If you want to call a generic method, that in "normal" usage would have had its type inferred, then it simply comes to casting the object of unknown type to <code>dynamic</code>. Here's an example:</p>\n<pre><code>class Alpha { }\nclass Beta { }\nclass Service\n{\n public void Process<T>(T item)\n {\n Console.WriteLine("item.GetType(): " + item.GetType()\n + "\\ttypeof(T): " + typeof(T));\n }\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n var a = new Alpha();\n var b = new Beta();\n\n var service = new Service();\n service.Process(a); // Same as "service.Process<Alpha>(a)"\n service.Process(b); // Same as "service.Process<Beta>(b)"\n\n var objects = new object[] { a, b };\n foreach (var o in objects)\n {\n service.Process(o); // Same as "service.Process<object>(o)"\n }\n foreach (var o in objects)\n {\n dynamic dynObj = o;\n service.Process(dynObj); // Or write "service.Process((dynamic)o)"\n }\n }\n}\n</code></pre>\n<p>And here's the output of this program:</p>\n<pre><code>item.GetType(): Alpha typeof(T): Alpha\nitem.GetType(): Beta typeof(T): Beta\nitem.GetType(): Alpha typeof(T): System.Object\nitem.GetType(): Beta typeof(T): System.Object\nitem.GetType(): Alpha typeof(T): Alpha\nitem.GetType(): Beta typeof(T): Beta\n</code></pre>\n<p><code>Process</code> is a generic instance method that writes the real type of the passed argument (by using the <code>GetType()</code> method) and the type of the generic parameter (by using <code>typeof</code> operator).</p>\n<p>By casting the object argument to <code>dynamic</code> type we deferred providing the type parameter until runtime. When the <code>Process</code> method is called with the <code>dynamic</code> argument then the compiler doesn't care about the type of this argument. The compiler generates code that at runtime checks the real types of passed arguments (by using reflection) and choose the best method to call. Here there is only this one generic method, so it's invoked with a proper type parameter.</p>\n<p>In this example, the output is the same as if you wrote:</p>\n<pre><code>foreach (var o in objects)\n{\n MethodInfo method = typeof(Service).GetMethod("Process");\n MethodInfo generic = method.MakeGenericMethod(o.GetType());\n generic.Invoke(service, new object[] { o });\n}\n</code></pre>\n<p>The version with a dynamic type is definitely shorter and easier to write. You also shouldn't worry about performance of calling this function multiple times. The next call with arguments of the same type should be faster thanks to the <a href=\"https://web.archive.org/web/20140422080408/http://blogs.msdn.com/b/samng/archive/2008/10/29/dynamic-in-c.aspx\" rel=\"noreferrer\">caching</a> mechanism in DLR. Of course, you can write code that cache invoked delegates, but by using the <code>dynamic</code> type you get this behaviour for free.</p>\n<p>If the generic method you want to call don't have an argument of a parametrized type (so its type parameter can't be inferred) then you can wrap the invocation of the generic method in a helper method like in the following example:</p>\n<pre><code>class Program\n{\n static void Main(string[] args)\n {\n object obj = new Alpha();\n\n Helper((dynamic)obj);\n }\n\n public static void Helper<T>(T obj)\n {\n GenericMethod<T>();\n }\n\n public static void GenericMethod<T>()\n {\n Console.WriteLine("GenericMethod<" + typeof(T) + ">");\n }\n}\n</code></pre>\n<h1>Increased type safety</h1>\n<p>What is really great about using <code>dynamic</code> object as a replacement for using reflection API is that you only lose compile time checking of this particular type that you don't know until runtime. Other arguments and the name of the method are staticly analysed by the compiler as usual. If you remove or add more arguments, change their types or rename method name then you'll get a compile-time error. This won't happen if you provide the method name as a string in <code>Type.GetMethod</code> and arguments as the objects array in <code>MethodInfo.Invoke</code>.</p>\n<p>Below is a simple example that illustrates how some errors can be caught at compile time (commented code) and other at runtime. It also shows how the DLR tries to resolve which method to call.</p>\n<pre><code>interface IItem { }\nclass FooItem : IItem { }\nclass BarItem : IItem { }\nclass Alpha { }\n\nclass Program\n{\n static void Main(string[] args)\n {\n var objects = new object[] { new FooItem(), new BarItem(), new Alpha() };\n for (int i = 0; i < objects.Length; i++)\n {\n ProcessItem((dynamic)objects[i], "test" + i, i);\n\n //ProcesItm((dynamic)objects[i], "test" + i, i);\n //compiler error: The name 'ProcesItm' does not\n //exist in the current context\n\n //ProcessItem((dynamic)objects[i], "test" + i);\n //error: No overload for method 'ProcessItem' takes 2 arguments\n }\n }\n\n static string ProcessItem<T>(T item, string text, int number)\n where T : IItem\n {\n Console.WriteLine("Generic ProcessItem<{0}>, text {1}, number:{2}",\n typeof(T), text, number);\n return "OK";\n }\n static void ProcessItem(BarItem item, string text, int number)\n {\n Console.WriteLine("ProcessItem with Bar, " + text + ", " + number);\n }\n}\n</code></pre>\n<p>Here we again execute some method by casting the argument to the <code>dynamic</code> type. Only verification of first argument's type is postponed to runtime. You will get a compiler error if the name of the method you're calling doesn't exist or if other arguments are invalid (wrong number of arguments or wrong types).</p>\n<p>When you pass the <code>dynamic</code> argument to a method then this call is <a href=\"https://ericlippert.com/2012/02/06/what-is-late-binding/\" rel=\"noreferrer\">lately bound</a>. Method overload resolution happens at runtime and tries to choose the best overload. So if you invoke the <code>ProcessItem</code> method with an object of <code>BarItem</code> type then you'll actually call the non-generic method, because it is a better match for this type. However, you'll get a runtime error when you pass an argument of the <code>Alpha</code> type because there's no method that can handle this object (a generic method has the constraint <code>where T : IItem</code> and <code>Alpha</code> class doesn't implement this interface). But that's the whole point. The compiler doesn't have information that this call is valid. You as a programmer know this, and you should make sure that this code runs without errors.</p>\n<h2>Return type gotcha</h2>\n<p>When you're calling a non-void method with a parameter of dynamic type, its return type will probably <a href=\"https://ericlippert.com/2012/10/22/a-method-group-of-one/\" rel=\"noreferrer\">be <code>dynamic</code> too</a>. So if you'd change previous example to this code:</p>\n<pre><code>var result = ProcessItem((dynamic)testObjects[i], "test" + i, i);\n</code></pre>\n<p>then the type of the result object would be <code>dynamic</code>. This is because the compiler don't always know which method will be called. If you know the return type of the function call then you should <a href=\"http://msdn.microsoft.com/en-us/library/dd264736.aspx\" rel=\"noreferrer\">implicitly convert</a> it to the required type so the rest of the code is statically typed:</p>\n<pre><code>string result = ProcessItem((dynamic)testObjects[i], "test" + i, i);\n</code></pre>\n<p>You'll get a runtime error if the type doesn't match.</p>\n<p>Actually, if you try to get the result value in the previous example then you'll get a runtime error in the second loop iteration. This is because you tried to save the return value of a void function.</p>\n"
},
{
"answer_id": 27870198,
"author": "Grax32",
"author_id": 1056639,
"author_profile": "https://Stackoverflow.com/users/1056639",
"pm_score": 4,
"selected": false,
"text": "<p>Adding on to <a href=\"https://stackoverflow.com/questions/232535/how-do-i-use-reflection-to-call-a-generic-method/5134251#5134251\">Adrian Gallero's answer</a>:</p>\n<p>Calling a generic method from type info involves three steps.</p>\n<p>##TLDR: Calling a known generic method with a type object can be accomplished by:##</p>\n<pre><code>((Action)GenericMethod<object>)\n .Method\n .GetGenericMethodDefinition()\n .MakeGenericMethod(typeof(string))\n .Invoke(this, null);\n</code></pre>\n<p>where <code>GenericMethod<object></code> is the method name to call and any type that satisfies the generic constraints.</p>\n<p>(Action) matches the signature of the method to be called i.e. (<code>Func<string,string,int></code> or <code>Action<bool></code>)</p>\n<p>##Step 1 is getting the MethodInfo for the generic method definition##</p>\n<p>###Method 1: Use GetMethod() or GetMethods() with appropriate types or binding flags.###</p>\n<pre><code>MethodInfo method = typeof(Sample).GetMethod("GenericMethod");\n</code></pre>\n<p>###Method 2: Create a delegate, get the MethodInfo object and then call GetGenericMethodDefinition</p>\n<p>From inside the class that contains the methods:</p>\n<pre><code>MethodInfo method = ((Action)GenericMethod<object>)\n .Method\n .GetGenericMethodDefinition();\n\nMethodInfo method = ((Action)StaticMethod<object>)\n .Method\n .GetGenericMethodDefinition();\n</code></pre>\n<p>From outside of the class that contains the methods:</p>\n<pre><code>MethodInfo method = ((Action)(new Sample())\n .GenericMethod<object>)\n .Method\n .GetGenericMethodDefinition();\n\nMethodInfo method = ((Action)Sample.StaticMethod<object>)\n .Method\n .GetGenericMethodDefinition();\n</code></pre>\n<p>In C#, the name of a method, i.e. "ToString" or "GenericMethod" actually refers to a group of methods that may contain one or more methods. Until you provide the types of the method parameters, it is not known which\nmethod you are referring to.</p>\n<p><code>((Action)GenericMethod<object>)</code> refers to the delegate for a specific method. <code>((Func<string, int>)GenericMethod<object>)</code>\nrefers to a different overload of GenericMethod</p>\n<p>###Method 3: Create a lambda expression containing a method call expression, get the MethodInfo object and then GetGenericMethodDefinition</p>\n<pre><code>MethodInfo method = ((MethodCallExpression)((Expression<Action<Sample>>)(\n (Sample v) => v.GenericMethod<object>()\n )).Body).Method.GetGenericMethodDefinition();\n</code></pre>\n<p>This breaks down to</p>\n<p>Create a lambda expression where the body is a call to your desired method.</p>\n<pre><code>Expression<Action<Sample>> expr = (Sample v) => v.GenericMethod<object>();\n</code></pre>\n<p>Extract the body and cast to MethodCallExpression</p>\n<pre><code>MethodCallExpression methodCallExpr = (MethodCallExpression)expr.Body;\n</code></pre>\n<p>Get the generic method definition from the method</p>\n<pre><code>MethodInfo methodA = methodCallExpr.Method.GetGenericMethodDefinition();\n</code></pre>\n<p>##Step 2 is calling MakeGenericMethod to create a generic method with the appropriate type(s).##</p>\n<pre><code>MethodInfo generic = method.MakeGenericMethod(myType);\n</code></pre>\n<p>##Step 3 is invoking the method with the appropriate arguments.##</p>\n<pre><code>generic.Invoke(this, null);\n</code></pre>\n"
},
{
"answer_id": 33292470,
"author": "Thierry",
"author_id": 815847,
"author_profile": "https://Stackoverflow.com/users/815847",
"pm_score": 2,
"selected": false,
"text": "<p>This is my 2 cents based on <a href=\"https://stackoverflow.com/questions/232535/how-do-i-use-reflection-to-call-a-generic-method/27870198#27870198\">Grax's answer</a>, but with two parameters required for a generic method.</p>\n\n<p>Assume your method is defined as follows in an Helpers class:</p>\n\n<pre><code>public class Helpers\n{\n public static U ConvertCsvDataToCollection<U, T>(string csvData)\n where U : ObservableCollection<T>\n {\n //transform code here\n }\n}\n</code></pre>\n\n<p>In my case, U type is always an observable collection storing object of type T.</p>\n\n<p>As I have my types predefined, I first create the \"dummy\" objects that represent the observable collection (U) and the object stored in it (T) and that will be used below to get their type when calling the Make</p>\n\n<pre><code>object myCollection = Activator.CreateInstance(collectionType);\nobject myoObject = Activator.CreateInstance(objectType);\n</code></pre>\n\n<p>Then call the GetMethod to find your Generic function:</p>\n\n<pre><code>MethodInfo method = typeof(Helpers).\nGetMethod(\"ConvertCsvDataToCollection\");\n</code></pre>\n\n<p>So far, the above call is pretty much identical as to what was explained above but with a small difference when you need have to pass multiple parameters to it.</p>\n\n<p>You need to pass an Type[] array to the MakeGenericMethod function that contains the \"dummy\" objects' types that were create above:</p>\n\n<pre><code>MethodInfo generic = method.MakeGenericMethod(\nnew Type[] {\n myCollection.GetType(),\n myObject.GetType()\n});\n</code></pre>\n\n<p>Once that's done, you need to call the Invoke method as mentioned above.</p>\n\n<pre><code>generic.Invoke(null, new object[] { csvData });\n</code></pre>\n\n<p>And you're done. Works a charm!</p>\n\n<p><strong>UPDATE:</strong></p>\n\n<p>As @Bevan highlighted, I do not need to create an array when calling the MakeGenericMethod function as it takes in params and I do not need to create an object in order to get the types as I can just pass the types directly to this function. In my case, since I have the types predefined in another class, I simply changed my code to:</p>\n\n<pre><code>object myCollection = null;\n\nMethodInfo method = typeof(Helpers).\nGetMethod(\"ConvertCsvDataToCollection\");\n\nMethodInfo generic = method.MakeGenericMethod(\n myClassInfo.CollectionType,\n myClassInfo.ObjectType\n);\n\nmyCollection = generic.Invoke(null, new object[] { csvData });\n</code></pre>\n\n<p>myClassInfo contains 2 properties of type <code>Type</code> which I set at run time based on an enum value passed to the constructor and will provide me with the relevant types which I then use in the MakeGenericMethod.</p>\n\n<p>Thanks again for highlighting this @Bevan.</p>\n"
},
{
"answer_id": 39113035,
"author": "Dimitre Novatchev",
"author_id": 36305,
"author_profile": "https://Stackoverflow.com/users/36305",
"pm_score": 4,
"selected": false,
"text": "<p><strong>Nobody provided the \"<em>classic Reflection</em>\" solution, so here is a complete code example:</strong></p>\n\n<pre><code>using System;\nusing System.Collections;\nusing System.Collections.Generic;\n\nnamespace DictionaryRuntime\n{\n public class DynamicDictionaryFactory\n {\n /// <summary>\n /// Factory to create dynamically a generic Dictionary.\n /// </summary>\n public IDictionary CreateDynamicGenericInstance(Type keyType, Type valueType)\n {\n //Creating the Dictionary.\n Type typeDict = typeof(Dictionary<,>);\n\n //Creating KeyValue Type for Dictionary.\n Type[] typeArgs = { keyType, valueType };\n\n //Passing the Type and create Dictionary Type.\n Type genericType = typeDict.MakeGenericType(typeArgs);\n\n //Creating Instance for Dictionary<K,T>.\n IDictionary d = Activator.CreateInstance(genericType) as IDictionary;\n\n return d;\n\n }\n }\n}\n</code></pre>\n\n<p>The above <code>DynamicDictionaryFactory</code> class has a method </p>\n\n<p><code>CreateDynamicGenericInstance(Type keyType, Type valueType)</code></p>\n\n<p>and it creates and returns an IDictionary instance, the types of whose keys and values are exactly the specified on the call <code>keyType</code> and <code>valueType</code>.</p>\n\n<p><strong>Here is a complete example</strong> how to call this method to instantiate and use a <code>Dictionary<String, int></code> :</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\n\nnamespace DynamicDictionary\n{\n class Test\n {\n static void Main(string[] args)\n {\n var factory = new DictionaryRuntime.DynamicDictionaryFactory();\n var dict = factory.CreateDynamicGenericInstance(typeof(String), typeof(int));\n\n var typedDict = dict as Dictionary<String, int>;\n\n if (typedDict != null)\n {\n Console.WriteLine(\"Dictionary<String, int>\");\n\n typedDict.Add(\"One\", 1);\n typedDict.Add(\"Two\", 2);\n typedDict.Add(\"Three\", 3);\n\n foreach(var kvp in typedDict)\n {\n Console.WriteLine(\"\\\"\" + kvp.Key + \"\\\": \" + kvp.Value);\n }\n }\n else\n Console.WriteLine(\"null\");\n }\n }\n}\n</code></pre>\n\n<p>When the above console application is executed, we get the correct, expected result:</p>\n\n<pre><code>Dictionary<String, int>\n\"One\": 1\n\"Two\": 2\n\"Three\": 3\n</code></pre>\n"
},
{
"answer_id": 60504770,
"author": "Matt",
"author_id": 1016343,
"author_profile": "https://Stackoverflow.com/users/1016343",
"pm_score": 0,
"selected": false,
"text": "<p>Inspired by <a href=\"https://stackoverflow.com/a/3958029/1016343\">Enigmativity's answer</a> - let's assume you have two (or more) classes, like</p>\n\n<pre><code>public class Bar { }\npublic class Square { }\n</code></pre>\n\n<p>and you want to call the method <code>Foo<T></code> with <code>Bar</code> and <code>Square</code>, which is declared as</p>\n\n<pre><code>public class myClass\n{\n public void Foo<T>(T item)\n {\n Console.WriteLine(typeof(T).Name);\n }\n}\n</code></pre>\n\n<p>Then you can implement an <strong>Extension method</strong> like:</p>\n\n<pre><code>public static class Extension\n{\n public static void InvokeFoo<T>(this T t)\n {\n var fooMethod = typeof(myClass).GetMethod(\"Foo\");\n var tType = typeof(T);\n var fooTMethod = fooMethod.MakeGenericMethod(new[] { tType });\n fooTMethod.Invoke(new myClass(), new object[] { t });\n }\n}\n</code></pre>\n\n<p>With this, you can simply invoke <code>Foo</code> like:</p>\n\n<pre><code>var objSquare = new Square();\nobjSquare.InvokeFoo();\n\nvar objBar = new Bar();\nobjBar.InvokeFoo();\n</code></pre>\n\n<p>which works for every class. In this case, it will output:</p>\n\n<blockquote>\n <p>Square <br/>\n Bar</p>\n</blockquote>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/232535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30280/"
] |
What's the best way to call a generic method when the type parameter isn't known at compile time, but instead is obtained dynamically at runtime?
Consider the following sample code - inside the `Example()` method, what's the most concise way to invoke `GenericMethod<T>()` using the `Type` stored in the `myType` variable?
```
public class Sample
{
public void Example(string typeName)
{
Type myType = FindType(typeName);
// What goes here to call GenericMethod<T>()?
GenericMethod<myType>(); // This doesn't work
// What changes to call StaticMethod<T>()?
Sample.StaticMethod<myType>(); // This also doesn't work
}
public void GenericMethod<T>()
{
// ...
}
public static void StaticMethod<T>()
{
//...
}
}
```
|
You need to use reflection to get the method to start with, then "construct" it by supplying type arguments with [MakeGenericMethod](http://msdn.microsoft.com/en-us/library/system.reflection.methodinfo.makegenericmethod.aspx):
```
MethodInfo method = typeof(Sample).GetMethod(nameof(Sample.GenericMethod));
MethodInfo generic = method.MakeGenericMethod(myType);
generic.Invoke(this, null);
```
For a static method, pass `null` as the first argument to `Invoke`. That's nothing to do with generic methods - it's just normal reflection.
As noted, a lot of this is simpler as of C# 4 using `dynamic` - if you can use type inference, of course. It doesn't help in cases where type inference isn't available, such as the exact example in the question.
|
232,545 |
<p>Say I have a rectangular string array - not a jagged array</p>
<pre><code>string[,] strings = new string[8, 3];
</code></pre>
<p>What's the best way to extract a one-dimensional array from this (either a single row or a single column)? I can do this with a for loop, of course, but I'm hoping .NET has a more elegant way built in.</p>
<p>Bonus points for converting the extracted string array to an object array.</p>
|
[
{
"answer_id": 232553,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 1,
"selected": false,
"text": "<p>LINQ is the answer </p>\n\n<pre><code>static object[] GetColumn(string[][] source, int col) {\n return source.Iterate().Select(x => source[x.Index][col]).Cast<object>().ToArray();\n}\nstatic object[] GetRow(string[][] source, int row) {\n return source.Skip(row).First().Cast<object>().ToArray();\n}\npublic class Pair<T> {\n public int Index;\n public T Value;\n public Pair(int i, T v) {\n Index = i;\n Value = v;\n }\n}\nstatic IEnumerable<Pair<T>> Iterate<T>(this IEnumerable<T> source) {\n int index = 0;\n foreach (var cur in source) {\n yield return new Pair<T>(index, cur);\n index++;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 232562,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": false,
"text": "<p>You can cast a string array to an object array trivially - going the other way doesn't work. The actual extraction <em>has</em> to use a for loop though, as far as I can see: <a href=\"http://msdn.microsoft.com/en-us/library/system.array.copy.aspx\" rel=\"noreferrer\"><code>Array.Copy</code></a> requires the source and target ranks to be the same, and <a href=\"http://msdn.microsoft.com/en-us/library/system.buffer.blockcopy.aspx\" rel=\"noreferrer\"><code>Buffer.BlockCopy</code></a> only works for value type arrays. It does seem odd though...</p>\n\n<p>You can use LINQ to extra a row or column in a single statement, although it will be inefficient (as it'll build up a list internally, then have to convert it to an array - if you do it yourself you can preallocate the array to the right size and copy directly).</p>\n\n<p>Copying a row (<code>rowNum</code> is the row to be copied):</p>\n\n<pre><code>object[] row = Enumerable.Range(0, rowLength)\n .Select(colNum => (object) stringArray[rowNum, colNum])\n .ToArray();\n</code></pre>\n\n<p>Copying a column (<code>colNum</code> is the column to be copied):</p>\n\n<pre><code>object[] column = Enumerable.Range(0, columnLength)\n .Select(rowNum => (object) stringArray[rowNum, colNum])\n .ToArray();\n</code></pre>\n\n<p>I'm not sure that this is really any better/simpler than a foreach loop though - particularly if you write an <code>ExtractRow</code> method and an <code>ExtractColumn</code> method and reuse them.</p>\n"
},
{
"answer_id": 232666,
"author": "nyxtom",
"author_id": 19753,
"author_profile": "https://Stackoverflow.com/users/19753",
"pm_score": 2,
"selected": false,
"text": "<p>I'd just like to clarify (given the example and what's being asked).</p>\n\n<p>A <strong>jagged array</strong> is an array of arrays and is declared like so:</p>\n\n<pre><code>string[][] data = new string[3][];\ndata[0] = new string[] { \"0,[0]\", \"0,[1]\", \"0,[2]\" };\ndata[1] = new string[] { \"1,[0]\", \"1,[1]\", \"1,[2]\" ];\ndata[2] = new string[] { \"2,[0]\", \"1,[1]\", \"1,[2]\" };\n</code></pre>\n\n<p>Versus a <strong>rectangular array</strong> being defined as a single array that holds multiple dimensions:</p>\n\n<pre><code>string[,] data = new string[3,3];\ndata[0,0] = \"0,0\";\ndata[0,1] = \"0,1\";\ndata[0,2] = \"0,2\";\n...etc\n</code></pre>\n\n<p>Because of this, a <strong><em>jagged array</em></strong> is IQueryable/IEnumerable because you can iterate over it to receive an array at each iteration. Whereas a <strong><em>rectangular array</em></strong> is <strong>not</strong> IQueryable/IEnumerable because elements are addressed in full dimension (0,0 0,1..etc) so you won't have the ability to use Linq or any predefined functions created for Array in that case.</p>\n\n<p>Though you can iterate over the array once (and achieve what you want) like this:</p>\n\n<pre><code>/// INPUT: rowIndex, OUTPUT: An object[] of data for that row\nint colLength = stringArray.GetLength(1);\nobject[] rowData = new object[colLength];\nfor (int col = 0; col < colLength; col++) {\n rowData[col] = stringArray[rowIndex, col] as object;\n}\nreturn rowData;\n\n/// INPUT: colIndex, OUTPUT: An object[] of data for that column\nint rowLength = stringArray.GetLength(0);\nobject[] colData = new object[rowLength];\nfor (int row = 0; r < rowLength; row++) {\n colData[row] = stringArray[row, colIndex] as object;\n}\nreturn colData;\n</code></pre>\n\n<p>Hope this helps :)</p>\n"
},
{
"answer_id": 232889,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Rows can be copied easily using Array.Copy:</p>\n\n<pre><code> int[][] arDouble = new int[2][];\n arDouble[0] = new int[2];\n arDouble[1] = new int[2];\n arDouble[0][0] = 1;\n arDouble[0][1] = 2;\n arDouble[1][0] = 3;\n arDouble[1][1] = 4;\n\n int[] arSingle = new int[arDouble[0].Length];\n\n Array.Copy(arDouble[0], arSingle, arDouble[0].Length);\n</code></pre>\n\n<p>This will copy the first row into the single Dimension array.</p>\n"
},
{
"answer_id": 233488,
"author": "Cameron MacFarland",
"author_id": 3820,
"author_profile": "https://Stackoverflow.com/users/3820",
"pm_score": 4,
"selected": true,
"text": "<p>For a rectangular array:</p>\n\n<pre><code>string[,] rectArray = new string[3,3] { \n {\"a\", \"b\", \"c\"}, \n {\"d\", \"e\", \"f\"}, \n {\"g\", \"h\", \"i\"} };\n\nvar rectResult = rectArray.Cast<object>().ToArray();\n</code></pre>\n\n<p>And for a jagged array:</p>\n\n<pre><code>string[][] jaggedArray = { \n new string[] {\"a\", \"b\", \"c\", \"d\"}, \n new string[] {\"e\", \"f\"}, \n new string[] {\"g\", \"h\", \"i\"} };\n\nvar jaggedResult = jaggedArray.SelectMany(s => s).Cast<object>().ToArray();\n</code></pre>\n"
},
{
"answer_id": 34525680,
"author": "user3521369",
"author_id": 3521369,
"author_profile": "https://Stackoverflow.com/users/3521369",
"pm_score": 0,
"selected": false,
"text": "<p>i made extention method. i dont know about the performance .</p>\n\n<pre><code>public static class ExtensionMethods \n{\n public static string[] get1Dim(this string[,] RectArr, int _1DimIndex , int _2DimIndex )\n {\n string[] temp = new string[RectArr.GetLength(1)];\n\n if (_2DimIndex == -1)\n {\n for (int i = 0; i < RectArr.GetLength(1); i++)\n { temp[i] = RectArr[_1DimIndex, i]; }\n }\n else\n {\n for (int i = 0; i < RectArr.GetLength(0); i++)\n { temp[i] = RectArr[ i , _2DimIndex]; }\n }\n\n return temp;\n }\n}\n</code></pre>\n\n<p>usage </p>\n\n<pre><code>// we now have this funtionaliy RectArray[1, * ] \n// -1 means ALL \nstring[] _1stRow = RectArray.get1Dim( 0, -1) ; \nstring[] _2ndRow = RectArray.get1Dim( 1, -1) ; \n\nstring[] _1stCol = RectArray.get1Dim( -1, 0) ; \nstring[] _2ndCol = RectArray.get1Dim( -1, 1) ; \n</code></pre>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/232545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14606/"
] |
Say I have a rectangular string array - not a jagged array
```
string[,] strings = new string[8, 3];
```
What's the best way to extract a one-dimensional array from this (either a single row or a single column)? I can do this with a for loop, of course, but I'm hoping .NET has a more elegant way built in.
Bonus points for converting the extracted string array to an object array.
|
For a rectangular array:
```
string[,] rectArray = new string[3,3] {
{"a", "b", "c"},
{"d", "e", "f"},
{"g", "h", "i"} };
var rectResult = rectArray.Cast<object>().ToArray();
```
And for a jagged array:
```
string[][] jaggedArray = {
new string[] {"a", "b", "c", "d"},
new string[] {"e", "f"},
new string[] {"g", "h", "i"} };
var jaggedResult = jaggedArray.SelectMany(s => s).Cast<object>().ToArray();
```
|
232,575 |
<p>How do I check if a column exists in SQL Server 2000?</p>
|
[
{
"answer_id": 232582,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 5,
"selected": false,
"text": "<pre><code>IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS\nWHERE TABLE_NAME='tablename' AND COLUMN_NAME='columname' )\n</code></pre>\n"
},
{
"answer_id": 232613,
"author": "user20358",
"author_id": 20358,
"author_profile": "https://Stackoverflow.com/users/20358",
"pm_score": 3,
"selected": false,
"text": "<p>In query analyzer, select the Database that contains the table in which you need to check if the field exists or not and run the query below.</p>\n\n<pre><code>SELECT count(*) AS [Column Exists] \nFROM SYSOBJECTS \nINNER JOIN SYSCOLUMNS ON SYSOBJECTS.ID = SYSCOLUMNS.ID \nWHERE \n SYSOBJECTS.NAME = 'myTable' \n AND SYSCOLUMNS.NAME = 'Myfield'\n</code></pre>\n"
},
{
"answer_id": 3613216,
"author": "Deepak Yadav",
"author_id": 217294,
"author_profile": "https://Stackoverflow.com/users/217294",
"pm_score": 3,
"selected": false,
"text": "<pre><code>If col_length('table_name','column_name') is null\n select 0 as Present\nELSE\n select 1 as Present\n</code></pre>\n\n<p>Present will be 0, is there is no column_name present in table_name , otherwise 1</p>\n\n<p>@CMS: I don't think that 'INFORMATION_SCHEMA.COLUMNS' have information about every table in DB. Because this didn't worked for me. But my answer did worked.</p>\n"
},
{
"answer_id": 5833757,
"author": "Dan",
"author_id": 731299,
"author_profile": "https://Stackoverflow.com/users/731299",
"pm_score": 2,
"selected": false,
"text": "<p>This should do nicely:</p>\n\n<pre><code>if COLUMNPROPERTY(object_id('table_name'), 'column_name', 'ColumnId') is null\n print 'doesn\\'t exist'\nelse\n print 'exists'\n</code></pre>\n"
},
{
"answer_id": 7610770,
"author": "Douglas Tondo",
"author_id": 973130,
"author_profile": "https://Stackoverflow.com/users/973130",
"pm_score": 0,
"selected": false,
"text": "<p>I don't know if this script will work in sqlserver 2000, but in 2008 works:</p>\n\n<pre><code>SELECT COLUMNS.*\nFROM INFORMATION_SCHEMA.COLUMNS COLUMNS, INFORMATION_SCHEMA.TABLES TABLES\nWHERE COLUMNS.TABLE_NAME=TABLES.TABLE_NAME AND UPPER(COLUMNS.COLUMN_NAME)=UPPER('column_name')\n</code></pre>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/232575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31071/"
] |
How do I check if a column exists in SQL Server 2000?
|
```
IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME='tablename' AND COLUMN_NAME='columname' )
```
|
232,596 |
<p>Let say I run this command:</p>
<pre><code>makecert testcert.cer
</code></pre>
<p>Is a private key created? If so, where is it automatically stored in the system even though I did not tell makecert to install this certificate in any certificate store?</p>
|
[
{
"answer_id": 341374,
"author": "Scott Ivey",
"author_id": 36297,
"author_profile": "https://Stackoverflow.com/users/36297",
"pm_score": 2,
"selected": false,
"text": "<p>It looks like the private key is stored in the file itself. From the documentation at <a href=\"http://msdn.microsoft.com/en-us/library/bfsktky3(VS.80).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/bfsktky3(VS.80).aspx</a> it states...</p>\n\n<p>Caution<br>\nYou should use a certificate store to securely store your certificates. The .snk files used by this tool store private keys in an unprotected manner. When you create or import a .snk file, you should be careful to secure it during use and remove it when you are done. </p>\n"
},
{
"answer_id": 499811,
"author": "Nicolas Dorier",
"author_id": 19803,
"author_profile": "https://Stackoverflow.com/users/19803",
"pm_score": 0,
"selected": false,
"text": "<p>The private key is not created because I HasPrivateKey of X509Certificate2 is set to false when I load the certificate in .NET.</p>\n"
},
{
"answer_id": 1158413,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>The way you run the commnand does not create any private key.\nTo generate a certificate with private key, you have to use the option -pe.\nBut this is not suficient. Private key will only be created if your certificate destination is a store. So you'll have to use the command like this:</p>\n\n<p>makecert -pe -ss My testcert.cer</p>\n\n<p>\"my\" corresponds to the \"personal\" store.</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/232596",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13484/"
] |
Let say I run this command:
```
makecert testcert.cer
```
Is a private key created? If so, where is it automatically stored in the system even though I did not tell makecert to install this certificate in any certificate store?
|
It looks like the private key is stored in the file itself. From the documentation at <http://msdn.microsoft.com/en-us/library/bfsktky3(VS.80).aspx> it states...
Caution
You should use a certificate store to securely store your certificates. The .snk files used by this tool store private keys in an unprotected manner. When you create or import a .snk file, you should be careful to secure it during use and remove it when you are done.
|
232,611 |
<p>I'm building a webpage that queries a MySQL database and (currently) produces a text-only list of the findings. The queries to complete a single record are similar to:</p>
<ul>
<li>movie (title, description, etc)
<ul>
<li>actors in the movie (name, gender)</li>
<li>related movies</li>
</ul></li>
</ul>
<p>Out of curiosity I've used <code>memory_get_peak_usage()</code> and <code>memory_get_usage()</code>:</p>
<pre>
start 110,440 bytes
peak 656,056 bytes
end 637,976 bytes
time 0.008 seconds
</pre>
<p>The above is with no records found!</p>
<p>With 40 records I'm reaching approximately 2MB, though the time remains the same.</p>
<p>I know that premature optimization is evil and all, but I have to ask: </p>
<p>Do I need to do some reworking? Is this memory usage normal? What is considered excessive?</p>
|
[
{
"answer_id": 232647,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 4,
"selected": false,
"text": "<p>Ultimately it's preferable to optimize when convenient of course, but 2MB of memory use sounds fine. PHP4 has a default config of 8mb, and PHP5 16mb. A lot of pre-packaged PHP builds will have different configs, of course, but generally speaking, if you can keep your app under 8mb, you can be sure it'll be highly portable in that regard.</p>\n"
},
{
"answer_id": 232805,
"author": "Bertrand Gorge",
"author_id": 30955,
"author_profile": "https://Stackoverflow.com/users/30955",
"pm_score": 3,
"selected": false,
"text": "<p>Obviously it all depends on the complexity of the application you're building. In average, the pages of our application take up to 20 MB (min) of memory. That's because there's a lot of objects in the session, and a lot of initialisation process that occur before the script can even say hello world (authentification, rights management, notifications, ...)</p>\n\n<p>There's a lot of things that go in the memory space, including classes definitions, globals, function definitions, etc. Reducing the amount of loaded classes (by using auto-includes) is a good way to keep your scripts with only the necessary amount of classes definitions.</p>\n\n<p>I don't know if loading up extensions changes the memory usage - that should be something to test, because by default we may not need all the default loaded extensions ?</p>\n"
},
{
"answer_id": 232824,
"author": "Berzemus",
"author_id": 2452,
"author_profile": "https://Stackoverflow.com/users/2452",
"pm_score": 0,
"selected": false,
"text": "<p>As long as you plan a good caching mechanism (opcode cache, object cache, etc.), memory usage becomes less relevant. You are still way below common php framework memory usage.</p>\n"
},
{
"answer_id": 848412,
"author": "Tower",
"author_id": 283055,
"author_profile": "https://Stackoverflow.com/users/283055",
"pm_score": 2,
"selected": false,
"text": "<p>Personally I set the limit to 8 MB. If I exceed that I try to improve my application. The reason is because some shared hosts and PHP 4 configurations have the default limit of 8 MB per process.</p>\n"
},
{
"answer_id": 848498,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>PHP doesn't free memory during script execution so your memory limit needs to be as high as the most memory one script will consume. If the most a script will ever consume is 2MB then set it to 2MB but if you need 780MB then set it to that.</p>\n\n<p>We have large production systems with the memory limit set over 2GB. But this is obviously highly tuned for us and for our scenario, I would never advocate it for shared hosting environments.</p>\n"
},
{
"answer_id": 5083624,
"author": "Clint Riddell",
"author_id": 629059,
"author_profile": "https://Stackoverflow.com/users/629059",
"pm_score": 0,
"selected": false,
"text": "<p>PHP has known resource limits dpending on which version you are using. The current version can handle 128MB, PHP 5.2.0=16MB, and all previous versions 8MB.</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/232611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29230/"
] |
I'm building a webpage that queries a MySQL database and (currently) produces a text-only list of the findings. The queries to complete a single record are similar to:
* movie (title, description, etc)
+ actors in the movie (name, gender)
+ related movies
Out of curiosity I've used `memory_get_peak_usage()` and `memory_get_usage()`:
```
start 110,440 bytes
peak 656,056 bytes
end 637,976 bytes
time 0.008 seconds
```
The above is with no records found!
With 40 records I'm reaching approximately 2MB, though the time remains the same.
I know that premature optimization is evil and all, but I have to ask:
Do I need to do some reworking? Is this memory usage normal? What is considered excessive?
|
Ultimately it's preferable to optimize when convenient of course, but 2MB of memory use sounds fine. PHP4 has a default config of 8mb, and PHP5 16mb. A lot of pre-packaged PHP builds will have different configs, of course, but generally speaking, if you can keep your app under 8mb, you can be sure it'll be highly portable in that regard.
|
232,625 |
<p>How to invoke the default browser with an URL from C#?</p>
|
[
{
"answer_id": 232633,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 3,
"selected": false,
"text": "<pre><code>System.Diagnostics.Process.Start(\"http://mysite.com\");\n</code></pre>\n"
},
{
"answer_id": 232634,
"author": "Anindya",
"author_id": 4741,
"author_profile": "https://Stackoverflow.com/users/4741",
"pm_score": 4,
"selected": false,
"text": "<pre><code>System.Diagnostics.Process.Start(\"http://www.google.com\");\n</code></pre>\n\n<p>More details here -\n<a href=\"http://msdn.microsoft.com/en-us/library/aa326951.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa326951.aspx</a></p>\n"
},
{
"answer_id": 235926,
"author": "Lex Li",
"author_id": 11182,
"author_profile": "https://Stackoverflow.com/users/11182",
"pm_score": 2,
"selected": false,
"text": "<p>I used System.Diagnostics.Process.Start in the past, but if Firefox or another browser is set as the default this method always throws a terrible exception to users. At last, I come across System.Windows.Forms.Help.ShowHelp</p>\n\n<p><code>\nHelp.ShowHelp(null, \"<a href=\"http://www.google.com\" rel=\"nofollow noreferrer\">http://www.google.com</a>\");\n</code></p>\n\n<p>Please notice that Help is a class only available for WinForms, while Process can be used for other cases (WebForms, WPF and so on).</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/232625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
How to invoke the default browser with an URL from C#?
|
```
System.Diagnostics.Process.Start("http://www.google.com");
```
More details here -
<http://msdn.microsoft.com/en-us/library/aa326951.aspx>
|
232,651 |
<p>While running a batch file in Windows XP I have found randomly occurring error message:</p>
<blockquote>
<p>The system cannot find the batch label specified name_of_label</p>
</blockquote>
<p>Of course label existed. What causes this error?</p>
|
[
{
"answer_id": 232656,
"author": "Slimak",
"author_id": 31086,
"author_profile": "https://Stackoverflow.com/users/31086",
"pm_score": 4,
"selected": false,
"text": "<p>If batch file has unix line endings (line separators) this can sometimes happen.</p>\n\n<p>Just <a href=\"http://dos2unix.sourceforge.net/\" rel=\"nofollow noreferrer\">unix2dos</a> it and problem should be solved.</p>\n"
},
{
"answer_id": 232674,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 8,
"selected": true,
"text": "<p>Actually, you need 2 conditions for this to happen:</p>\n<ul>\n<li>the batch file must not use CRLF line endings</li>\n<li>the label you jump to must span a block boundary (as opposed to and :end label wich is just a shortcut to the end of your script)</li>\n</ul>\n<p>See. <a href=\"https://web.archive.org/web/20160305063042/help.wugnet.com/windows/system-find-batch-label-ftopict615555.html\" rel=\"noreferrer\">The system cannot find the batch label specified</a> (by and <a href=\"http://www.clausbrod.de/cgi-bin/view.pl/Blog/BlogOnSoftware20060127\" rel=\"noreferrer\">Batch-as-batch-can!</a></p>\n<p><a href=\"https://stackoverflow.com/users/3079037/david-a-gray\">David A. Gray</a> mentions <a href=\"https://stackoverflow.com/questions/232651/why-the-system-cannot-find-the-batch-label-specified-is-thrown-even-if-label-e/232674?noredirect=1#comment101293044_232674\">in the comments</a> seeing (on Windows 10) what <a href=\"https://stackoverflow.com/users/548098/marshal\">Marshal</a>'s <a href=\"https://stackoverflow.com/a/6419068/6309\">answer</a> showed in 2014 (presumably on Windows 7 or 8): a script/batch program (<code>.bat</code> or <code>.cmd</code>) executed without <a href=\"https://ss64.com/nt/call.html\" rel=\"noreferrer\"><code>CALL</code></a> would trigger an eol conversion.</p>\n<blockquote>\n<p>I've written hundreds of batch scripts over the last 35 years, and the only time I've ever had an issue with labels not being found was when the file's line breaks got converted from Windows (CR/LF), which works, to Unix (LF), which doesn't.</p>\n</blockquote>\n<hr />\n<p>Feb. 2020, <a href=\"https://stackoverflow.com/users/1207818/kinar\">kinar</a> adds <a href=\"https://stackoverflow.com/questions/232651/why-the-system-cannot-find-the-batch-label-specified-is-thrown-even-if-label-e/232674?noredirect=1#comment106597844_232674\">in the comments</a>:</p>\n<blockquote>\n<p>Just encountered this issue on a Win7 machine.<br />\nTurns out this error can also be generated when trying to CALL another <code>.bat</code> file if that file doesn't exist on the system.<br />\nIn my case, I was trying to call the Visual Studio <code>vcvarsall.bat</code> file on a system without VS installed.</p>\n</blockquote>\n<p>See <a href=\"https://stackoverflow.com/users/463115/jeb\">jeb</a>'s <a href=\"https://stackoverflow.com/a/60265222/6309\">answer</a> for more: it was a case of an undefined label.</p>\n<hr />\n<p>Note: in a Git repository, I would recommend a <code>.gitattributes</code> file with the directive:</p>\n<pre><code>*.bat text eol=crlf\n</code></pre>\n"
},
{
"answer_id": 345210,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>You should also make sure that when calling other scripts you use CALL, instead of calling them in the caller's environment.</p>\n"
},
{
"answer_id": 3525677,
"author": "Masoud Kermani",
"author_id": 425686,
"author_profile": "https://Stackoverflow.com/users/425686",
"pm_score": 4,
"selected": false,
"text": "<p>Here is the issue and how to fix it. The issue is a bug or a feature in DOS batch cmd program. First the clear problem statement. If you have a DOS batch file with target labels like, \":dothis\", and at the end of the label you do not have space then the batch file will not work if the line ending are UNIX line endings. This means you have to run unix2dos on the file before you can use it.</p>\n\n<p>The root cause is the DOS command line processor, (shell program), takes the UNIX end-of-line character as part of the label. Since the go to part never uses this as the label, it is never found since such a label truly does not exist. The solution is to put an extra space at the end of each target label, or even better every line. Now UNIX end of lines do not come to play since the space acts as the separator and it all works.</p>\n"
},
{
"answer_id": 6419068,
"author": "Marshal",
"author_id": 548098,
"author_profile": "https://Stackoverflow.com/users/548098",
"pm_score": 6,
"selected": false,
"text": "<p>I have got the same issue before. However, the root cause was not CRLF at all. It was because in the script I executed an external program such as Ant, but did not put a <code>CALL</code> before Ant. So, make sure you <code>CALL</code> every external program used in your batch script.</p>\n"
},
{
"answer_id": 14316807,
"author": "Stefan Michev",
"author_id": 754571,
"author_profile": "https://Stackoverflow.com/users/754571",
"pm_score": 2,
"selected": false,
"text": "<p>i had this issue after copying a start command from word and paste it into the command window. There was a option with \"-\" on front, and thought the looks the same as the DOS \"-\" it wasn't :) After typing the \"-\" by myself the issue was solved and the batch worked ... a hard to find issue .... </p>\n"
},
{
"answer_id": 20558108,
"author": "Greg",
"author_id": 2081656,
"author_profile": "https://Stackoverflow.com/users/2081656",
"pm_score": 2,
"selected": false,
"text": "<p>I encountered a similar issue just now with a .cmd file and Windows 8.\nThe solution was to change all line endings to CR+LF DOS style.\nThe issue was confusing because the batch file mostly worked and rearranging lines changed the effect.</p>\n\n<p>The .cmd file looked like:</p>\n\n<pre><code>call:function_A \"..\\..\\folderA\\\"\ncall:function_B \"..\\..\\folderB\\\"\ncall:function_C \"..\\..\\folderC\\\"\ncall:function_D \"..\\..\\folderD\\\"\ngoto:eof\n\n:function_A\nrem do stuff\ngoto:eof\n\n...etc...\n</code></pre>\n\n<p>Function C would cause error \"The system cannot find the batch label specified\". Strangely it could go away by rearranging the calls.\nChanging line endings from 0x0A to 0x0D0A seems to have fixed it.</p>\n\n<p>Perhaps VonC meant \"the batch file must use CRLF line endings\".</p>\n"
},
{
"answer_id": 57527142,
"author": "Prasanna Mondkar",
"author_id": 678423,
"author_profile": "https://Stackoverflow.com/users/678423",
"pm_score": 0,
"selected": false,
"text": "<p>Little different use case ...</p>\n\n<p>I was calling a bat script during <strong>packer</strong> build of Windows Server 2012 Server, using the <em>shell</em> provisioner (OpenSSH).\nNow, the script was working fine through cmd in the provisioned Virtual Machine (put breakpoint in packer build to stop and confirmed this) ... but, it was failing with these call labels not found issues. </p>\n\n<p>The Line Endings were fine, CRLF (confirmed in Notepadd++). The script was working fine through command line as well. What more, sometimes, it just use to run fine and sometime fail, but once failed for some label, the failure was consistent.</p>\n\n<p>Initially, I just started removing the subroutines altogether by expanding the call itself and putting subroutine code inline. I did this for all instances where there was only one call (no code duplication).</p>\n\n<p>But, yeah, i did stumble upon one sub which was called from 3,4 places. After trying everything, this is what worked for me</p>\n\n<blockquote>\n <p>Adding 8-10 REM statements just above the subroutine. Yes, I am not kidding !!</p>\n</blockquote>\n\n<p>PS : The script is very very old, but management needed me to make that work through packer (we have a Day-2 plan of this to replace it with Ansible/Chef).</p>\n"
},
{
"answer_id": 60265222,
"author": "jeb",
"author_id": 463115,
"author_profile": "https://Stackoverflow.com/users/463115",
"pm_score": 2,
"selected": false,
"text": "<p>There are multiple possible ways to get the error. </p>\n\n<ol>\n<li><p><a href=\"https://stackoverflow.com/a/232674/463115\">Described by VonC</a> - Wrong line endings, LF instead of CR/LF</p></li>\n<li><p><a href=\"https://www.dostips.com/forum/viewtopic.php?f=3&t=8988#p58890\" rel=\"nofollow noreferrer\">Obscure long lines</a> (if that happens accidential, your code is incredible worse)</p></li>\n<li><p>Direct start another batch after calling a function.<br>\nSample:<pre><code>@echo off\ncall :func\necho back from second\nexit /b<br>\n:func\nsecond.bat\necho NEVER COME BACK HERE</code></pre>\nThis unexpectedly tries to <code>goto</code> to the label <code>:func</code> in second.bat.<br>\nBut this can be <em>(mis)</em>-used to directly call labels in another batch file</p></li>\n</ol>\n\n<p>This is the described behaviour of <a href=\"https://stackoverflow.com/a/6419068/463115\">the answer of Marshal\n</a></p>\n"
},
{
"answer_id": 73136207,
"author": "Cristian F.",
"author_id": 11302775,
"author_profile": "https://Stackoverflow.com/users/11302775",
"pm_score": 0,
"selected": false,
"text": "<p>I had the error :</p>\n<blockquote>\n<p>The system cannot find the batch label specified -</p>\n</blockquote>\n<p>and I found that on a line I used</p>\n<pre><code>goto : eof\n</code></pre>\n<p>instead</p>\n<pre><code>goto :eof\n</code></pre>\n<p>So check for the same issue of using labels, if the solutions from above didn't worked out.</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/232651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31086/"
] |
While running a batch file in Windows XP I have found randomly occurring error message:
>
> The system cannot find the batch label specified name\_of\_label
>
>
>
Of course label existed. What causes this error?
|
Actually, you need 2 conditions for this to happen:
* the batch file must not use CRLF line endings
* the label you jump to must span a block boundary (as opposed to and :end label wich is just a shortcut to the end of your script)
See. [The system cannot find the batch label specified](https://web.archive.org/web/20160305063042/help.wugnet.com/windows/system-find-batch-label-ftopict615555.html) (by and [Batch-as-batch-can!](http://www.clausbrod.de/cgi-bin/view.pl/Blog/BlogOnSoftware20060127)
[David A. Gray](https://stackoverflow.com/users/3079037/david-a-gray) mentions [in the comments](https://stackoverflow.com/questions/232651/why-the-system-cannot-find-the-batch-label-specified-is-thrown-even-if-label-e/232674?noredirect=1#comment101293044_232674) seeing (on Windows 10) what [Marshal](https://stackoverflow.com/users/548098/marshal)'s [answer](https://stackoverflow.com/a/6419068/6309) showed in 2014 (presumably on Windows 7 or 8): a script/batch program (`.bat` or `.cmd`) executed without [`CALL`](https://ss64.com/nt/call.html) would trigger an eol conversion.
>
> I've written hundreds of batch scripts over the last 35 years, and the only time I've ever had an issue with labels not being found was when the file's line breaks got converted from Windows (CR/LF), which works, to Unix (LF), which doesn't.
>
>
>
---
Feb. 2020, [kinar](https://stackoverflow.com/users/1207818/kinar) adds [in the comments](https://stackoverflow.com/questions/232651/why-the-system-cannot-find-the-batch-label-specified-is-thrown-even-if-label-e/232674?noredirect=1#comment106597844_232674):
>
> Just encountered this issue on a Win7 machine.
>
> Turns out this error can also be generated when trying to CALL another `.bat` file if that file doesn't exist on the system.
>
> In my case, I was trying to call the Visual Studio `vcvarsall.bat` file on a system without VS installed.
>
>
>
See [jeb](https://stackoverflow.com/users/463115/jeb)'s [answer](https://stackoverflow.com/a/60265222/6309) for more: it was a case of an undefined label.
---
Note: in a Git repository, I would recommend a `.gitattributes` file with the directive:
```
*.bat text eol=crlf
```
|
232,662 |
<p>I have a function which launches a javascript window, like this</p>
<pre><code> function genericPop(strLink, strName, iWidth, iHeight) {
var parameterList = "location=0,directories=0,status=0,menubar=0,resizable=no, scrollbars=no,toolbar=0,maximize=0,width=" + iWidth + ", height=" + iHeight;
var new_window="";
new_window = open(strLink, strName, parameterList);
window.self.name = "main";
new_window.moveTo(((screen.availWidth/2)-(iWidth/2)),((screen.availHeight/2)-(iHeight/2)));
new_window.focus();
}
</code></pre>
<p>This function is called about 52 times from different places in my web application.</p>
<p>I want to re-factor this code to use a DHTML modal pop-up window. The change should be as unobtrusive as possible.</p>
<p>To keep this solution at par with the old solution, I think would also need to do the following</p>
<ol>
<li>Provide a handle to "Close" the window.</li>
<li>Ensure the window cannot be moved, and is positioned at the center of the screen.</li>
<li>Blur the background as an option.</li>
</ol>
<p>I thought <a href="http://particletree.com/features/lightbox-gone-wild/" rel="nofollow noreferrer">this solution</a> is the closest to what I want, but I could not understand how to incorporate it.</p>
<p>Edit: A couple of you have given me a good lead. Thank you. But let me re-state my problem here. I am re-factoring existing code. I should avoid any change to the present HTML or CSS. Ideally I would like to achieve this effect by keeping the function signature of the genericPop(...) same as well.</p>
|
[
{
"answer_id": 232684,
"author": "Gene",
"author_id": 22673,
"author_profile": "https://Stackoverflow.com/users/22673",
"pm_score": 2,
"selected": false,
"text": "<p>I use this <a href=\"http://www.leigeber.com/2008/04/custom-javascript-dialog-boxes/\" rel=\"nofollow noreferrer\">dialog code</a> to do pretty much the same thing.</p>\n\n<p>If i remember correctly the default implementation does not support resizing the dialog. If you cant make with just one size you can modify the code or css to display multiple widths.</p>\n\n<p>usage is easy:</p>\n\n<pre><code>showDialog('title','content (can be html if encoded)','dialog_style/*4 predefined styles to choose from*/');\n</code></pre>\n\n<p>Modifying the js to support multiple widths:</p>\n\n<p>Add width and height as attributes to show dialog function and the set them to the dialog and dialog-content elements on line 68</p>\n"
},
{
"answer_id": 232727,
"author": "derfred",
"author_id": 10286,
"author_profile": "https://Stackoverflow.com/users/10286",
"pm_score": 1,
"selected": false,
"text": "<p>Try <a href=\"http://livepipe.net/control/window\" rel=\"nofollow noreferrer\">Control.Window</a>, which requires Prototype</p>\n\n<p>Here's how I use it:</p>\n\n<pre><code><a href=\"/messages/new\" class=\"popup_window\">New Message</a>\n</code></pre>\n\n<p>And in my Javascript file:</p>\n\n<pre><code>$(document).observe(\"dom:loaded\", function() {\n $$(\"a.popup_window\").each(function(element) {\n new Control.Modal(element, { overlayOpacity: 0.75, \n className: 'modal',\n method: 'get',\n position: 'center' });\n });\n});\n</code></pre>\n\n<p>Now if you want to close the currently open popup do:</p>\n\n<pre><code>Control.Modal.current.close()\n</code></pre>\n"
},
{
"answer_id": 233372,
"author": "Damir Zekić",
"author_id": 401510,
"author_profile": "https://Stackoverflow.com/users/401510",
"pm_score": 3,
"selected": true,
"text": "<p>Here is my solution using jQuery and jQuery UI libraries. Your API is not changed <del>, but parameter 'name' is ignored</del>. I use <code>iframe</code> to load content from given <code>strLink</code> and then display that <code>iframe</code> as a child to generated <code>div</code>, which is then converted to modal pop-up using jQuery:</p>\n\n<pre><code>function genericPop(strLink, strName, iWidth, iHeight) {\n var dialog = $('#dialog');\n if (dialog.length > 0) {\n dialog.parents('div.ui-dialog').eq(0).remove();\n }\n\n dialog = $(document.createElement('div'))\n .attr('id', 'dialog')\n .css('display', 'none')\n .appendTo('body');\n\n $(document.createElement('iframe'))\n .attr('src', strLink)\n .css('width', '100%')\n .css('height', '100%')\n .appendTo(dialog);\n\n dialog.dialog({ \n draggable: false,\n modal: true, \n width: iWidth,\n height: iHeight,\n title: strName,\n overlay: { \n opacity: 0.5, \n background: \"black\" \n } \n });\n dialog.css('display', 'block');\n}\n\n// example of use\n$(document).ready(function() {\n $('#google').click(function() {\n genericPop('http://www.google.com/', 'Google', 640, 480);\n return false;\n });\n $('#yahoo').click(function() {\n genericPop('http://www.yahoo.com/', 'Yahoo', 640, 480);\n return false;\n });\n});\n</code></pre>\n\n<p><a href=\"http://docs.jquery.com/UI/Dialog\" rel=\"nofollow noreferrer\">Documentation for jQuery UI/Dialog</a>.</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/232662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11602/"
] |
I have a function which launches a javascript window, like this
```
function genericPop(strLink, strName, iWidth, iHeight) {
var parameterList = "location=0,directories=0,status=0,menubar=0,resizable=no, scrollbars=no,toolbar=0,maximize=0,width=" + iWidth + ", height=" + iHeight;
var new_window="";
new_window = open(strLink, strName, parameterList);
window.self.name = "main";
new_window.moveTo(((screen.availWidth/2)-(iWidth/2)),((screen.availHeight/2)-(iHeight/2)));
new_window.focus();
}
```
This function is called about 52 times from different places in my web application.
I want to re-factor this code to use a DHTML modal pop-up window. The change should be as unobtrusive as possible.
To keep this solution at par with the old solution, I think would also need to do the following
1. Provide a handle to "Close" the window.
2. Ensure the window cannot be moved, and is positioned at the center of the screen.
3. Blur the background as an option.
I thought [this solution](http://particletree.com/features/lightbox-gone-wild/) is the closest to what I want, but I could not understand how to incorporate it.
Edit: A couple of you have given me a good lead. Thank you. But let me re-state my problem here. I am re-factoring existing code. I should avoid any change to the present HTML or CSS. Ideally I would like to achieve this effect by keeping the function signature of the genericPop(...) same as well.
|
Here is my solution using jQuery and jQuery UI libraries. Your API is not changed ~~, but parameter 'name' is ignored~~. I use `iframe` to load content from given `strLink` and then display that `iframe` as a child to generated `div`, which is then converted to modal pop-up using jQuery:
```
function genericPop(strLink, strName, iWidth, iHeight) {
var dialog = $('#dialog');
if (dialog.length > 0) {
dialog.parents('div.ui-dialog').eq(0).remove();
}
dialog = $(document.createElement('div'))
.attr('id', 'dialog')
.css('display', 'none')
.appendTo('body');
$(document.createElement('iframe'))
.attr('src', strLink)
.css('width', '100%')
.css('height', '100%')
.appendTo(dialog);
dialog.dialog({
draggable: false,
modal: true,
width: iWidth,
height: iHeight,
title: strName,
overlay: {
opacity: 0.5,
background: "black"
}
});
dialog.css('display', 'block');
}
// example of use
$(document).ready(function() {
$('#google').click(function() {
genericPop('http://www.google.com/', 'Google', 640, 480);
return false;
});
$('#yahoo').click(function() {
genericPop('http://www.yahoo.com/', 'Yahoo', 640, 480);
return false;
});
});
```
[Documentation for jQuery UI/Dialog](http://docs.jquery.com/UI/Dialog).
|
232,678 |
<p>I am working on implementing tail for an assignment. I have it working correctly however I seem to be getting an error from free at random times.</p>
<p>I can't see, to track it down to a pattern or anything besides it is consistent.</p>
<p>For example if I call my program as "tail -24 test.in" I would get the the the incorrect checksum error at the same line on multiple runs. However, with different files and even different numbers of lines to print back I will come back without errors.</p>
<p>Any idea on how to track down the issue, I've been trying to debug it for hours to no avail.</p>
<p>Here is the offending code:</p>
<p>lines is defined as a char** and was malloc as:</p>
<pre><code>lines = (char**) malloc(nlines * sizeof(char *));
void insert_line(char *s, int len){
printf("\t\tLine Number: %d Putting a %d line into slot: %d\n",processed,len,slot);
if(processed > numlines -1){//clean up
free(*(lines+slot));
*(lines + slot) = NULL;
}
*(lines + slot) = (char *) malloc(len * sizeof(char));
if(*(lines + slot) == NULL) exit(EXIT_FAILURE);
strcpy(*(lines+slot),s);
slot = ++processed % numlines;
}
</code></pre>
|
[
{
"answer_id": 232708,
"author": "Windows programmer",
"author_id": 23705,
"author_profile": "https://Stackoverflow.com/users/23705",
"pm_score": 0,
"selected": false,
"text": "<p>Do nlines and numlines have the same value?</p>\n\n<p>Does the caller of insert_line allow room for the trailing NUL when passing the length in the second parameter?</p>\n"
},
{
"answer_id": 232720,
"author": "Remo.D",
"author_id": 16827,
"author_profile": "https://Stackoverflow.com/users/16827",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not sure it's related but these two lines seems suspicious to me:</p>\n\n<pre><code> *(lines + slot) = (char *) malloc(len * sizeof(char));\n if((lines + slot) == NULL) exit(EXIT_FAILURE);\n</code></pre>\n\n<p>You first assign the return of malloc to <code>lines[slot]</code> and then you check <code>(lines+slot)</code>, if the latter was NULL, you had dereference a NULL pointer!</p>\n\n<p>Also if lines[slot] (your *(lines+slot)) is not null, you will leak memory when you will assign the result of malloc() to it. </p>\n\n<p>I assume <code>lines</code> is a <code>char</code>*lines[]` and slot is within the allowed boundary!</p>\n"
},
{
"answer_id": 232731,
"author": "Windows programmer",
"author_id": 23705,
"author_profile": "https://Stackoverflow.com/users/23705",
"pm_score": 0,
"selected": false,
"text": "<p>I agree with remo's suspicion about those two lines, but not the tangent that remo went off on. We should share credit for finding this bug.</p>\n\n<pre><code>*(lines + slot) = some value\nif((lines + slot) == NULL) then die\nshould be\nif(*(lines + slot) == NULL) then die\n</code></pre>\n"
},
{
"answer_id": 232756,
"author": "Rasmus Faber",
"author_id": 5542,
"author_profile": "https://Stackoverflow.com/users/5542",
"pm_score": 2,
"selected": false,
"text": "<p>If you can consistently reproduce the problem with specific input parameters, you should debug like this:</p>\n\n<ul>\n<li>First debug to the precise free that causes the problem.</li>\n<li>Then figure out when the memory that is about to be free'd was malloc'ed.</li>\n<li>Next, debug to the place where the memory is malloc'ed.</li>\n<li>Locate in the memory viewer the allocated block of memory. Note both the start and end of the block. There is probably a special value called a <em>guard block</em> just before and just after the block.</li>\n<li>Now step through the code until the memory is free'd. At some point your code should mistakenly overwrite the guard block. <em>That is the offending statement.</em></li>\n</ul>\n\n<p>Note that the problem might very well be in a completely different part of your program. Even though it is this free that is reporting the error, the code that overwrites the guard block can be anywhere.</p>\n"
},
{
"answer_id": 233424,
"author": "Todd",
"author_id": 30841,
"author_profile": "https://Stackoverflow.com/users/30841",
"pm_score": 1,
"selected": false,
"text": "<p>My first question is how do you calculate len? Is it just strlen or does it include room for the \\0 terminator? I think you may be overshooting your allocation in your strcpy. Bad behavior will tend to happen on word boundaries and appear random. Also, check to make sure that your source strings are null terminated. If you made a mistake on the read side and didn't terminate them. Then strcpy may be randomly overwriting things. </p>\n\n<pre><code> *(lines + slot) = (char *) malloc(len * sizeof(char));\n if(*(lines + slot) == NULL) exit(EXIT_FAILURE);\n strcpy(*(lines+slot),s);\n</code></pre>\n\n<p>Perhaps try:</p>\n\n<pre><code> lines[slot] = (char *) malloc((len + 1) * sizeof(char));\n if(lines[slot] == NULL) exit(EXIT_FAILURE);\n if(strlen(s) <= len){\n strcpy(lines[slot],s);\n }\n else{\n /* do something else... */\n }\n</code></pre>\n\n<p>In terms of general form, I'd also encourage you to make a few stylistic changes to make the whole thing a bit more readable, easier to follow and resistant to errors.</p>\n\n<p>Pointer arithmetic is valid and fun, but I think your intent is a little more clear if you use the array form like: </p>\n\n<pre><code>free(lines[slot]);\nlines[slot] = NULL;\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>free(*(lines+slot));\n*(lines + slot) = NULL;\n</code></pre>\n\n<p>I'd also encourage you to use fewer statics. It's easy enough to through them in a data structure and pass them around into your accessors and mutators. It becomes much more clear where the action is happening prevents you from doing things like:</p>\n\n<pre><code>static int numlines = 0;\nvoid insert_line(char *s, int len){\n int numlines = 5;\n</code></pre>\n\n<p>where you can introduce scoping issues that are just miserable to debug.</p>\n"
},
{
"answer_id": 233534,
"author": "JayG",
"author_id": 5823,
"author_profile": "https://Stackoverflow.com/users/5823",
"pm_score": 4,
"selected": true,
"text": "<p>Your routine is writing beyond the allocated line buffer.</p>\n\n<p>The size of the line passed as an argument (i.e. \"len\") probably does not include the NUL terminator. When you call malloc to copy the line (i.e. \"s\") you need to allocate an extra byte for the string terminator:</p>\n\n<pre><code> *(lines + slot) = (char *) malloc((len + 1) * sizeof(char));\n</code></pre>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/232678",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25012/"
] |
I am working on implementing tail for an assignment. I have it working correctly however I seem to be getting an error from free at random times.
I can't see, to track it down to a pattern or anything besides it is consistent.
For example if I call my program as "tail -24 test.in" I would get the the the incorrect checksum error at the same line on multiple runs. However, with different files and even different numbers of lines to print back I will come back without errors.
Any idea on how to track down the issue, I've been trying to debug it for hours to no avail.
Here is the offending code:
lines is defined as a char\*\* and was malloc as:
```
lines = (char**) malloc(nlines * sizeof(char *));
void insert_line(char *s, int len){
printf("\t\tLine Number: %d Putting a %d line into slot: %d\n",processed,len,slot);
if(processed > numlines -1){//clean up
free(*(lines+slot));
*(lines + slot) = NULL;
}
*(lines + slot) = (char *) malloc(len * sizeof(char));
if(*(lines + slot) == NULL) exit(EXIT_FAILURE);
strcpy(*(lines+slot),s);
slot = ++processed % numlines;
}
```
|
Your routine is writing beyond the allocated line buffer.
The size of the line passed as an argument (i.e. "len") probably does not include the NUL terminator. When you call malloc to copy the line (i.e. "s") you need to allocate an extra byte for the string terminator:
```
*(lines + slot) = (char *) malloc((len + 1) * sizeof(char));
```
|
232,682 |
<p>I've already written a generator that does the trick, but I'd like to know the best possible way to implement the off-side rule.</p>
<p>Shortly: <a href="http://en.wikipedia.org/wiki/Off-side_rule" rel="noreferrer">Off-side rule</a> means in this context that indentation is getting recognized as a syntactic element.</p>
<p>Here is the offside rule in pseudocode for making tokenizers that capture indentation in usable form, I don't want to limit answers by language:</p>
<pre><code>token NEWLINE
matches r"\n\ *"
increase line count
pick up and store the indentation level
remember to also record the current level of parenthesis
procedure layout tokens
level = stack of indentation levels
push 0 to level
last_newline = none
per each token
if it is NEWLINE put it to last_newline and get next token
if last_newline contains something
extract new_level and parenthesis_count from last_newline
- if newline was inside parentheses, do nothing
- if new_level > level.top
push new_level to level
emit last_newline as INDENT token and clear last_newline
- if new_level == level.top
emit last_newline and clear last_newline
- otherwise
while new_level < level.top
pop from level
if new_level > level.top
freak out, indentation is broken.
emit last_newline as DEDENT token
clear last_newline
emit token
while level.top != 0
emit token as DEDENT token
pop from level
comments are ignored before they are getting into the layouter
layouter lies between a lexer and a parser
</code></pre>
<p>This layouter doesn't generate more than one NEWLINE at time, and doesn't generate NEWLINE when there's indentation coming up. Therefore parsing rules remain quite simple. It's pretty good I think but inform if there's better way of accomplishing it.</p>
<p>While using this for a while, I've noticed that after DEDENTs it may be nice to emit newline anyway, this way you can separate the expressions with NEWLINE while keeping the INDENT DEDENT as a trailer for expression.</p>
|
[
{
"answer_id": 258167,
"author": "zaphod",
"author_id": 13871,
"author_profile": "https://Stackoverflow.com/users/13871",
"pm_score": 4,
"selected": true,
"text": "<p>I've written tokenizers and parsers for a couple of little indentation-centric domain-specific languages in the past couple of years, and what you have there looks pretty reasonable to me, for whatever that's worth. If I'm not mistaken, your method is quite similar to what Python does, for example, which seems like it ought to carry some weight.</p>\n\n<p>Converting NEWLINE NEWLINE INDENT to just INDENT before it hits the parser definitely seems like the right way to do things -- it's a pain (IME) to always be peeking ahead for that in the parser! I've actually done that step as a separate layer in what ended up being a three step process: the first combined what your lexer and layouter do minus all the NEWLINE lookahead stuff (which made it very simple), the second (also very simple) layer folded consecutive NEWLINEs and converted NEWLINE INDENT to just INDENT (or, actually, COLON NEWLINE INDENT to INDENT, since in this case all indented blocks were always preceded by colons), then the parser was the third stage on top of that. But it also makes a lot of sense to me to do things the way you've described them, especially if you want to separate the lexer from the layouter, which presumably you'd want to do if you were using a code-generation tool to make your lexer, for instance, as is common practice.</p>\n\n<p>I did have one application that needed to be a bit more flexible about indentation rules, essentially leaving the parser to enforce them when needed -- the following needed to be valid in certain contexts, for instance:</p>\n\n<pre><code>this line introduces an indented block of literal text:\n this line of the block is indented four spaces\n but this line is only indented two spaces\n</code></pre>\n\n<p>which doesn't work terribly well with INDENT/DEDENT tokens, since you end up needing to generate one INDENT for each column of indentation and an equal number of DEDENTs on the way back, unless you look way ahead to figure out where the indent levels are going to end up being, which it doesn't seem like you'd want a tokenizer to do. In that case I tried a few different things and ended up just storing a counter in each NEWLINE token that gave the change in indentation (positive or negative) for the following logical line. (Each token also stored all trailing whitespace, in case it needed preserving; for NEWLINE, the stored whitespace included the EOL itself, any intervening blank lines, and the indentation on the following logical line.) No separate INDENT or DEDENT tokens at all. Getting the parser to deal with that was a bit more work than just nesting INDENTs and DEDENTs, and might well have been hell with a complicated grammar that needed a fancy parser generator, but it wasn't nearly as bad as I'd feared, either. Again, no need for the parser to look ahead from NEWLINE to see if there's an INDENT coming up in this scheme.</p>\n\n<p>Still, I think you'd agree that allowing and preserving all manner of crazy-looking whitespace in the tokenizer/layouter and letting the parser decide what's a literal and what's code is a bit of an unusual requirement! You certainly wouldn't want your parser to be saddled with that indentation counter if you just wanted to be able to parse Python code, for example. The way you're doing things is almost certainly the right approach for your application and many others besides. Though if anyone else has thoughts on how best to do this sort of thing, I'd obviously love to hear them....</p>\n"
},
{
"answer_id": 946398,
"author": "dkagedal",
"author_id": 24458,
"author_profile": "https://Stackoverflow.com/users/24458",
"pm_score": 2,
"selected": false,
"text": "<p>Ive been experimenting with this recently, and I came to the conclusion that, for my needs at least, I wanted the NEWLINES to mark the end of each \"statement\", whether it was the last statement in an indented block or not, i.e. I need the newlines even before DEDENT.</p>\n\n<p>My solution was to turn it on its head, and instead of NEWLINES marking the end of lines, I use a LINE token to mark the start of a line.</p>\n\n<p>I have a lexer that collapses empty lines (including comment-only lines) and emits a single LINE token with information about the indentation of the last line. Then my preprocessing function takes this token stream and adds INDENT or DEDENT \"in between\" any lines where the indentation changes. So</p>\n\n<pre><code>line1\n line2\n line3\nline4\n</code></pre>\n\n<p>would give the token stream</p>\n\n<pre><code>LINE \"line1\" INDENT LINE \"line2\" LINE \"line3\" DEDENT LINE \"line4\" EOF\n</code></pre>\n\n<p>This allows me to write clear grammar productions for statements without worrying about detecting the end of statements even when they end with nested, indented, subblocks, something that can be hard if you are matching NEWLINES (and DEDENTS) instead.</p>\n\n<p>Here is the core of the preprocessor, written in O'Caml:</p>\n\n<pre><code> match next_token () with\n LINE indentation ->\n if indentation > !current_indentation then\n (\n Stack.push !current_indentation indentation_stack;\n current_indentation := indentation;\n INDENT\n )\n else if indentation < !current_indentation then\n (\n let prev = Stack.pop indentation_stack in\n if indentation > prev then\n (\n current_indentation := indentation;\n BAD_DEDENT\n )\n else\n (\n current_indentation := prev;\n DEDENT\n )\n )\n else (* indentation = !current_indentation *)\n let token = remove_next_token () in\n if next_token () = EOF then\n remove_next_token ()\n else\n token\n | _ ->\n remove_next_token ()\n</code></pre>\n\n<p>I haven't added support for parentheses yet, but that should be a simple extension. It does, however avoid emitting a stray LINE at the end of the file.</p>\n"
},
{
"answer_id": 6002740,
"author": "balu",
"author_id": 490153,
"author_profile": "https://Stackoverflow.com/users/490153",
"pm_score": 1,
"selected": false,
"text": "<p>Tokenizer in ruby for fun:</p>\n\n<pre><code>def tokenize(input)\n result, prev_indent, curr_indent, line = [\"\"], 0, 0, \"\"\n line_started = false\n\n input.each_char do |char|\n\n case char\n when ' '\n if line_started\n # Content already started, add it.\n line << char\n else\n # No content yet, just count.\n curr_indent += 1\n end\n when \"\\n\"\n result.last << line + \"\\n\"\n curr_indent, line = 0, \"\"\n line_started = false\n else\n # Check if we are at the first non-space character.\n unless line_started\n # Insert indent and dedent tokens if indentation changed.\n if prev_indent > curr_indent\n # 2 spaces dedentation\n ((prev_indent - curr_indent) / 2).times do\n result << :DEDENT\n end\n result << \"\"\n elsif prev_indent < curr_indent\n result << :INDENT\n result << \"\"\n end\n\n prev_indent = curr_indent\n end\n\n # Mark line as started and add char to line.\n line_started = true; line << char\n end\n\n end\n\n result\nend\n</code></pre>\n\n<p>Does only work for two-space-indentation. Result is something like <code>[\"Hello there from level 0\\n\", :INDENT, \"This\\nis level\\ntwo\\n\", :DEDENT, \"This is level0 again\\n\"]</code>.</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/232682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21711/"
] |
I've already written a generator that does the trick, but I'd like to know the best possible way to implement the off-side rule.
Shortly: [Off-side rule](http://en.wikipedia.org/wiki/Off-side_rule) means in this context that indentation is getting recognized as a syntactic element.
Here is the offside rule in pseudocode for making tokenizers that capture indentation in usable form, I don't want to limit answers by language:
```
token NEWLINE
matches r"\n\ *"
increase line count
pick up and store the indentation level
remember to also record the current level of parenthesis
procedure layout tokens
level = stack of indentation levels
push 0 to level
last_newline = none
per each token
if it is NEWLINE put it to last_newline and get next token
if last_newline contains something
extract new_level and parenthesis_count from last_newline
- if newline was inside parentheses, do nothing
- if new_level > level.top
push new_level to level
emit last_newline as INDENT token and clear last_newline
- if new_level == level.top
emit last_newline and clear last_newline
- otherwise
while new_level < level.top
pop from level
if new_level > level.top
freak out, indentation is broken.
emit last_newline as DEDENT token
clear last_newline
emit token
while level.top != 0
emit token as DEDENT token
pop from level
comments are ignored before they are getting into the layouter
layouter lies between a lexer and a parser
```
This layouter doesn't generate more than one NEWLINE at time, and doesn't generate NEWLINE when there's indentation coming up. Therefore parsing rules remain quite simple. It's pretty good I think but inform if there's better way of accomplishing it.
While using this for a while, I've noticed that after DEDENTs it may be nice to emit newline anyway, this way you can separate the expressions with NEWLINE while keeping the INDENT DEDENT as a trailer for expression.
|
I've written tokenizers and parsers for a couple of little indentation-centric domain-specific languages in the past couple of years, and what you have there looks pretty reasonable to me, for whatever that's worth. If I'm not mistaken, your method is quite similar to what Python does, for example, which seems like it ought to carry some weight.
Converting NEWLINE NEWLINE INDENT to just INDENT before it hits the parser definitely seems like the right way to do things -- it's a pain (IME) to always be peeking ahead for that in the parser! I've actually done that step as a separate layer in what ended up being a three step process: the first combined what your lexer and layouter do minus all the NEWLINE lookahead stuff (which made it very simple), the second (also very simple) layer folded consecutive NEWLINEs and converted NEWLINE INDENT to just INDENT (or, actually, COLON NEWLINE INDENT to INDENT, since in this case all indented blocks were always preceded by colons), then the parser was the third stage on top of that. But it also makes a lot of sense to me to do things the way you've described them, especially if you want to separate the lexer from the layouter, which presumably you'd want to do if you were using a code-generation tool to make your lexer, for instance, as is common practice.
I did have one application that needed to be a bit more flexible about indentation rules, essentially leaving the parser to enforce them when needed -- the following needed to be valid in certain contexts, for instance:
```
this line introduces an indented block of literal text:
this line of the block is indented four spaces
but this line is only indented two spaces
```
which doesn't work terribly well with INDENT/DEDENT tokens, since you end up needing to generate one INDENT for each column of indentation and an equal number of DEDENTs on the way back, unless you look way ahead to figure out where the indent levels are going to end up being, which it doesn't seem like you'd want a tokenizer to do. In that case I tried a few different things and ended up just storing a counter in each NEWLINE token that gave the change in indentation (positive or negative) for the following logical line. (Each token also stored all trailing whitespace, in case it needed preserving; for NEWLINE, the stored whitespace included the EOL itself, any intervening blank lines, and the indentation on the following logical line.) No separate INDENT or DEDENT tokens at all. Getting the parser to deal with that was a bit more work than just nesting INDENTs and DEDENTs, and might well have been hell with a complicated grammar that needed a fancy parser generator, but it wasn't nearly as bad as I'd feared, either. Again, no need for the parser to look ahead from NEWLINE to see if there's an INDENT coming up in this scheme.
Still, I think you'd agree that allowing and preserving all manner of crazy-looking whitespace in the tokenizer/layouter and letting the parser decide what's a literal and what's code is a bit of an unusual requirement! You certainly wouldn't want your parser to be saddled with that indentation counter if you just wanted to be able to parse Python code, for example. The way you're doing things is almost certainly the right approach for your application and many others besides. Though if anyone else has thoughts on how best to do this sort of thing, I'd obviously love to hear them....
|
232,688 |
<pre><code><style type="text/css">
html, body {
background: #fff;
margin: 0;
padding: 0;
}
#nav {
font-family: Verdana, sans-serif;
height: 29px;
font-size: 12px;
padding: 0 0 0 10px; /* this is used for something else */
background-color: #456;
}
#nav ul, #nav ul li {
list-style: none;
margin: 0;
padding: 9px 0 0 0px;
}
#nav ul {
text-align: center;
}
#nav ul li {
display: inline;
}
#nav ul li.last {
margin-right: 0;
}
#nav ul li a {
color: #FFF;
text-decoration: none;
padding: 0px 0 0 20px;
height: 29px;
}
#nav ul li a span {
padding: 8px 20px 0 0;
height: 21px;
}
#nav ul li a:hover {
background: #789;
}
</style>
<div id="nav">
<ul>
<li><a href="/1/"><span>One</span></a></li>
<li><a href="/2/"><span>Two</span></a></li>
<li><a href="/3/"><span>Three</span></a></li>
<li><a href="/4/"><span>Four</span></a></li>
</ul>
</div>
</code></pre>
<p>I have a little problem with that, as it doesn't make the "hover background" 100% of the height of the nav bar.</p>
|
[
{
"answer_id": 232699,
"author": "Gene",
"author_id": 22673,
"author_profile": "https://Stackoverflow.com/users/22673",
"pm_score": 0,
"selected": false,
"text": "<p>have you tried:</p>\n\n<pre><code>#nav ul li a {\n color: #FFF;\n text-decoration: none;\n padding: 0px 0 0 20px;\n height: 29px;\n line-height: 29px;\n}\n</code></pre>\n"
},
{
"answer_id": 232725,
"author": "Fuzzy76",
"author_id": 15932,
"author_profile": "https://Stackoverflow.com/users/15932",
"pm_score": 0,
"selected": false,
"text": "<p>Don't set the height on the outermost element. Set it on the innermost element (will require a display:block on your a-rule in addition to the height).</p>\n"
},
{
"answer_id": 232728,
"author": "Gene",
"author_id": 22673,
"author_profile": "https://Stackoverflow.com/users/22673",
"pm_score": 2,
"selected": true,
"text": "<p>This works on my machine:</p>\n\n<pre><code><style type=\"text/css\">\nhtml, body {\n background: #fff;\n margin: 0;\n padding: 0;\n}\n\n#nav {\n font-family: Verdana, sans-serif;\n height: 29px;\n font-size: 12px;\n padding: 0 0 0 10px; /* this is used for something else */\n background-color: #456;\n}\n\n#nav ul, #nav ul li {\n list-style: none;\n margin: 0;\n padding: 0 0 0 0px;\n}\n\n#nav ul {\n text-align: center;\n position:relative;\n width:300px;\n margin:0 auto 0 auto;\n}\n\n#nav ul li {\n float:left;\n}\n\n#nav ul li.last {\n margin-right: 0;\n}\n\n\n#nav ul li a {\n float:left;\n color: #FFF;\n text-decoration: none;\n padding: 9px 0 0 20px;\n height: 20px;\n\n}\n#nav ul li a span {\n padding: 8px 20px 0 0;\n height: 20px;\n}\n\n#nav ul li a:hover {\n background: #789;\n}\n</style>\n</code></pre>\n"
},
{
"answer_id": 244328,
"author": "Sal",
"author_id": 32144,
"author_profile": "https://Stackoverflow.com/users/32144",
"pm_score": 0,
"selected": false,
"text": "<p>You should put your padding and line-height on the <strong>a</strong> tag. The spans are not needed, and you also don't really need any padding in the li either. If the user changes the text size, the hover backgrounds come out of the tabe area though.</p>\n\n<pre><code><style type=\"text/css\">\nhtml, body {\n background: #fff;\n margin: 0;\n padding: 0;\n}\n\n#nav {\n font-family: Verdana, sans-serif;\n height: 29px;\n font-size: 12px;\n padding: 0 0 0 10px; /* this is used for something else */\n background-color: #456;\n}\n\n#nav ul, #nav ul li {\n list-style: none;\n margin: 0;\n padding: 0px;\n}\n\n#nav ul {\n text-align: center;\n}\n\n#nav ul li {\n display: inline;\n}\n\n#nav ul li.last {\n margin-right: 0;\n}\n\n\n#nav ul li a {\n color: #FFF;\n text-decoration: none;\n padding: 8px 20px 7px 20px;\n line-height:29px;\n}\n\n#nav ul li a:hover {\n background-color: #789;\n}\n</style>\n\n<div id=\"nav\">\n <ul>\n <li><a href=\"/1/\">One</a></li>\n <li><a href=\"/2/\">Two</a></li>\n <li><a href=\"/3/\">Three</a></li>\n <li><a href=\"/4/\">Four</a></li>\n </ul>\n</div>\n</code></pre>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/232688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21559/"
] |
```
<style type="text/css">
html, body {
background: #fff;
margin: 0;
padding: 0;
}
#nav {
font-family: Verdana, sans-serif;
height: 29px;
font-size: 12px;
padding: 0 0 0 10px; /* this is used for something else */
background-color: #456;
}
#nav ul, #nav ul li {
list-style: none;
margin: 0;
padding: 9px 0 0 0px;
}
#nav ul {
text-align: center;
}
#nav ul li {
display: inline;
}
#nav ul li.last {
margin-right: 0;
}
#nav ul li a {
color: #FFF;
text-decoration: none;
padding: 0px 0 0 20px;
height: 29px;
}
#nav ul li a span {
padding: 8px 20px 0 0;
height: 21px;
}
#nav ul li a:hover {
background: #789;
}
</style>
<div id="nav">
<ul>
<li><a href="/1/"><span>One</span></a></li>
<li><a href="/2/"><span>Two</span></a></li>
<li><a href="/3/"><span>Three</span></a></li>
<li><a href="/4/"><span>Four</span></a></li>
</ul>
</div>
```
I have a little problem with that, as it doesn't make the "hover background" 100% of the height of the nav bar.
|
This works on my machine:
```
<style type="text/css">
html, body {
background: #fff;
margin: 0;
padding: 0;
}
#nav {
font-family: Verdana, sans-serif;
height: 29px;
font-size: 12px;
padding: 0 0 0 10px; /* this is used for something else */
background-color: #456;
}
#nav ul, #nav ul li {
list-style: none;
margin: 0;
padding: 0 0 0 0px;
}
#nav ul {
text-align: center;
position:relative;
width:300px;
margin:0 auto 0 auto;
}
#nav ul li {
float:left;
}
#nav ul li.last {
margin-right: 0;
}
#nav ul li a {
float:left;
color: #FFF;
text-decoration: none;
padding: 9px 0 0 20px;
height: 20px;
}
#nav ul li a span {
padding: 8px 20px 0 0;
height: 20px;
}
#nav ul li a:hover {
background: #789;
}
</style>
```
|
232,691 |
<p>I've allocated an "array" of <code>mystruct</code> of size <code>n</code> like this:</p>
<pre><code>if (NULL == (p = calloc(sizeof(struct mystruct) * n,1))) {
/* handle error */
}
</code></pre>
<p>Later on, I only have access to <code>p</code>, and no longer have <code>n</code>. Is there a way to determine the length of the array given just the pointer <code>p</code>?</p>
<p>I figure it <em>must</em> be possible, since <code>free(p)</code> does just that. I know <code>malloc()</code> keeps track of how much memory it has allocated, and that's why it knows the length; perhaps there is a way to query for this information? Something like...</p>
<pre><code>int length = askMallocLibraryHowMuchMemoryWasAlloced(p) / sizeof(mystruct)
</code></pre>
<p>I know I should just rework the code so that I know <code>n</code>, but I'd rather not if possible. Any ideas?</p>
|
[
{
"answer_id": 232696,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 4,
"selected": false,
"text": "<p>keep track of the array size yourself; free uses the malloc chain to free the <em>block</em> that was allocated, which does not necessarily have the same size as the array you requested</p>\n"
},
{
"answer_id": 232697,
"author": "Bob Somers",
"author_id": 1384,
"author_profile": "https://Stackoverflow.com/users/1384",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not aware of a way, but I would imagine it would deal with mucking around in malloc's internals which is generally a very, very bad idea.</p>\n\n<p>Why is it that you can't store the size of memory you allocated?</p>\n\n<p>EDIT: If you know that you should rework the code so you know n, well, do it. Yes it might be quick and easy to try to poll malloc but knowing n for sure would minimize confusion and strengthen the design.</p>\n"
},
{
"answer_id": 232706,
"author": "David Arno",
"author_id": 7122,
"author_profile": "https://Stackoverflow.com/users/7122",
"pm_score": 2,
"selected": false,
"text": "<p>malloc will return a block of memory at least as big as you requested, but possibly bigger. So even if you could query the block size, this would not reliably give you your array size. So you'll just have to modify your code to keep track of it yourself.</p>\n"
},
{
"answer_id": 232709,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 1,
"selected": false,
"text": "<p>One of the reasons that you can't ask the malloc library how big a block is, is that the allocator will usually round up the size of your request to meet some minimum granularity requirement (for example, 16 bytes). So if you ask for 5 bytes, you'll get a block of size 16 back. If you were to take 16 and divide by 5, you would get three elements when you really only allocated one. It would take extra space for the malloc library to keep track of how many bytes you asked for in the first place, so it's best for you to keep track of that yourself.</p>\n"
},
{
"answer_id": 232719,
"author": "Barry Wark",
"author_id": 2140,
"author_profile": "https://Stackoverflow.com/users/2140",
"pm_score": 7,
"selected": true,
"text": "<p>No, there is no way to get this information without depending strongly on the implementation details of <code>malloc</code>. In particular, <code>malloc</code> may allocate more bytes than you request (e.g. for efficiency in a particular memory architecture). It would be much better to redesign your code so that you keep track of <code>n</code> explicitly. The alternative is <em>at least</em> as much redesign and a much more dangerous approach (given that it's non-standard, abuses the semantics of pointers, and will be a maintenance nightmare for those that come after you): store the length<code>n</code> at the malloc'd address, followed by the array. Allocation would then be:</p>\n\n<pre><code>void *p = calloc(sizeof(struct mystruct) * n + sizeof(unsigned long int),1));\n*((unsigned long int*)p) = n;\n</code></pre>\n\n<p><code>n</code> is now stored at <code>*((unsigned long int*)p)</code> and the start of your array is now</p>\n\n<pre><code>void *arr = p+sizeof(unsigned long int);\n</code></pre>\n\n<p><strong>Edit:</strong> Just to play devil's advocate... I know that these \"solutions\" all require redesigns, but let's play it out.\nOf course, the solution presented above is just a hacky implementation of a (well-packed) struct. You might as well define:</p>\n\n<pre><code>typedef struct { \n unsigned int n;\n void *arr;\n} arrInfo;\n</code></pre>\n\n<p>and pass around <code>arrInfo</code>s rather than raw pointers.</p>\n\n<p>Now we're cooking. But as long as you're redesigning, why stop here? What you really want is an abstract data type (ADT). Any introductory text for an algorithms and data structures class would do it. An ADT defines the public interface of a data type but hides the implementation of that data type. Thus, publicly an ADT for an array might look like</p>\n\n<pre><code>typedef void* arrayInfo;\n(arrayInfo)newArrayInfo(unsignd int n, unsigned int itemSize);\n(void)deleteArrayInfo(arrayInfo);\n(unsigned int)arrayLength(arrayInfo);\n(void*)arrayPtr(arrayInfo);\n...\n</code></pre>\n\n<p>In other words, an ADT is a form of data and behavior encapsulation... in other words, it's about as close as you can get to Object-Oriented Programming using straight C. Unless you're stuck on a platform that doesn't have a C++ compiler, you might as well go whole hog and just use an STL <code>std::vector</code>.</p>\n\n<p>There, we've taken a simple question about C and ended up at C++. God help us all.</p>\n"
},
{
"answer_id": 232729,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 3,
"selected": false,
"text": "<p>Just to confirm the previous answers: There is no way to know, just by studying a pointer, how much memory was allocated by a malloc which returned this pointer.</p>\n\n<h2>What if it worked?</h2>\n\n<p>One example of why this is not possible. Let's imagine the code with an hypothetic function called get_size(void *) which returns the memory allocated for a pointer:</p>\n\n<pre><code>typedef struct MyStructTag\n{ /* etc. */ } MyStruct ;\n\nvoid doSomething(MyStruct * p)\n{\n /* well... extract the memory allocated? */\n size_t i = get_size(p) ;\n initializeMyStructArray(p, i) ;\n}\n\nvoid doSomethingElse()\n{\n MyStruct * s = malloc(sizeof(MyStruct) * 10) ; /* Allocate 10 items */\n doSomething(s) ;\n}\n</code></pre>\n\n<h2>Why even if it worked, it would not work anyway?</h2>\n\n<p>But the problem of this approach is that, in C, you can play with pointer arithmetics. Let's rewrite doSomethingElse():</p>\n\n<pre><code>void doSomethingElse()\n{\n MyStruct * s = malloc(sizeof(MyStruct) * 10) ; /* Allocate 10 items */\n MyStruct * s2 = s + 5 ; /* s2 points to the 5th item */\n doSomething(s2) ; /* Oops */\n}\n</code></pre>\n\n<p>How get_size is supposed to work, as you sent the function a valid pointer, but not the one returned by malloc. And even if get_size went through all the trouble to find the size (i.e. in an inefficient way), it would return, in this case, a value that would be wrong in your context.</p>\n\n<h2>Conclusion</h2>\n\n<p>There are always ways to avoid this problem, and in C, you can always write your own allocator, but again, it is perhaps too much trouble when all you need is to remember how much memory was allocated.</p>\n"
},
{
"answer_id": 232743,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 2,
"selected": false,
"text": "<p>May I recommend a terrible way to do it?</p>\n\n<p>Allocate all your arrays as follows:</p>\n\n<pre><code>void *blockOfMem = malloc(sizeof(mystruct)*n + sizeof(int));\n\n((int *)blockofMem)[0] = n;\nmystruct *structs = (mystruct *)(((int *)blockOfMem) + 1);\n</code></pre>\n\n<p>Then you can always cast your arrays to <code>int *</code> and access the -1st element.</p>\n\n<p>Be sure to <code>free</code> that pointer, and not the array pointer itself!</p>\n\n<p>Also, this will likely cause terrible bugs that will leave you tearing your hair out. Maybe you can wrap the alloc funcs in API calls or something. </p>\n"
},
{
"answer_id": 232882,
"author": "quinmars",
"author_id": 18687,
"author_profile": "https://Stackoverflow.com/users/18687",
"pm_score": 2,
"selected": false,
"text": "<p>For an array of pointers you can use a NULL-terminated array. The length can then determinate like it is done with strings. In your example you can maybe use an structure attribute to mark then end. Of course that depends if there is a member that cannot be NULL. So lets say you have an attribute name, that needs to be set for every struct in your array you can then query the size by:</p>\n\n<pre><code>\nint size;\nstruct mystruct *cur;\n\nfor (cur = myarray; cur->name != NULL; cur++)\n ;\n\nsize = cur - myarray;\n</code></pre>\n\n<p>Btw it should be calloc(n, sizeof(struct mystruct)) in your example.</p>\n"
},
{
"answer_id": 232908,
"author": "dmityugov",
"author_id": 3232,
"author_profile": "https://Stackoverflow.com/users/3232",
"pm_score": 3,
"selected": false,
"text": "<p>Some compilers provide msize() or similar functions (_msize() etc), that let you do exactly that</p>\n"
},
{
"answer_id": 234492,
"author": "dmckee --- ex-moderator kitten",
"author_id": 2509,
"author_profile": "https://Stackoverflow.com/users/2509",
"pm_score": 2,
"selected": false,
"text": "<p>Other have discussed the limits of plain c pointers and the <code>stdlib.h</code> implementations of <code>malloc()</code>. Some implementations provide extensions which return the <em>allocated</em> block size which may be larger than the requested size.</p>\n\n<p>If you <em>must</em> have this behavior you can use or write a specialized memory allocator. This simplest thing to do would be implementing a wrapper around the <code>stdlib.h</code> functions. Some thing like:</p>\n\n<pre><code>void* my_malloc(size_t s); /* Calls malloc(s), and if successful stores \n (p,s) in a list of handled blocks */\nvoid my_free(void* p); /* Removes list entry and calls free(p) */\nsize_t my_block_size(void* p); /* Looks up p, and returns the stored size */\n...\n</code></pre>\n"
},
{
"answer_id": 3637498,
"author": "Wm J",
"author_id": 439131,
"author_profile": "https://Stackoverflow.com/users/439131",
"pm_score": 1,
"selected": false,
"text": "<p>This is a test of my sort routine. It sets up 7 variables to hold float values, then assigns them to an array, which is used to find the max value.</p>\n\n<p>The magic is in the call to myMax:</p>\n\n<p>float mmax = myMax((float *)&arr,(int) sizeof(arr)/sizeof(arr[0]));</p>\n\n<p>And that was magical, wasn't it? </p>\n\n<p>myMax expects a float array pointer (float *) so I use &arr to get the address of the array, and cast it as a float pointer. </p>\n\n<p>myMax also expects the number of elements in the array as an int. I get that value by using sizeof() to give me byte sizes of the array and the first element of the array, then divide the total bytes by the number of bytes in each element. (we should not guess or hard code the size of an int because it's 2 bytes on some system and 4 on some like my OS X Mac, and could be something else on others).</p>\n\n<p>NOTE:All this is important when your data may have a varying number of samples.</p>\n\n<p>Here's the test code:</p>\n\n<pre><code>#include <stdio.h>\n\nfloat a, b, c, d, e, f, g;\n\nfloat myMax(float *apa,int soa){\n int i;\n float max = apa[0];\n for(i=0; i< soa; i++){\n if (apa[i]>max){max=apa[i];}\n printf(\"on i=%d val is %0.2f max is %0.2f, soa=%d\\n\",i,apa[i],max,soa);\n }\n return max;\n}\n\nint main(void)\n{\n a = 2.0;\n b = 1.0;\n c = 4.0;\n d = 3.0;\n e = 7.0;\n f = 9.0;\n g = 5.0;\n float arr[] = {a,b,c,d,e,f,g};\n\n float mmax = myMax((float *)&arr,(int) sizeof(arr)/sizeof(arr[0]));\n printf(\"mmax = %0.2f\\n\",mmax);\n\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 3637637,
"author": "pm100",
"author_id": 173397,
"author_profile": "https://Stackoverflow.com/users/173397",
"pm_score": 2,
"selected": false,
"text": "<p>really your question is - \"can I find out the size of a malloc'd (or calloc'd) data block\". And as others have said: no, not in a standard way.</p>\n\n<p>However there are custom malloc implementations that do it - for example <a href=\"http://dmalloc.com/\" rel=\"nofollow noreferrer\">http://dmalloc.com/</a></p>\n"
},
{
"answer_id": 32662566,
"author": "Jonathon Reinhart",
"author_id": 119527,
"author_profile": "https://Stackoverflow.com/users/119527",
"pm_score": 0,
"selected": false,
"text": "<p>In <a href=\"http://www.uclibc.org/\" rel=\"nofollow\">uClibc</a>, there is a <code>MALLOC_SIZE</code> macro in <a href=\"http://git.uclibc.org/uClibc/tree/libc/stdlib/malloc/malloc.h#n103\" rel=\"nofollow\"><code>malloc.h</code></a>:</p>\n\n<pre><code>/* The size of a malloc allocation is stored in a size_t word\n MALLOC_HEADER_SIZE bytes prior to the start address of the allocation:\n\n +--------+---------+-------------------+\n | SIZE |(unused) | allocation ... |\n +--------+---------+-------------------+\n ^ BASE ^ ADDR\n ^ ADDR - MALLOC_HEADER_SIZE\n*/\n\n/* The amount of extra space used by the malloc header. */\n#define MALLOC_HEADER_SIZE \\\n (MALLOC_ALIGNMENT < sizeof (size_t) \\\n ? sizeof (size_t) \\\n : MALLOC_ALIGNMENT)\n\n/* Set up the malloc header, and return the user address of a malloc block. */\n#define MALLOC_SETUP(base, size) \\\n (MALLOC_SET_SIZE (base, size), (void *)((char *)base + MALLOC_HEADER_SIZE))\n/* Set the size of a malloc allocation, given the base address. */\n#define MALLOC_SET_SIZE(base, size) (*(size_t *)(base) = (size))\n\n/* Return base-address of a malloc allocation, given the user address. */\n#define MALLOC_BASE(addr) ((void *)((char *)addr - MALLOC_HEADER_SIZE))\n/* Return the size of a malloc allocation, given the user address. */\n#define MALLOC_SIZE(addr) (*(size_t *)MALLOC_BASE(addr))\n</code></pre>\n"
},
{
"answer_id": 68453433,
"author": "Parampreet Rai",
"author_id": 12615039,
"author_profile": "https://Stackoverflow.com/users/12615039",
"pm_score": 0,
"selected": false,
"text": "<p><code>malloc()</code> stores metadata regarding space allocation before 8 bytes from space actually allocated. This could be used to determine space of buffer. And on my x86-64 this always return multiple of 16. So if allocated space is multiple of 16 (which is in most cases) then this could be used:</p>\n<h2 id=\"code-e12i\">Code</h2>\n<pre class=\"lang-c prettyprint-override\"><code>#include <stdio.h>\n#include <malloc.h>\n\nint size_of_buff(void *buff) {\n return ( *( ( int * ) buff - 2 ) - 17 ); // 32 bit system: ( *( ( int * ) buff - 1 ) - 17 )\n}\n\nvoid main() {\n char *buff = malloc(1024);\n printf("Size of Buffer: %d\\n", size_of_buff(buff));\n}\n</code></pre>\n<h2 id=\"output-hsib\">Output</h2>\n<pre><code>Size of Buffer: 1024\n</code></pre>\n"
},
{
"answer_id": 73735629,
"author": "Aboutaleb Roshan",
"author_id": 14512444,
"author_profile": "https://Stackoverflow.com/users/14512444",
"pm_score": 0,
"selected": false,
"text": "<p>This is my approach:</p>\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct _int_array\n{\n int *number;\n int size;\n} int_array;\n\nint int_array_append(int_array *a, int n)\n{\n static char c = 0;\n if(!c)\n {\n a->number = NULL;\n a->size = 0;\n c++;\n }\n\n int *more_numbers = NULL;\n\n a->size++;\n more_numbers = (int *)realloc(a->number, a->size * sizeof(int));\n if(more_numbers != NULL)\n {\n a->number = more_numbers;\n a->number[a->size - 1] = n;\n }\n else\n {\n free(a->number);\n printf("Error (re)allocating memory.\\n");\n return 1;\n }\n\n return 0;\n}\n\nint main()\n{\n int_array a;\n\n int_array_append(&a, 10);\n int_array_append(&a, 20);\n int_array_append(&a, 30);\n int_array_append(&a, 40);\n\n int i;\n for(i = 0; i < a.size; i++)\n printf("%d\\n", a.number[i]);\n\n printf("\\nLen: %d\\nSize: %d\\n", a.size, a.size * sizeof(int));\n\n free(a.number);\n return 0;\n}\n</code></pre>\n<p><strong>Output:</strong></p>\n<pre><code>10\n20\n30\n40\n\nLen: 4\nSize: 16\n</code></pre>\n"
},
{
"answer_id": 73735889,
"author": "jxh",
"author_id": 315052,
"author_profile": "https://Stackoverflow.com/users/315052",
"pm_score": 0,
"selected": false,
"text": "<p>If your compiler supports VLA (variable length array), you can embed the array length into the pointer type.</p>\n<pre><code>int n = 10;\nint (*p)[n] = malloc(n * sizeof(int));\nn = 3;\nprintf("%d\\n", sizeof(*p)/sizeof(**p));\n</code></pre>\n<p>The output is 10.</p>\n<p>You could also choose to embed the information into the allocated memory yourself with a structure including a flexible array member.</p>\n<pre><code>struct myarray {\n int n;\n struct mystruct a[];\n};\n\nstruct myarray *ma =\n malloc(sizeof(*ma) + n * sizeof(struct mystruct));\nma->n = n;\nstruct mystruct *p = ma->a;\n</code></pre>\n<p>Then to recover the size, you would subtract the offset of the flexible member.</p>\n<pre><code>int get_size (struct mystruct *p) {\n struct myarray *ma;\n char *x = (char *)p;\n ma = (void *)(x - offsetof(struct myarray, a));\n return ma->n;\n}\n</code></pre>\n<hr />\n<p>The problem with trying to peek into heap structures is that the layout might change from platform to platform or from release to release, and so the information may not be reliably obtainable.</p>\n<p>Even if you knew exactly how to peek into the meta information maintained by your allocator, the information stored there may have nothing to do with the size of the array. The allocator simply returned memory that could be used to fit the requested size, but the actual size of the memory may be larger (perhaps even much larger) than the requested amount.</p>\n<p>The only reliable way to know the information is to find a way to track it yourself.</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/232691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31092/"
] |
I've allocated an "array" of `mystruct` of size `n` like this:
```
if (NULL == (p = calloc(sizeof(struct mystruct) * n,1))) {
/* handle error */
}
```
Later on, I only have access to `p`, and no longer have `n`. Is there a way to determine the length of the array given just the pointer `p`?
I figure it *must* be possible, since `free(p)` does just that. I know `malloc()` keeps track of how much memory it has allocated, and that's why it knows the length; perhaps there is a way to query for this information? Something like...
```
int length = askMallocLibraryHowMuchMemoryWasAlloced(p) / sizeof(mystruct)
```
I know I should just rework the code so that I know `n`, but I'd rather not if possible. Any ideas?
|
No, there is no way to get this information without depending strongly on the implementation details of `malloc`. In particular, `malloc` may allocate more bytes than you request (e.g. for efficiency in a particular memory architecture). It would be much better to redesign your code so that you keep track of `n` explicitly. The alternative is *at least* as much redesign and a much more dangerous approach (given that it's non-standard, abuses the semantics of pointers, and will be a maintenance nightmare for those that come after you): store the length`n` at the malloc'd address, followed by the array. Allocation would then be:
```
void *p = calloc(sizeof(struct mystruct) * n + sizeof(unsigned long int),1));
*((unsigned long int*)p) = n;
```
`n` is now stored at `*((unsigned long int*)p)` and the start of your array is now
```
void *arr = p+sizeof(unsigned long int);
```
**Edit:** Just to play devil's advocate... I know that these "solutions" all require redesigns, but let's play it out.
Of course, the solution presented above is just a hacky implementation of a (well-packed) struct. You might as well define:
```
typedef struct {
unsigned int n;
void *arr;
} arrInfo;
```
and pass around `arrInfo`s rather than raw pointers.
Now we're cooking. But as long as you're redesigning, why stop here? What you really want is an abstract data type (ADT). Any introductory text for an algorithms and data structures class would do it. An ADT defines the public interface of a data type but hides the implementation of that data type. Thus, publicly an ADT for an array might look like
```
typedef void* arrayInfo;
(arrayInfo)newArrayInfo(unsignd int n, unsigned int itemSize);
(void)deleteArrayInfo(arrayInfo);
(unsigned int)arrayLength(arrayInfo);
(void*)arrayPtr(arrayInfo);
...
```
In other words, an ADT is a form of data and behavior encapsulation... in other words, it's about as close as you can get to Object-Oriented Programming using straight C. Unless you're stuck on a platform that doesn't have a C++ compiler, you might as well go whole hog and just use an STL `std::vector`.
There, we've taken a simple question about C and ended up at C++. God help us all.
|
232,732 |
<p>How do I convert a string to DateTime format? For example, if I had a string like:</p>
<p><code>"24/10/2008"</code></p>
<p>How do I get that into DateTime format ?</p>
|
[
{
"answer_id": 232739,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": false,
"text": "<p>Use <a href=\"http://msdn.microsoft.com/en-us/library/system.datetime.parseexact.aspx\" rel=\"noreferrer\">DateTime.ParseExact</a>:</p>\n\n<pre><code>string str = \"24/10/2008\";\nDateTime dt = DateTime.ParseExact(str, \"dd/MM/yyyy\", \n Thread.CurrentThread.CurrentCulture);\n</code></pre>\n\n<p>(You should consider what culture you actually want to parse it in, admittedly.)</p>\n\n<p>EDIT: Other answers have specified \"null\" as the third parameter - this is equivalent to using <code>Thread.CurrentThread.CurrentCulture</code>.</p>\n\n<p>For other formats, see <a href=\"http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx\" rel=\"noreferrer\">\"Custom Date and Time Format Strings\"</a> in MSDN.</p>\n"
},
{
"answer_id": 232749,
"author": "Michal Sznajder",
"author_id": 501,
"author_profile": "https://Stackoverflow.com/users/501",
"pm_score": 0,
"selected": false,
"text": "<p>Try something like</p>\n\n<pre><code>DateTime date = System.DateTime.ParseExact(str, \"dd/MM/yyyy\", null);\n</code></pre>\n\n<p>For time this might work </p>\n\n<pre><code>DateTime date = System.DateTime.ParseExact(str, \"HH:mm:ss\", null);\n</code></pre>\n"
},
{
"answer_id": 232754,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<pre><code>string str = \"24/10/2008\";\nDateTime dt = Convert.ToDateTime(str);\n</code></pre>\n"
},
{
"answer_id": 232845,
"author": "mr_georg",
"author_id": 26070,
"author_profile": "https://Stackoverflow.com/users/26070",
"pm_score": 2,
"selected": false,
"text": "<p>If you don't know the format, use:</p>\n\n<pre><code>DateTime d = DateTime.Parse(dateString);\n</code></pre>\n\n<p>This tries to parse the string representation of a date and time using the formatting rules of the current culture (e.g. English (US) \"en-US\", German \"de-DE\", ...). It tries to ignore unrecognized data, and fills in missing values for year, month and day with the current date (if parsing only a string containing the time for example).</p>\n\n<p>If you know that the used culture of the string is different from the current one, you can specify the culture to use:</p>\n\n<pre><code>CultureInfo culture = CultureInfo.CreateSpecificCulture(\"en-US\");\nDateTime d = DateTime.Parse(dateString, culture);\n</code></pre>\n\n<p>You should allways suround the conversion by a try-catch block since the string must conform to a recognized pattern. Alternatively, you can also test the validity of the string with the method <code>DateTime.TryParse(dateString, out dateTime)</code> which returns true on success and the result in <code>dateTime</code>; or false otherwise.</p>\n\n<p>If you know the exact format, you can use</p>\n\n<pre><code>DateTime d = DateTime.ParseExact(dateString, \"dd/MM/yyyy\", null);\n</code></pre>\n\n<p>(See <a href=\"http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx\" rel=\"nofollow noreferrer\">Custom Date and Time Format Strings</a> from the MSDN site for other format strings).</p>\n"
},
{
"answer_id": 232966,
"author": "Jeff Atwood",
"author_id": 1,
"author_profile": "https://Stackoverflow.com/users/1",
"pm_score": 2,
"selected": false,
"text": "<p>I'd also suggest looking at <a href=\"http://msdn.microsoft.com/en-us/library/system.datetime.tryparse.aspx\" rel=\"nofollow noreferrer\"><code>DateTime.TryParse</code></a> if you aren't sure what format the date string will be in. This way you can avoid handing very expensive exceptions in the Parse routine.</p>\n\n<p>I'd also second Jon Skeet's recommendation to use <a href=\"http://msdn.microsoft.com/en-us/library/system.datetime.parseexact.aspx\" rel=\"nofollow noreferrer\"><code>DateTime.ParseExact</code></a> if you <strong>do</strong> know <em>exactly</em> what format the date will be in, every time.</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/232732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
How do I convert a string to DateTime format? For example, if I had a string like:
`"24/10/2008"`
How do I get that into DateTime format ?
|
Use [DateTime.ParseExact](http://msdn.microsoft.com/en-us/library/system.datetime.parseexact.aspx):
```
string str = "24/10/2008";
DateTime dt = DateTime.ParseExact(str, "dd/MM/yyyy",
Thread.CurrentThread.CurrentCulture);
```
(You should consider what culture you actually want to parse it in, admittedly.)
EDIT: Other answers have specified "null" as the third parameter - this is equivalent to using `Thread.CurrentThread.CurrentCulture`.
For other formats, see ["Custom Date and Time Format Strings"](http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx) in MSDN.
|
232,744 |
<p>Sometimes gdb prints "incomplete type" for some type of variables. What does this mean and how can we see that value?</p>
|
[
{
"answer_id": 240856,
"author": "Daniel Cassidy",
"author_id": 31662,
"author_profile": "https://Stackoverflow.com/users/31662",
"pm_score": 6,
"selected": true,
"text": "<p>It means that the type of that variable has been incompletely specified. For example:</p>\n\n<pre><code>struct hatstand;\nstruct hatstand *foo;\n</code></pre>\n\n<p>GDB knows that <code>foo</code> is a pointer to a <code>hatstand</code> structure, but the members of that structure haven't been defined. Hence, \"incomplete type\".</p>\n\n<p>To print the value, you can cast it to a compatible type.</p>\n\n<p>For example, if you know that <code>foo</code> is really a pointer to a <code>lampshade</code> structure:</p>\n\n<pre><code>print (struct lampshade *)foo\n</code></pre>\n\n<p>Or, you could print it as a generic pointer, or treat it as if it were an integer:</p>\n\n<pre><code>print (void *)foo\nprint (int)foo\n</code></pre>\n\n<p>See also these pages from the GDB manual:</p>\n\n<ul>\n<li><a href=\"http://sourceware.org/gdb/current/onlinedocs/gdb/Data.html#Data\" rel=\"noreferrer\">http://sourceware.org/gdb/current/onlinedocs/gdb/Data.html#Data</a></li>\n<li><a href=\"http://sourceware.org/gdb/current/onlinedocs/gdb/Symbols.html#Symbols\" rel=\"noreferrer\">http://sourceware.org/gdb/current/onlinedocs/gdb/Symbols.html#Symbols</a></li>\n</ul>\n"
},
{
"answer_id": 12884788,
"author": "Peter",
"author_id": 1128151,
"author_profile": "https://Stackoverflow.com/users/1128151",
"pm_score": 3,
"selected": false,
"text": "<p>What I've found is that if you disassemble a function that uses the incomplete struct type gdb 'discovers' the struct members and can subsequently display them. For example, say you have a string struct:</p>\n\n<pre><code>struct my_string {\n char * _string,\n int _size\n} ;\n</code></pre>\n\n<p>some functions to create and get the string via pointer:</p>\n\n<pre><code>my_string * create_string(const char *) {...}\nconst char * get_string(my_string *){...}\n</code></pre>\n\n<p>and a test that creates a string:</p>\n\n<pre><code>int main(int argc, char *argv[]) {\n my_string *str = create_string(\"Hello World!\") ;\n printf(\"String value: %s\\n\", get_string(str)) ;\n ...\n}\n</code></pre>\n\n<p>Run it in gdb and try to 'print *str' and you'll get an 'incomplete type' response. However, try 'disassemble get_string' and then 'print *str' and it'll display the struct and values properly. I have no idea why this works, but it does.</p>\n"
},
{
"answer_id": 36620946,
"author": "isilpekel",
"author_id": 1031224,
"author_profile": "https://Stackoverflow.com/users/1031224",
"pm_score": 0,
"selected": false,
"text": "<p>I had the same problem. If you load the symbols from your libraries manually:</p>\n\n<pre><code>set auto-solib-add off\nattach thread_id\nshared any_lib\nshared another_lib\n</code></pre>\n\n<p>You need to load the symbols from the library, where this object is declared, with the same command as well.</p>\n"
},
{
"answer_id": 41131314,
"author": "memerson",
"author_id": 7293188,
"author_profile": "https://Stackoverflow.com/users/7293188",
"pm_score": 0,
"selected": false,
"text": "<p>I don't know the full meaning of the error, but as Peter notes, disassembly of a related method does something that makes some of these type definitions available.</p>\n\n<p>My example:</p>\n\n<p>In the .h for a class, that class included a forward declaration of an inner helper class so that the outer class could contain a pointer to it. The corresponding .cpp had the full inner helper class definition.</p>\n\n<p>On breaking in a method of the outer class, gdb reported incomplete type for a dereference of the pointer to the inner class instance through an instance of the outer class.</p>\n\n<p>Issuing the disasemble command on one of the methods in the outer class allowed gdb to understand the structure of the inner class using the same pointer that previously failed.</p>\n"
},
{
"answer_id": 56313562,
"author": "I. Yegor",
"author_id": 4911986,
"author_profile": "https://Stackoverflow.com/users/4911986",
"pm_score": 2,
"selected": false,
"text": "<p>Disclaimer: I'm a Python developer with only some minimum knowledge of C++ and how Linux OS functions, so what I describe below is just my solution to a problem I personally experienced.</p>\n\n<h1>If you trying to work with types coming from 3rd party libraries, make sure those libraries aren't missing debug info.</h1>\n\n<h3>Example</h3>\n\n<pre><code>(gdb) info share Qt\nFrom To Syms Read Shared Object Library\n0x00007ffff5336080 0x00007ffff56ba585 Yes (*) /usr/lib/x86_64-linux-gnu/libQt5Widgets.so.5\n0x00007ffff4ad3510 0x00007ffff4ef0cbe Yes (*) /usr/lib/x86_64-linux-gnu/libQt5Gui.so.5\n0x00007ffff47829c0 0x00007ffff47e1ba1 Yes (*) /usr/lib/x86_64-linux-gnu/libQt5DBus.so.5\n0x00007ffff40bb5e0 0x00007ffff439dd92 Yes (*) /usr/lib/x86_64-linux-gnu/libQt5Core.so.5\n0x00007ffff2e581e0 0x00007ffff2e78e4f Yes (*) /usr/lib/x86_64-linux-gnu/libQt5Xml.so.5\n0x00007ffff28c8a00 0x00007ffff29d9999 Yes (*) /usr/lib/x86_64-linux-gnu/libQt5Network.so.5\n0x00007ffff2251750 0x00007ffff2252a46 Yes (*) /usr/lib/x86_64-linux-gnu/libQt5X11Extras.so.5\n0x00007ffff1cc9f80 0x00007ffff1cfc861 Yes (*) /usr/lib/x86_64-linux-gnu/libQt5PrintSupport.so.5\n0x00007fffee269c10 0x00007fffee297b57 Yes (*) /usr/lib/x86_64-linux-gnu/libQt5Svg.so.5\n0x00007fffed987560 0x00007fffed98b6a8 Yes (*) /usr/lib/x86_64-linux-gnu/libQt5TextToSpeech.so.5\n0x00007fffe980e130 0x00007fffe9900c0c Yes (*) /usr/lib/x86_64-linux-gnu/libQt5XcbQpa.so.5\n0x00007fffe69ef650 0x00007fffe69ffe0d Yes (*) /usr/lib/x86_64-linux-gnu/libQt5QuickControls2.so.5\n0x00007fffe5c0f890 0x00007fffe5eae1c1 Yes (*) /usr/lib/x86_64-linux-gnu/libQt5Quick.so.5\n0x00007fffe5522690 0x00007fffe581f636 Yes (*) /usr/lib/x86_64-linux-gnu/libQt5Qml.so.5\n0x00007fffe51996b0 0x00007fffe5221363 Yes (*) /usr/lib/x86_64-linux-gnu/libQt5QuickTemplates2.so.5\n(*): Shared library is missing debugging information.\n</code></pre>\n\n<p>^ all Qt libraries in current example are missing debug info. This is because debug info for qt libs are coming in separate packages, which are not being installed.</p>\n\n<p>Whenever I did <code>whatis</code> everything worked fine:</p>\n\n<pre><code>(gdb) whatis e\ntype = QEvent *\n</code></pre>\n\n<p>but when I tried to access it's members</p>\n\n<pre><code>(gdb) p e->type()\nCouldn't find method QEvent::type\n</code></pre>\n\n<p>and trying to get detailed type description</p>\n\n<pre><code>(gdb) ptype e\ntype = class QEvent {\n <incomplete type>\n} *\n</code></pre>\n\n<h3>Solution (for Qt on Ubuntu)</h3>\n\n<ol>\n<li>Find to which package within your OS distribution does the file belongs</li>\n</ol>\n\n<pre><code>$ dpkg -S /usr/lib/x86_64-linux-gnu/libQt5Core.so.5\nlibqt5core5a:amd64: /usr/lib/x86_64-linux-gnu/libQt5Core.so.5\n</code></pre>\n\n<ol start=\"2\">\n<li><p>Search for related packages</p>\n\n<p>Search with keywork <code>libqt5core5a</code> returned 2 packages, one is <code>libqt5core5a</code> itself, and another is <code>libqt5core5a-dbgsym</code>. Description for the latter says: \"debug symbols for libqt5core5a\"</p></li>\n<li><p>Install packages with debug symbols (I also installed debug symbols for some other essential Qt libraries)</p></li>\n</ol>\n\n<pre><code>$ sudo apt install libqt5core5a-dbgsym libqt5widgets5-dbgsym libqt5gui5-dbgsym\n</code></pre>\n\n<ol start=\"4\">\n<li>Make sure in <code>gdb</code> that libraries now have debug info</li>\n</ol>\n\n<pre><code>(gdb) info share Qt\nFrom To Syms Read Shared Object Library\n0x00007ffff5336080 0x00007ffff56ba585 Yes /usr/lib/x86_64-linux-gnu/libQt5Widgets.so.5\n0x00007ffff4ad3510 0x00007ffff4ef0cbe Yes /usr/lib/x86_64-linux-gnu/libQt5Gui.so.5\n0x00007ffff47829c0 0x00007ffff47e1ba1 Yes (*) /usr/lib/x86_64-linux-gnu/libQt5DBus.so.5\n0x00007ffff40bb5e0 0x00007ffff439dd92 Yes /usr/lib/x86_64-linux-gnu/libQt5Core.so.5\n0x00007ffff2e571e0 0x00007ffff2e77e4f Yes (*) /usr/lib/x86_64-linux-gnu/libQt5Xml.so.5\n0x00007ffff28c7a00 0x00007ffff29d8999 Yes (*) /usr/lib/x86_64-linux-gnu/libQt5Network.so.5\n0x00007ffff2250750 0x00007ffff2251a46 Yes (*) /usr/lib/x86_64-linux-gnu/libQt5X11Extras.so.5\n0x00007ffff1cc8f80 0x00007ffff1cfb861 Yes (*) /usr/lib/x86_64-linux-gnu/libQt5PrintSupport.so.5\n0x00007fffee268c10 0x00007fffee296b57 Yes (*) /usr/lib/x86_64-linux-gnu/libQt5Svg.so.5\n0x00007fffed985560 0x00007fffed9896a8 Yes (*) /usr/lib/x86_64-linux-gnu/libQt5TextToSpeech.so.5\n0x00007fffe95fc130 0x00007fffe96eec0c Yes (*) /usr/lib/x86_64-linux-gnu/libQt5XcbQpa.so.5\n0x00007fffe701f650 0x00007fffe702fe0d Yes (*) /usr/lib/x86_64-linux-gnu/libQt5QuickControls2.so.5\n0x00007fffe623c890 0x00007fffe64db1c1 Yes (*) /usr/lib/x86_64-linux-gnu/libQt5Quick.so.5\n0x00007fffe5b4f690 0x00007fffe5e4c636 Yes (*) /usr/lib/x86_64-linux-gnu/libQt5Qml.so.5\n0x00007fffe57c66b0 0x00007fffe584e363 Yes (*) /usr/lib/x86_64-linux-gnu/libQt5QuickTemplates2.so.5\n(*): Shared library is missing debugging information.\n</code></pre>\n\n<ol start=\"5\">\n<li>Now working with Qt types works as expected</li>\n</ol>\n\n<pre><code>(gdb) p e->type()\n$4 = QEvent::Paint\n(gdb) ptype e\ntype = class QEvent {\n public:\n...\n}\n</code></pre>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/232744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1692070/"
] |
Sometimes gdb prints "incomplete type" for some type of variables. What does this mean and how can we see that value?
|
It means that the type of that variable has been incompletely specified. For example:
```
struct hatstand;
struct hatstand *foo;
```
GDB knows that `foo` is a pointer to a `hatstand` structure, but the members of that structure haven't been defined. Hence, "incomplete type".
To print the value, you can cast it to a compatible type.
For example, if you know that `foo` is really a pointer to a `lampshade` structure:
```
print (struct lampshade *)foo
```
Or, you could print it as a generic pointer, or treat it as if it were an integer:
```
print (void *)foo
print (int)foo
```
See also these pages from the GDB manual:
* <http://sourceware.org/gdb/current/onlinedocs/gdb/Data.html#Data>
* <http://sourceware.org/gdb/current/onlinedocs/gdb/Symbols.html#Symbols>
|
232,747 |
<p>I'm trying to read variables from a batch file for later use in the batch script, which is a Java launcher. I'd ideally like to have the same format for the settings file on all platforms (Unix, Windows), and also be a valid Java Properties file. That is, it should look like this:</p>
<pre><code>setting1=Value1
setting2=Value2
...
</code></pre>
<p>Is it possible to read such values like you would in a Unix shell script? The could should look something like this:</p>
<pre><code>READ settingsfile.xy
java -Dsetting1=%setting1% ...
</code></pre>
<p>I know that this is probably possible with <code>SET setting1=Value1</code>, but I'd really rather have the same file format for the settings on all platforms.</p>
<p>To clarify: I need to do this in the command line/batch environment as I also need to set parameters that cannot be altered from within the JVM, like -Xmx or -classpath.</p>
|
[
{
"answer_id": 232788,
"author": "call me Steve",
"author_id": 24334,
"author_profile": "https://Stackoverflow.com/users/24334",
"pm_score": 2,
"selected": false,
"text": "<p>You can pass the property file as a parameter to a Java program (that may launch the main program later on). And then benefit from the multi platform paradigm.</p>\n"
},
{
"answer_id": 232813,
"author": "Joe",
"author_id": 13087,
"author_profile": "https://Stackoverflow.com/users/13087",
"pm_score": 6,
"selected": true,
"text": "<p>You can do this in a batch file as follows:</p>\n\n<pre><code>setlocal\nFOR /F \"tokens=*\" %%i in ('type Settings.txt') do SET %%i\njava -Dsetting1=%setting1% ...\nendlocal\n</code></pre>\n\n<p>This reads a text file containing strings like \"SETTING1=VALUE1\" and calls SET to set them as environment variables.</p>\n\n<p>setlocal/endlocal are used to limit the scope of the environment variables to the execution of your batch file.</p>\n\n<p>The CMD Command Processor is actually quite powerful, though with a rather byzantine syntax.</p>\n"
},
{
"answer_id": 235538,
"author": "micro",
"author_id": 23275,
"author_profile": "https://Stackoverflow.com/users/23275",
"pm_score": 0,
"selected": false,
"text": "<p>You can also access the OS' environment variables from within a Java program:</p>\n\n<pre><code>import java.util.Map;\n\npublic class EnvMap {\n public static void main (String[] args) {\n Map<String, String> env = System.getenv();\n for (String envName : env.keySet()) {\n System.out.format(\"%s=%s%n\", envName, env.get(envName));\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 6204481,
"author": "Jared",
"author_id": 745412,
"author_profile": "https://Stackoverflow.com/users/745412",
"pm_score": 1,
"selected": false,
"text": "<p>It may be wise to only import specific variables from a properties file (ones you know about ahead of time), in that case I recommend a function like the following:</p>\n\n<pre><code>:parsePropertiesFile\n set PROPS_FILE=%1\n shift\n :propLoop\n if \"%1\"==\"\" goto:eof\n FOR /F \"tokens=*\" %%i in ('type %PROPS_FILE% ^| findStr.exe \"%1=\"') do SET %%i\n shift\n GOTO propLoop\ngoto:eof\n</code></pre>\n\n<p>Which would be called by <code>call:parsePropertiesFile props.properties setting1 setting2</code> to set the variables setting1 and setting2</p>\n"
},
{
"answer_id": 70467042,
"author": "Eboubaker",
"author_id": 10387008,
"author_profile": "https://Stackoverflow.com/users/10387008",
"pm_score": 0,
"selected": false,
"text": "<h3>This will do the following:</h3>\n<ul>\n<li>Skips all lines that start with <code>#</code> (can be used for comments)</li>\n<li>Reads the file <code>.env</code> which sits in the same directory of the batch script and pass the lines to <code>SET</code></li>\n</ul>\n<h3>The script</h3>\n<pre><code>FOR /F "eol=# tokens=*" %%i IN (%~dp0.env) DO SET %%i\n</code></pre>\n<blockquote>\n<p>If you want to read a variable as a number then prepend the variable line in your .env file with <code>/A</code> flag<br>ie: <code>/A PORT=1215</code></p>\n</blockquote>\n<p><strong>To be more helpful This is the .env file i was parsing</strong></p>\n<pre class=\"lang-hs prettyprint-override\"><code># The name of the mariadb service to be installed\nMariaDb_serviceName=Swoole_MariaDB\n# which port the mariadb server will run at\n# notice i added /A flag so that the SET command stores the variable as a number\n/A MariaDb_port=1214\n# password of mariadb root user\nMariaDb_rootPassword=\n# Database to be created after installing mariadb\nMariaDb_createDataBase=data\n# the server service name to be installed\nServer_serviceName=Swoole_Server\n</code></pre>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/232747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22227/"
] |
I'm trying to read variables from a batch file for later use in the batch script, which is a Java launcher. I'd ideally like to have the same format for the settings file on all platforms (Unix, Windows), and also be a valid Java Properties file. That is, it should look like this:
```
setting1=Value1
setting2=Value2
...
```
Is it possible to read such values like you would in a Unix shell script? The could should look something like this:
```
READ settingsfile.xy
java -Dsetting1=%setting1% ...
```
I know that this is probably possible with `SET setting1=Value1`, but I'd really rather have the same file format for the settings on all platforms.
To clarify: I need to do this in the command line/batch environment as I also need to set parameters that cannot be altered from within the JVM, like -Xmx or -classpath.
|
You can do this in a batch file as follows:
```
setlocal
FOR /F "tokens=*" %%i in ('type Settings.txt') do SET %%i
java -Dsetting1=%setting1% ...
endlocal
```
This reads a text file containing strings like "SETTING1=VALUE1" and calls SET to set them as environment variables.
setlocal/endlocal are used to limit the scope of the environment variables to the execution of your batch file.
The CMD Command Processor is actually quite powerful, though with a rather byzantine syntax.
|
232,781 |
<p>can anybody show me how to build a string using checkbox. what would be the best way to do this.</p>
<p>for example i have 4 checkbox's each with its own value (valueA, valueB, valueC, valueD)
the thing is i want to display each result in different lines.</p>
<p>result if B & C is selected : </p>
<p>valueB <br>
valueC </p>
<p>and how would i display this again if i saved this into a database?</p>
|
[
{
"answer_id": 232801,
"author": "Unsliced",
"author_id": 2902,
"author_profile": "https://Stackoverflow.com/users/2902",
"pm_score": 0,
"selected": false,
"text": "<pre><code>\"if I saved this into a database\" ? \n</code></pre>\n\n<p>You'll need to be a bit more specific with your homework assignments if you're actually going to receive any help here ... </p>\n\n<p><strong>Edit:</strong> ok, it <em>might</em> not be homework but it certainly read like it - after all, manipulating a GUI to generate a view of the user's choices is Interfaces 101 - and even it wasn't it was a terrible question without enough detail to have any chance of getting a decent answer. </p>\n"
},
{
"answer_id": 232803,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": true,
"text": "<p>Use a StringBuilder to build the string, and append Environment.NewLine each time you append:</p>\n\n<pre><code>StringBuilder builder = new StringBuilder();\nforeach (CheckBox cb in checkboxes)\n{\n if (cb.Checked)\n {\n builder.AppendLine(cb.Text); // Or whatever\n\n // Alternatively:\n // builder.Append(cb.Text);\n // builder.Append(Environment.NewLine); // Or a different line ending\n }\n}\n// Call Trim if you want to remove the trailing newline\nstring result = builder.ToString();\n</code></pre>\n\n<p>To display it again, you'd have to split the string into lines, and check each checkbox to see whether its value is in the collection.</p>\n"
},
{
"answer_id": 232804,
"author": "Unsliced",
"author_id": 2902,
"author_profile": "https://Stackoverflow.com/users/2902",
"pm_score": 2,
"selected": false,
"text": "<p>Pseudo-code: </p>\n\n<pre><code>For each checkbox in the target list of controls\n append value and a newline character to a temporary string variable\noutput temporary string \n</code></pre>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/232781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23491/"
] |
can anybody show me how to build a string using checkbox. what would be the best way to do this.
for example i have 4 checkbox's each with its own value (valueA, valueB, valueC, valueD)
the thing is i want to display each result in different lines.
result if B & C is selected :
valueB
valueC
and how would i display this again if i saved this into a database?
|
Use a StringBuilder to build the string, and append Environment.NewLine each time you append:
```
StringBuilder builder = new StringBuilder();
foreach (CheckBox cb in checkboxes)
{
if (cb.Checked)
{
builder.AppendLine(cb.Text); // Or whatever
// Alternatively:
// builder.Append(cb.Text);
// builder.Append(Environment.NewLine); // Or a different line ending
}
}
// Call Trim if you want to remove the trailing newline
string result = builder.ToString();
```
To display it again, you'd have to split the string into lines, and check each checkbox to see whether its value is in the collection.
|
232,848 |
<p>I'm writing code like this, doing a little quick and dirty timing:</p>
<pre><code>var sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 1000; i++)
{
b = DoStuff(s);
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);
</code></pre>
<p>Surely there's a way to call this bit of timing code as a fancy-schmancy .NET 3.0 lambda rather than (God forbid) cutting and pasting it a few times and replacing the <strong><code>DoStuff(s)</code></strong> with <strong><code>DoSomethingElse(s)</code></strong>?</p>
<p>I know it can be done as a <code>Delegate</code> but I'm wondering about the lambda way.</p>
|
[
{
"answer_id": 232852,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 4,
"selected": false,
"text": "<p>You could try writing an extension method for whatever class you're using (or any base class).</p>\n\n<p>I would have the call look like:</p>\n\n<pre><code>Stopwatch sw = MyObject.TimedFor(1000, () => DoStuff(s));\n</code></pre>\n\n<p>Then the extension method: </p>\n\n<pre><code>public static Stopwatch TimedFor(this DependencyObject source, Int32 loops, Action action)\n{\nvar sw = new Stopwatch();\nsw.Start();\nfor (int i = 0; i < loops; ++i)\n{\n action.Invoke();\n}\nsw.Stop();\n\nreturn sw;\n}\n</code></pre>\n\n<p>Any object deriving from DependencyObject can now call TimedFor(..). The function can easily be adjusted to provide return values via ref params.</p>\n\n<p>--</p>\n\n<p>If you didn't want the functionality to be tied to any class / object you could do something like:</p>\n\n<pre><code>public class Timing\n{\n public static Stopwatch TimedFor(Action action, Int32 loops)\n {\n var sw = new Stopwatch();\n sw.Start();\n for (int i = 0; i < loops; ++i)\n {\n action.Invoke();\n }\n sw.Stop();\n\n return sw;\n }\n}\n</code></pre>\n\n<p>Then you could use it like:</p>\n\n<pre><code>Stopwatch sw = Timing.TimedFor(() => DoStuff(s), 1000);\n</code></pre>\n\n<p>Failing that, this answer looks like it has some decent \"generic\" ability:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/232848/wrapping-stopwatch-timing-with-a-delegate-or-lambda#232878\">Wrapping StopWatch timing with a delegate or lambda?</a></p>\n"
},
{
"answer_id": 232870,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 8,
"selected": true,
"text": "<p>How about extending the Stopwatch class?</p>\n\n<pre><code>public static class StopwatchExtensions\n{\n public static long Time(this Stopwatch sw, Action action, int iterations)\n {\n sw.Reset();\n sw.Start(); \n for (int i = 0; i < iterations; i++)\n {\n action();\n }\n sw.Stop();\n\n return sw.ElapsedMilliseconds;\n }\n}\n</code></pre>\n\n<p>Then call it like this:</p>\n\n<pre><code>var s = new Stopwatch();\nConsole.WriteLine(s.Time(() => DoStuff(), 1000));\n</code></pre>\n\n<p>You could add another overload which omits the \"iterations\" parameter and calls this version with some default value (like 1000).</p>\n"
},
{
"answer_id": 232871,
"author": "Morten Christiansen",
"author_id": 4055,
"author_profile": "https://Stackoverflow.com/users/4055",
"pm_score": 2,
"selected": false,
"text": "<p>You can overload a number of methods to cover various cases of parameters you might want to pass to the lambda:</p>\n\n<pre><code>public static Stopwatch MeasureTime<T>(int iterations, Action<T> action, T param)\n{\n var sw = new Stopwatch();\n sw.Start();\n for (int i = 0; i < iterations; i++)\n {\n action.Invoke(param);\n }\n sw.Stop();\n\n return sw;\n}\n\npublic static Stopwatch MeasureTime<T, K>(int iterations, Action<T, K> action, T param1, K param2)\n{\n var sw = new Stopwatch();\n sw.Start();\n for (int i = 0; i < iterations; i++)\n {\n action.Invoke(param1, param2);\n }\n sw.Stop();\n\n return sw;\n}\n</code></pre>\n\n<p>Alternatively, you can use the Func delegate if they must return a value. You can also pass in an array (or more) of parameters if each iteration must use a unique value.</p>\n"
},
{
"answer_id": 232879,
"author": "Mark S. Rasmussen",
"author_id": 12469,
"author_profile": "https://Stackoverflow.com/users/12469",
"pm_score": 3,
"selected": false,
"text": "<p>I wrote a simple CodeProfiler class some time ago that wrapped Stopwatch to easily profile a method using an Action:\n<a href=\"http://www.improve.dk/blog/2008/04/16/profiling-code-the-easy-way\" rel=\"nofollow noreferrer\">http://www.improve.dk/blog/2008/04/16/profiling-code-the-easy-way</a></p>\n\n<p>It'll also easily allow you to profile the code multithreaded. The following example will profile the action lambda with 1-16 threads:</p>\n\n<pre><code>static void Main(string[] args)\n{\n Action action = () =>\n {\n for (int i = 0; i < 10000000; i++)\n Math.Sqrt(i);\n };\n\n for(int i=1; i<=16; i++)\n Console.WriteLine(i + \" thread(s):\\t\" + \n CodeProfiler.ProfileAction(action, 100, i));\n\n Console.Read();\n}\n</code></pre>\n"
},
{
"answer_id": 232946,
"author": "Davy Landman",
"author_id": 11098,
"author_profile": "https://Stackoverflow.com/users/11098",
"pm_score": 1,
"selected": false,
"text": "<p>I like to use the CodeTimer classes from Vance Morrison (one of the performance dudes from .NET).</p>\n\n<p>He made a post on on his blog titled \"<a href=\"http://blogs.msdn.com/vancem/archive/2006/09/21/765648.aspx\" rel=\"nofollow noreferrer\">Measuring managed code quickly and easiliy: CodeTimers</a>\".</p>\n\n<p>It includes cool stuff such as a MultiSampleCodeTimer. It does automatic calculation of the mean and standard deviation and its also very easy to print out your results.</p>\n"
},
{
"answer_id": 233519,
"author": "jyoung",
"author_id": 14841,
"author_profile": "https://Stackoverflow.com/users/14841",
"pm_score": 2,
"selected": false,
"text": "<p>Assuming you just need a quick timing of one thing this is easy to use. </p>\n\n<pre><code> public static class Test {\n public static void Invoke() {\n using( SingleTimer.Start )\n Thread.Sleep( 200 );\n Console.WriteLine( SingleTimer.Elapsed );\n\n using( SingleTimer.Start ) {\n Thread.Sleep( 300 );\n }\n Console.WriteLine( SingleTimer.Elapsed );\n }\n}\n\npublic class SingleTimer :IDisposable {\n private Stopwatch stopwatch = new Stopwatch();\n\n public static readonly SingleTimer timer = new SingleTimer();\n public static SingleTimer Start {\n get {\n timer.stopwatch.Reset();\n timer.stopwatch.Start();\n return timer;\n }\n }\n\n public void Stop() {\n stopwatch.Stop();\n }\n public void Dispose() {\n stopwatch.Stop();\n }\n\n public static TimeSpan Elapsed {\n get { return timer.stopwatch.Elapsed; }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 741630,
"author": "Sam Saffron",
"author_id": 17174,
"author_profile": "https://Stackoverflow.com/users/17174",
"pm_score": 2,
"selected": false,
"text": "<p>For me the extension feels a little bit more intuitive on int, you no longer need to instantiate a Stopwatch or worry about resetting it.</p>\n\n<p>So you have: </p>\n\n<pre><code>static class BenchmarkExtension {\n\n public static void Times(this int times, string description, Action action) {\n Stopwatch watch = new Stopwatch();\n watch.Start();\n for (int i = 0; i < times; i++) {\n action();\n }\n watch.Stop();\n Console.WriteLine(\"{0} ... Total time: {1}ms ({2} iterations)\", \n description, \n watch.ElapsedMilliseconds,\n times);\n }\n}\n</code></pre>\n\n<p>With the sample usage of: </p>\n\n<pre><code>var randomStrings = Enumerable.Range(0, 10000)\n .Select(_ => Guid.NewGuid().ToString())\n .ToArray();\n\n50.Times(\"Add 10,000 random strings to a Dictionary\", \n () => {\n var dict = new Dictionary<string, object>();\n foreach (var str in randomStrings) {\n dict.Add(str, null);\n }\n });\n\n50.Times(\"Add 10,000 random strings to a SortedList\",\n () => {\n var list = new SortedList<string, object>();\n foreach (var str in randomStrings) {\n list.Add(str, null);\n }\n });\n</code></pre>\n\n<p>Sample output: </p>\n\n<pre><code>Add 10,000 random strings to a Dictionary ... Total time: 144ms (50 iterations)\nAdd 10,000 random strings to a SortedList ... Total time: 4088ms (50 iterations)\n</code></pre>\n"
},
{
"answer_id": 855624,
"author": "Mauricio Scheffer",
"author_id": 21239,
"author_profile": "https://Stackoverflow.com/users/21239",
"pm_score": 5,
"selected": false,
"text": "<p>Here's what I've been using:</p>\n\n<pre><code>public class DisposableStopwatch: IDisposable {\n private readonly Stopwatch sw;\n private readonly Action<TimeSpan> f;\n\n public DisposableStopwatch(Action<TimeSpan> f) {\n this.f = f;\n sw = Stopwatch.StartNew();\n }\n\n public void Dispose() {\n sw.Stop();\n f(sw.Elapsed);\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>using (new DisposableStopwatch(t => Console.WriteLine(\"{0} elapsed\", t))) {\n // do stuff that I want to measure\n}\n</code></pre>\n"
},
{
"answer_id": 1820942,
"author": "Anthony Mastrean",
"author_id": 3619,
"author_profile": "https://Stackoverflow.com/users/3619",
"pm_score": 3,
"selected": false,
"text": "<p>The <code>StopWatch</code> class does not need to be <code>Disposed</code> or <code>Stopped</code> on error. So, the simplest code to <em>time</em> some <em>action</em> is</p>\n\n<pre><code>public partial class With\n{\n public static long Benchmark(Action action)\n {\n var stopwatch = Stopwatch.StartNew();\n action();\n stopwatch.Stop();\n return stopwatch.ElapsedMilliseconds;\n }\n}\n</code></pre>\n\n<p>Sample calling code</p>\n\n<pre><code>public void Execute(Action action)\n{\n var time = With.Benchmark(action);\n log.DebugFormat(“Did action in {0} ms.”, time);\n}\n</code></pre>\n\n<p>I don't like the idea of including the iterations into the <code>StopWatch</code> code. You can always create another method or extension that handles executing <code>N</code> iterations.</p>\n\n<pre><code>public partial class With\n{\n public static void Iterations(int n, Action action)\n {\n for(int count = 0; count < n; count++)\n action();\n }\n}\n</code></pre>\n\n<p>Sample calling code</p>\n\n<pre><code>public void Execute(Action action, int n)\n{\n var time = With.Benchmark(With.Iterations(n, action));\n log.DebugFormat(“Did action {0} times in {1} ms.”, n, time);\n}\n</code></pre>\n\n<p>Here are the extension method versions</p>\n\n<pre><code>public static class Extensions\n{\n public static long Benchmark(this Action action)\n {\n return With.Benchmark(action);\n }\n\n public static Action Iterations(this Action action, int n)\n {\n return () => With.Iterations(n, action);\n }\n}\n</code></pre>\n\n<p>And sample calling code</p>\n\n<pre><code>public void Execute(Action action, int n)\n{\n var time = action.Iterations(n).Benchmark()\n log.DebugFormat(“Did action {0} times in {1} ms.”, n, time);\n}\n</code></pre>\n\n<p>I tested the static methods and extension methods (combining iterations and benchmark) and the delta of expected execution time and real execution time is <= 1 ms.</p>\n"
},
{
"answer_id": 57419714,
"author": "Alper Ebicoglu",
"author_id": 1767482,
"author_profile": "https://Stackoverflow.com/users/1767482",
"pm_score": 0,
"selected": false,
"text": "<pre><code>public static class StopWatchExtensions\n{\n public static async Task<TimeSpan> LogElapsedMillisecondsAsync(\n this Stopwatch stopwatch,\n ILogger logger,\n string actionName,\n Func<Task> action)\n {\n stopwatch.Reset();\n stopwatch.Start();\n\n await action();\n\n stopwatch.Stop();\n\n logger.LogDebug(string.Format(actionName + \" completed in {0}.\", stopwatch.Elapsed.ToString(\"hh\\\\:mm\\\\:ss\")));\n\n return stopwatch.Elapsed;\n }\n}\n</code></pre>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/232848",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1/"
] |
I'm writing code like this, doing a little quick and dirty timing:
```
var sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 1000; i++)
{
b = DoStuff(s);
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);
```
Surely there's a way to call this bit of timing code as a fancy-schmancy .NET 3.0 lambda rather than (God forbid) cutting and pasting it a few times and replacing the **`DoStuff(s)`** with **`DoSomethingElse(s)`**?
I know it can be done as a `Delegate` but I'm wondering about the lambda way.
|
How about extending the Stopwatch class?
```
public static class StopwatchExtensions
{
public static long Time(this Stopwatch sw, Action action, int iterations)
{
sw.Reset();
sw.Start();
for (int i = 0; i < iterations; i++)
{
action();
}
sw.Stop();
return sw.ElapsedMilliseconds;
}
}
```
Then call it like this:
```
var s = new Stopwatch();
Console.WriteLine(s.Time(() => DoStuff(), 1000));
```
You could add another overload which omits the "iterations" parameter and calls this version with some default value (like 1000).
|
232,861 |
<p>Generate the Fibonacci sequence in the fewest amount of characters possible. Any language is OK, except for one that you define with one operator, <code>f</code>, which prints the Fibonacci numbers.</p>
<p>Starting point: <strong><s>25</s> 14 characters</strong> in <strong>Haskell</strong>:</p>
<p><s> <code>f=0:1:zipWith(+)f(tail f)</code> </s></p>
<pre><code>f=0:scanl(+)1f
</code></pre>
|
[
{
"answer_id": 232943,
"author": "Chris Young",
"author_id": 9417,
"author_profile": "https://Stackoverflow.com/users/9417",
"pm_score": 3,
"selected": false,
"text": "<p>22 characters with dc:</p>\n\n<pre><code>1[pdd5**v1++2/lxx]dsxx\n</code></pre>\n\n<p>Invoke with either:</p>\n\n<pre>\ndc -e'1[pdd5**v1++2/lxx]dsxx'\n</pre>\n\n<p>Or:</p>\n\n<pre>\necho '1[pdd5**v1++2/lxx]dsxx' | dc\n</pre>\n\n<p>Note: not my work, poached from <a href=\"http://www.perlmonks.com/?node_id=626425\" rel=\"nofollow noreferrer\">perlmonks</a>.</p>\n"
},
{
"answer_id": 233161,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 5,
"selected": false,
"text": "<p>13 chars of <a href=\"http://www.golfscript.com/\" rel=\"noreferrer\">Golfscript</a>:</p>\n\n<pre><code>2,~{..p@+.}do\n</code></pre>\n\n<hr>\n\n<p>Update to explain the operation of the script:</p>\n\n<ol>\n<li><code>2,</code> makes an array of <code>[0 1]</code></li>\n<li><code>~</code> puts that array on the stack</li>\n<li>So, at the time we run the <code>do</code>, we start the stack off with <code>0 1</code> (1 at top of stack)</li>\n</ol>\n\n<p>The <code>do</code> loop:</p>\n\n<ol>\n<li>Each <code>.</code> duplicates the top item of the stack; here, we do this twice (leaving us with <code>0 1 1 1</code> on initial run)</li>\n<li><code>p</code> prints the topmost value (leaving us with <code>0 1 1</code>)</li>\n<li><code>@</code> rotates the top 3 items in the stack, so that the third-topmost is at the top (<code>1 1 0</code>)</li>\n<li><code>+</code> adds the top 2 items in the stack (leaving <code>1 1</code>)</li>\n<li><code>.</code> duplicates the top value, so that the <code>do</code> loop can check its truthiness (to determine whether to continue)</li>\n</ol>\n\n<p>Tracing this mentally a couple of loops will be enough to tell you that this does the required addition to generate the Fibonacci sequence values.</p>\n\n<p>Since GolfScript has bignums, there will never be an integer overflow, and so the top-of-stack value at the end of the <code>do</code> loop will never be 0. Thus, the script will run forever.</p>\n"
},
{
"answer_id": 233228,
"author": "Krakkos",
"author_id": 15533,
"author_profile": "https://Stackoverflow.com/users/15533",
"pm_score": 5,
"selected": false,
"text": "<p>18 characters of English..</p>\n\n<p>\"Fibonacci Sequence\"</p>\n\n<p>ok, I fail. :)</p>\n"
},
{
"answer_id": 233342,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 3,
"selected": false,
"text": "<p>For the record:</p>\n\n<ul>\n<li>Lua (66 chars): <code>function f(n)if n<2 then return n else return f(n-1)+f(n-2)end end</code></li>\n<li>JavaScript (41 chars): <code>function f(n){return n<2?n:f(n-1)+f(n-2)}</code></li>\n<li>Java (41 chars): <code>int f(int n){return n<2?n:f(n-1)+f(n-2);}</code></li>\n</ul>\n\n<p>I am not much adept of super concise languages... :-P</p>\n\n<p>Chris is right, I just took the simple, recursive algorithm. Actually, the linear one is even shorter in Lua (thanks to multiple assignment)! JavaScript isn't so lucky and Java is worse, having to declare vars...</p>\n\n<ul>\n<li>Lua (60 chars): <code>function f(n)a=1;b=0;for i=1,n do a,b=b,a+b end return b end</code></li>\n<li>JavaScript (60 chars): <code>function f(n){a=1;b=i=0;for(;i++<n;){x=a+b;a=b;b=x}return b}</code></li>\n<li>Java (71 chars): <code>int f(int n){int a=1,b=0,i=0;for(;i++<n;){int x=a+b;a=b;b=x;}return b;}</code></li>\n</ul>\n\n<p>I would write Lua's code with <code>local a,b=1,0</code> but it is longer, so let's pollute _G! ;-)\nIdem for JS.</p>\n\n<p>For completeness, here are the terminal recursive versions. Lua's one, using tail call, is as fast as the linear one (but 69 chars, it is the longest!) - need to call them with three params, n,1,0.</p>\n\n<ul>\n<li>Lua (69 char, longer!): <code>function f(n,a,b)if n<1 then return b else return f(n-1,b,a+b)end end</code></li>\n<li>JavaScript (44 chars): <code>function f(n,a,b){return n<1?b:f(n-1,b,a+b)}</code></li>\n<li>Java (52 chars): <code>int f(int n,int a,int b){return n<1?b:f(n-1,b,a+b);}</code></li>\n</ul>\n"
},
{
"answer_id": 233471,
"author": "Andrea Ambu",
"author_id": 21384,
"author_profile": "https://Stackoverflow.com/users/21384",
"pm_score": 3,
"selected": false,
"text": "<p>Corrected after comments (thanks Sebastian), it wasn't a sequence solution, so here we go with 42 chars (includes the \\n):</p>\n\n<pre><code>def f(a=0,b=1):\n while 1:yield a;a,b=b,a+b\n</code></pre>\n\n<hr>\n\n<h2>OLD post below</h2>\n\n<p>Python, 38 chars.</p>\n\n<pre><code>f=lambda n:n if n<2 else f(n-1)+f(n-2)\n</code></pre>\n\n<p>Not so short but the most readable in my opinion :P</p>\n\n<p>EDIT:\nHere is the analytic way (if someone needs to see it in python :-)</p>\n\n<pre><code>f=lambda n:int(.5+(.5+5**.5/2)**n/5**.5)\n</code></pre>\n"
},
{
"answer_id": 233568,
"author": "mpeters",
"author_id": 12094,
"author_profile": "https://Stackoverflow.com/users/12094",
"pm_score": 4,
"selected": false,
"text": "<p>Perl 6 - 22 characters:</p>\n\n<pre><code>sub f{1,1...{$^a+$^b}}\n</code></pre>\n"
},
{
"answer_id": 233889,
"author": "mstrobl",
"author_id": 25965,
"author_profile": "https://Stackoverflow.com/users/25965",
"pm_score": 1,
"selected": false,
"text": "<p>Not the shortest, but the fastest at the time of posting. :-)</p>\n\n<pre><code>float f(float n) {\n return (pow(1+sqrt(5.0))/2.0),n) - pow(1+sqrt(5.0))/2.0),n)/sqrt(n));\n}\n</code></pre>\n"
},
{
"answer_id": 234690,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://www.jsoftware.com/\" rel=\"noreferrer\">J</a>, 27 characters for a non-recursive function:</p>\n\n<pre><code>f=:3 :'{:}.@(,+/)^:y(0 1x)'\n</code></pre>\n\n<p><code>+/</code> sums over a list.<br>\n<code>(,+/)</code> appends the sum of a list to its tail.<br>\n<code>}.@(,+/)</code> sums a list, appends an element to its tail, and drops the first element.<br>\n<code>}.@(,+/)^:y</code> iterates the above function <code>y</code> times.<br>\n<code>}.@(,+/)^:y(0 1x)</code> applies the above function to the list <code>(0,1)</code> (the <code>x</code> makes it an integer).<br>\n<code>{:}.@(,+/)^:y(0 1x)</code> takes the last element of the output list of the above.<br>\n<code>f=:3 :'{:}.@(,+/)^:y(0 1x)'</code> defines <code>f</code> to be a function on one variable <code>y</code>.</p>\n"
},
{
"answer_id": 234747,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 1,
"selected": false,
"text": "<p>33 characters in C:</p>\n\n<pre><code>F(n){return n<2?n:F(n-1)+F(n-2);}</code></pre>\n"
},
{
"answer_id": 234767,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Generate the Fibonacci sequence.\nsequence\nSEQUENCE!</p>\n"
},
{
"answer_id": 249970,
"author": "Firas Assaad",
"author_id": 23153,
"author_profile": "https://Stackoverflow.com/users/23153",
"pm_score": 2,
"selected": false,
"text": "<p>Ruby (30 characters):</p>\n\n<pre><code>def f(n)n<2?n:f(n-1)+f(n-2)end\n</code></pre>\n"
},
{
"answer_id": 250041,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 2,
"selected": false,
"text": "<p>@Andrea Ambu</p>\n\n<p>An iterative pythonic <code>fibonacci()</code>'s version should look something like that:</p>\n\n<pre><code>def fibonacci(a=0, b=1):\n while True:\n yield b\n a, b = b, a+b\n</code></pre>\n"
},
{
"answer_id": 250202,
"author": "Paulius",
"author_id": 1353085,
"author_profile": "https://Stackoverflow.com/users/1353085",
"pm_score": 3,
"selected": false,
"text": "<p>Windows XP (and later versions) batch script. This batch function when given a single argument - amount, generates amount+1 Fibonacci numbers and returns them as a string (BATCH doesn't really have sets) in variable %r% (369 characters, or 347 characters - if we remove indentation):</p>\n\n<pre><code>:f\n set i=0\n set r=1\n set n=1\n set f=0\n :l\n if %n% GTR %~1 goto e\n set f=%f% %r%\n set /A s=%i%+%r%\n set i=%r%\n set r=%s%\n set /A n+=1\n goto l\n :e\n set r=%f%\n exit /B 0\n</code></pre>\n\n<p>And here's the complete script, to see it in action (just copy-past it into a CMD or BAT file and run it):</p>\n\n<pre><code>@echo off\ncall :ff 0\ncall :ff 1\ncall :ff 2\ncall :ff 3\ncall :ff 5\ncall :ff 10\ncall :ff 15\ncall :ff 20\nexit /B 0\n\n:ff\n call :f \"%~1\"\n echo %~1: %r%\n exit /B 0\n\n:f\n set i=0\n set r=1\n set n=1\n set f=0\n :l\n if %n% GTR %~1 goto e\n set f=%f% %r%\n set /A s=%i%+%r%\n set i=%r%\n set r=%s%\n set /A n+=1\n goto l\n :e\n set r=%f%\n exit /B 0\n</code></pre>\n"
},
{
"answer_id": 270470,
"author": "Steve",
"author_id": 22712,
"author_profile": "https://Stackoverflow.com/users/22712",
"pm_score": 1,
"selected": false,
"text": "<p>Delphi Prism (Delphi for .net)</p>\n\n<pre><code>f:func<int32,int32>:=n->iif(n>1,f(n-1)+f(n-2),n)\n</code></pre>\n\n<p>49 chars</p>\n"
},
{
"answer_id": 332302,
"author": "Lex",
"author_id": 28994,
"author_profile": "https://Stackoverflow.com/users/28994",
"pm_score": 1,
"selected": false,
"text": "<p>The previous Ruby example won't work w/o either semicolons or newlines, so it's actually 32 chars. Here's the first example to actually output the sequence, not just return the value of a specified index.</p>\n\n<p>Ruby:<br />\n53 chars, including newlines:</p>\n\n<pre><code>def f(n);n<2?1:f(n-1)+f(n-2);end\n0.upto 20 {|n|p f n}\n</code></pre>\n\n<p>or if you want function that outputs a usable data structure, 71 chars:</p>\n\n<pre><code>def f(n);n<2?1:f(n-1)+f(n-2);end\ndef s(n);(0..n).to_a.map {|n| f(n)};end\n</code></pre>\n\n<p>or accepting command-line args, 70 chars:</p>\n\n<pre><code>def f(n);n<2?1:f(n-1)+f(n-2);end\np (0..$*[0].to_i).to_a.map {|n| f(n)}\n</code></pre>\n"
},
{
"answer_id": 396990,
"author": "Hynek -Pichi- Vychodil",
"author_id": 49197,
"author_profile": "https://Stackoverflow.com/users/49197",
"pm_score": 3,
"selected": false,
"text": "<h3>Language: dc, Char count: 20</h3>\n\n<p>Shorter dc solution.</p>\n\n<pre><code>dc -e'1df[dsa+plarlbx]dsbx'\n</code></pre>\n"
},
{
"answer_id": 411894,
"author": "BenAlabaster",
"author_id": 40650,
"author_profile": "https://Stackoverflow.com/users/40650",
"pm_score": 2,
"selected": false,
"text": "<p><strong>C#</strong></p>\n\n<p>I'm seeing a lot of answers that don't actually generate the sequence, but instead give you only the fibonacci number at position *n using recursion, which when looped to generate the sequence gets increasingly slower at higher values of <em>n</em>.</p>\n\n<pre><code>using System;\nstatic void Main()\n{\n var x = Math.Sqrt(5);\n for (int n = 0; n < 10; n++)\n Console.WriteLine((Math.Pow((1 + x) / 2, n) - Math.Pow((1 - x) / 2, n)) / p) ;\n}\n</code></pre>\n"
},
{
"answer_id": 412040,
"author": "Henk",
"author_id": 44427,
"author_profile": "https://Stackoverflow.com/users/44427",
"pm_score": 3,
"selected": false,
"text": "<p>Here's my best using scheme, in 45 characters:</p>\n\n<pre><code>(let f((a 0)(b 1))(printf\"~a,\"b)(f b(+ a b)))\n</code></pre>\n"
},
{
"answer_id": 412152,
"author": "Eclipse",
"author_id": 8701,
"author_profile": "https://Stackoverflow.com/users/8701",
"pm_score": 4,
"selected": false,
"text": "<p>Language: C++ Compiler Errors<br>\nCharacters: 205</p>\n\n<pre><code>#define t template <int n> struct \n#define u template <> struct f\nt g { int v[0]; };\nt f { enum { v = f<n-1>::v + f<n-2>::v }; g<v> x;};\nu<1> { enum { v = 1 }; };\nu<0> { enum { v = 0 }; };\nint main() { f<10> x; }\n</code></pre>\n"
},
{
"answer_id": 537083,
"author": "leen",
"author_id": 26462,
"author_profile": "https://Stackoverflow.com/users/26462",
"pm_score": 3,
"selected": false,
"text": "<p>F#:</p>\n\n<pre><code>(0,1)|>Seq.unfold(fun(a,b)->Some(a,(b,a+b)))\n</code></pre>\n\n<p>44 Chars</p>\n"
},
{
"answer_id": 1057022,
"author": "Francois G",
"author_id": 47978,
"author_profile": "https://Stackoverflow.com/users/47978",
"pm_score": 2,
"selected": false,
"text": "<pre><code>let rec f l a b =function 0->a::l|1->b::l|n->f (a::l) b (a+b) (n-1) in f [] 1 1;;\n</code></pre>\n\n<p>80 characters, but truly generates the sequence, in linear time.</p>\n"
},
{
"answer_id": 1396539,
"author": "Matt Lewis",
"author_id": 28987,
"author_profile": "https://Stackoverflow.com/users/28987",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Euphoria: 44 characters</strong></p>\n\n<pre><code>object f=1&1 loop do f&=f[$]+f[$-1]until 0\n</code></pre>\n\n<p>Keeps on generating until RAM or doubles run out.</p>\n"
},
{
"answer_id": 1396574,
"author": "Nican",
"author_id": 99966,
"author_profile": "https://Stackoverflow.com/users/99966",
"pm_score": 2,
"selected": false,
"text": "<p>Lua - 49 chars</p>\n\n<pre><code>function f(n)return n<2 and n or f(n-1)+f(n-2)end\n</code></pre>\n"
},
{
"answer_id": 1396763,
"author": "I. J. Kennedy",
"author_id": 8677,
"author_profile": "https://Stackoverflow.com/users/8677",
"pm_score": 4,
"selected": false,
"text": "<p>x86 (C-callable) realmode, 14 bytes.<br />\nInput is n on stack, returns F<sub>n</sub> in AX.</p>\n\n<pre><code>59 31 C0 E3 08 89 C3 40 93 01 D8 E2 FB C3\n</code></pre>\n"
},
{
"answer_id": 1396828,
"author": "Chris Dodd",
"author_id": 29759,
"author_profile": "https://Stackoverflow.com/users/29759",
"pm_score": 0,
"selected": false,
"text": "<p>Lucid</p>\n\n<pre><code>f = 1 fby 1 fby f + prev f;\n</code></pre>\n\n<p>27 characters, including the spaces.</p>\n"
},
{
"answer_id": 1400219,
"author": "Hellion",
"author_id": 163109,
"author_profile": "https://Stackoverflow.com/users/163109",
"pm_score": 0,
"selected": false,
"text": "<p>Rexx:</p>\n\n<p>arg n;a=1;b=1;do i=1 to n;say a b;a=a+b;b=a+b;end</p>\n"
},
{
"answer_id": 1548888,
"author": "Mark Rushakoff",
"author_id": 126042,
"author_profile": "https://Stackoverflow.com/users/126042",
"pm_score": 2,
"selected": false,
"text": "<h1><a href=\"http://en.wikipedia.org/wiki/Befunge\" rel=\"nofollow noreferrer\">Befunge-93</a></h1>\n<h2>31 chars</h2>\n<p>Will output an infinite list of the Fibonacci numbers, from 0 upwards, separated by tabs (could be reduced to 29 chars by deleting <code>9,</code> in the first row, at the expense of no whitespace between numbers).</p>\n<p>Unfortunately, all the Befunge-93 interpreters I've tried seem to overflow after 65k, so the output is only correct until and including 46368 (which is <strong>F</strong><sub>24</sub>).</p>\n<pre>\n#v::1p1>01g:.\\:01p+9,#\n > ^\n</pre>\n<p>Confirmed to work (with caveat above) with <a href=\"http://www.quirkster.com/js/befunge.html\" rel=\"nofollow noreferrer\">the Befunge-93 interpreter in Javascript</a> and the <a href=\"http://www.ashleymills.com/?q=befunge_applet_full\" rel=\"nofollow noreferrer\">Visual Befunge Applet Full</a>.</p>\n<p>I'm proud to say this is a completely original work (i.e. I did not copy this code from anyone), and it's much shorter than <a href=\"http://rosettacode.org/wiki/Fibonacci_sequence#Befunge\" rel=\"nofollow noreferrer\">the Befunge solution currently on Rosetta Code</a>.</p>\n"
},
{
"answer_id": 2901383,
"author": "Eric Mickelsen",
"author_id": 214146,
"author_profile": "https://Stackoverflow.com/users/214146",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"http://en.wikipedia.org/wiki/Brainfuck\" rel=\"noreferrer\" title=\"Brainfuck\">Brainfuck</a>, 33 characters:</p>\n\n<pre><code>+.>+.[<[>+>+<<-]>.[<+>-]>[<+>-]<]\n</code></pre>\n"
},
{
"answer_id": 3029192,
"author": "Callum Rogers",
"author_id": 139766,
"author_profile": "https://Stackoverflow.com/users/139766",
"pm_score": 6,
"selected": true,
"text": "<h1>RePeNt, <strike>9</strike>, 8 chars</h1>\n\n<pre><code>1↓[2?+1]\n</code></pre>\n\n<p>Or 10 chars with printing:</p>\n\n<pre><code>1↓[2?+↓£1]\n</code></pre>\n\n<p>Run using:</p>\n\n<pre><code>RePeNt \"1↓[2?+1]\"\n</code></pre>\n\n<p>RePeNt is a stack based toy language I wrote (and am still improving) in which all operators/functions/blocks/loops use Reverse Polish Notation (RPN).</p>\n\n<pre><code>Command Explanation Stack\n------- ----------- -----\n\n1 Push a 1 onto the stack 1\n↓ Push last stack value 1 1\n[ Start a do-while loop 1 1\n2? Push a two, then pop the 2 and copy the last 2 stack 1 1 1 1\n items onto the stack\n+ Add on the stack 1 1 2\n↓£ Push last stack value then print it 1 1 2\n1 Push a 1 onto the stack 1 1 2 1\n] Pop value (1 in this case), if it is a 0 exit the loop 1 1 2\n otherwise go back to the loop start.\n</code></pre>\n\n<p>The answer is on the stack which builds itself up like:</p>\n\n<pre><code>1 1\n1 1 2\n1 1 2 3\n1 1 2 3 5\n</code></pre>\n\n<p>It never terminates (it has the eqivilent of a C#/JAVA <code>do { } while(true)</code> loop) because the sequence will never terminate, but a terminating solution can be written thus:</p>\n\n<pre><code>N_1↓nI{2?+}\n</code></pre>\n\n<p>which is 12 chars.</p>\n\n<p>I wonder if anyone will ever read this :(</p>\n"
},
{
"answer_id": 3029228,
"author": "JUST MY correct OPINION",
"author_id": 282658,
"author_profile": "https://Stackoverflow.com/users/282658",
"pm_score": 1,
"selected": false,
"text": "<p>PDP-11 Assembler (<a href=\"http://cubbi.com/fibonacci/asm.html\" rel=\"nofollow noreferrer\">source</a>)</p>\n\n<pre><code> .globl start\n .text\nstart:\n mov $0,(sp)\n mov $27,-(sp)\n jsr pc, lambda\nprint_r1:\n mov $outbyte,r3\ndiv_loop:\n sxt r0\n div $12,r0\n add $60,r1\n movb r1,-(r3)\n mov r0,r1\n tst r1\n jne div_loop\n mov $1,r0\n sys 4; outtext; 37\n mov $1,r0\n sys 1\nlambda:\n mov 2(sp),r1\n cmp $2,r1\n beq gottwo\n bgt gotone\n sxt r0\n div $2,r0\n tst r1\n beq even\nodd:\n mov 2(sp),r1\n dec r1\n sxt r0\n div $2,r0\n mov r0,-(sp)\n jsr pc,lambda\n add $2,sp\n mov r0,r3\n mov r1,r2\n mov r3,r4\n mul r2,r4\n mov r5,r1\n mov r3,r4\n add r2,r4\n mul r2,r4\n add r5,r1\n mul r3,r3\n mov r3,r0\n mul r2,r2\n add r3,r0\n rts pc\neven:\n mov 2(sp),r1\n sxt r0\n div $2,r0\n dec r0\n mov r0,-(sp)\n jsr pc,lambda\n add $2,sp\n mov r0,r3\n mov r1,r2\n mov r2,r4\n mul r2,r4\n mov r5,r1\n mov r2,r4\n add r3,r4\n mul r4,r4\n add r5,r1\n mov r2,r4\n add r3,r4\n mul r2,r4\n mov r5,r0\n mul r2,r3\n add r3,r0\n rts pc\ngotone:\n mov $1,r0\n mov $1,r1\n rts pc\ngottwo:\n mov $1,r0\n mov $2,r1\n rts pc\n\n .data\nouttext:\n .byte 62,63,162,144,40,106,151,142,157,156\n .byte 141,143,143,151,40,156,165,155\n .byte 142,145,162,40,151,163,40\n .byte 60,60,60,60,60\noutbyte:\n .byte 12\n</code></pre>\n"
},
{
"answer_id": 3040636,
"author": "Tom H",
"author_id": 350202,
"author_profile": "https://Stackoverflow.com/users/350202",
"pm_score": 2,
"selected": false,
"text": "<p>BrainF**k:</p>\n\n<pre><code>>+++++>+>+<[[>]<<[>>+>+<<<-]>>>[<<<+>>>-]<<[>+>+<<-]>>[<<+>>-]<[<]>-]\n</code></pre>\n\n<p>That'll generate the first 5. To generate more, replace the 5 + at the beginning with more: eg:</p>\n\n<pre><code>>++++++++++++++++++++++>+>+<[[>]<<[>>+>+<<<-]>>>[<<<+>>>-]<<[>+>+<<-]>>[<<+>>-]<[<]>-]\n</code></pre>\n"
},
{
"answer_id": 3146561,
"author": "st0le",
"author_id": 216517,
"author_profile": "https://Stackoverflow.com/users/216517",
"pm_score": 0,
"selected": false,
"text": "<p>Java Iterative (73)</p>\n\n<pre><code>void f(int n){for(int a=1,b=1;n-->0;b=a+(a=b)){System.out.print(a+\",\");}}\n</code></pre>\n\n<p>Ruby (46)</p>\n\n<pre><code>def f(n);a,b=1,1;1.upto(n){p a;b=a+(a=b);};end\n</code></pre>\n\n<p><strong>Update</strong>: Ruby(42)</p>\n\n<pre><code>def f(n);a=b=1;n.times{p a;b=a+(a=b);};end\n</code></pre>\n"
},
{
"answer_id": 4842173,
"author": "Eelvex",
"author_id": 349708,
"author_profile": "https://Stackoverflow.com/users/349708",
"pm_score": 1,
"selected": false,
"text": "<h3>J - 20 characters</h3>\n\n<p>First <em>n</em> terms:</p>\n\n<pre><code>(+/@(2&{.),])^:n i.2\n</code></pre>\n"
},
{
"answer_id": 4935807,
"author": "BradC",
"author_id": 21398,
"author_profile": "https://Stackoverflow.com/users/21398",
"pm_score": 2,
"selected": false,
"text": "<p>MS Excel: 11 characters:</p>\n\n<pre><code>=SUM(A1:A2)\n</code></pre>\n\n<p>Type <code>1</code> in the top 2 cells, then put the above formula in cell A3. Copy the formula down the spreadsheet.</p>\n\n<p>Starts losing accuracy due to floating point rounding on row 74.<br>\nExceeds 10^307 and overflows to a <code>#NUM!</code> error on row 1477.</p>\n"
},
{
"answer_id": 6639376,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Very old post but</p>\n\n<p><code>f(){int cn=2,*n=calloc(9,9);n[1]=1;while(cn<32)printf(\"%d \",n[cn]=n[cn-1]+n[cn++-2]);}</code>\n85char in C.</p>\n"
},
{
"answer_id": 11119340,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Microsoft Batch - 15 characters</p>\n\n<p>Old challenge, but the world must know it is possible:</p>\n\n<pre><code>%1\n%0 %1%2 %1 #\n</code></pre>\n\n<p>Output is to stderr in unary, counting only the # characters.\nDepending on the host system's space restrictions, it may produce only the first 14 numbers or so.</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/232861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15055/"
] |
Generate the Fibonacci sequence in the fewest amount of characters possible. Any language is OK, except for one that you define with one operator, `f`, which prints the Fibonacci numbers.
Starting point: **~~25~~ 14 characters** in **Haskell**:
~~`f=0:1:zipWith(+)f(tail f)`~~
```
f=0:scanl(+)1f
```
|
RePeNt, 9, 8 chars
==================
```
1↓[2?+1]
```
Or 10 chars with printing:
```
1↓[2?+↓£1]
```
Run using:
```
RePeNt "1↓[2?+1]"
```
RePeNt is a stack based toy language I wrote (and am still improving) in which all operators/functions/blocks/loops use Reverse Polish Notation (RPN).
```
Command Explanation Stack
------- ----------- -----
1 Push a 1 onto the stack 1
↓ Push last stack value 1 1
[ Start a do-while loop 1 1
2? Push a two, then pop the 2 and copy the last 2 stack 1 1 1 1
items onto the stack
+ Add on the stack 1 1 2
↓£ Push last stack value then print it 1 1 2
1 Push a 1 onto the stack 1 1 2 1
] Pop value (1 in this case), if it is a 0 exit the loop 1 1 2
otherwise go back to the loop start.
```
The answer is on the stack which builds itself up like:
```
1 1
1 1 2
1 1 2 3
1 1 2 3 5
```
It never terminates (it has the eqivilent of a C#/JAVA `do { } while(true)` loop) because the sequence will never terminate, but a terminating solution can be written thus:
```
N_1↓nI{2?+}
```
which is 12 chars.
I wonder if anyone will ever read this :(
|
232,869 |
<pre><code><style type="text/css">
body {
font-family:Helvetica, sans-serif;
font-size:12px;
}
p,
h1,
form,
button {
border: 0;
margin: 0;
padding: 0;
}
.spacer {
clear: both;
height: 1px;
}
/* ----------- My Form ----------- */
.myform {
margin: 0 auto;
width: 400px;
padding: 14px;
}
/* ----------- basic ----------- */
#basic {
border: solid 2px #DEDEDE;
}
#basic h1 {
font-size: 14px;
font-weight: bold;
margin-bottom: 8px;
}
#basic p {
font-size: 11px;
color: #666666;
margin-bottom: 20px;
border-bottom: solid 1px #dedede;
padding-bottom: 10px;
}
#basic label {
display: block;
font-weight: bold;
text-align: right;
width: 140px;
float: left;
}
#basic .small{
color:#666666;
display:block;
font-size:11px;
font-weight:normal;
text-align:right;
width:140px;
}
#basic input{
float:left;
width:200px;
margin:2px 0 30px 10px;
}
#basic button{
clear:both;
margin-left:150px;
background:#888888;
color:#FFFFFF;
border:solid 1px #666666;
font-size:11px;
font-weight:bold;
padding:4px 6px;
}
</style>
<div id="basic" class="myform">
<form id="form1" name="form1" method="post" action="">
<h1>Sign-up form</h1>
<p>This is the basic look of my form without table</p>
<label>Name
<span class="small">Add your name</span>
</label>
<input type="text" name="textfield" id="textfield" />
<label>Email
<span class="small">Add a valid address</span>
</label>
<input type="text" name="textfield" id="textfield" />
<label>Email
<span class="small">Add a valid address</span>
</label>
<!-- Problem --->
<input type="radio" name="something" id="r1" class="radio" value="1" /><label for="r1">One</label>
<input type="radio" name="something" id="r2" class="radio" value="2" /><label for="r2">Two</label>
<!-- Problem --->
<button type="submit">Sign-up</button>
<div class="spacer"></div>
</form>
</div>
</code></pre>
<p>I was given this example form, however I cannot add radio buttons without them being messed up.</p>
|
[
{
"answer_id": 232880,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 0,
"selected": false,
"text": "<p>You have them named the same as a text input - change <code>name=\"textfield\"</code> to <code>name=\"my_radio\"</code></p>\n\n<p>You also have no input for the email address, so your labels are out of sync with the inputs</p>\n"
},
{
"answer_id": 232901,
"author": "Wayne Austin",
"author_id": 31109,
"author_profile": "https://Stackoverflow.com/users/31109",
"pm_score": 0,
"selected": false,
"text": "<p>Your style #basic input is giving all your input fields within the form a width of 200px, including your radio buttons, create a new style like #basic input.radio and give the radio buttons an individual width like 20px (make sure you put this after the #basic input style), you will then also have to specify a smaller width for the labels that link with the radio buttons, add a class to them and reduce their width to something like 40px.</p>\n\n<p>Then the radio buttons and their associated labels should line up with each other.</p>\n"
},
{
"answer_id": 232910,
"author": "pilsetnieks",
"author_id": 6615,
"author_profile": "https://Stackoverflow.com/users/6615",
"pm_score": 1,
"selected": false,
"text": "<p>It is permitted, according to the spec, to put the form input elements inside the labels that refer to them, e.g.,</p>\n\n<pre><code><label for=\"input\">Label: <input type=\"radio\" id=\"input\" name=\"input\" /></label>\n</code></pre>\n\n<p>See if that makes styling it all easier. (It should.)</p>\n"
},
{
"answer_id": 232913,
"author": "monkey do",
"author_id": 29951,
"author_profile": "https://Stackoverflow.com/users/29951",
"pm_score": 2,
"selected": false,
"text": "<p>You've got the form inputs all styled the same width (200px) and floating left, this applies to the radio buttons as well.</p>\n\n<p>Something like this should get you heading in the right direction</p>\n\n<pre><code><style type=\"text/css\">\nbody{\n font-family:Helvetica, sans-serif; \n font-size:12px;\n}\np, h1, form, button{border:0; margin:0; padding:0;}\n.spacer{clear:both; height:1px;}\n/* ----------- My Form ----------- */\n.myform{\n margin:0 auto;\n width:400px;\n padding:14px;\n}\n /* ----------- basic ----------- */\n #basic{\n border:solid 2px #DEDEDE;\n }\n #basic h1 {\n font-size:14px;\n font-weight:bold;\n margin-bottom:8px;\n }\n #basic p{\n font-size:11px;\n color:#666666;\n margin-bottom:20px;\n border-bottom:solid 1px #dedede;\n padding-bottom:10px;\n }\n #basic label{\n font-weight:bold;\n text-align:right;\n width:140px;\n float:left;\n }\n #basic .small{\n color:#666666;\n display:block;\n font-size:11px;\n font-weight:normal;\n text-align:right;\n width:140px;\n }\n #basic input{\n float:left;\n width:200px;\n margin:2px 0 30px 10px;\n }\n #basic button{ \n clear:both;\n margin-left:150px;\n background:#888888;\n color:#FFFFFF;\n border:solid 1px #666666;\n font-size:11px;\n font-weight:bold;\n padding:4px 6px;\n }\n #basic input.radio{\n width:50px;\n margin:2px 0 30px 10px;\n }\n #basic label.radio {\n width:40px;\n text-align:left;\n }\n</style>\n\n<div id=\"basic\" class=\"myform\">\n <form id=\"form1\" name=\"form1\" method=\"post\" action=\"\">\n <h1>Sign-up form</h1>\n <p>This is the basic look of my form without table</p>\n <label>Name\n <span class=\"small\">Add your name</span>\n </label>\n <input type=\"text\" name=\"textfield\" id=\"textfield\" />\n\n <label>Email\n <span class=\"small\">Add a valid address</span>\n </label>\n <input type=\"text\" name=\"textfield\" id=\"textfield\" />\n\n <label>Email\n <span class=\"small\">Add a valid address</span>\n </label>\n <!-- Problem --->\n <input type=\"radio\" name=\"r1\" id=\"r1\" class=\"radio\" value=\"1\" /><label class=\"radio\" for=\"r1\">One</label>\n <input type=\"radio\" name=\"r2\" id=\"r2\" class=\"radio\" value=\"2\" /><label class=\"radio\" for=\"r2\">Two</label>\n <!-- Problem --->\n <button type=\"submit\">Sign-up</button>\n <div class=\"spacer\"></div>\n\n\n </form>\n</div>\n</code></pre>\n"
},
{
"answer_id": 232920,
"author": "Wayne Austin",
"author_id": 31109,
"author_profile": "https://Stackoverflow.com/users/31109",
"pm_score": 3,
"selected": true,
"text": "<p>(within the style tags)\nadd these new style rules: </p>\n\n<pre><code>#basic input.radio\n{\n width:20px;\n\n}\n#basic label.radiolabel\n{\n width:40px;\n text-align:left;\n line-height:24px;\n}\n</code></pre>\n\n<p>in your html:</p>\n\n<p>add a new class to each label, like so:</p>\n\n<pre><code><!-- Problem ---> \n<input type=\"radio\" name=\"textfield\" id=\"r1\" class=\"radio\" value=\"1\" />\n<label for=\"r1\" class=\"radiolabel\">One</label> \n<input type=\"radio\" name=\"textfield\" id=\"r2\" class=\"radio\" value=\"2\" />\n<label for=\"r2\" class=\"radiolabel\">Two</label> \n<!-- Problem --->\n</code></pre>\n\n<p>edit:added line-height to the label's styling :)</p>\n"
},
{
"answer_id": 232965,
"author": "philistyne",
"author_id": 16597,
"author_profile": "https://Stackoverflow.com/users/16597",
"pm_score": 0,
"selected": false,
"text": "<p>To fix your layout issue add the following CSS:</p>\n\n<pre><code>#basic input.radio { width:20px; }\n</code></pre>\n\n<p>This would fix the radio buttons' massive width - they were getting their width from the</p>\n\n<pre><code>#basic input { width:200px;}\n</code></pre>\n\n<p>was making ALL inputs 200px wide.</p>\n\n<p>Overall, your application of IDs and classes is not really promoting reuse, but that's another issue.</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/232869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21559/"
] |
```
<style type="text/css">
body {
font-family:Helvetica, sans-serif;
font-size:12px;
}
p,
h1,
form,
button {
border: 0;
margin: 0;
padding: 0;
}
.spacer {
clear: both;
height: 1px;
}
/* ----------- My Form ----------- */
.myform {
margin: 0 auto;
width: 400px;
padding: 14px;
}
/* ----------- basic ----------- */
#basic {
border: solid 2px #DEDEDE;
}
#basic h1 {
font-size: 14px;
font-weight: bold;
margin-bottom: 8px;
}
#basic p {
font-size: 11px;
color: #666666;
margin-bottom: 20px;
border-bottom: solid 1px #dedede;
padding-bottom: 10px;
}
#basic label {
display: block;
font-weight: bold;
text-align: right;
width: 140px;
float: left;
}
#basic .small{
color:#666666;
display:block;
font-size:11px;
font-weight:normal;
text-align:right;
width:140px;
}
#basic input{
float:left;
width:200px;
margin:2px 0 30px 10px;
}
#basic button{
clear:both;
margin-left:150px;
background:#888888;
color:#FFFFFF;
border:solid 1px #666666;
font-size:11px;
font-weight:bold;
padding:4px 6px;
}
</style>
<div id="basic" class="myform">
<form id="form1" name="form1" method="post" action="">
<h1>Sign-up form</h1>
<p>This is the basic look of my form without table</p>
<label>Name
<span class="small">Add your name</span>
</label>
<input type="text" name="textfield" id="textfield" />
<label>Email
<span class="small">Add a valid address</span>
</label>
<input type="text" name="textfield" id="textfield" />
<label>Email
<span class="small">Add a valid address</span>
</label>
<!-- Problem --->
<input type="radio" name="something" id="r1" class="radio" value="1" /><label for="r1">One</label>
<input type="radio" name="something" id="r2" class="radio" value="2" /><label for="r2">Two</label>
<!-- Problem --->
<button type="submit">Sign-up</button>
<div class="spacer"></div>
</form>
</div>
```
I was given this example form, however I cannot add radio buttons without them being messed up.
|
(within the style tags)
add these new style rules:
```
#basic input.radio
{
width:20px;
}
#basic label.radiolabel
{
width:40px;
text-align:left;
line-height:24px;
}
```
in your html:
add a new class to each label, like so:
```
<!-- Problem --->
<input type="radio" name="textfield" id="r1" class="radio" value="1" />
<label for="r1" class="radiolabel">One</label>
<input type="radio" name="textfield" id="r2" class="radio" value="2" />
<label for="r2" class="radiolabel">Two</label>
<!-- Problem --->
```
edit:added line-height to the label's styling :)
|
232,884 |
<p>Like most developers here and in the entire world, I have been developing software systems using object-oriented programming (OOP) techniques for many years. So when I read that aspect-oriented programming (AOP) addresses many of the problems that traditional OOP doesn't solve completely or directly, I pause and think, is it real?</p>
<p>I have read a lot of information trying to learn the keys of this AOP paradigm and I´m in the same place, so, I wanted to better understand its benefits in real world application development.</p>
<p>Does somebody have the answer?</p>
|
[
{
"answer_id": 232897,
"author": "Norbert B.",
"author_id": 2605840,
"author_profile": "https://Stackoverflow.com/users/2605840",
"pm_score": 5,
"selected": false,
"text": "<p>OOP and AOP are not mutually exclusive.\nAOP can be good addition to OOP.\nAOP is especially handy for adding standard code like logging, performance tracking, etc. to methods without clogging up the method code with this standard code.</p>\n"
},
{
"answer_id": 232900,
"author": "nkr1pt",
"author_id": 24046,
"author_profile": "https://Stackoverflow.com/users/24046",
"pm_score": 5,
"selected": false,
"text": "<p>Aspect oriented programming provides a nice way to implement cross-cutting concerns like logging, security.\nThese cross-cutting concerns are pieces of logic that have to be applied at many places but actually don't have anything to do with the business logic.</p>\n<p>You shouldn't see AOP as a replacement of OOP, but more as a nice add-on that\nmakes your code more clean, loosely-coupled and focused on the business logic.</p>\n<p>So by applying AOP you will get 2 major benefits:</p>\n<ol>\n<li><p>The logic for each concern is now in one place, as opposed to being scattered all over the code base.</p>\n</li>\n<li><p>Classes are cleaner since they only contain code for their primary concern (or core functionality) and secondary concerns have been moved to aspects.</p>\n</li>\n</ol>\n"
},
{
"answer_id": 232907,
"author": "fhe",
"author_id": 4445,
"author_profile": "https://Stackoverflow.com/users/4445",
"pm_score": 4,
"selected": false,
"text": "<p>I think there is no general answer to this question but one thing to be noted is, that AOP does not <em>replace</em> OOP but adds certain decomposition features that address the so-called <em>tyranny of the dominant composition</em> (<a href=\"http://portal.acm.org/citation.cfm?id=302457\" rel=\"nofollow noreferrer\">1</a>) (or crosscutting concerns).</p>\n\n<p>It surely helps in certain cases as long as you're in control of the tools and languages to use for a specific project, but also adds a new level of complexity regarding interaction of aspects and the need for additional tools like the <a href=\"http://www.eclipse.org/ajdt\" rel=\"nofollow noreferrer\">AJDT</a> to still understand your program.</p>\n\n<p>Gregor Kiczales once gave an interesting introductory talk on AOP at Google Tech Talks which I recommend watching: <a href=\"https://www.youtube.com/watch?v=cq7wpLI0hco\" rel=\"nofollow noreferrer\">Aspect Oriented Programming: Radical Research in Modularity</a>.</p>\n"
},
{
"answer_id": 232909,
"author": "Mendelt",
"author_id": 3320,
"author_profile": "https://Stackoverflow.com/users/3320",
"pm_score": 3,
"selected": false,
"text": "<p>First of all AOP will not replace OOP. AOP extends OOP. The ideas and practices of OOP stay relevant. Having a good object design will probably make it easier to extend it with aspects.</p>\n\n<p>I think the ideas that AOP brings are important. We need to work out ways to implement cross-cutting-concerns over different classes in your program without having to change the classes themselves. But I think the AOP will eventually just become part of other tools we use and not a separate tool or technique. We already see this happening.</p>\n\n<p>A couple of dynamic languages like Ruby and Python have language constructs like mixins that solve the same problems. This looks a lot like AOP but is better integrated in the language.</p>\n\n<p>Spring and Castle and a couple of other dependency injection framework have options to add behaviour to the classes they inject. This is a way of doing runtime-weaving and I think this has a lot of potential.</p>\n\n<p>I don't think you'll have to learn a completely new paradigm to use AOP. The ideas are interesting but are slowly being absorbed by existing tools and languages. Just stay informed and try out these tools.</p>\n"
},
{
"answer_id": 232918,
"author": "Mecki",
"author_id": 15809,
"author_profile": "https://Stackoverflow.com/users/15809",
"pm_score": 9,
"selected": true,
"text": "<p>Why "vs"? It is not "vs". You can use Aspect Oriented programming in combination with functional programming, but also in combination with Object Oriented one. It is not "vs", it is "Aspect Oriented Programming <strong>with</strong> Object Oriented Programming".</p>\n<p>To me AOP is some kind of "meta-programming". Everything that AOP does could also be done without it by just adding more code. AOP just saves you writing this code.</p>\n<p>Wikipedia has one of the best examples for this meta-programming. Assume you have a graphical class with many "set...()" methods. After each set method, the data of the graphics changed, thus the graphics changed and thus the graphics need to be updated on screen. Assume to repaint the graphics you must call "Display.update()". The classical approach is to solve this by adding <em>more code</em>. At the end of each set method you write</p>\n<pre><code>void set...(...) {\n :\n :\n Display.update();\n}\n</code></pre>\n<p>If you have 3 set-methods, that is not a problem. If you have 200 (hypothetical), it's getting real painful to add this everywhere. Also whenever you add a new set-method, you must be sure to not forget adding this to the end, otherwise you just created a bug.</p>\n<p>AOP solves this without adding tons of code, instead you add an aspect:</p>\n<pre><code>after() : set() {\n Display.update();\n}\n</code></pre>\n<p>And that's it! Instead of writing the update code yourself, you just tell the system that after a set() pointcut has been reached, it must run this code and it will run this code. No need to update 200 methods, no need to make sure you don't forget to add this code on a new set-method. Additionally you just need a pointcut:</p>\n<pre><code>pointcut set() : execution(* set*(*) ) && this(MyGraphicsClass) && within(com.company.*);\n</code></pre>\n<p>What does that mean? That means if a method is named "set*" (* means any name might follow after set), regardless of what the method returns (first asterisk) or what parameters it takes (third asterisk) <em>and</em> it is a method of MyGraphicsClass <em>and</em> this class is part of the package "com.company.*", then this is a set() pointcut. And our first code says "<em>after</em> running any method that is a set pointcut, run the following code".</p>\n<p>See how AOP elegantly solves the problem here? Actually everything described here can be done at compile time. A AOP preprocessor can just modify your source (e.g. adding Display.update() to the end of every set-pointcut method) before even compiling the class itself.</p>\n<p>However, this example also shows one of the big downsides of AOP. AOP is actually doing something that many programmers consider an "<strong><a href=\"http://en.wikipedia.org/wiki/Anti-pattern\" rel=\"noreferrer\">Anti-Pattern</a></strong>". The exact pattern is called "<a href=\"http://en.wikipedia.org/wiki/Action_at_a_distance_(computer_science)\" rel=\"noreferrer\">Action at a distance</a>".</p>\n<blockquote>\n<p>Action at a distance is an\nanti-pattern (a recognized common\nerror) in which behavior in one part\nof a program varies wildly based on\ndifficult or impossible to identify\noperations in another part of the\nprogram.</p>\n</blockquote>\n<p>As a newbie to a project, I might just read the code of any set-method and consider it broken, as it seems to not update the display. I don't <strong>see</strong> by just looking at the code of a set-method, that after it is executed, some other code will "magically" be executed to update the display. I consider this a serious downside! By making changes to a method, strange bugs might be introduced. Further understanding the code flow of code where certain things seem to work correctly, but are not obvious (as I said, they just magically work... somehow), is really hard.</p>\n<h2>Update</h2>\n<p>Just to clarify that: Some people might have the impression I'm saying AOP is something bad and should not be used. That's not what I'm saying! AOP is actually a great feature. I just say "Use it carefully". AOP will only cause problems if you mix up normal code and AOP for the same <em>Aspect</em>. In the example above, we have the Aspect of updating the values of a graphical object and painting the updated object. That is in fact a single aspect. Coding half of it as normal code and the other half of it as aspect is what adds the problem.</p>\n<p>If you use AOP for a completely different aspect, e.g. for logging, you will not run into the anti-pattern problem. In that case a newbie to the project might wonder "Where do all these log messages come from? I don't see any log output in the code", but that is not a huge problem. Changes he makes to the program logic will hardly break the log facility and changes made to the log facility will hardly break his program logic - these aspects are totally separated. Using AOP for logging has the advantage that your program code can fully concentrate on doing whatever it should do and you still can have sophisticated logging, without having your code being cluttered up by hundreds of log messages everywhere. Also when new code is introduced, magically log messages will appear at the right time with the right content. The newbie programmer might not understand why they are there or where they came from, but since they will log the "right thing" at the "right time", he can just happily accept the fact that they are there and move on to something else.</p>\n<p>So a good usage of AOP in my example would be to always log if any value has been updated via a set method. This will not create an anti-pattern and hardly ever be the cause of any problem.</p>\n<p>One might say, if you can easily abuse AOP to create so many problems, it's a bad idea to use it all. However which technology can't be abused? You can abuse data encapsulation, you can abuse inheritance. Pretty much every useful programming technology can be abused. Consider a programming language so limited that it only contains features that can't be abused; a language where features can only be used as they were initially intended to be used. Such a language would be so limited that it's arguable if it can be even used for real world programming.</p>\n"
},
{
"answer_id": 3923146,
"author": "JafTalks",
"author_id": 474396,
"author_profile": "https://Stackoverflow.com/users/474396",
"pm_score": 1,
"selected": false,
"text": "<p>AOP is a new programming paradigm dealing with this concept. An aspect is a software entity implementing a specific non-functional part of the application.</p>\n\n<p>I think this article is a good place to start with Aspect Oriented Programming:\n<a href=\"http://www.jaftalks.com/wp/index.php/introduction-to-aspect-oriented-programming/\" rel=\"nofollow\">http://www.jaftalks.com/wp/index.php/introduction-to-aspect-oriented-programming/</a></p>\n"
},
{
"answer_id": 56809115,
"author": "GPopat",
"author_id": 3669507,
"author_profile": "https://Stackoverflow.com/users/3669507",
"pm_score": 3,
"selected": false,
"text": "<p><strong>OOP</strong> is mainly used to organise your <strong>business logic</strong> while <strong>AOP</strong> helps to organise your <strong>non-functional things</strong> like Auditing, Logging, Transaction Management, Security etc.</p>\n<p>This way you can decouple your business logic from non-functional logic, which makes code cleaner.</p>\n<p>Other advantage is you can apply the advice (such as auditing) very consistently, without implementing any interface, which gives great flexibility for modification without touching the business logic.</p>\n<p>This way its easy to implement <strong>Separation Of Concern</strong> and <strong>Single Responsibility</strong>.</p>\n<p>Moreover, its easy to port business logic from one framework (say Spring) to somewhere else (in future) when its only solve a business problem</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/232884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30715/"
] |
Like most developers here and in the entire world, I have been developing software systems using object-oriented programming (OOP) techniques for many years. So when I read that aspect-oriented programming (AOP) addresses many of the problems that traditional OOP doesn't solve completely or directly, I pause and think, is it real?
I have read a lot of information trying to learn the keys of this AOP paradigm and I´m in the same place, so, I wanted to better understand its benefits in real world application development.
Does somebody have the answer?
|
Why "vs"? It is not "vs". You can use Aspect Oriented programming in combination with functional programming, but also in combination with Object Oriented one. It is not "vs", it is "Aspect Oriented Programming **with** Object Oriented Programming".
To me AOP is some kind of "meta-programming". Everything that AOP does could also be done without it by just adding more code. AOP just saves you writing this code.
Wikipedia has one of the best examples for this meta-programming. Assume you have a graphical class with many "set...()" methods. After each set method, the data of the graphics changed, thus the graphics changed and thus the graphics need to be updated on screen. Assume to repaint the graphics you must call "Display.update()". The classical approach is to solve this by adding *more code*. At the end of each set method you write
```
void set...(...) {
:
:
Display.update();
}
```
If you have 3 set-methods, that is not a problem. If you have 200 (hypothetical), it's getting real painful to add this everywhere. Also whenever you add a new set-method, you must be sure to not forget adding this to the end, otherwise you just created a bug.
AOP solves this without adding tons of code, instead you add an aspect:
```
after() : set() {
Display.update();
}
```
And that's it! Instead of writing the update code yourself, you just tell the system that after a set() pointcut has been reached, it must run this code and it will run this code. No need to update 200 methods, no need to make sure you don't forget to add this code on a new set-method. Additionally you just need a pointcut:
```
pointcut set() : execution(* set*(*) ) && this(MyGraphicsClass) && within(com.company.*);
```
What does that mean? That means if a method is named "set\*" (\* means any name might follow after set), regardless of what the method returns (first asterisk) or what parameters it takes (third asterisk) *and* it is a method of MyGraphicsClass *and* this class is part of the package "com.company.\*", then this is a set() pointcut. And our first code says "*after* running any method that is a set pointcut, run the following code".
See how AOP elegantly solves the problem here? Actually everything described here can be done at compile time. A AOP preprocessor can just modify your source (e.g. adding Display.update() to the end of every set-pointcut method) before even compiling the class itself.
However, this example also shows one of the big downsides of AOP. AOP is actually doing something that many programmers consider an "**[Anti-Pattern](http://en.wikipedia.org/wiki/Anti-pattern)**". The exact pattern is called "[Action at a distance](http://en.wikipedia.org/wiki/Action_at_a_distance_(computer_science))".
>
> Action at a distance is an
> anti-pattern (a recognized common
> error) in which behavior in one part
> of a program varies wildly based on
> difficult or impossible to identify
> operations in another part of the
> program.
>
>
>
As a newbie to a project, I might just read the code of any set-method and consider it broken, as it seems to not update the display. I don't **see** by just looking at the code of a set-method, that after it is executed, some other code will "magically" be executed to update the display. I consider this a serious downside! By making changes to a method, strange bugs might be introduced. Further understanding the code flow of code where certain things seem to work correctly, but are not obvious (as I said, they just magically work... somehow), is really hard.
Update
------
Just to clarify that: Some people might have the impression I'm saying AOP is something bad and should not be used. That's not what I'm saying! AOP is actually a great feature. I just say "Use it carefully". AOP will only cause problems if you mix up normal code and AOP for the same *Aspect*. In the example above, we have the Aspect of updating the values of a graphical object and painting the updated object. That is in fact a single aspect. Coding half of it as normal code and the other half of it as aspect is what adds the problem.
If you use AOP for a completely different aspect, e.g. for logging, you will not run into the anti-pattern problem. In that case a newbie to the project might wonder "Where do all these log messages come from? I don't see any log output in the code", but that is not a huge problem. Changes he makes to the program logic will hardly break the log facility and changes made to the log facility will hardly break his program logic - these aspects are totally separated. Using AOP for logging has the advantage that your program code can fully concentrate on doing whatever it should do and you still can have sophisticated logging, without having your code being cluttered up by hundreds of log messages everywhere. Also when new code is introduced, magically log messages will appear at the right time with the right content. The newbie programmer might not understand why they are there or where they came from, but since they will log the "right thing" at the "right time", he can just happily accept the fact that they are there and move on to something else.
So a good usage of AOP in my example would be to always log if any value has been updated via a set method. This will not create an anti-pattern and hardly ever be the cause of any problem.
One might say, if you can easily abuse AOP to create so many problems, it's a bad idea to use it all. However which technology can't be abused? You can abuse data encapsulation, you can abuse inheritance. Pretty much every useful programming technology can be abused. Consider a programming language so limited that it only contains features that can't be abused; a language where features can only be used as they were initially intended to be used. Such a language would be so limited that it's arguable if it can be even used for real world programming.
|
232,895 |
<p>I came across an interesting article which shows how we can transparently encrypt jdbc connections using java thin client. </p>
<p><a href="http://javasight.wordpress.com/2008/08/29/network-data-encryption-and-integrity-for-thin-jdbc-clients/" rel="nofollow noreferrer">http://javasight.wordpress.com/2008/08/29/network-data-encryption-and-integrity-for-thin-jdbc-clients/</a></p>
<p>However I want to know how this can be achieved for application servers (like oc4j) datasources.</p>
|
[
{
"answer_id": 574473,
"author": "Franklin",
"author_id": 67517,
"author_profile": "https://Stackoverflow.com/users/67517",
"pm_score": 1,
"selected": false,
"text": "<p>It can be similarly done. I believe on the Oracle AS there is an option at the bottom of the page when you create datasource which says add properties. I believe you can add the following over there and give it a try.</p>\n\n<pre><code>// Set the Client encryption level \n\"oracle.net.encryption_client\" = Service.getLevelString(level) \n\n// Set the Client encryption selected list \n\"oracle.net.encryption_types_client\"= \"(RC4_40)\"\n\n// Set the Client integrity level \n\"oracle.net.crypto_checksum_client\"= Service.getLevelString(level) \n\n// Set the client integrity selected list \n\"oracle.net.crypto_checksum_types_client\"=\"( MD5 )\"\n</code></pre>\n\n<p>If it works out. Please let us know.</p>\n\n<p>Thanks,\nFranklin.</p>\n"
},
{
"answer_id": 33154232,
"author": "osama yaccoub",
"author_id": 2866298,
"author_profile": "https://Stackoverflow.com/users/2866298",
"pm_score": 0,
"selected": false,
"text": "<p>Late reply somehow, but for any one who come across this question again</p>\n\n<p><strong><em>For Enryption/Integrity:</em></strong></p>\n\n<p>you will need to insert this properties manually in $J2EE_HOME/config/data-sources.xml as follows : -not tested thoroughly but should work, at least with little twicking , but should be using OracleDataSource factory class - </p>\n\n<pre><code><connection-factory factory-class=\"oracle.jdbc.pool.OracleDataSource\" user=... >\n <connection-properties>\n <property name=\"oracle.net.encryption_client\" value=\"REQUIRED123\"/>\n <property name=\"oracle.net.crypto_checksum_types_client\" value=\"(SHA1123)\"/>\n <property name=\"oracle.net.crypto_checksum_client\" value=\"REQUIRED\"/>\n <property name=\"oracle.net.encryption_types_client\" value=\"(AES256)\"/>\n </connection-properties>\n </connection-factory>\n</code></pre>\n\n<p><strong><em>For SSL :</em></strong></p>\n\n<p>check the \"Configuring a TCPS Data Source\" section in this <a href=\"https://docs.oracle.com/cd/E16439_01/doc.1013/e13977/configssl.htm\" rel=\"nofollow\">link</a></p>\n\n<p>Franklin's solution won't work because properties allowed to be added in OC4J are limited to some enumerated values, so no property like \"oracle.net.encryption_client\" for example can't be added ... instead you will get this <a href=\"http://i.stack.imgur.com/j8aNp.jpg\" rel=\"nofollow\">oc4j error</a></p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/232895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I came across an interesting article which shows how we can transparently encrypt jdbc connections using java thin client.
<http://javasight.wordpress.com/2008/08/29/network-data-encryption-and-integrity-for-thin-jdbc-clients/>
However I want to know how this can be achieved for application servers (like oc4j) datasources.
|
It can be similarly done. I believe on the Oracle AS there is an option at the bottom of the page when you create datasource which says add properties. I believe you can add the following over there and give it a try.
```
// Set the Client encryption level
"oracle.net.encryption_client" = Service.getLevelString(level)
// Set the Client encryption selected list
"oracle.net.encryption_types_client"= "(RC4_40)"
// Set the Client integrity level
"oracle.net.crypto_checksum_client"= Service.getLevelString(level)
// Set the client integrity selected list
"oracle.net.crypto_checksum_types_client"="( MD5 )"
```
If it works out. Please let us know.
Thanks,
Franklin.
|
232,905 |
<p>I got this logic in a control to create a correct url for an image. My control basically needs to diplay an image, but the src is actually a complex string based on different parameters pointing at an image-server.</p>
<p>So we decided to to create a control MyImage derived from asp:Image - it works like a charm. Now i need the same logic but my image now needs to respond to a click. What i mean is - the 'MyImage' is used to display images on the site but in a few rare cases i would like it to be clickable.</p>
<p>I think i got three choices.</p>
<ol>
<li>Change MyImage to derive from asp:ImageButton instead of asp:Image.</li>
<li>Copy all the code from MyImage into a new MyClickImage and derive from asp:ImageButton.</li>
<li>Wrap logic on MyImage to add a hyperlink, implement IPostbackHandler for that hyperlink and add the logic to handle the event.</li>
</ol>
<p>Obviously i would very much like to avoid using option 2) since i would have to maintain two almost identically controls. The problem with option 1) <em>as i see it</em> (perhaps i'm wrong?) Is that all the images on the site that are not supposed to be clickable will automaticly become clickable. Option 3) seems overly complicated as i would have to maintain state, events and building the link manually.</p>
<p>I'm looking for a quick answer like 'you're stupid, just set property 'x' to false when you don't want it to be clickable' - but if i'm not mistaking it is not that obvious and ofcourse a more elaborate answer would be fine :)</p>
<p>EDIT: Added the 3rd option - i forgot to put that there in the first place :)</p>
|
[
{
"answer_id": 574473,
"author": "Franklin",
"author_id": 67517,
"author_profile": "https://Stackoverflow.com/users/67517",
"pm_score": 1,
"selected": false,
"text": "<p>It can be similarly done. I believe on the Oracle AS there is an option at the bottom of the page when you create datasource which says add properties. I believe you can add the following over there and give it a try.</p>\n\n<pre><code>// Set the Client encryption level \n\"oracle.net.encryption_client\" = Service.getLevelString(level) \n\n// Set the Client encryption selected list \n\"oracle.net.encryption_types_client\"= \"(RC4_40)\"\n\n// Set the Client integrity level \n\"oracle.net.crypto_checksum_client\"= Service.getLevelString(level) \n\n// Set the client integrity selected list \n\"oracle.net.crypto_checksum_types_client\"=\"( MD5 )\"\n</code></pre>\n\n<p>If it works out. Please let us know.</p>\n\n<p>Thanks,\nFranklin.</p>\n"
},
{
"answer_id": 33154232,
"author": "osama yaccoub",
"author_id": 2866298,
"author_profile": "https://Stackoverflow.com/users/2866298",
"pm_score": 0,
"selected": false,
"text": "<p>Late reply somehow, but for any one who come across this question again</p>\n\n<p><strong><em>For Enryption/Integrity:</em></strong></p>\n\n<p>you will need to insert this properties manually in $J2EE_HOME/config/data-sources.xml as follows : -not tested thoroughly but should work, at least with little twicking , but should be using OracleDataSource factory class - </p>\n\n<pre><code><connection-factory factory-class=\"oracle.jdbc.pool.OracleDataSource\" user=... >\n <connection-properties>\n <property name=\"oracle.net.encryption_client\" value=\"REQUIRED123\"/>\n <property name=\"oracle.net.crypto_checksum_types_client\" value=\"(SHA1123)\"/>\n <property name=\"oracle.net.crypto_checksum_client\" value=\"REQUIRED\"/>\n <property name=\"oracle.net.encryption_types_client\" value=\"(AES256)\"/>\n </connection-properties>\n </connection-factory>\n</code></pre>\n\n<p><strong><em>For SSL :</em></strong></p>\n\n<p>check the \"Configuring a TCPS Data Source\" section in this <a href=\"https://docs.oracle.com/cd/E16439_01/doc.1013/e13977/configssl.htm\" rel=\"nofollow\">link</a></p>\n\n<p>Franklin's solution won't work because properties allowed to be added in OC4J are limited to some enumerated values, so no property like \"oracle.net.encryption_client\" for example can't be added ... instead you will get this <a href=\"http://i.stack.imgur.com/j8aNp.jpg\" rel=\"nofollow\">oc4j error</a></p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/232905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11619/"
] |
I got this logic in a control to create a correct url for an image. My control basically needs to diplay an image, but the src is actually a complex string based on different parameters pointing at an image-server.
So we decided to to create a control MyImage derived from asp:Image - it works like a charm. Now i need the same logic but my image now needs to respond to a click. What i mean is - the 'MyImage' is used to display images on the site but in a few rare cases i would like it to be clickable.
I think i got three choices.
1. Change MyImage to derive from asp:ImageButton instead of asp:Image.
2. Copy all the code from MyImage into a new MyClickImage and derive from asp:ImageButton.
3. Wrap logic on MyImage to add a hyperlink, implement IPostbackHandler for that hyperlink and add the logic to handle the event.
Obviously i would very much like to avoid using option 2) since i would have to maintain two almost identically controls. The problem with option 1) *as i see it* (perhaps i'm wrong?) Is that all the images on the site that are not supposed to be clickable will automaticly become clickable. Option 3) seems overly complicated as i would have to maintain state, events and building the link manually.
I'm looking for a quick answer like 'you're stupid, just set property 'x' to false when you don't want it to be clickable' - but if i'm not mistaking it is not that obvious and ofcourse a more elaborate answer would be fine :)
EDIT: Added the 3rd option - i forgot to put that there in the first place :)
|
It can be similarly done. I believe on the Oracle AS there is an option at the bottom of the page when you create datasource which says add properties. I believe you can add the following over there and give it a try.
```
// Set the Client encryption level
"oracle.net.encryption_client" = Service.getLevelString(level)
// Set the Client encryption selected list
"oracle.net.encryption_types_client"= "(RC4_40)"
// Set the Client integrity level
"oracle.net.crypto_checksum_client"= Service.getLevelString(level)
// Set the client integrity selected list
"oracle.net.crypto_checksum_types_client"="( MD5 )"
```
If it works out. Please let us know.
Thanks,
Franklin.
|
232,926 |
<p>For instance, winsock libs works great across all versions of the visual studio. But I am having real trouble to provide a consistent binary across all the versions. The dll compiled with VS 2005 won't work when linked to an application written in 2008. I upgraded both 2k5 and 2k8 to SP1, but the results haven't changed much. It works some what ok. But when they include this with a C# app, the C# app gets access violation errors, but with classic C++ application it works fine.</p>
<p>Is there a strategy that I should know when I provide dlls ?</p>
|
[
{
"answer_id": 232959,
"author": "Chris Becke",
"author_id": 27491,
"author_profile": "https://Stackoverflow.com/users/27491",
"pm_score": 5,
"selected": true,
"text": "<p>First, dont pass anything other than plain old data accross DLL boundries. i.e. structs are fine. classes are not.\nSecond, make sure that ownership is not transferred - i.e. any structs passed accross the dll boundry are never deallocated outside the dll. So, if you dll exports a X* GetX() function, there is a corresponding FreeX(X*) type function ensuring that the same runtime that allocated is responsible for de-allocation.</p>\n\n<p>Next: Get your DLLs to link to the static runtime. Putting together a project comprimising dls from several 3rd parties, each linked to and expecting different runtimes, potentially different to the runtime expected by the app, is a pain, potentially forcing the installer software to install runtimes for 7.0, 7.1, 8.0 and 9.0 - several of which exist in different service packs which may or may not cause issues. Be kind - statically link your dll projects.</p>\n\n<p>-- Edit:\nYou cannot export a c++ class directly with this approach. Sharing class definitions between modules means you MUST have a homogeneous runtime environment as different compilers or versions of compilers will generate decorated names differently.</p>\n\n<p>You <em>can</em> bypass this restriction by exporting your class instead as a COM style interface... which is to say, while you cannot export a class in a runtime independent way, you CAN export an \"interface\", which you can easilly make by declaring a class containing only pure virtual functions...</p>\n\n<pre><code> struct IExportedMethods {\n virtual long __stdcall AMethod(void)=0;\n };\n // with the win32 macros:\n interface IExportedMethods {\n STDMETHOD_(long,AMethod)(THIS)PURE;\n };\n</code></pre>\n\n<p>In your class definition, you inherit from this interface:</p>\n\n<pre><code> class CMyObject: public IExportedMethods { ...\n</code></pre>\n\n<p>You can export interfaces like this by making C factory methods:</p>\n\n<pre><code> extern \"C\" __declspec(dllexport) IExportedClass* WINAPI CreateMyExportedObject(){\n return new CMyObject; \n }\n</code></pre>\n\n<p>This is a very lightweight way of exporting compiler version and runtime independent class versions. Note that you still cannot delete one of these. You Must include a release function as a member of the dll or the interface. As a member of the interface it could look like this:</p>\n\n<pre><code> interface IExportedMethods {\n STDMETHOD_(void) Release(THIS) PURE; };\n class CMyObject : public IExportedMethods {\n STDMETHODIMP_(void) Release(){\n delete this;\n }\n };\n</code></pre>\n\n<p>You can take this idea and run further with it - inherit your interface from IUnknown, implement ref counted AddRef and Release methods as well as the ability to QueryInterface for v2 interfaces or other features. And finally, use DllCreateClassObject as the means to create your object and get the necessary COM registration going. All this is optional however, you can easilly get away with a simple interface definition accessed through a C function.</p>\n"
},
{
"answer_id": 233038,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 3,
"selected": false,
"text": "<p>I disagree with Chris Becke's viewpoint, while seeing the advantages of his approach.</p>\n<p>The disadvantage is that you are unable to create libraries of utility objects, because you are forbidden to share them across libraries.</p>\n<h2>Expanding Chris' solution</h2>\n<p><a href=\"https://stackoverflow.com/questions/232926/how-to-make-consistent-dll-binaries-across-vs-versions#232959\">How to make consistent dll binaries across VS versions?</a></p>\n<p>Your choices depend on how much the compilers are different. In one side, different versions of the same compiler could handle data alignement the same way, and thus, you could expose structs and classes across your DLLs. In the other side, you could mistrust the other libraries compilers or compile options.</p>\n<p>In Windows Win32 API, they handled the problem through "handlers". You do the same by:</p>\n<p>1 - Never expose a struct. <strong>Expose only pointers</strong> (i.e. a void * pointer)<br>\n2 - This struct data's <strong>access is through functions</strong> taking the pointer as first parameter<br>\n3 - this struct's pointer <strong>allocation/deallocation data is through functions</strong></p>\n<p>This way, you can avoid recompiling everything when your struct change.</p>\n<p>The C++ way of doing this is the PImpl. See <a href=\"http://en.wikipedia.org/wiki/Opaque_pointer\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Opaque_pointer</a></p>\n<p>It has the same behaviour as the void * concept above, but with the PImpl, you can use both RAII, encapsulation, and profit from strong type safety. This would need compatible decoration (same compiler), but not the same runtime or version (if decorations are the same between versions).</p>\n<h2>Another solution?</h2>\n<p>Hoping to mix together DLLs from different compilers/compiler versions is either a recipe for disaster (as you explained in your question) or tedious as you have let go most (if not all) C++ solutions to your code to fall back to basic C coding, or both.</p>\n<p>My solution would be:</p>\n<p>1 - Be sure all your modules are compiled with the <strong>same compiler/version</strong>. Period.<br>\n2 - Be sure all your modules are compiled to <strong>link dynamically with the same runtime</strong><br>\n3 - Be sure to have an <strong>"encapsulation" of all third-party modules</strong> over which you have no control (unable to compile with your compiler), as explained quite rightly by Chris Becke at <a href=\"https://stackoverflow.com/questions/232926/how-to-make-consistent-dll-binaries-across-vs-versions#232959\">How to make consistent dll binaries across VS versions?</a>.</p>\n<p><strong>Note that it is not surprising nor outrageous to mandate that all modules of your application compiled against the same compiler and the same version of the compiler.</strong></p>\n<p>Don't let anyone tell you mixing compilers is a good thing. It is not. The freedom of mixing compiler is, for most people, the same kind of freedom one can enjoy by jumping from the top of a building: You are free to do so, but usually, you just don't want that.</p>\n<p>My solution enables you to:</p>\n<p>1 - export classes and thus, make real, non-castrated, <strong>C++ libraries</strong> (as you are supposed to do with the __declspec(dllexport) of Visual C++ for example)<br>\n2 - <strong>transfert allocation ownership</strong> (which happens without your consent when using allocating and/or deallocating inlined code, or STL)<br>\n3 - <strong>not be annoyed with problems</strong> tied to the fact each module has its own version of the runtime (i.e. memory allocation, and some global data used by the C or C++ API)</p>\n<p>Note that it means you're not supposed to mix debug version of your modules with release versions of other modules. Your app is either fully in debug or fully in release.</p>\n"
},
{
"answer_id": 233197,
"author": "botismarius",
"author_id": 4528,
"author_profile": "https://Stackoverflow.com/users/4528",
"pm_score": 2,
"selected": false,
"text": "<p>regarding the problem of passing a structure, this thing is safe as long as you align your structure such as:</p>\n\n<pre>\n<code>\n#pragma pack(push,4)\ntypedef myStruct {\n int a;\n char b;\n float c;\n}myStruct;\n#pragma pack(pop)\n</code>\n</pre>\n\n<p>You can put this declaration in a header file and include it in both projects. This way you will not have any problem while passing structures.</p>\n\n<p>Also, make sure you link statically with the runtime libraries and do not try thing such as allocating memory (ptr=malloc(1024)) in a module and then releasing that memory in another module (free(ptr)).</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/232926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1781/"
] |
For instance, winsock libs works great across all versions of the visual studio. But I am having real trouble to provide a consistent binary across all the versions. The dll compiled with VS 2005 won't work when linked to an application written in 2008. I upgraded both 2k5 and 2k8 to SP1, but the results haven't changed much. It works some what ok. But when they include this with a C# app, the C# app gets access violation errors, but with classic C++ application it works fine.
Is there a strategy that I should know when I provide dlls ?
|
First, dont pass anything other than plain old data accross DLL boundries. i.e. structs are fine. classes are not.
Second, make sure that ownership is not transferred - i.e. any structs passed accross the dll boundry are never deallocated outside the dll. So, if you dll exports a X\* GetX() function, there is a corresponding FreeX(X\*) type function ensuring that the same runtime that allocated is responsible for de-allocation.
Next: Get your DLLs to link to the static runtime. Putting together a project comprimising dls from several 3rd parties, each linked to and expecting different runtimes, potentially different to the runtime expected by the app, is a pain, potentially forcing the installer software to install runtimes for 7.0, 7.1, 8.0 and 9.0 - several of which exist in different service packs which may or may not cause issues. Be kind - statically link your dll projects.
-- Edit:
You cannot export a c++ class directly with this approach. Sharing class definitions between modules means you MUST have a homogeneous runtime environment as different compilers or versions of compilers will generate decorated names differently.
You *can* bypass this restriction by exporting your class instead as a COM style interface... which is to say, while you cannot export a class in a runtime independent way, you CAN export an "interface", which you can easilly make by declaring a class containing only pure virtual functions...
```
struct IExportedMethods {
virtual long __stdcall AMethod(void)=0;
};
// with the win32 macros:
interface IExportedMethods {
STDMETHOD_(long,AMethod)(THIS)PURE;
};
```
In your class definition, you inherit from this interface:
```
class CMyObject: public IExportedMethods { ...
```
You can export interfaces like this by making C factory methods:
```
extern "C" __declspec(dllexport) IExportedClass* WINAPI CreateMyExportedObject(){
return new CMyObject;
}
```
This is a very lightweight way of exporting compiler version and runtime independent class versions. Note that you still cannot delete one of these. You Must include a release function as a member of the dll or the interface. As a member of the interface it could look like this:
```
interface IExportedMethods {
STDMETHOD_(void) Release(THIS) PURE; };
class CMyObject : public IExportedMethods {
STDMETHODIMP_(void) Release(){
delete this;
}
};
```
You can take this idea and run further with it - inherit your interface from IUnknown, implement ref counted AddRef and Release methods as well as the ability to QueryInterface for v2 interfaces or other features. And finally, use DllCreateClassObject as the means to create your object and get the necessary COM registration going. All this is optional however, you can easilly get away with a simple interface definition accessed through a C function.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.