instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>Is it possible to impersonate a user without supplying user name/password? Basically, I'd like to get the <code>CSIDL_LOCAL_APPDATA</code> for a user (not the current one) using the <code>ShGetFolderPath()</code> function. All I currently have is a SID for that user.</p>
|
<p>No, you have to call Win32 API <strong>LogonUser</strong> function to get windows account token back so you can then impersonate.</p>
|
<p>You can impersonate a user without supplying password by calling ZwCreateToken.
See the CreatePureUserToken function in this article:
<a href="http://www.codeproject.com/KB/system/RunUser.aspx" rel="noreferrer" title="GUI-Based RunAsEx">GUI-Based RunAsEx</a>
You must be running as an admin (or LocalSystem) for this to work.</p>
<p>Another technique is to use Windows Subauthentication Packages.
This allows you to override windows built-in authentication and allow a LogonUser to succeed even if no password was supplied. See this <a href="http://support.microsoft.com/kb/216828" rel="noreferrer" title="KB article">KB article</a>.</p>
| 16,601
|
<p>I have an ASP.NET 2.0 application. The login page redirects twice when the login is successful. This works OK on all test environment and production servers except one. We can see with Fiddler that the login redirects to the second page and it redirects to the third. When getting to the third page the authentication cookie is lost, and the page redirects back to the login.
As mentioned this happens only on one production server with IE7.
It works fine if we try IE7 from the server itself. It only fails from other client machines.
It works perfectly well if I just try the same from FireFox. I can see clearly of fiddler, that in this case the cookie is not lost.</p>
<p>Any ideas?</p>
|
<p>This is a longshot, but does the servername have an underscore in it? A while back, there was an IE bug where it couldn't save cookies from a servername/URL that had an underscore in it, so if I accessed the server by <a href="http://server_name" rel="nofollow noreferrer">http://server_name</a>, I couldn't save a cookie, but accessing it via <a href="http://intranetdnsalias" rel="nofollow noreferrer">http://intranetdnsalias</a> would work just fine.</p>
|
<p>This sounds like an IIS config problem. Have you tried to recreate the website on that server with defaults?</p>
| 41,271
|
<p>What interop signature would you use for the following COM method? I am interested particularly in the final two parameters, and whether to try to use <code>MarshalAs</code> with a <code>SizeParamIndex</code> or not.</p>
<pre><code>HRESULT GetOutputSetting(
DWORD dwOutputNum,
LPCWSTR pszName,
WMT_ATTR_DATATYPE* pType,
BYTE* pValue,
WORD* pcbLength
);
</code></pre>
<p>Documentation states:</p>
<blockquote>
<p><strong>pValue</strong> [out] Pointer to a byte buffer containing the value. Pass NULL
to retrieve the length of the buffer
required.</p>
<p><strong>pcbLength</strong> [in, out] On input, pointer to a variable containing the
length of pValue. On output, the
variable contains the number of bytes
in pValue used.</p>
</blockquote>
|
<p>You could try the <a href="http://www.codeplex.com/clrinterop/Release/ProjectReleases.aspx?ReleaseId=14120" rel="nofollow noreferrer" title="PInvoke Signature Toolkit">PInvoke Signature Toolkit</a>. It's rather useful for getting marshaling right when performing platform interops. It quite possibly won't cover your particular problem, but you may find a comparable one that gives you the information you seek.</p>
|
<p>I would use the SizeParamIndex, because your scenario is exactly the one this feature is for: To specify the length of a variable sized array.</p>
<p>So the last to parameters would be in C# signature:</p>
<pre><code>byte[] pValue,
ref ushort pcbLength
</code></pre>
<p>The byte-Array is passed without <em>ref</em>, because the array corresponds to a pointer in native code.
If you pass NULL (or null in C#) for pValue in order to retrieve the size of the buffer needed. That means also that the caller has to allocate the byte-Array.
The parameter pcbLength is passed by <em>ref</em>, because it is used as an in/out-parameter.</p>
| 27,403
|
<p>I am trying to learn how to use MSBuild so we can use it to build our project. There's what seems to be a very big hole in the documentation, and I find the hole everywhere I look, the hole being how do you name or otherwise designate the MSBuild project file? </p>
<p>For example, the tutorial on MSBuild that can be downloaded from Microsoft goes into some detail on the contents of the build file. For example, here's a little bit of their Hello World project file.</p>
<pre><code><Project MSBuildVersion = "1.0" DefaultTargets = "Compile">
<Property appname = "HelloWorldCS"/>
<Item Type = "CSFile" Include = "consolehwcs1.cs"/>
<Target Name = "Compile">
<Task Name = "CSC" Sources = "@(CSFile)">
<OutputItem TaskParameter = "OutputAssembly" Type = "EXEFile" Include = "$(appname).exe"/>
</Task>
<Message Text="The output file is @(EXEFile)"/>
</Target>
</Project>
</code></pre>
<p>And it goes on blah, blah, blah Items blah blah blah tasks, here's how you do this and here's how you do that. Useless, completely useless. Because they never get around to saying how this xml file is supposed to be recognized by the MSBuild app. Is it supposed to be named in a particular way? Is it supposed to be placed in a particular directory? Both? Neither? </p>
<p>It isn't just the MS tutorial where they don't tell about it. I haven't been able to find it on MSDN, or on any link I can wring out of Groups.Google, either.</p>
<p>Does someone here know? I sure hope so.</p>
<blockquote>
<p><strong>Edited to add:</strong> I mistook the
.proj file included in the tutorial
to be the .csproj file and that is what
one fed to MSBuild, but it took the answer below before I saw this.
It should have been rather obvious, but I missed it.</p>
</blockquote>
|
<p>You can name the file as you see fit. From the help for MSBuild</p>
<pre><code>msbuild.exe /?
Microsoft (R) Build Engine Version 2.0.50727.3053
[Microsoft .NET Framework, Version 2.0.50727.3053]
Copyright (C) Microsoft Corporation 2005. All rights reserved.
Syntax: MSBuild.exe [options] [project file]
</code></pre>
<p>So if you save the file as mybuildfile.xml you would use the syntax:</p>
<pre><code>msbuild.exe mybuildfile.xml
</code></pre>
|
<p>Or for the truly lazy, like me.</p>
<pre><code>msbuild.exe project-file-name.vcproj /t:Rebuild /p:Configuration=Release
</code></pre>
| 14,373
|
<p>I am using NUnit to test my C# code and have so far been keeping unit tests (fast running ones) and integration tests (longer running) separate, and in separate project files. I use NUnit for doing both the unit tests and the integration tests. I just noticed the <a href="http://www.nunit.org/index.php?p=category&r=2.2" rel="nofollow noreferrer">category attribute</a> that NUnit provides, so that tests can be categorized. This begs the question, should I mix them together and simply use the category attribute to distinguish between them?</p>
|
<p>if it is not too difficult to separate them, do so now</p>
<p>unit tests should be run early and often (e.g. every time you change something, before check-in, after check-in), and should complete in a short time-span.</p>
<p>integration tests should be run periodically (daily, for example) but may take significant time and resources to complete</p>
<p>therefore it is best to keep them separate</p>
|
<p>I would keep with whatever method you're currently using. It's more of an opinion thing, and you wouldn't want to have to re-tool your whole testing method.</p>
| 48,589
|
<p>I've worked on a variety of systems as a programmer, some with Oracle, some with MySQL. I keep hearing people say that Oracle is more stable, more robust, and more secure. Is this the case?</p>
<p>If so in what ways and why?</p>
<p>For the purposes of this question, consider a small-medium sized production DB, perhaps 500,000 records or so.</p>
|
<p>Yes. Oracle is enterprise grade software.</p>
<p>I'm not sure if its really any more stable that mysql, I haven't used mysql that much, but I dont ever remember having mysql crash on me. I've had oracle crash, but when it does, it gives me more information about why it crashed than I could possibly want, and Oracle support is always there to help ( for a fee ).</p>
<p>Its very very robust, Oracle DB will do virtually everything it can before breaking your data, I've had mysql servers do really weird things when they run out of disk space, Oracle will just halt all transactions, and eventually shutdown if it can't write the files it needs. I've never lost data in oracle, even when I do stupid things like forget the where clause and update every row rather than a single row, its very easy to get the database back to how it was before screwing up.</p>
<p>Not sure about security, certainly Oracle gives you lots of options for how you are going to connect to the DB and authenticate. It gives lots of options regarding which users have access to what, etc. But as with most things, if you want to take security seriously, then you need an expert to do it. Oracle certainly has a lot more to lose if they don't get security right. But, as with all things there has been exploits.</p>
<p>If nothing else, just consider this... When Oracle stuffs up, they have customers who are paying $40k per CPU (if they are suckers and pay list price) license + yearly maintenance fees.. This gives them a very strong intensive to make sure the customers are happy with the product.</p>
<p>For a small database, I'd seriously recommend Oracle XE well before mysql. It has the important features of mysql (Free), its dead easy to install, comes with a nice web interface and application framework (Application Express), if you DB will happy run on a single cpu, 1gb ram and 4gb data, then XE is the way to go IMHO.</p>
<p>Mysql has its uses, many many people have shown that you can build great things with it, but its far behind oracle (and SQL Server, and DB2) in terms of features... But then, its also free and very easy to learn, which for many people is the most important feature.</p>
|
<p>I'm using Oracle/SQL Server/MySql for different applications and site</p>
<p>No Database beat can Oracle in many different area, but it's the most database that require deep knowledge for the administration.</p>
<p>and if you found a problem with oracle, may spend few times to solve it even with good DBAs guys.</p>
<p>You can go with MySql for 500K or millions of records, it's more light than other DB, and require zero administration work, and will not take a lot of your computer resources, I always have it in my development PC, and never had faced any serious problem with it.</p>
<p>I would require you go with MySql or PostgreSQL if you don't need the advanced featuers of Oracle.</p>
| 12,734
|
<p>I have a WinForms app with an input textbox, button, and a multiline output textbox.
A root path is entered in the textbox. Button click calls a function to recursively check all subdirectories for some proper directory naming validation check.
The results are output into the multiline textbox.</p>
<p>If the recursive work is done in a separate class, I have two options:</p>
<ol>
<li><p>Keep track of improper directories in a class property(e.g. ArrayList),return the ArrayList when done, and update the output textbox with all results.</p></li>
<li><p>Pass in ByRef the output textbox and update/refresh it for each improper directory.
Even though 1 & 2 are single-threaded, with 2, I would at least get my results updated per directory.</p></li>
</ol>
<p>If the recursive work is done in the presentation layer and the validation is done in a separate class, I can multithread.</p>
<p>Which is a cleaner way?</p>
|
<p>You don't need to pass the TextBox ByRef. It's already a reference object. Passing it ByRef would only have an effect if you planned to assign a different or new TextBox to the reference.</p>
<p>If you're going to do the work in a separate class, it seems as simple as passing in the contents of the TextBox as a string, and getting the results back as a string or a set of strings (array or <code>List<string></code> or the like). This is better than passing in the TextBox in case someday you decide to use a different kind of control to store this information.</p>
|
<p>[not sure if this is the place for a follow up to the original question]</p>
<p>so, is it safe to say that a recursive business layer function will not be able to update a presentation level control at each recursive iteration?</p>
| 28,956
|
<p>What is the prefered method for creating a byte array from an input stream? </p>
<p>Here is my current solution with .NET 3.5. </p>
<pre><code>Stream s;
byte[] b;
using (BinaryReader br = new BinaryReader(s))
{
b = br.ReadBytes((int)s.Length);
}
</code></pre>
<p>Is it still a better idea to read and write chunks of the stream?</p>
|
<p>It really depends on whether or not you can trust <code>s.Length</code>. For many streams, you just don't know how much data there will be. In such cases - and before .NET 4 - I'd use code like this:</p>
<pre><code>public static byte[] ReadFully(Stream input)
{
byte[] buffer = new byte[16*1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
</code></pre>
<p>With .NET 4 and above, I'd use <a href="https://msdn.microsoft.com/en-us/library/system.io.stream.copyto" rel="noreferrer"><code>Stream.CopyTo</code></a>, which is basically equivalent to the loop in my code - create the <code>MemoryStream</code>, call <code>stream.CopyTo(ms)</code> and then return <code>ms.ToArray()</code>. Job done.</p>
<p>I should perhaps explain why my answer is longer than the others. <a href="http://msdn.microsoft.com/en-us/library/system.io.stream.read.aspx" rel="noreferrer"><code>Stream.Read</code></a> doesn't guarantee that it will read everything it's asked for. If you're reading from a network stream, for example, it may read one packet's worth and then return, even if there will be more data soon. <a href="http://msdn.microsoft.com/en-us/library/system.io.binaryreader.read.aspx" rel="noreferrer"><code>BinaryReader.Read</code></a> will keep going until the end of the stream or your specified size, but you still have to know the size to start with.</p>
<p>The above method will keep reading (and copying into a <code>MemoryStream</code>) until it runs out of data. It then asks the <code>MemoryStream</code> to return a copy of the data in an array. If you know the size to start with - or <em>think</em> you know the size, without being sure - you can construct the <code>MemoryStream</code> to be that size to start with. Likewise you can put a check at the end, and if the length of the stream is the same size as the buffer (returned by <a href="http://msdn.microsoft.com/en-us/library/system.io.memorystream.getbuffer.aspx" rel="noreferrer"><code>MemoryStream.GetBuffer</code></a>) then you can just return the buffer. So the above code isn't quite optimised, but will at least be correct. It doesn't assume any responsibility for closing the stream - the caller should do that.</p>
<p>See <a href="https://jonskeet.uk/csharp/readbinary.html" rel="noreferrer">this article</a> for more info (and an alternative implementation).</p>
|
<p>i was able to make it work on a single line:</p>
<pre><code>byte [] byteArr= ((MemoryStream)localStream).ToArray();
</code></pre>
<p>as clarified by <a href="https://stackoverflow.com/users/2840103/johnnyrose">johnnyRose</a>, Above code will only work for MemoryStream</p>
| 27,364
|
<p>I'm working on a legacy application that has a C++ extended stored procedure. This xsproc uses ODBC to connect to the database, which means it requires a DSN to be configured.</p>
<p>I'm updating the installer (created using Visual Studio 2008 setup project), and want to have a custom action that can create the ODBC DSN entry, but am struggling to find useful information on Google.</p>
<p>Can anyone help?</p>
|
<p>I actually solved this myself in the end by manipulating the registry. I've created a class to contain the functionality, the contents of which I've included here:</p>
<pre><code>///<summary>
/// Class to assist with creation and removal of ODBC DSN entries
///</summary>
public static class ODBCManager
{
private const string ODBC_INI_REG_PATH = "SOFTWARE\\ODBC\\ODBC.INI\\";
private const string ODBCINST_INI_REG_PATH = "SOFTWARE\\ODBC\\ODBCINST.INI\\";
/// <summary>
/// Creates a new DSN entry with the specified values. If the DSN exists, the values are updated.
/// </summary>
/// <param name="dsnName">Name of the DSN for use by client applications</param>
/// <param name="description">Description of the DSN that appears in the ODBC control panel applet</param>
/// <param name="server">Network name or IP address of database server</param>
/// <param name="driverName">Name of the driver to use</param>
/// <param name="trustedConnection">True to use NT authentication, false to require applications to supply username/password in the connection string</param>
/// <param name="database">Name of the datbase to connect to</param>
public static void CreateDSN(string dsnName, string description, string server, string driverName, bool trustedConnection, string database)
{
// Lookup driver path from driver name
var driverKey = Registry.LocalMachine.CreateSubKey(ODBCINST_INI_REG_PATH + driverName);
if (driverKey == null) throw new Exception(string.Format("ODBC Registry key for driver '{0}' does not exist", driverName));
string driverPath = driverKey.GetValue("Driver").ToString();
// Add value to odbc data sources
var datasourcesKey = Registry.LocalMachine.CreateSubKey(ODBC_INI_REG_PATH + "ODBC Data Sources");
if (datasourcesKey == null) throw new Exception("ODBC Registry key for datasources does not exist");
datasourcesKey.SetValue(dsnName, driverName);
// Create new key in odbc.ini with dsn name and add values
var dsnKey = Registry.LocalMachine.CreateSubKey(ODBC_INI_REG_PATH + dsnName);
if (dsnKey == null) throw new Exception("ODBC Registry key for DSN was not created");
dsnKey.SetValue("Database", database);
dsnKey.SetValue("Description", description);
dsnKey.SetValue("Driver", driverPath);
dsnKey.SetValue("LastUser", Environment.UserName);
dsnKey.SetValue("Server", server);
dsnKey.SetValue("Database", database);
dsnKey.SetValue("Trusted_Connection", trustedConnection ? "Yes" : "No");
}
/// <summary>
/// Removes a DSN entry
/// </summary>
/// <param name="dsnName">Name of the DSN to remove.</param>
public static void RemoveDSN(string dsnName)
{
// Remove DSN key
Registry.LocalMachine.DeleteSubKeyTree(ODBC_INI_REG_PATH + dsnName);
// Remove DSN name from values list in ODBC Data Sources key
var datasourcesKey = Registry.LocalMachine.CreateSubKey(ODBC_INI_REG_PATH + "ODBC Data Sources");
if (datasourcesKey == null) throw new Exception("ODBC Registry key for datasources does not exist");
datasourcesKey.DeleteValue(dsnName);
}
///<summary>
/// Checks the registry to see if a DSN exists with the specified name
///</summary>
///<param name="dsnName"></param>
///<returns></returns>
public static bool DSNExists(string dsnName)
{
var driversKey = Registry.LocalMachine.CreateSubKey(ODBCINST_INI_REG_PATH + "ODBC Drivers");
if (driversKey == null) throw new Exception("ODBC Registry key for drivers does not exist");
return driversKey.GetValue(dsnName) != null;
}
///<summary>
/// Returns an array of driver names installed on the system
///</summary>
///<returns></returns>
public static string[] GetInstalledDrivers()
{
var driversKey = Registry.LocalMachine.CreateSubKey(ODBCINST_INI_REG_PATH + "ODBC Drivers");
if (driversKey == null) throw new Exception("ODBC Registry key for drivers does not exist");
var driverNames = driversKey.GetValueNames();
var ret = new List<string>();
foreach (var driverName in driverNames)
{
if (driverName != "(Default)")
{
ret.Add(driverName);
}
}
return ret.ToArray();
}
}
</code></pre>
|
<p>Thanks for providing this code, I have used it myself. I had to change two things tough:</p>
<p>To get the <code>driverName</code> I had to use <code>OpenSubKey</code> instead of <code>CreateSubKey</code> to get the values:</p>
<pre><code>// Lookup driver path from driver name
var driverKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(
ODBCINST_INI_REG_PATH + driverName);
</code></pre>
<p>Since I am running Vista, I had to use an application manifest and set the <code>requestedPrivileges</code> to:</p>
<pre><code><requestedExecutionLevel level="requireAdministrator" uiAccess="false"/>
</code></pre>
<p>The following article helped me to find the <code>OpenSubKey</code> issue: <a href="http://www.daveoncsharp.com/2009/08/read-write-delete-from-windows-registry-with-csharp/" rel="nofollow noreferrer">http://www.daveoncsharp.com/2009/08/read-write-delete-from-windows-registry-with-csharp/</a></p>
| 43,440
|
<p>Looking for code samples to access a memory map file in C#</p>
|
<p>Looks like C# 4.0 will have MemoryMappedFile support in the library</p>
|
<p><a href="http://1code.codeplex.com/wikipage?title=IRPC" rel="nofollow">http://1code.codeplex.com/wikipage?title=IRPC</a></p>
<p>Search with </p>
<pre><code>CSFileMappingClient
CSFileMappingServer
</code></pre>
| 26,564
|
<p>I'm reading <em>The C++ Programming Language.</em> In it Stroustrup states that <code>sizeof(char) == 1</code> and <code>1 <= sizeof(bool)</code>. The specifics depend on the implementation. Why would such a simple value as a boolean take the same space as a char?</p>
|
<p>In modern computer architectures, a byte is the smallest addressable unit of memory. To pack multiple bits into a byte requires applying extra bit-shift operations. At the compiler level, it's a trade off of memory vs. speed requirements (and in high-performance software, those extra bit-shift operations can add up and slow down the application needlessly).</p>
|
<p>Actually, in most implementation that I know of sizeof(bool) == sizeof(int). "int" is intended to be the data size that is most efficient for the CPU to work with. Hence things which do not have a specific size (like "char") are the same size as an int. If you had a large number of them per object, you may want to implement a means of packing them for storage, but during normal calculation, it should be left it's native size.</p>
| 33,460
|
<p>I'm stuck with .Net 1.1 application (i.e. I can not use the generics goodies from 2.0 for now), and I was trying to optimize some parts of the code. As it deals a lot with runtime callable wrappers, which need to be released, I ended up to create a utility method which loops until all references are released. The signature of the method is:</p>
<pre><code>void ReleaseObject(object comObject)
</code></pre>
<p>After releasing all comObjects, I call GC.Collect and GC.WaitForPendingFinalizers (don't ask - anybody dealing with Office interop knows).</p>
<p>And ... as usual, I hit a corner case - if I do not assign the corresponding managed reference to null before the GC.Collect call, it does not cleanup properly.</p>
<p>So, my code looks like:</p>
<pre><code>ReleaseObject(myComObject);
myComObject = null;
GC.Collect()
...
</code></pre>
<p>As, there are a bunch of xxx=null, I decided to put this in the util method, but as there is a difference between passing by reference, and passing a reference parameter, obviously I had to change the method to:</p>
<pre><code>void ReleaseObject(out object comObject)
{
//do release
comObject = null;
}
</code></pre>
<p>and edit the caller to:</p>
<pre><code>MyComClass myComObject = xxxx;
ReleaseObject(out myComObject);
</code></pre>
<p>This fails with a message: "Cannot convert from 'out MyComClass' to 'out object'"</p>
<p>While I can think of why it can be a problem (i.e. the reverse cast from object to MyComClass is not implicit, and there is no guarantee what the method will do), I was wondering if there is a workaround, or I need to stay with my hundreds assignments of nulls.</p>
<p>Note: I have a bunch of different COM objects types, thats why I need a "object" parameter, and not a type safe one.</p>
|
<p>Why is it better to call a method than to just set the variable to null? They're both single line calls, and the latter is a lot simpler.</p>
<p>It does sound very odd that you need to set them to null in the first place though. Are these static variables, or instance variables whose values need to be released earlier than their containing object? If the variable is just a local variable which will go out of scope anyway, setting it to null shouldn't make any difference (in release).</p>
<p>Do the RCWs not implement IDisposable? If so, calling Dispose (preferably via a using statement) would be the best bet.</p>
<p>(After discussions in comments.)</p>
<p>These are local variables, which aren't referenced later in the method. That means the garbage collector will realise that they don't need to be treated as "root" references - so setting them to null shouldn't make any difference.</p>
<p>To answer the original question directly, however: no, you can't pass a variable by reference unless the method parameter is of exactly the same type, so you're out of luck here. (With generics it would be possible, but you've said you're limited to .NET 1.1.)</p>
|
<p>You should be calling <a href="http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.releasecomobject.aspx" rel="nofollow noreferrer"><code>Marshal.ReleaseComObject</code></a>, which AFAIK was available in 1.1.</p>
<p>You probably mean "ref":</p>
<pre><code>static void ReleaseObject(ref object comObject)
{
if(comObject != null)
{
//do release
comObject = null;
}
}
</code></pre>
<p>[edit re comments] however, this will only work for untyped objects, so not much use without generics! Oh for C# 2.0...</p>
<p>Re the "ref"; if the variables are truly variables (meaning: method variables), then they will go out of scope shortly and get collected. The "ref" would only be useful to release fields. But to be honest, it would be simpler just to set them to null...</p>
<p>A typical COM pattern is:</p>
<pre><code>SomeType obj = new SomeType();
try {
obj.SomeMethod(); // etc
} finally {
Marshal.ReleaseComObject(obj);
}
</code></pre>
| 30,364
|
<p>After cleaning a folder full of HTML files with TIDY, how can the tables content be extracted for further processing?</p>
|
<p>I've used BeautifulSoup for such things in the past with great success.</p>
|
<p>In .NET you could use <a href="http://www.codeplex.com/htmlagilitypack" rel="nofollow noreferrer">HTMLAgilityPack</a>.</p>
<p>See this <a href="https://stackoverflow.com/questions/2861/options-for-html-scraping">previous question</a> on StackOverflow for more information.</p>
| 9,426
|
<p>I was chatting to someone the other day who suggested that Rails and PHP are the most suitable platforms for web applications, and to avoid Java. My background is mainly Java, and I know that it is considered by some to be too verbose and "heavyweight", but is used occasionally (e.g. by LinkedIn).</p>
<p>So I'm wondering whether anyone has had success using Java for a recent web application that has gone live, either using the language itself (e.g. with Stripes/Spring + Hibernate), or the runtime with a dymamic language (such as JRuby, Groovy, Jython)? If so, please share what worked and what you would do differently.</p>
<p><strong>Some background</strong> <em>(added later)</em>:
Tim O'Reilly coined the phrased "Web 2.0" and here is his definition: <a href="http://www.oreillynet.com/lpt/a/6228" rel="nofollow noreferrer">http://www.oreillynet.com/lpt/a/6228</a></p>
<p>I think it's the "End of the release cycle" and "Lightweight programming model", involving rapid iterations and simplified deployment, where Java may be less suitable. Thoughts?</p>
|
<p>I would argue that there is no specific technology for Web 2.0. The main concept behind a Web 2.0 application is that much of the content is provided by it's users and not one specific person. If you can achieve this with Java, then that is fine. Many people are creating startup companies with technology that is free because they don't have the capital. </p>
|
<p>I build Web apps at work in Java and then I use PHP for my personal projects. While Java is certainly capable of all that you might require it to do, I've found it a little cumbersome at times and have wished I was using PHP (or another language, for that matter). It does depend on what type and size of application you're building, but I think there are good reasons why many people choose PHP, Ruby and Python for their personal projects, i.e. where <em>they</em> get to choose what language they build Web apps in (and not their superiors).</p>
| 43,722
|
<p>I am exploring ASP.NET MVC and I wanted to add jQuery to make the site interactive. I used StringTemplate, ported to .Net, as my template engine to generate html and to send JSON. However, when I view the page, I could not see it. After debugging, I've realized that the $ is used by the StringTemplate to access property, etc and jQuery uses it too to manipulate the DOM. Gee, I've looked on other template engines and most of them uses the dollar sign :(.</p>
<p>Any alternative template engine for ASP.Net MVC? I wanted to retain jQuery because MSFT announced that it will used in the Visual Studio (2008?)</p>
<p>Thanks in Advance :)</p>
<p><strong>Update</strong></p>
<p>Please go to <a href="https://stackoverflow.com/questions/1451319/asp-net-mvc-view-engine-comparison/1451355#1451355">the answer</a> in <a href="https://stackoverflow.com/questions/1451319/asp-net-mvc-view-engine-comparison">ASP.NET MVC View Engine Comparison</a> question for a comprehensive list of Template engine for ASP.NET MVC, and their pros and cons</p>
<p><strong>Update 2</strong></p>
<p>At the end I'll just put the JavaScript code, including JQuery, in a separate script file, hence I wouldn't worry about the <code>$</code> mingling in the template file.</p>
<p><strong>Update 3</strong></p>
<p>Changed the Title to reflect what I need to resolve. After all "The Best X in Y" is very subjective question.</p>
|
<p>You can of course move your js logic into a .js file. But if you want it inline with your StringTemplate views, you can escape it using the \$ construct.</p>
<p>In addition, you can simply use the jQuery("selector"), instead of $("selector") construct if you want to avoid the escaping syntax.</p>
<p>Here's a good article on <a href="http://websitelogic.net/articles/MVC/stringtemplate-viewengine-asp-net-mvc/" rel="noreferrer">using StringTemplate as a View Engine in MVC</a>. </p>
<p>There's also an accompanying <a href="http://code.google.com/p/string-template-view-engine-mvc/" rel="noreferrer">OpenSource engine, along with some samples</a>.</p>
<p>Also, as mentioned above, you can modify your Type Lexer. (make it an alternate character to the $). </p>
|
<p>You could try <a href="http://jsrepeater.devprog.com/introduction.html" rel="nofollow noreferrer">jsRepeater</a>.</p>
| 20,864
|
<p>I think you can do GDI+ drawing in just about any window in a .net windows forms project, but what do you recommend as the best built-in control for containing custom drawing? I'm going to be drawing my own x-y plots, text and images. I could use a Panel, UserControl, etc. </p>
|
<p>If you're just drawing the control and not hosting children, then derive from Control - VS will make you a suitable class (it calls this a 'Custom Control') with the OnDraw handler already stubbed in.</p>
<p>If you're hosting other controls within your control, then derive from UserControl, (VS calls this a 'User Control' and you'll get support for VS designer, so you can drag around other controls on top.</p>
<p>For simple non-scrolling charting I would derive from Control.</p>
|
<p>Do your GDI+ drawing in an offscreen bitmap surface, and then blit it to whatever control you need.</p>
<p>Your controls Paint method only needs to copy the surface to itself.</p>
| 31,808
|
<p>I want to detect users' screen size and pass this into a charting application (Chart Director by <a href="http://www.advsofteng.com" rel="nofollow noreferrer">http://www.advsofteng.com</a>) to control how big an image to display.</p>
<p>I have to use ASP, but I can only think to use JavaScript to detect screen-size and then pass this into the server-side script. Is there an easier way?</p>
<p>Thanks</p>
|
<p>No, the server knows nothing about the client other than basic info like IP and browser version.
Screen resolution can easily be determined via javascript and passed to the server though, using ajax, or via form submission.</p>
|
<p>No, this is not possible for desktop browsers. I suggest embedding an image that's appropriate for typical screen resolutions, then detecting the canvas size, and rewriting the image's <code>src</code> attribute to reflect that.</p>
<p>In any case, you <em>don't</em> want to look at the screen resolution, you want to look at the canvas size. Not everybody uses their browser with a maximised window, especially those with large screens. If you use the screen resolution, then you'll end up serving images that are way too big for some people.</p>
| 14,830
|
<p>Inspired by another question and due to the fact that some of my filament will face the same problem when I will use them again, I wanted to know if there are proven recipies to get rid of water that has ben incorporated to PLA filament from humidity? One knows the filament had too much exposure to humidity when hearing tiny puffs during extrusion and/or more brittle prints.</p>
<p>I know about suggestions to heat the water out of the filament at a temperature well below the glass transition temperature, but can someone provide first hand knowledge or even evidence?</p>
|
<p><strong>The easiest way to freshen up filament is hot air, although there are other options.</strong></p>
<p>There is an optimal melt processing <em>moisture level</em> for every plastic, typically in the range of 0.1-0.2% water content by weight. But the equilibrium moisture content of most plastics in humid air can be more like 1%. As a consequence, <strong>hot air dehydration is standard practice</strong> to prepare plastic pellets for extrusion in industry. Pretty much every injection-molded and extruded plastic product in the world -- including 3d printer filament -- is made with pre-dried pellets. Hot air is blown through the pellets until they are below the moisture limit.</p>
<p>Different plastics tolerate extrusion with different amounts of moisture, and absorb different amounts of moisture. They can also tolerate different drying temperatures. So the ideal storage and drying conditions vary by material. </p>
<ul>
<li><strong>PLA</strong> absorbs relatively little moisture, but in humid environments can accumulate enough water content to cause steam bubbles during extrusion. In some cases, steam bubbles can contribute to hot end jamming. Extreme wetness has been known to cause swelling that can increase filament feed drag. It's arguable whether wetness actually causes brittleness, or if that is a separate aging issue. People who keep their homes below ~50% relative humidity usually don't have any problems. Leaving PLA in a dry environment for a week or two should adequately re-dry it, or it can be gently heated to about 120F / 50C for a couple hours. (Some people dry it hotter. but that risks deforming the filament.)</li>
<li><strong>ABS</strong> also doesn't absorb very much water, but perhaps a little more than PLA. It also experiences steam bubbles, but that's typically the only issue. Homes below ~45% RH usually don't have problems. Storing ABS with fresh silica gel for a couple weeks will dry it. Or it can be oven-dried up to about 180F / 80C for an couple hours. <strong>HIPS</strong> can be treated the same. </li>
<li>The kind of PET used in plastic bottles is rapidly degraded into tar by hydrolysis when melted with any significant water content. So <strong>PETG</strong> filaments are specially blended to absorb less water and to be less damaged by water than PET. But there is still the possibility of bubbles and cloudy strands due to steam expansion at higher temperatures, and there is some evidence that wet PETG produces weaker, more brittle prints than dry PETG. Different manufacturers' blends require different conditions: some people report Taulman t-glase needs oven-drying and careful storage while Esun PETG is fairly tolerant of normal home humidity levels. Oven-drying at 150F / 65C should work well. </li>
<li><strong>Nylon</strong> absorbs a huge amount of water, which causes it to swell considerably, produce massive steam bubbles, look cloudy, warp more, and adhere less than properly-dried nylon. It's nearly unprintable when wet. It should be oven-dried at around 150F / 65C for 4+ hours -- desiccant will not strip enough moisture from it. In fact, nylon will pull water out of used silica gel! Once dry, it should be stored with an aggressive desiccant (either bone-dry silica or preferably calcium chloride). It only takes a few hours of exposure to air for it to become excessively moist. Building a sealed drybox feed system is highly recommended to avoid exposed time during and between prints. </li>
<li><strong>Polycarbonate</strong> is similar to nylon in that is is an aggressive water-absorber. It will look cloudy, produce steam bubbles, warp more, and provide very poor layer bonding when wet. It should be oven-dried at 180F / 80C if on a plastic spool (up to 250F / 120C if dried alone) for 4+ hours and then stored in a drybox with aggressive desiccant just like nylon. Note that some modern PC blends like Esun ePC are less prone to water absorption, at the cost of some decrease in mechanical properties. </li>
<li><strong>PVA</strong> is basically destroyed by airborne humidity, since it literally dissolves in water. Store in a drybox with an aggressive desiccant at all times. </li>
</ul>
<p>Composite filaments should be treated like the base material. </p>
<p>Some drying and prevention options:</p>
<ul>
<li><strong>Oven</strong>: The "warm" setting will usually work pretty well. Let the oven preheat and settle out for a while, and measure temperature with a good oven thermometer or thermocouple. Shield the filament from direct radiant heating and hot spots with aluminum foil, cookie sheets, etc. Electric ovens will dry faster than gas ovens, because burning natural gas produces some additional moisture. Do not leave the oven unattended if using temperatures above the glass point of the filament, or bad things may happen!</li>
<li><strong>"Light bucket"</strong>: A 5-gallon plastic bucket with an incandescent lightbulb inside is a pretty effective way to gently warm low-temp filament like PLA for drying or medium-term storage. Leave the lid slightly open if drying. </li>
<li><strong>Food dehydrator</strong>: Works great. Set temperatures as per the oven temps above. The main challenge is getting a large enough space inside for a filament spool. </li>
<li><strong>Desiccant</strong>: In order for desiccant to actively dry filament, it must be significantly more attractive to water than the filament is. And affinity for water is a function of how wet the material already is. That means dry desiccant can easily pull some water out of very wet filament, but wet desiccant can actually give water TO the filament! Rechargeable indicator desiccant (such as an <em>Eva-Dry E-333</em> unit) is ideal. It's also important to have ENOUGH desiccant: silica gel can only absorb 10% of its weight in water at 20% RH. That means to pull 1% moisture content out of a wet 1kg spool, you would need to start with at least 100g of bone-dry, fresh-baked silica! "Used" silica is basically useless, it already contains too much water to pull any more from the filament. But you can re-dry the silica in an oven. 250F / 120C for 6 hours should be safe for all types of silica gel, but more aggressive drying (including microwave drying) is possible for some silica gels. Follow the gel manufacturer instructions. </li>
<li><strong>Rice</strong>: Does not work. It's basically a myth that rice has drying power. A bag of rice you buy at the store is already pretty close to moisture equilibrium with the air, so it has minimal capacity to pull water from filament (or a soaked iPhone, for that matter). If you dry the rice in an oven to drive out its water first, it will work to some degree, but silica gel is considerably more effective. </li>
<li><strong>Kitty litter</strong>: Silica gel style kitty litter is nearly identical to desiccant silica gel. Like rice, it is fairly close to saturated when you open the container, but can be dried in the oven to be a good cheap bulk desiccant. Clay type kitty litter is not as effective. Be careful of getting kitty litter dust all over your filament. </li>
<li><strong>Dry storage</strong> A thick plastic box with an airtight seal is preferable. Look for recycling code 2 (HDPE) or 5 (PP) on the box. 5 gallon buckets with sealing lids also work fine. Ziplocks and other thin plastic bags are better than nothing, but are permeable to water (yes, really) and can only be relied on as long as there is fresh desiccant in the bag. Acrylic/plexiglas dryboxes have been sold by various people, but acrylic is very permeable to water, so I don't recommend that option. </li>
<li><strong>Air conditioning</strong>: Simply keeping the air in your printing environment reasonably dry will protect PLA and ABS and other low-absorption filaments. It may help to buy a humidity monitor to get an understanding of your ambient humidity. </li>
</ul>
<p>Now, considering the original question here, it's important to note that moisture content is not the only way filament can age or be damaged. PLA in particular is prone to becoming brittle over time. There are different theories for why this occurs. One is gradual chemical aging because poly(lactic acid) simply is not a very stable polymer. Moisture could contribute to that aging process, but true chemical aging would be irreversible even if the filament is later dried. How much this occurs should depend on the specific polymer blend and storage conditions. </p>
<p>Another theory for PLA aging is that the residual filament extrusion stresses (from being drawn down to the correct diameter and rapidly quenched in a water bath) are slowly creeping over time. Anyone who has placed a PLA part under heavy load for more than a few weeks will see PLA creep. It's a rather odd polymer in that it will "creep to failure" and crack at very low creep elongations rather than progressively deform in a ductile manner like most creep-prone materials. So if the PLA has significant stresses locked-in from the initial extrusion process (which is very common) it may be creeping into a more brittle arrangement of polymer molecules over time. That would explain the aging effect, and it would explain why "drying" sometimes rejuvenates the PLA: heating the filament near its glass point will allow the polymer molecules to gently relax and basically anneal to a less brittle state. </p>
|
<p>Keep in mind gas ovens produce water when the gas is burned, so it isn't as effective as an electric oven for drying.</p>
<p>Silica desiccant is excellent for drying filament, but you will want at least some of the desiccant beads to be "indicating" type. That is they show a color change when saturated with moisture. Silica desiccant can be recharged in a 220 °F (104 °C) oven, and can withstand a higher temperature than the filament, and it expels water when warm even though a lot is present in a gas oven. Indicating silica is typically blue or orange dry, pink or green when wet. If you have white silica beads with just a small percentage of indicating beads in it, they will equalize in moisture so the indicating beads can be trusted to indicate for the whole batch. Non-indicating silica is cheaper and can be spiked with a small dose of indicating beads.</p>
<p>I use an x-large (~5 gallon) double zipper ziploc "big bag" with my entire supply of filament inside, along with a cloth bag holding 2.5 pounds of indicating silica beads. Even if the ziploc seal isn't perfect, the silica will maintain a low humidity until spent. It is rated to reduce humidity to 40 % and hold 40 % by weight in water (not the 10 % mentioned above, past 40 % water and the humidity will rise past 40 %), but in my 46 % rh (relative humidity) house, my filament bag dropped to 15 % rh within 20 minutes (measured with a HVAC humidity meter). The 2.5 pounds (1.1 kg) of silica can absorb 1 pound of water (0.45 kg). You can weigh your silica to get an indication of how much water is in it. I stored my filament in a vacuum chamber for a week while I waited for my order of desiccant to arrive, so the filament was quite dry before I filled the bag. The vacuum chamber is not practical for storage as you have to evacuate it every time you open it, and it doesn't hold much.</p>
| 327
|
<p>Are there any IQueriable implementaions for linq-to-objects that perform better than the default O(n) linear search performance that you get when calling myEnumerable.AsQueriable()?</p>
<p>I've had a look at <a href="http://www.codeplex.com/i4o/" rel="nofollow noreferrer">http://www.codeplex.com/i4o/</a> which has better performance, but seems to rely on using extension methods on IndexedCollection rather than making IndexedColleciton implement IQueriable. </p>
<p>I'm keen to keep my interface returning IQueriable<T> as I don't want anyone to know whether they are hitting a cache or a db.</p>
|
<p>you might want to have a look at plinq <a href="http://msdn.microsoft.com/en-us/magazine/cc163329.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/magazine/cc163329.aspx</a></p>
|
<p>Another answer might be to back it by an in memory object database like: <a href="http://www.db4o.com/s/linqdb.aspx" rel="nofollow noreferrer">db4o</a></p>
| 11,799
|
<p>I never use Access 2007 - until today.</p>
<p>I want to connect to an existing SQL Server 2008 database. I have tried using:</p>
<ul>
<li>External Data ODBC option - but get DSN errror</li>
<li>Upsizing wizard with ODBC - get an error</li>
<li>Upsizing wizard with SNAC - get ODBC error. So that one seems a none starter :-)</li>
</ul>
<p>I have done some searching and only found others with same issue. About to do some more... but hoping one of you has the answer OTTOYH. Thanks.</p>
|
<p>The upsizing wizard in Access 2007 is not aware of SQL Server 2008 and therefore won't connect. You should use the <a href="http://www.microsoft.com/sqlserver/en/us/product-info/migration-tool.aspx#Access" rel="nofollow noreferrer">SQL Server migration assistant for Access</a> tool that is provided with SQL Server 2008.</p>
|
<p>What error do you get when trying to link to the ODBC connection?
Just to confirm, you are selecting ODBC Database from the Import part of the 'External Data' ribbon?
If you test your ODBC conneciton does it pass?</p>
| 34,220
|
<p>OpenID is a great idea in principle, but the UI and the explanation as to why it is good are currently not tailored for general use -- what do you think it would take to make OpenID work for the general public? Can this be solved with technology, or is the problem so intrinsically hard that we are stuck with difficult explanations/multi-step registration procedures, numerous accounts, or poor security?</p>
|
<p>It needs to be much simpler: involve less knowledge of the concepts, and require fewer steps - preferably zero. When the technology works with little or no assistance, it'll take off.</p>
<p>The mechanics of OpenID credentials, providers and suppliers shouldn't need to be exposed to the user. People talk about educating the masses of internet users, but that's never going to happen - the masses never stop being stupid. If you want to appeal to the masses, you need to bring the technology down to meet their level instead. When a Google-affiliated site picks up that you're logged into Google and silently uses that account, it works without you ever having to tell it who you are. The fact that OpenID is so clumsy in comparison is why the big providers like Google are still avoiding it, and why the general public won't adopt it.</p>
<p>I think the developers of OpenID messed up when they used a URL rather than an email address for the IDs. People know what email addresses are, they already have one that's associated with them (or can get one easily), and email providers like Google and Microsoft are happy to adopt a role as portals. In fact, an automatic translation from email address to URL is all it would take:</p>
<blockquote>
<p>myname@example.com -> <a href="http://www.example.com/openid/myname" rel="nofollow noreferrer">http://www.example.com/openid/myname</a></p>
</blockquote>
|
<p>Make it less open.</p>
<p>i do not want the same identity on multiple sites.
i do not want to have to create a flickr account before StackOverflow will let me post.
i do not have to have to create a new flickr account for each website that i want to register with.</p>
| 7,354
|
<p>It is really annoying.</p>
<pre><code>Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new mainForm()); <-- pausing visual studio breaks here.
</code></pre>
<p>Thanks guys.</p>
|
<p>@sramey are you sure pausing always breaks on the said line? If I may hazard a guess here I think when you press the pause button you application is idle and the program is spending most of its time in the Win32 message loop abstracted by Application.Run(). Hence there is a high probability that VS breaks the execution of the main thread there.</p>
<p>I think pressing pause is not always the best way of debugging things. You need to make educated guesses about problem areas and set breakpoints in relevant methods (like Constructors, API calls etc)</p>
<p>Need more info on what you are trying to accomplish here.</p>
|
<p>Taking into account the previous comments, you might want to set a Breakpoint where you want your application to stop.</p>
<p>I usually do this by going to where I want the debugger to stop, then pressing <code>F9</code>. You can also click in the left-hand margin. There are other ways.</p>
<p>You can also configure breakpoints to stop only when a certain condition is true (such as <code>i == 0</code>).</p>
<p>Microsoft have <a href="http://msdn.microsoft.com/en-us/library/sc65sadd.aspx" rel="nofollow noreferrer" title="MSDN Link">a guide on Debugging in Visual Studio</a>.</p>
| 39,814
|
<p>This is a new gmail labs feature that lets you specify an RSS feed to grab random quotes from to append to your email signature. I'd like to use that to generate signatures programmatically based on parameters I pass in, the current time, etc. (For example, I have a script in pine that appends the current probabilities of McCain and Obama winning, fetched from intrade's API. See below.) But it seems gmail caches the contents of the URL you specify. Any way to control that or anyone know how often gmail looks at the URL?</p>
<p>ADDED: Here's the program I'm using to test this. This file lives at <a href="http://kibotzer.com/sigs.php" rel="nofollow noreferrer">http://kibotzer.com/sigs.php</a>. The no-cache header idea, taken from here -- <a href="http://mapki.com/wiki/Dynamic_XML" rel="nofollow noreferrer">http://mapki.com/wiki/Dynamic_XML</a> -- seems to not help.</p>
<pre><code><?php
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
// HTTP/1.1
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
// HTTP/1.0
header("Pragma: no-cache");
//XML Header
header("content-type:text/xml");
?>
<!DOCTYPE rss PUBLIC "-//Netscape Communications//DTD RSS 0.91//EN" "http://my.netscape.com/publish/formats/rss-0.91.dtd">
<rss version="0.91">
<channel>
<title>Dynamic Signatures</title>
<link>http://kibotzer.com</link>
<description>Blah blah</description>
<language>en-us</language>
<pubDate>26 Sep 2008 02:15:01 -0000</pubDate>
<webMaster>dreeves@kibotzer.com</webMaster>
<managingEditor>dreeves@kibotzer.com (Daniel Reeves)</managingEditor>
<lastBuildDate>26 Sep 2008 02:15:01 -0000</lastBuildDate>
<image>
<title>Kibotzer Logo</title>
<url>http://kibotzer.com/logos/kibo-logo-1.gif</url>
<link>http://kibotzer.com/</link>
<width>120</width>
<height>60</height>
<description>Kibotzer</description>
</image>
<item>
<title>
Dynamic Signature 1 (<?php echo gmdate("H:i:s"); ?>)
</title>
<link>http://kibotzer.com</link>
<description>This is the description for Signature 1 (<?php echo gmdate("H:i:s"); ?>) </description>
</item>
<item>
<title>
Dynamic Signature 2 (<?php echo gmdate("H:i:s"); ?>)
</title>
<link>http://kibotzer.com</link>
<description>This is the description for Signature 2 (<?php echo gmdate("H:i:s"); ?>) </description>
</item>
</channel>
</rss>
</code></pre>
<pre>
--
http://ai.eecs.umich.edu/people/dreeves - - search://"Daniel Reeves"
Latest probabilities from intrade...
42.1% McCain becomes president (last trade 18:07 FRI)
57.0% Obama becomes president (last trade 18:34 FRI)
17.6% US recession in 2008 (last trade 16:24 FRI)
16.1% Overt air strike against Iran in '08 (last trade 17:39 FRI)
</pre>
|
<p>The stream has a reference graph, so an object which is sent twice will not give two objects on the other end, you will only get one. And sending the same object twice separately will give you the same instance twice (each with the same data - which is what you're seeing).</p>
<p>See the reset() method if you want to reset the graph.</p>
|
<p>Max is correct, but you can also use:</p>
<pre><code>public void writeUnshared(Object obj);
</code></pre>
<p>See comment below for caveat</p>
| 17,202
|
<p>I have an executable module created by third party. I would like to "inject" my code (kind of watchdog running in separate thread) into this process. </p>
<p>So far there are two possible ways - one is to run my code as executable and dynamically load a proess on top of it (seems to be very hard and tricky) or to make my code a shared object, load it via LD_PRELOAD and initialize from some static variable constructor.</p>
<p>Are there more convenient ways to do this ?
My OS are Linux x86 and Solaris-SPARC.</p>
<p>Update: If possible, I'd like not to patch the process, but load my code dynamicaly.</p>
|
<p>Sounds like you're looking for <a href="http://www.securiteam.com/tools/5EP0P157PG.html" rel="nofollow noreferrer">InjectSo</a>. There's a <a href="http://www.blackhat.com/presentations/bh-europe-01/shaun-clowes/bh-europe-01-clowes.ppt" rel="nofollow noreferrer">Powerpoint presentation</a> that explains how it works. I haven't gotten around to trying it out yet.</p>
|
<p>Rob Kennedy told you about InjectSo - that's probably what you need.</p>
<p>Beware that the introduction of a thread into a non-threaded process would be fraught with synchronization issues. The problems are less serious if the application is already threaded, but even so, the application may object to a thread that it doesn't know about.</p>
| 49,530
|
<p>I've personally always used some type of external application for my SCM work; these days, that means <a href="http://tortoisesvn.tigris.org" rel="nofollow noreferrer">tortoiseSVN</a> on windows and <a href="http://versionsapp.com" rel="nofollow noreferrer">versions.app</a> on the mac. However, I keep running up against developers (namely eclipse users) who argue that SCM is better done within the IDE itself. I've yet to hear any really compelling arguments in favor of this workflow, and I personally like a degree of "separation" between the IDE and SCM operations. This has been burned into me from using unstable SVN plugins in Visual Studio, and the sub-standard SVN support in Xcode in years past when working offline.</p>
<p>Which way promotes the better workflow in your opinion?</p>
|
<p>I definitely prefer outside. That being said, my primary IDE is Visual Studio, and I haven't used eclipse or intellij (although I have used cvs-mode in emacs...), so your mileage may vary...</p>
<ul>
<li><p>Making changes and committing changes are separate tasks - having them both be easily available in the IDE means you don't clearly delineate between completing a set of changes and committing them. Quite often it's a case of type type type, compile, test, test, commit...'oh, wait - I forgot to foo the bar as well. Context switching from IDE mode to SCM mode tends to trigger the 'oh, wait' before the commit.</p></li>
<li><p>Keeping related files for commits together - it's all too easy to commit source changes, then remember the related SQL scripts and commit those separately and then add the new image files as you forgot those because they're new to the repository and so on.</p></li>
<li><p>Similar to the above, it tends to be a lot easier to commit things at the wrong level/directory in the repository when in the IDE. (e.g. I should have committed at solution level, not project level)</p></li>
<li><p>It tends to be easier to get a complete diff of your workspace against the repository outside the IDE, which is often worthwhile.</p></li>
<li><p>It also probably makes your IDE that extra bit faster</p></li>
</ul>
<p>I also agree with a previous poster - all non-trivial SCM tasks tend to be easier outside development IDE integration.</p>
<p>To be honest, as long as you're avoiding messy commit situations described above, do whatever you find most comfortable. In terms of workflow - the separation has to be 'cleaner', whether this cleanliness outweighs the convenience is going to be in the eye of the beholder - we're largely reacting to our personal experience (I suspect mine is similar to yours).</p>
<p>Whatever you do, use <a href="http://www.codinghorror.com/blog/archives/000660.html'" rel="nofollow noreferrer">anything but SourceSafe...</a> I have to at the moment for legacy code - I find it abhorrent that files are made read only and that the SCM integration physically alters the contents of files...</p>
|
<p>It very much depends on the IDE/SCM combination. I'm currently using IntelliJ with SVN, and find that IntelliJ's SVN plugin is generally much more pleasant to use than Tortoise. Not that I have any particular complaints about Tortoise -- IntelliJ is just better.</p>
| 29,015
|
<p>I have a very large C project with many separate C files and headers and many dozens of contributors. Many contributors do not have a strong knowledge of makefiles and dependencies, resulting in the not uncommon problem where you almost always have to "make clean" before you can trust "make" to have produced correct output.</p>
<p>If make took minutes, this wouldn't be an issue, but it's nearly 2 hours on a fast machine now, and people are starting to check in code that works when they make, but they don't clean first and their code ultimately breaks the build. Don't ask why these aren't caught by the build manager before a new baseline is cut...</p>
<p>Yes, we shouldn't have let it go this far.</p>
<p>Yes, we're educating our developers.</p>
<p>As usual, we don't have time to stop everything and fix it by hand.</p>
<p>I'm thinking there are tools along these lines:</p>
<ul>
<li>Are there automated tools to help build correct dependency information for an existing project from the C and H files?</li>
<li>Are there automated tools to describe dependency information according to the makefiles?</li>
<li>Is there a holy grail of a tool to describe the differences between the above two dependency trees?</li>
</ul>
<p>But what else can/should be done to resolve this issue?</p>
<p>Thanks in advance...</p>
<p>-Adam</p>
|
<p>It might be easiest to switch from Make to a tool which automatically detects dependencies. For example, <a href="http://www.scons.org/" rel="nofollow noreferrer">SCons</a> doesn't make you list dependencies but instead automatically parses the files being compiled and looks for includes. You simply specify which files should be compiled and which files go into which executables. Switching build systems will be easier for the fact that your developers aren't really Make experts.</p>
<p>Another alternative if you stick with Make is to use the <code>gcc -M</code> option to automatically detect dependencies. The answer to the <a href="https://stackoverflow.com/questions/204823/automatically-discovering-c-dependencies">Automatically discovering C dependencies</a> question has an example of how to have your makefiles automatically discover dependencies so that you don't need to specify them by hand.</p>
|
<p>We have the same problem at my workplace. The Trunk was always broken after merges or check-ins. </p>
<p>We set up a <a href="http://en.wikipedia.org/wiki/Continuous_Integration" rel="nofollow noreferrer">continuous integation</a> build machine that does a make clean in about 45 minutes compared to about 2 hours on a dev machine.The integration server polls the SVN repository every 2 hours for new check-ins and starts a make clean.</p>
<p>That way, we can monitor exactly when the build was broken and fix it right away.
We use <a href="http://hudson-ci.org/" rel="nofollow noreferrer">Hudson</a> as our continuous integration server, its free and open source, its a work of art and very easy to set up. Plus the User Interface is very intuitive, all the other developers love it.</p>
<p>Cheers,</p>
| 29,715
|
<p>Code I have:</p>
<pre><code>cell_val = CStr(Nz(fld.value, ""))
Dim iter As Long
For iter = 0 To Len(cell_val) - 1 Step 1
If Asc(Mid(cell_val, iter, 1)) > 127 Then
addlog "Export contains ascii character > 127"
End If
Next iter
</code></pre>
<p>This code doesn't work. Anyone know how to do this? I've simply got no idea with VB or VBA.</p>
|
<p>I believe your problem is that in VBA string indexes start at 1 and not at 0. Try the following:</p>
<pre><code>For iter = 1 To Len(cell_val)
If Asc(Mid(cell_val, iter, 1)) > 127 Then
addlog "Export contains ascii character > 127"
End If
Next
</code></pre>
|
<p>Did you debug it? ;) Are you sure the cell_val is not empty? Also you don't need the 'Step 1' in the For loop since it's default. Also what do you expect to acomplish with your code? It logs if any ascii values are above 127? But that's it - there is no branching depending on the result?</p>
| 10,590
|
<p>I need to sum points on each level earned by a tree of users. Level 1 is the sum of users' points of the users 1 level below the user. Level 2 is the Level 1 points of the users 2 levels below the user, etc...</p>
<p>The calculation happens once a month on a non production server, no worries about performance.</p>
<p>What would the SQL look like to do it?</p>
<p>If you're confused, don't worry, I am as well!</p>
<p>User table:</p>
<pre><code>ID ParentID Points
1 0 230
2 1 150
3 0 80
4 1 110
5 4 54
6 4 342
Tree:
0
|---\
1 3
| \
2 4---
\ \
5 6
</code></pre>
<p>Output should be:</p>
<pre><code>ID Points Level1 Level2
1 230 150+110 150+110+54+342
2 150
3 80
4 110 54+342
5 54
6 342
</code></pre>
<p>SQL Server Syntax and functions preferably...</p>
|
<p>If you were using Oracle DBMS that would be pretty straightforward since Oracle supports tree queries with the <strong>CONNECT BY/STARTS WITH</strong> syntax. For SQL Server I think you might find <a href="http://searchwindevelopment.techtarget.com/tip/0,289483,sid8_gci1277481,00.html" rel="nofollow noreferrer">Common Table Expressions</a> useful</p>
|
<p>You have a couple of options:</p>
<ol>
<li>Use a cursor and a recursive user-defined function call (it's quite slow)</li>
<li>Create a cache table, update it on INSERT using a trigger (it's the fastest solution but could be problematic if you have lots of updates to the main table)</li>
<li>Do a client-side recursive calculation (preferable if you don't have too many records)</li>
</ol>
| 11,678
|
<p>What's the best way to unify several overlapping id systems into a unified one while maintaining the old id system.</p>
<p>I have several different ids on my website... (E.g /publisher/1234 and /designer/1234) I would like to unify the ids into a new system, but want to preserve the functionality of the older system.</p>
|
<p>You can try using <a href="http://msdn.microsoft.com/en-us/library/aa387764.aspx" rel="noreferrer">Microsoft's Sign Tool</a></p>
<p>You download it as part of the Windows SDK for Windows Server 2008 and .NET 3.5. Once downloaded you can use it from the command line like so:</p>
<blockquote>
<p>signtool sign /a MyFile.exe</p>
</blockquote>
<p>This signs a single executable, using the "best certificate" available. (If you have no certificate, it will show a SignTool error message.)</p>
<p>Or you can try:</p>
<blockquote>
<p>signtool signwizard</p>
</blockquote>
<p>This will launch a wizard that will walk you through signing your application. (This option is not available after Windows SDK 7.0.)</p>
<hr>
<p>If you'd like to get a hold of certificate that you can use to test your process of signing the executable you can use the .NET tool <em>Makecert</em>.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/bfsktky3(v=vs.80).aspx" rel="noreferrer">Certificate Creation Tool (Makecert.exe)</a></p>
<p>Once you've created your own certificate and have used it to sign your executable, you'll need to manually add it as a Trusted Root CA for your machine in order for <a href="http://en.wikipedia.org/wiki/User_Account_Control" rel="noreferrer">UAC</a> to tell the user running it that it's from a trusted source. <strong>Important</strong>. <em><a href="http://www.computerworld.com/article/3008113/security/dell-installs-self-signed-root-certificate-on-laptops-endangers-users-privacy.html" rel="noreferrer">Installing a certificate as ROOT CA will endanger your users privacy. Look what happened with DELL.</a></em> You can find more information for accomplishing this both in code and through Windows in:</p>
<ul>
<li><p>Stack Overflow question <em><a href="https://stackoverflow.com/questions/308554">Install certificates in to the Windows Local user certificate store in C#</a></em></p></li>
<li><p><a href="http://blogs.technet.com/b/sbs/archive/2007/04/10/installing-a-self-signed-certificate-as-a-trusted-root-ca-in-windows-vista.aspx" rel="noreferrer">Installing a Self-Signed Certificate as a Trusted Root CA in Windows Vista</a></p></li>
</ul>
<p>Hopefully that provides some more information for anyone attempting to do this!</p>
|
<p>And yet another option, if you're developing on Windows 10 but don't have Microsoft's signtool.exe installed, you can use Bash on Ubuntu on Windows to sign your app. Here is a run down:</p>
<p><a href="https://blog.synapp.nz/2017/06/16/code-signing-a-windows-application-on-linux-on-windows/" rel="noreferrer">https://blog.synapp.nz/2017/06/16/code-signing-a-windows-application-on-linux-on-windows/</a></p>
| 31,425
|
<p>I'm looking for a small C library to handle utf8 strings.</p>
<p>Specifically, splitting based on unicode delimiters for use with stemming algorithms.</p>
<p>Related posts have suggested:</p>
<p>ICU <a href="http://www.icu-project.org/" rel="noreferrer">http://www.icu-project.org/</a> (I found it too bulky for my purposes on embedded devices)</p>
<p>UTF8-CPP: <a href="http://utfcpp.sourceforge.net/" rel="noreferrer">http://utfcpp.sourceforge.net/</a> (Excellent, but C++ not C)</p>
<p>Has anyone found any platform independent, small codebase libraries for handling unicode strings (doesn't need to do naturalisation).</p>
|
<p>A nice, light, library which I use successfully is <a href="https://github.com/JuliaLang/utf8proc" rel="noreferrer">utf8proc</a>.</p>
|
<p>UTF-8 is specially designed so that many byte-oriented string functions continue to work or only need minor modifications.</p>
<p>C's <strong><code>strstr</code></strong> function, for instance, will work perfectly as long as both its inputs are valid, null-terminated UTF-8 strings. <strong><code>strcpy</code></strong> works fine as long as its input string starts at a character boundary (for instance the return value of <strong><code>strstr</code></strong>).</p>
<p>So you may not even need a separate library!</p>
| 40,426
|
<p>I have been trying to make a case for using Python at my work. We use C# and ASP.NET for basically all of our development. 80% or more of our projects are web applications. It seems natural that we would look at some of the nice dynamic web languages (Ruby, Python, etc), and with things like <a href="http://en.wikipedia.org/wiki/Ironruby" rel="noreferrer">IronRuby</a> and <a href="http://en.wikipedia.org/wiki/Ironpython" rel="noreferrer">IronPython</a>, I started seriously investigating.</p>
<p>I love Python. It's a beautiful, expressive language. It's a joy to code in, for sure. The multitude of python modules and frameworks make it very appealing. Problem is, I cannot think of any specific problems, any specific hurdles that would <b>require</b> a language like Python. ASP.NET gives us RAD, it gives us a full-featured framework and all that good stuff. Also, we all already know C# and have lots of projects in C#, learning a new language just <i>because</i> doesn't quite work. </p>
<p>Can you guys help me think of something to finally convince my boss to really learn Python and start using it on projects?</p>
<p>Edit: I know that no problem requires only one language, I just meant, are there any specific problems in which dynamic languages excel over static languages.</p>
<p>Edit again: Let me also mention that my boss prompted ME to investigate this. He has put aside hours to research these languages, find a good one, learn it, and then figure out how we can use it. I'm at the last step here, I do not need a lecture on why I should consider my motivation for changing something my company does because they do it for a reason. </p>
|
<p>"Can you guys help me think of something to finally convince my boss to really learn Python and start using it on projects?"</p>
<p>Nope.</p>
<p>Nothing succeeds like success. Use Python. Be successful. Make people jealous.</p>
<p>When asked why you're successful, you can talk about Python. Not before.</p>
<p>Choose projects wisely: things where a dynamic language has significant advantages. Things where the requirements are <strong>not</strong> nailed down in detail. Things like data transformations, log-file scraping, and super-sophisticated replacements for BAT files.</p>
<p>Use Python to get started doing something useful while everyone else is standing around trying to get enough business and domain information to launch a project to develop a complicated MVC design.</p>
<hr />
<p>Edit: Some Python to the Rescue stories.</p>
<ul>
<li><a href="http://www.itmaybeahack.com/homepage/iblog/C551260341/E20081005191603.html" rel="nofollow noreferrer">Exploratory Programming</a></li>
<li><a href="http://www.itmaybeahack.com/homepage/iblog/C20071019092637/E20080830091128.html" rel="nofollow noreferrer">Tooling to build test cases</a></li>
<li><a href="http://www.itmaybeahack.com/homepage/iblog/C465799452/E20080712112540.html" rel="nofollow noreferrer">What's Central Here?</a></li>
<li><a href="http://www.itmaybeahack.com/homepage/iblog/C588245363/E20060206184914.html" rel="nofollow noreferrer">Control-Break Reporting</a></li>
<li><a href="http://www.itmaybeahack.com/homepage/iblog/C588245363/E20051022112554.html" rel="nofollow noreferrer">One More Cool Thing About Python Is...</a></li>
<li><a href="http://www.itmaybeahack.com/homepage/iblog/C465799452/E20080603055001.html" rel="nofollow noreferrer">In Praise of Serialization</a></li>
</ul>
<p>And that's just me.</p>
<hr />
<p>Edit: "boss prompted ME to investigate", "figure out how we can use it" changes everything.</p>
<p>The "finally convince my boss to really learn Python" is misleading. You aren't swimming upstream. See <a href="https://stackoverflow.com/questions/202337/how-do-i-make-the-business-case-for-python">How Do I Make the Business Case for Python</a> for the "convince my boss" problem. The edit says you're past this phase.</p>
<p>Dynamic languages offer flexibility. Exploit that. My two sets of examples above are two areas where flexibility matters.</p>
<ul>
<li><p>Requirements aren't totally nailed down. With a dynamic language, you can get started. Rework won't be a deal-breaker. With Java (and C++ and C#) you are reluctant to tackle devastating design changes because it's hard to break everything and get it to compile and work again. In Python, devastating changes aren't as expensive.</p>
</li>
<li><p>Design is in flux because you can't pick components. You can write Wrappers and Facades very easily in Python. It's a scripting language. And, Python modules compose into larger aggregates very simply.</p>
</li>
<li><p>Coding is in flux because requirements and design keep changing. It's scripted -- not compiled. You just make a change to the code and you're off and running. Testing is easier because the work cycle is shorter. It isn't code-compile-build-test it's code-test.</p>
</li>
<li><p>Testing is in flux because the requirements keep changing. Same as above. The work cycle is shorter and faster.</p>
</li>
</ul>
|
<p>I am pretty sure (100%) that you don't need to use Python for MS Windows at least.</p>
<p>In cases of other platforms you can use any language you like.</p>
| 30,958
|
<p>Been having a "heated debate" with a colleague about his practice of wrapping most of his functions in a try/catch but the catch has JUST a "throw" in it e.g.</p>
<pre><code>Private sub foo()
try
'Do something'
catch
throw 'And nothing else!'
End Try
End Sub
</code></pre>
<p>My thought was to not even bother (assuming you don't need to do anything at this point) - the exception would bubble to the next exception handler in a parent member.</p>
<p>The only argument that sounded plausible was that sometimes exceptions weren't caught and your code stopped (in debug mode) with the current line highlighted in green...and that this may be something to do with multiple threads?
Best practice does state "an exception handler for each thread" but mostly we work single-threaded.</p>
<p>The good thing may be it could be useful in debug mode to not suddenly pop out to a parent member (yes, Joel!) - you'd move to the "throw" statement and be able to examine your locals.
But then your code would be "littered with try/catch/throws" (to quote another thread here)?</p>
<p>And what sort of overhead would be involved in adding try/catch/throws everywhere if no exception occurs (i.e. should you avoid try/catches in tight loops)?</p>
|
<p>The reason you have a lone throw inside a catch rather than throwing a new exception is because this causes the original stack trace/exception data to be preserved. And one reason you might do this is because you can now set a break-point there for debugging.</p>
|
<p>Since there is zero error handling, this catch is useless. If there was logging or some cleanup done sure, but in this situation I'd get rid of the try/catch.</p>
| 26,921
|
<p>Taking over some code from my predecessor and I found a query that uses the Like operator:</p>
<pre><code>SELECT * FROM suppliers
WHERE supplier_name like '%'+name+%';
</code></pre>
<p>Trying to avoid SQL Injection problem and parameterize this but I am not quite sure how this would be accomplished. Any suggestions ?</p>
<p>note, I need a solution for classic ADO.NET - I don't really have the go-ahead to switch this code over to something like LINQ.</p>
|
<p>try this: </p>
<pre><code>var query = "select * from foo where name like @searchterm";
using (var command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("@searchterm", String.Format("%{0}%", searchTerm));
var result = command.ExecuteReader();
}
</code></pre>
<p>the framework will automatically deal with the quoting issues.</p>
|
<p>Short Anwser:</p>
<p>1) name.Replace("'", "''").... Replace any escape characters that your database may have (single quotes being the most common)</p>
<p>2) if you are using a language like .net use Parameterized Queries</p>
<pre><code>sql="Insert into Employees (Firstname, Lastname, City, State, Zip, Phone, Email) Values ('" & frmFirstname.text & "', '" & frmLastName & "', '" & frmCity & "', '" & frmState & "', '" & frmZip & "', '" & frmPhone & "', '" & frmEmail & "')"
</code></pre>
<p>The above gets replaced with the below</p>
<pre><code>Dim MySQL as string = "Insert into NewEmp (fname, LName, Address, City, State, Postalcode, Phone, Email) Values (@Firstname, @LastName, @Address, @City, @State, @Postalcode, @Phone, @Email)"
With cmd.Parameters:
.Add(New SQLParameter("@Firstname", frmFname.text))
.Add(New SQLParameter("@LastName", frmLname.text))
.Add(New SQLParameter("@Address", frmAddress.text))
.Add(New SQLParameter("@City", frmCity.text))
.Add(New SQLParameter("@state", frmState.text))
.Add(New SQLParameter("@Postalcode", frmPostalCode.Text))
.Add(New SQLParameter("@Phone", frmPhone.text))
.Add(New SQLParameter("@email", frmemail.text))
end with
</code></pre>
<p>3) user Stored procs</p>
<p>4) use Linq to SQL, again if you are using .net</p>
| 28,271
|
<p>I have two arrays. One contains <code>id=>count</code> and the other contains <code>id=>name</code>. I'm trying to produce a single array that is <code>name=>count</code>. Any suggestions on a straightforward way to do this?</p>
<p>I have looked at the <a href="http://us2.php.net/manual/en/ref.array.php" rel="nofollow noreferrer">Array Functions in the PHP Manual</a> and didn't see anything that stood out as doing what I want, so I'm guessing I'll need a combination of functions, but I'm having trouble coming up with something that's not convoluted.</p>
|
<p>Something like:</p>
<pre><code>foreach($countA as $id => $count)
{
$newArray[$nameA[$id]] = $count;
}
</code></pre>
<p>This does assume that the keys are in correspondence between the two arrays, since your requirements are ambiguous otherwise.</p>
|
<p>Use <a href="http://ca.php.net/manual/en/function.array-combine.php" rel="nofollow noreferrer">array_combine</a>...</p>
<pre><code>$countArray = array(0 => 1, 1 => 5);
$namesArray = array(0 => "Bob", 1 => "Alice");
$assocArray = array_combine($namesArray, $countArray);
</code></pre>
<p><strong>Edit:</strong> Here is a revised solution for the new requirements expressed in comment #2</p>
<pre><code>$assocArray = array();
foreach($namesArray as $id => $name) {
$assocArray[$name] = (array_key_exists($id, $countArray)) ? $countArray[$id] : 0;
}
</code></pre>
| 22,711
|
<p>I'm running a Django site using the fastcgi interface to nginx. However, some pages are being served truncated (i.e. the page source just stops, sometimes in the middle of a tag). How do I fix this (let me know what extra information is needed, and I'll post it)</p>
<p>Details:</p>
<p>I'm using flup, and spawning the fastcgi server with the following command:</p>
<pre><code>python ./manage.py runfcgi umask=000 maxchildren=5 maxspare=1 minspare=0 method=prefork socket=/path/to/runfiles/django.sock pidfile=/path/to/runfiles/django.pid
</code></pre>
<p>The nginx config is as follows:</p>
<pre><code># search and replace this: {project_location}
pid /path/to/runfiles/nginx.pid;
worker_processes 2;
error_log /path/to/runfiles/error_log;
events {
worker_connections 1024;
use epoll;
}
http {
# default nginx location
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main
'$remote_addr - $remote_user [$time_local] '
'"$request" $status $bytes_sent '
'"$http_referer" "$http_user_agent" '
'"$gzip_ratio"';
client_header_timeout 3m;
client_body_timeout 3m;
send_timeout 3m;
connection_pool_size 256;
client_header_buffer_size 1k;
large_client_header_buffers 4 2k;
request_pool_size 4k;
output_buffers 4 32k;
postpone_output 1460;
sendfile on;
tcp_nopush on;
keepalive_timeout 75 20;
tcp_nodelay on;
client_max_body_size 10m;
client_body_buffer_size 256k;
proxy_connect_timeout 90;
proxy_send_timeout 90;
proxy_read_timeout 90;
client_body_temp_path /path/to/runfiles/client_body_temp;
proxy_temp_path /path/to/runfiles/proxy_temp;
fastcgi_temp_path /path/to/runfiles/fastcgi_temp;
gzip on;
gzip_min_length 1100;
gzip_buffers 4 32k;
gzip_types text/plain text/html application/x-javascript text/xml text/css;
ignore_invalid_headers on;
server {
listen 80;
server_name alpha2.sonyalabs.com;
index index.html;
root /path/to/django-root/static;
# static resources
location ~* ^/static/.*$
{
root /path/to/django-root;
expires 30d;
break;
}
location / {
# host and port to fastcgi server
fastcgi_pass unix:/path/to/runfiles/django.sock;
fastcgi_param PATH_INFO $fastcgi_script_name;
fastcgi_param REQUEST_METHOD $request_method;
fastcgi_param QUERY_STRING $query_string;
fastcgi_param CONTENT_TYPE $content_type;
fastcgi_param CONTENT_LENGTH $content_length;
fastcgi_pass_header Authorization;
fastcgi_intercept_errors off;
}
location /403.html {
root /usr/local/nginx;
access_log off;
}
location /401.html {
root /usr/local/nginx;
access_log off;
}
location /404.html {
root /usr/local/nginx;
access_log off;
}
location = /_.gif {
empty_gif;
access_log off;
}
access_log /path/to/runfiles/localhost.access_log main;
error_log /path/to/runfiles/localhost.error_log;
}
}
</code></pre>
|
<p>Check your error logs for "Permission denied" errors writing to <code>.../nginx/tmp/...</code> files. Nginx will work fine unless it needs temporary space, and that typically happens at 32K boundaries. If you find these errors, make sure the tmp directory is writable by the user nginx runs as.</p>
|
<p>I'm running very similar configurations to this both on my webhost (Webfaction) and on a local Ubuntu dev server and I don't see any problems. I'm guessing it's a time-out or full buffer that's causing this.</p>
<p>Can you post the output of the nginx error log? Also what version of nginx are you using?</p>
<p>As a side note it may be worth looking at <a href="http://code.google.com/p/django-logging/wiki/Overview" rel="nofollow noreferrer">django-logging</a> to find out what your fastcgi process is doing.</p>
| 19,298
|
<p>When I try the following lookup in my code:</p>
<pre><code>Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
return (DataSource) envCtx.lookup("jdbc/mydb");
</code></pre>
<p>I get the following exception:</p>
<pre><code>java.sql.SQLException: QueryResults: Unable to initialize naming context:
Name java:comp is not bound in this Context at
com.onsitemanager.database.ThreadLocalConnection.getConnection
(ThreadLocalConnection.java:130) at
...
</code></pre>
<p>I installed embedded JBoss following the JBoss <a href="http://wiki.jboss.org/wiki/Tomcat5.5.x?action=e&windowstate=normal&mode=view" rel="nofollow noreferrer">wiki instructions</a>. And I configured Tomcat using the "Scanning every WAR by default" deployment as specified in the <a href="http://wiki.jboss.org/wiki/EmbeddedAndTomcat" rel="nofollow noreferrer">configuration wiki page</a>.</p>
<p>Quoting the config page:</p>
<blockquote>
<p>JNDI</p>
<p>Embedded JBoss components like connection pooling, EJB, JPA, and transactions make
extensive use of JNDI to publish services. Embedded JBoss overrides Tomcat's JNDI
implementation by layering itself on top of Tomcat's JNDI instantiation. There are a few > reasons for this:</p>
<ol>
<li>To avoid having to declare each and every one of these services within server.xml</li>
<li>To allow seemeless integration of the java:comp namespace between web apps and
EJBs.</li>
<li>Tomcat's JNDI implementation has a few critical bugs in it that hamper some JBoss
components ability to work</li>
<li>We want to provide the option for you of remoting EJBs and other services that can > be remotely looked up</li>
</ol>
</blockquote>
<p>Anyone have any thoughts on how I can configure the JBoss naming service which according to the above quote is overriding Tomcat's JNDI implementation so that I can do a lookup on java:comp/env? </p>
<p>FYI - My environment Tomcat 5.5.9, Seam 2.0.2sp, Embedded JBoss (Beta 3), </p>
<p>Note: I do have a -ds.xml file for my database connection properly setup and accessible on the class path per the instructions.</p>
<p>Also note: I have posted this question in embedded Jboss forum and seam user forum. </p>
|
<p>Thanks for the response toolkit.... yes, I can access my datasource by going directly to java:jdbc/mydb, but I'm using an existing code base that connects via the ENC. Here's some interesting info that I've found out ....</p>
<ol>
<li><p>The above code works with <strong>JBoss 4.2.2.GA</strong> and here's the JNDI ctx parameters being used:<br/>
java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces:
org.jboss.naming:org.jnp.interfaces</p></li>
<li><p>The above code works with <strong>Tomcat 5.5.x</strong> and here's the JNDI ctx parameters being used:<br/>
java.naming.factory.initial=org.apache.naming.java.javaURLContextFactory
java.naming.factory.url.pkgs=org.apache.naming</p></li>
<li><p>The above code fails with <strong>Embedded JBoss (Beta 3)</strong> in Tomcat 5.5.x with the above error message. <br/>
java.naming.factory.initial=org.apache.naming.java.javaURLContextFactory
java.naming.factory.url.pkgs=org.apache.namingThe above code fails with the above error using JBoss Embedded in tomcat 5.5.x</p></li>
</ol>
<p>Anyone have any thoughts I what I need to do with configuring embedded JBoss JNDI configuration?</p>
|
<p>java:comp/env is known as the Enterprise Naming Context (ENC) and is not globally visible. See <a href="http://www.informit.com/articles/article.aspx?p=384904" rel="nofollow noreferrer">here</a> for more information. You will need to locate the global JNDI name which your datasource is regsitered at.</p>
<p>The easiest way to do this is to navigate to JBoss' web-based JMX console and look for a 'JNDIView' (not exactly sure of the name - currently at home) mbean. This mbean should have a list method which you can invoke, which will display the context path for all of the JNDI-bound objects.</p>
| 14,925
|
<p>There was no endpoint listening at http;//localhost:8080/xdxservice/xdsrepository that could accept the message. This is often caused by an incorrect address or SOAP action. </p>
|
<p>Probably a typo in the question, but your URL is invalid. </p>
<pre><code>http;//localhost:8080/xdxservice/xdsrepository
</code></pre>
<p>should have a colon rather than a semi-colon</p>
<pre><code>http://localhost:8080/xdxservice/xdsrepository
</code></pre>
<p>This may well not be your problem, but I thought it was worth pointing out.</p>
|
<p>the url should have a .svc extention, no? (answered in comments)</p>
<p>Are you running the WCF in ASP.NET or the VS webserver?</p>
| 30,606
|
<p>When a process in jBPM forks into concurrent paths, each of these paths gets their own copy of the process variables, so that they run isolated from each other.</p>
<p>But what happens when the paths join again ?
Obviously there could be conflicting updates.
Does the context revert back to the state before the fork?
Can I choose to copy individual variables from the separate tracks?</p>
|
<p>I think that you have to configure the Task Controllers of your tasks. In some cases it is enough to set the <code>access</code> attribute in a way that does not result in conflicts (e.g. <code>read</code> access to the first path and <code>read,write</code> access to the second path). If this is not the case then you can implement your own <code>TaskControllerHandler</code> and implement the method <code>void submitTaskVariables(TaskInstance taskInstance, ContextInstance contextInstance, Token token)</code> with your custom logic. Please see: <a href="http://docs.jboss.com/jbpm/v3.2/userguide/html/taskmanagement.html#taskcontrollers" rel="nofollow noreferrer">Task Controllers</a>.</p>
|
<p>I tried a little experiment:</p>
<pre><code><fork name="fork1" >
<transition to="right" />
<transition to="left" />
</fork>
<node name="left">
<event type="node-enter">
<script>
<expression >
left="left";
shared = left;
</expression>
<variable name='left' access='write' />
<variable name='shared' access='write' />
</script>
</event>
<transition to="join" />
</node>
<node name="right">
<event type="node-enter">
<script>
<expression >
right="right";
token.parent.processInstance.contextInstance.setVariable("fromRight", "woot!");
shared = right;
</expression>
<variable name='right' access='write' />
<variable name='shared' access='write' />
</script>
</event>
<transition to="join" />
</node>
<join name="join" >
<transition to="done"></transition>
</join>
<end-state name="done"/>
</code></pre>
<p>At the end I had access to three variables, shared, right and "fromRight" which was set by the script against the parent explicitly.</p>
<p>The shared variable took its value from the right fork, changes made on the left seemed to dissappear.</p>
<p>Note that the transitions aren't actually asynchronous for me, and the whole experiment will have run in one transaction, these factors may affect the outcome</p>
| 13,873
|
<p>This question is the other side of the question asking, "<a href="https://stackoverflow.com/questions/11/how-do-i-calculate-relative-time">How do I calculate relative time?</a>".</p>
<p>Given some human input for a relative time, how can you parse it? By default you would offset from <code>DateTime.Now()</code>, but could optionally offset from another <code>DateTime</code>.</p>
<p>(Prefer answers in C#)</p>
<p>Example input:</p>
<ul>
<li>"in 20 minutes"</li>
<li>"5 hours ago"</li>
<li>"3h 2m"</li>
<li>"next week"</li>
</ul>
<p><strong>Edit:</strong> Let's suppose we can define some limits on the input. This sort of code would be a useful thing to have out on the web.</p>
|
<p>That's building a DSL (Domain specific language) for date handling. I don't know if somebody has done one for .NET but the construction of a DSL is fairly straightforward:</p>
<ol>
<li>Define the language precisely, which input forms you will accept and what will you do with ambiguities</li>
<li>Construct the grammar for the language</li>
<li>Build the finite state machine that parses your language into an actionable AST</li>
</ol>
<p>You can do all that by yourself (with the help of <a href="http://en.wikipedia.org/wiki/Compilers:_Principles,_Techniques,_and_Tools" rel="nofollow noreferrer">the Dragon Book</a>, for instance) or with the help of tools to the effect, as shown in this <a href="http://www.codeproject.com/KB/recipes/YourFirstDSL.aspx" rel="nofollow noreferrer">link</a>.</p>
<p>Just by thinking hard about the possibilities you have a good chance, with the help of good UI examples, of covering more than half of the actual inputs your application will receive. If you aim to accept everything a human could possibly type, you can record the input determined as ambiguous and then add them to the grammar, whenever they can be interpreted, as there are things that will be inherently ambiguous.</p>
|
<p>This: <a href="http://www.codeproject.com/KB/edit/dateparser.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/edit/dateparser.aspx</a>
Is fairly close to what you are trying to accomplish. Not the most elegant solution, but certainly might save you some work.</p>
| 7,919
|
<p>Many websites, including this one, add what are apparently called <em>slugs</em> - descriptive but as far as I can tell useless bits of text - to the end of URLs.</p>
<p>For example, the URL the site gives for this question is:</p>
<p><a href="https://stackoverflow.com/questions/47427/why-do-some-websites-add-slugs-to-the-end-of-urls"><code>https://stackoverflow.com/questions/47427/why-do-some-websites-add-slugs-to-the-end-of-urls</code></a></p>
<p>But the following URL works just as well:</p>
<p><a href="https://stackoverflow.com/questions/47427/"><code>https://stackoverflow.com/questions/47427/</code></a></p>
<p>Is the point of this text just to somehow make the URL more user friendly or are there some other benefits? </p>
|
<p>The slugs make the URL more user-friendly and you know what to expect when you click a link. Search engines such as Google, rank the pages higher if the searchword is in the URL.</p>
|
<p>Ideally, the "slug" should be the only identifier needed. In practice, on dynamic sites such as this, you either have to have a unique numerical identifier or start appending/incrementing numbers to the "slug" like Digg does.</p>
| 6,966
|
<p>I am considering writing two limited precision alternatives to BigDecimal, namely DecimalInt and DecimalLong. These would be capable of dealing with numbers within the real bounds of int and long with an arbitrary number of decimal places, creatable in both mutable and immutable form. My plan is to make DecimalInt support +/-999,999,999 to +/- 0.999999999 and DecimalLong the same, but with up to 18 digits.</p>
<p>This would be done by maintaining a decimal digit count value of 0-9 for DecimalInt and 0-18 for DecimalLong along side the actual value stored as a scaled int or long. The normal use would be for small numbers of decimals such as for money and stock prices, typically 2-4 decimal places.</p>
<p>The essential requirements are (a) lean footprint (2 classes, plus OverflowException), and (b) full support of all basic operations plus all of Math that makes sense.</p>
<p>Googling for results did not return any obvious hits - they all seemed to pertain to arbitrary decimals.</p>
<p>My questions are: Has this already been done? Are there hidden subtleties in this which is why it has not already been done? Has anyone heard rumors of Java supporting a decimal type like DotNet's.</p>
<p>EDIT: This is different from BigDecimal because it should be (a) a hell of a lot more efficient to not deal with an array of ints, and (b) it won't wrap BigInteger so it will be leaner on memory too, and (c) it will have a mutable option so it will be faster there as well. In summary - less overhead for the simple use cases like "I want to store a bank balance without the overhead of BigDecimal and the inaccuracy of double".</p>
<p>EDIT: I intend on doing all the math using int or long to avoid the classic problem of: 1586.60-708.75=877.8499999999999 instead of 877.85</p>
|
<p>I strongly suspect the reason why this has not been done is that the overhead of BigDecimal and BigInteger is not as relevant as you think, and avoiding it not worth the effort and the risk of getting it wrong in some subtle way.</p>
<p>To use your example: for any financial application, saving a few dozen bytes is a non-issue and limited precision a deal-breaker (stock prices my have typically 2-4 digits in the USA, but if you want to deal with emerging markets, you'll encounter currencies with runaway inflation, where a 15-digit sum buys you half a loaf of bread).</p>
<p>Basically, it sounds like just another case of premature optimization.</p>
|
<p>If your focus is for portable devices look at <a href="http://real-java.sourceforge.net/Real.html" rel="nofollow noreferrer">Real</a>. Real allows for the <a href="http://real-java.sourceforge.net/javadoc/index.html" rel="nofollow noreferrer">precision</a> of the number to be set from 0 to 16. It is designed for MIDP cell phones. </p>
<p>Also of interest, look at the <a href="http://www.hpl.hp.com/personal/Hans_Boehm/new_crcalc/CRCalc.html" rel="nofollow noreferrer">constructive reals</a> library. It's not lightweight though.</p>
<p>In reference to the comment below, can you not use the <a href="http://commons.apache.org/math/userguide/fraction.html" rel="nofollow noreferrer">Apache Commons Math Library</a> to work with fractions? Is there some reason that won't work?</p>
| 46,117
|
<p>Trying to get this example working from <a href="http://www.munna.shatkotha.com/blog/post/2008/10/26/Light-box-effect-with-WPF.aspx" rel="nofollow noreferrer">http://www.munna.shatkotha.com/blog/post/2008/10/26/Light-box-effect-with-WPF.aspx</a></p>
<p>However, I can't seem to get the namespace or syntax right for "Process" below.</p>
<pre><code><Border x:Name="panelDialog" Visibility="Collapsed">
<Grid>
<Border Background="Black" Opacity="0.49"></Border>
<!--While Xmal Content of the dialog will go here-->
</Grid>
</Border>
</code></pre>
<p>The blog post goes on to say.....</p>
<p>Just put two function for hide and display the dialog. Total Code is given bellow. In bellow code I have Displayed a loading screen with light box effect. When displaying modal dialog just invoke show and hide wait screen methods. Its good to send your cpu expansive jobs to background thread and use dispatcher to update UI while you are in background thread.</p>
<pre><code><Page x:Class="Home">
<Grid>
<ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
<!--All the contents will go here-->
</ScrollViewer>
<Border x:Name="panelLoading" Visibility="Collapsed">
<Grid>
<Border Background="Black" Opacity="0.49"></Border>
<local:TMEWaitScreen></local:TMEWaitScreen>
</Grid>
</Border>
</Grid>
</Page>
</code></pre>
<p>Here is the codebehind</p>
<pre><code>#region About Wait Screen
/// <summary>
/// Show wait screen before a web request
/// </summary>
public void ShowWaitScreen()
{
Process del = new Process(ShowWaitScreenUI);
Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, del);
}
private void ShowWaitScreenUI()
{
panelLoading.Visibility = Visibility.Visible;
}
/// <summary>
/// Hide a wait screen after a web request
/// </summary>
public void HideWaitScreen()
{
Process del = new Process(HideWaitScreenUI);
Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, del);
}
private void HideWaitScreenUI()
{
panelLoading.Visibility = Visibility.Collapsed;
}
#endregion
</code></pre>
<p>I'm having issues with this lines specifically:</p>
<pre><code>Process del = new Process(ShowWaitScreenUI);
</code></pre>
<p>The only Process I can find is in System.Diagnostics, and takes no arguments. Is the blog post I'm trying to learn from off,or am I just in the wrong place?</p>
|
<p>Looks like the person who wrote the blog forgot to define their custom delegate called Process (a bit of an odd name for it).</p>
<pre><code>private delegate void Process();
</code></pre>
<p>It should compile now with it defined. </p>
<p>But I like these kind of names instead. </p>
<pre><code>private delegate void HideWaitScreenHandler();
private delegate void ShowWaitScreenHandler();
</code></pre>
<p>Actually you can refactor this to make more simple.</p>
<pre><code>private delegate void ShowWaitScreenUIHandler(bool show);
void ShowWaitScreenUIThreaded(bool show)
{
Process del = new ShowWaitScreenHandler(OnShowWaitScreenUI);
Dispatcher.Invoke(DispatcherPriority.Normal, del, show);
}
void OnShowWaitScreenUI(bool show)
{
panelLoading.Visibility = show ? Visibility.Visible : Visibility.Collapsed;
}
</code></pre>
|
<p>Looks like the person who wrote the blog forgot to define their custom delegate called Process (a bit of an odd name for it).</p>
<pre><code>private delegate void Process();
</code></pre>
<p>It should compile now with it defined. </p>
<p>But I like these kind of names instead. </p>
<pre><code>private delegate void HideWaitScreenHandler();
private delegate void ShowWaitScreenHandler();
</code></pre>
<p>Actually you can refactor this to make more simple.</p>
<pre><code>private delegate void ShowWaitScreenUIHandler(bool show);
void ShowWaitScreenUIThreaded(bool show)
{
Process del = new ShowWaitScreenHandler(OnShowWaitScreenUI);
Dispatcher.Invoke(DispatcherPriority.Normal, del, show);
}
void OnShowWaitScreenUI(bool show)
{
panelLoading.Visibility = show ? Visibility.Visible : Visibility.Collapsed;
}
</code></pre>
| 44,813
|
<p>An idiom commonly used in OO languages like Python and Ruby is instantiating an object and chaining methods that return a reference to the object itself, such as:</p>
<pre><code>s = User.new.login.get_db_data.get_session_data
</code></pre>
<p>In PHP, it is possible to replicate this behavior like so:</p>
<pre><code>$u = new User();
$s = $u->login()->get_db_data()->get_session_data();
</code></pre>
<p>Attempting the following results in <code>syntax error, unexpected T_OBJECT_OPERATOR</code>:</p>
<pre><code>$s = new User()->login()->get_db_data()->get_session_data();
</code></pre>
<p>It seems like this could be accomplished using static methods, which is probably what I'll end up doing, but I wanted to check the lazyweb: <strong>Is there actually a clean, simple way to instantiate PHP classes "inline" (as shown in the above snippet)</strong> for this purpose?</p>
<p>If I do decide to use static methods, <strong>is it too sorcerous to have a class's static method return an instantiation of the class itself</strong>? (Effectively writing my own constructor-that-isn't-a-constructor?) It feels kind of dirty, but if there aren't too many scary side effects, I might just do it.</p>
<p>I guess I could also pre-instantiate a UserFactory with a get_user() method, but I'm curious about solutions to what I asked above.</p>
|
<p>All of these proposed solutions complicate your code in order to bend PHP to accomplish some syntactic nicety. Wanting PHP to be something it's not (like good) is the path to madness.</p>
<p>I would just use:</p>
<pre><code>$u = new User();
$s = $u->login()->get_db_data()->get_session_data();
</code></pre>
<p>It is clear, relatively concise and involves no <em>black magic</em> that can introduce errors.</p>
<p>And of course, you could always move to Ruby or Python. It will change your life. </p>
<ul>
<li>And yeah, I am harsh on PHP. I use it every day. Been using it for years. The reality is that it has <strong>accreted</strong>, rather than been designed and it shows. </li>
</ul>
|
<pre><code><?php
//PHP 5.4+ class member access on instantiation support.
$s = (new User())->login()->get_db_data()->get_session_data();
</code></pre>
| 23,053
|
<p>I flashed the TH3D unified firmware (R2.7) yesterday and so far everything works. I printed the 20 mm cube using the same G-code file I used for my very first print ever. However, with TH3D firmware I noticed that the print head was ridiculously fast compared to the previous firmware. The new cube has layer shifting and more noticeable ghosting so I know it's not just my imagination/faulty memory. </p>
<p>The slicer should have everything moving at 60 mm/s but I feel like the printer is going like 80+ mm/s. I only uncommented my printer model and a couple of features of the firmware; nothing involving speed (mainly the mesh bed leveling). Is it possible that the new firmware thinks 60 mm/s is a different speed than the original?</p>
<hr>
<p><sup>Note: This question isn't about print quality. While the cube had flaws, it was just testing that the printer would actually print. And, of course, I can just dial things down. This question's scope is just about the input of the G-code and the output of an actual speed of printer head facilitated by the firmware.</sup></p>
|
<p>I agree with @silver, but also wanted to point out that maybe the acceleration values on the old firmware you had were different from the default in TH3D R2.7.</p>
<p>The current settings can be retrieved using the M503 command, which should return the values from the eeprom:</p>
<pre><code>Maximum Acceleration (units/s2):
M201 X1000 Y1000 Z100 E10000
Acceleration (units/s2): P R T
M204 P400.00 R1000.00 T1000.00
</code></pre>
<p>You can then lookup the default settings for your printer model and use <a href="http://marlinfw.org/docs/gcode/M201.html" rel="nofollow noreferrer">M201</a> and <a href="http://marlinfw.org/docs/gcode/M204.html" rel="nofollow noreferrer">M204</a> to set the new values. Then M500 to save the new settings to the EEPROM.</p>
|
<p>Yes, the limits are often subject to some "interpretation" in the limiting algorithms, even if they are totally unchanged values. Eg, your speed may remain higher around corners if the momentum calculations were optimized to take into account print head weight and extrusion instead of only per axis speed curves.</p>
| 1,182
|
<p>I want to load the flex framework as an RSL (SWZ, using player caching) but I need to monkey patch a couple of bug fixes in the framework.</p>
<p>A number of forums suggest this is not possible. Has anyone gotten this to work?</p>
|
<p>Same thing as other answer to use frame1, but James Ward has some code to see: <a href="http://www.jamesward.com/blog/2009/03/10/flex-monkey-patching-and-framework-rsls/" rel="nofollow noreferrer">http://www.jamesward.com/blog/2009/03/10/flex-monkey-patching-and-framework-rsls/</a></p>
|
<p>One of the guys on my team tried this about a month ago and said he had no problems. If your monkey-patched classes are part of your application project then it should work, since they are compiled into the SWF and basically "override" what's in the framework. You are not changing the Flex framework RSL, so it should still load and be cached fine. There isn't much published by Adobe to explain this but that's how I've understood it to work.</p>
| 26,312
|
<p>In MonoRail you can just CancelLayout() to not render the layout. In ASP.NET MVC, the only way to affect the layout seems to be to pass the layout name into the View() method like View("myview", "mylayout"); only it seems that passing null or an empty string doesn't do what I'd want. </p>
<p>I ended up creating an empty layout that just rendered the content, but that seems silly.</p>
<p>"Not Render the layout" means exactly that. In the web forms view engine they call layouts "master pages". I want to render <em>just</em> my action's view and not surround it with the master page.</p>
|
<p>In MVC 3, you can remove the master layout code with:</p>
<pre><code> @{
Layout = "";
}
</code></pre>
|
<p>You can create a custom ActionResult that does pretty much anything. The ActionResult controls what is sent back to the client as the response. It would be trivial to create a class that extends ActionResult that does nothing. </p>
| 27,131
|
<p>I use Virtual PC to create fresh environments for testing my installer. But I must be doing something wrong because a VPC image with Vista or XP inside is taking around 15GB of disk space (that includes VS2005/S2008 installed in them). </p>
<p>To create a new copy for testing I copy and paste the folder that has the .vhd, .vmc and .vsv files inside. After using the new VPC image for testing I then delete that copied folder. This works but it takes a looong time to copy 15GB each time. Is there some faster/more efficent approach?</p>
|
<p>Use <a href="http://www.petri.co.il/virtual_creating_differencing_disks_with.htm" rel="nofollow noreferrer">differencing/undo disks</a>. This means when you shut down your VPC you'll be asked if you want to save changes, simply answer no and you'll be back to where you started.</p>
|
<p>Also, you mentioned cut & paste, this is not the best way to be copying large amounts of data within windows. At least use xcopy, robocopy is even faster.</p>
| 10,761
|
<p>Is there a better <strong>free</strong> TreeView control that exists for Visual Studio 2008 / .NET 3.5?</p>
<p>I believe I need something a little more powerful than the out-of-the box version. I'm not exactly sure for what yet but I thought I'd ask quickly before I get too far in to my project.</p>
|
<p><a href="http://treeviewadv.sourceforge.net/" rel="noreferrer">TreeViewAdv</a> seems to be pretty nice. It is described with the following features on SourceForge.net:</p>
<ul>
<li>Extensible advanced TreeView.</li>
<li>100% management C# code.</li>
<li>Features: Model/View architecture.
<ul>
<li>Multicolumns.</li>
<li>Multiselection.</li>
<li>Different controls for each node: CheckBox, Icon, Label ...</li>
<li>Drag&Drop highlighting.</li>
<li>Load on demand.</li>
<li>Incremental search.</li>
</ul></li>
</ul>
<p>We will most likely use this in one or two occasions in an upcoming project, IIRC.</p>
<p>HTH</p>
|
<p>I would be wary with what you are going to use for a tree view control, make sure to test the amount of memory they consume vs speed of drawing.</p>
<p>We are having problems at work with the treeview control (made by Crownwood Software, called DotNetMagic) as it is causing memory leaks a lot, although its speed of drawing is <em>very</em> quick.</p>
<p>Most component vendors supply trials, so make good use of those! here are some to help you on your way:</p>
<p><a href="http://www.componentone.com/SuperProducts/StudioWinForms/" rel="nofollow noreferrer">C1 Controls</a><br>
<a href="http://www.dotnetmagic.com/features_treeControl.html" rel="nofollow noreferrer">DotNetMagic</a> (but beware of the memory in this one, check for yourself, it still might be suitable)</p>
<p><strong>Edit:</strong> Sorry, missed the free bit, sorry</p>
| 36,799
|
<p>Recently I have been getting some layer shifting starting at layer one. I have had layer shifting at higher layers due to various reasons but mainly for the belts being too loose. But now I am reading that layer shifting can also be caused by belts being too tight.</p>
<p>The <a href="https://reprap.org/wiki/Shifted_layers" rel="nofollow noreferrer">RepRap wiki</a> page for layer shifting simply gives the mechanical reason for this as "binding". Can anyone explain what binding means? I thought it meant that the rails were crashing into something but apparently it doesn't. Then I thought it meant that the X and Y axes weren't perfectly perpendicular. </p>
<p>Does it mean that the "teeth" of the belts stay "stuck" to the gear for too long when moving in one direction? Why would this happen in one direction and not the other? Because the pulleys/gears are at different heights? Or just because of the belts being tighter? Or one of these reasons?</p>
<p>Just trying to understand what its happening so I can debug it for my particular 3D printer. </p>
|
<p>I think the RepRap wiki is using the word "binding", which translates to <em>"stick together or cause to stick together in a single mass"</em> (from Google dictionary), to indicate that some sort of friction is experienced (as you experience when things are sticking together).</p>
<p>When there is too much tension in the belt, pulleys and bearings experience a larger radial force stressing the balls of the bearings and pulley shafts. This causes extra friction for the stepper motor to overcome (as the friction force, tangential, is related to the radial force); this means that the stepper has to work harder and can skip steps (for more insight please read below).</p>
<hr>
<p>While ball bearings are used to <em>reduce</em> friction (opposed to a bush bearing), each ball has a little friction from a couple of sources according to <a href="https://www.amroll.com/friction-frequency-factors.html" rel="nofollow noreferrer">this reference</a>:</p>
<blockquote>
<p>The sources of this friction are: slight deformation of the rolling elements and raceways under load, sliding friction of the rolling elements against the cage and guiding surfaces. </p>
</blockquote>
<p>These effects are generally captured in a single friction coefficient called "μ". The relation between friction force (tangential) and bearing loading (radial) is written by <span class="math-container">$$P_{friction}=P_{load} \times \mu$$</span> so the higher the belt tension (<span class="math-container">$P_{load}$</span>), the higher the frictional force (<span class="math-container">$P_{friction}$</span>), the harder the stepper has to work.</p>
|
<p>It is the bearings that are binding (dragging), due to lateral forces caused by over-tight belts. It may be the bearings in the stepper motors that are binding, but it is more likely to be the bearings in the idler pulleys.</p>
| 1,423
|
<p><img src="https://i.stack.imgur.com/xE1dA.gif" alt="enter image description here"></p>
<p>This is what is happening to my motor. Any suggestions would help.
1. I have tried adjusting the trimpot.
2. Rewire the connector to match the one on the motherboard.
3. Anything else I found on the internet.</p>
|
<p>If the one in your question is your <em>complete</em> code, a possibility is that your computer is just buffering the output for the serial port, withholding it in memory. Try to add</p>
<pre><code>ser.flush()
</code></pre>
<p>after your last line. This command will... well... <em>flush</em> anything into the buffer through the actual connection.</p>
|
<p>Sorry for the late answer, but with Repetrel v3 and later, we have the option for you to configure a secondary COM port, and relay G- or M-Code commands from your other source through the Repetrel software to the printer. Please contact us for assistance.</p>
<p>Note: I work for Hyrel 3D.</p>
| 802
|
<p>I have an application which is a relatively old. Through some minor changes, it builds nearly perfectly with Visual C++ 2008. One thing that I've noticed is that my "debug console" isn't quite working right. Basically in the past, I've use <code>AllocConsole()</code> to create a console for my debug output to go to. Then I would use <code>freopen</code> to redirect <code>stdout</code> to it. This worked perfectly with both C and C++ style IO.</p>
<p>Now, it seems that it will only work with C style IO. What is the proper way to redirect things like <code>cout</code> to a console allocated with <code>AllocConsole()</code>?</p>
<p>Here's the code which used to work:</p>
<pre><code>if(AllocConsole()) {
freopen("CONOUT$", "wt", stdout);
SetConsoleTitle("Debug Console");
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_RED);
}
</code></pre>
<p><strong>EDIT</strong>: one thing which occurred to me is that I could make a custom streambuf whose overflow method writes using C style IO and replace <code>std::cout</code>'s default stream buffer with it. But that seems like a cop-out. Is there a proper way to do this in 2008? Or is this perhaps something that MS overlooked?</p>
<p><strong>EDIT2</strong>: OK, so I've made an implementaiton of the idea I spelled out above. Basically it looks like this:</p>
<pre><code>class outbuf : public std::streambuf {
public:
outbuf() {
setp(0, 0);
}
virtual int_type overflow(int_type c = traits_type::eof()) {
return fputc(c, stdout) == EOF ? traits_type::eof() : c;
}
};
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) {
// create the console
if(AllocConsole()) {
freopen("CONOUT$", "w", stdout);
SetConsoleTitle("Debug Console");
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_RED);
}
// set std::cout to use my custom streambuf
outbuf ob;
std::streambuf *sb = std::cout.rdbuf(&ob);
// do some work here
// make sure to restore the original so we don't get a crash on close!
std::cout.rdbuf(sb);
return 0;
}
</code></pre>
<p>Anyone have a better/cleaner solution than just forcing <code>std::cout</code> to be a glorified <code>fputc</code>?</p>
|
<h2>Updated Feb 2018:</h2>
<p>Here is the latest version of a function which fixes this problem:</p>
<pre><code>void BindCrtHandlesToStdHandles(bool bindStdIn, bool bindStdOut, bool bindStdErr)
{
// Re-initialize the C runtime "FILE" handles with clean handles bound to "nul". We do this because it has been
// observed that the file number of our standard handle file objects can be assigned internally to a value of -2
// when not bound to a valid target, which represents some kind of unknown internal invalid state. In this state our
// call to "_dup2" fails, as it specifically tests to ensure that the target file number isn't equal to this value
// before allowing the operation to continue. We can resolve this issue by first "re-opening" the target files to
// use the "nul" device, which will place them into a valid state, after which we can redirect them to our target
// using the "_dup2" function.
if (bindStdIn)
{
FILE* dummyFile;
freopen_s(&dummyFile, "nul", "r", stdin);
}
if (bindStdOut)
{
FILE* dummyFile;
freopen_s(&dummyFile, "nul", "w", stdout);
}
if (bindStdErr)
{
FILE* dummyFile;
freopen_s(&dummyFile, "nul", "w", stderr);
}
// Redirect unbuffered stdin from the current standard input handle
if (bindStdIn)
{
HANDLE stdHandle = GetStdHandle(STD_INPUT_HANDLE);
if(stdHandle != INVALID_HANDLE_VALUE)
{
int fileDescriptor = _open_osfhandle((intptr_t)stdHandle, _O_TEXT);
if(fileDescriptor != -1)
{
FILE* file = _fdopen(fileDescriptor, "r");
if(file != NULL)
{
int dup2Result = _dup2(_fileno(file), _fileno(stdin));
if (dup2Result == 0)
{
setvbuf(stdin, NULL, _IONBF, 0);
}
}
}
}
}
// Redirect unbuffered stdout to the current standard output handle
if (bindStdOut)
{
HANDLE stdHandle = GetStdHandle(STD_OUTPUT_HANDLE);
if(stdHandle != INVALID_HANDLE_VALUE)
{
int fileDescriptor = _open_osfhandle((intptr_t)stdHandle, _O_TEXT);
if(fileDescriptor != -1)
{
FILE* file = _fdopen(fileDescriptor, "w");
if(file != NULL)
{
int dup2Result = _dup2(_fileno(file), _fileno(stdout));
if (dup2Result == 0)
{
setvbuf(stdout, NULL, _IONBF, 0);
}
}
}
}
}
// Redirect unbuffered stderr to the current standard error handle
if (bindStdErr)
{
HANDLE stdHandle = GetStdHandle(STD_ERROR_HANDLE);
if(stdHandle != INVALID_HANDLE_VALUE)
{
int fileDescriptor = _open_osfhandle((intptr_t)stdHandle, _O_TEXT);
if(fileDescriptor != -1)
{
FILE* file = _fdopen(fileDescriptor, "w");
if(file != NULL)
{
int dup2Result = _dup2(_fileno(file), _fileno(stderr));
if (dup2Result == 0)
{
setvbuf(stderr, NULL, _IONBF, 0);
}
}
}
}
}
// Clear the error state for each of the C++ standard stream objects. We need to do this, as attempts to access the
// standard streams before they refer to a valid target will cause the iostream objects to enter an error state. In
// versions of Visual Studio after 2005, this seems to always occur during startup regardless of whether anything
// has been read from or written to the targets or not.
if (bindStdIn)
{
std::wcin.clear();
std::cin.clear();
}
if (bindStdOut)
{
std::wcout.clear();
std::cout.clear();
}
if (bindStdErr)
{
std::wcerr.clear();
std::cerr.clear();
}
}
</code></pre>
<p>In order to define this function, you'll need the following set of includes:</p>
<pre><code>#include <windows.h>
#include <io.h>
#include <fcntl.h>
#include <iostream>
</code></pre>
<p>In a nutshell, this function synchronizes the C/C++ runtime standard input/output/error handles with the current standard handles associated with the Win32 process. As mentioned in <a href="https://learn.microsoft.com/en-us/windows/console/allocconsole" rel="noreferrer">the documentation</a>, AllocConsole changes these process handles for us, so all that's required is to call this function after AllocConsole to update the runtime handles, otherwise we'll be left with the handles that were latched when the runtime was initialized. Basic usage is as follows:</p>
<pre><code>// Allocate a console window for this process
AllocConsole();
// Update the C/C++ runtime standard input, output, and error targets to use the console window
BindCrtHandlesToStdHandles(true, true, true);
</code></pre>
<p>This function has gone through several revisions, so check the edits to this answer if you're interested in historical information or alternatives. The current answer is the best solution to this problem however, giving the most flexibility and working on any Visual Studio version.</p>
|
<p>I am not sure I understand the problem completely but if you want to be able to simply spit out data to console for diagnostic purpose.. why dont you try out System::Diagnostics::Process::Execute() method or some method in that namespace?? </p>
<p>Apologies in advance if it was irrelevant</p>
| 40,201
|
<p>I just started thinking about creating/customizing a web crawler today, and know very little about web crawler/robot etiquette. A majority of the writings on etiquette I've found seem old and awkward, so I'd like to get some current (and practical) insights from the web developer community.</p>
<p>I want to use a crawler to walk over "the web" for a super simple purpose - "does the markup of site XYZ meet condition ABC?".</p>
<p>This raises a lot of questions for me, but I think the two main questions I need to get out of the way first are:</p>
<ul>
<li>It feels a little "iffy" from the get go -- is this sort of thing acceptable?</li>
<li>What specific considerations should the crawler take to not upset people?</li>
</ul>
|
<p>Obey robots.txt (and not too aggressive like has been said already).</p>
<p>You might want to think about your user-agent string - they're a good place to be up-front about what you're doing and how you can be contacted.</p>
|
<p>I'd say that it is very important to consider how much load you are causing. For instance, if your crawler requests every object of a single site, more or less at once, it might cause load problems for that particular site.</p>
<p>In other words, make sure your crawler is not too aggressive.</p>
| 5,228
|
<p>How can I rotate the Apache Access and Error logs on a Window 2000 box?</p>
<p>I include my batch file below as an answer.</p>
<p>Is there a way of doing this directly via the Apache config file? I'm currently using the following customlog command to generate daily logs.</p>
<p>CustomLog '|" "*Apache-Path/bin/rotatelogs.exe" "*Apache-Path/logs/backup/internet_access_%d-%m-%y.log" 86400' combined</p>
|
<p>Here's the DOS batch file, modified as annotated.
I run it weekly and it keeps 8 weeks of zipped backups.
You'll need to install 7 zip.</p>
<p>I haven't parametrised the paths, feel free to.</p>
<hr>
<pre><code>@echo off
:: Name - svrlogmng.bat
:: Description - Server Log File Manager
::
:: History
:: Date Authory Change
:: 22-May-2005 AGButler Original
:: 14-Jan-2008 AIMackenzie Changed net stops and paths where necessary
:: ========================================================
:: setup variables and parameters
:: ========================================================
:: generate date and time variables
for /f "tokens=2,3,4 delims=/ " %%i in ('date /T') do set trdt=%%k%%j%%i
for /f "tokens=1,2 delims=: " %%i in ('time /T') do set trtt=%%i%%j
set nftu=%trdt%%trtt%
:: set the Number Of Archives To Keep
set /a noatk=8
:: ========================================================
:: turn over log files
:: ========================================================
:: change to the apache log file directory
cd /D "D:\Program Files\Apache Software Foundation\Apache2.2\logs\"
:: stop Apache Service, Move log files and restart Apache Service
"D:\Program Files\Apache Software Foundation\Apache2.2\bin\httpd.exe" -k stop
echo %nftu% >> access.log
move "D:\Program Files\Apache Software Foundation\Apache2.2\logs\access.log" "D:\Program Files\Apache Software Foundation\Apache2.2\logs\%nftu%_access.log"
echo %nftu% >> error.log
move "D:\Program Files\Apache Software Foundation\Apache2.2\logs\error.log" "D:\Program Files\Apache Software Foundation\Apache2.2\logs\%nftu%_error.log"
"D:\Program Files\Apache Software Foundation\Apache2.2\bin\httpd.exe" -k start
:: ========================================================
:: zip todays Access and Error log files, then delete old logs
:: ========================================================
:: zip the files
"D:\Program Files\7-Zip\7z.exe" a -tzip %nftu%_logs.zip %nftu%_access.log %nftu%_error.log
:: del the files
del /Q %nftu%_*.log
:: ========================================================
:: rotate the zip files
:: ========================================================
:: make list of archive zip files
type NUL > arclist.dat
for /F "tokens=1,2 delims=[] " %%i in ('dir /B *_logs.zip ^| find /N "_logs.zip"') do echo %%i = %%j>> arclist.dat
:: count total number of files
for /F "tokens=1 delims=" %%i in ('type arclist.dat ^| find /C "_logs.zip"') do set tnof=%%i
:: setup for and create the deletion list
set /a negtk=%noatk%*-1
set /a tntd=%tnof% - %noatk%
type NUL>dellist.dat
for /L %%i in (%negtk%,1,%tntd%) do find " %%i = " arclist.dat >> dellist.dat
:: del the old files
for /F "tokens=3 delims= " %%i in ('find "_logs.zip" dellist.dat') do del /Q %%i
:: remove temp files
del /Q arclist.dat
del /Q dellist.dat
</code></pre>
<hr>
|
<p>As stated I don't think this is strictly a programming question, but AFAIK there is no built-in functionality in Apache to support log rotation. There's a standard utility on unix systems called <code>logrotate</code>, so that functionality would be redundant on those systems.</p>
<p>If you rephrase your question to ask how you can write a batch file to handle Apache log rotation on Windows 2000, then answer yourself with your batch file source, that might be helpful to others.</p>
| 46,369
|
<p>I have an SSIS package, which depending on a boolean variable, should either go to a Script Task or an Email task.(Note: the paths are coming <em>from</em> a Script Task)</p>
<p>I recall in the old dts designer there was a way to do this via code. What is the proper way to accomplish this in SSIS?</p>
|
<blockquote>
<p>Isn't a Conditional Split a data flow
task, which takes a row of data and
pushes it in one of two directions
according to some property of the
data???</p>
</blockquote>
<p>Oops, that is correct. I found <a href="http://dichotic.wordpress.com/2006/11/01/ssis-test-for-data-files-existence/" rel="nofollow noreferrer">this</a> blog entry which explains how to do proper control flow conditional branching based on boolean values.</p>
|
<p>A Conditional Split task does what you want. Add the Conditional Split task, add in an additional output (a default output is provided), and set up the Condition for that output. Then just tie the outputs (default and new) to the Script and Email tasks as appropriate.</p>
| 15,528
|
<p>I'm running into a problem when modifying a WCF service.</p>
<p>The original service method looks like this:</p>
<pre><code>[OperationContract(IsOneWay = true, IsInitiating = true, IsTerminating = false)]
void Login(string userName, string password);
</code></pre>
<p>This method works.</p>
<p>The problem is that when I change it to this:</p>
<pre><code>[OperationContract(IsOneWay = false, IsInitiating = true, IsTerminating = false)]
bool Login(string userName, string password);
</code></pre>
<p>It stops working and times out.</p>
<p>Any ideas?</p>
|
<p>Select street_name from tablex
order by udf_getStreetNumber(street_name)</p>
<p>in your udf_getStreetNumber - write your business rule for stripping out the number</p>
<p>EDIT</p>
<p>I think you can use regex functionality in SQL Server now. I'd just strip out all non-number characters from the input.</p>
|
<p>Yes it's possible! But definitely of no interest! If you find somebody here ready to spend a few hours writing down and testing the SP that will split your streetNames into a streetName + streetNumber combination, give me his name: I will submit him a few problems where I thought I had to pay to get the work done.</p>
<p>By the way, can't you split your data into 2 fields, one 'streetName' with only the name of the street, and a new 'buildingNumber' field? (Avoid to name this one 'streetNumber', as, in some countries/cities, streets are given numbers).</p>
| 45,983
|
<p>What is a good Hash function? I saw a lot of hash function and applications in my data structures courses in college, but I mostly got that it's pretty hard to make a good hash function. As a rule of thumb to avoid collisions my professor said that:</p>
<pre><code>function Hash(key)
return key mod PrimeNumber
end
</code></pre>
<p>(mod is the % operator in C and similar languages)</p>
<p>with the prime number to be the size of the hash table. I get that is a somewhat good function to avoid collisions and a fast one, but how can I make a better one? Is there better hash functions for string keys against numeric keys?</p>
|
<p>There's no such thing as a “good hash function” for universal hashes (ed. yes, I know there's such a thing as “universal hashing” but that's not what I meant). Depending on the context different criteria determine the quality of a hash. Two people already mentioned SHA. This is a cryptographic hash and it isn't at all good for hash tables which you probably mean.</p>
<p>Hash tables have very different requirements. But still, finding a good hash function universally is hard because different data types expose different information that can be hashed. As a rule of thumb it is good to consider <em>all</em> information a type holds equally. This is not always easy or even possible. For reasons of statistics (and hence collision), it is also important to generate a good spread over the problem space, i.e. all possible objects. This means that when hashing numbers between 100 and 1050 it's no good to let the most significant digit play a big part in the hash because for ~ 90% of the objects, this digit will be 0. It's far more important to let the last three digits determine the hash.</p>
<p>Similarly, when hashing strings it's important to consider all characters – except when it's known in advance that the first three characters of all strings will be the same; considering these then is a waste.</p>
<p>This is actually one of the cases where I advise to read what Knuth has to say in <em>The Art of Computer Programming</em>, vol. 3. Another good read is Julienne Walker's <a href="http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx" rel="noreferrer">The Art of Hashing</a>.</p>
|
<p>I highly recommend the SMhasher GitHub project <a href="https://github.com/rurban/smhasher" rel="nofollow noreferrer">https://github.com/rurban/smhasher</a> which is a test suite for hash functions. The fastest state-of-the-art non-cryptographic hash functions without known quality problems are listed here: <a href="https://github.com/rurban/smhasher#summary" rel="nofollow noreferrer">https://github.com/rurban/smhasher#summary</a>.</p>
| 5,491
|
<p>I'm looking to implement the Observer pattern in VB.NET or C# or some other first-class .NET language. I've heard that delegates can be used for this, but can't figure out why they would be preferred over plain old interfaces implemented on observers. So,</p>
<ul>
<li>Why should I use delegates instead of defining my own interfaces and passing around references to objects implementing them?</li>
<li>Why might I want to avoid using delegates, and go with good ol'-fashioned interfaces?</li>
</ul>
|
<p>You're an O/S, and I'm an application. I want to tell you to call one of my methods when you detect something happening. To do that, I pass you a delegate to the method of mine which I want you to call. I don't call that method of mine myself, because I want you to call it when you detect the something. You don't call my method directly because you don't know (at your compile-time) that the method exists (I wasn't even written when you were built); instead, you call whichever method is specified by the delegate which you receive at run-time.</p>
|
<p>i think it is more related to <strong>syntatic sugar</strong> and a way to organize your code, a good use would be to handle several methods related to a common context which ones belong to a object or a static class.</p>
<p>it is not that you are forced to use them, you can programme sth with and without them, but maybe using them or not might affect how organized, readable and why not cool the code would be, maybe bum some lines in your code.</p>
<p>Every example given here is a good one where you could implement them, as someone said it, is just another feature in the language you can play with.</p>
<p>greetings</p>
| 38,899
|
<p>I want to read an XML file into a <code>char *buffer</code> using C.</p>
<p>What is the best way to do this?</p>
<p>How should I get started?</p>
|
<p>And if you want to <em>parse</em> XML, not just reading it into a buffer (something which would not be XML-specific, see Christoph's and Baget's answers), you can use for instance <a href="http://xmlsoft.org/" rel="noreferrer">libxml2</a>:</p>
<pre><code>#include <stdio.h>
#include <string.h>
#include <libxml/parser.h>
int main(int argc, char **argv) {
xmlDoc *document;
xmlNode *root, *first_child, *node;
char *filename;
if (argc < 2) {
fprintf(stderr, "Usage: %s filename.xml\n", argv[0]);
return 1;
}
filename = argv[1];
document = xmlReadFile(filename, NULL, 0);
root = xmlDocGetRootElement(document);
fprintf(stdout, "Root is <%s> (%i)\n", root->name, root->type);
first_child = root->children;
for (node = first_child; node; node = node->next) {
fprintf(stdout, "\t Child is <%s> (%i)\n", node->name, node->type);
}
fprintf(stdout, "...\n");
return 0;
}
</code></pre>
<p>On an Unix machine, you typically compile the above with:</p>
<pre><code>% gcc -o read-xml $(xml2-config --cflags) -Wall $(xml2-config --libs) read-xml.c
</code></pre>
|
<p>I believe that question was about XML parsing and not about file reading, however OP should really clarify this.<br>
Any way you got plenty example how to read file.<br>
Another option to xml parsing in additional to <a href="https://stackoverflow.com/questions/381300/how-can-i-read-an-xml-file-into-a-buffer-in-c#381547">sgm</a> suggestion will be <a href="http://expat.sourceforge.net/" rel="nofollow noreferrer">Expat library</a> </p>
| 49,981
|
<p>I'm trying to foresee how big my database will be. Let's say I have only one table: </p>
<p>CREATE TABLE user (<br>
<strong>id</strong> INT UNSIGNED NOT NULL AUTO_INCREMENT,<br>
<strong>email</strong> VARCHAR(50),<br>
<strong>pass</strong> CHAR(40),<br>
<strong>url</strong> VARCHAR(1000),<br>
PRIMARY KEY(id));</p>
<p>Adding all up: 4 + 51 + 40 + 1001 = 1096 bytes in one record.<br>
If I have 1 million records: 1,000,000 x 1096 bytes = 1,045 Mb! </p>
<p>So, it is one tiny table and I'm looking at <strong>1 gig to store it</strong>. Am I correct in my estimation?</p>
|
<p>Apart from the varchar issue you also need to be aware that most databases store the records in allocated blocks of storage (sometimes termed extents - although the precise terminology depends on the rdbms) which contain a certain amount of free space. The intention of this is to allow updates whilst minimizing table and index fragmentation. Of course allocated free space increases database file size even though there's no actual data in it.</p>
<p>These overheads can generally be specified and controlled when creating the table using rdbms-specific clauses, and even virtually eliminated if it's a read-only snapshot. OTOH you might want to make this padding larger than usual if your table is going to see a lot of IUD activity.</p>
<p>A good rule of thumb is to calculate you expected table size as you do - although guesstimating on varchar sizes as discussed in other posts (or better running analysis on sample data) then add 20% - a common default free space allocation. Actually in practice it's unusual for free space allocation to cause an issue, especially if you deploy a sensible maintenance routine (so most folks never think about it), but failure to anticipate and make suitable allocation on a table hit by unusually high IUD activity can give rise to tricky to trace performance problems. </p>
<p>To be honest in these days of 600Gb disks as commonplace it's a long time since I've seriously sized a database at any level other than a quick guesstimate. </p>
<p>*EDITED to reply to comment - "What is IUD and what do you mean by maintenance? Removing old records? – sneg"</p>
<p>IUD = Insert Update Delete activity. To illustrate the maintenance issue lets consider what would happen if we created a database with no free space and loaded a table like the one you propose with records containing varchar data. All records would be placed in our database file end to end, with no space between them.</p>
<p>If the user then updated the varchar part of the record there's three possibilities. If the field is the same length then there's no structural change. If it's shorter we overwrite the old field and there's a few spare bytes at the end of the field - no biggie. If however it's longer then we have a problem - the record will no longer fit. In that case one solution would be to copy the whole amended record to a new location and update the indexes (and in some management schemes drop a pointer in where the old record was). The issue now is that a sequential read of the data - not an uncommon operation - will now have to jump around the database file rather than read straight through - a classic fragmentation scenario - and performance will gradually get hosed.</p>
<p>By allocating free space to the table then when we're updating we have a certain amount of elbow room that allows us to change the record length without having to move the record from the page. Of course over time if the table sees a lot of activity it will still fragment (as we only allocate enough free space to cover some percentage of record changes in place), which is where maintenance comes in.</p>
<p>Maintenance in this case is essentially a defragmentation process to move records around so they are repositioned and free space allocated so that they are distributed efficiently again. In some (most) RDBMs you can just designate a maintenance plan and schedule a job to do this at q quiet time (SQL Server for instance) but in others you might have to do it manually - for example in older versions of Oracle the recommended approach was to export the data, drop the table and recreate, then re-import again from backup - the export/reload process would clean up the data as per any fresh load.</p>
<p>Index structures have similar issues.</p>
<p>I am of course glossing over a lot here, but the essential issues of storing variable length random access data records in a file will remain, no matter how many abstraction layers you pile on top of it. The good thing is that this sort of problem is well understood and most of the time it's not something you need to worry about - until you ask an apparently simple question like 'how much space will this table require' :-)</p>
|
<p>Actually a varchar field represents more than one char field. This is also true of other datatypes as well.</p>
<p>An easy way would be to add 100 records with random test data then look at how big the database file is in your file system. Then add another hundred and see how much larger it grew. </p>
| 33,437
|
<p>3D Printers (those who print, not the machine, dummy)!</p>
<p>I haven't been printing in a while, so when I returned to my Monoprice Select Mini VII, of course it had been sprung out of whack. Some of my first prints would not even come out of the extruder until I realized I had some pretty bad (and worse, unnoticed!) heat creep going on. After fixing that issue, it became apparent that many more persisted.</p>
<p>My question for you all is this: In general, what problems should be addressed first when looking at a complete disaster of a print?</p>
<p>I'm not going to specify any singular problem, but I am interested in seeing the "order of operations" for general problem solving when multiple issues exist. For example, "Fix bed height before anything else; this is a common problem that produces multiple others." Hopefully, this can help others with multiple printing issues, too.</p>
|
<p>for sure the answer could be dissertation or even a book because there is no simple way to address "all" issues - it's just to wide area</p>
<p>but as the simple troubleshooting i would list it this way</p>
<ol>
<li>is your printer alive so is it
<ul>
<li>working at all (check power, cables)</li>
<li>communicate with the world (check app, drivers, cables)</li>
<li>moving HE and heating HB (check jams, end-points, belts, screws)</li>
<li>is it extruding (check heating, temperature, HE jams, filament path)</li>
</ul></li>
</ol>
<p>if all above is "yes" then</p>
<ol start="2">
<li>is your printer making printouts and are those printouts
<ul>
<li>starts and continues (check heating HB, HB adhesion, leveling, cooling)</li>
<li>finished at all (check all above again, stepsticks temerature)</li>
<li>keeping the shape (check screws and nuts, couplings, stiffness, stability, temperatures)</li>
</ul></li>
</ol>
<p>if all above is "yes" then in general you are half way ;)</p>
<ol start="3">
<li>common issues - printout is
<ul>
<li>bent or skewed (check geometry, stiffnes, leveling, belts, vibrations, stepsticks temerature)</li>
<li>wrapped or overextruded (check temperature, extruding, printout angles)</li>
<li>underextruded (check filament flow, filament path, stepsticks temerature)</li>
<li>stringy (check temperatures, app settings)</li>
</ul></li>
</ol>
<p>that is the main path i think. all above is more or less applicable to all DIY printers and all prusa clones and all clones of clones ;)</p>
<p>it can go wrong and fork in all possible moments as there is so many aspects to screw...</p>
|
<h1>The obvious ones first</h1>
<p>This is, well, obvious. It is, what a visual and smell inspection shows. Stuff like missing or ruptured cables, bent rails, ripped or very loose belts, burnt smell or hung up software that is easy to see that it is going on needs to be addressed first.</p>
<h1>The not so obvious next</h1>
<p>Next on the list are problems that have no obvious cause and effect. My order of operations to find these is like this:</p>
<ul>
<li>Homing</li>
<li>movement of XYZ</li>
<li>Bed leveling</li>
<li>Heating test to 200 °C</li>
<li>Extrusion of some millimeters</li>
<li>Retract some millimeters</li>
</ul>
<p>That solves the basic mechanical side, it shows that the machine technically could print. It is a visual as well as audial inspection. It also prepares the printer for printing.</p>
<h1>A test print next</h1>
<p>What's next, after having a machine that theoretically should be able to print is to print.</p>
<p>Start with a simple thing. A cube for example. It shows problems with bed adhesion, surface finish, extrusion, temperature, layer shifting and layer adhesion.</p>
<p>Half of these problems are usually the result of temperature control. The rest but for layer shifting usually as a result of slicer settings.</p>
<ul>
<li>Layer shifting, the odd one out, most often would either be caused by a mechanical problem are using speeds which the printer can't cope with.</li>
<li>Surface imperfections like blobbing shows too much extrusion and heat.</li>
<li>Ghosting so that the printer is resonating with its movement.</li>
</ul>
| 1,315
|
<p>I have a bunch of regression test data. Each test is just a list of messages (associative arrays), mapping message field names to values. There's a lot of repetition within this data.</p>
<p>For example</p>
<pre><code> test1 = [
{ sender => 'client', msg => '123', arg => '900', foo => 'bar', ... },
{ sender => 'server', msg => '456', arg => '800', foo => 'bar', ... },
{ sender => 'client', msg => '789', arg => '900', foo => 'bar', ... },
]
</code></pre>
<p>I would like to represent the field data (as a minimal-depth decision tree?) so that each message can be programatically regenerated using a minimal number of parameters. For example, in the above</p>
<ul>
<li>foo is always 'bar', so I don't need to mention it</li>
<li>sender and client are correlated, so I only need to mention one or the other</li>
<li>and msg is different each time</li>
</ul>
<p>So I would like to be able to regenerate these messages with a program along the lines of</p>
<pre><code>write_msg( 'client', '123' )
write_msg( 'server', '456' )
write_msg( 'client', '789' )
</code></pre>
<p>where the write_msg function would be composed of nested if statements or subfunction calls using the parameters.</p>
<p>Based on my original data, how can I determine the 'most important' set of parameters, i.e. the ones that will let me recreate my data set using the smallest number of arguments?</p>
|
<p>The following papers describe algortithms for discovering functional dependencies:</p>
<blockquote>
<p>Y. Huhtala, J. Kärkkäinen, P. Porkka,
and H. Toivonen. TANE: An efficient
algorithm for discovering functional
and approximate dependencies. <em>The
Computer Journal</em>, 42(2):100–111,
1999, <a href="http://dx.doi.org/10.1093/comjnl/42.2.100" rel="nofollow noreferrer">doi:10.1093/comjnl/42.2.100</a>.</p>
<p>I. Savnik and P. A. Flach. Bottom-up
induction of functional dependencies
from relations. In Proc. <em>AAAI-93 Workshop:
Knowledge Discovery in Databases</em>,
pages 174–185, Washington, DC, USA,
1993. </p>
<p>C. Wyss, C. Giannella, and E.
Robertson. FastFDs: A
Heuristic-Driven, Depth-First
Algorithm for Mining Functional
Dependencies from Relation Instances.
In <i>Proc. Data Warehousing and Knowledge Discovery</i>, pages 101–110, Munich,
Germany, 2001, <a href="http://dx.doi.org/10.1007/3-540-44801-2" rel="nofollow noreferrer">doi:10.1007/3-540-44801-2</a>.</p>
<p>Hong Yao and Howard J. Hamilton. "Mining functional dependencies from data." <em>Data Mining and Knowledge Discovery</em>, 2008, <a href="http://dx.doi.org/10.1007/s10618-007-0083-9" rel="nofollow noreferrer">doi:10.1007/s10618-007-0083-9</a>.</p>
</blockquote>
<p>There has also been some work on discovering multivalued dependencies:</p>
<blockquote>
<p>I. Savnik and P. A. Flach. "Discovery
of Mutlivalued Dependencies from
Relations." <i>Intelligent Data Analysis
Journal</i>, 4(3):195–211, <a href="http://iospress.metapress.com/content/18wpfh7nvxqjamnm/" rel="nofollow noreferrer">IOS Press</a>, 2000.</p>
</blockquote>
|
<p>This looks very similar to <a href="http://en.wikipedia.org/wiki/Database_normalization" rel="nofollow noreferrer">Database Normalization</a>.</p>
<p>You have a relation (your test data set), and some known functional dependencies ({sender} => arg, {} => foo and possibly {msg} => sender. If the order of tests is important then add {testNr} => msg.) and you want to eliminate redundancies.</p>
<p>Treat your test set as a database table, apply the normalization rules and create equivalent functions (getArgFromSender(sender) etc.) for each join.</p>
| 20,325
|
<p>As I am coding my unit tests, I tend to find that I insert the following lines:</p>
<pre><code>Console.WriteLine("Starting InteropApplication, with runInBackground set to true...");
try
{
InteropApplication application = new InteropApplication(true);
application.Start();
Console.WriteLine("Application started correctly");
}
catch(Exception e)
{
Assert.Fail(string.Format("InteropApplication failed to start: {0}", e.ToString()));
}
//test code continues ...
</code></pre>
<p>All of my tests are pretty much the same thing. They are displaying information as to why they failed, or they are displaying information about what they are doing. I haven't had any <em>formal</em> methods of how unit tests should be coded. Should they be displaying information as to what they are doing? Or should the tests be silent and not display any information at all as to what they are doing, and only display failure messages?</p>
<p>NOTE: The language is C#, but I don't care about a language specific answer.</p>
|
<p>I personally would recommend that you output only errors and a summary of the number of tests run and how many passed. This is a completely subjective view though. Display what suits your needs.</p>
|
<p>Well, you should only know when a test failed and why it failed. It's no use to know what's going on, unless, for example, you have a loop and you want to know exactly where in the loop the test died.</p>
| 21,140
|
<p>I suppose there could be historical reasons for this naming and that other languages have similar feature, but it also seems to me that parameters always had a name in C#. Arguments are the unnamed ones. Or is there a particular reason why this terminology was chosen?</p>
|
<p>Yes, you're absolutely right (to my mind, anyway). Ironically, although I'm usually picky about these terms, I still use "parameter passing" when I should probably talk about "argument passing". I suppose one could argue that prior to C# 4.0, if you're calling a method you don't care about the parameter names, whereas the names become part of the significant metadata when you can specify them on the arguments as well.</p>
<p>I agree that it makes a difference, and that terminology is important.</p>
<p>"Optional parameters" is definitely okay though - that's adding metadata to the parameter when you couldn't do so before :) (Having said that, it's not going to be optional in terms of the generated IL...)</p>
<p>Would you like me to ask the team for their feedback?</p>
|
<p>I dont know if its worth adding it now, but MS calls it <em>named arguments</em> anyway. See <a href="http://msdn.microsoft.com/en-us/library/dd264739%28v=vs.100%29.aspx" rel="nofollow">named and optional arguments</a></p>
| 39,375
|
<p>What's the better way to insert cell comments in excel 2007 files programmatically using c# and .net 3.5?</p>
|
<p>I just did exactly that but with MS Word (using Microsoft.Office.Interop.Word</p>
<p>range.Comments.Add ( range, ref _categoryMessage );</p>
<p>So, I would suggest using Microsoft.Office.Interop.Excel and the similar method.
Consider this from MSDN:</p>
<p><a href="https://learn.microsoft.com/en-us/dotnet/api/microsoft.office.interop.excel.range.addcomment" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/dotnet/api/microsoft.office.interop.excel.range.addcomment</a></p>
<p>Also see <a href="https://stackoverflow.com/questions/213303/sofware-requirements-analysis#213452">this</a> too</p>
|
<p>Have you tried using VSTO ? You can easily load an Excel document and manipulate it. To add a comment to a cell, load the file, activate the worksheet, then select the cell as a range and set the comment.</p>
| 27,488
|
<p>I have a table with a "Date" column, and I would like to do a query that does the following:</p>
<p>If the date is a <strong>Monday</strong>, <strong>Tuesday</strong>, <strong>Wednesday</strong>, or <strong>Thursday</strong>, the displayed date should be shifted up by 1 day, as in <pre>DATEADD(day, 1, [Date])</pre> On the other hand, if it is a <strong>Friday</strong>, the displayed date should be incremented by 3 days (i.e. so it becomes the following <em>Monday</em>).</p>
<p>How do I do this in my SELECT statement? As in,</p>
<pre>SELECT somewayofdoingthis([Date]) FROM myTable</pre>
<p>(This is SQL Server 2000.)</p>
|
<p>Here is how I would do it. I do recommend a function like above if you will be using this in other places.</p>
<pre><code>CASE
WHEN
DATEPART(dw, [Date]) IN (2,3,4,5)
THEN
DATEADD(d, 1, [Date])
WHEN
DATEPART(dw, [Date]) = 6
THEN
DATEADD(d, 3, [Date])
ELSE
[Date]
END AS [ConvertedDate]
</code></pre>
|
<pre><code>create table #dates (dt datetime)
insert into #dates (dt) values ('1/1/2001')
insert into #dates (dt) values ('1/2/2001')
insert into #dates (dt) values ('1/3/2001')
insert into #dates (dt) values ('1/4/2001')
insert into #dates (dt) values ('1/5/2001')
select
dt, day(dt), dateadd(dd,1,dt)
from
#dates
where
day(dt) between 1 and 4
union all
select
dt, day(dt), dateadd(dd,3,dt)
from
#dates
where
day(dt) = 5
drop table #dates
</code></pre>
| 12,992
|
<p>Looking at this LINQ demo:</p>
<p><a href="http://www.microsoft.com/emea/msdn/spotlight/sessionh.aspx?videoid=716" rel="nofollow noreferrer">LINQ Framework Overview</a></p>
<p>When going in debug mode, the output have colors in it. I'm using the same ObjectDumper class and I only have the black/white console window.</p>
<p>How can I have the same results in the console window?</p>
<p>Thanks</p>
|
<p>What about :</p>
<pre><code> Console.ForegroundColor = ConsoleColor.Yellow;
Console.BackgroundColor = ConsoleColor.DarkRed;
Console.WriteLine("Test");
</code></pre>
|
<p>You can set colors of the console text and/or background in the properties if that's what you're looking for...
Just right click the title bar, click Properties and choose desired colors.</p>
| 38,923
|
<p>I get the following error pretty regularly when compiling in Visual Studio and running my web application:</p>
<p>"Unable to start debugging on the web server. The web server did not respond in a timely manner. This may be because another debugger is already attached to the web server."</p>
<p>Normally this is after having debug the application once already. From the command line I run "iisreset /restart" and it fixes the problem.</p>
<p>How do I prevent this from happening in the first place?</p>
|
<p>I find that this happens if I'm debugging with Firefox as my browser. When I exit Firefox the VS2005/8 debug session doesn't terminate. I have not found a solution for this (yet).</p>
<p>If this is what's happening with you then a quicker solution than running iisreset is to hit Shift-F5 when in Visual Studio and this will terminate the current debug session. You can then hit F5 and this will start a new debug session.</p>
|
<p>I just solved this problem on my machine.
My problem is that I upgraded IE 9 To IE 10 and I got this error.
Solution : Remove IE 10 and downgrade to IE 9.
Go to "Programs and Features" --> "View recent updates" --> find IE 10---> Uninstall it-->reboot--->ie 9 is back--->debug--->works OK.</p>
| 2,463
|
<p>How do you redirect HTTPS to HTTP?. That is, the opposite of what (seemingly) everyone teaches.</p>
<p>I have a server on HTTPS for which I paid an SSL certification for and a mirror for which I haven't and keep around for just for emergencies so it doesn't merit getting a certification for.</p>
<p>On my client's desktops I have SOME shortcuts which point to <code>http://production_server</code> and <code>https://production_server</code> (both work). However, I know that if my production server goes down, then DNS forwarding kicks in and those clients which have "https" on their shortcut will be staring at <code>https://mirror_server</code> (which doesn't work) and a big fat Internet Explorer 7 red screen of uneasyness for my company. </p>
<p>Unfortunately, I can't just switch this around at the client level. These users are very computer illiterate: and are very likely to freak out from seeing HTTPS "insecurity" errors (especially the way Firefox 3 and Internet Explorer 7 handle it nowadays: FULL STOP, kind of thankfully, but not helping me here LOL).</p>
<p>It's <a href="http://www.cyberciti.biz/tips/howto-apache-force-https-secure-connections.html" rel="noreferrer">very easy</a> <a href="http://bytes.com/forum/thread54801.html" rel="noreferrer">to find</a> <a href="http://support.jodohost.com/showthread.php?t=6678" rel="noreferrer">Apache solutions</a> for <a href="http://www.google.com/search?q=https+redirection&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a" rel="noreferrer">http->https redirection</a>, but for the life of me I can't do the opposite.</p>
<p>Ideas?</p>
|
<p>This has not been tested but I think this should work using mod_rewrite</p>
<pre><code>RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI}
</code></pre>
|
<p>As far as I'm aware of a simple meta refresh also works without causing errors:</p>
<pre><code><meta http-equiv="refresh" content="0;URL='http://www.yourdomain.com/path'">
</code></pre>
| 2,980
|
<p>Are all of these equal? Under what circumstances should I choose each over the others?</p>
<ul>
<li><p>var.ToString()</p></li>
<li><p>CStr(var)</p></li>
<li><p>CType(var, String)</p></li>
<li><p>DirectCast(var, String)</p></li>
</ul>
<hr>
<p><em>EDIT: Suggestion from <strong><a href="https://stackoverflow.com/users/303/notmyself">NotMyself</a></strong>…</em></p>
<ul>
<li>TryCast(var, String)</li>
</ul>
|
<p>Those are all slightly different, and generally have an acceptable usage.</p>
<ul>
<li><code>var.</code><a href="http://msdn.microsoft.com/en-us/library/system.object.tostring.aspx" rel="noreferrer"><code>ToString</code></a><code>()</code> is going to give you the string representation of an object, regardless of what type it is. Use this if <code>var</code> is not a string already.</li>
<li><a href="http://msdn.microsoft.com/en-us/library/0zk841e9.aspx" rel="noreferrer"><code>CStr</code></a><code>(var)</code> is the VB string cast operator. I'm not a VB guy, so I would suggest avoiding it, but it's not really going to hurt anything. I think it is basically the same as <code>CType</code>.</li>
<li><a href="http://msdn.microsoft.com/en-us/library/4x2877xb.aspx" rel="noreferrer"><code>CType</code></a><code>(var, String)</code> will convert the given type into a string, using any provided conversion operators.</li>
<li><a href="http://msdn.microsoft.com/en-us/library/7k6y2h6x.aspx" rel="noreferrer"><code>DirectCast</code></a><code>(var, String)</code> is used to up-cast an object into a string. If you know that an object variable is, in fact, a string, use this. This is the same as <code>(string)var</code> in C#.</li>
<li><a href="http://msdn.microsoft.com/en-us/library/zyy863x8.aspx" rel="noreferrer"><code>TryCast</code></a> (as mentioned by @<a href="https://stackoverflow.com/questions/40764/how-should-i-cast-in-vbnet#40771">NotMyself</a>) is like <code>DirectCast</code>, but it will return <code>Nothing</code> if the variable can't be converted into a string, rather than throwing an exception. This is the same as <code>var as string</code> in C#. The <code>TryCast</code> page on MSDN has a good comparison, too.</li>
</ul>
|
<p>At one time, I remember seeing the MSDN library state to use CStr() because it was faster. I do not know if this is true though.</p>
| 6,203
|
<p>How do I handle the scenario where I making a synchronous request to the server using XMLHttpRequest and the server is not available?</p>
<pre><code>xmlhttp.open("POST","Page.aspx",false);
xmlhttp.send(null);
</code></pre>
<p>Right now this scenario results into a JavaScript error:
"The system cannot locate the resource specified"</p>
|
<p>Ok I resolved it by using try...catch around xmlhttprequest.send</p>
<p>:</p>
<pre><code>xmlhttp.open("POST","Page.aspx",false);
try
{
xmlhttp.send(null);
}
catch(e)
{
alert('there was a problem communicating with the server');
}
</code></pre>
|
<p>You don't check for properly returned status. By the code you gave you are doing a GET request.
To properly check the status of your request, you must create an event handler for the onreadystatechange event and then inside it check if the readyState property is equal 4 and then inside the method if the status is 200. </p>
<p>You can find a detailed explanation here :<a href="https://developer.mozilla.org/en/AJAX/Getting_Started" rel="nofollow noreferrer">Ajax Tutorial by Mozilla</a> </p>
<pre> <code>
xmlhttp.onreadystatechange=function()
xmlhttp.open("GET","Page.aspx",false);
{
if (xmlhttp.readyState==4)
{
if (xmlhttp.status==200)
{
//Ajax handling logic
}
}
}
xmlhttp.send(null);
</code></pre>
| 49,400
|
<p>How can I tell if an App is ASP.NET 2.0 or ASP.NET 1.1. This is in C#</p>
<p>I don't have the source code and I don't have access to IIS Manager. But I can ftp and check the ASPX files. Any Ideas?</p>
|
<p>if you can get an error message to show it will tell you at the bottom of the page what version of the framework is in use.</p>
<p>or, if you could upload a file, you could upload an aspx page containing code to output the framework version:</p>
<pre><code><%@ Page Language="C#" EnableSessionState="False" EnableViewState="False" Trace="False" Debug="False" %>
<script language="C#" runat="server">
protected void Page_Load(object s, EventArgs e)
{
Response.Write(System.Environment.Version);
}
</script>
</code></pre>
<p>this was just typed in, there could be syntax or other code errors.</p>
|
<p>You can do this through your browser - just look in the response headers for "X-AspNet-Version" </p>
<p>In FireFox you can do this with the web developer toolbar... -> Information -> View Response Headers. </p>
<p>You can also check Response Headers with <a href="http://www.fiddlertool.com/fiddler/" rel="nofollow noreferrer">Fiddler</a></p>
<p>Or just use the ViewHtml website <a href="http://www.viewhtml.com" rel="nofollow noreferrer">here</a> to view Response Headers</p>
| 25,554
|
<p>I am interested in doing development on Cura. Initially I want to start with the UI rather than the Engine. I have found the <a href="https://github.com/Ultimaker/Cura" rel="nofollow noreferrer">repository</a> and have cloned it to my PC. I have also looked over the <a href="https://github.com/Ultimaker/Cura/wiki" rel="nofollow noreferrer">Wiki</a> and searched the web. For such a popular open-source product, I was surprised I couldn't find a build guide.</p>
<p>Can someone direct me on how to get started. I have a LOT of experience in Software Development (more years and languages than I want to admit to); but, I have never used Python. Consider that in your instructions.</p>
|
<p>As you are an experienced developer, these links should help:</p>
<p>This is a related question, but for Ubuntu <a href="https://3dprinting.stackexchange.com/questions/1309/how-to-build-curaengine">How to build CuraEngine?</a></p>
<p>Wikipedia has an informative page on <a href="https://en.wikipedia.org/wiki/Cura_(software)" rel="nofollow noreferrer">Cura</a>, which lists the Github development pages:</p>
<blockquote>
<ul>
<li><a href="https://github.com/Ultimaker/Cura" rel="nofollow noreferrer">Cura Github development page</a></li>
<li><a href="https://github.com/daid/LegacyCura" rel="nofollow noreferrer">Cura Github legacy (pre-Ultimaker) development page</a></li>
<li><a href="https://github.com/Ultimaker/CuraEngine" rel="nofollow noreferrer">Cura slicing engine Github development page</a></li>
</ul>
</blockquote>
<p>Reading the development pages is a good place to start. The <a href="https://github.com/Ultimaker/Cura" rel="nofollow noreferrer">Cura Github development page</a> does contain resources for Windows.</p>
<p>The top level Ultimaker <a href="https://github.com/Ultimaker" rel="nofollow noreferrer">Github page</a> contains links to all of the relevant repositories, amongst other useful resources, including:</p>
<blockquote>
<ul>
<li><a href="https://github.com/Ultimaker/CuraEngine" rel="nofollow noreferrer">CuraEngine</a> - CuraEngine is a powerful, fast and robust engine for processing 3D models into 3D printing instruction for Ultimaker
and other GCode based 3D printers. It is part of the larger open
source project called "Cura".</li>
<li><a href="https://github.com/Ultimaker/Cura" rel="nofollow noreferrer">Cura</a> - 3D printer / slicing GUI built on top of the Uranium framework</li>
<li><a href="http://cura-build" rel="nofollow noreferrer">cura-build</a> - Build scripts for Cura</li>
</ul>
</blockquote>
<hr>
<p>With respect to Python, I, myself, am slowly making my way through this Python tutorial, <a href="https://www.codecademy.com/en/courses/introduction-to-python-6WeG3/0/1" rel="nofollow noreferrer">Python Code Academy</a>. However, there are a many other good Python tutorials out there, the best resource is probably <a href="https://www.python.org/" rel="nofollow noreferrer">Python.org</a>. </p>
<p>One thing to note is that Python 2.x and 3.x are markedly different (see <a href="https://wiki.python.org/moin/Python2orPython3" rel="nofollow noreferrer">Should I use Python 2 or Python 3 for my development activity?</a>). <a href="http://learntocodewith.me/programming/python/python-2-vs-python-3/" rel="nofollow noreferrer">What should I learn as a beginner: Python 2 OR Python 3?</a> is also an interesting read.</p>
|
<p>As you are an experienced developer, these links should help:</p>
<p>This is a related question, but for Ubuntu <a href="https://3dprinting.stackexchange.com/questions/1309/how-to-build-curaengine">How to build CuraEngine?</a></p>
<p>Wikipedia has an informative page on <a href="https://en.wikipedia.org/wiki/Cura_(software)" rel="nofollow noreferrer">Cura</a>, which lists the Github development pages:</p>
<blockquote>
<ul>
<li><a href="https://github.com/Ultimaker/Cura" rel="nofollow noreferrer">Cura Github development page</a></li>
<li><a href="https://github.com/daid/LegacyCura" rel="nofollow noreferrer">Cura Github legacy (pre-Ultimaker) development page</a></li>
<li><a href="https://github.com/Ultimaker/CuraEngine" rel="nofollow noreferrer">Cura slicing engine Github development page</a></li>
</ul>
</blockquote>
<p>Reading the development pages is a good place to start. The <a href="https://github.com/Ultimaker/Cura" rel="nofollow noreferrer">Cura Github development page</a> does contain resources for Windows.</p>
<p>The top level Ultimaker <a href="https://github.com/Ultimaker" rel="nofollow noreferrer">Github page</a> contains links to all of the relevant repositories, amongst other useful resources, including:</p>
<blockquote>
<ul>
<li><a href="https://github.com/Ultimaker/CuraEngine" rel="nofollow noreferrer">CuraEngine</a> - CuraEngine is a powerful, fast and robust engine for processing 3D models into 3D printing instruction for Ultimaker
and other GCode based 3D printers. It is part of the larger open
source project called "Cura".</li>
<li><a href="https://github.com/Ultimaker/Cura" rel="nofollow noreferrer">Cura</a> - 3D printer / slicing GUI built on top of the Uranium framework</li>
<li><a href="http://cura-build" rel="nofollow noreferrer">cura-build</a> - Build scripts for Cura</li>
</ul>
</blockquote>
<hr>
<p>With respect to Python, I, myself, am slowly making my way through this Python tutorial, <a href="https://www.codecademy.com/en/courses/introduction-to-python-6WeG3/0/1" rel="nofollow noreferrer">Python Code Academy</a>. However, there are a many other good Python tutorials out there, the best resource is probably <a href="https://www.python.org/" rel="nofollow noreferrer">Python.org</a>. </p>
<p>One thing to note is that Python 2.x and 3.x are markedly different (see <a href="https://wiki.python.org/moin/Python2orPython3" rel="nofollow noreferrer">Should I use Python 2 or Python 3 for my development activity?</a>). <a href="http://learntocodewith.me/programming/python/python-2-vs-python-3/" rel="nofollow noreferrer">What should I learn as a beginner: Python 2 OR Python 3?</a> is also an interesting read.</p>
| 603
|
<p>I was asked a question in C last night and I did not know the answer since I have not used C much since college so I thought maybe I could find the answer here instead of just forgetting about it.</p>
<p>If a person has a define such as:</p>
<pre><code>#define count 1
</code></pre>
<p>Can that person find the variable name <code>count</code> using the 1 that is inside it?</p>
<p>I did not think so since I thought the count would point to the 1 but do not see how the 1 could point back to count.</p>
|
<p>The simple answer is no they can't. #Defines like that are dealt with by the preprocessor, and they only point in one direction. Of course the other problem is that even the compiler wouldn't know - as a "1" could point to anything - multiple variables can have the same value at the same time.</p>
|
<p>What do you mean by "finding"?</p>
<p>The line </p>
<pre><code>#define count 1
</code></pre>
<p>defines a symbol "count" that has value 1.</p>
<p>The first step of the compilation process (called preprocessing) will replace every occurence of the symbol count with 1 so that if you have:</p>
<pre><code>if (x > count) ...
</code></pre>
<p>it will be replaced by:</p>
<pre><code>if (x > 1) ...
</code></pre>
<p>If you get this, you may see why "finding count" is meaningless.</p>
| 15,500
|
<p>I'm using C++ and accessing a UNC path across the network. This path is slightly greater than MAX_PATH. So I cannot obtain a file handle.</p>
<p>But if I run the program on the computer in question, the path is not greater than MAX_PATH. So I can get a file handle. If I rename the file to have less characters (minus length of computer name) I can access the file. </p>
<p>Can this file be accessed across the network even know the computer name in the UNC path puts it over the MAX_PATH limit?</p>
|
<p>I recall that there is some feature like using <code>\\?\</code> at the start of the path to get around the <code>MAX_PATH</code> limit. Here is a reference on MSDN:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx</a></p>
<p>For remote machines, you would use a path name such as: <code>\\?\unc\server\share\path\file</code>. The <code>\\?\unc\</code> is the special prefix and is not used as part of the actual filename.</p>
|
<p>You might be able to get a handle to the file if you try opening the file after converting the file name to a short (8.3) file name. Failing that can you map the dir the file is in as a drive and access the file that way?</p>
| 13,802
|
<p>I am currently having a hardtime understanding and implementing events in C# using delagates. I am used to the Java way of doing things:</p>
<ol>
<li>Define an interface for a listener type which would contain a number of method definitions</li>
<li>Define adapter class for that interface to make things easier if I'm not interested in all the events defined in a listener</li>
<li>Define Add, Remove and Get[] methods in the class which raises the events</li>
<li>Define protected fire methods to do the dirty work of looping through the list of added listeners and calling the correct method</li>
</ol>
<p>This I understand (and like!) - I know I could do this exactly the same in c#, but it seems that a new (better?) system is in place for c#. After reading countless tutorials explaining the use of delegates and events in c# I still am no closer to really understanding what is going on :S</p>
<hr>
<p>In short, for the following methods how would I implement the event system in c#:</p>
<pre><code>void computerStarted(Computer computer);
void computerStopped(Computer computer);
void computerReset(Computer computer);
void computerError(Computer computer, Exception error);
</code></pre>
<p>^ The above methods are taken from a Java application I once made which I'm trying to port over to c#.</p>
<p>Many many thanks!</p>
|
<p>You'd create four events, and methods to raise them, along with a new EventArgs-based class to indicate the error:</p>
<pre><code>public class ExceptionEventArgs : EventArgs
{
private readonly Exception error;
public ExceptionEventArgs(Exception error)
{
this.error = error;
}
public Error
{
get { return error; }
}
}
public class Computer
{
public event EventHandler Started = delegate{};
public event EventHandler Stopped = delegate{};
public event EventHandler Reset = delegate{};
public event EventHandler<ExceptionEventArgs> Error = delegate{};
protected void OnStarted()
{
Started(this, EventArgs.Empty);
}
protected void OnStopped()
{
Stopped(this, EventArgs.Empty);
}
protected void OnReset()
{
Reset(this, EventArgs.Empty);
}
protected void OnError(Exception e)
{
Error(this, new ExceptionEventArgs(e));
}
}
</code></pre>
<p>Classes would then subscribe to the event using either a method or a an anonymous function:</p>
<pre><code>someComputer.Started += StartEventHandler; // A method
someComputer.Stopped += delegate(object o, EventArgs e)
{
Console.WriteLine("{0} has started", o);
};
someComputer.Reset += (o, e) => Console.WriteLine("{0} has been reset");
</code></pre>
<p>A few things to note about the above:</p>
<ul>
<li>The OnXXX methods are protected so that derived classes can raise the events. This isn't always necessary - do it as you see fit.</li>
<li>The <code>delegate{}</code> piece on each event declaration is just a trick to avoid having to do a null check. It's subscribing a no-op event handler to each event</li>
<li>The event declarations are <em>field-like events</em>. What's actually being created is both a variable <em>and</em> an event. Inside the class you see the variable; outside the class you see the event.</li>
</ul>
<p>See my <a href="http://pobox.com/~skeet/csharp/events.html" rel="noreferrer">events/delegates</a> article for much more detail on events.</p>
|
<p>The delegate declares a function signature, and when it's used as an event on a class it also acts as a collection of enlisted call targets. The += and -= syntax on an event is used to adding a target to the list.</p>
<p>Given the following delegates used as events:</p>
<pre><code>// arguments for events
public class ComputerEventArgs : EventArgs
{
public Computer Computer { get; set; }
}
public class ComputerErrorEventArgs : ComputerEventArgs
{
public Exception Error { get; set; }
}
// delegates for events
public delegate void ComputerEventHandler(object sender, ComputerEventArgs e);
public delegate void ComputerErrorEventHandler(object sender, ComputerErrorEventArgs e);
// component that raises events
public class Thing
{
public event ComputerEventHandler Started;
public event ComputerEventHandler Stopped;
public event ComputerEventHandler Reset;
public event ComputerErrorEventHandler Error;
}
</code></pre>
<p>You would subscribe to those events with the following:</p>
<pre><code>class Program
{
static void Main(string[] args)
{
var thing = new Thing();
thing.Started += thing_Started;
}
static void thing_Started(object sender, ComputerEventArgs e)
{
throw new NotImplementedException();
}
}
</code></pre>
<p>Although the arguments could be anything, the object sender and EventArgs e is a convention that's used very consistently. The += thing_started will first create an instance of the delegate pointing to target method, then add it to the event.</p>
<p>On the component itself you would typically add methods to fire the events:</p>
<pre><code>public class Thing
{
public event ComputerEventHandler Started;
public void OnStarted(Computer computer)
{
if (Started != null)
Started(this, new ComputerEventArgs {Computer = computer});
}
}
</code></pre>
<p>You must test for null in case no delegates have been added to the event. When you make the method call however all delegates which have been added will be called. This is why for events the return type is void - there is no single return value - so to feed back information you would have properties on the EventArgs which the event handlers would alter.</p>
<p>Another refinement would be to use the generic EventHandler delegate rather than declaring a concrete delegate for each type of args.</p>
<pre><code>public class Thing
{
public event EventHandler<ComputerEventArgs> Started;
public event EventHandler<ComputerEventArgs> Stopped;
public event EventHandler<ComputerEventArgs> Reset;
public event EventHandler<ComputerErrorEventArgs> Error;
}
</code></pre>
| 21,899
|
<p>I need to get execution time in milliseconds.</p>
<blockquote>
<p>I originally asked this question back in 2008. The accepted answer then was to use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime" rel="noreferrer"><code>new Date().getTime()</code></a> However, we can all agree now that using the standard <a href="https://developer.mozilla.org/en-US/docs/Web/API/Performance.now" rel="noreferrer"><code>performance.now()</code></a> API is more appropriate. I am therefore changing the accepted answer to this one.</p>
</blockquote>
|
<h2>Using <a href="https://developer.mozilla.org/en-US/docs/Web/API/Performance.now" rel="noreferrer"><strong>performance.now()</strong></a>:</h2>
<pre class="lang-js prettyprint-override"><code>var startTime = performance.now()
doSomething() // <---- measured code goes between startTime and endTime
var endTime = performance.now()
console.log(`Call to doSomething took ${endTime - startTime} milliseconds`)
</code></pre>
<blockquote>
<p>In <code>Node.js</code> it is required to import the <a href="https://nodejs.org/api/perf_hooks.html#perf_hooks_class_performance" rel="noreferrer"><code>performance</code></a> class</p>
</blockquote>
<p>importing performance</p>
<pre class="lang-js prettyprint-override"><code>const { performance } = require('perf_hooks');
</code></pre>
<hr />
<h2>Using <strong><a href="https://developer.mozilla.org/en-US/docs/DOM/console.time" rel="noreferrer">console.time</a></strong>: (<a href="https://console.spec.whatwg.org/#time" rel="noreferrer">living standard</a>)</h2>
<pre class="lang-js prettyprint-override"><code>console.time('doSomething')
doSomething() // <---- The function you're measuring time for
console.timeEnd('doSomething')
</code></pre>
<p><em><strong>Note:</strong></em> <br>The string being passed to the <code>time()</code> and <code>timeEnd()</code> methods must match<br>(<em>for the timer to finish as expected</em>).</p>
<blockquote>
<h3><code>console.time()</code> documentations:</h3>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Console/time" rel="noreferrer">MDN documentation</a></li>
<li><a href="https://nodejs.org/api/console.html#console_console_timeend_label" rel="noreferrer">Node.js documentation</a></li>
</ul>
</blockquote>
|
<p>As previously stated check for and use built in timer. But if you want or need to write your own here is my two cents:</p>
<pre><code>//=-=|Source|=-=//
/**
* JavaScript Timer Object
*
* var now=timer['elapsed']();
* timer['stop']();
* timer['start']();
* timer['reset']();
*
* @expose
* @method timer
* @return {number}
*/
timer=function(){
var a=Date.now();
b=0;
return{
/** @expose */
elapsed:function(){return b=Date.now()-a},
start:function(){return a=Date.now()},
stop:function(){return Date.now()},
reset:function(){return a=0}
}
}();
//=-=|Google Advanced Optimized|=-=//
timer=function(){var a=Date.now();b=0;return{a:function(){return b=Date.now()-a},start:function(){return a=Date.now()},stop:function(){return Date.now()},reset:function(){return a=0}}}();
</code></pre>
<h3>Compilation was a success!</h3>
<ul>
<li>Original Size: 219 bytes gzipped (405 bytes uncompressed)</li>
<li>Compiled Size: 109 bytes gzipped (187 bytes uncompressed)</li>
<li>Saved 50.23% off the gzipped size (53.83% without gzip</li>
</ul>
| 40,480
|
<p>How do you invoke a tkinter <code>event</code> from a separate object? </p>
<p>I'm looking for something like wxWidgets <code>wx.CallAfter</code>. For example, If I create an object, and pass to it my <code>Tk</code> root instance, and then try to call a method of that root window from my object, my app locks up.</p>
<p>The best I can come up with is to use the the <code>after</code> method and check the status from my separate object, but that seems wasteful.</p>
|
<p>To answer your specific question of "How do you invoke a TkInter event from a separate object", use the <code>event_generate</code> command. It allows you to inject events into the event queue of the root window. Combined with Tk's powerful virtual event mechanism it becomes a handy message passing mechanism. </p>
<p>For example:</p>
<pre><code>from tkinter import *
def doFoo(*args):
print("Hello, world")
root = Tk()
root.bind("<<Foo>>", doFoo)
# some time later, inject the "<<Foo>>" virtual event at the
# tail of the event queue
root.event_generate("<<Foo>>", when="tail")
</code></pre>
<p>Note that the <code>event_generate</code> call will return immediately. It's not clear if that's what you want or not. Generally speaking you don't want an event based program to block waiting for a response to a specific event because it will <em>freeze the GUI</em>. </p>
<p>I'm not sure if this solves your problem though; without seeing your code I'm not sure what your real problem is. I can, for example, access methods of root in the constructor of an object where the root is passed in without the app locking up. This tells me there's something else going on in your code.</p>
<p>Here's an example of successfully accessing methods on a root window from some other object:</p>
<pre><code>from tkinter import *
class myClass:
def __init__(self, root):
print("root background is %s" % root.cget("background"))
root = Tk()
newObj = myClass(root)
</code></pre>
|
<p>Here below just some doc and link to better understand Bryan's answer above.</p>
<p>function description from <a href="https://web.archive.org/web/20190527174904/http://infohost.nmt.edu:80/tcc/help/pubs/tkinter/web/universal.html" rel="nofollow noreferrer">New Mexico Tech</a> :</p>
<p><code>w.event_generate(sequence, **kw)</code></p>
<blockquote>
<p>This method causes an event to trigger without any external stimulus. The handling of the event is the same as if it had been triggered by an external stimulus. The sequence argument describes the event to be triggered. You can set values for selected fields in the Event object by providing keyword=value arguments, where the keyword specifies the name of a field in the Event object.</p>
</blockquote>
<p>list and description of tcl/tk event attributes <a href="https://www.tcl.tk/man/tcl/TkCmd/event.htm" rel="nofollow noreferrer">here</a></p>
| 34,025
|
<p>i'm want to have a repeater generate a bunch of checkboxes, e.g.:</p>
<pre><code><tr><td><input type="checkbox" name="t" value="11cbf4deb87" /> <input type="checkbox" name="a" value="33cbf4deb87" />stackoverflow.com</td></tr>
<tr><td><input type="checkbox" name="t" value="11cbf4deb88" /> <input type="checkbox" name="a" value="33cbf4deb87" />microsoft.com</td></tr>
<tr><td><input type="checkbox" name="t" value="11cd3f33a89" /> <input type="checkbox" name="a" value="33cbf4deb87" />gmail.com</td></tr>
<tr><td><input type="checkbox" name="t" value="1138fecd337" /> <input type="checkbox" name="a" value="33cbf4deb87" />youporn.com</td></tr>
<tr><td><input type="checkbox" name="t" value="11009efdacc" /> <input type="checkbox" name="a" value="33bf4deb87" />fantasti.cc</td></tr>
</code></pre>
<p>Question 1: How do i individually reference each checkbox when the repeater is running so i can set the unique value?</p>
<p>Do i data-bind it with something like:</p>
<pre><code><itemtemplate>
<tr>
<td>
<input type="checkbox" name="t"
value="<%# ((Item)Container.DataItem).TangoUniquifier %>" />
<input type="checkbox" name="a"
value="<%# ((Item)Container.DataItem).AlphaUniquifier %>" />
<%# ((Item)Container.DataItem).SiteName %>
</td>
</tr>
</itemtemplate>
</code></pre>
<p>Or am i supposed to set it somehow in the OnItemDataBound?</p>
<pre><code><asp:repeater id="ItemsRepeater"
OnItemDataBound="ItemsRepeater_OnItemDataBound" runat="server">
...
<itemtemplate>
<tr>
<td>
<input id="chkTango" type="checkbox" name="t" runat="server" />
<input id="chkAlpha" type="checkbox" name="a" runat="server" />
<%# ((Item)Container.DataItem).SiteName %>
</td>
</tr>
</itemtemplate>
...
</asp:repeater>
protected void ItemsRepeater_OnItemDataBound(object sender, RepeaterItemEventArgs e)
{
// if the data bound item is an item or alternating item (not the header etc)
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
// get the associated item
Item item = (Item)e.Item.DataItem;
//???
this.chkTango.Value = item.TangoUniquifier;
this.chkAlpha.Value = item.AlphaUniquifier;
}
}
</code></pre>
<p>But if i'm supposed to reference it in the code-behind, how do i reference it in the code-behind? Am i supposed to reference it using the (server-side) id property of an <code><INPUT></code> control? i realize that the ID of a control on the server-side is not the same as the ID that will be present on the client.</p>
<p>Or do i have to do something where i have to find an INPUT control with a name of "t" and another with a name of "a"? And what kind of control is a CheckBox that allows me to set it's input value?</p>
<pre><code>protected void ItemsRepeater_OnItemDataBound(object sender, RepeaterItemEventArgs e)
{
// if the data bound item is an item or alternating item (not the header etc)
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
// get the associated item
Item item = (Item)e.Item.DataItem;
CheckBox chkTango = (CheckBox)e.Item.FindControl("chkTango");
chkTango.Value = item.TangoUniquifier;
CheckBox chkAlpha = (CheckBox)e.Item.FindControl("chkAlpha");
chkAlpha.Value = item.AlphaUniquifier;
}
}
</code></pre>
<hr>
<p>Question 2:
When the user later clicks SUBMIT, how do i find all the checked checkboxes, or more specifically their VALUES?</p>
<p>Do i have to FindControl?</p>
<pre><code>protected void DoStuffWithLinks_Click(object sender, EventArgs e)
{
// loop through the repeater items
foreach (RepeaterItem repeaterItem in actionItemRepeater.Items)
{
Item item = repeaterItem.DataItem as Item;
// grab the checkboxes
CheckBox chkAlpha = (CheckBox)repeaterItem.FindControl("chkAlpha");
CheckBox chkTango = (CheckBox)repeaterItem.FindControl("chkTango");
if (chkAlpha.Checked)
{
item.DoAlphaStuff(chkAlpha.Name);
}
if (chkTango.Checked)
{
item.DoTangoStuff(chkTango.Name);
}
}
}
</code></pre>
<p>Is the repeater items DataItem still there on a click event handler?</p>
|
<p>Use the server control instead of making an input control runat=server</p>
<pre><code> <asp:CheckBox id="whatever" runat="Server" />
</code></pre>
<p>When you set the value in your ItemDataBound, you use FindControl</p>
<pre><code>CheckBox checkBox = (CheckBox)e.Item.FindControl("whatever");
checkBox.Checked = true;
</code></pre>
<p>When you get the items, you also use FindControl from the item in a foreach construct. Also, depending on how you databound it, the DataItem may no longer be there after a postback.</p>
<pre><code>foreach (RepeaterItem item in myRepeater.Items)
{
if (item.ItemType == ListItemType.Item
|| item.ItemType == ListItemType.AlternatingItem)
{
CheckBox checkBox = (CheckBox)item.FindControl("whatever");
if (checkBox.Checked)
{ /* do something */ }
}
}
</code></pre>
<ul>
<li>Many people are tempted to 'safe cast' using the <code>as</code> operator with <code>FindControl()</code>. I don't like that because when you change the control name on the form, you can silently ignore a development error and make it harder to track down. I try to only use the <code>as</code> operator if the control isn't guaranteed to be there.</li>
</ul>
<p>Update for: <em>Which CheckBox is which?</em> In the rendered html you'll end up having all these checkbox name like</p>
<pre><code>ctl00_cph0_ParentContainer_MyRepeater_ctl01_MyCheckbox
ctl00_cph0_ParentContainer_MyRepeater_ctl02_MyCheckbox
ctl00_cph0_ParentContainer_MyRepeater_ctl03_MyCheckbox
</code></pre>
<p>You don't care what the names are because the foreach item.FindControl() gets them for you, and you shouldn't assume anything about them. However, when you iterate via foreach, you usually need a way to reference that back to something. Most of the time this is done by also having an asp:HiddenField control alongside each CheckBox to hold an identifier to match it back up to the correct entity. </p>
<p><em>Security note</em>: there is a security issue with using hidden fields because a hidden field can be altered in javascript; always be conscious that this value could have been modified by the user before the form was submitted. </p>
|
<p>I believe this KB gave me the best answer:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/1d04y8ss.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/1d04y8ss.aspx</a></p>
<p>to my own lack of luck, this seems to be available for the .net 4.0 version only (and I'm still stuck at 3.5 SP1).</p>
<p>quoting (bold is mine):</p>
<blockquote>
<p>When a control is inside a data-bound control that generates repeated instances of the control, ASP.NET generates <strong>UniqueID and ClientID values for each instance</strong> of the control. The UniqueID value is generated by combining the naming container's UniqueID value, the control's ID value, and a sequential number. This is the case in controls such as the DataList, <strong>Repeater</strong>, GridView, and ListView controls.</p>
<p>ASP.NET generates ClientID values in a similar manner when the ClientIDMode property is set to AutoID. This can make it difficult to reference the control in client script, because you typically cannot predict the values of the sequential numbers that are used. If you want to access data-bound controls from client script, you can <strong>set the ClientIDMode property to Predictable.</strong> This makes it easier to predict what the ClientID values will be.</p>
<p>When you set the ClientIDMode to Predictable, you can <strong>also set the ClientIDRowSuffixDataKeys property to the name of a data field that is unique</strong>, such as the primary key in a database table. This causes ASP.NET to generate a client ID that will be easier to predict and reference in client script if you can predict data key values.</p>
</blockquote>
<p>So, in version 3.5, I'm doing it using hidden fields:</p>
<pre><code> foreach (RepeaterItem item in rptClientes.Items)
{
Panel pnl = (Panel)item.FindControl("divCliente");
Control c = pnl.FindControl("hdnID");
if (c is HiddenField)
{
if (((HiddenField)c).Value == hdnClienteNome.Value)
pnl.BackColor = System.Drawing.Color.Beige;
}
}
</code></pre>
| 21,708
|
<p>I'm porting an application from Crystal Reports 8 to Crystal Reports XI in Delphi 5, using the RDC/ActiveX interface.</p>
<p>In Crystal Reports 8, I was able to bring up the crystal reports default report viewer window for a report like so:</p>
<pre><code>RptInvoicing.Destination := 0; // To: window
RptInvoicing.Action := 1; // Execute
</code></pre>
<p>However, this does not fly with CR XI. Printing and exporting I've figured out to work like this:</p>
<pre><code>crReport.PrintOut(True);
...
crReport.Export(True);
</code></pre>
<p>But I haven't been able to find anything relevant to show the default preview window. I've tried implementing my own using the report viewer component, but it has a lot of problems like locking up when resizing, freezing and crashes, so it's not a viable solution for a production app.</p>
<p>Even the official support forums weren't of help, I only got a nasty answer to go look at the manuals, which I've been through several times and can only refer to as bad. It's not every day you see such bad documentation for an enterprise product. I found nothing relevant to this in their manuals, so I'm led to think their own staff have no idea about this either.</p>
<p>So I'm hoping someone here could tell me if the default report viewer still exists in CR XI, and if it does, how to invoke it? If it doesn't, is using the report designer component really the only solution to create one?</p>
|
<p>I recently had the same problem, and <a href="https://stackoverflow.com/questions/378089/how-can-i-display-crystal-xi-reports-inside-a-delphi-2007-application#378099">described the solution here</a>. I am using Delphi 2007, but since the code involves calls to an external ActiveX DLL, it should work for you too.</p>
|
<p>I can't say anything about Delphi, but in VB we are using CRViewer ActiveX Control. Using it is straightforward - you put viewer control on form and assign RDC object to it. This is covered in CR help somewhere. (I can't look at code ATM to provide working exmples.)</p>
| 25,969
|
<p>How does one choose the size of a buffer (bytes I read from or write to socket) for the maximum throughput when implementing a low-level HTTP and FTP transfer? My application should transfer data with HTTP or FTP on connections varying from 130 Kbps to 3 Mbps (I know the expected speed beforehand). Sometimes it's a one way transfer, sometimes it goes in both directions. Should I stick with some average buffer size or I must vary it depending on the connection speed?</p>
<p>Thanks.</p>
|
<p>Choose a buffer size over 8KB. 9000 is typically the largest MTU (maximum transmission unit) size used in even the fastest networks. </p>
<p>When you use a buffer larger than the MTU of the connection, the operating system will break it down in to MTU sized pieces as needed, and thus anything you use over the MTU will have little effect on network performance. </p>
<p>However, using a large buffer will likely have other effect on performance, if you're transferring files, then using large buffers may increase the read performance, thus improving the speed of your application.</p>
<p>So, Usually picking a nice round number like 16KB is a good idea. Definitely don't go under 1500, as this can negatively effect network performance (causing the operating system to sometimes send small packets, which decrease performance on the network).</p>
|
<p>You can get buffer size: httpSocket.getReceiveBufferSize();
I highly recommend writing this buffer to RAM in the process of reading.
For example: ByteArrayOutputStream memoryFile.
and only after filling the buffer write it to disk.</p>
| 35,778
|
<p>I recently installed a SKR 1.3 Board with a 3DTouch-Probe on my Creality Ender 3 Pro.
The probe works, <code>G29</code> does its magic, but:</p>
<p>If i issue a plain <code>G28</code>, the hotend first homes X and Y like before the Z-probe.
The probe is now next to, not above, the bed.
As the next step, the printer is supposed to home the Z-axis. The probe deploys and Z starts to lower until it smashes into the bed, because the probe misses the bed (if I don't stop it, that is).</p>
<p>I configured X/Y offsets for the probe, but they don't seem to be honored when performing the <code>G28</code> code.</p>
<p>If I home X/Y "manually" with <code>G28 X Y</code>, move the hotend with like <code>G1 X45 Y10</code>, then home Z with <code>G28 Z</code> it works fine.</p>
<p>What did I miss? Is this intended behaviour & the user has to take care never to issue a plain <code>G28</code>?!</p>
|
<p>You need to enable the constant <code>Z_SAFE_HOMING</code> (like: <code>#define Z_SAFE_HOMING</code>) in your <a href="https://github.com/MarlinFirmware/Marlin/blob/1.1.x/Marlin/Configuration.h" rel="nofollow noreferrer">printer configuration file</a> (if you're using Marlin firmware that is). This will move the nozzle to the middle of the plate prior to lowering the nozzle by default:</p>
<pre><code>#if ENABLED(Z_SAFE_HOMING)
#define Z_SAFE_HOMING_X_POINT ((X_BED_SIZE) / 2) // X point for Z homing when homing all axes (G28).
#define Z_SAFE_HOMING_Y_POINT ((Y_BED_SIZE) / 2) // Y point for Z homing when homing all axes (G28).
#endif
</code></pre>
|
<p>Use <code>Z Safe Homing</code> to avoid homing with a Z probe outside the bed area</p>
<p>According to Marlin firmware with this feature enabled:</p>
<ul>
<li>Allow Z homing only after X and Y homing AND stepper drivers still
enabled.</li>
<li>If stepper drivers time out, it will need X and Y homing again before Z homing.</li>
<li>Move the Z probe (or nozzle) to a defined XY point before Z Homing when homing all axes (G28).</li>
<li>Prevent Z homing when the Z probe is outside the bed area.</li>
</ul>
<p>To Enable Z SAFE HOMING, In the <code>configuration.h</code> file search (Ctrl+F) for <code>#define Z_SAFE_HOMING</code>. By default, it will be disabled to enable it just uncomment
the line</p>
<p><a href="https://i.stack.imgur.com/5KfmU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5KfmU.png" alt="enter image description here"></a></p>
| 1,479
|
<p>Take the following snippet:</p>
<pre><code>List<int> distances = new List<int>();
</code></pre>
<p>Was the redundancy intended by the language designers? If so, why?</p>
|
<p>The reason the code appears to be redundant is because, to a novice programmer, it appears to be defining the same thing twice. But this is not what the code is doing. It is defining two separate things that just happen to be of the same type. It is defining the following:</p>
<ol>
<li>A variable named distances of type <code>List<int></code>. </li>
<li>An object on the heap of type <code>List<int></code>.</li>
</ol>
<p>Consider the following:</p>
<pre><code>Person[] coworkers = new Employee[20];
</code></pre>
<p>Here the non-redundancy is clearer, because the variable and the allocated object are of two different types (a situation that is legal if the object’s type derives from or implements the variable’s type).</p>
|
<p>Because we're addicted to compilers and compiler errors.</p>
| 16,626
|
<p>I'm wanting to capture my search terms and pass them to a JavaScript variable, but I don't know how to handle quotes that might come through.</p>
<p>Here's what I have currently:</p>
<pre><code>var searchTerms = "<!--#echo var="terms"-->";
var pattern = / /g;
newSearchTerms = searchTerms.replace(/[^a-zA-Z 0-9]+/g,'');
var searchStr=newSearchTerms.replace(pattern,"_");
</code></pre>
<p>I'm concerned that should "terms" contain double quotes (or an apostrophy if I use single quotes in the JS) then my function will fail.</p>
<p>How do I escape the string before it gets into script?</p>
<p>Thanks,<br />
Steve</p>
<hr>
<p>Edit/answer: I ended up doing this by moving this to an external script that captured and parsed the querystring rather than echoing it in the HTML.</p>
|
<p>If <code>terms</code> contains quotation marks, by the time you have done <code>var searchTerms = "<!--#echo var="terms"-->";</code> it is already too late to replace any quotation marks, your JavaScript will be invalid. For example, if <code>terms</code> contains <strong>These are the "terms"</strong> your JavaScript would appear as follows (and produce a syntax error in the browser):</p>
<pre><code>var searchTerms = "These are the "terms"";
</code></pre>
<p>If you are sure <code>terms</code> only contains double-quotes, you could do:</p>
<p><code>var searchTerms = '<!--#echo var="terms"-->';</code></p>
<p>If it could contain both single-quotes and double-quotes, you need to sanitize the output on the server using a server-side technology more sophisticated than <code><!--#echo var="..."--></code>.</p>
|
<p>i would add a javascript to the onchange event for the search textbox. capture the keystroke and ignore the quotes and any other special characters that might be entered. if the input is coming from the server side, then sanitize it before sending it to your script. </p>
| 49,627
|
<p>On Fedora Core 7, I'm writing some code that relies on <code>ARG_MAX</code>. However, even if I <code>#include <limits.h></code>, the constant is still not defined. My investigations show that it's present in <code><sys/linux/limits.h></code>, but this is supposed to be portable across Win32/Mac/Linux, so directly including it isn't an option. What's going on here?</p>
|
<p>The reason it's not in limits.h is that it's not a quantity giving the limits of the value range of an integral type based on bit width on the current architecture. That's the role assigned to limits.h by the ISO standard.</p>
<p>The value in which you're interested is not hardware-bound in practice and can vary from platform to platform and perhaps system build to system build.</p>
<p>The correct thing to do is to call <code>sysconf</code> and ask it for "ARG_MAX" or "_POSIX_ARG_MAX". I <em>think</em> that's the POSIX-compliant solution anyway.</p>
<p>Acc. to my documentation, you include one or both of unistd.h or limits.h based on what values you're requesting.</p>
<p>One other point: many implementations of the exec family of functions return E2BIG or a similar value if you try to call them with an oversized environment. This is one of the defined conditions under which exec can actually return.</p>
|
<p>ARG_MAX is defined in /usr/include/linux/limits.h. My linux kernel version is 3.2.0-38.</p>
| 6,890
|
<p>On some websites or forums I usually go to, entries that I havn't read yet are marked as "new". I would like to implement this feature on a website I have developed (with news being posted from time to time) -- php/mySQL. How is this usually done ? Does it require using a cookie remembering the last visit date/time ? Or the last viewed posts/urls ? How can I identify the users ?</p>
|
<p>Cookies are just one possible way of identifying the user for the session, or between visits for those without authentication. Though a very common and useful way. (PHP can also use the sid or another parameter, though its not common anymore.)</p>
<p>You need to store either which threads/posts the user have read, or which he/she has not. You can sum things up with read everything before 'date' or postId for certain subforums. </p>
<p>This all depends on the lay out of your forums, posts and news, and how dynamic they are. You might also only want to show new posts since last visit, show new posts while the user is currently at your site, then use the new posts since last visit if the user is away for more then a predefined (x hours)/calculated (y hours if weekend, z hours if admin) time. </p>
<p>Edit: CSS for visited links will not help you with new comments for news, new posts in a thread, go directly to the first unread post or accessing the site at work/school and home.</p>
|
<p>Cookie is about the only reliable way to do this type of thing.</p>
<p>I'd use a cookie to store when a user last visited, but also have a reasonable default of say 1 week if the cookie doesn't exist.</p>
<p>Then show new against things newer than that date.</p>
| 40,969
|
<p>I like to use Emacs' shell mode, but it has a few deficiencies. One of those is that it's not smart enough to open a new buffer when a shell command tries to invoke an editor. For example with the environment variable <code>VISUAL</code> set to <code>vim</code> I get the following from <code>svn propedit</code>:</p>
<pre>
$ svn propedit svn:externals .
"svn-prop.tmp" 2L, 149C[1;1H
~ [4;1H~ [5;1H~ [6;1H~ [7;1H~
...
</pre>
<p>(It may be hard to tell from the representation, but it's a horrible, ugly mess.)</p>
<p>With <code>VISUAL</code> set to <code>"emacs -nw"</code>, I get</p>
<pre>
$ svn propedit svn:externals .
emacs: Terminal type "dumb" is not powerful enough to run Emacs.
It lacks the ability to position the cursor.
If that is not the actual type of terminal you have,
use the Bourne shell command `TERM=... export TERM' (C-shell:
`setenv TERM ...') to specify the correct type. It may be necessary
to do `unset TERMINFO' (C-shell: `unsetenv TERMINFO') as well.svn: system('emacs -nw svn-prop.tmp') returned 256
</pre>
<p>(It works with <code>VISUAL</code> set to just <code>emacs</code>, but only from inside an Emacs X window, not inside a terminal session.)</p>
<p>Is there a way to get shell mode to do the right thing here and open up a new buffer on behalf of the command line process?</p>
|
<p>You can attach to an Emacs session through <code>emacsclient</code>. First, start the emacs server with </p>
<pre><code>M-x server-start
</code></pre>
<p>or add <code>(server-start)</code> to your <code>.emacs</code>. Then,</p>
<pre><code>export VISUAL=emacsclient
</code></pre>
<p>Edit away.</p>
<p>Note:</p>
<ul>
<li>The versions of <code>emacs</code> and <code>emacsclient</code> must agree. If you have multiple versions of Emacs installed, make sure you invoke the version of <code>emacsclient</code> corresponding to the version of Emacs running the server.</li>
<li>If you start the server in multiple Emacs processes/frames (e.g., because <code>(server-start)</code> is in your <code>.emacs</code>), the buffer will be created in the last frame to start the server.</li>
</ul>
|
<p>Not entirely true. <code>ansi-term</code> can run an emacs fine (although I usually run mg for commit logs, in the rare event I don't commit from emacs directly). <code>eshell</code> can also run an emacs if you start a <code>screen</code> first and run it from within there.</p>
| 14,197
|
<p>I have one java program that has to be compiled as 1.4, and another program that could be anything (so, 1.4 or 1.6), and the two need to pass serialized objects back and forth. If I define a serializable class in a place where both programs can see it, will java's serialization still work, or do I need 1.6-1.6 or 1.4-1.4 only?</p>
|
<p>Make sure the classes to be serialized define and assign a value to <code>static final long serialVersionUID</code> and you should be ok.</p>
<p>That said, normally I would not do this. My preference is to only use normal serialization either within a single process, or between two processes are on the same machine and getting the serialized classes out of the same jar file. If that's not the case, serializing to XML is the better and safer choice.</p>
|
<p>If both sides uses the same jar file, it will work most of the times. However if you use different versions of the same package/module/framework ( for instance different weblogic jars or extended usage of some "rare" exceptions ) a lot of integration test is needed before it can be approved. </p>
| 41,197
|
<p>Using the instructions from <a href="http://blogs.msdn.com/pajohn/archive/2008/06/18/web-widgets-with-net-part-one.aspx" rel="nofollow noreferrer">Paul Johnson's Web Widgets</a> page I created my own custom widget. However because I was deploying to IIS 6.0 I utilized the <a href="http://blogs.msdn.com/pajohn/archive/2008/06/18/web-widgets-with-net-part-one.aspx#8998840" rel="nofollow noreferrer">web.config change recommended</a> to render the page since the IIS 7.0 configuration management option was not available in IIS 6.0. </p>
<p>The widget renders correctly when debugging with VS 2008. However once the files and the updated web.config are deployed to the Windows 2003 Server running IIS 6.0 and the address referenced the error rendered is "The page cannot be found".</p>
<p>The development machine is a Windows Vista machine, however since VS 2008 uses its own internal web server and not Vista's IIS 7.0 for debugging I did not believe this would have been an issue.</p>
<p>Any help debugging this issue would be much appreciated.</p>
|
<p>His instructions are incomplete. You will also need to add a script mapping in the application configuration for .jss to the aspnet_isapi.dll in windows\microsoft.NET\framework\vXXXX\ directory.</p>
<p>IIS6 doesn't do the intergrated pipeline that is intrinsic to Cassini and is default in IIS7.</p>
<p><strong>Edit</strong>: Details</p>
<ul>
<li>In IIS manager open application properties.</li>
<li>Select Home Directory tab</li>
<li>Click Configuration...</li>
<li>Select entry in mappings list for .aspx, click Edit...</li>
<li>Highlight and copy contents of Executable text box, click Cancel</li>
<li>Click Add...</li>
<li>Paste into Executable text box</li>
<li>Enter .jss in Extension text box</li>
<li>Enter GET. HEAD in Limit to: box</li>
<li>You might need to disable Verify that file exists</li>
</ul>
<p>Ok that lot out.</p>
<p>Now a URL that has the extension .jss will be handed over to ASP.NET for handling.</p>
|
<p>A couple of other changes I had to make...</p>
<p>Config change (handler should map to EventsWidget, not WidgetBase):</p>
<pre><code><system.web>
<httpHandlers>
<add verb="GET,HEAD" path="eventswidget.jss" type="Demo1.Handlers.EventsWidget, Demo1" validate="false" />
</httpHandlers>
</system.web>
</code></pre>
<p>EventsWidget.BuildOutput should return Javascript (depending on how you set the 'script' tag in Default.aspx):</p>
<pre><code>Public Overrides Function BuildOutput() As String
Dim sOutput As String = "document.write('<br><b>Hello World</b>');"
Return sOutput
End Function
</code></pre>
| 45,609
|
<p>I have an object that can build itself from an XML string, and write itself out to an XML string. I'd like to write a unit test to test round tripping through XML, but I'm having trouble comparing the two XML versions. Whitespace and attribute order seem to be the issues. Any suggestions for how to do this? This is in Python, and I'm using ElementTree (not that that really matters here since I'm just dealing with XML in strings at this level).</p>
|
<p>First normalize 2 XML, then you can compare them. I've used the following using lxml</p>
<pre><code>obj1 = objectify.fromstring(expect)
expect = etree.tostring(obj1)
obj2 = objectify.fromstring(xml)
result = etree.tostring(obj2)
self.assertEquals(expect, result)
</code></pre>
|
<p>The Java component <code>dbUnit</code> does a lot of XML comparisons, so you might find it useful to look at their approach (especially to find any gotchas that they may have already addressed).</p>
| 41,653
|
<p>Is it possible to post a description/comment variable to the facebook sharer url? It's only possible for url and title as far as I can figure out.</p>
|
<p>The parameters that you can pass to the actual <code>sharer.php</code> are "u" and "t" which are <code>url</code> and <code>title</code>. You can add <code>meta</code> tags to your page to get more info to appear in the sharer. To quote the <a href="http://www.facebook.com/share_partners.php" rel="nofollow noreferrer">docs</a> (make sure you click the advance partners link):</p>
<blockquote>
<p>In order to make sure that the preview
is always correctly populated, you
should add the tags shown below to
your html. An example news story could
have the following: </p>
<pre class="lang-html prettyprint-override"><code><meta name="title"
content="Smith hails 'unique' Wable legacy">
<meta name="description"
content="John Smith claims beautiful football ..." />
<link rel="image_src"
href="http://www.onjd.com/design05/images/PH2/WableAFC205.jpg" />
</code></pre>
<p>As shown, title contains the preview
title, description contains the
preview summary and image_src contains
the preview image. Please make sure
that none of the content fields
contain any html markup because it
will be stripped out. For
consistency's sake, please use the
<meta> tag to provide text data for
the preview, and the <link> tag for
any source urls.</p>
<p>The title and summary tags are the
minimum requirements for any preview,
so make sure to include these two.</p>
</blockquote>
|
<p>Facebook sharer use the description <code>meta</code> tag to add a description in your post for the pictures. I don't really know how it works but I think it uses this tag in your header:</p>
<pre class="lang-html prettyprint-override"><code><link rel='image_src' href='http://www.yourwebsite/dir1/dir2/picture.jpg' />
</code></pre>
| 46,043
|
<p>I have a strange problem on a PeopleSoft application. It appears that integration broker messages are being processed out of order. There is another possibility, and that is that the commit is being fired asynchronously, allowing the transactions to complete out of order.</p>
<p>There are many inserts of detail records, followed by a trailer record which performs an update on the rows just inserted. Some of the rows are not receiving the update. This problem is sporadic, about once every 6 months, but it causes statistically significant financial reporting errors.</p>
<p>I am hoping that someone has had enough dealings with the internals of PeopleTools to know what it is up to, so that perhaps I can find a work around to the problem.</p>
|
<p>You don't mentioned whether you've set this or not, but you have a choice with Integration Broker. All messages flow through message channels, and a channel can either be ordered or unordered. If a channel is ordered then - if a message errors - all subsequent messages queue up behind it and will not be processed until it succeeds. </p>
<p>Whether a channel is ordered or not depends upon the checkbox on the message channel properties in Application Designer. From memory channels are ordered by default, but you can uncheck the box to increase throughput.</p>
<p>Hope this helps. </p>
<p>PS. As of Tools 8.49 the setup changed slightly, Channels became Queues, Messages Service Operations etc.</p>
|
<p>I heard from GSC. We had two domains on the sending end as well as two domains on the receiving end. All were active. According to them, it is possible when you have multiple domains for each of the servers to pick up some of the messages in the group, and therefore, process them asynchronously, rather than truly serially.</p>
<p>We are going to reduce the active servers to one, and see it it happens again, but it is so sporadic that we may never know for sure.</p>
| 12,781
|
<p>Is there a name meaning "not a singleton"?</p>
|
<p>Castle Windsor uses the term "transient" to describe all non-Singleton objects.</p>
<p>I personally prefer the term "non-Singleton" though.</p>
|
<p>Simply, a 'Single Instance of a Class.'</p>
| 28,851
|
<p>Hopefully this won't be taken as asking the same question twice...</p>
<p>So I'm working on a Flash website (in AS2) which has an outer index swf which loads sub swf files using <code>loadMovie("subfoo1.swf", placeToShowSwf)</code>. These in turn load an xml file which tells it what content to load. Everything works peachy, but we'd like to add a button to the index swf that opens a sub swf file with one or two different values for one or two variables.</p>
<p>Unfortunately, just adding a button that says</p>
<pre><code>loadMovie("foo1.swf", placeToShowSwf);
placeToShowSwf.openProject(x);
</code></pre>
<p>doesn't work, I assume because <code>openProject(x)</code> is called on a file that isn't fully loaded. I know that there's not a problem with the code, because I made a button elsewhere that only calls <code>placeToShowSwf.openProject(x)</code> and there aren't any problems. </p>
<p>I see two solutions, both of which I'm unsure how to do.</p>
<ol>
<li>Change the desired value when the swf file is made, like a constructor for a class. But is there some sort of constructor function for swf files? It'd be really nice just to say <code>loadMovie(new foo1.swf(x), placeToShowSwf)</code> or something equivalent.</li>
<li>Wait until after swf (and probably xml) is loaded, and then call <code>placeToShowSwf.openProject(x)</code>. </li>
</ol>
<p>Anyone got any guidance towards either of these solutions, or perhaps some other way that my pea-like brain has been unable to fathom?</p>
|
<p>If you're not using <code>ConfigurationManager</code> to manage your application and user settings, you should be. The configuration toolkit in the .NET Framework is remarkably well thought out, and the Visual Studio tools that interoperate with it are too. </p>
<p>The default behavior of <code>ConfigurationManager</code> puts both invariant (application) and modifiable (user) settings in the right places: the application settings go in the application folder, and the user settings go in <code>System.Environment.SpecialFolder.LocalApplicationData</code>. It works properly under all versions of Windows that support .NET.</p>
<p>As for log files, <code>System.Environment.SpecialFolder.LocalApplicationData</code> is generally the place that you want to put them, because it's guaranteed to be user-writeable. </p>
<p>There are certainly cases where you wouldn't - for instance, if you want to write files to a network share so that you easily can access them remotely. There's a pretty wide range of ways to implement that, but most of them start with creating an application setting that contains the path to the shared folder. All of them involve administration.</p>
<p>I have a couple of complaints about <code>ConfigurationManager</code> and the VS tools: there needs to be better high-level documentation than there is, and better documentation of the VS-generated <code>Settings</code> class. The mechanism by which the <code>app.config</code> file turns into the application configuration file in the target build directory is opaque (and the source of one of the most frequently asked questions of all: "what happened to my connection string?"). And if there's a way of creating settings that don't have default values, I haven't found it.</p>
|
<p>I use the <strong>Isolation Storage</strong> for configuration. You can also use the <strong>Temp</strong> folder to store temporary information like log.</p>
| 33,916
|
<p>Does anyone know a way to convert from VB6 code to C#?</p>
<p>Is there a tool that can do this for me?</p>
<p>Is there any migration process that I can follow to do this?</p>
|
<p>VisualStudio offers (or at least offered) a wizard to do a conversion from VB6 to VB.NET (which could then be converted to C# with a bit of work, possibly helped by #develop's VB.NET <-> C# converter), but when last I used it, for anything non-trivial there was a lot of manual work needing to be done so I suspect you're probably better rewriting or porting by hand if this is a large and/or important application.</p>
|
<p>At GreatMigrations, we do this by hand -- we use our hands to develop a VB6/COM compiler. The compiler reads a VBP (or group of related VBPs) and referenced COM libraries and constructs a "semantic model". This model is an extremely detailed set of symbol tables and opcode streams that fully and accurately describe all information structures defined and operations performed by the source system. </p>
<p>The tool then applies a series of algorithms that modify and restructure the model to make it more compatible with .NET and optionally applies custom transformations; for example to replace COM components with .NET classes. The transformation rules are designed by people and created "by hand" to meet their unique requirements.</p>
<p>Finally, the model is "executed" but instead of allocating the data model and executing the operations, we author the file structures, data model, and operations in the notation of the target platform. We can author both VB.NET and C# using this approach. We also use this process to migrate ASP sites to ASPX, (we also have a multi-dialect FORTRAN-to-C product)</p>
<p>The approach does not produce production ready software on the first try, but it can be improved and made to produce "better" software by modifying the configuration of the tool and re-running the translation process. The advantage of our tool is its repeatability, speed, and flexibility which facilitates an agile tool-assisted-rewrite methodology. IMO, migration teams that leverage our approach will benefit from allocating a lot more resources to evaluating alternatives for redesign, and development process improvements rather than to re-gathering functional requirements, hand coding, and testing. They will ultimately enjoy a more maintainable system and a much more faithful reproduction of the original application functionality after the migration as well as greater control and visibility during the migration.</p>
<p>A trial edition of our tool is available here <a href="http://www.greatmigrations.com/resources_gmStudio_demo.aspx" rel="nofollow noreferrer">gmStudio Trail Request Download</a>. It will allow you to experiment with ASP/VB codes up to 10K LOC and runs for up to 30 sessions. </p>
| 21,663
|
<p>If you were allowed to add another coding guideline to the 101 guidelines of the <a href="http://www.gotw.ca/publications/c++cs.htm" rel="noreferrer">"C++ coding standards" (Herb Sutter and Andrei Alexandrescu)</a>, which would you add?</p>
|
<p>Write for a year later.</p>
|
<p>Rule 102: Any change to expected functionality should result in a regression test that fails.</p>
| 26,483
|
<p>Clicking through to the download-page if see that the last version of the download is <strong>over one year old</strong> and it's also "just" a <strong>Release Candidate</strong> of version 1.0. There are really no news on any development.</p>
<p>Yes, you can find newer versions from the nightly builds, but that's not a real serious option.</p>
<p>Also, the "getting-started" and description-pages are sometimes not even started and some not completed.</p>
<p>What's the deal? Any C# 3.0 features on the way or what?</p>
|
<p>I'd suggest PNG. Most software supports writing it, most libraries support reading it, it's lossless and supports alpha transparency. And it's a standard format.</p>
<p>And, maybe important for hobbyist 2D games, very small images also result in very small files (i.e. a 16x16 icon can be 1KB or less).</p>
|
<p>PNG does NOT support alpha transparency, it has a translucency channel, which is different. This can lead to problems depending on how you are rendering sprites to the screen. TGA, hands down.</p>
| 17,576
|
<p>Say I want to copy the contents of a directory excluding files and folders whose names contain the word 'Music'.</p>
<pre><code>cp [exclude-matches] *Music* /target_directory
</code></pre>
<p>What should go in place of [exclude-matches] to accomplish this?</p>
|
<p>In Bash you can do it by enabling the <code>extglob</code> option, like this (replace <code>ls</code> with <code>cp</code> and add the target directory, of course)</p>
<pre><code>~/foobar> shopt extglob
extglob off
~/foobar> ls
abar afoo bbar bfoo
~/foobar> ls !(b*)
-bash: !: event not found
~/foobar> shopt -s extglob # Enables extglob
~/foobar> ls !(b*)
abar afoo
~/foobar> ls !(a*)
bbar bfoo
~/foobar> ls !(*foo)
abar bbar
</code></pre>
<p>You can later disable extglob with</p>
<pre><code>shopt -u extglob
</code></pre>
|
<p>this would do it excluding exactly 'Music'</p>
<pre><code>cp -a ^'Music' /target
</code></pre>
<p>this and that for excluding things like Music?* or *?Music</p>
<pre><code>cp -a ^\*?'complete' /target
cp -a ^'complete'?\* /target
</code></pre>
| 26,676
|
<p>I'm trying to develop some SharePoint workflows for the company I work for, and I'm not too familiar with the ins and outs of the technology. Normally when I want to familiarize myself with something, I just play with it, look at the properties, find all the methods, etc. </p>
<p>When I fire up Visual Studio and try to create a SharePoint workflow, it gives me an error indicating I don't have a reference to "Microsoft.SharePoint.dll". Someone told me that it was normal to see that because you have to do all your development on the SharePoint Server itself if you want to do workflows. Is this true?</p>
<p>If so, is there anyone out there that has successfully developed SharePoint workflows in a multi-developer environment without resorting to any "hacks"?? Thank you for reading and your responses...</p>
|
<p>If you want to create a Sharepoint workflow using the Sharepoint Templates, you need to have a Windows 2003 or 2008 Server running Sharepoint. Essentially, that is true for all Sharepoint development: For it to be really efficient, you <strong>need</strong> to run Visual Studio on a Sharepoint Server. This in turn means that every developer needs his own Sharepoint server and then you have one additional "Staging"-Server where you deploy and test your combined solutions. Suddenly, that MSDN Subscription looks very attractive :-)</p>
<p>As for your Workflow learning question: I can highly recommend "<a href="http://www.apress.com/book/view/1590597001" rel="nofollow noreferrer">Workflow in the 2007 Microsoft Office System</a>" by Apress.</p>
|
<p>While it's true you need SharePoint installed on your development computer for most SharePoint development, you can get away without it for workflow development. Follow these steps:</p>
<ul>
<li>Copy the SharePoint DLLs to your development computer (for workflow you'll need microsoft.sharepoint.WorkflowActions.dll).</li>
<li>Open Visual Studio and open the Toolbox tab</li>
<li>Add a new tab (call it SharePoint Workflow Items)</li>
<li>In the new tab, click "Add Items"</li>
<li>Click the "Activities" tab </li>
<li>Locate and add microsoft.sharepoint.WorkflowActions.dll </li>
<li>You'll see a few new tasks show up and already selected.</li>
</ul>
<p>Once you do this, you'll be able to develop WF workflows that can use SharePoint-specific tasks. Deployment and testing the workflow is another task altogether.</p>
| 38,465
|
<p>I created a Web site in VS2008. I'm wondering if I should have created it as a project instead and, if so, can it be converted? Any advantages/disadvantages to either approach?</p>
<p>TIA</p>
|
<p>This may sound a bit obvious, but I think it's something that is misunderstood because VS2005 only shipped with the web site originally. If your project deals with a website that is fairly limited and doesn't have a lot of logical or physical separation, the website is fine. However if it is truly a web application with different modules where many users add and update data, you are better off with the web application.</p>
<p>The biggest pro of the website model is that anything in the app_code section is dynamically compiled. You can make cs file updates without a full redeploy. However this comes at a great sacrifice. A lot of things happen under the covers that are difficult to control. Namespaces are difficult to control and specific dll usage goes out the window by default for anything under app_code since everything is dynamically compiled.</p>
<p>The web application model does not have dynamic compilation, but you gain control over the things that I have mentioned. </p>
<p>If you are doing nTier development, I highly recommend the web application model. If you are doing a limited web site or a quick and dirty implementation, the web site model make have advantages. </p>
<p>More detailed analysis can be found here:<br>
<a href="http://west-wind.com/weblog/posts/5601.aspx" rel="nofollow noreferrer">http://west-wind.com/weblog/posts/5601.aspx</a><br>
<a href="http://blogs.vertigo.com/personal/swarren/Blog/Lists/Posts/Post.aspx?ID=10" rel="nofollow noreferrer">http://blogs.vertigo.com/personal/swarren/Blog/Lists/Posts/Post.aspx?ID=10</a></p>
|
<p>There's some information on an old blog post of mine about the differences between the Web Site and Web Application project - <a href="http://www.aaron-powell.com/blog.aspx?id=1126" rel="nofollow noreferrer">http://www.aaron-powell.com/blog.aspx?id=1126</a></p>
<p>Personally i always use/ convert existing projects to Web Applications as I find them a lot more powerful and configuravle.</p>
| 45,346
|
<p>I have an Eclipse RCP application that displays a lot (10k+) of small images next to each other, like a film strip. For each image, I am using a SWT <code>Image</code> object. This uses an excessive amount of memory and resources. I am looking for a more efficient way. I thought of taking all of these images and concatenating them by creating an <code>ImageData</code> object of the proper total, concatenated width (with a constant height) and using <code>setPixel()</code> for the rest of the pixels. However, the <code>Palette</code> used in the <code>ImageData</code> constructor I can't figure out.</p>
<p>I also searched for SWT tiling or mosaic functionality to create one image from a group of images, but found nothing.</p>
<p>Any ideas how I can display thousands of small images next to each other efficiently? Please note that once the images are displayed, they are not manipulated, so this is a one-time cost.</p>
|
<p>You can draw directly on the GC (graphics context) of a new (big) image. Having one big Image should result in much less resource usage than thousands of smaller images (each image in SWT keeps some OS graphics object handle)</p>
<p>What you can try is something like this:</p>
<pre><code> final List<Image> images;
final Image bigImage = new Image(Display.getCurrent(), combinedWidth, height);
final GC gc = new GC(bigImage);
//loop thru all the images while increasing x as necessary:
int x = 0;
int y = 0;
for (Image curImage : images) {
gc.drawImage(curImage, x, y);
x += curImage.getBounds().width;
}
//very important to dispose GC!!!
gc.dispose();
//now you can use bigImage
</code></pre>
|
<p>Presumably not every image is visible on screen at any one time? Perhaps a better solution would be to only load the images when they become (or are about to become) visible, disposing of them when they have been scrolled off the screen. Obviously you'd want to keep a few in memory on either side of the current viewport in order to make a smooth transition for the user.</p>
| 34,488
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.