instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>I want find the index of a given DOM node. It's like the inverse of doing </p>
<pre><code>document.getElementById('id_of_element').childNodes[K]
</code></pre>
<p>I want to instead extract the value of <code>K</code> given that I already have the reference to the child node and the parent node. How do I do this? </p>
|
<p>The shortest possible way, without any frameworks, in all versions of Safari, FireFox, Chrome and IE >= 9:</p>
<p><code>var i = Array.prototype.indexOf.call(e.childNodes, someChildEl);</code></p>
|
<p>using a framework like prototype you could use this :</p>
<pre><code>$(el).up().childElements().indexOf($(el))
</code></pre>
| 49,555
|
<p>I recently inherited an old visual basic 6/ crystal reports project which connects to a sql server database. The error message I get (Error# -2147191803 A String is required here) when I attempt to run the project seems to be narrowed down to the .Printout command in the following code: </p>
<pre>
'Login to database
Set Tables = Report.Database.Tables
Set Table = Tables.Item(1)
Table.SetLogOnInfo ConnName, DBName, user, pass
DomainName = CStr(selected)
'Set parameter Fields
'Declare parameter holders
Set ParamDefs = Report.ParameterFields
'Store parameter objects
For Each ParamDef In ParamDefs
With ParamDef
MsgBox("DomainName : " + DomainName)
Select Case .ParameterFieldName
Case "Company Name"
.SetCurrentValue DomainName
End Select
Select Case .Name
Case "{?Company Name}"
.SetCurrentValue DomainName
End Select
'Flag to see what is assigned to Current value
MsgBox("paramdef: " + ParamDef.Value)
End With
Next
Report.EnableParameterPrompting = False
Screen.MousePointer = vbHourglass
'CRViewer1.ReportSource = Report
'CRViewer1.ViewReport
test = 1
**Report.PrintOut**
test = test + 3
currenttime = Str(Now)
currenttime = Replace(currenttime, "/", "-")
currenttime = Replace(currenttime, ":", "-")
DomainName = Replace(DomainName, ".", "")
startName = mPath + "\crysta~1.pdf"
endName = mPath + "\" + DomainName + "\" + DomainName + " " + currenttime + ".pdf"
rc = MsgBox("Wait for PDF job to finish", vbInformation, "H/W Report")
Name startName As endName
Screen.MousePointer = vbDefault
End If
</pre>
<p>During the run, the form shows up, the ParamDef variable sets the "company name" and when it gets to the <strong>Report.PrintOut</strong> line which prompts to print, it throws the error. I'm guessing the crystal report isn't receiving the "Company Name" to properly run the crystal report. Does any one know how to diagnose this...either on the vb6 or crystal reports side to determine what I'm missing here? </p>
<p><strong>UPDATE:</strong> </p>
<ul>
<li>inserted CStr(selected) to force DomainName to be a string</li>
<li>inserted msgboxes into the for loop above and below the .setcurrentvalue line </li>
<li>inserted Case "{?Company Name}" statement to see if that helps setting the value</li>
<li>tried .AddCurrentValue and .SetCurrentValue functions as suggested by other forum websites</li>
<li>ruled out that it was my development environement..loaded it on another machine with the exact same vb6 crystal reports 8.5 running on winxp prof sp2 and the same errors come up. </li>
</ul>
<p>and when I run the MsgBox(ParamDef.Value) and it also turns up blank with the same missing string error. I also can't find any documentation on the craxdrt.ParameterFieldDefinition class to see what other hidden functions are available. When I see the list of methods and property variables, it doesn't list SetCurrentValue as one of the functions.
Any ideas on this?</p>
|
<p>What is the value of your selected variable?</p>
<p>Table.SetLogOnInfo ConnName, DBName, user, pass<br />
<strong>DomainName = selected</strong><br />
'Set parameter Fields<br /></p>
<p>If it is not a string, then that might be the problem. Crystal expects a string variable and when it doesn't receive what it expects, it throws errors.</p>
|
<p>This can happen in crystal reports 8.5 if you changed the length of a string column you use in your report so that it exceeds 255 bytes. This can also happen if you change the column type from varchar to nvarchar (double byte string!)</p>
<p>The reason for this is that crystal reports 8.5 treats all strings longer than 255 bytes as memo fields.</p>
<p>I would suggest youe upgrade to crystal reports XI - the API has not changed that much.</p>
| 12,881
|
<p>Well i am currently working on a project doing some UI mockups when certain users wanted to have two logo on the top left ot the website.
One is to indicate what is the website about then another is to indicate that this website is actually belong to this particular sector.</p>
<p>I thought that UI design wise this is very bad because two logos on top left. If users go in initially he won't be able to know which logo means what.</p>
<p>What are your opinions regarding this?</p>
|
<p>It does sound rather confusing, though it may depend on the content of the logos as to whether they are difficult to figure out.</p>
<p>I would recommend getting someone who hasn't used the site to see the mockup and see what they think about it (without guidance)... ie some usability testing.</p>
<p>Check out <a href="https://rads.stackoverflow.com/amzn/click/com/0321344758" rel="nofollow noreferrer" rel="nofollow noreferrer">Don't Make Me Think by Steve Krug</a>... you will want to do some tests right away after you read that, and he goes into detail about what to do when you get pulled in the wrong direction by people who don't really understand the consequences of the decision.</p>
|
<p>Sounds dependent on the implementation to me.</p>
| 14,131
|
<p>I'm going to start a new project - rewriting an existing system (PHP + SQL Server) from scratch because of some very serious limitations by design.</p>
<p>We have some quite good knowledge of SQL Server (currently we're using SQL Server 2000 in existing system) and we would like to employ its newer version (2008 I guess) in our new project.</p>
<p>I am really fond of technologies that Java offers - particularly Spring Framework and Wicket and I am quite familiar with Java from others projects and assignments before.
Therefore, we consider using Java and Microsoft SQL Server.</p>
<p>There are two JDBC drivers for SQL Server - jTDS and Microsoft's one - <a href="http://msdn.microsoft.com/en-us/data/aa937724.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/data/aa937724.aspx</a>. I think we should test both of them.<br/></p>
<p>Are there any limitations in such solution I should know of? Has someone experience with such a technology combination?</p>
|
<p>I've worked on a project using MSQL Server in conjunction with a Java Stack. It works very well and as long, since JDBC shouldn't really care about your database. We used ehcache together with Hibernate and had problems with the MS JDBC Driver, so we switched to jtds and it works really good.</p>
<p>It's quite a while ago, so you still might wanna give the MS driver a chance...</p>
|
<p>The JDBC driver works well with SQL Server 2008, I've not had any problems with it. The version that you need to download depends on the version of the JRE you have installed. JRE6 uses JDBC4, JRE7 uses JDBC4.1, etc. Once you download the correct driver from Microsoft and run the installer you will need to copy the
<strong>sqljdbc_auth.dll</strong> from the <strong>\auth</strong> directory to the <strong>c:\windows\system32</strong> directory. Then can then use this code to make a connection:</p>
<p>In your header:</p>
<pre><code>import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
</code></pre>
<p>and in your class:</p>
<pre><code>public class connectToSQL {
public void connectToDB() throws Exception {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl = "jdbc:sqlserver://<IPADDRESS>:<PORT>;DatabaseName=<NAME OF DATABASE TO CONNECT TO>;IntegratedSecurity=false";
Connection con = DriverManager.getConnection(connectionUrl, "<SQL SERVER USER LOGIN>", "<SQL SERVER PASSWORD>");
Statement s = con.createStatement();
ResultSet r = s.executeQuery("SELECT * FROM <TABLENAME TO SELECT FROM>");
while (r.next()) {
System.out.println(r.getString(1));
}
}
}
</code></pre>
| 2,847
|
<p>i have a link to a media file such as an mp3, and i want it to get downloaded when the user clicks on it, instead of just having the file get played. the page i have in mind is just a plain static html page.</p>
<p>any ideas?</p>
|
<p>In order to make that happen you need to send a header with <code>Content-disposition: attachment; filename=fname.ext</code> header in your favorite language before sending the file. </p>
<p>Without knowing the specifics such as what language and what control you have over your server configuration I cannot give you more detailed instructions. You cannot do it with just html and javascript however.</p>
|
<p>While this is not a solution, change the file extension to anything other than MP3.
And, ask the user to rename it once downloaded.</p>
| 43,959
|
<p>I'm using Castle Windsor for dependency injection in my test project. I'm trying to create an instance one of my 'Repository' classes. "It works fine on my machine", but when I run a nightly build in TFS, my tests are not able to load said classes.</p>
<pre><code>private static readonly WindsorContainer _container = new WindsorContainer(new XmlInterpreter());
public void MyTestInitialize()
{
var testRepository = (IBogusRepository)_container[typeof(IBogusRepository)];
}
</code></pre>
<p>xml configuration:</p>
<pre><code><castle>
<components>
<component id="primaryBogusRepository" type="Example2008.Repository.LALALALALA, Example2008.Repository" service="Example2008.Domain.Repository.IBogusRepository, Example2008.Domain" />
<component id="primaryProductRepository" type="Example2008.Repository.ProductRepository, Example2008.Repository" service="Example2008.Domain.Repository.IProductRepository, Example2008.Domain" />
</components>
</castle>
</code></pre>
<p>When I queue a new build it produces
the following message:</p>
<blockquote>
<p>Unable to create instance of class
Example2008.Test.ActiveProductRepositoryTest. Error:
System.Configuration.ConfigurationException:
The type name
Example2008.Repository.LALALALALA,
Example2008.Repository could not be
located.</p>
<p>Castle.Windsor.Installer.DefaultComponentInstaller.ObtainType(String
typeName)
Castle.Windsor.Installer.DefaultComponentInstaller.SetUpComponents(IConfiguration[]
configurations, IWindsorContainer
container)
Castle.Windsor.Installer.DefaultComponentInstaller.SetUp(IWindsorContainer
container, IConfigurationStore store)
Castle.Windsor.WindsorContainer.RunInstaller()
Castle.Windsor.WindsorContainer..ctor(IConfigurationInterpreter
interpreter)
Example2008.Test.ActiveProductRepositoryTest..cctor()
in d:\Code_Temp\Example Project
Nightly\Sources\Example2008.Test\ProductRepositoryTest.cs:
line 19</p>
</blockquote>
<p>From this message, it seems that my configuration is correct (it can see that I want to instantiate the concrete class 'LALALALALA', so the xml configuration has obviously been red correctly)</p>
<p>I think I have my dependencies set up correctly as well (because it works locally, even if I clean the solution and rebuild).</p>
<p>Any thoughts?</p>
<p>(using VS2008, TFS 2008.Net 3.5, Castle 1.03, by the way) </p>
|
<p>Mac OS X's "Keychain Access" application gives you access to the nice OS X password generator. Hit command-N and click the key icon. You get to choose password style (memorable, numeric, alphanumeric, random, FIPS-181) and choose the length. It also warns you about weak passwords.</p>
|
<pre><code><?php
print md5(rand(0, 99999));
?>
</code></pre>
| 12,684
|
<p>I want to limit my users to a directory and its sub directories but the "Parent Directory" button allows them to browse to an arbitrary directory.</p>
<p>How should I go about doing that?</p>
|
<p>You can probably do this by setting your own <a href="https://docs.oracle.com/javase/8/docs/api/javax/swing/filechooser/FileSystemView.html" rel="noreferrer">FileSystemView</a>.</p>
|
<p>No need to be that complicated. You can easily set selection mode of a JFileChooser like this</p>
<pre><code>JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fc.setMultiSelectionEnabled(false);
</code></pre>
<p>You can read more reference here <a href="http://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html" rel="nofollow">How to Use File Choosers</a></p>
| 5,246
|
<p>I have a SharePoint site with multiple lists, some of which have the same fields - a choice of products or countries.</p>
<p>How can I build the lists in a way that I configure the choice field once and use it in multiple lists, so that in the future, if I add a value to the choice, I add it only once?</p>
|
<p>If you go to Site Settings, under Galleries there is an option for Site Columns. You can create your choice list there. Then, under the Library Settings there is an option to Add From Existing Site Columns. You should be able to see and select your newly created column there.</p>
|
<p>You should create a list which contains the countries. Then in the lists where you want to reuse the countries lookup, create a column of type Lookup and select the countries list in the "Get infomation from" dropdown.</p>
<p>Here is a link to a more visual guide:
<a href="http://blog.phase2int.com/?p=101" rel="nofollow noreferrer">http://blog.phase2int.com/?p=101</a></p>
| 10,797
|
<p>How does one check if a directory is already present in the PATH environment variable? Here's a start. All I've managed to do with the code below, though, is echo the first directory in %PATH%. Since this is a FOR loop you'd think it would enumerate all the directories in %PATH%, but it only gets the first one.</p>
<p>Is there a better way of doing this? Something like <a href="https://ss64.com/nt/find.html" rel="nofollow noreferrer">FIND</a> or <a href="https://ss64.com/nt/findstr.html" rel="nofollow noreferrer">FINDSTR</a> operating on the %PATH% variable? I'd just like to check if a directory exists in the list of directories in %PATH%, to avoid adding something that might already be there.</p>
<pre><code>FOR /F "delims=;" %%P IN ("%PATH%") DO (
@ECHO %%~P
)
</code></pre>
|
<p>First I will point out a number of issues that make this problem difficult to solve perfectly. Then I will present the most bullet-proof solution I have been able to come up with.</p>
<p>For this discussion I will use lower case path to represent a single folder path in the file system, and upper case PATH to represent the PATH environment variable.</p>
<p>From a practical standpoint, most people want to know if PATH contains the logical equivalent of a given path, not whether PATH contains an exact string match of a given path. This can be problematic because:</p>
<ol>
<li><p><strong>The trailing <code>\</code> is optional in a path</strong><br>
Most paths work equally well both with and without the trailing <code>\</code>. The path logically points to the same location either way. The PATH frequently has a mixture of paths both with and without the trailing <code>\</code>. This is probably the most common practical issue when searching a PATH for a match.</p>
<ul>
<li>There is one exception: The relative path <code>C:</code> (meaning the current working directory of drive C) is very different than <code>C:\</code> (meaning the root directory of drive C)
<br/><br/></li>
</ul></li>
<li><p><strong>Some paths have alternate short names</strong><br>
Any path that does not meet the old 8.3 standard has an alternate short form that does meet the standard. This is another PATH issue that I have seen with some frequency, particularly in business settings.</p></li>
<li><p><strong>Windows accepts both <code>/</code> and <code>\</code> as folder separators within a path.</strong><br>
This is not seen very often, but a path can be specified using <code>/</code> instead of <code>\</code> and it will function just fine within PATH (as well as in many other Windows contexts)</p></li>
<li><p><strong>Windows treats consecutive folder separators as one logical separator.</strong><br>
C:\FOLDER\\ and C:\FOLDER\ are equivalent. This actually helps in many contexts when dealing with a path because a developer can generally append <code>\</code> to a path without bothering to check if the trailing <code>\</code> already exists. But this obviously can cause problems if trying to perform an exact string match.</p>
<ul>
<li>Exceptions: Not only is <code>C:</code>, different than <code>C:\</code>, but <code>C:\</code> (a valid path), is different than <code>C:\\</code> (an invalid path).
<br/><br/></li>
</ul></li>
<li><p><strong>Windows trims trailing dots and spaces from file and directory names.</strong><br>
<code>"C:\test. "</code> is equivalent to <code>"C:\test"</code>.</p></li>
<li><p><strong>The current <code>.\</code> and parent <code>..\</code> folder specifiers may appear within a path</strong><br>
Unlikely to be seen in real life, but something like <code>C:\.\parent\child\..\.\child\</code> is equivalent to <code>C:\parent\child</code></p></li>
<li><p><strong>A path can optionally be enclosed within double quotes.</strong><br>
A path is often enclosed in quotes to protect against special characters like <code><space></code> <code>,</code> <code>;</code> <code>^</code> <code>&</code> <code>=</code>. Actually any number of quotes can appear before, within, and/or after the path. They are ignored by Windows except for the purpose of protecting against special characters. The quotes are never required within PATH unless a path contains a <code>;</code>, but the quotes may be present never-the-less.</p></li>
<li><p><strong>A path may be fully qualified or relative.</strong><br>
A fully qualified path points to exactly one specific location within the file system. A relative path location changes depending on the value of current working volumes and directories. There are three primary flavors of relative paths: </p>
<ul>
<li><strong><code>D:</code></strong> is relative to the current working directory of volume D:</li>
<li><strong><code>\myPath</code></strong> is relative to the current working volume (could be C:, D: etc.)</li>
<li><strong><code>myPath</code></strong> is relative to the current working volume and directory </li>
</ul>
<p>It is perfectly legal to include a relative path within PATH. This is very common in the Unix world because Unix does not search the current directory by default, so a Unix PATH will often contain <code>.\</code>. But Windows does search the current directory by default, so relative paths are rare in a Windows PATH.</p></li>
</ol>
<p>So in order to reliably check if PATH already contains a path, we need a way to convert any given path into a canonical (standard) form. The <code>~s</code> modifier used by FOR variable and argument expansion is a simple method that addresses issues 1 - 6, and partially addresses issue 7. The <code>~s</code> modifier removes enclosing quotes, but preserves internal quotes. Issue 7 can be fully resolved by explicitly removing quotes from all paths prior to comparison. Note that if a path does not physically exist then the <code>~s</code> modifier will not append the <code>\</code> to the path, nor will it convert the path into a valid 8.3 format.</p>
<p>The problem with <code>~s</code> is it converts relative paths into fully qualified paths. This is problematic for Issue 8 because a relative path should never match a fully qualified path. We can use FINDSTR regular expressions to classify a path as either fully qualified or relative. A normal fully qualified path must start with <code><letter>:<separator></code> but not <code><letter>:<separator><separator></code>, where <separator> is either <code>\</code> or <code>/</code>. UNC paths are always fully qualified and must start with <code>\\</code>. When comparing fully qualified paths we use the <code>~s</code> modifier. When comparing relative paths we use the raw strings. Finally, we never compare a fully qualified path to a relative path. This strategy provides a good practical solution for Issue 8. The only limitation is two logically equivalent relative paths could be treated as not matching, but this is a minor concern because relative paths are rare in a Windows PATH.</p>
<p>There are some additional issues that complicate this problem:</p>
<p>9) <strong>Normal expansion is not reliable when dealing with a PATH that contains special characters.</strong><br>
Special characters do not need to be quoted within PATH, but they could be. So a PATH like
<code>C:\THIS & THAT;"C:\& THE OTHER THING"</code> is perfectly valid, but it cannot be expanded safely using simple expansion because both <code>"%PATH%"</code> and <code>%PATH%</code> will fail.</p>
<p>10) <strong>The path delimiter is also valid within a path name</strong><br>
A <code>;</code> is used to delimit paths within PATH, but <code>;</code> can also be a valid character within a path, in which case the path must be quoted. This causes a parsing issue.</p>
<p>jeb solved both issues 9 and 10 at <a href="https://stackoverflow.com/questions/5471556/pretty-print-windows-path-variable-how-to-split-on-in-cmd-shell/5472168#5472168">'Pretty print' windows %PATH% variable - how to split on ';' in CMD shell</a> </p>
<p>So we can combine the <code>~s</code> modifier and path classification techniques along with my variation of jeb's PATH parser to get this nearly bullet proof solution for checking if a given path already exists within PATH. The function can be included and called from within a batch file, or it can stand alone and be called as its own inPath.bat batch file. It looks like a lot of code, but over half of it is comments.</p>
<pre><code>@echo off
:inPath pathVar
::
:: Tests if the path stored within variable pathVar exists within PATH.
::
:: The result is returned as the ERRORLEVEL:
:: 0 if the pathVar path is found in PATH.
:: 1 if the pathVar path is not found in PATH.
:: 2 if pathVar is missing or undefined or if PATH is undefined.
::
:: If the pathVar path is fully qualified, then it is logically compared
:: to each fully qualified path within PATH. The path strings don't have
:: to match exactly, they just need to be logically equivalent.
::
:: If the pathVar path is relative, then it is strictly compared to each
:: relative path within PATH. Case differences and double quotes are
:: ignored, but otherwise the path strings must match exactly.
::
::------------------------------------------------------------------------
::
:: Error checking
if "%~1"=="" exit /b 2
if not defined %~1 exit /b 2
if not defined path exit /b 2
::
:: Prepare to safely parse PATH into individual paths
setlocal DisableDelayedExpansion
set "var=%path:"=""%"
set "var=%var:^=^^%"
set "var=%var:&=^&%"
set "var=%var:|=^|%"
set "var=%var:<=^<%"
set "var=%var:>=^>%"
set "var=%var:;=^;^;%"
set var=%var:""="%
set "var=%var:"=""Q%"
set "var=%var:;;="S"S%"
set "var=%var:^;^;=;%"
set "var=%var:""="%"
setlocal EnableDelayedExpansion
set "var=!var:"Q=!"
set "var=!var:"S"S=";"!"
::
:: Remove quotes from pathVar and abort if it becomes empty
set "new=!%~1:"=!"
if not defined new exit /b 2
::
:: Determine if pathVar is fully qualified
echo("!new!"|findstr /i /r /c:^"^^\"[a-zA-Z]:[\\/][^\\/]" ^
/c:^"^^\"[\\][\\]" >nul ^
&& set "abs=1" || set "abs=0"
::
:: For each path in PATH, check if path is fully qualified and then do
:: proper comparison with pathVar.
:: Exit with ERRORLEVEL 0 if a match is found.
:: Delayed expansion must be disabled when expanding FOR variables
:: just in case the value contains !
for %%A in ("!new!\") do for %%B in ("!var!") do (
if "!!"=="" endlocal
for %%C in ("%%~B\") do (
echo(%%B|findstr /i /r /c:^"^^\"[a-zA-Z]:[\\/][^\\/]" ^
/c:^"^^\"[\\][\\]" >nul ^
&& (if %abs%==1 if /i "%%~sA"=="%%~sC" exit /b 0) ^
|| (if %abs%==0 if /i "%%~A"=="%%~C" exit /b 0)
)
)
:: No match was found so exit with ERRORLEVEL 1
exit /b 1
</code></pre>
<p>The function can be used like so (assuming the batch file is named inPath.bat):</p>
<pre><code>set test=c:\mypath
call inPath test && (echo found) || (echo not found)
</code></pre>
<p><br/>
<hr/>
Typically the reason for checking if a path exists within PATH is because you want to append the path if it isn't there. This is normally done simply by using something like <code>path %path%;%newPath%</code>. But Issue 9 demonstrates how this is not reliable.</p>
<p>Another issue is how to return the final PATH value across the ENDLOCAL barrier at the end of the function, especially if the function could be called with delayed expansion enabled or disabled. Any unescaped <code>!</code> will corrupt the value if delayed expansion is enabled.</p>
<p>These problems are resolved using an amazing safe return technique that jeb invented here: <a href="http://www.dostips.com/forum/viewtopic.php?p=6930#p6930" rel="noreferrer">http://www.dostips.com/forum/viewtopic.php?p=6930#p6930</a></p>
<pre><code>@echo off
:addPath pathVar /B
::
:: Safely appends the path contained within variable pathVar to the end
:: of PATH if and only if the path does not already exist within PATH.
::
:: If the case insensitive /B option is specified, then the path is
:: inserted into the front (Beginning) of PATH instead.
::
:: If the pathVar path is fully qualified, then it is logically compared
:: to each fully qualified path within PATH. The path strings are
:: considered a match if they are logically equivalent.
::
:: If the pathVar path is relative, then it is strictly compared to each
:: relative path within PATH. Case differences and double quotes are
:: ignored, but otherwise the path strings must match exactly.
::
:: Before appending the pathVar path, all double quotes are stripped, and
:: then the path is enclosed in double quotes if and only if the path
:: contains at least one semicolon.
::
:: addPath aborts with ERRORLEVEL 2 if pathVar is missing or undefined
:: or if PATH is undefined.
::
::------------------------------------------------------------------------
::
:: Error checking
if "%~1"=="" exit /b 2
if not defined %~1 exit /b 2
if not defined path exit /b 2
::
:: Determine if function was called while delayed expansion was enabled
setlocal
set "NotDelayed=!"
::
:: Prepare to safely parse PATH into individual paths
setlocal DisableDelayedExpansion
set "var=%path:"=""%"
set "var=%var:^=^^%"
set "var=%var:&=^&%"
set "var=%var:|=^|%"
set "var=%var:<=^<%"
set "var=%var:>=^>%"
set "var=%var:;=^;^;%"
set var=%var:""="%
set "var=%var:"=""Q%"
set "var=%var:;;="S"S%"
set "var=%var:^;^;=;%"
set "var=%var:""="%"
setlocal EnableDelayedExpansion
set "var=!var:"Q=!"
set "var=!var:"S"S=";"!"
::
:: Remove quotes from pathVar and abort if it becomes empty
set "new=!%~1:"^=!"
if not defined new exit /b 2
::
:: Determine if pathVar is fully qualified
echo("!new!"|findstr /i /r /c:^"^^\"[a-zA-Z]:[\\/][^\\/]" ^
/c:^"^^\"[\\][\\]" >nul ^
&& set "abs=1" || set "abs=0"
::
:: For each path in PATH, check if path is fully qualified and then
:: do proper comparison with pathVar. Exit if a match is found.
:: Delayed expansion must be disabled when expanding FOR variables
:: just in case the value contains !
for %%A in ("!new!\") do for %%B in ("!var!") do (
if "!!"=="" setlocal disableDelayedExpansion
for %%C in ("%%~B\") do (
echo(%%B|findstr /i /r /c:^"^^\"[a-zA-Z]:[\\/][^\\/]" ^
/c:^"^^\"[\\][\\]" >nul ^
&& (if %abs%==1 if /i "%%~sA"=="%%~sC" exit /b 0) ^
|| (if %abs%==0 if /i %%A==%%C exit /b 0)
)
)
::
:: Build the modified PATH, enclosing the added path in quotes
:: only if it contains ;
setlocal enableDelayedExpansion
if "!new:;=!" neq "!new!" set new="!new!"
if /i "%~2"=="/B" (set "rtn=!new!;!path!") else set "rtn=!path!;!new!"
::
:: rtn now contains the modified PATH. We need to safely pass the
:: value accross the ENDLOCAL barrier
::
:: Make rtn safe for assignment using normal expansion by replacing
:: % and " with not yet defined FOR variables
set "rtn=!rtn:%%=%%A!"
set "rtn=!rtn:"=%%B!"
::
:: Escape ^ and ! if function was called while delayed expansion was enabled.
:: The trailing ! in the second assignment is critical and must not be removed.
if not defined NotDelayed set "rtn=!rtn:^=^^^^!"
if not defined NotDelayed set "rtn=%rtn:!=^^^!%" !
::
:: Pass the rtn value accross the ENDLOCAL barrier using FOR variables to
:: restore the % and " characters. Again the trailing ! is critical.
for /f "usebackq tokens=1,2" %%A in ('%%^ ^"') do (
endlocal & endlocal & endlocal & endlocal & endlocal
set "path=%rtn%" !
)
exit /b 0
</code></pre>
|
<p>This routine will search for a path\ or file.ext in the path variable.
It returns 0 if found. Path\ or file may contain spaces if quoted.
If a variable is passed as the last argument, it will be set to <code>d:\path\file</code>.</p>
<pre><code>@echo off&goto :PathCheck
:PathCheck.CMD
echo.PathCheck.CMD: Checks for existence of a path or file in %%PATH%% variable
echo.Usage: PathCheck.CMD [Checkpath] or [Checkfile] [PathVar]
echo.Checkpath must have a trailing \ but checkfile must not
echo.If Checkpath contains spaces use quotes ie. "C:\Check path\"
echo.Checkfile must not include a path, just the filename.ext
echo.If Checkfile contains spaces use quotes ie. "Check File.ext"
echo.Returns 0 if found, 1 if not or -1 if checkpath does not exist at all
echo.If PathVar is not in command line it will be echoed with surrounding quotes
echo.If PathVar is passed it will be set to d:\path\checkfile with no trailing \
echo.Then %%PathVar%% will be set to the fully qualified path to Checkfile
echo.Note: %%PathVar%% variable set will not be surrounded with quotes
echo.To view the path listing line by line use: PathCheck.CMD /L
exit/b 1
:PathCheck
if "%~1"=="" goto :PathCheck.CMD
setlocal EnableDelayedExpansion
set "PathVar=%~2"
set "pth="
set "pcheck=%~1"
if "%pcheck:~-1%" equ "\" (
if not exist %pcheck% endlocal&exit/b -1
set/a pth=1
)
for %%G in ("%path:;=" "%") do (
set "Pathfd=%%~G\"
set "Pathfd=!Pathfd:\\=\!"
if /i "%pcheck%" equ "/L" echo.!Pathfd!
if defined pth (
if /i "%pcheck%" equ "!Pathfd!" endlocal&exit/b 0
) else (
if exist "!Pathfd!%pcheck%" goto :CheckfileFound
)
)
endlocal&exit/b 1
:CheckfileFound
endlocal&(
if not "%PathVar%"=="" (
call set "%~2=%Pathfd%%pcheck%"
) else (echo."%Pathfd%%pcheck%")
exit/b 0
)
</code></pre>
| 17,075
|
<p>What is an elegant way to sort objects in PHP? I would love to accomplish something similar to this.</p>
<pre><code>$sortedObjectArary = sort($unsortedObjectArray, $Object->weight);
</code></pre>
<p>Basically specify the array I want to sort as well as the field I want to sort on. I looked into multidimensional array sorting and there might be something useful there, but I don't see anything elegant or obvious.</p>
|
<p>Almost verbatim from the manual: </p>
<pre><code>function compare_weights($a, $b) {
if($a->weight == $b->weight) {
return 0;
}
return ($a->weight < $b->weight) ? -1 : 1;
}
usort($unsortedObjectArray, 'compare_weights');
</code></pre>
<p>If you want objects to be able to sort themselves, see example 3 here: <a href="http://php.net/usort" rel="noreferrer">http://php.net/usort</a></p>
|
<p>If you want to explore the full (terrifying) extent of lambda style functions in PHP, see:
<a href="http://docs.php.net/manual/en/function.create-function.php" rel="nofollow noreferrer">http://docs.php.net/manual/en/function.create-function.php</a></p>
| 15,116
|
<p>My company is using Python for a relatively simple embedded project. Is anyone else out there using Python on embedded platforms? Overall it's working well for us, quick to develop apps, quick to debug. I like the overall "conciseness" of the language.</p>
<p>The only real problem I have in day to day work is that the lack of static checking vs a regular compiler can cause problems to be thrown at run-time, e.g. a simple accidental cat of a string and an int in a print statement can bring the whole application down.</p>
|
<p>We use python in quite a lot of <a href="http://www.embeddedarm.com/products/arm-sbc.php" rel="noreferrer">embedded boards with ARM processors</a> and 16 MB of RAM (running linux).</p>
<p>It works really well and is really easy to make custom code quickly - one of the strong points of python.</p>
<p>As for reliability of the code - we try to have 100% test coverage. Writing tests with python is very quick and it gives you a wonderful feeling of confidence. We use <a href="http://twistedmatrix.com/trac/wiki/TwistedTrial" rel="noreferrer">twisted trial</a> to run the tests and report on coverage, but there are many other tools available.</p>
<p>In my experience python + tests is more reliable and much quicker to write than any other alternatives.</p>
<p>The only downsides for embedded work is that sometimes python can be slow and sometimes it uses a lot of memory (relatively speaking). This hasn't causes us a show stopping problem yet, and python is quite easy to profile for both speed and memory if it becomes a problem.</p>
<p><a href="http://pychecker.sourceforge.net/" rel="noreferrer">pychecker</a> is a very useful too also which will catch quite a lot of common errors.</p>
|
<blockquote>
<p>Blockquote
The only real problem I have in day to day work is that the last of static checking vs a regular compiler can cause problems to be thrown at run-time, e.g. a simple accidental cat of a string and an int in a print statement can bring the whole application down</p>
</blockquote>
<p>To me it is a huge deal. Problems you could find at compile time and fix the problem now have to rely at run time. Not knowing the data type and having to write additional function just to check the datatype is hassle. There is no need to do that in C. How would you declare 'volatile' in python?</p>
<blockquote>
<p>Blockquote
The only downsides for embedded work is that sometimes python can be slow and sometimes it uses a lot of memory (relatively speaking). This hasn't causes us a show stopping problem yet, and python is quite easy to profile for both speed and memory if it becomes a problem.</p>
</blockquote>
<p>This is also huge. For Embedded sytems or RTOS time constraint is very important.</p>
<p>Python is not necessary quick to code. It really depends what language you are comfortable with. Honestly it takes me 1 day to write function and unnecessary object orientation stuff which I can do in 2 hours in C.
Testing is so inconvenient I have to write the code, py_compile, copy pyc in the target then run the program, then python quits complaining variable not defined or type cast error or some petty thing like that.</p>
<p>My suggestion is C toolchain is available for any target. C is fast, hardware oriented,challenging and fun. Stick with C for Embedded systems. No need to install configure silly python packages just to run it. </p>
| 29,820
|
<p>I have seen many programs consisting of structures like the one below</p>
<pre><code>typedef struct
{
int i;
char k;
} elem;
elem user;
</code></pre>
<p>Why is it needed so often? Any specific reason or applicable area?</p>
|
<p>As Greg Hewgill said, the typedef means you no longer have to write <code>struct</code> all over the place. That not only saves keystrokes, it also can make the code cleaner since it provides a smidgen more abstraction.</p>
<p>Stuff like</p>
<pre><code>typedef struct {
int x, y;
} Point;
Point point_new(int x, int y)
{
Point a;
a.x = x;
a.y = y;
return a;
}
</code></pre>
<p>becomes cleaner when you don't need to see the "struct" keyword all over the place, it looks more as if there really is a type called "Point" in your language. Which, after the <code>typedef</code>, is the case I guess.</p>
<p>Also note that while your example (and mine) omitted naming the <code>struct</code> itself, actually naming it is also useful for when you want to provide an opaque type. Then you'd have code like this in the header, for instance:</p>
<pre><code>typedef struct Point Point;
Point * point_new(int x, int y);
</code></pre>
<p>and then provide the <code>struct</code> definition in the implementation file:</p>
<pre><code>struct Point
{
int x, y;
};
Point * point_new(int x, int y)
{
Point *p;
if((p = malloc(sizeof *p)) != NULL)
{
p->x = x;
p->y = y;
}
return p;
}
</code></pre>
<p>In this latter case, you cannot return the Point by value, since its definition is hidden from users of the header file. This is a technique used widely in <a href="http://www.gtk.org/" rel="noreferrer">GTK+</a>, for instance.</p>
<p><strong>UPDATE</strong> Note that there are also highly-regarded C projects where this use of <code>typedef</code> to hide <code>struct</code> is considered a bad idea, the Linux kernel is probably the most well-known such project. See Chapter 5 of <a href="https://www.kernel.org/doc/html/latest/process/coding-style.html#typedefs" rel="noreferrer">The Linux Kernel CodingStyle document</a> for Linus' angry words. :) My point is that the "should" in the question is perhaps not set in stone, after all.</p>
|
<p>At all, in C language, struct/union/enum are macro instruction processed by the C language preprocessor (do not mistake with the preprocessor that treat "#include" and other)</p>
<p>so :</p>
<pre><code>struct a
{
int i;
};
struct b
{
struct a;
int i;
int j;
};
</code></pre>
<p>struct b is expended as something like this :</p>
<pre><code>struct b
{
struct a
{
int i;
};
int i;
int j;
}
</code></pre>
<p>and so, at compile time it evolve on stack as something like:
b:
int ai
int i
int j</p>
<p>that also why it's dificult to have selfreferent structs, C preprocessor round in a déclaration loop that can't terminate.</p>
<p>typedef are type specifier, that means only C compiler process it and it can do like he want for optimise assembler code implementation. It also dont expend member of type par stupidly like préprocessor do with structs but use more complex reference construction algorithm, so construction like :</p>
<pre><code>typedef struct a A; //anticipated declaration for member declaration
typedef struct a //Implemented declaration
{
A* b; // member declaration
}A;
</code></pre>
<p>is permited and fully functional. This implementation give also access to compilator type conversion and remove some bugging effects when execution thread leave the application field of initialisation functions. </p>
<p>This mean that in C typedefs are more near as C++ class than lonely structs.</p>
| 31,491
|
<p>I am re-designing an application for a ASP.NET CMS that I really don't like. I have made som improvements in performance only to discover that not only does this CMS use MS SQL but some users "simply" use MS Access database.</p>
<p>The problem is that I have some tables which I inner join, that with the MS Access version are in two different files. I am not allowed to simply move the tables to the other mdb file.</p>
<p>I am now trying to figure out a good way to "inner join" across multiple access db files?</p>
<p>It would really be a pity if I have fetch all the data and the do it programmatically!</p>
<p>Thanks</p>
|
<p>You don't need linked tables at all. There are two approaches to using data from different MDBs that can be used without a linked table. The first is to use "IN 'c:\MyDBs\Access.mdb'" in the FROM clause of your SQL. One of your saved queries would be like:</p>
<pre><code>SELECT MyTable.*
FROM MyTable IN 'c:\MyDBs\Access.mdb'
</code></pre>
<p>and the other saved query would be:</p>
<pre><code>SELECT OtherTable.*
FROM OtherTable IN 'c:\MyDBs\Other.mdb'
</code></pre>
<p>You could then save those queries, and then use the saved queries to join the two tables.</p>
<p>Alternatively, you can manage it all in a single SQL statement by specifying the path to the source MDB for each table in the FROM clause thus:</p>
<pre><code>SELECT MyTable.ID, OtherTable.OtherField
FROM [c:\MyDBs\Access.mdb].MyTable
INNER JOIN [c:\MyDBs\Other.mdb].OtherTable ON MyTable.ID = OtherTable.ID
</code></pre>
<p>Keep one thing in mind, though:</p>
<p>The Jet query optimizer won't necessarily be able to use the indexes from these tables for the join (whether it will use them for criteria on individual fields is another question), so this could be extremely slow (in my tests, it's not, but I'm not using big datasets to test). But that performance issue applies to linked tables, too.</p>
|
<p>Within Access, you can add remote tables through the "Linked Table Manager". You could add the links to one Access file or the other, or you could create a new Access file that references the tables in both files. After this is done, the inner-join queries are no different than doing them in a single database. </p>
| 14,320
|
<p>I'm at step 8 of the authentication overview found here: <a href="http://wiki.developers.facebook.com/index.php/How_Connect_Authentication_Works" rel="noreferrer">http://wiki.developers.facebook.com/index.php/How_Connect_Authentication_Works</a></p>
<p>In particular, the user has logged into facebook via Facebook Connect and their web session has been created. How do I use the facebook developer toolkit v2.0 (from clarity) to retrieve information about the user. For example, I'd like to get the user's first name and last name.</p>
<p>Examples in the documentation are geared towards facebook applications, which this is not.</p>
<h2>Update</h2>
<p>Facebook recently released the Graph API. Unless you are maintaining an application that is using Facebook Connect, you should check out the latest API: <a href="http://developers.facebook.com/docs/" rel="noreferrer">http://developers.facebook.com/docs/</a></p>
|
<p>I had a lot of trouble figuring out how to make server side calls once a user logged in with Facebook Connect. The key is that the Facebook Connect javascript sets cookies on the client once there's a successful login. You use the values of these cookies to perform API calls on the server.</p>
<p>The confusing part was looking at the PHP sample they released. Their server side API automatically takes care of reading these cookie values and setting up an API object that's ready to make requests on behalf of the logged in user.</p>
<p>Here's an example using the <a href="http://www.codeplex.com/FacebookToolkit" rel="nofollow noreferrer">Facebook Toolkit</a> on the server after the user has logged in with Facebook Connect.</p>
<p>Server code:</p>
<pre><code>API api = new API();
api.ApplicationKey = Utility.ApiKey();
api.SessionKey = Utility.SessionKey();
api.Secret = Utility.SecretKey();
api.uid = Utility.GetUserID();
facebook.Schema.user user = api.users.getInfo();
string fullName = user.first_name + " " + user.last_name;
foreach (facebook.Schema.user friend in api.friends.getUserObjects())
{
// do something with the friend
}
</code></pre>
<p>Utility.cs</p>
<pre><code>public static class Utility
{
public static string ApiKey()
{
return ConfigurationManager.AppSettings["Facebook.API_Key"];
}
public static string SecretKey()
{
return ConfigurationManager.AppSettings["Facebook.Secret_Key"];
}
public static string SessionKey()
{
return GetFacebookCookie("session_key");
}
public static int GetUserID()
{
return int.Parse(GetFacebookCookie("user"));
}
private static string GetFacebookCookie(string name)
{
if (HttpContext.Current == null)
throw new ApplicationException("HttpContext cannot be null.");
string fullName = ApiKey() + "_" + name;
if (HttpContext.Current.Request.Cookies[fullName] == null)
throw new ApplicationException("Could not find facebook cookie named " + fullName);
return HttpContext.Current.Request.Cookies[fullName].Value;
}
}
</code></pre>
|
<p>My two cents: a <strong>very</strong> simple project utilizing the "login with Facebook" feature - <a href="http://facebooklogin.codeplex.com/" rel="nofollow">facebooklogin.codeplex.com</a></p>
<p>Not a library, but shows how it all works.</p>
| 41,803
|
<p>When I try to use the code below I get a duplicate variable error because variables are immutable. How do I set the smaller of the two variables (<code>$nextSubPartPos</code> and <code>$nextQuestionStemPos</code>) as my new variable (<code>$nextQuestionPos</code>)?</p>
<pre><code> <xsl:variable name="nextQuestionPos"/>
<xsl:choose>
<xsl:when test="$nextSubPartPos &lt; $nextQuestionStemPos">
<xsl:variable name="nextQuestionPos" select="$nextSubPartPos"/>
</xsl:when>
<xsl:otherwise>
<xsl:variable name="nextQuestionPos" select="$nextSubPartPos"/>
</xsl:otherwise>
</xsl:choose>
</code></pre>
|
<p>Don't close the xsl:variable node in the first line. That is, take the / out of it, then put an <code></xsl:variable></code> after <code></xsl:choose></code>. Next, change the <code><xsl:variable></code> nodes inside the choose to <code><xsl:value-of></code> nodes.</p>
<p>That is, you want to set the value of the variable with the choose. There are two ways to set the value of a variable. One is the select attribute, the other is the inner text of the node.</p>
<pre><code><xsl:variable name="nextQuestionPos">
<xsl:choose>
<xsl:when test="$nextSubPartPos &lt; $nextQuestionStemPos">
<xsl:value-of select="$nextSubPartPos"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$nextSubPartPos"/>
</xsl:otherwise>
</xsl:choose>
</xsl:variable>
</code></pre>
|
<p>Variables in XSLT are immutable. This has tripped me up so many times.</p>
| 41,135
|
<p>How do I list and export a private key from a keystore?</p>
|
<p>You can extract a private key from a keystore with Java6 and OpenSSL. This all depends on the fact that both Java and OpenSSL support PKCS#12-formatted keystores. To do the extraction, you first use <code>keytool</code> to convert to the standard format. Make sure you <strong><em>use the same password for both files (private key password, not the keystore password)</em></strong> or you will get odd failures later on in the second step.</p>
<pre><code>keytool -importkeystore -srckeystore keystore.jks \
-destkeystore intermediate.p12 -deststoretype PKCS12
</code></pre>
<p>Next, use OpenSSL to do the extraction to PEM:</p>
<pre><code>openssl pkcs12 -in intermediate.p12 -out extracted.pem -nodes
</code></pre>
<p>You should be able to handle that PEM file easily enough; it's plain text with an encoded unencrypted private key and certificate(s) inside it (in a pretty obvious format).</p>
<p><em>When you do this, take care to keep the files created secure. They contain secret credentials. Nothing will warn you if you fail to secure them correctly.</em> The easiest method for securing them is to do all of this in a directory which doesn't have any access rights for anyone other than the user. And never put your password on the command line or in environment variables; it's too easy for other users to grab.</p>
|
<p>Another less-conventional but arguably easier way of doing this is with <a href="http://jxplorer.org/" rel="nofollow">JXplorer</a>. Although this tool is designed to browse LDAP directories, it has an easy-to-use GUI for manipulating keystores. One such function on the GUI can export private keys from a JKS keystore.</p>
| 18,097
|
<p>When I run prints on my Creality CR-10S Pro 3D printer (using Ultimaker Cura as slicer), I set the heated bed to around 70 °C for PETG. after the first few layers, the heated bed set point changes to 0 °C. </p>
<p>Is it normal for a 3D printer to turn the heated bed off during a print, or is this a problem?</p>
<p>I have had some parts warping, and wonder if this is a potential cause.</p>
|
<p><strong>No</strong>, this is not common behavior, and <strong>yes</strong> this can cause your prints to warp or detach from the build plate.</p>
<p>The question is whether you instructed this (by accident) or not (e.g. it can be a result from slicing or some economy mode of the printer). This should be clear if you look into the G-code file that you print. The typical commands that concern bed heating are <a href="https://reprap.org/wiki/G-code#M140:_Set_Bed_Temperature_.28Fast.29" rel="nofollow noreferrer"><code>M140</code></a> and <a href="https://reprap.org/wiki/G-code#M190:_Wait_for_bed_temperature_to_reach_target_temp" rel="nofollow noreferrer"><code>M190</code></a>.</p>
<p>Please note that this a generic answer to find bed heating operation in your G-code file. Other answers, e.g <a href="/a/8425/">this one</a> and <a href="/a/8285/">this one</a> hint to a specific ability of the printer that shuts off the heating of the bed when it is working in an economic mode. Note that this is printer specific.</p>
|
<p>That is not normal behavior for the heated beds. I don't have that exact model, but when I print the heated bed will stay to whatever temp was set in the slicer program. Unless you override it manually on the printer itself during the print. I would check slicer settings ensuring temp doesn't change after it's first layers. </p>
| 1,205
|
<p>Sybase db tables do not have a concept of self updating row numbers. However , for one of the modules , I require the presence of rownumber corresponding to each row in the database such that max(Column) would always tell me the number of rows in the table.</p>
<p>I thought I'll introduce an int column and keep updating this column to keep track of the row number. However I'm having problems in updating this column in case of deletes. What sql should I use in delete trigger to update this column? </p>
|
<p>You can easily assign a unique number to each row by using an identity column. The identity can be a numeric or an integer (in ASE12+).</p>
<p>This will <em>almost</em> do what you require. There are certain circumstances in which you will get a gap in the identity sequence. (These are called "identity gaps", the best discussion on them is <a href="http://www.sypron.nl/idgaps.html" rel="nofollow noreferrer">here</a>). Also deletes will cause gaps in the sequence as you've identified.</p>
<p>Why do you need to use max(col) to get the number of rows in the table, when you could just use count(*)? If you're trying to get the last row from the table, then you can do</p>
<pre><code>select * from table where column = (select max(column) from table).
</code></pre>
<p>Regarding the delete trigger to update a manually managed column, I think this would be a potential source of deadlocks, and many performance issues. Imagine you have 1 million rows in your table, and you delete row 1, that's 999999 rows you now have to update to subtract 1 from the id.</p>
|
<p>I'm not sure why you would want to do this. You could experiment with using temporary tables and <a href="http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.help.ase_12.5.sqlug/html/sqlug/sqlug345.htm" rel="nofollow noreferrer">"select into" with an Identity column</a> like below.</p>
<pre><code>create table test
(
col1 int,
col2 varchar(3)
)
insert into test values (100, "abc")
insert into test values (111, "def")
insert into test values (222, "ghi")
insert into test values (300, "jkl")
insert into test values (400, "mno")
select rank = identity(10), col1 into #t1 from Test
select * from #t1
delete from test where col2="ghi"
select rank = identity(10), col1 into #t2 from Test
select * from #t2
drop table test
drop table #t1
drop table #t2
</code></pre>
<p>This would give you a dynamic id (of sorts)</p>
| 22,063
|
<p>I have binary data in a file that I can read into a byte array and process with no problem. Now I need to send parts of the data over a network connection as elements in an XML document. My problem is that when I convert the data from an array of bytes to a String and back to an array of bytes, the data is getting corrupted. I've tested this on one machine to isolate the problem to the String conversion, so I now know that it isn't getting corrupted by the XML parser or the network transport.</p>
<p>What I've got right now is</p>
<pre><code>byte[] buffer = ...; // read from file
// a few lines that prove I can process the data successfully
String element = new String(buffer);
byte[] newBuffer = element.getBytes();
// a few lines that try to process newBuffer and fail because it is not the same data anymore
</code></pre>
<p>Does anyone know how to convert binary to String and back without data loss?</p>
<p>Answered: Thanks Sam. I feel like an idiot. I had this answered yesterday because my SAX parser was complaining. For some reason when I ran into this seemingly separate issue, it didn't occur to me that it was a new symptom of the same problem.</p>
<p>EDIT: Just for the sake of completeness, I used the <a href="http://commons.apache.org/codec/apidocs/org/apache/commons/codec/binary/Base64.html" rel="noreferrer">Base64</a> class from the <a href="http://commons.apache.org/" rel="noreferrer">Apache Commons</a> <a href="http://commons.apache.org/codec/" rel="noreferrer">Codec</a> package to solve this problem.</p>
|
<p>If you encode it in base64, this will turn any data into ascii safe text, but base64 encoded data is larger than the orignal data</p>
|
<p>How are you building your XML document? If you use java's built in XML classes then the string encoding should be handled for you.</p>
<p>Take a look at the javax.xml and org.xml packages. That's what we use for generating XML docs, and it handles all the string encoding and decoding quite nicely.</p>
<p>---EDIT:</p>
<p>Hmm, I think I misunderstood the problem. You're not trying to encode a regular string, but some set of arbitrary binary data? In that case the Base64 encoding suggested in an earlier comment is probably the way to go. I believe that's a fairly standard way of encoding binary data in XML.</p>
| 4,110
|
<p>I am implementing exception handling for our BizTalk services, and have run into a fairly major stumbling block.</p>
<p>In order to make the exception processing as generic as possible, and therefore to allow us to use it for any BizTalk application, our XML error schema includes an xs:any node, into which we can place a variety of data, depending on the actual exception. The generated XML should then be presented to a user through an InfoPath 2003 form for manual intervention before being represented back to BizTalk.</p>
<p>The problem is that InfoPath 2003 doesn't like schemas with an xs:any node. What we'd really like to do is the show the content of the exception report in a form with all relevant parameters mapped , and the entire content of the xs:any node in a text box, since users who are able to see these messages will be conversant with XML. Unfortunately, I am unable to make InfoPath even load the schema at design time.</p>
<p>Does anyone have any recommendation for how to achieve what we need, please?</p>
|
<p>Does your xs:any element have a minOccurs > 0?</p>
<p><a href="http://msdn.microsoft.com/en-us/library/bb251017.aspx#UnsupportedConstructs" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/bb251017.aspx#UnsupportedConstructs</a></p>
<p>I've also read that due to the way that InfoPath works, it can not handly more than one schema for each namespace. Hence, your xs:any (and the sequence that it defines) should have a unique namespace.</p>
|
<p>Does your xs:any element have a minOccurs > 0?</p>
<p><a href="http://msdn.microsoft.com/en-us/library/bb251017.aspx#UnsupportedConstructs" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/bb251017.aspx#UnsupportedConstructs</a></p>
<p>I've also read that due to the way that InfoPath works, it can not handly more than one schema for each namespace. Hence, your xs:any (and the sequence that it defines) should have a unique namespace.</p>
| 5,834
|
<p>Is it really viable to use GCJ to publish server-side applications? Webapps? </p>
<p>My boss is convinced that compiling our (<strong><em>my</em></strong>) webapp into a binary executable is a brilliant idea. (Then again, he likes nice, small simple things with blinky lights that he can understand.) He instinctively sees no issues with this, while I only see an endless series of problems and degradations. Once I start talking to him about the complexity of our platform, and more in depth specifics of byte code, JVMs, libraries, differences between operating systems, processor architectures, etc...well...his eyes glaze over, he smiles and he has made it clear he thinks I'm being childishly resistive.</p>
<p>Why does he want a single magic executable? He sees a couple of "benefits":</p>
<ul>
<li>If it is a binary executable, then it is hard to reverse engineer and circumvent any licensing. Management lives in constant fear that this is happening, even though we sell into larger corporates who generally do not do cheat with server software. </li>
<li>There is that vision of downloading this magic executable, running it, and everything works. (No more sending me out to do customer installations, which is not that frequent.)</li>
</ul>
<p>So, I've done my obligatory 20 minutes of googling, and now I am here. </p>
<p>A bit of background on my application: </p>
<p><strong>What it is made from:</strong></p>
<ul>
<li>Java 6 (Sun's JVM)</li>
<li>AspectJ 1.6</li>
<li>Tomcat 6</li>
<li>Hibernate 3</li>
<li>Spring 2</li>
<li>another two dozen supporting jar files</li>
</ul>
<p><strong>What it does</strong></p>
<ul>
<li>A streaming media CMS</li>
<li>Performance sensitive</li>
<li>Deployed on Linux, Solaris, Windows (and developed on a Mac)</li>
</ul>
<p>As you can probably gather, I'm highly skeptical of this <em>"compiling Java to native code"</em> thing. It sound like where Mono (VB on Linux) was back in 2000. But am I being overly pessimistic? Is it viable? Should I actually spend the time (days if not weeks) to try this out?</p>
<p>There is one other similar thread (<a href="https://stackoverflow.com/questions/53845/java-compiler-options-to-produce-exe-files">Java Compiler Options to produce .exe files</a>) but it is a bit too simple, the links dated, and not really geared towards a server-side question.</p>
<p>Your informed opinions will be highly cherished, my dear SOpedians! TIA!</p>
|
<p>FWIW: I have never had good luck with GCJ, I have had a lot of problems using it and have had some obscure issues pop up that took forever to diagnose to GCJ rather than me (I am always very very reluctant to blame things on external libraries). I will openly admit this happened several years ago and I have never wanted to go near GCJ again. To give that more substance this was while I was in school and was working on a mostly trivial program so on an <em>"enterprise level"</em> I have had a healthy fear of GCJ.</p>
|
<p>I don't think that a large application like yours will compile to machine code. Remember that java is not only java syntax (might compile to machine code) but also a virtual machine which is more like an application / process environment. I would suggest making an <a href="http://classworlds.codehaus.org/uberjar.html" rel="nofollow noreferrer">uberjar</a> or like that instead.</p>
| 9,071
|
<p>Has anyone used <a href="http://www.ayende.com/Blog/archive/2007/09/03/Rhino-Igloo-ndash-MVC-Framework-for-Web-Forms.aspx" rel="nofollow noreferrer">Rhino igloo</a> in a non-trivial project? I am curious if it's worth, what are its drawbacks, does it enhance testability a lot, is it easy to use. How would you compare it to a pure MVC framework (ASP.NET MVC)? Please share the experience.</p>
|
<p>If you want, you can translate this VB.Net code to C#. The theory here is that you change the size of a tab in the control.</p>
<pre><code>Private Declare Function SendMessage _
Lib "user32" Alias "SendMessageA" _
(ByVal handle As IntPtr, ByVal wMsg As Integer, _
ByVal wParam As Integer, ByRef lParam As Integer) As Integer
Private Sub SetTabStops(ByVal ctlTextBox As TextBox)
Const EM_SETTABSTOPS As Integer = &HCBS
Dim tabs() As Integer = {20, 40, 80}
SendMessage(ctlTextBox.Handle, EM_SETTABSTOPS, _
tabs.Length, tabs(0))
End Sub
</code></pre>
<p>I converted a version to C# for you, too. Tested and working in VS2005.</p>
<p>Add this using statement to your form: </p>
<pre><code>using System.Runtime.InteropServices;
</code></pre>
<p>Put this right after the class declaration:</p>
<pre><code> private const int EM_SETTABSTOPS = 0x00CB;
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr SendMessage(IntPtr h, int msg, int wParam, int[] lParam);
</code></pre>
<p>Call this method when you want to set the tabstops:</p>
<pre><code> private void SetTabStops(TextBox ctlTextBox)
{
const int EM_SETTABSTOPS = 203;
int[] tabs = { 100, 40, 80 };
SendMessage(textBox1.Handle, EM_SETTABSTOPS, tabs.Length, tabs);
}
</code></pre>
<p>To use it, here is all I did:</p>
<pre><code> private void Form1_Load(object sender, EventArgs e)
{
SetTabStops(textBox1);
textBox1.Text = "Hi\tWorld";
}
</code></pre>
|
<p>Don't the text boxes allow HTML usage? If that is the case, just use HTML to format the text into a table. Otherwise, try adding the text to a datagrid and then adding that to the form.</p>
| 9,782
|
<p>Yeah, I know the title is a mouthful...</p>
<p>What I mean is to say is how do you communicate with a subject matter expert who needs a theory coded and tested?</p>
<p>For example, weather simulation is a collaboration between meteorologists, computer scientists, and software engineers. The computer scientists and software engineers generally speak the same language, but he meteorologist is in a completely different world.</p>
<p>How do you increase the level of communication and understanding between disciplines? And not necessarily just for weather, other sciences too.</p>
|
<p>The shortest possible answer is Continuous customer involvement. </p>
<p>All the pretty UML diagrams, crayola UI mockups, explanations-to-four-year-olds and other techniques will never give the full experience of using a working application. Keeping the consumer in the loop allows for a feedback cycle both to the client, and from the client to you. This symbiotic relationship has the greatest likelyhood of producing a product that will be useful to them.</p>
<p>If you go into a box and come out with a product that you think they need it will likely be a whole lot of what they don't want. By regularly demoing your product you limit the impact of any misunderstanding, so that you don't spend too much time going down the wrong path.</p>
<p>It can be compared to dead reckoning. If you blindfold yourself and try to navigate through an area you know, the error between where you are and where you think you are will accumulate with time. If, however, you take off the blindfold periodically you can update your mental location. There will still be an error factor, but you are eliminating the accumulating error factor.</p>
<p>Even if you think your communication/explanatory skills are top notch, you still have to account for error in the way they communicate. </p>
|
<p>With great care and patience. You cannot assume understanding so use a technique like prototyping or pictures to communicate.</p>
<p>When the customer makes a statement you need to implement what you think he says, or draw a picture of it and show him. It is easier for him to recognize your misunderstandings this way. I would avoid long written descriptions because its very difficult to know if you understand.</p>
<p>The customer should not need to know your language, so do not try to teach the meteorologist the CS lingo. You need to learn his language. Even the most trivial requirement should be tested with a prototype. If they say: "We need to see a map of the US", then you need to draw a map of the US and show them and say "Is this what you want to see"? He's then going to say "But I can't see the mississipi river on this map" then you say "but you didn't ask for rivers" Then go back and re draw the map. etc etc.</p>
<p>I have had situations with much simpler requirements that went horribly wrong because the customer assumed that it was simple and I assumed that I understood.</p>
| 33,062
|
<p>Is there an API to access Subversion from C#?</p>
|
<p><a href="http://www.pumacode.org/projects/svndotnet/" rel="nofollow noreferrer"><strong>Svn.NET</strong></a> is a continuation (fork) of <a href="http://www.softec.st/en/OpenSource/ClrProjects/SubversionSharp/SubversionSharp.html" rel="nofollow noreferrer">SubversionSharp</a> mentioned in <a href="https://stackoverflow.com/users/5445/cms">CMS</a>'s <a href="https://stackoverflow.com/questions/287862/subversion-access-from-net#287869">answer</a>. SubversionSharp is limited to the .NET 1.1 platform.</p>
<p>Svn.NET supports the following platforms:</p>
<ul>
<li>.NET 2.0 on Windows Platforms</li>
<li>Mono on Win32 (2.0 framework)</li>
<li>Mono on Linux (2.0 framework)</li>
</ul>
|
<p>Check <a href="http://www.softec.st/en/OpenSource/ClrProjects/SubversionSharp/SubversionSharp.html" rel="nofollow noreferrer">SubversionSharp</a>, its basically a C# wrapper library that fully covers the client API of Subversion.</p>
| 36,630
|
<p>I would like to know your experience when you need to take over somebody else's software project - more so when the original software developer has already resigned.</p>
|
<p>The most success that we've had with that is to "wiki" everything. During the notice period ask the leaving developer to help you document everything in the team/company wiki and see if you can do code reviews with him/her and add comments to the code while doing the reviews that explain sections. Best for the "taking over" developer to write the comments in the code under the supervision of the leaver.</p>
|
<p>We actually have a specified set of "Deliverables" that has to be present for us to take over a project.</p>
<p>If we have the chance we try to push in one of our folks within the group developing the project at first. That way we get some firsthand knowledgde before our group takes over the code. (in the line of what @Guy wrote)</p>
<p>That being said, the most important part for me would be:</p>
<ul>
<li>Some kind og highlevel overview(drawing?) of what the code do.</li>
<li>Easy access to ask questions of the people who actually wrote the code</li>
</ul>
<p>This for me is alpha omega when taking over code and projects</p>
| 15,286
|
<p>Can you use windows hooks or other methods to do code injection with c#? I've seen lots of things about code injection but all of them are done in C/C++. I don't know either of those languages and have a really hard time translating. Does anyone have any ideas on how to do this?</p>
|
<p>Kevin,
it is possible. You can create library with window hook proc using managed C++. All you need to do is to inject this hook into some application using standard WinAPI (SetWindowsHookEx etc.). Inside this hook you can call System::AppDomain::CurrentDomain->Load method to load your assembly into target application's AppDomain. Then you can call methods defined in your assembly using reflection. For example, <a href="https://web.archive.org/web/20081228210203/http://blois.us/Snoop/" rel="nofollow noreferrer">Snoop</a> uses this method.</p>
|
<p>Mike Stall has <a href="http://blogs.msdn.com/jmstall/archive/2006/09/28/managed-create-remote-thread.aspx" rel="nofollow noreferrer">this sample</a>, that uses CreateRemoteThread. It has the advantage of not requiring any C++. </p>
| 4,397
|
<p>The MSI stores the installation directory for the future uninstall tasks.</p>
<p>Using the <code>INSTALLPROPERTY_INSTALLLOCATION</code> property (that is <code>"InstallLocation"</code>) works only the installer has set the <code>ARPINSTALLLOCATION</code> property during the installation. But this property is optional and almost nobody uses it.</p>
<p>How could I retrieve the installation directory?</p>
|
<p>Use a registry key to keep track of your install directory, that way you can reference it when upgrading and removing the product.</p>
<p>Using WIX I would create a Component that creates the key, right after the Directy tag of the install directory, declaration</p>
|
<p>I would try to use Installer.OpenProduct(productcode). This opens a session, on which you can then ask for Property("TARGETDIR").</p>
| 31,938
|
<p>I seem to be missing something about LINQ. To me, it looks like it's taking some of the elements of SQL that I like the least and moving them into the C# language and using them for other things.</p>
<p>I mean, I could see the benefit of using SQL-like statements on things other than databases. But if I wanted to write SQL, well, why not just write SQL and keep it out of C#? What am I missing here?</p>
|
<p>LINQ is not about SQL. LINQ is about being apply functional programming paradigmns on objects.</p>
<p>LINQ to SQL is an ORM built ontop of the LINQ foundation, but LINQ is much more. I don't use LINQ to SQL, yet I use LINQ all the time.</p>
<p>Take the task of finding the intersection of two lists:</p>
<p>Before LINQ, this tasks requires writing a nested foreach that iterates the small list once for every item in the big list O(N*M), and takes about 10 lines of code.</p>
<pre><code>foreach (int number in list1)
{
foreach (int number2 in list2)
{
if (number2 == number)
{
returnList.add(number2);
}
}
}
</code></pre>
<p>Using LINQ, it does the same thing in one line of code:</p>
<pre><code>var results = list1.Intersect(list2);
</code></pre>
<p>You'll notice that doesn't look like LINQ, yet it is. You don't need to use the expression syntax if you don't want to.</p>
|
<p>The point is that LINQ integrates your queries into your primary programming language, allowing your IDE to provide you with some facilities (Intellisense and debug support, for example) that you otherwise would not have, and to allow the compiler to type-check your SQL code (which is impossible with a normal string query).</p>
| 4,151
|
<p>I've heard that enabling Link-Time Code Generation (the /LTCG switch) can be a major optimization for large projects with lots of libraries to link together. My team is using it in the Release configuration of our solution, but the long compile-time is a real drag. One change to one file that no other file depends on triggers another 45 seconds of "Generating code...". Release is certainly much faster than Debug, but we might achieve the same speed-up by disabling LTCG and just leaving /O2 on.</p>
<p>Is it worth it to leave /LTCG enabled?</p>
|
<p>It is hard to say, because that depends mostly on your project - and of course the quality of the LTCG provided by VS2005 (which I don't have enough experience with to judge). In the end, you'll have to measure.</p>
<p>However, I wonder why you have that much problems with the extra duration of the release build. You should only hand out reproducible, stable, versioned binaries that have reproducible or archived sources. I've rarely seen a reason for frequent, incremental release builds.</p>
<p>The recommended setup for a team is this:
Developers typically create only incremental debug builds on their machines. Building a release should be a complete build from source control to redistributable (binaries or even setup), with a new version number and labeling/archiving the sources. Only these should be given to in-house testers / clients. </p>
<p>Ideally, you would move the complete build to a separate machine, or maybe a virtual machine on a good PC. This gives you a stable environment for your builds (includes, 3rd party libraries, environment variables, etc.).</p>
<p>Ideally, these builds should be automated ("one click from source control to setup"), and should run daily.</p>
|
<p>I also don't see problems with extra compilation time using link-time code generation with the release build. I only build my release version once per day (overnight), and use the unit-test and debug builds during the day.</p>
| 36,753
|
<p>In this sentence:</p>
<pre><code>myCommand.ExecuteReader(CommandBehavior.CloseConnection)
</code></pre>
<p>does it close connection in case of exception?</p>
|
<p>There are plenty of ways that the command can go wrong.</p>
<p>Ultimately it is the Close method of the data reader that will close the connection, provided nothing has gone wrong before.</p>
<p>If there is an exception that occurs inside ExecuteReader or any of its called methods, before the actual DataReader object is constructed, then no, the connection will not be closed.</p>
<p>In case of an exception, I wouldn't trust it to close the connection.</p>
|
<p>It depends where the exception occurs!</p>
<p>If you structure your try catch correctly, it will be fine.</p>
<p>For example:</p>
<pre><code>SqlCommand myCommand = new SqlCommand();
try
{
myCommand.dostuff();
}
catch(Exception ex)
{
// display error message
}
finally
{
myCommand.ExecuteReader(CommandBehavior.CloseConnection);
}
</code></pre>
<p>If the line: myCommand.ExecuteReader(CommandBehavior.CloseConnection) fails (perhaps the database has gone down?) then the connection cannot be closed programmatically.</p>
| 27,230
|
<p>I have the following in a page e.g. <code>/mypage?myvar=oldvalue</code></p>
<pre><code>$_SESSION['myvar'] = $_GET['myvar'];
$myvar = 'a_new_string'
</code></pre>
<p>Now <code>$_SESSION['myvar']</code> has the value <code>'a_new_string'</code></p>
<p>Is this by design?</p>
<p>How can I copy the <em>value</em> of <code>'myvar'</code> rather than a reference to it?</p>
|
<p>register_globals is the invention of the devil. Fortunately in PHP 6.0 it will be entirely disabled. It wasn't just a huge security problem, it makes people confuse. Please turn it off in your php.ini using
register_globals = Off
More information: <a href="http://us2.php.net/register_globals" rel="nofollow noreferrer">http://us2.php.net/register_globals</a>
Also you can check the current settings with the command
if (ini_get(register_globals)) echo "turn it off! :)';</p>
|
<p>After running this:</p>
<pre><code><?php
session_start();
$_GET['myvar'] = '';
$_SESSION['myvar'] = $_GET['myvar'];
$myvar = 'a_new_string';
var_dump($_SESSION);
?>
</code></pre>
<p>on PHP 5.2.6 I get this:</p>
<pre><code>array(1) { ["myvar"]=> string(0) "" }
</code></pre>
| 38,732
|
<p>Is there a way in MySQL 5 to show only the current user's processes(queries)?</p>
<p>The user has the <code>PROCESS</code> privilege, therefore <code>SHOW PROCESSLIST</code> displays running processes of all users. According to the documentation, <code>SHOW PROCESSLIST</code> does not allow any kind of <code>WHERE</code> syntax, nor did I manage to make it into a subquery.</p>
<p>Of course, I could simply send the query, e.g. in a PHP script, and go through the results in a loop, discarding everything that's not mine, but it seems rather inefficient. Changing the user privileges is not feasible.</p>
<p>Are there any other ways? Thanks in advance.</p>
|
<p>If you use MySQL 5.1.7 or newer, you can use the <a href="http://dev.mysql.com/doc/refman/5.1/en/processlist-table.html" rel="noreferrer">PROCESSLIST</a> table in the INFORMATION_SCHEMA. So you can query it with ordinary <code>SELECT</code> queries and apply filtering conditions in a <code>WHERE</code> clause.</p>
<p>This feature is not implemented in MySQL 5.0 and prior.</p>
|
<p>If the user does not have <code>PROCESS</code>, then <code>SHOW PROCESSLIST</code> will only show their own threads.</p>
| 43,338
|
<p>Guys, I’ve been writing code for 15+ years, but managed to avoid “Web Development” until 3 months ago.</p>
<p>I have inherited a legacy Asp.net application (started in .net 1.1, we’re now on .Net 2.0), it’s the administration tool for our product.</p>
<p>In several places the admin tool simply maintains long lists of values.</p>
<p>The list (could be 200+ items) appear in a GridView (Page A), user clicks an edit button for an item, this brings them to an edit page for the item (Page B) where they can change the value (or values, an item in the list may be associated with several values e.g. name and address and preferred colour, breed of cat . . .)</p>
<p>Currently when the user presses “Save” on Page B, we redirect back to Page A. The page opens at the top of the list, this annoys the user as often several items in sequence will need to be configured together, and the user needs to 1. Remember which item they just edited, 2. scroll down to that item</p>
<p>What I want to do is have the list bring the user back to the item they just edited, as often several items in sequence will need to be configured together.</p>
<p><strong>Fastest Gun Stop</strong> . . . and keep reading</p>
<ol>
<li>Suggestions on the lines of “regroup the items so there are fewer in the list” will be considered unhelpful</li>
<li>Valid points that .Net 3.5 does this automatically, will be considered unhelpful by me (but post them anyway, it may help some other poor fool)</li>
<li>I think I could do this by posting the Id of the edited item when re-loading Page A, and scrolling the grid to this point, however <strong>My Question is</strong> . . .</li>
</ol>
<p>Is there a feature to do this that I don’t know about (and what is it)
and/or<br>
What is the accepted way of doing this?</p>
<p>Thanks in advance
B. Worrier</p>
|
<p>This could be achieved using Anchor Tags.
When you output your elements on Page A, set an anchor tag next to each element like follows:</p>
<pre><code><a name="#175"></a>
</code></pre>
<p>Where this item would be item id 175.
Then when you redirect back to PageA, add a "#175" onto the end of the url</p>
<pre><code>Response.Redirect("PageA.aspx#175");
</code></pre>
|
<p>The simplest way you can do is to pass back an id from PageB in the querystring in the URL while redirecting back to PageA after saving in PageB.</p>
<p>e.g. www.example.com/PageA.aspx?editedId=89</p>
<p>and in PageLoad of PageA, you can check if this is from the editing detail page by examineing whether there is a valid value in HttpContext.Current.QueryStrubg["editedId"],
if there was, it means it is from PageB.
You can use this value to highlight or select the row in the datagrid easily</p>
<p><strong>Fastest Gun Stop . . .</strong> and keep reading...</p>
<p>A good control allows you to edit multiple rows at the same time on same page for example on PageA, and save them together. Check you Telerik control for datagrid. You'd love it.</p>
| 27,830
|
<p>What is the simplest (shortest, fewest rules, and no warnings) way to parse both valid dates and numbers in the same grammar? My problem is that a lexer rule to match a valid month (1-12) will match any occurrence of 1-12. So if I just want to match a number, I need a parse rule like:</p>
<pre><code>number: (MONTH|INT);
</code></pre>
<p>It only gets more complex when I add lexer rules for day and year. I want a parse rule for date like this:</p>
<pre><code>date: month '/' day ( '/' year )? -> ^('DATE' year month day);
</code></pre>
<p>I don't care if month,day & year are parse or lexer rules, just so long as I end up with the same tree structure. I also need to be able to recognize numbers elsewhere, e.g.:</p>
<pre><code>foo: STRING OP number -> ^(OP STRING number);
STRING: ('a'..'z')+;
OP: ('<'|'>');
</code></pre>
|
<p>The problem is that you seem to want to perform both syntactical and semantical checking in your lexer and/or your parser. It's a common mistake, and something that is only possible in very simple languages.</p>
<p>What you really need to do is accept more broadly in the lexer and parser, and then perform semantic checks. How strict you are in your lexing is up to you, but you have two basic options, depending on whether or not you need to accept zeroes preceding your days of the month: 1) Be really accepting for your INTs, 2) define DATENUM to only accept those tokens that are valid days, yet not valid INTs. I recommend the second because there will be less semantic checks necessary later in the code (since INTs will then be verifiable at the syntax level and you'll only need to perform semantic checks on your dates. The first approach:</p>
<pre><code>INT: '0'..'9'+;
</code></pre>
<p>The second approach:</p>
<pre><code>DATENUM: '0' '1'..'9';
INT: '0' | SIGN? '1'..'9' '0'..'9'*;
</code></pre>
<p>After accepting using these rules in the lexer, your date field would be either:</p>
<pre><code>date: INT '/' INT ( '/' INT )?
</code></pre>
<p>or:</p>
<pre><code>date: (INT | DATENUM) '/' (INT | DATENUM) ('/' (INT | DATENUM) )?
</code></pre>
<p>After that, you would perform a semantic run over your AST to make sure that your dates are valid.</p>
<p>If you're dead set on performing semantic checks in your grammar, however, ANTLR allows semantic predicates in the parser, so you could make a date field that checks the values like this:</p>
<pre><code>date: month=INT '/' day=INT ( year='/' INT )? { year==null ? (/* First check /*) : (/* Second check */)}
</code></pre>
<p>When you do this, however, you are embedding language specific code in your grammar, and it won't be portable across targets.</p>
|
<p>Using ANTLR4, here is a simple combined grammar that I used. It makes use of the lexer to match simple tokens only, leaving the parser rules to interpret dates vs numbers. </p>
<pre><code>// parser rules
date
: INT SEPARATOR month SEPARATOR INT
| INT SEPARATOR month SEPARATOR INT4
| INT SEPARATOR INT SEPARATOR INT4;
month : JAN | FEB | MAR | APR | MAY | JUN | JUL | AUG | SEP | OCT | NOV | DEC ;
number : FLOAT | INT | INT4 ;
// lexer rules
FLOAT : DIGIT+ '.' DIGIT+ ;
INT4 : DIGIT DIGIT DIGIT DIGIT;
INT : DIGIT+;
JAN : [Jj][Aa][Nn] ;
FEB : [Ff][Ee][Bb] ;
MAR : [Mm][Aa][Rr] ;
APR : [Aa][Pp][Rr] ;
MAY : [Mm][Aa][Yy] ;
JUN : [Jj][Uu][Nn] ;
JUL : [Jj][Uu][Ll] ;
AUG : [Aa][Uu][Gg] ;
SEP : [Ss][Ee][Pp] ;
OCT : [Oo][Cc][Tt] ;
NOV : [Nn][Oo][Vv] ;
DEC : [Dd][Ee][Cc] ;
SEPARATOR : [/\\\-] ;
fragment DIGIT : [0-9];
</code></pre>
| 17,150
|
<p><strong><em>Skunk Works Project</em></strong>: A project carried out by one part of a company without the knowledge of the remainder of the company.</p>
<p>Looking for stories about any skunk works projects you've worked on or initiated:</p>
<ul>
<li>Was it successful? </li>
<li>Were you found out? </li>
<li>Were you punished or rewarded? </li>
<li>How did you fund it? </li>
<li>How did you staff it? </li>
<li>How long did it take to finish, compared to above-ground projects? </li>
<li>What was the cost, compared to above-ground projects? </li>
<li>Was it formally adopted?</li>
</ul>
|
<p>Excellent question. Very important question.</p>
<p>Geoffrey Moore (Inside the Tornado, Crossing the Chasm, etc.) has written that, as he lectured around the world, he had one question he would ask every client (including those like GE, Motorola, etc.)</p>
<p>The question was:</p>
<p><strong>"Can you give me even one example of a truly ground-breaking, paradigm shifting innovation that has ever come out of your company's research or product development process?"</strong></p>
<p>At least at the point where I read the quote, <strong>not one example</strong> had been identified. And in most cases, such products or services had been conceived, designed, and largely developed by small groups of people who at best were <strong>ignored</strong>, but were often <strong>actively opposed</strong> by R&D.</p>
|
<p>I did one of these. It's actually how I ended up programming. </p>
<p>I was responsible for maintaining a legacy, er... "database". I won't go into gory details but it was the usual evil application. The company pretty much ran on it, it would sometimes go down for days. At the time the IS director (a friend) was actively looking for replacements, talking to large consulting organizations, etc.etc. but management was committted/emotionally invested in the existing system. I volunteered (to the IS director) to try to rewrite is (well, more like he asked if anyone was interested in trying to deal with this mess and I volunteered because I was bored). We had no real programmers on staff, and I'd only written a few small ad-hoc things. I had no idea how little I knew. </p>
<p>Finished the thing in about 8 months or maybe a year (this was a while ago, don't remember exactly). </p>
<p><strong>Was it successful?</strong>
yes, worked as advertised.</p>
<p><strong>Were you found out?</strong>
It initially started as a sort of super-secret, cloak and dagger thing. Kind of silly in retrospect, but it made it more fun. About halfway through it just started to become more obvious that that was what I was doing, and as it turned out the idea was supported. Writing this thing eventually became my job. </p>
<p><strong>Were you punished or rewarded?</strong>
Rewarded</p>
<p><strong>How did you fund it? / How did you staff it?</strong>
The success of it was pretty much due to the support of my boss, who made sure I had the time and resources I needed to do it.</p>
<p><strong>Was it formally adopted?</strong>
Yes, we eventually ran the company on it. </p>
| 48,232
|
<p>What is the best way to setup your pool with respect to:-</p>
<ol>
<li>When do you create connections?</li>
<li>When do you close connections, and would you close all of them?</li>
<li>Do you test connections are still good. When and how?</li>
<li>How do you figure out a good number for the maximum number of connections?</li>
<li>What sort of monitoring do you have in place to ensure users of the pool are well behaved? Can you stop one bad piece of code from taking out everything?</li>
<li>Have you written your own pool, or used a third-party library?</li>
</ol>
<p>I believe this is an agnostic question, but comments about "features" of particular databases/languages are welcome. For example, it might be slower or more expensive to connect on some databases than others.</p>
<p>To clarify, I do not intend to write a pool from scratch, this question is more about how to configure an existing library that does pooling.</p>
|
<p>I wrote a connection pool for the database in Java when it was just a design pattern and not a common library. Now I use the one built into Tomcat.</p>
<p>I used a thread to monitor several aspects of the pool and several parameters to control its behavior...</p>
<ol>
<li>minimumInPool="3"... These first three are created upon launch. The pool is never allowed to drop below three.</li>
<li>maximumIdleTimeBeforeRemoval="60"... If a connect is idle for an hour, then drop it and create a new one. Idle time probably means there is only the minimum of three in the pool.</li>
<li>maximumInUseTimeBeforeRemoval="30"... If a given connection has been checked out for over 30 minutes, then something is probably wrong. Recall it, and kill the connection.</li>
<li>maximumTimeBeforeRemoval="60"... Remove it if it is over 60 minutes old.</li>
<li>maximumUsageBeforeRemoval="1000"... Remove it if it has been checked out over 1000 times.</li>
<li>monitorInterval="15"... Check the above parameters every 15 minutes.</li>
</ol>
<p>This served me very well for a couple of years. The highest I ever saw the pool was 151 connections during a wild peek. Usually the pool was at about a dozen during heavy usage and idled down to the minimum three in the early morning hours.</p>
<p>I used Oracle's JDBC thin drivers and connected to an Oracle database.</p>
|
<p>Why re-invent the wheel?</p>
<p>Someone has already probably solved the problem, and better.</p>
<p>If you're in the Java world, you can use <a href="http://commons.apache.org/dbcp/" rel="nofollow noreferrer">Commons DBCP</a>.</p>
| 34,098
|
<p>I have several identical elements with different attributes that I'm accessing with SimpleXML:</p>
<pre><code><data>
<seg id="A1"/>
<seg id="A5"/>
<seg id="A12"/>
<seg id="A29"/>
<seg id="A30"/>
</data>
</code></pre>
<p>I need to remove a specific <strong>seg</strong> element, with an id of "A12", how can I do this? I've tried looping through the <strong>seg</strong> elements and <em>unset</em>ting the specific one, but this doesn't work, the elements remain.</p>
<pre><code>foreach($doc->seg as $seg)
{
if($seg['id'] == 'A12')
{
unset($seg);
}
}
</code></pre>
|
<p>While <a href="http://de.php.net/manual/en/book.simplexml.php" rel="noreferrer">SimpleXML</a> provides <a href="https://stackoverflow.com/a/16062633/367456">a way to remove</a> XML nodes, its modification capabilities are somewhat limited. One other solution is to resort to using the <a href="http://de.php.net/manual/en/book.dom.php" rel="noreferrer">DOM</a> extension. <a href="http://de.php.net/manual/en/function.dom-import-simplexml.php" rel="noreferrer">dom_import_simplexml()</a> will help you with converting your <code>SimpleXMLElement</code> into a <code>DOMElement</code>.</p>
<p>Just some example code (tested with PHP 5.2.5):</p>
<pre><code>$data='<data>
<seg id="A1"/>
<seg id="A5"/>
<seg id="A12"/>
<seg id="A29"/>
<seg id="A30"/>
</data>';
$doc=new SimpleXMLElement($data);
foreach($doc->seg as $seg)
{
if($seg['id'] == 'A12') {
$dom=dom_import_simplexml($seg);
$dom->parentNode->removeChild($dom);
}
}
echo $doc->asXml();
</code></pre>
<p>outputs</p>
<pre><code><?xml version="1.0"?>
<data><seg id="A1"/><seg id="A5"/><seg id="A29"/><seg id="A30"/></data>
</code></pre>
<p>By the way: selecting specific nodes is much more simple when you use XPath (<a href="http://de.php.net/manual/en/function.simplexml-element-xpath.php" rel="noreferrer">SimpleXMLElement->xpath</a>): </p>
<pre><code>$segs=$doc->xpath('//seq[@id="A12"]');
if (count($segs)>=1) {
$seg=$segs[0];
}
// same deletion procedure as above
</code></pre>
|
<p>Your initial approach was right, but you forgot one little thing about foreach. It doesn't work on the original array/object, but creates a copy of each element as it iterates, so you did unset the copy. Use reference like this:</p>
<pre><code>foreach($doc->seg as &$seg)
{
if($seg['id'] == 'A12')
{
unset($seg);
}
}
</code></pre>
| 32,829
|
<p>The simple HTML below displays differently in Firefox and WebKit-based browsers (I checked in Safari, Chrome and iPhone).</p>
<p>In Firefox both border and text have the same color (<code>#880000</code>), but in Safari the text gets a bit lighter (as if it had some transparency applied to it).</p>
<p>Can I somehow fix this (remove this transparency in Safari)?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style type="text/css">
input:disabled{
border:solid 1px #880000;
background-color:#ffffff;
color:#880000;
}
</style>
</head>
<body>
<form action="">
<input type="text" value="disabled input box" disabled="disabled"/>
</form>
</body>
</html></code></pre>
</div>
</div>
</p>
|
<pre><code>-webkit-text-fill-color: #880000;
opacity: 1; /* required on iOS */
</code></pre>
|
<p>Can you use a button instead of an input?</p>
<pre><code><html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style type="text/css">
button:disabled{
border:solid 1px #880000;
background-color:#ffffff;
color:#880000;
}
</style>
</head>
<body>
<form action="">
<button type="button" disabled="disabled">disabled input box</button>
</form>
</body>
</html>
</code></pre>
| 32,801
|
<p>I downloaded a VM image of a web application that uses MySQL.</p>
<p>How can I monitor its space consumption and know when additional space must be added?</p>
|
<p>I have some great big queries to share:</p>
<p>Run this to get the Total MySQL Data and Index Usage By Storage Engine</p>
<pre><code>SELECT IFNULL(B.engine,'Total') "Storage Engine",
CONCAT(LPAD(REPLACE(FORMAT(B.DSize/POWER(1024,pw),3),',',''),17,' '),' ',
SUBSTR(' KMGTP',pw+1,1),'B') "Data Size", CONCAT(LPAD(REPLACE(
FORMAT(B.ISize/POWER(1024,pw),3),',',''),17,' '),' ',
SUBSTR(' KMGTP',pw+1,1),'B') "Index Size", CONCAT(LPAD(REPLACE(
FORMAT(B.TSize/POWER(1024,pw),3),',',''),17,' '),' ',
SUBSTR(' KMGTP',pw+1,1),'B') "Table Size" FROM
(SELECT engine,SUM(data_length) DSize,SUM(index_length) ISize,
SUM(data_length+index_length) TSize FROM
information_schema.tables WHERE table_schema NOT IN
('mysql','information_schema','performance_schema') AND
engine IS NOT NULL GROUP BY engine WITH ROLLUP) B,
(SELECT 3 pw) A ORDER BY TSize;
</code></pre>
<p>Run this to get the Total MySQL Data and Index Usage By Database</p>
<pre><code>SELECT DBName,CONCAT(LPAD(FORMAT(SDSize/POWER(1024,pw),3),17,' '),' ',
SUBSTR(' KMGTP',pw+1,1),'B') "Data Size",CONCAT(LPAD(
FORMAT(SXSize/POWER(1024,pw),3),17,' '),' ',SUBSTR(' KMGTP',pw+1,1),'B') "Index Size",
CONCAT(LPAD(FORMAT(STSize/POWER(1024,pw),3),17,' '),' ',
SUBSTR(' KMGTP',pw+1,1),'B') "Total Size" FROM
(SELECT IFNULL(DB,'All Databases') DBName,SUM(DSize) SDSize,SUM(XSize) SXSize,
SUM(TSize) STSize FROM (SELECT table_schema DB,data_length DSize,
index_length XSize,data_length+index_length TSize FROM information_schema.tables
WHERE table_schema NOT IN ('mysql','information_schema','performance_schema')) AAA
GROUP BY DB WITH ROLLUP) AA,(SELECT 3 pw) BB ORDER BY (SDSize+SXSize);
</code></pre>
<p>Run this to get the Total MySQL Data and Index Usage By Database and Storage Engine</p>
<pre><code>SELECT Statistic,DataSize "Data Size",IndexSize "Index Size",TableSize "Table Size"
FROM (SELECT IF(ISNULL(table_schema)=1,10,0) schema_score,
IF(ISNULL(engine)=1,10,0) engine_score,
IF(ISNULL(table_schema)=1,'ZZZZZZZZZZZZZZZZ',table_schema) schemaname,
IF(ISNULL(B.table_schema)+ISNULL(B.engine)=2,"Storage for All Databases",
IF(ISNULL(B.table_schema)+ISNULL(B.engine)=1,
CONCAT("Storage for ",B.table_schema),
CONCAT(B.engine," Tables for ",B.table_schema))) Statistic,
CONCAT(LPAD(REPLACE(FORMAT(B.DSize/POWER(1024,pw),3),',',''),17,' '),' ',
SUBSTR(' KMGTP',pw+1,1),'B') DataSize,CONCAT(LPAD(REPLACE(
FORMAT(B.ISize/POWER(1024,pw),3),',',''),17,' '),' ',
SUBSTR(' KMGTP',pw+1,1),'B') IndexSize,
CONCAT(LPAD(REPLACE(FORMAT(B.TSize/POWER(1024,pw),3),',',''),17,' '),' ',
SUBSTR(' KMGTP',pw+1,1),'B') TableSize FROM (SELECT table_schema,engine,
SUM(data_length) DSize,SUM(index_length) ISize,
SUM(data_length+index_length) TSize FROM information_schema.tables
WHERE table_schema NOT IN ('mysql','information_schema','performance_schema')
AND engine IS NOT NULL GROUP BY table_schema,engine WITH ROLLUP) B,
(SELECT 3 pw) A) AA ORDER BY schemaname,schema_score,engine_score;
</code></pre>
<p>CAVEAT</p>
<p>In each query, you will see <code>(SELECT 3 pw)</code>. The pw stands for the Power Of 1024 to display the results.</p>
<ul>
<li><code>(SELECT 0 pw)</code> will Display the Report in Bytes</li>
<li><code>(SELECT 1 pw)</code> will Display the Report in KiloBytes</li>
<li><code>(SELECT 2 pw)</code> will Display the Report in MegaBytes</li>
<li><code>(SELECT 3 pw)</code> will Display the Report in GigaBytes</li>
<li><code>(SELECT 4 pw)</code> will Display the Report in TeraBytes</li>
<li><code>(SELECT 5 pw)</code> will Display the Report in PetaBytes (please contact me if you run this one)</li>
</ul>
<p>Here is a report query with a little less formatting:</p>
<pre><code>SELECT IFNULL(db,'Total') "Database",
datsum / power(1024,pw) "Data Size",
ndxsum / power(1024,pw) "Index Size",
totsum / power(1024,pw) "Total"
FROM (SELECT db,SUM(dat) datsum,SUM(ndx) ndxsum,SUM(dat+ndx) totsum
FROM (SELECT table_schema db,data_length dat,index_length ndx
FROM information_schema.tables WHERE engine IS NOT NULL
AND table_schema NOT IN ('information_schema','mysql')) AA
GROUP BY db WITH ROLLUP) A,(SELECT 1 pw) B;
</code></pre>
<p>Trust me, I made these queries over 4 years ago and still use them today.</p>
<h1>UPDATE 2013-06-24 15:53 EDT</h1>
<p>I have something new. I have changed the queries so that you do not have to set the <code>pw</code> parameter for different unit displays. Each unit display is calculated for you.</p>
<p>Report By Storage Engine</p>
<pre><code>SELECT
IFNULL(ENGINE,'Total') "Storage Engine",
LPAD(CONCAT(FORMAT(DAT/POWER(1024,pw1),2),' ',
SUBSTR(units,pw1*2+1,2)),17,' ') "Data Size",
LPAD(CONCAT(FORMAT(NDX/POWER(1024,pw2),2),' ',
SUBSTR(units,pw2*2+1,2)),17,' ') "Index Size",
LPAD(CONCAT(FORMAT(TBL/POWER(1024,pw3),2),' ',
SUBSTR(units,pw3*2+1,2)),17,' ') "Total Size"
FROM
(
SELECT ENGINE,DAT,NDX,TBL,
IF(px>4,4,px) pw1,IF(py>4,4,py) pw2,IF(pz>4,4,pz) pw3
FROM
(SELECT *,
FLOOR(LOG(IF(DAT=0,1,DAT))/LOG(1024)) px,
FLOOR(LOG(IF(NDX=0,1,NDX))/LOG(1024)) py,
FLOOR(LOG(IF(TBL=0,1,TBL))/LOG(1024)) pz
FROM
(SELECT
ENGINE,
SUM(data_length) DAT,
SUM(index_length) NDX,
SUM(data_length+index_length) TBL
FROM
(
SELECT engine,data_length,index_length FROM
information_schema.tables WHERE table_schema NOT IN
('information_schema','performance_schema','mysql')
AND ENGINE IS NOT NULL
) AAA GROUP BY ENGINE WITH ROLLUP
) AAA ) AA) A,(SELECT ' BKBMBGBTB' units) B;
</code></pre>
<p>Report By Database</p>
<pre><code>SELECT
IFNULL(DB,'Total') "Database",
LPAD(CONCAT(FORMAT(DAT/POWER(1024,pw1),2),' ',
SUBSTR(units,pw1*2+1,2)),17,' ') "Data Size",
LPAD(CONCAT(FORMAT(NDX/POWER(1024,pw2),2),' ',
SUBSTR(units,pw2*2+1,2)),17,' ') "Index Size",
LPAD(CONCAT(FORMAT(TBL/POWER(1024,pw3),2),' ',
SUBSTR(units,pw3*2+1,2)),17,' ') "Total Size"
FROM
(
SELECT DB,DAT,NDX,TBL,
IF(px>4,4,px) pw1,IF(py>4,4,py) pw2,IF(pz>4,4,pz) pw3
FROM
(SELECT *,
FLOOR(LOG(IF(DAT=0,1,DAT))/LOG(1024)) px,
FLOOR(LOG(IF(NDX=0,1,NDX))/LOG(1024)) py,
FLOOR(LOG(IF(TBL=0,1,TBL))/LOG(1024)) pz
FROM
(SELECT
DB,
SUM(data_length) DAT,
SUM(index_length) NDX,
SUM(data_length+index_length) TBL
FROM
(
SELECT table_schema DB,data_length,index_length FROM
information_schema.tables WHERE table_schema NOT IN
('information_schema','performance_schema','mysql')
AND ENGINE IS NOT NULL
) AAA GROUP BY DB WITH ROLLUP
) AAA) AA) A,(SELECT ' BKBMBGBTB' units) B;
</code></pre>
<p>Report By Database / Storage Engine</p>
<pre><code>SELECT
IF(ISNULL(DB)+ISNULL(ENGINE)=2,'Database Total',
CONCAT(DB,' ',IFNULL(ENGINE,'Total'))) "Reported Statistic",
LPAD(CONCAT(FORMAT(DAT/POWER(1024,pw1),2),' ',
SUBSTR(units,pw1*2+1,2)),17,' ') "Data Size",
LPAD(CONCAT(FORMAT(NDX/POWER(1024,pw2),2),' ',
SUBSTR(units,pw2*2+1,2)),17,' ') "Index Size",
LPAD(CONCAT(FORMAT(TBL/POWER(1024,pw3),2),' ',
SUBSTR(units,pw3*2+1,2)),17,' ') "Total Size"
FROM
(
SELECT DB,ENGINE,DAT,NDX,TBL,
IF(px>4,4,px) pw1,IF(py>4,4,py) pw2,IF(pz>4,4,pz) pw3
FROM
(SELECT *,
FLOOR(LOG(IF(DAT=0,1,DAT))/LOG(1024)) px,
FLOOR(LOG(IF(NDX=0,1,NDX))/LOG(1024)) py,
FLOOR(LOG(IF(TBL=0,1,TBL))/LOG(1024)) pz
FROM
(SELECT
DB,ENGINE,
SUM(data_length) DAT,
SUM(index_length) NDX,
SUM(data_length+index_length) TBL
FROM
(
SELECT table_schema DB,ENGINE,data_length,index_length FROM
information_schema.tables WHERE table_schema NOT IN
('information_schema','performance_schema','mysql')
AND ENGINE IS NOT NULL
) AAA GROUP BY DB,ENGINE WITH ROLLUP
) AAA) AA) A,(SELECT ' BKBMBGBTB' units) B;
</code></pre>
|
<p>For MyISAM tables, I usually check the size of the /var/lib/mysql/mydatabasename/ directory. InnoDB tables use monolithic files, so you have to use SHOW TABLE STATUS.</p>
| 22,315
|
<p>What could the following line possibly mean?</p>
<pre><code>my $x = shift;
</code></pre>
|
<p><code>shift()</code> is a built in Perl subroutine that takes an array as an argument, then returns and deletes the first item in that array. It is common practice to obtain all parameters passed into a subroutine with <code>shift</code> calls. For example, say you have a subroutine <code>foo</code> that takes three arguments. One way to get these parameters assigned to local variables is with <code>shift</code> like so:</p>
<pre><code>sub foo() {
my $x = shift;
my $y = shift;
my $z = shift;
# do something
}
</code></pre>
<p>The confusion here is that it appears shift is not being passed an array as an argument. In fact, it is being passed the "default" array implicitly, which is <code>@_</code> inside a subroutine or <code>@ARGV</code> outside a subroutine.</p>
|
<p>Do you still have questions after reading the output of <code>perldoc -f shift</code>?</p>
<p>(That is not a question; it is an answer ;-))</p>
<p>Another recommended reading is <code>man perlbook</code>.</p>
<p>Perl "shifts off" the first element from <code>@_</code>, returning it.
So <code>$x</code> is assigned to the first element of <code>@_</code> after removing it from there.
<code>@_</code> itself are the routine parameters.</p>
<p>So these three are common alternatives (not the very same, however):</p>
<pre class="lang-perl prettyprint-override"><code>my $a = shift;
my $b = shift;
my $c = shift;
</code></pre>
<pre class="lang-perl prettyprint-override"><code>my ($a, $b, $c) = @_;
</code></pre>
<pre class="lang-perl prettyprint-override"><code>my $a = $_[0];
my $b = $_[1];
my $c = $_[2];
</code></pre>
<p>Only the first variant modifies <code>@_</code>.</p>
| 37,979
|
<p>I need to have my installer include the .NET Framework 3.5 SP1 as well as SQL Compact 3.5. I remember seeing a place somewhere in the Visual Studio IDE where these could be included in the install, but I can't find them. Does anyone know how to do this? Thanks!</p>
|
<p>Found it! It looks like you can go to the "Properties" window of the Installer project and click on the "Prerequisites" button to see a list of prerequisite installers to include in your installer like SQL Server, SQL Compact, .NET Framework versions, etc.</p>
<p>It appears that the list is driven off of things that you have installed on the development computer.</p>
|
<p>You might also want to register for redistribution rights:</p>
<p><a href="http://www.microsoft.com/sqlserver/2005/en/us/compact-redistribute.aspx" rel="nofollow noreferrer">http://www.microsoft.com/sqlserver/2005/en/us/compact-redistribute.aspx</a></p>
| 37,810
|
<p>I'd like to know how to convert this vb script to C#</p>
<pre><code>Dim strFolder As String
Dim objShell As Object
strFolder = "C:\zz"
Set objShell = CreateObject("Wscript.Shell")
objShell.Run "%COMSPEC% /c Echo Y| cacls " & _
strFolder & _
" /t /c /g everyone:F ", 2, True
</code></pre>
<p>What I'm trying to do is set permissions to "Everyone" on a newly created folder on the users C:\ drive.</p>
<p>I'm using Visual Studio, .Net 1.1</p>
<p>Thanks.
Iain</p>
|
<p>It's not possible to upgrade unfortunately - I work for a big company, so would mean updating loads of people - which would be a mission...</p>
<p>But - creating a process worked!</p>
<pre><code>System.Diagnostics.Process meProc = System.Diagnostics.Process.Start ("cmd.exe", " /c echo y| cacls C:\\zzz /t /c /g everyone:F");
</code></pre>
<p>Thanks both of you for your help.</p>
|
<p>Is upgrading to a newer version not possible? .NET 2.0 introduced classes in the <a href="http://msdn.microsoft.com/en-us/library/system.security.accesscontrol.aspx" rel="nofollow noreferrer">System.Security.AccessControl</a> namespace to handle this. If it's really not possible and you only have this one command to execute, you may want to create a <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.process.aspx" rel="nofollow noreferrer">Process</a> and just execute the <code>cacls</code> command in it.</p>
| 48,954
|
<p>I'm using Windows Vista and C#.net 3.5, but I had my friend run the program on XP and has the same problem.</p>
<p>So I have a C# program that I have running in the background with an icon in the SystemTray. I have a low level keyboard hook so when I press two keys (Ctr+windows in this case) it'll pull of the application's main form. The form is set to be full screen in the combo key press even handler:</p>
<pre><code>this.FormBorderStyle = FormBorderStyle.None;
this.WindowState = FormWindowState.Maximized;
</code></pre>
<p>So it basically works. When I hit CTR+Windows it brings up the form, no matter what program I have given focus to. But sometimes, the taskbar will still show up over the form, which I don't want. I want it to always be full screen when I hit that key combo.</p>
<p>I figure it has something to do with what application has focus originally. But even when I click on my main form, the taskbar sometimes stays there. So I wonder if focus really is the problem. It just seems like sometimes the taskbar is being stubborn and doesn't want to sit behind my program.</p>
<p>Anyone have any ideas how I can fix this?</p>
<p>EDIT: More details-
I'm trying to achieve the same effect that a web browser has when you put it into fullscreen mode, or when you put powerpoint into presentation mode.</p>
<p>In a windows form you do that by putting the border style to none and maximizing the window. But sometimes the window won't cover the taskbar for some reason. Half the time it will.</p>
<p>If I have the main window topmost, the others will fall behind it when I click on it, which I don't want if the taskbar is hidden.</p>
|
<p>Try this (where <code>this</code> is your form):</p>
<pre><code>this.Bounds = Screen.PrimaryScreen.Bounds;
this.TopMost = true;
</code></pre>
<p>That'll set the form to fullscreen, and it'll cover the taskbar.</p>
|
<p>As far as I know, the taskbar is either above or below windows based on the "Keep the taskbar on top of other windows" setting. (At least, that's the wording in XP.) I suppose you could try to see if you can detect this setting and toggle it if needed?</p>
| 14,379
|
<p>I'm having a strange problem.</p>
<p>I have to use <code>GetPostBackEventRefence</code> to force a Postback, but it works the first time, after the first postback, the .NET function is not rendered... any ideas?</p>
<p>This is what I'm missing after the postback:</p>
<pre><code><script language="javascript" type="text/javascript">
<!--
function __doPostBack(eventTarget, eventArgument) {
var theform;
if (window.navigator.appName.toLowerCase().indexOf("microsoft") > -1) {
theform = document.Main;
}
else {
theform = document.forms["Main"];
}
theform.__EVENTTARGET.value = eventTarget.split("$").join(":");
theform.__EVENTARGUMENT.value = eventArgument;
theform.submit();
}
// -->
</script>
</code></pre>
|
<p>The first thing I would look at is whether you have any asp controls (such as linkbutton, comboboxes,that don't normally generate a submit but requre a postback) being displayed on the page.
<strong>The __doPostback function will only be put into the page if ASP thinks that one of your controls requires it.</strong></p>
<p>If you aren't using one of those you can use: </p>
<pre><code>Page.ClientScript.GetPostBackClientHyperlink(controlName, "")
</code></pre>
<p>to add the function to your page</p>
|
<p>Well, following that idea I created a dummy function with the postbackreference, and it works... it still is weird though, because of it rendering correctly the first time</p>
<pre><code>this.Page.RegisterClientScriptBlock("DUMMY", "<script language='javascript'>function dummy() { " + this.Page.GetPostBackEventReference(this) + "; } </script>");
</code></pre>
| 7,340
|
<p>How can I know what encoding will be used by PHP when sending data to the browser? I.e. with the Cotent-Type header, for instance: iso-8859-1.</p>
|
<p>Usually Apache + PHP servers of webhosters are configured to send out <strong>NO <code>charset</code> header</strong>.
The shortest way to test how your server is configured are these:</p>
<ul>
<li>Use <a href="http://www.seoconsultants.com/tools/headers" rel="nofollow">this tool to see the server header</a> by getting any one of your pages on your webiste.
If in the server headers you see a <code>charset</code> it means your server is using it, usually it won't contain a <code>charset</code>.</li>
<li>Another way is to run this simple script on your server: <code><?php echo ini_get('default_charset'); ?></code> As said above this usually prints out an empty string, if different it will show you the <code>charset</code> of the PHP.</li>
</ul>
<p>The 2nd solution is supposing Apache is not configured with <code>AddDefaultCharset some_charset</code> which is not usually the case, but in such case I'm afraid Apache setting might override PHP deafult_charset ini directive.</p>
|
<p>You can set your own with <code>header('Content-type: xxx/yyy');</code>, but I believe that text/html is sent by default.</p>
| 15,848
|
<p>Anyone knows of a good tool for developing add-ins for Word in .net?
Hopefully something that supports both office 2003 and 2007.</p>
<p>Thanks.</p>
|
<p>There are lots of options for development tools for Office. The most obvious one is of course Office itself. It has rich support for macros and VBA. You could also use SharePoint to extend document sharing and management functionality. But if your add-in is more complex than can be handled inside of Office, I suggest you use <a href="http://msdn.microsoft.com/en-us/vs2008/default.aspx" rel="noreferrer" title="Visual Studio 2008 Developer Center">Visual Studio 2008</a> or the <a href="http://msdn.microsoft.com/en-us/office/aa905543.aspx" rel="noreferrer" title="VSTO 2005 add-on">Tools For Office</a> add-on for Visual Studio 2005.</p>
<p>One thing to keep in mind is that Office is mostly a collection of COM objects. So while tools like Visual Studio, with its deep support of the .NET Framework and Office classes make it very simple to develop solutions for Office applications, with some time, energy, and a high tolerance for pain, you could develop an Office add-in with Notepad.</p>
<p>Microsoft has a very nice resource site for Office developers <a href="http://msdn.microsoft.com/en-us/office/default.aspx" rel="noreferrer" title="Office Developer Center">here</a>.</p>
|
<p>Visual Studio 2008. VB.NET.</p>
| 13,623
|
<p>I'm a self-taught developer and my experience is all in small applications that I've developed.</p>
<p>I'm currently working on an application that I've made public, and I've realized that I need to start doing good unit testing to catch regressions and generally make sure everything works.</p>
<p>I've read up on a <a href="https://stackoverflow.com/questions/205566/comprehensive-introduction-to-unit-testing">previous question</a>. I would like to know if there are any resources online specifically dealing with C# unit testing in Visual Studio 2008, preferably with examples.</p>
<p>EDIT: I'm using Visual Studio 2008 Professional for Windows applications, no web development.</p>
|
<p>You don't specify which <a href="http://msdn.microsoft.com/en-us/subscriptions/subscriptionschart.aspx" rel="noreferrer">flavor of VS2008</a> you are using. If it is Pro or above, then MSTest is bundled, but a lot of people have issues with it - it isn't always very intuitive, and it takes far too much setup to do simple things like coverage / file deployment.</p>
<p>A walkthrough is <a href="http://msdn.microsoft.com/en-us/library/ms379625(VS.80).aspx" rel="noreferrer">here</a>.</p>
<p>As a recommendation, I suggest using VS2008 with <a href="http://www.nunit.org/" rel="noreferrer">NUnit</a> (free) and <a href="http://testdriven.net/" rel="noreferrer">TestDriven.NET</a> (not free). It takes away all the pain, allowing you to just write simple things like:</p>
<pre><code>[TestFixture]
public class Foo {
[Test]
public void Bar() {
Assert.AreEqual(2, 1+1);
}
}
</code></pre>
<p>Then just right-click (on the class, on the method, on the project, on the solution) and use the Test options that TestDriven.NET provides, including (if you have MSTest) "Test With -> Team Coverage", which runs your NUnit tests with the MSTest coverage tools, including giving the colorization back into the IDE to show which lines executed. No messing with "testrunconfig" and the other files that MSTest wants you to use.</p>
|
<p>If you interested in more than just normal unit-tests, then take a look at <a href="http://research.microsoft.com/Pex/" rel="nofollow noreferrer">PEX</a></p>
| 34,893
|
<p>Does anyone have examples of how to use <a href="http://www.oracle-base.com/articles/8i/DBMS_APPLICATION_INFO.php" rel="nofollow noreferrer">DBMS_APPLICATION_INFO</a> package with JBOSS? </p>
<p>We have a various applications which run within JBOSS and share db pools. I would like, at the start of each session these applications to identify themselves to the database using DBMS_APPLICATION_INFO so I can more easily track which sections of the application is causing database issues.</p>
<p>I'm not too familiar with session life cycles in JBOSS, but at the end of the day, what needs to happen is at the start and end of a transaction, this package needs to be called.</p>
<p>Has anyone done this before?</p>
|
<p>yes, you can write a wrapper class around your connection pool, and a wraper around the connection
so lets say you have:</p>
<pre>
OracleConnection conn=connectionPool.getConnection("java:scott@mydb");
</pre>
<p>Change it to:</p>
<pre>
public class LoggingConnectionPool extends ConnectionPool{
public OracleConnection getConnection(String datasourceName, String module, String action){
OracleConnection conn=getConnection(datasourceName);
CallableStatement call=conn.preparedCall("begin dbms_application_info.setModule(module_name => ?, action_name => ?); end;");
try{
call.setString(1,module);
call.setString(2,action);
call.execute();
finally{
call.close();
}
return new WrappedOracleConnection(conn);
}
</pre>
<p>Note the use of WrappedOracleConnection above. You need this because you need to trap the close call</p>
<pre>
public class WrappedOracleConnection extends OracleConnection{
public void close(){
CallableStatement call=this.preparedCall("begin dbms_application_info.setModule(module_name => ?, action_name => ?); end;");
try{
call.setNull(1,Types.VARCHAR);
call.setNull(2,Types.VARCHAR);
call.execute();
finally{
call.close();
}
}
// and you need to implement every other method
//for example
public CallableStatement prepareCall(String command){
return super.prepareCall(command);
}
...
}
</pre>
<p>Hope this helps, I do something similar on a development server to catch connections that are not closed (not returned to the pool).</p>
|
<p>In your <em>-ds.xml</em>, you can set a connection property called <strong>v$session.program</strong> and the value of that property will populate the <strong>PROGRAM</strong> column of each session in the <strong>V$SESSION</strong> view created for connections originating from your connection pool. I usually set it to the <em>jboss.server.name</em> property.</p>
<p>See <a href="http://www.magpiebrain.com/2006/05/09/specifying-a-program-name-in-oracle-jdbc-connections/" rel="nofollow">here</a> for an example.</p>
| 7,680
|
<p>Does anybody knows how can I get the max and min value of the 2nd and 3rd columns in PHP?</p>
<pre><code>$ar = array(array(1, 10, 9.0, 'HELLO'),
array(1, 11, 12.9, 'HELLO'),
array(3, 12, 10.9, 'HELLO'));
</code></pre>
<p>Output should be like:</p>
<p>max(12.9)
min(10)</p>
|
<pre><code><?php
$ar = array(array(1, 10, 9.0, 'HELLO'),
array(1, 11, 12.9, 'HELLO'),
array(3, 12, 10.9, 'HELLO'));
function col($tbl,$col){
$ret = array();
foreach ($tbl as $row){
$ret[count($ret)+1] = $row[$col];
}
return $ret;
}
print (max(col($ar,2))."\n");
print (min(col($ar,1))."\n");
?>
</code></pre>
<p>is this what you look for? I guess its not the most efficient way. </p>
|
<pre><code><?php
$ar = array(array(1, 10, 9.0, 'HELLO'),
array(1, 11, 12.9, 'HELLO'),
array(3, 12, 10.9, 'HELLO'));
function col($tbl,$col){
$ret = array();
foreach ($tbl as $row){
$ret[count($ret)+1] = $row[$col];
}
return $ret;
}
print (max(col($ar,2))."\n");
print (min(col($ar,1))."\n");
?>
</code></pre>
<p>is this what you look for? I guess its not the most efficient way. </p>
| 31,351
|
<p>Our coding standards ask that we minimise the use of C# var (suggests limiting it's use to being in conjunction with Linq). However there are times when using generics where it's reasonably convenient e.g.</p>
<pre><code>Dictionary<DateTime, Dictionary<string, float>> allValues = ...
// ...
foreach (var dateEntry in allValue)
</code></pre>
<p>is easier to type </p>
<pre><code>foreach (KeyValue<DateTime, Dictionary<string, float>> dateEntry in allValue)
</code></pre>
<p>(and easier than remembering what the explicit type is in some cases). </p>
<p>Do any of the refactoring tools have the ability to convert the former to the latter. I've had a look at Resharper but it doesn't seem to do (indeed it's default suggestion is to go in the opposite direction).</p>
|
<p>I've got ReSharper 4.1, and it does offer this option (in either direction).</p>
<p>Actually, I'd recommend challenging the standard... the former is far more readable than the latter (especially if you call the variable <code>pair</code> or something similar). I would't use "var" for <code>var i = 0</code>, but it is ideally suited to the above.</p>
<p>For bulk changing, go to:</p>
<ul>
<li>Cleanup Code... (pick a profile => "Edit Profiles" => Tools => Code Cleanup)
<ul>
<li>C#
<ul>
<li>Use 'var' in declaration
<ul>
<li>Replace direction = Can 'var' to type usage</li>
<li>'foreach' iterator declaration style = Always use explicit type</li>
<li>Local variable declaration style = Always use explicit type</li>
</ul></li>
</ul></li>
</ul></li>
</ul>
<p>and run...</p>
|
<p>I'd argue that where you have complex generic types on your domain objects you should typedef them</p>
<pre>
class DomainValueCollection : KeyValue<DateTime, Dictionary<string, float>>{}
</pre>
<p>where DomainValueCollection is somehting that makes sense in your domain context</p>
<p>the code then becomes</p>
<pre>
var allItems = new DomainValueCollection();
</pre>
<p>rather than</p>
<pre>
var allItems = new KeyValue<DateTime, Dictionary<string, float>>();
</pre>
| 36,911
|
<p>Test the following code:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
main()
{
const char *yytext="0";
const float f=(float)atof(yytext);
size_t t = *((size_t*)&f);
printf("t should be 0 but is %d\n", t);
}
</code></pre>
<p>Compile it with:</p>
<pre><code>gcc -O3 test.c
</code></pre>
<p>The GOOD output should be:</p>
<pre><code>"t should be 0 but is 0"
</code></pre>
<p>But with my gcc 4.1.3, I have:</p>
<pre><code>"t should be 0 but is -1209357172"
</code></pre>
|
<p>Use the compiler flag -fno-strict-aliasing.</p>
<p>With strict aliasing enabled, as it is by default for at least -O3, in the line:</p>
<pre><code>size_t t = *((size_t*)&f);
</code></pre>
<p>the compiler assumes that the size_t* does NOT point to the same memory area as the float*. As far as I know, this is standards-compliant behaviour (adherence with strict aliasing rules in the ANSI standard start around gcc-4, as Thomas Kammeyer pointed out).</p>
<p>If I recall correctly, you can use an intermediate cast to char* to get around this. (compiler assumes char* can alias anything)</p>
<p>In other words, try this (can't test it myself right now but I think it will work):</p>
<pre><code>size_t t = *((size_t*)(char*)&f);
</code></pre>
|
<p>-O3 is not deemed "sane", -O2 is generally the upper threshold except maybe for some multimedia apps. </p>
<p>Some apps can't even go that far, and die if you go beyond -O1 . </p>
<p>If you have a new enough GCC ( I'm on 4.3 here ), it may support this command </p>
<pre><code> gcc -c -Q -O3 --help=optimizers > /tmp/O3-opts
</code></pre>
<p>If you're careful, you'll possibly be able to go through that list and find the given singular optimization you're enabling which causes this bug. </p>
<p>From <code>man gcc</code> :</p>
<pre><code> The output is sensitive to the effects of previous command line options, so for example it is possible to find out which
optimizations are enabled at -O2 by using:
-O2 --help=optimizers
Alternatively you can discover which binary optimizations are enabled by -O3 by using:
gcc -c -Q -O3 --help=optimizers > /tmp/O3-opts
gcc -c -Q -O2 --help=optimizers > /tmp/O2-opts
diff /tmp/O2-opts /tmp/O3-opts | grep enabled
</code></pre>
| 10,949
|
<p>How can I convert an <code>Int64</code> to an <code>Int32</code> type in F# without using the <code>Microsoft.FSharp.Compatibility.Int32.of_int64</code>?</p>
<p>I'm doing this because interactive doesn't seem to work when I try:</p>
<pre><code>open Microsoft.FSharp.Compatibility
</code></pre>
<p>With <code>FSharp.PowerPack</code> added as a reference it says: </p>
<blockquote>
<p>error FS0039: The namespace 'Compatibility' is not defined.</p>
</blockquote>
<p><strong>Edit:</strong> Does anyone have an answer to the question? The suggestions about the int types are useful and informative, but I'm having the same issue opening the powerpack namespace in F# interactive.</p>
|
<p>F# 1.9.6 has a type conversion function so you can do this: </p>
<pre><code>let num = 1000
let num64 = int64(num)
</code></pre>
|
<p>Note that the functions for converting to each integer type have the same names as the types themselves, and are defined in the library spec (see below). (With the release of the CTP (1.9.6.2), a lot of the library and the namespaces changed a bit compared to previous releases, but it will probably be more 'stable' moving forward.)</p>
<p><a href="http://research.microsoft.com/fsharp/manual/FSharp.Core/Microsoft.FSharp.Core.Operators.html" rel="nofollow noreferrer">http://research.microsoft.com/fsharp/manual/FSharp.Core/Microsoft.FSharp.Core.Operators.html</a></p>
| 29,193
|
<p>I'm creating a UI that allows the user the select a date range, and tick or un-tick the days of the week that apply within the date range.</p>
<p>The date range controls are <code>DateTimePickers</code>, and the Days of the Week are <code>CheckBoxes</code></p>
<p>Here's a mock-up of the UI:</p>
<p><code>From Date: (dtpDateFrom)</code><br/>
<code>To Date: (dtpDateTo)</code></p>
<p><code>[y] Monday, [n] Tuesday, [y] Wednesday, (etc)</code></p>
<p>What's the best way to show a total count the number of days, based not only on the date range, but the ticked (or selected) days of the week?</p>
<p>Is looping through the date range my only option?</p>
|
<p>Here's how I would approach it:</p>
<ul>
<li>Find day of week (dow) of first and last date</li>
<li>Move first day forward to same dow as last. Store number of days moved that are to be included</li>
<li>Calculate number of weeks between first and last</li>
<li>Calculate number of included days in a week * number of weeks + included days moved</li>
</ul>
<p>As pseudo code:</p>
<pre><code> moved = start + end_dow - start_dow
extras = count included days between start and moved
weeks = ( end - moved ) / 7
days = days_of_week_included * weeks + extras
</code></pre>
<p>This will take constant time, no matter how far apart the start and end days.</p>
<p>The details of implementing this algorithm depend on what language and libraries you are using. Where possible, I use C++ plus boost::date_time for this sort of thing.</p>
|
<p>Looping through wouldn't be your only option - you could perform <a href="http://msdn.microsoft.com/en-us/library/8ysw4sby.aspx" rel="nofollow noreferrer">subtraction</a> to figure out the total number of days, and subtract one for each of your "skipped" dates every week range in between that contains one of those days. By the time you figure out whether a day lands on one of the partial weeks at the beginning or end of the range and add <code>#weeks * skipped days in a week</code>, your code will be more complicated than it would be if just counted, but if you're expecting to have huge date ranges, it might perform better.</p>
<p>If I were you, I'd write the simple looping option and rewrite it if it turned out that profiling revealed it to be a bottleneck.</p>
| 16,071
|
<p>We are designing a Payroll Generation System for a client.</p>
<p>The organization we are targeting has a hierarchy as follows:
Company -> Cluster -> Business Unit (BU) -> Department -> Employee</p>
<p>The salary for an employee is made up of various salary components.
Each salary component has 3 rules associated with it, a Calculation Rule (Calculate component as % of another component, or % of a fixed number or a fixed number), an Eligibility Rule (whether an Employee/Dept is eligible for a component) and a Constraint Rule which limits tha max and min of a component.</p>
<p><strong>These rules are editable and can be edited by a user end user</strong>. Also these rules are inherited top-down, but if defined at a lower level, the lower level rule takes precedence.</p>
<p><strong>We have a database which has Attendance, Leaves, Bonuses tables and these rules are also supposed to interact with these tables.</strong></p>
<p>The client will be generating payroll for multiple clients each hosting a Separate Database instance. They may each have a different interpretation of each component and may have different components.</p>
<p>We are only looking to support SQL Server, and payroll generation will be an offline activity.</p>
<p><strong>We are divided upon where to put the logic which uses these rules to generate the individual tax components (which will include Tax Deductions, Tax Write-offs, Allowances, etc).</strong></p>
<p>Some people are advocating magic SPs which will take an employee Id and generate a payroll for that month.
Others want the logic to be split into separate components which will get the dependent data for an employee in the application layer and calculate these components there.</p>
<p>The order of our priorities are:
1. The ability to adapt changes to new clients quickly
2. Long term maintainability
3. Performance</p>
<p>1 and 2 outweigh 3 here by a large factor as this will be an offline activity.</p>
<p>Maintainability and Quick Customizability are very important, we will be deploying the application for different clients.
Client A may have a Salary Component Rule as ((0.3 * Basic) + 800)
and Client B as (0.2 * Basic) + (0.1 * Atendance Bonus)</p>
<p><strong>Will SPs cause a mess here, as the rules suggested above will be specified by the end user and will need to be customizable through a web UI.
We will have to parse the formulas from SQL. How difficult or easy will it be?
What advantage will doing this in the Application Layer (C# .Net) have over using SPs?</strong></p>
<p>Suggestions and pointers to existing systems' architecture will be very helpful.
...and yes, we are using LINQ to SQL elsewhere in the system.</p>
<p>Kind regards,
Ashish Sharma</p>
|
<p>My only suggestion after looking at that is to check out the strategy pattern from the GoF design patterns book. You'd probably want the strategies done in a scripting language rather than your main compiled language though as then you will find editing them easier.</p>
|
<p>Maybe you want to check <a href="http://www.amazon.ca/Agile-Principles-Patterns-Practices-C/dp/0131857258/ref=sr_1_29?ie=UTF8&s=books&qid=1224166307&sr=1-29" rel="nofollow noreferrer">Agile Principles, Patterns, and Practices in C# </a> The core example in the book is designing a payroll system the agile way....</p>
| 25,607
|
<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>
|
<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>
<pre><code>$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";
</code></pre>
|
<pre><code>$query = "SELECT ven.venue_name AS 'Venue', count(*) AS 'Number of venues'
FROM volunteers_2009 AS vol, venues AS ven WHERE vol.venue_id = ven.id
GROUP BY ven.venue_name";
</code></pre>
| 28,732
|
<p>I would like to do something like add a nice-to-Excel-functions <code>Name</code> property to the <code>WorkBook</code> class. Is there a good way to do this?</p>
<p>More detailed problem: In VBA you can assign a formula to a range in an Excel worksheet. I want to do so, and I want my formula to refer to a second workbook, which is an object called <code>wb</code> in my code. I then use <code>wb.Name</code> in assigning a formula to a range. </p>
<p>The problem arises when <code>wb.Name</code> has a single-quote in it. Then you wind up with something like this:</p>
<pre><code>=MONTH('[Ryan's WB]Sheet1'A1)
</code></pre>
<p>in the spreadsheet, which fails because the single-quote in the workbook name matches to the first single-quote.</p>
<p>What I would like is a <code>FunName</code> property for the <code>WorkBook</code> class that replaces all single-quotes in the <code>Name</code> property with two single-quotes and returns that. Then the above formula would properly wind up looking like</p>
<pre><code>=MONTH('[Ryan''s WB]Sheet1'A1)
</code></pre>
|
<p>You don't need to make a separate class to extend the workbook class. You can add properties to the existing ThisWorkbook class module, like this:</p>
<pre><code>Public Property Get FunName() As String
FunName = Replace(Me.Name, "'", "''")
End Property
</code></pre>
<p>Then you call <code>ThisWorkbook.FunName</code> to get your cleaned up name. However, this code has to exist in the workbook at hand. If you want it to work on <em>any</em> workbook, your function is the way to go.</p>
|
<p>Just do a replace to double up the single quotes</p>
<pre><code>WorksheetName = Replace(WB.Name, "'", "''")
</code></pre>
| 36,173
|
<p>I'm a long-time Windows developer, having cut my teeth on win32 and early COM. I've been working with .NET since 2001, so I'm pretty fluent in C# and the CLR. I'd never heard of Castle Windsor until I started participating in Stack Overflow. I've read the Castle Windsor "Getting Started" guide, but it's not clicking.</p>
<p>Teach this old dog new tricks, and tell me why I should be integrating Castle Windsor into my enterprise apps.</p>
|
<p>Castle Windsor is an inversion of control tool. There are others like it.</p>
<p>It can give you objects with pre-built and pre-wired dependencies right in there. <strong>An entire object graph created via reflection and configuration rather than the "new" operator.</strong></p>
<p>Start here: <a href="http://tech.groups.yahoo.com/group/altdotnet/message/10434" rel="noreferrer">http://tech.groups.yahoo.com/group/altdotnet/message/10434</a></p>
<hr />
<p>Imagine you have an email sending class. EmailSender. Imagine you have another class WorkflowStepper. Inside WorkflowStepper you need to use EmailSender.</p>
<p>You could always say <code>new EmailSender().Send(emailMessage);</code></p>
<p>but that - the use of <code>new</code> - creates a TIGHT COUPLING that is hard to change. (this is a tiny contrived example after all)</p>
<p>So what if, instead of newing this bad boy up inside WorkflowStepper, you just passed it into the constructor?</p>
<p>So then whoever called it had to new up the EmailSender.</p>
<p><code>new WorkflowStepper(emailSender).Step()</code></p>
<p>Imagine you have hundreds of these little classes that only have one responsibility (google SRP).. and you use a few of them in WorkflowStepper:</p>
<p><code>new WorkflowStepper(emailSender, alertRegistry, databaseConnection).Step()</code></p>
<p>Imagine not worrying about the details of <code>EmailSender</code> when you are writing <code>WorkflowStepper</code> or <code>AlertRegistry</code></p>
<p>You just worry about the concern you are working with.</p>
<p>Imagine this whole graph (tree) of objects and dependencies gets wired up at RUN TIME, so that when you do this:</p>
<p><code>WorkflowStepper stepper = Container.Get<WorkflowStepper>();</code></p>
<p>you get a real deal <code>WorkflowStepper</code> with all the dependencies automatically filled in where you need them.</p>
<h2>There is no <code>new</code></h2>
<p>It just <em>happens</em> - because it knows what needs what.</p>
<p>And you can write fewer defects with better designed, DRY code in a testable and repeatable way.</p>
|
<p>Put simply. Imagine you have some class buried in your code that needs a few simple config values to do its job. That means everything that creates an instance of that class needs to get those dependencies, so you usually end up having to refactor loads of classes along the way to just pass a bit of config down to where the instance gets created.</p>
<p>So either lots of classes are needlessly altered, you bunch the config values into one big config class which is also bad... or worst still go Service Locator!</p>
<p>IoC allows your class to get all its depencencies without that hassle, and manages lifetimes of instances more explicitly too.</p>
| 15,183
|
<p>My question is based off of inheriting a great deal of legacy code that I can't do very much about. Basically, I have a device that will produce a block of data. A library which will call the device to create that block of data, for some reason I don't entirely understand and cannot change even if I wanted to, writes that block of data to disk.</p>
<p>This write is not instantaneous, but can take up to 90 seconds. In that time, the user wants to get a partial view of the data that's being produced, so I want to have a consumer thread which reads the data that the other library is writing to disk.</p>
<p>Before I even touch this legacy code, I want to mimic the problem using code I entirely control. I'm using C#, ostensibly because it provides a lot of the functionality I want.</p>
<p>In the producer class, I have this code creating a random block of data:</p>
<pre><code>FileStream theFS = new FileStream(this.ScannerRawFileName,
FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read);
//note that I need to be able to read this elsewhere...
BinaryWriter theBinaryWriter = new BinaryWriter(theFS);
int y, x;
for (y = 0; y < imheight; y++){
ushort[] theData= new ushort[imwidth];
for(x = 0; x < imwidth;x++){
theData[x] = (ushort)(2*y+4*x);
}
byte[] theNewArray = new byte[imwidth * 2];
Buffer.BlockCopy(theImage, 0, theNewArray, 0, imwidth * 2);
theBinaryWriter.Write(theNewArray);
Thread.Sleep(mScanThreadWait); //sleep for 50 milliseconds
Progress = (float)(y-1 >= 0 ? y-1 : 0) / (float)imheight;
}
theFS.Close();
</code></pre>
<p>So far, so good. This code works. The current version (using FileStream and BinaryWriter) appears to be equivalent (though slower, because of the copy) to using File.Open with the same options and a BinaryFormatter on the ushort[] being written to disk.</p>
<p>But then I add a consumer thread:</p>
<pre><code>FileStream theFS;
if (!File.Exists(theFileName)) {
//do error handling
return;
}
else {
theFS = new FileStream(theFileName, FileMode.Open,
FileAccess.Read, FileShare.Read);
//very relaxed file opening
}
BinaryReader theReader = new BinaryReader(theFS);
//gotta do this copying in order to handle byte array swaps
//frustrating, but true.
byte[] theNewArray = theReader.ReadBytes(
(int)(imheight * imwidth * inBase.Progress) * 2);
ushort[] theData = new ushort[((int)(theNewArray.Length/2))];
Buffer.BlockCopy(theNewArray, 0, theData, 0, theNewArray.Length);
</code></pre>
<p>Now, it's possible that the declaration of theNewArray is broken, and will cause some kind of read overflow. However, this code never gets that far, because it always always always breaks on trying to open the new FileStream with a System.IO.IOException that states that another process has opened the file.</p>
<p>I'm setting the FileAccess and FileShare enumerations as stated in the FileStream documentation on MSDN, but it appears that I just can't do what I want to do (ie, write in one thread, read in another). I realize that this application is a bit unorthodox, but when I get the actual device involved, I'm going to have to do the same thing, but using MFC.</p>
<p>In any event, What am I forgetting? Is what I'm wanting to do possible, since it's specified as possible in the documentation? </p>
<p>Thanks!
mmr</p>
|
<p>Your consumer must specify FileShare.ReadWrite.</p>
<p>By trying to open the file as FileShare.Read in the consumer you are saying "I want to open the file and let others read it at the same time" ... since there is <strong>already</strong> a writer that call fails, you have to allow concurrent writes with the reader.</p>
|
<p>I haven't had time to test this but I think you may need to call the Flush method of the BinaryWriter</p>
<pre><code>FileStream theFS = new FileStream(this.ScannerRawFileName,
FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read);
//note that I need to be able to read this elsewhere...
BinaryWriter theBinaryWriter = new BinaryWriter(theFS);
int y, x;
for (y = 0; y < imheight; y++){
ushort[] theData= new ushort[imwidth];
for(x = 0; x < imwidth;x++){
theData[x] = (ushort)(2*y+4*x);
}
byte[] theNewArray = new byte[imwidth * 2];
Buffer.BlockCopy(theImage, 0, theNewArray, 0, imwidth * 2);
theBinaryWriter.Write(theNewArray);
Thread.Sleep(mScanThreadWait); //sleep for 50 milliseconds
Progress = (float)(y-1 >= 0 ? y-1 : 0) / (float)imheight;
theBinaryWriter.Flush();
}
theFS.Close();
</code></pre>
<p>Sorry I haven't had time to test this. I ran into an issue with a file I was creating that was similar to this (although not exact) and a missing "Flush" was the culprit.</p>
| 15,189
|
<p>Is there a way to disable the drag&drop functionality for Solution Explorer?
Why would you ask? I'm using an wacom pen tablet for quite some years and I love
it. But when you use it in solution explorer in combination with a source control
like TFS or AnkhSvn it's a disaster when you accidentally move a file into an
different directory.</p>
<p>I currently set visual studio to prompt when files are wanted to check out, but when
a solution/project file already is checked out then the above problems still exist.</p>
|
<p>There is a plugin to Visual Studio 2010 that will prompt you drag & drop files in Solution Explorer: <a href="http://visualstudiogallery.msdn.microsoft.com/en-us/d491911d-97f3-4cf6-87b0-6a2882120acf" rel="noreferrer">http://visualstudiogallery.msdn.microsoft.com/en-us/d491911d-97f3-4cf6-87b0-6a2882120acf</a></p>
|
<p>I looks like they have finally attempted to enable this functionality in 2017 Community (15.7.5)</p>
<p>Tools -> Options -> Projects and Solutions -> General -> "Prompt before moving files to a new location"</p>
<p>I say attempted because I have still had occasions where this setting hasn't displayed the dialog box, so as of V15.7.5 it is a little buggy still.</p>
| 43,635
|
<p>When I dynamically create a Datagrid and add in a new buttoncolumn how do I access the buttoncolumn_click event? </p>
<p>Thanks.</p>
|
<pre><code>protected void Page_Load(object sender, EventArgs e)
{
DataGrid dg = new DataGrid();
dg.GridLines = GridLines.Both;
dg.Columns.Add(new ButtonColumn {
CommandName = "add",
HeaderText = "Event Details",
Text = "Details",
ButtonType = ButtonColumnType.PushButton
});
dg.DataSource = getDataTable();
dg.DataBind();
dg.ItemCommand += new DataGridCommandEventHandler(dg_ItemCommand);
pnlMain.Controls.Add(dg);
}
protected void dg_ItemCommand(object source, DataGridCommandEventArgs e)
{
if (e.CommandName == "add")
{
throw new Exception("add it!");
}
}
protected DataTable getDataTable()
{
// returns your data table
}
</code></pre>
|
<p>This article on the MSDN site clearly explains how to go about <a href="http://msdn.microsoft.com/en-us/library/aa984252(VS.71).aspx" rel="nofollow noreferrer">adding a button into a datagrid</a>. Instead of using the click event of the button you'll use the command event of the DataGrid. Each button will be passing specific commandarguments that you will set.</p>
<p>This article shows <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.command.aspx" rel="nofollow noreferrer">how to use the command event with buttons</a>. In it you use CommandArguments and CommandNames.</p>
| 18,052
|
<p>In my spring application context file, I have something like:</p>
<pre><code><util:map id="someMap" map-class="java.util.HashMap" key-type="java.lang.String" value-type="java.lang.String">
<entry key="some_key" value="some value" />
<entry key="some_key_2" value="some value" />
</util:map>
</code></pre>
<p>In java class, the implementation looks like:</p>
<pre><code>private Map<String, String> someMap = new HashMap<String, String>();
someMap = (HashMap<String, String>)getApplicationContext().getBean("someMap");
</code></pre>
<p>In Eclipse, I see a warning that says:</p>
<p><strong>Type safety: Unchecked cast from Object to HashMap<String,String></strong></p>
<p>What went wrong?</p>
|
<p>Well, first of all, you're wasting memory with the new <code>HashMap</code> creation call. Your second line completely disregards the reference to this created hashmap, making it then available to the garbage collector. So, don't do that, use:</p>
<pre><code>private Map<String, String> someMap = (HashMap<String, String>)getApplicationContext().getBean("someMap");
</code></pre>
<p>Secondly, the compiler is complaining that you cast the object to a <code>HashMap</code> without checking if it is a <code>HashMap</code>. But, even if you were to do:</p>
<pre><code>if(getApplicationContext().getBean("someMap") instanceof HashMap) {
private Map<String, String> someMap = (HashMap<String, String>)getApplicationContext().getBean("someMap");
}
</code></pre>
<p>You would probably still get this warning. The problem is, <code>getBean</code> returns <code>Object</code>, so it is unknown what the type is. Converting it to <code>HashMap</code> directly would not cause the problem with the second case (and perhaps there would not be a warning in the first case, I'm not sure how pedantic the Java compiler is with warnings for Java 5). However, you are converting it to a <code>HashMap<String, String></code>.</p>
<p>HashMaps are really maps that take an object as a key and have an object as a value, <code>HashMap<Object, Object></code> if you will. Thus, there is no guarantee that when you get your bean that it can be represented as a <code>HashMap<String, String></code> because you could have <code>HashMap<Date, Calendar></code> because the non-generic representation that is returned can have any objects.</p>
<p>If the code compiles, and you can execute <code>String value = map.get("thisString");</code> without any errors, don't worry about this warning. But if the map isn't completely of string keys to string values, you will get a <code>ClassCastException</code> at runtime, because the generics cannot block this from happening in this case.</p>
|
<p>Another solution, if you find yourself casting the same object a lot and you don't want to litter your code with <code>@SupressWarnings("unchecked")</code>, would be to create a method with the annotation. This way you're centralizing the cast, and hopefully reducing the possibility for error.</p>
<pre><code>@SuppressWarnings("unchecked")
public static List<String> getFooStrings(Map<String, List<String>> ctx) {
return (List<String>) ctx.get("foos");
}
</code></pre>
| 32,834
|
<p>I'd like some sorthand for this:</p>
<pre><code>Map rowToMap(row) {
def rowMap = [:];
row.columns.each{ rowMap[it.name] = it.val }
return rowMap;
}
</code></pre>
<p>given the way the GDK stuff is, I'd expect to be able to do something like:</p>
<pre><code>Map rowToMap(row) {
row.columns.collectMap{ [it.name,it.val] }
}
</code></pre>
<p>but I haven't seen anything in the docs... am I missing something? or am I just way too lazy?</p>
|
<p>I've recently came across the need to do exactly that: converting a list into a map. This question was posted before Groovy version 1.7.9 came out, so the method <a href="http://docs.groovy-lang.org/latest/html/api/org/codehaus/groovy/runtime/DefaultGroovyMethods.html#collectEntries(java.lang.Iterable,%20groovy.lang.Closure)" rel="noreferrer"><code>collectEntries</code></a> didn't exist yet. It works exactly as the <code>collectMap</code> method <a href="https://stackoverflow.com/questions/18538/shortcut-for-creating-a-map-from-a-list-in-groovy/19077#19077">that was proposed</a>:</p>
<pre><code>Map rowToMap(row) {
row.columns.collectEntries{[it.name, it.val]}
}
</code></pre>
<p>If for some reason you are stuck with an older Groovy version, the <a href="http://docs.groovy-lang.org/latest/html/api/org/codehaus/groovy/runtime/DefaultGroovyMethods.html#inject(java.lang.Object,%20groovy.lang.Closure)" rel="noreferrer"><code>inject</code></a> method can also be used (as proposed <a href="https://stackoverflow.com/questions/18538/shortcut-for-creating-a-map-from-a-list-in-groovy/198614#198614">here</a>). This is a slightly modified version that takes only one expression inside the closure (just for the sake of character saving!):</p>
<pre><code>Map rowToMap(row) {
row.columns.inject([:]) {map, col -> map << [(col.name): col.val]}
}
</code></pre>
<p>The <code>+</code> operator can also be used instead of the <code><<</code>.</p>
|
<p>What about something like this?</p>
<pre><code>// setup
class Pair {
String k;
String v;
public Pair(def k, def v) { this.k = k ; this.v = v; }
}
def list = [ new Pair('a', 'b'), new Pair('c', 'd') ]
// the idea
def map = [:]
list.each{ it -> map.putAt(it.k, it.v) }
// verify
println map['c']
</code></pre>
| 3,910
|
<p>We encountered a problem with using Subversion on Windows. A developer committed a file <code>foo.Data.sql</code> and later another developer committed a file called <code>foo.data.sql</code>. Naturally, this caused a problem on Windows clients (all clients are Windows in our environments) because files are case sensitive in Subversion but not in Windows.</p>
<p>We managed to resolve this problem by deleting one of the files directly in the repository, but I still have two questions:</p>
<ol>
<li>How is it possible for a developer to do this using a Windows client? Does he have an invalid working copy, or is there a bug in the client (TortoiseSVN)?</li>
<li>How can we prevent changes like these from entering the repository (i.e. has anyone written a hook script that performs a sanity check for file casing issues)?</li>
</ol>
|
<p>There is definitely a hook script that checks case sensitivity - Sourceforge have it as one of their options. A quick google turns up: <a href="http://www.subversionary.org/howto/using-check-case-insensitive-py-on-windows" rel="nofollow noreferrer">http://www.subversionary.org/howto/using-check-case-insensitive-py-on-windows</a> and <a href="http://svn.apache.org/repos/asf/subversion/trunk/contrib/hook-scripts/case-insensitive.py" rel="nofollow noreferrer">http://svn.apache.org/repos/asf/subversion/trunk/contrib/hook-scripts/case-insensitive.py</a></p>
<p>The issue will have arisen on a windows platform if user 1 added foo.data.sql and user 2 added foo.Data.sql before getting an update from user 1. </p>
<p>Hope that helps :)</p>
|
<p>1; It is possible, because the two files came from two developers. One is renaming or creating the file with different cases and during commit does not realise that it will be an add not a commit changes.</p>
<p>2; Check <a href="http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-rename.html#tsvn-dug-renameincase" rel="nofollow noreferrer">TortoiseSVN FAQ</a></p>
| 7,989
|
<p>We have a large database on which we have DB side pagination. This is quick, returning a page of 50 rows from millions of records in a small fraction of a second.</p>
<p>Users can define their own sort, basically choosing what column to sort by. Columns are dynamic - some have numeric values, some dates and some text.</p>
<p>While most sort as expected text sorts in a dumb way. Well, I say dumb, it makes sense to computers, but frustrates users.</p>
<p>For instance, sorting by a string record id gives something like:</p>
<pre><code>rec1
rec10
rec14
rec2
rec20
rec3
rec4
</code></pre>
<p>...and so on.</p>
<p>I want this to take account of the number, so:</p>
<pre><code>rec1
rec2
rec3
rec4
rec10
rec14
rec20
</code></pre>
<p>I can't control the input (otherwise I'd just format in leading 000s) and I can't rely on a single format - some are things like "{alpha code}-{dept code}-{rec id}".</p>
<p>I know a few ways to do this in C#, but can't pull down all the records to sort them, as that would be to slow.</p>
<p>Does anyone know a way to quickly apply a natural sort in Sql server?</p>
<hr>
<p>We're using:</p>
<pre><code>ROW_NUMBER() over (order by {field name} asc)
</code></pre>
<p>And then we're paging by that.</p>
<p>We can add triggers, although we wouldn't. All their input is parametrised and the like, but I can't change the format - if they put in "rec2" and "rec10" they expect them to be returned just like that, and in natural order.</p>
<hr>
<p>We have valid user input that follows different formats for different clients.</p>
<p>One might go rec1, rec2, rec3, ... rec100, rec101</p>
<p>While another might go: grp1rec1, grp1rec2, ... grp20rec300, grp20rec301</p>
<p>When I say we can't control the input I mean that we can't force users to change these standards - they have a value like grp1rec1 and I can't reformat it as grp01rec001, as that would be changing something used for lookups and linking to external systems.</p>
<p>These formats vary a lot, but are often mixtures of letters and numbers.</p>
<p>Sorting these in C# is easy - just break it up into <code>{ "grp", 20, "rec", 301 }</code> and then compare sequence values in turn.</p>
<p>However there may be millions of records and the data is paged, I need the sort to be done on the SQL server.</p>
<p>SQL server sorts by value, not comparison - in C# I can split the values out to compare, but in SQL I need some logic that (very quickly) gets a single value that consistently sorts.</p>
<p>@moebius - your answer might work, but it does feel like an ugly compromise to add a sort-key for all these text values.</p>
|
<p>Most of the SQL-based solutions I have seen break when the data gets complex enough (e.g. more than one or two numbers in it). Initially I tried implementing a NaturalSort function in T-SQL that met my requirements (among other things, handles an arbitrary number of numbers within the string), but the performance was <em>way</em> too slow.</p>
<p>Ultimately, I wrote a scalar CLR function in C# to allow for a natural sort, and even with unoptimized code the performance calling it from SQL Server is blindingly fast. It has the following characteristics:</p>
<ul>
<li>will sort the first 1,000 characters or so correctly (easily modified in code or made into a parameter)</li>
<li>properly sorts decimals, so 123.333 comes before 123.45</li>
<li>because of above, will likely NOT sort things like IP addresses correctly; if you wish different behaviour, modify the code</li>
<li>supports sorting a string with an arbitrary number of numbers within it</li>
<li>will correctly sort numbers up to 25 digits long (easily modified in code or made into a parameter)</li>
</ul>
<p>The code is here:</p>
<pre><code>using System;
using System.Data.SqlTypes;
using System.Text;
using Microsoft.SqlServer.Server;
public class UDF
{
[SqlFunction(DataAccess = DataAccessKind.None, IsDeterministic=true)]
public static SqlString Naturalize(string val)
{
if (String.IsNullOrEmpty(val))
return val;
while(val.Contains(" "))
val = val.Replace(" ", " ");
const int maxLength = 1000;
const int padLength = 25;
bool inNumber = false;
bool isDecimal = false;
int numStart = 0;
int numLength = 0;
int length = val.Length < maxLength ? val.Length : maxLength;
//TODO: optimize this so that we exit for loop once sb.ToString() >= maxLength
var sb = new StringBuilder();
for (var i = 0; i < length; i++)
{
int charCode = (int)val[i];
if (charCode >= 48 && charCode <= 57)
{
if (!inNumber)
{
numStart = i;
numLength = 1;
inNumber = true;
continue;
}
numLength++;
continue;
}
if (inNumber)
{
sb.Append(PadNumber(val.Substring(numStart, numLength), isDecimal, padLength));
inNumber = false;
}
isDecimal = (charCode == 46);
sb.Append(val[i]);
}
if (inNumber)
sb.Append(PadNumber(val.Substring(numStart, numLength), isDecimal, padLength));
var ret = sb.ToString();
if (ret.Length > maxLength)
return ret.Substring(0, maxLength);
return ret;
}
static string PadNumber(string num, bool isDecimal, int padLength)
{
return isDecimal ? num.PadRight(padLength, '0') : num.PadLeft(padLength, '0');
}
}
</code></pre>
<p>To register this so that you can call it from SQL Server, run the following commands in Query Analyzer:</p>
<pre><code>CREATE ASSEMBLY SqlServerClr FROM 'SqlServerClr.dll' --put the full path to DLL here
go
CREATE FUNCTION Naturalize(@val as nvarchar(max)) RETURNS nvarchar(1000)
EXTERNAL NAME SqlServerClr.UDF.Naturalize
go
</code></pre>
<p>Then, you can use it like so:</p>
<pre><code>select *
from MyTable
order by dbo.Naturalize(MyTextField)
</code></pre>
<p><strong>Note</strong>: If you get an error in SQL Server along the lines of <em>Execution of user code in the .NET Framework is disabled. Enable "clr enabled" configuration option.</em>, follow the instructions <a href="http://www.novicksoftware.com/TipsAndTricks/tip-sql-server-2005-enable-clr-programming.htm" rel="nofollow noreferrer">here</a> to enable it. Make sure you consider the security implications before doing so. If you are not the db admin, make sure you discuss this with your admin before making any changes to the server configuration.</p>
<p><strong>Note2</strong>: This code does not properly support internationalization (e.g., assumes the decimal marker is ".", is not optimized for speed, etc. Suggestions on improving it are welcome!</p>
<p><strong>Edit:</strong> Renamed the function to <em>Naturalize</em> instead of <em>NaturalSort</em>, since it does not do any actual sorting.</p>
|
<p>I still don't understand (probably because of my poor English).</p>
<p>You could try:</p>
<pre><code>ROW_NUMBER() OVER (ORDER BY dbo.human_sort(field_name) ASC)
</code></pre>
<p>But it won't work for millions of records.</p>
<p>That why I suggested to use trigger which <em>fills</em> <em>separate</em> column with <em>human value</em>.</p>
<p>Moreover:</p>
<ul>
<li>built-in T-SQL functions are really
slow and Microsoft suggest to use
.NET functions instead.</li>
<li><em>human value</em> is constant so there is no point calculating it each time
when query runs.</li>
</ul>
| 5,477
|
<p>Is it possible to have a WPF window/element detect the drag'n'dropping of a file from windows explorer in C# .Net 3.5? I've found solutions for WinForms, but none for WPF.</p>
|
<p>Unfortunately, TextBox, RichTextBox, and FlowDocument viewers always mark drag-and-drop events as handled, which prevents them from bubbling up to your handlers. You can restore drag-and-drop events being intercepted by these controls by force-handling the drag-and-drop events (use UIElement.AddHandler and set handledEventsToo to true) and setting e.Handled to false in your handler.</p>
|
<p>I had similar Issue, The drop events and drag enter events were not fired. The issue was with the windows User Account Settings. Set it to least secure setting and try the same code it works. </p>
| 43,140
|
<p>I have a solution consisting of five projects, each of which compile to separate assemblies. Right now I'm code-signing them, but I'm pretty sure I'm doing it wrong. What's the best practice here?</p>
<ul>
<li>Sign each with a different key; make sure the passwords are different</li>
<li>Sign each with a different key; use the same password if you want</li>
<li>Sign each with the same key</li>
<li>Something else entirely</li>
</ul>
<p>Basically I'm not quite sure what "signing" does to them, or what the best practices are here, so a more generally discussion would be good. All I really know is that <a href="http://en.wikipedia.org/wiki/FxCop" rel="noreferrer">FxCop</a> yelled at me, and it was easy to fix by clicking the "Sign this assembly" checkbox and generating a .pfx file using Visual Studio (2008).</p>
|
<p>If your only objective is to stop FxCop from yelling at you, then you have found the best practice.</p>
<p>The best practice for signing your assemblies is something that is completely dependent on your objectives and needs. We would need more information like your intended deployment:</p>
<ul>
<li>For personal use</li>
<li>For use on corporate network PC's as a client application</li>
<li>Running on a web server</li>
<li>Running in SQL Server</li>
<li>Downloaded over the internet</li>
<li>Sold on a CD in shrink wrap</li>
<li>Uploaded straight into a cybernetic brain</li>
<li>Etc.</li>
</ul>
<p>Generally you use code signing to verify that the Assemblies came from a specific trusted source and have not been modified. <strong><em>So each with the same key is fine.</em></strong> Now how that trust and identity is determined is another story.</p>
<p><strong>UPDATE:</strong> How this benefits your end users when you are deploying over the web is if you have obtained a <a href="http://www.thawte.com/code-signing/index.html?click=main-nav-products-codesigning" rel="noreferrer">software signing certificate from a certificate authority</a>. Then when they download your assemblies they can verify they came from <em>Domenic's Software Emporium</em>, and they haven't been modified or corrupted along the way. You will also want to sign the installer when it is downloaded. This prevents the warning that some browsers display that it has been obtained from an unknown source.</p>
<p>Note, you will pay for a software signing certificate. What you get is the certificate authority become the trusted 3rd party who verifies you are who you say you are. This works because of a web of trust that traces its way back to a root certificate that is installed in their operating system. There are a few certificate authorities to choose from, but you will want to make sure they are supported by the root certificates on the target operating system.</p>
|
<p>Signing is used to uniquely identify an assembly. More details are in <em><a href="http://msdn.microsoft.com/en-us/library/ms247123%28VS.80%29.aspx" rel="nofollow noreferrer">How to: Sign an Assembly (Visual Studio)</a></em>.</p>
<p>In terms of best practice, it's fine to use the same key as long as the assemblies have different names.</p>
| 5,585
|
<p>The Eclipse projects are all stored in the Eclipse Foundation CVS servers. Using the source is a great way to debug your code and to figure out how to do new things. </p>
<p>Unfortunately in a large software project like BIRT, it can be difficult to know which projects and versions are required for a particular build. So what is the best way to get the source for a particular build?</p>
|
<p>Use <a href="https://docs.python.org/3/library/itertools.html#itertools.permutations" rel="noreferrer"><code>itertools.permutations</code></a> from the <strong>standard library</strong>:</p>
<pre><code>import itertools
list(itertools.permutations([1, 2, 3]))
</code></pre>
<hr />
<p>Adapted from <a href="http://code.activestate.com/recipes/252178/" rel="noreferrer">here</a> is a demonstration of how <code>itertools.permutations</code> might be implemented:</p>
<pre><code>def permutations(elements):
if len(elements) <= 1:
yield elements
return
for perm in permutations(elements[1:]):
for i in range(len(elements)):
# nb elements[0:1] works in both string and list contexts
yield perm[:i] + elements[0:1] + perm[i:]
</code></pre>
<p>A couple of alternative approaches are listed in the documentation of <code>itertools.permutations</code>. Here's one:</p>
<pre><code>def permutations(iterable, r=None):
# permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
# permutations(range(3)) --> 012 021 102 120 201 210
pool = tuple(iterable)
n = len(pool)
r = n if r is None else r
if r > n:
return
indices = range(n)
cycles = range(n, n-r, -1)
yield tuple(pool[i] for i in indices[:r])
while n:
for i in reversed(range(r)):
cycles[i] -= 1
if cycles[i] == 0:
indices[i:] = indices[i+1:] + indices[i:i+1]
cycles[i] = n - i
else:
j = cycles[i]
indices[i], indices[-j] = indices[-j], indices[i]
yield tuple(pool[i] for i in indices[:r])
break
else:
return
</code></pre>
<p>And another, based on <code>itertools.product</code>:</p>
<pre><code>def permutations(iterable, r=None):
pool = tuple(iterable)
n = len(pool)
r = n if r is None else r
for indices in product(range(n), repeat=r):
if len(set(indices)) == r:
yield tuple(pool[i] for i in indices)
</code></pre>
|
<p>for Python we can use itertools and import both permutations and combinations to solve your problem</p>
<pre><code>from itertools import product, permutations
A = ([1,2,3])
print (list(permutations(sorted(A),2)))
</code></pre>
| 13,002
|
<p>Say you want a simple maze on an N by M grid, with one path through, and a good number of dead ends, but that looks "right" (i.e. like someone made it by hand without too many little tiny dead ends and all that). Is there a known way to do this?</p>
|
<p>From <a href="http://www.astrolog.org/labyrnth/algrithm.htm" rel="noreferrer">http://www.astrolog.org/labyrnth/algrithm.htm</a></p>
<blockquote>
<p>Recursive backtracker: This is somewhat related to the recursive backtracker solving method described below, and requires stack up to the size of the Maze. When carving, be as greedy as possible, and always carve into an unmade section if one is next to the current cell. Each time you move to a new cell, push the former cell on the stack. If there are no unmade cells next to the current position, pop the stack to the previous position. The Maze is done when you pop everything off the stack. This algorithm results in Mazes with about as high a "river" factor as possible, with fewer but longer dead ends, and usually a very long and twisty solution. It runs quite fast, although Prim's algorithm is a bit faster. Recursive backtracking doesn't work as a wall adder, because doing so tends to result in a solution path that follows the outside edge, where the entire interior of the Maze is attached to the boundary by a single stem. </p>
</blockquote>
<p>They produce only 10% dead ends</p>
<p><img src="https://i.stack.imgur.com/vWo6P.gif"></p>
<p>is an example of a maze generated by that method.</p>
|
<p>Here's the DFS algorithm written as pseudocode: </p>
<p>create a CellStack (LIFO) to hold a list of cell locations<br>
set TotalCells = number of cells in grid<br>
choose a cell at random and call it CurrentCell<br>
set VisitedCells = 1 </p>
<p>while VisitedCells < TotalCells
find all neighbors of CurrentCell with all walls intact<br>
if one or more found
choose one at random<br>
knock down the wall between it and CurrentCell<br>
push CurrentCell location on the CellStack<br>
make the new cell CurrentCell<br>
add 1 to VisitedCells
else
pop the most recent cell entry off the CellStack<br>
make it CurrentCell
endIf
endWhile </p>
| 5,940
|
<p>Why is the following?:</p>
<pre><code> const int i0 = 5;
//int i1 = const_cast<int>(i0); // compilation error
int i2 = (int)i0; // okay
int i3 = 5;
//const int i4 = const_cast<const int>(i3); // compilation error
const int i5 = (const int)i3; // okay
</code></pre>
|
<pre><code> const int i0 = 5;
//int i1 = const_cast<int>(i0); // compilation error
int i2 = (int)i0; // okay
int i3 = 5;
//const int i4 = const_cast<const int>(i3); // compilation error
const int i5 = (const int)i3; // okay
</code></pre>
<p>The compilation errors are caused because you don't cast const away/add const. Instead, you copy i0. For that operation, no cast is required at all:</p>
<pre><code>int i1 = i0;
const int i4 = i3;
</code></pre>
<p>The type you cast to should actually be a pointer or reference. Otherwise, using const_cast doesn't make sense since you could straight copy it. For pointers, for example, you can cast away the const, because dereferencing the pointer will yield another type for a <code>const T*</code> (yields <code>const T</code>) than for a <code>T*</code> (yields <code>T</code>). For references, the same is true: <code>T&</code> will access the object using another <em>this</em> pointer type than using <code>const T&</code>. Now what you really wanted to archive:</p>
<pre><code> const int i0 = 5;
//int & i1 = const_cast<int&>(i0); // okay (but dangerous)
int & i2 = (int&)i0; // okay (but dangerous)
int i3 = 5;
//const int&i4 = const_cast<const int&>(i3); // ok now and valid!
const int&i5 = (const int&)i3; // okay too!
</code></pre>
<p>The above can lead to undefined behavior, when you write to an originally const object through a reference to non-const (actually, merely casting and reading it isn't undefined behavior in itself. But if you're casting away const, you may also write to it, which then yields the undefined behavior)</p>
|
<p>For the first error. const_cast can only be used on pointer or reference types. "int" is neither. This may or may not be the C++ standard (couldn't find a good reference). But it is the case for certain implementations such as MS's C++ compiler.</p>
<p>For the second error. const_cast can only be used to remove a const or volatile qualifier not add it. </p>
<p>Reference: <a href="http://msdn.microsoft.com/en-us/library/bz6at95h(VS.80).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/bz6at95h(VS.80).aspx</a></p>
| 48,414
|
<p>I have a strange bug with WPF Interop and an Excel Addin. I'm using .Net 3.5 SP1.</p>
<p>I'm using Add-in Express to create a Custom Task Pane for Excel 2003. Within that taskpane I'm using ElementHost to host a WPF UserControl. The UserControl simply contains a Grid with a TextBox and ComboBox. My problem is that whilst everything displays properly, the ComboBox won't stay dropped-down unless I hold the mouse down over the down-arrow.</p>
<p>I don't believe this is necessarily related to Add-in Express because I've had a similar problem when I tried displaying a WPF window modelessly in Excel.</p>
<p>A second problem is that the ComboBox seems reluctant to give up focus. If I click it, the text area goes grey to indicate that it has focus, but I can't move focus anywhere else in the window. The only way to wrest focus away is to move the mousewheel.</p>
<p>Anybody else had a similar problem, and managed to fix it?</p>
|
<p>Add-in Express looked into this for me, and it turns out to have something to do with the Window style of the Task Pane that gets added to Excel. If you turn off the WS_CHILD flag in the Windows CreateParams then Combo Boxes and other popups work as expected. </p>
<p>They gave me this snippet of code to add to my ADXExcelTaskPane:</p>
<pre><code>private const uint WS_CHILD = 0x40000000;
private const uint WS_CLIPCHILDREN = 0x02000000;
private const uint WS_CLIPSIBLINGS = 0x04000000;
private CreateParams _CreateParams = new CreateParams();
protected override CreateParams CreateParams
{
get
{
_CreateParams = base.CreateParams;
if (!DesignMode)
_CreateParams.Style = (int)(WS_CLIPCHILDREN | WS_CLIPSIBLINGS); //| WS_CHILD
return _CreateParams;
}
}
</code></pre>
|
<p>I had the same problem. I have a WPF user control hosted in a WinForm user control and the whole is an Excel AddIn. I work with Visual Studio 2010 and Excel 2007 and Excel 2010.</p>
<p>My problem was that when I clicked once in the Excel sheet, the AddIn never gains focus again.
I found a workaround. </p>
<ol>
<li>In the constructor of my WinForm user control, I register on the event MouseEnter of my WPF user control.</li>
<li><p>In the MouseEnter event handler, I give the focus to myself (this.Focus())</p>
<pre><code>public WpfContainerUserControl()
{
InitializeComponent();
GpecsBrowserTabUserControl gpecBrowser = elementHost1.Child as GpecsBrowserTabUserControl;
gpecBrowser.MouseEnter += new System.Windows.Input.MouseEventHandler(gpecBrowser_MouseEnter);
}
void gpecBrowser_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
{
this.Focus();
}
</code></pre></li>
</ol>
| 22,123
|
<p>I've been handing a design for a webpage which I'm trying to implement correctly. This design contains navigation elements which are partially or entirely duplicated all over the page - in particular, links to the main 3 categories for navigation are present on the page no less than 4 times.</p>
<p>I'm no web design expert, but I don't like the idea of having the same content duplicated in the html. Can I use CSS so that my html contains a single list of navigation links in a sane format, but the standard browser view contains multiple partial duplicates?</p>
<p>(Also, assuming this is possible, is it a good idea? or would I be better just getting used to the idea that my html is going to contain the same links 4 times?)</p>
<p>EDIT: Actually generating the nav links is not an issue; I was looking to clean up the output html</p>
|
<h2>Sort of Possible, But Still Not Sure You Would Want To</h2>
<p><strong>And poses some serious challenges which varies depending on the context.</strong></p>
<p>One problem is that your stated goal is to reduce html clutter and redundancy. However, to have a link, you still need to have an anchor element (<code><a></a></code>) as the root for the link. </p>
<p>Nevertheless, <strong>one way</strong> you could do something like that with today's browsers (now that pseudo-elements are more generally supported) is to divorce the text from the <code>a</code> which leaves an <em>empty</em> anchor in your code. So you still have the HTML <code>a</code> in the code, but eliminates any redundant <em>text</em>. How useful really is that? Not very is my thought. Especially if you are dealing at all with <em>inline</em> links that <em>are part of the text</em>, because what you would do is then add text to those links via the pseudo-element, something like:</p>
<pre><code>a[href='#oneUrl']:before {
content: 'your anchor text';
}
</code></pre>
<p>Look at <a href="http://jsfiddle.net/hSNLr/8/">this fiddle example</a>. </p>
<p>However, there is <strong>another way <em>that reduces HTML further</em></strong>, but has some other severe limitations. You could have links in the text itself (let's say), which allows for relevant real content wording in those. However, each of those can have two (<em>max</em> at present) pseudo-elements associated that could "extend" to be separate links in headers, footers, etc. Look at <a href="http://jsfiddle.net/hSNLr/15/">this fiddle example</a>. Obviously, this requires you to be able to precisely locate those links (perhaps using <code>position: fixed</code> as the example has), which can be challenging. A big issue, however, is that search engines are not going to pick up those extra links or their text, and screen readers are not either, so your "main navigation" actually becomes <em>invisible</em> to some extent. That would seem to be undesirable to me, but <em>it does indeed limit your html redundancy</em>. </p>
|
<p>I think you will use HTML includes and SSI or server side includes to incorporate same methods on same pages,
this is the format for the which you will use.
<code><!--#include virtual="path to file/include-file.html" --></code>, always include that file in every pages that is similar..
just go to this link..<a href="http://webdesign.about.com/od/ssi/a/aa052002a.htm" rel="nofollow">http://webdesign.about.com/od/ssi/a/aa052002a.htm</a></p>
| 45,453
|
<p>I am facing a performance issue on a multi-core (8+) architecture with software written in C++ / VistualStudio / WindowsXP.</p>
<p>Suddenly I realized that I have no idea of the performances of my L1 and L2 cache and CPU->to->Memory bandwidth.</p>
<p>I have tested several tools (including VTune, Glowcode, etc, etc) but all of them fails when tested on load in a multicore architecture (which is the very reason why I need them!).</p>
<p>Can you suggest any other tool which is not so fancy in doing graphs but can give me at least few indications of my cache/memory performances or can suggest snippets of code to manually instrument my application?</p>
<p>Thanks!</p>
|
<pre><code>set WshShell = WScript.CreateObject("WScript.Shell")
WScript.Sleep(100)
WshShell.Run "%SystemRoot%\system32\sndrec32.exe"
WScript.Sleep(100)
WshShell.AppActivate "Sound - Sound Recorder"
WScript.Sleep(100)
WshShell.SendKeys " "
WScript.Sleep(100)
</code></pre>
<p>Save the above text as RunSoundRecorder.vbs. This will start the sound record application and start it recording. Just point the task scheduler at this file.</p>
<p>Incase you want to make changes:<br>
The third line is the exe to run<br>
The fifth line is the what is in the application title bar.</p>
|
<p>Start-Programs-Accessories-System Tools-Scheduled Tasks</p>
| 20,045
|
<p>Let's say the first N integers divisible by 3 starting with 9.</p>
<p>I'm sure there is some one line solution using lambdas, I just don't know it that area of the language well enough yet.</p>
|
<p>Just to be different (and to avoid using a where statement) you could also do:</p>
<pre><code>var numbers = Enumerable.Range(0, n).Select(i => i * 3 + 9);
</code></pre>
<p><strong>Update</strong> This also has the benefit of not running out of numbers.</p>
|
<p>I can't say this is any good, I'm not a C# expert and I just whacked it out, but I think it's probably a canonical example of the use of <code>yield</code>.</p>
<pre><code>internal IEnumerable Answer(N)
{
int n=0;
int i=9;
while (true)
{
if (i % 3 == 0)
{
n++;
yield return i;
}
if (n>=N) return;
i++;
}
}
</code></pre>
| 9,302
|
<p>I am running a query from ASP using a MySQL database, I want to create a variable (ssResult) based on the result with a person's name (fullname), if the record does not exist I want to assign the text 'N/A' to the variable, code below, I currently use a function getOther for my database connections which passes the column name "fullname":</p>
<pre><code>ssResult = getOtherElse("SELECT fullname FROM table WHERE id=" & inArr(j), "fullname")
</code></pre>
<p>Below is the code for the function getOtherElse which only works when a result is returned but not when there is an empty result:</p>
<pre><code>Function getOtherElse(inSQL, getColumn)
Dim conn, rstemp
Set conn = Server.CreateObject("ADODB.Connection")
conn.open myDSN
Set Session("lp_conn") = conn
Set rstemp = Server.CreateObject("ADODB.Recordset")
rstemp.Open inSQL, conn
if not rstemp.eof then
rstemp.movefirst
getOtherElse=rstemp.fields(getColumn)
else
getOtherElse="N/A"
end if
rstemp.close
set rstemp=nothing
conn.close
set conn=nothing
End Function
</code></pre>
<p>Thanks!</p>
|
<p>You could try changing the line</p>
<pre><code>if not rstemp.eof then
</code></pre>
<p>with</p>
<pre><code>if rstemp.RecordCount > 0 then
</code></pre>
|
<p>Why not change the SQL to only pull out a result with a First Name, that way the "N/A" would apply:</p>
<pre>sResult = getOtherElse("SELECT fullname FROM table WHERE id=" & inArr(j), "fullname AND fullname<>''")</pre>
| 41,003
|
<p>I'd like to allow a user to open files in their own client applications via Silverlight. I'd like this to work similarly to WebDAV, in the sense that they could read/write the file back into Silverlight's isolated storage...</p>
<p>Is it possible to construct a file:// link to an isolated storage file?
Is there a uri scheme that is defined for silverlight in a browser that has the silverlight plugin?</p>
<p>Am I totally nuts?</p>
|
<p>You can use Windows server to create users that are allowed to access your SQL Server database. Then you can use integrated windows login in connection strings. </p>
<p>BTW Storing passwords in public MDB renders them irelevant. Same as they don't exist. </p>
|
<p>Is it not possible to move to Window Integrated Security in the connection strings, then you do not have to worry about the security aspect as much (unless you need to secure the actual location of the connection I guess). </p>
| 41,034
|
<p>Other than using raw XML, is there an easy way in .NET to open and read a config file belonging to another assembly...? I don't need to write to it, just grab a couple of values from it.</p>
|
<p><a href="http://msdn.microsoft.com/en-us/library/ms224437.aspx" rel="nofollow noreferrer">Here's</a> MSDN on OpenExeConfiguration.</p>
<p>Edit: <a href="http://www.eggheadcafe.com/software/aspnet/32181042/using-configurationmanage.aspx" rel="nofollow noreferrer">link</a> to a how-to on eggheadcafe.com disappeared. Looks like EggheadCafe moved to NullSkull but dropped the article ID's.</p>
|
<p>Or perhaps you could Serialize a simple class with the [Serializable()] attribute to a file... and deserialize in the other app...</p>
<p><a href="http://www.dotnetperls.com/serialize-list" rel="nofollow">http://www.dotnetperls.com/serialize-list</a><br />
<a href="http://msdn.microsoft.com/en-us/library/system.serializableattribute.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/system.serializableattribute.aspx</a></p>
<p>The sample program shows one short bit of code to serialize to a file and another to read file...</p>
<p>You can serialize to a file, to XML, to SOAP...</p>
| 29,664
|
<p>I am implementing a quite simple state-machine order processing application. It is a e-commerce application with a few twists. The users of the application will not be editing workflows by themselves.</p>
<p>Microsoft claims that asp.net and Windows Workflow is possible to combine. How hard is it to install and maintain a combination of asp.net and Windows Workflow? I would be keeping the workflow state in sql-server.</p>
<p>Is it easier for me to roll my own state machine code or is Windows Workflow the right tool for the job? </p>
|
<p>Asp.net and WF get along just fine, and WF doesn't add much maintenance overhead.</p>
<p>Whether or not this is the right design for you depends a lot on your needs. If you have a lot of event driven actions then WF might be worthwhile, otherwise the overhead of rolling your own tracking would probably add less complexity to the system.</p>
<p>WF is reasonably easy to work with so I'd suggest working up a prototype and experimenting with it.</p>
<p>Also, in my opinion, based on your requirements, I doubt WF would be the right solution for you.</p>
|
<p>If your state machine is very simple, then I would say that you should just roll your own. You have more control over everything. You can deal with persistence on your own terms and not worry about how they do it.</p>
<p>WF does look pretty cool though, but I think that it's power probably lies in the fact that it is easy to tie it into frameworks like CRM and Sharepoint. If you are going to use these in your application, then I would definitely consider using WF.</p>
<p>Full disclosure: I am definitely not a WF expert.</p>
| 9,269
|
<p>I got this error when trying to run a query in SQL server query analyzer.
What is the reason?</p>
|
<p>If you're using cursors, then you've probably closed the cursor. Check out MSDN for more information (<a href="http://support.microsoft.com/kb/15169" rel="nofollow noreferrer">http://support.microsoft.com/kb/15169</a>3)</p>
<p>If you're not using cursors, then it could be an issue with the server, check the log.</p>
|
<p>And before it's lost to the sands of time, the KB article:</p>
<hr />
<p>Article ID: 151693 - Last Review: October 3, 2003 - Revision: 3.0</p>
<h1><a href="https://web.archive.org/web/20091123103812/http://support.microsoft.com/kb/151693" rel="nofollow noreferrer">FIX: Err Msg "Unknown Token Received from SQL Server"</a></h1>
<h2>Symptoms</h2>
<p>When you set the statement options to use a server-side cursor and prepare a select statement on a SQL Server system table, the first execution of the select creates the cursor successfully. After you close this cursor, if you execute the prepared statement again, the following error message appears:</p>
<blockquote>
<p>unknown token received from SQL Server.</p>
</blockquote>
<h2>Workaround</h2>
<p>Use a forward-only cursor instead of a static, keyset, or dynamic cursor on the system tables. Note that the problem does not occur if a server-side cursor is created on a user-defined table or view.</p>
<p>If a forward-only cursor is unacceptable, prepare the select statement again on the system table and execute it to create a server-side cursor. Note that the first execution works fine and applications typically do not need to create a cursor on a system table repeatedly.</p>
<h2>Status</h2>
<p>Microsoft has confirmed this to be a problem in Microsoft SQL Server version 6.50.0201. This problem has been corrected in U.S. Service Pack 1 for Microsoft SQL Server version 6.5. For more information, contact your primary support provider.</p>
| 27,392
|
<p>Suppose I have this code:</p>
<pre><code>var myArray = new Object();
myArray["firstname"] = "Bob";
myArray["lastname"] = "Smith";
myArray["age"] = 25;
</code></pre>
<p>Now if I wanted to remove "lastname"?....is there some equivalent of
<code>myArray["lastname"].remove()</code>?</p>
<p>(I need the element gone because the number of elements is important and I want to keep things clean.)</p>
|
<p>Objects in JavaScript can be thought of as associative arrays, mapping keys (properties) to values.</p>
<p>To remove a property from an object in JavaScript you use the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete" rel="noreferrer"><code>delete</code></a> operator:</p>
<pre><code>const o = { lastName: 'foo' }
o.hasOwnProperty('lastName') // true
delete o['lastName']
o.hasOwnProperty('lastName') // false
</code></pre>
<p>Note that when <code>delete</code> is applied to an index property of an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" rel="noreferrer"><code>Array</code></a>, you will create a <a href="https://2ality.com/2012/06/dense-arrays.html" rel="noreferrer">sparsely populated array</a> (ie. an array with a missing index).</p>
<p>When working with instances of <code>Array</code>, if you do not want to create a sparsely populated array - and you usually don't - then you should use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice" rel="noreferrer"><code>Array#splice</code></a> or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop" rel="noreferrer"><code>Array#pop</code></a>.</p>
<p>Note that the <code>delete</code> operator in JavaScript does not directly free memory. Its purpose is to remove properties from objects. Of course, if a property being deleted holds the only remaining reference to an object <code>o</code>, then <code>o</code> will subsequently be garbage collected in the normal way.</p>
<p>Using the <code>delete</code> operator can affect JavaScript engines' ability to <a href="http://www.html5rocks.com/en/tutorials/speed/v8/" rel="noreferrer">optimise</a> <a href="http://www.smashingmagazine.com/2012/11/writing-fast-memory-efficient-javascript/" rel="noreferrer">code</a>.</p>
|
<pre><code>var myArray = newmyArray = new Object();
myArray["firstname"] = "Bob";
myArray["lastname"] = "Smith";
myArray["age"] = 25;
var s = JSON.stringify(myArray);
s.replace(/"lastname[^,}]+,/g, '');
newmyArray = JSON.parse(p);
</code></pre>
<p>Without looping/iterates we get the same result.</p>
| 45,025
|
<p>I need to check whether the user executing the script has administrative privileges on the machine.</p>
<p>I have specified the user executing the script because the script could have been executed with a user other than the logged on using something similar to "Runas".</p>
<p>@Javier: Both solutions work in a PC with an English version of Windows installed but not if the installed is in different language. This is because the Administrators group doesn't exist, the name is different for instance in Spanish. I need the solution to work in all configurations. </p>
|
<p>You can use script if you want to see if the logged on user is an administrator</p>
<pre><code>Set objNetwork = CreateObject("Wscript.Network")
strComputer = objNetwork.ComputerName
strUser = objNetwork.UserName
isAdministrator = false
Set objGroup = GetObject("WinNT://" & strComputer & "/Administrators")
For Each objUser in objGroup.Members
If objUser.Name = strUser Then
isAdministrator = true
End If
Next
If isAdministrator Then
Wscript.Echo strUser & " is a local administrator."
Else
Wscript.Echo strUser & " is not a local administrator."
End If
</code></pre>
<p>I am not sure how to handle it when the script is run with "Runas" I am afraid.</p>
|
<pre><code>Function isAdmin
Dim shell
Set shell = CreateObject("WScript.Shell")
isAdmin = false
errorLevel = shell.Run("%comspec% /c net session >nul 2>&1", 0, True)
if errorLevel = 0
isAdmin = true
End If
End Function
</code></pre>
| 38,744
|
<p>I'm building an HTML UI with some text elements, such as tab names, which look bad when selected. Unfortunately, it's very easy for a user to double-click a tab name, which selects it by default in many browsers.</p>
<p>I might be able to solve this with a JavaScript trick (I'd like to see those answers, too) -- but I'm really hoping there's something in CSS/HTML directly that works across all browsers.</p>
|
<p>In most browsers, this can be achieved using CSS:</p>
<pre class="lang-css prettyprint-override"><code>*.unselectable {
-moz-user-select: -moz-none;
-khtml-user-select: none;
-webkit-user-select: none;
/*
Introduced in IE 10.
See http://ie.microsoft.com/testdrive/HTML5/msUserSelect/
*/
-ms-user-select: none;
user-select: none;
}
</code></pre>
<p>For IE < 10 and Opera, you will need to use the <code>unselectable</code> attribute of the element you wish to be unselectable. You can set this using an attribute in HTML:</p>
<pre><code><div id="foo" unselectable="on" class="unselectable">...</div>
</code></pre>
<p>Sadly this property isn't inherited, meaning you have to put an attribute in the start tag of every element inside the <code><div></code>. If this is a problem, you could instead use JavaScript to do this recursively for an element's descendants:</p>
<pre><code>function makeUnselectable(node) {
if (node.nodeType == 1) {
node.setAttribute("unselectable", "on");
}
var child = node.firstChild;
while (child) {
makeUnselectable(child);
child = child.nextSibling;
}
}
makeUnselectable(document.getElementById("foo"));
</code></pre>
|
<p>The following works in Firefox interestingly enough if I remove the write line it doesn't work.
Anyone have any insight why the write line is needed.</p>
<pre><code><script type="text/javascript">
document.write(".");
document.body.style.MozUserSelect='none';
</script>
</code></pre>
| 9,480
|
<p>I have an Ender 3 with a removeable build surface. The build surface backing has become warped - the center is at least 0.3 mm higher than the corners. I'm not sure what the material of this plate is - it's the part behind the BuildTak-clone surface that sits on the aluminum heat bed and is clipped to it. This makes it impossible to level the entire bed, and annoyingly tedious to level it enough just to use the center, since the paper method doesn't work at the corners. Can this be fixed, or do I need to source a replacement for it?</p>
|
<p>I measured mine with a thread gauge and it says the pitch is <strong>0.7 mm</strong>.</p>
<p>So, as the stock adjustment wheels have 14 bumps around their circumference, turning by one of those is an adjustment of exactly 0.05 mm (assuming no backlash).</p>
<p>I can't speak for anyone else's, but due to the availability of replacement height adjustment wheels which don't specify alternative thread pitches, I <em>guess</em> that's the only one in use. I encourage you to verify my finding before relying on it.</p>
|
<p>I don't know what the value is, but there are a few ways to find out. It is very hard to measure this with a caliper, but it can be done, mark the upper and bottom of e.g. 10 windings and measure this with a caliper. Alternatively measure how much the screw drops after 10 full turns. </p>
<p>There are special tools that give you the answer directly, they cost a few Euros/bucks but can be very handy; a thread gauge, just place the 0.5 mm and the 0.7 mm beside the screw and you will instantly see which is the correct one.</p>
<p><a href="https://i.stack.imgur.com/UYqFm.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UYqFm.jpg" alt="enter image description here"></a></p>
<p><em>I bought mine at a typical Chinese vendor site.</em></p>
| 1,571
|
<p>For my program, I'm attempting to replace the value of a specific hash in an external file with a newly created value. The external file has the value tab-delimited from the key, and I had read the hash in from the external file. I've been looking around online, and this is the closest way I could figure out how to do it, yet it doesn't seem to work.</p>
<pre><code> open(IN, ">>$file") || die "can't read file $file";
while (<IN>) {
print IN s/$hash{$key}/$newvalue/;
}
close (IN)
</code></pre>
<p>I'm not quite sure what I'm missing in this formula.</p>
|
<p><a href="http://search.cpan.org/perldoc?Tie::File" rel="nofollow noreferrer">Tie::File</a> can fix this for you.</p>
<pre><code>use Tie::File;
tie @array, 'Tie::File', $file or die "Could not tie $file: $!";
for (@array) {
s/$hash{$key}/$newvalue/;
}
untie @array;
</code></pre>
|
<p>You are trying to read and write to the same file, that is not going to work. You have to read, substitute then write in another file. Afterwards, you can replace the input file by the one you've just written if you really want one file.</p>
| 49,715
|
<p>When adding a bookmark or favorite the browser uses the TITLE tag of the page to automatically populate the title of the bookmark. However, my web pages use SEO-friendly titles which are not really user-friendly. Is there a method to override the title when the browser makes a bookmark?</p>
<p>I am aware that I can create a link on the page that calls javascript: </p>
<pre><code>javascript:window.external.addFavorite("url","custom title");
</code></pre>
<p>But is is possible to do something similar when a user uses the menu or hotkey to create a bookmark?</p>
|
<p>I can't see how that would be possible. The browser takes the Title loaded, which is the Title displayed on the top of the page. When saving a bookmark, it doesnt go through the code. It just adds the URL and takes the site Title.</p>
<p>You could check if the "bookmark"-pressing triggers a javascript event, though, i think it woudlnt be cross-browser :)</p>
|
<p>You're trying to solve the wrong problem.</p>
<blockquote>
<p>However, my web pages use SEO-friendly titles which are not really user-friendly</p>
</blockquote>
<p>This is what you need to fix. Your page titles should be user friendly.</p>
<p>To be honest, if you're doing it right SEO and User friendly titles should be synonymous... can you post some examples as to why you feel the need for them to be so different? </p>
| 43,818
|
<p>I have a lot of XML files which have something of the form:</p>
<pre><code><Element fruit="apple" animal="cat" />
</code></pre>
<p>Which I want to be removed from the file.</p>
<p>Using an XSLT stylesheet and the Linux command-line utility xsltproc, how could I do this?</p>
<p>By this point in the script I already have the list of files containing the element I wish to remove, so the single file can be used as a parameter.</p>
<hr />
<p><strong>EDIT:</strong> the question was originally lacking in intention.</p>
<p>What I am trying to achieve is to remove the entire element "Element" where (fruit=="apple" && animal=="cat"). In the same document there are many elements named "Element", I wish for these to remain. So</p>
<pre><code><Element fruit="orange" animal="dog" />
<Element fruit="apple" animal="cat" />
<Element fruit="pear" animal="wild three eyed mongoose of kentucky" />
</code></pre>
<p>Would become:</p>
<pre><code><Element fruit="orange" animal="dog" />
<Element fruit="pear" animal="wild three eyed mongoose of kentucky" />
</code></pre>
|
<p>Using one of the most fundamental XSLT design patterns: "Overriding the <a href="https://www.w3.org/TR/1999/REC-xslt-19991116#copying" rel="noreferrer"><strong>identity transformation</strong></a>" one will just write the following:</p>
<pre>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="Element[@fruit='apple' and @animal='cat']"/>
</xsl:stylesheet>
</pre>
<p><strong>Do note</strong> how the second template overrides the identity (1st) template only for elements named "Element" that have an attribute "fruit" with value "apple" and attribute "animal" with value "cat". This template has empty body, which means that the matched element is simply ignored (nothing is produced when it is matched).</p>
<p>When this transformation is applied on the following source XML document:</p>
<pre>
<doc>...
<Element name="same">foo</Element>...
<Element fruit="apple" animal="cat" />
<Element fruit="pear" animal="cat" />
<Element name="same">baz</Element>...
<Element name="same">foobar</Element>...
</doc>
</pre>
<p>the wanted result is produced:</p>
<pre>
<doc>...
<Element name="same">foo</Element>...
<Element fruit="pear" animal="cat"/>
<Element name="same">baz</Element>...
<Element name="same">foobar</Element>...
</doc>
</pre>
<p>More code snippets of using and overriding the identity template can be found <strong><a href="http://www.dpawson.co.uk/xsl/sect2/identity.html" rel="noreferrer">here</a></strong>.</p>
|
<p>The answer by <a href="https://stackoverflow.com/users/36305/dimitre-novatchev">@Dimitre Novatchev</a> is certainly both correct and elegant, but there's a generalization (that the OP didn't ask about): what if the element you want to filter also has child elements or text that you want to <em>keep</em>? </p>
<p>I believe this minor variation covers that case:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
version="2.0">
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<!-- drop DropMe elements, keeping child text and elements -->
<xsl:template match="DropMe">
<xsl:apply-templates/>
</xsl:template>
</xsl:stylesheet>
</code></pre>
<p>The match condition can be complicated to specify other attributes, etc., and you can use multiple such templates if you're dropping other things. </p>
<p>So this input:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<mydocument>
<p>Here's text to keep</p>
<p><DropMe>Keep this text but not the element</DropMe>; and keep what follows.</p>
<p><DropMe>Also keep this text and <b>this child element</b> too</DropMe>, along with what follows.</p>
</mydocument>
</code></pre>
<p>produces this output:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?><mydocument>
<p>Here's text to keep</p>
<p>Keep this text but not the element; and keep what follows.</p>
<p>Also keep this text and <b>this child element</b> too, along with what follows.</p>
</mydocument>
</code></pre>
<p>Credit to <a href="https://learning.oreilly.com/library/view/xslt-cookbook/0596003722/ch04s04.html" rel="nofollow noreferrer">XSLT Cookbook</a>. </p>
| 41,661
|
<p>I have an <code>NSArray</code> and I'd like to create a new <code>NSArray</code> with objects from the original array that meet certain criteria. The criteria is decided by a function that returns a <code>BOOL</code>.</p>
<p>I can create an <code>NSMutableArray</code>, iterate through the source array and copy over the objects that the filter function accepts and then create an immutable version of it.</p>
<p>Is there a better way?</p>
|
<p><code>NSArray</code> and <code>NSMutableArray</code> provide methods to filter array contents. <code>NSArray</code> provides <strong>filteredArrayUsingPredicate:</strong> which returns a new array containing objects in the receiver that match the specified predicate. <code>NSMutableArray</code> adds <strong>filterUsingPredicate:</strong> which evaluates the receiver’s content against the specified predicate and leaves only objects that match. These methods are illustrated in the following example.</p>
<pre><code>NSMutableArray *array =
[NSMutableArray arrayWithObjects:@"Bill", @"Ben", @"Chris", @"Melissa", nil];
NSPredicate *bPredicate =
[NSPredicate predicateWithFormat:@"SELF beginswith[c] 'b'"];
NSArray *beginWithB =
[array filteredArrayUsingPredicate:bPredicate];
// beginWithB contains { @"Bill", @"Ben" }.
NSPredicate *sPredicate =
[NSPredicate predicateWithFormat:@"SELF contains[c] 's'"];
[array filteredArrayUsingPredicate:sPredicate];
// array now contains { @"Chris", @"Melissa" }
</code></pre>
|
<p>Checkout this library</p>
<p><a href="https://github.com/BadChoice/Collection" rel="nofollow">https://github.com/BadChoice/Collection</a></p>
<p>It comes with lots of easy array functions to never write a loop again</p>
<p>So you can just do:</p>
<pre><code>NSArray* youngHeroes = [self.heroes filter:^BOOL(Hero *object) {
return object.age.intValue < 20;
}];
</code></pre>
<p>or</p>
<pre><code>NSArray* oldHeroes = [self.heroes reject:^BOOL(Hero *object) {
return object.age.intValue < 20;
}];
</code></pre>
| 13,557
|
<p>I'm told that the template system in C++ is Turing-complete at compile time. This is mentioned in <a href="https://stackoverflow.com/questions/75538/hidden-features-of-c#75627">this post</a> and also on <a href="http://en.wikipedia.org/wiki/C%2B%2B" rel="noreferrer">wikipedia</a>.</p>
<p>Can you provide a nontrivial example of a computation that exploits this property?</p>
<p>Is this fact useful in practice?</p>
|
<p>Example</p>
<pre><code>#include <iostream>
template <int N> struct Factorial
{
enum { val = Factorial<N-1>::val * N };
};
template<>
struct Factorial<0>
{
enum { val = 1 };
};
int main()
{
// Note this value is generated at compile time.
// Also note that most compilers have a limit on the depth of the recursion available.
std::cout << Factorial<4>::val << "\n";
}
</code></pre>
<p>That was a little fun but not very practical.<br></p>
<p>To answer the second part of the question:<br>
<b>Is this fact useful in practice?</b></p>
<p>Short Answer: Sort of.</p>
<p>Long Answer: Yes, but only if you are a template daemon.</p>
<p>To turn out good programming using template meta-programming that is really useful for others to use (ie a library) is really really tough (though do-able). To Help boost even has <a href="http://www.boost.org/doc/libs/1_36_0/libs/mpl/doc/index.html" rel="noreferrer">MPL</a> aka (Meta Programming Library). But try debugging a compiler error in your template code and you will be in for a long hard ride.</p>
<p>But a good practical example of it being used for something useful: </p>
<p>Scott Meyers has been working extensions to the C++ language (I use the term loosely) using the templating facilities. You can read about his work here '<a href="http://www.artima.com/cppsource/codefeaturesP.html" rel="noreferrer">Enforcing Code Features</a>'</p>
|
<p>A <a href="http://en.wikipedia.org/wiki/Turing_machine" rel="nofollow noreferrer">Turing machine</a> is Turing-complete, but that doesn't mean you should want to use one for production code.</p>
<p>Trying to do anything non-trivial with templates is in my experience messy, ugly and pointless. You have no way to "debug" your "code", compile-time error messages will be cryptic and usually in the most unlikely places, and you can achieve the same performance benefits in different ways. (Hint: 4! = 24). Worse, your code is incomprehensible to the average C++ programmer, and will be likely be non-portable due to wide ranging levels of support within current compilers. </p>
<p>Templates are great for generic code generation (container classes, class wrappers, mix-ins), but no - in my opinion the Turing Completeness of templates is <strong>NOT USEFUL</strong> in practice. </p>
| 22,941
|
<p>This seems like the most basic question in the world, but damned if I can find an answer.</p>
<p>Is there a keyboard shortcut, either native to Visual Studio or through Code Rush or other third-party plug-in, to wrap the current selection with an HTML tag? I'm tired of typing the opening tag, cutting the misplaced closing tag to the clipboard, moving the cursor, and pasting it at the end where it belongs.</p>
<p><strong>Update:</strong> <a href="http://screencast.com/t/pesxOgON" rel="noreferrer">This is how TextMate handles surrounding a selection with a tag</a>. Frankly, I'm stunned that Visual Studio doesn't seem to have a similar feature. Creating a macro or snippet for every conceivable tag I might want to use seems absurd.</p>
|
<p>Visual Studio 2015 comes with a new shortcut, Shift+Alt+W, that wraps the current selection with a div. This shortcut leaves the text "div" selected, making it seamlessly changeable to any desired tag. This coupled with the automatic end tag replacement makes for a quick solution.</p>
<h3>UPDATE</h3>
<p>This shortcut is available in Visual Studio 2017 as well, but you must have the "ASP.NET and Web Development" workload installed.</p>
<h1>Example</h1>
<pre><code>Shift+Alt+W > p > Enter
</code></pre>
|
<p>I know this is an old question but I was just struggling with the same thing. You can install the Emmet Keybindings extension by Andrés Gutiérrez. Once installed you can highlight text then use control + MW to wrap with any tag you'd like. To give each line an opening and closing tag include an * after the tag.</p>
| 23,253
|
<p>When I create a New Project of type ASP.Net MVC Web Application, I expect the dialog for unit test applications to show up, but it does not. I cannot find the Unit Test App among the product types I can create either. How do I set up my VS so that the dialog shows up?</p>
<p>I have installed Visual Studio 2008, .Net Framework 3.5 SP1 and ASP.Net MVC Framework (Beta).</p>
|
<p>As @MrJavaGuy says, you need to install at least the Professional, not Express, version of VS2008. Alternatively, you can install nUnit and/or TestDriven.Net and get unit testing capabilities. Info on nUnit can be found at <a href="http://www.nunit.org/index.php" rel="nofollow noreferrer">http://www.nunit.org/</a> and TestDriven.Net at <a href="http://www.testdriven.net/" rel="nofollow noreferrer">http://www.testdriven.net/</a>. I recommend TestDriven.Net even if you have the testing capabilities of Visual Studio baked in.</p>
|
<p>Had the same problem with Visual Web Developer Express, I found this blog.</p>
<p><a href="http://blogs.msdn.com/webdevtools/archive/2008/05/30/asp-net-mvc-preview-3-tooling-updates.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/webdevtools/archive/2008/05/30/asp-net-mvc-preview-3-tooling-updates.aspx</a></p>
<p>I downloaded </p>
<p><a href="http://www.box.net/shared/zmp0cdxsss" rel="nofollow noreferrer">http://www.box.net/shared/zmp0cdxsss</a></p>
<p>and that worked for me.. Not sure if this will sort your issue though. Best of luck with it.</p>
| 37,543
|
<p>How would one create an iterative function (or iterator object) in python?</p>
|
<p>Iterator objects in python conform to the iterator protocol, which basically means they provide two methods: <code>__iter__()</code> and <code>__next__()</code>. </p>
<ul>
<li><p>The <code>__iter__</code> returns the iterator object and is implicitly called
at the start of loops.</p></li>
<li><p>The <code>__next__()</code> method returns the next value and is implicitly called at each loop increment. This method raises a StopIteration exception when there are no more value to return, which is implicitly captured by looping constructs to stop iterating.</p></li>
</ul>
<p>Here's a simple example of a counter:</p>
<pre><code>class Counter:
def __init__(self, low, high):
self.current = low - 1
self.high = high
def __iter__(self):
return self
def __next__(self): # Python 2: def next(self)
self.current += 1
if self.current < self.high:
return self.current
raise StopIteration
for c in Counter(3, 9):
print(c)
</code></pre>
<p>This will print:</p>
<pre><code>3
4
5
6
7
8
</code></pre>
<p>This is easier to write using a generator, as covered in a previous answer:</p>
<pre><code>def counter(low, high):
current = low
while current < high:
yield current
current += 1
for c in counter(3, 9):
print(c)
</code></pre>
<p>The printed output will be the same. Under the hood, the generator object supports the iterator protocol and does something roughly similar to the class Counter.</p>
<p>David Mertz's article, <a href="https://www.ibm.com/developerworks/library/l-pycon/" rel="noreferrer">Iterators and Simple Generators</a>, is a pretty good introduction. </p>
|
<blockquote>
<pre class="lang-py prettyprint-override"><code>class uc_iter():
def __init__(self):
self.value = 0
def __iter__(self):
return self
def __next__(self):
next_value = self.value
self.value += 2
return next_value
</code></pre>
</blockquote>
<p>Improving previous <a href="https://stackoverflow.com/a/7542261/11671779">answer</a>, one of the advantage of using <code>class</code> is that you can add <code>__call__</code> to return <code>self.value</code> or even <code>next_value</code>.</p>
<pre class="lang-py prettyprint-override"><code>class uc_iter():
def __init__(self):
self.value = 0
def __iter__(self):
return self
def __next__(self):
next_value = self.value
self.value += 2
return next_value
def __call__(self):
next_value = self.value
self.value += 2
return next_value
</code></pre>
<pre class="lang-py prettyprint-override"><code>c = uc_iter()
print([c() for _ in range(10)])
print([next(c) for _ in range(5)])
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# [20, 22, 24, 26, 28]
</code></pre>
<hr />
<p>Other example of a class based on Python Random that can be both called and iterated could be seen on my implementation <a href="https://github.com/yasirroni/fakertype/blob/main/fakertype/generator.py" rel="nofollow noreferrer">here</a></p>
| 3,964
|
<p>I'm a .Net developer and want to get into developing Silverlight applications. I have VS 2008 but wanted to know if I should/need expression blend. What are pros/cons of having blend along side VS? </p>
|
<p>I don't mean to push my own questions, but this might help you a little, especially if you are not familiar with Expression Studio or Expression Blend: "<a href="https://stackoverflow.com/questions/28826/what-exactly-is-microsoft-expression-studio-and-how-does-it-integrate-with-visu">What exactly is Microsoft Expression Studio and how does it integrate with Visual Studio?</a>"</p>
|
<p>Blend is very useful for designing, and its new feature of control visual states editing it can be very useful. However, the XAML it generates might be more difficult to maintain than custom written one.</p>
<p>Personally, I use blend whenever I need to generate a certain visual effect, and then copy the XAML into the actual solution, but in an ideal environment, you should be providing the designer with a raw XAML generated in VS, and he should edit it with Blend.</p>
| 14,873
|
<p>I am looking for the highest key value (a defined by the comparison operator) of a std::map.</p>
<p>Is this guaranteed to be </p>
<pre><code>map.rbegin()->first
</code></pre>
<p>? </p>
<p>(I am a bit shaky on reverse iterators, and how much freedom there is in the implementation of std::map) </p>
<p>If not, please advise. I cannot change the data structure.</p>
|
<p>Yes. Map is a sorted container, the reverse iterator must return the elements in reverse (i.e. decreasing) order of their keys.</p>
<p>[Edit: as Charles Bailey points out in his answer, your code gives the greatest key <strong>if it exists</strong> - i.e. if the map is non-empty]</p>
|
<p>Map store the key value pairs in sorted order so we can access the last element by :-</p>
<pre><code>auto it=m.end();
it--;
int element=it->first;
</code></pre>
| 36,903
|
<p>I wonder if someone knows if there is a pre-made solution for this: I have a List on an ASP.net Website, and I want that the User is able to re-sort the list through Drag and Drop. Additionally, I would love to have a second list to which the user can drag items from the first list onto.</p>
<p>So far, I found two solutions:</p>
<ul>
<li>The ReorderList from the <a href="http://www.codeplex.com/AjaxControlToolkit" rel="nofollow noreferrer">Ajax Control Toolkit</a>, which requires a bit of manual work to make sure changes <a href="http://www.codeproject.com/KB/ajax/PersistentReorderList.aspx" rel="nofollow noreferrer">are persisted</a> into the database, and that does not support drag/drop between lists.</li>
<li>The <a href="http://www.telerik.com/DEMOS/ASPNET/Prometheus/Grid/Examples/Programming/DragAndDrop/DefaultCS.aspx" rel="nofollow noreferrer">RadGrid</a> from Telerik which does all I want, but is priced far far beyond my Budget.</li>
</ul>
<p>Does anyone else have some ideas or at least some keywords/pointers to do further investigation on? Espectially the Drag/Drop between two lists is something I am rather clueless about how to do that in ASP.net.</p>
<p>Target Framework is 3.0 by the way.</p>
|
<p>The Mootools sortables plugin does just that, and best of all, it's free ;)</p>
<p><a href="http://demos.mootools.net/Sortables" rel="nofollow noreferrer">http://demos.mootools.net/Sortables</a></p>
|
<p>I've evaluated the <a href="http://www.telerik.com/" rel="nofollow noreferrer">Telerik</a> grid as well as <a href="http://www.infragistics.com/Default.aspx" rel="nofollow noreferrer">Infragistics</a> version. In the end we took an approach similar to what tags2k suggested. We just wrote our own javascript and called <a href="http://www.singingeels.com/Articles/Using_Page_Methods_in_ASPNET_AJAX.aspx" rel="nofollow noreferrer">.Net PageMethods</a> to do the server side work. </p>
<p>We found both of the "out of the box" solutions to be bloated. Unless you put paging in at like 20 records per row they really stunk performance wise. </p>
| 3,453
|
<p>I need to make a Control which shows only an outline, and I need to place it over a control that's showing a video. If I make my Control transparent, then the video is obscured, because transparent controls are painted by their parent control and the video isn't painted by the control; it's shown using DirectShow or another library, so instead the parent control paints its BackColor.</p>
<p>So - can I make a control that doesn't get painted <em>at all</em>, except where it's opaque? That way, the parent control wouldn't paint over the video.</p>
<p>I know I could make the border out of four controls (or more if I want it dashed) but is it possible to do what I want using just one control?</p>
<hr>
<p>rslite is right - although you don't even need to go so far as to use PInvoke like his example does - the Control.Region property is entirely sufficient.</p>
|
<p>You could try to make a Region with a hole inside and set the control region with SetWindowRgn.</p>
<p>Here is an <a href="http://www.java2s.com/Code/CSharp/GUI-Windows-Form/PictureButton.htm" rel="nofollow noreferrer">example</a> (I couldn't find a better one). The idea is to create two regions and subtract the inner one from the outer one. I think that should give you what you need.</p>
|
<p>You could try setting the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.form.transparencykey.aspx" rel="nofollow noreferrer"><code>Form.TransparencyKey</code></a> property. Failing that, you could use DirectX to get access to the frame buffer and draw directly to it.</p>
| 39,766
|
<p>I'm curious about what it takes to program for mobile devices (Windows Mobile 6.1) and if I can use the IDE's we're already used to (RAD Studio 2009). </p>
<p>Is there a Mobile Development Community around where Delphi or C++Builder users can learn from? </p>
<p>Are there differences in development techniques, like: Drivers, Memory Limits, Device Specific Considerations and others? </p>
<p>Links to Documentation and Tutorials are always awesome! </p>
<p>Thanks!</p>
|
<p>Use <a href="http://mail.google.com/support/bin/answer.py?answer=75725&topic=12891" rel="noreferrer">Gmail with IMAP</a>.</p>
|
<p>You can get an <a href="https://mail.google.com/mail/feed/atom" rel="nofollow noreferrer">Atom Feed of your GMAIL</a>, which can be fetched with a regular web request, and parse as a regular XML document. I made a PHP page I could access from my phone (which doesn't support Atom Feeds, or pages as advanced as Google Mobile), to show me a list of new emails.</p>
| 44,468
|
<p>I need to find a bottleneck and need to accurately as possible measure time.</p>
<p>Is the following code snippet the best way to measure the performance?</p>
<pre><code>DateTime startTime = DateTime.Now;
// Some execution process
DateTime endTime = DateTime.Now;
TimeSpan totalTimeTaken = endTime.Subtract(startTime);
</code></pre>
|
<p>No, it's not. Use the <a href="http://msdn2.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx" rel="noreferrer">Stopwatch</a> (in <code>System.Diagnostics</code>)</p>
<pre><code>Stopwatch sw = Stopwatch.StartNew();
PerformWork();
sw.Stop();
Console.WriteLine("Time taken: {0}ms", sw.Elapsed.TotalMilliseconds);
</code></pre>
<p>Stopwatch automatically checks for the existence of high-precision timers.</p>
<p>It is worth mentioning that <code>DateTime.Now</code> often is quite a bit slower than <code>DateTime.UtcNow</code> due to the work that has to be done with timezones, <a href="http://en.wikipedia.org/wiki/Daylight_saving_time" rel="noreferrer">DST</a> and such.</p>
<p>DateTime.UtcNow typically has a resolution of 15 ms. See <a href="http://jaychapman.blogspot.com/2007/12/datetimenow-precision-issues-enter.html" rel="noreferrer">John Chapman's blog post</a> about <code>DateTime.Now</code> precision for a great summary.</p>
<p>Interesting trivia: The stopwatch falls back on <code>DateTime.UtcNow</code> if your hardware doesn't support a high frequency counter. You can check to see if Stopwatch uses hardware to achieve high precision by looking at the static field <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.ishighresolution.aspx" rel="noreferrer">Stopwatch.IsHighResolution</a>.</p>
|
<p>Since I do not care to much about precision I ended up comparing them. I am capturing lots of packets on the network and I want to place the time when I receive each packet. Here is the code that tests 5 million iterations</p>
<pre><code> int iterations = 5000000;
// Test using datetime.now
{
var date = DateTime.UtcNow.AddHours(DateTime.UtcNow.Second);
var now = DateTime.UtcNow;
for (int i = 0; i < iterations; i++)
{
if (date == DateTime.Now)
Console.WriteLine("it is!");
}
Console.WriteLine($"Done executing {iterations} iterations using datetime.now. It took {(DateTime.UtcNow - now).TotalSeconds} seconds");
}
// Test using datetime.utcnow
{
var date = DateTime.UtcNow.AddHours(DateTime.UtcNow.Second);
var now = DateTime.UtcNow;
for (int i = 0; i < iterations; i++)
{
if (date == DateTime.UtcNow)
Console.WriteLine("it is!");
}
Console.WriteLine($"Done executing {iterations} iterations using datetime.utcnow. It took {(DateTime.UtcNow - now).TotalSeconds} seconds");
}
// Test using stopwatch
{
Stopwatch sw = new Stopwatch();
sw.Start();
var now = DateTime.UtcNow;
for (int i = 0; i < iterations; i++)
{
if (sw.ElapsedTicks == DateTime.Now.Ticks)
Console.WriteLine("it is!");
}
Console.WriteLine($"Done executing {iterations} iterations using stopwatch. It took {(DateTime.UtcNow - now).TotalSeconds} seconds");
}
</code></pre>
<p>The output is:</p>
<pre><code>Done executing 5000000 iterations using datetime.now. It took 0.8685502 seconds
Done executing 5000000 iterations using datetime.utcnow. It took 0.1074324 seconds
Done executing 5000000 iterations using stopwatch. It took 0.9625021 seconds
</code></pre>
<p><strong>So in conclusion DateTime.UtcNow is the fastest if you do not care to much about precision</strong>. This also supports the answer <a href="https://stackoverflow.com/a/6986472/637142">https://stackoverflow.com/a/6986472/637142</a> from this question.</p>
| 4,824
|
<p>I have an Internet Explorer Browser Helper Object (BHO), written in c#, and in various places I open forms as modal dialogs. Sometimes this works but in some cases it doesn't. The case that I can replicate at present is where IE is running javascript to open other child windows... I guess it's getting a bit confused somewhere.... </p>
<p>The problem is that when I call:</p>
<pre><code>(new MyForm(someParam)).ShowDialog();
</code></pre>
<p>the form is not modal, so I can click on the IE window and it gets focus. Since IE is in the middle of running my code it doesn't refresh and therefore to the user it appears that IE is hanging.</p>
<p>Is there a way of ensuring that the form will be opened as modal, ie that it's not possible for the form to be hidden behind IE windows.</p>
<p>(I'm using IE7.)</p>
<p>NB: this is a similar question to <a href="https://stackoverflow.com/questions/73000/modal-dialogs-in-ie-gets-hidden-behind-ie-if-user-clicks-on-ie-pane">this post</a> although that's using java. I guess the solution is around correctly passing in the IWin32Window of the IE window, so I'm looking into that.</p>
|
<p>It wasn't my intention to answer my own question, but...</p>
<p>It seems that if you pass in the correct IWin32Window to the ShowDialog() method it works fine. The trick is how to get this. Here's how I did this, where 'siteObject' is the object passed in to the SetSite() method of the BHO:</p>
<pre><code>IWebBrowser2 browser = siteObject as IWebBrowser2;
if (browser != null) hwnd = new IntPtr(browser.HWND);
(new MyForm(someParam)).ShowDialog(new WindowWrapper(hwnd));
...
// Wrapper class so that we can return an IWin32Window given a hwnd
public class WindowWrapper : System.Windows.Forms.IWin32Window
{
public WindowWrapper(IntPtr handle)
{
_hwnd = handle;
}
public IntPtr Handle
{
get { return _hwnd; }
}
private IntPtr _hwnd;
}
</code></pre>
<p>Thanks to <a href="http://ryanfarley.com/blog/archive/2004/03/23/465.aspx" rel="nofollow noreferrer">Ryan</a> for the WindowWrapper class, although I'd hoped there was a built-in way to do this?</p>
<p>UPDATE: this won't work on IE8 with Protected Mode, since it's accessing an HWND outside what it should be. Instead you'll have to use the HWND of the current tab (or some other solution?), e.g. see .net example in <a href="http://social.msdn.microsoft.com/Forums/en-US/ieextensiondevelopment/thread/df0fe7f2-0153-47d9-b18f-266d57ab7909" rel="nofollow noreferrer">this post</a> for a way of getting that.</p>
|
<p>It wasn't my intention to answer my own question, but...</p>
<p>It seems that if you pass in the correct IWin32Window to the ShowDialog() method it works fine. The trick is how to get this. Here's how I did this, where 'siteObject' is the object passed in to the SetSite() method of the BHO:</p>
<pre><code>IWebBrowser2 browser = siteObject as IWebBrowser2;
if (browser != null) hwnd = new IntPtr(browser.HWND);
(new MyForm(someParam)).ShowDialog(new WindowWrapper(hwnd));
...
// Wrapper class so that we can return an IWin32Window given a hwnd
public class WindowWrapper : System.Windows.Forms.IWin32Window
{
public WindowWrapper(IntPtr handle)
{
_hwnd = handle;
}
public IntPtr Handle
{
get { return _hwnd; }
}
private IntPtr _hwnd;
}
</code></pre>
<p>Thanks to <a href="http://ryanfarley.com/blog/archive/2004/03/23/465.aspx" rel="nofollow noreferrer">Ryan</a> for the WindowWrapper class, although I'd hoped there was a built-in way to do this?</p>
<p>UPDATE: this won't work on IE8 with Protected Mode, since it's accessing an HWND outside what it should be. Instead you'll have to use the HWND of the current tab (or some other solution?), e.g. see .net example in <a href="http://social.msdn.microsoft.com/Forums/en-US/ieextensiondevelopment/thread/df0fe7f2-0153-47d9-b18f-266d57ab7909" rel="nofollow noreferrer">this post</a> for a way of getting that.</p>
| 15,444
|
<p>I have a table view setup which currently, when being flickered up, has its sections flush up against right underneath the status bar, instead of flushing against the the navigation bar. I'm not sure if this is the proper behavior, but most applications have the Section Title flush properly below the navigation bar when it's slid into view.</p>
<p>What's the right way to correct this instead of downsizing the tableView arbitrarily?</p>
<p><strong>* EDIT *</strong></p>
<p>Related to a thread I created in <a href="https://stackoverflow.com/questions/321522/iphone-devel-broken-cell-with-an-odd-strikethrough">Broken cell with an odd strikethrough?</a>. This problem plus the 'cell strike-through' problem occurs when I set my Navigation Bar to a Translucent Black. When it's Black Opaque or Normal, such a problem does not exist. I'm not sure if that's a result of something else in my code or an issue with the SDK.</p>
|
<p>Sounds like you either don't have the bounds set properly in IB, or your springs-and-struts aren't correct. Is this the top level of the UIViewController, or a subview? Are you using a UINavigationController? If you test the interface in IB, does it look okay?</p>
|
<p>As I indicated in the other post, I suspect the hierarchy of views under the UINavigationController has become disrupted.</p>
<p>The layoutSubviews in the content view (which contains the navigation bar and your UITableView) of the UINavigationController should be sizing the UITableView such that it doesn't overlap the navigation bar. In your case, I'm guessing that either the UITableView is resizing itself afterwards or the layoutSubviews doesn't know about the UITableView for some reason and the UITableView is passing underneath the navigation bar, causing the alignment issue you are seeing.</p>
| 41,619
|
<p>So, bitfields. Specifically, large bitfields. I understand how to manipulate individual values in a bitfield, but how would I go about doing this on a large set, such as say:</p>
<pre><code>uint[] bitfield = new uint[4] { 0x0080000, 0x00FA3020, 0x00C8000, 0x0FF00D0 };
</code></pre>
<p>The specific problem I'm having is doing left and right shifts that carry through across the whole array. So for instance, if I did a <code>>> 4</code> on the above array, I'd end up with:</p>
<pre><code>uint[4] { 0x0008000, 0x000FA302, 0x000C800, 0x00FF00D };
</code></pre>
<p>Now, an (overly) simplistic algorithm here might look something like (this is me writting code on the fly):</p>
<pre><code>int shift = 4;
for (int i = 0; i <= shift; i++) {
for (int j = bitfield.GetUpperBound(0); j > 0; j--) {
bitfield[j] = bitfield[j] >> 1;
bitfield[j] = bitfield[j] + ((bitfield[j-1] & 1) << (sizeof(uint)*8));
}
bitfield[0] = bitfield[0] >> 1;
}
</code></pre>
<p>Is there anything built in that might ease working with this sort of data? </p>
|
<p>What makes you think that BitArray uses bools internally? It uses Boolean values to represent the bits in terms of the API, but under the hood I believe it uses an int[].</p>
|
<p>Using extension methods, you could do this:</p>
<pre><code>public static class BitArrayExtensions
{
public static void DownShift(this BitArray bitArray, int places)
{
for (var i = 0; i < bitArray.Length; i++)
{
bitArray[i] = i + places < bitArray.Length && bitArray[i + places];
}
}
public static void UpShift(this BitArray bitArray, int places)
{
for (var i = bitArray.Length - 1; i >= 0; i--)
{
bitArray[i] = i - places >= 0 && bitArray[i - places];
}
}
}
</code></pre>
<p>Unfortunately, I couldn't come up with a way to overload the shift operators. (Mainly because <code>BitArray</code> is sealed.)</p>
<p>If you intend to manipulate <code>int</code>s or <code>uint</code>s, you could create extension methods for inserting bits into / extracting bits from the <code>BitArray</code>. (<code>BitArray</code> has a constructor that takes an array of <code>int</code>s, but that only takes you that far.)</p>
| 21,467
|
<p>I am wondering how the HttpContext is maintained given that the request-response nature of the web is essentially stateless.</p>
<p>Is an identifier being for the HttpContext object being sent as part of the __EVENTTarget / __EVENTARGUMENTS hidden fields so that the HttpRuntime class can create the HttpContext class by reading this section from the request (HttpWorkerRequest)? I don't think</p>
<p>Please let me know as I am trying to fill some holes in my understanding of the http pipeline and I was unable to find any information about this.</p>
<p>I understand something like
HttpContext.Current.Session["myKey"] = Value;</p>
<p>just works but if I had to do something similar in a different language (say perl), I would have to use hidden fields for the same, wouldn't I?</p>
<p>Thanks
-Venu</p>
|
<p>The HttpContext is recreated for each request. The HttpSession, however, is stored on the server across requests. Basically, HttpSession is a Dictionary<string, Dictionary<string, object>>. The initial key, the session id, is provided by either a cookie or a query string parameter (if using cookie-less sessions). If you use Fiddler, you'll see the ASP.NET_SessionId cookie that contains the key for that user's session.</p>
<p>In code:</p>
<pre><code>class HttpSessionState {
private static readonly Sessions =
new Dictionary<string, Dictionary<string, object>>();
public object this(string key) {
get {
return GetCurrentUserSession()[key]
}
set {
GetCurrentUserSession()[key] = value;
}
}
private Dictionary<string, object> GetCurrentUserSession() {
var id = GetCurrentUserSessionId[]
var d = Sessions[id];
if (d == null) {
d = new Dictionary<string, object>();
Sessions[id] = d;
}
return d;
}
private string GetCurrentUserSessionId() {
return HttpContext.Current.Request.Cookies["ASP.NET_SessionId"].Value;
}
}
</code></pre>
<p>The real implementation also handles session timeouts, abandons, and cookieless sessions - but the basic idea is the same.</p>
|
<p>I don't think there is one answer to your question, because I don't think everything under the HttpContext umbrella works the same way. In the example you chose, session state, both the key and value are stored on the server side. The way it knows how to hook up future requests to that session state is by using a cookie that has a (totally different) key in it. When the browser makes another request, it sends this cookie with the request and the server uses it to figure out which session to map to. Once it figures it out, you've again got access to your dictionary, across responses.</p>
<p>So, to do it in perl, you'd want to manually create a cookie and store a unique key in it, have a server-side mapping of those unique keys to session state dictionaries, and pretty much do what I described above.</p>
| 34,396
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.