instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>Is there a difference between generating multiple numbers using a single random number generator (RNG) versus generating one number per generator and discarding it? Do both implementations generate numbers which are equally random? Is there a difference between the normal RNGs and the secure RNGs for this?</p>
<p>I have a web application that is supposed to generate a list of random numbers on behalf of clients. That is, the numbers should appear to be random from each client's point of view. Does this mean I need retain a separate random RNG per client session? Or can I share a single RNG across all sessions? Or can I create and discard a RNG on a per-request basis?</p>
<p><strong>UPDATE</strong>: This question is related to <a href="https://stackoverflow.com/questions/471157/is-a-subset-of-a-random-sequence-also-random">Is a subset of a random sequence also random?</a></p>
|
<p>A random number generator has a state -- that's actually a necessary feature. The next "random" number is a function of the previous number and the seed/state. The purists call them pseudo-random number generators. The numbers will pass statistical tests for randomness, but aren't -- actually -- random.</p>
<p>The sequence of random values is finite and does repeat. </p>
<p>Think of a random number generator as shuffling a collection of numbers and then dealing them out in a random order. The seed is used to "shuffle" the numbers. Once the seed is set, the sequence of numbers is fixed and very hard to predict. Some seeds will repeat sooner than others.</p>
<p>Most generators have period that is long enough that no one will notice it repeating. A 48-bit random number generator will produce several hundred billion random numbers before it repeats -- with (AFAIK) any 32-bit seed value. </p>
<p>A generator will <strong>only</strong> generate random-like values when you give it a single seed and let it spew values. If you change seeds, then numbers generated with the new seed value may not appear random when compared with values generated by the previous seed -- all bets are off when you change seeds. So don't.</p>
<p>A sound approach is to have one generator and "deal" the numbers around to your various clients. Don't mess with creating and discarding generators. Don't mess with changing seeds.</p>
<p>Above all, never try to write your own random number generator. The built-in generators in most language libraries are really good. Especially modern ones that use more than 32 bits.</p>
<p>Some Linux distros have a <code>/dev/random</code> and <code>/dev/urandom</code> device. You can read these once to seed your application's random number generator. These have more-or-less random values, but they work by "gathering noise" from random system events. Use them sparingly so there are lots of random events between uses.</p>
|
<p>Well, as long as they are seeded differently each time they're created, then no, I don't think there'd be any difference; however, if it depended on something like the time, then they'd probably be non-uniform, due to the biased seed.</p>
| 24,883
|
<p>I'm doing some research on the feasibility of an iPhone application, and can't find any indication in Apple's documentation that an iPhone app can read the call history of the phone, specifically the number/address book entry called, when, and the duration.</p>
<p>Does anyone know if this is possible, and how?</p>
<p>Note: The purpose is to remove the need for the user to perform this data-entry themselves. The application is for recording interactions with customer service centers.</p>
|
<p>Unfortunately you can't access the call history. The only User Data you have API access to is the address book. You can also access photos/pictures but only by starting an iPhone-controlled dialog that allows the user to choose a single image.</p>
<p>It's a bit sucky, hopefully this will be expanded in future versions.</p>
|
<p>AFAIK you can't access call history. The address book is a database of contacts, not call information.</p>
<p>You can read more about the address book in the SDK's "Address Book Programming Guide for iPhone OS."</p>
| 17,472
|
<p>I'm writing a function that gets the path environment variable of a system, splits up each path, then concats on some other extra characters onto the end of each path.</p>
<p>Everything works fine until I use the <code>strcat()</code> function (see code below).</p>
<pre><code>char* prependPath( char* exeName )
{
char* path = getenv("PATH");
char* pathDeepCopy = (char *)malloc(strlen(path) + 1);
char* token[80];
int j, i=0; // used to iterate through array
strcpy(pathDeepCopy, path);
//parse and split
token[0] = strtok(pathDeepCopy, ":"); //get pointer to first token found and store in 0
//place in array
while(token[i]!= NULL) { //ensure a pointer was found
i++;
token[i] = strtok(NULL, ":"); //continue to tokenize the string
}
for(j = 0; j <= i-1; j++) {
strcat(token[j], "/");
//strcat(token[j], exeName);
printf("%s\n", token[j]); //print out all of the tokens
}
}
</code></pre>
<p>My shell output is like this (I'm concatenating "/which" onto everything):</p>
<pre><code>...
/usr/local/applic/Maple/bin/which
which/which
/usr/local/applic/opnet/8.1.A.wdmguru/sys/unix/bin/which
which/which
Bus error (core dumped)
</code></pre>
<p>I'm wondering why <code>strcat</code> is displaying a new line and then repeating <code>which/which</code>.
I'm also wondering about the <code>Bus error (core dumped)</code> at the end.</p>
<p>Has anyone seen this before when using <code>strcat()</code>?
And if so, anyone know how to fix it?</p>
<p>Thanks</p>
|
<p>strtok() does not give you a new string.<br>
It mutilates the input string by inserting the char '\0' where the split character was.</p>
<p>So your use of strcat(token[j],"/") will put the '/' character where the '\0' was.<br>
Also the last token will start appending 'which' past the end of your allocated memory into uncharted memory.</p>
<p>You can use strtok() to split a string into chunks. But if you want to append anything onto a token you need to make a copy of the token otherwise what your appending will spill over onto the next token.</p>
<p>Also you need to take more care with your memory allocation you are leaking memory all over the place :-)</p>
<p>PS. If you must use C-Strings. use strdup() to copy the string.</p>
<pre><code>char* prependPath( char* exeName )
{
char* path = getenv("PATH");
char* pathDeepCopy = strdup(path);
char* token[80];
int j, i; // used to iterate through array
token[0] = strtok(pathDeepCopy, ":");
for(i = 0;(token[i] != NULL) && (i < 80);++i)
{
token[i] = strtok(NULL, ":");
}
for(j = 0; j <= i; ++j)
{
char* tmp = (char*)malloc(strlen(token[j]) + 1 + strlen(exeName) + 1);
strcpy(tmp,token[j]);
strcat(tmp,"/");
strcat(tmp,exeName);
printf("%s\n",tmp); //print out all of the tokens
free(tmp);
}
free(pathDeepCopy);
}
</code></pre>
|
<p>replace that with</p>
<p>strcpy(pathDeepCopy, path);</p>
<pre><code> //parse and split
token[0] = strtok(pathDeepCopy, ":");//get pointer to first token found and store in 0
//place in array
while(token[i]!= NULL) { //ensure a pointer was found
i++;
token[i] = strtok(NULL, ":"); //continue to tokenize the string
}
// use new array for storing the new tokens
// pardon my C lang skills. IT's been a "while" since I wrote device drivers in C.
const int I = i;
const int MAX_SIZE = MAX_PATH;
char ** newTokens = new char [MAX_PATH][I];
for (int k = 0; k < i; ++k) {
sprintf(newTokens[k], "%s%c", token[j], '/');
printf("%s\n", newtoken[j]); //print out all of the tokens
}
</code></pre>
<p>this will replace overwriting the contents and prevent the core dump.</p>
| 20,475
|
<p>I have some local changes to an open source project which uses Subversion as its source control. (I do not have commit access on the original project repository.)</p>
<p>My change adds a file, but this file is not included in the output of "svn diff". (It may be worth noting that the new file is a binary, not plain text.)</p>
<p>How can I make a <a href="http://en.wikipedia.org/wiki/Patch_(Unix)" rel="nofollow noreferrer">patch</a> which includes the new files?</p>
<hr>
<pre><code> $ svn st
A tests/foo.zip
$ svn diff
$
</code></pre>
|
<p>I experienced similar behavior to Pozsar. And his answer worked for me better than the normal svn diff --force. However, if running on a DOS machine (e.g. via Cygwin), you may need to modify his answer slightly. The following diff + patch worked for patching my text + binary files in Cygwin using the --binary arg:</p>
<pre><code>svn diff --force --diff-cmd /usr/bin/diff -x "-au --binary" OLD-URL NEW-URL > mybinarydiff.diff
patch -p0 --binary -i mybinarydiff.diff
</code></pre>
|
<p>If you're building a patch, you might want to use plain old 'diff' with the --new-file option which treats the missing file as empty.</p>
<p>Note that the syntax for this option may actually vary depending on what version of plain old diff you're using. </p>
| 19,330
|
<p>I would like to send a (as yet undetermined) SIGnal from a bash script to a Gambas program when a specific file has been changed. </p>
<p>How can I get my Gambas program to process this SIGnal?</p>
|
<p>The <code>gb.signal</code> component allows you to manage signals. You can intercept them, ignore them, and so on. See <a href="http://gambaswiki.org/wiki/comp/gb.signal" rel="nofollow noreferrer">http://gambaswiki.org/wiki/comp/gb.signal</a> for the details.</p>
|
<p>If the documentation is anything to go by, this doesn't seem possible. However, I would suggest asking the same question on the Gambas mailing list (and/or link to this question on Stack Overflow). Please report back if you get an answer via the mailing list.</p>
| 21,983
|
<p>I´m looking for a unit tests framework for database development. I´m currently developing for SQL Server 2000, 2005 and 2008. Do you know of any good frameworks with similar functionality as JUnit and NUnit?<br>
Perhaps it´s better to ask, what do you use to unit test your stored procedures and user defined functions?</p>
|
<p>There is TSQLUnit... Link here: <a href="http://tsqlunit.sourceforge.net/" rel="nofollow noreferrer">http://tsqlunit.sourceforge.net/</a></p>
|
<p>I'm currently using DBUnit in my project. It's quite a good tool to test a database to see if the results you expect are there, but also it can alter the data in a database to predefined values, for example, it will reset a database to the data you were using before the tests, leaving the tables unchanged.</p>
<p><a href="http://dbunit.sourceforge.net/" rel="nofollow noreferrer">http://dbunit.sourceforge.net/</a></p>
| 24,820
|
<p>This is a follow up question to <a href="https://stackoverflow.com/questions/85815/how-to-tell-if-a-javascript-function-is-defined">This Question</a>. </p>
<p>I like (and understand) the solution there. However, in the code I am working in, another way to solve the same problem is used:</p>
<pre><code>function exist(sFN) {
if(self[sFN]) return true;
return false;
}
</code></pre>
<p>It seems to work fine, although I don't understand how. Does it work? How? What are minuses of this approach? Should I switch to solution from the other question?</p>
|
<p>Your condition is checking the existence of the "sFN" property in the "self" object. Anything that isn't null, undefined, 0, and "" will evaluate to true. </p>
<p>As others have said, you can use typeof, or instanceof to see if it's actually a function. </p>
<p>Looking at your linked example, you should read up on the difference between ==/!= and ===/!== in javascript. Short answer: ("" == null) is true, ("" === null) is false.</p>
|
<p>I read somewhere (<a href="http://www.electrictoolbox.com/check-javascript-function-exists/" rel="nofollow noreferrer">here</a> and <a href="http://bytes.com/forum/thread90633.html" rel="nofollow noreferrer">here</a>) that functions are properties of the window object, so you can do the following:</p>
<pre><code>if (window.my_func_name) {
my_func_name('tester!');
}
</code></pre>
<p>or for popups:</p>
<pre><code>if (window.opener.my_func_name) {
my_func_name('tester!');
}
</code></pre>
<p>A complete solution then:</p>
<pre><code>function function_exists(func_name) {
var eval_string;
if (window.opener) {
eval_string = 'window.opener.' + func_name;
} else {
eval_string = 'window.' + func_name;
}
return eval(eval_string + ' ? true : false');
}
</code></pre>
| 11,412
|
<p>Announced today. Descriptions so far are confusing. Let's put together a good starting point for understanding Windows Azure.</p>
<p>Strongly related to <a href="https://stackoverflow.com/questions/280037/what-is-a-cloud-os">What is a "Cloud OS"?</a>, but not enough to warrant closing.</p>
|
<h2>Description</h2>
<p>The Azure™ Services Platform (Azure) <strong>is an internet-scale cloud services platform hosted in Microsoft data centers</strong>, which provides an operating system and a set of developer services that can be used individually or together. Azure’s flexible and interoperable platform can be used to build new applications to run from the cloud or enhance existing applications with cloud-based capabilities. Its open architecture gives developers the choice to build web applications, applications running on connected devices, PCs, servers, or hybrid solutions offering the best of online and on-premises.</p>
<p>Azure <strong>reduces the need for up-front technology purchases</strong>, and it enables developers to quickly and <strong>easily create applications running in the cloud</strong> by using their existing skills with the Microsoft Visual Studio development environment and the Microsoft .NET Framework. In addition to managed code languages supported by .NET, Azure will support more programming languages and development environments in the near future. Azure simplifies maintaining and operating applications by providing on-demand compute and storage to host, scale, and manage web and connected applications. Infrastructure management is automated with a platform that is designed for high availability and dynamic scaling to match usage needs with the option of a pay-as-you-go pricing model. Azure provides an open, standards-based and interoperable environment with support for multiple internet protocols, including HTTP, REST, SOAP, and XML.</p>
<h2>Features</h2>
<p>Key components of the Azure Services Platform include the following:</p>
<ul>
<li>Windows Azure for service hosting and management, low-level scalable storage, computation and networking</li>
<li>Microsoft SQL Services for a wide range of database services and reporting</li>
<li>Microsoft .NET Services which are service-based implementations of familiar .NET Framework concepts such as workflow and access control</li>
<li>Live Services for a consistent way for users to store, share and synchronize documents, photos, files and information across their PCs, phones, PC applications and Web sites</li>
<li>Microsoft SharePoint Services and Microsoft Dynamics CRM Services for business content, collaboration and rapid solution development in the cloud.</li>
</ul>
|
<p>Azure is a cloud hosting, if we have a web app application we can hosting on it.
Azure also support various script languages (C#, PHP, Phyton etc).
Today Azure also support for wordpress and various databases.
We can subscribe azure by period or "pay as you go".</p>
| 29,766
|
<p>I know of the following:</p>
<ul>
<li>The venerable <code>getopt(3)</code></li>
<li>The extended <code>getopt_long</code></li>
<li>glibc's <a href="http://www.gnu.org/software/libtool/manual/libc/Argp.html" rel="noreferrer"><code>argp</code></a> parser for Unix-style argument vectors</li>
<li><a href="http://developer.gnome.org/arch/misc/popt.html" rel="noreferrer">popt</a> from the GNOME project (or its spiritual successor in <a href="http://library.gnome.org/devel/glib/stable/glib-Commandline-option-parser.html" rel="noreferrer">Glib</a>)</li>
</ul>
<p>I'm sure there's more that I haven't used or even heard of; a quick Google search reveals <a href="http://www.purposeful.co.uk/software/gopt/" rel="noreferrer">Gopt</a>, <a href="http://argtable.sourceforge.net/" rel="noreferrer">argtable</a>, and <a href="http://michael.dipperstein.com/optlist/" rel="noreferrer">Optlist</a>.</p>
<p>Personally, I like <code>argp</code> best, and every program I wrote using <code>getopt</code>/<code>getopt_long</code> (beyond a certain baseline of complexity) has been converted to use <code>argp</code>. It's more widely available than <code>popt</code>, more powerful than <code>getopt_long</code>, well-documented, consistent with all the GNU-style conventions, and very flexible. On the downside, it's far from the easiest to use (thanks to being so flexible), and the code to support it is quite verbose (as are many things in C).</p>
<p>What do you use, and why?</p>
<p>Yes, I mean C rather than C++. There are a ton of C++ parsers, but I don't use C++.</p>
<p>John Millikin notes that <code>popt</code> is no longer maintained. I list it because many programs still use it -- including AbiWord, rpm, rsync, and samba -- despite Gnome's efforts to <a href="http://live.gnome.org/ProjectRidley" rel="noreferrer">migrate away</a>. But I've added a link to Glib's argument parser now, too.</p>
<hr/>
<p>For C++ argument parsing, see the question <em><a href="https://stackoverflow.com/questions/253556/what-parameter-parser-libraries-are-there-for-c">What parameter parser libraries are there for C++?</a></em></p>
|
<p>GNU has <A href="http://www.gnu.org/software/gengetopt/" rel="noreferrer">gengetopt</A> which generates code for an options data structure and the <code>getopt_long</code> code to parse the command line and fill the structure.. It's fairly easy to learn and works well.</p>
<p>As a bonus you can pass the options structure around your code and avoid global storage if desired.</p>
<p>It provides GNU style semantics (obviously), and is small enough to simply include with the project for distribution if you're not sure of your audience's build environment.</p>
|
<p>I really like the <a href="http://tclap.sourceforge.net/" rel="nofollow noreferrer">TCLAP</a> library, because it is very flexible and easy to use. It is also completely template-based, so it is a header-only library.</p>
<p>My mistake: you said C and I posted a C++ library...</p>
| 23,049
|
<p>I have discovered through trial and error that the MATLAB engine function is not completely thread safe.</p>
<p>Does anyone know the rules?</p>
<p>Discovered through trial and error:</p>
<p>On Windows, the connection to MATLAB is via COM, so the COM Apartment threading rules apply. All calls must occur in the same thread, but multiple connections can occur in multiple threads as long as each connection is isolated.</p>
<p>From the answers below, it seems that this is not the case on UNIX, where calls can be made from multiple threads as long as the calls are made serially.</p>
|
<p>When I first started using the engine, I didn't run across any documentation on thread safety, so I assumed that it was not thread-safe.</p>
<p>I use a C++ class to synchronize access to an engine instance. For more parallel processing designs, I instantiate multiple instances of the engine class.</p>
<p>(edit) I'm using MATLAB R14 on Solaris. I open the engine using the 'engOpen' call, and close it using 'engClose'. My platform does not crash when the Close is called by a different thread than the one that called Open.</p>
|
<p>You can use <code>engOpenSingleUse</code> instead of using <code>engOpen</code> to make more than one thread working separately. (Only Windows)</p>
| 30,868
|
<p>Is there a way set flags on a per-file basis with automake?<br>
In particular, if I have a c++ project and want to compile with -WAll all the files except one for which I want to disable a particular warning, what could I do?</p>
<p>I tried something like:</p>
<pre><code>CXXFLAGS = -WAll ...
bin_PROGRAMS = test
test_SOURCES = main.cpp utility.cpp
utility_o_CXXFLAGS = $(CXXFLAGS) -Wno-unused-value
</code></pre>
<p>but it didn't work.</p>
<p>EDITED: removed reference to automake manual, which was actually misleading (thanks to Douglas Leeder).</p>
|
<p>Automake only supports per-target flags, while you want per-object flags. One way around is to create a small library that contains your object: </p>
<pre><code>CXXFLAGS = -Wall ...
bin_PROGRAMS = test
test_SOURCES = main.cpp
test_LDADD = libutility.a
noinst_LIBRARIES = libutility.a
libutility_a_SOURCES = utility.cpp
libutility_a_CXXFLAGS = $(CXXFLAGS) -Wno-unused-value
</code></pre>
|
<p>You've got confused - that section is referring to options to automake itself.</p>
<p>It's a way of setting the automake command-line options:</p>
<blockquote>
<p>-W CATEGORY
--warnings=category
Output warnings falling in category. category can be one of:</p>
<pre><code>gnu
warnings related to the GNU Coding Standards (see Top).
obsolete
obsolete features or constructions
override
user redefinitions of Automake rules or variables
portability
portability issues (e.g., use of make features that are known to be not portable)
syntax
weird syntax, unused variables, typos
unsupported
unsupported or incomplete features
all
all the warnings
none
turn off all the warnings
error
treat warnings as errors
</code></pre>
<p>A category can be turned off by prefixing its name with ‘no-’.
For instance, -Wno-syntax will hide the
warnings about unused variables.</p>
<p>The categories output by default are ‘syntax’ and ‘unsupported’.
Additionally, ‘gnu’ and ‘portability’
are enabled in --gnu and --gnits
strictness.</p>
<p>The environment variable WARNINGS can contain a comma separated list of
categories to enable. It will be taken
into account before the command-line
switches, this way -Wnone will also
ignore any warning category enabled by
WARNINGS. This variable is also used
by other tools like autoconf; unknown
categories are ignored for this
reason.</p>
</blockquote>
<p>The per-file listed in section 17 refers to per-Makefile not source file.</p>
<p>I'm not aware of any per-source file flag setting, but you can set the option for each result binary with:</p>
<pre><code>binaryname_CXXFLAGS
</code></pre>
| 17,997
|
<p>One of the best tips for using vim that I have learned so far has been that one can press <kbd>Ctrl</kbd>+<kbd>C</kbd> or <kbd>Ctrl</kbd>+<kbd>[</kbd> instead of the <kbd>Esc</kbd> key. However I use a dvorak keyboard so <kbd>Ctrl</kbd>+<kbd>[</kbd> is a little out of reach for me as well so I mostly use <kbd>Ctrl</kbd>+<kbd>C</kbd>. Now I've read somewhere that these two key combinations don't actually have exactly the same behaviour and that it is better to use <kbd>Ctrl</kbd>+<kbd>[</kbd>. I haven't come across any problems so far though so I'd like to know what exactly is the difference between the two?</p>
|
<p>According to Vim's documentation, <kbd>Ctrl</kbd>+<kbd>C</kbd> does not check for abbreviations and does not trigger the <code>InsertLeave</code> autocommand event while <kbd>Ctrl</kbd>+<kbd>[</kbd> does.</p>
<p>One option is to use the following to remap <kbd>Ctrl</kbd>+<kbd>C</kbd></p>
<pre><code>inoremap <C-c> <Esc><Esc>
</code></pre>
|
<p>As it turns out, <code><C-[></code> is exactly identical to Esc, they are the same character. So no need to wonder about any difference there. :)</p>
| 10,619
|
<p>Any ideas on how i get MVP working with Silverlight? How Do I get around the fact there is no load event raised?</p>
<p>This the view I have:</p>
<pre><code> public partial class Person: IPersonView
{
public event RoutedEventHandler Loaded;
public Person()
{
new PersonPresenter(this);
InitializeComponent();
}
public Person Person
{
set { Person.ItemsSource = value; }
}
}
</code></pre>
<p>And my presenter:</p>
<pre><code> public class PersonPresenter
{
private readonly IPersonView _view;
private readonly ServiceContractClient _client;
public PersonPresenter(IPersonView view)
{
_client = new ServiceContractClient();
_view = view;
WireUpEvents();
}
private void WireUpEvents()
{
_view.Loaded += Load;
}
private void Load(object sender, EventArgs e)
{
_client.GetPersonCompleted += Client_GetPerson;
_client.GetPersonAsync();
}
private void Client_GetPerson(object sender, GetPersonCompletedEventArgs e)
{
_view.Person= e.Result;
}
}
</code></pre>
<p>Nothing happened for me as the Loaded event dont seem to get called, how do i get around this?</p>
|
<p><a href="http://timross.wordpress.com/2008/03/16/implementing-the-mvp-pattern-in-silverlight/" rel="nofollow noreferrer">Tim Ross</a> has a good introduction to Silverlight MVP implementation, with source code.</p>
|
<h2>You may consider using <a href="http://www.mvcsharp.org" rel="nofollow noreferrer">MVC#</a> - a Model View Presenter framework with Silverlight 2.0 support.</h2>
<p>Oleg Zhukov</p>
| 16,438
|
<p>I'm learning some PowerShell. Is it possible to see the source code for a built-in cmdlet like <a href="http://technet.microsoft.com/en-us/library/hh849800.aspx" rel="noreferrer">Get-ChildItem</a>?</p>
|
<p>Actually, your best bet is to go check out <a href="https://github.com/Pscx/Pscx" rel="nofollow noreferrer">PowerShell Community Extensions</a>. This open source software community project is "aimed at providing a widely useful set of additional cmdlets...". The developers on the project are PowerShell MVPs and know their stuff.</p>
<p>As far as using reflection on the existing PowerShell cmdlets, PowerShell MVP Oisin Grehan made a handy function titled "<a href="https://web.archive.org/web/20190521090145/https://www.nivot.org/post/2008/10/30/ATrickToJumpDirectlyToACmdletsImplementationInReflector" rel="nofollow noreferrer">Reflect-Cmdlet</a>". I won't steal his code and place it here, but basically what you do is:</p>
<pre><code>Get-Command Get-ChildItem | Reflect-Cmdlet
</code></pre>
<p>And then <a href="https://en.wikipedia.org/wiki/.NET_Reflector" rel="nofollow noreferrer">.NET Reflector</a> pops up with the right assembly opened up and expanded and everything. It's really pretty cool.</p>
|
<p>I do not believe that the source code for PowerShell has ever been released.</p>
| 33,382
|
<p>I just wrote a new web part and now I am getting this error when I try to deploy them on my non-dev servers:</p>
<blockquote>
<p>the default namespace
'<a href="http://schemas.microsoft.com/WebPart/v2" rel="nofollow noreferrer">http://schemas.microsoft.com/WebPart/v2</a>'
is a reserved namespace for base Web
Part propertiees. Custom Web Part
properties require a unique namespace
(specified through an
XmlElementAttribute on the property ,
or an XmlRootAttribute on the class).</p>
</blockquote>
<p>I am writing the web parts into CAB files and deploying them with this:</p>
<pre><code>stsadm -o addwppack -filename web_part_name.CAB -url http://your_url_here -globalinstall -force
</code></pre>
<p>Everything works fine until I try to add the web part, then I get this error in a popup. It works just fine on my dev VM...?</p>
<p>Any ideas would be appreciate, thank you.</p>
|
<p>Well, it looks like your webpart definition file si somehow broken. The wey i do it is to put webpart into page and then export it. You can do this just by opening webpart galery, which can be located in site settings of root site collection and add your webpart there. </p>
<p>After that just place webpart to any page and use export button in webpart settings. This will produce .webpart or .dwp file depending on your webpart (.webpart is 'new' definition which is used by webparts native to MOSS 2007 and .dwp is for older webparts, but it depends how you have written your webpart)</p>
<p>Then just take exported file and include it into your project. This approach works for me at least.</p>
|
<p>A bit of a educated guess here but anyway :-</p>
<p>First check that you have XmlRoot attribute like this in your web part</p>
<pre><code>[XmlRoot(Namespace = "Your.Namespace")]
public class YourWebPart: WebPart
{
...
</code></pre>
<p>and XmlElement attribute on your custom properties</p>
<pre><code> [DefaultValue(0)]
[WebPartStorage(Storage.Shared)]
[Browsable(false)]
[XmlElement(ElementName = "YourProperty")]
public Int64 YourProperty
{
...
}
</code></pre>
<p>This error is happening when .NET is attempting to desterilize the data from the .DWP file and set the custom properties in your web part.</p>
<p>I suspect that the error may have nothing to do with namespace conflicts as SharePoint sometimes tends to fall back to an error messages that can be a red herring.</p>
<p>I would firstly examine your .dwp file. Do you have any custom properties set there, if so remove them and retest.</p>
<p>Comment out the custom properties in your web part code one by one and retest at each step.</p>
<p>I think you will find one of these is causing the problem - exactly why is the next question!</p>
| 25,438
|
<p>From time to time, I run into communications issue with other programmers, when we talk about NULL. Now NULL could be
<BR>
<BR> a NULL pointer
<BR> the NUL character
<BR> an empty data element in some sort of database.</p>
<p><BR> NUL seems to be the most confusing. It is the ASCII character 0x00.
<BR> I tend to use '\0' in my code to represent it. Some developers in my group
<BR> tend to prefer to simply use 0, and let the compiler implicitly cast it to a char.</p>
<p><BR> What do you prefer to use for NUL? and why?</p>
|
<p>I use <code>'\0'</code> for the nul-character and <code>NULL</code> for pointers because it is clearest in both cases. </p>
<p>BTW, both <code>0</code> and <code>'\0'</code> are <code>int</code>s in C and either one will be converted to <code>char</code> when stored in a <code>char</code> variable.</p>
|
<p>For communication I use NULL. If I'm working with a developer who cannot grasp the concept of NULL for different data-types then I'd be concerned.</p>
<p>For implementation it's case-specific. Numbers are 0 (post-fixed f for floating-point), pointers are NULL and character strings are 0.</p>
| 27,145
|
<p>I've been benchmarking the performance of a framework I'm writing in Perl and I'm getting a 50% decrease in requests per second over our existing codebase (some hit is understandable, because we're going from procedural spaghetti code to an OOP MVC framework).</p>
<p>The application is running under mod_perl, and I've added <a href="http://search.cpan.org/dist/Moose/" rel="noreferrer">Moose</a> and all my framework code into the <a href="http://perl.apache.org/docs/2.0/user/config/config.html#C_PerlPostConfigRequire_" rel="noreferrer">startup.pl script</a>, which itself doubled my requests per second amount. I'm looking to further enhance this number to get it as close as possible to the existing amount. The argument is there that this is premature optimisation, but there are a couple of glaring inefficiencies that I'd like to fix and see how it effects performance.</p>
<p>Like most frameworks, I have a configuration file and a dispatcher. The config part is handled by <a href="http://search.cpan.org/dist/Config-General/" rel="noreferrer">Config::General</a>, so a bit of IO and parsing is involved to get my config file loaded into the app. The biggest problem I see here is that I'm doing this for EVERY REQUEST that comes in! </p>
<p>Running Devel::Dprof on my app points to Config::General::BEGIN and a bunch of related IO modules as one of the major slow points that isn't Moose. So what I'd like to do, and what makes a lot more sense in hindsight is take advantage of mod_perl's persistence and the startup.pl compilation stuff to only do the work to load in the config file once - when the server starts.</p>
<p>The problem is that I'm not too familiar with how this would work. </p>
<p>Currently each project has a PerlHandler bootstrapping class which is pretty lean and looks like this:</p>
<pre><code>use MyApp;
MyApp->new(config_file => '/path/to/site.config')->run();
</code></pre>
<p>MyApp.pm inherits from the framework Project module, which has this code:</p>
<pre><code>my $config = Config::General->new(
-ConfigFile => $self->config_file,
-InterPolateVars => 1,
);
$self->config({$config->getall});
</code></pre>
<p>To only do this at compile time, both my bootstrap and Project base modules will have to change (I think), but I'm pretty unsure as to what changes to make and still keep the code nice and lean. Can anyone point me in the right direction here? </p>
<p><strong>UPDATE</strong></p>
<p>I tried the BEGIN BLOCK in each project module approach as described by ysth in his answer. So I now have:</p>
<pre><code>package MyApp::bootstrap;
use MyApp;
my $config;
BEGIN
{
$config = {Config::General->new(...)->getall};
}
sub handler { ..etc.
MyApp->new(config => $config)->run();
</code></pre>
<p>This quick change alone gave me a <strong>50%</strong> increase in requests per second, confirming my thoughts that the config file was a major bottleneck worth fixing. The benchmark figure on our crotchety old dev machine is 60rps, and my framework has went from 30rps to 45rps with this change alone. For those who say Moose is slow and has a compile time hit.. I got the same (50%) increase when compiling all my Moose code at start-up as I did from pre-compiling my config file.</p>
<p>The only problem I have now is that this violates the DRY principal since the same Config::General->new code is in every BEGIN block with only the path to the config file differing. I have a few different strategies to limit this, but I just wanted to post the results of this change.</p>
|
<p>Assuming your applications don't change the config at all, move it into a begin block:</p>
<pre><code># this code goes at file scope
my $config;
BEGIN {
$config = { Config::General->new( ... )->getall }
}
# when creating a new instance
$self->config( $config );
</code></pre>
<p>And make sure all your modules are compiled in startup.pl.</p>
<p>You could get fancier, and have a singleton class provide the config hash,
but you don't need to.</p>
|
<p>JackM has the right idea. </p>
<p>By loading all of your classes and instantiating your Application-level objects (in your case, the configuration) in the "<em>Mother</em>" Apache process, You Don't have to compile them each time a new worker spawns, since they're already available and in memory. The very meticulous amongst us add a "use" line for every module that their application uses regularly. If you don't load your packages and modules in the mother ship, each worker takes not only the performance hit of loading the modules, but does not gain the benefit of memory sharing that modern operating systems provide.</p>
<p>It is really the other half of the difference between mod_perl and CGI. With the first half being mod_perl's persistent perl-engine vs CGI's respawning perl for each invocation.</p>
| 44,525
|
<p>In terms of general operating system concepts, what is the difference between a file and a record?</p>
<p>How the OS will manage them? I know what a file is and what a record is but how it is distinguished in an
OS?</p>
|
<p>yeap <p>I got the answer
<p>A file is a collection or set of records. </p>
<p><p>Typically, In database sense, A Group of records makes a file. </p>
<p><p>A group of attributes makes a record</p>
|
<p>The Good answer is that 1
""A collection of related fields treated as a single unit is called a record. A collection of related record treated as a single unit is called a file or a data set""</p>
| 31,463
|
<p>How do I figure out if an array contains an element?
I thought there might be something like <code>[1, 2, 3].includes(1)</code> which would evaluate as <code>true</code>.</p>
|
<p>Some syntax sugar</p>
<pre><code>1 in [1,2,3]
</code></pre>
|
<p>You can also use matches with regular expression like this:</p>
<pre><code>boolean bool = List.matches("(?i).*SOME STRING HERE.*")
</code></pre>
| 7,514
|
<p>What ist most concise way to read the contents of a file or input stream in Java? Do I always have to create a buffer, read (at most) line by line and so on or is there a more concise way? I wish I could do just</p>
<pre><code>String content = new File("test.txt").readFully();
</code></pre>
|
<p>Use the <a href="http://commons.apache.org/io/description.html" rel="noreferrer">Apache Commons IOUtils</a> package. In particular the <code>IOUtils</code> class provides a set of methods to read from streams, readers etc. and handle all the exceptions etc. </p>
<p>e.g.</p>
<pre><code>InputStream is = ...
String contents = IOUtils.toString(is);
// or
List lines = IOUtils.readLines(is)
</code></pre>
|
<p>You have to create your own function, I suppose. The problem is that Java's read routines (those I know, at least) usually take a buffer argument with a given length.</p>
<p>A solution I saw is to get the size of the file, create a buffer of this size and read the file at once. Hoping the file isn't a gigabyte log or XML file...</p>
<p>The usual way is to have a fixed size buffer or to use readLine and concatenate the results in a StringBuffer/StringBuilder.</p>
| 27,805
|
<p>I have some code documentation in MS Powerpoint 2003 that I'm revision-controlling in an SVN repository. I'd like to auto-insert the latest revision number into this document whenever I open it. I am using TortoiseSVN. I've been able to google up a macro or two that might work but wanted advice from experts. :) Thanks!</p>
|
<p>I think it should be possible to use the $Rev$ macro inside it with the Office 2007 XML formats, but I am not too sure what will happen with older formats that might contain binary data. You might need to tweak svn settings a bit so it sees .ppt files as text and not binary for this to work, I am not sure what is the default behavior. See svn:mime-type for this : <a href="http://svnbook.red-bean.com/en/1.2/svn.advanced.props.html" rel="nofollow noreferrer">http://svnbook.red-bean.com/en/1.2/svn.advanced.props.html</a></p>
<p>Read this for detailed infos on $Rev$ replacement: <a href="http://svnbook.red-bean.com/en/1.4/svn.advanced.props.special.keywords.html" rel="nofollow noreferrer">http://svnbook.red-bean.com/en/1.4/svn.advanced.props.special.keywords.html</a></p>
|
<p>A little late but I consider that the original question is still relevant today.</p>
<p>Did you ever try <a href="https://insights.oetiker.ch/windows/SvnProperties4MSOffice/" rel="nofollow noreferrer">SvnProperties4MSOffice</a>? The second version (V2) seemed to be designed exactly as an alternative to keyword replacement for MS Office 2007 and above. It uses TortoiseSVN in the background: the SubWCRev tool (packaged with TortoiseSVN) is accessed through its COM interface by means of a VB macro.<br>
I know that the word "macro" can be frightening by itself but wait: this one is open source and quite simple. This makes it easily editable thus maintainable.</p>
<p>If you're interested to go further with the topic "MS Office & SVN" I invite you to <a href="https://gotomation.info/2019/01/svn-version-control-office-documents/" rel="nofollow noreferrer" title="Blog post: SVN version control for MS Office documents">read one of my blog posts</a>. You would have a chance to:</p>
<ul>
<li>Install a SVN menu right inside MS Word, MS Excel and MS PowerPoint</li>
<li>Diff two MS Office documents</li>
</ul>
<p><em>Disclaimer: I'm the owner of the blog.</em></p>
| 10,898
|
<p>The company I work for has recently been hit with many header injection and file upload exploits on the sites we host and while we have fixed the problem with respect to header injection attacks, we have yet to get the upload exploits under control.</p>
<p>I'm trying to set up a plug-and-play-type series of upload scripts to use in-house that a designer can copy into their site's structure, modify a few variables, and have a ready-to-go upload form on their site. We're looking to limit our exposure as much as possible (we've already shut down fopen and shell commands).</p>
<p>I've searched the site for the last hour and found many different answers dealing with specific methods that rely on outside sources. What do you all think is the best script-only solution that is specific enough to use as a reliable method of protection? Also, I'd like to keep the language limited to PHP or pseudo-code if possible.</p>
<p><strong>Edit:</strong> I've found my answer (posted below) and, while it does make use of the shell command exec(), if you block script files from being uploaded (which this solution does very well), you won't run into any problems.</p>
|
<p>The best solution, IMHO, is to put the directory containing the uploaded files outside of the "web" environment and use a script to make them downloadable. In this way, even if somebody uploads a script it can not be executed by calling it from the browser and you don't have to check the type of the uploaded file.</p>
|
<p>Use and configure <a href="http://www.hardened-php.net/suhosin/a_feature_list.html" rel="nofollow noreferrer">Hardened-PHP</a> create a plain script using <a href="http://www.php.net/move_uploaded_file" rel="nofollow noreferrer">move_uploaded_file</a> and the <a href="http://es.php.net/features.file-upload" rel="nofollow noreferrer">$_FILES superglobal</a>. The simplest the script, the safest it will be (at least, as safe as the running PHP version itself)</p>
| 31,965
|
<p>What do you use to validate an email address on a ASP.NET form. I want to make sure that it contains no XSS exploits.</p>
<p>This is ASP.NET 1.1</p>
|
<p>Any script tags posted on an ASP.NET web form will cause your site to throw and unhandled exception.</p>
<p>You can use a asp regex validator to confirm input, just ensure you wrap your code behind method with a if(IsValid) clause in case your javascript is bypassed.
If your client javascript is bypassed and script tags are posted to your asp.net form, asp.net will throw a unhandled exception.</p>
<p>You can use something like:</p>
<pre><code><asp:RegularExpressionValidator ID="regexEmailValid" runat="server" ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" ControlToValidate="tbEmail" ErrorMessage="Invalid Email Format"></asp:RegularExpressionValidator>
</code></pre>
|
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Globalization;
using System.Text.RegularExpressions;
/// <summary>
/// Summary description for RegexUtilities
/// </summary>
public class RegexUtilities
{
bool InValid = false;
public bool IsValidEmail(string strIn)
{
InValid = false;
if (String.IsNullOrEmpty(strIn))
return false;
// Use IdnMapping class to convert Unicode domain names.
strIn = Regex.Replace(strIn, @"(@)(.+)$", this.DomainMapper);
if (InValid)
return false;
// Return true if strIn is in valid e-mail format.
return Regex.IsMatch(strIn, @"^(?("")(""[^""]+?""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" + @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9]{2,17}))$",
RegexOptions.IgnoreCase);
}
private string DomainMapper(Match match)
{
// IdnMapping class with default property values.
IdnMapping idn = new IdnMapping();
string domainName = match.Groups[2].Value;
try
{
domainName = idn.GetAscii(domainName);
}
catch (ArgumentException)
{
InValid = true;
}
return match.Groups[1].Value + domainName;
}
}
RegexUtilities EmailRegex = new RegexUtilities();
if (txtEmail.Value != "")
{
string[] SplitClients_Email = txtEmail.Value.Split(',');
string Send_Email, Hold_Email;
Send_Email = Hold_Email = "";
int CountEmail;/**Region For Count Total Email**/
CountEmail = 0;/**First Time Email Counts Zero**/
bool EmaiValid = false;
Hold_Email = SplitClients_Email[0].ToString().Trim().TrimEnd().TrimStart().ToString();
if (SplitClients_Email[0].ToString() != "")
{
if (EmailRegex.IsValidEmail(Hold_Email))
{
Send_Email = Hold_Email;
CountEmail = 1;
EmaiValid = true;
}
else
{
EmaiValid = false;
}
}
if (EmaiValid == false)
{
divStatusMsg.Style.Add("display", "");
divStatusMsg.Attributes.Add("class", "alert alert-danger alert-dismissable");
divStatusMsg.InnerText = "ERROR !!...Please Enter A Valid Email ID.";
txtEmail.Focus();
txtEmail.Value = null;
ScriptManager.RegisterStartupScript(Page, this.GetType(), "SmoothScroll", "SmoothScroll();", true);
divStatusMsg.Visible = true;
ClientScript.RegisterStartupScript(this.GetType(), "alert", "HideLabel();", true);
return false;
}
}
</code></pre>
| 22,058
|
<p>Does anyone know about a Docking Control like Visual Studio for WPF, where Databinding for the Panes is supported?
I tried the DockManager from Infragistics and from Actipro, but they lack this support.
For example, the Panes for the content need to be bound through Databinding, so removing the Entity on the other side of the binding would also remove it from the DocumentHost.</p>
<p>Any Idea? Or a lightweight workaround for any control?
Full databinding support from every control is crucial for my project.
Thanks in advance.</p>
|
<p>You might consider <a href="http://www.codeplex.com/AvalonDock/" rel="nofollow noreferrer">AvalonDock on Codeplex</a>. If it doesn't have the functionality you are looking for you can add it yourself since you get full source code!</p>
|
<p>I know this won't help the original poster but in case someone else comes across this with a similar question, there is a <a href="http://blogs.infragistics.com/blogs/andrew_smith/archive/2010/01/12/itemssource-for-xamdockmanager-elements.aspx" rel="nofollow noreferrer">blog post</a> with a sample using an attached property to implement binding support in the Infragistics XamDockManager.</p>
| 46,413
|
<p>I just wrote the following C++ function to programmatically determine how much RAM a system has installed. It works, but it seems to me that there should be a simpler way to do this. Am I missing something?</p>
<pre><code>getRAM()
{
FILE* stream = popen("head -n1 /proc/meminfo", "r");
std::ostringstream output;
int bufsize = 128;
while( !feof(stream) && !ferror(stream))
{
char buf[bufsize];
int bytesRead = fread(buf, 1, bufsize, stream);
output.write(buf, bytesRead);
}
std::string result = output.str();
std::string label, ram;
std::istringstream iss(result);
iss >> label;
iss >> ram;
return ram;
}
</code></pre>
<p>First, I'm using <code>popen("head -n1 /proc/meminfo")</code> to get the first line of the meminfo file from the system. The output of that command looks like</p>
<blockquote>
<p>MemTotal: 775280 kB</p>
</blockquote>
<p>Once I've got that output in an <code>istringstream</code>, it's simple to tokenize it to get at the information I want. Is there a simpler way to read in the output of this command? Is there a standard C++ library call to read in the amount of system RAM?</p>
|
<p>On Linux, you can use the function <code>sysinfo</code> which sets values in the following struct:</p>
<pre><code> #include <sys/sysinfo.h>
int sysinfo(struct sysinfo *info);
struct sysinfo {
long uptime; /* Seconds since boot */
unsigned long loads[3]; /* 1, 5, and 15 minute load averages */
unsigned long totalram; /* Total usable main memory size */
unsigned long freeram; /* Available memory size */
unsigned long sharedram; /* Amount of shared memory */
unsigned long bufferram; /* Memory used by buffers */
unsigned long totalswap; /* Total swap space size */
unsigned long freeswap; /* swap space still available */
unsigned short procs; /* Number of current processes */
unsigned long totalhigh; /* Total high memory size */
unsigned long freehigh; /* Available high memory size */
unsigned int mem_unit; /* Memory unit size in bytes */
char _f[20-2*sizeof(long)-sizeof(int)]; /* Padding for libc5 */
};
</code></pre>
<p>If you want to do it solely using functions of C++ (I would stick to <code>sysinfo</code>), I recommend taking a C++ approach using <code>std::ifstream</code> and <code>std::string</code>:</p>
<pre><code>unsigned long get_mem_total() {
std::string token;
std::ifstream file("/proc/meminfo");
while(file >> token) {
if(token == "MemTotal:") {
unsigned long mem;
if(file >> mem) {
return mem;
} else {
return 0;
}
}
// Ignore the rest of the line
file.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
return 0; // Nothing found
}
</code></pre>
|
<p>Even <code>top</code> (from <code>procps</code>) parses <code>/proc/meminfo</code>. See <a href="http://procps.cvs.sourceforge.net/viewvc/procps/procps/proc/sysinfo.c?revision=1.40&view=markup" rel="nofollow noreferrer">here</a>.</p>
| 45,530
|
<p>In my browsings amongst the Internet, I came across <a href="http://www.reddit.com/r/programming/comments/6y6lr/ask_proggit_which_is_more_useful_to_know_c_or_java/" rel="nofollow noreferrer">this post</a>, which includes this</p>
<blockquote>
<p>"(Well written) C++ goes to great
lengths to make stack automatic
objects work "just like" primitives,
as reflected in Stroustrup's advice to
"do as the ints do". This requires a
much greater adherence to the
principles of Object Oriented
development: your class isn't right
until it "works like" an int,
following the "Rule of Three" that
guarantees it can (just like an int)
be created, copied, and correctly
destroyed as a stack automatic."</p>
</blockquote>
<p>I've done a little C, and C++ code, but just in passing, never anything serious, but I'm just curious, what it means exactly?</p>
<p>Can someone give an example?</p>
|
<p>Stack objects are handled automatically by the compiler.</p>
<p>When the scope is left, it is deleted.</p>
<pre><code>{
obj a;
} // a is destroyed here
</code></pre>
<p>When you do the same with a 'newed' object you get a memory leak :</p>
<pre><code>{
obj* b = new obj;
}
</code></pre>
<p>b is not destroyed, so we lost the ability to reclaim the memory b owns. And maybe worse, the object cannot clean itself up.</p>
<p>In C the following is common :</p>
<pre><code>{
FILE* pF = fopen( ... );
// ... do sth with pF
fclose( pF );
}
</code></pre>
<p>In C++ we write this :</p>
<pre><code>{
std::fstream f( ... );
// do sth with f
} // here f gets auto magically destroyed and the destructor frees the file
</code></pre>
<p>When we forget to call fclose in the C sample the file is not closed and may not be used by other programs. (e.g. it cannot be deleted).</p>
<p>Another example, demonstrating the object string, which can be constructed, assigned to and which is destroyed on exiting the scope.</p>
<pre><code>{
string v( "bob" );
string k;
v = k
// v now contains "bob"
} // v + k are destroyed here, and any memory used by v + k is freed
</code></pre>
|
<p>Variables in C++ can either be declared on the stack or the heap. When you declare a variable in C++, it automatically goes onto the stack, unless you explicitly use the new operator (it goes onto the heap).</p>
<pre><code>MyObject x = MyObject(params); // onto the stack
MyObject * y = new MyObject(params); // onto the heap
</code></pre>
<p>This makes a big difference in the way the memory is managed. When a variable is declared on the stack, it will be deallocated when it goes out of scope. A variable on the heap will not be destroyed until delete is explicitly called on the object.</p>
| 4,997
|
<p>I'm wondering how to use a VideoDisplay object (defined in MXML) to display video streamed from FMS via a NetStream.</p>
<p>The <a href="http://livedocs.adobe.com/flex/3/langref/mx/controls/VideoDisplay.html" rel="noreferrer">Flex3 docs</a> suggest this is possible:</p>
<blockquote>
<p>The Video Display ... supports progressive download over HTTP, streaming from the Flash Media Server, and streaming from a Camera object.</p>
</blockquote>
<p>However, later in the docs all I can see is an attachCamera() method. There doesn't appear to be an attachStream() method like the old Video object has.</p>
<p>It looks like you can play a fixed file served over HTML by using the source property, but I don't see anything about how to attach a NetStream.</p>
<p>The old <a href="http://livedocs.adobe.com/flex/3/langref/flash/media/Video.html" rel="noreferrer">Video</a> object still seems to exist, though it's not based on UIComponent and doesn't appear to be usable in MXML.</p>
<p>I found <a href="http://blog.flexexamples.com/2008/03/01/displaying-a-video-in-flex-using-the-netconnection-netstream-and-video-classes/" rel="noreferrer">this blog post</a> that shows how to do it with a regular Video object, but I'd much prefer to use VideoDisplay (or something else that can be put directly in the MXML).</p>
|
<p>Unfortunately you can attachNetStream() only on Video object. So you are doomed to use em if you want to get data from FMS.</p>
<p>By the way attachCamera() method <strong>publishes</strong> local camera video to the server so be careful ;)</p>
|
<p>it works.</p>
<p>mx:VideoDisplay live="true" autoPlay="true" source="rtmp://server.com/appname/streamname" /></p>
<p>that will give you live video through a videodisplay... problem is it won't use an existing netconnection object, it creates it's own... which is what I'm trying to find a work around for.</p>
| 6,377
|
<p>I have always made a point of writing nice code comments for classes and methods with the C# xml syntax. I always expected to easily be able to export them later on.</p>
<p>Today I actually have to do so, but am having trouble finding out how. Is there something I'm missing? I want to go <em>Menu->Build->Build Code Documentation</em>, but there is no option to do that, there.</p>
|
<p>Actually it's in the project properties. Build tab, Output section, XML documentation file, and enter the filename. It will be built on every build of the project.</p>
<p>After that you can build the actual help with <a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=E82EA71D-DA89-42EE-A715-696E3A4873B2&displaylang=en" rel="noreferrer">Sandcastle</a>.</p>
|
<p>The original NDoc project (mentioned by others) is dead, but there is a new project called <a href="https://sourceforge.net/projects/ndoc3/" rel="nofollow noreferrer">NDoc3</a>.</p>
<p>NDoc3 supports .NET 2.0 - 3.5. It is currently available as a beta version and worked great for me. I'm not sure if the project is still active - the last beta was release in april 2009.</p>
| 7,498
|
<p>what's the quickest way to extract a 5 digit number from a string in c#. </p>
<p>I've got </p>
<pre><code>string.Join(null, System.Text.RegularExpressions.Regex.Split(expression, "[^\\d]"));
</code></pre>
<p>Any others?</p>
|
<p>The regex approach is probably the quickest to implement but not the quickest to run. I compared a simple regex solution to the following manual search code and found that the manual search code is ~2x-2.5x faster for large input strings and up to 4x faster for small strings:</p>
<pre><code>static string Search(string expression)
{
int run = 0;
for (int i = 0; i < expression.Length; i++)
{
char c = expression[i];
if (Char.IsDigit(c))
run++;
else if (run == 5)
return expression.Substring(i - run, run);
else
run = 0;
}
return null;
}
const string pattern = @"\d{5}";
static string NotCached(string expression)
{
return Regex.Match(expression, pattern, RegexOptions.Compiled).Value;
}
static Regex regex = new Regex(pattern, RegexOptions.Compiled);
static string Cached(string expression)
{
return regex.Match(expression).Value;
}
</code></pre>
<p>Results for a ~50-char string with a 5-digit string in the middle, over 10^6 iterations, latency per call in microseconds (smaller number is faster):</p>
<p>Simple search: 0.648396us</p>
<p>Cached Regex: 2.1414645us</p>
<p>Non-cached Regex: 3.070116us</p>
<p>Results for a ~40K string with a 5-digit string in the middle over 10^4 iterations, latency per call in microseconds (smaller number is faster):</p>
<p>Simple search: 423.801us</p>
<p>Cached Regex: 1155.3948us</p>
<p>Non-cached Regex: 1220.625us</p>
<p>A little surprising: I would have expected Regex -- which is compiled to IL -- to be comparable to the manual search, at least for very large strings.</p>
|
<p>If you have a simple test case like "12345" or even "12345abcd" don't use regex at all. They are not known by they speed.</p>
| 32,858
|
<p>A lot of programs log things into a text file in a format something like this:</p>
<p>11/19/2008 13:29:01 DEBUG Opening connection to localhost.</p>
<p>11/19/2008 13:29:01 DEBUG Sending login message for user 'ADMIN'.</p>
<p>11/19/2008 13:29:03 DEBUG Received login response 'OK' for user 'ADMIN'.</p>
<p>...</p>
<p>However, I prefer something more structured like XML so I can parse the logs more easily. I've been doing this in my VB6 / Asp Classic programs for years and I want to do it in .Net now. <strong>Is there anything out there that will do this already or should I just re-write my VB6 code in C#?</strong></p>
<p>Here is how a call to my logging component looks for my VB6 programs:</p>
<pre><code>Trace.Warn "MMain", "Main(command, other data)", "Deprecated command", _
sCommandName, sOtherData
</code></pre>
<p>resulting in the following log entry:</p>
<pre><code><Info time="11/17/2008 04:49:45 PM" mod="MMain" proc="Main" entry="Deprecated command" command="The_Bad_Command" other_data="The other data." />
</code></pre>
<p>When I want to open the log with my custom log viewer, I simply wrap the whole file in a root node, and then I can easily do this using MSXML to filter the entries that I'm seeing, find a specific user's login, etc. etc...</p>
<pre><code><Log>
...the log file text...
</Log>
</code></pre>
|
<p>I'm not sure of any products that do that, but you could use <a href="http://www.ondotnet.com/pub/a/dotnet/2003/06/16/log4net.html" rel="nofollow noreferrer">log4net</a> and write your own <a href="http://logging.apache.org/log4net/release/features.html" rel="nofollow noreferrer">appender</a> (output handler).</p>
|
<p>Enteprise library Logging block provides different loggings formats such as xml but it is a long way to configure and deal with it</p>
| 39,009
|
<p>I'm trying to host a python script using an apache web server, but the server tries to run the script instead of just offering it for download.</p>
<p>I do not have direct access to server, and adding the line</p>
<pre><code>AddType text/plain .py
</code></pre>
<p>to .htaccess in the root folder does not appear to work, though I could be doing something wrong.</p>
<p>How do I get the server to just send the file as text instead of trying to run it?</p>
<p>-Edit</p>
<p>Changing the name does not work. Script.py.safe still give a 500 Server error when you click it. </p>
<p>I should also mention that the .htaccess file does work, but for some reason that one addType line is not working. Either because it's not overriding something, or the line is wrong.</p>
|
<p>In your .htaccess:</p>
<blockquote>
<p>RemoveHandler .py </p>
</blockquote>
|
<p>One option is to change the extention and make clear that it should be renamed. IE python.py.safe or python.py.dl. The user would then need to remove the extra bit.</p>
<p>You could also Zip it up.</p>
| 16,451
|
<p>I have the following construction:</p>
<pre><code>typedef struct bucket {
char *key;
ENTRY *data;
struct bucket *next;
} bucket;
typedef struct {
size_t size;
bucket **table;
} hash_table;
</code></pre>
<p>But I have no idea how to allocate memory for that. I tried: </p>
<pre><code>hash_table* ht = malloc(sizeof(hash_table)*101);
</code></pre>
<p>in order to create a hashtable for 101 entries but it din't work! Can anyone help me? I would really appreciate it!</p>
|
<p>It doesn't make sense to allocate all 101 (or however many) buckets upfront, you'd typically allocate them one at a time, when inserting new data into the table.</p>
<p>It <em>does</em> make sense to pre-allocate the hash array, which will have a fixed size, but that is an <em>array of bucket pointers</em>, not an array of buckets, so some of the answers are wrong.</p>
<p>You'd have something like this, to create a an empty hash table, with a fixed-size bucket array:</p>
<pre><code>hash_table * hash_table_new(size_t capacity)
{
size_t i;
hash_table *t = malloc(sizeof *t);
t->size = capacity;
t->bucket = malloc(t->size * sizeof *t->bucket);
for(i = 0; i < t->size; i++)
t->bucket[i] = NULL;
return t;
}
</code></pre>
<p>This code:</p>
<ul>
<li>Allocates a hash_table structure to hold the table</li>
<li>Initializes it's size with indicated capacity</li>
<li>Allocates an array of bucket pointers of the proper length</li>
<li>Makes sure each bucket pointer is NULL (which cannot properly be done with memset(), as it's not safe to assume that "all bits zero" is the way NULL looks in memory)</li>
<li>Uses <code>sizeof</code> whenever possible, but not on types, so no parenthesis</li>
<li>Doesn't cast the return value of <code>malloc()</code>, since that is never a good idea in C</li>
<li>Doesn't check the return value of malloc(), of course you should do that in real code</li>
</ul>
<p>A second function would be needed to do an actual hash insert, which will then need to allocate a new bucket, compute the hash value from the key, pick the proper location in the hash table's array, and insert the new entry there.</p>
|
<p>The <code>hash_table</code> will always be only <code>sizeof(hash_table)</code> bytes big. The <code>table</code> element is a pointer to an array of poiinters to <code>bucket</code> elements. So you'd need something like this:</p>
<pre><code>hash_table* ht = malloc(sizeof(hash_table));
ht->size = 101;
ht->table = malloc(sizeof(bucket*)*ht->size);
</code></pre>
<p>But I suspect that there may be some initialization method that comes with that, and you could then do something like this:</p>
<pre><code>hash_table* ht = alloc_hash_table(101);
</code></pre>
<p>Anyway, I'm kind of rusty in C, so take this with a grain of salt.</p>
| 48,436
|
<p>Linq To SQL or Entity framework both integrate nicely with SQL Server 2005.</p>
<p>The SQL Server 2008 spec sheet promises even better integration - but I can't see it.</p>
<p>What are some examples of what you can do Linq-wise when talking to a 2008 server that you can't when talking to SQL Server 2005?</p>
|
<p>There is a problem of paging over a joined set that SQL 2005 mis-interprets.</p>
<pre><code>var orders = (
from c in Customers
from o in c.Orders
select new {c, o}
).Skip(10).Take(10).ToList();
</code></pre>
<p>LINQ generates a ROW_Number against the joined set. SQL2005 generates a bad plan from that code. Here's a link to the <a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=3091519&SiteID=1" rel="nofollow noreferrer">discussion</a>.</p>
<p>Edit#2: I'd like to clarify that I don't know that SQL2008 solves this problem. I'm just hopeful.</p>
|
<p>it has full support for the new data types. lol. beyond that you got me, other than possibilities of optimised queries (like the merge command, etc).</p>
| 3,621
|
<p>Does anyone know of a way to store values as NVARCHAR in a manually created query in ColdFusion using the querynew() function? I have multiple parts of a largish program relying on using a query as an input point to construct an excel worksheet (using Ben's POI) so it's somewhat important I can continue to use it as a query to avoid a relatively large rewrite.</p>
<p>The problem came up when a user tried storing something that is outside of the VARCHAR range, some Japanese characters and such.</p>
<p>Edit: If this is not possible, and you are 100% sure, I'd like to know that too :)</p>
|
<p>When creating a ColdFusion query with queryNew(), you can pass a list of datatypes as a second argument. For example:</p>
<pre><code><cfset x = queryNew("foo,bar","integer,varchar") />
</code></pre>
<p>Alternatively, you can use cf_sql_varchar (which you would use in queryparam tags). According to the livedocs, nvarchar is accepted for the CF varchar data type.</p>
<p><a href="http://livedocs.adobe.com/coldfusion/7/htmldocs/wwhelp/wwhimpl/common/html/wwhelp.htm?context=ColdFusion_Documentation&file=part_cfm.htm" rel="nofollow noreferrer">QueryParam livedoc (referenced for nvarchar data type)</a></p>
<p><a href="http://livedocs.adobe.com/coldfusion/7/htmldocs/wwhelp/wwhimpl/common/html/wwhelp.htm?context=ColdFusion_Documentation&file=00000600.htm" rel="nofollow noreferrer">QueryNew livedoc (referenced for data type definition)</a></p>
<p><a href="http://livedocs.adobe.com/coldfusion/7/htmldocs/wwhelp/wwhimpl/common/html/wwhelp.htm?context=ColdFusion_Documentation&file=00001270.htm#1182700" rel="nofollow noreferrer">Managing Data Types livedoc (referenced for using cf_sql_datatype)</a></p>
|
<p>This is pretty much all you need: </p>
<pre><code><cfprocessingdirective pageEncoding="utf-8">
</code></pre>
<p>ColdFusion (& java) stores string in UTF-8 by default. All you need is to tell CF that the encoding of the page is UTF8. The alternative way is to save the Byte-order mark (BOM), but Eclipse/CFEclipse doesn't do it.</p>
| 35,692
|
<p>A problem that we need to solve regularly at my workplace is how to build sql statements based on user supplied table/column names. The issue I am trying to address is the commas between column names. </p>
<p>One technique looks something like this.</p>
<pre><code>selectSql = "SELECT ";
for (z = 0; z < columns.size(); z++)
{
selectSql += columns[z]._name;
selectSql += ", ";
}
selectSql = selectSql(0, selectSql.len() - 2);
selectSql += "FROM some-table";
</code></pre>
<p>Another technique looks something like this</p>
<pre><code>selectSql = "SELECT ";
for (z = 0; z < columns.size(); z++)
{
selectSql += columns[z]._name;
if (z < columns.size() - 1)
selectSql += ", ";
}
selectSql += "FROM some-table";
</code></pre>
<p>I am not particularly enthralled by either of these implementations.</p>
<p>I am interesting in hearing ideas for other ways to address this issue, with an eye toward making the code easier to read/understand/maintain.</p>
<p>What alternate techniques are available?</p>
|
<p>In your case it is probably safe to assume that there is at least one column since otherwise there is no point in doing the select. In that case you could do:</p>
<pre><code>selectSql = "SELECT ";
selectSql += columns[0]._name;
for (z = 1; z < columns.size(); z++) {
selectSql += ", ";
selectSql += columns[z]._name;
}
selectSql += " FROM some-table";
</code></pre>
|
<p>I would suggest building a generic join function to do this. You can use the e.g. accumulate algorithm to join columns.</p>
<p>EDIT: <strong>See <a href="https://stackoverflow.com/questions/327010/using-a-vector-of-column-names-to-generate-a-sql-statement#327862">litb's implementation</a></strong>; it's much less naïve.</p>
<pre><code>// Untested
#include <numeric>
template<std::string separator>
struct JoinColumns {
std::string operator()(Column a, Column b) {
return a._name + separator + b._name;
}
// Too lazy to come up with a better name
std::string inArray(T array) {
stl::accumulate(array.begin(), array.end(), std::string(), *this);
}
};
selectSql += stl::accumulate(columns.begin(), columns.end(), std::string(), JoinColumns<", ">());
// or
selectSql += JoinColumns<", ">().inArray(columns);
</code></pre>
<p>You can get a cleaner syntax by using better wrappers, of course.</p>
| 42,368
|
<p>[This is a community Wiki so do <strong>not</strong> bother voting it down if it seems like a poll question. It is.]</p>
<p>Will Adobe be able to translate its success in Flash Penetration (although also questionable, see my post <a href="http://compileyouidontevenknowyou.blogspot.com/2008/01/flash-penetration-and-bullshit.html" rel="nofollow noreferrer">here</a>) to Adobe AIR? Is Adobe AIR the "next big thing" in a desktop platform, just another player (along with what else?), or will it die a silent and unimportant death?</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,773
|
<p>A database that stores a lot of credit card information is an inevitable part of the system we have just completed. What I want though is ultimate security of the card numbers whereby we setup a mechanism to encrypt and decrypt but of ourselves cannot decrypt any given number. </p>
<p>What I am after is a way to secure this information even down at the database level so no one can go in and produce a file of card numbers. How have others overcome this issue? What is the 'Standard' approach to this?</p>
<p>As for usage of the data well the links are all private and secure and no transmission of the card number is performed except when a record is created and that is encrypted so I am not worried about the front end just the back end.</p>
<hr>
<p>Well the database is ORACLE so I have PL/SQL and Java to play with.</p>
|
<p>Unless you are a payment processor you don't really need to store any kind of CC information.</p>
<p>Review your requirements, there really is not many cases where you need to store CC information</p>
|
<p>It would be helpful to know the DB server and language/platform types so we could get more specific, but I would be looking into <a href="http://en.wikipedia.org/wiki/SHA" rel="nofollow noreferrer">SHA</a>.</p>
| 8,374
|
<p>I have a large database and would like to select table names that have a certain column name. I have done something like this in MySQL, but can't find any info on SQL Server.</p>
<p>I want to do something like:</p>
<pre><code>select [table]
from [db]
where table [has column 'classtypeid']
</code></pre>
<p>How can I do something like this?</p>
|
<p>Use the ANSI information_schema views, this will also work in MySQL</p>
<pre><code>select table_name
from information_schema.columns
where column_name = 'classtypeid'
</code></pre>
|
<p>Here you go:</p>
<pre><code>SELECT C.TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS AS C
INNER JOIN INFORMATION_SCHEMA.TABLES AS T ON C.TABLE_NAME = T.TABLE_NAME
AND C.TABLE_SCHEMA = T.TABLE_SCHEMA
WHERE C.COLUMN_NAME = 'classtypeid'
AND T.TABLE_TYPE = 'BASE TABLE'
</code></pre>
<hr>
<p><strong>Edit</strong>: Note that this will not list views based on any tables with that column. If you only query INFORMATION_SCHEMA.COLUMNS you will also get back views.</p>
| 4,768
|
<p>Let me preface this question by saying I use TextMate on Mac OSX for my text needs and I am in love with it. Anything comparable on the Linux platform? I'll mostly use it for coding python/ruby.</p>
<p>Doing a google search yielded outdated answers.</p>
<p>Edit: Since there has been some concern about the 'merit' of this question. I am about to start a new Ruby Programming Project in Linux and before I got started I wanted to make sure I had the right tools to do the job.</p>
<p>Edit #2: I use VIM on a daily basis -- all . the . time. I enjoy using it. I was just looking for some alternatives.</p>
|
<p><img src="https://i.stack.imgur.com/YayAV.png" alt="Real programmers set the universal constants at the start such that the universe evolves to contain the disk with the data they want."></p>
<p><a href="http://xkcd.com/378/" rel="noreferrer">http://xkcd.com/378/</a></p>
|
<p>You can try Emacs with ruby-mode, <a href="http://rinari.rubyforge.org/" rel="nofollow noreferrer">Rinari</a> (for Rails) and <a href="http://code.google.com/p/yasnippet/" rel="nofollow noreferrer">yasnippet</a> which provides automatic snippets like Textmate.</p>
| 2,504
|
<p>I have recently bought a spool of eSun PETG. So far I really like the filament. My only complaint is, I get lumps of charred filament deposited on my object. The slicer I used is Craft Ware and I have played with the Far Travel -> Elevation settings. I have noticed that this helps but then I have little to no adhesion to the print surface and my supports do not stick to the raft. Does any one know how to mitigated PETG from collecting on the extruder?</p>
|
<p>Different brands and blends of PET filaments seem to do this to different degrees. Esun's PETG is definitely one that tends to glob onto the nozzle. Basically, the nozzle plows through the top surface of the filament and lifts up some plastic, much like the bow of a ship lifting up some water at high speeds. PET's viscosity and stickiness seem to amplify this effect more than other filaments. </p>
<p>Some things you can do to minimize the globbing:</p>
<ul>
<li>Calibrate extrusion volume on the low end of what you'd normally use for other filaments (how you do this depends on your slicer)</li>
<li>Use your slicer's "Z-hop" or "avoid perimeters" feature so you don't do travel moves across printed surfaces</li>
<li>Invest in an anti-stick coated nozzle, such as are sold by <a href="http://www.micro-swiss.com/#!3d-printing/c843" rel="noreferrer">Micro Swiss</a> or <a href="https://www.p3-d.com/collections/duraplat-3d-extruder-nozzles" rel="noreferrer">Performance 3-d</a> (these don't eliminate globbing, but they do reduce it and make the nozzle much easier to clean)</li>
<li>Play with slicer settings such as extrusion width, layer height, and infill/perimeter overlap to reduce the amount of "excess material" that sticks above the print surface</li>
</ul>
<p>Again, this is a common problem with PET blend filaments. Anecdotally, some brands seem to glob more or less than others, so switching to a different vendor may be worth trying if you want to do a lot of PETG prints. </p>
|
<p>For me, none of the classic solutions to PETG zits worked; these include extra retraction, slower/faster retraction, lower extrusion width, lower extrusion multiplier, avoid perimeters etc. It was especially disappointing to see lower extrusion multiplier making no difference whatsoever in reducing the zits, but only resulting in a mechanically weaker and even spongy result. What made all the difference is to <strong>disable z lifting during retraction</strong> which my slicer profile has enabled by default. This setting alone eliminated nearly all zits and most stringing (i.e spiderwebs). </p>
<p>Of course, the amount of zits and stringing will heavily depend on the particular filament you're using and the particular model you're printing.</p>
<p><em>Additional note:</em> I was getting extra zits/overextrusion on a particular model I had that was exceptionally thin and tall when attempting to print with PETG. Lower extrusion multiplier made no improvement but weakened the part and resulted in spongy structure. I was successful in printing this part <strong>along with another part that was of similar height</strong>. I'm suspecting that printing the part alone but <strong>much more slowly</strong> to help with cooling would also succeed.</p>
| 216
|
<p>Is there some simple way to calculate a Weeknumber value from a date value stored in XML?</p>
<p>It needs to be pure XSLT solution. I cannot use any code :(</p>
|
<p>If you can use EXSLT, there are <a href="http://www.exslt.org/date/index.html" rel="nofollow noreferrer">several date functions</a> available. All of them are implemented in Saxon, but if you're using MSXSL, Chris Bayes has implemented them as extension functions, which you can actually place within your transform inside an msxsl:script element. His implementations are linked from each specific date function page. </p>
<p>Is <a href="http://www.exslt.org/date/functions/week-in-year/index.html" rel="nofollow noreferrer">week-in-year()</a> the function you're looking for?</p>
<p><b>Edit:</b> Per JeniT's comment, there's a <a href="http://www.exslt.org/date/functions/week-in-year/date.week-in-year.template.xsl" rel="nofollow noreferrer">pure XSLT 1.0 template</a> available on the same site with the same functionality as week-in-year() (which she wrote, I think), which might fit your requirements better. </p>
|
<p>I program in Visual Basic, so I know how to do it using VB.NET. Read your XML date into a variable (let's call it <em>SomeDate</em>). Then you construct a new date that you <strong>know</strong> is the beginning of the year that contains your unknown date. Then, you let the <em>DateDiff</em> function do its work to tell you the week number.</p>
<pre><code>Dim SomeDate As Date = ReadDateFromXML()
Dim YearStart As New Date(Year(SomeDate), 1, 1)
Dim WeekNumber As Integer = DateDiff(DateInterval.WeekOfYear, YearStart, SomeDate)
</code></pre>
| 21,559
|
<p>I want to do some pattern matching on lists in Python. For example, in Haskell, I can do something like the following:</p>
<pre><code>fun (head : rest) = ...
</code></pre>
<p>So when I pass in a list, <code>head</code> will be the first element, and <code>rest</code> will be the trailing elements.</p>
<p>Likewise, in Python, I can automatically unpack tuples:</p>
<pre><code>(var1, var2) = func_that_returns_a_tuple()
</code></pre>
<p>I want to do something similar with lists in Python. Right now, I have a function that returns a list, and a chunk of code that does the following:</p>
<pre><code>ls = my_func()
(head, rest) = (ls[0], ls[1:])
</code></pre>
<p>I wondered if I could somehow do that in one line in Python, instead of two.</p>
|
<p>So far as I know there's no way to make it a one-liner in current Python without introducing another function, e.g.:</p>
<pre><code>split_list = lambda lst: (lst[0], lst[1:])
head, rest = split_list(my_func())
</code></pre>
<p>However, in Python 3.0 the specialized syntax used for variadic argument signatures and argument unpacking will become available for this type of general sequence unpacking as well, so in 3.0 you'll be able to write:</p>
<pre><code>head, *rest = my_func()
</code></pre>
<p>See <a href="https://www.python.org/dev/peps/pep-3132/" rel="noreferrer">PEP 3132</a> for details.</p>
|
<p>there was a reciepe in the python cookbook to do this. i cant seem to find it now but here is the code (i modified it slightly)</p>
<pre><code>
def peel(iterable,result=tuple):
'''Removes the requested items from the iterable and stores the remaining in a tuple
>>> x,y,z=peel('test')
>>> print repr(x),repr(y),z
't' 'e' ('s', 't')
'''
def how_many_unpacked():
import inspect,opcode
f = inspect.currentframe().f_back.f_back
if ord(f.f_code.co_code[f.f_lasti])==opcode.opmap['UNPACK_SEQUENCE']:
return ord(f.f_code.co_code[f.f_lasti+1])
raise ValueError("Must be a generator on RHS of a multiple assignment!!")
iterator=iter(iterable)
hasItems=True
amountToUnpack=how_many_unpacked()-1
next=None
for num in xrange(amountToUnpack):
if hasItems:
try:
next = iterator.next()
except StopIteration:
next = None
hasItems = False
yield next
if hasItems:
yield result(iterator)
else:
yield None
</code></pre>
<p>however you should note that that only works when using an assignment unpack because of the way it inespects the previous frame... still its quite useful.</p>
| 29,453
|
<p>I have found some in the Cappuccino website (vim, textmate and SubEthaEdit), but not for jEdit, and unfortunately I'm just starting on Objective-J so can't make my own. If anyone has got one of them lying around it would be greatly appreciated.</p>
|
<p>According to the JEdit <a href="http://jedit.org/index.php?page=features" rel="nofollow noreferrer">features page</a> it already supports Objective C.</p>
|
<p>One of my favorite things about JEdit is how easy it is to define a new syntax highlighting mode. I work in a land in which every fool wants to create his own custom configuration file language and I've gotten to where I can create a new approximate syntax highlighting mode in about 5 minutes. I start by copying a mode that is similar to the new language I wanted to create and then iteratively refining the edit mode as I learn more parts of the language. I did this with Specman ( a hardware verification language ) as I was going through the intro course.</p>
| 14,093
|
<p>Does anyone know of any way to convert a simple gif to xaml? E.G. A tool that would look at an image and create elipses, rectangles and paths based upon a gif / jpg / bitmap?</p>
|
<p>Illustrator has a trace tool which will do this</p>
<p>a cheaper option might be </p>
<p><a href="http://vectormagic.com" rel="noreferrer">http://vectormagic.com</a></p>
<p>it will export a svg that you should be able to convert to xaml</p>
|
<p>With this online converter you can convert an image to SVG Format. then download Converted File and open it in a text File Editor then you can easily copy path data</p>
<p><a href="http://image.online-convert.com/convert-to-svg" rel="nofollow noreferrer">image.online-convert</a> </p>
| 15,787
|
<p>Can someone please let me know how to get the different segments of the three rows that are intersecting in different ways using SQL? The three rows in #t2 represent sets A,B, C - I am looking for A I B, A I C, B I C, A I B I C, A' , B', C' etc., (7 possible segments with 3 rows as in a Venn diagram) where I is the Intersection.</p>
<p>I am looking for a generic solution which can handle n number of rows in #t2.</p>
<pre><code>-- SQL Code Begin
create table #t1 (key1 int, key2 int) -- for each Key1 there can be 1 or more Key2
go
create table #t2 (row_id int identity(101, 1), key1 int) --row_id is the primary key
go
insert into #t1
select 1, 11 union select 1, 12 union select 1, 13 union select 1, 14 union
select 2, 13 union select 2, 15 union select 2, 16 union select 2, 17 union
select 3, 13 union select 3, 12 union select 3, 16 union select 3, 17
-- 1 --> 11, 12, 13, 14
-- 2 --> 13, 15, 16, 17
-- 3 --> 13, 12, 16, 17
insert into #t2 (key1)
select 1 union select 2 union select 3
-- SQL Code End
</code></pre>
<p>The output I am looking for is,</p>
<pre><code>1001 11 (A')
1001 14 (A')
1002 12 (A I C - A I B I C)
1003 13 (A I B I C)
1004 15 (B')
1005 16 (B I C - A I B I C)
1005 17 (B I C - A I B I C)
</code></pre>
<p>The output has 5 segments, instead of the possible 7 as two of them are NULL.</p>
|
<p>If I have understood the problem correctly, I think you may have to resort to using a loop to cope with 'n' number of rows</p>
<pre><code>DECLARE @Key2 INT
DECLARE @Subset VARCHAR(1000)
DECLARE @tblResults TABLE
(
Key2 INT,
Subset VARCHAR(1000)
)
SET @Subset = ''
SELECT @Key2 = MIN(Key2) FROM #t1
WHILE @Key2 IS NOT NULL
BEGIN
SELECT @Subset = @Subset + CAST(Key1 AS VARCHAR(10))
FROM #t1
WHERE Key2 = @Key2
INSERT INTO @tblResults (Key2, Subset)
VALUES (@Key2, @Subset)
SET @Subset = ''
SELECT @Key2 = MIN(Key2) FROM #t1 WHERE Key2 > @Key2
END
SELECT * FROM @tblResults
</code></pre>
|
<p>How about this?</p>
<pre><code>SELECT key2,
CASE
WHEN InA = 1 and InB = 1 and InC = 1 THEN 'ABC'
WHEN InA = 0 and InB = 1 and InC = 1 THEN 'BC'
WHEN InA = 1 and InB = 0 and InC = 1 THEN 'AC'
WHEN InA = 1 and InB = 1 and InC = 0 THEN 'AB'
WHEN InA = 1 and InB = 0 and InC = 0 THEN 'A'
WHEN InA = 0 and InB = 1 and InC = 0 THEN 'B'
WHEN InA = 0 and InB = 0 and InC = 1 THEN 'C'
ELSE 'I''m broke'
END as [SubSet]
FROM
(
SELECT key2,
MAX(CASE WHEN key1 = 1 THEN 1 ELSE 0 END) as InA,
MAX(CASE WHEN key1 = 2 THEN 1 ELSE 0 END) as InB,
MAX(CASE WHEN key1 = 3 THEN 1 ELSE 0 END) as InC
FROM #t1
WHERE key1 in (1, 2, 3)
GROUP BY key2
) sub
ORDER BY key2
</code></pre>
| 27,104
|
<p>I am actually trying to start a process for winzip and zip a folder. This i am doing using the below code in vb.</p>
<pre><code>Dim startInfo As New System.Diagnostics.ProcessStartInfo
Dim pStart As New System.Diagnostics.Process
Dim tempFileName As String
Try
startInfo = New System.Diagnostics.ProcessStartInfo( _
"c:\Program Files\WinZip\WINZIP32.EXE")
startInfo.Arguments = " -a -r ""c:\test.zip"" c:\test"
startInfo.UseShellExecute = False
startInfo.WindowStyle = Diagnostics.ProcessWindowStyle.Normal
pStart.StartInfo = startInfo
'startInfo.WorkingDirectory = "c:\Program Files\WinZip"
'startInfo.FileName = "WINZIP32.EXE"
pStart.Start()
pStart.WaitForExit()
Catch ex As Exception
Throw
End Try
</code></pre>
<p>This works fine when it's put in a button click event of a windows application. But when the same is done in a button click event of a web application I can see the process is started in the task manager of the machine. But its doesn't zip nor does it close the application nor does it pop up its winzip ui.... But in very few machines this does work fine. In most of the machine i am facing the problem and also able to reproduce the problem consistently...</p>
<p>But a similar thing if i try doing using 7z zip, it does work fine form a web application itself...</p>
<p>Is there a workaround for this process?</p>
|
<p>I believe that the .Net framework has built in zip capabilities. I would try using those first. Your zip program probably isn't running because of permissions on the web server.</p>
<p>Edit</p>
<p>I just checked and there seems to be limited zip support in System.IO.Compression. But according to <a href="http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/a343411d-f577-431b-92d7-5792912a7652/" rel="nofollow noreferrer">this discussion</a>, it might not be what you need. That discussion however, mentions an article called "<a href="http://geraldgibson.net/dnn/Home/CZipFileDecompression/tabid/149/Default.aspx" rel="nofollow noreferrer">Decompress Zip files with Windows Shell API and C#</a>". </p>
|
<p>It might be something to do with the user that IIS is running as; try changing the app-pool to run in your identity to see if it works. Of course, winzip is a UI tool - you might do better using a command-line zip utility... pkzip ;-p</p>
<p>Personally, I'd look at using <a href="http://www.icsharpcode.net/OpenSource/SharpZipLib/" rel="nofollow noreferrer">#ZipLib</a> instead - this will allow you to manipulate zip files in managed code.</p>
| 47,355
|
<p>Using Oracle 10g, accessed via Perl DBI, I have a table with a few tens of million rows being updated a few times per second while being read from much more frequently form another process.</p>
<p>Soon the update frequency will increase by an order of magnitude (maybe two).
Someone suggested that committing every N updates instead of after every update will help performance.</p>
<p>I have a few questions:</p>
<ul>
<li>Will that be faster or slower or it depends (planning to benchmark both way as soon as can get a decent simulation of the new load)</li>
<li>Why will it help / hinder performance.</li>
<li>If "it depends ..." , on what ?</li>
<li>If it helps what's the best value of N ?</li>
<li>Why can't my local DBA have an helpful straight answer when I need one? <br />(Actually I know the answer to that one) :-) </li>
</ul>
<blockquote>
<p>EDIT:</p>
<p>@codeslave : Thanks, btw losing
uncommited changes is not a problem, I
don't delete the original data used
for updating till I am sure everything
is fine , btw cleaning lady did
unplugs the server, TWICE :-)</p>
<p>Some googling showed it might help
because of issue related to rollback
segments, but I still don't know a
rule of thumb for N every few tens ?
hundreds? thousand ?</p>
<p>@diciu : Great info, I'll definitely
look into that.</p>
</blockquote>
|
<p>A commit results in Oracle writing stuff to the disk - i.e. in the redo log file so that whatever the transaction being commited has done can be recoverable in the event of a power failure, etc.
Writing in file is slower than writing in memory so a commit will be slower if performed for many operations in a row rather then for a set of coalesced updates.</p>
<p>In Oracle 10g there's an asynchronous commit that makes it much faster but less reliable: <a href="https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-6158695.html" rel="nofollow noreferrer">https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-6158695.html</a></p>
<p>PS I know for sure that, in a scenario I've seen in a certain application, changing the number of coalesced updates from 5K to 50K makes it faster by an order of magnitude (10 times faster).</p>
|
<blockquote>
<p>Faster/Slower? </p>
</blockquote>
<p>It will probably be a little faster. However, you run a greater risk of running into deadlocks, losing uncommitted changes should something catastrophic happen (cleaning lady unplugs the server), FUD, Fire, Brimstone, etc.</p>
<blockquote>
<p>Why would it help? </p>
</blockquote>
<p>Obviously fewer commit operations, which in turn means fewer disk writes, etc.</p>
<blockquote>
<p>DBA's and straight answers? </p>
</blockquote>
<p>If it was easy, you won't need one.</p>
| 5,319
|
<p>Is there an equivalent schema & data export/dumping tool for SQL Server as there is for MySQL with mysqldump. Trying to relocate a legacy ASP site and I am way out of happy place with working on a windows server.</p>
<p>Note: The DTS export utility own seems to export data, without table defs.
Using the Enterprise Manager and exporting the db gets closer with exporting the schema & data... but still misses stored procedures.</p>
<p>Basically looking for a one does it all solution that grabs everything I need at once.</p>
|
<h2>To do this really easily with SQL Server 2008 Management Studio:</h2>
<p>1.) Right click on the database (not the table) and select Tasks -> Generate Scripts</p>
<p><img src="https://i.stack.imgur.com/9MnoI.jpg" alt="location of tool"></p>
<p>2.) Click Next on the first page</p>
<p>3.) If you want to copy the whole database, just click next. If you want to copy specific tables, click on "Select Specific Database Objects", select the tables you want, and then click next.</p>
<p>4.) "Save to File" should be selected. <strong>IMPORTANT</strong>: Click the Advanced button next to "Save to File", find "Types of data to script", and change "Schema only" to "Schema and data" (if you want to create the table) or "Data only" (if you're copying data to an existing table).</p>
<p><img src="https://i.stack.imgur.com/nFnug.jpg" alt="adding data to the script"></p>
<p>5.) Click through the rest and you're done! It will save as a .sql file.</p>
|
<p>easiest would be a backup and restore or detach and attach</p>
<p>or script out all the tables and BCP out the data then BCP in the data on the new server</p>
<p>or use DTS/SSIS to do this</p>
| 11,077
|
<p>i am trying to find the best way to display results on my page via an Ajax call using jQuery, do you think the best way is to pass it as JSON or plain text? I have worked with ajax calls before, but not sure which is preferred over the other and for the JSON version what is the best way to read from a JSON file generated by a PHP page to display my results.</p>
<p>i know I would include a <code>.each</code> to run through it to display them all.</p>
|
<p>Something like this:</p>
<pre><code>$.getJSON("http://mywebsite.com/json/get.php?cid=15",
function(data){
$.each(data.products, function(i,product){
content = '<p>' + product.product_title + '</p>';
content += '<p>' + product.product_short_description + '</p>';
content += '<img src="' + product.product_thumbnail_src + '"/>';
content += '<br/>';
$(content).appendTo("#product_list");
});
});
</code></pre>
<p>Would take a json object made from a PHP array returned with the key of products. e.g:</p>
<pre><code>Array('products' => Array(0 => Array('product_title' => 'Product 1',
'product_short_description' => 'Product 1 is a useful product',
'product_thumbnail_src' => '/images/15/1.jpg'
)
1 => Array('product_title' => 'Product 2',
'product_short_description' => 'Product 2 is a not so useful product',
'product_thumbnail_src' => '/images/15/2.jpg'
)
)
)
</code></pre>
<p>To reload the list you would simply do:</p>
<pre><code>$("#product_list").empty();
</code></pre>
<p>And then call getJSON again with new parameters.</p>
|
<p>You can create a jQuery object from a JSON object:</p>
<pre><code>$.getJSON(url, data, function(json) {
$(json).each(function() {
/* YOUR CODE HERE */
});
});
</code></pre>
| 42,402
|
<p>I'm trying to write a Selenium test for a web page that uses an onbeforeunload event to prompt the user before leaving. Selenium doesn't seem to recognize the confirmation dialog that comes up, or to provide a way to hit OK or Cancel. Is there any way to do this? I'm using the Java Selenium driver, if that's relevant.</p>
|
<p>You could write a user extension (or just some JavaScript in a storeEval etc) that tests that window.onbeforeunload is set, and then replaces it with null before continuing on from the page. Ugly, but ought to get you off the page.</p>
|
<p>When I was confronted with limited control which I had over browser using Selenium, I turned to <a href="http://hyperstruct.net/projects/mozlab" rel="nofollow noreferrer">MozLab</a> plugin which solved my problem if only for one browser platform.</p>
| 19,837
|
<p>This is what I'd like to do, but it doesn't seem possible:
(edit: changed single to double quotes)</p>
<pre><code>function get_archives($limit, $offset)
{
$query = $this->db->query("
SELECT archivalie.id,
archivalie.signature,
type_of_source.description AS type_of_source_description,
media_type.description AS media_type_description,
origin.description AS origin_description
FROM archivalie,
type_of_source,
media_type,
origin
WHERE archivalie.type_of_source_id = type_of_source.id
AND type_of_source.media_type_id = media_type.id
AND archivalie.origin_id = origin.id
ORDER BY archivalie.id ASC
LIMIT $limit, $offset
");
// etc...
}
</code></pre>
<p>It gives this error:
(edit: new error message using double quotes, and with an offset number passed in the URL)</p>
<pre><code>ERROR: LIMIT #,# syntax is not supported HINT: Use separate LIMIT and OFFSET clauses.
</code></pre>
<p>It only works if you pass the variables using the ActiveRecord format:</p>
<pre><code>$this->db->select('archivalie.id, archivalie.signature, etc, etc');
// from, where, etc.
$this->db->limit($limit, $offset);
$query = $this->db->get();
</code></pre>
|
<pre><code>$query = $this->db->query('
SELECT archivalie.id,
archivalie.signature,
type_of_source.description AS type_of_source_description,
media_type.description AS media_type_description,
origin.description AS origin_description
FROM archivalie,
type_of_source,
media_type,
origin
WHERE archivalie.type_of_source_id = type_of_source.id
AND type_of_source.media_type_id = media_type.id
AND archivalie.origin_id = origin.id
ORDER BY archivalie.id ASC
LIMIT ?
OFFSET ?',array($limit,$offset));
</code></pre>
|
<p>If you used double quotes instead of single quotes it would work, but you'd be open to an injection attack if the variables weren't sanitized properly.</p>
| 22,770
|
<p>How can I do this fast?</p>
<p>Sure I can do this:</p>
<pre><code>static bool ByteArrayCompare(byte[] a1, byte[] a2)
{
if (a1.Length != a2.Length)
return false;
for (int i=0; i<a1.Length; i++)
if (a1[i]!=a2[i])
return false;
return true;
}
</code></pre>
<p>But I'm looking for either a <a href="https://en.wikipedia.org/wiki/Standard_Libraries_%28CLI%29#Base_Class_Library" rel="noreferrer">BCL</a> function or some highly optimized proven way to do this.</p>
<pre><code>java.util.Arrays.equals((sbyte[])(Array)a1, (sbyte[])(Array)a2);
</code></pre>
<p>works nicely, but it doesn't look like that would work for x64.</p>
<p>Note my super-fast answer <a href="https://stackoverflow.com/a/8808245/4489">here</a>.</p>
|
<p>You can use <a href="http://msdn.microsoft.com/en-us/library/bb348567.aspx" rel="noreferrer">Enumerable.SequenceEqual</a> method.</p>
<pre><code>using System;
using System.Linq;
...
var a1 = new int[] { 1, 2, 3};
var a2 = new int[] { 1, 2, 3};
var a3 = new int[] { 1, 2, 4};
var x = a1.SequenceEqual(a2); // true
var y = a1.SequenceEqual(a3); // false
</code></pre>
<p>If you can't use .NET 3.5 for some reason, your method is OK.<br>
Compiler\run-time environment will optimize your loop so you don't need to worry about performance. </p>
|
<p>If you are looking for a very fast byte array equality comparer, I suggest you take a look at this STSdb Labs article: <a href="http://stsdb.com/forum/stsdb-4-x/sts-labs/466-byte-array-equality-comparer.html#post1249" rel="nofollow">Byte array equality comparer.</a> It features some of the fastest implementations for byte[] array equality comparing, which are presented, performance tested and summarized.</p>
<p>You can also focus on these implementations:</p>
<p><a href="http://svn.stsdb.com:221/svn/STSdb/STSdb4/STSdb4/General/Comparers/BigEndianByteArrayComparer.cs" rel="nofollow">BigEndianByteArrayComparer</a> - fast byte[] array comparer from left to right (BigEndian)
<a href="http://svn.stsdb.com:221/svn/STSdb/STSdb4/STSdb4/General/Comparers/BigEndianByteArrayComparer.cs" rel="nofollow">BigEndianByteArrayEqualityComparer</a> - - fast byte[] equality comparer from left to right (BigEndian)
<a href="http://svn.stsdb.com:221/svn/STSdb/STSdb4/STSdb4/General/Comparers/BigEndianByteArrayEqualityComparer.cs" rel="nofollow">LittleEndianByteArrayComparer</a> - fast byte[] array comparer from right to left (LittleEndian)
<a href="http://svn.stsdb.com:221/svn/STSdb/STSdb4/STSdb4/General/Comparers/LittleEndianByteArrayEqualityComparer.cs" rel="nofollow">LittleEndianByteArrayEqualityComparer</a> - fast byte[] equality comparer from right to left (LittleEndian)</p>
| 6,488
|
<p>I have a Panel with a collection of controls in it. How can I get the index of a specific control when iterating through them? I'm using <code>foreach</code> to iterate, but there's no Index property. Should I use <code>for x = 0...</code> and return <code>x</code> when my match is made, or what?</p>
|
<p>You could use:</p>
<pre><code>panel.Controls.IndexOf(control);
</code></pre>
<p>Or you could iterate over them with a for loop instead of a foreach loop. Or you could just create an index that you increment inside of the foreach loop.</p>
|
<p>You can just use the IndexOf method. Something like panel1.Controls.IndexOf(textBox1);</p>
| 49,097
|
<p>I have a bunch of JSP files and backend in Tomcat. I have 3 different versions of JSP with same logic inside but with different layouts. So if I change some logic I have three JSP file to fix.</p>
<p>What is the proper soution for such a scenario? I thought of some XML and XSLT stack: backend gives only data in XML and than for each layout I have XSLT that does some magic. </p>
<p>Just imagine that you need to provide stackoverflow in various languages in JSP. Logic the same but layout different.</p>
<p>Could you point me into some direction?</p>
|
<p>Learn about MVC (Model View Controller) and the idea that JSP should be the View part of it and should not contain any logic whatsoever. Logic belongs in a Model class.</p>
|
<p>Take a look at Tiles.</p>
| 16,092
|
<p>I'm learning ASP.NET MVC Framework, From some articles like <a href="http://weblogs.asp.net/stephenwalther/archive/2008/03/17/asp-net-mvc-in-depth-the-life-of-an-asp-net-mvc-request.aspx" rel="nofollow noreferrer">this</a>, it seems that MvcHandler has only Execute() implemented, there is no asynchronous API implemented. Actually, I don't think Controller has asynchronous API either.</p>
<p>So, ASP.NET MVC doesn't support asynchronous programming? this could be a big hurdle to scalability if the web page needs I/O operation.</p>
|
<p>At the moment, async support is not built into MVC. It's on the feature list, but no guarantees as to exactly when it might be released (and in what form).</p>
|
<p>As Brad mentioned, Microsoft is working on a solution as part of MVC futures. There is also an implementation at: <a href="http://code.msdn.microsoft.com/AsyncMvc/Wiki/View.aspx?id=11350" rel="nofollow noreferrer">http://code.msdn.microsoft.com/AsyncMvc/Wiki/View.aspx?id=11350</a></p>
| 34,733
|
<p>I want to read a string value from the registry and concatenate it with another certain string. I'm calling RegQueryValueEx() , like this: </p>
<pre><code>Dim lResult As Long
Dim sLength As Long
Dim sString As String
sString = Space$(256)
sLength = 256
lResult = RegQueryValueEx(hKey, "MyKey", 0, REG_SZ, ByVal sString, sLength)
MsgBox sString & "blah-blah-blah"
</code></pre>
<p>RegQueryValueEx() works fine, I'm getting the needed string in sString and even can display it with MsgBox. But when I try to concat it with "some_string" I get only sString showed. Plz, help me.</p>
<p>Thanks</p>
|
<p>There is probably a null-character in the string, because VB strings store the length of the string in memory just before the contents of the string. In your case that length is 256. When you load the content using RegQueryValueEx, it null-terminates the string (C-style), but does not change its indicated length, so in the VB world it's still 256 characters long. Then when you append the second string, it gets appended after the first 256 characters, but MsgBox only shows the contents up to the null-character.</p>
<p>Because RegQueryValueEx puts the length of the actual data in sLength, you can add this line before the MsgBox</p>
<pre><code>sString = Left$(sString, sLength)
</code></pre>
|
<p>Perhaps the string contains a 0-character so that it ends prematurely?</p>
| 43,870
|
<p>I have an SSIS package that exports data to a couple of Excel files for transfer to a third party. To get this to run as a scheduled job on a 64-bit server I understand that I need to set the step as a CmdExec type and call the 32-bit version of DTExec. But I don't seem to be able to get the command right to pass in the connection string for the Excel files.</p>
<p>So far I have this: </p>
<pre><code>DTExec.exe /SQL \PackageName /SERVER OUR2005SQLSERVER /CONNECTION
LETTER_Excel_File;\""Provider=Microsoft.Jet.OLEDB.4.0";"Data
Source=""C:\Temp\BaseFiles\LETTER.xls";"Extended Properties=
""Excel 8.0;HDR=Yes"" /MAXCONCURRENT " -1 " /CHECKPOINTING OFF /REPORTING E
</code></pre>
<p>This gives me the error: <strong><code>Option "Properties=Excel 8.0;HDR=Yes" is not valid.</code></strong></p>
<p>I've tried a few variations with the Quotation marks but have not been able to get it right yet.</p>
<p>Does anyone know how to fix this?</p>
<p><strong><code>UPDATE:</code></strong></p>
<p>Thanks for your help but I've decided to go with CSV files for now, as they seem to just work on the 64-bit version.</p>
|
<p>This step-by-step example is for others who might stumble upon this question. This example uses <em>SSIS 2005</em> and uses <em>SQL Server 2005 64-bit edition server</em> to run the job.</p>
<p>The answer here concentrates only on fixing the error message mentioned in the question. The example will demonstrate the steps to recreate the issue and also the cause of the issue followed by how to fix it.</p>
<p><strong><code>NOTE:</code></strong> I would recommend using the option of storing the package configuration values in database or using indirect XML configuration with the help of Environment Variables. Also, the steps to create Excel file would be done using a template which would then archived by moving to a different folder. These steps are not discussed in this post. As mentioned earlier, the purpose of this post is to address the error.</p>
<p>Let’s proceed with the example. I have also blogged about this answer, which can be found in <a href="http://learnbycoding.com/2011/07/accessing-excel-data-source-from-an-ssis-package-that-is-deployed-on-a-64-bit-server/" rel="nofollow noreferrer">this link</a>. It is the same answer.</p>
<p>Create an SSIS package (<a href="http://learnbycoding.com/2011/07/creating-a-simple-ssis-package-using-bids/" rel="nofollow noreferrer">Steps to create an SSIS package</a>). This example uses BIDS 2005. I have named the package in the format YYYYMMDD_hhmm in the beginning followed by SO stands for Stack Overflow, followed by the SO question id, and finally a description. I am not saying that you should name your package like this. This is for me to easily refer this back later. Note that I also have a Data Sources named Adventure Works. I will be using Adventure Works data source, which points to AdventureWorks database downloaded from <a href="http://msftdbprodsamples.codeplex.com/" rel="nofollow noreferrer">this link</a>. The example uses SQL Server 2008 R2 database. Refer screenshot <strong>#1</strong>.</p>
<p>In the AdventureWorks database, create a stored procedure named <em>dbo.GetCurrency</em> using the below given script.</p>
<pre><code>CREATE PROCEDURE [dbo].[GetCurrency]
AS
BEGIN
SET NOCOUNT ON;
SELECT
TOP 10 CurrencyCode
, Name
, ModifiedDate
FROM Sales.Currency
ORDER BY CurrencyCode
END
GO
</code></pre>
<p>On the package’s Connection Manager section, right-click and select <em>New Connection From Data Source</em>. On the <em>Select Data Source</em> dialog, select <em>Adventure Works</em> and click OK. You should now see the Adventure Works data source under the <em>Connection Managers</em> section.</p>
<p>On the package’s Connection Managers section, right-click again but this time select <em>New Connection…</em>. This is to create the Excel connection. On the Add SSIS Connection Manager, select <em>EXCEL</em>. On the Excel Connection Manager, enter the path <em>C:\Temp\Template.xls</em>. When we deploy it to the server, we will change this path. I have selected Excel version <em>Microsoft Excel 97-2005</em> and chose to leave the checkbox <em>First row has column names</em> checked so that the create the Excel file is created column headers. Click <em>OK</em>. Rename the Excel connection to <em>Excel</em>, just to keep it simple. Refer screenshots <strong>#2</strong> - <strong>#7</strong>.</p>
<p>On the package, create the following variable. Refer screenshot <strong>#8</strong>.</p>
<ul>
<li><em>SQLGetData</em>: This variable is of type String. This will contain the Stored Procedure execution statement. This example uses the value <em>EXEC dbo.GetCurrency</em></li>
</ul>
<p>Screenshot <strong>#9</strong> shows the output of the stored procedure execution statement <em>EXEC dbo.GetCurrency</em></p>
<p>On the package’s Control Flow tab, place a <code>Data Flow task</code> and name it as Export to Excel. Refer screenshot <strong>#10</strong>.</p>
<p>Double-click on the Data Flow Task to switch to the Data Flow tab.</p>
<p>On the Data Flow tab, place an <code>OLE DB Source</code> to connect to the SQL Server data to fetch the data from the stored procedure and name it as SQL. Double-click on the OLE DB Source to bring up the OLE DB Source Editor. On the Connection Manager section, select <em>Adventure Works</em> from the OLE DB connection manager, select SQL command from variable from Data access mode and select the variable <em>User::SQLGetData</em> from the Variable name drop down. On the Columns section, make sure the column names are mapped correctly. Click OK to close the OLE DB Source Editor. Refer screenshots <strong>#11</strong> and <strong>#12</strong>.</p>
<p>On the Data Flow tab, place an <code>Excel Destination</code> to insert the data into the Excel file and name it as Excel. Double-click on the Excel Destination to open the Excel Destination Editor. On the Connection Manager section, select Excel from the OLE DB connection manager and select Table or view from Data access mode. At this point, we don’t have an Excel because while creating the Excel connection manager, we simply specified the path but never created the file. Hence, there won’t be any values in the drop down Name of the Excel sheet. So, click the <em>New…</em> button (the second New one) to create a new Excel sheet. On the Create Table window, BIDS automatically provide a create sheet based on the incoming data source. You can change the values according to your preferences. I will simply click OK by retaining the default value. The name of the sheet will be populated in the drop down Name of the Excel sheet. The name of the sheet is taken from the task name, here in this case the Excel Destination, which we have named it as Excel. On the Mappings section, make sure the column names are mapped correctly. Click OK to close the Excel Destination Editor. Refer screenshots <strong>#13</strong> - <strong>#16</strong>.</p>
<p>Once the data flow task is configured, it should look like as shown in screenshot <strong>#17</strong>.</p>
<p>Execute the package by pressing F5. Screenshots <strong>#18</strong> - <strong>#21</strong> show the successful execution of the package in both Control Flow and Data Flow Task. Also, the file is generated in the path <em>C:\Temp\Template.xls</em> provided in the Excel connection and the data shown in the stored procedure execution output matches with the data written to the file.</p>
<p>The package developed on my local machine in the folder path <em>C:\Learn\Learn.VS2005\Learn.SSIS</em>. Now, we need to deploy the files on to the Server that hosts the 64-bit version of the SQL Server to schedule a job. So, the folder on the server would be <em>D:\SSIS\Practice</em>. Copy the package file (<strong>.dtsx</strong>) from the local machine and paste it in the server folder. Also, in order for the package to run correctly, we need to have the Excel spreadsheet present on the server. Otherwise, the validation will fail. Usually, I create a Template folder that will contain the empty Excel spreadsheet file that matches the output. Later, during run time I will change the Excel output path to a different location using package configuration. For this example, I am going to keep it simple. So, let’s copy the Excel file generated in the local machine in the path <em>C:\Temp\Template.xls</em> to the server location <em>D:\SSIS\Practice</em>. I want the SQL job to generate the file in the name Currencies.xls. So, rename the file Template.xls to <em>Currencies.xls</em>. Refer screenshot <strong>#22</strong>.</p>
<p>To show that I am indeed going to run the job on the server in a 64-bit edition of SQL Server, I executed the command SELECT @@version on the SQL Server and screenshot <strong>#23</strong> shows the results.</p>
<p>We will use <em>Execute Package Utility</em> (dtexec.exe) to generate the command line parameters. Log into the server which will run the SSIS package in an SQL job. Double-click on the package file, this will bring the Execute Package Utility. On the General section, select File system from Package source. Click on the Ellipsis and browse to the package path. On the Connection Managers section, select Excel and change the path inside the Excel file from C:\Temp\Template.xls to D:\SSIS\Practice\Currencies.xls. The changes made in the Utility will generate a command line accordingly on the Command Line section. On the Command Line section, copy the Command line that contains all the necessary parameters. We are not going to execute the package from here. Click <em>Close</em>. Refer screenshots <strong>#24</strong> - <strong>#26</strong>.</p>
<p>Next, we need to set up a job to run the SSIS package. We cannot choose SQL Server Integration Services Package type because that will run under 64-bit and won’t find the Excel connection provider. So, we have to run it as <code>Operating System (CmdExec)</code> job type. Go to SQL Server Management Studio and connect to the Database Engine. Expand SQL Server Agent and right-click on Jobs node. Select New Job…. On the General section of the Job Properties window, provide the job name as 01_SSIS_Export_To_Excel, Owner will be the user creating the job. I have a Category named SSIS, so I will select that but the default category is <em>[Uncategorized (Local)]</em> and provide a brief description. On the Steps section, click <em>New…</em> button. This will bring Job Step properties. On the General section of the Job Step properties, provide Step name as Export to Excel, Select type <code>Operating system (CmdExec)</code>, leave the default Run as account as SQL Server Agent Service Account and provide the following Command. Click OK. On the New Job window, Click OK. Refer screenshots <strong>#27</strong> - <strong>#31</strong>.</p>
<pre><code>C:\Program Files (x86)\Microsoft SQL Server\90\DTS\Binn\DTExec.exe /FILE
"D:\SSIS\Practice\20110723_1015_SO_21448_Excel_64_bit_Error.dtsx"
/CONNECTION Excel;"\"Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=D:\SSIS\Practice\Currencies.xls;Extended Properties=""EXCEL 8.0;HDR=YES"";\""
/MAXCONCURRENT " -1 " /CHECKPOINTING OFF /REPORTING EWCDI
</code></pre>
<p>The new job should appear under SQL Server Agent –> Jobs node. Right-click on the newly created job 01_SSIS_Export_To_Excel and select <em>Start Job at Step…</em>, this will commence the job execution. The job will fail as expected because that is the context of this issue. Click Close to close the Start Jobs dialog. Refer screenshots <strong>#32</strong> and <strong>#33</strong>.</p>
<p>Let’s take a look at what happened. Go to SQL Server Agent and Jobs node. Right-click on the job 01_SSIS_Export_To_Excel and select View History. This will bring the Log File Viewer window. You can notice that the job failed. Expand the node near the red cross and click on the line that Step ID value of 1. At the bottom section, you can see the error message <strong><code>Option “8.0;HDR=YES’;” is not valid.</code></strong> Click Close to close the Log File Viewer window. Refer screenshots <strong>#34</strong> and <strong>#35</strong>.</p>
<p>Now, right-click on the job and select Properties to open the Job Properties. You can also double-click on the job to bring the Job Properties window. Click on the Steps on the left section. and click Edit. Replace the command with the following command and click OK. Click OK on the Job Properties to close the window. Right-click on the job 01_SSIS_Export_To_Excel and select Start Job at Step…, this will commence the job execution. The job will fail execute successfully. Click Close to close the Start Jobs dialog. Let’s take a look at the history. Right-click on the job 01_SSIS_Export_To_Excel and select View History. This will bring the Log File Viewer window. You can notice that the job succeeded during the second run. Expand the node near the green tick cross and click on the line that Step ID value of 1. At the bottom section, you can see the message Option The step succeeded. Click Close to close the Log File Viewer window. The file D:\SSIS\Practice\Currencies.xls will be successfully populated with the data. If you execute the job successfully multiple times, the data will get appended to the file and you will find more data. As I mentioned earlier, this is not the right-way to generate the files. This example was created to demonstrate a fix for this issue. Refer screenshots <strong>#36</strong> - <strong>#38</strong>.</p>
<p>Screenshot <strong>#39</strong> shows the differences between the working and the non-working command line arguments. The one on the right is the working command line and the left one is incorrect. It required another double quotes with backslash escape sequence to fix the error. There could be other ways to fix this well but this option seems to work.</p>
<p>Thus, the example demonstrated a way to fix the command line argument issue while accessing Excel data source from an SSIS package that is deployed on a 64-bit server.</p>
<p>Hope that helps someone.</p>
<p><strong>Screenshots:</strong></p>
<p><strong>#1:</strong> Solution_Explorer</p>
<p><img src="https://i.stack.imgur.com/8LXYw.png" alt="Solution_Explorer"></p>
<p><strong>#2:</strong> New_Connection_Data_Source</p>
<p><img src="https://i.stack.imgur.com/kLUaJ.png" alt="New_Connection_Data_Source"></p>
<p><strong>#3:</strong> Select_Data_Source</p>
<p><img src="https://i.stack.imgur.com/dctco.png" alt="Select_Data_Source"></p>
<p><strong>#4:</strong> New_Connection</p>
<p><img src="https://i.stack.imgur.com/ENgBq.png" alt="New_Connection"></p>
<p><strong>#5:</strong> Add_SSIS_Connection_Manager</p>
<p><img src="https://i.stack.imgur.com/e477v.png" alt="Add_SSIS_Connection_Manager"></p>
<p><strong>#6:</strong> Excel_Connection_Manager</p>
<p><img src="https://i.stack.imgur.com/rLuSb.png" alt="Excel_Connection_Manager"></p>
<p><strong>#7:</strong> Connection_Managers</p>
<p><img src="https://i.stack.imgur.com/Tw4K1.png" alt="Connection_Managers"></p>
<p><strong>#8:</strong> Variables</p>
<p><img src="https://i.stack.imgur.com/wOuU5.png" alt="Variables"></p>
<p><strong>#9:</strong> Stored_Procedure_Output</p>
<p><img src="https://i.stack.imgur.com/mynyS.png" alt="Stored_Procedure_Output"></p>
<p><strong>#10:</strong> Control_Flow</p>
<p><img src="https://i.stack.imgur.com/DTucs.png" alt="enter image description here"></p>
<p><strong>#11:</strong> OLE_DB_Source_Connections_Manager</p>
<p><img src="https://i.stack.imgur.com/tLHQP.png" alt="OLE_DB_Source_Connections_Manager"></p>
<p><strong>#12:</strong> OLE_DB_Source_Columns</p>
<p><img src="https://i.stack.imgur.com/uxZZ4.png" alt="OLE_DB_Source_Columns"></p>
<p><strong>#13:</strong> Excel_Destination_Editor_New</p>
<p><img src="https://i.stack.imgur.com/nyUgx.png" alt="Excel_Destination_Editor_New"></p>
<p><strong>#14:</strong> Excel_Destination_Create_Table</p>
<p><img src="https://i.stack.imgur.com/UN5xT.png" alt="Excel_Destination_Create_Table"></p>
<p><strong>#15:</strong> Excel_Destination_Edito</p>
<p><img src="https://i.stack.imgur.com/RdH54.png" alt="Excel_Destination_Edito"></p>
<p><strong>#16:</strong> Excel_Destination_Mappings</p>
<p><img src="https://i.stack.imgur.com/iPO8y.png" alt="Excel_Destination_Mappings"></p>
<p><strong>#17:</strong> Data_Flow</p>
<p><img src="https://i.stack.imgur.com/wLxa4.png" alt="Data_Flow"></p>
<p><strong>#18:</strong> Successful_Package_Execution_Control</p>
<p><img src="https://i.stack.imgur.com/TZ0ou.png" alt="Successful_Package_Execution_Control"></p>
<p><strong>#19:</strong> Successful_Package_Execution_Data_Flow</p>
<p><img src="https://i.stack.imgur.com/FI6VA.png" alt="Successful_Package_Execution_Data_Flow"></p>
<p><strong>#20:</strong> C_Temp_File_Created</p>
<p><img src="https://i.stack.imgur.com/VMjnn.png" alt="C_Temp_File_Created"></p>
<p><strong>#21:</strong> Data_Populated</p>
<p><img src="https://i.stack.imgur.com/IYhUg.png" alt="Data_Populated"></p>
<p><strong>#22:</strong> File_On_Server</p>
<p><img src="https://i.stack.imgur.com/k7hKu.png" alt="File_On_Server"></p>
<p><strong>#23:</strong> SQL_Server_Version</p>
<p><img src="https://i.stack.imgur.com/n2gpY.png" alt="SQL_Server_Version"></p>
<p><strong>#24:</strong> Execute_Package_Utility_General</p>
<p><img src="https://i.stack.imgur.com/ZNCW0.png" alt="Execute_Package_Utility_General"></p>
<p><strong>#25:</strong> Execute_Package_Utility_Connection_Managers</p>
<p><img src="https://i.stack.imgur.com/o39ar.png" alt="Execute_Package_Utility_Connection_Managers"></p>
<p><strong>#26:</strong> Execute_Package_Utility_Command_Line</p>
<p><img src="https://i.stack.imgur.com/mq9Ts.png" alt="Execute_Package_Utility_Command_Line"></p>
<p><strong>#27:</strong> Job_New_Job</p>
<p><img src="https://i.stack.imgur.com/Dx17J.png" alt="Job_New_Job"></p>
<p><strong>#28:</strong> New_Job_General</p>
<p><img src="https://i.stack.imgur.com/Wwk7H.png" alt="New_Job_General"></p>
<p><strong>#29:</strong> New_Job_Step</p>
<p><img src="https://i.stack.imgur.com/5VDWF.png" alt="New_Job_Step"></p>
<p><strong>#30:</strong> New_Job_Step_General </p>
<p><img src="https://i.stack.imgur.com/MTXMT.png" alt="New_Job_Step_General"></p>
<p><strong>#31:</strong> New_Job_Steps_Added</p>
<p><img src="https://i.stack.imgur.com/p9IeS.png" alt="New_Job_Steps_Added"></p>
<p><strong>#32:</strong> Job_Start_Job_at_Step</p>
<p><img src="https://i.stack.imgur.com/Qpef2.png" alt="Job_Start_Job_at_Step"></p>
<p><strong>#33:</strong> SQL_Job_Execution_Failure</p>
<p><img src="https://i.stack.imgur.com/qSPdR.png" alt="SQL_Job_Execution_Failure"></p>
<p><strong>#34:</strong> View_History</p>
<p><img src="https://i.stack.imgur.com/xZqWk.png" alt="View_History"></p>
<p><strong>#35:</strong> SQL_Job_Error_Message</p>
<p><img src="https://i.stack.imgur.com/oYovo.png" alt="SQL_Job_Error_Message"></p>
<p><strong>#36:</strong> SQL_Job_Execution_Success</p>
<p><img src="https://i.stack.imgur.com/fYeKc.png" alt="SQL_Job_Execution_Success"></p>
<p><strong>#37:</strong> SQL_Job_Success_Message</p>
<p><img src="https://i.stack.imgur.com/3yEQe.png" alt="SQL_Job_Success_Message"></p>
<p><strong>#38:</strong> Excel_File_Generated</p>
<p><img src="https://i.stack.imgur.com/ovlVm.png" alt="Excel_File_Generated"></p>
<p><strong>#39:</strong> Command_Comparison</p>
<p><img src="https://i.stack.imgur.com/2h7mX.png" alt="39_Command_Comparison"></p>
|
<p>I kinda did what Dr Zim did but I copied the DTExec file <code>C:\Program Files (x86)\Microsoft SQL Server\90\DTS\Binn\DTExec.exe</code> to <code>C:\Program Files\Microsoft SQL Server\90\DTS\Binn\</code> folder but named the 32 bit one to DTExec32.exe</p>
<p>then I was able to run my SSIS script through a stored proc:</p>
<pre><code>set @params = '/set \package.variables[ImportFilename].Value;"\"' + @FileName + '\"" '
set @cmd = 'dtexec32 /SQ "' + @packagename + ' ' + @params + '"'
--DECLARE @returncode int
exec master..xp_cmdshell @cmd
--exec @returncode = master..xp_cmdshell @cmd
--select @returncode
</code></pre>
| 4,160
|
<p>I know that IList is the interface and List is the concrete type but I still don't know when to use each one. What I'm doing now is if I don't need the Sort or FindAll methods I use the interface. Am I right? Is there a better way to decide when to use the interface or the concrete type?</p>
|
<p>There are two rules I follow:</p>
<ul>
<li>Accept the most basic type that will work</li>
<li>Return the richest type your user will need</li>
</ul>
<p>So when writing a function or method that takes a collection, write it not to take a List, but an IList<T>, an ICollection<T>, or IEnumerable<T>. The generic interfaces will still work even for heterogenous lists because System.Object can be a T too. Doing this will save you headache if you decide to use a Stack or some other data structure further down the road. If all you need to do in the function is foreach through it, IEnumerable<T> is really all you should be asking for.</p>
<p>On the other hand, when returning an object out of a function, you want to give the user the richest possible set of operations without them having to cast around. So in that case, if it's a List<T> internally, return a copy as a List<T>.</p>
|
<p>In situations I usually come across, I rarely use IList directly.</p>
<p>Usually I just use it as an argument to a method </p>
<pre><code>void ProcessArrayData(IList almostAnyTypeOfArray)
{
// Do some stuff with the IList array
}
</code></pre>
<p>This will allow me to do generic processing on almost any array in the .NET framework, unless it uses IEnumerable and not IList, which happens sometimes.</p>
<p>It really comes down to the kind of functionality you need. I'd suggest using the List class in most cases. IList is best for when you need to make a custom array that could have some very specific rules that you'd like to encapsulate within a collection so you don't repeat yourself, but still want .NET to recognize it as a list.</p>
| 3,786
|
<p>Lets say that you have websites www.xyz.com and www.abc.com.</p>
<p>Lets say that a user goes to www.abc.com and they get authenticated through the normal ASP .NET membership provider. </p>
<p>Then, from that site, they get sent to (redirection, linked, whatever works) site www.xyz.com, and the intent of site www.abc.com was to pass that user to the other site as the status of isAuthenticated, so that the site www.xyz.com does not ask for the credentials of said user again.</p>
<p>What would be needed for this to work? I have some constraints on this though, the user databases are completely separate, it is not internal to an organization, in all regards, it is like passing from stackoverflow.com to google as authenticated, it is that separate in nature. A link to a relevant article will suffice.</p>
|
<p>Try using FormAuthentication by setting the web.config authentication section like so:</p>
<pre><code><authentication mode="Forms">
<forms name=".ASPXAUTH" requireSSL="true"
protection="All"
enableCrossAppRedirects="true" />
</authentication>
</code></pre>
<p>Generate a machine key. Example: <a href="https://blogs.msdn.microsoft.com/amb/2012/07/31/easiest-way-to-generate-machinekey/" rel="nofollow noreferrer">Easiest way to generate MachineKey – Tips and tricks: ASP.NET, IIS ...</a></p>
<p>When posting to the other application the authentication ticket is passed as a hidden field. While reading the post from the first app, the second app will read the encrypted ticket and authenticate the user. Here's an example of the page that passes that posts the field:</p>
<p>.aspx:</p>
<pre><code><form id="form1" runat="server">
<div>
<p><asp:Button ID="btnTransfer" runat="server" Text="Go" PostBackUrl="http://otherapp/" /></p>
<input id="hdnStreetCred" runat="server" type="hidden" />
</div>
</form>
</code></pre>
<p>code-behind:</p>
<pre><code>protected void Page_Load(object sender, EventArgs e)
{
FormsIdentity cIdentity = Page.User.Identity as FormsIdentity;
if (cIdentity != null)
{
this.hdnStreetCred.ID = FormsAuthentication.FormsCookieName;
this.hdnStreetCred.Value = FormsAuthentication.Encrypt(((FormsIdentity)User.Identity).Ticket);
}
}
</code></pre>
<p>Also see the cross app form authentication section in Chapter 5 of this <a href="http://www.wrox.com/WileyCDA/WroxTitle/Professional-ASP-NET-2-0-Security-Membership-and-Role-Management.productCd-0764596985.html" rel="nofollow noreferrer">book</a> from Wrox. It recommends answers like the ones above in addition to providing a homebrew SSO solution. </p>
|
<p>Alternatively if you want to roll your own and the sites in question are not on the same servers or don't have access to a shared database (in which case see the above responses) then you could place a <a href="http://en.wikipedia.org/wiki/Web_beacon" rel="nofollow noreferrer">web beacon</a> on each of the sites which would refer back to the other site. </p>
<p>Place a single pixel image (web beacon) on site A which would call site B passing through the users ID (encrypted & time stamped). This would then create a new user session on site B for the user which would be set as logged in. Then when the user visited site B they would already be logged in.</p>
<p>To minimise calls you could only place the web beacon on the home page and or log in confirmation pages. I've used this successfully in the past to pass information between partner sites. </p>
| 9,772
|
<p>All of my methods are failing me in various ways.
different lighting can mess it all up too.</p>
<p>has anyone every trying to return a name given a rgb value? "red" "green" "blue" would be enough to satisfy my needs for today.</p>
<p>i have unsafe byte processing of images from my web cam.</p>
<p><a href="https://i.stack.imgur.com/ptjtc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ptjtc.png" alt="webcam"></a>
</p>
<p><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/5/55/Color_star-en.svg/646px-Color_star-en.svg.png" alt="colors"></p>
|
<p>If you have a list of known colors with names, you can see which of those known colors a given target color is 'closest' to, using a 'closeness' function along the lines of (F# code):</p>
<pre><code>let Diff (c1:Color) (c2:Color) =
let dr = (c1.R - c2.R) |> int
let dg = (c1.G - c2.G) |> int
let db = (c1.B - c2.B) |> int
dr*dr + dg*dg + db*db
</code></pre>
<p>Whichever one of the known colors has the smallest diff to the target color you want to name, use that name.</p>
|
<p>Well, Red/Green/Blue are fairly easy to identify by inspection; what range of values do you need to support?</p>
<p>The problem is that unless you start with a named color, it is very hard to get <em>back</em> to one; <code>IsNamedColor</code> will return false even if you create an obvious color via FromArgb.</p>
<p>If you only need the actual expected standard colors, you could enumerate the known colors via reflection?</p>
<pre><code> Color test = Color.FromArgb(255,0,0);
Color known = (
from prop in typeof(Color)
.GetProperties(BindingFlags.Public | BindingFlags.Static)
where prop.PropertyType == typeof(Color)
let color = (Color)prop.GetValue(null, null)
where color.A == test.A && color.R == test.R
&& color.G == test.G && color.B == test.B
select color)
.FirstOrDefault();
Console.WriteLine(known.Name);
</code></pre>
<p>You might also be able to use this approach as a source of known colors for a more sophisticated algorithm.</p>
| 47,769
|
<p>I am having a similar issue to <a href="https://stackoverflow.com/questions/28387/sql-server-2k5-memory-consumption">this person</a>. The primary difference being the application is NOT meant for a developer environment, and therefore I need to know how to optimize the space used by Sql Server (possibly per machine based on specs).</p>
<p>I was intrigued by <a href="https://stackoverflow.com/users/10795/ricardo-c">Ricardo C's</a> answer, particularly the following:</p>
<blockquote>
<p>Extracted fromt he SQL Server
documentation:</p>
<p>Maximum server memory (in MB)</p>
<p>Specifies the maximum amount of memory SQL Server can allocate when it
starts and while it runs. This
configuration option can be set to a
specific value if you know there are
multiple applications running at the
same time as SQL Server and you want
to guarantee that these applications
have sufficient memory to run. If
these other applications, such as Web
or e-mail servers, request memory only
as needed, then do not set the option,
because SQL Server will release memory
to them as needed. <strong>However,
applications often use whatever memory
is available when they start and do
not request more if needed</strong>. If an
application that behaves in this
manner runs on the same computer at
the same time as SQL Server, set the
option to a value that guarantees that
the memory required by the application
is not allocated by SQL Server.</p>
</blockquote>
<p>My question is: how does an application request memory from the OS when it needs it? Is this something built into compilation or something managed by the developer? The two primary apps running on this machine are Sql Server and the (fairly heavyweight) C# application I'm developing, and I'm almost certain we didn't specifically do anything in the realm of asking the OS for memory. Is there a correct/necessary way to do this?</p>
|
<p>Some applications allocate a lot of memory at startup, and then run their own memory management system on it.
This can be good for applications that have particular allocation patterns, and that feel they can do a better job than the more generic memory manager provided by the runtime system.</p>
<p>Many games do this, since they often have a very good idea of how their memory usage pattern is going to look, and often are heavily optimized. The default/system allocator is general-purpose and not always fast enough. <a href="http://doom.wikia.com/wiki/Zone_memory" rel="nofollow noreferrer">Doom did this</a>, and is fairly well-known for it and of course its code is available and widely discussed.</p>
<p>In "managed" languages like C# I think this is very rare, and nothing you need to worry about.</p>
|
<p>Each time you create a new object, you are asking the .NET garbage collector to give you memory. If the GC has insufficient memory on the managed heap then it will ask the OS for more.
As the other question says, although SQL server is meant to give the memory back it doesn't seem to do it very well. There is not going to be any hard and fast rules here, you will have to guess at some setting for SQL server and then test the performance. If you post some information about the server, database size, how much memory your application seems to require then I am sure people wil be happy to give you some suggestions for a starting configuration.
One warning though, I think changing its memory limits requires a service re-start.</p>
| 37,694
|
<p>I am working on a rails project. Using the tag observe_field, I am taking text typed into a text area, processing it in a control, and displaying the result in a div (very similar to the preview in stack overflow). Everything works fine until I type certain special chars.</p>
<ol>
<li>? => causes the variable not to be found in the params object</li>
<li>(pound) => causes an invalid authenticity error</li>
<li>% => stops the div from being updated</li>
<li>& => every thing after the & is no longer passed into the variable on the server. </li>
</ol>
<p>Is there a way to solve this?</p>
<p>--- code sample ---</p>
<p>this is the view. ( 'postbody' is a text area)</p>
<pre><code><%= observe_field 'postbody',
:update => 'preview',
:url => {:controller => 'blog', :action => 'textile_to_html'},
:frequency => 0.5,
:with => 'postbody' -%>
</code></pre>
<p>this is the controller that is called</p>
<pre><code>def textile_to_html
text = params['postbody']
if text == nil then
@textile_to_html = '<br/>never set'
else
r = RedCloth.new text
@textile_to_html = r.to_html
end
render :layout => false
end
</code></pre>
<p>and this is the javascript that is created:</p>
<pre><code>new Form.Element.Observer('postbody', 0.5, function(element, value) {new Ajax.Updater('preview', '/blog/textile_to_html', {asynchronous:true, evalScripts:true, parameters:'postbody=' + value + '&authenticity_token=' + encodeURIComponent('22f7ee12eac9efd418caa0fe76ae9e862025ef97')})})
</code></pre>
|
<p>This is an escaping issue (as stated by others).</p>
<p>You'll want to change your observe_field :with statement to something like:</p>
<pre><code> :with => "'postbody=' + encodeURIComponent(value)"
</code></pre>
<p>Then in your controller:</p>
<pre><code>def textile_to_html
text = URI.unescape(params['postbody'])
...
</code></pre>
|
<p>Can you provide a code sample?</p>
<p>More likely than not you'll just need to escape your HTML entities using <a href="http://www.w3schools.com/jsref/jsref_encodeURI.asp" rel="nofollow noreferrer">encodeuri</a> or something like that.</p>
| 5,124
|
<p>I am building a <a href="https://andypi.co.uk/2017/09/17/dolly-build-notes-prusa-i3-mk2-clone-3d-printer/" rel="nofollow noreferrer">dolly</a> and I am confused as to which proximity sensor to use. </p>
<p>Should I go for M8 or M12 and 5 V or 6-36 V? </p>
<p>What should be the best detecting distance? Should it be 2/4/8 mm. Which one should I select?</p>
|
<p>Tomas Sanladerer has produced a nice video on this topic: <a href="https://www.youtube.com/watch?v=il9bNWn66BY" rel="nofollow noreferrer">https://www.youtube.com/watch?v=il9bNWn66BY</a></p>
<p>@ 7:31 you see an overview of the precision of various sensors, including the ones you mention. It appears that the M12-4 and M18-8 sensors are more accurate than the M8-8.</p>
|
<p>As always cost will be a factor. I found the M4 sensors to be be just not good enough, they have to be too close, and eventually it's going to catch on your print and damage sensor mounting and/or the hot-end assembly.</p>
<p>The 8mm range sensors seem like a good distance, but you'll need to decide between a wider, heavier but cheaper model or the think, lighter more expensive model.</p>
<p>If your goal is to optimise for speed, go the lighter version.</p>
<p>In terms of sensing accuracy, if your layer height is typically 0.2mm then I don't think there's much point paying for more accuracy.</p>
| 851
|
<p>I know there's no standard C function to do this. I was wondering what are the techniques to to this on Windows and *nix? (Windows XP is my most important OS to do this on right now.)</p>
|
<p>glibc provides <code>backtrace()</code> function.</p>
<p><a href="http://www.gnu.org/software/libc/manual/html_node/Backtraces.html" rel="nofollow noreferrer">http://www.gnu.org/software/libc/manual/html_node/Backtraces.html</a></p>
|
<p>You can do it by walking the stack backwards. In reality, though, it's frequently easier to add an identifier onto a call stack at the beginning of each function and pop it at the end, then just walk that printing the contents. It's a bit of a PITA, but it works well and will save you time in the end.</p>
| 13,116
|
<p>Greetings!</p>
<p>I'm scratching my head, wondering why when I do the following:</p>
<pre><code>Response.Redirect(@"http://www.example.com/file.exe?id=12345");
</code></pre>
<p>Both IE6 and IE7 will download the file as "file" (with no extension), but Firefox, Opera, Google Chrome and Safari have no problems at all downloading the file as "file.exe".</p>
<p>Any idea what IE6/7's problem is and how can I fix this?</p>
|
<p>Have You tried to set correct content-type in Your response headers? For example:</p>
<pre><code>Content-Type: application/octet-stream
Content-Disposition: attachment; filename="file.exe"
</code></pre>
|
<p>You will probably need to get the filesize remotely and add it to Content-Length on the header section.</p>
| 37,928
|
<p>Let's say I have the following simple enum:</p>
<pre><code>enum Response
{
Yes = 1,
No = 2,
Maybe = 3
}
</code></pre>
<p>How can I bind this enum to a DropDownList control so that the descriptions are displayed in the list as well as retrieve the associated numeric value (1,2,3) once an option has been selected?</p>
|
<p>I probably wouldn't <strong>bind</strong> the data as it's an enum, and it won't change after compile time (unless I'm having one of those <em>stoopid</em> moments). </p>
<p>Better just to iterate through the enum: </p>
<pre><code>Dim itemValues As Array = System.Enum.GetValues(GetType(Response))
Dim itemNames As Array = System.Enum.GetNames(GetType(Response))
For i As Integer = 0 To itemNames.Length - 1
Dim item As New ListItem(itemNames(i), itemValues(i))
dropdownlist.Items.Add(item)
Next
</code></pre>
<p>Or the same in C# </p>
<pre><code>Array itemValues = System.Enum.GetValues(typeof(Response));
Array itemNames = System.Enum.GetNames(typeof(Response));
for (int i = 0; i <= itemNames.Length - 1 ; i++) {
ListItem item = new ListItem(itemNames[i], itemValues[i]);
dropdownlist.Items.Add(item);
}
</code></pre>
|
<p>This is my solution for Order an Enum and DataBind(Text and Value)to Dropdown using LINQ</p>
<pre><code>var mylist = Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>().ToList<MyEnum>().OrderBy(l => l.ToString());
foreach (MyEnum item in mylist)
ddlDivisao.Items.Add(new ListItem(item.ToString(), ((int)item).ToString()));
</code></pre>
| 8,728
|
<p>Let's assume we've got the following Java code:</p>
<pre><code>public class Maintainer {
private Map<Enum, List<Listener>> map;
public Maintainer() {
this.map = new java.util.ConcurrentHashMap<Enum, List<Listener>>();
}
public void addListener( Listener listener, Enum eventType ) {
List<Listener> listeners;
if( ( listeners = map.get( eventType ) ) == null ) {
listeners = new java.util.concurrent.CopyOnWriteArrayList<Listener>();
map.put( eventType, listeners );
}
listeners.add( listener );
}
}
</code></pre>
<p>This code snippet is nothing but a bit improved listener pattern where each listener is telling what type of event it is interested in, and the provided method maintains a concurrent map of these relationships.</p>
<p>Initially, I wanted this method to be called via my own annotation framework, but bumped into a brick wall of various annotation limitations (e.g. you can't have <em>java.lang.Enum</em> as annotation param, also there's a set of various classloader issues) therefore decided to use Spring.</p>
<p>Could anyone tell me how do I Spring_ify_ this? What I want to achive is:<br>
1. Define <em>Maintainer</em> class as a Spring bean.<br>
2. Make it so that all sorts of listeners would be able to register themselves to <em>Maintainer</em> via XML by using <em>addListener</em> method. Spring doc nor Google are very generous in examples.</p>
<p>Is there a way to achieve this easily?</p>
|
<p>What would be wrong with doing something like the following:</p>
<p>Defining a 'Maintainer' interface with the addListener(Listener, Enum) method.</p>
<p>Create a DefaultMaintainer class (as above) which implements Maintainer.</p>
<p>Then, in each Listener class, 'inject' the Maintainer interface (constructor injection might be a good choice). The listener can then register itself with the Maintainer.</p>
<p>other than that, I'm not 100% clear on exactly what your difficulty is with Spring at the moment! :)</p>
|
<blockquote>
<p>You said "... you can't have java.lang.Enum as"
annotation param ..."</p>
</blockquote>
<p>I think you are wrong on that. I have recently used on a project something like this :</p>
<pre><code>public @interface MyAnnotation {
MyEnum value();
}
</code></pre>
| 9,696
|
<p>I'm using polar plots (POLAR(THETA,RHO)) in MATLAB.</p>
<p>Is there an easy way to fix the range for the radial axis to say, 1.5?</p>
<p>I'm looking for something analogous to the xlim, ylim commands for cartesian axes. Haven't found anything in the docs yet.</p>
|
<p>Here's how I was able to do it. </p>
<p>The MATLAB polar plot (if you look at the Handle Graphics options available) does not have anything like xlim or ylim. However, I realized that the first thing plotted sets the range, so I was able to plot a function with radius range [-.5 .5] on a [-1 1] plot as follows:</p>
<pre><code>theta = linspace(0,2*pi,100);
r = sin(2*theta) .* cos(2*theta);
r_max = 1;
h_fake = polar(theta,r_max*ones(size(theta)));
hold on;
h = polar(theta, r);
set(h_fake, 'Visible', 'Off');
</code></pre>
<p>That doesn't look very good and hopefully there's a better way to do it, but it works.</p>
|
<p>In case anyone else comes across this, here's <em>the</em> solution:</p>
<p>As <strong><em>Scottie T</em></strong> and <strong><em>gnovice</em></strong> pointed out, Matlab basically uses the polar function as an interface for standard plots, but with alot of formatting behind the scenes to make it look polar. Look at the values of the XLim and YLim properties of a polar plot and you'll notice that they are literally the x and y limits of your plot in Cartesian coordinates. So, to set a radius limit, use xlim and ylim, or axis, and be smart about the values you set:</p>
<pre><code>rlim = 10;
axis([-1 1 -1 1]*rlim);
</code></pre>
<p>...that's all there is to it. Happy Matlabbing :)</p>
| 27,981
|
<p>Does anyone know of an already implemented money type for the .NET framework that supports i18n (currencies, formatting, etc)? I have been looking for a well implemented type and can't seem to find one.</p>
|
<p>Check this article <a href="http://www.codeproject.com/KB/recipes/MoneyTypeForCLR.aspx" rel="noreferrer">A Money type for the CLR</a></p>
<blockquote>
<p>A convenient, high-performance money
structure for the CLR which handles
arithmetic operations, currency types,
formatting, and careful distribution
and rounding without loss.</p>
</blockquote>
|
<p>i would use integer/long, and use a very low denomination like cents (or pence) - then there would be no decimal to work with, and all calculations can be rounded to the nearest cent. </p>
<p>or, take a look at Martin Fowler's book "Patterns of Enterprise Application Architecture". In that book, he talked about how to implement a money class. <a href="https://rads.stackoverflow.com/amzn/click/com/0321127420" rel="nofollow noreferrer" rel="nofollow noreferrer">http://www.amazon.com/Enterprise-Application-Architecture-Addison-Wesley-Signature/dp/0321127420</a></p>
| 34,551
|
<p>Can anyone recommend a simple API that will allow me to use read a CSV input file, do some simple transformations, and then write it.</p>
<p>A quick google has found <a href="http://flatpack.sourceforge.net/" rel="noreferrer">http://flatpack.sourceforge.net/</a> which looks promising.</p>
<p>I just wanted to check what others are using before I couple myself to this API.</p>
|
<h1>Apache Commons CSV</h1>
<p>Check out <a href="http://commons.apache.org/proper/commons-csv/" rel="nofollow noreferrer"><em>Apache Common CSV</em></a>.</p>
<p>This library reads and writes <a href="http://commons.apache.org/proper/commons-csv/archives/1.6/apidocs/index.html" rel="nofollow noreferrer">several variations of CSV</a>, including the standard one <a href="https://www.rfc-editor.org/rfc/rfc4180" rel="nofollow noreferrer">RFC 4180</a>. Also reads/writes <a href="https://en.wikipedia.org/wiki/Tab-separated_values" rel="nofollow noreferrer">Tab-delimited</a> files.</p>
<ul>
<li>Excel</li>
<li>InformixUnload</li>
<li>InformixUnloadCsv</li>
<li>MySQL</li>
<li>Oracle</li>
<li>PostgreSQLCsv</li>
<li>PostgreSQLText</li>
<li>RFC4180</li>
<li>TDF</li>
</ul>
|
<p>If you intend to read csv from excel, then there are some interesting corner cases. I can't remember them all, but the apache commons csv was not capable of handling it correctly (with, for example, urls).</p>
<p>Be sure to test excel output with quotes and commas and slashes all over the place.</p>
| 12,647
|
<p>This is truly a beginner question, so I apologize in advance.</p>
<p>I have Visual Studio 2008 Standard installed and would like to create a small Windows application that does NOT require any .NET framework when run on computers. Does VS 2008 Standard support such a feature? Any pointers on how to accomplish this would be fantastic.</p>
<p>Thanks in advance.</p>
|
<p>Sure, you can definitely do this. You'll have to write your application in C++, though.</p>
<p>To get started, go to File | New, and under Project Types pick one of the options under Visual C++. For the minimal dependencies, I would suggest one of the Win32 options. Both the "Win32 Console Application" and the "Win32 Project" options appear to take you to the same wizard, which if you click Application Settings on the left lets you pick whether to create a console app or a windows app. A console app will run in a console window like cmd.exe, whereas a windows app will initially have no UI (you'll have to do the UI yourself).</p>
<p>Be aware that even if you don't depend on the .NET runtime, you'll still need to have the CRT dlls available on machines that will be running your program. The redistributables for these live under the Visual Studio install dir, which if you installed in the default location would be C:\Program Files\Microsoft Visual Studio 9.0\VC\redist.</p>
|
<p>VB 6 is not based on the .NET framework. VB**.NET** is.</p>
| 34,114
|
<p>I have recently written a dynamic querying tool using expression trees and as I went the power of expression trees began to dawn on me. My querying tool could also form the basis of a reporting tool, a dynamic decision engine and maybe other cases where you need to work with dynamic objects in abstract ways. </p>
<p>The process has been painful (recursive calls to generic methods by reflection - ugh) so I am wondering whether anyone has created a generic library that might harness the power of expression trees to accomplish some of these kinds of tasks? I have seen <a href="http://www.albahari.com/nutshell/predicatebuilder.aspx" rel="noreferrer">PredicateBuilder</a> but does anyone know of any others?</p>
|
<p><a href="http://www.pobox.com/~skeet/csharp/miscutil/usage/genericoperators.html" rel="nofollow noreferrer">Generic operators</a> (in <a href="http://www.pobox.com/~skeet/csharp/miscutil/" rel="nofollow noreferrer">MiscUtil</a>) is a pretty well utilised bit of code based on expression trees; very simple, but very versatile. Some other ideas:</p>
<ul>
<li><a href="http://groups.google.com/group/microsoft.public.dotnet.languages.csharp/browse_thread/thread/d9722a51b04300a/0edae91abc1c0f1a#0edae91abc1c0f1a" rel="nofollow noreferrer">cloning objects</a></li>
<li><a href="http://groups.google.com/group/microsoft.public.dotnet.languages.csharp/browse_thread/thread/9ca28e3f0205bb87/c5b6c43ef3f38ae9" rel="nofollow noreferrer">dynamic ordering</a></li>
<li><a href="http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx" rel="nofollow noreferrer">dynamic LINQ</a></li>
</ul>
<p>(lots of others)</p>
|
<p>Have you looked at LINQ and the IQueryable interface? That's how they implemented LINQ to SQL, etc.</p>
| 44,050
|
<p>I've always been using the cookie-based session store, and never even knew about <a href="http://api.rubyonrails.com/classes/ActionController/Cookies.html" rel="nofollow noreferrer">Cookies</a> until now. So is there any situation where I'd need the cookies hash?</p>
|
<p>The cookies hash definitely has value in Rails apps. <strong>You should use cookies to store values on the client side that you want to remember between sessions.</strong> </p>
<p>A 'remember me' token is a great example. If you want to allow a user to be auto logged in when they visit your site, just store a persistent cookie with some user tamper-proof value (like a unique hash or guid (good) that maps to that user's row in your db but isn't hackable like just using a plain old integer user id (bad)). Then, when a user visits your site, you can check the cookies hash for a remember me token and, if found, do a lookup in your db and log the user in if a match is found. This is a very common practice.</p>
<p>If you need/want to store plaintext values in the client side cookie, but don't want the user to be able to futz with the values, just store a hash of that value in a companion cookie and salt the hash with some value unknown to the user. Then you just need to compute the salted hash of the plaintext value received from the client cookie and compare it against the hashed value also passed from the client cookie. If they match, you can trust it.</p>
|
<p>You shouldn't store anything you don't want the user to see or change in cookie. If you store a member ID then the user could easily change the value and pretend to be someone else. Cookies are also sent with every single request to your web server including image, JS and CSS requests. If you are storing lots of information in cookies, this could have an impact on speed.</p>
<p>Cookie-based sessions (in a general context, I can't say I know what Rails does) means your session variables are associated with a session ID which is randomly generated. This ID, and only the ID, is returned to the the user as a cookie. This allows you to associate the users request (because you have session ID cookies) with the user's sessions. This is safer because it would be very difficult for someone to guess the ID of another user's session.</p>
| 40,006
|
<p>Multithread algorithms are notably hard to design/debug/prove. Dekker's algorithm is a prime example of how hard it can be to design a correct synchronized algorithm. Tanenbaum's Modern operating systems is filled with examples in its IPC section. Does anyone have a good reference (books, articles) for this? Thanks!</p>
|
<p>It is impossible to prove anything without building upon guarentees, so the first thing you want to do is to get familiar with the memory model of your target platform; Java and x86 both have solid and standardized memory models - I'm not so sure about CLR, but if all else fails, you'll have build upon the memory model of your target CPU architecture. The exception to this rule is if you intend to use a language that does does not allow any shared mutable state at all - I've heard Erlang is like that.</p>
<p>The first problem of concurrency is shared mutable state.</p>
<p>That can be fixed by:</p>
<ul>
<li>Making state immutable</li>
<li>Not sharing state</li>
<li>Guarding shared mutable state by the <em>same</em> lock (two different locks cannot guard the same piece of state, unless you <em>always</em> use exactly these two locks)</li>
</ul>
<p>The second problem of concurrency is safe publication. How do you make data available to other threads? How do you perform a hand-over? You'll the solution to this problem in the memory model, and (hopefully) in the API. Java, for instance, has many ways to publish state and the java.util.concurrent package contains tools specifically designed to handle inter-thread communication.</p>
<p>The third (and harder) problem of concurrency is locking. Mismanaged lock-ordering is the source of dead-locks. You can analytically prove, building upon the memory model guarentees, whether or not dead-locks are possible in your code. However, you need to design and write your code with that in mind, otherwise the complexity of the code can quickly render such an analysis impossible to perform in practice.</p>
<p>Then, once you have, or before you do, prove the correct use of concurrency, you will have to prove single-threaded correctness. The set of bugs that can occur in a concurrent code base is equal to the set of single-threaded program bugs, plus all the possible concurrency bugs.</p>
|
<p>@Just in case: I is. But from what i learnt, doing so for a non trivial algorithm is a major pain. I leave that sort of a thing for brainier people. I learnt what i know from Parallel Program Design: A Foundation (1988)
by K M Chandy, J Misra </p>
| 10,003
|
<p>As developers and as professional engineers have you been exposed to the tenants of Extreme Programming as defined in the "version 1" by Kent Beck.
Which of those 12 core principles do you feel you have been either allowed to practice or at least be a part of in your current job or others?</p>
<pre><code>* Pair programming[5]
* Planning game
* Test driven development
* Whole team (being empowered to deliver)
* Continuous integration
* Refactoring or design improvement
* Small releases
* Coding standards
* Collective code ownership
* Simple design
* System metaphor
* Sustainable pace
</code></pre>
<p>From an engineers point of view I feel that the main engineering principles of XP arevastly superior to anything else I have been involved in. What is your opinion?</p>
|
<p>We are following these practices you've mentioned:</p>
<ul>
<li>Planning game</li>
<li>Test driven development</li>
<li>Whole team (being empowered to
deliver)</li>
<li>Continuous integration</li>
<li>Refactoring or design improvement</li>
<li>Small releases</li>
<li>Coding standards</li>
<li>Collective code ownership</li>
<li>Simple design</li>
</ul>
<p>And I must say that after one year I can't imagine working differently.</p>
<p>As for Pair programming I must say that it makes sense in certain areas, where there is a very high difficult area or where an initial good design is essential (e.g. designing interfaces). However I don't consider this as very effective. In my opinion it is better to perform code and design reviews of smaller parts, where Pair programming would have made sense.</p>
<p>As for the 'Whole team' practice I must admit that it has suffered as our team grew. It simply made the planning sessions too long, when everybody can give his personal inputs. Currently a core team is preparing the planning game by doing some initial, rough planning.</p>
|
<ul>
<li>Whole team (being empowered to deliver)</li>
<li>Small releases</li>
<li>Coding standards</li>
<li>Collective code ownership</li>
</ul>
<p>But then, I do work in a mission-critical development team that's quite conservative. I don't necessarily thing XP is a good way to develop, you must find a way that's right for you and ignore the dogma.</p>
| 10,207
|
<p>Is there a good <code>.Net</code> implementation of the <code>NNTP</code> protocol?</p>
|
<p>Try libraries like <a href="http://sourceforge.net/projects/dougnewsnntp/" rel="nofollow noreferrer">http://sourceforge.net/projects/dougnewsnntp/</a> and <a href="http://www.codeplex.com/nntpclientlib" rel="nofollow noreferrer">http://www.codeplex.com/nntpclientlib</a></p>
|
<p>There is a C# tutorial for reading posts using NNTP <a href="http://www.geekpedia.com/tutorial212_Developing-an-NNTP-Newsgroup-Reader.html" rel="nofollow noreferrer">here</a>. It should be enough to get you started but if you wish to start getting into processing binary posts, you're probably going to have to deal with some mime-type content too. I don't think this article covers that.</p>
| 9,000
|
<p>I can't figure out how to compile thrift files for C#. I've read, "thrift files which can then be compiled down to language-specific interfaces for a wide variety of different programming platforms (Java, PHP, C/C++, Cocoa, Perl, C#, Ruby, etc.)."</p>
<p>I was looking here: <a href="http://www.markhneedham.com/blog/2008/08/29/c-thrift-examples/" rel="nofollow noreferrer">http://www.markhneedham.com/blog/2008/08/29/c-thrift-examples/</a> and it's like I have to compile the compiler, and then build the C# version from the thrift files provided.</p>
<p>Any ideas on how to do this?</p>
|
<p>Yes, that's right, you first compile the Win32 compiler using a <a href="http://www.cygwin.com/" rel="nofollow noreferrer">Cygwin</a> environment and then in turn use that compiler to create Thrift language interfaces.</p>
|
<p>I was searching your question and I found <a href="http://www.robertsindall.co.uk/blog/how-to-generate-cassandra-0-8-1-thrift-api/" rel="nofollow">this useful topic</a>. May this helping :)</p>
| 19,791
|
<p>A couple of years ago the media was rife with all sorts of articles on
how the idea of code reuse was a simple way to improve productivity
and code quality.</p>
<p>From the blogs and sites I check on a regular basis it seems as though
the idea of "code reuse" has gone out of fashion. Perhaps the 'code
reuse' advocates have all joined the SOA crowd instead? :-)</p>
<p>Interestingly enough, when you search for 'code reuse' in Google the
second result is titled:</p>
<p>"Internal Code Reuse Considered Dangerous"!</p>
<p>To me the idea of code reuse is just common sense, after all look at
the success of the apache commons project!</p>
<p>What I want to know is:</p>
<ul>
<li>Do you or your company try and reuse code?</li>
<li>If so how and at what level, i.e. low level api, components or
shared business logic? How do you or your company reuse code?</li>
<li>Does it work?</li>
</ul>
<p>Discuss?</p>
<hr>
<p>I am fully aware that there are many open source libs available and that anyone who has used .NET or the Java has reused code in some form. That is common sense!</p>
<p>I was referring more to code reuse within an organizations rather than across a community via a shared lib etc. </p>
<p>I originally asked;</p>
<ul>
<li>Do you or your company try and reuse code?</li>
<li>If so how and at what level, i.e. low level api, components or shared business logic? How do you or your company reuse code?</li>
</ul>
<p>From where I sit I see very few example of companies trying to reuse code internally? </p>
<p>If you have a piece of code which could potentially be shared across a medium size organization how would you go about informing other members of the company that this lib/api/etc existed and could be of benefit? </p>
|
<p>The title of the article you are referring to is misleading, and is actually a very good read. Code reuse is very beneficial, but there are downsides with everything. Basically, if I remember correctly, the gist of the article is that you are sealing the code in a black box and not revisiting it, so as the original developers leave you lose the knowledge. While I see the point, I don't necessarily agree with it - at least not to a "sky is falling" regard.</p>
<p>We actually group code reuse into more than just reusable classes, we look at the entire enterprise. Things that are more like framework enhancement or address cross-cutting concerns are put into a development framework that all of our applications use (think things like pre- and post-validation, logging, etc.). We also have business logic that is applicable to more than one application, so those sort of things get moved to a BAL core that is accessible anywhere.</p>
<p>I think that the important thing is not to promote things for reuse if they are not going to really be reused. They should be well documented, so that new developers can have a resource to help them come up to speed, as well. Chances are, if the knowledge isn't shared, the code will eventually be reinvented somewhere else and will lead to duplication if you are not rigorous in documentation and knowledge sharing.</p>
|
<p>Maven has solved code reuse. I'm completely serious.</p>
| 46,449
|
<p>Is there a way using the Google Maps API to get back an "optimized" route given a set of waypoints (in other words, a "good-enough" solution to the traveling salesman problem), or does it always return the route with the points in the specified order?</p>
|
<p>There is an option in Google Maps API DirectionsRequest called optimizeWaypoints, which should do what you want. This can only handle up to 8 waypoints, though.</p>
<p>Alternatively, there is an open source (MIT license) library that you can use with the Google Maps API to get an optimal (up to 15 locations) or pretty close to optimal (up to 100 locations) route.</p>
<p>See <a href="http://code.google.com/p/google-maps-tsp-solver/" rel="noreferrer">http://code.google.com/p/google-maps-tsp-solver/</a></p>
<p>You can see the library in action at <a href="http://www.optimap.net" rel="noreferrer">www.optimap.net</a></p>
|
<p>Just found <a href="http://gebweb.net/optimap/" rel="nofollow">http://gebweb.net/optimap/</a> It looks nice and easy. Online version using google maps. </p>
| 43,809
|
<p>What are all the problem that you foresee in doing that.</p>
|
<ol>
<li><strong>VC 6 is no longer supported by Microsoft</strong>, in any way. If something goes wrong and for whatever reason we were not able to compile, we would be completely on our own unable to get any assistance from Microsoft. It seems unlikely that something could go wrong in this way, but if the code in question is a main source of revenue then you have take things in balance.</li>
<li><strong>It is impossible to compile 64-bit code in VC6</strong>. 32-bit programs run on 64-bit Windows -- at least for now. But if you need to take advantage of the potential speed and memory gains from creating a native 64-bit product (for example, being able to use more than 3 GB of RAM in a single process), then VC6 is out.</li>
<li><strong>VC9 has much better Standards compliance</strong>. VC6's Standards compliance was very poor. This is actually both a reason to port and possibly a reason not to. Programmers who used VC6 got used to doing things the 'Wrong Way', and much of that code will need to be refactored to work in VC9. </li>
</ol>
<p>A simple example of #3 above is a for loop:</p>
<pre><code>for( int n = 0; n < someMax; ++n )
{
// do stuff
}
printf("Did %d stuffs", n);
</code></pre>
<p>This code works in VC6 but won't in VC9. It is in fact a malformed program -- the fact that VC6 allows it is a defect in VC6.</p>
<p>The decision to port from VC6 to VC9 is not a slam dunk. You have to consider how difficult the project will be and balance that with any gains you get and any problems you avoid.</p>
<p>You should review Microsoft's lists of breaking changes when deciding if and how to undertake this project. The first list, breaking changes from VC6 to VC7, is a huge list. The others are much smaller in comparison. Which suggests that if you port from VC6 to anything, it should be at least 2005.</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/bb531344.aspx" rel="noreferrer">Breaking Changes VC 2005 - 2008 (VC 2005 -> VC 2008) </a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/ms177253.aspx" rel="noreferrer">Breaking Changes in the Visual C++ 2005 Compiler (VC 2003 -> VC 2005) </a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/ms177251(vs.80).aspx" rel="noreferrer">Breaking Changes in Visual C++ .NET 2003 (VC6 -> VC 2003) </a></li>
</ul>
|
<p>How big of a code base are you talking about?</p>
<p>Porting a little program (that is mostly non-templated C++ code) should be fairly trivial.</p>
<p>However I once had to convert 100.000 lines of template-using code from VC6 to VC2005, and it was a nightmare week(5 days of work), the main problem was that I had to fix by hand about 30% of the problems (70% were fairly trivial and could fix them with search & replaces). But more of an issue was the fact that the old code had no test cases and no test framework, so even after I got the application to compile and not segfault, and look ok(?), I had no assurance everything it was actually working as it was supposed to be.</p>
<p>So actually my advice is to consider the size of the code, and the availability of tests, and also consider if the code really needs to be ported (in my case that was a Yes, but its not always the case, especially if the software will be faded out soon)</p>
| 38,141
|
<p>I've always struggled with how to best include classes into my php code. Pathing is usually an issue but a few minutes ago i found <a href="https://stackoverflow.com/questions/4369/how-to-include-php-files-that-require-an-absolute-path">this question</a> which dramatically helps that. Now I'm reading about __autoload and thinking that it could make the process of developing my applications much easier. The problem is i like to maintain folder structure to separate areas of functionality as opposed to throwing everything into a general /lib folder. So if i override autoload to do a deep search of a class folder including all subfolders, what performance hits can i expect?</p>
<p>Obviously this will depend on scale, depth of the folder structure and number of classes but generally I'm asking on a medium scale project will it cause problems. </p>
|
<p>__autoload is great, but the cost of stating all the files in a recursive search function is expensive. You might want to look at building a tree of files to use for autoloading. In my framework, I consistently name files for their classes and use a map that is cached for the data.</p>
<p>Check out <strike><a href="http://trac.framewerk.org/cgi-bin/trac.fcgi/browser/trunk/index.php" rel="nofollow noreferrer">http://trac.framewerk.org/cgi-bin/trac.fcgi/browser/trunk/index.php</a></strike> [<strong>dead link</strong>] starting at line 68 for an idea of how this can be done.</p>
<p>Edit: And to more directly answer your question, without caching, you can expect a performance hit on a site with medium to heavy traffic.</p>
|
<p>Hunting for files all over the place will make things slower (many more disk hits). Loading all of your classes in case you might need them will make things take more memory. Specifying which classes you need in every file is difficult to maintain (i.e. they don't get removed if they're no longer used).</p>
<p>The real question is which of these is more important to you? They're all tradeoffs, in the end, so you have to pick one. It's arguable, though, that most of the overhead in the second and third options has to do with actually compiling the code. Using something like <a href="http://ca3.php.net/apc" rel="nofollow noreferrer">APC</a> can significantly reduce the overhead of loading and compiling every class on every page load.</p>
<p>Given the use of APC, I would likely take the approach of dividing up my code into modules (e.g. the web interface module, the database interaction module, etc.) and have each of those modules import all the classes for their module, plus classes from other modules they may need. It's a tradeoff between the last two, and I've found it works well enough for my needs.</p>
| 16,398
|
<p>I have been assigned a project to develop a set of classes that act as an interface to a storage system. A requirement is that the class support a get method with the following signature:</p>
<pre><code>public CustomObject get(String key, Date ifModifiedSince)
</code></pre>
<p>Basically the method is supposed to return the <code>CustomObject</code> associated with the <code>key</code> if and only if the object has been modified after <code>ifModifiedSince</code>. If the storage system does not contain the <code>key</code> then the method should return null.</p>
<p>My problem is this:</p>
<p><strong>How do I handle the scenario where the key exists but the object has <b>not</b> been modified?</strong></p>
<p>This is important because some applications that use this class will be web services and web applications. Those applications will need to know whether to return a 404 (not found), 304 (not modified), or 200 (OK, here's the data).</p>
<p>The solutions I'm weighing are:</p>
<ol>
<li>Throw a custom exception when the
storage system does not contain the
<code>key</code></li>
<li>Throw a custom exception when the
<code>ifModifiedSince</code> fails.</li>
<li>Add a status property to the CustomObject. Require caller to check property.</li>
</ol>
<p>I'm not happy with any of these three options. I don't like options 1 and 2 because I don't like using exceptions for flow control. Neither do I like returning a value when my intent is to indicate that there was <b>no value</b>.</p>
<p>Nonetheless, I am leaning towards option 3.</p>
<p>Is there an option I'm not considering? Does anyone have strong feelings about any of these three options?</p>
<hr>
<p><b>Answers to this Question, Paraphrased:</b></p>
<ol>
<li>Provide a <code>contains</code>
method and require caller to call it
before calling <code>get(key,
ifModifiedSince)</code>, throw
exception if key does not exist,
return null if object has not been
modified.</li>
<li>Wrap the response and data (if any)
in a composite object. </li>
<li>Use a predefined constant to denote some state (<code>UNMODIFIED, KEY_DOES_NOT_EXIST</code>).</li>
<li>Caller implements interface to be
used as callbacks.</li>
<li>The design sucks.</li>
</ol>
<hr>
<p><b>Why I Cannot Choose Answer #1</b></p>
<p>I agree that this is the ideal solution, but it was one I have already (reluctantly) dismissed. The problem with this approach is that in a majority of the cases in which these classes will be used, the backend storage system will be a third party remote system, like Amazon S3. This means that a <code>contains</code> method would require a round trip to the storage system, which would in most cases be followed by another round trip. Because this <b>would cost both time and money</b>, it is not an option.</p>
<p><strong>If not for that limitation, this would be the best approach.</strong></p>
<p>(I realize I didn't mention this important element in the question, but I was trying to keep it brief. Obviously it was relevant.)</p>
<hr>
<p><strong>Conclusion:</strong></p>
<p>After reading all of the answers I have come to the conclusion that a wrapper is the best approach in this case. Essentially I'll mimic HTTP, with meta data (headers) including a response code, and content body (message).</p>
|
<p>It sounds like you actually want to return two items: the response code and the object found. You might consider creating a lightweight wrapper that holds both and return them together.</p>
<pre><code>public class Pair<K,V>{
public K first;
public V second;
}
</code></pre>
<p>Then you can create a new Pair that holds your response code and the data. As a side effect to using generics, you can then reuse this wrapper for whatever pair you actually need.</p>
<p>Also, if the data hasn't expired, you could still return it, but give it a 303 code to let them know that it is unchanged. 4xx series would be paired with <code>null</code>.</p>
|
<p>If it is acceptable, you may return an amplified CustomObject (a wrapper), which contained values which represented the object and its modification state, if any, etc.</p>
| 44,971
|
<p>I have been studying the differences between version 2.x and version 4 of the <a href="https://reprap.org/wiki/P3Steel" rel="nofollow noreferrer">P3Steel frames</a> - in particular the AC08 bracket at the top of the frame which secures the top of the smooth bars and threaded rods of the Z axis on both the left and right sides. Here is the laser cut parts, for version 1.x, showing the part labelled as AC08:</p>
<p><a href="https://i.stack.imgur.com/2AN9z.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2AN9z.jpg" alt="Laser cut parts for P3Steel v1"></a></p>
<p>Version 1.x/2.x has the AC08 bracket with two holes, one for the threaded rod and one for the top of the smooth bar (from the <a href="http://reprap.org/wiki/P3Steel_Vitamins#Lasercut_parts" rel="nofollow noreferrer">lasercut image</a>):</p>
<p><a href="https://i.stack.imgur.com/6yZMo.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6yZMo.jpg" alt="P3Steel v2 Z axis top bracket"></a></p>
<p>However, in version 4, the corresponding top Z axis bracket only has one hole for the smooth bar and just an indentation for the bearing which holds the top of the threaded rod (from <a href="https://twitter.com/AlvaroReyRdz/status/738406531943763968" rel="nofollow noreferrer">Twitter</a>):</p>
<p><a href="https://i.stack.imgur.com/MZe2i.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MZe2i.jpg" alt="P3Steel v4 Z axis top bracket"></a></p>
<p>Here is a close up of the <a href="https://drive.google.com/open?id=0BxUhvFbuwEAZNjA0dUhwNmFMd2c" rel="nofollow noreferrer">diagram</a> from the <a href="https://drive.google.com/open?id=0BxUhvFbuwEAZfkJDUUE0bm1pTXNfMFRKemdUUzJNZ2xIT0xybFJLdmdyQV9MZGFpcG42UlE&authuser=0" rel="nofollow noreferrer">google docs repository</a>, listed in the <a href="http://reprap.org/wiki/P3Steel#Frame_versions" rel="nofollow noreferrer">v4 section</a> on the RepRap Wiki page for the P3Steel, which shows the bearing assembly just apparently "resting" against the indentation:</p>
<p><a href="https://i.stack.imgur.com/dAVUM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dAVUM.png" alt="Close up of P3Steel Z axis top bracket"></a></p>
<p>Here is the bracket shown with the bar and threaded rod (again, from <a href="https://drive.google.com/file/d/0BxUhvFbuwEAZQjkyTDM3SndMSTA/view" rel="nofollow noreferrer">google docs</a>):</p>
<p><a href="https://i.stack.imgur.com/X0fcG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/X0fcG.png" alt="P3Steel v4 z axis top bracket"></a></p>
<p>Does anyone know why the top of the threaded rod is not secured by a hole, as it was in version 1.x/2.x? It just does not look particularly well secured.</p>
<p>Under the list of version 4 changes, see <a href="https://reprap.org/wiki/P3Steel#Frame_versions" rel="nofollow noreferrer">2. Frame versions</a>, it is mentioned:</p>
<blockquote>
<p>The extruder no longer hits the Z axis top bracket</p>
</blockquote>
<p>Is this the reason why the change has been made?</p>
|
<p>I've just seen this right now, I'm Alvaro Rey, the designer of the p3steel v4 mod. The change was made, because with previous versions with the extruder homed, if you go up in the Z axis, the extruder motor could hit the Z axis top plate. So, in order to avoid that, I just changed the design.</p>
<p>The bearing in the z axis is not necessary but some people prefer to use it, in order to avoid wobble in the threaded rod. </p>
<p>Anyways, I designed a printer part to fix the bearing in the Z top plate.</p>
|
<p><em>This is mere supposition on my part, and not a definitive answer. This was posted prior to Alvaro's answer.</em></p>
<hr />
<p>In response, or - rather - with respect to, to the comments under the question by <a href="https://3dprinting.stackexchange.com/questions/3015/z-axis-top-brackets-of-p3steel-differ-between-v1-x-2-x-and-v4#comment3919_3015">tjb1</a> and <a href="https://3dprinting.stackexchange.com/questions/3015/z-axis-top-brackets-of-p3steel-differ-between-v1-x-2-x-and-v4#comment3916_3015">Tom</a>, I have been reading around the topic, and found some interesting articles.</p>
<p>The excerpt below from "<a href="http://www.soliforum.com/topic/2342/backlash-hysterisis-and-wobble-an-exploration-of-the-topic/" rel="nofollow noreferrer">An exploration of the topic</a>", backs up Tom's argument about constraining the rods at both ends being bad practice, and explains why it is so. Whilst acknowledging that a loose, or floating end, is still an issue that needs to be dealt with, the article also states that constraining the end is not really a solution, as it can create more problems elsewhere (I have added the bold highlighting to the relevant text):</p>
<blockquote>
<p>Wobble is pretty simple. Because the lead screw is mounted rigidly to
the motor, it needs to be perfectly straight and square to the axis
its trying to move. If it's not, as the motor rotates, that offset will
be converted into an elliptical motion instead of turning in a perfect
circle. In big CNC world, as the axis is normally bolted to a
huge/heavy table which refuses to yield to this movement, it results
in breaking your motor or motor coupling (weakest point in the
connection). This is what flex couplings are designed to fix – if you
can’t guarantee a perfectly square mating between motor and axis, you
use a coupler with flex so that any movement can be soaked up in
flexing the coupler and the lead screw/rod moves in a nice circle
without busting your motor or mounts. This is true when you have a
good solid supported connection on the lead screw like you’d see on a
‘proper’ CNC. <strong>However on the Solidoodle, as the top end of the Z-Axis
is ‘unsupported’ and its only connection to <em>anything</em> is to the table
via a tiny little nut, its free to ‘flop about in the breeze’ so to
speak.</strong> Even a small 0.1mm offset from center can result in a much much
greater ‘wiggle’ at the top of the screw clearly visible to the eye.
Throw in even a 0.05mm bend in the rod, and it gets further amplified.</p>
<p>Adding better support to the axis, through a taller nut, multiple
nuts, or <strong>supporting the end, would reduce the influence of this
wobble. You do however, risk moving it to something else entirely</strong> –
for example, making the lead screw rigid would mean that the forces
would end up moving the motor itself, potentially causing fatigue
issues with how its bolted to the sheet metal case (mine already moves
a fair bit and its ‘stock’... making the screw rigid would see the
motor having to absorb all that movement instead of half of it
disappearing in movement of the screw...). Solving the motor movement
by securing it ‘better’ to the case would mean that the movement now
gets soaked up in the motor shaft and bearing, leading to premature
stepper motor death.</p>
</blockquote>
<p>Thus, when first posting this question, I had originally presumed that the earlier versions of the model would be superior: Due to the fact that the earlier versions secured the top of the z-axis screw mechanism, then that would reduce the amount of "flapping about" of the loose end, which in turn would result in <em>less wobble</em>. However, I had not bargained for the negative consequences (such as the increased motor wear, mentioned above).</p>
<p>So, is the reason that the top brackets of the z-axis, in the version 4 of the frame, lost their threaded rod/leadscrew top-end constraint, therefore to prevent premature motor wear, at the expense of exhibited wobble?</p>
| 420
|
<p>I am currently running my Tronxy X5s with a MKS Gen L board. So far I have not ran the heat bed over 50 degrees C since I have only printed with PLA so far. I plan to try PETG and/or ABS in the near future and I have a spare power supply 12V/360W laying around. </p>
<p>When I first got my printer I purchased <a href="http://www.lerdge.com/prod_view.aspx?TypeId=12&Id=212&FId=t3:12:3" rel="nofollow noreferrer">this</a> external MOSFET board after reading about X5s "upgrades", but so far have not used it.</p>
<p><a href="https://i.stack.imgur.com/u6M16.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/u6M16.png" alt="enter image description here"></a>
<a href="https://i.stack.imgur.com/QiqlH.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QiqlH.jpg" alt="enter image description here"></a></p>
<p>My plan is to now run the heat bed using a separate power supply than the one running my control board using the external MOSFET to switch it. Since this power supply will only be powering the bed, I would like to bump up the voltage, via trim-pot somewhere from 12V-15V, to gain some watts per square inch on my heat bed. </p>
<p>Will this MOSFET isolate the heat bed circuit from my control board to allow it be ran at a higher voltage? Is it safe to run the power supply/heat bed at a higher voltage than it is rated for a significant amount of time?</p>
|
<p>Short answer YES. You can run it from a different power supply at a higher voltage. Also it has a PC817 Optical isolator (for some reason) therefore the second power supply and your main board should not be electrically connected at all.</p>
|
<p>For reference,I done tracing this module as shown.
<a href="https://i.stack.imgur.com/ols3z.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ols3z.jpg" alt="enter image description here" /></a>
<a href="https://i.stack.imgur.com/r8ao6.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/r8ao6.jpg" alt="enter image description here" /></a>
So you can use isolated power supply for load.
Also you can use up to 24V without any problem.
Edit:
This module still work with higher voltage up to 24V. But according to question. Using higher voltage supply more than rated is same as my question <a href="https://3dprinting.stackexchange.com/questions/15263/can-we-apply-more-voltage-to-a-pcb-heated-bed-to-get-faster-heating">here</a>.
For summary. Adding more voltage to resistive load results to higher current flow. Recheck your wire and connectors for current rate so you will know the limit of voltage you can go with.
One more thing, mosfet can fail like short circuit. At this situation the temperature of bed cannot be controlled.
At normal voltage rate even we left the bed connected to power supply the temperature will rising to about 100C if you add more voltage it will go higher than that can the heated bed will broken or burned or start to fires</p>
| 1,261
|
<p>let us have a situation in which the following program prints some 10 lines of #</p>
<pre><code>for(i=0;i<10;i++)
prinf("\n#");
</code></pre>
<p>now how to go back to 5 th line and edit that # and change the color of it without clearing the screen or clearing the below 5 lines?
<p>I have tried </p>
<pre><code>window(5,0,20,20);
textcolor(GREEN);
cprintf("#");
</code></pre>
<p>but it is not editing that one but it is printing on the side of the original one.why?
<p>is there any other way of doing it and changing the color of the already printed text dynamically?
please help me..my environment is turbo c on windows</p>
|
<p>It looks like you are mixing printf and another output library - this isn't recommended. Printf expects to be sent to a character terminal, while the output library in question may falsly assume that it has exclusive access (and might misbehave.)</p>
<p>Based on one function, you're likely using conio.h. The documentation can be found <a href="http://poli.cs.vsb.cz/c/help/conio.htm" rel="nofollow noreferrer">here</a>, with a table of contents showing each available function. From that index, you should be able to spot the function instantly. </p>
<p>The window function doesn't do what you want it to, since it only sets the area in which the cursor may change text - it doesn't move the cursor, you need to use the other library functions. </p>
|
<p>maybe- </p>
<pre><code>cprintf("\b#");
</code></pre>
<p>'b' is for backspace</p>
| 33,109
|
<p>I'm an email n00b but I am working on an application that sends HTML email with Unicode characters (as my friend noted "enjoy encoding hell").</p>
<p>The <code>Subject:</code> header comes from user input and therefore may contain Unicode characters. Some mail clients (like GMail and Outlook 2007) are OK with this, but from my reading it seems the right way to do this is to use <a href="http://en.wikipedia.org/wiki/MIME#Encoded-Word" rel="noreferrer">MIME Encoded-Word encoding</a> for the headers.</p>
<p>I cannot find a Ruby library to do this. Is there one?</p>
<p>Also, is there a header to add that will tell mail clients to use UTF-8 when displaying the message? We are sending multipart email so our <code>Content-Type</code> is <code>multipart/mixed</code>. Apple Mail.app in particular is not using the right encoding, even though it's specified in the individual parts as being UTF-8.</p>
|
<p>Ahah! <code>ActionMailer::Quoting</code> has a <code>quoted_printable</code> method.</p>
<p>So here's what I did:</p>
<pre><code>def my_email(foo)
...
@subject = quoted_printable(foo.some_subject_with_accented_chars, 'utf-8')
...
end
</code></pre>
<p>Doing this convinced Mail.app to display the rest of the email using UTF-8. Now to test the rest!</p>
|
<p>Since none of the answers tells about whole message with pure Ruby, here it is.</p>
<pre><code>Net::SMTP.start("localhost") do |smtp|
smtp.open_message_stream opts[:sender_address], opts[:receiver_address] do |f|
f.puts "Content-type: text/plain; charset=UTF-8"
f.puts from
f.puts to
f.puts subject
f.puts message
end
end
</code></pre>
<p>Here you open connection to localhost. Using external SMTP server is also possible, refer to documentation of net/smtp.</p>
<p>First line sets character set used in the message. Rest of the lines are variables defined separately:</p>
<p>from is an address in form of <code>From: Name here <address@here.fi></code>. If no name is wanted, only address can be specified, like <code>From: address@here.fi</code>.</p>
<p>to uses same syntax, with exception <code>From:</code> changed to <code>To:</code>.</p>
<p>subject is in form of Subject: subject here. For UTF-8, it needs to be Base64-encoded to be shown correctly for clients.</p>
<pre><code>subject = "Subject: =?UTF-8?B?" + Base64.strict_encode64(subject) + "?="
</code></pre>
<p>Message is plain text message encoded in UTF-8, without any prefix. net/smtp will take care of forming proper mail.</p>
| 44,417
|
<p>I've been working on a project that accesses the WMI to get information about the software installed on a user's machine. We've been querying Win32_Product only to find that it doesn't exist in 64-bit versions of Windows because it's an <a href="http://msdn.microsoft.com/en-us/library/aa392726(VS.85).aspx" rel="nofollow noreferrer">"optional component"</a>.</p>
<p>I know there are a lot of really good alternatives to querying the WMI for this information, but I've got a bit of a <a href="http://www.codeplex.com/linq2wmi" rel="nofollow noreferrer">vested interest</a> in finding out how well this is going to work out.</p>
<p>What I want to know is if there's some kind of redistributable that can be packaged with our software to allow 64-bit users to get the WMI Installer Provider put onto their machines? Right now, they have to install it manually and the installation requires they have their Windows disc handy.</p>
<p>Edit:</p>
<blockquote>
<p>You didn't mention for what OS, but the WMI Redistributable Components version 1.0 definitely exists.</p>
</blockquote>
<p>For Operation System, we've been using .NET 3.5 so we need packages that will work on XP64 and 64bit versions of Windows Vista.</p>
|
<p>You didn't mention for what OS, but the <a href="http://www.microsoft.com/downloads/details.aspx?familyid=013BB284-3946-44A9-AC3C-BF2A569EAA72&displaylang=en" rel="nofollow noreferrer" title="Microsoft Download Center">WMI Redistributable Components version 1.0</a> definitely exists.</p>
<p>For Windows Server 2003, the WMI SDK and redistributables are part of the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=484269E2-3B89-47E3-8EB7-1F2BE6D7123A&displaylang=en" rel="nofollow noreferrer" title="Windows Server 2003 SDK Full Download">Server SDK</a></p>
<p><em>I believe</em> that the same is true for the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=F26B1AA4-741A-433A-9BE5-FA919850BDBF&displaylang=en" rel="nofollow noreferrer" title="Microsoft Download Center">Server 2008 SDK</a></p>
|
<p>Wouldn't the normal approach for a Windows component be that the administrators of a set of servers use whatever their local software push technology (i.e. SMS) to ensure that component is installed? This is not that uncommon of a requirement for the remote management of servers via WMI.</p>
<p>By the way, the WMI Installer Provider is not provided in the Standard Edition of the server products, but it is in the Enterprise Edition. So, Windows 2003 Server will not have this installed by default, but Windows 2003 Server Enterprise (and DataCenter) will.</p>
<p>This answer does imply that you are putting the burden of installation back on your user base, but for Windows administrators this should not be any issue.</p>
| 2,581
|
<p>I've got a .NET 3.5 class lib that I am trying to write some automated tests for but I'm getting the following error when running any tests in the solution:</p>
<blockquote>
<p>Test method Common.Tests.CommonTests.TestMethod1 threw exception: System.IO.FileNotFoundException: Could not load file or assembly 'Library.Common, Version=0.0.1.22004, Culture=en-AU, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.WRN: Assembly binding logging is turned OFF.</p>
<p>To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.</p>
<p>Note: There is some performance penalty associated with assembly bind failure logging.</p>
<p>To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].</p>
</blockquote>
<p>I'm fairly new to unit testing so I'm stumped.</p>
<p>I've compaired the references between the lib and the tests project and the only difference is that the tests project references the MS unit test DLL.</p>
<p><strong>Edit to clarify</strong></p>
<p>I used the test creation wizard from within my 'Library.Common' project so the test project has the reference to the Library.Common project. I've cleaned and built the solution too, that's not the problem.</p>
<p>Library.Common.dll is also in the bin\Debug folder of my test project output.</p>
|
<p>Found the problem, I had set the <em>AssemblyCultureAttribute</em> in the AssemblyInfo.cs file in my Library.Common project. Once removing it the tests run.</p>
<p>Now to actually learn how to use that attribute!</p>
|
<p>Can you rebuild the solution? And do you reference to that Library.Common? </p>
<p>You may want to provide more details ( such as what is Library.Common).</p>
| 24,351
|
<p>I'm a long time hobbyist programmer interested in getting into web application development. I have a fair amount of personal experience with various non-web languages, but have never really branched over to web applications.</p>
<p>I don't usually have any issues learning new languages or technologies, so I'm not worried about which is the "best" language or web stack to work with. Instead, I'd like to know of any recommended resources (books, articles, web sites, maybe even college courses) that discuss web application design: managing and optimizing server interaction, security concerns, scalability, and other topics that fall under design rather than implementation.</p>
<p>What would you recommend for a Standalone Application Developer wanting to branch out into Web Development?</p>
|
<p>There is a wide variety of web application languages you could get into. The ones I have most experience with (and therefore will be talking about here) are PHP, eRuby and Ruby on Rails. All of these have good tutorials available on the internet - I'll link to some of them below.</p>
<p>Which to choose depends on exactly what you're looking to do. Using PHP and eRuby you have to do most things yourself - whereas Ruby on Rails will do lots of stuff for you (useful, but can also be dangerous if you don't know what you're doing). Ruby on Rails is good for doing database related things - for example the standard CRUD (Create, Read, Update, Delete) application. The standard kind of app Ruby on Rails (often abbreviated to RoR) tutorials teach you is a blog application (Create entries, Read entries, Update entries, Delete entries) or an Address Book Application. It is possible to do many of these sort of applications almost in one line of code - using RoR's 'scaffold' function.</p>
<p>PHP and eRuby make you do more of the work yourself - but this can be better in some situations. PHP is more well known and used than eRuby, but I like the Ruby language so I tend to like using eRuby. These are both good for doing simple applications (like contact forms on websites) or more complex applications (phpBB - a piece of forum software is written in php).</p>
<p>As for which one to choose - I'd have a play with them and see what you think. Try running through the first few bits of a tutorial with each and see how whether you like it or not.</p>
<p>Here come the links to various tutorials:</p>
<p><strong>PHP</strong></p>
<ul>
<li><a href="http://devzone.zend.com/node/view/id/627" rel="nofollow noreferrer">PHP 101</a></li>
<li><a href="http://www.w3schools.com/php/php_intro.asp" rel="nofollow noreferrer">PHP Intro from W3Schools</a></li>
</ul>
<p><strong>eRuby</strong></p>
<ul>
<li><a href="http://www.osix.net/modules/article/?id=384" rel="nofollow noreferrer">Beginning eRuby</a> - not great, but shows you how you can embed it in HTML</li>
<li><a href="http://tryruby.hobix.com/" rel="nofollow noreferrer">Try Ruby in your Browser</a> - helps you learn Ruby which you need to know for eRuby</li>
</ul>
<p><strong>Ruby on Rails</strong></p>
<ul>
<li><a href="http://www.onlamp.com/pub/a/onlamp/2006/12/14/revisiting-ruby-on-rails-revisited.html" rel="nofollow noreferrer">Rolling with Ruby on Rails</a> - the latest 'revisited' version for the latest version of RoR</li>
<li><a href="http://www.onlamp.com/pub/a/onlamp/2007/01/05/revisiting-ruby-on-rails-revisited-2.html" rel="nofollow noreferrer">Rolling with Ruby on Rails part 2</a></li>
</ul>
<p>There are a few tutorials to get you started. Some of these take you through installing the necessary software (webserver and anything else needed - eg. php or ruby) and some don't. A good way to get Apache (webserver), MySQL (db) and PHP installed on windows is to use <a href="http://www.apachefriends.org/en/xampp.html" rel="nofollow noreferrer">XAMPP</a>. If you're on linux then apache, mysql and php will be in your package repositories and there may be distro specific guides to setting them up.</p>
|
<p><a href="http://eloquentjavascript.net/" rel="nofollow noreferrer">Eloquent JavaScript</a> and <a href="http://appjet.com/learn-to-program/lessons/intro" rel="nofollow noreferrer">AppJet</a> offer great tutorials that allow you to follow along while you learn.</p>
<p>Once you cover all the basics, <a href="http://ajaxian.com/" rel="nofollow noreferrer">Ajaxian</a> should answer many of the questions you have about application design, etc. Not only do they post many excellent articles on these topics, but you should explore many of the sites they link to, as these sites usually also provide a wealth of info.</p>
<p>When it comes to server interactions, know your options. Ajax isn't all there is. Research technologies like <a href="http://cometdaily.com/" rel="nofollow noreferrer">Comet</a> and <a href="http://en.wikipedia.org/wiki/JSON-RPC" rel="nofollow noreferrer">JSON-RPC</a>, as well as looking at various server-side frameworks that provide easy access to JavaScript such as <a href="http://directwebremoting.org/" rel="nofollow noreferrer">DWR</a>, <a href="http://jayrock.berlios.de/" rel="nofollow noreferrer">Jayrock</a>, or any tool that exposes your functions to JavaScript using whatever language you choose to use on the server.</p>
| 3,888
|
<p>How do I get a list of all the headings in a word document by using VBA?</p>
|
<p>You mean like this <a href="http://msdn.microsoft.com/en-us/library/bb960898.aspx" rel="nofollow noreferrer">createOutline</a> function (which actually copy all headings from a source word document into a new word document):</p>
<p>(I believe the <code>astrHeadings = docSource.<strong><a href="http://msdn.microsoft.com/en-us/library/aa201500(office.10).aspx" rel="nofollow noreferrer">GetCrossReferenceItems</a></strong>(wdRefTypeHeading)</code> function is the key in this program, and should allow you to retrieve what you are asking for)</p>
<pre><code>Public Sub CreateOutline()
Dim docOutline As Word.Document
Dim docSource As Word.Document
Dim rng As Word.Range
Dim astrHeadings As Variant
Dim strText As String
Dim intLevel As Integer
Dim intItem As Integer
Set docSource = ActiveDocument
Set docOutline = Documents.Add
' Content returns only the main body of the document, not the headers/footer.
Set rng = docOutline.Content
' GetCrossReferenceItems(wdRefTypeHeading) returns an array with references to all headings in the document
astrHeadings = docSource.GetCrossReferenceItems(wdRefTypeHeading)
For intItem = LBound(astrHeadings) To UBound(astrHeadings)
' Get the text and the level.
strText = Trim$(astrHeadings(intItem))
intLevel = GetLevel(CStr(astrHeadings(intItem)))
' Add the text to the document.
rng.InsertAfter strText & vbNewLine
' Set the style of the selected range and
' then collapse the range for the next entry.
rng.Style = "Heading " & intLevel
rng.Collapse wdCollapseEnd
Next intItem
End Sub
Private Function GetLevel(strItem As String) As Integer
' Return the heading level of a header from the
' array returned by Word.
' The number of leading spaces indicates the
' outline level (2 spaces per level: H1 has
' 0 spaces, H2 has 2 spaces, H3 has 4 spaces.
Dim strTemp As String
Dim strOriginal As String
Dim intDiff As Integer
' Get rid of all trailing spaces.
strOriginal = RTrim$(strItem)
' Trim leading spaces, and then compare with
' the original.
strTemp = LTrim$(strOriginal)
' Subtract to find the number of
' leading spaces in the original string.
intDiff = Len(strOriginal) - Len(strTemp)
GetLevel = (intDiff / 2) + 1
End Function
</code></pre>
<p><strong>UPDATE by @kol on March 6, 2018</strong></p>
<p>Although <code>astrHeadings</code> is an array (<code>IsArray</code> returns <code>True</code>, and <code>TypeName</code> returns <code>String()</code>) I get a <code>type mismatch</code> error when I try to access its elements in VBScript (v5.8.16384 on Windows 10 Pro 1709 16299.248). This must be a VBScript-specific problem, because I can access the elements if I run the same code in Word's VBA editor. I ended up iterating the lines of the TOC, because it works even from VBScript:</p>
<pre><code>For Each Paragraph In Doc.TablesOfContents(1).Range.Paragraphs
WScript.Echo Paragraph.Range.Text
Next
</code></pre>
|
<p>You can also create a Table of Contents in the doc and copy that. This separates out the para ref from the title, which is handy if you need to present that in another context.
If you do not want the ToC in your doc, just delete that after the Copy n Paste. JK.</p>
| 34,624
|
<p>How to get the phone number of the device in Symbian?</p>
|
<p>According to the GSM specs, only the <a href="http://en.wikipedia.org/wiki/IMSI" rel="nofollow noreferrer">IMSI</a> is required to be available on the <a href="http://en.wikipedia.org/wiki/Subscriber_Identity_Module#Data" rel="nofollow noreferrer">SIM</a> card.</p>
<p>The actual phone number <a href="http://en.wikipedia.org/wiki/MSISDN" rel="nofollow noreferrer">MSISDN</a> is stored on the <a href="http://en.wikipedia.org/wiki/GSM_core_network#Home_Location_Register_.28HLR.29" rel="nofollow noreferrer">HLR</a> database in the operator's network and does not need to be available on the SIM card or transmitted to the phone.</p>
<p>So no matter what technology you are using (Symbina, Java ...) you can never count on being able to consistently get your own phone number from the device or SIM. You might be lucky if the operator stores it on the SIM or if the phone provides the user with a possibility to enter it manually, but it does not have to be this way.</p>
|
<p>You can't. Afaik.</p>
<p>Check this discussion:
<a href="http://discussion.forum.nokia.com/forum/showthread.php?t=65117" rel="nofollow noreferrer">http://discussion.forum.nokia.com/forum/showthread.php?t=65117</a></p>
| 8,534
|
<p>On my Vista machine I cannot install the .Net framework 3.5 SP1. Setup ends few moments after ending the download of the required files, stating in the log that: </p>
<pre><code>[08/26/08,09:46:11] Microsoft .NET Framework 2.0SP1 (CBS): [2] Error: Installation failed for component Microsoft .NET Framework 2.0SP1 (CBS). MSI returned error code 1
[08/26/08,09:46:13] WapUI: [2] DepCheck indicates Microsoft .NET Framework 2.0SP1 (CBS) is not installed.
</code></pre>
<p>First thing I did was trying to install 2.0 SP1, but this time setup states that the "product is not supported on Vista system". Uhm.</p>
<p>The real big problem is that this setup fails also when it is called by the Visual Studio 2008 SP1.</p>
<p>Now, I searched the net for this, but I'm not finding a real solution... Any idea / hint? Did anybody have problems during SP1 install?</p>
<p>Thanks</p>
|
<p><a href="http://blogs.msdn.com/astebner/archive/2007/08/24/4548657.aspx" rel="nofollow noreferrer">Here is an article describing what might be your problem.</a></p>
|
<p>I also experienced it on my XP.</p>
<p>I searched for it, and the result was that some kind of beta .NET remained on my PC.</p>
<p>There is a <a href="http://blogs.msdn.com/astebner/archive/2005/04/08/406671.aspx" rel="nofollow noreferrer">tool to remove all</a> .NET framework from the system. I run it and after it I successfully installed 3.5 SP1.</p>
| 4,731
|
<p>I have a CakePHP 1.2 application.</p>
<p>I'm running into the case where I need to do some logic to render things correctly in the view. </p>
<p>Example:
I have a table called Types. There are flags for various types, so each row has one or more BOOL fields set. For one type of type, I store the contents of an RTF in another field.</p>
<p>So when I display a listing of all typoes in the view, I want to create a link for the types that are the type where I store RTF. I don't want to show a link, otherwise.</p>
<p>Where is the best place for this logic?</p>
<p>I want to use html->link to create the link, but I can't use that inside of my model. Should the logic go in the model, and if so, should I be building HTML in my model, e.g. the link?</p>
|
<p>i'd suggest keeping that logic in the view, building HTML in your model breaks the whole view/model separation. i don't think there's anything wrong with view logic, personally i tend to constrain it to basic conditionals.</p>
<p>ultimately i think the idea is figuring out where this logic best fits. in this case, the logic is, "if i have a certain type, i should provide a link to it", which is a view problem, not a model problem.</p>
|
<p>Build your own AppHtmlHelper which extends HtmlHelper and does the check for you.</p>
| 16,344
|
<p>In the following code, both the INPUT and TEXTAREA elements render wider than they should. How can I limit them to 100% of the usable area within the div?</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<style>
.mywidth{ width:100%; }
</style>
</head>
<body>
<div style="border: 3px solid green; width: 100px;">
<input class="mywidth" ><br />
<textarea class="mywidth"></textarea><br />
<div style="background-color: yellow;" class="mywidth">test</div>
</div>
</body>
</html>
</code></pre>
<p>Note: If I remove the DOCTYPE, it renders as expected, with the INPUT, TEXTAREA and inner DIV all the same width and not going outside the containing DIV.</p>
<p>Update: Not withstanding the default borders on those elements, it still appears to render incorrectly in <strong>IE7</strong>.</p>
|
<p>Inputs and textareas both have borders by default</p>
<pre><code><style>
.mywidth{
width:100%;
border:0;
}
</style>
</code></pre>
<p>will render all the elements within your container.</p>
<p><strong>Update</strong></p>
<p>IE also has left and right padding on each element and the following css fits all the elements within the container in FF3, FF2, Safari 3, IE6 and IE7.</p>
<pre><code><style>
.mywidth{ width:100%; border:0; padding-left:0; padding-right:0; }
</style>
</code></pre>
<p>However, don't forget that you will probably need a border, and perhaps the padding too, in order to make the fields appear to users as normal. If you set that border and padding yourself then you will know what the difference is, across browsers, between the width of the container and the width you will need to give to the input/textarea elements.</p>
|
<p>You could try using this DOCTYPE instead</p>
<pre><code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
</code></pre>
| 32,414
|
<p>When I try to create a new task in the task scheduler via the Java ProcessBuilder class I get an access denied error an Windows Vista. On XP it works just fine.</p>
<p>When I use the "Run as adminstrator" option it runs on Vista as well..</p>
<p>However this is a additional step requeried an the users might not know about this. When the user just double clicks on the app icon it will fail with access denied. My question is how can I force a java app to reuest admin privileges right after startup?</p>
|
<p>Have you considered wrapping your Java application in an .exe using launch4j? By doing this you can embed a manifest file that allows you to specify the "execution level" for your executable. In other words, you control the privileges that should be granted to your running application, effectively telling the OS to "Run as adminstrator" without requiring the user to manually do so.</p>
<p>For example...</p>
<p>build.xml:</p>
<pre><code><target name="wrapMyApp" depends="myapp.jar">
<launch4j configFile="myappConfig.xml" />
</target>
</code></pre>
<p>myappConfig.xml:</p>
<pre><code><launch4jConfig>
<dontWrapJar>false</dontWrapJar>
<headerType>gui</headerType>
<jar>bin\myapp.jar</jar>
<outfile>bin\myapp.exe</outfile>
<priority>normal</priority>
<downloadUrl>http://java.com/download</downloadUrl>
<customProcName>true</customProcName>
<stayAlive>false</stayAlive>
<manifest>myapp.manifest</manifest>
<jre>
<path></path>
<minVersion>1.5.0</minVersion>
<maxVersion></maxVersion>
<jdkPreference>preferJre</jdkPreference>
</jre>
</launch4jConfig>
</code></pre>
<p>myapp.manifest:</p>
<pre><code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
<security>
<requestedPrivileges>
<requestedExecutionLevel level="highestAvailable"
uiAccess="False" />
</requestedPrivileges>
</security>
</trustInfo>
</assembly>
</code></pre>
<p>See <a href="http://msdn.microsoft.com/en-us/library/bb756929.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/bb756929.aspx</a> and the launch4j website for mode details.</p>
|
<p>I haven't found the best solution yet. But I have an alternative work-around comparing to "James Van Huis". Use RUNASINVOKE instead so you don't have to see the prompt Allow/Deny everytime you run the app.</p>
<p>Note: you always have to be Admin, that what I am trying to solve</p>
| 32,300
|
<p>This question follows on from <a href="https://stackoverflow.com/questions/299114/can-i-search-for-php-class-members-and-methods-with-vim-star-search">this vim search question</a></p>
<p>I have a setting in my .vimrc which excludes $ as a valid part of a word:</p>
<pre><code>set iskeyword-=$
</code></pre>
<p>This works fine for most files but isn't working in PHP. I assume it is being overwritten by a php plugin, but since plugins are loaded after .vimrc I can't work out how to overwrite this setting. I'd prefer not to have to type </p>
<pre><code>:set isk-=$
</code></pre>
<p>every time I load a PHP file.</p>
<p>Any suggestions?</p>
<p>( Ubuntu 8.04 / Vim 7.1.138 if it matters )</p>
<p><strong>Summary</strong></p>
<p>Two excellent answers, thank you!</p>
<p>I went with <a href="https://stackoverflow.com/users/18771/tomalak">tomalak</a>'s because it was less effort, and added the following to my ~/.vimrc</p>
<pre><code>autocmd FileType php setlocal isk-=$
</code></pre>
<p>but thanks also to <a href="https://stackoverflow.com/questions/305574/can-i-stop-settings-in-vimrc-from-being-overwritten-by-plugins#305820">Luc Hermitte</a>. Putting the settings in a ~/vim/after/ftplugin/php.vim file also worked.</p>
<p><em>:help autocmd</em> and <em>:help after-directory</em> both helped too</p>
|
<p>I would probably just add <code>set isk-=$</code> to my syntax highlighting auto command in <code>$VIMRUNTIME\filetype.vim</code>. Don't know if it is the nicest way to do it, though.</p>
<p>Thinking about it... I think it would be enough to have an appropriate autocommand in your <code>vimrc</code>.</p>
<pre><code>au FileType php set isk-=$
</code></pre>
<p>This executes after the FileType has been set. Auto commands are executed in the order they are given, so when you put it late in your <code>vimrc</code> it will execute last for PHP files.</p>
|
<p>Make a copy of your .vimrc, e.g. .vimrc.ref </p>
<p>Make the copy in another directory.</p>
<p>Then find out why the plugin authors really need to just clobber your .vimrc without:</p>
<ol>
<li>letting you know that they're clobbering it, and</li>
<li>saving a copy of your .vimrc file so you can easily roll back.</li>
</ol>
<p>Edit: And let <a href="http://www.vim.org/" rel="nofollow noreferrer">http://www.vim.org/</a> know about those who would reach under your covers without letting you know!</p>
| 39,310
|
<p>Here's the situation: I am trying to launch an application, but the location of the .exe isn't known to me. Now, if the file extension is registered (in Windows), I can do something like:</p>
<pre><code>Process.Start("Sample.xls");
</code></pre>
<p>However, I need to pass some command line arguments as well. I couldn't get this to work</p>
<pre><code> Process p = new Process();
p.StartInfo.FileName = "Sample.xls";
p.StartInfo.Arguments = "/r"; // open in read-only mode
p.Start();
</code></pre>
<p>Any suggestions on a mechanism to solve this?</p>
<p><strong>Edit</strong> @ aku</p>
<p>My StackOverflow search skills are weak; I did not find that post. Though I generally dislike peering into the registry, that's a great solution. Thanks!</p>
|
<p>Using my code from <a href="https://stackoverflow.com/questions/24954/windows-list-and-launch-applications-associated-with-an-extension#24974">this</a> answer you can get command associated with xls extension. Then you can pass this command to <code>Process.Start</code> method.</p>
|
<p>If you query the registry, you can retrieve the data about the registered file type and then call the app directly passing the command line arguments. See <a href="http://www.blackwasp.co.uk/ProgrammaticFileTypes.aspx" rel="nofollow noreferrer">Programmatically Checking and Setting File Types</a> for an example of retrieving shell information for a file type.</p>
| 5,651
|
<p>I'm trying to use class names to change the color of a link after it has been selected, so that It will remain the new color, but only until another link is selected, and then it will change back.</p>
<p>I'm using this code that was posted by Martin Kool in <a href="https://stackoverflow.com/questions/206689/changing-the-bg-color-of-a-selected-link">this</a> question:</p>
<pre><code><html>
<head>
<script>
document.onclick = function(evt) {
var el = window.event? event.srcElement : evt.target;
if (el && el.className == "unselected") {
el.className = "selected";
var siblings = el.parentNode.childNodes;
for (var i = 0, l = siblings.length; i < l; i++) {
var sib = siblings[i];
if (sib != el && sib.className == "selected")
sib.className = "unselected";
}
}
}
</script>
<style>
.selected { background: #f00; }
</style>
</head>
<body>
<a href="#" class="selected">One</a>
<a href="#" class="unselected">Two</a>
<a href="#" class="unselected">Three</a>
</body>
</code></pre>
<p>It works fine until I try to out the links in a table. Why is this? Be easy, I'm a beginner.</p>
<hr>
<p>There is no error, the links are changing to the "selected" class, but when another link is selected, the old links are keeping the "selected" class instead of changing to "unselected". Basically, as far as I can tell, it's functioning like a vlink attribute, which is not what I'm going for.</p>
<p>And yes, the links are all in different cells, how would you suggest I change the code so that it works correctly?</p>
<hr>
<p>OK, actually, I spoke too soon.</p>
<pre><code>document.onclick = function(evt)
{
var el = window.event? event.srcElement : evt.target;
if (el && el.className == 'unselected')
{
var links = document.getElementsByTagName('a');
for (var i = links.length - 1; i >= 0; i--)
{
if (links[i].className == 'selected')
links[i].className = 'unselected';
}
el.className = 'selected';
}
return false;
}
</code></pre>
<p>This code you gave me works great, visually, it does exactly what I want it to do. However, It makes my links stop working... They change color, but dont link to anything, and then when I remove the script, they work fine. What am I doing wrong/what do I have to change to make this work?</p>
<p>Also, I want to do the same thing somewhere else in my website, where the links are all in one <code><div></code> tag, separated by <code><p></code> tags. How can I make this work?</p>
|
<p>You're looping through the siblings. If the links are in separate <code><td></code>'s then they're no longer siblings.</p>
<p>You can loop through all the links like this:</p>
<pre><code>document.onclick = function(evt)
{
var el = window.event? event.srcElement : evt.target;
if (el && el.className == 'unselected')
{
var links = document.getElementsByTagName('a');
for (var i = links.length - 1; i >= 0; i--)
{
if (links[i].className == 'selected')
links[i].className = 'unselected';
}
el.className = 'selected';
}
return false;
}
</code></pre>
<p>I've also added a <code>return false;</code> at the end of the function to stop you going to '#'</p>
|
<p>Is there an error or is there just nothing happening? A good first step if you are a javascript beginner is to use a tool like Firebug so you see detailed error messages, and you can add in console.log statements to see what's going on while you run your code.</p>
| 31,957
|
<p>How can I capture enter keypresses anywhere on my form and force it to fire the submit button event?</p>
|
<p>If you set your <code>Form</code>'s <code>AcceptButton</code> property to one of the <code>Button</code>s on the <code>Form</code>, you'll get that behaviour by default.</p>
<p>Otherwise, set the <code>KeyPreview</code> property to <code>true</code> on the <code>Form</code> and handle its <code>KeyDown</code> event. You can check for the <code>Enter</code> key and take the necessary action.</p>
|
<pre><code> if (e.KeyCode.ToString() == "Return")
{
//do something
}
</code></pre>
| 19,931
|
<p>When I'm working on a project, sometimes I'll design the GUI first and then write the backend code to make it work, but other times I'll do the opposite and make the GUI once I have the system working. How do you choose which way round to code and are there any particular types of project or circumstances that would lean you either way?</p>
|
<p>You need to create something which would let your testers start immediately. Try to think from that prospective.</p>
<p>If they are working on manual UI testing give them a shell of UI with stubs for all the functionality. If there is an interface to be tested make sure it works (even if it returns dummy data) so they could start working with it, etc.</p>
<p>Most of the time it's the UI. You could show it to your users and get immediate feedback which is really useful.</p>
|
<p>My way is:</p>
<ol>
<li>Write on paper very specifically what I want the app to do</li>
<li>Draw on paper the basic views of the app, based on what I want the app to do</li>
<li>Think of the basic elements that are needed to be on the app</li>
<li>Prototype a basic view of the app, either on the SDK I am using or a prototyping app (a prototyping app is better because this way you will save time just in case you see in the process that what you have thought is not helping with the usage of the app)</li>
<li>Transfer the prototype to your SDK and write the code</li>
<li>Study the UX "laws" and apply to the design... this is the point that you may have to change your code accordingly</li>
</ol>
| 22,580
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.