instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>I'm using a Flash TextField control to display some HTML content inside a Flash presentation to be shown on a large touch-screen kiosk. Unfortunately, if any image tag in the displayed HTML content points to a non-existent image, a dialogue is shown with the error message </p>
<pre><code>Error #2044: Unhandled IOErrorEvent:. text=Error #2035: URL Not Found.
</code></pre>
<p>I am trying to avoid having that dialogue pop up. The <a href="http://www.kirupa.com/forum/showthread.php?t=287501" rel="nofollow noreferrer">solution</a> for loading content through a loader class is to catch <code>IOErrorEvent.IO_ERROR</code>, but I've tried listening for that on the TextField, on stage, Main and loaderInfo to no avail. I've tried wrapping the whole thing in a try-catch, and that also doesn't work.</p>
<p>Here's the simplified code I'm using to find solutions:</p>
<pre><code>package {
import flash.display.Sprite;
import flash.errors.IOError;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.text.TextField;
import flash.text.TextFieldType;
public class Main extends Sprite {
public function Main():void {
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void {
removeEventListener(Event.ADDED_TO_STAGE, init);
var html:TextField = new TextField();
html.type = TextFieldType.DYNAMIC;
html.multiline = true;
html.htmlText = "Bogus image: <img src=\"foo.jpg\" />";
addChild(html);
}
}
}
</code></pre>
<p><strong>Edit: And here's the entire working code.</strong></p>
<p>For dynamic content and so forth, of course, you would need a list of images and a function to generate handlers, etc.</p>
<pre><code>package {
import flash.display.Loader;
import flash.display.Sprite;
import flash.errors.IOError;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.text.TextField;
import flash.text.TextFieldType;
public class Main extends Sprite {
public function Main():void {
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void {
removeEventListener(Event.ADDED_TO_STAGE, init);
var html:TextField = new TextField();
html.type = TextFieldType.DYNAMIC;
html.multiline = true;
html.htmlText = "Bogus image: <img id=\"image\" src=\"foo.jpg\" />";
var loader:Loader = html.getImageReference("image") as Loader;
if(loader){
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, function(e:Event):void {
trace("Error loading foo.jpg!");
});
}
addChild(html);
}
}
}
</code></pre>
|
<p>You can add ID's to images </p>
<pre><code>html.htmlText = "Bogus image: <img src=\"foo.jpg\" id="image" />";
</code></pre>
<p>And then setup IOErrorEvent handler to each image in HTML</p>
<pre><code>var loader:Loader = html.getImageReference("image") as Loader;
if(loader){
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, function(e:Event):void{});
}
</code></pre>
|
<p>This is a problem I'm also dealing with: it's a real annoyance. I'd really like to be able to catch all the errors. I assumed you could say...</p>
<pre><code>stage.addEventListener(IOError.IO_ERROR, myErrorHandler);
</code></pre>
<p>...but that doesn't seem to work, as you've pointed out.</p>
<p>Perhaps you can check to make sure the kiosk's flash player isn't the debug version. I don't think that the release version throws the dialogs (could be wrong).</p>
| 39,902
|
<p>How do I make <a href="http://logging.apache.org/log4net/index.html" rel="noreferrer">Log4net</a> only log Info level logs? Is that even possible? Can you only set a threshold? </p>
<p>This is what I have, and it logs Info and above as I would expect. Is there anything i can do to make it only log info?</p>
<pre class="lang-xml prettyprint-override"><code><logger name="BrokerCollection.Model.XmlDocumentCreationTask">
<appender-ref ref="SubmissionAppender"/>
<level value="Info" />
</logger>
</code></pre>
|
<p>Within the definition of the appender, I believe you can do something like this:</p>
<pre class="lang-xml prettyprint-override"><code><appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
<filter type="log4net.Filter.LevelRangeFilter">
<param name="LevelMin" value="INFO"/>
<param name="LevelMax" value="INFO"/>
</filter>
...
</appender>
</code></pre>
|
<p>you can use log4net.Filter.LevelMatchFilter.
other options can be found at
<a href="http://www.beefycode.com/post/log4net-tutorial-pt-7-filters.aspx" rel="nofollow noreferrer">log4net tutorial - filters</a></p>
<p>in ur appender section add</p>
<pre class="lang-xml prettyprint-override"><code><filter type="log4net.Filter.LevelMatchFilter">
<levelToMatch value="Info" />
<acceptOnMatch value="true" />
</filter>
</code></pre>
<p>the accept on match default is true so u can leave it out but if u set it to false u can filter out log4net filters</p>
| 2,786
|
<p>Here's one that has me perplexed. I'm trying to implement a basic Hibernate DAO structure, but am having a problem.</p>
<p>Here's the essential code:</p>
<pre><code>int startingCount = sfdao.count();
sfdao.create( sf );
SecurityFiling sf2 = sfdao.read( sf.getId() );
sfdao.delete( sf );
int endingCount = sfdao.count();
assertTrue( startingCount == endingCount );
assertTrue( sf.getId().longValue() == sf2.getId().longValue() );
assertTrue( sf.getSfSubmissionType().equals( sf2.getSfSubmissionType() ) );
assertTrue( sf.getSfTransactionNumber().equals( sf2.getSfTransactionNumber() ) );
</code></pre>
<p>It fails on the third assertTrue where it's trying to compare a value in sf to the corresponding value in sf2. Here's the exception:</p>
<pre><code>org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:86)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:140)
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:190)
at com.freightgate.domain.SecurityFiling_$$_javassist_7.getSfSubmissionType(SecurityFiling_$$_javassist_7.java)
at com.freightgate.dao.SecurityFilingTest.test(SecurityFilingTest.java:73)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:40)
</code></pre>
|
<p>The problem is that you are trying to access a collection in an object that is <a href="http://docs.jboss.org/hibernate/core/3.3/reference/en/html/objectstate.html" rel="noreferrer">detached</a>. You need to re-attach the object before accessing the collection to the current session. You can do that through</p>
<pre><code>session.update(object);
</code></pre>
<p>Using <code>lazy=false</code> is not a good solution because you are throwing away the Lazy Initialization feature of hibernate. When <code>lazy=false</code>, the collection is loaded in memory at the same time that the object is requested. This means that if we have a collection with 1000 items, they all will be loaded in memory, despite we are going to access them or not. And this is not good.</p>
<p>Please read this <a href="http://community.jboss.org/wiki/OpenSessioninView" rel="noreferrer">article</a> where it explains the problem, the possible solutions and why is implemented this way. Also, to understand Sessions and Transactions you must read <a href="http://community.jboss.org/wiki/Sessionsandtransactions" rel="noreferrer">this other article</a>.</p>
|
<p>If you are managing the Hibernate session manually, you may want to look into sessionFactory.getCurrentSession() and associated docs here:</p>
<p><a href="http://www.hibernate.org/hib_docs/v3/reference/en/html/architecture-current-session.html" rel="nofollow noreferrer">http://www.hibernate.org/hib_docs/v3/reference/en/html/architecture-current-session.html</a></p>
| 44,980
|
<p>My applications installer offers the user the ability to run the application as a service through use of the <code>srvany.exe</code> application. To remove the application on uninstall, I've been using the application <code>instsrv.exe</code> with the following command:</p>
<blockquote>
<p>instsrv "myservice" REMOVE</p>
</blockquote>
<p>On Windows Server 2003, I encounter error 1783.</p>
<p>Any ideas on what is causing this problem? Am I using the wrong approach for <code>Win2k3</code>?</p>
|
<p>I tried the same with Rk-Tools 2003 and 2000 and I get the same error both times.
But after removing the registry-parameters manually after the next reboot the services (I tried out several constellations) were gone.
Please think about stopping the service before(!) you're gonna delete the registry-entries, because otherwise the service will not accept any further commands.
Maybe this will help you.</p>
|
<p>First of all - references to instsrv.c is just an error message (it tells you where the error has actually happened in the source code). I think (but I am not sure) that this 1783 error occurs when it tries to enumerate services but hits an overflow error (too many services installed?)</p>
<p>A better approach would be to use sc.exe:</p>
<pre><code>SC STOP servicename
SC DELETE servicename
</code></pre>
| 27,103
|
<p>I'd like to use Doxygen to document legacy code that's a mix of C and x86 assembly language. The assembly language is not inline, but in separate assembly-only files. How can I document the assembly language portion?</p>
|
<p>See question 12 of the <a href="http://www.doxygen.nl/manual/faq.html" rel="nofollow noreferrer">Doxygen FAQ</a>. Are you dealing with pure assembly files, or inline assembly inside C sources? Assuming the former, you'll have to either write an input filter to transform the assembly code into something C-like (easier), or write a new parser (much harder).</p>
|
<p>See question 12 of the <a href="http://www.doxygen.nl/manual/faq.html" rel="nofollow noreferrer">Doxygen FAQ</a>. Are you dealing with pure assembly files, or inline assembly inside C sources? Assuming the former, you'll have to either write an input filter to transform the assembly code into something C-like (easier), or write a new parser (much harder).</p>
| 33,501
|
<p>I would like to create a page where all images which reside on my website are listed with title and alternative representation.</p>
<p>I already wrote me a little program to find and load all HTML files, but now I am stuck at how to extract <code>src</code>, <code>title</code> and <code>alt</code> from this HTML:</p>
<pre><code><img <b>src</b>="/image/fluffybunny.jpg" <b>title</b>="Harvey the bunny" <b>alt</b>="a cute little fluffy bunny" /></code></pre>
<p>I guess this should be done with some regex, but since the order of the tags may vary, and I need all of them, I don't really know how to parse this in an elegant way (I could do it the hard char by char way, but that's painful).</p>
|
<h2>EDIT : now that I know better</h2>
<p>Using regexp to solve this kind of problem is <a href="https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454">a bad idea</a> and will likely lead in unmaintainable and unreliable code. Better use an <a href="http://simplehtmldom.sourceforge.net/" rel="noreferrer">HTML parser</a>. </p>
<h2>Solution With regexp</h2>
<p>In that case it's better to split the process into two parts :</p>
<ul>
<li>get all the img tag</li>
<li>extract their metadata</li>
</ul>
<p>I will assume your doc is not xHTML strict so you can't use an XML parser. E.G. with this web page source code :</p>
<pre><code>/* preg_match_all match the regexp in all the $html string and output everything as
an array in $result. "i" option is used to make it case insensitive */
preg_match_all('/<img[^>]+>/i',$html, $result);
print_r($result);
Array
(
[0] => Array
(
[0] => <img src="/Content/Img/stackoverflow-logo-250.png" width="250" height="70" alt="logo link to homepage" />
[1] => <img class="vote-up" src="/content/img/vote-arrow-up.png" alt="vote up" title="This was helpful (click again to undo)" />
[2] => <img class="vote-down" src="/content/img/vote-arrow-down.png" alt="vote down" title="This was not helpful (click again to undo)" />
[3] => <img src="http://www.gravatar.com/avatar/df299babc56f0a79678e567e87a09c31?s=32&d=identicon&r=PG" height=32 width=32 alt="gravatar image" />
[4] => <img class="vote-up" src="/content/img/vote-arrow-up.png" alt="vote up" title="This was helpful (click again to undo)" />
[...]
)
)
</code></pre>
<p>Then we get all the img tag attributes with a loop :</p>
<pre><code>$img = array();
foreach( $result as $img_tag)
{
preg_match_all('/(alt|title|src)=("[^"]*")/i',$img_tag, $img[$img_tag]);
}
print_r($img);
Array
(
[<img src="/Content/Img/stackoverflow-logo-250.png" width="250" height="70" alt="logo link to homepage" />] => Array
(
[0] => Array
(
[0] => src="/Content/Img/stackoverflow-logo-250.png"
[1] => alt="logo link to homepage"
)
[1] => Array
(
[0] => src
[1] => alt
)
[2] => Array
(
[0] => "/Content/Img/stackoverflow-logo-250.png"
[1] => "logo link to homepage"
)
)
[<img class="vote-up" src="/content/img/vote-arrow-up.png" alt="vote up" title="This was helpful (click again to undo)" />] => Array
(
[0] => Array
(
[0] => src="/content/img/vote-arrow-up.png"
[1] => alt="vote up"
[2] => title="This was helpful (click again to undo)"
)
[1] => Array
(
[0] => src
[1] => alt
[2] => title
)
[2] => Array
(
[0] => "/content/img/vote-arrow-up.png"
[1] => "vote up"
[2] => "This was helpful (click again to undo)"
)
)
[<img class="vote-down" src="/content/img/vote-arrow-down.png" alt="vote down" title="This was not helpful (click again to undo)" />] => Array
(
[0] => Array
(
[0] => src="/content/img/vote-arrow-down.png"
[1] => alt="vote down"
[2] => title="This was not helpful (click again to undo)"
)
[1] => Array
(
[0] => src
[1] => alt
[2] => title
)
[2] => Array
(
[0] => "/content/img/vote-arrow-down.png"
[1] => "vote down"
[2] => "This was not helpful (click again to undo)"
)
)
[<img src="http://www.gravatar.com/avatar/df299babc56f0a79678e567e87a09c31?s=32&d=identicon&r=PG" height=32 width=32 alt="gravatar image" />] => Array
(
[0] => Array
(
[0] => src="http://www.gravatar.com/avatar/df299babc56f0a79678e567e87a09c31?s=32&d=identicon&r=PG"
[1] => alt="gravatar image"
)
[1] => Array
(
[0] => src
[1] => alt
)
[2] => Array
(
[0] => "http://www.gravatar.com/avatar/df299babc56f0a79678e567e87a09c31?s=32&d=identicon&r=PG"
[1] => "gravatar image"
)
)
[..]
)
)
</code></pre>
<p>Regexps are CPU intensive so you may want to cache this page. If you have no cache system, you can tweak your own by using <a href="http://fr2.php.net/manual/fr/function.ob-start.php" rel="noreferrer">ob_start</a> and loading / saving from a text file.</p>
<h2>How does this stuff work ?</h2>
<p>First, we use <a href="http://fr2.php.net/manual/fr/function.preg-match-all.php" rel="noreferrer">preg_ match_ all</a>, a function that gets every string matching the pattern and ouput it in it's third parameter.</p>
<p>The regexps :</p>
<pre><code><img[^>]+>
</code></pre>
<p>We apply it on all html web pages. It can be read as <em>every string that starts with "<code><img</code>", contains non ">" char and ends with a ></em>.</p>
<pre><code>(alt|title|src)=("[^"]*")
</code></pre>
<p>We apply it successively on each img tag. It can be read as <em>every string starting with "alt", "title" or "src", then a "=", then a ' " ', a bunch of stuff that are not ' " ' and ends with a ' " '. Isolate the sub-strings between ()</em>. </p>
<p>Finally, every time you want to deal with regexps, it handy to have good tools to quickly test them. Check this <a href="http://regex.larsolavtorvik.com/" rel="noreferrer">online regexp tester</a>.</p>
<p>EDIT : answer to the first comment.</p>
<p>It's true that I did not think about the (hopefully few) people using single quotes.</p>
<p>Well, if you use only ', just replace all the " by '. </p>
<p>If you mix both. First you should slap yourself :-), then try to use ("|') instead or " and [^ø] to replace [^"].</p>
|
<p>Here is THE solution, in PHP:</p>
<p>Just download QueryPath, and then do as follows:</p>
<pre><code>$doc= qp($myHtmlDoc);
foreach($doc->xpath('//img') as $img) {
$src= $img->attr('src');
$title= $img->attr('title');
$alt= $img->attr('alt');
}
</code></pre>
<p>That's it, you're done !</p>
| 16,742
|
<p>I have a table, call it TBL. It has two columns,call them A and B. Now in the query I require one column as A and other column should be a comma seprated list of all B's which are against A in TBL.
e.g. TBL is like this</p>
<p>1 Alpha</p>
<p>2 Beta</p>
<p>1 Gamma</p>
<p>1 Delta</p>
<p>Result of query should be </p>
<p>1 Alpha,Gamma,Delta</p>
<p>2 Beta</p>
<p>This type of thing is very easy to do with cursors in stored procedure. But I am not able to do it through MS Access, because apparently it does not support stored procedures.
Is there a way to run stored procedure in MS access? or is there a way through SQL to run this type of query</p>
|
<p>You can concatenate the records with a User Defined Function (UDF).</p>
<p>The code below can be pasted 'as is' into a standard module. The SQL for you example would be:</p>
<pre><code>SELECT tbl.A, Concatenate("SELECT B FROM tbl
WHERE A = " & [A]) AS ConcA
FROM tbl
GROUP BY tbl.A
</code></pre>
<p>This code is by DHookom, Access MVP, and is taken from <a href="http://www.tek-tips.com/faqs.cfm?fid=4233" rel="noreferrer">http://www.tek-tips.com/faqs.cfm?fid=4233</a></p>
<pre><code>Function Concatenate(pstrSQL As String, _
Optional pstrDelim As String = ", ") _
As String
'example
'tblFamily with FamID as numeric primary key
'tblFamMem with FamID, FirstName, DOB,...
'return a comma separated list of FirstNames
'for a FamID
' John, Mary, Susan
'in a Query
'(This SQL statement assumes FamID is numeric)
'===================================
'SELECT FamID,
'Concatenate("SELECT FirstName FROM tblFamMem
' WHERE FamID =" & [FamID]) as FirstNames
'FROM tblFamily
'===================================
'
'If the FamID is a string then the SQL would be
'===================================
'SELECT FamID,
'Concatenate("SELECT FirstName FROM tblFamMem
' WHERE FamID =""" & [FamID] & """") as FirstNames
'FROM tblFamily
'===================================
'======For DAO uncomment next 4 lines=======
'====== comment out ADO below =======
'Dim db As DAO.Database
'Dim rs As DAO.Recordset
'Set db = CurrentDb
'Set rs = db.OpenRecordset(pstrSQL)
'======For ADO uncomment next two lines=====
'====== comment out DAO above ======
Dim rs As New ADODB.Recordset
rs.Open pstrSQL, CurrentProject.Connection, _
adOpenKeyset, adLockOptimistic
Dim strConcat As String 'build return string
With rs
If Not .EOF Then
.MoveFirst
Do While Not .EOF
strConcat = strConcat & _
.Fields(0) & pstrDelim
.MoveNext
Loop
End If
.Close
End With
Set rs = Nothing
'====== uncomment next line for DAO ========
'Set db = Nothing
If Len(strConcat) > 0 Then
strConcat = Left(strConcat, _
Len(strConcat) - Len(pstrDelim))
End If
Concatenate = strConcat
End Function
</code></pre>
|
<p>Well, you can use a Recordset object to loop through your query in VBA, concatenating field values based on whatever criteria you need.</p>
<p>If you want to return the results as strings, you'll be fine. If you want to return them as a query, that will be more complicated. You might have to create a temporary table and store the results in there so you can return them as a table or query.</p>
| 28,499
|
<p>Are there any known methods of finding peers without using a dedicated central server?</p>
<p>ie: If I have peers which are disconnecting and reconnecting to the internet but getting a new IP address each time, and I want to connect to them without setting up a dedicated server to register with.</p>
<p>I was thinking about using peers email address to send a manifest of connected peers periodically, with some sort of timecode, negating the need for a dedicated server. This would be a fallback if none of the peers could be connected to after trying all the previously known peer addresses. But existing models of finding peers would be preferable.</p>
|
<p>There's no way around having to know at least one initial peer to discover more.
Fully P2P protocols, such as Gnutella or Gnutella2, or the simpler Overnet (made famous by Storm Worm), are based on each client having a start-up list of a few peers. These can come off a web-based automated tracker for example. The client will discover the whole network or portions of it by asking other peers for more addresses, for example when delegating a file search.</p>
<p>If you truly can't have any kind of a centralized resource, the best you can do is find the first peer through broadcasted messages and ultimately IP address scanning. The first approach is well-meaning but in at least 98% of cases won't yield any results. The later approach, of course, is abusing the internet, as well as illegal in most countries.</p>
<p>I really would rethink having some kind of a central tracker. It can be something as simple as a PHP script on a webserver (the gnutella network, today, is held up by ten-twenty such scripts, hosted by people who don't even know each other). And this sure is more lightweight than email (which, due to spam filters at the very least, would not work anyway).</p>
|
<p>This is a typical use of a distributed hash table algorithm. I'd suggest looking at something like pastry. It uses a overlay network (Application layer network) on top of other layers. </p>
<p>Each node has a GUID which is used to route requests across the peer network. </p>
| 40,023
|
<p>I develop and maintain small intranet web apps(JSP and Resin).</p>
<p>Some users takes so much time to complete the forms that,
when they submit, they lose all their input data because of session timeout.</p>
<p>Currently I prolonged session timeout to 30 minutes and
display count-down clock till session timeout on top of the page, but,
I think their must be better ways to
protect user inputs.</p>
<p>What is the best practices?</p>
<hr>
<p><strong>Addendum</strong>
Our users make several kind of reports with the web-app,
and the whole contents of each report are stored in a JavaBean stored in the session.</p>
<p>As suggested by some, Ajax or iframe should do the quick fix.</p>
<p>I now know that it is better not to abuse session with heavy objects,
but I'm not sure how best to refactor current mess.
Some people suggested to make the web-app <em>stateless</em>.
Any suggestion for refactoring is welcome.</p>
|
<p>This may or may not be the case with your framework, but I think that if your page just uses AJAX to call the server every five minutes (or whatever), then that will keep your user's session alive. You don't even have to do a partial save of your form this way.</p>
|
<p>You could store the data in a cookie every once in a while, use Gears as a temporary storage (if the data is complex or requires more than 4K storage) or send the temporary data to the server every n second using AJAX. </p>
| 31,435
|
<p>My question is related to the command pattern, where we have the following abstraction (C# code) :</p>
<pre><code>public interface ICommand
{
void Execute();
}
</code></pre>
<p>Let's take a simple concrete command, which aims to delete an entity from our application. A <code>Person</code> instance, for example.</p>
<p>I'll have a <code>DeletePersonCommand</code>, which implements <code>ICommand</code>. This command needs the <code>Person</code> to delete as a parameter, in order to delete it when <code>Execute</code> method is called.</p>
<p>What is the best way to manage parametrized commands ? How to pass parameters to commands, before executing them ?</p>
|
<p>You'll need to associate the parameters with the command object, either by constructor or setter injection (or equivalent). Perhaps something like this:</p>
<pre><code>public class DeletePersonCommand: ICommand
{
private Person personToDelete;
public DeletePersonCommand(Person personToDelete)
{
this.personToDelete = personToDelete;
}
public void Execute()
{
doSomethingWith(personToDelete);
}
}
</code></pre>
|
<p>Have "Person" implement some sort of IDeletable interface, then make the command take whatever base class or interface your entities use. That way, you can make a DeleteCommand, which tries to cast the entity to an IDeletable, and if that works, call .Delete</p>
<pre><code>public class DeleteCommand : ICommand
{
public void Execute(Entity entity)
{
IDeletable del = entity as IDeletable;
if (del != null) del.Delete();
}
}
</code></pre>
| 13,051
|
<p>I am looking to protect the code of my Firefox extension because it has server calls in it that no would be a security risk if someone could make them outside of the extension. Any suggestions on how to encrypt it?</p>
|
<p>This is basically impossible. You want to give executable code to an untrusted client that has "secret" calls in it, yet not let the client know the secrets? How, then, is it going to execute the code?</p>
<p>At some point, it must be decrypted. Which means the client has everything it needs to perform the decryption, which means a user can do it, and build a malicious version of your extension.</p>
<p>The only choice you have is to redesign such that vulnerable services are not publically exposed.</p>
|
<p>You could use xauth, which is a variant of OAuth designed to solve this type of problem. Twitter uses xauth: <a href="http://dev.twitter.com/pages/xauth" rel="nofollow">http://dev.twitter.com/pages/xauth</a></p>
<p>Additionally, you could obfuscate your Javascript code, or even write it in C (as a NPAPI plugin).</p>
| 35,545
|
<p>I am a developer for a .net application that uses ClickOnce for deployment. I have deployed it over 60 times and computers have not had any issues downloading the latest release. However, when I deployed this morning, the following error occurs when computers with Office 2007 installed tries to start the application:</p>
<blockquote>
<p>Unable to install or run the application. The application requires that assembly stdole Version 7.0.3300.0 be installed in the Global Assembly Cache (GAC) first. Please contact your system administrator.</p>
</blockquote>
<p>However, computers with Office 2003 can start the application with no problem.</p>
<p>Does anyone have any recommendations on resolving this issue?</p>
|
<p>As far as I know this version of stdole is removed when Office2k7 is installed. You could install it individually via gacutil on all target machines <em>or</em> somehow include it via the ClickOnce package bootstrapper. On a mac right now so I can't test. </p>
|
<p>I am not sure about your particular problem, but the Office 12 version of the stdole library is different (and -in my experience- not always backwards compatible) than then one you have when you use Office 2003. </p>
<p>We use a wrapper around the Office DLLs to use the Mailmerge features Office has to offer and, believe it or not, Microsoft changed the interfaces <strong>again</strong>, therefore we have to compile <em>two</em> different wrappers, linked against <em>two</em> different office versions. In short, a PITA.</p>
<p>I am not coding against MS office again until they don't provide a Managed library. </p>
<p>Despite the rant, I think that you should install Office 12 in your computer and test from there. You'll notice that all the Office stuff is different. If you can make it work under Office 12 it <strong>may</strong> be compatible with machines with Office 11 (also known as 2003), but don't count on it and test it before deploying anything.</p>
<p>I don't think that this has anything to do with ClickOnce; it's more a GAC/OfficeVersion issue. Also, check for possible Vista problems, as the UAC and the DEP stuff tend to interfere with the way "old" applications used to work. </p>
| 14,947
|
<p>I want to draw spinner controls, such as those found on a NumericUpDown, on a custom component. If I want to draw a drop-down button, I can use ComboBoxRenderer. Is there an equivalent of ComboBoxRenderer for NumericUpDown?</p>
|
<p>Turns out there is. See the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.visualstyles.visualstyleelement.spin.aspx" rel="nofollow noreferrer">VisualStyleElement.Spin class</a>.</p>
|
<p>I do not think a ComboBoxRenderer exists in the Windows Forms namespace. You need to directly draw the UpDown control arrows (spin buttons) using interop and the Theme API. I don't have a complete sample for you, but you'll need</p>
<pre><code>[DllImport("uxtheme.dll", ExactSpelling = true, CharSet = CharSet.Unicode)]
public static extern IntPtr OpenThemeData(IntPtr hWnd, String classList);
[DllImport("uxtheme", ExactSpelling = true)]
public extern static Int32 DrawThemeBackground(IntPtr hTheme, IntPtr hdc, int iPartId, int iStateId, ref RECT pRect, IntPtr pClipRect);
[DllImport("uxtheme.dll", ExactSpelling = true)]
public extern static Int32 CloseThemeData(IntPtr hTheme);
</code></pre>
<p>and you can find the required parts and states in <a href="http://msdn.microsoft.com/en-us/library/bb773210(VS.85).aspx" rel="nofollow noreferrer">this page</a> (look for the SPIN style class and its associated parts and states).</p>
| 30,586
|
<p>Up until now I have been using std::string in my C++ applications for embedded system (routers, switches, telco gear, etc.).</p>
<p>For the next project, I am considering to switch from std::string to std::wstring for Unicode support. This would, for example, allow end-users to use Chinese characters in the command line interface (CLI).</p>
<p>What complications / headaches / surprises should I expect? What, for example, if I use a third-party library which still uses std::string?</p>
<p>Since support for international strings isn't that strong of a requirement for the type of embedded systems that I work on, I would only do it if it isn't going to cause major headaches.</p>
|
<p>Not to my knowledge.</p>
<p>To get around this, I manage my stored procedures in a Visual Studio database project. Every stored procedure is in its own file and has a drop command at the top of the file. When I update the stored through Visual Studio, the database's created date is updated in the database because of the drop/create statement. I am able to use the created date in SQL Server 2000 as the last modified date in this manner.</p>
|
<p>From all the research I've done on this in the past, I unfortunately have to say no. SQL Server 2000 simply does not store this information, and I've never seen any solution for retrieving it.</p>
<p>There are a few alternative methods, but they all involve user intervention. Besides keeping stored procedure scripts in a source control system, I think the next best approach is to use comments inside the stored procedure. Not ideal, but it's better than nothing if you want to track what gets updated.</p>
| 19,819
|
<p>I recently started facelets development, and a couple of days ago made my first useful custom tag. Now I would like to have auto-completion support in eclipse, like I have for standard taglibs like h, c and ui.</p>
<p>Is there any easy way (less than 30 min work) to enable tool support for custom tags?</p>
<p>I'm using eclipse 3.4 with jboss tools.</p>
|
<p>You can use Jboss Tools 3.0M3 or newer.
About it support of custom facelets you can find information here <a href="http://www.jboss.org/index.html?module=bb&op=viewtopic&t=154315" rel="nofollow noreferrer">Jboss Tools Forum</a></p>
|
<p>What version of Eclipse are you using?</p>
<p>My current version (Version: 3.4.0, Build id: I20080617-2000, with WTP)has autocompletion for any taglib added as a directive on my JSP page (even if the current JSP file does a <code><%@ include file="..." %></code> to the actual file with the taglib declarations in it), even the non-standard ones. </p>
<p>For example, Eclipse will autocomplete any <code><form:blah></code> tags for me if I have the following declaration:</p>
<pre><code><%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
</code></pre>
| 38,415
|
<p>I want to automate a Windows 2000+ server reboot process using Task Scheduler or similar tool to remotely reboot a server and wait for it to come back up. I can issue <code>shutdown</code> or <code>psshutdown</code> to remotely reboot, but I want something better than <code>sleep</code> to wait for it to come back. I need to verify it is back online within <code>n</code> minutes or throw an error.</p>
<p>By 'back online', I would like to verify more than just that it can be pinged, but perhaps its RFC service is responding or some other determinate vital sign.</p>
<p>I'd prefer an NT script approach, but I'm not ruling out writing a custom tool to do this.</p>
<p>Any ideas?</p>
|
<p>Your remote restart script could start the server, wait n minutes, then query your RFC service. You could also have a local script on the server do the same thing.</p>
|
<p>You can poll some core service to see if it has started:</p>
<pre><code>sc "\\server_name" query EventSystem
</code></pre>
| 8,062
|
<p>Every method I write to encode a string in Java using 3DES can't be decrypted back to the original string. Does anyone have a simple code snippet that can just encode and then decode the string back to the original string?</p>
<p>I know I'm making a very silly mistake somewhere in this code. Here's what I've been working with so far:</p>
<p>** note, I am not returning the BASE64 text from the encrypt method, and I am not base64 un-encoding in the decrypt method because I was trying to see if I was making a mistake in the BASE64 part of the puzzle.</p>
<pre><code>public class TripleDESTest {
public static void main(String[] args) {
String text = "kyle boon";
byte[] codedtext = new TripleDESTest().encrypt(text);
String decodedtext = new TripleDESTest().decrypt(codedtext);
System.out.println(codedtext);
System.out.println(decodedtext);
}
public byte[] encrypt(String message) {
try {
final MessageDigest md = MessageDigest.getInstance("md5");
final byte[] digestOfPassword = md.digest("HG58YZ3CR9".getBytes("utf-8"));
final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
for (int j = 0, k = 16; j < 8;)
{
keyBytes[k++] = keyBytes[j++];
}
final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
final byte[] plainTextBytes = message.getBytes("utf-8");
final byte[] cipherText = cipher.doFinal(plainTextBytes);
final String encodedCipherText = new sun.misc.BASE64Encoder().encode(cipherText);
return cipherText;
}
catch (java.security.InvalidAlgorithmParameterException e) { System.out.println("Invalid Algorithm"); }
catch (javax.crypto.NoSuchPaddingException e) { System.out.println("No Such Padding"); }
catch (java.security.NoSuchAlgorithmException e) { System.out.println("No Such Algorithm"); }
catch (java.security.InvalidKeyException e) { System.out.println("Invalid Key"); }
catch (BadPaddingException e) { System.out.println("Invalid Key");}
catch (IllegalBlockSizeException e) { System.out.println("Invalid Key");}
catch (UnsupportedEncodingException e) { System.out.println("Invalid Key");}
return null;
}
public String decrypt(byte[] message) {
try
{
final MessageDigest md = MessageDigest.getInstance("md5");
final byte[] digestOfPassword = md.digest("HG58YZ3CR9".getBytes("utf-8"));
final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
for (int j = 0, k = 16; j < 8;)
{
keyBytes[k++] = keyBytes[j++];
}
final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
final Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
decipher.init(Cipher.DECRYPT_MODE, key, iv);
//final byte[] encData = new sun.misc.BASE64Decoder().decodeBuffer(message);
final byte[] plainText = decipher.doFinal(message);
return plainText.toString();
}
catch (java.security.InvalidAlgorithmParameterException e) { System.out.println("Invalid Algorithm"); }
catch (javax.crypto.NoSuchPaddingException e) { System.out.println("No Such Padding"); }
catch (java.security.NoSuchAlgorithmException e) { System.out.println("No Such Algorithm"); }
catch (java.security.InvalidKeyException e) { System.out.println("Invalid Key"); }
catch (BadPaddingException e) { System.out.println("Invalid Key");}
catch (IllegalBlockSizeException e) { System.out.println("Invalid Key");}
catch (UnsupportedEncodingException e) { System.out.println("Invalid Key");}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
</code></pre>
|
<p>Your code was fine except for the Base 64 encoding bit (which you mentioned was a test), the reason the output may not have made sense is that you were displaying a raw byte array (doing toString() on a byte array returns its internal Java reference, not the String representation of the <strong>contents</strong>). Here's a version that's just a teeny bit cleaned up and which prints "kyle boon" as the decoded string:</p>
<pre><code>import java.security.MessageDigest;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class TripleDESTest {
public static void main(String[] args) throws Exception {
String text = "kyle boon";
byte[] codedtext = new TripleDESTest().encrypt(text);
String decodedtext = new TripleDESTest().decrypt(codedtext);
System.out.println(codedtext); // this is a byte array, you'll just see a reference to an array
System.out.println(decodedtext); // This correctly shows "kyle boon"
}
public byte[] encrypt(String message) throws Exception {
final MessageDigest md = MessageDigest.getInstance("md5");
final byte[] digestOfPassword = md.digest("HG58YZ3CR9"
.getBytes("utf-8"));
final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
for (int j = 0, k = 16; j < 8;) {
keyBytes[k++] = keyBytes[j++];
}
final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
final byte[] plainTextBytes = message.getBytes("utf-8");
final byte[] cipherText = cipher.doFinal(plainTextBytes);
// final String encodedCipherText = new sun.misc.BASE64Encoder()
// .encode(cipherText);
return cipherText;
}
public String decrypt(byte[] message) throws Exception {
final MessageDigest md = MessageDigest.getInstance("md5");
final byte[] digestOfPassword = md.digest("HG58YZ3CR9"
.getBytes("utf-8"));
final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
for (int j = 0, k = 16; j < 8;) {
keyBytes[k++] = keyBytes[j++];
}
final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
final Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
decipher.init(Cipher.DECRYPT_MODE, key, iv);
// final byte[] encData = new
// sun.misc.BASE64Decoder().decodeBuffer(message);
final byte[] plainText = decipher.doFinal(message);
return new String(plainText, "UTF-8");
}
}
</code></pre>
|
<pre><code>import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.util.Base64;
import java.util.Base64.Encoder;
/**
*
* @author shivshankar pal
*
* this code is working properly. doing proper encription and decription
note:- it will work only with jdk8
*
*
*/
public class TDes {
private static byte[] key = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x02,
0x02, 0x02, 0x02, 0x02, 0x02, 0x02 };
private static byte[] keyiv = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00 };
public static String encode(String args) {
System.out.println("plain data==> " + args);
byte[] encoding;
try {
encoding = Base64.getEncoder().encode(args.getBytes("UTF-8"));
System.out.println("Base64.encodeBase64==>" + new String(encoding));
byte[] str5 = des3EncodeCBC(key, keyiv, encoding);
System.out.println("des3EncodeCBC==> " + new String(str5));
byte[] encoding1 = Base64.getEncoder().encode(str5);
System.out.println("Base64.encodeBase64==> " + new String(encoding1));
return new String(encoding1);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static String decode(String args) {
try {
System.out.println("encrypted data==>" + new String(args.getBytes("UTF-8")));
byte[] decode = Base64.getDecoder().decode(args.getBytes("UTF-8"));
System.out.println("Base64.decodeBase64(main encription)==>" + new String(decode));
byte[] str6 = des3DecodeCBC(key, keyiv, decode);
System.out.println("des3DecodeCBC==>" + new String(str6));
String data=new String(str6);
byte[] decode1 = Base64.getDecoder().decode(data.trim().getBytes("UTF-8"));
System.out.println("plaintext==> " + new String(decode1));
return new String(decode1);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "u mistaken in try block";
}
private static byte[] des3EncodeCBC(byte[] key, byte[] keyiv, byte[] data) {
try {
Key deskey = null;
DESedeKeySpec spec = new DESedeKeySpec(key);
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
deskey = keyfactory.generateSecret(spec);
Cipher cipher = Cipher.getInstance("desede/ CBC/PKCS5Padding");
IvParameterSpec ips = new IvParameterSpec(keyiv);
cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);
byte[] bout = cipher.doFinal(data);
return bout;
} catch (Exception e) {
System.out.println("methods qualified name" + e);
}
return null;
}
private static byte[] des3DecodeCBC(byte[] key, byte[] keyiv, byte[] data) {
try {
Key deskey = null;
DESedeKeySpec spec = new DESedeKeySpec(key);
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
deskey = keyfactory.generateSecret(spec);
Cipher cipher = Cipher.getInstance("desede/ CBC/NoPadding");//PKCS5Padding NoPadding
IvParameterSpec ips = new IvParameterSpec(keyiv);
cipher.init(Cipher.DECRYPT_MODE, deskey, ips);
byte[] bout = cipher.doFinal(data);
return bout;
} catch (Exception e) {
System.out.println("methods qualified name" + e);
}
return null;
}
}
</code></pre>
| 4,057
|
<p>We have a couple of developers asking for <code>allow_url_fopen</code> to be enabled on our server. What's the norm these days and if <code>libcurl</code> is enabled is there really any good reason to allow?</p>
<p>Environment is: Windows 2003, PHP 5.2.6, FastCGI</p>
|
<p>You definitely want <code>allow_url_include</code> set to Off, which mitigates many of the risks of <code>allow_url_fopen</code> as well.</p>
<p>But because not all versions of PHP have <code>allow_url_include</code>, best practice for many is to turn off fopen. Like with all features, the reality is that if you don't need it for your application, disable it. If you do need it, the curl module probably can do it better, and refactoring your application to use curl to disable <code>allow_url_fopen</code> may deter the least determined cracker.</p>
|
<p>The big problem is that <strong>allow_url_fopen is not more secured</strong>, so if you want to save file from a url using curl, you must pass from fopen/file_get to save the file. </p>
<blockquote>
<ul>
<li>CURL is only good to retrieve remote content from URL.
<strong>(allow_url_fopen not necessary)</strong></li>
<li>CURL must be added with Fopen or File_get if you want to save remote
file to your server.
<strong>(allow_url_fopen obligatory with CURL)</strong></li>
</ul>
</blockquote>
<p>Php must find other ways to make it more secured. </p>
| 15,519
|
<p>Exactly what the title says. Note, this is not about "<a href="https://stackoverflow.com/questions/216972/in-python-what-does-it-mean-if-an-object-is-scriptable-or-not">subscriptable</a>" objects.</p>
|
<p>A scriptable object is an object that records the operations done to it and it can store them as a "script" which can be replayed.</p>
<p>For example, see: <a href="https://svn.enthought.com/enthought/browser/AppTools/trunk/docs/source/appscripting/Introduction.rst" rel="nofollow noreferrer">Application Scripting Framework</a></p>
|
<p>A scriptable object is an object that records the operations done to it and it can store them as a "script" which can be replayed.</p>
<p>For example, see: <a href="https://svn.enthought.com/enthought/browser/AppTools/trunk/docs/source/appscripting/Introduction.rst" rel="nofollow noreferrer">Application Scripting Framework</a></p>
| 26,688
|
<p>I have noticed in phpMyAdmin you can click 'optimise' on tables, and it runs:</p>
<pre><code>OPTIMIZE TABLE table_name
</code></pre>
<p>What does this actually do?</p>
<p>Should I have some cron job running daily that runs OPTIMIZE TABLE on my tables?</p>
<p>Thank you</p>
|
<p>From <a href="http://www.informit.com/articles/article.aspx?p=29406&seqNum=3" rel="noreferrer">InformIT</a></p>
<blockquote>
<p>An optimized table structure is
different than a well-designed table.
Table structure optimization has to do
with reclaiming unused space after
deletions and basically cleaning up
the table after structural
modifications have been made. The
OPTIMIZE SQL command takes care of
this, using the following syntax:</p>
</blockquote>
<pre><code>OPTIMIZE TABLE table_name[,table_name]
</code></pre>
<p>Think of it like defragging your tables. A cron job might be a good idea, but do it during low/no load as it locks the tables.</p>
|
<p>I'd start with the <a href="http://dev.mysql.com/doc/refman/5.0/en/optimize-table.html" rel="nofollow noreferrer">MySQL documentation about that command</a>. After reading that, do you still have questions?</p>
| 46,280
|
<p>When using host headers to host multiple websites on the same IP address in IIS, is there any way of accessing that website from a browser running on the local machine?</p>
<p>This is normally required when a given web component only allows configuration from the local machine. It's also useful when things like ASP.Net's built in error handling isn't working and you can only view the error in the browser but don't want to allow remote users to see it. </p>
<p>This has baffled me for a while and everytime I come across it I end up giving up in frustration and reconfigure stuff so I can accomplish such tasks remotely.</p>
<p><strong>Added:</strong> @Ishmaeel - modifying hosts doesn't seem to help - you either get a 400 error (if all websites have host headers) or whichever site is configured without a host header.</p>
|
<p>Just an idea: Mapping the hostname to 127.0.0.1 in the hosts ($WINDOWS$\system32\drivers\etc) file may help. This way you should be able to pull up the local IIS site by typing the hostname as if it's a remote server</p>
|
<p>Maybe I am not understanding the question, but what's wrong with just typing in the URL for the website? If it's the matter of domain name resolution, you can point to the right DNS or put it in <a href="http://en.wikipedia.org/wiki/Hosts_file" rel="nofollow noreferrer">hosts</a> file.</p>
| 5,733
|
<p>Is there any meaningful distinction between:</p>
<pre><code>class A(object):
foo = 5 # some default value
</code></pre>
<p>vs.</p>
<pre><code>class B(object):
def __init__(self, foo=5):
self.foo = foo
</code></pre>
<p>If you're creating a lot of instances, is there any difference in performance or space requirements for the two styles? When you read the code, do you consider the meaning of the two styles to be significantly different?</p>
|
<p>There is a significant <em>semantic</em> difference (beyond performance considerations):</p>
<ul>
<li><strong>when the attribute is defined on the instance</strong> (which is what we usually do), there can be multiple objects referred to. <strong>Each gets a totally separate version of that attribute</strong>.</li>
<li><strong>when the attribute is defined on the class</strong>, there is only one underlying object referred to, so if operations on different instances of that class both attempt to set/(append/extend/insert/etc.) the attribute, then:
<ul>
<li>if the attribute is a <strong>builtin type</strong> (like int, float, boolean, string), operations on one object will overwrite (clobber) the value</li>
<li>if the attribute is a <strong>mutable type</strong> (like a list or a dict), we will get unwanted leakage.</li>
</ul>
</li>
</ul>
<p>For example:</p>
<pre><code>>>> class A: foo = []
>>> a, b = A(), A()
>>> a.foo.append(5)
>>> b.foo
[5]
>>> class A:
... def __init__(self): self.foo = []
>>> a, b = A(), A()
>>> a.foo.append(5)
>>> b.foo
[]
</code></pre>
|
<p>There is one more situation. </p>
<p>Class and instance attributes is <strong>Descriptor</strong>.</p>
<pre><code># -*- encoding: utf-8 -*-
class RevealAccess(object):
def __init__(self, initval=None, name='var'):
self.val = initval
self.name = name
def __get__(self, obj, objtype):
return self.val
class Base(object):
attr_1 = RevealAccess(10, 'var "x"')
def __init__(self):
self.attr_2 = RevealAccess(10, 'var "x"')
def main():
b = Base()
print("Access to class attribute, return: ", Base.attr_1)
print("Access to instance attribute, return: ", b.attr_2)
if __name__ == '__main__':
main()
</code></pre>
<p>Above will output:</p>
<pre><code>('Access to class attribute, return: ', 10)
('Access to instance attribute, return: ', <__main__.RevealAccess object at 0x10184eb50>)
</code></pre>
<p><strong>The same type of instance access through class or instance return different result!</strong></p>
<p>And i found in <a href="https://docs.python.org/2/c-api/object.html#c.PyObject_GenericGetAttr" rel="nofollow noreferrer">c.PyObject_GenericGetAttr definition</a>,and a great <a href="https://medium.com/stepping-through-the-cpython-interpreter/how-does-attribute-access-work-d19371898fee" rel="nofollow noreferrer">post</a>.</p>
<h2>Explain</h2>
<blockquote>
<p>If the attribute is found in the dictionary of the classes which make up.
the objects MRO, then check to see if the attribute being looked up points to a Data Descriptor (which is nothing more that a class implementing both the <code>__get__</code> and the <code>__set__</code> methods).
If it does, resolve the attribute lookup by calling the <code>__get__</code> method of the Data Descriptor (lines 28–33).</p>
</blockquote>
| 25,368
|
<p>I need to be able to launch a process and read the output into a variable. Then based on the return of the command I can choose to show the full output or just a selected subset.</p>
<p>So to be clear, I want to launch a text based process (psexec actually) and read the output from that command (stdout, stderr, etc) into a variable rather than have it directly outputted to the console.</p>
|
<p>You left off some details regarding what kind of process, but I think <a href="http://blogs.msdn.com/powershell/archive/2007/01/16/managing-processes-in-powershell.aspx" rel="nofollow noreferrer">this article</a> from the Powershell Team Blog has whatever you'd like to do, either from piping the executable's output somewhere or utilizing <code>System.Diagnostics.Process</code>.</p>
<p>Now that the second option sounds like what you want to do, you can use the <code>ProcessStartInfo</code> class to feed in <code>true</code> as the <code>RedirectStandardOutput</code> property, and then read from the <code>StandardOutput</code> property of the <code>Process</code> object to do whatever you want with the output. <code>StandardError</code> works identically.</p>
|
<p>As far as reading stuff into variables is concerned, you should just be able to do something like</p>
<pre><code>$output = ps
</code></pre>
<p>This will only capture stdout, though, not the verbose, warning or error streams. You can get the exit code of the previous command by testing the special variable <code>$?</code>. </p>
<p>I think a little more information would be of use to provide a more complete answer, but hopefully this is some way towards what you're looking for. </p>
| 28,187
|
<p>Within the last year I have become addicted to subversion. I am an only developer and I also work on a few of my own projects. With SVN its really easy to manage everything - and because it is hosted on an online server though HTTPS I can access my code from anywhere. It is also great for deploying code to our production/development servers.</p>
<p>My point is that it does everything that I need it to do and has never failed me.</p>
<p>Is there anything better? Am I missing some feature in another product that I could be using to make my life easier? I am always all about using the best software out there and have no problem migrating to new technologies.</p>
<p>I have heard of GIT and have done some research. I plan on giving that a try but while I am messing with that, are there another other source control systems that are considered "industry standard" and do they do things better then SVN?</p>
|
<p>Git, Mercurial and Bazaar are distributed control systems that operate of the idea that you aren't always connected to the Net, and that there need not be one central version of the repository.</p>
<p>If you're doing a lot of detached work, sometimes called "airplane mode", as in you're on an airplane and can't commit, take a look at Bazaar. I've found it easier to acclimate to than Git or Mercurial.</p>
<p>If you're always doing work connected to the Net, and you're the only developer, then you can probably stick with Subversion.</p>
<p>Also, please consider the value of <a href="http://xoa.petdance.com/How_to:_Keep_your_home_directory_in_Subversion" rel="noreferrer">keeping your home directory in Subversion</a>.</p>
|
<p>If SVN addresses all of your needs then I don't see the reason for change.
If curiosity is the driver of your quest for a different source control then I would recommend reading about git or other distributed scm solution and try to figure out if it's worth the investment in order to switch (which i doubt it is in your situation).</p>
| 27,719
|
<p>If I have something like a UILabel linked to a xib file, do I need to release it on dealloc of my view? The reason I ask is because I don't alloc it, which makes me think I don't need to release it either?
eg (in the header):</p>
<pre><code>IBOutlet UILabel *lblExample;
</code></pre>
<p>in the implementation:</p>
<pre><code>....
[lblExample setText:@"whatever"];
....
-(void)dealloc{
[lblExample release];//?????????
}
</code></pre>
|
<p>If you follow what is now considered to be best practice, you <em>should</em> release outlet properties, because you should have retained them in the set accessor:</p>
<pre><code>@interface MyController : MySuperclass {
Control *uiElement;
}
@property (nonatomic, retain) IBOutlet Control *uiElement;
@end
@implementation MyController
@synthesize uiElement;
- (void)dealloc {
[uiElement release];
[super dealloc];
}
@end
</code></pre>
<p>The advantage of this approach is that it makes the memory management semantics explicit and clear, <em>and it works consistently across all platforms for all nib files</em>.</p>
<p>Note: The following comments apply only to iOS prior to 3.0. With 3.0 and later, you should instead simply nil out property values in viewDidUnload.</p>
<p>One consideration here, though, is when your controller might dispose of its user interface and reload it dynamically on demand (for example, if you have a view controller that loads a view from a nib file, but on request -- say under memory pressure -- releases it, with the expectation that it can be reloaded if the view is needed again). In this situation, you want to make sure that when the main view is disposed of you also relinquish ownership of any other outlets so that they too can be deallocated. For UIViewController, you can deal with this issue by overriding <code>setView:</code> as follows:</p>
<pre><code>- (void)setView:(UIView *)newView {
if (newView == nil) {
self.uiElement = nil;
}
[super setView:aView];
}
</code></pre>
<p>Unfortunately this gives rise to a further issue. Because UIViewController currently implements its <code>dealloc</code> method using the <code>setView:</code> accessor method (rather than simply releasing the variable directly), <code>self.anOutlet = nil</code> will be called in <code>dealloc</code> as well as in response to a memory warning... This will lead to a crash in <code>dealloc</code>.</p>
<p>The remedy is to ensure that outlet variables are also set to <code>nil</code> in <code>dealloc</code>:</p>
<pre><code>- (void)dealloc {
// release outlets and set variables to nil
[anOutlet release], anOutlet = nil;
[super dealloc];
}
</code></pre>
|
<p>Related: <a href="https://stackoverflow.com/questions/6578/understanding-reference-counting-with-cocoa-objective-c">Understanding reference counting with Cocoa / Objective C</a></p>
| 8,714
|
<p>I'm using SQL Server 2005.</p>
<p>I have a field that must either contain a unique value or a NULL value. I think I should be enforcing this with either a <code>CHECK CONSTRAINT</code> or a <code>TRIGGER for INSERT, UPDATE</code>.</p>
<p>Is there an advantage to using a constraint here over a trigger (or vice-versa)? What might such a constraint/trigger look like?</p>
<p>Or is there another, more appropriate option that I haven't considered? </p>
|
<p>Here is an alternative way to do it with a constraint. In order to enforce this constraint you'll need a function that counts the number of occurrences of the field value. In your constraint, simply make sure this maximum is 1.</p>
<p>Constraint:</p>
<pre><code> field is null or dbo.fn_count_maximum_of_field(field) < 2
</code></pre>
<p><strong>EDIT I can't remember right now -- and can't check it either -- whether the constraint check is done before the insert/update or after. I think after with the insert/update being rolled back on failure. If it turns out I'm wrong, the 2 above should be a 1.</strong></p>
<p>Table function returns an int and uses the following select to derive it</p>
<pre><code> declare @retVal int
select @retVal = max(occurrences)
from (
select field, count(*) as occurrences
from dbo.tbl
where field = @field
group by field
) tmp
</code></pre>
<p>This should be reasonably fast if your column as a (non-unique) index on it.</p>
|
<p>Usually a trigger will allow you to provide a more verbose and explanatory message than a check constraint, so I have used those to avoid the "which column was bad" game in debugging. </p>
| 49,479
|
<p>I am pondering about buying a Creality Ender-3, and I am honestly confused about some reviews. Some claim it is running 24 V, one did claim it was 12 V, most don't mention it. Since I know about some issues with the clamps, if I get myself an Ender-3, I want to replace the hotend with a proper one from day one. So knowing its voltage is needed to order the right parts.</p>
|
<p>Bearing in mind that the specifications on Amazon's page are sometimes not 100% (even though they are <em>in this case</em>), it is always best to check on the manufacturer's website.</p>
<p>From Creality3D's own website, <a href="https://www.creality3dofficial.com/" rel="nofollow noreferrer">Creality3D.shop</a>, on the Creality3D Ender-3 product page, <a href="https://www.creality3dofficial.com/products/official-creality-ender-3-3d-printer" rel="nofollow noreferrer">Creality3D Ender-3 3D Printer Economic Ender DIY KITS</a>, the specifications are given as (emphasis is mine):</p>
<blockquote>
<p>##ender-3 Machine Parameter:</p>
<ul>
<li>Modeling Technology:FDM (Fused Deposition Modeling)</li>
<li>Printing Size:220<em>220</em>250mm</li>
<li>Machine Size:440<em>410</em>465mm</li>
<li>Package weight:8kg Max</li>
<li>Traveling Speed:180mm/s</li>
<li>Filament:1.75mm PLA,TPU,ABS</li>
<li><strong>Input:AC 100-265V 50-60Hz</strong></li>
<li><em><strong>Output:DC 24V 15A 360W</strong></em></li>
<li>Layer Thickness:0.1-0.4mm</li>
<li>Nozzle diameter:0.4mm</li>
<li>Precision:±0.1mm</li>
<li>File Format:STL,OBJ,G-Code</li>
<li>Working Mode:Online or SD offline</li>
<li>Max Nozzle Temperature:255℃</li>
<li>Max Hot bed Temperature:110℃</li>
</ul>
</blockquote>
|
<p>After checking the amazon listings of the ender-3, they contain more information than the gearbest listing: indeed it is a <strong>24V</strong> machine.</p>
<blockquote>
<p>Product description</p>
<p>[...]</p>
<p><strong>Output: DC 24 V 15 A 360 W</strong></p>
<p>[...]</p>
</blockquote>
| 956
|
<p>I have a star schema type data base, with fact tables that have many foreign keys to dimension tables. The number of records in each dimension table is small - often less than 256 bytes, but always less than 64k. The fact tables typically have hundreds of thousands of records, so I want maximize join speed.</p>
<p>I'd like to use tinyints and smallints, but a coworker says I'm crazy to worry about this and just use 4 byte ints in every case. Who is right? </p>
|
<p>Yr co-worker is wrong. If you use four byte integers for the foreign Keys, then the primary keys in the fact table have to be 4-byte integers as well. And then you are making your fact table wider than it needs to be, reducing the number of records that can fit on a single index page. To the degree that this changes the width of the primary Key Index, this will adversely affect index performance. If your Primary key could have been two tinyInts and 3 smallints, and you change to five 4-byte ints, you have changed the width of the index from 8 bytes wide to 20 bytes wide. Your index will have less than half as many entries per I/O page, and it will require twice as many logical and/or physical reads to traverse. </p>
<p>NOTE: As Jim McLeod's answer below, SQL Server 2008, (Enterprise or Developer edition), includes row-level compression, which means you can declare the value as a 4-byte INT, but it will store the value in the most appropriately sized type for each row.</p>
|
<p>As always with performance questions, it depends. If your fact rows are tiny, say 20 bytes each, then a saving of two bytes per row will save 400 bytes, and allow you to fit an extra 20 rows on each page. If your fact rows are larger, say 500 bytes, then you'll only be able to save 32 bytes, which won't matter at all.</p>
<p>The benefit of using an INT over a SMALLINT is that you don't have to worry about what happens if you suddenly get more rows than you expected.</p>
<p>SQL Server 2008 includes row-level compression, which means you can declare the value as a 4-byte INT, but it will store the value in the most appropriately sized type for each row.</p>
| 45,759
|
<p>I'm trying to extract the attributes of a anchor tag (<code><a></code>). So far I have this expression:</p>
<pre><code>(?<name>\b\w+\b)\s*=\s*("(?<value>[^"]*)"|'(?<value>[^']*)'|(?<value>[^"'<> \s]+)\s*)+
</code></pre>
<p>which works for strings like</p>
<pre><code><a href="test.html" class="xyz">
</code></pre>
<p>and (single quotes)</p>
<pre><code><a href='test.html' class="xyz">
</code></pre>
<p>but not for a string without quotes:</p>
<pre><code><a href=test.html class=xyz>
</code></pre>
<p>How can I modify my regex making it work with attributes without quotes? Or is there a better way to do that?</p>
<p><strong>Update:</strong> <em>Thanks for all the good comments and advice so far. There is one thing I didn't mention: I sadly have to patch/modify code not written by me. And there is no time/money to rewrite this stuff from the bottom up.</em></p>
|
<p>Update 2021: <a href="https://stackoverflow.com/users/2377961/radon8472">Radon8472</a> proposes in <a href="https://stackoverflow.com/questions/317053/regular-expression-for-extracting-tag-attributes/317081?noredirect=1#comment121192951_317081">the comments</a> the regex <a href="https://regex101.com/r/tOF6eA/1" rel="noreferrer">https://regex101.com/r/tOF6eA/1</a> (note <code>regex101.com</code> did not exist when I wrote originally this answer)</p>
<pre><code><a[^>]*?href=(["\'])?((?:.(?!\1|>))*.?)\1?
</code></pre>
<p>Update 2021 bis: <a href="https://stackoverflow.com/users/1081918/dave">Dave</a> proposes in <a href="https://stackoverflow.com/questions/317053/regular-expression-for-extracting-tag-attributes/317081#comment122184813_317081">the comments</a>, to take into account an attribute value containing an equal sign, like <code><img src="test.png?test=val" /></code>, as in <a href="https://regex101.com/r/ypPqjy/1" rel="noreferrer">this regex101</a>:</p>
<pre><code>(\w+)=["']?((?:.(?!["']?\s+(?:\S+)=|\s*\/?[>"']))+.)["']?
</code></pre>
<hr />
<p>Update (2020), <a href="https://stackoverflow.com/users/1010492/gyum-fox">Gyum Fox</a> proposes <a href="https://regex101.com/r/U9Yqqg/2" rel="noreferrer">https://regex101.com/r/U9Yqqg/2</a> (again, note <code>regex101.com</code> did not exist when I wrote originally this answer)</p>
<pre><code>(\S+)=["']?((?:.(?!["']?\s+(?:\S+)=|\s*\/?[>"']))+.)["']?
</code></pre>
<p>Applied to:</p>
<pre class="lang-html prettyprint-override"><code><a href=test.html class=xyz>
<a href="test.html" class="xyz">
<a href='test.html' class="xyz">
<script type="text/javascript" defer async id="something" onload="alert('hello');"></script>
<img src="test.png">
<img src="a test.png">
<img src=test.png />
<img src=a test.png />
<img src=test.png >
<img src=a test.png >
<img src=test.png alt=crap >
<img src=a test.png alt=crap >
</code></pre>
<hr />
<p>Original answer (2008):
If you have an element like</p>
<pre><code><name attribute=value attribute="value" attribute='value'>
</code></pre>
<p>this regex could be used to find successively each attribute name and value</p>
<pre><code>(\S+)=["']?((?:.(?!["']?\s+(?:\S+)=|[>"']))+.)["']?
</code></pre>
<p>Applied on:</p>
<pre><code><a href=test.html class=xyz>
<a href="test.html" class="xyz">
<a href='test.html' class="xyz">
</code></pre>
<p>it would yield:</p>
<pre><code>'href' => 'test.html'
'class' => 'xyz'
</code></pre>
<blockquote>
<p><strong>Note:</strong> This does not work with numeric attribute values e.g. <code><div id="1"></code> won't work.</p>
<p><strong>Edited:</strong> Improved regex for getting attributes with no value and values with " ' " inside.</p>
</blockquote>
<pre><code>([^\r\n\t\f\v= '"]+)(?:=(["'])?((?:.(?!\2?\s+(?:\S+)=|\2))+.)\2?)?
</code></pre>
<p>Applied on:</p>
<pre><code><script type="text/javascript" defer async id="something" onload="alert('hello');"></script>
</code></pre>
<p>it would yield:</p>
<pre><code>'type' => 'text/javascript'
'defer' => ''
'async' => ''
'id' => 'something'
'onload' => 'alert(\'hello\');'
</code></pre>
|
<p>Extract the element:</p>
<pre><code>var buttonMatcherRegExp=/<a[\s\S]*?>[\s\S]*?<\/a>/;
htmlStr=string.match( buttonMatcherRegExp )[0]
</code></pre>
<p>Then use jQuery to parse and extract the bit you want:</p>
<pre><code>$(htmlStr).attr('style')
</code></pre>
| 40,948
|
<p>I'm currently working on an internal sales application for the company I work for, and I've got a form that allows the user to change the delivery address.</p>
<p>Now I think it would look much nicer, if the textarea I'm using for the main address details would just take up the area of the text in it, and automatically resize if the text was changed.</p>
<p>Here's a screenshot of it currently.</p>
<p><img src="https://i.stack.imgur.com/XK48E.png" alt="ISO Address"></p>
<p>Any ideas?</p>
<hr>
<p>@Chris</p>
<p>A good point, but there are reasons I want it to resize. I want the area it takes up to be the area of the information contained in it. As you can see in the screen shot, if I have a fixed textarea, it takes up a fair wack of vertical space.</p>
<p>I can reduce the font, but I need address to be large and readable. Now I can reduce the size of the text area, but then I have problems with people who have an address line that takes 3 or 4 (one takes 5) lines. Needing to have the user use a scrollbar is a major no-no.</p>
<p>I guess I should be a bit more specific. I'm after vertical resizing, and the width doesn't matter as much. The only problem that happens with that, is the ISO number (the large "1") gets pushed under the address when the window width is too small (as you can see on the screenshot).</p>
<p>It's not about having a gimick; it's about having a text field the user can edit that won't take up unnecessary space, but will show all the text in it.</p>
<p>Though if someone comes up with another way to approach the problem I'm open to that too.</p>
<hr>
<p>I've modified the code a little because it was acting a little odd. I changed it to activate on keyup, because it wouldn't take into consideration the character that was just typed.</p>
<pre><code>resizeIt = function() {
var str = $('iso_address').value;
var cols = $('iso_address').cols;
var linecount = 0;
$A(str.split("\n")).each(function(l) {
linecount += 1 + Math.floor(l.length / cols); // Take into account long lines
})
$('iso_address').rows = linecount;
};
</code></pre>
|
<p>Facebook does it, when you write on people's walls, but only resizes vertically.</p>
<p>Horizontal resize strikes me as being a mess, due to word-wrap, long lines, and so on, but vertical resize seems to be pretty safe and nice.</p>
<p>None of the Facebook-using-newbies I know have ever mentioned anything about it or been confused. I'd use this as anecdotal evidence to say 'go ahead, implement it'.</p>
<p>Some JavaScript code to do it, using <a href="http://en.wikipedia.org/wiki/Prototype_JavaScript_Framework" rel="noreferrer">Prototype</a> (because that's what I'm familiar with):</p>
<pre><code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="http://www.google.com/jsapi"></script>
<script language="javascript">
google.load('prototype', '1.6.0.2');
</script>
</head>
<body>
<textarea id="text-area" rows="1" cols="50"></textarea>
<script type="text/javascript" language="javascript">
resizeIt = function() {
var str = $('text-area').value;
var cols = $('text-area').cols;
var linecount = 0;
$A(str.split("\n")).each( function(l) {
linecount += Math.ceil( l.length / cols ); // Take into account long lines
})
$('text-area').rows = linecount + 1;
};
// You could attach to keyUp, etc. if keydown doesn't work
Event.observe('text-area', 'keydown', resizeIt );
resizeIt(); //Initial on load
</script>
</body>
</html>
</code></pre>
<p>PS: Obviously this JavaScript code is very naive and not well tested, and you probably don't want to use it on textboxes with novels in them, but you get the general idea.</p>
|
<p>Here is an extension to the Prototype widget that Jeremy posted on June 4th:</p>
<p>It stops the user from entering more characters if you're using limits in textareas. It checks if there are characters left. If the user copies text into the textarea, the text is cut off at the max. length:</p>
<pre><code>/**
* Prototype Widget: Textarea
* Automatically resizes a textarea and displays the number of remaining chars
*
* From: http://stackoverflow.com/questions/7477/autosizing-textarea
* Inspired by: http://github.com/jaz303/jquery-grab-bag/blob/63d7e445b09698272b2923cb081878fd145b5e3d/javascripts/jquery.autogrow-textarea.js
*/
if (window.Widget == undefined) window.Widget = {};
Widget.Textarea = Class.create({
initialize: function(textarea, options){
this.textarea = $(textarea);
this.options = $H({
'min_height' : 30,
'max_length' : 400
}).update(options);
this.textarea.observe('keyup', this.refresh.bind(this));
this._shadow = new Element('div').setStyle({
lineHeight : this.textarea.getStyle('lineHeight'),
fontSize : this.textarea.getStyle('fontSize'),
fontFamily : this.textarea.getStyle('fontFamily'),
position : 'absolute',
top: '-10000px',
left: '-10000px',
width: this.textarea.getWidth() + 'px'
});
this.textarea.insert({ after: this._shadow });
this._remainingCharacters = new Element('p').addClassName('remainingCharacters');
this.textarea.insert({after: this._remainingCharacters});
this.refresh();
},
refresh: function(){
this._shadow.update($F(this.textarea).replace(/\n/g, '<br/>'));
this.textarea.setStyle({
height: Math.max(parseInt(this._shadow.getHeight()) + parseInt(this.textarea.getStyle('lineHeight').replace('px', '')), this.options.get('min_height')) + 'px'
});
// Keep the text/character count inside the limits:
if($F(this.textarea).length > this.options.get('max_length')){
text = $F(this.textarea).substring(0, this.options.get('max_length'));
this.textarea.value = text;
return false;
}
var remaining = this.options.get('max_length') - $F(this.textarea).length;
this._remainingCharacters.update(Math.abs(remaining) + ' characters remaining'));
}
});
</code></pre>
| 2,901
|
<p>What is the best way to send e-mail using outlook express from the command line? It has to be an automated operation with no user interaction. There will be some .jpg files in attachment.
Thanks.</p>
|
<p>Perhaps <a href="https://stackoverflow.com/questions/248569/starting-outlook-and-having-an-email-pre-populated-from-command-line">this post</a> is helpful. It speaks pre-populating a new e-mail message and including a file.</p>
|
<p>This thread: <a href="https://stackoverflow.com/questions/152323/send-mail-from-a-windows-script#152411" title="Send mail from a Windows script">Send mail from a Windows script</a> might help you, I think.</p>
| 31,560
|
<p>I was previously taught today how to set parameters in a SQL query in .NET in this answer (<a href="https://stackoverflow.com/questions/169359/improving-code-readability-for-sql-commands#169369">click</a>).</p>
<p>Using parameters with values are fine, but when I try to set a field in the database to null I'm unsuccessful. Either the method thinks I am not setting a valid parameter or not specifying a parameter.</p>
<p>e.g.</p>
<pre><code>Dim dc As New SqlCommand("UPDATE Activities SET [Limit] = @Limit WHERE [Activity] = @Activity", cn)
If actLimit.ToLower() = "unlimited" Then
' It's not nulling :(
dc.Parameters.Add(New SqlParameter("Limit", Nothing))
Else
dc.Parameters.Add(New SqlParameter("Limit", ProtectAgainstXSS(actLimit)))
End If
</code></pre>
<p>Is there something I'm missing? Am I doing it wrong?</p>
|
<p>you want <a href="http://msdn.microsoft.com/en-us/library/system.dbnull.aspx" rel="noreferrer">DBNull</a>.Value.</p>
<p>In my shared DAL code, I use a helper method that just does:</p>
<pre><code> foreach (IDataParameter param in cmd.Parameters)
{
if (param.Value == null) param.Value = DBNull.Value;
}
</code></pre>
|
<p>Try setting it to <code>DbNull.Value</code>.</p>
| 20,539
|
<p>I am designing a web site but it is behind a firewall and such services like <a href="http://validator.w3.org/" rel="nofollow noreferrer">http://validator.w3.org/</a> will not work.</p>
<p>Are there any free apps I could run on Windows or Mac OS X that will validate html and css?</p>
|
<p>Use the HTML Validator plugin for Firefox</p>
<p><a href="http://users.skynet.be/mgueury/mozilla/download.html" rel="nofollow noreferrer">http://users.skynet.be/mgueury/mozilla/download.html</a></p>
<p>It will even work on HTML files on your PC</p>
|
<p>the w3 validator does have a 'validate by direct input' option (which I use constantly) however TravisO's answer is worthy as the chosen answer :)</p>
| 37,618
|
<p>Say I've got two scheduled processes: A and B.</p>
<p>Given that B should not run until A has completed, how might I gracefully enforce this dependency?</p>
<p>Approaches that have been considered:</p>
<ol>
<li><p>Have A schedule B upon completion. This has the downside of B never being scheduled if for some reason A failed.</p></li>
<li><p>When B runs, have it ping A to see if the latter has completed. How this might be accomplished (network, file, database record, message queue) could be messy and problematic introducing a third dependency.</p></li>
<li><p>Combine A and B into a single process. This has the downside of tightly binding the two, making it harder to re-run one or the other in isolation if need be.</p></li>
</ol>
<p>Thoughts?</p>
|
<p>Your option 1 directly answers your question: if B is dependent on A, and A fails, A not scheduling B means that B can't happen.</p>
<p>Unless B merely has to run after A does, whether or not A was successful.</p>
<p>In that case, something like the following (in bash) would work:</p>
<pre><code>A && B
</code></pre>
|
<p>You could modify step 3: Create your two processes to run in isolation, and then create a third process that runs the other two.</p>
| 21,600
|
<p>i want to be a good developer citizen, <a href="http://blogs.msdn.com/oldnewthing/archive/2005/08/22/454487.aspx" rel="nofollow noreferrer">pay my taxes</a>, and disable things if we're running over Remote Desktop, or running on battery.</p>
<p>If we're running over remote desktop (or equivalently in a Terminal server session), we must disable animations and double-buffering. You can check this with:</p>
<pre><code>/// <summary>
/// Indicates if we're running in a remote desktop session.
/// If we are, then you MUST disable animations and double buffering i.e. Pay your taxes!
///
/// </summary>
/// <returns></returns>
public static Boolean IsRemoteSession
{
//This is just a friendly wrapper around the built-in way
get
{
return System.Windows.Forms.SystemInformation.TerminalServerSession;
}
}
</code></pre>
<p>Now i need to find out if the user is running on battery power. If they are, i don't want to blow through their battery. i want to do things such as</p>
<ul>
<li>disable animations</li>
<li>disable background spell-checking</li>
<li>disable background printing</li>
<li>turn off gradients </li>
<li>use <code>graphics.SmoothingMode = SmoothingMode.HighSpeed;</code> </li>
<li>use <code>graphics.InterpolationMode = InterpolationMode.Low;</code></li>
<li>use <code>graphics.CompositingQuality = CompositingQuality.HighSpeed;</code></li>
<li>minimize hard drive access - to avoid spin up</li>
<li>minimize network access - to save WiFi power</li>
</ul>
<p>Is there a managed way to see if the machine is <strong>currently</strong> running on battery?</p>
<h2>Bonus Reading</h2>
<ul>
<li><a href="http://blogs.msdn.com/oldnewthing/archive/2005/08/22/454487.aspx" rel="nofollow noreferrer">How do you convince developers to pay their "taxes"?</a> <em>(<a href="https://archive.fo/iNVg5" rel="nofollow noreferrer">archive.is</a>)</em></li>
<li><a href="http://blogs.msdn.com/oldnewthing/archive/2006/01/03/508694.aspx" rel="nofollow noreferrer">Taxes: Remote Desktop Connection and painting</a> <em>(<a href="https://archive.fo/lJx1u" rel="nofollow noreferrer">archive.is</a>)</em></li>
<li><a href="http://msdn.microsoft.com/en-us/library/ms724385(VS.85).aspx" rel="nofollow noreferrer">GetSystemMetrics(SM_REMOTESESSION)</a> <em>(<a href="https://archive.fo/Ywbw7" rel="nofollow noreferrer">archive.is</a>)</em></li>
</ul>
|
<p>I believe you can check <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.systeminformation.powerstatus(VS.80).aspx" rel="noreferrer">SystemInformation.PowerStatus</a> to see if it's on battery or not.</p>
<pre><code>Boolean isRunningOnBattery =
(System.Windows.Forms.SystemInformation.PowerStatus.PowerLineStatus ==
PowerLineStatus.Offline);
</code></pre>
<p>Edit: In addition to the above, there's also a System.Windows.Forms.<a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.powerstatus(VS.80).aspx" rel="noreferrer">PowerStatus</a> class. One of its methods is <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.powerstatus.powerlinestatus(VS.80).aspx" rel="noreferrer">PowerLineStatus</a>, which will equal PowerLineStatus.Online if it's on AC Power.</p>
|
<p>I don't believe it's exposed in managed code, but you can use the Win32 GetSystemPowerStatus via pinvoke to get this info.</p>
<p>As an aside, you may want to consider using the GetCurrentPowerPolicies or similar to determine the users preferences relating to performance/power management. </p>
| 29,843
|
<p>This might be on the "discussy" side, but I would really like to hear your view on this.</p>
<p>Previously I have often written data access classes that handled both reading and writing, which often led to poor naming, like FooIoHandler etc. The rule of thumb that classes that are hard to name probably are poorly designed suggests that this is not a good solution.</p>
<p>So, I have recently started splitting the data access into FooWriter and FooReader, which leads to nicer names and gives some additional flexibility, but at the same time I kind of like keeping it together, if the classes are not to big.</p>
<p>Is a reader/writer separation a better design, or should I combine them? If I should combine them, what the heck should I name the class?</p>
<p>Thanks /Erik</p>
|
<p>ORM might be your best solution.<br>
Or use a repository type pattern, with a "thingContext" object that is responsible for state persistence.</p>
<p>Personally, I use the activeRecord pattern, where save logic is baked into a base class, but I'm leaving it in favor of an nHibernate style repository pattern. The allowance for DDD and testing things without a db is very nice to have in a framework type situation, where my business logic is now gaining traction for a new UI.</p>
|
<p>When given the choice I generally subclass the reader to create the writer. </p>
| 4,923
|
<p>I have a memory of talking to people who have got so far in using Ruby on Rails and then had to abandon it when they have hit limits, or found it was ultimately too rigid. I forget the details but it may have had to do with using more than one database.</p>
<p>So what I'd like is to know is what features/requirements fall outside of Ruby on Rails, or at least requires such contortions that it is better to use another more flexible framework, even though you may have to lose some elegance or write extra boilerplate code. </p>
|
<p>Rails (not ruby itself) is proud to be "Opinionated Software".</p>
<p>What this means in practice is that the authors of rails have a certain target audience in mind (themselves basically) and aim rails specifically at that. If X feature isn't needed for that target audience, it doesn't get added.</p>
<p>Off the top of my head, things that rails explicitly doesn't support that people may care about:</p>
<ol>
<li>Foreign keys in databases</li>
<li>Connections to multiple DB's at once</li>
<li>SOAP web services (since rails 2.0)</li>
<li>Connections to multiple database <em>servers</em> at once</li>
</ol>
<p>That said, it is very easy to extend rails with plugins, and there are plugins which add all of the above functionality to rails, and a lot more, so I wouldn't really count these as limits.</p>
<p>The only other caveat is that rails is <em>built</em> around the idea of creating CRUD web applications using MVC. If you're trying to do something which is NOT a CRUD web app (like twitter, which is actually a messaging system, or if you are insane and want to use a model like ASP.NET webforms) then you will also encounter problems. In this case you're better off not using rails, as you're essentially trying to build a boat out of bicycle parts.</p>
<p>In all likelihood, the problems you will run into that can't just be fixed with a quick plugin or a day or 2 of coding are all inherent problems with the underlying C Ruby runtime (memory leaks, green threads, crap performance, etc).</p>
|
<p>Orion's answer is right on. There are few hard limits to AR/Rails: deploying to Windows, AR connectors that aren't frequently used, e.g. Firebird, ), but even the things he mentioned, multiple databases and DB servers, there are gems and plugins that address those for legacy, sharding, and other reasons.</p>
<p>The real limitation is how time-consuming it is to keep on top of all the things that rails devs are working on, and researching specific issues, given how many blogs, and how much mailing list volume there are. </p>
| 21,745
|
<p>In AJAX applications that need to poll the server in regular intervals (like a chat applications), what is the recommended minimum time between two calls, so that the update is done as quickly as possible? What times are considered as hogs for the server and the client?</p>
|
<p>The answer to this question is very much dependent on:</p>
<ol>
<li>How much data is sent in each poll</li>
<li>How many users you will have online at a time</li>
<li>How much bandwidth your server can handle</li>
<li>How "fresh" the data on your client needs to be</li>
</ol>
<p>Without knowing any of these specifics for your app, it's going to be hard to give a good recommendation. Have you looked into a method where the client connects to the server, and the server holds the connection open until there is data available? Then the server delivers the data, and the client immediately reconnects and waits again. That can be tricky to get working, but you might be able to maximize both efficiency of bandwidth AND responsiveness that way.</p>
|
<p>There is no real limit, other than the number of simultaneous users you expect to burden your server load with. You can probably dynamically tune this on the client end by keeping track of average response times.</p>
<p>In order to do this properly, under a decent load, you're betting off using <a href="http://en.wikipedia.org/wiki/Comet_(programming)" rel="nofollow noreferrer">Comet</a>.</p>
| 31,318
|
<p>I have created a Custom Server Control (Inherited from GridView).</p>
<p>On the page, the GridView is DataBound to a DataSet, so I do not know at design time what columns will be present in my GridView.</p>
<p>Now, what I want to do is, to add a textbox in every Cell for the GridView Header row, and those textboxes will control column filtering. (textboxes are added using the GridView OnRowCreated method).</p>
<p>So far so good, the textboxes appear, and the filtering is working.</p>
<p>Problem is, after every postback, the Text value of the textboxes is lost. From my experimentations, this seems to be because I'm adding the textboxes too late in the Page/Control lifecycle.</p>
<p>How does one deal with this type of problem, where I would need to create and add the textboxes early in the Lifecycle (like, the GridView's OnInit), but adding the textboxes is dependant on information that is obtained later in the lifecycle?</p>
|
<p>Why not store the values in the ViewState and read them back (refill the text boxes) on the postback?</p>
|
<p>You don't have to worry about the textbox's values, just their ID and when you create them; control state(...hmmm...or maybe the viewstate) will take care of the rest, as long as you create and "supply" the page with the same number of textboxes and their respective (unique(!)) ID's.</p>
<p>You can do this is both Page_Init and Page_Load...Page_Init is somewhat recommended, but that depend on your needs.</p>
| 41,311
|
<p>What internal web service did your company implement first? What did you learn?</p>
|
<p>One of the first movers was the "Customer base system". </p>
<p>The common authority for all customers in the company.</p>
<p>EDIT:<br>
regarding the comment:<br>
It did indeed open up for more SOA. It's about 3-5years ago (before me) and currently it was publicly known last year that the SOA helped the company switch from a 3years delayed system to a new one within a year.</p>
<p>Regarding other stuff:<br>
Dont get me started on our SAP integration :S Thats 3 years old as well, and nobody is really able to debug or update the setup. Currently we are POCing webservice integration with SAP. Pheeew</p>
|
<p>Let me see if I can get this conversation going. My company implemented a wrapper around the most common Active Directory look-up needs. I imagine this might be one of the most common things to do first in Microsoft/.NET shops.</p>
<p>Anybody implement a library of utility services? Write a facade to some SAP module? Wrap up some services for Human Resources? I'm curious to what people are working on.</p>
| 38,080
|
<p>Consider a <em>hypothetical</em> method of an object that does stuff for you:</p>
<pre><code>public class DoesStuff
{
BackgroundWorker _worker = new BackgroundWorker();
...
public void CancelDoingStuff()
{
_worker.CancelAsync();
//todo: Figure out a way to wait for BackgroundWorker to be cancelled.
}
}
</code></pre>
<p>How can one wait for a BackgroundWorker to be done?</p>
<hr>
<p>In the past people have tried:</p>
<pre><code>while (_worker.IsBusy)
{
Sleep(100);
}
</code></pre>
<p>But <a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1819196&SiteID=1" rel="noreferrer">this deadlocks</a>, because <code>IsBusy</code> is not cleared until after the <code>RunWorkerCompleted</code> event is handled, and that event can't get handled until the application goes idle. The application won't go idle until the worker is done. (Plus, it's a busy loop - disgusting.)</p>
<p>Others have add suggested kludging it into:</p>
<pre><code>while (_worker.IsBusy)
{
Application.DoEvents();
}
</code></pre>
<p>The problem with that is that is <code>Application.DoEvents()</code> causes messages currently in the queue to be processed, which cause re-entrancy problems (.NET isn't re-entrant).</p>
<p>I would hope to use some solution involving Event synchronization objects, where the code <strong>waits</strong> for an event - that the worker's <code>RunWorkerCompleted</code> event handlers sets. Something like:</p>
<pre><code>Event _workerDoneEvent = new WaitHandle();
public void CancelDoingStuff()
{
_worker.CancelAsync();
_workerDoneEvent.WaitOne();
}
private void RunWorkerCompletedEventHandler(sender object, RunWorkerCompletedEventArgs e)
{
_workerDoneEvent.SetEvent();
}
</code></pre>
<p>But I'm back to the deadlock: the event handler can't run until the application goes idle, and the application won't go idle because it's waiting for an Event.</p>
<p>So how can you wait for an BackgroundWorker to finish?</p>
<hr>
<p><strong>Update</strong>
People seem to be confused by this question. They seem to think that I will be using the BackgroundWorker as:</p>
<pre><code>BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += MyWork;
worker.RunWorkerAsync();
WaitForWorkerToFinish(worker);
</code></pre>
<p>That is <em>not</em> it, that is <em>not</em> what I'm doing, and that is <em>not</em> what is being asked here. If that were the case, there would be no point in using a background worker.</p>
|
<p>If I understand your requirement right, you could do something like this (code not tested, but shows the general idea):</p>
<pre><code>private BackgroundWorker worker = new BackgroundWorker();
private AutoResetEvent _resetEvent = new AutoResetEvent(false);
public Form1()
{
InitializeComponent();
worker.DoWork += worker_DoWork;
}
public void Cancel()
{
worker.CancelAsync();
_resetEvent.WaitOne(); // will block until _resetEvent.Set() call made
}
void worker_DoWork(object sender, DoWorkEventArgs e)
{
while(!e.Cancel)
{
// do something
}
_resetEvent.Set(); // signal that worker is done
}
</code></pre>
|
<p>oh man, some of these have gotten ridiculously complex. all you need to do is check the BackgroundWorker.CancellationPending property inside the DoWork handler. you can check it at any time. once it's pending, set e.Cancel = True and bail from the method.</p>
<p>// method here
private void Worker_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker bw = (sender as BackgroundWorker);</p>
<pre><code>// do stuff
if(bw.CancellationPending)
{
e.Cancel = True;
return;
}
// do other stuff
</code></pre>
<p>}</p>
| 15,042
|
<p>can anybody recommend some really good resources for how to get Apache authenticating users with Kerberos.</p>
<p>Background reading on Kerberos would also be useful </p>
<p>Thanks</p>
<p>Peter</p>
|
<p>mod_auth_kerb is a good start: <a href="http://modauthkerb.sourceforge.net/" rel="nofollow noreferrer">http://modauthkerb.sourceforge.net/</a>. If you need Active Directory support, look here: <a href="http://support.microsoft.com/?id=555092" rel="nofollow noreferrer">http://support.microsoft.com/?id=555092</a>.</p>
|
<p>I found mod_auth_spnego also quite okay, as it can use SSPI on windows instead of requiring MIT Kerberos. <a href="http://sourceforge.net/projects/modgssapache/" rel="nofollow noreferrer">mod_spnego</a></p>
| 6,504
|
<p>I'm having trouble trying to map nested conditions onto an intuitive interface.</p>
<p>eg. How would you represent ((Condition1 AND Condition2) OR (Condition1 AND Condition5)) AND Condition4</p>
|
<p>Here's a screenshot of prototype I did for a linux app a few years ago. You could click on the +/- icons to add rows to a group and click on the "add new..." and "remove last..." buttons to remove the bottom-most group. </p>
<p>Above each group was a couple of menubuttons that had the choices of "AND items that match..." / "OR items that match..." (except for the first group which varied slightly), and "ANY of the following" / "ALL of the following". Each row was type-aware, so if you selected a string for the variable the conditions would be "IS", "IS NOT", "BEGINS WITH" and so on. For integers you would get "IS", "GREATER THAN", etc, and for dates "ON", "BEFORE", "ON OR BEFORE" and so on.</p>
<p>Where you see the word "or" before the second and third row of the first group, that would be "or" if "ANY of the following" was selected, and "and" if "ALL of the following:" was selected to reinforce the choice and make it easier to "read" the dialog.</p>
<p>It wouldn't let you do any conceivable query but I think it covered about 90% of what an average user would want to do and did it in what I thought was a fairly usable way.</p>
<p><a href="https://i.stack.imgur.com/GcvPR.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GcvPR.jpg" alt="screenshot of db query form"></a><br>
<sub>(source: <a href="http://www1.clearlight.com/~oakley/dbquery.jpg" rel="nofollow noreferrer">clearlight.com</a>)</sub> </p>
|
<p>The best interface I've seen for this was a home-grown control that drew a tree to clearly show the order of operations. I've never seen a third-party control that did this but I haven't looked for one either.</p>
| 14,368
|
<p>Visual Studio 2003 and 2005 (and perhaps 2008 for all I know) require the command line user to run in the 'Visual Studio Command Prompt'. When starting this command prompt it sets various environment variables that the C++ compiler, cl, uses when compiling.</p>
<p>This is not always desirable. If, for example, I want to run 'cl' from within Ant, I'd like to avoid having to run Ant from within the 'Visual Studio Command Prompt'. Running vcvars32.bat isn't an option as the environment set by vcvars32.bat would be lost by the time cl was run (if running from within Ant).</p>
<p>Is there an easy way to run cl without having to run from within the Visual Studio command prompt?</p>
|
<p>The compilers can be used from command line (or makefiles) just like any other compilers. The main things you need to take care of are the INCLUDE and LIB environment variables, and PATH. If you're running from cmd.exe, you can just run this .bat to set the environment:</p>
<p><blockquote>C:\Program Files\Microsoft Visual Studio 9.0\VC\vcvarsall.bat</blockquote></p>
<p>If you're trying to use the compilers from a makefile, Cygwin, MinGW, or something like that you need to set the environment variables manually. Assuming the compiler is installed in the default location, this should work for the Visual Studio 2008 compiler and the latest Windows SDK:</p>
<p>Add to PATH:</p>
<ul>
<li>C:\Program Files\Microsoft SDKs\Windows\v6.1\Bin</li>
<li>C:\Program Files\Microsoft Visual Studio 9.0\VC\Bin</li>
<li>C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE</li>
</ul>
<p>Add to INCLUDE:</p>
<ul>
<li>C:\Program Files\Microsoft SDKs\Windows\v6.1\Include</li>
<li>C:\Program Files\Microsoft Visual Studio 9.0\VC\include</li>
<li>C:\Program Files\Microsoft Visual Studio 9.0\VC\atlmfc\include</li>
</ul>
<p>Add to LIB:</p>
<ul>
<li>C:\Program Files\Microsoft SDKs\Windows\v6.1\Lib</li>
<li>C:\Program Files\Microsoft Visual Studio 9.0\VC\lib</li>
</ul>
<p>These are the bare minimum, but should be enough for basic things. Study the vcvarsall.bat script to see what more you may want to set.</p>
|
<p>My version of opening the visual studio command line for Visual Studio Command Prompt in <a href="/questions/tagged/visual-studio-2010" class="post-tag" title="show questions tagged 'visual-studio-2010'" rel="tag">visual-studio-2010</a>. Used internally to build a library/project and then perform some extra steps with the resulting DLL files.</p>
<p>Copy these lines to your <code>Compile and execute other steps.cmd</code> file, or similar.</p>
<pre><code>@echo off
REM Load Visual Studio's build tools
call "%ProgramFiles(x86)%\Microsoft Visual Studio 10.0\VC\vcvarsall.bat" x86
REM Choose what you want to do, 1 or 2 by (un)commenting
REM 1. Add your cl.exe (or msbuild.exe or other) commands here
REM msbuild.exe MyProject.csproj
REM cl.exe
REM custom-step.exe %*
REM pause
REM 2. Open a normal interactive system command shell with all variables loaded
%comspec% /k
</code></pre>
<p>In this version of the script, I "stay" in interactive command line mode afterwards. Comment to <code>REM %comspec% /k</code> to only use the script for non-interactive purposes.</p>
| 10,999
|
<p>After Visual Studio 2005 displays the splash screen it locks up on me. No error, no cpu utilization, just a frozen splash screen. I've tried it in both /safemode and /resetsettings</p>
<p>I'm sure it's one of the services on my machine, just wonder if anyone else has had the problem and can help me with the hunt?</p>
<p>BTW, it's works in a VM in the same machine.</p>
<p>Update: I finally tried something new, I started VS2005 in Windows compatibility 2000 mode, it starts then shuts down immediately. I reset it to not run in compatibility mode and it starts right up. grrrrr</p>
<p>I think it might be a profile issue, but the root cause is still unresolved.</p>
|
<p>Have you tried running it in <a href="http://msdn.microsoft.com/en-us/library/xee0c8y7(VS.80).aspx" rel="nofollow noreferrer">safe mode</a> - if that doesn't let you sort it out you can try the /resetsettings switch, which has sorted out similar problems for me in the past.</p>
<p>/resetuserdata can also help.</p>
|
<p>Try starting up with the log command:</p>
<pre><code>devenv.exe /Log c:\vs.log
</code></pre>
<p>And see if anything is noted in it.</p>
<p>Another thing to try is to run VS in a temporary user account to see if the problem is strictly with your user environment or is system-wide. See <a href="https://stackoverflow.com/questions/851477/visual-studion-2008-exits-as-soon-as-i-open-it/853198#853198">this post</a>.</p>
| 21,056
|
<p>I am trying to create 1 Parent Drop Down, that has 2 dependent child drop down lists using JAVASCRIPT.</p>
<p>My html page is at - <a href="http://www.larkgrove.com/entryform/entryform.html" rel="nofollow noreferrer">http://www.larkgrove.com/entryform/entryform.html</a></p>
<p>I am using the Dynamic Options Lists / Dependent Selects:
<a href="http://www.javascripttoolbox.com/lib/dynamicoptionlist/examples.php" rel="nofollow noreferrer">http://www.javascripttoolbox.com/lib/dynamicoptionlist/examples.php</a></p>
<p>If you check out my site, you can see that I can get the Child lists to change between nothing there and "NULL", but thats about all I can do.</p>
<p>THANKS!</p>
|
<p>I know you are using the Dynamic options script, but I thought that I would put up a quick from scratch solution. The code is a little verbose, but I am hoping it will be easier to see whats going on this way. The final working page is here: <a href="http://ryanscook.com/Files/DropDownListTest.htm" rel="nofollow noreferrer">http://ryanscook.com/Files/DropDownListTest.htm</a></p>
<p>Lets start by assuming you have this html:</p>
<pre><code><select id="parentList" onchange="parentList_OnChange(this)">
<option>Choose an option</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
<select id="childList1"></select>
<select id="childList2"></select>
</code></pre>
<p>You will notice that we have an onchange handler, here is the java script:</p>
<pre><code>// Data for child list 1, this is a of the parent value to one or more options
var childList1Data = {
"A": ["ChildList1 - A1", "ChildList1 - A2", "ChildList1 - A3"],
"B": ["ChildList1 - B1"],
"C": ["ChildList1 - C1", "ChildList1 - C2"],
"D": ["ChildList1 - D1", "ChildList1 - D2"]
};
// Data for child list 2, this is a of the parent value to one or more options
var childList2Data = {
"A": ["ChildList2 - A1", "ChildList2 - A2"],
"B": ["ChildList2 - B1", "ChildList2 - B2", "ChildList2 - B3"],
"C": ["ChildList2 - C1", "ChildList2 - C2"],
"D": ["ChildList2 - D1"]
};
// onchange is called when the parent value is changed
function parentList_OnChange(objParentList) {
var child1 = document.getElementById("childList1");
var child2 = document.getElementById("childList2");
// Remove all options from both child lists
removeOptions(child1);
removeOptions(child2);
// Lookup and get the array of values for child list 1, using the parents selected value
var child1Data = childList1Data[objParentList.options[objParentList.selectedIndex].value];
// Add the options to child list 1
if (child1Data) {
for (var i = 0; i < child1Data.length; i++) {
child1.options[i] = new Option(child1Data[i], child1Data[i]);
}
}
// Do the same for the second list
var child2Data = childList2Data[objParentList.options[objParentList.selectedIndex].value];
if (child2Data) {
for (var i = 0; i < child2Data.length; i++) {
child2.options[i] = new Option(child2Data[i], child2Data[i]);
}
}
}
function removeOptions(objSelect) {
while (objSelect.options.length > 0)
objSelect.options[0] = null;
}
</code></pre>
<p>I hope this helps and was not to far off from your question.</p>
|
<p>Well, first of all, let's have a look at your code:</p>
<pre><code><script type="text/javascript">
var TESTLIST = new DynamicOptionList("PARENT1","CHILD1","CHILD2");
TESTLIST.forValue("A").forValue("A").forValue("A").addOptionsTextValue("C","C","D","D");
</script>
<select name="PARENT1">
<option value="A">A</option>
<option value="B">B</option>
</select>
<br /><br />
<select name="CHILD1"><script type="text/javascript">TESTLIST.printOptions("CHILD1")</script></select>
<br /><br />
<select name="CHILD2"><script type="text/javascript">TESTLIST.printOptions("CHILD2")</script></select>
</code></pre>
<p>I don't think that's doing what you are intending it to do, especially this:</p>
<pre><code>TESTLIST.forValue("A").forValue("A").forValue("A").addOptionsTextValue("C","C","D","D");
</code></pre>
<p>See how you call .forvalue("A") several times redundantly? If you look at the code example you see:</p>
<pre><code>regionState.forValue("west").addOptions("California","Washington","Oregon");
</code></pre>
<p>I would try something more like this:</p>
<pre><code>TESTLIST.forValue("A").addOptionsTextValue("C","D");
TESTLIST.forValue("B").addOptionsTextValue("E","F");
</code></pre>
| 47,239
|
<p>Is there a way to get Visual Studio to display strings as verbatim strings (prefixed with '@')? I'd like to easily cut strings containing file paths from Visual Studio into Explorer or other apps.</p>
<p>Clarification: when VS displays a string in the auto, watch, immediate, etc. window, I'd like it to be formatted as as verbatim string so that I can simple copy it for use elsewhere.</p>
|
<p>You can click on the magnifier in VS 2008 debugger variable display and select "Text Visualizer" which will give you the text in an unmassaged format.</p>
|
<p>You may need to clarify your question. My first thought was that you just need to prefix the string with '@' to make them verbatim, but you already know that.</p>
<pre><code>string s = @"c:\my folder\";
</code></pre>
<p>What exactly are you trying to do with the string?</p>
| 44,474
|
<p>To create a new event handler on a control you can do this</p>
<pre><code>c.Click += new EventHandler(mainFormButton_Click);
</code></pre>
<p>or this</p>
<pre><code>c.Click += mainFormButton_Click;
</code></pre>
<p>and to remove an event handler you can do this</p>
<pre><code>c.Click -= mainFormButton_Click;
</code></pre>
<p>But how do you remove all event handlers from an event?</p>
|
<p>I found a solution on the <a href="http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/576f69e7-55aa-4574-8d31-417422954689/" rel="noreferrer">MSDN forums</a>. The sample code below will remove all <code>Click</code> events from <code>button1</code>.</p>
<pre><code>public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
button1.Click += button1_Click;
button1.Click += button1_Click2;
button2.Click += button2_Click;
}
private void button1_Click(object sender, EventArgs e) => MessageBox.Show("Hello");
private void button1_Click2(object sender, EventArgs e) => MessageBox.Show("World");
private void button2_Click(object sender, EventArgs e) => RemoveClickEvent(button1);
private void RemoveClickEvent(Button b)
{
FieldInfo f1 = typeof(Control).GetField("EventClick",
BindingFlags.Static | BindingFlags.NonPublic);
object obj = f1.GetValue(b);
PropertyInfo pi = b.GetType().GetProperty("Events",
BindingFlags.NonPublic | BindingFlags.Instance);
EventHandlerList list = (EventHandlerList)pi.GetValue(b, null);
list.RemoveHandler(obj, list[obj]);
}
}
</code></pre>
|
<p>I found this answer and it almost fit my needs. Thanks to SwDevMan81 for the class. I have modified it to allow suppression and resumation of individual methods, and I thought I'd post it here.</p>
<pre><code>// This class allows you to selectively suppress event handlers for controls. You instantiate
// the suppressor object with the control, and after that you can use it to suppress all events
// or a single event. If you try to suppress an event which has already been suppressed
// it will be ignored. Same with resuming; you can resume all events which were suppressed,
// or a single one. If you try to resume an un-suppressed event handler, it will be ignored.
//cEventSuppressor _supButton1 = null;
//private cEventSuppressor SupButton1 {
// get {
// if (_supButton1 == null) {
// _supButton1 = new cEventSuppressor(this.button1);
// }
// return _supButton1;
// }
//}
//private void button1_Click(object sender, EventArgs e) {
// MessageBox.Show("Clicked!");
//}
//private void button2_Click(object sender, EventArgs e) {
// SupButton1.Suppress("button1_Click");
//}
//private void button3_Click(object sender, EventArgs e) {
// SupButton1.Resume("button1_Click");
//}
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Windows.Forms;
using System.ComponentModel;
namespace Crystal.Utilities {
public class cEventSuppressor {
Control _source;
EventHandlerList _sourceEventHandlerList;
FieldInfo _headFI;
Dictionary<object, Delegate[]> suppressedHandlers = new Dictionary<object, Delegate[]>();
PropertyInfo _sourceEventsInfo;
Type _eventHandlerListType;
Type _sourceType;
public cEventSuppressor(Control control) {
if (control == null)
throw new ArgumentNullException("control", "An instance of a control must be provided.");
_source = control;
_sourceType = _source.GetType();
_sourceEventsInfo = _sourceType.GetProperty("Events", BindingFlags.Instance | BindingFlags.NonPublic);
_sourceEventHandlerList = (EventHandlerList)_sourceEventsInfo.GetValue(_source, null);
_eventHandlerListType = _sourceEventHandlerList.GetType();
_headFI = _eventHandlerListType.GetField("head", BindingFlags.Instance | BindingFlags.NonPublic);
}
private Dictionary<object, Delegate[]> BuildList() {
Dictionary<object, Delegate[]> retval = new Dictionary<object, Delegate[]>();
object head = _headFI.GetValue(_sourceEventHandlerList);
if (head != null) {
Type listEntryType = head.GetType();
FieldInfo delegateFI = listEntryType.GetField("handler", BindingFlags.Instance | BindingFlags.NonPublic);
FieldInfo keyFI = listEntryType.GetField("key", BindingFlags.Instance | BindingFlags.NonPublic);
FieldInfo nextFI = listEntryType.GetField("next", BindingFlags.Instance | BindingFlags.NonPublic);
retval = BuildListWalk(retval, head, delegateFI, keyFI, nextFI);
}
return retval;
}
private Dictionary<object, Delegate[]> BuildListWalk(Dictionary<object, Delegate[]> dict,
object entry, FieldInfo delegateFI, FieldInfo keyFI, FieldInfo nextFI) {
if (entry != null) {
Delegate dele = (Delegate)delegateFI.GetValue(entry);
object key = keyFI.GetValue(entry);
object next = nextFI.GetValue(entry);
if (dele != null) {
Delegate[] listeners = dele.GetInvocationList();
if (listeners != null && listeners.Length > 0) {
dict.Add(key, listeners);
}
}
if (next != null) {
dict = BuildListWalk(dict, next, delegateFI, keyFI, nextFI);
}
}
return dict;
}
public void Resume() {
}
public void Resume(string pMethodName) {
//if (_handlers == null)
// throw new ApplicationException("Events have not been suppressed.");
Dictionary<object, Delegate[]> toRemove = new Dictionary<object, Delegate[]>();
// goes through all handlers which have been suppressed. If we are resuming,
// all handlers, or if we find the matching handler, add it back to the
// control's event handlers
foreach (KeyValuePair<object, Delegate[]> pair in suppressedHandlers) {
for (int x = 0; x < pair.Value.Length; x++) {
string methodName = pair.Value[x].Method.Name;
if (pMethodName == null || methodName.Equals(pMethodName)) {
_sourceEventHandlerList.AddHandler(pair.Key, pair.Value[x]);
toRemove.Add(pair.Key, pair.Value);
}
}
}
// remove all un-suppressed handlers from the list of suppressed handlers
foreach (KeyValuePair<object, Delegate[]> pair in toRemove) {
for (int x = 0; x < pair.Value.Length; x++) {
suppressedHandlers.Remove(pair.Key);
}
}
//_handlers = null;
}
public void Suppress() {
Suppress(null);
}
public void Suppress(string pMethodName) {
//if (_handlers != null)
// throw new ApplicationException("Events are already being suppressed.");
Dictionary<object, Delegate[]> dict = BuildList();
foreach (KeyValuePair<object, Delegate[]> pair in dict) {
for (int x = pair.Value.Length - 1; x >= 0; x--) {
//MethodInfo mi = pair.Value[x].Method;
//string s1 = mi.Name; // name of the method
//object o = pair.Value[x].Target;
// can use this to invoke method pair.Value[x].DynamicInvoke
string methodName = pair.Value[x].Method.Name;
if (pMethodName == null || methodName.Equals(pMethodName)) {
_sourceEventHandlerList.RemoveHandler(pair.Key, pair.Value[x]);
suppressedHandlers.Add(pair.Key, pair.Value);
}
}
}
}
}
}
</code></pre>
| 11,720
|
<p>I'm looking for a free/open source collaborative project manager that can be deployed internally in my workplace that would act similar to Codeplex or Sourceforge. Does anyone know of something like this, and if so do you have experience with it.</p>
<p><strong>Requirements:</strong></p>
<ul>
<li>Open Source <em>or</em> Free</li>
<li>Locally Deployable</li>
<li>Has the same types of features found in Sourceforge / Codeplex
<ul>
<li>Issue/Feature Tracking</li>
<li>Community Interaction (ie. Voting, Roles, etc.)</li>
<li>SCM Integration <em>(Optional)</em></li>
</ul></li>
<li>.NET/Windows Friendly <em>(Optional)</em></li>
</ul>
<p>Every business ends up having internal utilities, and domain specific apps that developers create to make life easier. Given the input of the internal developer community they have the potential to become much better (can you say <a href="http://en.wikipedia.org/wiki/History_of_Gmail#Internal_development" rel="nofollow noreferrer">GMail</a>...), and I would simply like to foster such an environment internally by providing an easy place for that interaction to take place.</p>
<p><strong>UPDATE:</strong></p>
<p>So I like what I am seeing in both Trac and GForge, but both are heavily geared towards UNIX/Subversion environments. I should have specified this, but we are a MS shop from top to bottom. How practical do you think it is going to be to try and use these in a MS .NET environment? Would that be like trying to shove a square peg through a round hole?</p>
|
<p>I like redmine for this: <a href="http://www.redmine.org" rel="noreferrer">http://www.redmine.org</a>. The only thing it's missing from your criteria is voting, but there might even be a plugin for this.</p>
<p>Trac is also popular (<a href="http://trac.edgewall.org" rel="noreferrer">http://trac.edgewall.org</a>) but it lacks suport for aggregation of data across projects.</p>
|
<p><a href="http://www.assembla.com/" rel="nofollow noreferrer">Assembla</a> and <a href="http://beanstalkapp.com/" rel="nofollow noreferrer">BeanStalk</a> are nice, both have things like; wiki, discussion, alerts, chat, ticketing, Trac, Git and Subversion</p>
| 10,895
|
<p>From the wikipedia entry on NP-Complete:</p>
<p>"The easiest way to prove that some new problem is NP-complete is first to prove that it is in NP, and then to reduce some known NP-complete problem to it"</p>
<p>I'm pretty sure that I understand this: If I have a problem, I can show that it is NP-Complete if I: </p>
<ol>
<li><p>show that it is in NP (a solution to
the problem can be verified in
polynomial time on a
non-deterministic Turing machine)</p></li>
<li><p>Show that a problem already known to be NP-Complete can be
'reduced' to the new problem</p></li>
</ol>
<p>So, my question is, how were the first NP-complete problems 'proven' to be NP-complete? At one time, the set of known NP-complete problems must have been zero, and this would have made it impossible to resort to step 2 in the above process. </p>
<p>This makes me think that there is a different method for proof which I'm not aware of. Either that, or maybe the whole NP-complete property is 'assumed' for certain problems due to lack of a known polynomial time solution. (actually, having written this, I wouldn't be surprised if this is the case, but I'd like some guru-feedback either way). </p>
|
<p><a href="http://en.wikipedia.org/wiki/Cook%27s_theorem" rel="noreferrer">Cook's Theorem</a></p>
<p>The class NP can be defined as the class of problems decidable by a nondeterministic Turing machine in polynomial time. This theorem shows that <strong>SAT is NP-complete</strong> by encoding the operation of any nondeterministic Turing machine by a boolean formula, in such a way that the machine accepts if and only if that formula is SATisfiable.</p>
<p>Historically speaking, the notion of NP-completeness was introduced in Richard Karp's seminal paper (<i><a href="http://en.wikipedia.org/wiki/Karp%27s_21_NP-complete_problems" rel="noreferrer">Reducibility Among Combinatorial Problems</a></i>), where he defined NP-completeness, used Cook's theorem, and in one big shot, proved 21 problems NP-complete.</p>
|
<p>To give you the essence of the proof (which is several pages of hard going in Garey & Johnson's <em>Computers and Intractibility</em>):</p>
<p>Any computational problem can be expressed as a Turing machine.</p>
<p>It is possible to express the Turing machine as a logic problem, satisfying certain complexity constraints.</p>
<p>Therefore, if you can solve the logic problem in polynomial time, you can solve the Turing machine problem in polynomial time.</p>
<p>This (along with some other considerations) shows that if you can solve the logic problem in polynomial time, you can solve any NP problem in polynomial time. This being the definition of NP-complete, the logic problem is therefore NP-complete, and can be used as a basis for other problems.</p>
<p>The logic problem used is called Satisfiability (often abbreviated to SAT). Given a series of clauses of the form (A or not-B or not-C) (clauses consisting of any number of propositions and negations of propositions connected by logical or), is there an assignment of truth values to the propositions that makes all the clauses true?</p>
<p>NP-completeness is a well-defined property. The only reason you'd be in doubt about a problem being NP-complete is that you thought you could reduce another NP-complete problem to it, but haven't managed to find a convenient problem or derive a proof yet.</p>
<p>The question is not whether NP-complete problems exist, or how to prove a problem is NP-complete, but what that means. Nobody has yet produced a polynomial-time algorithm to solve an NP-complete problem, and nobody has proved that such an algorithm can't exist. Whether or not P=NP, we certainly don't have good algorithms to solve any NP-complete problem.</p>
<p>This is one of the Claypool Foundation's Millenium Problems, so if you can come up with a proof that has been eluding some very bright people for quite a few years, there's a million dollars in it for you.</p>
| 39,395
|
<p>I have a website with a mix of ASP (classic) and ASP.NET pages.</p>
<p>For some reason Visual Studio (specifically 2008 Pro) keeps trying to compile the ASP classic pages.</p>
<p><strong><em>How do I prevent it from trying to compile the .asp pages?</em></strong></p>
<p>Reason: I'm getting a ton of errors on a specific .asp file that includes a Class. I believe it's trying to compile it as a Visual Basic class instead of seeing it as a vBScript class. It should be skipping over .asp files anyway, correct?</p>
<p>Here is the error:</p>
<blockquote>
<p>Property Get/Let/Set are no longer
supported; use the new Property
declaration syntax.</p>
</blockquote>
|
<p>Have you installed Service Pack 1? It addresses some issues with classic ASP.</p>
|
<p>What is in the @Page directive on those classic ASP pages? Have you tried inserting <code><% @Page language="vbscript" %></code> Maybe this does it already?</p>
| 34,969
|
<p>What are the ways that you use to model and retrieve hierarchical info in a database? </p>
|
<p>The definitive pieces on this subject have been written by Joe Celko, and he has worked a number of them into a book called Joe Celko's Trees and Hierarchies in SQL for Smarties.</p>
<p>He favours a technique called directed graphs. An introduction to his work on this subject can be found <a href="http://web.archive.org/web/20081102031702/http://www.intelligententerprise.com/001020/celko.jhtml" rel="nofollow noreferrer">here</a></p>
|
<p>If you're using SQL Server 2005 then <a href="https://web.archive.org/web/20210927200924/http://www.4guysfromrolla.com/webtech/071906-1.shtml" rel="nofollow noreferrer">this link</a> explains how to retrieve hierarchical data.</p>
<p>Common Table Expressions (CTEs) can be your friends once you get comfortable using them.</p>
| 5,977
|
<p>I have some configuration values for an asp.net web app. They will be maintained by a system admin once the system goes live. Should I store these values in the database or in a config file? Is there a best practice for this sort of thing?</p>
|
<p>It's easy and convenient to create a robust interface to edit the values in the database.</p>
<p>It's less easy to create a good one for the config file.</p>
<p>So I would usually you want to store everything which you would like your users/administrators to be able to edit later in the database. Everything which only needs to be touched during serious changes like re-installation etc is better off in the config file.</p>
|
<p>Depending on the context of the config information, you could choose to leave it in the web.config or you could create maintenance tables for it in the database. I would typcially keep things more backend specific, like connection strings, ftp locations, usernames/passwords(for the application, not user permissions) in the web.config though.</p>
<p>I normally keep more relative information that relates to the information in the database rather than the application itself, in the database.</p>
<p>This is all loosely based though and not always the case.</p>
| 30,856
|
<p>When is a good idea to save information in a XML file and when in a own-format file?</p>
<p>For XML (or other standard) I see:</p>
<ul>
<li>(+) Standard format.</li>
<li>(-) It's tedious to hand modify.</li>
</ul>
<p>For own-format files I see:</p>
<ul>
<li>(-) We need to build a own-parser (non-standard).</li>
<li>(+) It can be easy to hand modify the files.</li>
</ul>
|
<p>Use XML when it's a good fit in various ways:</p>
<ul>
<li>Need to share between different applications which are all capable of handling XML</li>
<li>Natural tree-like structure</li>
<li>Primarily data easily represented as text (binary data is a bit of a kludge in text-based formats)</li>
<li>Extensibility is important</li>
<li>Performance isn't critical (parsing XML isn't exactly blazingly fast - although if performance is important and you go for XML, shop around for a fast parser, as there's a wide difference between fastest and slowest)</li>
<li>Schema can be pre-defined and documents can be verified against it</li>
<li>Simpler formats (e.g. name=value pairs) don't cut it</li>
</ul>
<p>Basically if there's a pretty natural representation of your data model in XML, that may well be the easiest way of handling it. If you'd end up having to mess around a lot to fit it in with XML, think about other formats. Note that there are plenty of other standard (or "somewhat standard" - e.g. supported by tools on multiple platforms) formats available beyond just XML.</p>
|
<p>The ease of editing isn't a major issue, as pointed out above: there are lot of good (and free for some) XML editors around.</p>
<p>Another potential issue is verbosity, although the answer for large files is to gzip them: in lot of languages, it is nearly transparent.</p>
<p>XML is good in a number of ways: the standard is well defined (you don't have to think how to define charset, how to escape stuff, how to handle special cases (multi-lines, binary, etc.)); it has lot of tools (editors, parsers, XPath, etc.); it is great to exchange data with other tools.</p>
<p>If your needs are very simple, manipulating only Ascii, self-sufficient (only this app will use this format), maybe you can go with another format. But before defining your own, you might take a look at existing text-based formats, like Json, Yaml, even Lua (was a data description language at the origin) or for very simple needs, Windows' ini format or Java's properties.</p>
| 45,446
|
<p>How can I test the same regex against different regular expression engines?</p>
|
<p>The most powerful free online regexp testing tool is by far <a href="http://regex101.com/" rel="nofollow noreferrer">http://regex101.com/</a> - lets you select the RE engine (PCRE, JavaScript, Python), has a debugger, colorizes the matches, explains the regexp on the fly, can create permalinks to the regex playground.</p>
<p>Other online tools:</p>
<ul>
<li><a href="http://www.rexv.org/" rel="nofollow noreferrer">http://www.rexv.org/</a> - supports PHP and Perl PCRE, Posix, Python, JavaScript, and Node.js</li>
<li><a href="http://refiddle.com/" rel="nofollow noreferrer">http://refiddle.com/</a> - Inspired by jsfiddle, but for regular expressions. Supports JavaScript, Ruby and .NET expressions.</li>
<li><a href="http://regexpal.com/" rel="nofollow noreferrer">http://regexpal.com/</a> - powered by the <a href="http://xregexp.com/" rel="nofollow noreferrer">XRegExp</a> JavaScript library</li>
<li><a href="http://www.rubular.com/" rel="nofollow noreferrer">http://www.rubular.com/</a> - Ruby-based</li>
<li><a href="http://www.perlfect.com/articles/regextutor.shtml" rel="nofollow noreferrer">Perl Regex Tutor</a> - uses PCRE</li>
</ul>
<p>Windows desktop tools:</p>
<ul>
<li><a href="http://www.weitz.de/regex-coach/" rel="nofollow noreferrer">The Regex Coach</a> - free Windows application</li>
<li><a href="http://www.regexbuddy.com/" rel="nofollow noreferrer">RegexBuddy</a> recommended by most, costs US$ 39.95</li>
</ul>
<p>Jeff Atwood [wrote about regular expressions]( post:).</p>
<p>Other tools recommended by SO users include:</p>
<ul>
<li><a href="http://www.txt2re.com/" rel="nofollow noreferrer"><a href="http://www.txt2re.com/" rel="nofollow noreferrer">http://www.txt2re.com/</a></a> Online free tool to generate regular expressions for multiple language (@<a href="https://stackoverflow.com/questions/4736/learning-regular-expressions#4763">palmsey</a> another thread)</li>
<li>The Added Bytes <a href="http://www.addedbytes.com/cheat-sheets/regular-expressions-cheat-sheet/" rel="nofollow noreferrer">Regular Expressions Cheat Sheet</a> (@<a href="https://stackoverflow.com/questions/4736/learning-regular-expressions#4739">GateKiller</a> another thread)</li>
<li><a href="http://regexhero.net/" rel="nofollow noreferrer">http://regexhero.net/</a> - The Online .NET Regular Expression Tester. Not free.</li>
</ul>
|
<p>RegExBuddy so far I concur with and endorse.</p>
| 5,221
|
<p>I noticed that many people here use <a href="http://macromates.com/" rel="nofollow noreferrer">TextMate</a> for coding on OS X. I've recently started using it, and although I like its minimalistic interface, it makes it harder to stumble upon cool features if you don't know what you're looking for.</p>
<p>So, what feature have you found most helpful for coding (mainly in Python)? Are there any third-party bundles I should know about, besides what's included?</p>
|
<p>Don't neglect the 'mate' command line tool. You can use it to pipe output into TextMate, so if you do the following...</p>
<pre><code>diff file1.py file2.py | mate
</code></pre>
<p>...it will not only open in TextMate, but it is smart enough to know that you're looking at a diff and highlight lines on screen.</p>
<p>TextMate's SVN integration is great; it also seems to have bundles for some other version control systems as well.</p>
<p>Add GetBundle to browse the bundle repository. I found the jQuery bundle through it and it's very handy.</p>
<p>As others have mentioned, rolling your own bundle for frequently used snippets is very helpful. If you have some snippets that are specific to a project or framework, you might want to prefix all of them with a common letter to keep the namespace tidy.</p>
|
<p>The <code>mate</code> command line tool is great, you can open an individual file or my favourite use of it is to open a directory of files as a project (e.g. <code>mate .</code>)</p>
| 5,390
|
<p>I have been rather successful in promoting JQuery within my organization. No small feat on it's own. However, one of the ideas being kicked around here to make it part of our app is to create an ASP.net server side control. (We are going to be sticking with WebForms for the foreseeable future.)</p>
<p>I'm not too wild about this approach as it seems like overkill when a couple of script tags will do the job. We found an <a href="http://www.west-wind.com/WebLog/posts/167052.aspx" rel="nofollow noreferrer">article</a> on the web, and the amount of code involved really doesn't seem to justify itself. However, I do hear that there is some benefit in the script caching or generating that happens with the server controls.</p>
<p>My questions:</p>
<ul>
<li>Has anyone else written an ASP.net server control to serve up the JQuery js code?</li>
<li>Does anyone else think that this is a crazy idea to just avoid writing JQuery or Javascript code?</li>
</ul>
|
<p>I know Microsoft (along with Nokia) is "mainstreaming" jQuery and will be integrating it with future versions of Visual Studio. You may want to explore how they'll be officially using it so you can tailor your setup now, and hopefully ease your transition to "official MS jQuery" down the road.</p>
|
<p>I found Scott Hanselman's <a href="http://www.hanselman.com/blog/jQuerytoshipwithASPNETMVCandVisualStudio.aspx" rel="nofollow noreferrer">blog post</a> with a sample app that has ASP.net AJAX + JQuery. It's a simple app, but it includes all the javascript with script tags. I don't see any advisement to use a server control to serve up the scripts.</p>
| 21,054
|
<p>I want to do this (no particular language):</p>
<pre><code>print(foo.objects.bookdb.books[12].title);
</code></pre>
<p>or this:</p>
<pre><code>book = foo.objects.bookdb.book.new();
book.title = 'RPC for Dummies';
book.save();
</code></pre>
<p>Where foo actually is a service connected to my program via some IPC, and to access its methods and objects, some layer actually sends and receives messages over the network.</p>
<p>Now, I'm not really looking for an IPC mechanism, as there are plenty to choose from. It's likely not to be XML based, but rather s. th. like Google's protocol buffers, dbus or CORBA. What I'm unsure about is how to structure the application so I can access the IPC just like I would any object.</p>
<p>In other words, how can I have OOP that maps transparently over process boundaries?</p>
<p>Not that this is a design question and I'm still working at a pretty high level of the overall architecture. So I'm pretty agnostic yet about which language this is going to be in. C#, Java and Python are all likely to get used, though.</p>
|
<p>I think the way to do what you are requesting is to have all object communication regarded as message passing. This is how object methods are handled in ruby and smalltalk, among others. </p>
<p>With message passing (rather than method calling) as your object communication mechanism, then operations such as calling a method that didn't exist when you wrote the code becomes sensible as the object can do something sensible with the message anyway (check for a remote procedure, return a value for a field with the same name from a database, etc, or throw a 'method not found' exception, or anything else you could think of).</p>
<p>It's important to note that for languages that don't use this as a default mechanism, you can do message passing anyway (every object has a 'handleMessage' method) but you won't get the syntax niceties, and you won't be able to get IDE help without some extra effort on your part to get the IDE to parse your handleMessage method to check for valid inputs.</p>
|
<p>You shouldn't do it! It is very important for programmers to see and feel the difference between an IPC/RPC and a local method call in the code. If you make it so, that they don't have to think about it, they won't think about it, and that will lead to very poorly performing code.</p>
<p>Think of:</p>
<pre><code>foreach o, o.isGreen in someList {
o.makeBlue;
}
</code></pre>
<p>The programmer assumes that the loops takes a few nanoseconds to complete, instead it takes close to a second if someList happens to be remote.</p>
| 24,005
|
<p>I have set of names and addresses that have been entered into and excel spreadsheet, but the problem is that the many people that entered the addresses entered them in many different non-standard formats. I want to scrub the addresses before transferring all of of them to my database. Looking around, all I really found in the way of address scrubbers(parsers or formatters) is the one that is put out by <a href="http://www.semaphorecorp.com/" rel="noreferrer">Semaphore</a>. For my purposes, I don't really need all of that and I don't want to pay for the licensing fees for the software. Is there anything out there that is Free and/or Open Source that will do the scrubbing for me? </p>
|
<p>Since I work in the mailing business ...</p>
<p>A mailable address is not geo-coding. One allows the USPS to deliver mail to and the other tells you where on earth that point is. The USPS does not geo-code their mailable addresses. It's useful for marking areas/regions of people for targeting.</p>
<p>You're not buying a license to the software, you're buying the data. The post office has lots of rules especially if you're doing this commercially and trying to get a better rate than first class. See <a href="http://pe.usps.com/text/dmm300/dmm300_landing.htm" rel="noreferrer">USPS Domestic Mail Manual</a> for the complete list of rules. The USPS moves zips and households between zips all the time. The company (I work for) pays the USPS for its updated mailing list so we can keep our DBs updated. Weekly.</p>
<p>Back to your question. Do you want to change the data into a common format (street -> st) or are you looking for duplicates and want to only store real mailable addresses ?</p>
<p>for common format; you can break the address into pieces, clean up the white space and apply a dictionary of terms/translations. Then apply some sql to find the duplicates. Keep in mind households (1 main st) are different from persons (john doe, 1 main st).</p>
<p>for the mailable addresses, well some of you (the readers) won't like this answer, but you want information and that isn't free. Someone spends time or money to acquire and maintain these lists. So, find a business model to acquire funds for the list or go to someone who will do it for you. <a href="http://valassis.com/1024/Services/datamail.aspx" rel="noreferrer">Data and mail management</a></p>
<p>Realistically, <a href="http://www.semaphorecorp.com/" rel="noreferrer">Semaphore</a> is pretty cheap, just keep in mind that the address db will have to be updated quarterly and $19/quarter is pretty cheap.</p>
<p>Another Address Scrubbing product. <a href="http://www.businessobjects.com/product/catalog/postalsoft_solutions/" rel="noreferrer">SAP PostalSoft</a>. I don't know what the data will cost though.</p>
|
<p>Most of the software that I've worked with to do this is very expensive (or to put it another way, marketing departments are naive and have huge budgets). </p>
<p>This sort of work is a precursor to Geo-coding. This <a href="http://en.wikipedia.org/wiki/Geocoding" rel="nofollow noreferrer">linked Wiki article</a> includes a list of Geocoding software, some of which is free. If you're lucky, some of the free ones may include address standardizing routines.</p>
<p>If you find a good one, let me know. </p>
| 37,209
|
<p>How can I get a full list of Groups in my Active Directory?</p>
|
<p>Check out System.DirectoryServices (An ASP.NET 2.0 reference):</p>
<p>C#-example to get groups: </p>
<pre><code>using System.DirectoryServices;
public class test
{
private void main()
{
foreach (string @group in GetGroups())
{
Debug.Print(@group);
}
}
public List<string> GetGroups()
{
DirectoryEntry objADAM = default(DirectoryEntry);
// Binding object.
DirectoryEntry objGroupEntry = default(DirectoryEntry);
// Group Results.
DirectorySearcher objSearchADAM = default(DirectorySearcher);
// Search object.
SearchResultCollection objSearchResults = default(SearchResultCollection);
// Results collection.
string strPath = null;
// Binding path.
List<string> result = new List<string>();
// Construct the binding string.
strPath = "LDAP://stefanserver.stefannet.local";
//Change to your ADserver
// Get the AD LDS object.
try
{
objADAM = new DirectoryEntry(strPath);
objADAM.RefreshCache();
}
catch (Exception e)
{
throw e;
}
// Get search object, specify filter and scope,
// perform search.
try
{
objSearchADAM = new DirectorySearcher(objADAM);
objSearchADAM.Filter = "(&(objectClass=group))";
objSearchADAM.SearchScope = SearchScope.Subtree;
objSearchResults = objSearchADAM.FindAll();
}
catch (Exception e)
{
throw e;
}
// Enumerate groups
try
{
if (objSearchResults.Count != 0)
{
foreach (SearchResult objResult in objSearchResults)
{
objGroupEntry = objResult.GetDirectoryEntry();
result.Add(objGroupEntry.Name);
}
}
else
{
throw new Exception("No groups found");
}
}
catch (Exception e)
{
throw new Exception(e.Message);
}
return result;
}
}
</code></pre>
<p>VB-example to get groups:</p>
<pre><code>Imports System.DirectoryServices
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
For Each group As String In GetGroups()
Debug.Print(group)
Next
End Sub
Public Function GetGroups() As List(Of String)
Dim objADAM As DirectoryEntry ' Binding object.
Dim objGroupEntry As DirectoryEntry ' Group Results.
Dim objSearchADAM As DirectorySearcher ' Search object.
Dim objSearchResults As SearchResultCollection ' Results collection.
Dim strPath As String ' Binding path.
Dim result As New List(Of String)
' Construct the binding string.
strPath = "LDAP://stefanserver.stefannet.local" 'Change to your ADserver
' Get the AD LDS object.
Try
objADAM = New DirectoryEntry(strPath)
objADAM.RefreshCache()
Catch e As Exception
Throw e
End Try
' Get search object, specify filter and scope,
' perform search.
Try
objSearchADAM = New DirectorySearcher(objADAM)
objSearchADAM.Filter = "(&(objectClass=group))"
objSearchADAM.SearchScope = SearchScope.Subtree
objSearchResults = objSearchADAM.FindAll()
Catch e As Exception
Throw e
End Try
' Enumerate groups
Try
If objSearchResults.Count <> 0 Then
Dim objResult As SearchResult
For Each objResult In objSearchResults
objGroupEntry = objResult.GetDirectoryEntry
result.Add(objGroupEntry.Name)
Next objResult
Else
Throw New Exception("No groups found")
End If
Catch e As Exception
Throw New Exception(e.Message)
End Try
Return result
End Function
End Class
</code></pre>
|
<p>Microsoft .NET Framework provides a standard library for working with Active Directory: <strong><a href="http://msdn.microsoft.com/en-us/library/ms682458(VS.85).aspx" rel="nofollow noreferrer">System.DirectoryServices namespace</a></strong> in the System.DirectoryServices.dll.</p>
<p>Microsoft recommends using two main classes from the System.DirectoryServices namespace: <strong>DirectoryEntry</strong> and <strong>DirectorySearcher</strong>. In most cases, it is enough to use DirectorySearcher class only.</p>
<p>You can find some examples in this <a href="http://www.codeproject.com/KB/system/QueryADwithDotNet.aspx" rel="nofollow noreferrer">CodeProject article</a>.</p>
| 41,881
|
<p>When using Aspect Oriented Programming with Policy injection, how do you deal with policy errors gracefully in your design?</p>
<p>In Aspect Oriented Programming the objects should be unconcerned with how a particular policy is configured, but a particular policy may throw particular errors. What's the most graceful design to deal with that?</p>
|
<p>If you consider the policy to be an "aspect" of the system then the specific aspect should handle everything that has to do with that policy. The objects should be unaware of the specific policy. This way, if you you need to change the policy in the future, you won't need to change anything in the objects.</p>
|
<p>Why not have your aspect that injects the policy validate it/handle errors that may occur?</p>
| 22,754
|
<p>I'm printing a Soma cube I found on Thingiverse -- it's a puzzle toy I remember from the early 1970s, and the kind of thing that ought to be really easy-peasy to print. Each of the seven pieces is made of four cubes (or three for one piece) joined face to face in every possible combination, so that they can be assembled to make a single 3x3 cube (the claim in the day was, in literally tens of millions of ways -- though many of those were reflections or rotations of others).</p>
<p>Problem is, in order for the seven pieces to fit together correctly to make the 3x3 cube, they have to be flat and square on all faces, and dimensionally accurate.</p>
<p>I have an Ender 3 that's just a few weeks old (first print was May 8th to 9th of this year, also my own first 3D print). I'm printing these parts in gray Amazon Basics PLA at 200 °C, with the Creality coated glass build surface at 55 °C. I'm printing on a raft; the first layer goes down well, but over the course of the first forty or so layers, I get this:</p>
<p><a href="https://i.stack.imgur.com/GCk17.jpg" rel="nofollow noreferrer" title="Raft lifting from build surface"><img src="https://i.stack.imgur.com/GCk17.jpg" alt="Raft lifting from build surface" title="Raft lifting from build surface" /></a></p>
<p>I presume this is due to the upper layers shrinking, though the horizontal dimensions look fine at the level where I stopped the print. I have Cura Slicer 4.9.1 set to print with no part cooling for initial layer, increasing to 100 % at layer 4. When I removed this part (immediately after stopping the print, so the bed was still in the low 50s), it was still stuck fairly well -- except where it had lifted.</p>
<p>What's causing this warping/lifting?</p>
|
<blockquote>
<p>What's causing this warping/lifting?</p>
</blockquote>
<p>The warping and lifting is caused by insufficient adhesion. This can be caused by an incorrect first layer (it is difficult to see the raft, but generally, rafts have no solid bottom, so less adhesion as there is less material), e.g. not sufficiently squished to the plate. Note that a raft is absolutely unnecessary for PLA, you should use it for high temperature filaments that experience a lot of shrinkage, PLA does not.</p>
<p>What you should do is make sure the bed is completely clean and free from grease. Use isopropyl/isopropanol alcohol to clean the bed.</p>
<p>Temperature of the bed should be fine, but you could try to notch it up with 5 °C.</p>
<p>I've seen people use an adhesive between the bed and the print, even on coated beds. But, I can imagine you don't want to try that, it needs more cleaning.</p>
<p>Also, make sure that the printer isn't in front of a window or in the path of an air-conditioning airflow.</p>
|
<ol>
<li><p>What has worked for me is to keep the bed temperature constant at 60 °C. Use a higher extrusion temperature for the first layer to promote adhesion. (Differences in PLA composition could cause these temperatures to vary.)</p>
</li>
<li><p>Sometimes it helps to have an bed temperature for the 1st layer as high as 75 °C to promote adhesion. While depositing the first layer with this bed temperature promotes adhesion, leaving the bed temperature this high actually decreases it, besides risking the print sagging under its weight.</p>
</li>
<li><p>Additional adhesion layers such as glue sticks might help.</p>
</li>
<li><p>If not already using it, less stiff fill patterns (rectangular) can help, as well as a lower percentage fill.</p>
</li>
</ol>
| 1,975
|
<p>As much as we would all like to say it is a benefit to programmers to be language agnostic, is it really feasible to support multiple enterprise Web applications of the same type all written in different languages? Think about how complicated a CMS or e-commerce system can be -- now imagine supporting three different CMS platforms all written in different languages. I would hate to be known as a .NET or Java or PHP shop, but I also don't want to be the vendor who says they can support a solution they have never worked with, upsetting a client who wonders why we can't get something done right on time. Can anyone speak from experience on this? Does your company usually just suck it up, and try and to learn a new platform on the fly? Do you bill up-to-speed, or eat those costs?</p>
|
<p><a href="http://racket-lang.org/" rel="noreferrer">Racket</a> (<a href="http://racket-lang.org/new-name.html" rel="noreferrer">formerly Dr Scheme</a>) has a nice editor, several different Scheme dialects, an attempt at visual debugging, lots of libraries, and can run on most platforms. It even has some modes specifically geared around learning the language.</p>
|
<p>LispMe works on a Palm Pilot, take it anywhere, and scheme on the go. GREAT way to learn scheme.</p>
| 8,403
|
<p>I'm using <code>.htaccess</code> and <code>mod_rewrite</code> to point to files that reside behind the DocumentRoot. My folder structure looks like this:</p>
<pre><code>home/
webroot/
other_files/
</code></pre>
<p>I have a <code>.htaccess</code> file in webroot with the following content:</p>
<pre>
RewriteEngine on
RewriteRule ^(.*)$ /home/other_files/$1
</pre>
<p>If I try to access <a href="http://example.com/file.html" rel="noreferrer">http://example.com/file.html</a> I receive the following error: </p>
<blockquote>
<p>The requested URL /home/other_files/file.html was not found on this server. </p>
</blockquote>
<p>Is it even possible to load files that are behind the DocumentRoot? If so, can someone point me in the right direction?</p>
|
<p>I believe you need to add a section with </p>
<pre><code><Directory "/home/other_files">
(options)
</Directory>
</code></pre>
<p>to your server configuration before apache will be able to serve anything from it. For an example, my DocumentRoot is /var/www but there is this section in the default available site:</p>
<pre><code>Alias /doc/ "/usr/share/doc/"
<Directory "/usr/share/doc/">
Options Indexes MultiViews FollowSymLinks
AllowOverride None
Order deny,allow
Deny from all
Allow from 127.0.0.0/255.0.0.0 ::1/128
</Directory>
</code></pre>
<p>You could then rewrite a URL to go to /doc/ and the server would know where to get the files from.</p>
|
<p>Just so you know why that rule doesn't work:</p>
<p>The reason that it isn't able to rewrite to <code>/home/other_files/file.html</code> is that mod_rewrite is parsing the path as <code>/home/webroot/home/other_files/file.html</code> since from mod_rewrite's point of view the preceding slash is equivalent to your document root of <code>/home/webroot</code>.</p>
<p><a href="https://stackoverflow.com/questions/8441/mod-rewrite-loading-files-behind-the-documentroot#8454">Ryan Ahearn's suggestion</a> is a decent one, and is likely the route you want to go.</p>
| 2,985
|
<p>I am trying to set one bindable variable to be bound to another. Essentially I want to create an alias. I would give up, but this seems like something that would be good to know.</p>
<p>essentially, I want changes in model.configView to be reflected in view, so that things bound to view.... behave the same as things bound to model.configView... in this example <pre>[Bindable]
var view = model.configView;</p>
<p>...
<mx:Label text="{view.lblThisLabel.name}" />
</pre></p>
<p>at the moment it does not, and I am getting errors that say "unable to bind to property 'lblThisLabel' on class 'Object' (class is not an IEventDispatcher)"</p>
|
<p>Not quite enough code here to really say what's going on, however you have made <code>view</code> bindable and that does not automatically mean that all of <code>view</code>'s children are bindable. You'll have to go into <code>view</code> and make <code>lblThisLabel</code> bindable too.</p>
<p>Also it is hard for the rest of us to know how it works in your head. Perhaps you should describe that too.</p>
|
<p>Moreover, I think that even if, with your actual code, <code>view</code> changes should be detected, <code>view</code> won't be updated if assigned <code>model.configView</code> property is not bindable as well...</p>
| 42,031
|
<p>Situation: A PHP application with multiple installable modules creates a new table in database for each, in the style of mod_A, mod_B, mod_C etc. Each has the column section_id.</p>
<p>Now, I am looking for all entries for a specific section_id, and I'm hoping there's another way besides "Select * from mod_a, mod_b, mod_c ... mod_xyzzy where section_id=value"... or even worse, using a separate query for each module.</p>
|
<p>If the tables are changing over time, you can inline code gen your solution in an SP (pseudo code - you'll have to fill in):</p>
<pre><code>SET @sql = ''
DECLARE CURSOR FOR
SELECT t.[name] AS TABLE_NAME
FROM sys.tables t
WHERE t.[name] LIKE 'SOME_PATTERN_TO_IDENTIFY_THE_TABLES'
</code></pre>
<p>-- or this</p>
<pre><code>DECLARE CURSOR FOR
SELECT t.[name] AS TABLE_NAME
FROM TABLE_OF_TABLES_TO_SEACRH t
START LOOP
IF @sql <> '' SET @sql = @sql + 'UNION ALL '
SET @sql = 'SELECT * FROM [' + @TABLE_NAME + '] WHERE section_id=value '
END LOOP
EXEC(@sql)
</code></pre>
<p>I've used this technique occasionally, when there just isn't any obvious way to make it future-proof without dynamic SQL.</p>
<p>Note: In your loop, you can use the COALESCE/NULL propagation trick and leave the string as NULL before the loop, but it's not as clear if you are unfamiliar with the idiom:</p>
<pre><code>SET @sql = COALESCE(@sql + ' UNION ALL ', '')
+ 'SELECT * FROM [' + @TABLE_NAME + '] WHERE section_id=value '
</code></pre>
|
<p>I was going to suggest the same think as borjab. The only problem with that is that you will have to update all of these queries if you add another table. The only other option I see is a stored procedure.</p>
<p>I did think of another option here, or at least an easier way to present this. You can also use a view to these multiple tables to make them appear as one, and then your query would look cleaner, be easier to understand and you wouldn't have to rewrite a long union query when you wanted to do other queries on these multiple tables.</p>
| 12,979
|
<p>Is it possible to create an instance of a generic type in Java? I'm thinking based on what I've seen that the answer is <code>no</code> (<em>due to type erasure</em>), but I'd be interested if anyone can see something I'm missing:</p>
<pre><code>class SomeContainer<E>
{
E createContents()
{
return what???
}
}
</code></pre>
<p>EDIT: It turns out that <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=208860" rel="noreferrer">Super Type Tokens</a> could be used to resolve my issue, but it requires a lot of reflection-based code, as some of the answers below have indicated.</p>
<p>I'll leave this open for a little while to see if anyone comes up with anything dramatically different than Ian Robertson's <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=208860" rel="noreferrer">Artima Article</a>.</p>
|
<p>You are correct. You can't do <code>new E()</code>. But you can change it to</p>
<pre><code>private static class SomeContainer<E> {
E createContents(Class<E> clazz) {
return clazz.newInstance();
}
}
</code></pre>
<p>It's a pain. But it works. Wrapping it in the factory pattern makes it a little more tolerable.</p>
|
<p>You can with a classloader and the class name, eventually some parameters.</p>
<pre><code>final ClassLoader classLoader = ...
final Class<?> aClass = classLoader.loadClass("java.lang.Integer");
final Constructor<?> constructor = aClass.getConstructor(int.class);
final Object o = constructor.newInstance(123);
System.out.println("o = " + o);
</code></pre>
| 10,078
|
<p>I am trying to get the DB2 data provider from a 32-bit .Net application to connect to DB2 running as a 32-bit application on Vista 64 (is that confusing enough yet)? Unfortunately, I am getting the following error:</p>
<blockquote>
<p>SQL1159 Initialization error with DB2 .NET Data Provider, reason code 7, tokens 9.5.0.DEF.2, SOFTWARE\IBM\DB2\InstalledCopies</p>
</blockquote>
<p>There are several <a href="http://www-128.ibm.com/developerworks/forums/thread.jspa?threadID=207638&tstart=45" rel="nofollow noreferrer">IBM forum posts</a> mentioning it, but little useful guidance. Has anyone experienced this before? Or do you have better ideas for fixing it?</p>
|
<p>Are you required to have it run as x86? I had similar issues with web apps under Visual Studio's dev web server (which is x86), but switching over to IIS (x64) worked for me. Since I was deploying to IIS x64, I called it a day at that point.</p>
<p>I tried tracing with Filemon and Regmon, but didn't get any denied or missing keys errors. If I were to look again, I'd check HKLM\Software\WOW6432Node, guessing that the installer writes to the x64 HKLM\Software node, but not the x86 one.</p>
|
<p>I uninstalled the previous 32bit version, reinstalled as 64bit, and now I get a completely different error. Its mentioned as requiring FP2 to fix, but since I'm using Express-C, I can't install the fixpack (IBM doesn't provide fixpacks for free DB2 products). Anyway, thanks for the help. At least I can come closer to connecting now. :)</p>
| 4,901
|
<p>I currently use Notepad++ for most of my development. I have been checking out other, more full-featured options and would like to switch (I'm in particular a fan of Aptana so far) but there is one thing about Notepad++ that I really like and I haven't been able to get so far. </p>
<p>My current workflow is something like this: <a href="http://evanalyze.com/images/workflow" rel="nofollow noreferrer">Workflow</a> (I tried to embed this image and it showed up in previews but not in the post, sorry)
<a href="http://evanalyze.com/images/workflow.jpg" rel="nofollow noreferrer">Workflow http://evanalyze.com/images/workflow.jpg</a></p>
<p>The process is this:</p>
<ol>
<li>Download file from web server</li>
<li>Make edits in NP++</li>
<li>Save (this automatically saves a local copy in my default directory, which is also the folder I have setup using Subversion with Tourtise SVN)</li>
<li>When I want to commit a change to SVN, go through the local folder that has an up to date copy</li>
</ol>
<p>What I can't figure out how to do with Aptana is automatically store a local copy of a file I download from my server, edit and save back to the server. Is there some way to do this? If so, that would solve my problem immediately.</p>
<p>Other options would be a suggestion for a better way to manage the relationship between my server, my editor and my SVN repository. I know Aptana can access my SVN repository too. Is there an easy way to commit changes from within Aptana when I want to (which means I could take Tourtise out of the equation I guess)?</p>
<p>Any suggestions appreciated. Thanks.</p>
|
<p>I think you're doing things a bit strange.</p>
<p>You already have all your information in an SVN repository, so why not take advantage of that?</p>
<p>You keep a working copy on your computer for development and testing. Save and commit your changes to SVN. On your server, do an SVN <code>export</code> (or <code>checkout</code>, with appropriate server rules to block web access to the <code>.svn</code> folders), and you're sweet!</p>
<pre>
---------------------- ------------ ---------------
| Local Working Copy | <---> | SVN Repo | <---> | Live server |
---------------------- ------------ ---------------
</pre>
<p>This means you never have to worry about FTP, or have to figure out which files have been changed locally and hence need to be updated.</p>
|
<p>Eclipse has a plugin called <a href="http://www.eclipse.org/dsdp/tm/" rel="nofollow noreferrer">RSE</a> allow you to work on remote sources thru ssh,ftp etc.
You can use <a href="http://www.eclipse.org/pdt" rel="nofollow noreferrer">PDT</a> but I guess it may work on Aptana as well.</p>
<p>I'm using the Zend Studio For Eclipse which has both SVN and RSE built in.
I'm guessing it's the same in PDT (after installing the RSE plugin), you can either work directly in the RSE perspective or add a remove folder to your project (you can do this only after adding connections in the RSE)</p>
<p>BTW, I found the following link that can give you some more options for remote machine:
<a href="http://wiki.eclipse.org/index.php/TM_and_RSE_FAQ#Working_with_TM_.2F_RSE_as_a_User" rel="nofollow noreferrer">http://wiki.eclipse.org/index.php/TM_and_RSE_FAQ#Working_with_TM_.2F_RSE_as_a_User</a></p>
| 30,920
|
<p>I have written a console application that sets the size of the console and output buffer. My problem is that after the program ends I cannot resize my cmd.exe window the way I did before. After the program sets the size of the window it retains that size no matter what I do afterwards. </p>
|
<p>It works for me in C#. </p>
<pre><code>namespace CSharpTest
{
class Program
{
static void Main(string[] args)
{
System.Console.WindowHeight = 50;
System.Console.WindowWidth = 100;
System.Console.BufferHeight = 6000;
System.Console.BufferWidth = 100;
}
}
}
</code></pre>
<p>After running the program, I can change the height of the window and make it narrower, just like before. I can't make it wider, but then I couldn't before, either.</p>
|
<p>It is not clear what you mean. But are you setting the default values for all Cmd consoles when you change the size - That would make new cmd consoles that size too.</p>
<p>Could we have a bit more information about what you mean please.</p>
| 43,506
|
<p>What experience can you share about using multiple AJAX libraries?</p>
<p>There are useful features in Prototype, some in jQuery, the Yahoo library, etc. Is it possible to include all libraries and use what you want from each, do they generally all play nicely together with name spaces, etc. For the sake of speed is there a practical limit to the size/number of libraries to include or is this negligible? Are there pairs that work particularly well together (e.g. Prototype/Scriptaculous) or pairs that don't?</p>
|
<p>You could use all those libraries, but I highly recommend against it. Downloading and executing that much JavaScript will most likely choke the browser and slow down your user's experience. It would be much better from a user's perspective and a developer's to pick one. Less context/architecture switching and less code to maintain.</p>
<p>Like other answers have said, most don't conflict. </p>
<p>See Yahoo!'s <a href="http://developer.yahoo.com/performance/" rel="noreferrer">Exceptional Performance</a> site for more info. </p>
|
<p>Ruby on Rails uses both prototype and Scriptaculous by default, as there is little overlap between the two. I've also used yui snippets in addition to that and have never had a problem. Load times are an issue, but the libraries are usually cached, so it's only on the first page loaded.</p>
| 8,522
|
<p>Are there LaTeX packages for (more or less) easily drawing Gantt diagrams?</p>
<p>Thanks.</p>
|
<p>The <a href="http://www.ctan.org/pkg/pgfgantt" rel="noreferrer">pgfgantt</a> package is quite easy to use and does linking.</p>
|
<p>There is the <a href="http://www.ctan.org/tex-archive/graphics/pstricks/contrib/pst-gantt/" rel="nofollow noreferrer">pst-gantt package</a>. The bad news is, that you have to draw dependencies between the tasks yourself. So you need to use the <code>\psline</code> macro to draw lines and arrows.</p>
| 20,712
|
<p>I want to expand my programming horizons to Linux. A good, dependable basic toolset is important, and what is more basic than an IDE?</p>
<p>I could find these SO topics:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/2756/lightweight-ide-for-linux">Lightweight IDE for linux</a> and</li>
<li><a href="https://stackoverflow.com/questions/17228/what-tools-do-you-use-to-develop-c-applications-on-linux">What tools do you use to develop
C++ applications on Linux?</a></li>
</ul>
<p>I'm not looking for a <em>lightweight</em> IDE. If an IDE is worth the money, then I will pay for it, so it need not be free.</p>
<p>My question, then:</p>
<blockquote>
<p><em>What good, C++ programming IDE is available for Linux?</em></p>
</blockquote>
<p>The minimums are fairly standard: syntax highlighting, code completion (like <a href="http://en.wikipedia.org/wiki/IntelliSense" rel="nofollow noreferrer">intellisense</a> or its Eclipse counterpart) and integrated debugging (e.g., basic
breakpoints).</p>
<p>I have searched for it myself, but there are so many that it is almost impossible to separate the good from the bads by hand, especially for someone like me who has little C++ coding experience in Linux. I know that <a href="http://www.eclipse.org/cdt/" rel="nofollow noreferrer">Eclipse supports C++</a>, and I really like that IDE for Java, but is it any good for C++ and is there something better?</p>
<p>The second post actually has some good suggestions, but what I am missing is what exactly makes the sugested IDE so good for the user, what are its (dis)advantages?</p>
<p>Maybe my question should therefore be:</p>
<blockquote>
<p><em>What IDE do you propose (given your experiences), and why?</em></p>
</blockquote>
|
<h2>Initially: confusion</h2>
<p>When originally writing this answer, I had recently made the switch from Visual Studio (with years of experience) to Linux and the first thing I did was try to find a reasonable IDE. At the time this was impossible: no good IDE existed.</p>
<h2>Epiphany: UNIX is an IDE. <em>All of it.</em><sup>1</sup></h2>
<p>And then I realised that the IDE in Linux is the command line with its tools:</p>
<ul>
<li>First you set up your shell
<ul>
<li>Bash, in my case, but many people prefer</li>
<li><a href="https://fishshell.com/" rel="noreferrer">fish</a> or</li>
<li><a href="https://github.com/robbyrussell/oh-my-zsh" rel="noreferrer">(Oh My) Zsh</a>;</li>
</ul></li>
<li>and your editor; pick your poison — both are state of the art:
<ul>
<li><a href="https://neovim.io/" rel="noreferrer">Neovim</a><sup>2</sup> or</li>
<li><a href="https://www.gnu.org/software/emacs/" rel="noreferrer">Emacs</a>.</li>
</ul></li>
</ul>
<p>Depending on your needs, you will then have to install and configure several plugins to make the editor work nicely (that’s the one annoying part). For example, most programmers on Vim will benefit from the <a href="https://valloric.github.io/YouCompleteMe/" rel="noreferrer">YouCompleteMe</a> plugin for smart autocompletion.</p>
<p>Once that’s done, the shell is your command interface to interact with the various tools — Debuggers (gdb), Profilers (gprof, valgrind), etc. You set up your project/build environment using <a href="https://www.gnu.org/software/make/" rel="noreferrer">Make</a>, <a href="https://bitbucket.org/snakemake/snakemake/wiki/Home" rel="noreferrer">CMake</a>, <a href="https://bitbucket.org/snakemake/snakemake/wiki/Home" rel="noreferrer">SnakeMake</a> or any of the various alternatives. And you manage your code with a version control system (most people use <a href="https://git-scm.com/" rel="noreferrer">Git</a>). You also use <a href="https://tmux.github.io/" rel="noreferrer">tmux</a> (previously also screen) to multiplex (= think multiple windows/tabs/panels) and persist your terminal session.</p>
<p>The point is that, thanks to the shell and a few tool writing conventions, these all <em>integrate with each other</em>. And that way <strong>the Linux shell is a truly integrated development environment</strong>, completely on par with other modern IDEs. (This doesn’t mean that individual IDEs don’t have features that the command line may be lacking, but the inverse is also true.)</p>
<h2>To each their own</h2>
<p>I cannot overstate how well the above workflow functions once you’ve gotten into the habit. But some people simply prefer graphical editors, and in the years since this answer was originally written, Linux has gained a suite of excellent graphical IDEs for several different programming languages (but not, as far as I’m aware, for C++). Do give them a try even if — like me — you end up not using them. Here’s just a small and biased selection:</p>
<ul>
<li>For Python development, there’s <a href="https://www.jetbrains.com/pycharm/" rel="noreferrer">PyCharm</a></li>
<li>For R, there’s <a href="https://www.rstudio.com/" rel="noreferrer">RStudio</a></li>
<li>For JavaScript and TypeScript, there’s <a href="https://code.visualstudio.com/" rel="noreferrer">Visual Studio Code</a> (which is also a good all-round editor)</li>
<li>And finally, many people love the <a href="https://www.sublimetext.com/" rel="noreferrer">Sublime Text editor</a> for general code editing.</li>
</ul>
<p>Keep in mind that this list is far from complete.</p>
<hr>
<p><sup>1</sup> I stole that title from dsm’s comment.</p>
<p><sup>2</sup> I used to refer to Vim here. And while plain Vim is still more than capable, Neovim is a promising restart, and it’s modernised a few old warts.</p>
|
<blockquote>
<p><a href="https://stackoverflow.com/questions/24109/c-ide-for-linux#219039">why wouldn't you also use it for C++?
CDT meets every requirement you've
mentioned.</a></p>
</blockquote>
<p>I didn't use eclipse at first because I wasn't sure that it was equally good at giving me the means of developing in C++ (efficiently). Besides that, I was also convinced that there had to be better, more specialized tools available for c++ development in Linux: </p>
<blockquote>
<p>and I really like that [eclipse] IDE for java,
but is it any good for c++ and won't I
miss out on something that is even
better?</p>
</blockquote>
<p>I honestly believe that, although some tools (like eclipse) are great at many things, it is best to look for other options as well (and I don't mean that for IDE's only, but in general and even in <em>real life</em>)...<br>
Like in this case, vim is really great, and I would have missed out on it if I sticked to something I already knew. </p>
| 4,386
|
<p>Unable to find a SQL diff tool that meets my needs, I am writing my own. Between the INFORMATION_SCHEMA and sys tables, I have a mostly-complete working version. But one thing I can't find in the metadata is the <em>definition</em> of a trigger, you know, the actual SQL code. Am I overlooking something?</p>
<p>Thanks.</p>
<hr>
<p>Thanks, Pete, I didn't know about that!</p>
<p>Scott, I'm working with very basic hosting packages that don't allow remote connections to the DB. I don't know from the specs on RedGate (which I can't afford anyway) whether they provide a workaround for that, and although there are also API's out there (such as the one from Apex), I didn't see the point in investing in a solution that was still going to require more programming on my part. :)</p>
<p>My solution is to drop an ASPX page on the site that acts as a kind of "schema service", returning the collected metadata as XML. I set up a little AJAX app that compares any number of catalog instances to a master and shows the diffs. It's not perfect, but a major step forward for me.</p>
<p>Thanks again!</p>
|
<p>sp_helptext works to get the sql that makes up a trigger.</p>
<p>The text column in the syscomments view also contains the sql used for object creation.</p>
|
<p>this query return trigger with its name and body.</p>
<pre><code>Select
[tgr].[name] as [trigger name],
[tbl].[name] as [table name] ,
OBJECT_DEFINITION(tgr.id) body
from sysobjects tgr
join sysobjects tbl
on tgr.parent_obj = tbl.id
WHERE tgr.xtype = 'TR'
</code></pre>
| 6,566
|
<p>In the application I'm writing, one of the methods allows for the numbers the user entered to be turned into letters.</p>
<p>For example, the user will be entering grades (as doubles) and the program will decide (when the criteria is met) to return the letter associated with the number. Initially, I had it written like this:</p>
<pre><code>public void GetGrade(double scores)
Console.Write("Score of {0} earns: ", score);
if (score >= 95.0)
Console.WriteLine("A+");
else if (score >= 90.0)
Console.WriteLine("A");
else if (score >= 85.0)
Console.WriteLine("B+");
else if (score >= 80.0)
Console.WriteLine("B");
else if (score >= 75.0)
Console.WriteLine("C+");
else if (score >= 70.0)
Console.WriteLine("C");
else if (score >= 65.0)
Console.WriteLine("D+");
else if (score >= 60.0)
Console.WriteLine("D");
else
Console.WriteLine("F");
</code></pre>
<p>But it needs to be written with a RETURN in mind.
So, I think it should be public string <code>GetGrade(double scores)</code>
And since it's in an array I would need:</p>
<pre><code>foreach(double score in scoress)
{
THE CODE I POSTED ABOVE
}
</code></pre>
<p>Except I'd change all the <code>console.writeline</code>s to return.
However, when I do that I get a syntax error telling me:</p>
<blockquote>
<p>A local variable named score cannot be declared in this scope because it would give a different meaning to 'score', which is already used in parent or current scope to denote something else.</p>
</blockquote>
<p>So, I gather that I cannot use <code>score</code> because the header already contains <code>score</code>.
How do I go about getting this to work the way I want it to?</p>
|
<p>Your question is confusing. </p>
<blockquote>
<p>And since its in an array...</p>
</blockquote>
<p>but none of your examples include an array. Your method would work fine as</p>
<pre><code>public string ToGrade(double score)
{
if (score >= 95.0)
return "A+";
else if (score >= 90.0)
return "A";
/* snip */
else
return "YOU GET NOTHING! YOU LOSE! GOOD DAY SIR!";
}
</code></pre>
<p>Seems to me your method isn't the issue, its the code in which you're calling it that's the problem. You'll have to post that to get a correct answer to your question.</p>
<p>If you're getting an array of "grades" and transforming them into a bunch of letter grades, you'll have to have an array to store the letter grades. Something like this may be what you need:</p>
<pre><code>public static string[] ToGrade(double[] grades)
{
// sanity checks go here
string[] result = new string[grades.Length];
for(int i = 0; i < grades.Length; i++)
result[i] = ToGrade(grades[i]);
return result;
}
</code></pre>
|
<pre><code>var list = [
[95.0, "A+"],
[90.0, "A"],
[85.0, "B+"],
[80.0, "B"],
[75.0, "C+"],
[70.0, "C"],
[65.0, "D+"],
[60.0, "D"]
];
for (var i in list)
if (score >= list[0])
return list[1];
return "F";
</code></pre>
| 42,510
|
<p>In some editors there exist plugins implementing a feature called "hungry backspace" or "hungry delete".</p>
<p>If this mode is active in a text editor then one hit to the backspace key will automatically delete all whitespace chars backwards from the current cursor position up to the first non-whitespace character.</p>
<p>For example, this feature exists for <a href="http://www.gnu.org/software/emacs/manual/html_node/ccmode/Hungry-WS-Deletion.html" rel="nofollow noreferrer">Emacs</a> and <a href="http://plugins.intellij.net/plugin/?id=162" rel="nofollow noreferrer">IntelliJ IDEA</a>.</p>
<p>Does anyone know if it is also available in Eclipse?</p>
|
<p>Alt-Del is probably as close as you're going to get without writing a plugin yourself. Others have asked for this feature (coming from intelliJ) but so far it doesn't exist, or it's not published.</p>
<p>-Adam</p>
|
<p>In SciTE, and Eclipse (3.4), Ctrl+Shift+Del with the caret after the last visible character will delete these spaces. Ie. it deletes from caret to end of line.</p>
<p>Actually, in SciTE I don't need to do that, since I have set it up to automatically remove these trailing spaces when saving.</p>
<p>Note: In Preferences > General > Keys, there is a Remove Trailing Whitespace binding (without key assignment by default) which seems to apply to File.</p>
| 38,436
|
<p>How can I use Doxygen to create the HTML documentation as a single, very long file? I want something like the RTF output, but as HTML.</p>
<p>The reason: I need my API published as a single, printable, document. Something that can be loaded into Word, converted to PDF, etc.</p>
|
<p>I think you can use <a href="https://www.msweet.org/htmldoc/index.html" rel="nofollow noreferrer">HTMLDOC</a> to convert the generated html files to a single html file. (I did not try it myself)</p>
<p>The <a href="https://www.msweet.org/htmldoc/htmldoc.html" rel="nofollow noreferrer">manual</a> includes the following example to generate a html from two source html files:</p>
<pre><code>htmldoc --book -f output.html file1.html file2.html
</code></pre>
<p>But there is also a gui.</p>
|
<p>I don't think there's an option that will produce the output as a single HTML file, but the RTF output may be suitable if you need an editable output format (I haven't tried this myself so I don't know how well this works).</p>
<p>If you want good quality printable output, then Doxygen can output LaTeX format (set <code>GENERATE_LATEX</code> to <code>YES</code> in your doxygen configuration file). This can then be converted to PDF, although you'll need to install a LaTeX distribution such as <a href="http://miktex.org/" rel="nofollow noreferrer">MiKTeX</a>.</p>
| 48,909
|
<p>Are there any <strong>good</strong> grid-hosting companies out there that offer .NET stacks? Something like MediaTemple - which won't host the worlds fastest websites, but for the price is far better than "shared hosting". I've used Rackspace's Mosso, but it sucked - it never felt like a normal .NET stack (caching was odd, site recompilation was odd).</p>
|
<p>Try <a href="http://www.gogrid.com" rel="noreferrer">gogrid.com</a> they seem to have a very nice following in the cloud computing circles.</p>
|
<p>can talk a bit more about the not so normal .net experience? I was thinking to go for Mosso...</p>
| 2,631
|
<p>I'm currently maintaining some flex code and noticed very many functions which are declared like:</p>
<pre><code>private function exampleFunc():void {
....
}
</code></pre>
<p>These functions are in the <em>global scope</em>, and aren't part of any specific class, so it's a bit unclear to me what effect declaring them as private would have. What restrictions does the "private" qualifier have for functions like this?</p>
|
<p>The actionscript functions that are included in your mxmlc code will we available as a part of your mxmlc component, which behind the scenes is compiled into a class. Therefore marking them as private makes them inaccessible. </p>
<p>Here is an example to make that clear, say you have the following component, we'll call it FooBox:</p>
<pre>
<code>
<!-- FooBox.mxml -->
<mx:Box xmlns:mx="http://www.macromedia.com/2003/mxml">
<mx:Script><![CDATA[
private function foo():void {
lbl.text = "foo";
}
public function bar():void {
lbl.text = "bar";
}
]]></mx:Sctipt>
<mx:Label id="lbl">
</mx:Box>
</code>
</pre>
<p>I can now add FooBox to my application, and use it's functions:</p>
<pre>
<code>
<mx:Application
xmlns:mx="http://www.macromedia.com/2003/mxml"
xmlns:cc="controls.*"
>
<mx:Script><![CDATA[
private function init():void {
fbox.foo(); // opps, this function is unaccessible.
fbox.bar(); // this is ok...
}
]]></mx:Sctipt>
<cc:FooBox id="fbox" />
</mx:Application>
</code>
</pre>
<p>If the actionscript functions are included in your Main Application file, the I <em>think</em> you can call the functions from an child control through the Application.application object, something like:</p>
<pre>
<code>
Application.application.bar();
</code>
</pre>
<p>if the bar function was placed in the main mxmlc code. </p>
|
<p>What do you mean by global scope? Are these functions declared in the main MXML file?</p>
<p>In general, private means that functions can only be called from within the class that declares them.</p>
| 37,722
|
<p>I want to create a class which implements IEnumerable<T> but, using reflection, generates T's and returns them via IEnumerable<T>, where T' is a entirely constructed subclass of T with some properties hidden and others read-only. </p>
<p>Okay., that might not be very clear. Let me explain this via the medium of code - I'd like to have a class CollectionView<T> as follows:-</p>
<pre><code>public class CollectionView<T> : IEnumerable<T> {
public CollectionView(IEnumerable<T> inputCollection,
List<string> hiddenProperties, List<string> readonlyProperties) {
// ...
}
// IEnumerable<T> implementation which returns a collection of T' where T':T.
}
...
public class SomeObject {
public A { get; set; }
public B { get; set; }
public C { get; set; }
}
...
var hiddenProperties = new List<string>(new[] { "A" });
var readOnlyProperties = new List<string>(new[] { "C" });
IEnumerable<SomeObject> someObjects = CollectionView<SomeObject>(hiddenProperties,
readOnlyProperties);
...
dataGridView1.DataSource = someObjects;
</code></pre>
<p>(When displayed in dataGridView1 shows columns B and C and C has an underlying store which is read-only)</p>
<p>Is this possible/desirable or have I completely lost my mind/does this question demonstrate my deep inadequacy as a programmer?</p>
<p>I want to do this so I can manipulate a collection that is to be passed into a DataGridView, <em>without having to directly manipulate the DataGridView to hide columns/make columns read-only</em>. So no 'oh just use dataGridView1.Columns.Remove(blah) / dataGridView1.Columns[blah].ReadOnly = true' answers please!!</p>
<p>Help!</p>
|
<p><a href="http://www.castleproject.org/dynamicproxy/index.html" rel="nofollow noreferrer">Castle.DynamicProxy</a> will help you accomplish this.
What you would do is create an interceptor that inherits T. You would store the collection of hidden and read-only properties. When a getter or setter is called, the interceptor would check to see if the property exists in either collection and then take appropriate action. </p>
<p>However, I know not how you would hide a property. You cannot change the access modifier of a base class in a derived class. You MAY be able to use the <code>new</code> keyword, but I know not how to do that with Castle.DynamicProxy.</p>
|
<p>You just can't hide properties, even by creating subclassed proxies. You could at least construct a different type dynamically, which holds good properties, but it would not be a <code>T</code>.</p>
<p>But returning an object list could be sufficient if you just need to use databinding.</p>
| 16,244
|
<p>I am trying to help a small business that has an application that could benefit from occasional (or temporary) database expertise. The problem is, this company has all their IP in this database, so they are rightfully hesitant to give someone access it. </p>
<p>They would typically meet and gain trust in person, but the talent pool within physical proximity to them is pretty limited. I would like to think that they could still somehow tap into the global DBA expertise though...</p>
<p>Even the crappiest DBA will be able to dance SQL Circles around these guys - so exposing only pieces of the database doesn't sound feasible to me, but I am hoping I just don't know how. </p>
<p>Anyone have any tips on how they could find a trustworthy company (or individual)? When I hire a programmer, I start them on basic stuff that if they mess up won't hurt too much. With a database, is there something that I can start with that can limit their exposure. Maybe Profiler output for analysis or something?</p>
|
<p>As the others have mentioned, NDA's are a good idea, that covers you from the standpoint of WHAT they see...</p>
<p>However, I can feel that you are also concerned about any potential "damage" the person could do to your database if they make mistakes. To get around, and protect from this is a bit harder, but there a few good key items that I would recommend.</p>
<ol>
<li>BACKUP EVERYTHING before starting, this is common sense, but cannot be overstated</li>
<li>Provide the consultant a test environment if you are able to replicate production issues. This gives an isolated environment where testing can be done.</li>
<li>DO NOT limit their database access. Database issues require digging into the system, limiting their access, could actually contribute to an error rather than preventing them.</li>
<li>Look for references, or evidence of the persons abilities.</li>
</ol>
<p>I provide this information as a consultant myself. I do .NET and SQL Server consulting, and I ensure that all of the above are true in my consulting cases, and I have not had a fault. Steven points out the biggest key in this all and that is <strong>all a consultant has is his reputation</strong>. Serious consultants fully understand this, and because of it will make sure that they do NOT put themselves into tricky situations.</p>
|
<p>consultants sign NDAs all the time, and the good ones take them seriously because a consultant's reputation is <em>all he has</em></p>
<p>while not a DBA, i can highly recommend <a href="http://www.nov8r.com/about.aspx" rel="nofollow noreferrer">this fellow</a> as I have known him all my life ;-)</p>
| 37,463
|
<p>I'm looking for a high performance Java library for fuzzy string search.</p>
<p>There are numerous algorithms to find similar strings, Levenshtein distance, Daitch-Mokotoff Soundex, n-grams etc.</p>
<p>What Java implementations exists? Pros and cons for them? I'm aware of Lucene, any other solution or Lucene is best?</p>
<p>I found these, does anyone have experience with them? </p>
<ul>
<li><a href="http://www.dcs.shef.ac.uk/~sam/simmetrics.html" rel="noreferrer">SimMetrics</a> </li>
<li><a href="http://ngramj.sourceforge.net/" rel="noreferrer">NGramJ</a> </li>
</ul>
|
<p>Commons Lang has an implementation of <a href="http://commons.apache.org/lang/apidocs/org/apache/commons/lang3/StringUtils.html#getLevenshteinDistance%28java.lang.CharSequence,%20java.lang.CharSequence%29" rel="noreferrer">Levenshtein distance</a>.</p>
<p>Commons Codec has an implementation of <a href="http://commons.apache.org/proper/commons-codec/apidocs/org/apache/commons/codec/language/Soundex.html" rel="noreferrer">soundex</a> and <a href="http://commons.apache.org/proper/commons-codec/apidocs/org/apache/commons/codec/language/Metaphone.html" rel="noreferrer">metaphone</a>.</p>
|
<p>You can try bitap. I was playing with bitap written in ANSI C and it was pretty fast there is java implementation in <a href="http://www.crosswire.org" rel="nofollow noreferrer">http://www.crosswire.org</a>. </p>
| 42,443
|
<p>How can i release the memory that I used for a variable (e.g. a long string) in C?</p>
|
<p>Assuming that you allocated the memory dynamically (using <code>malloc</code> or another memory allocator) you free it using <code>free</code>. If the memory was statically allocated, you can't free it.</p>
|
<p>I'd suggest you have a look at <a href="http://www.and.org/ustr/" rel="nofollow noreferrer">ustr</a>, which is a string API that you can use with automatic, constant and dynamicly allocated strings ... only two of which you can actually "free", but all of which you can treat the same way and pass to ustr_free().</p>
<p>You might well still want to learn about how the stack, the heap and data (RO text strings) are "allocated" and "freed" ... but using a usable API while you are learning that will stop help you you a lot (and are going to be much faster than what you'd do on your own).</p>
| 23,622
|
<p>There are so many little options and settings within Microsoft Visual Studio. Which adjustments do you recommend to others?</p>
|
<p><strong>Line Numbers</strong></p>
<ul>
<li>Tools > Options</li>
<li>Text Editor > All Languages > General</li>
<li>Display: Line Numbers</li>
</ul>
<p><img src="https://i.stack.imgur.com/urAYz.png" alt="Visual Studio Line Numbers"></p>
|
<p>Besides, Line Numbers, the first thing I always do in a newly-installed IDE is set the <strong><code>Edit.GoToDefinition</code></strong> keyboard shortcut.</p>
<p>Tools > Options > Keyboard</p>
| 22,934
|
<p>I have a CR-10S 500 and want to change a capacitor on it to improve and solve temperature issues. This capacitor that needs to be changed should be labeled as "C4" as mentioned on <a href="https://www.jozerworx.com/creality-cr-10s-c4-capacitor-diy-fix-tutorial/" rel="nofollow noreferrer">this</a> post but it's not present on my motherboard. The goal is to replace 100uF capacitor with 220uF 16V capacitor.</p>
<p>This is what the motherboard <strong>should</strong> look like:</p>
<p><a href="https://i.stack.imgur.com/AgZyh.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AgZyh.jpg" alt="enter image description here"></a></p>
<p>but mine looks different. Below is what it looks like:</p>
<p><a href="https://i.stack.imgur.com/Aw0Ww.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Aw0Ww.jpg" alt="enter image description here"></a></p>
<p>There is no version number on my motherboard and there is no "C4" capacitor. Also, the component that's labeled "330" on the original board is labeled "470" on my motherboard. It's hard to decide which capacitor to change. On my motherboard, there two capacitors instead of one, closer to the location of the capacitor that needs to be replaced. They are labeled "C42" and "C35" instead of "C4". I do not want to replace the wrong one since it's risky enough to replace just one capacitor on these boards.</p>
<p>Anyone know my motherboard type or version? Also, which capacitor to change?</p>
<p>EDIT:</p>
<p>Here is a better or zoomed in section of the place:</p>
<p><a href="https://i.stack.imgur.com/896Ft.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/896Ft.jpg" alt="enter image description here"></a></p>
<p>As <a href="https://3dprinting.stackexchange.com/questions/7462/which-capacitor-to-change-on-cr-10s-s500-motherboard#comment11920_7462">Trish</a> requested in the comment, below is also the back side of the motherboard.</p>
<p><a href="https://i.stack.imgur.com/oj12r.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oj12r.jpg" alt="enter image description here"></a></p>
<p>theSealion might be right in his answer and I did a test and it all points to "C31" as he suggested but the problem is that the capacitor is different from the one it is supposed to be replaced with like on other CR-10 boards. I am not entirely sure if this is the capacitor since the type of capacitor are different from the one I was suggested to use. Below is the new capacitor:</p>
<p><a href="https://i.stack.imgur.com/O4iFm.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/O4iFm.jpg" alt="enter image description here"></a></p>
<p>My current idea is to remove the tiny "C31", solver wire to pin 4 of LM2596 and to the new capacitor but I do not want to remove the "C31" because I don't want anything to go bad. </p>
<p>Can I add the new capacitor parallel to the existing "C31" without removing the "C31"?</p>
|
<p>You are looking for a capacitor that must be connected to Pin 4 of the LM2596.</p>
<p>Maybe you could provide a better picture of that area so we could see the different tracks on the board.</p>
<p>The LM2596 is in the center of the right side of the board (it is also labeled with LM2596D). The pins should be counted from top to bottom (in your picture)</p>
<p>My guess is, the Elko you are looking for is connected to C31, and you must look for the positive pin.</p>
<p><a href="https://i.stack.imgur.com/1h1U6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1h1U6.png" alt="LM2596 Wiring"></a></p>
<p>In this wiring diagram Cout is the capacitor you are looking for. The SMD Parts R1, R2 and CFF should be R31, R32 and C31 in your picture.</p>
<p>With the corresponging measurements I would say you do not need to replace the capacitors. </p>
<p>In comparison to the old board your board already has the "fix" implemented. </p>
|
<h1>You are looking at the wrong board</h1>
<p>Your board might on the surface look like a Creality v 2.0 board, and is indeed from the same family of boards. After trying to discern the parts and finally resorting to google image search, I almost had to maniacally laugh:</p>
<p>The currently latest version is the <a href="https://www.creality3d.shop/products/mainboard-upgraded-replacement-controller-board-latest-v2-1-version-motherboard-for-creality-cr-10s-s4-s5-3d-printer" rel="nofollow noreferrer">Creality 2.1</a>, but your board clearly is a pre 2.0 board, as the 2.0 and 2.1 are quite similar, almost identical in the areas in question. According to the standard nomenclature, a 2.X board should be a full new engineering or vastly re-engineered board. So I looked up a Creality 1.X board - And indeed, it looks somewhat closer to a CR-10 motherboard in the area around the black capacitor, but that is marked 150/151. So it is <a href="https://www.creality3d.shop/collections/accessories/products/creality-cr-10-motherboard" rel="nofollow noreferrer">not a Creality 1.1.2 / 1.1.3</a>, also known as "CR-10" board.</p>
<p>My best guess (Confirmed by OP and <a href="https://www.th3dstudio.com/knowledge-base/creality-cr-10-and-cr-10s-models-what-printer-do-you-have/" rel="nofollow noreferrer">this</a>) is, that your board is an intermediate step between the Creality 1.1.x Board for the CR-10 and the <em>new</em> CR-10S 2.0/2.1, so by nomenclature a <em>proto-2.0</em>. Among Makers, it is called "original CR-10S" at times. Your numbers should thus be read from this board:</p>
<p><a href="https://i.stack.imgur.com/Zgh0z.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Zgh0z.jpg" alt="Original CR10S Board" /></a></p>
<p>There is a 100/35V/UT Capacity in the indicated spot in both the green and black renditions.</p>
| 1,098
|
<p>I'm currently working on an application where we have a SQL-Server database and I need to get a full text search working that allows us to search people's names.</p>
<p>Currently the user can enter a into a name field that searches 3 different varchar cols. First, Last, Middle names</p>
<p>So say I have 3 rows with the following info.</p>
<p>1 - Phillip - J - Fry</p>
<p>2 - Amy - NULL - Wong</p>
<p>3 - Leo - NULL - Wong</p>
<p>If the user enters a name such as 'Fry' it will return row 1. However if they enter Phillip Fry, or Fr, or Phil they get nothing.. and I don't understand why its doing this. If they search for Wong they get rows 2 and 3 if they search for Amy Wong they again get nothing.</p>
<p>Currently the query is using CONTAINSTABLE but I have switched that with FREETEXTTABLE, CONTAINS, and FREETEXT without any noticeable differences in the results. The table methods are be preferred because they return the same results but with ranking.</p>
<p>Here is the query.</p>
<pre><code>....
@Name nvarchar(100),
....
--""s added to prevent crash if searching on more then one word.
DECLARE @SearchString varchar(100)
SET @SearchString = '"'+@Name+'"'
SELECT Per.Lastname, Per.Firstname, Per.MiddleName
FROM Person as Per
INNER JOIN CONTAINSTABLE(Person, (LastName, Firstname, MiddleName), @SearchString)
AS KEYTBL
ON Per.Person_ID = KEYTBL.[KEY]
WHERE KEY_TBL.RANK > 2
ORDER BY KEYTBL.RANK DESC;
....
</code></pre>
<p>Any Ideas...? Why this full text search is not working correctly ?</p>
|
<p>If you're just searching people's names, it might be in your best interest to not even use the full text index. Full text index makes sense when you have large text fields, but if you're mostly dealing with one word per field, I'm not sure how much extra you would get out of full text indexes. Waiting for the full text index to reindex itself before you can search for new records can be one of the many problems.</p>
<p>You could just make a query such as the following. Split your searchstring on spaces, and create a list of the search terms.</p>
<pre>
Select FirstName,MiddleName,LastName
From person
WHERE
Firstname like @searchterm1 + '%'
or MiddleName like @searchterm1 + '%'
or LastName like @searchterm1 + '%'
or Firstname like @searchterm2 + '%'
etc....
</pre>
|
<p>FreeTextTable should work.</p>
<pre><code>INNER JOIN FREETEXTTABLE(Person, (LastName, Firstname, MiddleName), @SearchString)
</code></pre>
<p>@SearchString should contain the values like 'Phillip Fry' (one long string containing all of the lookup strings separated by spaces).</p>
<p>If you would like to search for Fr or Phil, you should use asterisk: Phil* and Fr*</p>
<p>'Phil' is looking for exactly the word 'Phil'. 'Phil*' is looking for every word which is starting with 'Phil'</p>
| 3,776
|
<p>I've been impressed by the screencasts for Rails that demonstrate the built-in web server, and database to allow development and testing to occur on the local machine. How can I get an instance of Apache to execute a project directory as its DocumentRoot, and maybe serve up the files on port 8080 (or something similar)?</p>
<p>The reason why I'm asking is that I'm going to be trying out CodeIgniter, and I would like to use it for multiple projects. I would rather not clutter up my machine's DocumentRoot with each one. Suggestions on how to do database migrations are also welcome.</p>
<hr />
<p>Thank you for your responses so far. I should clarify that I'm on Mac OS X. It looks like WAMP is Windows-only. Also, XAMPP looks like a great way to install Apache and many other web tools, but I don't see a way of loading up an instance to serve up a project directory. Mac OS X has both Apache and PHP installed - I'm just looking for a way to get it to serve up a project on a non-standard port.</p>
<p>I just found <a href="http://www.mamp.info/en/mamp-pro/" rel="nofollow noreferrer">MAMP Pro</a> which does what I want, but a more minimalist approach would be better if it's possible. Does anyone have a <code>httpd.conf</code> file that can be edited and dropped into a project directory?</p>
<p>Also, sorry that I just threw in that database migration question. What I'm hoping to find is something that will enable me to push schema changes onto a live server without losing the existing data. I suspect that this is difficult and highly dependent on environmental factors.</p>
|
<p>Your Mac comes with both an Apache Web Server and a build of PHP. It's one of the big reasons the platform is well loved by web developers.</p>
<p>Since you're using Code Igniter, you'll want PHP 5, which is the default version of PHP shipped with 10.5. If you're on a previous version of the OS hop on over to <a href="http://www.entropy.ch/home/" rel="nofollow noreferrer">entropy.ch</a> and install the provided PHP5 package.</p>
<p>Next, you'll want to turn Apache on. In the sharing preferences panel, turn on personal web sharing. This will start up apache on your local machine.</p>
<p>Next, you'll want to setup some fake development URLs to use for your sites. Long standing tradition was that we'd use the fake TLD .dev for this (ex. stackoverflow.dev). However, <code>.dev</code> is now an actual TLD so you probably don't want to do this -- <code>.localhost</code> seems like an emerging defacto standard. Edit your /etc/hosts file and add the following lines</p>
<pre><code>127.0.0.1 www.example.localhost
127.0.0.1 example.localhost
</code></pre>
<p>This points the above URLs at your local machine. The last step is configuring apache. Specifically, enabling named virtual hosting, enabling PHP and setting up a few virtual hosts. If you used the entropy PHP package, enabling PHP will already be done. If not, you'll need to edit your http.conf file as described <a href="http://foundationphp.com/tutorials/php_leopard.php" rel="nofollow noreferrer">here</a>. Basically, you're uncommenting the lines that will load the PHP module.</p>
<p>Whenever you make a change to your apache config, you'll need to restart apache for the changes to take effect. At a terminal window, type the following command</p>
<pre><code>sudo apachectl graceful
</code></pre>
<p>This will gracefully restart apache. If you've made a syntax error in the config file apache won't restart. You can highlight config problems with</p>
<pre><code>sudo apachectl configtest
</code></pre>
<p>So,with PHP enabled, you'll want to turn on NamedVirtualHosts. This will let apache respond to multiple URLs. Look for the following (or similar) line in your http.conf file and uncomment it.</p>
<pre><code>#NameVirtualHost *
</code></pre>
<p>Finally, you'll need to tell apache where it should look for the files for your new virtual hosts. You can do so by adding the following to your http.conf file. NOTE: I find it's a good best practice to break out config rules like this into a separate file and use the include directive to include your changes. This will stop any automatic updates from wiping out your changes.</p>
<pre><code><VirtualHost *>
DocumentRoot /Users/username/Sites/example.localhost
ServerName example.localhost
ServerAlias www.example.localhost
</VirtualHost>
</code></pre>
<p>You can specify any folder as the DocumentRoot, but I find it convenient to use your personal Sites folder, as it's already been configured with the correct permissions to include files.</p>
|
<p>You could use a low up front setup package such as <a href="http://www.apachefriends.org/en/index.html" rel="nofollow noreferrer">XAMPP</a> and run it as a separate instance. There are many other similar projects as well.</p>
| 14,415
|
<p>Is there any way to validate the width and height of image when uploaded?
using javascript of server side ? like jsp, aspx etc?</p>
|
<p>If you're using the Java platform, you can use <a href="http://java.sun.com/javase/6/docs/api/javax/imageio/ImageIO.html" rel="nofollow noreferrer">ImageIO</a> to read the image, then use <code>getHeight</code> and <code>getWidth</code> on the <a href="http://java.sun.com/javase/6/docs/api/java/awt/image/BufferedImage.html" rel="nofollow noreferrer"><code>BufferedImage</code></a> returned from the read operation.</p>
<p>I admit this is quite a heavyweight approach, so I'm sure there is an even better approach. I just have to find it. :-P</p>
<p>As for .NET, I have no idea. :-)</p>
|
<p>I've done this by execing the Image Magick "identify" command.</p>
<p>Easy enough if you're using Unix - although I think it runs on Windows too.</p>
<p>I doubt you can do it client-side.</p>
| 22,507
|
<p>We have inherited VB6 dll which we need to make changes to. We have the code but don't have VB6 compiler. How can we rebuild the dll? Where can we download the VB6 environment/compiler from?
Thanks in advance.</p>
|
<p>VB6 is still available as a part of the MSDN subscription.</p>
|
<p>You can import the legacy VB6 code into a newer version of Visual Studio.</p>
<p>Just open the VB6 project using <em>File → Open → Convert</em> and it'll automatically upgrade the VB6 code to the current version.</p>
| 28,454
|
<p>How to export pictures in Microsoft Word to TIFF file using Visual Studio Tools for Office? I can obtain a reference to the pictures as InlineShape object collection, the hard part now is how to save them as TIFF images.</p>
|
<p>OK guys, I got the problem solved. Here's the code snippet:</p>
<pre><code> private void SaveToImage(Word.InlineShape picShape, string filePath)
{
picShape.Select();
theApp.Selection.CopyAsPicture();
IDataObject data = Clipboard.GetDataObject();
if (data.GetDataPresent(typeof(Bitmap)))
{
Bitmap image = (Bitmap)data.GetData(typeof(Bitmap));
image.Save(filePath);
}
}
</code></pre>
<p>Hope it helps :)</p>
|
<p>Well. not sure if this is helpful, but you if you are okay with jpegs, then one really cool technique for extracting images from Word 2007 file is as follows:</p>
<ol>
<li>Rename the .docx file to .zip.</li>
<li>Under the (now) zip file, go to the following path: word/media.</li>
<li>All the images in the document are found here as jpeg files.</li>
</ol>
<p>Cheers.</p>
| 20,501
|
<p>in the out of the project template solution (Dynamic Data Web Application), I have the model created and all is good. - Get the list of the tables, and the select edit etc.</p>
<p>But my database has linking tables that just contain forgien keys - so the list template just displays the fk value</p>
<p><img src="https://lh6.ggpht.com/_KoHB_k0rTus/SSUbvobGucI/AAAAAAAAAB4/MYPlVYtB2zQ/s288/PARLinkTable.jpg" alt="diagram of the table"></p>
<p>Is there away to combine the list of the row in the primary table with an inspection of another table based on the fk?</p>
<p>More akin to a join in SQL? but using Linq2Entity and the MetaModel?</p>
<p>Below is the List.aspx.cs - this seems to bind the standard grid to the entitydatasource, but this is to the current table as per the route in the MVC.</p>
<p>But as you can see i need to go and query the Person, Role and Link table via the model to get the other fields so that this would be useful.
<img src="https://lh5.ggpht.com/_KoHB_k0rTus/SSUd7yGYUgI/AAAAAAAAADI/cbHUjV1GfrA/VS-Plain.jpg" alt="vstudio"></p>
<p>PS want to try and keep this in LINQ2Entity if possible -trying to grok</p>
<p>the natural thing that I want to do is start to spin off new sql queries to go and retrive the values. But this is not in this idiom.</p>
|
<p>you can reference the metaModel via the dataContext</p>
<pre><code>MetaModel refMetaModel = MetaModel.GetModel(typeof(yourdataContextName));
MetaTable refMetaModel;
refMetaModel = refMetaModel.GetTable("yourTableName");
</code></pre>
<p>PS looked at your code and this works in your sceanrio. You can get the tables from the model then inspect the data returned for each table in the model</p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.web.dynamicdata.metamodel.aspx" rel="nofollow noreferrer">MSDN article on the MetaModel</a></p>
|
<p>Uselful to use this as well from the Linq to Entities Model - </p>
<p>Using the dataContext - you can get the acutal data most useful.</p>
<p>The metaModel allows access to the dataModel which gives you the underlying ddl type information </p>
<pre><code>//use the datacontext to get the underlying data
using (brrdbEntities brr = new brr_dbEntities())
{
ObjectQuery<person> people = brr.person;
IQueryable<string> names = from p in people select p.person_name;
foreach (var name in names)
</code></pre>
| 38,871
|
<p>What books have helped you get a grasp of n-Tier development (Presentation Layer, UI Business Objects, Data Business Objects, and Data sets)? </p>
<p>I'd prefer books, but blogs and other sites are welcome suggestions too. I've inherited a n-Tier designed application at a new job and although it's taken me some time to get used to it, I see the usefulness of the concepts. Moving forward, I want to make sure my development falls in the same standards. A focus in C# would be great too. </p>
<p>Also, are there other design patterns that you would suggest for scalability? Is there any suggested reading you can provide for those design patterns?</p>
|
<p>Reading <a href="http://martinfowler.com/books.html#eaa" rel="noreferrer">Patterns of Enterprise Application Architecture</a> (PoEAA) was a great eye-opener for me. It's geared towards the web, and goes into great detail in explaining how all those tiers ought to interact.</p>
<p>IIRC, examples are in both C# and Java. </p>
|
<p>books are great for specifics and details of certain solutions/approaches, but the <a href="http://en.wikipedia.org/wiki/Separation_of_concerns" rel="nofollow noreferrer">Separation of Concerns</a> principle is sufficient to logically derive the n-tier architecture</p>
| 49,655
|
<p>Based on geographical data in classic GIS formats. These matrices are a basic input for different vehicle routing problems and such. They can usually be produced an best time or shortest distance basis.</p>
|
<p><a href="http://www.codeplex.com/quickgraph" rel="nofollow noreferrer">QuickGraph</a></p>
|
<p><a href="http://thinkgeo.com/" rel="nofollow">ThinkGeo</a> has a routing extension that you can use to build a matrix with. This does involve some extra work.</p>
| 16,202
|
<p>-Edit-
FYI.. I am converting b&w documents scanned in as greyscale or color. </p>
<p>1)The first solution worked, it just reversed black & white (black background, white text). It also took nearly 10 minutes.<br>
2)The JAI solution in the 2nd answer didn't work for me. I tried it before posting here.</p>
<p>Has anyone worked with other libraries free or pay that handle image manipulation well?</p>
<p>-Original-
I am trying to convert an PNG to a bitonal TIFF using Java ImageIO. Has anyone had any luck doing this? I have got it to convert from PNG to TIFF. I am not sure if I need to convert the BufferedImage (PNG) that I read in or convert on the TIFF as I write it. I have searched and searched but nothing seems to work? Does anyone have an suggestions where to look?</p>
<p>Here is the code that converts... </p>
<pre><code>public static void test() throws IOException {
String fileName = "4848970_1";
// String fileName = "color";
String inFileType = ".PNG";
String outFileType = ".TIFF";
File fInputFile = new File("I:/HPF/UU/" + fileName + inFileType);
InputStream fis = new BufferedInputStream(new FileInputStream(fInputFile));
ImageReaderSpi spi = new PNGImageReaderSpi();
ImageReader reader = spi.createReaderInstance();
ImageInputStream iis = ImageIO.createImageInputStream(fis);
reader.setInput(iis, true);
BufferedImage bi = reader.read(0);
int[] xi = bi.getSampleModel().getSampleSize();
for (int i : xi) {
System.out.println("bitsize " + i);
}
ImageWriterSpi tiffspi = new TIFFImageWriterSpi();
TIFFImageWriter writer = (TIFFImageWriter) tiffspi.createWriterInstance();
// TIFFImageWriteParam param = (TIFFImageWriteParam) writer.getDefaultWriteParam();
TIFFImageWriteParam param = new TIFFImageWriteParam(Locale.US);
String[] strings = param.getCompressionTypes();
for (String string : strings) {
System.out.println(string);
}
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionType("LZW");
File fOutputFile = new File("I:\\HPF\\UU\\" + fileName + outFileType);
OutputStream fos = new BufferedOutputStream(new FileOutputStream(fOutputFile));
ImageOutputStream ios = ImageIO.createImageOutputStream(fos);
writer.setOutput(ios);
writer.write(null, new IIOImage(bi, null, null), param);
ios.flush();
writer.dispose();
ios.close();
}
</code></pre>
<p>I have tried changing the compression to type "CCITT T.6" as that appears to be what I want, but I get an error " Bits per sample must be 1 for T6 compression! " Any suggestion would be appreciated. </p>
|
<p>Most likely, you want something like <a href="http://image4j.sourceforge.net/javadoc/net/sf/image4j/util/ConvertUtil.html" rel="nofollow noreferrer">this</a> to convert to 1 bit before you save to TIFF with CCITT compression.</p>
<p>To expound a little bit - be aware that converting from other bit depths to 1 bit is non-trivial. You are doing a data reduction operation and there are dozens of domain specific solutions which vary greatly in output quality (blind threshold, adaptive threshold, dithering, local threshold, global threshold and so on). None of them are particularly good at all image types (adaptive threshold is pretty good for documents, but lousy for photographs, for example).</p>
|
<p>As plinth said, you have to do the conversion, Java won't do it magically for you...
If the PNG image is already black & white (as it seems, looking at your comment), using a threshold is probably the best solution.</p>
<p>Somebody seems to have the same problem: <a href="http://forums.java.net/jive/thread.jspa?threadID=17031" rel="nofollow noreferrer" title="HELP: how to compress the tiff">HELP: how to compress the tiff</a>. A solution is given on the thread (untested!).</p>
| 39,301
|
<p>Py3k <a href="http://mail.python.org/pipermail/python-list/2008-December/518408.html" rel="nofollow noreferrer">just came out</a> and has gobs of <a href="http://docs.python.org/3.0/whatsnew/3.0.html" rel="nofollow noreferrer">neat new stuff</a>! I'm curious, what are SO pythonistas most excited about? What features are going to affect the way you write code on a daily basis, or have you been looking forward to?</p>
|
<p>There are a few things I'm quite interested in:</p>
<ul>
<li><em>Text and data</em> instead of <em>unicode and 8 bit</em></li>
<li><a href="http://www.python.org/dev/peps/pep-3132" rel="noreferrer">Extended Iterable Unpacking</a></li>
<li><a href="http://www.python.org/dev/peps/pep-3107/" rel="noreferrer">Function annotations</a></li>
<li>Binary literals</li>
<li><a href="http://www.python.org/dev/peps/pep-3110/" rel="noreferrer">New exception catching syntax</a></li>
<li>A number of Python 2.6 features, eg: the <em>with</em> statement</li>
</ul>
|
<p>Just about all of them as I am taking the release of Python 3 as motivation to learn the language.</p>
| 44,298
|
<p>Although the general case is undecidable, many people still do solve problems that are equivilent well enough for day to day use.</p>
<p>In cohen's phd thesis on computer viruses, he showed how virus scanning is equivilent to the halting problem, yet we have an entire industry based around this challenge.</p>
<p>I also have seen microsoft's terminator project - <a href="http://research.microsoft.com/Terminator/" rel="noreferrer">http://research.microsoft.com/Terminator/</a> </p>
<p>Which leads me to ask - is the halting problem overrated - do we need to worry about the general case?</p>
<p>Will types become turing complete over time - dependant types do seem like a good development?</p>
<p>Or, to look the other way, will we begin to use non turing complete languages to gain the benefits of static analysis ?</p>
|
<blockquote>
<p>Is solving the halting problem easier than people think?</p>
</blockquote>
<p>I think it is exactly as difficult as people think.</p>
<blockquote>
<p>Will types become turing complete over time?</p>
</blockquote>
<p><a href="http://en.wikipedia.org/wiki/C%2B%2B#Templates" rel="noreferrer">My dear, they already are!</a></p>
<blockquote>
<p>dependant types do seem like a good development?</p>
</blockquote>
<p>Very much so.</p>
<p>I think there could be a growth in non-Turing complete-but-provable languages. For quite some time, SQL was in this category (it isn't any more), but this didn't really diminish its utility. There is certainly a place for such systems, I think.</p>
|
<p>The Halting Problem is really only interesting if you look at it in the general case, since if the Halting problem were decidable, all other undecidable problems would also be decidable via reduction.</p>
<p>So, my opinion on this question is, no, it is not easy in the cases that matter. That said, in the real world, it may not be such a big deal.</p>
<p>See also: <a href="http://en.wikipedia.org/wiki/Halting_problem#Importance_and_consequences" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Halting_problem#Importance_and_consequences</a></p>
| 6,196
|
<p>Recently, I read an article entitled <a href="http://alumnit.ca/~apenwarr/log/?m=200809#08" rel="nofollow noreferrer">"SATA vs. SCSI reliability"</a>. It mostly discusses the very high rate bit flipping in consumer SATA drives and concludes "A 56% chance that you can't read all the data from a particular disk now". Even Raid-5 can't save us as it must be constantly scanned for problems and if a disk does die you are pretty much guaranteed to have some flipped bits on your rebuilt file system.</p>
<p>Considerations:</p>
<p>I've heard great things about Sun's <a href="http://en.wikipedia.org/wiki/ZFS" rel="nofollow noreferrer">ZFS</a> with <a href="http://en.wikipedia.org/wiki/Non-standard_RAID_levels#RAID-Z" rel="nofollow noreferrer">Raid-Z</a> but the Linux and BSD implementations are still experimental. I'm not sure it's ready for prime time yet.</p>
<p>I've also read quite a bit about the <a href="http://en.wikipedia.org/wiki/Parchive" rel="nofollow noreferrer">Par2</a> file format. It seems like storing some extra % parity along with each file would allow you to recover from most problems. However, I am not aware of a file system that does this internally and it seems like it could be hard to manage the separate files.</p>
<p>Backups (Edit):</p>
<p>I understand that backups are paramount. However, without some kind of check in place you could easily be sending bad data to people without even knowing it. Also figuring out which backup has a good copy of that data could be difficult. </p>
<p>For instance, you have a Raid-5 array running for a year and you find a corrupted file. Now you have to go back checking your backups until you find a good copy. Ideally you would go to the first backup that included the file but that may be difficult to figure out, especially if the file has been edited many times. Even worse, consider if that file was appended to or edited after the corruption occurred. That alone is reason enough for block-level parity such as Par2.</p>
|
<p>That article significantly exaggerates the problem by misunderstanding the source. It assumes that data loss events are independent, ie that if I take a thousand disks, and get five hundred errors, that's likely to be one each on five hundred of the disks. But actually, as anyone who has had disk trouble knows, it's probably five hundred errors on one disk (still a tiny fraction of the disk's total capacity), and the other nine hundred and ninety-nine were fine. Thus, in practice it's not that there's a 56% chance that you can't read all of your disk, rather, it's probably more like 1% or less, but most of the people in that 1% will find they've lost dozens or hundreds of sectors even though the disk as a whole hasn't failed.</p>
<p>Sure enough, practical experiments reflect this understanding, not the one offered in the article.</p>
<p>Basically this is an example of "Chinese whispers". The article linked here refers to another article, which in turn refers indirectly to a published paper. The paper says that of course these events are <em>not independent</em> but that vital fact disappears on the transition to easily digested blog format.</p>
|
<p>56% chance I can't read something, I doubt it. I run a mix of RAID 5 and other goodies and just good backup practices but with Raid 5 and a hot spare I haven't ever had data loss so I'm not sure what all the fuss is about. If you're storing parity information ... well you're creating a RAID system using software, a disk failure in R5 results in a parity like check to get back the lost disk data so ... it is already there.</p>
<p>Run Raid, backup your data, you be fine :)</p>
| 11,206
|
<p>Expanding this question on how I learnt to pass from <a href="https://stackoverflow.com/questions/137375/"> problem description to code </a> Two people mentioned TDD.</p>
<p>Would it be good for a starter to get into TDD ( and avoid bad habits in the future ? ) Or would it be too complex for a stage when understand what a programming language is?</p>
|
<p>TDD is meant to be simpler than the "traditional" method (of not testing it till the end) - because the tests clarify what you understand of the problem. If you actually didn't have a clear idea of what the problem was, writing tests is quite hard. </p>
<p>So for a beginner, writing tests gets the thinking juice going in the right direction, which is contractual behaviour, not implementation behaviour.</p>
|
<p>Yes! Definitely. </p>
| 16,643
|
<p>According to the C# compiler and the Silverlight 2 documentation, Silverlight doesn't provide a FindName method for the DataTemplate class. I want to find a Border that's inside a ContentPresenter. What's the best way in SilverLight 2?</p>
|
<p>If the border is inside a DataTemplate, not a ControlTemplate, then the only way I've been able to do that in the past is to use VisualTreeHelper to locate the element I need.</p>
|
<p>Not totally sure I understand the scenario, but since you mention the DataTemplate I'm assuming you're using a template. </p>
<p>If you're using a template then what you do is give your border a name (x:Name="border") and then override the OnApplyTemplate method. In that method you use GetTemplateChild and pass the name you used. This will return a reference to your border.</p>
<p>If you're not use a template and have a reference to the ContentPresenter then you could write a recursive function that looks at the Content property of the child and if it isn't a border then calls your same function on its content.</p>
| 36,666
|
<p>Some background: In Germany (at least) invoice numbers have to follow certain rules:</p>
<ol>
<li>The have to be ordered</li>
<li>They have to be continuous (may not have gaps)</li>
</ol>
<p>Since a few months they are allowed to contain characters. Some customers want to use that possibility and customers don't know that or are afraid and they insist on digit-only invoice numbers.</p>
<p>Additionally the customers don't want to start them at zero.</p>
<p>Is I can think of many ways to generate such a number I wonder: What's the best way to do this?</p>
|
<p>In order to avoid starting at 0 - just start at 10000. Forget about the zero-padding.</p>
<p>You have to consider when the number is going to be allocated.</p>
<p>If you allocate the number when the invoice is first opened for edit, for instance the number 10014 is allocated, and the user cancels the invoice then you have a gap, since you have to keep in mind that someone else could already have begun to create an invoice with the id 10015, so you can't just rollback the number.</p>
<p>If you allocate the number when the invoice has been completely written and is being saved then you'll avoid the scenario, and you'll avoid having gaps, but you will not know which invoice number the invoice is going to have before it is saved.</p>
<p>Also, you need to make sure that it is threadsafe, so that two users can't create the same invoice number.</p>
<pre><code>static object _invoiceNumberLock = new object();
public static string GetInvoiceNumber()
{
lock(_invoiceNumberLock)
{
//Connect to database and get MAX(invoicenumber)+1
//Increase the invoicenumber in SQL database by one
//Perhaps also add characters
}
}
</code></pre>
<p>Also consider backing up the uniqueness by having a UNIQUE INDEX on the invoicenumber column in the SQL database.</p>
|
<p>For my invoices, they always consist of the last digit of the year followed by a 4-digit invoice number starting at 4096, so you would get a value like 85021. This was to easily handle billing my (up to) 15 clients twice a month.</p>
<p>It's irrelevant now since I raise only about 6 invoices a year (I went permanent and now only do small bits of work, mostly leaving the company for investment purposes) but this scheme always worked for me.</p>
<p>It stopped the clients from feeling that they were getting work done by a small company (no invoice number 1 or even 80001).</p>
<p>In terms of the sequential nature, the invoices were simply stored in files with the invoice number in the file name, so it was easy to create the next one. No database was required - it really depends on how big your shop is.</p>
| 40,089
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.