instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p><strong>Premise:</strong>
Usually during preparation of a new Ruby on Rails App, I draw out models and relations regarding user navigations. Usually I hit a place where I need to ask myself, whether or not I should go beyond the usual "rule of thumb" of nesting no more 1 level deep. Sometimes I feel the need to nest, rather than creating another namespace route and duplicating work.
<br/>Here's an example:<br/></p>
<p><strong>Models:</strong> User, Company, Location <br/>
User has and belongs to many Companies (many to many) <br/>
User has and belongs to many Locations (many to many) <br/>
Company has and belongs to many Locations (many to many) <br/></p>
<p><strong>Routes:</strong><br/>
<strong><em>1 level nesting</em></strong> <br/>
users/:user_id/companies/ - list all companies related to a user<br/>
users/:user_id/locations/ - list all locations related to a user<br/>
<strong><em>more than 1 level nesting</em></strong><br/>
users/:user_id/companies/:company_id/locations/ - list all company-locations of a user</p>
<p><strong>So, my question is whether or not it is appropriate to nest more than 1 level deep in RoR? Yes or no? And why?</strong></p>
|
<p>I tend to follow Jamis Buck's <a href="http://weblog.jamisbuck.org/2007/2/5/nesting-resources" rel="nofollow noreferrer">advice</a> and never nest more than one level deep.</p>
<p>Edit:
If you are going to nest more than 1 level I would check out the new <a href="http://ryandaigle.com/articles/2008/9/7/what-s-new-in-edge-rails-shallow-routes" rel="nofollow noreferrer">shallow routes</a> feature in Edge</p>
|
<p>Whilst it sounds good in theory, I've found nesting more than one level can start to get confusing - particularly if you have the same named controller at different levels (which can be quite common)</p>
<p>Eg</p>
<pre><code> user/x/blog/y/profile/z, and
user/x/profile/a
</code></pre>
<p>I'll often find I'm working in a different namespace to what I think I'm working in. If they do similar, but different things, it can get quite confusing =)</p>
<p>My current app, I went thru last week and removed most of the nested routes.
(Of course, YMMV)</p>
| 19,889
|
<p>I want to get my databases under version control.</p>
<p>I'll always want to have at least <em>some</em> data in there (as <a href="https://stackoverflow.com/users/80/alumb">alumb</a> mentions: user types and administrators). I'll also often want a large collection of generated test data for performance measurements.</p>
<p>How would I apply version control to my database?</p>
|
<p>Martin Fowler wrote my favorite article on the subject, <a href="http://martinfowler.com/articles/evodb.html" rel="noreferrer">http://martinfowler.com/articles/evodb.html</a>. I choose not to put schema dumps in under version control as <em>alumb</em> and others suggest because I want an easy way to upgrade my production database.</p>
<p>For a web application where I'll have a single production database instance, I use two techniques:</p>
<h1>Database Upgrade Scripts</h1>
<p>A sequence database upgrade scripts that contain the DDL necessary to move the schema from version N to N+1. (These go in your version control system.) A _version_history_ table, something like</p>
<pre><code>create table VersionHistory (
Version int primary key,
UpgradeStart datetime not null,
UpgradeEnd datetime
);
</code></pre>
<p>gets a new entry every time an upgrade script runs which corresponds to the new version.</p>
<p>This ensures that it's easy to see what version of the database schema exists and that database upgrade scripts are run only once. Again, these are <strong>not</strong> database dumps. Rather, each script represents the <strong>changes</strong> necessary to move from one version to the next. They're the script that you apply to your production database to "upgrade" it.</p>
<h1>Developer Sandbox Synchronization</h1>
<ol>
<li>A script to backup, sanitize, and shrink a production database. Run this after each upgrade to the production DB.</li>
<li>A script to restore (and tweak, if necessary) the backup on a developer's workstation. Each developer runs this script after each upgrade to the production DB.</li>
</ol>
<p><em>A caveat: My automated tests run against a schema-correct but empty database, so this advice will not perfectly suit your needs.</em></p>
|
<p>An alternative to version controlling your database is to use a version-controlled database, of which there are now several.</p>
<p><a href="https://www.dolthub.com/blog/2021-09-17-database-version-control/" rel="nofollow noreferrer">https://www.dolthub.com/blog/2021-09-17-database-version-control/</a></p>
<p>These products don't apply version control on top of another type of database -- they are their own database engines that support version control operations. So you need to migrate to them or start building on them in the first place.</p>
<p>I write one of them, DoltDB, which combines the interfaces of MySQL and Git. Check it out here:</p>
<p><a href="https://github.com/dolthub/dolt" rel="nofollow noreferrer">https://github.com/dolthub/dolt</a></p>
| 2,264
|
<p>I started web programming with raw PHP, gradually moving on to its various frameworks, then to Django and Rails. In every framework I've used, pretty much everything I need to do with a database (even involving relatively complex things like many-to-many relationships) could be taken care of by the automatically generated database API without much work. Those few operations that were more complex could be done with straight SQL or by tying together multiple API calls.</p>
<p>Now I'm starting to learn Java, and it's confusing me that the language celebrated for being so robust for back-end infrastructure requires so much more code (doesn't that mean harder to maintain?) to do simple things. Example from a tutorial: say you want to search by last name. You write the method in the DAO using Hibernate query language, then you write a method in the Service to call it (couldn't that be automated?), then you call the Service method from the controller. Whereas in any other framework I've worked with, you could call something to the effect of</p>
<pre><code>Person.find_by_last_name(request.POST['last_name'])
</code></pre>
<p>Straight out of the controller - you don't have to write anything custom to do something like that.</p>
<p>Is there some kind of code generation I haven't found yet? Something in Eclipse? Just doesn't seem right to me that the language regraded as one of the best choices for complex back-ends is so much harder to work with. Is there something I'm missing?</p>
|
<p><a href="http://grails.org" rel="nofollow noreferrer">Grails</a> for the win. Groovy is very similar to Java but with a lot of nice dynamic language additions/simplifications. Grails has GORM, which is exactly what you're looking for.</p>
|
<p>Get <a href="http://ibatis.apache.org/" rel="nofollow noreferrer">iBatis</a> for Java. It isn't as robust as Django's ORM (nothing is), but it's a big, big step above JDBC.</p>
| 32,590
|
<p>What is a simple way of downloading a file from a URL path?</p>
|
<pre><code>using (var client = new WebClient())
{
client.DownloadFile("http://example.com/file/song/a.mpeg", "a.mpeg");
}
</code></pre>
|
<pre class="lang-cs prettyprint-override"><code>static void Main(string[] args)
{
DownloadFileAsync().GetAwaiter();
Console.WriteLine("File was downloaded");
Console.Read();
}
private static async Task DownloadFileAsync()
{
WebClient client = new WebClient();
await client.DownloadFileTaskAsync(new Uri("http://somesite.com/myfile.txt"), "mytxtFile.txt");
}
</code></pre>
| 39,609
|
<p>I tried scouring the web for help on this issue, but there are so many generic words in there, that I couldn't find much of anything that was relevant.</p>
<p>I have MS Office 2007 installed on Vista and later installed XML Notepad 2007 (also a Microsoft product). It seems that the MS Access help system is using some sort of XML format that XML Notepad took control of. Now, whenever I open help in Access, the little help window opens and instead of displaying content, attempts to download the content with XML Notepad. Grrr....</p>
<p>Is there a fix for this?</p>
|
<p>Okay, I found the answer and I'm a little embarrassed by it. In fact, my question was pretty much off the mark.</p>
<p>First, there is no involvement in this problem with XML Notepad 2007. It didn't hijack a file extension or make a registry entry or anything else like that. It's a great little program if you just want to open and examine an XML file. I use it kinda the same way I use notepad for text files. I just want a quick look and I don't need to weight or wait of a full ide at the moment.</p>
<p>What causes the help application to attempt to download a file called browse0.access.xml, is to be in offline mode. If you open up the table of contents, all the content is available except the home page which must require an internet connection.</p>
<p>To correct the issue, click the "offline" word in the lower right corner of the application and select "show content from Office Online". That should get it back to it's normal state.</p>
|
<p>Do a repair on your Office installation. That, or remove XMl Notepad (it's not that good imho).</p>
| 11,139
|
<p><strong>Note: Mathematical expression evaluation is not the focus of this question. I want to compile and execute new code at runtime in .NET.</strong> That being said...</p>
<p>I would like to allow the user to enter any equation, like the following, into a text box:</p>
<pre><code>x = x / 2 * 0.07914
x = x^2 / 5
</code></pre>
<p>And have that equation applied to incoming data points. The incoming data points are represented by <strong>x</strong> and each data point is processed by the user-specified equation. I did this years ago, but I didn't like the solution because it required parsing the text of the equation for every calculation:</p>
<pre><code>float ApplyEquation (string equation, float dataPoint)
{
// parse the equation string and figure out how to do the math
// lots of messy code here...
}
</code></pre>
<p>When you're processing boatloads of data points, this introduces quite a bit of overhead. I would like to be able to translate the equation into a function, on the fly, so that it only has to be parsed once. It would look something like this:</p>
<pre><code>FunctionPointer foo = ConvertEquationToCode(equation);
....
x = foo(x); // I could then apply the equation to my incoming data like this
</code></pre>
<p>Function ConvertEquationToCode would parse the equation and return a pointer to a function that applies the appropriate math.</p>
<p>The app would basically be writing new code at run time. Is this possible with .NET?</p>
|
<p>Yes! Using methods found in the <a href="http://msdn.microsoft.com/en-us/library/microsoft.csharp.aspx">Microsoft.CSharp</a>, <a href="http://msdn.microsoft.com/en-us/library/system.codedom.compiler.aspx">System.CodeDom.Compiler</a>, and <a href="http://msdn.microsoft.com/en-us/library/system.reflection.aspx">System.Reflection</a> name spaces. Here is a simple console app that compiles a class ("SomeClass") with one method ("Add42") and then allows you to invoke that method. This is a bare-bones example that I formatted down to prevent scroll bars from appearing in the code display. It is just to demonstrate compiling and using new code at run time.</p>
<pre><code>using Microsoft.CSharp;
using System;
using System.CodeDom.Compiler;
using System.Reflection;
namespace RuntimeCompilationTest {
class Program
{
static void Main(string[] args) {
string sourceCode = @"
public class SomeClass {
public int Add42 (int parameter) {
return parameter += 42;
}
}";
var compParms = new CompilerParameters{
GenerateExecutable = false,
GenerateInMemory = true
};
var csProvider = new CSharpCodeProvider();
CompilerResults compilerResults =
csProvider.CompileAssemblyFromSource(compParms, sourceCode);
object typeInstance =
compilerResults.CompiledAssembly.CreateInstance("SomeClass");
MethodInfo mi = typeInstance.GetType().GetMethod("Add42");
int methodOutput =
(int)mi.Invoke(typeInstance, new object[] { 1 });
Console.WriteLine(methodOutput);
Console.ReadLine();
}
}
}
</code></pre>
|
<p>I would do a recursive function that doesn't write code but instead applies basic operators to portions of a string based on special characters found in that string.
If more than one special character is found, it breaks up the string and calls itself on those two portions.</p>
| 28,988
|
<p>How do I display a leading zero for all numbers with less than two digits?</p>
<pre class="lang-none prettyprint-override"><code>1 → 01
10 → 10
100 → 100
</code></pre>
|
<p>In Python 2 (and Python 3) you can do:</p>
<pre><code>number = 1
print("%02d" % (number,))
</code></pre>
<p>Basically <strong>%</strong> is like <code>printf</code> or <code>sprintf</code> (see <a href="https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting" rel="noreferrer">docs</a>).</p>
<hr />
<p>For Python 3.+, the same behavior can also be achieved with <a href="https://docs.python.org/3/library/stdtypes.html#str.format" rel="noreferrer"><code>format</code></a>:</p>
<pre><code>number = 1
print("{:02d}".format(number))
</code></pre>
<hr />
<p>For Python 3.6+ the same behavior can be achieved with <a href="https://docs.python.org/3/reference/lexical_analysis.html#f-strings" rel="noreferrer">f-strings</a>:</p>
<pre><code>number = 1
print(f"{number:02d}")
</code></pre>
|
<p>If dealing with numbers that are either one or two digits:</p>
<p><code>'0'+str(number)[-2:]</code> or <code>'0{0}'.format(number)[-2:]</code></p>
| 16,342
|
<p>I have been working on a web services related project for about the last year. Our team found <a href="http://www.soapui.org" rel="noreferrer">soapUI</a> near the start of our project and we have been <em>mostly</em>(*) satisfied with it (the free version, that is).</p>
<p>My question is: are there other tools/clients/frameworks that you have used/currently use for web services testing and would recommend?</p>
<p>(*) There are some weird GUI glitches that appear once in a while. As is mentioned by some of the answers, we attributed this to a memory leak.</p>
|
<p>I use soapUI, and it's generally pretty good. Be aware that it seems to leak memory, and eventually it will no longer save your project, so save regularly!</p>
<p>This is about the only hassle I have with it (other than the general ugliness that almost every Java application has!), and I can't live without it.</p>
|
<p>We've been using SoapUI since 1.x (will soon be adopting 3.0 from 2.5.1) and are all happy.
It's much more stable when running with native LnF (File - Preferences - UI Settings - Native LF).
I know it's available as an Eclipse plugin as well, but last I tried I failed to find how to add JAR-files to it (i.e. bin/ext in the stand-alone variant).</p>
| 5,196
|
<p>I'm following several tutorials and references trying to get my kernel set up. I've come across some unfamiliar code in a tutorial that isn't explaining it at all. It's code that I'm told maps the <code>16 IRQs (0-15)</code> to ISR locations <code>32-47</code>:</p>
<pre><code>void irq_remap(void)
{
outportb(0x20, 0x11);
outportb(0xA0, 0x11);
outportb(0x21, 0x20);
outportb(0xA1, 0x28);
outportb(0x21, 0x04);
outportb(0xA1, 0x02);
outportb(0x21, 0x01);
outportb(0xA1, 0x01);
outportb(0x21, 0x0);
outportb(0xA1, 0x0);
}
</code></pre>
<p>The code for <code>outportb()</code> is as follows, but I already have a clear grasp of what its doing:</p>
<pre><code>void outPortB(unsigned short port, unsigned char data)
{
__asm__ __volatile__ ("outb %1, %0" : : "dN" (port), "a" (data));
}
</code></pre>
<p>I should mention that this is on x86 architecture in protected mode. This source code works fine and I understand what it does, but I don't understand how it does it. Can someone explain to me what's going on here, so that in case I need to expand on this I will know what I'm doing?</p>
|
<p><code>outb</code> and similar, write to hardware IO ports. Basically, there are 2 primary options for communicating with a device. You can have the device mapped to memory or IO ports.</p>
<p>As for how this code works, i'll comment it for you:</p>
<p>ICW stands for "Initialization Commands Words"</p>
<pre><code>outportb(0x20, 0x11); /* write ICW1 to PICM, we are gonna write commands to PICM */
outportb(0xA0, 0x11); /* write ICW1 to PICS, we are gonna write commands to PICS */
outportb(0x21, 0x20); /* remap PICM to 0x20 (32 decimal) */
outportb(0xA1, 0x28); /* remap PICS to 0x28 (40 decimal) */
outportb(0x21, 0x04); /* IRQ2 -> connection to slave */
outportb(0xA1, 0x02);
outportb(0x21, 0x01); /* write ICW4 to PICM, we are gonna write commands to PICM */
outportb(0xA1, 0x01); /* write ICW4 to PICS, we are gonna write commands to PICS */
outportb(0x21, 0x0); /* enable all IRQs on PICM */
outportb(0xA1, 0x0); /* enable all IRQs on PICS */
</code></pre>
<p>hope this helps</p>
<p>Welcome to the world of OS dev :) I also recommend that you visit: <a href="http://forum.osdev.org/" rel="noreferrer">http://forum.osdev.org/</a>, it is an invaluable resource for a new hobby OS developer.</p>
|
<p>The simple answer is that in protected mode the interrupts used by the 1st Programmable Interrupt Controller are protected mode exceptions, which means that they have to be remapped.</p>
<blockquote>
<p></p>
</blockquote>
<p>The happy answer is that only the first <code>PIC</code> needs to be remapped ( the remapping of the second is only for convenience since it begins at <code>int 70h</code>).
Here's a quote from the original AT BIOS.</p>
<pre><code>INTA00 equ 020h ; 8259 port
INTA01 equ 021h ; 8259 port
INTB00 equ 0A0h ; 2nd 8259
INTB01 equ 0A1h
INT_TYPE equ 070h ; start of 8259 interrupt table location
;---------------------------------------------------------
; re-initialize the 8259 interrupt #1 controller chip :
;---------------------------------------------------------
mov al, 11h ; icw1 - edge, master, icw4
out INTA00,al
jmp $+2 ; wait state for i/o
mov al, 8 ; setup icw2 - int type 8 (8-f)
out INTA01, al
jmp $+2
mov al, 4 ; setup icw3 - master lv 2
out INTA01, al
jmp $+2
mov al, 1 ; setup icw4 - master, 8086 mode
out INTA01, al
jmp $+2
mov al, 0FFh ; mask all ints. off
out INTA01, al ; (video routine enables interrupts)
;---------------------------------------------------------
; re-initialize the 8259 interrupt #2 controller chip :
;---------------------------------------------------------
mov al, 11h ; icw1 - edge, slave icw4
out INTB00, al
jmp $+2
mov al, INT_TYPE ; setup icw2 - int type 70 (70-7f)
out INTB01, al
mov al, 2 ; setup icw3 - slave lv 2
jmp $+2
out INTB01, al
jmp $+2
mov al, 1 ; setup icw4 - 8086 mode, slave
out INTB01, al
jmp $+2
mov al, 0FFh ; mask all ints. off
out INTB01, al
;--------------------------------------------------------------------------------
</code></pre>
<p>Technical Reference AT BIOS (c) 1984 IBM</p>
<p>Note:</p>
<p>The <code>jmp $+2 ; wait state for i/o</code> is not required on a current PC.</p>
<p>The <code>icw1</code> clears the interrupt mask register, which enables the interrupts on that PIC.</p>
<p>The 8259A chip is long since gone but the programming interface is still used.
<a href="http://pdos.csail.mit.edu/6.828/2005/readings/hardware/8259A.pdf" rel="nofollow noreferrer" title="8259A Programmable Interrupt Controller">8259A Programmable Interrupt Controller</a></p>
| 35,852
|
<p>My current solution for renaming the project folder is:</p>
<ul>
<li>Remove the project from the solution.</li>
<li>Rename the folder outside Visual Studio.</li>
<li>Re-add the project to the solution.</li>
</ul>
<p>Is there a better way?</p>
|
<blockquote>
<p><em>TFS users:</em> If you are using source control that requires you to warn it before your rename files/folders then look at <strong><em><a href="https://stackoverflow.com/a/10853509/10245">this answer instead</a></em></strong> which covers the extra steps required.</p>
</blockquote>
<hr>
<p>To rename a project's <strong>folder</strong>, <strong>file</strong> (<code>.*proj</code>) and <strong>display name</strong> in Visual Studio:</p>
<ul>
<li>Close the solution.</li>
<li>Rename the folder(s) outside Visual Studio. (Rename in TFS if using source control)</li>
<li>Open the solution, ignoring the warnings (answer "no" if asked to load a project from source control).</li>
<li>Go through all the <strong>unavailable</strong> projects and...
<ul>
<li>Open the <strong>properties</strong> window for the project (highlight the project and press <kbd>Alt</kbd>+<kbd>Enter</kbd> or <kbd>F4</kbd>, or right-click > properties).</li>
<li>Set the property '<strong>File Path</strong>' to the new location.
<ul>
<li>If the property is not editable (as in Visual Studio 2012), then open the <code>.sln</code> file directly in another editor such as <a href="http://en.wikipedia.org/wiki/Notepad%2B%2B" rel="noreferrer">Notepad++</a> and update the paths there instead. (You may need to check-out the solution first in TFS, etc.)</li>
</ul></li>
<li><strong>Reload</strong> the project - right-click > reload project.</li>
<li>Change the display name of the project, by highlighting it and pressing <kbd>F2</kbd>, or right-click > <strong>rename</strong>.</li>
</ul></li>
</ul>
<p><strong>Note:</strong> Other suggested solutions that involve removing and then re-adding the project to the solution will break project references.</p>
<p>If you perform these steps then you might also consider renaming the following to match:</p>
<ol>
<li>Assembly</li>
<li>Default/Root Namespace</li>
<li>Namespace of existing files (use the refactor tools in Visual Studio or <a href="https://en.wikipedia.org/wiki/JetBrains#ReSharper_Ultimate" rel="noreferrer">ReSharper's</a> inconsistent namespaces tool)</li>
</ol>
<p>Also consider modifying the values of the following <a href="http://msdn.microsoft.com/en-us/library/4w8c1y2s.aspx" rel="noreferrer">assembly attributes</a>:</p>
<ol>
<li><code>AssemblyProductAttribute</code></li>
<li><code>AssemblyDescriptionAttribute</code></li>
<li><code>AssemblyTitleAttribute</code></li>
</ol>
|
<p>Right click project → <em>Properties</em>, and set (name) to the required name.</p>
| 25,949
|
<p>I have been tasked to implement a WCF service that makes use of NetMsmqBinding. I wrote the service and it works fine. The problem is that in the last minute they told me that there will be no Active Directory integration. So I don't know how to configure the security of the service. There is a VPN tunnel between the service's and the client's machines but they do not use the same active directory. Please advice. Any kind of help or tutorials would be appreciated.</p>
<hr>
<p>The problem is that the service is not always online. That is why using WCF over MSMQ is preferred for this scenario. So I am sending one way messages through MSMQ - which works fine. My only problem is that I am new to WCF and am not familiar with WCF security. I would like to be able to sign and encrypt the messages since the information to be sent to the service is confidential. I would like to make sure that only authorized clients call the service. Any suggestions?</p>
|
<p>I'm not sure I understand your question so correct me, if I'm wrong. I have recently been woring on a WCF service that was hosted on a computer with no Active Directory available. We secured it using certificates. Is it an option for you? It's pretty painless (if you get past the 'put the certificate in the store and give the correct user access to it' part).</p>
|
<p>You should be able to take advantage of network transparency.</p>
<p>Use webservices to communicate from one system to the other. You might have to deal with extra latency, but it should still be usable.</p>
| 25,977
|
<p>Is there a way to determine the number of users that have active sessions in an ASP.NET application? I have an admin/tools page in a particular application, and I would like to display info regarding all open sessions, such as the number of sessions, and perhaps the requesting machines' addresses, or other credential information for each user.</p>
|
<p><a href="http://technet.microsoft.com/en-us/library/cc775901.aspx" rel="noreferrer">ASP.NET Performance Counters</a> like State Server Sessions Active (The number of active user sessions) should help you out. Then you can just <a href="http://www.developer.com/net/net/article.php/11087_3356561_1" rel="noreferrer">read and display the performance counters</a> from your admin page..</p>
|
<p>You can use PerformanceCounter to get data from System.Diagnostics namespace. It allows you to get "Sessions Active" and much more. It allows you to get from local server as well as remote.</p>
<p>Here is an example of how to do it on local machine</p>
<pre><code>void Main()
{
var pc = new PerformanceCounter("ASP.NET Applications", "Sessions Active", "__Total__");
Console.WriteLine(pc.NextValue());
}
</code></pre>
<p>or for remote server you would do:</p>
<pre><code>void Main()
{
var pc = new PerformanceCounter("ASP.NET Applications", "Sessions Active", "__Total__", "ServerHostName.domain");
Console.WriteLine(pc.NextValue());
}
</code></pre>
<p><a href="http://msdn.microsoft.com/en-us/library/fxk122b4.aspx" rel="nofollow">Performance Counters for ASP.NET</a> provides full list of ASP.NET counters that you can monitor</p>
| 18,821
|
<p>This originally was a problem I ran into at work, but is now something I'm just trying to solve for my own curiosity.</p>
<p>I want to find out if int 'a' contains the int 'b' in the most efficient way possible. I wrote some code, but it seems no matter what I write, parsing it into a string and then using indexOf is twice as fast as doing it mathematically.</p>
<p>Memory is not an issue (within reason), just sheer processing speed.</p>
<p>This is the code I have written to do it mathematically:</p>
<pre><code>private static int[] exponents = {10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 };
private static boolean findMatch(int a, int b) {
if (b > a) return false;
if (a == b) return true;
int needleLength = getLength(b);
int exponent = exponents[needleLength];
int subNum;
while (a >= 1) {
subNum = a % exponent;
if (subNum == b)
return true;
a /= 10;
}
return false;
}
private static int getLength(int b) {
int len = 0;
while (b >= 1) {
len++;
b /= 10;
}
return len;
}
</code></pre>
<p>Here's the string method I'm using, which seems to trump the mathematical method above:</p>
<pre><code>private static boolean findStringMatch(int a, int b) {
return String.valueOf(a).indexOf(String.valueOf(b)) != -1;
}
</code></pre>
<p>So although this isn't really required for me to complete my work, I was just wondering if anyone could think of any way to further optimize my way of doing it mathematically, or an entirely new approach altogether. Again memory is no problem, I am just shooting for sheer speed.</p>
<p>I'm really interested to see or hear anything anyone has to offer on this.</p>
<p><strong>EDIT:</strong> When I say contains I mean can be anywhere, so for example, findMatch(1234, 23) == true</p>
<p><strong>EDIT:</strong> For everyone saying that this crap is unreadable and unnecessary: you're missing the point. The point was to get to geek out on an interesting problem, not come up with an answer to be used in production code.</p>
|
<p>It <em>should</em> be faster string way, because your problem is textual, not mathematical. Notice that the your "contains" relationship says nothing about the numbers, it only says something about their <em>decimal</em> representations.</p>
<p>Notice also that the function you want to write will be unreadable - another developer will never understand what you are doing. (See what trouble you had with that here.) The string version, on the other hand, is perfectly clear.</p>
|
<p>FYI</p>
<p><a href="http://refactormycode.com/" rel="nofollow noreferrer">http://refactormycode.com/</a></p>
<p>Could work for you.</p>
| 28,710
|
<p>The code looks like below:</p>
<pre><code>namespace Test
{
public interface IMyClass
{
List<IMyClass> GetList();
}
public class MyClass : IMyClass
{
public List<IMyClass> GetList()
{
return new List<IMyClass>();
}
}
}
</code></pre>
<p>When I Run Code Analysis i get the following recommendation.</p>
<blockquote>
<p>Warning 3 CA1002 : Microsoft.Design : Change 'List' in 'IMyClass.GetList()' to use Collection, ReadOnlyCollection or KeyedCollection</p>
</blockquote>
<p>How should I fix this and what is good practice here?</p>
|
<p>To answer the "why" part of the question as to why not <a href="https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1" rel="noreferrer"><code>List<T></code></a>, The reasons are future-proofing and API simplicity.</p>
<p><strong>Future-proofing</strong></p>
<p><a href="https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1" rel="noreferrer"><code>List<T></code></a> is not designed to be easily extensible by subclassing it; it is designed to be fast for internal implementations. You'll notice the methods on it are not virtual and so cannot be overridden, and there are no hooks into its <a href="https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.add" rel="noreferrer"><code>Add</code></a>/<a href="https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.insert" rel="noreferrer"><code>Insert</code></a>/<a href="https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.remove" rel="noreferrer"><code>Remove</code></a> operations. </p>
<p>This means that if you need to alter the behavior of the collection in the future (e.g. to reject null objects that people try to add, or to perform additional work when this happens such as updating your class state) then you need to change the type of collection you return to one you can subclass, which will be a breaking interface change (of course changing the semantics of things like not allowing null may also be an interface change, but things like updating your internal class state would not be).</p>
<p>So by returning either a class that can be easily subclassed such as <a href="https://learn.microsoft.com/en-us/dotnet/api/system.collections.objectmodel.collection-1" rel="noreferrer"><code>Collection<T></code></a> or an interface such as <a href="https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.ilist-1" rel="noreferrer"><code>IList<T></code></a>, <a href="https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.icollection-1" rel="noreferrer"><code>ICollection<T></code></a> or <a href="https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.ienumerable-1" rel="noreferrer"><code>IEnumerable<T></code></a> you can change your internal implementation to be a different collection type to meet your needs, without breaking the code of consumers because it can still be returned as the type they are expecting.</p>
<p><strong>API Simplicity</strong></p>
<p><a href="https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1" rel="noreferrer"><code>List<T></code></a> contains a lot of useful operations such as <a href="https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.binarysearch" rel="noreferrer"><code>BinarySearch</code></a>, <a href="https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.sort" rel="noreferrer"><code>Sort</code></a> and so on. However if this is a collection you are exposing then it is likely that you control the semantics of the list, and not the consumers. So while your class internally may need these operations it is very unlikely that consumers of your class would want to (or even should) call them.</p>
<p>As such, by offering a simpler collection class or interface, you reduce the number of members that users of your API see, and make it easier for them to use.</p>
|
<p>Well the Collection class is really just a wrapper class around other collections to hide their implementation details and other features. I reckon this has something to do with the property hiding coding pattern in object-oriented languages.</p>
<p>I think you shouldn't worry about it, but if you really want to please the code analysis tool, just do the following:</p>
<pre><code>//using System.Collections.ObjectModel;
Collection<MyClass> myCollection = new Collection<MyClass>(myList);
</code></pre>
| 34,180
|
<p>Can't find anything relevant about Entity Framework/MySQL on Google so I'm hoping someone knows about it.</p>
|
<p>It's been released - Get the <a href="http://www.mysql.com/downloads/connector/net" rel="noreferrer">MySQL connector for .Net v6.5</a> - this has support for
[Entity Framework]</p>
<p>I was waiting for this the whole time, although the support is basic, works for most basic scenarios of db interaction. It also has basic Visual Studio integration.</p>
<p><strong>UPDATE</strong>
<a href="http://dev.mysql.com/downloads/connector/net/" rel="noreferrer">http://dev.mysql.com/downloads/connector/net/</a>
Starting with version 6.7, Connector/Net will no longer include the MySQL for Visual Studio integration. That functionality is now available in a separate product called MySQL for Visual Studio available using the MySQL Installer for Windows (see <a href="http://dev.mysql.com/tech-resources/articles/mysql-installer-for-windows.html" rel="noreferrer">http://dev.mysql.com/tech-resources/articles/mysql-installer-for-windows.html</a>).</p>
|
<p>I didn't see the link here, but there's a beta .NET Connector for MySql. Click "Development Releases" to download 6.3.2 beta, which has EF4/VS2010 integration:</p>
<p><a href="http://dev.mysql.com/downloads/connector/net/5.0.html#downloads" rel="nofollow noreferrer">http://dev.mysql.com/downloads/connector/net/5.0.html#downloads</a></p>
| 10,213
|
<p>I have heard using PDB files can help diagnose where a crash occurred.<br>
My <em>basic</em> understanding is that you give Visual studio the source file, the pdb file and the crash information (from Dr Watson?)<br>
Can someone please explain how it all works / what is involved?
(Thank you!)</p>
|
<p>PDB files are generated when you build your project. They contain information relating to the built binaries which Visual Studio can interpret.</p>
<p>When a program crashes and it generates a crash report, Visual Studio is able to take that report and link it back to the source code via the PDB file for the application. PDB files must be built from the same binary that generated the crash report!</p>
<p>There are some issues that we have encountered over time.</p>
<ul>
<li>The machine that is debugging the crash report needs to have the source on the same path as the machine that built the binary.</li>
<li>Release builds often optimize to the extent where you cannot view the state of object member variables</li>
</ul>
<p>If anyone knows how to defeat the former, I would be grateful for some input.</p>
|
<p>You should look into setting up a symbol server and indexing the PDB files to your source code control system. I just recently went through this process for our product and it works very well. You don't have to be concerned about making PDB files available with the binaries, nor how to get the appropriate source code when debugging dump files.</p>
<p>John Robbins' book: <a href="https://rads.stackoverflow.com/amzn/click/com/0735622027" rel="nofollow noreferrer" rel="nofollow noreferrer">http://www.amazon.com/Debugging-Microsoft-NET-2-0-Applications/dp/0735622027/ref=pd_bbs_sr_1?ie=UTF8&s=books&qid=1222366012&sr=8-1</a></p>
<p>Look here for some sample code for generating minidumps (which don't have to be restricted to post-crash analysis -- you can generate them at any point in your code without crashing): <a href="http://www.codeproject.com/KB/debug/postmortemdebug_standalone1.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/debug/postmortemdebug_standalone1.aspx</a></p>
| 9,768
|
<p>How can I calculate the last business day of the month in .NET?</p>
|
<p>I would do it like this for a Monday through Friday business week:</p>
<pre><code>var holidays = new List<DateTime>{/* list of observed holidays */};
DateTime lastBusinessDay = new DateTime();
var i = DateTime.DaysInMonth(year, month);
while (i > 0)
{
var dtCurrent = new DateTime(year, month, i);
if(dtCurrent.DayOfWeek < DayOfWeek.Saturday && dtCurrent.DayOfWeek > DayOfWeek.Sunday &&
!holidays.Contains(dtCurrent))
{
lastBusinessDay = dtCurrent;
i = 0;
}
else
{
i = i - 1;
}
}
</code></pre>
|
<p>Here is how to find the last day of the month in C#:</p>
<pre><code>DateTime today = DateTime.Today;
DateTime endOfMonth = new DateTime(today.Year,
today.Month,
DateTime.DaysInMonth(today.Year,
today.Month));
</code></pre>
<p><a href="http://geekprogrammers.com/question/how-can-i-find-the-last-day-of-the-month-in-c/" rel="nofollow">Source</a></p>
| 34,387
|
<p>All, </p>
<p>I currently have my solution comprising of 2 Class librarys and a Web Site building within teamCity using Msbuild. Now I want to precompile the website and make it available as an artifact. However when i try to Precompile it using </p>
<pre><code><Target Name="PrecompileWeb" DependsOnTargets="Build">
<AspNetCompiler
PhysicalPath="$(BuildDir)\Location\"
TargetPath="$(BuildDir)\Publish"
Force="true"
Debug="true"
/>
</Target>
</code></pre>
<p>I get an error becasue it is looking for a virtual path (which i don't have as all I want to do it precompile the files I am not interested in publishing the site) if I put a dummy path in I get another error (correctly) about it not being an application under IIS </p>
<p>Any ideas</p>
|
<p>Is this a Web Site or Web Application Project? If the latter, instead of doing an AspNetCompiler task, do an MSBuild task to the csproj/vbproj file, calling the targets <code>Rebuild;ResolveReferences;_CopyWebApplication</code> and specifying the <code>OutDir</code> property.</p>
<p>If you are using a website, then specify the VirtualPath to be a valid IIS path. What is happening is that, when you don't specify the VirtualPath property, it tries to resolve it using the PhysicalPath and IIS. I believe that's just an artifact of how the AspNetCompiler works.</p>
|
<p>I am not sure this will work as this will happen on every build? I only want to do this when I run the build on the TeamCity Server not local builds. </p>
<p>Essentially I currently </p>
<p>Build all the required solutions
Execute the unit tests
Create the Zip folder for the artifact</p>
<p>Cheers</p>
| 39,805
|
<p>When I type <code>uname -a</code>, it gives the following output.</p>
<pre><code>Linux mars 2.6.9-67.0.15.ELsmp #1 SMP Tue Apr 22 13:50:33 EDT 2008 i686 i686 i386 GNU/Linux
</code></pre>
<p>How can I know from this that the given OS is 32 or 64 bit?</p>
<p>This is useful when writing <code>configure</code> scripts, for example: what architecture am I building for?</p>
|
<p>Try <a href="http://linuxmanpages.net/manpages/fedora16/man1/uname.1.html" rel="noreferrer"><code>uname -m</code></a>. Which is short of <code>uname --machine</code> and it outputs: </p>
<pre><code>x86_64 ==> 64-bit kernel
i686 ==> 32-bit kernel
</code></pre>
<hr>
<p>Otherwise, <strong>not for the Linux kernel, but for the CPU</strong>, you type:</p>
<pre><code>cat /proc/cpuinfo
</code></pre>
<p>or:</p>
<pre><code>grep flags /proc/cpuinfo
</code></pre>
<p>Under "flags" parameter, you will see various values: see "<a href="https://unix.stackexchange.com/a/43540">What do the flags in /proc/cpuinfo mean?</a>"
Among them, one is named <code>lm</code>: <code>Long Mode</code> (<a href="http://en.wikipedia.org/wiki/X86-64" rel="noreferrer">x86-64</a>: amd64, also known as Intel 64, i.e. 64-bit capable)</p>
<pre><code>lm ==> 64-bit processor
</code></pre>
<p>Or <a href="http://linux.die.net/man/1/lshw" rel="noreferrer">using <code>lshw</code></a> (as mentioned <a href="https://stackoverflow.com/a/32717681/6309">below</a> by <a href="https://stackoverflow.com/users/4637585/rolf-of-saxony">Rolf of Saxony</a>), without <code>sudo</code> (just for grepping the cpu width):</p>
<pre><code>lshw -class cpu|grep "^ width"|uniq|awk '{print $2}'
</code></pre>
<p><strong>Note: you can have a 64-bit CPU with a 32-bit kernel installed</strong>.<br>
(as <a href="https://stackoverflow.com/users/637866/ysdx">ysdx</a> mentions in <a href="https://stackoverflow.com/a/32665383/6309">his/her own answer</a>, "Nowadays, a system can be <strong><a href="https://wiki.debian.org/Multiarch" rel="noreferrer">multiarch</a></strong> so it does not make sense anyway. You might want to find the default target of the compiler")</p>
|
<p>First you have to download Virtual Box. Then select new and a 32-bit Linux. Then boot the linux using it. If it boots then it is 32 bit if it doesn't then it is a 64 bit.</p>
| 30,522
|
<p>I came across <a href="http://www.catonmat.net/blog/edsger-dijkstra-discipline-in-thought/" rel="nofollow noreferrer">this article</a> about programming styles, seen by Edsger Dijsktra. To quickly paraphrase, the main difference is Mozart, when the analogy is made to programming, fully understood (debatable) the problem before writing anything, while Beethoven made his decisions as he wrote the notes out on paper, creating many revisions along the way. With Mozart programming, version 1.0 would be the only version for software that should aim to work with no errors and maximum efficiency. Also, Dijkstra says software not at that level of refinement and stability should not be released to the public.</p>
<p>Based on his views, two questions. Is Mozart programming even possible? Would the software we write today really benefit if we adopted the Mozart style instead? </p>
<p>My thoughts. It seems, to address the increasing complexity of software, we've moved on from this method to things like agile development, public beta testing, and constant revisions, methods that define web development, where speed matters most. But when I think of all the revisions web software can go through, especially during maintenance, when often patches are applied over patches, to then be refined through a tedious refactoring process—the Mozart way seems very attractive. It would at least lessen those annoying software updates, e.g. Digsby, Windows, iTunes, etc., many the result of unforeseen vulnerabilities that require a new and immediate release.</p>
<p>Edit: Refer to <a href="https://stackoverflow.com/questions/292682/understanding-dijkstras-mozart-programming-style#292955">the response below</a> for a more accurate explanation of Dijsktra's views.</p>
|
<p>The Mozart programming style is a complete myth (everybody has to edit and modify their initial efforts), and although "Mozart" is essentially a metaphor in this example, it's worth noting that Mozart was substantially a myth himself.</p>
<p>Mozart was a supposed magical child prodigy who composed his first sonata at 4 (he was actually 6, and it sucked - you won't ever hear it performed anywhere). It's rarely mentioned, of course, that his father was considered Europe's greatest music teacher, and that he forced all of his children to practice playing and composition for hours each day as soon as they could pick up an instrument or a pen.</p>
<p>Mozart himself was careful to perpetuate the illusion that his music emerged whole from his mind by destroying most of his drafts, although enough survive to show that he was an editor like everyone else. Beethoven was just more honest about the process (maybe because he was deaf and couldn't tell if anyone was sneaking up on him anyway).</p>
<p>I won't even mention the theory that Mozart got his melodies from listening to songbirds. Or the <em>fact</em> that he created a system that used dice to randomly generate music (which is actually pretty cool, but might also explain how much of Mozart's music appeared to come from nowhere).</p>
<p>The moral of the story is: don't believe the hype. Programming is work, followed by more work to fix the mistakes you made the first time around, followed by more work to fix the mistakes you made the second time around, and so on and so forth until you die.</p>
|
<p>Progress in computing is worth a sacrifice in glory or genius here and there.</p>
| 37,344
|
<p>I have a native VC++ project that uses a dll (which is not in a project). Now, I must to put the dll in one the "Search Path Used by Windows to Locate a DLL"
<a href="http://msdn.microsoft.com/en-us/library/7d83bc18(VS.80).aspx" rel="nofollow noreferrer">link</a></p>
<p>but I don't want the dll to sit in the exectuable or current or windows or system directory.</p>
<p>So my only option according to that is adding the path to the %PATH% environment variable.</p>
<p>Is there any other way?</p>
<p>Is there an elegant way to do so (adding to PATH)? should I do this on installation? should I be concerned if i'm doing this?</p>
|
<p>Summing up all the techniques I have found:</p>
<ul>
<li>If you use a managed project as the startup project (which is actually my case)
use Enviroment class</li>
</ul>
<p>string temp = "myFullDirectoryPathToDll";
string temp2 =Environment.GetEnvironmentVariable("PATH") + ";" + temp;
Environment.SetEnvironmentVariable("PATH", temp2);</p>
<p>this, and I think MSDN should have stressed that, changes the environment variable PATH only in this process.</p>
<p>when debugging in VS the appPath doesn't 'work'
use properties->debug->environment and merge environment variables
<a href="https://stackoverflow.com/questions/100543/how-do-i-set-specific-environment-variables-when-debugging-in-visual-studio">link</a></p>
<ul>
<li>If you use a native:
do explicit linking - seems like big work for something simple,
maybe use appPath registery key on deployment
<a href="http://www.codeguru.com/cpp/w-p/dll/print.php/c99" rel="nofollow noreferrer">link</a>,
nobody had a tested-and-proved answer </li>
</ul>
|
<p>If you're launching from a Windows shortcut, you could specify the DLL's path in the "Start in" location, while specifying the .exe's full name and path in the "Target" location.</p>
<p>If there are DLLs in the .exe's directory that are needed, Windows <em>should</em> be able find them as well, because I believe that the Windows DLL search order looks in the .exe's path first (the current directory is fifth on the list).</p>
<p>I've used the LoadLibrary/GetProcAddress method many times, I try to avoid it, as it does entail a bit of extra work - lots of typedefs and typecasts.</p>
| 28,431
|
<p>I have been tasked with developing a solution that tracks changes to a database.</p>
<p>For updates I need to capture:</p>
<ul>
<li>date of update</li>
<li>old value</li>
<li>new value</li>
<li>field affected</li>
<li>person doing change</li>
<li>record id</li>
<li>table record is in</li>
</ul>
<p>For deletes:</p>
<ul>
<li>date of delete</li>
<li>person doing delete</li>
<li>The title/description/id of record deleted. The tables I am tracking changes on all have a title or description field. I'd like to capture this before the record is deleted.</li>
<li>table record was in</li>
</ul>
<p>For inserts:</p>
<ul>
<li>date of insert</li>
<li>person doing change</li>
<li>record id</li>
<li>table record is in</li>
</ul>
<p>I've thought of a few ways to do this:</p>
<ul>
<li>I am using stored procedures for any updates/deletes/inserts. I would create a generic "tracking" table. It would have enough fields to capture all the data. I would then add another line in each stored proc to the effect of "Insert record into tracking table".
<ul>
<li>downside: all updates/deletes/inserts are all jumbled in the same table</li>
<li>lots of NULLed fields</li>
<li>how do I track batch updates/deletes/inserts? <---- this might not be an issue. I don't really do any thing like this in the application.</li>
<li>how do I capture the user making the update. The database just sees one account.</li>
<li>edit a lot of existing code to edit.</li>
</ul></li>
<li>Lastly, I could create a trigger that is called after updates/deletes/inserts. Many of the same downsides as the first solution except: I would have to edit as much code. I am not sure how I would track updates. It doesn't look like there's a way using triggers to see recently updated records.</li>
</ul>
<p>I am using asp.net, C#, sql server 2005, iis6, windows 2003. I have no budget so sadly I can't buy anything to help me with this.</p>
<p>Thanks for your answers!</p>
|
<p>A trigger wouldn't have all the information you need for a bunch of reasons - but no user id is the clincher.</p>
<p>I'd say you're on the right track with a common sp to insert wherever a change is made. If you're standardizing on sp's for your interfaces then you're ahead of the game - it will be hard to sneak in a change that isn't tracked.</p>
<p>Look at this as the equivalent of an audit trail in an accounting application - this is the Journal - a single table with every transaction recorded. They wouldn't implement separate journals for deposits, withdrawals, adjustments, etc. and this is the same principle.</p>
|
<p>we built our own and just needed the user and pc passed into each add/update stored procedure. then it's just a matter of getting the original record adn populating the variables and comparing them to the passed in variables and logging the data to our table.
for deletes we just have a copy of the originating tables + a timestamp field so the record is never really deleted and can be restored anytime we need (obviously the delete routine checks for FK relationships and such).</p>
<p>add/update log table looks like
datetime,
table_name,
column_name,
record_id,
old_value,
new_value,
user_id,
computer</p>
<p>we never insert nulls so we convert them to empty strings, new entries are marked with '{new entry}' in the old_value column. record_id is made up of as many key columns to uniquely identify that single record ( field1 + '.' + field2 + ... )</p>
| 38,440
|
<p>Code:</p>
<pre><code><html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Unusual Array Lengths!</title>
<script type="text/javascript">
var arrayList = new Array();
arrayList = [1, 2, 3, 4, 5, ];
alert(arrayList.length);
</script>
</head>
<body>
</body>
</html>
</code></pre>
<p>Notice the extra comma in the array declaration.
The code above gives different outputs for various browsers:</p>
<p>Safari: 5</p>
<p>Firefox: 5</p>
<p>IE: 6</p>
<p>The extra comma in the array is being ignored by Safari and FF while IE treats it as another object in the array.</p>
<p>On some search, I have found mixed opinions about which answer is correct. Most people say that IE is correct but then Safari is also doing the same thing as Firefox. I haven't tested this on other browsers like Opera but I assume that there are discrepancies.</p>
<p>My questions:</p>
<p>i. <strong>Which one of these is correct?</strong></p>
<p><em>Edit: By general consensus (and ECMAScript guidelines) we assume that IE is again at fault.</em> </p>
<p>ii. <strong>Are there any other such Javascript browser quirks that I should be wary of?</strong></p>
<p><em>Edit: Yes, there are loads of Javascript quirks. <a href="http://www.quirksmode.org" rel="nofollow noreferrer">www.quirksmode.org</a> is a good resource for the same.</em></p>
<p>iii. <strong>How do I avoid errors such as these?</strong></p>
<p><em>Edit: Use <a href="http://www.jslint.com/" rel="nofollow noreferrer">JSLint</a> to validate your javascript. Or, use some external <a href="http://openjsan.org/" rel="nofollow noreferrer">libraries</a>. Or, <a href="https://stackoverflow.com/questions/29053/javascript-browser-quirks-arraylength#29062">sanitize</a> your code.</em></p>
<p><em>Thanks to <a href="https://stackoverflow.com/users/3069/damien-b">DamienB</a>, <a href="https://stackoverflow.com/users/1790/jasonbunting">JasonBunting</a>, <a href="https://stackoverflow.com/users/2168/john">John</a> and <a href="https://stackoverflow.com/users/1968/konrad-rudolph">Konrad Rudolph</a> for their inputs.</em></p>
|
<p>It seems to me that the Firefox behavior is correct. What is the value of the 6th value in IE (sorry I don't have it handy to test). Since there is no actual value provided, I imagine it's filling it with something like 'null' which certainly doesn't seem to be what you intended to have happen when you created the array.</p>
<p>At the end of the day though, it doesn't really matter which is "correct" since the reality is that either you are targeting only one browser, in which case you can ignore what the others do, or you are targeting multiple browsers in which case your code needs to work on all of them. In this case the obvious solution is to never include the dangling comma in an array initializer.</p>
<p>If you have problems avoiding it (e.g. for some reason you have developed a (bad, imho) habit of including it) and other problems like this, then something like <a href="http://www.jslint.com/" rel="noreferrer">JSLint</a> might help. </p>
|
<p><a href="https://stackoverflow.com/questions/29053/javascript-browser-quirks-arraylength#29073">@John</a>: The value of arrayList[5] comes out to be 'undefined'.</p>
<p>Yes, there should never be a dangling comma in declarations. Actually, I was just going through someone else's long long javascript code which somehow was not working correctly in different browers. Turned out that the dangling comma was the culprit that has accidently been typed in! :)</p>
| 4,872
|
<p>Is it possible to throw an exception in a JSP without using scriptlet code?</p>
|
<p>You really shouldn't be doing anything at the JSP layer that explicitly throws exceptions. The reason you don't want to use scriptlets in JSPs is because that puts application logic in your view. Throwing an exception is inherently application logic, so it doesn't belong in your JSP, scriptlet or not.</p>
|
<p>You can throw an exception if you do this:</p>
<pre><code><c:out value="${1/0}" />
</code></pre>
<p>or something that is similarly "illegal"</p>
<p>Ideally though, since JSPs are associated with the view...you don't want to throw an exception. You want to catch them with <code><c:catch></code></p>
| 14,912
|
<p>In Django's template language, you can use <code>{% url [viewname] [args] %}</code> to generate a URL to a specific view with parameters. How can you programatically do the same in Python code?</p>
<p>What I need is to create a list of menu items where each item has name, URL, and an active flag (whether it's the current page or not). This is because it will be a lot cleaner to do this in Python than the template language.</p>
|
<p>If you need to use something similar to the <code>{% url %}</code> template tag in your code, Django provides the <code>django.core.urlresolvers.reverse()</code>. The <code>reverse</code> function has the following signature:</p>
<pre><code>reverse(viewname, urlconf=None, args=None, kwargs=None)
</code></pre>
<p><a href="https://docs.djangoproject.com/en/dev/ref/urlresolvers/" rel="noreferrer">https://docs.djangoproject.com/en/dev/ref/urlresolvers/</a></p>
<p>At the time of this edit the import is <code>django.urls import reverse</code></p>
|
<p>Be aware that using <code>reverse()</code> requires that your urlconf module is 100% error free and can be processed - iow no <code>ViewDoesNotExist</code> errors or so, or you get the dreaded <code>NoReverseMatch</code> exception (errors in templates usually fail silently resulting in <code>None</code>).</p>
| 6,489
|
<p>As title. I didn't find one via google, at any rate.</p>
<p>Update: thanks for the links from the two answers; this is very useful, but not what I was after - I am curious to see whether it is possible to query an IRepository backed by memcached (or some other distributed cache), backed by a RDBMS. I've really no idea how that might work in practise; I don't know very much about the internals of either distributed caches or LINQ providers.</p>
<p>I'm maybe envisaging something like the cache LINQ provider generating cache-keys based on the query automatically (where query could be Expression> or some kind of Specification pattern implementation), and basically can be plumped down inbetween my app and my DB. Does that sound useful?</p>
|
<p>If you don't mind throwing <a href="http://www.hibernate.org/343.html" rel="nofollow noreferrer">NHibernate</a> between them, you can use <a href="http://ayende.com/Blog/archive/2007/03/16/Linq-for-NHibernate.aspx" rel="nofollow noreferrer">LINQ to NHibernate</a> to query entities which <a href="http://www.hibernate.org/hib_docs/nhibernate/1.2/reference/en/html/caches.html" rel="nofollow noreferrer">can be set</a> to use <a href="http://www.hibernate.org/hib_docs/nhibernate/1.2/reference/en/html/caches.html" rel="nofollow noreferrer">memcached</a> as their cache.</p>
|
<p>I encounter some problem with linq for memcached also. But you should check out the serialization of your linq DBML whether it's Unidirectional or not.</p>
<p>you might have luck for this solution, worth to try out. For me, i sitll having problem with linq, but other object that have [Serilizable] attribute works fine.</p>
| 29,889
|
<p>To start with, as stated in the title, I am very new to 3D printing.</p>
<p>We're a toy/boardgame shop and we're experimenting with 3D printing because it could open up a huge market for us. To this end, I'm asked to try to get this off the ground, but also for me it's a big experiment.</p>
<h2>General Information</h2>
<p><strong>Printer:</strong> Craftbot Plus<br />
<strong>Slicer:</strong> CraftwarePro (1.1.4.368)<br />
<strong>Filament:</strong> PLA - 1.75 mm<br />
<strong>Designed in:</strong> Tinkercad</p>
<h2>Problem</h2>
<p>I designed a puzzle box in Tinkercad. Here are some images of the design:</p>
<p><a href="https://i.stack.imgur.com/VA4j3.png" rel="nofollow noreferrer" title="Screenshot of puzzle box designed in Tinkercad"><img src="https://i.stack.imgur.com/VA4j3.png" alt="Screenshot of puzzle box designed in Tinkercad" title="Screenshot of puzzle box designed in Tinkercad" /></a></p>
<p>I've printed it twice, but both have some problems. I made some pictures, hopefully showing the flaws clearly.</p>
<h4>Print 1</h4>
<p>This print actually came out pretty ok, but not the quality I'm looking for.</p>
<p><a href="https://i.stack.imgur.com/xeFkM.jpg" rel="nofollow noreferrer" title="Photo 1 of a printed model #1 with printing errors on bottom layer"><img src="https://i.stack.imgur.com/xeFkM.jpg" alt="Photo 1 of a printed model #1 with printing errors on bottom layer" title="Photo 1 of a printed model #1 with printing errors on bottom layer" /></a></p>
<p><a href="https://i.stack.imgur.com/cOst8.jpg" rel="nofollow noreferrer" title="Photo 2 of a printed model #1 with printing errors on bottom layer"><img src="https://i.stack.imgur.com/cOst8.jpg" alt="Photo 2 of a printed model #1 with printing errors on bottom layer" title="Photo 2 of a printed model #1 with printing errors on bottom layer" /></a></p>
<p><a href="https://i.stack.imgur.com/UxaPx.jpg" rel="nofollow noreferrer" title="Photo 3 of a printed model #1 with printing errors on bottom layer"><img src="https://i.stack.imgur.com/UxaPx.jpg" alt="Photo 3 of a printed model #1 with printing errors on bottom layer" title="Photo 3 of a printed model #1 with printing errors on bottom layer" /></a></p>
<h4>Print 2</h4>
<p>For some reason, this one came out way worse in my opinion. I didn't change any settings. The reason why I made this second print is that there are some design flaws in the first print.</p>
<p><a href="https://i.stack.imgur.com/x35Wf.jpg" rel="nofollow noreferrer" title="Photo 1 of a printed model #2 with printing errors"><img src="https://i.stack.imgur.com/x35Wf.jpg" alt="Photo 1 of a printed model #2 with printing errors" title="Photo 1 of a printed model #2 with printing errors" /></a></p>
<p><a href="https://i.stack.imgur.com/lq7Cx.jpg" rel="nofollow noreferrer" title="Photo 2 of a printed model #2 with printing errors"><img src="https://i.stack.imgur.com/lq7Cx.jpg" alt="Photo 2 of a printed model #2 with printing errors" title="Photo 2 of a printed model #2 with printing errors" /></a></p>
<p>As you might be able to tell, this one has some more severe problems, like the prolapse on one of the corners of the lid and some threads that just seem to be broken off here and there.</p>
<h2>Question</h2>
<p>My question is basically, what is likely to be the problem, and how should I solve them. Are there some settings on the printer, or in the slicer that needs to be changed? Or could it be something with the design, for example, would it be better to have the lids laying down on the bed, instead of standing up as I have them in the design right now?</p>
<p>Also, here and there seem to be threads of plastic where I think there should not be any.</p>
<h2>What have I found myself</h2>
<p>Since I'm very new to this, I wasn't really sure what to search/look for. I know it's expected to do some research yourself before posting any question, but I really didn't have a clue where to start.</p>
<p>Though, while typing in the question, 2 suggestions showed up:</p>
<h4>Suggestion 1</h4>
<p><a href="https://3dprinting.stackexchange.com/questions/13433/i-have-bad-print-quality-what-should-i-do">I have bad print quality, what should I do?</a></p>
<p>I'm not sure this looks like any of my problem areas, but somewhat similar.</p>
<h3>Suggestion 2</h3>
<p><a href="https://3dprinting.stackexchange.com/questions/13856/bad-quality-at-horizontal-faces">Bad quality at horizontal faces</a></p>
<p>This looks very much similar to how some of my areas look. Is the problem described in this post indeed the same as mine, based on the pictures?</p>
<h4>Conclusion</h4>
<p>In both posts, <em>"Under Extrusion"</em> is mentioned this is probably something to look into?</p>
<h2>Some personal observations</h2>
<p>There are 2 things I noticed myself, maybe some conclusions can be made from this:</p>
<ol>
<li><p>Something else I'm noticing while heating up the extruder is that plastic already leaks out in a very thin thread before it actually starts printing.</p>
</li>
<li><p>When the print is done, I notice thin threads of plastic between the different objects (Like a spiderweb), this probably has something to do with point 1.</p>
</li>
<li><p>When the printer is starting, I notice that the very first threads of plastic are not a fluent string, but sometimes get interrupted, as if no plastic is coming out of the extruder for a short moment.</p>
</li>
</ol>
<h2>Conclusion</h2>
<p>Hopefully, I provided every information that is required to answer this question properly. I'm looking forward to any offered assistance.</p>
<p>In case any additional information is required, I'm happy to give this next time I'm at the office.</p>
<p><em>P.S. I had to remove 6 links (pictures) to get to my maximum of 8</em></p>
|
<p>There are several issue at hand here, first you have an adhesion problem.</p>
<p><a href="https://i.stack.imgur.com/2CU9L.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2CU9L.png" alt="enter image description here" /></a></p>
<p>This print shows that the print (as it is printed upright) has come loose during printing and lifted up. Such a print should have been printed as it is now laying on your table. You will then also get far better quality of printed holes. So, second is print orientation on the build plate.</p>
<p><a href="https://i.stack.imgur.com/MvN6n.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MvN6n.png" alt="enter image description here" /></a></p>
<p>This shows another example of adhesion problems, but it also shows that you initial distance between the nozzle and the bed is slightly too large. The paper method usually works fine, but you can use feeler gauges. Alternatively use a specific 3D print adhesion spray (3DLAC, Magigoo, DimaFix) or alternatively some <a href="https://3dprinting.stackexchange.com/a/11183/">hairsprays</a> or <a href="https://3dprinting.stackexchange.com/a/15282/">glue sticks</a>.</p>
<p>Third, design. Just a tip, I see that your design uses some sort of a pin:</p>
<p><a href="https://i.stack.imgur.com/6UKxk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6UKxk.png" alt="enter image description here" /></a></p>
<p>you should avoid thin pole/spike like prints. These are difficult to print and usually very weak. Think of an alternative, an embedded shaft or a bolt is usually a much better solution.</p>
<p><a href="https://i.stack.imgur.com/HZ2Cq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HZ2Cq.png" alt="enter image description here" /></a></p>
<p>Fourth, this shows that there was no filament printed, it could be that the spool had extra resistance or the filament was entangled. Check your filament spool.</p>
<p><a href="https://i.stack.imgur.com/xQlzr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xQlzr.png" alt="enter image description here" /></a></p>
<p>Fifth, this shows that you have a retraction problem, the filament pressure is still too large when the head moves to the next coordinates, it then oozes until the pressure has been released. Changing retraction speed or distance may help.</p>
|
<p><strong>Adhesion</strong></p>
<p>Try raising your bed temperature a couple of degrees at a time. Presumably your filament has some "suggested temperatures" on the spool, but they sometimes only give a hotend's temp. For PLA some people get good results with a 50 degree C bed, I find nothing less than 60 degrees C. Esun's rec seems to be 60-80 for the bed.</p>
<p>For the hotend my esun PLA+ suggests 205-225 and I print at 218.</p>
<p>Depending on the environment, draughts can upset things and trigger lifting. If the printer is in a place where there are winds/breezes, or airconditioning that cycles on and off, the temperature fluctuations can start lifting. Try putting your printer somewhere that there is no wind and air conditions are static. I have a curtain around mine, and some people use enclosures made from popup laundry baskets or similar. Doesn't have to be fancy.</p>
<p>You can try things with light layers of water-soluble gluestick on the bed, which works for me. Others have had success in laying blue painter's tape on the bed but I found the heat made the adhesive a hot mess.</p>
<p><strong>Orientation</strong></p>
<p>That pin will never work - 3D printing has layers and items are always weak along the layers. So that part is a poor candidate for 3D printing.</p>
<p>Instead, buy a large assortment box of M3 nuts and bolts. These work much better than thin printed parts.</p>
<p>Also, that large lid should be printed laying flat on its back. Even the action of the bed moving around could be creating enough breeze to cool that part quickly and cause shrinkage.</p>
<p><strong>Design</strong></p>
<p>That dovetail at the foot of the box, as printed it will have a layer line right across the base. Since that looks like the most economical way to print this part, you might consider making the dovetail a lot wider, and it may need a slight draught angle added to help the lid engage smoothly.</p>
<p>The lid might spin around the pin and whack the dovetail clean off too - perhaps the two sidewalls should be raised so the lid only slides off in one direction?</p>
<p><strong>Lack of filament</strong></p>
<p>Holes in a printed part are a kind of under-extrusion, and mean there's not enough plastic at that time. If your roll of filament is under friction then the printer may not be able to pull it in fast enough.</p>
<p>Also if the hotend isn't hot enough it may not be melting quick enough for your print speed, or there may be clogs in the nozzle from contaminations in the filament.</p>
<p><strong>Suggestion</strong></p>
<p>Start by levelling the bed, and then print one item in your set. Use a "brim" to improve adhesion, and it will be done first. As your printer starts the job, watch it closely and manually adjust the bed on the fly.</p>
<p>Imagine these as side-views:</p>
<p>____ <strong><sub>__</sub></strong> _____ Nozzle is way too low, you're scratching the bed<br>
____ <strong>__</strong> ____ Nozzle is too low, so drop the bed down a bit. The filament should have colour.<br>
____ <strong><sup>__</sup></strong> ____ This is about right. <br>
____ <strong>o</strong> _____ Nozzle is a bit too high<br>
____ <strong>O</strong> _____ Nozzle is a lot too high<br>
____ <strong><sup>O</sup></strong> _____ Filament is floating in the air which is sub-optimal<br></p>
<p>Ideally you want to feel the printed filament line as a flattened line stuck to the bed, and not a round string lying on the print bed. It should almost feel like the edges of a sticker.</p>
<p>Of course, the printer is moving all the time. Do not get in its way, and if you do block the motion in any direction then the print will likely be ruined.</p>
| 2,173
|
<p>Is it true that a WCF either runs as a console application that you have to manually start OR under a more traditional IIS application (like a website or webservice)</p>
|
<p><strong>EDIT</strong>: No, that is not quite true. </p>
<p>Those are two hosting options for WCF. There are others.</p>
<hr>
<p>orig answer:</p>
<p>you can actually execute a wcf service everywhere, where you can execute managed code.
i've seen wcf services running inside sql server, wpf apps, windows services and even one running on a linux box on mono.</p>
|
<p>Yes, that's correct... you can also host them as a Windows Service</p>
| 25,609
|
<p>I would like to be able to drop to the python REPL from the debugger -- if this is not possible is there an easier way to evaluate python expressions in the context of the current breakpoint other than manually adding them all as watch expressions?</p>
|
<p>I don't use <em>pydev</em>, but to drop to python's interactive REPL from code:</p>
<pre><code>import code
code.interact(local=locals())
</code></pre>
<p>To drop to python's debugger from code:</p>
<pre><code>import pdb
pdb.set_trace()
</code></pre>
<p>Finally, to run a interactive REPL after running some code, you can use python's <code>-i</code> switch:</p>
<pre><code>python -i script.py
</code></pre>
<p>That will give you a python prompt after the code, even if it throws an exception.</p>
<p>You may be able to hook some of those solutions into <em>pydev</em>, I think.</p>
|
<p>As Dag Høidahl said, the PyDev Console is actually the best option (at least on Eclipse Indigo), no need to hack around. </p>
<p>Just go to Open Console:
<img src="https://i.stack.imgur.com/nXYND.png" alt="Open Console"></p>
<p>Then select PyDev Console:</p>
<p><img src="https://i.stack.imgur.com/nx9M1.png" alt="PyDev Console"></p>
<p>If you need to add specific parameters (for example, Jython tends to miss the python.os VM property), you can change them under Window -> Properties -> PyDev -> Interactive Console.
<img src="https://i.stack.imgur.com/ysj5d.png" alt="enter image description here"></p>
| 29,960
|
<p><a href="https://stackoverflow.com/questions/12073/what-is-the-best-xml-editor">https://stackoverflow.com/questions/12073/what-is-the-best-xml-editor</a> was a great question regarding XML editors on Windows. What about on OS X?</p>
<p>Oxygen is feature complete, but, it's a Java app and a bit clunky on OSX. It's also extremely expensive.</p>
<p>Anything Mac native and comparable in features for less than $300 ?</p>
<p>Thanks</p>
<p>Andrew</p>
|
<p><a href="http://www.editix.com/" rel="nofollow noreferrer">EditiX XML Editor</a> (starts at $60) or maybe <a href="http://www.oxygenxml.com/" rel="nofollow noreferrer">oXygen</a> ($299 is less than $300, right).</p>
<p>You'll find a big list of the optiosn over at <a href="http://xmacl.com/" rel="nofollow noreferrer">XMacL</a> if you want more choices.</p>
|
<p>Netbeans could be a good and free choice too.</p>
| 6,796
|
<p>How can a .net class library project and resulting dll be protected so it cant be referenced by other applications (.net projects) except those projects in my own solution?</p>
|
<p>I think you can't forbid other applications to reference you library.<br>
You can make library's classes internal and provide access to them via <a href="http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx" rel="nofollow noreferrer">InternalVisibleTo</a> attribute but it won't save you from reflection.</p>
|
<p>Forgive my ignorance, but if they're all class libraries, what does the code do? Isn't the purpose of having a dll so that the code can be referenced.</p>
<p>In any case if you mark everything <a href="http://msdn.microsoft.com/en-us/library/7c5ka91b.aspx" rel="nofollow noreferrer"><code>internal</code></a> it won't be able to be accessed outside its own library</p>
| 6,022
|
<p>Why does Resharper want you to change most variables to var type instead of the actual type in the code?</p>
|
<p>It's just an option. You can disable it:</p>
<p>ReSharper -> Options -> Code Inspection -> Inspection Severity -> Code Redundencies -> Use 'var' keyword where possible: change this to "Do not show"</p>
<p>There's also the context (lightbulb) option which will take you in each direction - this is under ReSharper -> Options -> Languages -> C# -> Context Actions -> "Replaces explicit type declaration with 'var'"</p>
|
<p>Vars help to make the code more readable inside a method, especially if you use generics.</p>
<p>As Jon says, it is just an option.</p>
| 37,954
|
<p>So here I am just about to start a big project using LINQ to SQL and then I read this:</p>
<p><a href="http://www.infoq.com/news/2008/11/DLINQ-Future" rel="nofollow noreferrer">Is LINQ to SQL Truly Dead?</a> by Jonathan Allen for InfoQ.com</p>
<p>Well, I don't want to be supporting LINQ to SQL indefinitely if it's a dead end. So, how should I get started learning about ADO.NET Entity Framework?</p>
|
<p>How Do I...? Videos</p>
<ul>
<li><a href="http://blogs.msdn.com/adonet/archive/2008/05/20/how-do-i-new-entity-framework-videos.aspx" rel="noreferrer">How Do I Get Started with the Entity Framework?</a> </li>
<li><a href="http://blogs.msdn.com/adonet/archive/2008/05/20/how-do-i-new-entity-framework-videos.aspx" rel="noreferrer">How Do I Use the new Entity Data Source?</a> </li>
<li><a href="http://blogs.msdn.com/adonet/archive/2008/05/20/how-do-i-new-entity-framework-videos.aspx" rel="noreferrer">How Do I Serialize a Graph with the Entity Framework?</a> </li>
<li><a href="http://blogs.msdn.com/adonet/archive/2008/05/20/how-do-i-new-entity-framework-videos.aspx" rel="noreferrer">How do I use Entity Client?</a> </li>
<li><a href="http://www.asp.net/learn/3.5-SP1/video-245.aspx" rel="noreferrer">ADO.NET Entity Designer Video - CTP 2</a></li>
</ul>
<p>Webcasts</p>
<ul>
<li><a href="http://www.asp.net/learn/webcasts/webcast-181.aspx" rel="noreferrer">MSDN Webcast: Framework Masterclass: LINQ to Entities (Level 200)</a></li>
</ul>
|
<p>Conference Sessions</p>
<p><a href="http://channel9.msdn.com/pdc2008/TL20/" rel="nofollow noreferrer">PDC 2008 Entity Framework Futures session</a></p>
| 32,319
|
<p>I am newbie to <code>Spring Webflow</code>, I have am using Custom <code>FlowHandler</code> </p>
<p>I can reach the respective Controller, but if set an attribute in a request Object I don't get it in JSP that is <code>View state</code>.</p>
<p>How can I proceed in this?</p>
|
<p>you shouldn't set anything to your request attributes in spring webflow - there is no need, besides webflow does some internal request redirecting and probably your attributes are los. </p>
<p>all the variables you create in the flow are available in view as if they were set by adding attribute to request. wether you create them via tag or create by executing some service calls via tag</p>
|
<p>Hey Miceuz thanks for Replying .....</p>
<pre><code><on-start>
<evaluate expression="XXXXControllerwsf.firstHit(flowRequestContext)" result="flowScope.res"/>
</on-start>
<decision-state id="urlcheck">
<if test="flowScope.res.reurl== 'splash' " then="splash" else="change"/>
</decision-state>
<view-state id="change" view="${flowScope.res.reurl}">
</view-state>
<view-state id="splash" view="forward:/Jahia/jsp1/XXXXchange1.jsp">
<transition on="buy" to="SignInSignUp"/>
</view-state>
</flow>
</code></pre>
<p>On start of the flow I am invoking a Contorller which extends FormAction </p>
<p>In firsthit Method I am setting a request Attribute as below</p>
<pre><code>request.setAttribute("rajan", "rajanweww");
request.setAttribute("rajan", Object);
</code></pre>
<p>If i try to access in JSP , getting it as null... as you said Webflow has internal redirect.. Then how can I access the Value that has been set in Controller?</p>
| 49,444
|
<p>I'm tired of opening Dia and creating a database diagram at the beginning of every project. Is there a tool out there that will let me select specific tables and then create a database diagram for me based on a MySQL database? Preferably it would allow me to edit the diagram afterward since none of the foreign keys are set...</p>
<p>Here is what I am picturing diagram-wise (please excuse the horrible data design, I didn't design it. Let's focus on the diagram concept and not on the actual data it represents for this example ;) ):</p>
<p><img src="https://i.stack.imgur.com/lxvlR.jpg" alt="diagram">
<a href="https://i.stack.imgur.com/ZnN2O.png" rel="noreferrer">see full size diagram</a></p>
|
<p>Try MySQL Workbench, formerly DBDesigner 4:</p>
<p><a href="http://dev.mysql.com/workbench/" rel="noreferrer">http://dev.mysql.com/workbench/</a></p>
<p>This has a "Reverse Engineer Database" mode:</p>
<p>Database -> Reverse Engineer</p>
<p><a href="https://i.stack.imgur.com/wcoq9.png" rel="noreferrer"><img src="https://i.stack.imgur.com/wcoq9.png" alt="enter image description here"></a></p>
|
<p>The "Reverse Engineer Database" mode in Workbench is only part of the paid version, not the free one.</p>
| 2,460
|
<p>This is what I have so far: </p>
<pre><code>myArray.map!{ rand(max) }
</code></pre>
<p>Obviously, however, sometimes the numbers in the list are not unique. How can I make sure my list only contains unique numbers without having to create a bigger list from which I then just pick the n unique numbers?</p>
<p><strong>Edit:</strong><br>
I'd really like to see this done w/o loop - if at all possible.</p>
|
<p>This uses Set:</p>
<pre><code>require 'set'
def rand_n(n, max)
randoms = Set.new
loop do
randoms << rand(max)
return randoms.to_a if randoms.size >= n
end
end
</code></pre>
|
<p>Here is one solution:</p>
<p>Suppose you want these random numbers to be between <code>r_min</code> and <code>r_max</code>. For each element in your list, generate a random number <code>r</code>, and make <code>list[i]=list[i-1]+r</code>. This would give you random numbers which are monotonically increasing, guaranteeing uniqueness provided that</p>
<ul>
<li><code>r+list[i-1]</code> does not over flow</li>
<li><code>r</code> > 0</li>
</ul>
<p>For the first element, you would use <code>r_min</code> instead of <code>list[i-1]</code>. Once you are done, you can shuffle the list so the elements are not so obviously in order.</p>
<p>The only problem with this method is when you go over <code>r_max</code> and still have more elements to generate. In this case, you can reset <code>r_min</code> and <code>r_max</code> to 2 adjacent element you have already computed, and simply repeat the process. This effectively runs the same algorithm over an interval where there are no numbers already used. You can keep doing this until you have the list populated.</p>
| 14,488
|
<p>Is there any way to restrict users with administrative privileges from managing specific Windows service based applications? I would like to restrict administrators from stopping or re-starting my service very similar to the Windows event log service. What are some of the more popular approaches or recommended approaches to securing services followed by product vendors (like antivirus applications, firewalls etc where the service has to be running continuously)?</p>
|
<p>To remove the stop option from the service management mmc. With .net service you:</p>
<pre><code>ServicesToRun = new ServiceBase[] { new Service1() };
ServicesToRun[0].CanStop = false;
</code></pre>
<p>With win32 see the <a href="http://msdn.microsoft.com/en-us/library/ms685996(VS.85).aspx" rel="nofollow noreferrer">SERVICE_STATUS</a> structure and <a href="http://msdn.microsoft.com/en-us/library/ms686241(VS.85).aspx" rel="nofollow noreferrer">SetServiceStatus</a> function documentation. Did not test this option.</p>
<p>That said, I don't think ( and hope I am right ) that there is possibility, in user space, to prevent the administrator from stopping a service. The admin can still stop the service by killing the process from taskmanager or taskkill.</p>
|
<p>Here is one approach using access control - <a href="http://support.microsoft.com/?kbid=288129" rel="nofollow noreferrer">http://support.microsoft.com/?kbid=288129</a></p>
| 37,386
|
<p>I'm building an application against some legacy, third party libraries, and having problems with the linking stage. I'm trying to compile with Visual Studio 9. My compile command is:</p>
<pre><code>cl -DNT40 -DPOMDLL -DCRTAPI1=_cdecl
-DCRTAPI2=cdecl -D_WIN32 -DWIN32 -DWIN32_LEAN_AND_MEAN -DWNT -DBYPASS_FLEX -D_INTEL=1 -DIPLIB=none -I. -I"D:\src\include" -I"C:\Program Files\Microsoft Visual Studio
9.0\VC\include" -c -nologo -EHsc -W1 -Ox -Oy- -MD mymain.c
</code></pre>
<p>The code compiles cleanly. The link command is:</p>
<pre><code>link -debug -nologo -machine:IX86
-verbose:lib -subsystem:console mymain.obj wsock32.lib advapi32.lib
msvcrt.lib oldnames.lib kernel32.lib
winmm.lib [snip large list of
dependencies] D:\src\lib\app_main.obj
-out:mymain.exe
</code></pre>
<p>The errors that I'm getting are:</p>
<pre><code>app_main.obj : error LNK2019:
unresolved external symbol
"_\_declspec(dllimport) public: void
__thiscall std::locale::facet::_Register(void)"
(__imp_?_Register@facet@locale@std@@QAEXXZ)
referenced in function "class
std::ctype<char> const & __cdecl
std::use_facet<class std::ctype<char>
(class std::locale const &)" (??$use_facet@V?$ctype@D@std@@@std@@YAABV?$ctype@D@0@ABVlocale@0@@Z)
app_main.obj : error LNK2019:
unresolved external symbol
"__declspec(dllimport) public: static
unsigned int __cdecl
std::ctype<char>::_Getcat(class
std::locale::facet const * *)"
(__imp_?_Getcat@?$ctype@D@std@@SAIPAPBVfacet@locale@2@@Z)
referenced in function "class
std::ctype<char> const & __cdecl
std::use_facet<class std::ctype<char>
(class std::locale const &)" (??$use_facet@V?$ctype@D@std@@@std@@YAABV?$ctype@D@0@ABVlocale@0@@Z)
app_main.obj : error LNK2019:
unresolved external symbol
"__declspec(dllimport) public: static
unsigned int __cdecl
std::ctype<unsigned
short>::_Getcat(class
std::locale::facet const * *)"
(__imp_?_Getcat@?$ctype@G@std@@SAIPAPBVfacet@locale@2@@Z)
referenced in function "class
std::ctype<unsigned short> const &
__cdecl std::use_facet<class std::ctype<unsigned short> >(class
std::locale const &)"
(??$use_facet@V?$ctype@G@std@@@std@@YAABV?$ctype@G@0@ABVlocale@0@@Z)
mymain.exe : fatal error LNK1120: 3
unresolved externals
</code></pre>
<p>Notice that these errors are coming from the legacy code, not my code - app_main.obj is part of the legacy code, while mymain.c is my source. I've done some searching around, and what that I've read says that this type of error is caused by a mismatch with the -MD switch between my code and the library that I'm linking to. Since I'm dealing with legacy code, a solution has to come from my environment. It's been a long time since I've done C++ work, and even longer since I've used Visual Studio, so I'm hoping that this is just some ignorance on my part. Any ideas on how to get these resolved?</p>
|
<p>These are standard library references. Make sure that all libraries (including the standard library) are using the <em>same</em> linkage. E.g. you can't link statically while linking the standard lib dynamically. The same goes for the threading model used. Take special care that you and the 3rd party library use the same linkage options.</p>
<p>This can be a real pain in the *ss.</p>
|
<p>After trying to get this stuff to compile under VS 2008, I tried earlier versions of VS - 2005 worked with warnings, and 2003 just worked. I double checked the linkages and couldn't find any problems, so either I just couldn't find it, or that wasn't the problem. </p>
<p>So to reiterate, downgrading to VS 2003 fixed it.</p>
| 4,321
|
<p>Let's say I have the following code:</p>
<pre><code>@sites = Site.find(session[:sites]) # will be an array of Site ids
@languages = Language.for_sites(@sites)
</code></pre>
<p>for_sites is a named_scope in the Language model that returns the languages associated with those sites, and languages are associated with sites using has_many through. The goal is for @languages to have a distinct array of the languages associated with the sites.</p>
<p>Instead of calling the Language object on the second line, I'd ideally like to say </p>
<pre><code>@sites.languages
</code></pre>
<p>and have the same list returned to me. Is there any way to do that cleanly in Rails 2.1 (or edge)? I know associations and named scopes can extend the array object to have attributes, but unless I'm missing something that doesn't apply here. Any plugins that do this would be welcome, it doesn't have to be in core.</p>
|
<p>You could extend the array returned by Site.find.</p>
<pre><code>class Site
def find(*args)
result = super
result.extend LanguageAggregator if Array === result
result
end
end
module LanguageAggregator
def languages
Language.find(:all, :conditions => [ 'id in (?)', self.collect { |site| site.id } ])
end
end
</code></pre>
|
<p>Your instance variable @sites is an Array object and not Site so I don't think named_scope can be used. You can open up Array class to achieve this effect though (yikes)</p>
<pre><code>class Array
def languages
...
end
end
</code></pre>
| 27,099
|
<p>We all write reusable classes and code. </p>
<p>We factor in configurability to allow us to reuse this fantastic new class again and again. </p>
<p>We tell our bosses that spending this extra time now will save us time and money later. </p>
<p>But in reality, for those of us who don't write third party libraries, and spend our time working on a application as a whole, how many times does that one class you spent extra time writing to be reused actually get reused in another project? </p>
<p>How many bespoke classes do you have in your library which will get used in more than one project?</p>
|
<p>My common rule of thumb is:</p>
<ol>
<li>If you repeat it once, copy it.</li>
<li>If you repeat it twice, refactor it.</li>
</ol>
|
<p>I agree with you insofar as there is no point in coding in a way that makes the class easy to use outside of the current application. Most if us don't do this and in business environments there is no need to. If another application needs this functionality at a later date then extracting and commonalising the code can be done as part of that second project, and management are likely to agree with this viewpoint.</p>
<p>However it is good practice to make your code reusable within the constraints of the current application. Refactor your code so as to avoid duplication within your current scope of work. This way you make it easier to work with at a later date. Don't so much code for reuse as for change, change is far more common.</p>
| 42,156
|
<p>How would you take an arbitrary list of strings (of the form "%[text]%") and a database column, and turn them into a SQL query that does a LIKE comparison for each string in the list?</p>
<p>An example: I have three strings in my list, "%bc%", "%def%" and "%ab%". This builds the query:</p>
<pre><code>([ColumnName] LIKE "%bc" AND [ColumnName] LIKE "%def%") AND [ColumnName] LIKE "%ab%"
</code></pre>
<p>A C# example would be excellent, but feel free to write it in the language of your choice.</p>
|
<p>To answer your question directly,</p>
<pre><code>string.join(" and ",
(new[] { "%bc%", "%def%", "%ab%" })
.Select(x => string.Format("[{0}] LIKE '{1}'",columnName, x))
.ToArray());
</code></pre>
<p>To solve your problem, you should use the Sql Server full-text search tools. the query would be:</p>
<pre><code>select * from table
where FREETEXT("bc def ab")
</code></pre>
<p>With the correct indices, this should outperform a list of LIKEs </p>
|
<p>It's just a string join on a map:</p>
<pre><code>>>> los=['ab', 'cd', 'ef']
>>> ' and '.join(("somecolumn like '%%%s%%'" % s) for s in los)
"somecolumn like '%ab%' and somecolumn like '%cd%' and somecolumn like '%ef%'"
</code></pre>
<p>or</p>
<pre><code>>>> ' and '.join(("somecolumn like '%" + s + "%'") for s in los)
"somecolumn like '%ab%' and somecolumn like '%cd%' and somecolumn like '%ef%'"
</code></pre>
| 41,267
|
<p>How do I find out whether or not Caps Lock is activated, using VB.NET?</p>
<p>This is a follow-up to my <a href="https://stackoverflow.com/questions/58937/how-do-i-toggle-caps-lock-in-vbnet">earlier question</a>.</p>
|
<p><a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.control.iskeylocked.aspx" rel="noreferrer">Control.IsKeyLocked(Keys) Method - MSDN</a></p>
<pre><code>Imports System
Imports System.Windows.Forms
Imports Microsoft.VisualBasic
Public Class CapsLockIndicator
Public Shared Sub Main()
if Control.IsKeyLocked(Keys.CapsLock) Then
MessageBox.Show("The Caps Lock key is ON.")
Else
MessageBox.Show("The Caps Lock key is OFF.")
End If
End Sub 'Main
End Class 'CapsLockIndicator
</code></pre>
<hr>
<p>C# version:</p>
<pre class="lang-cs prettyprint-override"><code>using System;
using System.Windows.Forms;
public class CapsLockIndicator
{
public static void Main()
{
if (Control.IsKeyLocked(Keys.CapsLock)) {
MessageBox.Show("The Caps Lock key is ON.");
}
else {
MessageBox.Show("The Caps Lock key is OFF.");
}
}
}
</code></pre>
|
<p>The solution posted by <a href="https://stackoverflow.com/a/58993/7444103">.rp</a> works, but conflicts with the <code>Me.KeyDown</code> event handler.<br>
I have a sub that calls a sign in function when enter is pressed (shown below).<br>
The <code>My.Computer.Keyboard.CapsLock</code> state works and does not conflict with <code>Me.Keydown</code>.</p>
<pre><code>Private Sub WindowLogin_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown
If Keyboard.IsKeyDown(Key.Enter) Then
Call SignIn()
End If
End Sub
</code></pre>
| 8,343
|
<p>I want to know when an image has finished loading. Is there a way to do it with a callback?</p>
<p>If not, is there a way to do it at all?</p>
|
<p><strong><code>.complete</code> + callback</strong></p>
<p>This is a standards compliant method without extra dependencies, and waits no longer than necessary:</p>
<pre><code>var img = document.querySelector('img')
function loaded() {
alert('loaded')
}
if (img.complete) {
loaded()
} else {
img.addEventListener('load', loaded)
img.addEventListener('error', function() {
alert('error')
})
}
</code></pre>
<p>Source: <a href="http://www.html5rocks.com/en/tutorials/es6/promises/" rel="noreferrer">http://www.html5rocks.com/en/tutorials/es6/promises/</a></p>
|
<p>If you are using React.js, you could do this:</p>
<pre><code>render() {
</code></pre>
<p>// ...</p>
<pre><code><img
onLoad={() => this.onImgLoad({ item })}
onError={() => this.onImgLoad({ item })}
src={item.src} key={item.key}
ref={item.key} />
</code></pre>
<p>// ...
}</p>
<p>Where:
<li>- onLoad (...) now will called with something like this:
{ src: "<a href="https://......png" rel="nofollow noreferrer">https://......png</a>", key:"1" }
you can use this as "key" to know which images is loaded correctly and which not.
<li>- onError(...) it is the same but for errors.
<li>- the object "item" is something like this { key:"..", src:".."}
you can use to store the images' URL and key in order to use in a list of images.</p>
| 35,400
|
<p>I am a Delphi novice, but I'm trying to understand the relationship between TApplication and TfrmMain windows using Spy++. It seems that the TfrmMain window is the real window that has proper screen coordinates, but the TApplication window is the one that appears in the Windows taskbar. Also, they don't seem to be related to each other at all. One isn't the parent window of the other, so how are the windows linked together? And why is the non-UI window the one that gets the Windows taskbar button? Can any Delphi experts help me understand this?</p>
|
<p>TApplication is the class that encapsulates your application and handles things like the Windows Messaging. TfrmMain will be a subclass of TForm which will be your Applications "Main Form".</p>
<p>So basically, TApplication is the controller so to speak and it owns and creates TfrmMain, and forwards messages to it, or any of it's children.</p>
<p>Look in your projectname.pas file and you'll see something like:</p>
<pre><code>program Project1;
uses
Forms,
Unit1 in 'Unit1.pas' {Form1};
{$R *.RES}
begin
Application.Initialize;
Application.CreateForm(TfrmMain, frmMain) ;
Application.Run;
end.
</code></pre>
<p>where Application is of type TApplication.</p>
|
<p>With applications made with versions of Delphi BEFORE Delphi 2007, the "secret window" would be the visible window in Vista's Flip 3D or preview. Here's a great article explaining how to compile Delphi applications on Delphi 2006 (and earlier) so that the "secret window" is not shown: <a href="http://www.installationexcellence.com/articles/VistaWithDelphi/Original/Index.html#Wheres_My_Induction" rel="nofollow noreferrer">here</a></p>
| 45,763
|
<p>I'm currently displaying a UIViewController like this:</p>
<pre><code>[[self navigationController] presentModalViewController:modalViewController animated:YES];
</code></pre>
<p>and hiding it like this:</p>
<pre><code>[self.navigationController dismissModalViewControllerAnimated:YES];
</code></pre>
<p>The animation is "slide up from the bottom"... then slide back down. How can I change the animation style? Can I made it fade in/out?</p>
<p>Cheers!</p>
|
<p>For iPhone 3.0+, a basic crossfade is easiest to do like this:</p>
<pre><code>modalViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[[self navigationController] presentModalViewController:modalViewController
animated:YES];
</code></pre>
|
<p>It should be <code>[self.view.window]</code> in order for the code to work</p>
<p>(at least that's the way that it is in ios 3.2)</p>
| 29,371
|
<p>What exactly is GUID? Why and where I should use it? <br/>
I've seen references to GUID in a lot of places, and in wikipedia,
but it is not very clear telling you where to use it.
If someone could answer this, it would be nice.
Thanks</p>
|
<p>GUID technically stands for globally unique identifier. What it is, actually, is a 128 bit structure that is <em>unlikely</em> to ever repeat or create a collision. If you do the maths, the domain of values is in the <a href="https://en.wikipedia.org/wiki/Names_of_large_numbers#Standard_dictionary_numbers" rel="noreferrer">undecillions</a>.</p>
<p>Use guids when you have multiple independent systems or clients generating ID's that need to be unique. </p>
<p>For example, if I have 5 client apps creating and inserting transactional data into a table that has a unique constraint on the ID, then use guids. This prevents having to force a client to request an issued ID from the server first.</p>
<p>This is also great for object factories and systems that have numerous object types stored in different tables where you don't want any 2 objects to have the same ID. This makes caching and scavenging schemas much easier to implement.</p>
|
<p>To actually see what it looks like on a windows computer, go to cmd or powershell.</p>
<ol>
<li><p>Powershell => <code>[guid]::NewGuid()</code></p>
</li>
<li><p>CMD => <code>powershell [guid]::NewGuid()</code></p>
</li>
</ol>
<p><a href="https://i.stack.imgur.com/LMEoD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LMEoD.png" alt="enter image description here" /></a></p>
| 48,594
|
<p>I need to extract the icon from a windows shortcut (.lnk) file (or find the icon file, if it's just pointed to by the shortcut).</p>
<p>I'm not asking about extracting icons from exe's, dll's, etc. The shortcut in question is created when I run a installation program. And the icon displayed by the shortcut is not contained in the .exe that the shortcut points to. Presumably the icon is embedded in the .lnk file, or the .lnk file contains a pointer to where this icon lives. But none of the utilities I've found work address this -- they all just go to the .exe.</p>
<p>Many thanks!</p>
|
<p>This thread provides interesting informations about the <a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1407242&SiteID=1" rel="noreferrer">data contained in a .lnk file</a></p>
<p>The <a href="http://www.codeproject.com/KB/shell/systemiconsimagelist.aspx?display=PrintAll" rel="noreferrer">sSHGetFileInfoss</a> function should be able to extract the icon file.</p>
<p>Documented <a href="http://msdn.microsoft.com/en-us/library/bb762179.aspx" rel="noreferrer">here</a>, and used for a lnk file:</p>
<pre><code>Path2Link := 'C:\Stuff\TBear S Saver.lnk';
SHGetFileInfo(PChar(Path2Link), 0, ShInfo1, SizeOf(TSHFILEINFO),
SHGFI_ICON);
// this ShInfo1.hIcon will have the Icon Handle for the Link Icon with
// the small ShortCut arrow added}
</code></pre>
<p>From the first link, you could build such an utility in c#, where you would declare this function like:</p>
<pre><code>[DllImport("shell32.dll")]
public static extern IntPtr SHGetFileInfo(
string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi,
uint cbSizeFileInfo, uint uFlags);
</code></pre>
<hr>
<p>You could also built an utility in <a href="http://www.autoitscript.com/forum/index.php?s=36edb56d0daa23b6cf8c4f3ec49dcb84&showtopic=70788" rel="noreferrer">autoit script language</a>, where you would use that function declared like this:</p>
<pre><code>Func _ShellGetAssocIcon(Const $szFile,Const $IconFlags = 0)
Local $tFileInfo = DllStructCreate($tagSHFILEINFO)
If @error Then
Return SetError(1,@extended,0)
EndIf
Local $Ret = DllCall("shell32.dll","int","SHGetFileInfo","str",$szFile,"dword",0, _
"ptr",DllStructGetPtr($tFileInfo),"uint",DllStructGetSize($tFileInfo),"uint",BitOr($SHGFI_ICON,$IconFlags))
MsgBox(0,0,@error)
Return DllStructGetData($tFileInfo,"hIcon")
EndFunc
</code></pre>
|
<p>To add a few more resources to this, because presumeably you wan't the Application's icon and not icon that has the shortcut in the bottom left corner:</p>
<ul>
<li><a href="http://www.msjogren.net/dotnet/eng/samples/dotnet_shelllink.asp" rel="nofollow noreferrer">Here's how to parse the LNK format using the WinApi's IShellLink</a></li>
<li><a href="http://www.pinvoke.net/default.aspx/Interfaces/IShellLinkA.html" rel="nofollow noreferrer">An IShellLink definition</a></li>
<li><a href="http://www.stdlib.com/art6-Shortcut-File-Format-lnk.html" rel="nofollow noreferrer">The LNK format if you don't want to use IShellLink to parse it</a></li>
</ul>
| 44,626
|
<p>This is baffling me, maybe somebody can shine the light of education on my ignorance. This is in a C# windows app. I am accessing the contents of a listbox from a thread. When I try to access it like this<pre><code>prgAll.Maximum = lbFolders.SelectedItems.Count;</code></pre>
I get the error. However, here is the part I don't get. If I comment out that line, the very next line<pre><code>foreach (string dir in lbFolders.SelectedItems)</code></pre>
executes just fine.</p>
<p>Edit:
As usual, my communication skills are lacking. Let me clarify.</p>
<p>I know that accessing GUI items from threads other than the ones they were created on causes problems. I know the right way to access them is via delegate.</p>
<p>My question was mainly this:
Why can I access and iterate through the SelectedItems object just fine, but when I try to get (not set) the Count property of it, it blows up.</p>
|
<pre><code>prgAll.Maximum = lbFolders.SelectedItems.Count;
</code></pre>
<p>On that line you perform an assignment (<strong>set/add</strong>), which by default is not thread-safe.</p>
<p>On the second line it's just a <strong>get</strong> operation, where thread-safety merely doesn't matter.</p>
<p>EDIT: I don't mean access to the prgAll element.</p>
<p>Accessing the Count property <strong>changes the internal state</strong> of the ListBox inner collection, that is why it throws the exception.</p>
|
<p>Try this:</p>
<pre><code>private delegate void xThreadCallBack();
private void ThreadCallBack()
{
if (this.InvokeRequired)
{
this.BeginInvoke(new xThreadCallBack(ThreadCallBack));
}
else
{
//do what you want
}
}
</code></pre>
<p>Though, the answer with the lambda expression would suffice.</p>
| 30,332
|
<p>For those of us that like to use the graphical version of Vim or Emacs, instead of the console version, which version do you recommend?</p>
<p>For Vim, there's <a href="http://sourceforge.net/projects/macosxvim/" rel="nofollow noreferrer">Mac OS X Vim</a>, <a href="http://code.google.com/p/macvim/" rel="nofollow noreferrer">MacVim</a>, <a href="http://code.google.com/p/vim-cocoa/" rel="nofollow noreferrer">Vim-Cocoa</a>.</p>
<p>For Emacs, <a href="http://www.apple.com/downloads/macosx/unix_open_source/carbonemacspackage.html" rel="nofollow noreferrer">CarbonEmacs</a>, <a href="http://www.xemacs.org/" rel="nofollow noreferrer">XEmacs</a>, and <a href="http://aquamacs.org/" rel="nofollow noreferrer">Aquamacs</a>.</p>
<p>Are there more? Which of these are ready for prime-time? If it's a tough call, what are the trade-offs? Are all of these still being maintained?</p>
<p>No discussion of Vim versus Emacs, if you don't mind, or comparisons with other editors.</p>
|
<p><strong>MacVim</strong> works well and certainly looks more mature than Vim-Cocoa, moreover there is a Cocoa plugin architecture in the pipeline for MacVim (and someone is already working on a TextMate style file browser tray plugin which is a huge ++ IMHO).</p>
<p>There was also a Carbon version of Vim, but this didn't offer a great deal over the Terminal version. i.e. only allowed one window open, not very OSX in appearance...</p>
<p><strong>Aquamacs</strong> is very usable and looks pretty good. Supports both traditional Mac OS style keyboard shortcuts (command-O, command-S) and the Control/Meta shortcuts for those raised on traditional Emacs. It is definitely more Mac-like than Carbon Emacs. It seems stable and fast, but I am not an Emacs guru so I don't stress it all that much when I use it. I can't speak to the extensiveness of the included elisp packages, either.</p>
<p>Someone syncs Carbon Emacs with the upstream tree quarterly I think. Aquamacs has a more irregular schedule, but it's seen some pretty major updates over the last year.</p>
<p><strong>GNU Emacs</strong> for OSX can be found at <a href="http://emacsformacosx.com" rel="nofollow noreferrer">emacsformacosx.com</a>. In addition to the latest stable release, there are also pre-release test builds and nightly builds, and Atom feeds are provided for tracking all three release types.</p>
|
<p>I love CarbonEmacs because it sticks very close to the standard GNU Emacs distribution, while still fitting in nicely with the Mac desktop. To me, it "felt" like Emacs on my Ubuntu desktop even if it looked like a Mac application.</p>
| 2,386
|
<p>is there a way to add an existing classic ASP webapp into a solution in VS? The application is around 4000 files large and currently maintained outisde Visual Studio.</p>
|
<p>The best way to do this IMO is:-</p>
<p>In VS 2008 File | Open | Web Site...</p>
<p>In the dialog ensure File System is selected. Navigate to the physical folder that represents the root of your Web app.</p>
<p>Click Open. Job Done.</p>
|
<p>There's no real point though is there? As Classic ASP files aren't compiled. I keep just opening them individually as needed from File Explorer. </p>
<p>Although you could add them all to a VBProj or CSProj so you get them all showing up in your Solution Explorer, and could use features like Project -> Deploy. </p>
| 12,539
|
<p>how come this work </p>
<pre><code>public IQueryable<Category> getCategories(int postId)
{
subnusMVCRepository<Categories> categories = new subnusMVCRepository<Categories>();
subnusMVCRepository<Post_Category_Map> postCategoryMap = new subnusMVCRepository<Post_Category_Map>();
var query = from c in categories.GetAll()
join pcm in postCategoryMap.GetAll() on c.CategoryId equals pcm.CategoryId
where pcm.PostId == 1
select new Category
{
Name = c.Name,
CategoryId = c.CategoryId
};
return query;
}
</code></pre>
<p>but this does not</p>
<pre><code>public IQueryable<Category> getCategories(int postId)
{
subnusMVCRepository<Categories> categories = new subnusMVCRepository<Categories>();
subnusMVCRepository<Post_Category_Map> postCategoryMap = new subnusMVCRepository<Post_Category_Map>();
var query = from c in categories.GetAll()
join pcm in postCategoryMap.GetAll() on c.CategoryId equals pcm.CategoryId
where pcm.PostId == postId
select new Category
{
Name = c.Name,
CategoryId = c.CategoryId
};
return query;
}
</code></pre>
|
<p>The issue is most likely in the implementation of the query provider.</p>
<p>pcm.PostId == 1 </p>
<p>and</p>
<p>pcm.PostId == postId </p>
<p>actually have a big difference. In the expression tree the first is generated as a ConstantExpression which doesnt need to be evaulated.</p>
<p>With the second, the compiler actually generates an inner class here (this is the _DisplayClassX that you see). This class will have a property (will most likely be the same name as your parameter) and the expression tree will create a MemberAccessExpression which points to the auto-generated DisplayClassX. When you query provider comes accross this you need to Compile() the Lambda expression and evaluate the delegate to get the value to use in your query. </p>
<p>Hope this helps.</p>
<p>cosullivan</p>
|
<p>The problem is not the linq itself,
you need to be sure that the context or provider object is able to fetch the data.
try testing the </p>
<pre><code>subnusMVCRepository<Categories> categories = new subnusMVCRepository<Categories>();
subnusMVCRepository<Post_Category_Map> postCategoryMap = new subnusMVCRepository<Post_Category_Map>();
</code></pre>
<p>objects and see if they are populated or if they behaving as required.</p>
<p>you may want to search the generated code for c__DisplayClass1 and see what you can see there. some times the generated code dose some weird things.</p>
<p>when you step into you code check the locals and the variable values. this may also give you some clues.</p>
<p><strong>Edit :</strong> Have you tried to return a List<> collection ? or an Enumerable type?</p>
<p><strong>Edit :</strong> What is the real type of the <strong>item</strong> and query may not be iterable</p>
| 36,924
|
<p>Lets say I have a single object of type Car which I want to render as HTML:</p>
<pre><code>class Car {
public int Wheels { get; set; }
public string Model { get; set; }
}
</code></pre>
<p>I don't want to use the ASP.NET Repeater or ListView controls to bind because it seems too verbose. I just have the one object. But I still want to be able to use the databinding syntax so I won't have to use Labels or Literals. Something like:</p>
<pre><code><div>
Wheels: <%# (int)Eval("Wheels") %><br />
Model: <%# (string)Eval("Model") %>
</div>
</code></pre>
<p>Does anybody know about a control out there that does just that?</p>
<p>And I am not ready to switch to ASP.NET MVC just yet.</p>
<hr>
<p>Unfortunately, the DetailsView control doesn't satisfy my needs because it doesn't seem to support the template-style syntax that I am after. It, too, needs to be bound to a DataSource object of a kind.</p>
<p>I liked better the solution Maxim and Torkel suggested. I will try to go for that.</p>
|
<p>if the page is about a specific item (For exemple, Car.aspx?CarID=ABC123), I normally have a public property on the page called "CurrentCar"</p>
<pre><code>public Car CurrentCar { get; set; }
</code></pre>
<p>And I can then have the following:</p>
<pre><code><div>
Wheels: <%= CurrentCar.Wheels %><br />
Model: <%= CurrentCar.Model %>
</div>
</code></pre>
<p>That allow you to have type safety. Just make sure to have a valid object assigned before the actual rendering.</p>
|
<p>One drawback of the protected property solution is that you cannot use it to bind to properties of controls.</p>
<p>For example, the following would not work:</p>
<pre><code><asp:Label ID="Label1" Text="Probably a truck" Visible='<%# CurrentCart.Wheels > 4 %>' runat="server" />
</code></pre>
| 27,841
|
<p>All I need is a way to make a property of one class only 'settable' from one other class (a sort of manager class).</p>
<p>Is this even possible in c#?</p>
<p>My colleague 'reliably' informs me that I have a design flaw, but I feel I should at least ask the community before I concede defeat!</p>
|
<p>No, it's not really possible to do this in any clean way in C#. You probably have a design flaw ;-)</p>
|
<p>if it is a design flaw depends on what you want to do. You could use the StackTrace class from System.Diagnostics to get the Type of the class setting your property and then compare to the type you want to allow setting yor property..but maybe there are better ways for performing something like this (e.g. boxing)</p>
| 29,657
|
<p>I'm just starting my first project in ASP.NET MVC. In my webforms experience, I would usually have a separate project dedicated to my domain layer. In here, I would have my Domain specific objects along with my NHibernate mapping files and some business logic. Most of the examples I am seeing online are putting these classes along with business logic into the Models folder on the MVC app, then calling into this from the controller. From my experience, this would seem to make it harder to move that logic into a different platform if need be. Specifically, I was thinking about the possibility of needing to move it to a webforms app if the environment dictated it. This might be a naive question, but is it better to have the Domain data in its own project, or in the Models folder?</p>
|
<p>If you plan to reuse the model outside of the MVC app, a separate class library is still an acceptable setup. I do that, but leave the Models folder and put the models for my views in it.</p>
<p>If you would put your DAL in App_Code in a Webforms project, then I would put it in Models in your MVC project. Otherwise, keep using separate projects like you have been.</p>
|
<p>I layout my solutions in a similar manner -- businessLogic, dataaccess, domain objects all reside in one project. The view(s) (Web, Web services, windows forms, WPF..) all go into their own separate projects.</p>
<p>That way UI specific code doesn't filter down in to the lower layers of the application. In most web projects I've had to hack together a windows form to inject new data into the database or manage some type of the application that isnt' fesiable in the web medium.</p>
<p>If I bake in HttpCaching at the business level I wouldn't be able to switch between views.</p>
| 48,660
|
<p>This follows on from <a href="https://stackoverflow.com/questions/292395/php-templating">this question</a> where I was getting a few answers assuming I was using files for storing my HTML templates.</p>
<p>Before recently I've always saved 'compiled' templates as html files in a directory (above the root). My templates usually have two types of variable - 'static' variables which are not replaced on every usage but are used across the site - basically for ease of maintenanceif I decide to change the site name for example; and dynamic vars that change on every page load.</p>
<p>I always used to save these as files on the server - but my friend pointed out something I'd overlooked: why have 5-10 filesystem calls when you can have one database call?</p>
<p><strong>What I want to know is which is more efficient? Calling several HTML files from the system or calling several rows of templates from the database (in one query/call).</strong></p>
|
<p><strong>Don't Store Editable HTML In the database</strong></p>
<p>Seriously, because the maintenance overhead for mere changes becomes exhaustive once you realise you can no longer just pop open a text editor. </p>
<p>I worked on many projects which had HTML content in the database, and it was a constant nightmare of "find that row the content is on" and I really would liked to have <em>shot</em> the person whom made it. </p>
<p>Also, <strong>DON'T PREMATURELY OPTIMISE</strong> . If you find it a problem thats slowing the project down, then change it. Because making the code exhaustively less maintainable to save a millisecond. But design the code well enough that should you need to change where the content comes from later it should be easy to do. </p>
<blockquote>
<p>Surely that can be resolved by having
a suitable web interface for editing
the templates?</p>
</blockquote>
<p>Erm, really not, unless you're only trying to compete with notepad. Syntax highlighting and all the other full host of features you can get in a standard editor just make your developers suicidal when they find themselves editing web pages by hacking at an undersized text area with awful white on black ( not to mention the extra fun you get with having to worry about entity encoding etc, for instance, try editing html with in a text area where the html content contains a text area element! )</p>
<p><h3>On FileIO </h3> While File IO can be a bottleneck, keep in mind that if you have a proper linux install, and plenty of memory, a handy thing known as "disk-cache" takes effect, which in effect, keeps files used in memory, so file IO becomes mere memcpy.</p>
<p>On the contrary, in real stress tests on any of the code I have used, the biggest slowdowns have been in the database!, primarily the nice slow CONNECT string, query parse time, extra php<->mysql interactions. You're not really looking at gaining anything. Filesystem lookup is close to database index lookup, and you don't have any unknowns other than "you need to stream it from a disk", no table locking stuff to worry about!</p>
<p>You should probably try something like a caching library, X-Cache comes highly recommended, thats more likely to give you visible performance gains. </p>
|
<p>I pretty much agree with the gist of Kent Fredric's answer. But, if you really want to know, which is more efficient/faster, you cannot reasonably expect to get the answer here. If you want that answer, there is only one way to get it: profile the application both ways.</p>
| 37,312
|
<p>How do I go from this string: "ThisIsMyCapsDelimitedString"</p>
<p>...to this string: "This Is My Caps Delimited String"</p>
<p>Fewest lines of code in VB.net is preferred but C# is also welcome.</p>
<p>Cheers!</p>
|
<p>I made this a while ago. It matches each component of a CamelCase name.</p>
<pre><code>/([A-Z]+(?=$|[A-Z][a-z])|[A-Z]?[a-z]+)/g
</code></pre>
<p>For example:</p>
<pre><code>"SimpleHTTPServer" => ["Simple", "HTTP", "Server"]
"camelCase" => ["camel", "Case"]
</code></pre>
<p>To convert that to just insert spaces between the words:</p>
<pre><code>Regex.Replace(s, "([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))", "$1 ")
</code></pre>
<hr>
<p>If you need to handle digits:</p>
<pre><code>/([A-Z]+(?=$|[A-Z][a-z]|[0-9])|[A-Z]?[a-z]+|[0-9]+)/g
Regex.Replace(s,"([a-z](?=[A-Z]|[0-9])|[A-Z](?=[A-Z][a-z]|[0-9])|[0-9](?=[^0-9]))","$1 ")
</code></pre>
|
<p>There's probably a more elegant solution, but this is what I come up with off the top of my head:</p>
<pre><code>string myString = "ThisIsMyCapsDelimitedString";
for (int i = 1; i < myString.Length; i++)
{
if (myString[i].ToString().ToUpper() == myString[i].ToString())
{
myString = myString.Insert(i, " ");
i++;
}
}
</code></pre>
| 18,778
|
<p>I've seen a few fixes for allowing PNG images to have transparency in Internet Explorer 6, but I've yet to find one that also allows you to set the background position in CSS. If you use sprites, it's a deal-breaker. I've resorted to using GIF's (which are not as high quality), not using transparent images at all, or serving a completely different stylesheet to IE6. Is there a fix for IE6 that allows for PNG transparencies AND background positioning?</p>
|
<p>Yes. Convert your images to use indexed pallets (png256). You can support transparency (just like gif), but not an alpha channel.</p>
<p>You can do this using <a href="http://www.irfanview.com/" rel="nofollow noreferrer">Irfanview</a> and the pngout plugin, <a href="http://www.libpng.org/pub/png/apps/pngquant.html" rel="nofollow noreferrer">pngquant</a> or <a href="http://pngnq.sourceforge.net/" rel="nofollow noreferrer">pngnq</a>.</p>
<p>The YUI performance team also did a <a href="http://assets.en.oreilly.com/1/event/7/Image%20Optimization_%20How%20Many%20of%20These%207%20Mistakes%20Are%20You%20Making%20Presentation.ppt" rel="nofollow noreferrer">great presentation</a> that covers this an many other image optimization concepts.</p>
|
<p>You can actually use pure CSS to get positioned background images with alpha transparency in IE6 by taking advantage of IE6's alpha filters and the CSS <code>clip</code> property. Julien Lecomte <a href="http://www.julienlecomte.net/blog/2007/07/4/" rel="nofollow noreferrer">describes the technique on his blog</a>.</p>
<p>Note that this technique does result in a performance hit for each use of an alpha filter.</p>
| 11,205
|
<p>I have seen some gridview header freezing examples on the web but I have a special case where the gridview is in a fixed width div. The examples I tried make the header fixed but the full width of the header is shown and it overflows out of the div while the grid body has a horizontal scroll bar.</p>
<p>I need it to:<br>
1- Header and tbody scroll together horizontally and both confined in the fixed width div.<br>
2- Header is fixed while gridview body scrolls vertically.<br>
3- Don't want to use a commercial grid.<br>
4- I am using IE only. Don't care if it works in FF, Opera, ..etc.</p>
|
<p>I just wrote a jQuery plugin that does exactly what you need. You just build 1 table with a thead and tbody and it does the rest for you. Very simple to use...i posted the solution under another question linked below. Supported in IE6/7/8 too.</p>
<p><a href="https://stackoverflow.com/questions/486576/frozen-table-header-inside-scrollable-div/1533619#1533619">Frozen table header inside scrollable div</a></p>
<p>or a link straight to my plugin site:</p>
<p><a href="http://fixedheadertable.mmalek.com" rel="nofollow noreferrer">http://fixedheadertable.mmalek.com</a></p>
|
<p>Did you see this example?
<a href="http://web.tampabay.rr.com/bmerkey/examples/locked-column-csv.html" rel="nofollow noreferrer">http://web.tampabay.rr.com/bmerkey/examples/locked-column-csv.html</a></p>
| 32,962
|
<p>I am trying to input data from a .txt file into a scheme structure. Each element is separated by a tab in the data file and each structure set is on a new line. I want to be able to read in the data from one line into a structure and make a list of each structure set in the file. Any suggestions?</p>
|
<p>Not really sure what structures you had in mind, but say you had a text file like the following:</p>
<pre>
--> cat blah.txt
foo bar baz
1 2 3 4 5
aa bb cc dd ee
</pre>
<p>You could convert it directly into a list of lists in scheme using sed:</p>
<pre>
--> echo "(define mylist '("`sed -e 's/\(.*\)/(\1)/' blah.txt`"))" > foo.txt
</pre>
<p>which then produces the following file:</p>
<pre>
--> cat foo.txt
(define mylist '((foo bar baz) (1 2 3 4 5) (aa bb cc dd ee)))
</pre>
<p>And now all you have to do is load the file into scheme:</p>
<pre>
(load "foo.txt")
</pre>
<p>And you can access the structure via the `mylist' variable.</p>
|
<p>Sounds like a CSV file with tabs instead of commas. If you're using PLT Scheme (DrScheme/mzscheme)
neil's csv library is probably what you want.</p>
<p><a href="http://planet.plt-scheme.org/package-source/neil/csv.plt/1/2/doc.txt" rel="nofollow noreferrer">Here is the documentation</a>.</p>
<p>Here is how to load it remotely:</p>
<pre><code>(require (planet neil/csv:1:2/csv))
</code></pre>
<p>At least, that's what the instructions say. On my slightly oodate DrScheme, this is what worked:</p>
<pre><code>(require (planet "csv.ss" ("neil" "csv.plt" 1 (= 1))))
</code></pre>
| 42,523
|
<p>Regarding the same program as <a href="https://stackoverflow.com/questions/20061/store-data-from-a-c-application">my question a few minutes ago</a>... I added a setup project and built an MSI for the program (just to see if I could figure it out) and it works great except for one thing. When I tried to install it on my parent's laptop, their antivirus (the free Avast Home Edition) set off an alarm and accused my setup.exe of being a Trojan.</p>
<p>Does anyone have any idea why this would be happening and how I can fix it?</p>
|
<p>Indeed, boot from a clean CD (use a known good machine to build <a href="http://nu2.nu/pebuilder/" rel="nofollow noreferrer">BartPE</a> or something similar) and scan your machine thoroughly. Another good thing to check, though, would be exactly which virus Avast! thinks your program is. Once you know that, you should be able to look it up in one of the virus databases and insure that your software can't contain it.</p>
<p>The odds are that Avast! is just getting a false positive for some reason, and I don't know that there's much you can do about that other than contacting Avast! and hoping for a reply.</p>
|
<p>The very first thing to do would be to scan your build PC for viruses.</p>
| 4,051
|
<p>I'd love to figure it out myself but I was wondering <strong>roughly what's the algorithm for converting a function with yield statements into a state machine for an enumerator?</strong> For example how does C# turn this:</p>
<pre><code>IEnumerator<string> strings(IEnumerable<string> args)
{ IEnumerator<string> enumerator2 = getAnotherEnumerator();
foreach(var arg in arg)
{ enumerator2.MoveNext();
yield return arg+enumerator.Current;
}
}
</code></pre>
<p>into this:</p>
<pre><code>bool MoveNext()
{ switch (this.state)
{
case 0:
this.state = -1;
this.enumerator2 = getAnotherEnumerator();
this.argsEnumerator = this.args.GetEnumerator();
this.state = 1;
while (this.argsEnumerator.MoveNext())
{
this.arg = this.argsEnumerator.Current;
this.enumerator2.MoveNext();
this.current = this.arg + this.enumerator2.Current;
this.state = 2;
return true;
state1:
this.state = 1;
}
this.state = -1;
if (this.argsEnumerator != null) this.argsEnumerator.Dispose();
break;
case 2:
goto state1;
}
return false;
}
</code></pre>
<p>Of course the result can be completely different depending on the original code.</p>
|
<p>The particular code sample you are looking at involves a series of transformations.
Please note that this is an approximate description of the algorithm. The actual names used by the compiler and the exact code it generates may be different. The idea is the same, however.</p>
<p>The first transformation is the "foreach" transformation, which transforms this code:</p>
<pre><code>foreach (var x in y)
{
//body
}
</code></pre>
<p>into this code:</p>
<pre><code>var enumerator = y.GetEnumerator();
while (enumerator.MoveNext())
{
var x = enumerator.Current;
//body
}
if (y != null)
{
enumerator.Dispose();
}
</code></pre>
<p>The second transformation finds all the yield return statements in the function body, assigns a number to each (a state value), and creates a "goto label" right after the yield. </p>
<p>The third transformation lifts all the local variables and function arguments in the method body into an object called a closure. </p>
<p>Given the code in your example, that would look similar to this:</p>
<pre><code> class ClosureEnumerable : IEnumerable<string>
{
private IEnumerable<string> args;
private ClassType originalThis;
public ClosureEnumerator(ClassType origThis, IEnumerable<string> args)
{
this.args = args;
this.origianlThis = origThis;
}
public IEnumerator<string> GetEnumerator()
{
return new Closure(origThis, args);
}
}
class Closure : IEnumerator<string>
{
public Closure(ClassType originalThis, IEnumerable<string> args)
{
state = 0;
this.args = args;
this.originalThis = originalThis;
}
private IEnumerable<string> args;
private IEnumerator<string> enumerator2;
private IEnumerator<string> argEnumerator;
//- Here ClassType is the type of the object that contained the method
// This may be optimized away if the method does not access any
// class members
private ClassType originalThis;
//This holds the state value.
private int state;
//The current value to return
private string currentValue;
public string Current
{
get
{
return currentValue;
}
}
}
</code></pre>
<p>The method body is then moved from the original method to a method inside "Closure" called MoveNext, which returns a bool, and implements IEnumerable.MoveNext.
Any access to any locals is routed through "this", and any access to any class members are routed through this.originalThis.</p>
<p>Any "yield return expr" is translated into:</p>
<pre><code>currentValue = expr;
state = //the state number of the yield statement;
return true;
</code></pre>
<p>Any yield break statement is translated into:</p>
<pre><code>state = -1;
return false;
</code></pre>
<p>There is an "implicit" yield break statement at the end of the function.
A switch statement is then introduced at the beginning of the procedure that looks at the state number and jumps to the associated label. </p>
<p>The original method is then translated into something like this:</p>
<pre><code>IEnumerator<string> strings(IEnumerable<string> args)
{
return new ClosureEnumerable(this,args);
}
</code></pre>
<p>The fact that the state of the method is all pushed into an object and that the MoveNext method uses a switch statement / state variable is what allows the iterator to behave as if control is being passed back to the point immediately after the last "yield return" statement the next time "MoveNext" is called.</p>
<p>It is important to point out, however, that the transformation used by the C# compiler is not the best way to do this. It suffers from poor performance when trying to use "yield" with recursive algorithms. There is a good paper that outlines a better way to do this here:</p>
<p><a href="http://research.microsoft.com/en-us/projects/specsharp/iterators.pdf" rel="nofollow noreferrer">http://research.microsoft.com/en-us/projects/specsharp/iterators.pdf</a></p>
<p>It's worth a read if you haven't read it yet.</p>
|
<p>Raymond Chen answers this <a href="https://devblogs.microsoft.com/oldnewthing/20080812-00/?p=21273" rel="nofollow noreferrer">here</a>.</p>
| 15,997
|
<p>Is it possible for a stand alone executable to generate a report and output it as PDF (or one of the other export options available from the report viewer) without displaying the ReportViewer control? </p>
<p>The report definition should be embedded in the executable and should not use the Reporting Services web service.</p>
|
<p>Actually you don't need a ReportViewer at all, you can directly instantiate and use a LocalReport:</p>
<pre><code>LocalReport report = new LocalReport();
report.ReportPath = "templatepath";
// or use file from resource with report.ReportEmbeddedResource
// add parameters, datasource, etc.
Warning[] warnings;
string[] streamids;
string mimeType;
string encoding;
string filenameExtension;
byte[] bytes;
bytes =report.Render("PDF", null, out mimeType, out encoding, out filenameExtension, out streamids, out warnings);
// save byte[] to file with FileStream or something else
</code></pre>
|
<p>Can you pass a .rdlc report directly to pdf with parameters? I have two dropdownlists that i pull my report with. I can't get the parameters to work when automatically exporting to pdf. Here is the error I get: Microsoft.ReportingServices.ReportProcessing.ReportProcessingException: One or more parameters required to run the report have not been specified.</p>
<p>The dropdownlists work when I use the reportviewer, but i want to skip this step. I can also get my data to go directly to a pdf if it doesn't have any parameters. My dropdownlists are called ddlyear and ddlmonth.</p>
| 16,727
|
<p>I am looking for a simple, clean, correct XML parser to use in my C++ project. Should I write my own?</p>
|
<p>How about <a href="http://rapidxml.sourceforge.net/" rel="noreferrer"><strong>RapidXML</strong></a>? RapidXML is a very fast and small XML DOM parser written in C++. It is aimed primarily at embedded environments, computer games, or any other applications where available memory or CPU processing power comes at a premium. RapidXML is licensed under Boost Software License and its source code is freely available.</p>
<p><strong>Features</strong></p>
<ul>
<li>Parsing speed (including DOM tree
building) approaching speed of
strlen function executed on the
same data.</li>
<li>On a modern CPU (as of 2008) the
parser throughput is about 1 billion
characters per second. See
Performance section in the Online
Manual.</li>
<li>Small memory footprint of the code
and created DOM trees.</li>
<li>A headers-only implementation,
simplifying the integration process.</li>
<li>Simple license that allows use for
almost any purpose, both commercial
and non-commercial, without any
obligations.</li>
<li>Supports UTF-8 and partially UTF-16,
UTF-32 encodings.</li>
<li>Portable source code with no
dependencies other than a very small
subset of C++ Standard Library.</li>
<li>This subset is so small that it can
be easily emulated manually if use
of standard library is undesired.</li>
</ul>
<p><strong>Limitations</strong></p>
<ul>
<li>The parser ignores DOCTYPE
declarations. </li>
<li>There is no support for XML namespaces.</li>
<li>The parser does not check for
character validity.</li>
<li>The interface of the parser does not
conform to DOM specification.</li>
<li>The parser does not check for
attribute uniqueness.</li>
</ul>
<p>Source: <a href="http://en.wikipedia.org/wiki/Rapidxml" rel="noreferrer">wikipedia.org://Rapidxml</a></p>
<hr>
<p>Depending on you use, you may use an XML Data Binding? <a href="http://www.codesynthesis.com/products/xsd/" rel="noreferrer"><strong>CodeSynthesis XSD</strong></a> is an XML Data Binding compiler for C++ developed by Code Synthesis and dual-licensed under the GNU GPL and a proprietary license. Given an XML instance specification (XML Schema), it generates C++ classes that represent the given vocabulary as well as parsing and serialization code.</p>
<p>One of the unique features of CodeSynthesis XSD is its support for two different XML Schema to C++ mappings: in-memory C++/Tree and stream-oriented C++/Parser. The C++/Tree mapping is a traditional mapping with a tree-like, in-memory data structure. C++/Parser is a new, SAX-like mapping which represents the information stored in XML instance documents as a hierarchy of vocabulary-specific parsing events. In comparison to C++/Tree, the C++/Parser mapping allows one to handle large XML documents that would not fit in memory, perform stream-oriented processing, or use an existing in-memory representation.</p>
<p>Source: <a href="http://en.wikipedia.org/wiki/CodeSynthesis_XSD" rel="noreferrer">wikipedia.org://CodeSynthesis XSD</a></p>
|
<p>Try <a href="http://sourceforge.net/projects/tinyxml" rel="nofollow noreferrer">TinyXML</a> or <a href="http://www.ambiera.com/irrxml/" rel="nofollow noreferrer">IrrXML</a>...Both are lightweight XML parsers ( I'd suggest you to use TinyXML, anyway ). </p>
| 20,591
|
<p>I am trying to take a shapefile of subdivisions within a county that I have created and line it up with another shapefile that was given to me by the County Appraisal District (parcel data). When I try to get them to line up then my streets shapefiles is not aligned with everything else. They are all on the same coordinate system and I do not want to have to recreate the shapefile for the subdivisions. Any thoughts? </p>
|
<p>This is a question with answers that may be simple or may be very complex, depending on your situation. As a GIS developer, I've most commonly seen this as a symptom of an incorrectly defined coordinate system. However, whether this is the case or not, and what the solution is strongly depends on your environment. From here on, I'll assume that you're working in an ESRI package...</p>
<p>I agree with the other posters that your problem is one of mismatching projections and/or datum definitions. </p>
<p>The most important thing to understand as regards projections in ESRI software is this:</p>
<p><strong>Manually setting the projection of a dataset (shapefile, geodatabase feature class, etc) in ArcCatalog does NOT reproject that dataset!!!</strong></p>
<p>In order to reproject your data, you must EXPORT the data from an ArcMap session in which you've been working and where the data is obviously lined up correctly. During the EXPORT, you are given the choice of saving your data with the coordinate system of the underlying map or that of the original dataset.</p>
<p>Your best bet is to follow these steps to create a new dataset with the correct projection and then extrapolate what you need to do to fix your specific problem:</p>
<ol>
<li>Create a new ArcMap session and set its coordinate system:</li>
</ol>
<p>Do this in a fresh ArcMap session with NO OTHER DATA. Be sure to explicitly set the coordinate system of the ArcMap mapview to your desired coordinate system (I recommend the one that matches the data you're trying to overlay, or one from another well-established dataset). </p>
<ol>
<li><p>Add one other dataset with a known good coordinate system.</p></li>
<li><p>Create your new dataset in this ArcMap session. Give your new data the same coordinate system as the ArcMap mapview and the one other dataset in the map. Set the XY domain of the new data to exceed the area defined by your other dataset, but don't go beyond the size that will reduce your desired spatial resolution.</p></li>
<li><p>Create your data. It can be any data at this point. Some lines, some polygons, etc. Save your work. </p></li>
<li><p>Export your new dataset. When prompted, choose to save with the coordinate system of the underlying mapview.</p></li>
<li><p>Create a new ArcMap session and add your new dataset. Then add your parcel dataset. They should now occupy the same space in your map window.</p></li>
<li><p>Edit your new data to your heart's content.</p></li>
</ol>
<p>Some probable issues if this doesn't help:</p>
<ul>
<li><p>You didn't follow these steps correctly - check the ESRI documentation; this is a well documented issue.</p></li>
<li><p>The parcel data you're trying to match doesn't have properly defined coordinate system. It's always possible that the keepers of this data don't know what they're doing and have munged it up. I've seen this problem more times that I care to admit. </p></li>
<li><p>You've matched the projection but have mis-matched the datum. Many municipalities are still using data in NAD27, which is way out of date. Some have moved to the modern NAD83. The difference can be up to 300 meters, depending on where in the country you are. Also, data that originates from surveying or GPS equipment is usually collected in WGS84 (the typical default for satellite surveying), which is for all practical purposes the same as NAD83, at least at mapping scale resolutions.</p></li>
</ul>
<p>Try researching these issues and see how it goes. I'll say it again:</p>
<p><strong>Manually setting the projection does NOT actually project that data!!</strong></p>
<p>Good luck!</p>
|
<p>Your problem is probably one of projection</p>
<p>| projection: character string that names a map projection to use. See
| 'mapproject' (in the 'mapproj' library). The default is to
| use a rectangular projection with the aspect ratio chosen so
| that longitude and latitude scales are equivalent at the
| center of the picture.
`-----</p>
| 29,013
|
<p>I have designed this in Blender:</p>
<p><a href="https://i.stack.imgur.com/ucC7j.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ucC7j.png" alt="Screenshot"></a></p>
<p>The bottom is a regular n-gon with 0.8mm in height. In Slic3r, I see that the bottom-most layer is not solid:</p>
<p><a href="https://i.stack.imgur.com/5QkC7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5QkC7.png" alt="Screenshot"></a></p>
<p>The green parts (of the first image) are going into that layer, because I wanted to ensure that I don't have air between the bottom and the green parts. Unfortunately they become printed non-solid / empty. </p>
<p>This does not only take extra time for printing, it's also not what I want. What seems to be the bottom here is in fact the top of something and I want it to be a flat surface.</p>
<p>How can I tell Slic3r to recognize overlapping items and generate them in a solid way?</p>
<p>I have already set the infill to 100%, but that doesn't change anything. The Boolean modifier of Blender is also not very helpful. It creates topologies with gaps.</p>
|
<p>I printed the thing for some layers to see what the printer actually does:
<a href="https://i.stack.imgur.com/mwBgB.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mwBgB.jpg" alt="Inner ring"></a></p>
<p>There are clearly too many retractions and unretractions.</p>
<p>This can be seen in advance by letting Slic3r show the retractions and unretractions.
<a href="https://i.stack.imgur.com/8Vo55.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8Vo55.png" alt="Slic3r screenshots"></a></p>
<p><a href="https://i.stack.imgur.com/fDdn7.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fDdn7.jpg" alt="Green items"></a></p>
<p>For the green "walls", it became clear that it prints them exactly onto the empty space, so in fact the seem to be floating. </p>
<p>That made it obvious to me: the normals were pointing into the wrong direction. Therefore, Slic3r seems to have interpreted the material side of the green parts inside out. I had the same issue on some other parts as well.</p>
<p>I went to Blender, selected the object(s), chose edit mode and found a function called "Recalculate normals". Since then, the bottom layer is solid.</p>
<p>Also printing time is reduced by half an hour.</p>
<p><a href="https://i.stack.imgur.com/kDh7y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kDh7y.png" alt="Result after recalculating the normals"></a></p>
|
<p>Blender is not a preferred program to model solids, it is great though for many other visualizations. Apparently, the green parts are not solid models in your original Blender design, they are most probably surfaces, when you create an STL, the model is not solid, it contains surfaces. All this causes problems for your slicer (the slicer ignores the surfaces and makes an empty hole instead, hence the sliced image). You should look into the options, manuals or fora of Blender to create solid models. Otherwise, use a proper 3D modelling tool for creating solid models.</p>
| 1,111
|
<p>How do I configure Apache 2.0's log format so that it timestamps each request log with millisecond (or microsecond) accuracy? The <a href="http://httpd.apache.org/docs/2.0/logs.html" rel="nofollow noreferrer">docs</a> say that timestamps are specified in strftime format and strftime doesn't seem to handle anyting smaller than seconds.</p>
|
<p>I don't think it's possible (without rewriting APR, atleast). Apache uses <a href="https://apr.apache.org/docs/apr/2.0/group__apr__time.html#ga3f5e1aa45e735f3bcf8c13fb718c214f" rel="nofollow noreferrer">apr_strftime</a>. On Unix, this calls the C library's strftime, but doesn't even fill milliseconds into struct tm (not surprisingly, because this structure doesn't usually support milliseconds in the first place). The Windows versions isn't much different.</p>
|
<p>use %D option for microsecond accuracy</p>
| 43,505
|
<p>I need to cast single figures (1 to 9) to (01 to 09). I can think of a way but its big and ugly and cumbersome. I'm sure there must be some concise way. Any Suggestions</p>
|
<p>First of all, your description is misleading. <code>Double</code> is a floating point data type. You presumably want to pad your digits with leading zeros in a string. The following code does that:</p>
<pre><code>$s = sprintf('%02d', $digit);
</code></pre>
<p>For more information, refer to the documentation of <a href="http://php.net/sprintf" rel="noreferrer"><code>sprintf</code></a>.</p>
|
<p>Here is my solution to handle both positive and negative numbers</p>
<pre class="lang-php prettyprint-override"><code><?php
// add zeros to a number at left or right side.
function add_zeros_to_number( $number, $number_of_zeros, $zeros_position="left"){
// check if number is negative
$is_negative = FALSE;
if ( strpos($number , '-') !== FALSE ){
$is_negative = TRUE;
$number = substr($number, 1);
}
if($zeros_position == "right"){
$r = str_pad($number, $number_of_zeros, "0", STR_PAD_RIGHT);
}else{
$r = str_pad($number, $number_of_zeros, "0", STR_PAD_LEFT);
}
if( $is_negative ){
return "-".$r;
}else{
return $r;
}
}
// how to use
$number = -333; // Desire number
$number_of_zeros = 4; // number of zeros [ your number length + zeros ]
$position = "right"; // left or right . default left
echo $result = add_zeros_to_number($number, $number_of_zeros, $position);
// output
// -333 => -3330 left
// -333 => -0333 right
</code></pre>
| 42,006
|
<p>Often times I find myself using std::pair to define logical groupings of two related quantities as function arguments/return values. Some examples: row/col, tag/value, etc.</p>
<p>Often times I should really be rolling my own class instead of just using std::pair. It's pretty easy to see when things start breaking down - when the code becomes littered with make_pair, first, and second, its very hard to remember what is what - an <code>std::pair<int, int></code> conveys less meaning than a type <code>Position</code>.</p>
<p>What have you found are the best ways to wrap the functionality of std::pair in a type that conveys real meaning?</p>
<p>Here are some things I have considered:</p>
<pre><code>typedef std::pair<int, int> Position;
</code></pre>
<p>This at least gives the type a meaningful name when passing it around, but the type isn't enforced, its still really just a pair, and most of the same problems still exist. This is however very simple to write.</p>
<pre><code>struct Position : public std::pair<int, int>
{
typedef std::pair<int, int> Base;
Position() : Base() {}
Position(const Position &x) : Base(x) {}
Position(int a, int b) : Base(a, b) {}
int &row() { return first; }
const int &row() const { return first; }
int &col() { return second; }
const int &col() const { return second; }
};
</code></pre>
<p>This is better, since we can access the variables via a reasonably descriptive name. The problem here is that you can still access first and second, so its easy for the abstraction to leak. Also, accessing simple variables via functions makes the syntax annoying.</p>
<p>The obvious next step is to make the inheritance private:</p>
<pre><code>struct Position : private std::pair<int, int>
{
typedef std::pair<int, int> Base;
Position() {}
Position(const Position &x) : Base(x) {}
Position(int a, int b) : Base(a, b) {}
int &row() { return first; }
const int &row() const { return first; }
int &col() { return second; }
const int &col() const { return second; }
bool operator<(const Position &x) const { return Base(*this) < Base(x); }
// other forwarding operators as needed...
};
</code></pre>
<p>So now at least we have gotten rid of the access to first and second, but now a new problem pops up. When we want to store the type in an std::set, we now don't have access to the operator< overload since we don't have access to first and second. This means we have to define a forwarding function for each operator overload we want. For me this is usually ==, !=, and <, but there could be others that I'd want. Yes I know I probably shouldn't overload operator< just to stick it in an associative container, but it makes everything so darn simple... And defining these operators for each new type is a pain, and we STILL have to access via functions. We can fix that:</p>
<pre><code>struct Position
{
Position() {}
Position(const Position &x) : row(x.row), col(x.col) {}
Position(int row, int col) : row(row), col(col) {}
int row, col;
};
bool operator<(const Position &a, const Position &b)
{
return a.row < b.row || (!(b.row < a.row) && a.col < b.col);
}
// more overloads as needed
</code></pre>
<p>So now we have simple variable access, but now defining overloaded operators is even more of a pain, because instead of just forwarding them to the pair's implementation, we actually have to re-implement them each time...</p>
<p>Are there any solutions I have overlooked that make this easy without the drawbacks? If there aren't which would you tend to prefer?</p>
|
<p>This is what <a href="http://www.boost.org/doc/libs/1_36_0/libs/tuple/doc/tuple_users_guide.html" rel="nofollow noreferrer">Boost.Tuple</a> was made for.</p>
<p>But you should probably be using <a href="http://en.cppreference.com/w/cpp/utility/tuple" rel="nofollow noreferrer">std::tuple</a> now...</p>
|
<p>Unfortunately <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n2141.html" rel="nofollow noreferrer">strong <code>typedef</code>s</a> will not make it into <a href="http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2008/n2565.html" rel="nofollow noreferrer">C++0x</a>, it has been given the classification of <em>Not ready for C++0x, but open to resubmit in future</em>.</p>
| 24,738
|
<p>I am using VC++. Is <code>assert(false)</code> ignored in release mode?</p>
|
<p>If compiling in release mode includes defining NDEBUG, then yes.</p>
<p>See <a href="https://msdn.microsoft.com/library/9sb57dw4.aspx" rel="noreferrer">assert (CRT)</a></p>
|
<p>I think it is a mistake to rely too much on the exact behavior of the assert. The correct semantics of "assert(expr)" are:</p>
<ul>
<li>The expression expr may or may not be evaluated.</li>
<li>If expr is true, execution continues normally.</li>
<li>If expr is false, what happens is undefined.</li>
</ul>
<p>More at <a href="http://nedbatchelder.com/text/assert.html" rel="nofollow noreferrer">http://nedbatchelder.com/text/assert.html</a></p>
| 33,995
|
<p>This article on Microsoft's tech net site supplies an <code>exe</code> that will calculate your windows machine's minimum time resolution - this should be the smallest "tick" available to any application on that machine:</p>
<p><a href="http://technet.microsoft.com/en-us/sysinternals/bb897568.aspx" rel="nofollow noreferrer">http://technet.microsoft.com/en-us/sysinternals/bb897568.aspx</a></p>
<p>The result of running this app on my current box is 15.625 ms. I have also run tests against Internet Explorer and gotten the exact same resolution from the Date() javascript function.</p>
<p>What is confusing is that the SAME test I ran against IE gives back much finer resolution for Google's Chrome browser (resolution of 1ms) and for a flash movie running in IE (1ms). Can anyone explain how any application can get a clock resolution better then the machine's clock? If so, is there some way I can get a consistently better resolution in browsers other then Chrome (without using flash)?</p>
<p>The first answer below leads to two other questions:</p>
<ol>
<li>How does a multi-media timer get
times between system clock ticks. I
imagine the system clock as an
analog watch with a ticking hand,
each tick being 15ms. How are times
between ticks measured? </li>
<li>Are multimedia timers available to
browsers, especially Internet
Explorer? Can I access one with C#
or Javascript without having to push
software to a user's
browser/machine?</li>
</ol>
|
<p>You can get down to 1 ms with <a href="http://msdn.microsoft.com/en-us/library/ms712704(VS.85).aspx" rel="nofollow noreferrer">multimedia timers</a> and even further with QueryPerformanceCounter.</p>
<p>See also <a href="https://stackoverflow.com/questions/49668/getlocaltime-api-time-resolution#49720">GetLocalTime() API time resolution</a>.</p>
<p>EDIT: Partial answer to the new subquestion ...</p>
<p>System time resolution was around 15 ms on the Windows 3 and 95 architecture. On NT (and successors) you can get better resolution from the hardware abstraction layer (HAL). The <a href="http://blogs.msdn.com/oldnewthing/archive/2008/09/08/8931563.aspx" rel="nofollow noreferrer">QueryPerformanceCounter counts elapsed time, not CPU cycles</a> article, written by the Raymond Chen, may give you some additional insights.</p>
<p>As for the browsers - I have no idea what they are using for timers and how they interact with the OS.</p>
|
<p>The <a href="http://en.wikipedia.org/wiki/Intel_APIC_Architecture" rel="nofollow noreferrer">APIC</a> on the processor runs at bus speed and has a timer. They may be using that instead of the system time. (Or they might just be giving a bunch of precision that isn't there.)</p>
<p>This <a href="http://osdev.berlios.de/pic.html" rel="nofollow noreferrer">description of the Local APIC</a> mentions using it as a timer. </p>
<p>(It may also be the case that there is some performance counter they are using. That actually seems more likely since a device driver would be needed to program the APIC.)</p>
| 16,384
|
<p><code>Checkboxes</code> in <code>HTML</code> forms don't have implicit <em>labels</em> with them. Adding an explicit label (some text) next to it doesn't toggle the <code>checkbox</code>.</p>
<p><strong>How do I make a checkbox toggle from clicking on the text label as well?</strong></p>
|
<p>If you correctly markup your HTML code, there is no need for javascript. The following code will allow the user to click on the label text to tick the checkbox.</p>
<pre><code><label for="surname">Surname</label>
<input type="checkbox" name="surname" id="surname" />
</code></pre>
<p>The <em>for</em> attribute on the label element links to the <em>id</em> attribute on the input element and the browser does the rest.</p>
<p>This has been testing to work in:</p>
<ul>
<li>IE6</li>
<li>IE7</li>
<li>Firefox</li>
</ul>
|
<p>Wrapping with the label still doesn't allow clicking 'anywhere in the box' - still just on the text!
This does the job for me:</p>
<pre><code><div onclick="dob.checked=!dob.checked" class="checkbox"><input onclick="checked=!checked" id="dob" type="checkbox"/>Date of birth entry must be completed</div>
</code></pre>
<p>but unfortunately has lots of javascript that is effectively toggling twice.</p>
| 2,431
|
<p>I want to keep my website/s in version control (Subversion specifically) and use <code>svn co</code> to update it when there are stable versions to update, but I'm concerned about the security of doing so, as all the <code>.svn</code> folders will be public, and these include all sorts of private data, not least of which is complete source code to my website! </p>
<p>Is there anything I can I do to prevent this?</p>
|
<p>Two things:</p>
<ol>
<li><p>Do not use IfModule for functionality you need to be present. It's okay to do it for the autoindex because it might not be present and is not crucial to the scheme. But you are counting on rewrite being present to protect your content. Thus, it's better to remove the IfModule directive and let apache tell you when rewrite is not present for you to enable it (or at least know that you won't be 'protected' and consciously comment the lines)</p></li>
<li><p>No need to use rewrite there if you have access to main configuration files, much easier would be one of</p>
<pre><code><DirectoryMatch \.svn>
Order allow,deny
Deny from all
</DirectoryMatch>
</code></pre></li>
</ol>
<p>which will generate 403 Forbidden (which is better from HTTP compliance point of view)
or, if you want to take the security by obscurity route, use AliasMatch</p>
<pre><code> AliasMatch \.svn /non-existant-page
</code></pre>
<p>If you don't have access to main configuration files you're left with hoping mod_rewrite is enabled for usage in .htaccess.</p>
|
<p>Hiding the directories as Vinko says should work. But it would probably be simpler to use <a href="http://svnbook.red-bean.com/en/1.5/svn.ref.svn.c.export.html" rel="nofollow noreferrer">svn export</a> instead of svn co. This should not generate the .svn directories. </p>
| 26,415
|
<p>Ok, so I'm building bread crumbs and depending on the value of the breadcrumb an image will be the seperator. So "HOME" will have one image and "SEARCH" will have another. </p>
<p>I know I can do this programatically (at least I ASSUME) but is there an easier way to do this? Can I link an image to a node based on the value of the node? Can I do it with PathSeparatorTemplate? </p>
<p>Thank you. </p>
|
<p>You can put an</p>
<pre><code><asp:Image ... />
</code></pre>
<p>into the PathSerparatorTemplate but you still have to set the image url from code.</p>
|
<p>I see you have already accepted an answer, but I thought some code would help, so here is some:</p>
<h2>Site1.Master</h2>
<hr>
<pre><code> <asp:SiteMapPath ID="SiteMapPath1" Runat="server" OnItemDataBound="Item_Bound">
<PathSeparatorTemplate>
<asp:Image ID="SepImage" runat="server" ImageUrl="/images"/>
</PathSeparatorTemplate>
</asp:SiteMapPath>
</code></pre>
<h2>Site1.Master.cs</h2>
<hr>
<pre><code> private string lastItemKey = "";
public void Item_Bound(Object sender, SiteMapNodeItemEventArgs e)
{
if (e.Item.ItemType == SiteMapNodeItemType.PathSeparator)
{
string imageUrl = ((Image) e.Item.Controls[1]).ImageUrl;
imageUrl += lastItemKey + ".png";
((Image) e.Item.Controls[1]).ImageUrl = imageUrl;
}
else
{
lastItemKey = e.Item.SiteMapNode.Key;
}
}
</code></pre>
<p>Then I have an <code>/images</code> directory containing an image for each of the <code>Key</code>'s of the <code>SiteMapNode</code>s. In other terms: this code will result in the image being displayed, after each of the path nodes, to depend on the key of the node before it.</p>
<p>Hope this helps someone.</p>
| 24,218
|
<p>For example:</p>
<pre><code>public class A : A.B
{
public class B { }
}
</code></pre>
<p>Which generates this error from the compiler:</p>
<blockquote>
<p>Circular base class dependency
involving 'A' and 'A.B'</p>
</blockquote>
<p>I always figured a nested class behaved just like a regular class except with special rules concerning accessing the outer class's private members, but I guess there's some implicit inheritance occurring between the two classes?</p>
|
<p>There's no implicit inheritance involved as far as I can tell. I would have expected this to be okay - although I can imagine weirdness if A and B were generic.</p>
<p>It's specified in section 10.1.4 of the spec:</p>
<blockquote>
<p>When a class B derives from a class A,
it is a compile-time error for A to
depend on B. A class directly depends
on its direct base class (if any) and
<strong>directly depends on the class within
which it is immediately nested</strong> (if
any). Given this definition, the
complete set of classes upon which a
class depends is the transitive
closure of the directly depends on
relationship.</p>
</blockquote>
<p>I've highlighted the relevant section.</p>
<p>That explains why the compiler is rejecting it, but not why the language prohibits it. I wonder if there's a CLI restriction...</p>
<p>EDIT: Okay, I've had a response from Eric Lippert. Basically, it would be technically possible (there's nothing in the CLI to prohibit it), but:</p>
<ul>
<li>Allowing it would be difficult in the compiler, invalidating various current assumptions around ordering and cycles</li>
<li>It's a pretty odd design decision which is easier to prohibit than to support</li>
</ul>
<p>It was also noted on the email thread that it would make this kind of thing valid:</p>
<pre><code>A.B x = new A.B.B.B.B.B.B.B.B.B.B.B.B();
</code></pre>
<p>... but that would already (as noted by Tinister) be valid if B derived from A.</p>
<p>Nesting + inheritance = oddness...</p>
|
<p>This makes no sense to me... You are trying to extend something that doesn't exist !!! Class B only exists in the scope of class A and because of this I think there is some kind of inheritance.</p>
| 33,293
|
<p>I'm trying to write some LINQ To SQL code that would generate SQL like</p>
<pre><code>SELECT t.Name, g.Name
FROM Theme t
INNER JOIN (
SELECT TOP 5 * FROM [Group] ORDER BY TotalMembers
) as g ON t.K = g.ThemeK
</code></pre>
<p>So far I have</p>
<pre><code>var q = from t in dc.Themes
join g in dc.Groups on t.K equals g.ThemeK into groups
select new {
t.Name, Groups = (from z in groups orderby z.TotalMembers select z.Name )
};
</code></pre>
<p>but I need to do a top/take on the ordered groups subquery. According to <a href="http://blogs.msdn.com/vbteam/archive/2008/01/08/converting-sql-to-linq-part-7-union-top-subqueries-bill-horst.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/vbteam/archive/2008/01/08/converting-sql-to-linq-part-7-union-top-subqueries-bill-horst.aspx</a> in VB I could just add TAKE 5 on the end, but I can't get this syntax to work in c#. How do you use the take syntax in c#?</p>
<p>edit: PS adding .Take(5) at the end causes it to run loads of individual queries</p>
<p>edit 2: I made a slight mistake with the intent of the SQL above, but the question still stands. <b>The problem is that if you use extension methods in the query like .Take(5), LinqToSql runs lots of SQL queries instead of a single query.</b></p>
|
<p>Just bracket your query expression and call Take on it:</p>
<pre><code>var q = from t in dc.Themes
join g in dc.Groups on t.K equals g.ThemeK into groups
select new { t.Name, Groups =
(from z in groups orderby z.TotalMembers select z.Name).Take(5) };
</code></pre>
<p>In fact, the query expression isn't really making things any simpler for you - you might as well call OrderBy directly:</p>
<pre><code>var q = from t in dc.Themes
join g in dc.Groups on t.K equals g.ThemeK into groups
select new { t.Name, Groups = groups.OrderBy(z => z.TotalMembers).Take(5) };
</code></pre>
|
<p>Just bracket your query expression and call Take on it:</p>
<pre><code>var q = from t in dc.Themes
join g in dc.Groups on t.K equals g.ThemeK into groups
select new { t.Name, Groups =
(from z in groups orderby z.TotalMembers select z.Name).Take(5) };
</code></pre>
<p>In fact, the query expression isn't really making things any simpler for you - you might as well call OrderBy directly:</p>
<pre><code>var q = from t in dc.Themes
join g in dc.Groups on t.K equals g.ThemeK into groups
select new { t.Name, Groups = groups.OrderBy(z => z.TotalMembers).Take(5) };
</code></pre>
| 31,684
|
<p>I created a couple of tables procedurally via C# named something like <code>[MyTableOneCustom0]</code> and <code>[MyTableTwoCustom0]</code>. When I try to return all of the values from these tables via "Open Table" in MSSQL Server Management Studio, I receive the following error:</p>
<blockquote>
<p>Error Source:
Microsoft.VisualStudio.DataTools</p>
<p>Error Message: Exception has been
thrown by the target of an invocation.</p>
</blockquote>
<p>However, I can still bring up all of the data via a <code>SELECT *</code> statement.</p>
<p>Does anyone know what is causing this?</p>
|
<p>Based on a similar post loacated at at <a href="http://www.eggheadcafe.com/software/aspnet/30462589/exception-has-been-thrown.aspx" rel="nofollow noreferrer">Egg Head Cafe</a>, it looks like the Management Studio will thrown an exception if there are too many columns included explicitly in the query. Select * returns them implicitly, so there doesn't seem to be an issue.</p>
<p>I have over 800 columns in this table, so I'm sure this is the problem.</p>
|
<p>I hesitate to ask, but normally you would not want 800 or columns in a database, so why did you do this? Given how databases store information you are possibly creating many problems for yourself with a design like that in terms of data retrieval and storage. How many bytes of data woudl a full row have? You know there is a limit to the number of bytes of data that can be stored in a row. You could be setting yourself up for issues entering data when a row exceeds those limits. It might be best to break into separate tables even if there is a one-to-one relationship. Read in BOL about data pages and how data is stored to understand why this concerns me.</p>
| 12,866
|
<p>When I was learning Java coming from a background of some 20 years of procedural programming with basic, Pascal, COBOL and C, I thought at the time that the hardest thing about it was wrapping my head around the OOP jargon and concepts. Now with about 8 years of solid Java under my belt, I have come to the conclusion that the single hardest thing about programming in Java and similar languages like C# is the multithreaded/concurrent aspects.</p>
<p>Coding reliable and scalable multi-threaded applications is just plain hard! And with the trend for processors to grow "wider" rather than faster, it is rapidly becoming just plain critical.</p>
<p>The hardest area is, of course, controlling interactions between threads and the resulting bugs: deadlocks, race conditions, stale data and latency.</p>
<p>So my question to you is this: what approach or methodology do <em>you</em> employ for producing safe concurrent code while mitigating the potential for deadlocks, latency, and other problems? I have come up with an approach which is a little unconventional but has worked very well in several large applications, which I will share in a detailed answer to this question.</p>
|
<p>There are a number of techniques which are coming into the public consciousness just now (as in: the last few years). A big one would be actors. This is something that Erlang first brought to the grid iron but which has been carried forward by newer languages like Scala (actors on the JVM). While it is true that actors don't solve every problem, they do make it <em>much</em> easier to reason about your code and identify trouble spots. They also make it much simpler to design parallel algorithms because of the way they force you to use continuation passing over shared mutable state.</p>
<p>Fork/Join is something you should look at, especially if you're on the JVM. Doug Lea wrote the seminal paper on the topic, but many researchers have discussed it over the years. As I understand it, Doug Lea's reference framework is scheduled for inclusion into Java 7.</p>
<p>On a slightly less-invasive level, often the only steps necessary to simplify a multi-threaded application are just to reduce the complexity of the locking. Fine-grained locking (in the Java 5 style) is great for throughput, but very very difficult to get right. One alternative approach to locking which is gaining some traction through Clojure would be software-transactional memory (STM). This is essentially the opposite of conventional locking in that it is optimistic rather than pessimistic. You start out by assuming that you won't have any collisions, and then allow the framework to fix the problems if and when they occur. Databases often work this way. It's great for throughput on systems with low collision rates, but the big win is in the logical componentization of your algorithms. Rather than arbitrarily associating a lock (or a series of locks) with some data, you just wrap the dangerous code in a transaction and let the framework figure out the rest. You can even get a fair bit of compile-time checking out of decent STM implementations like GHC's STM monad or my experimental Scala STM.</p>
<p>There are a lot of new options for building concurrent applications, which one you pick depends greatly on your expertise, your language and what sort of problem you're trying to model. As a general rule, I think actors coupled with persistent, immutable data structures are a solid bet, but as I said, STM is a little less invasive and can sometimes yield more immediate improvements.</p>
|
<p>Writing all the code in a multi-threaded application very... carefully! I don't know any better answer than that. (This involves stuff like <a href="https://stackoverflow.com/questions/256517/best-programming-approachmethodology-to-assure-thread-safety#256535">jonnii</a> mentioned). </p>
<p>I've heard people argue (and agree with them) that the traditional threading model really won't work going into the future, so we're going to have to develop a different set of paradigms / languages to really use these newfangled multi-cores effectively. Languages like Haskell, whose programs are easily parallelizable since any function that has side effects must be explicitly marked that way, and Erlang, which I unfortunately don't know that much about.</p>
| 32,010
|
<p>I have installed Delphi Prism and XNA Game Studio 3.0. I have managed to translate to Delphi Prism XNA Tutorial 1 "Displaying a 3D Model on the Screen" (<a href="http://msdn.microsoft.com/en-us/library/bb197293.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/bb197293.aspx</a>).
Project compiles fine, but I cannot load a model. It looks like there is a new "contentproj" type in XNA that is not in Delphi Prism...
Any idea how to get it to work?</p>
|
<p>You could just manually build the content project using msbuild. It might not have the same integration where you can just add content and change settings in solution explorer ... but it'll do the trick :-) </p>
<p>here is more info about this: <a href="http://blogs.msdn.com/shawnhar/archive/2006/11/07/build-it-ahead-of-time.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/shawnhar/archive/2006/11/07/build-it-ahead-of-time.aspx</a></p>
|
<p>I haven't done any XNA stuff yet, but here is my best guess :-)</p>
<p>So, the Content Project type is a sub-project for a standard XNA project that just compiles the game content (textures, sound etc) as a nested compile process, correct?</p>
<p>So I would assume that there must be some reference to the sub-project in either the project file or the solution file, perhaps the best way would be to create a simple XMA proj in C# or VB and look at the generated meta-files (csproj, contentproj etc)</p>
<p><em>Edit:</em></p>
<hr>
<p><em>Oh, I'm suggesting here that you manually create the contentproj file and insert the reference, once you know what they look like, I assume that VS will then allow you to add, delete your content etc</em></p>
<hr>
<p>That then just leaves the question of how is the XNA content pipeline compile process is fired, if it doesn't "just happen" that might be a question for marc hoffman et al</p>
<p>Hope this helps a little, its just a guess.</p>
<p>Good to see you in StackOverFlow by the way.</p>
<p>Rgds Tim Jarvis.</p>
| 42,016
|
<p>I have an enumeration: <code>ENUM( 'alpha', 'beta', 'gamma', 'delta', 'omega' )</code></p>
<p>If I sort my table by this column I get them in the correct order defined above.</p>
<p>However, I can't find a way to select a subset of these, e.g. everything before delta. Using <code>WHERE status < 'delta'</code> only returns alpha and beta, not gamma. It seems MySQL uses a string comparison, not enum index comparison.</p>
<p>I could use the index numbers - i.e. <code>WHERE status < 4</code> - but it's a bit of a code smell (magic numbers) and may break if I insert new values into the enumeration.</p>
|
<p>You're trying to use data-manipulation methods on metadata, and this is bound to be awkward. </p>
<p>This is a good reason to replace the <code>ENUM</code> with a foreign key to a lookup table. Then you can use conventional data-manipulation techniques.</p>
|
<p>Create a function:</p>
<pre><code>CREATE fEnumIndex(_table VARCHAR(50), _col VARCHAR(50), _val VARCHAR(50))
RETURNS INT DETERMINISTIC
BEGIN
DECLARE _lst VARCHAR(8192);
DECLARE _ndx INT;
SELECT REPLACE(REPLACE(REPLACE(COLUMN_TYPE,''', ''',','),'enum(',''),')','')
FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND
TABLE_NAME=_table AND COLUMN_NAME=_col INTO _lst;
SET _ndx = FIND_IN_SET(_val, _lst);
RETURN _ndx;
END
</code></pre>
<p>Then use it in a query as follows:</p>
<pre><code>SELECT * FROM MyTable WHERE Status < fEnumIndex('MyTable','Status','delta') ;
</code></pre>
<p>The <code>SELECT REPLACE(REPLACE(REPLACE(COLUMN_TYPE,''', ''',','),'enum(',''),')','')</code> will take the <code>COLUMN_TYPE</code> such as <code>ENUM( 'alpha', 'beta', 'gamma', 'delta', 'omega' )</code> and turn it into a comma-separated list: <code>'alpha, beta, gamma, delta, omega'</code>. Then the <code>FIND_IN_SET(_val, _lst)</code> gets the index.</p>
<p>The only thing you need to be careful with is how you define the ENUMs (with or without spaces between the items) and the inner-most <code>REPLACE</code> (with or without a space in the from_string).</p>
| 37,601
|
<p>IIS is literally sending <code><?php ... ?></code> code to the browser rather then executing it.</p>
<p>But, only for the root <code>http://domain.com/index.php</code> file.</p>
<p>All other .php files in that folder and index.php files in subfolders execute as expected.</p>
<p>How can I get my root index.php code to execute?</p>
<hr>
<p>Update: "index.php" is a Default Document of my Web Site...</p>
<p><a href="http://img412.imageshack.us/img412/4130/defaultdocumentmt9.gif" rel="nofollow noreferrer">alt text http://img412.imageshack.us/img412/4130/defaultdocumentmt9.gif</a></p>
|
<ul>
<li><a href="http://forums.devshed.com/iis-97/iis-5-1-does-not-run-php-properly-under-root-163070.html" rel="nofollow noreferrer">IIS 5.1 does not run PHP properly under root directory, but fine in all other folders</a></li>
<li><a href="http://www.simmonsconsulting.com/2008/04/21/running-a-wordpress-blog-in-site-root-using-iis/" rel="nofollow noreferrer">Running a WordPress blog in site root using IIS</a></li>
</ul>
<p>UPDATED: I have found a few possible workarounds for PHP 5 and IIS 7. If those solutions are not working, please provide more details about your <code>index.php</code>, IIS setup, or try to use IIS 6 compatibility.</p>
<ul>
<li><a href="http://codingforums.com/showthread.php?t=148637" rel="nofollow noreferrer">Problem with PHP Includes on IIS7</a></li>
<li><a href="http://www.webmasterworld.com/php/3685216.htm" rel="nofollow noreferrer">PHP5 set-up - Relative paths for includes and other file references</a></li>
</ul>
|
<p>All though this is an old question, over 11 years later this is still an issue. My work around was to create default.aspx file and perform a redirect from within it. Save the file to the root directory of your website and add default.aspx to the default documents in IIS. Make sure you move it to the top of the list to prioritize it to be processed first. The below code is what I used.</p>
<pre><code><%@ Page Language="C#" %>
<!DOCTYPE html>
<script runat="server">
protected override void OnLoad(EventArgs e) {
Response.Redirect("index.php");
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Title Of Your Website Here</title>
</head>
</code></pre>
| 22,904
|
<p>I've seen this weird behavior on several sites recently: I scroll down a page and follow a link to another page. When I click the Back button and return, I am left back at the top of the previous page, not at the link. This is very annoying if I'm clicking on links in a search results page or a list of "10 Best Foo Bars...".</p>
<p>See this page as an <a href="http://www.typophile.com/forum/5" rel="nofollow noreferrer">example</a>. Strangely, the page works as expected in IE6 on WinXP, but not on FF2 on the same machine. On Mac OS X 10.4 it works in FF2, but not in FF3. I checked for any weird preference settings, but I can't find any that are different.</p>
<p>Any idea what is causing this?</p>
|
<p>Many sites have a text box (for searching the site, or something) that is set to automatically take focus when the page loads (using javascript or something). In many browsers, the page will jump to that text box when it gets focus.</p>
<p>It really is very annoying :(</p>
|
<p>Typically this behaviour is caused by the browser cache set by the site having a small or no time before expiry.</p>
<p>On many sites, when you hit "back" you get brought back to the link you hit, as your browser is pulling the page from your cache. If this cache has not been set, a new page request is made, and the browser treats it as fresh content.</p>
<p>On the page <a href="http://www.typophile.com/forum/5" rel="nofollow noreferrer">linked above</a>, the <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.21" rel="nofollow noreferrer">"Expires" header</a> seems to be set to less than a minute ahead of my local clock, which is causing my browser to get a fresh copy when I hit "back" after that expiry time.</p>
| 9,523
|
<p>What is the best way of doing case-insensitive string comparison in C++ without transforming a string to all uppercase or all lowercase?</p>
<p>Please indicate whether the methods are Unicode-friendly and how portable they are.</p>
|
<p>Boost includes a handy algorithm for this:</p>
<pre><code>#include <boost/algorithm/string.hpp>
// Or, for fewer header dependencies:
//#include <boost/algorithm/string/predicate.hpp>
std::string str1 = "hello, world!";
std::string str2 = "HELLO, WORLD!";
if (boost::iequals(str1, str2))
{
// Strings are identical
}
</code></pre>
|
<pre class="lang-c++ prettyprint-override"><code>bool insensitive_c_compare(char A, char B){
static char mid_c = ('Z' + 'a') / 2 + 'Z';
static char up2lo = 'A' - 'a'; /// the offset between upper and lowers
if ('a' >= A and A >= 'z' or 'A' >= A and 'Z' >= A)
if ('a' >= B and B >= 'z' or 'A' >= B and 'Z' >= B)
/// check that the character is infact a letter
/// (trying to turn a 3 into an E would not be pretty!)
{
if (A > mid_c and B > mid_c or A < mid_c and B < mid_c)
{
return A == B;
}
else
{
if (A > mid_c)
A = A - 'a' + 'A';
if (B > mid_c)/// convert all uppercase letters to a lowercase ones
B = B - 'a' + 'A';
/// this could be changed to B = B + up2lo;
return A == B;
}
}
}
</code></pre>
<p>this could probably be made much more efficient, but here is a bulky version with all its bits bare.</p>
<p>not all that portable, but works well with whatever is on my computer (no idea, I am of pictures not words)</p>
| 3,273
|
<p>From a desktop application developer point of view, is there any difference between developing for Windows XP and developing for Windows Vista?</p>
|
<p><strong>User Interface</strong></p>
<p>Looking at the <a href="http://msdn.microsoft.com/en-us/library/aa511258.aspx" rel="nofollow noreferrer">Windows Vista User Experience Guidelines</a> you can see that they have changed many UI elements, which you should be aware of. Some major things to take note of:</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/aa511280.aspx" rel="nofollow noreferrer">Larger icons</a></li>
<li>New <a href="http://msdn.microsoft.com/en-us/library/aa511295.aspx" rel="nofollow noreferrer">font</a> (Which affects some custom UI constistency)</li>
<li>New <a href="http://msdn.microsoft.com/en-us/library/aa511268.aspx" rel="nofollow noreferrer">dialog box features</a> (<a href="http://msdn.microsoft.com/en-us/library/bb787471%28VS.85%29.aspx" rel="nofollow noreferrer">task dialogs</a>)</li>
<li>Altered <a href="http://msdn.microsoft.com/en-us/library/aa511293.aspx" rel="nofollow noreferrer">common dialogs</a> (like File Open, Save As, etc.)</li>
<li>Dialog text <a href="http://msdn.microsoft.com/en-us/library/aa974175.aspx" rel="nofollow noreferrer">style and tone</a>, and <a href="http://msdn.microsoft.com/en-us/library/aa974176.aspx" rel="nofollow noreferrer">look and feel</a></li>
<li>New <a href="http://msdn.microsoft.com/en-us/library/aa511302.aspx" rel="nofollow noreferrer">Aero Wizards</a></li>
<li>Redesigned <a href="http://msdn.microsoft.com/en-us/library/aa511500.aspx" rel="nofollow noreferrer">toolbars</a></li>
<li>Better <a href="http://msdn.microsoft.com/en-us/library/aa511297.aspx" rel="nofollow noreferrer">notification UI</a></li>
<li>New recommended method of including a <a href="http://msdn.microsoft.com/en-us/library/aa511327.aspx#search" rel="nofollow noreferrer">search control</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/aa511327.aspx#frames" rel="nofollow noreferrer">Glass</a></li>
</ul>
<p><strong>64-bit</strong></p>
<p>Vista has a 64-bit edition, and although XP did too, your users are more likely to use Vista 64 than XP 64. Now you have to deal with:</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/aa965884.aspx" rel="nofollow noreferrer">Registry virtualization</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/aa384232%28VS.85%29.aspx" rel="nofollow noreferrer">Registry redirection</a> (<a href="http://msdn.microsoft.com/en-us/library/ms724072%28VS.85%29.aspx" rel="nofollow noreferrer">Wow6432Node</a>)</li>
<li><a href="http://msdn.microsoft.com/en-us/library/aa384235.aspx" rel="nofollow noreferrer">Registry reflection</a></li>
<li><a href="http://www.microsoft.com/whdc/winlogo/drvsign/kmsigning.mspx" rel="nofollow noreferrer">Digital signatures for kernel modules</a></li>
<li>MSI installers have <a href="http://blogs.msdn.com/heaths/archive/2005/10/24/windows-installer-on-64-bit-platforms.aspx" rel="nofollow noreferrer">new properties</a> to deal with</li>
</ul>
<p><strong>UAC</strong></p>
<p><a href="http://en.wikipedia.org/wiki/User_Account_Control" rel="nofollow noreferrer">User Account Control</a> vastly affects the default permissions that your application has when interacting with the OS.</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/bb756996.aspx" rel="nofollow noreferrer">How UAC works and affects your application</a> (also see the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=BA73B169-A648-49AF-BC5E-A2EEBB74C16B&displaylang=en" rel="nofollow noreferrer">requirements doc</a>)</li>
<li><a href="http://msdn.microsoft.com/en-us/library/aa372468%28VS.85%29.aspx" rel="nofollow noreferrer">Installers have to deal with UAC</a></li>
</ul>
<p><strong>New APIs</strong></p>
<p>There are new APIs which are targeted at either new methods of application construction or allowing new functionality:</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/aa376210%28VS.85%29.aspx" rel="nofollow noreferrer">Cryptography API: Next Generation</a> (CNG)</li>
<li><a href="http://en.wikipedia.org/wiki/Extensible_Application_Markup_Language" rel="nofollow noreferrer">Extensible Application Markup Language</a> (XAML)</li>
<li><a href="http://msdn.microsoft.com/en-us/netframework/aa663324.aspx" rel="nofollow noreferrer">Windows Communication Foundation</a> (WCF)</li>
<li><a href="http://msdn.microsoft.com/en-us/netframework/aa663328.aspx" rel="nofollow noreferrer">Windows Workflow Foundation</a> (WF)</li>
<li>And <a href="http://msdn.microsoft.com/en-us/library/aa383874.aspx" rel="nofollow noreferrer">many more smaller ones</a></li>
</ul>
<p><strong>Installers</strong></p>
<p>Because installations can only use common runtimes they install after a transaction has completed, <a href="http://blogs.msdn.com/astebner/archive/2007/05/20/2760317.aspx" rel="nofollow noreferrer">custom actions</a> <a href="http://blogs.msdn.com/astebner/archive/2007/01/09/problems-with-custom-actions-that-depend-on-the-visual-c-8-0-runtime-files-on-windows-vista.aspx" rel="nofollow noreferrer">will fail</a> if your custom action dll requires the Visual C++ runtimes above the VS 2005 CRT (non-SP1).</p>
|
<p>By far the most painful part of moving an application from XP to Vista (from my point of view) is dealing with the numerous services and IPv6 stuff that uses ports which were previously free, and dealing with the Wireless Provisioning -> Native WiFi transition.</p>
<p>The UAC stuff is basically a moot point; there is very little the application developer needs to do.</p>
| 4,268
|
<p>I have a button inside an update panel that I would like to update the whole page. I have set <code>ChildrenAsTriggers="false"</code> and <code>UpdateMode="Conditional"</code>.</p>
<p>I have some sample code here that demonstrates my problem.</p>
<pre><code><asp:UpdatePanel ID="myFirstPanel" runat="server" ChildrenAsTriggers="false" UpdateMode="Conditional">
<ContentTemplate>
<asp:Button runat="server" ID="myFirstButton" Text="My First Button" onclick="myFirstButton_Click" />
<asp:Button runat="server" ID="mySecondButton" Text="My Second Button" onclick="mySecondButton_Click" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel ID="mySecondPanel" runat="server">
<ContentTemplate>
<asp:Label runat="server" ID="myFirstLabel" Text="My First Label"></asp:Label>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="myFirstButton" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
<asp:Label runat="server" ID="mySecondLabel" Text="My Second Label"></asp:Label>
</code></pre>
<p>And the code behind:</p>
<pre><code>protected void myFirstButton_Click(object sender, EventArgs e)
{
myFirstLabel.Text = "Inside Panel " + DateTime.Now.ToString("mm:ss");
}
protected void mySecondButton_Click(object sender, EventArgs e)
{
mySecondLabel.Text = "Outside Panel " + DateTime.Now.ToString("mm:ss");
}
</code></pre>
<p>I want to update the label that is not inside an update panel when the second button is clicked.
The second button needs to be in an update panel. I don't want to put the lable into an update panel.</p>
|
<p>Try adding a PostBackTrigger to the first UpdatePanel, for the secound button. That will tell that update panel, that the button should make a full postback.</p>
|
<p>If the label is not in an update panel the only way to refresh the value is by refreshing the entire page like in a normal postback. You would have to do a redirect to the same page to refresh it. The ajax framework knows to handle the redirects even if the request is from an update panel so just do an Response.Redirect(...) on the button click.</p>
| 27,322
|
<p>What I'd like to avoid: </p>
<pre><code>ManagementClass m = new ManagementClass("Win32_LogicalDisk");
ManagementObjectCollection managementObjects = m.GetInstances();
List<ManagementObject> managementList = new List<ManagementObject>();
foreach(ManagementObject m in managementObjects){
managementList.Add(m);
}
</code></pre>
<p>Isn't there a way to get that collection into a List that looks something like: </p>
<pre><code>List<ManagementObject> managementList = new List<ManagementObjec>(collection_array);
</code></pre>
|
<p>What version of the framework? With 3.5 you could presumably use:</p>
<pre><code>List<ManagementObject> managementList = managementObjects.Cast<ManagementObject>().ToList();
</code></pre>
<p>(edited to remove simpler version; I checked and <code>ManagementObjectCollection</code> only implements the non-generic <code>IEnumerable</code> form)</p>
|
<p>you can convert like below code snippet</p>
<pre><code>Collection<A> obj=new Collection<return ListRetunAPI()>
</code></pre>
| 22,773
|
<p>Input: A positive integer K and a big text. The text can actually be viewed as word sequence. So we don't have to worry about how to break down it into word sequence.<br>
Output: The most frequent K words in the text.</p>
<p>My thinking is like this. </p>
<ol>
<li><p>use a Hash table to record all words' frequency while traverse the whole word sequence. In this phase, the key is "word" and the value is "word-frequency". This takes O(n) time. </p></li>
<li><p>sort the (word, word-frequency) pair; and the key is "word-frequency". This takes O(n*lg(n)) time with normal sorting algorithm. </p></li>
<li><p>After sorting, we just take the first K words. This takes O(K) time. </p></li>
</ol>
<p>To summarize, the total time is O(n+n<em>lg(n)+K), Since K is surely smaller than N, so it is actually O(n</em>lg(n)).</p>
<p>We can improve this. Actually, we just want top K words. Other words' frequency is not concern for us. So, we can use "partial Heap sorting". For step 2) and 3), we don't just do sorting. Instead, we change it to be</p>
<p>2') build a heap of (word, word-frequency) pair with "word-frequency" as key. It takes O(n) time to build a heap;</p>
<p>3') extract top K words from the heap. Each extraction is O(lg(n)). So, total time is O(k*lg(n)).</p>
<p>To summarize, this solution cost time O(n+k*lg(n)).</p>
<p>This is just my thought. I haven't find out way to improve step 1).<br>
I Hope some Information Retrieval experts can shed more light on this question.</p>
|
<p>This can be done in O(n) time</p>
<p><strong>Solution 1:</strong></p>
<p>Steps:</p>
<ol>
<li><p>Count words and hash it, which will end up in the structure like this</p>
<pre><code>var hash = {
"I" : 13,
"like" : 3,
"meow" : 3,
"geek" : 3,
"burger" : 2,
"cat" : 1,
"foo" : 100,
...
...
</code></pre></li>
<li><p>Traverse through the hash and find the most frequently used word (in this case "foo" 100), then create the array of that size</p></li>
<li><p>Then we can traverse the hash again and use the number of occurrences of words as array index, if there is nothing in the index, create an array else append it in the array. Then we end up with an array like:</p>
<pre><code> 0 1 2 3 100
[[ ],[cat],[burger],[like, meow, geek],[]...[foo]]
</code></pre></li>
<li><p>Then just traverse the array from the end, and collect the k words.</p></li>
</ol>
<p><strong>Solution 2:</strong></p>
<p>Steps:</p>
<ol>
<li>Same as above</li>
<li>Use min heap and keep the size of min heap to k, and for each word in the hash we compare the occurrences of words with the min, 1) if it's greater than the min value, remove the min (if the size of the min heap is equal to k) and insert the number in the min heap. 2) rest simple conditions.</li>
<li>After traversing through the array, we just convert the min heap to array and return the array.</li>
</ol>
|
<p>Suppose we have a word sequence "ad" "ad" "boy" "big" "bad" "com" "come" "cold". And K=2.
as you mentioned "partitioning using the first letter of words", we got
("ad", "ad") ("boy", "big", "bad") ("com" "come" "cold")
"then partitioning the largest multi-word set using the next character until you have k single-word sets."
it will partition ("boy", "big", "bad") ("com" "come" "cold"), the first partition ("ad", "ad") is missed, while "ad" is actually the most frequent word.</p>
<p>Perhaps I misunderstand your point. Can you please detail your process about partition?</p>
| 22,467
|
<p>I will choose Java as an example, most people know it, though every other OO language was working as well.</p>
<p>Java, like many other languages, has interface inheritance and implementation inheritance. E.g. a Java class can inherit from another one and every method that has an implementation there (assuming the parent is not abstract) is inherited, too. That means the interface is inherited and the implementation for this method as well. I can overwrite it, but I don't have to. If I don't overwrite it, I have inherited the implementation.</p>
<p>However, my class can also "inherit" (not in Java terms) just an interface, without implementation. Actually interfaces are really named that way in Java, they provide interface inheritance, but without inheriting any implementation, since all methods of an interface have no implementation.</p>
<p>Now there was this <a href="http://www.javaworld.com/javaworld/jw-08-2003/jw-0801-toolbox.html" rel="noreferrer">article, saying it's better to inherit interfaces than implementations</a>, you may like to read it (at least the first half of the first page), it's pretty interesting. It avoids issues like the <a href="http://en.wikipedia.org/wiki/Fragile_base_class" rel="noreferrer">fragile base class problem</a>. So far this makes all a lot of sense and many other things said in the article make a lot of sense to me.</p>
<p>What bugs me about this, is that implementation inheritance means <strong>code reuse</strong>, one of the most important properties of OO languages. Now if Java had no classes (like James Gosling, the godfather of Java has wished according to this article), it solves all problems of implementation inheritance, but how would you make code reuse possible then?</p>
<p>E.g. if I have a class Car and Car has a method move(), which makes the Car move. Now I can sub-class Car for different type of cars, that are all cars, but are all specialized versions of Car. Some may move in a different way, these need to overwrite move() anyway, but most would simply keep the inherited move, as they move alike just like the abstract parent Car. Now assume for a second that there are only interfaces in Java, only interfaces may inherit from each other, a class may implement interfaces, but all classes are always final, so no class can inherit from any other class.</p>
<p>How would you avoid that when you have an Interface Car and hundred Car classes, that you need to implement an identical move() method for each of them? What concepts for code reuse other than implementation inheritance exist in the the OO world?</p>
<p>Some languages have Mixins. Are Mixins the answer to my question? I read about them, but I cannot really imagine how Mixins would work in a Java world and if they can really solve the problem here.</p>
<p>Another idea was that there is a class that only implements the Car interface, let's call it AbstractCar, and implements the move() method. Now other cars implement the Car interface as well, internally they create an instance of AbstractCar and they implement their own move() method by calling move() on their internal abstract Car. But wouldn't this be wasting resources for nothing (a method calling just another method - okay, JIT could inline the code, but still) and using extra memory for keeping internal objects, you wouldn't even need with implementation inheritance? (after all every object needs more memory than just the sum of the encapsulated data) Also isn't it awkward for a programmer to write dummy methods like</p>
<pre><code>public void move() {
abstractCarObject.move();
}
</code></pre>
<p>?</p>
<p>Anyone can imagine a better idea how to avoid implementation inheritance and still be able to re-use code in an easy fashion?</p>
|
<p>Short answer: Yes it is possible. But you have to do it on purpose and no by chance ( using final, abstract and design with inheritance in mind, etc. )</p>
<p>Long answer:</p>
<p>Well, inheritance is not actually for "code re-use", it is for class "specialization", I think this is a misinterpretation. </p>
<p>For instance is it a very bad idea to create a Stack from a Vector, just because they are alike. Or properties from HashTable just because they store values. See [Effective].</p>
<p>The "code reuse" was more a "business view" of the OO characteristics, meaning that you objects were easily distributable among nodes; and were portable and didn't not have the problems of previous programming languages generation. This has been proved half rigth. We now have libraries that can be easily distributed; for instance in java the jar files can be used in any project saving thousands of hours of development. OO still has some problems with portability and things like that, that is the reason now WebServices are so popular ( as before it was CORBA ) but that's another thread.</p>
<p>This is one aspect of "code reuse". The other is effectively, the one that has to do with programming. But in this case is not just to "save" lines of code and creating fragile monsters, but designing with inheritance in mind. This is the item 17 in the book previously mentioned; <strong>Item 17: Design and document for inheritance or else prohibit it.</strong> See [Effective]</p>
<p>Of course you may have a Car class and tons of subclasses. And yes, the approach you mention about Car interface, AbstractCar and CarImplementation is a correct way to go. </p>
<p>You define the "contract" the Car should adhere and say these are the methods I would expect to have when talking about cars. The abstract car that has the base functionality that every car but leaving and documenting the methods the subclasses are responsible to handle. In java you do this by marking the method as abstract.</p>
<p>When you proceed this way, there is not a problem with the "fragile" class ( or at least the designer is conscious or the threat ) and the subclasses do complete only those parts the designer allow them.</p>
<p>Inheritance is more to "specialize" the classes, in the same fashion a Truck is an specialized version of Car, and MosterTruck an specialized version of Truck.</p>
<p>It does not make sanse to create a "ComputerMouse" subclase from a Car just because it has a Wheel ( scroll wheel ) like a car, it moves, and has a wheel below just to save lines of code. It belongs to a different domain, and it will be used for other purposes. </p>
<p>The way to prevent "implementation" inheritance is in the programming language since the beginning, you should use the final keyword on the class declaration and this way you are prohibiting subclasses. </p>
<p>Subclassing is not evil if it's done on purpose. If it's done uncarefully it may become a nightmare. I would say that you should start as private and "final" as possible and if needed make things more public and extend-able. This is also widely explained in the presentation"How to design good API's and why it matters" See [Good API]</p>
<p>Keep reading articles and with time and practice ( and a lot of patience ) this thing will come clearer. Although sometime you just need to do the work and copy/paste some code :P . This is ok, as long you try to do it well first.</p>
<p>Here are the references both from Joshua Bloch ( formerly working in Sun at the core of java now working for Google )
<hr>
[Effective]
Effective Java. Definitely the best java book a non beginner should learn, understand and practice. A must have.</p>
<p><a href="http://java.sun.com/docs/books/effective" rel="noreferrer">Effective Java</a></p>
<p><hr>
[Good API]Presentation that talks on API's design, reusability and related topics.
It is a little lengthy but it worth every minute. </p>
<p><a href="http://www.youtube.com/watch?v=aAb7hSCtvGw" rel="noreferrer">How To Design A Good API and Why it Matters</a></p>
<p>Regards.</p>
<p><hr>
Update: Take a look at minute 42 of the video link I sent you. It talks about this topic:</p>
<p>"When you have two classes in a public API and you think to make one a subclass of another, like Foo is a subclass of Bar, ask your self , is Every Foo a Bar?... "</p>
<p>And in the minute previous it talks about "code reuse" while talking about TimeTask.</p>
|
<p>You should read Design Patterns. You will find that Interfaces are critical to many types of useful Design Patterns. For example abstracting different types of network protocols will have the same interface (to the software calling it) but little code reuse because of different behaviors of each type of protocol.</p>
<p>For some algorithms are eye opening in showing how to put together the myriad elements of a programming to do some useful task. Design Patterns do the same for objects.Shows you how to combine objects in a way to perform a useful task.</p>
<p><a href="https://rads.stackoverflow.com/amzn/click/com/0201633612" rel="nofollow noreferrer" rel="nofollow noreferrer">Design Patterns by the Gang of Four</a></p>
| 15,052
|
<p>I have a system which generates a large number of XML documents every day (of the order of 1 million) and I would like to be able to store and index these so that I can, for example, search for all documents with a certain field set to a given value.</p>
<p>I understand that there are fundamentally two types of XML database, those that provide XML support on top of a conventional relational database and those that are "native" XML database. Given that I am open to using either, what would you recommend?</p>
|
<p>Microsoft SQL Server has support for XML columns. This is more than just BLOB/TEXT support. </p>
<p>You can use XML columns in an unstructured manner, where SQL Server will just ensure they are correct XML. This allows storage of arbitrary XML documents inside SQL Server, but still ensuring you're dealing with XML and not just arbitrary bytes/characters. SQL Server lets you query on top of this using XQuery.</p>
<p>You can also create XML columns that conform to a schema using XSD. More interestingly, SQL Server allows indexing the XML so that your XPath queries can perform well.</p>
<p>See "<a href="http://www.microsoft.com/sqlserver/2008/en/us/wp-sql-2008-whats-new-xml.aspx" rel="nofollow noreferrer">What's New for XML in SQL Server 2008</a>" for more information. (Although most of the XML support exists in SQL Server 2005.)</p>
|
<p>Definitely try MS-SQL, Oracle, and other existing systems that support XQuery.</p>
<p>But, if the XML-based queries you'll need are known in advance, it might be easier to just store the XML in a BLOB, and add an indexed field or two with a copy of the relevant XML element(s).</p>
| 23,823
|
<p>I am using Scribd API (www.scribd.com) to display the PDF files in my website. I just want to know is there any other PDF API which i can use to embed the PDF in my website. FASTER and MORE customizable than Scribd, Mainly i want to put my company logo in that API, whereas in scribd they are displaying there logo.</p>
<p>So just want to know any opensource, FREE and customizable PDF API for website.</p>
<p>Thanks</p>
|
<p>Depending on how much functionality you're looking for, it's not incredibly difficult to roll your own. <a href="http://www.swftools.org/" rel="noreferrer">SWFTools</a> lets you convert PDF to SWF, a format you can load in to a simple Flash viewer.</p>
|
<p>May be you could try this one: <a href="http://lededansdubocal.net/spip.php?article22" rel="nofollow noreferrer">FreepapeR</a></p>
| 47,637
|
<p>One of our clients is upgrading their servers because the old machines can't handle the load of the database anymore. They have been using sql 2000 for the last 6 years and the db has grown to hold a few GB of data.</p>
<p><strong>Will it be worth upgrading to 2005 or 2008? What are the major benefits of the new versions compared to 2000?</strong></p>
|
<p>I you are planing to upgrade from SqlServer 2000 I would skip 2005 and go directly to SqlServer 2008</p>
<p>It has all the features of 2005 plus some extras (for example an option to pass a table variable as a parameter to stored procedure, new date types, spatial data handling,etc.)</p>
<p>You can refer to <a href="https://stackoverflow.com/questions/198478/advantages-of-ms-sql-server-2008-over-ms-sql-server-2005">Advantages of MS SQL Server 2008 over MS SQL Server 2005</a> question for the comprehensive list of features</p>
<p><strong>EDIT</strong></p>
<p>I can see that the question has been updated and now SqlServer 2008 is included in the question.</p>
|
<p>Online index rebuilds are a nice feature to have. I think it might only be an option in Enterprise edition though.</p>
| 42,810
|
<p>In the spirit of being helpful, this is a problem I had and solved, so I will answer the question here. </p>
<p><strong>Problem</strong></p>
<p>I have:</p>
<p>An application that has to be installed on on Redhat or SuSE enterprise. </p>
<p>It has huge system requirements and requires OpenGL.</p>
<p>It is part of a suite of tools that need to operate together on one machine.</p>
<p>This application is used for a time intensive task in terms of man hours.</p>
<p>I don't want to sit in the server room working on this application.</p>
<p>So, the question came up... how do I run this application from a remote windows machine?</p>
<p>I'll outline my solution. Feel free to comment on alternatives. This solution should work for simpler environments as well. My case is somewhat extreme.</p>
|
<p><strong>Solution</strong></p>
<p>I installed two pieces of software:</p>
<p><a href="http://www.chiark.greenend.org.uk/~sgtatham/putty/" rel="noreferrer">PuTTY</a></p>
<p><a href="http://www.straightrunning.com/XmingNotes/" rel="noreferrer">XMing-mesa</a> The mesa part is important.</p>
<p><strong>PuTTY configuration</strong></p>
<pre><code>Connection->Seconds Between Keepalives: 30
Connection->Enable TCP Keepalives: Yes
Connection->SSH->X11->Enable X11 forwarding: Yes
Connection->SSH->X11->X display location: localhost:0:0
</code></pre>
<p><strong>Lauching</strong></p>
<p>Run <em>Xming</em> which will put simply start a process and put an icon in your system tray.
Launch putty, pointing to your linux box, with the above configuration.
Run program</p>
<p>Hopefully, <strong>Success!</strong></p>
|
<p>For OpenGL, running an X server is definitely a better solution. Just make sure the application is developed to be networked. It should NOT use immediate mode for rendering and textures should be RARELY transferred. </p>
<p>Why is X server a better solution in this case (as opposed to VNC)? Because you get acceleration on workstation, while VNC'ed solution is usually not even accelerated on the mainframe. So as long as data is buffered on the X server (using vertex arrays, vertex buffer objects, texture objects, etc) you should get much higher speed than using VNC, especially with complex scenes since VNC has to analyze, transfer and decode them as pixels.</p>
| 13,167
|
<p>From my experiments, it does not appear to do so. If this is indeed true, what is the best method for removing line breaks? I'm currently experimenting with the parameters that TRIM accepts of the character to remove, starting with trimming <code>\n</code> and <code>\r</code>.</p>
|
<p>My line breaks were in the middle of the string, and I didn't have control over the source data. The following mysql command worked for me:</p>
<pre><code>REPLACE(FIELD,'\r\n',' ')
</code></pre>
|
<p><code>REPLACE(FIELD,'\r\n',' ')</code> works perfectly on MySql 5.1 database </p>
| 35,658
|
<p>We have a application that should always be running. Does anyone know of a way to create an automated way of monitoring to see if this application is running (possibly using a batch file)? If it is not running, then send an email notification and start the application?</p>
|
<p><a href="http://www.nagios.org/" rel="nofollow noreferrer">Nagios</a> is generally what's used by systems administrators that I've come across. You can script it to do whatever check you need and alert based on a variety of conditions. Works well with cacti so you can graph stuff too :)</p>
<p>If you want to ensure that your service always restarts should it die you could use <a href="http://cr.yp.to/daemontools/supervise.html" rel="nofollow noreferrer">supervise</a> from daemontools.</p>
|
<p>You don't mention an OS but if you're looking for something on Windows, <a href="http://www.jockersoft.com/english/appmonitor_index.php" rel="nofollow noreferrer">Application Monitor</a> might be a good start.</p>
<p>If you're on Linux, <a href="http://mmonit.com/monit/" rel="nofollow noreferrer">monit</a> look pretty useful.</p>
| 36,415
|
<p>I'm involved on a project to make a survey system. We've been hammering out the logic for a few question types, and I could use a second opinion on what is the best way to proceed. We work on a ASP.NET 2.0 website using VB(VS2005) with an Oracle database.</p>
<p>In our oracle server, we plan for some tables to organize our data. There's a table for our surveys, one for questions (keys determine which survey it goes on), one for answers (again, keys determine what question it belongs to), and one for answer collection. Most questions only return one response, and that's pretty easy to figure out. However, when we start thinking about items that return multiple answers, it starts to get tricky.</p>
<p>For example, if we have a simple matrix of 3x3 filled with check boxes. The rows are days 'Monday', 'Wednesday', 'Friday'. The columns are activities like 'Biking', 'Running', 'Driving'. The user checks each one they did for a given day, thus each row can have more than one response. Another one we want to think about is what if instead of checkboxes, we have textboxes where users write in a value of how many minutes they spent on an activity.</p>
<p>So far, for collecting responses, I like the idea of <a href="https://web.archive.org/web/20210510022603/https://aspnet.4guysfromrolla.com/articles/081402-1.2.aspx" rel="nofollow noreferrer">traversing a list of controls</a> in the form and keeping tabs on the kinds of controls that collect data. Since the controls are created in code, usually they're given an ID of a string with a number affixed to the end to keep track of what question type it is, and what number it is.</p>
<p>Question #1:
Should the data returned from the user be in a single database entry with delimiters to separate each answer, or should each answer get it's own entry?</p>
<p>Question #2:
What's the best way to identify what response goes with what answer (on the survey)?</p>
|
<p>Unfortunately no, until they sort out, at the least, the following issue:</p>
<p>When you visit a site that needs Flash and you haven't got Flash installed, you get a very standard looking popup asking you if you to install it, and mentioning in the notes that it may not be safe to install an untrusted plugin.</p>
<p>When you visit a site that lets you download an AIR app, it pops up big red screaming warnings about the imminent trashing of your computer, the theft of your identity and a life of torment[1]. Unless, of course, all the bedroom programmers decide to cough up the <em>ongoing</em> cost of certification.</p>
<p>User encouragement FAIL. Hobby developer encouragement FAIL. Technophobe terrorficiation avoidance FAIL.</p>
<p>I love AIR, but I don't know what they were thinking with the installer. Laywers' office moved closer to the developers' over at HQ or something?</p>
<p>[1]Actual message may vary.</p>
|
<p>No.<br>
The competition on desktop application market is much bigger, and users are expectiong more functionality and performance from desktop application than from web application, and AIR is just not there yet wrt performance and desktop capabilities.</p>
| 44,774
|
<p>Basically, I'm trying to write the following (pseudocode) in an ASP.NET HttpModule:</p>
<pre><code>*pre-code*
try { handler.ProcessRequest(...) }
catch (Exception) { *error-code* }
finally { *post-code* }
</code></pre>
<p>I've found that I can hook into HttpModule.PreExecuteHandler for "pre-code" and .Error for "error-code". But PostExecuteHandler doesn't seem to be running reliably.</p>
<p>BeginRequest and EndRequest run reliably but are too early for the code I need to write, which requires inspection of the handler that was chosen to execute. The handler isn't chosen until after BeginRequest.</p>
<p>Is there a best practice for writing this kind of wrapper?</p>
<p>Thanks!</p>
|
<p>There is no way to do what you want (in a HttpModule, at least), other than to not call Response.End. <a href="http://www.west-wind.com/Weblog/posts/494.aspx" rel="nofollow noreferrer">This article</a> explains it pretty well and offers an alternative to Response.End in case it is a side-effect of your having called Server.Transfer.</p>
|
<p>Add this to your Global.asax file:</p>
<pre><code>protected void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{
//
}
protected void Application_PostRequestHandlerExecute(object sender, EventArgs e)
{
//
}
</code></pre>
<p>That should work 100%.</p>
| 36,855
|
<p>is it possible to create something like <a href="https://web.archive.org/web/20200805044711/http://geekswithblogs.net/AzamSharp/archive/2008/02/24/119946.aspx" rel="nofollow noreferrer">this</a> i ASP.NET MVC beta 1</p>
<p>i have tried but the</p>
<pre><code>override bool OnPreAction(string actionName,
System.Reflection.MethodInfo methodInfo)
</code></pre>
<p>does not exsist anymore and</p>
<pre><code>override void OnActionExecuting(ActionExecutingContext filterContext)
</code></pre>
<p>don't give me access to the action name</p>
|
<p>In the blogpost you are referring to, the author states that </p>
<blockquote>
<p>One way to solve this problem is by using the attribute based security as shown on this post. But then you will have to decorate your actions with the security attribute which is not a good idea.</p>
</blockquote>
<p>I think it's a perfectly fine way to go about it and it is supported by the framework. It will give you a nice declarative implementation. Check out the AuthorizeAttribute in System.Web.Mvc. It will allow you to do something like this:</p>
<pre><code>[Authorize(Roles="Admin, Editor")]
public ActionResult Delete(int id){
(...)
}
</code></pre>
<p>Since the Delete action alters the state of your system, I would also add an AcceptVerbs attribute like so:</p>
<pre><code>[AcceptVerbs(HttpVerbs.Post)]
[Authorize(Roles="Admin, Editor")]
public ActionResult Delete(int id){
(...)
}
</code></pre>
<p>This will make sure that the action will not accept GET requests.</p>
|
<p>What is the reasoning for not wanting to decorate your actions with an authorization attribute? Sorry, but I think I'll have to understand your situation better, if I am to try to provide a better answer than the one already given.</p>
| 41,121
|
<p>I'm writing an Excel Addin using COM Interop from .net. I have a command that pops up a dialog, and from the dialog I do some work like collecting data from the used range of several sheets. The problem is that if a cell is in edit mode, some of the calls that I need to make will throw exceptions. I would like a way of determining before-hand that Excel is in edit mode, so that I can warn the user to finish editing the cell first.</p>
<p>Any ideas?</p>
|
<p>There is an Application.Ready property that is supposed to give you this information but in practice it doesn't work reliably. See <a href="http://www.codeproject.com/KB/office/Excel_Edit_Mode.aspx" rel="noreferrer">here</a> for a hackaround.</p>
<p>You might also want to look at setting Application.Interactive=false while your .net code is doing its stuff.</p>
|
<p>You didn't mention which language you're using. <a href="https://stackoverflow.com/a/25057820/3626160">SZL's function</a> is written in VB. Since I'm using C# I had to convert it. Worked great. Here is the equivalent C# code.</p>
<pre><code> bool IsInEditMode(ref Microsoft.Office.Interop.Excel.Application exapp)
{
if (exapp.Interactive == false)
{
return false;
}
else
{
try
{
exapp.Interactive = false;
exapp.Interactive = true;
return false;
}
catch
{
return true;
}
}
}
</code></pre>
| 27,372
|
<p>I am using LINQ-to-SQL for an application that queries a legacy database. I need to call a stored procedure, that selects a single integer value. Changing the stored procedure is not an option.</p>
<p>The designer creates a method with this signature:</p>
<pre><code>private ISingleResult<sp_xal_seqnoResult> NextRowNumber([Parameter(DbType="Int")] System.Nullable<int> increment, [Parameter(DbType="Char(3)")] string dataset)
</code></pre>
<p>I would like the return type to be int. How do I do this using LINQ-to-SQL ? </p>
|
<p>This would be trivial with a scalar function (UDF) rather than an SP. However, it should work easily enough - although if the SP is complex (i.e. FMT_ONLY can't inspect it 100%) then you might need to "help" it...</p>
<p>Here's some dbml that I generated from a simplfied SP that returns an integer; you can edit the dbml via "open with... xml editor):</p>
<pre><code><Function Name="dbo.foo" Method="foo">
<Parameter Name="inc" Type="System.Int32" DbType="Int" />
<Parameter Name="dataset" Type="System.String" DbType="VarChar(20)" />
<Return Type="System.Int32" />
</Function>
</code></pre>
<p>(note you obviously need to tweak the names and data-types).</p>
<p>And here is the generated C#:</p>
<pre><code>[Function(Name="dbo.foo")]
public int foo([Parameter(DbType="Int")] System.Nullable<int> inc, [Parameter(DbType="VarChar(20)")] string dataset)
{
IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), inc, dataset);
return ((int)(result.ReturnValue));
}
</code></pre>
<p>If your current SP uses SELECT (instead of RETURN), then the DBML will need to reflect this. You can fix this by hiding the implementation details, and providing a public wrapper in a partial class; for example:</p>
<pre><code><Function Name="dbo.foo" Method="FooPrivate" AccessModifier="Private">
<Parameter Name="inc" Type="System.Int32" DbType="Int" />
<Parameter Name="dataset" Type="System.String" DbType="VarChar(20)" />
<ElementType Name="fooResult" AccessModifier="Internal">
<Column Name="value" Type="System.Int32" DbType="Int NOT NULL" CanBeNull="false" />
</ElementType>
</Function>
</code></pre>
<p>The above describes an SP that returns a single table with a single column; but I've made the SP "private" to the data-context, and the result-type "internal" to the assembly (hiding it):</p>
<pre><code>[Function(Name="dbo.foo")]
private ISingleResult<fooResult> FooPrivate(
[Parameter(DbType="Int")] System.Nullable<int> inc,
[Parameter(DbType="VarChar(20)")] string dataset)
{
IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), inc, dataset);
return ((ISingleResult<fooResult>)(result.ReturnValue));
}
</code></pre>
<p>Now <em>in my own class file</em> I can add a new partial class (a new .cs file) in the correct namespace, that exposes the method more conveniently:</p>
<pre><code>namespace MyNamespace {
partial class MyDataContext
{
public int Foo(int? inc, string dataSet)
{
return FooPrivate(inc, dataSet).Single().value;
}
}
}
</code></pre>
<p>(the namespace and context names need to be the same as the actual data-context). This adds a public method that hides the grungy details from the caller.</p>
<p><strong>Don't</strong> edit the designer.cs file directly; your changes will be lost. Only edit either the dbml or partial classes.</p>
|
<p>If you are using Visual Studio's .xsd file in a Linq to SQL classes project, make sure you:</p>
<ol>
<li>Right click the stored procedure or function call in the Adapter.</li>
<li>Select Properties</li>
<li><strong>Change Execute Mode to Scalar</strong></li>
</ol>
<p>That will make your adapter function return type to "Object". You then need to cast it to int or string, or whatever type it should be.</p>
| 36,519
|
<p>Every so often I get an error saying one of my tables "is marked as crashed and should be repaired". I then do a REPAIR TABLE and repair it. What causes them to be marked as crashed and how can I prevent it? I am using MyISAM tables with MySQL 5.0.45.</p>
|
<p>There can be a few reasons tables get corrupted, it is discussed in detail in the <a href="http://dev.mysql.com/doc/refman/5.0/en/corrupted-myisam-tables.html" rel="noreferrer">manual</a>. </p>
<p>To combat it, the following things work best:</p>
<ol>
<li>Make sure you always MySQL shutdown properly</li>
<li>Consider using --myisam-recover option to automatically check/repair your tables in the event that shutdown wasn't done properly</li>
<li>Make sure you are on the most recent versions as known corruption bugs are normally fixed ASAP</li>
<li>Double check your hardware with a test to see if it is causing problems. Tools like <a href="http://sysbench.sourceforge.net/" rel="noreferrer">sysbench</a> and <a href="http://www.memtest86.com/" rel="noreferrer">memtest86</a> can often help verify if things are working as they should.</li>
<li>Make sure nothing is touching the data directory externally, such as virus checkers, backup programs, etc...</li>
</ol>
|
<p>It could be many things, but <a href="http://www.mysqlperformanceblog.com/2006/06/17/using-myisam-in-production/" rel="nofollow noreferrer" title="Using MyISAM in production">MySQL Performance Blog</a> mentions bad memory, OS or MySQL bugs that could cause hidden corruption. Also, that and <a href="http://www.mysqlperformanceblog.com/2006/07/30/mysql-crash-recovery/" rel="nofollow noreferrer" title="MySQL crash recovery">another article</a> mention several things to keep in mind when doing crash recovery. </p>
| 12,238
|
<p>I get the following error when attempting to install <a href="http://docs.rubygems.org/" rel="nofollow noreferrer">RubyGems</a>. I've tried Googling but have had no luck there. Has anybody encountered and resolved this issue before?</p>
<pre><code>
C:\rubygems-1.3.0> ruby setup.rb
.
.
install -c -m 0644 rubygems/validator.rb C:/Ruby/lib/ruby/site_ruby/1.8/rubygems/validator.rb
install -c -m 0644 rubygems/version.rb C:/Ruby/lib/ruby/site_ruby/1.8/rubygems/version.rb
install -c -m 0644 rubygems/version_option.rb C:/Ruby/lib/ruby/site_ruby/1.8/rubygems/version_option.rb
install -c -m 0644 rubygems.rb C:/Ruby/lib/ruby/site_ruby/1.8/rubygems.rb
install -c -m 0644 ubygems.rb C:/Ruby/lib/ruby/site_ruby/1.8/ubygems.rb
cp gem C:/Users/brian/AppData/Local/Temp/gem
install -c -m 0755 C:/Users/brian/AppData/Local/Temp/gem C:/Ruby/bin/gem
rm C:/Users/brian/AppData/Local/Temp/gem
install -c -m 0755 C:/Users/brian/AppData/Local/Temp/gem.bat C:/Ruby/bin/gem.bat
rm C:/Users/brian/AppData/Local/Temp/gem.bat
Removing old RubyGems RDoc and ri
Installing rubygems-1.3.0 ri into C:/Ruby/lib/ruby/gems/1.8/doc/rubygems-1.3.0/ri
./lib/rubygems.rb:713:in `set_paths': undefined method `uid' for nil:NilClass (NoMethodError)
from ./lib/rubygems.rb:711:in `each'
from ./lib/rubygems.rb:711:in `set_paths'
from ./lib/rubygems.rb:518:in `path'
from ./lib/rubygems/source_index.rb:66:in `installed_spec_directories'
from ./lib/rubygems/source_index.rb:56:in `from_installed_gems'
from ./lib/rubygems.rb:726:in `source_index'
from ./lib/rubygems.rb:138:in `activate'
from ./lib/rubygems.rb:49:in `gem'
from setup.rb:279:in `run_rdoc'
from setup.rb:296
C:\rubygems-1.3.0></code></pre>
<p>I have Ruby 1.8.6 installed on my laptop running Windows Vista.</p>
|
<p>I assume you're not trying to install under cygwin; that install is meant for unix-like operating systems. Edit: (Actually, from the log above it looks like there is some Windows-specific stuff being run... perhaps you're running into a UAC protection issue?)</p>
<p>If you just use the <a href="http://rubyforge.org/projects/rubyinstaller/" rel="nofollow noreferrer">Windows ruby one-click installer</a>, it includes rubygems. If you're not getting the rubygems functionality, you may need to
<code>require "rubygems"</code> in your script, or add -rubygems to your RUBYOPT environment variable. (You can also require rubygems from the command line with <code>ruby -rubygems myscript.rb</code>.</p>
<p>Are you trying to install it separately for some other reason?</p>
|
<p>I have rubygems 1.2.0 installed on Vista and it works fine. I have no tested rubygems 1.3.0 yet.</p>
| 18,200
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.