instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>I've been trying to use Zsh within my emacs session, without emacs remapping all the Zsh keys. I found ansi-term works pretty well for this but, I'm still having some problems. I was getting lots of junk characters outputted with, I was able to fix it with:</p>
<pre><code>## Setup proper term information for emacs ansi-term mode
[[ $TERM == eterm-color ]] && export TERM=xterm
</code></pre>
<p>But everything still doesn't work perfectly. Now I am having trouble with output being drawn offscreen , especially when using something like C-r for search.</p>
<p>What I found is that it works fine if you don't resize the window. I can reproduce it like:</p>
<ol>
<li>Launch a clean <code>emacs -q</code></li>
<li>Start <code>ansi-term</code> and use <code>zsh</code></li>
<li>Make window fullscreen</li>
<li>Output something that fills the screen</li>
<li>Type <kbd>C-r</kbd></li>
<li>The prompt will be off the screen</li>
</ol>
<p>Maybe there is some way I can make the space between the output and the minibuffer larger to compensate for the overshoot?</p>
<p>Anyone else have Zsh + Ansi-term working properly?</p>
|
<p>Try <a href="http://www.emacswiki.org/emacs/MultiTerm">MultiTerm</a>.</p>
<p>Its the only Emacs terminal mode that seems to play nice with zsh. It allows you to easily set which commands you want captured by emacs and which you want routed to the terminal. The default settings have been good enough for me so far though.</p>
<p>Also, add the following to your .zshrc to allow emacs to track your current directory as you cd around.</p>
<pre><code>if [ -n "$INSIDE_EMACS" ]; then
chpwd() { print -P "\033AnSiTc %d" }
print -P "\033AnSiTu %n"
print -P "\033AnSiTc %d"
fi
</code></pre>
|
<p>I figured it out. It was an emacs config problem. This bit of elisp in my .emacs was causing it:</p>
<pre><code>(custom-set-variables
'(fringe-mode nil nil (fringe))
'(fringes-outside-margins t t))
</code></pre>
<p>Thanks for the help.</p>
| 47,956
|
<p>I have a query which is meant to show me any rows in table A which have not been updated recently enough. (Each row should be updated within 2 months after "month_no".):</p>
<pre><code>SELECT A.identifier
, A.name
, TO_NUMBER(DECODE( A.month_no
, 1, 200803
, 2, 200804
, 3, 200805
, 4, 200806
, 5, 200807
, 6, 200808
, 7, 200809
, 8, 200810
, 9, 200811
, 10, 200812
, 11, 200701
, 12, 200702
, NULL)) as MONTH_NO
, TO_NUMBER(TO_CHAR(B.last_update_date, 'YYYYMM')) as UPD_DATE
FROM table_a A
, table_b B
WHERE A.identifier = B.identifier
AND MONTH_NO > UPD_DATE
</code></pre>
<p>The last line in the WHERE clause causes an "ORA-00904 Invalid Identifier" error. Needless to say, I don't want to repeat the entire DECODE function in my WHERE clause. Any thoughts? (Both fixes and workarounds accepted...)</p>
|
<p>This is not possible directly, because chronologically, WHERE happens <em>before</em> SELECT, which always is the last step in the execution chain.</p>
<p>You can do a sub-select and filter on it:</p>
<pre><code>SELECT * FROM
(
SELECT A.identifier
, A.name
, TO_NUMBER(DECODE( A.month_no
, 1, 200803
, 2, 200804
, 3, 200805
, 4, 200806
, 5, 200807
, 6, 200808
, 7, 200809
, 8, 200810
, 9, 200811
, 10, 200812
, 11, 200701
, 12, 200702
, NULL)) as MONTH_NO
, TO_NUMBER(TO_CHAR(B.last_update_date, 'YYYYMM')) as UPD_DATE
FROM table_a A
, table_b B
WHERE A.identifier = B.identifier
) AS inner_table
WHERE
MONTH_NO > UPD_DATE
</code></pre>
<p>Interesting bit of info moved up from the comments:</p>
<blockquote>
<p>There should be no performance hit.
Oracle does not need to materialize
inner queries before applying outer
conditions -- Oracle will consider
transforming this query internally and
push the predicate down into the inner
query and will do so if it is cost
effective. – <a href="https://stackoverflow.com/users/10397/justin-cave">Justin Cave</a></p>
</blockquote>
|
<p>It's possible to effectively define a variable that can be used in both the SELECT, WHERE and other clauses.</p>
<p>A subquery doesn't necessarily allow for appropriate binding to the referenced table columns, however OUTER APPLY does.</p>
<pre><code>SELECT A.identifier
, A.name
, vars.MONTH_NO
, TO_NUMBER(TO_CHAR(B.last_update_date, 'YYYYMM')) as UPD_DATE
FROM table_a A
, table_b B ON A.identifier = B.identifier
OUTER APPLY (
SELECT
-- variables
MONTH_NO = TO_NUMBER(DECODE( A.month_no
, 1, 200803
, 2, 200804
, 3, 200805
, 4, 200806
, 5, 200807
, 6, 200808
, 7, 200809
, 8, 200810
, 9, 200811
, 10, 200812
, 11, 200701
, 12, 200702
, NULL))
) vars
WHERE vars.MONTH_NO > UPD_DATE
</code></pre>
<p>Kudos to <a href="https://smehrozalam.wordpress.com/2010/01/25/referring-computedcalculated-columns-in-the-where-and-group-by-clause/" rel="nofollow noreferrer">Syed Mehroz Alam</a>.</p>
| 46,508
|
<blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/48935/how-can-i-register-a-global-hot-key-to-say-ctrlshiftletter-using-wpf-and-ne">How can I register a global hot key to say CTRL+SHIFT+(LETTER) using WPF and .NET 3.5?</a> </p>
</blockquote>
<p>I'd like to have multiple global hotkeys in my new app (to control the app from anywhere in windows), and all of the given sources/solutions I found on the web seem to provide with a sort of a limping solution (either solutions only for one g.hotkey, or solutions that while running create annoying mouse delays on the screen).</p>
<p>Does anyone here know of a resource that can help me achive this, that I can learn from?
Anything?</p>
<p>Thanks ! :)</p>
|
<p>The nicest solution I've found is <a href="http://bloggablea.wordpress.com/2007/05/01/global-hotkeys-with-net/" rel="noreferrer">http://bloggablea.wordpress.com/2007/05/01/global-hotkeys-with-net/</a></p>
<pre><code>Hotkey hk = new Hotkey();
hk.KeyCode = Keys.1;
hk.Windows = true;
hk.Pressed += delegate { Console.WriteLine("Windows+1 pressed!"); };
hk.Register(myForm);
</code></pre>
<p>Note how you can set different lambdas to different hotkeys</p>
|
<p><a href="http://www.codeproject.com/KB/cs/CSLLKeyboardHook.aspx" rel="noreferrer">http://www.codeproject.com/KB/cs/CSLLKeyboardHook.aspx</a></p>
<p>If you're not using .net 3.5.</p>
| 10,670
|
<p>POSIX allows mutexes to be recursive. That means the same thread can lock the same mutex twice and won't deadlock. Of course it also needs to unlock it twice, otherwise no other thread can obtain the mutex. Not all systems supporting pthreads also support recursive mutexes, but if they want to be <a href="http://www.opengroup.org/onlinepubs/009695399/functions/pthread_mutexattr_gettype.html" rel="noreferrer">POSIX conform, they have to</a>.</p>
<p>Other APIs (more high level APIs) also usually offer mutexes, often called Locks. Some systems/languages (e.g. Cocoa Objective-C) offer both, recursive and non recursive mutexes. Some languages also only offer one or the other one. E.g. in Java mutexes are always recursive (the same thread may twice "synchronize" on the same object). Depending on what other thread functionality they offer, not having recursive mutexes might be no problem, as they can easily be written yourself (I already implemented recursive mutexes myself on the basis of more simple mutex/condition operations).</p>
<p>What I don't really understand: What are non-recursive mutexes good for? Why would I want to have a thread deadlock if it locks the same mutex twice? Even high level languages that could avoid that (e.g. testing if this will deadlock and throwing an exception if it does) usually don't do that. They will let the thread deadlock instead.</p>
<p>Is this only for cases, where I accidentally lock it twice and only unlock it once and in case of a recursive mutex, it would be harder to find the problem, so instead I have it deadlock immediately to see where the incorrect lock appears? But couldn't I do the same with having a lock counter returned when unlocking and in a situation, where I'm sure I released the last lock and the counter is not zero, I can throw an exception or log the problem? Or is there any other, more useful use-case of non recursive mutexes that I fail to see? Or is it maybe just performance, as a non-recursive mutex can be slightly faster than a recursive one? However, I tested this and the difference is really not that big.</p>
|
<p>The difference between a recursive and non-recursive mutex has to do with ownership. In the case of a recursive mutex, the kernel has to keep track of the thread who actually obtained the mutex the first time around so that it can detect the difference between recursion vs. a different thread that should block instead. As another answer pointed out, there is a question of the additional overhead of this both in terms of memory to store this context and also the cycles required for maintaining it.</p>
<p><em>However</em>, there are other considerations at play here too.</p>
<p>Because the recursive mutex has a sense of ownership, the thread that grabs the mutex must be the same thread that releases the mutex. In the case of non-recursive mutexes, there is no sense of ownership and any thread can usually release the mutex no matter which thread originally took the mutex. In many cases, this type of "mutex" is really more of a semaphore action, where you are not necessarily using the mutex as an exclusion device but use it as synchronization or signaling device between two or more threads.</p>
<p>Another property that comes with a sense of ownership in a mutex is the ability to support priority inheritance. Because the kernel can track the thread owning the mutex and also the identity of all the blocker(s), in a priority threaded system it becomes possible to escalate the priority of the thread that currently owns the mutex to the priority of the highest priority thread that is currently blocking on the mutex. This inheritance prevents the problem of priority inversion that can occur in such cases. (Note that not all systems support priority inheritance on such mutexes, but it is another feature that becomes possible via the notion of ownership).</p>
<p>If you refer to classic VxWorks RTOS kernel, they define three mechanisms:</p>
<ul>
<li><strong>mutex</strong> - supports recursion, and optionally priority inheritance. This mechanism is commonly used to protect critical sections of data in a coherent manner.</li>
<li><strong>binary semaphore</strong> - no recursion, no inheritance, simple exclusion, taker and giver does not have to be same thread, broadcast release available. This mechanism can be used to protect critical sections, but is also particularly useful for coherent signalling or synchronization between threads.</li>
<li><strong>counting semaphore</strong> - no recursion or inheritance, acts as a coherent resource counter from any desired initial count, threads only block where net count against the resource is zero.</li>
</ul>
<p>Again, this varies somewhat by platform - especially what they call these things, but this should be representative of the concepts and various mechanisms at play.</p>
|
<blockquote>
<p>What are non-recursive mutexes good for?</p>
</blockquote>
<p>They are absolutely good when you have to make sure the mutex is <strong>unlocked</strong> before doing something. This is because <code>pthread_mutex_unlock</code> can guarantee that the mutex is unlocked only if it is non-recursive.</p>
<pre><code>pthread_mutex_t g_mutex;
void foo()
{
pthread_mutex_lock(&g_mutex);
// Do something.
pthread_mutex_unlock(&g_mutex);
bar();
}
</code></pre>
<p>If <code>g_mutex</code> is non-recursive, the code above is guaranteed to call <code>bar()</code> with the mutex <em>unlocked</em>.</p>
<p>Thus eliminating the possibility of a deadlock in case <code>bar()</code> happens to be an unknown external function which may well do something that may result in another thread trying to acquire the same mutex. Such scenarios are not uncommon in applications built on thread pools, and in distributed applications, where an interprocess call may spawn a new thread without the client programmer even realising that. In all such scenarios it's best to invoke the said external functions only after the lock is released.</p>
<p>If <code>g_mutex</code> was recursive, there would be simply <em>no way</em> to make sure it is unlocked before making a call.</p>
| 22,748
|
<p>Okay, so I'm doing my first foray into using the ADO.NET Entity Framework. </p>
<p>My test case right now includes a SQL Server 2008 database with 2 tables, Member and Profile, with a 1:1 relationship.</p>
<p>I then used the Entity Data Model wizard to auto-generate the EDM from the database. It generated a model with the correct association. Now I want to do this:</p>
<pre><code>ObjectQuery<Member> members = entities.Member;
IQueryable<Member> membersQuery = from m in members select m;
foreach (Member m in membersQuery)
{
Profile p = m.Profile;
...
}
</code></pre>
<p>Which halfway works. I am able to iterate through all of the Members. But the problem I'm having is that m.Profile is always null. The examples for LINQ to Entities on the MSDN library seem to suggest that I will be able to seamlessly follow the navigation relationships like that, but it doesn't seem to work that way. I found that if I first load the profiles in a separate call somehow, such as using entities.Profile.ToList, then m.Profile will point to a valid Profile.</p>
<p>So my question is, is there an elegant way to force the framework to automatically load the data along the navigation relationships, or do I need to do that explicitly with a join or something else?</p>
<p>Thanks</p>
|
<p>Okay I managed to find the answer I needed here <a href="http://msdn.microsoft.com/en-us/magazine/cc507640.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/magazine/cc507640.aspx</a>. The following query will make sure that the Profile entity is loaded:</p>
<pre><code>IQueryable<Member> membersQuery = from m in members.Include("Profile") select m;
</code></pre>
|
<p>I used this technique on a 1 to many relationship and works well. I have a Survey class and many questions as part of that from a different db table and using this technique managed to extract the related questions ...</p>
<pre><code>context.Survey.Include("SurveyQuestion").Where(x => x.Id == id).First()
</code></pre>
<p>(context being the generated ObjectContext).</p>
<pre><code>context.Survey.Include<T>().Where(x => x.Id == id).First()
</code></pre>
<p>I just spend 10mins trying to put together an extention method to do this, the closest I could come up with is ...</p>
<pre><code> public static ObjectQuery<T> Include<T,U>(this ObjectQuery<T> context)
{
string path = typeof(U).ToString();
string[] split = path.Split('.');
return context.Include(split[split.Length - 1]);
}
</code></pre>
<p>Any pointers for the improvements would be most welcome :-)</p>
| 20,707
|
<p>I've got an old classic ASP site that connects to a local sql server 2000 instance. We're moving the db to a new box, and the port is non standard for sql (out of my control). .NET connection strings handle the port number fine by adding it with ,1999 after the server name/IP. The classic ASP connection string isn't working with the same syntax. I checked connectionstrings.com and couldn't find one that worked.</p>
<p>Current connection string (set to an Application variable in Global.asa):</p>
<pre><code>Driver={SQL Server};Server=xxx.xxx.xxx.xxx;Database=dbname;Uid=dbuser;Pwd=dbpassword
</code></pre>
<p>I've installed the SQL Native Client and couldn't get that working either (still working on this)</p>
<p>Any ideas?</p>
|
<p>The solution was installing the SQL Native Driver from MS, then updating the connection string to the following:</p>
<pre><code>Driver={SQL Native Client};Server=xxx.xxx.xxx.xxx,port;Database=dbname;Uid=dbuser;Pwd=dbpassword
</code></pre>
<p>I originally couldn't get it working with the SQL Native Client because of a firewall issue that was later resolved.</p>
|
<p>I think we need more information. What are you using to connect to the database? ODBC? OLE DB? Are you connecting through and ODBC DSN? Is the connection string in your ASP code, or is your data access via a VB or COM DLL?</p>
| 32,628
|
<p>This may seem a bit trivial, but I have not been able to figure it out. I am opening up a SPSite and then trying to open up a SPWeb under that SPSite. This is working fine on the VPC, which has the same Site Collection/Site hierarchy, but on production, I get an exception telling me that the URL is invalid when I try the SPSite.OpenWeb(webUrl);. I have verified that the URL’s are correct.</p>
<p>The Code:</p>
<pre><code> try
{
SPSite scheduleSiteCol = new SPSite(branchScheduleURL);
lblError.Text += Environment.NewLine + "Site Collection URL: " + scheduleSiteCol.Url;
SPWeb scheduleWeb = scheduleSiteCol.OpenWeb(branchScheduleURL.Replace(scheduleSiteCol.Url, "")); //<--- Throws error on this line
SPList scheduleList = scheduleWeb.GetList(branchScheduleURL + "/lists/" + SPContext.Current.List.Title);
return scheduleList.GetItemById(int.Parse(testID));
}
catch (System.Exception ex)
{
lblError.Text += Environment.NewLine + ex.ToString();
return null;
}
</code></pre>
<p>Note:<br>
branchScheduleURL is actually the whole URL that includes the URL of the Web as well.</p>
<p>The output + exception:</p>
<blockquote>
<p>Site Collection URL: <a href="https://ourSite.com/mocc" rel="nofollow noreferrer">https://ourSite.com/mocc</a>
<br>System.ArgumentException: Invalid URL: /internal/scheduletool. at Microsoft.SharePoint.SPSite.OpenWeb(String strUrl, Boolean requireExactUrl) at Microsoft.SharePoint.SPSite.OpenWeb(String strUrl) at MOCCBranchScheduleListWeb.MOCCBranchScheduleListV3.GetConflictListItem(String branchScheduleURL, String testID)System.NullReferenceException: Object reference not set to an instance of an object. at MOCCBranchScheduleListWeb.MOCCBranchScheduleListV3.CheckForConflicts(String[] cfcFlags1, DateTime startTime, DateTime endTime, String[] cfcFlags2)</p>
</blockquote>
<p>Note:<br><a href="https://ourSite.com/mocc/internal/scheduletool" rel="nofollow noreferrer">https://ourSite.com/mocc/internal/scheduletool</a> is the SPWeb I am trying to open.</p>
<p>Am I missing something obvious? Any help would be greatly appreciated.</p>
<p>Thanks.</p>
|
<p>Looks at the examples table at the bottom of <a href="http://msdn.microsoft.com/en-us/library/ms955307.aspx" rel="nofollow noreferrer">this page</a>.</p>
<p>Try not sending any parameters into the OpenWeb() method (2nd row).</p>
|
<p>It says your Site Collection URL is /mocc, thus your SPWeb underneath would be something like /mocc/internal/scheduletool. So do something like</p>
<p><code>string webServerRelativeUrl = site.ServerRelativeUrl + "/internal/scheduletool"</code></p>
| 23,349
|
<p>DDL for Database Tables:</p>
<pre><code> Users:
id - int - identity
name - varchar - unique
PCs:
id - int - idnetity
name - varchar - unique
userid - FK to Users
Apps:
id - int - identity
name - varchar
pcid - FK to PCs
</code></pre>
<p>I created a DataContext using the Linq To SQL designer in Visual Studio 2008.</p>
<p>I want to perform this query:</p>
<pre><code>select
users.name,
pcs.name,
apps.name
from
users u
join pcs p on p.userid = u.id
join apps a on a.pcid = p.id
</code></pre>
<p>I was told in another thread where I posted an answer that the following was incorrect and that it created a cross-join.</p>
<pre><code>var query = from u in db.Users // gets all users
from p in u.PCs // gets all pcs for user
from a in p.Apps // gets all apps for pc
select new
{
username = u.Name,
pcname = p.Name,
appname = a.Name
};
</code></pre>
<p>When I execute this query I get the correct results. A cross-join with two records in each table should return 8 records but my query correctly returns the two records.</p>
<p>Am I lucky, or is the person telling me that I'm wrong confused?</p>
|
<p>That will work. It's normal because the second "from" inquires in the PC's set of the users and the third "from", the Apps set of the pcs. And I guess that is not going generate a cross join as T-Sql, because the conditions are already defined in the foreign keys and associations.</p>
<p>But I guess this should be the syntactically you want by inner join;</p>
<pre><code>var query = from u in db.Users
join p in db.PCs on p.UserId == u.Id
join a in db.Apps on a.PCId == p.Id
select new
{
username = u.Name,
pcname = p.Name,
appname = a.Name
};
</code></pre>
|
<p>That looks fine to me, I'm not sure why that would create a cross join</p>
| 35,873
|
<p>I'm working on a project with a friend that will utilize Hbase to store it's data. Are there any good query examples? I seem to be writing a ton of Java code to iterate through lists of RowResult's when, in SQL land, I could write a simple query. Am I missing something? Or is Hbase missing something?</p>
|
<p>I think you, like many of us, are making the mistake of treating bigtable and HBase like just another RDBMS when it's actually a column-oriented storage model meant for efficiently storing and retrieving large sets of sparse data. This means storing, ideally, many-to-one relationships within a single row, for example. Your queries should return very few rows but contain (potentially) many datapoints.</p>
<p>Perhaps if you told us more about what you were trying to store, we could help you design your schema to match the bigtable/HBase way of doing things.</p>
<p>For a good rundown of what HBase does differently than a "traditional" RDBMS, check out this awesome article: <a href="http://blog.csdn.net/arthurbryant/article/details/6643933" rel="nofollow noreferrer">Matching Impedance: When to use HBase</a> by Bryan Duxbury.</p>
|
<p>Thanks for the reply Sean, and sorry for my late response. I often make the mistake of treating HBase like a RDBMS. So often in fact that I've had to re-write code because of it! It's such a hard thing to unlearn.</p>
<p>Right now we have only 4 tables. Which, in this case, is very few considering my background. I was just hoping to use <em>some</em> RDBMS functionality while mostly sticking to the column-oriented storage model.</p>
| 7,040
|
<p>I am planning to design an address validation for users registering in my app. Possibly validating by zipcode and state.</p>
<p>Any idea how to handle addresses from around the globe?</p>
<p>Do i need to insert all the zipcodes in the database and then validate the address. Any possible suggestion for the implementation?</p>
<p>Thanks and Welcome :)
Krisp</p>
|
<p>Since there is no international standard for zip codes and a list of all zip codes in the world would be out of date before you were finished putting it together, I suggest a smaller approach:</p>
<p>Identify the countries that you will have to handle most and develop seperate validation rules for each of them. Make certain that with this you handle a vast majority of your users (e.g. 95%, or98%). For all the other countries, just accept what they enter vithout further validation. </p>
<p>There are so many different address formats in the world that it is just not worth the effort (if at all possible) to handle them all.</p>
|
<p>Postal Codes can actually be a headache because in some places they can represent very tiny areas as opposed to the US where they often represent relatively large areas (except in a big city where they may represent a few blocks).</p>
<p>Look at Canada, their postal codes can actually represent very very tiny areas. Two stores on opposite sides of the street often have different Canadian postal codes. Also in a list of Canadian businesses, when merging the list it is not uncommon to see the same address with a slightly different postal code. This just indicates that a lot of people get it wrong. On a customer basis I don't know how realistic it is that they actually get their exact zip code right.</p>
<p><a href="http://www.columbia.edu/kermit/postal-ca.html" rel="nofollow noreferrer">http://www.columbia.edu/kermit/postal-ca.html</a></p>
<p>Basically it seems that each apartment or business dwelling may get their own zip code, which would make sense based upon what I have seen with Canadian business addresses.</p>
<p>The other point is that this is just Canada. Each European country will have its own address/postal code, so will Australia, Russia, etc... If you really want to do address verification, this is a major project.</p>
<p>To actually verify the address you need to to verify the postal code, city, and street. In the US the census releases the TIGER database files which often have a list of streets. But for other countries I don't know how you can get a list of streets. It may be best to look into a commercial package (maybe one of the GIS packages, although a lot of them only offer detailed addresses for the US/Canada and sometimes a few European countries).</p>
| 46,441
|
<p>AFAIK one of the objectives of Stack Overflow is to make sure anyone can come here and find <b>good</b> answers to her Perl related questions. Certainly beginners would ask what is the <a href="https://stackoverflow.com/questions/70573/best-online-%0Asource-to-learn-perl">best online source to learn Perl</a> but others might just want to ask a question.</p>
<p>Probably the friendliest place is the <a href="http://perlmonks.org/" rel="nofollow noreferrer">Monastery of Perl Monks</a>. It is a web site with a rating system similar to but more simple than Stack Overflow. You can find lots of good answers there and if you don't find an answer you can always ask.</p>
<p>The other big resource would be the mailing list of your local <a href="http://www.pm.org/" rel="nofollow noreferrer">Perl Mongers</a> group.</p>
<p>Where do <b>you</b> go when you are looking for an answer to a Perl related question?</p>
|
<p>It's worth noting that <a href="http://perlmonks.org" rel="nofollow noreferrer">http://perlmonks.org</a>, in addition to the fora, has the Chatterbox, where simple questions can be answered immediately in conversation with other users.</p>
<p>It requires <a href="http://perlmonks.org/?node=Create+a+New+User" rel="nofollow noreferrer">setting up an account</a> and <a href="http://perlmonks.org/?node=login" rel="nofollow noreferrer">logging in</a> before <a href="http://perlmonks.org/?node=fullpage+chat" rel="nofollow noreferrer">using the Chatterbox</a>, though.</p>
|
<p>I would say <a href="http://www.stackoverflow.com/">Stackoverflow</a></p>
| 12,553
|
<p>I'm developing an <code>ActiveX EXE</code> that exposes an specific class to a third-party software. This third-party software instanciates an object of this class and uses its methods. </p>
<p>Strangely, this third-party software destroys its object of my exposed class as soon as it calls an specific method, but I have no idea why this happens.</p>
<p>The only clue I have is that this method is the only one that returns a value. All the other ones are simple 'subs' that do not return any value, and when they are called nothing wrong happens.</p>
<p>I'm using VB6.</p>
<p>Do you guys have any idea of why it's happening?</p>
|
<p>Your object gets "destroyed" when the last reference to it is deleted. Thats normal COM behavior. Or is your object dying unexcepted and the third-party app is getting an activex error?</p>
<p>Some more questions:</p>
<ul>
<li>I don't know what you mean with "data server"? </li>
<li>Do you have access to the source code of the third-party app? </li>
<li>Are you sure, the third-party app holds a reference to your object? </li>
<li>Is your objects Class_Terminate Method called?</li>
</ul>
<p><strong>EDIT:</strong>
OK, when Class_Terminate is getting called its obvious, that the third-party app has dropped its reference to your object. </p>
|
<p>As Jan stated in COM it is normal, that your object is terminated if no one is referencing it. If you would like to do some kind of caching (e.g. keep the DB connection open), you can use a global variable defined in a bas-module.</p>
<p><strong>basGlobal.bas</strong></p>
<pre><code>Global AGlobalVariable As Object
</code></pre>
<p><strong>Connector.cls</strong></p>
<pre><code>Public Function GetFoo() As Object
If AGlobalVariable Is Nothing then
Set AGlobalVariable = ...
End If
Set GetFoo = AGlobalVariable
End Function
</code></pre>
| 29,719
|
<p>We have a class library where we keep a lot of the stuff that we often use when doing sharepoint development. How would you go around deploying this? Right now our best bet is to have it in a separate solution, and deploy that so that the assembly is deployed to GAC. That way we ensure that the assembly is deployed to all application tiers and is available. </p>
<p>Is there a better approach than this?</p>
|
<p>The GAC is usually your best choice. Like ensuring you deploy to all applications, it's also easier in terms of security.</p>
|
<p>If I remember correctly, putting it in the GAC is the recommended course of action.</p>
| 14,650
|
<p>In the middle of some refactoring and I've moved a resources file from one project to another. I think I clicked a warning telling me to Strongly type the resource file at one point and now I'm getting:</p>
<blockquote>
<p>Could not find any resources
appropriate for the specified culture
or the neutral culture. Make sure
"MyProject.Common.ResourceManagement.resources"
was correctly embedded or linked into
assembly "MyProject.Common" at compile
time, or that all the satellite
assemblies required are loadable and
fully signed.</p>
</blockquote>
<p>Which is from a MissingManifestResourceException I beleive.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.resources.missingmanifestresourceexception.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.resources.missingmanifestresourceexception.aspx</a></p>
<p>I've looked up a couple of the solutions:</p>
<ul>
<li><a href="http://weblogs.asp.net/ngur/archive/2003/12/28/46219.aspx" rel="nofollow noreferrer">http://weblogs.asp.net/ngur/archive/2003/12/28/46219.aspx</a></li>
<li><a href="http://jameswho.blogspot.com/2004/06/missingmanifestresourceexception.html" rel="nofollow noreferrer">http://jameswho.blogspot.com/2004/06/missingmanifestresourceexception.html</a></li>
<li><a href="http://support.microsoft.com/kb/318603" rel="nofollow noreferrer">http://support.microsoft.com/kb/318603</a></li>
</ul>
<p>But none of them seem relevant to my situation.</p>
<p>Any ideas? This has been bugging me for a few days now.</p>
<p>Am I doing something stupid?</p>
|
<p>Are you sure these resource files are embedded into the assembly? Maybe you've lost the "Embedded Resource" settings as you moved the files.
Further, the resource names may have changed. The fully qualified name of a resource is
AssemblyName + physical subfolder(s) + resource name</p>
|
<p>Can you export them to a text file from the original project and import them into the new project? If it's just key/value pairs it should be simple.</p>
| 30,093
|
<p>I'm looking for (simple) examples of problems for which JMS is a good solution, and also reasons why JMS is a good solution in these cases. In the past I've simply used the database as a means of passing messages from A to B when the message cannot necessarily be processed by B immediately.</p>
<p>A hypothetical example of such a system is where all newly registered users should be sent a welcome e-mail within 24 hours of registration. For the sake of argument, assume the DB does not record the time when each user registered, but instead a reference (foreign key) to each new user is stored in the pending_email table. The e-mail sender job runs once every 24 hours, sends an e-mail to all the users in this table, then deletes all the pending_email records.</p>
<p>This seems like the kind of problem for which JMS should be used, but it's not clear to me what benefit JMS would have over the approach I've described. One advantage of the DB approach is that the messages are persistent. I understand that JMS message queues can also be persisted, but in that case there seems to be little difference between JMS and the "database as message queue" approach I've described?</p>
<p>What am I missing?
- Don</p>
|
<p>JMS and messaging is really about 2 totally different things.</p>
<ul>
<li>publish and subscribe (sending a message to as many consumers as are interested - a bit like sending an email to a mailing list, the sender does not need to know who is subscribed</li>
<li>high performance reliable load balancing (message queues)</li>
</ul>
<p>See more info on <a href="http://activemq.apache.org/how-does-a-queue-compare-to-a-topic.html" rel="noreferrer">how a queue compares to a topic</a></p>
<p>The case you are talking about is the second case, where yes you can use a database table to kinda simulate a message queue. </p>
<p>The main difference is a JMS message queue is a high performance highly concurrent load balancer designed for huge throughput; you can send usually tens of thousands of messages per second to many concurrent consumers in many processes and threads. The reason for this is that a message queue is basically highly asynchronous - a <a href="http://activemq.apache.org/what-is-the-prefetch-limit-for.html" rel="noreferrer">good JMS provider will stream messages ahead of time to each consumer</a> so that there are thousands of messages available to be processed in RAM as soon as a consumer is available. This leads to massive throughtput and very low latency.</p>
<p>e.g. imagine writing a web load balancer using a database table :)</p>
<p>When using a database table, typically one thread tends to lock the whole table so you tend to get very low throughput when trying to implement a high performance load balancer.</p>
<p>But like most middleware it all depends on what you need; if you've a low throughput system with only a few messages per second - feel free to use a database table as a queue. But if you need low latency and high throughput - then JMS queues are highly recommended.</p>
|
<p>The 'database as message queue' solution may be heavy for the task. The JMS solution is less tightly coupled in that the message sender does not need to know anything about the recipient. This could be accomplished with some additional abstraction in the 'database as message queue' as well so it is not a huge win...Also, you can use the queue in a 'publish and subscribe' way which can be handy depending on what you are trying to accomplish. It is also a nice way to further decouple your components. If all of your communication is within one system and/or having a log that is immediately available to an application is very important, your method seems good. If you are communicating between separate systems JMS is a good choice. </p>
| 27,378
|
<p>I have two questions.</p>
<ol>
<li><p>Do <code>realloc()</code> and <code>memcpy()</code> copy the entries in an array to another in a way faster than just iterating on each element <code>O(N)</code> ? If the answer is yes then what do you think is its complexity ?</p></li>
<li><p>If the size allocated is smaller than the original size, does <code>realloc()</code> copy the entries to somewhere else or just leave them as they are decreasing the size of the array ?</p></li>
</ol>
|
<p>1 - No. They copy a block at a time. See <a href="http://www.embedded.com/design/configurable-systems/4024961/Optimizing-Memcpy-improves-speed" rel="noreferrer">http://www.embedded.com/design/configurable-systems/4024961/Optimizing-Memcpy-improves-speed</a> for a pretty good analysis.</p>
<p>2 - This is implementation dependent. See <a href="http://www.gnu.org/software/libtool/manual/libc/Changing-Block-Size.html" rel="noreferrer">http://www.gnu.org/software/libtool/manual/libc/Changing-Block-Size.html</a> for glibc details. "In several allocation implementations, making a block smaller sometimes necessitates copying it"</p>
|
<p>Presuming you are talking about glibc, and since your questions are implementation dependent, it's probably best just to check the source:</p>
<p><a href="http://sourceware.org/cgi-bin/cvsweb.cgi/libc/malloc/malloc.c?rev=1.190&content-type=text/x-cvsweb-markup&cvsroot=glibc" rel="nofollow noreferrer">malloc.c</a></p>
<p><a href="http://sourceware.org/cgi-bin/cvsweb.cgi/libc/string/memcpy.c?rev=1.1&content-type=text/x-cvsweb-markup&cvsroot=glibc" rel="nofollow noreferrer">memcpy.c</a></p>
<p>The way I read it, the answers would be:</p>
<ol>
<li>O(N) --- there is no way to copy items in better than linear time.</li>
<li>Occasionally large items will be copied when realloc() is used to shrink them.</li>
</ol>
| 47,347
|
<p>First sorry for my bad english but I'll try my best.</p>
<p>Right now I'm programming a .net application using Access 2007 as datastore.</p>
<p>In a nutshell: I have two threads. One thread inserts a row with a transaction into a table. The other thread updates many rows in constant intervals. </p>
<p><strong>Thread 1</strong></p>
<pre><code>Database db = _loggingDatabase;
using (DbConnection conn = db.CreateConnection())
{
conn.Open();
DbTransaction txn = conn.BeginTransaction();
try
{
string qryInsert = "Insert this";
DbCommand cmdIns = db.GetSqlStringCommand(qryInsert);
db.ExecuteNonQuery(cmdIns, txn);
txn.Commit();
}
catch (Exception ex)
{
txn.Rollback();
throw ex;
}
finally
{
conn.Close();
}
</code></pre>
<p><strong>Thread 2</strong></p>
<pre><code> Database db = _loggingDatabase;
using (DbConnection conn = db.CreateConnection())
{
conn.Open();
DbTransaction txn = conn.BeginTransaction();
try
{
string qryUpdate = "Update that";
DbCommand cmdUpdt = db.GetSqlStringCommand(qryUpdate);
db.ExecuteNonQuery(cmdUpdt, txn);
txn.Commit();
}
catch (Exception ex)
{
txn.Rollback();
throw ex;
}
finally
{
conn.Close();
}
</code></pre>
<p>If I trigger to insert many records I'll get an System.Data.OleDb.OleDbException which says: "Could not update; currently locked". I tried to change the Connectionstring to </p>
<pre><code>connectionString="Provider=Microsoft.ACE.OLEDB.12.0; Data Source=datastore.accdb; Jet OLEDB:Database Locking Mode=1;"
</code></pre>
<p>with no effects on my application behavior. I descided to uses those transactions to avoid chaotic inserts and updates.</p>
<p>Is there a workaround?
What am I doing wrong?
Can I insert my transactions to some kind of transaction queue into Access?
Why isn't Access doing this by itselft?</p>
|
<p>Stefan Gruber asked:</p>
<blockquote>
<p>Can I insert my transactions to some
kind of transaction queue into Access?
Why isn't Access doing this by
itselft?</p>
</blockquote>
<p>I think you are failing to understand the Jet database engine. First off, a clarification: MS may use "MS Access" as the name in it's ODBC and OLEDB connection strings, but you're not using Access at all in that case -- just Access's default database engine, Jet.</p>
<p>Jet is not a server database engine. That is, there is no server process standing between clients and the MDB file where the data is stored. All "users" of an MDB file are accessing it via the file system. To manage multi-user access, there is a locking file (the LDB file) that keeps track of what tables/records are locked and what kinds of locks. Jet checks that LDB file in order to determine what it can and cannot do.</p>
<p>Now, because there is no server-level process to manage all interaction with the on-disk data, there is no possibility of there ever being any marshalling of the requests for access to the MDB file. Your app has to do that itself.</p>
<p>If that is unsatisfactory, then you're using the wrong data store.</p>
|
<p>Use MARS(Multiple Active Resultsets) in this case.
Search on net for how to implement MARS.</p>
| 48,982
|
<p>Is there such thing as a 3D printer with a very large diameter nozzle, that can make low fidelity, large and fast prints? I'm picturing a soft serve ice-cream machine on a gantry, with a hopper. You feed it shredded plastic, and it prints bricks, or boards.</p>
|
<p>Yes these exist. 3D printers using pellets is not uncommon for industry, but for the user at home this might be a different question. Pellets are the pre-fabricate before it is extruded into filament (small balls/cylinders of plastic).</p>
<p><a href="https://i.stack.imgur.com/0RIoy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0RIoy.png" alt="enter image description here" /></a><br>
<em>Random image showing a variety of pellets in different colors</em></p>
<p>There are even processes to turn used plastic into pellets, so if you combine it all this should be very doable. The problem is to get a consistent type of waste plastic to feed your machine. The size of the nozzle doesn't matter, as long as your shredding, compressing and heating process can keep up with the flow you need. It would be an excellent idea to get rid of plastic waste and turning these into building bricks e.g. for insulation of heat.</p>
<hr />
<p><em>I've seen prototype printers printing PEEK from pallets having a nozzle (slot) diameter of several millimeters.</em></p>
|
<p>You can certainly get large nozzles, but the material for extrusion still needs to be consistent. So any chunked plastic would have to be melted and that will produce an erratic flow at the extruder.</p>
<p>By reforming your shredded plastic into a consistent string of filament, then the printer has a steady supply of material to use. There are already filament extruders for the small shop, but they're still expensive for the home user. The main problems are getting consistent thickness of filament, and minimising contaminants. Also colours tend to be lost and muddied. These might be economical if you have a print farm and are consuming a spool a day on average.</p>
<p>On a large scale, there are "3d printers" that can place a special quick-drying concrete and produce small buildings as homes in a matter of days. However they're fed a special mixture of smooth cement and accelerators to set the concrete ready for the next layer.</p>
<p><a href="https://i.stack.imgur.com/y1vWs.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/y1vWs.jpg" alt="Tecla 3d printed house" /></a></p>
| 2,054
|
<p>I plan to be storing all my config settings in my application's app.config section (using the <code>ConfigurationManager.AppSettings</code> class). As the user changes settings using the app's UI (clicking checkboxes, choosing radio buttons, etc.), I plan to be writing those changes out to the <code>AppSettings</code>. At the same time, while the program is running I plan to be accessing the <code>AppSettings</code> constantly from a process that will be constantly processing data. Changes to settings via the UI need to affect the data processing in real-time, which is why the process will be accessing the <code>AppSettings</code> constantly.</p>
<p>Is this a good idea with regard to performance? Using <code>AppSettings</code> is supposed to be "the right way" to store and access configuration settings when writing .Net apps, but I worry that this method wasn't intended for a constant load (at least in terms of settings being constantly read).</p>
<p>If anyone has experience with this, I would greatly appreciate the input.</p>
<p><strong>Update:</strong> I should probably clarify a few points.</p>
<p>This is not a web application, so connecting a database to the application might be overkill simply for storing configuration settings. This is a Windows Forms application.</p>
<p>According to the MSDN documention, the <code>ConfigurationManager</code> is for storing not just application level settings, but user settings as well. (Especially important if, for instance, the application is installed as a partial-trust application.)</p>
<p><strong>Update 2:</strong> I accepted lomaxx's answer because <code>Properties</code> does indeed look like a good solution, without having to add any additional layers to my application (such as a database). When using Properties, it already does all the caching that others suggested. This means any changes and subsequent reads are all done in memory, making it extremely fast. Properties only writes the changes to disk when you explicitly tell it to. This means I can make changes to the config settings on-the-fly at run time and then only do a final save out to disk when the program exits.</p>
<p>Just to verify it would actually be able to handle the load I need, I did some testing on my laptop and was able to do 750,000 reads and 7,500 writes per second using Properties. That is so far above and beyond what my application will <em>ever</em> even come close to needing that I feel quite safe in using Properties without impacting performance.</p>
|
<p>since you're using a winforms app, if it's in .net 2.0 there's actually a user settings system (called Properties) that is designed for this purpose. <a href="https://learn.microsoft.com/en-us/previous-versions/aa730869%28v=vs.80%29" rel="nofollow noreferrer">This article on MSDN</a> has a pretty good introduction into this</p>
<p>If you're still worried about performance then take a look at <a href="https://web.archive.org/web/20080918011815/http://www.microsoft.com:80/sql/editions/compact/default.mspx" rel="nofollow noreferrer">SQL Compact Edition</a> which is similar to SQLite but is the Microsoft offering which I've found plays very nicely with winforms and there's even the ability to <a href="https://web.archive.org/web/20181015183404/http://geekswithblogs.net:80/steveclements/archive/2007/11/13/linq-to-sql.compact.aspx" rel="nofollow noreferrer">make it work with Linq</a></p>
|
<p>Could I ask why you're not saving the user's settings in a database?</p>
<p>Generally, I save application settings that are changed very infrequently in the appSettings section (the default email address error logs are sent to, the number of minutes after which you are automatically logged out, etc.) The scope of this really is at the application, not at the user, and is generally used for deployment settings.</p>
| 2,615
|
<p>Is it possible to delete an GAE application after it has been created?</p>
<p>I made a mistake while typing the name and now have a dummy application that I haven't been able to remove.</p>
|
<p>With the new Google Cloud console, you can still disable GAE applications as before (App Engine --> Settings --> Disable). They cannot currently be deleted. However you can delete the entire project by going to IAM --> Settings --> Shut Down. This button is in the header and a bit tricky to spot. It looks like this:</p>
<p><a href="https://i.stack.imgur.com/5EnZv.png" rel="noreferrer"><img src="https://i.stack.imgur.com/5EnZv.png" alt="enter image description here"></a></p>
<hr>
<p>As of <a href="http://googleappengine.blogspot.com/2009/10/app-engine-sdk-126-released-with.html" rel="noreferrer">AppEngine SDK 1.2.6</a> it's possible to <a href="http://code.google.com/appengine/kb/adminconsole.html#delete_app" rel="noreferrer">delete apps completely</a>. But beware, the app-id won't be usable again.</p>
|
<p>I wanted to delete some legacy Google App Engine applications I made years ago, but when I tried to delete them from the new Google Cloud Platform (like this: <a href="https://support.google.com/cloud/answer/6251787#shut-down-a-project" rel="nofollow">https://support.google.com/cloud/answer/6251787#shut-down-a-project</a>) I kept getting "You do not have permission" errors. The solution I found was to sign up for a free trial of Google Cloud Platform, then I was able to delete them.</p>
| 6,403
|
<p>In C#, if I declare an auto-implemented property, why do I have to declare BOTH the get and set part? </p>
<p>i.e.</p>
<pre><code>public string ThisWorks { get; set; }
public string ThisDoesnt { get; }
</code></pre>
<p>Isn't this just syntactic sugar - i.e. the compiler inserts a private field for the property? So why the problem?</p>
<p>Curious.</p>
|
<p>If you didn't have a setter - then how would you ever set the property?</p>
<p>Incidentally, you can specify the accessibility, eg:</p>
<pre><code>public string Foo
{
get;
private set;
}
</code></pre>
|
<p>Interestingly, the new Roslyn compiler in Visual Studio 2015 now allows this, even if the project is configured to use C# version 5.</p>
| 43,757
|
<p>In my C# source code I may have declared integers as:</p>
<pre><code>int i = 5;
</code></pre>
<p>or</p>
<pre><code>Int32 i = 5;
</code></pre>
<p>In the currently prevalent 32-bit world they are equivalent. However, as we move into a 64-bit world, am I correct in saying that the following will become the same?</p>
<pre><code>int i = 5;
Int64 i = 5;
</code></pre>
|
<p>No. The C# specification rigidly defines that <code>int</code> is an alias for <code>System.Int32</code> with exactly 32 bits. Changing this would be a <em>major</em> breaking change.</p>
|
<p>int without suffix can be either 32bit or 64bit, it depends on the value it represents.</p>
<p>as defined in MSDN:</p>
<blockquote>
<p>When an integer literal has no suffix, its type is the first of these types in which its value can be represented: int, uint, long, ulong.</p>
</blockquote>
<p>Here is the address:
<a href="https://msdn.microsoft.com/en-us/library/5kzh1b5w.aspx" rel="nofollow">https://msdn.microsoft.com/en-us/library/5kzh1b5w.aspx</a></p>
| 19,903
|
<p>We have some methods that call File.Copy, File.Delete, File.Exists, etc. How can we test these methods without actually hitting the file system?</p>
<p>I consider myself a unit testing n00b, so any advice is appreciated.</p>
|
<pre><code>public interface IFile {
void Copy(string source, string dest);
void Delete(string fn);
bool Exists(string fn);
}
public class FileImpl : IFile {
public virtual void Copy(string source, string dest) { File.Copy(source, dest); }
public virtual void Delete(string fn) { File.Delete(fn); }
public virtual bool Exists(string fn) { return File.Exists(fn); }
}
[Test]
public void TestMySystemCalls() {
var filesystem = new Moq.Mock<IFile>();
var obj = new ClassUnderTest(filesystem);
filesystem.Expect(fs => fs.Exists("MyFile.txt")).Return(true);
obj.CheckIfFileExists(); // doesn't hit the underlying filesystem!!!
}
</code></pre>
|
<p>You can use a mock framework for this and it will create a fake copy of the File object and you can inject the file in the system under test.</p>
<p>I will recommend Rhino Mock.</p>
| 33,443
|
<p>The exact error is as follows</p>
<blockquote>
<p>Could not load file or assembly 'Microsoft.SqlServer.Replication,
Version=9.0.242.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91'
or one of its dependencies. An attempt was made to load a program with
an incorrect format.</p>
</blockquote>
<p>I've recently started working on this project again after a two month move to another project. It worked perfectly before, and I've double checked all the references.</p>
|
<p>The <a href="https://stackoverflow.com/a/41451/148412">answer by baldy</a> below is correct, but you may also need to enable 32-bit applications in your AppPool. </p>
<p>Source: <a href="http://www.alexjamesbrown.com/uncategorized/could-not-load-file-or-assembly-chilkatdotnet2-or-one-of-its-dependencies-an-attempt-was-made-to-load-a-program-with-an-incorrect-format/" rel="noreferrer">http://www.alexjamesbrown.com/uncategorized/could-not-load-file-or-assembly-chilkatdotnet2-or-one-of-its-dependencies-an-attempt-was-made-to-load-a-program-with-an-incorrect-format/</a></p>
<p>Whilst setting up an application to run on my local machine (running Vista 64bit) I encountered this error:</p>
<blockquote>
<p>Could not load file or assembly <code>ChilkatDotNet2</code> or one of its
dependencies. An attempt was made to load a program with an incorrect
format.</p>
</blockquote>
<p>Obviously, the application uses <a href="http://www.chilkatsoft.com/" rel="noreferrer">ChilKat components</a>, but it would seem that the version we are using, is only the 32bit version.</p>
<p>To resolve this error, I set my app pool in IIS to allow 32bit applications.
Open up IIS Manager, right click on the app pool, and select Advanced Settings (See below)</p>
<p><img src="https://i.stack.imgur.com/LQkqf.jpg" alt="enter image description here"></p>
<p>Then set "Enable 32-bit Applications" to True.</p>
<p><img src="https://i.stack.imgur.com/7ltqt.jpg" alt="enter image description here"></p>
<p>All done!</p>
|
<p>in windows form application I do this,
Right-click on Project->Properties->Build->Check Prefer 32-bit checkbox.
Thanks all</p>
| 6,274
|
<p>I have a .NET web-service client that has been autogenerated from a wsdl-file using the wsdl.exe tool.</p>
<p>When I first instantiate the generated class, it begins to request a bunch of documents from w3.org and others. The first one being <a href="http://www.w3.org/2001/XMLSchema.dtd" rel="nofollow noreferrer">http://www.w3.org/2001/XMLSchema.dtd</a></p>
<p>Besides not wanting to cause unnecessary traffic to w3.org, I need to be able to run the application without a connection to the Internet (the web-service is a "Intra-web-service").</p>
<p>Anyone know the solution?</p>
<p>If it helps, here is the stacktrace I get when I do not have Internet:</p>
<pre><code>"An error has occurred while opening external DTD 'http://www.w3.org/2001/XMLSchema.dtd': The remote name could not be resolved: 'www.w3.org'"
at System.Net.HttpWebRequest.GetResponse()
at System.Xml.XmlDownloadManager.GetNonFileStream(Uri uri, ICredentials credentials)
at System.Xml.XmlDownloadManager.GetStream(Uri uri, ICredentials credentials)
at System.Xml.XmlUrlResolver.GetEntity(Uri absoluteUri, String role, Type ofObjectToReturn)
at System.Xml.XmlTextReaderImpl.OpenStream(Uri uri)
at System.Xml.XmlTextReaderImpl.DtdParserProxy_PushExternalSubset(String systemId, String publicId)
at System.Xml.XmlTextReaderImpl.Throw(Exception e)
at System.Xml.XmlTextReaderImpl.DtdParserProxy_PushExternalSubset(String systemId, String publicId)
at System.Xml.XmlTextReaderImpl.DtdParserProxy.System.Xml.IDtdParserAdapter.PushExternalSubset(String systemId, String publicId)
at System.Xml.DtdParser.ParseExternalSubset()
at System.Xml.DtdParser.ParseInDocumentDtd(Boolean saveInternalSubset)
at System.Xml.DtdParser.Parse(Boolean saveInternalSubset)
at System.Xml.XmlTextReaderImpl.DtdParserProxy.Parse(Boolean saveInternalSubset)
at System.Xml.XmlTextReaderImpl.ParseDoctypeDecl()
at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
at System.Xml.XmlTextReaderImpl.Read()
at System.Xml.Schema.Parser.StartParsing(XmlReader reader, String targetNamespace)
at System.Xml.Schema.Parser.Parse(XmlReader reader, String targetNamespace)
at System.Xml.Schema.XmlSchemaSet.ParseSchema(String targetNamespace, XmlReader reader)
at System.Xml.Schema.XmlSchemaSet.Add(String targetNamespace, XmlReader schemaDocument)
at [...]WebServiceClientType..cctor() in [...]
</code></pre>
|
<p>I needed the XmlResolver, so <a href="https://stackoverflow.com/questions/217841/net-autogenerated-web-service-client-how-do-i-avoid-requesting-schemas-from-w3o#218105">tamberg's solution</a> did not quite work. I solved it by implementing my own XmlResolver that read the necessary schemas from embedded resources instead of downloading them.</p>
<p>The problem did not have anything to do with the autogenerated code, by the way.</p>
<p>The web-service-client had another implementation file that contained something like this:</p>
<pre><code>public partial class [...]WebServiceClientType
{
private static readonly XmlSchemaSet _schema;
static KeyImportFileType()
{
_schema = new XmlSchemaSet();
_schema.Add(null, XmlResourceResolver.GetXmlReader("http://www.w3.org/TR/2002/REC-xmldsig-core-20020212/xmldsig-core-schema.xsd"));
_schema.Add(null, XmlResourceResolver.GetXmlReader("http://www.w3.org/TR/2002/REC-xmlenc-core-20021210/xenc-schema.xsd"));
_schema.Compile();
}
</code></pre>
<p>and it was this class-constructor that failed.</p>
|
<p>Thanks Tamberg, you saved me a great deal of time with your succinct and correct answer. I didn't realise the default resolver would go to the web. Checking MSDN is states - </p>
<blockquote>
<p><em>XmlResolver is the default resolver for all classes in the System.Xml namespace. You can also create your own resolver...</em></p>
</blockquote>
<p>I've implemented your answer, setting the resolver to NULL which solves the problem and reduces the network overhead.</p>
<pre><code>XmlReader r = ...r.XmlResolver = null; // prevent xsd or dtd parsing
</code></pre>
<p>Thanks again,
Andy</p>
| 26,777
|
<p>I am in search for a database with translations so I can have comonly used phrases and words translated by a machine and not by an expensive translator. Is there such a thing as a translation database with words and often used phrases?</p>
<p>If you don't know any would you use such a service?</p>
<p>edit: the database should only be monitored by people and not some automatic translater since they tend to be VERY bad</p>
|
<blockquote>
<p>edit: the database should only be monitored by people and not some automatic translater since they tend to be VERY bad</p>
</blockquote>
<p>I don't think this is enough. If you're going to translate single words, you need to have some idea of the context in which the word will be used.</p>
<p>For instance, consider the english word "row"</p>
<p>Does this mean
1. A line of things
2. An argument
3. To move a boat with oars
4. An uproar
5. Several things in succession ("they won four years in a row")</p>
<p>These are likely to have very different translations.</p>
<p>So instead, it might well be worth keeping a multi-language glossary, where you record the definition of a term and its translation in all the languages you care about, but I think you'll need a professional translator to get the translations right, and the "lookup" will always need to be manual.</p>
|
<p><a href="http://www.google.com/language_tools" rel="nofollow noreferrer">http://www.google.com/language_tools</a></p>
| 34,845
|
<p>I want to call my .NET code from unmanaged C++. My process entrypoint is .NET based, so I don't have to worry about hosting the CLR. I know it can be done using COM wrappers for .NET objects, but I would like to access individual static methods of managed classes, so COM isn't my shortest/easiest route.</p>
|
<p>Look at this solution:
<a href="https://sites.google.com/site/robertgiesecke/Home/uploads/unmanagedexports" rel="noreferrer">https://sites.google.com/site/robertgiesecke/Home/uploads/unmanagedexports</a>
The solution allows to call C# function from C by decorating your function with [DllExport] attribute (opposite of P/Invoke DllImport).</p>
<p><strong>Exmaple:</strong></p>
<p>C# code</p>
<pre><code>class Test
{
[DllExport("add", CallingConvention = CallingConvention.StdCall)]
public static int Add(int left, int right)
{
return left + right;
}
}
</code></pre>
<p>C code:</p>
<pre><code> extern "C" int add(int, int);
int main()
{
int z = add(5,10);
printf("The solution is found!!! Z is %i",z);
return 0;
}
</code></pre>
<p>Output: </p>
<pre><code>The solution is found!!! Z is 15
</code></pre>
<p><strong>Update</strong>: There is a question and a good answer in comments: </p>
<p>How do I include the dll in the unmanaged project?</p>
<p>You have to link to the .lib file that is generated upon compiling your C# code (<a href="https://msdn.microsoft.com/en-us/library/ba1z7822.aspx?f=255&MSPPError=-2147217396" rel="noreferrer">https://msdn.microsoft.com/en-us/library/ba1z7822.aspx?f=255&MSPPError=-2147217396</a>)</p>
|
<p>Your calling code is C++ with <code>/clr</code> enabled. Right? </p>
<p>If yes, then you can simply use the using statement to use your .NET dll in your code. Something like:</p>
<pre><code>#using <Mydll.dll>
</code></pre>
<p>and then you can simply make the objects of your managed classes like:</p>
<pre><code>MyNameSpace::MyClass^ obj = new MyNameSpace::MyClass();
</code></pre>
<p>If you want to make this obj a data member of your class the using gcroot is the way to go.</p>
| 27,844
|
<p>Is there a way to hide the google toolbar in my browser programmable?</p>
|
<p>You haven't said which browser you are using so I'm going to assume Internet Explorer* and answer No.</p>
<p>If JavaScript on a web page could manipulate the browser, it would be a serious security hole and could create a lot of confusion for users.</p>
<p>So no... for a good reason: Security.</p>
<p>*. If you were using Firefox, and were talking about JavaScript within an extension to manipulate and theme the window chrome then this would be a different story.</p>
|
<p>I really think that it is imposible to do that with javascript. This is because javascript is designed to control the behaviour of the site. And the browser is not part of the site.
<br/><br/>
Of course maby you are talking about some other Google toolbar then the plugin in the browser.</p>
| 10,765
|
<p>I'm trying to output a list of string values into a 2 column format. The standard way of making a list of strings into "normal text" is by using the <strong>string.join</strong> method. However, it only takes 2 arguments so I can only make a single column using "\n". I thought trying to make a loop that would simply add a tab between columns would do it but the logic didn't work correctly.</p>
<p>I found an <a href="http://code.activestate.com/recipes/302380/" rel="noreferrer">ActiveState page</a> that has a fairly complicated way of doing it but it's from 4 years ago. Is there an easy way to do it nowadays?</p>
<hr>
<p><strong>Edit</strong> Here is the list that I want to use.</p>
<pre><code>skills_defs = ["ACM:Aircraft Mechanic", "BC:Body Combat", "BIO:Biology",
"CBE:Combat Engineer", "CHM:Chemistry", "CMP:Computers",
"CRM:Combat Rifeman", "CVE:Civil Engineer", "DIS:Disguise",
"ELC:Electronics","EQ:Equestrian", "FO:Forward Observer",
"FOR:Forage", "FRG:Forgery", "FRM:Farming", "FSH:Fishing",
"GEO:Geology", "GS:Gunsmith", "HW:Heavy Weapons", "IF:Indirect Fire",
"INS:Instruction", "INT:Interrogation", "JP:Jet Pilot", "LB:Longbow",
"LAP:Light Aircraft Pilot", "LCG:Large Caliber Gun", "LNG:Language",
"LP:Lockpick", "MC:Melee Combat", "MCY:Motorcycle", "MEC:Mechanic",
"MED:Medical", "MET:Meterology", "MNE:Mining Engineer",
"MTL:Metallurgy", "MTN:Mountaineering", "NWH:Nuclear Warhead",
"PAR:Parachute", "PST:Pistol", "RCN:Recon", "RWP:Rotary Wing Pilot",
"SBH:Small Boat Handling","SCD:Scuba Diving", "SCR:Scrounging",
"SWM:Swimming", "TW:Thrown Weapon", "TVD:Tracked Vehicle Driver",
"WVD:Wheeled Vehicle Driver"]
</code></pre>
<p>I just want to output this list into a simple, 2 column format to reduce space. Ideally there should be a standard amount of space between the columns but I can work with it.</p>
<pre><code>ACM:Aircraft Mechanic BC:Body Combat
BIO:Biology CBE:Combat Engineer
CHM:Chemistry CMP:Computers
CRM:Combat Rifeman CVE:Civil Engineer
DIS:Disguise ELC:Electronics
EQ:Equestrian FO:Forward Observer
FOR:Forage FRG:Forgery
FRM:Farming FSH:Fishing
GEO:Geology GS:Gunsmith
HW:Heavy Weapons IF:Indirect Fire
INS:Instruction INT:Interrogation
JP:Jet Pilot LB:Longbow
LAP:Light Aircraft Pilot LCG:Large Caliber Gun
LNG:Language LP:Lockpick
MC:Melee Combat MCY:Motorcycle
MEC:Mechanic MED:Medical
MET:Meterology MNE:Mining Engineer
MTL:Metallurgy MTN:Mountaineering
NWH:Nuclear Warhead PAR:Parachute
PST:Pistol RCN:Recon
RWP:Rotary Wing Pilot SBH:Small Boat Handling
SCD:Scuba Diving SCR:Scrounging
SWM:Swimming TW:Thrown Weapon
TVD:Tracked Vehicle Driver WVD:Wheeled Vehicle Driver
</code></pre>
|
<p>Two columns, separated by tabs, joined into lines. Look in <em>itertools</em> for iterator equivalents, to achieve a space-efficient solution.</p>
<pre><code>import string
def fmtpairs(mylist):
pairs = zip(mylist[::2],mylist[1::2])
return '\n'.join('\t'.join(i) for i in pairs)
print fmtpairs(list(string.ascii_uppercase))
A B
C D
E F
G H
I J
...
</code></pre>
<p>Oops... got caught by S.Lott (thank you).</p>
<p>A more general solution, handles any number of columns and odd lists. Slightly modified from <a href="https://stackoverflow.com/questions/171662/formatting-a-list-of-text-into-columns#173823">S.lott</a>, using generators to save space.</p>
<pre><code>def fmtcols(mylist, cols):
lines = ("\t".join(mylist[i:i+cols]) for i in xrange(0,len(mylist),cols))
return '\n'.join(lines)
</code></pre>
|
<pre><code>data = [ ("1","2"),("3","4") ]
print "\n".join(map("\t".join,data))
</code></pre>
<p>Not as flexible as the ActiveState solution, but shorter :-)</p>
| 20,697
|
<p>3D Printing's <a href="https://3dprinting.stackexchange.com/election/1">First Pro-Tem moderator election</a> has come to a close, the votes have been tallied, and the new moderators is:</p>
<p><a href="https://3dprinting.stackexchange.com/users/5740"><img src="https://3dprinting.stackexchange.com/users/flair/5740.png" alt="MOD1_NAME"></a></p>
<p>They'll be joining <a href="https://3Dprinting.stackexchange.com/users?tab=moderators">the existing crew</a> shortly — please thank them for volunteering, and share your assistance and advice with them as they learn the ropes!</p>
<p>Also, please join me in thanking tbm0115 who will be stepping down as moderator.</p>
<p>For details on how the voting played out, you can download the election results <a href="https://3dprinting.stackexchange.com/election/1">here</a>, or <a href="https://www.opavote.com/results/5831275661230080" rel="nofollow noreferrer">view a summary report online</a>.</p>
|
<p>I like the expanded definitions, but there is probably an issue with some of the things you'd put into "just rough around the edges" portion of what you state.</p>
<p>For instance, "Print Services" are mentioned as far as on-topic and what is allowed. <em>To what extent are Print Services</em> on-topic and allowed? In and of itself, as you've stated it, it could be anything from what to expect to giving them service recommendations (ie: <em>What's a good place to get xxxx done?</em> or <em>Who provides to best services in the Dallas, TX area?</em>) This isn't the only place where it could be done. If you don't want questions like this, throw a little more specification in there as far as what would be acceptable. </p>
|
<p>I like the expanded definitions, but there is probably an issue with some of the things you'd put into "just rough around the edges" portion of what you state.</p>
<p>For instance, "Print Services" are mentioned as far as on-topic and what is allowed. <em>To what extent are Print Services</em> on-topic and allowed? In and of itself, as you've stated it, it could be anything from what to expect to giving them service recommendations (ie: <em>What's a good place to get xxxx done?</em> or <em>Who provides to best services in the Dallas, TX area?</em>) This isn't the only place where it could be done. If you don't want questions like this, throw a little more specification in there as far as what would be acceptable. </p>
| 69
|
<p>How do you create a 1 bit per pixel mask from an image using GDI in C#? The image I am trying to create the mask from is held in a System.Drawing.Graphics object.</p>
<p>I have seen examples that use Get/SetPixel in a loop, which are too slow. The method that interests me is one that uses only BitBlits, like <a href="http://www.vbaccelerator.com/home/VB/Tips/Mask_Images/article.asp" rel="nofollow noreferrer">this</a>. I just can't get it to work in C#, any help is much appreciated.</p>
|
<p>Try this:</p>
<pre><code>using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
</code></pre>
<p>...</p>
<pre><code> public static Bitmap BitmapTo1Bpp(Bitmap img) {
int w = img.Width;
int h = img.Height;
Bitmap bmp = new Bitmap(w, h, PixelFormat.Format1bppIndexed);
BitmapData data = bmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadWrite, PixelFormat.Format1bppIndexed);
for (int y = 0; y < h; y++) {
byte[] scan = new byte[(w + 7) / 8];
for (int x = 0; x < w; x++) {
Color c = img.GetPixel(x, y);
if (c.GetBrightness() >= 0.5) scan[x / 8] |= (byte)(0x80 >> (x % 8));
}
Marshal.Copy(scan, 0, (IntPtr)((int)data.Scan0 + data.Stride * y), scan.Length);
}
bmp.UnlockBits(data);
return bmp;
}
</code></pre>
<p>GetPixel() is slow, you can speed it up with an unsafe byte*.</p>
|
<p>Do you mean LockBits? Bob Powell has an overview of LockBits <a href="https://web.archive.org/web/20141229164101/http://bobpowell.net/lockingbits.aspx" rel="nofollow noreferrer">here</a>; this should provide access to the RGB values, to do what you need. You might also want to look at ColorMatrix, <a href="http://www.java2s.com/Code/CSharp/2D-Graphics/UseColorMatrixtograytheimage.htm" rel="nofollow noreferrer">like so</a>.</p>
| 34,474
|
<p>While looking at a micro-optimization question that I asked yesterday (<a href="https://stackoverflow.com/questions/295579/fastest-way-to-determine-if-an-integers-square-root-is-an-integer">here</a>), I found something strange: an <code>or</code> statement in Java is running <em>slightly</em> faster than looking up a boolean value in an array of booleans.</p>
<p>In my tests, running the below algorithms on <code>long</code> values from 0 to 1 billion, alg1 is about 2% faster. (I have altered the order in which the algorithms are tested, and I get the same results). My question is: <strong>Why is alg1 faster?</strong> I would have expected alg2 to be slightly faster since it uses a lookup table, whereas alg1 has to execute 4 comparisons and 3 or operations for 75% of inputs.</p>
<pre><code>private final static boolean alg1(long n)
{
int h = (int)(n & 0xF);
if(h == 0 || h == 1 || h == 4 || h == 9)
{
long tst = (long)Math.sqrt(n);
return tst*tst == n;
}
return false;
}
private final static boolean[] lookup = new boolean[16];
static
{
lookup[0] = lookup[1] = lookup[4] = lookup[9] = true;
}
private final static boolean alg2(long n)
{
if(lookup[(int)(n & 0xF)])
{
long tst = (long)Math.sqrt(n);
return tst*tst == n;
}
else
return false;
}
</code></pre>
<p><em>If you're curious, this code is testing if a number is a perfect square, and utilizes the fact that perfect squares must end in 0, 1, 4, or 9 in hex.</em></p>
|
<p>Loading some random piece of data is generally slower than a little non-branching code.</p>
<p>It all depends upon processor architecture, of course. Your first if statement could be implemented as four instructions. The second may potentially need null pointer checking, bounds checking as well as the load and compare. Also more code means more compile time, and more chance for the optimisation to be impeeded in some manner.</p>
|
<p>It's an interesting piece of code, but 2% is a really small difference. I don't think you can conclude very much from that.</p>
| 38,295
|
<p>When I supply the script with the argument: hi[123].txt it will do exactly what I want.
But if I specify the wildcard character ( hi*.txt ) it will be re-reading some files.</p>
<p>I was wondering how to modify this script to fix that silly problem:</p>
<pre><code>#!/bin/sh
count="0"
total="0"
FILE="$1" #FILE specification is now $1 Specification..
for FILE in $@
do
#if the file is not readable then say so
if [ ! -r $FILE ];
then
echo "File: $FILE not readable"
exit 0
fi
# Start processing readable files
while read line
do
if [[ "$line" =~ ^Total ]];
then
tmp=$(echo $line | cut -d':' -f2)
total=$(expr $total + $tmp)
echo "$FILE (s) have a total of:$tmp "
count=$(expr $count + 1)
fi
done < $FILE
done
echo " Total is: $total"
echo " Number of files read is:$count"
</code></pre>
|
<p>I don't know what is wrong with it, but one little point i noticed:</p>
<p>Change <code>for FILE in $@</code> into <code>for FILE in "$@"</code> . Because if files have embedded spaces, you are now on the safe way. It will expand into <code>"$1" "$2" ...</code> then, instead of <code>$1 $2 ...</code> (and note everywhere you use $FILE too remember to <code>""</code> it).</p>
<p>And what others say, you don't need to initialize <code>FILE</code> before you enter the loop. It will be set to each of the filenames of the expanded positional parameters in the for loop automatically. </p>
<p>However, i would go with an awk script like this:</p>
<pre><code>awk -F: '
/^Total/ {
total += $2
# count++ not needed. see below
print FILENAME "(s) have a total of: " $2
}
END {
print "Total is: " total
print "Number of files read is: " (ARGC-1)
}' foo*.txt
</code></pre>
<p>Note that when a file contains multiple "^Count" lines, you would indeed say you read more files than you actually read if you rely on <code>count</code> to tell you the number of files read.</p>
|
<p>How about this solution:</p>
<pre><code>for FILE in `/bin/ls $@`
do
. . .
</code></pre>
<p>This will effectively eliminate duplicates because <code>/bin/ls hi1.txt hi1.txt hi1.txt</code> should only show <code>hi1.txt</code> once.</p>
<p>Though I'm not sure why it's re-reading files. The wildcard expansion should only include each file once. Do you have some files matched by <code>hi*.txt</code> that are links to files matched by <code>hi[123].txt</code>?</p>
| 42,539
|
<p>How can I select multiple elements using a WHERE...IN... type of clause as in</p>
<pre><code>select * from orders where orderid in (1, 4, 5)
</code></pre>
<p>in LinqToSql? I'd prefer not to have a lambda expression since they scare me.</p>
|
<p>LINQ has "Contains" which is like "IN" but expressed the other way round - an element isn't "in" a set, a set "contains" an element.</p>
<pre><code>int[] validIds = { 1, 4, 5 };
var query = from order in db.Orders
where validIds.Contains(order.Id)
select order
</code></pre>
<p>This is more simply expressed (IMO) with a lambda though:</p>
<pre><code>int[] validIds = { 1, 4, 5 };
var query = db.Orders.Where(order => validIds.Contains(order.Id));
</code></pre>
<p>I realise lambdas are "new" and therefore scary to some extent, but it's really well worth grabbing hold of them with both hands. They're lovely.</p>
|
<pre><code>int[] arry = new int[] {1,4,5};
var q = from r in orders
where Array.IndexOf(array, orderid) != -1
select r;
</code></pre>
<p>or</p>
<pre><code>List<int> lst = new List<int>(new int[] {1,4,5});
var q = from r in orders
where lst.Contains(orderid);
select r;
</code></pre>
| 41,025
|
<p>I need to get the lesser n numbers of a list in Python. I need this to be really fast because it's in a critical part for performance and it needs to be repeated a lot of times.</p>
<p>n is usually no greater than 10 and the list usually has around 20000 elements. The list is always different each time I call the function. Sorting can't be made in place.</p>
<p>Initially, I have written this function:</p>
<pre><code>def mins(items, n):
mins = [float('inf')]*n
for item in items:
for i, min in enumerate(mins):
if item < min:
mins.insert(i, item)
mins.pop()
break
return mins
</code></pre>
<p>But this function can't beat a simple sorted(items)[:n] which sort the entire list. Here is my test:</p>
<pre><code>from random import randint, random
import time
test_data = [randint(10, 50) + random() for i in range(20000)]
init = time.time()
mins = mins(test_data, 8)
print 'mins(items, n):', time.time() - init
init = time.time()
mins = sorted(test_data)[:8]
print 'sorted(items)[:n]:', time.time() - init
</code></pre>
<p>Results:</p>
<pre><code>mins(items, n): 0.0632939338684
sorted(items)[:n]: 0.0231449604034
</code></pre>
<p>sorted()[:n] is three times faster. I believe this is because:</p>
<ol>
<li>insert() operation is costly because Python lists are not linked lists.</li>
<li>sorted() is an optimized c function and mine is pure python.</li>
</ol>
<p>Is there any way to beat sorted()[:n] ?
Should I use a C extension, or Pyrex or Psyco or something like that?</p>
<p>Thanks in advance for your answers.</p>
|
<p>You actually want a sorted sequence of mins.</p>
<pre><code>mins = items[:n]
mins.sort()
for i in items[n:]:
if i < mins[-1]:
mins.append(i)
mins.sort()
mins= mins[:n]
</code></pre>
<p>This runs <em>much</em> faster because you aren't even looking at mins unless it's provably got a value larger than the given item. About 1/10th the time of the original algorithm.</p>
<p>This ran in zero time on my Dell. I had to run it 10 times to get a measurable run time.</p>
<pre><code>mins(items, n): 0.297000169754
sorted(items)[:n]: 0.109999895096
mins2(items)[:n]: 0.0309998989105
</code></pre>
<p>Using <code>bisect.insort</code> instead of append and sort may speed this up a hair further.</p>
|
<p>why not just call the select_n_th element in O(N) time and then divide the array into two parts by the n_th element, this should be the fastest one.</p>
<p>ps:
This O(N) algorithm works if you don't specify the order of the n-smallest elements
The link below seems to do the selection algorithm.
<a href="http://code.activestate.com/recipes/269554-select-the-nth-smallest-element/" rel="nofollow">http://code.activestate.com/recipes/269554-select-the-nth-smallest-element/</a></p>
<p>Assuming the array doesn't have duplicate elements, the code works for me. The efficiency still depends on the problem scale, if n<10, probably an O(logn*N) algorithm is enough. </p>
<pre><code>import random
import numpy as np
def select(data, n):
"Find the nth rank ordered element (the least value has rank 0)."
data = list(data)
if not 0 <= n < len(data):
raise ValueError('not enough elements for the given rank')
while True:
pivot = random.choice(data)
pcount = 0
under, over = [], []
uappend, oappend = under.append, over.append
for elem in data:
if elem < pivot:
uappend(elem)
elif elem > pivot:
oappend(elem)
else:
pcount += 1
if n < len(under):
data = under
elif n < len(under) + pcount:
return pivot
else:
data = over
n -= len(under) + pcount
def n_lesser(data,n):
data_nth = select(data,n)
ind = np.where(data<data_nth)
return data[ind]
</code></pre>
| 45,626
|
<p>I need to transform an Oracle SQL statement into a Stored Procedure therefore users with less privileges can access certain data field:</p>
<pre><code>SELECT
info_field, data_field
FROM
table_one
WHERE
some_id = '<id>' -- I need this <id> to be the procedure's parameter
UNION ALL
SELECT
info_field, data_field
FROM
table_two
WHERE
some_id = '<id>'
UNION ALL
SELECT
info_field, data_field
FROM
table_three
WHERE
some_id = '<id>'
UNION ALL
...
</code></pre>
<p>Given that I'm no SP expert I've been unable to figure out a good solution to loop through all the involved tables (12 aprox.).</p>
<p>Any ideas would be helpful. Thanks much!</p>
|
<p>If you just want to restrict users' access you could create a view and grant them select on the view but not the tables:</p>
<pre><code>CREATE VIEW info_and_data AS
SELECT info_field, data_field
FROM table_one
UNION ALL
SELECT info_field, data_field
FROM table_two
UNION ALL
SELECT info_field, data_field
FROM table_three
...
</code></pre>
<p>The users could then type:</p>
<pre><code>SELECT info_field, data_field
FROM info_and_data
WHERE some_id = <id>
</code></pre>
|
<p>Is the expectation that, among all these tables, only one will have a match for a given ID?</p>
<p>If no: You need to explain what you want to do when there are multiple matches.</p>
<p>If yes: You simply do the same SQL query, selecting the result into a variable that you then return.</p>
<p>It would look something like this:</p>
<pre><code>PROCEDURE get_fields( the_id NUMBER,
info_field_out OUT table_one.info_field%TYPE,
data_field_out OUT table_one.data_field%TYPE
)
IS
BEGIN
SELECT info_field, data_field
INTO info_field_out, data_field_out
FROM (
... put your full SQL query here, using 'the_id' as the value to match against ..
);
EXCEPTION
WHEN no_data_found THEN
-- What do you want to do here? Set the outputs to NULL? Raise an error?
WHEN too_many_rows THEN
-- Is this an invalid condition?
END;
</code></pre>
| 39,788
|
<p>Googling 'HDPLA' has so far availed me very little. </p>
<p><a href="http://3dinsider.com/what-is-pla/" rel="nofollow noreferrer">http://3dinsider.com/what-is-pla/</a> indicates that /all/ modern PLA is 'high density' compared to 'the early days'. But a fellow at the local makerspace indicated that he was specifically using 'HDPLA', with [he claimed] markedly better properties than regular PLA in the final product.</p>
<p>A company named Florion claims to have some secret sauce they add to their PLA, and Maker Filament touts a high temp PLA; but neither seems to use the 'HD' prefix.</p>
<p>I haven't yet been able to track down the fellow to get any more specifics from him. There's no reel of the stuff sitting around so I can't look at its labeling for clues. He claimed to be fabbing lab fittings but I don't know the intended operating situation/requirements. </p>
<p>It's possible he meant something else, like HDPE, which would be quite inert and thus a good choice for lab fittings--but I'd like to think that if it was lab equipment he was making he'd get the name of the polymer right.</p>
<p>Comments, including any regarding the Florion or Maker Filament or any other 'high performance' PLAs, would be most welcome.</p>
|
<p>So, low-teck, old-style investigative work from my side.... I contacted <a href="http://www.filright.com" rel="nofollow noreferrer">a company</a> selling HDPLA and they got back to me with the following reply.</p>
<blockquote>
<p>We created HDPLA as an industrial PLA with special additives. As a result, our so called HDPLA has the advantages of ABS, but prints as easy as regular PLA. HDPLA has high impact, high strength and high heat deflection temperature (hdt). You can also print at high speed (max 140mm/s inhouse tests). HDPLA has is own high strength, but is even more strong after annealing. A heated bed is not necessary (50-60˚C recommended), and you can print with HDPLA with a 3D printer with open structure.</p>
</blockquote>
<p>This is strikingly similar to the <a href="https://www.3dprima.com/filaments/primaselect-pla-pro-1-75mm-750-g-black/a-22432/" rel="nofollow noreferrer">description of what 3Dprima calls "Prima SELECT PRO"</a>:</p>
<blockquote>
<p>PrimaSelect™ PLA PRO ist the next generation of high performance PLA for demanding industrial applications. Designed to be able to print fast >120mm/s so you can save on production time. Very high heat resistance (95°C+) after annealing. Excellent mechanical properties combined with a matte surface finish that helps concealing the printed layers for optimum appearance.</p>
</blockquote>
<p>While writing this answer I also found <a href="http://fiberlogy.com/en/fiberlogy-filaments/filament-hd-pla/" rel="nofollow noreferrer">a page</a> that escaped my googling until now, sating an additional property of "their" HDPLA: food safety.</p>
<blockquote>
<p>With our HD PLA you have many more options. You can use this material in two ways. Choose the one you like best. You can use it as a normal PLA and get prints characterized by a very good adhesion between the layers and high precision. You can also make your prints acquire similar properties to that of ABS – better impact resistance and high temperature resistance. All you need is an oven. Yes, an oven! By annealing our HD PLA in an oven, in accordance with the manual, you will avoid all the inconveniences of printing with ABS, such as unpleasant odour or hazardous fumes. But these are not all the advantages of HD PLA. For the production of this material we have chosen raw materials that are approved for food contact in compliance with the EU directive and FDA regulations. HD PLA is also certified by RoHS.</p>
</blockquote>
<p>So, it looks like HDPLA is not the shorthand of a polymer molecule, but rather <strong>a trade word indicating that the base PLA has been mixed with additives</strong>. Furthermore, the answer I got via mail seems to indicate that <strong>"HD" refers to the high <em>Heat Deflection</em> temperature</strong> of the filament (the <a href="https://en.wikipedia.org/wiki/Heat_deflection_temperature" rel="nofollow noreferrer">heat deflection temperature</a> is the temperature at which a polymer or plastic sample deforms under a specified load).</p>
|
<p>I doubt that it means very much at all. Filament manufacturers are very tight-lipped about the co-polymers that they add to their base stock in order to improve handling and performance characteristics, so it is impossible to say. The only common attribute that I can see is an advertised diameter tolerance of ±0.02mm. Maybe HD stands for <em>high-definition</em>, rather than <em>high-density</em>?</p>
| 790
|
<p>As part of a build setup on a windows machine I need to add a registry entry and I'd like to do it from a simple batch file.</p>
<p>The entry is for a third party app so the format is fixed.</p>
<p>The entry takes the form of a REG_SZ string but needs to contain newlines ie. 0xOA characters as separators.</p>
<p>I've hit a few problems.</p>
<p>First attempt used regedit to load a generated .reg file. This failed as it did not seem to like either either long strings or strings with newlines. I discovered that export works fine import fails. I was able to test export as the third party app adds similar entries directly through the win32 api.</p>
<p>Second attempt used the command REG ADD but I can't find anyway to add the newline characters everything I try just ends up with a literal string being added.</p>
|
<p>You could create a VBScript(.vbs) file and just call it from a batch file, assuming you're doing other things in the batch other than this registry change. In vbscript you would be looking at something like:</p>
<pre><code>set WSHShell = CreateObject("WScript.Shell")
WSHShell.RegWrite "HKEY_LOCAL_MACHINE\SOMEKEY", "value", "type"
</code></pre>
<p>You should be able to find the possible type values using Google.</p>
|
<p>Another approach -- that is much easier to read and maintain -- is to use a PowerShell script. Run PowerShell as Admin.</p>
<hr />
<p># SetLegalNotice_AsAdmin.ps1</p>
<p># Define multi-line legal notice registry entry</p>
<p>Push-Location</p>
<p>Set-Location -Path Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\</p>
<p>$contentCaption="Legal Notice"</p>
<p>$contentNotice= @"</p>
<p>This is a very long string that runs to many lines.</p>
<p>You are accessing a U.S. Government (USG) Information System (IS) that is provided for USG-authorized use only.</p>
<p>By using this IS (which includes any device attached to this IS), you consent to the following conditions:</p>
<p>-The USG routinely intercepts and monitors communications on this IS for purposes including, but not limited to, penetration testing, COMSEC monitoring, network operations and defense, personnel misconduct (PM), law enforcement (LE), and counterintelligence (CI) investigations.</p>
<p>etc...</p>
<p>"@</p>
<p># Caption</p>
<p>New-ItemProperty -Path . -Name legalnoticetext -PropertyType MultiString -Value $contentCaption -Force</p>
<p># Notice</p>
<p>New-ItemProperty -Path . -Name legalnoticetext -PropertyType MultiString -Value $contentNotice -Force</p>
<p>Pop-Location</p>
<p><a href="https://i.stack.imgur.com/dE6i3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dE6i3.png" alt="enter image description here" /></a></p>
| 18,587
|
<p>What I would like is be able to generate a simple report that is the output of svn log for a certain date range. Specifically, all the changes since 'yesterday'. </p>
<p>Is there an easy way to accomplish this in Subversion besides grep-ing the svn log output for the timestamp?</p>
<p>Example:</p>
<pre><code>svn -v log -d 2008-9-23:2008-9:24 > report.txt
</code></pre>
|
<p>Very first hit by google for "svn log date range": <a href="http://svn.haxx.se/users/archive-2006-08/0737.shtml" rel="noreferrer">http://svn.haxx.se/users/archive-2006-08/0737.shtml</a></p>
<blockquote>
<p>So <code>svn log <url> -r
{2008-09-19}:{2008-09-26}</code> will get
all changes for the past week,
including today.</p>
</blockquote>
<p>And if you want to generate reports for a repo, there's a solution: <a href="http://statsvn.org/index.html" rel="noreferrer">Statsvn</a>.</p>
<p>HTH</p>
|
<p>You can do this:</p>
<pre><code>svn log -r{2008-9-23}:{2008-9-24} > report.txt
</code></pre>
<p>Add a <code>--xml</code> before the <code>-r</code> if you want ot get the output in xml format for "easier" post processing. </p>
| 17,111
|
<p>Is it possible to use EventListener to Listen to a variable and detect when the value of that variable changes? Thanks.</p>
|
<p>This is quite easy to do if you wrap it all into a class. We will be using getter/setter methods. The setter method will dispatch and event whenever it is called. </p>
<p>(Note: Setters and Getters are treated like properties). You merely assign a value, as opposed to calling a method (e.g <code>someVar = 5</code> instead of <code>someVar(5);</code> Even though setters / getters are functions/methods, they are treated like properties.</p>
<pre><code>//The document class
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.EventDispatcher;
public Class TestDocClass extends Sprite
{
private var _model:Model;
public function TestDocClass():void
{
_model = new Model();
_model.addEventListener(Model.VALUE_CHANGED, onModelChanged);
}
private function onModelChanged(e:Event):void
{
trace('The value changed');
}
}
}
//The model that holds the data (variables, etc) and dispatches events. Save in same folder as DOC Class;
package
{
import flash.events.Event;
import flash.events.EventDispatcher;
public class Model extends EventDispatcher
{
public static const VALUE_CHANGED:String = 'value_changed';
private var _someVar:someVarType;
public function Model():void
{
trace('The model was instantiated.');
}
public function set someVariable(newVal:someVarType):void
{
_someVar = newVal;
this.dispatchEvent(new Event(Model.VALUE_CHANGED));
}
}
}
</code></pre>
|
<p>You used to be able to do something similar in AS2 using Object.watch. I don't see a direct equivalent, but it looks like <a href="http://livedocs.adobe.com/flex/3/langref/mx/binding/utils/ChangeWatcher.html" rel="nofollow noreferrer">mx.binding.utils.ChangeWatcher</a> will give you similar functionality for any variables that are bindable.</p>
<p>I don't know of a way to do it in AS3 for non-bindable variables, but if the variable you want to watch is bindable (or if you can modify it to be binadable) then ChangeWatcher might give you what you want.</p>
| 39,481
|
<p>I have animation code in a class that extends the UIView:</p>
<pre><code>// Start Animation Block
CGContextRef context = UIGraphicsGetCurrentContext();
[UIView beginAnimations:nil context:context];
[UIView setAnimationTransition: UIViewAnimationTransitionFlipFromLeft forView:[self superview] cache:YES];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationDuration:1.0];
//int nextView = currentView + 1;
// Animations
[[self superview] exchangeSubviewAtIndex:0 withSubviewAtIndex:1];
//And so I would do: [[self superview exchangeSubviewAtIndex:currentView withSubviewAtIndex:nextView];
//Doesn't work because curentView is not global... with each instance of a class it's reset to what it's instanciated to.
//currentView++;
// Commit Animation Block
[UIView commitAnimations];
</code></pre>
<p>This animation code works fine for two views. But I am trying to do this for many views. I tried by adding in a global variable (nextview index and currentView index), however this doesn't work since each custom view class has it's own instance and these variables aren't shared.</p>
<p>Does anyone know how I can accomplish what I want to do?</p>
<p>Thanks!</p>
<p>Edit: I would be able to do this, if I could use [self superview] to access the index of the currentview and of the nextview. Are there some methods to do this?</p>
|
<p>Apple have a pretty good tutorial on view transitions <a href="https://developer.apple.com/iphone/library/samplecode/ViewTransitions/index.html" rel="nofollow noreferrer">here</a>. Other than the way they implement them you can also look at using a UINavigationController which manages a bunch of views and transitioning between them.</p>
<p>Essentially you need to manage the transition in the superview rather than the view - the superview can know who it's currently displaying and who's next.</p>
|
<p>I think a Linked List of views might be what you should think about implementing.</p>
| 29,518
|
<p>I am using ehCache to store larges amount of data.
This cache is accessed about 3 times every second and must be kept up to date.
I have a thread that runs which retrieves all the data i need for the cache from the database every minute into a different cache(different cachemanager also).
What i want to do is copy the contents of the data from the new cache into the cache which is being accessed every second in a quick, reliable and synchronized manner. (e.g. call a replace method passing in the existing cache, and the new cache and update the new cache quickly and safely)</p>
<p>Is there any way off hand to do this in ehCache?</p>
<p>Any help is greatly appreciated.</p>
<p>Thanks
Damien</p>
|
<p>It sounds like you are looking for a complicated solution to a problem ehcache solves out-of-the-box.</p>
<p>You only need one cache manager. Configure it to flush once a minute. If need be, do this by creating a thread that flushes the cache once a minute. </p>
<p>When you try to retrieve something from the cache and it is not there load the data again. Put this cache retrieval bit in a synchronized method or block if you want to be sure that the populating the cache blocks progress.</p>
|
<p>+1 to <a href="https://stackoverflow.com/users/2959/steve-mcleod">Steve McLeod</a>.</p>
<p>See <a href="http://ehcache.sourceforge.net/documentation/cache_decorators.html" rel="nofollow noreferrer">SelfPopulatingCache</a></p>
<p>I believe this will do <em>exactly</em> what you want, and quickly.</p>
<p>If you still want to maintain two caches, this is <em>still</em> the way to go. Just make the <code>CacheFactory</code> instance return cached values from your self-maintained cache.</p>
| 32,727
|
<p>I'm trying to wrap my head around asp.net. I have a background as a long time php developer, but I'm now facing the task of learning asp.net and I'm having some trouble with it. It might very well be because I'm trying to force the framework into something it is not intended for - so I'd like to learn how to do it "the right way". :-)</p>
<p>My problem is how to add controls to a page programmatically at runtime. As far as I can figure out you need to create the controls at page_init as they otherwise disappears at the next PostBack. But many times I'm facing the problem that I don't know which controls to add in page_init as it is dependent on values from at previous PostBack.</p>
<p>A simple scenario could be a form with a dropdown control added in the designer. The dropdown is set to AutoPostBack. When the PostBack occur I need to render one or more controls denepending on the selected value from the dropdown control and preferably have those controls act as if they had been added by the design (as in "when posted back, behave "properly").</p>
<p>Am I going down the wrong path here?</p>
|
<p>I agree with the other points made here "If you can get out of creating controls dynamically, then do so..." (by @<a href="https://stackoverflow.com/users/11559/jesper-blad-jensen-aka-deldy">Jesper Blad Jenson aka</a>) but here is a trick I worked out with dynamically created controls in the past.</p>
<p>The problem becomes chicken and the egg. You need your ViewState to create the control tree and you need your control tree created to get at your ViewState. Well, that's almost correct. There is a way to get at your ViewState values <i>just before</i> the rest of the tree is populated. That is by overriding <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.control.loadviewstate.aspx" rel="nofollow noreferrer" title="MSDN - Control.LoadViewState Method"><code>LoadViewState(...)</code></a> and <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.control.saveviewstate.aspx" rel="nofollow noreferrer" title="MSDN - Control.SaveViewState Method"><code>SaveViewState(...)</code></a>.</p>
<p>In SaveViewState store the control you wish to create:</p>
<pre><code>protected override object SaveViewState()
{
object[] myState = new object[2];
myState[0] = base.SaveViewState();
myState[1] = controlPickerDropDown.SelectedValue;
return myState
}
</code></pre>
<p>When the framework calls your "LoadViewState" override you'll get back the exact object you returned from "SaveViewState":</p>
<pre><code>protected override void LoadViewState(object savedState)
{
object[] myState = (object[])savedState;
// Here is the trick, use the value you saved here to create your control tree.
CreateControlBasedOnDropDownValue(myState[1]);
// Call the base method to ensure everything works correctly.
base.LoadViewState(myState[0]);
}
</code></pre>
<p>I've used this successfully to create ASP.Net pages where a DataSet was serialised to the ViewState to store changes to an entire grid of data allowing the user to make multiple edits with PostBacks and finally commit all their changes in a single "Save" operation.</p>
|
<p>Well. If you can get out of creating controls dynamicly, then do so - otherwise, what i whould do is to use Page_Load instead of Page_Init, but instead of placing stuff inside the If Not IsPostBack, then set i just directly in the method.</p>
| 13,847
|
<p>Is there a function in the C Library under Linux which can set the length of a file? Under Windows I know there is a SetFileLength() function.
If there is not, what is the best way of shortening a file without deleting and rewriting it?</p>
|
<p>You can use the <a href="http://homepages.cwi.nl/~aeb/linux/man2html/man2/truncate.2.html" rel="nofollow noreferrer">truncate function</a>.</p>
<p><code>int truncate(const char *path, off_t length);</code> </p>
<p>From the man page:</p>
<p>"The truncate() and ftruncate() functions cause the regular file named by path or referenced by fd to be truncated to a size of precisely length bytes. If the file previously was larger than this size, the extra data is lost. If the file previously was shorter, it is extended, and the extended part reads as null bytes"</p>
|
<pre><code> #include <unistd.h>
#include <sys/types.h>
int truncate(const char *path, off_t length);
int ftruncate(int fd, off_t length);
</code></pre>
<p>From its manpage:</p>
<blockquote>
<p>The truncate() and ftruncate()
functions cause the regular file named
by path or referenced by fd to be
truncated to a size of precisely
length bytes.</p>
<p>If the file previously was larger
than this size, the extra data is
lost. If the file previously was
shorter, it is extended, and the
extended part reads as null bytes
('\0').</p>
</blockquote>
| 46,683
|
<p>Given a SCHEMA for implementing tags</p>
<p>ITEM
ItemId, ItemContent</p>
<p>TAG
TagId, TagName</p>
<p>ITEM_TAG
ItemId, TagId</p>
<p>What is the best way to limit the number of ITEMS to return when selecting with tags?</p>
<pre><code>SELECT i.ItemContent, t.TagName FROM item i
INNER JOIN ItemTag it ON i.id = it.ItemId
INNER JOIN tag t ON t.id = it.TagId
</code></pre>
<p>is of course the easiest way to get them all back, but using a limit clause breaks down, because you get an duplicate of all the items for each tag, which counts toward the number of rows in LIMIT.</p>
|
<p>My second solution uses a MySQL function GROUP_CONCAT() to combine all tags matching the item into a comma-separated string in the result set.</p>
<pre><code>SELECT i.ItemContent, GROUP_CONCAT(t.TagName ORDER BY t.TagName) AS TagList
FROM item AS i
INNER JOIN ItemTag AS it ON i.id = it.ItemId
INNER JOIN tag AS t ON t.id = it.TagId
GROUP BY i.ItemId;
</code></pre>
<p>The GROUP_CONCAT() function is a MySQL feature, it's not part of standard SQL.</p>
|
<p>My first suggestion is to use a subquery to generate the list of item ID's and return items matching those item ID's. But this doesn't include the TagName in your result set. I'll submit a separate answer with another solution.</p>
<pre><code>SELECT i.ItemContent
FROM item AS i
WHERE i.id IN (
SELECT it.ItemId
FROM ItemTag AS it
INNER JOIN tag AS t ON (t.id = it.TagId)
WHERE t.TagName IN ('mysql', 'database', 'tags', 'tagging')
);
</code></pre>
<p>This is a non-correlated subquery, so a good SQL engine should factor it out and run it only once.</p>
| 20,174
|
<p>I'm working on a database project and I need to create Outlook 2007 plugin that saves the current previewed message into my database.</p>
<p>Can someone give me a step-by-step guide on how to create an Outlook plugin in Delphi, and how to deploy it?</p>
<p>Thanks</p>
|
<p>If you just want to learn and understand how to do it, just google for Delphi Outlook addin (I'm pretty sure "addin" should give you much more relevant results than "plugin" in this context) and you should come up with a number of slightly dated but still formally correct sample addins, e.g. the <a href="http://www.paulqualls.com/delphi_com_addin.zip" rel="nofollow noreferrer">Babelfish addin</a> from Dmitry Streblechenko (which is no longer useful because the web service it relies on no longer exists but still shows the basics) or the sample addin from Paul Qualls (which is unfortunately no longer available from the original site). There's also a <a href="http://www.benziegler.com/TrustFilter/" rel="nofollow noreferrer">mail whitelister addin</a> available with complete source, but I haven't looked at that yet.</p>
<p>However, sooner or later you <strong>will</strong> want to start using a proven framework like <a href="http://www.add-in-express.com/add-in-delphi/" rel="nofollow noreferrer">ADX</a>, especially if your addin is going to be used outside your company. We develop a shareware addin in Delphi and about 75% of the code in the addin is just there to provide support for the various versions of Outlook (especially Outlook XP) and different setups (most notably the option to use Word for message editing has been a major table-biter for us).</p>
<p>Another factor is having to constantly work around the stupid OOM security model. You're pretty much busted without <a href="http://dimastr.com/redemption/" rel="nofollow noreferrer">Redemption</a> or <a href="http://www.add-in-express.com/outlook-security/" rel="nofollow noreferrer">Outlook Security Manager</a> there. Redemption especially could not be recommended highly enough, not only for avoiding the security prompts but also for simplifying a plethora of tedious routine tasks with a solid, easy-to-use framework of its own.</p>
<p>[Addition:]
We did start out with our own home-grown framework and all was well with it until the number of users and with them the number of different configurations to support exploded. We switched to ADX about a year ago and never looked back. Using Redemption was a no-brainer right from the beginning though - it was either that or spend months learning Extended MAPI before we even got started (you do still tend to pick that up much easier as you go along once Redemption has guided you over the first few hurdles).</p>
<p>BTW: Another indispensable tool for any self-respecting addin developer (regardless of programming language used) is <a href="http://dimastr.com/outspy" rel="nofollow noreferrer">OutlookSpy</a>. This will really allow you to see (and manipulate) what goes on inside Outlook (and to some extent Exchange) as it happens and give you a much better understanding of what your addin will have to do in order to achieve the effect you want.</p>
|
<p>To bad the job has to be done in Delphi. With .NET and VSTO creating Outlook addins is far less painfull compared to the bad old days. I have made Office addins in COM (that was NOT funny at all) and in the previous version of VSTO, but VSTO 3 is very good news for the office developer.</p>
| 26,471
|
<p>Is it alright to do this?</p>
<pre><code>$author = strtolower($_SESSION['valid_username']);
</code></pre>
<p>I want to enter all authors into the table as lower case.</p>
|
<p>Yes, that's fine as long as <code>$_SESSION['valid_username']</code> is set, otherwise you'll get a notice (if your error reporting is set that low).</p>
<p>You can check if it exists with <code>if (isset($_SESSION['valid_username']))</code></p>
|
<p>yes.</p>
<pre><code>$_SESSION['valid_username']
</code></pre>
<p>is a session variable which evaluates to a string so passing it as a parameter to the strtolower function is not a problem.</p>
| 35,071
|
<p>What's the best way to view the data that LoadPostData event is loading to the controls in ASP.NET? </p>
|
<p>It's actually really simple. The NameValueCollection that get's passed to this method of EVERY control that implements the IPostbackDataHandler interface is the contents of Page.Request.Form. So you can access it at any time by getting a Watch on <code>HttpContext.Current.Request.Form</code>.</p>
|
<p>Ugh... I would suggest setting your IDE environment up to <a href="http://blogs.msdn.com/sburke/archive/2008/01/16/configuring-visual-studio-to-debug-net-framework-source-code.aspx" rel="nofollow noreferrer">debug the .net framework</a>, and set a breakpoint on the LoadPostData() method of Control. That's a bit heavy-handed, but if you're willing to wade through the recursive calls to the Control class (perhaps set a conditional breakpoint on the method?), you will be able to get to the data that way.</p>
<p>Good luck!</p>
| 49,350
|
<p>I have a requirement to create a simple database in Access to collect some user data that will be loaded into another database for further reporting. There will be a module in the Access db that when invoked by the user (probably by clicking a button) will output a query to a delimited file. The user also needs a mechanism (for example a form with a button) to easily transfer the file to a remote server, using sftp. Does anyone have an idea of how to accomplish this?</p>
|
<p>You can simply write a call to the sftp command line client via a batch file if you want to accomplish that.</p>
<p>Check out the Shell() function in VBA.</p>
<p>Under the click event of the button on your form add in the code:</p>
<pre><code>mySFTPCall = "sftp <insert your options here!>"
Call Shell(mySFTPCall, 1)
</code></pre>
<p>I've used this before to just copy files straight across network shares etc. to share data from an in-house Access DB. Of course you could get more fancy if necessary.</p>
|
<p>I would imagine you just need to find an FTP COM object. You should then be able to instantiate this in the Access module code. dart.com has one and I'm sure there are many more (just Google FTP COM).</p>
| 24,714
|
<p>A long while back I transitioned to doing all my web application development in Eclipse from BBEdit. But I miss one little feature from BBEdit. I used to be able to show invisible characters like tabs but not show other invisibles like spaces. I know that I can bulk turn all of these on in Eclipse, but I wonder if there is a way to show only some invisibles in Eclipse.</p>
|
<p>Unfortunately, you can only turn on all invisible (whitespace) characters at the same time. I suggest you file an enhancement request but I doubt they will pick it up.</p>
<p>The text component in Eclipse is very complicated as it is and they are not keen on making them even worse.</p>
<p><strong>[UPDATE]</strong> This has been fixed in Eclipse 3.7: Go to Window > Preferences > General > Editors > Text Editors</p>
<p>Click on the link "whitespace characters" to fine tune what should be shown.</p>
<p>Kudos go to <a href="https://stackoverflow.com/users/46011/john-isaacks">John Isaacks</a></p>
|
<p>AnyEdit
Scroll all the way down: <a href="http://andrei.gmxhome.de/anyedit/examples.html" rel="nofollow">http://andrei.gmxhome.de/anyedit/examples.html</a></p>
| 47,541
|
<p>I'm using system catalog views such as SYS.ALL_ OBJECTS, SYS.FOREIGN_KEYS etc. to get information about my database structure in MS SQL 2005. </p>
<p>Are there equivalent functions/views for MySQL (v. 5) servers? </p>
|
<p>For the schema (All objects);</p>
<pre><code>SELECT * FROM information_schema.SCHEMATA S;
</code></pre>
<p>For constraints and foreign keys also;</p>
<pre><code>SELECT * FROM information_schema.TABLE_CONSTRAINTS T;
</code></pre>
<p>For everything else check this queries;</p>
<pre><code>SELECT * FROM information_schema.CHARACTER_SETS C;
SELECT * FROM information_schema.COLLATION_CHARACTER_SET_APPLICABILITY C;
SELECT * FROM information_schema.COLLATIONS C;
SELECT * FROM information_schema.COLUMN_PRIVILEGES C;
SELECT * FROM information_schema.`COLUMNS` C;
SELECT * FROM information_schema.KEY_COLUMN_USAGE K;
SELECT * FROM information_schema.PROFILING P;
SELECT * FROM information_schema.ROUTINES R;
SELECT * FROM information_schema.SCHEMA_PRIVILEGES S;
SELECT * FROM information_schema.STATISTICS S;
SELECT * FROM information_schema.TABLE_PRIVILEGES T;
SELECT * FROM information_schema.`TABLES` T;
SELECT * FROM information_schema.TRIGGERS T;
SELECT * FROM information_schema.USER_PRIVILEGES U;
SELECT * FROM information_schema.VIEWS V;
</code></pre>
|
<p>Hmm, I haven't studied everything it contains, but there's a good deal of information in the <a href="http://dev.mysql.com/doc/refman/5.0/en/information-schema.html" rel="nofollow noreferrer">information_schema</a>. There's also the <a href="http://dev.mysql.com/doc/refman/5.0/en/show.html" rel="nofollow noreferrer">show</a> command.</p>
<p>Still, I don't see a single command to show all the foreign keys in there.</p>
| 36,084
|
<p>I have a DataGrid, with an ItemTemplate that has an image and label. In the EditItemTemplate the label is replaced by a textbox. My problem is that the edit template only shows when I click the Edit button the second time. What gives?</p>
|
<p>Make sure you check for Page.IsPostback before binding your datagrid. It may be the case that you are binding during every page load.</p>
<pre><code>If Not Page.IsPostBack() Then
DoDataBinding()
End If
</code></pre>
|
<p>Make sure you check for Page.IsPostback before binding your datagrid. It may be the case that you are binding during every page load.</p>
<pre><code>If Not Page.IsPostBack() Then
DoDataBinding()
End If
</code></pre>
| 16,306
|
<p>I'm work on project with django framework and use control version system to synchronize my code with other peoples. But i don't know how organize work with database.
In django, any people, worked on project, may changes django models, and tell 'syncdb' to synchronize model objects with db.
But other people don't about this changes, and it's code revision may not works.
Please, tell me some ways to solve this problem (maybe, different db or something another).</p>
<p>Thanks, and excuse my english :)</p>
|
<p>You have to actually talk to the people on your project.</p>
<p>If someone changes any database model, they have to actually tell everyone else about the change. This is not a Django problem. </p>
<p>Think of any SQL database -- without Django. When the DBA drop's a table, they have to tell everyone that they changed the database. Otherwise all programs that use the table break.</p>
<p>The model definition is special, and whoever can change this must tell everyone else. </p>
|
<p>Sounds like you want migrations.</p>
<p>As an example:
<a href="http://www.aswmc.com/dbmigration/" rel="nofollow noreferrer">http://www.aswmc.com/dbmigration/</a></p>
<p>You may also want to add functional unit tests that actually test that the schema is as expected, that way when the tests fail, you can see that it is a schema change, and audit whether it will affect other parts of the app. If it doesn't, fix your test to take into account the new schema.</p>
| 23,598
|
<p>.NET has System.Uri for Uris and System.IO.FileInfo for file paths. I am looking for classes which are traditionally object oriented in that they specify both meaning and behavior for the string which is used in the object's construction. What other useful string encapsulation classes exist?</p>
<p>Things such as regular expressions and StringBuilders are useful for the gross manipulation of strings but they aren't what I'm looking for.</p>
|
<p>Probably trivial, but there are also System.IO.DirectoryInfo and System.Info.Path</p>
|
<p>System.Text.StringBuilder
and
System.Text.RegularExpressions.Regex</p>
| 20,372
|
<p>I want to use Apple's or RedHat's built-in Apache but I want to use Perl 5.10 and mod_perl. What's the least intrusive way to accomplish this? I want the advantage of free security patching for the vendor's Apache, dav, php, etc., but I care a lot about which version of Perl I use and what's in my @INC path. I don't mind compiling my own mod_perl.</p>
|
<ol>
<li><p>Build your version of Perl 5.10 following any special instructions from the mod_perl documentation. Tell Perl configurator to install in some non-standard place, like /usr/local/perl/5.10.0</p></li>
<li><p>Use the instructions to build a shared library (or dynamic, or .so) mod_perl against your distribution's Apache, but make sure you run the Makefile.PL using <em>your</em> version of perl:</p>
<p>/usr/local/perl/5.10.0/bin/perl Makefile.PL APXS=/usr/bin/apxs</p></li>
<li><p>Install and configure mod_perl like normal.</p></li>
</ol>
<p>It may be helpful, after step one, to change your path so you don't accidentially get confused about which version of Perl you're using:</p>
<pre><code>export PATH=/usr/local/perl/5.10.0/bin:$PATH
</code></pre>
|
<p>You'll want to look into <a href="http://httpd.apache.org/docs/2.2/mod/mod_so.html" rel="nofollow noreferrer">mod_so</a></p>
| 10,489
|
<p>I have a textbox with an onchange event. Why does this event not fire when the user uses the autocomplete feature to populate the textbox?</p>
<p>I am working with Internet Explorer. Is there a standard and relatively simple solution to workaround this problem, without me having to disable the autocomplete feature?</p>
|
<p>Last time I had that issue, I ended up using the <code>onpropertychange</code> event for Internet Explorer instead. I read about that <a href="http://msdn.microsoft.com/en-us/library/ms533032(VS.85).aspx" rel="nofollow noreferrer">here on MSDN</a>: it is the recommended way to get around it.</p>
|
<p>I found that the following jQuery (v1.10+) JavaScript does work in the case of text being auto-completed for HTML text input fields. This was tested to work reliably at least in Safari 6.1.1 on Mac OS X 10.8.5, but should work in other compliant browsers also:</p>
<pre><code>$("input:text[id=text_field_id]").bind("focus change keyup blur", function(event) {
// handle text change here...
});
</code></pre>
<p>It seemed the addition of the <code>blur</code> event handler was the key to making this work, although the other event handlers help ensure that the event handler is called any time the text changes, whether due to an edit or new input by the browser's auto-complete feature.</p>
<p>Simply replace the <code>"input:text[id=text_field_id]"</code> code above with the relevant selector for your desired text input field, or if using the <code>id</code> attribute to refer to your field, replace <code>text_field_id</code> with your text field's <code>id</code> attribute value.</p>
| 44,625
|
<p>How do I programmatically find out the width and height of the video in an mpeg-2 <strike>transport</strike> program stream file? </p>
<p>Edit: I am using C++, but am happy for examples in any language.
Edit: Corrected question - it was probably program streams I was asking about</p>
|
<p>Check out the source code to <a href="http://libmpeg2.sourceforge.net/" rel="nofollow noreferrer">libmpeg2</a>, a F/OSS MPEG2 decoder. It appears that the width and height are set in the <code>mpeg2_header_sequence()</code> function in <code>header.c</code>. I'm not sure how control flows to that particular function, though. I'd suggest opening up an MPEG2 file in something using libmpeg2 (such as <a href="http://www.mplayerhq.hu" rel="nofollow noreferrer">MPlayer</a>) and attaching a debugger to see more closely exactly what it's doing.</p>
|
<p>hamishmcn said that Adam Rosenfield's answer was what he needed. This makes me wonder about the accuracy of the question. An MPEG transport stream doesn't <strong><em>have</em></strong> a video sequence header. That header is found in an MPEG program stream.</p>
<p>I don't have an answer. I was just hoping against hope that someone's answer was correct, because I need one.</p>
| 36,508
|
<p>I have been tinkering with BSP trees for a while now and am also playing with threads. When adding a triangle to a BSP tree, an opportunity arises to create a new thread for the purposes of processing data in parallel.</p>
<pre>
insert(triangle, bspnode)
{
....
else if(triangle spans bspnode)
{
(frontpiece, backpiece) = plane_split(triangle, bspnode)
insert(frontpiece, bspnode.front)
insert(backpiece, bspnode.back)
}
....
}
</pre>
<p>The two insert operations above could be executed by two threads, and since they do not modify the same data, cheap synchronization can be used.</p>
<pre>
insert(triangle, bspnode)
{
....
else if(triangle spans bspnode)
{
(frontpiece, backpiece) = split(triangle, bspnode)
handle = beginthread(insert(backpiece, bspnode.front))
insert(frontpiece, bspnode.back)
if(handle)
{
waitforthread(handle)
}
else
{
insert(backpiece, bspnode.front)
}
}
....
}
</pre>
<p>This new method attempts to create a thread to complete the operation in parallel, but should not fail if the thread cannot be created (it will simply revert to the original algorithm).</p>
<p>Is this a sound programming practice, or am I using threads improperly? I have not been able to find any literature on this technique. I like that it tends to use my CPU to its fullest (2 cores), and would theoretically scale to any number of processors available. I don't like that it might be horribly wasteful on CPU and memory.</p>
|
<p>Threads are great if some part of the processing is waiting on something external (user input, I/O, some other processing) - the thread that's waiting can continue to wait, while a thread that isn't waiting forges on ahead.</p>
<p>However, for processing-intensive tasks, more threads than processors actually creates overhead. It seems like your threads are doing all "CPU work", so I'd stick to one thread per core - test to find the optimal number, though.</p>
<p>The biggest overhead created is from context switching (freezing one thread and loading the execution context of the next one), as well as cache misses when threads are doing tasks with different memory (if your thread can use the CPU cache effectively).</p>
|
<p>Sure, for example, Quicksort can be programmed multithreaded quite easily and get some large performance gains on multi-core systems, and some small performance losses on non-multithreaded. Just remember that you're adding overhead twice now - once for the stack save on the recursion and once on the thread, so if you're doing a large number of recursions then it could overwhelm a system faster than a non-multithreaded approach.</p>
| 20,168
|
<p>I am getting the following error trying to read from a socket. I'm doing a <code>readInt()</code> on that <code>InputStream</code>, and I am getting this error. Perusing the documentation this suggests that the client part of the connection closed the connection. In this scenario, I am the server.</p>
<p>I have access to the client log files and it is not closing the connection, and in fact its log files suggest I am closing the connection. So does anybody have an idea why this is happening? What else to check for? Does this arise when there are local resources that are perhaps reaching thresholds?</p>
<hr>
<p>I do note that I have the following line:</p>
<pre><code>socket.setSoTimeout(10000);
</code></pre>
<p>just prior to the <code>readInt()</code>. There is a reason for this (long story), but just curious, are there circumstances under which this might lead to the indicated error? I have the server running in my IDE, and I happened to leave my IDE stuck on a breakpoint, and I then noticed the exact same errors begin appearing in my own logs in my IDE.</p>
<p>Anyway, just mentioning it, hopefully not a red herring. :-(</p>
|
<p>There are several possible causes.</p>
<ol>
<li><p>The other end has deliberately reset the connection, in a way which I will not document here. It is rare, and generally incorrect, for application software to do this, but it is not unknown for commercial software.</p></li>
<li><p>More commonly, it is caused by writing to a connection that the other end has already closed normally. In other words an application protocol error.</p></li>
<li><p>It can also be caused by closing a socket when there is unread data in the socket receive buffer.</p></li>
<li><p>In Windows, 'software caused connection abort', which is not the same as 'connection reset', is caused by network problems sending from your end. There's a Microsoft knowledge base article about this.</p></li>
</ol>
|
<p>In my experience, I often encounter the following situations;</p>
<ol>
<li><p>If you work in a corporate company, contact the network and security team. Because in requests made to external services, it may be necessary to <strong>give permission for the relevant endpoint.</strong></p></li>
<li><p>Another issue is that the <strong>SSL certificate may have expired</strong> on the server where your application is running.</p></li>
</ol>
| 8,844
|
<p>How do you run a scheduled task with Quest powershell snap in? </p>
|
<p>You would schedule PowerShell.exe, and use one of its command-line parameters to specify the script to run. At the start of that script, add:</p>
<p>Add-PSSnapin Quest.ActiveRoles.ADManagement</p>
<p>That will load the snapin for that script, and then execute whatever else is in the script.</p>
<p>(BTW, this would be the case for any script that needs one or more extra snapins.)</p>
|
<p>Another option would be to create a console file (using Export-Console - which will create a *.psc1 ) and adding -PSConsoleFile YourConsole.psc1 to your powershell.exe command line.</p>
| 44,527
|
<h3>TL;DR</h3>
<p>Is it possible to build a hotend, using separate parts, sourced on eBay, from China, and still achieve a high quality print?</p>
<hr />
<p>In my opinion, the E3D V6 hotend is rather expensive, at $/£70, especially to those building to a tight budget. Now, obviously/presumably, there is some quite rigorous QA and testing of the build, and they have to pay for their research costs and initial machining set ups and this is reflected in the high cost. Also, the expression, <em>you get what you pay for</em>, springs to mind.</p>
<p>However, I wondered if I sourced the individual parts from China, for a dollar apiece, that is to say the:</p>
<ul>
<li>Throat (with Teflon lining)</li>
<li>Heating block</li>
<li>Heatsink</li>
<li>Nozzle</li>
<li>Pneumatic connector (PC4-05/PC4-M06)</li>
<li>Heater</li>
<li>Thermistor</li>
</ul>
<p>could I too, end up with a hotend, that performs as well as, or even out performs, an E3D hotend, or am I living in cloud cuckoo land?</p>
<p>After all, let's not forget that most, if not, all of the parts used in a E3D hotend probably come from China anyway, these days, as most production facilites have moved from the US/EU to the cheaper manufacturing bases and machining shops, in SE Asia.</p>
<p>I have read <em>so many times</em> that people were experiencing extrusion problems, shoddy prints, etc, from their cheap printer, until they finally shelled out the cash and upgraded to a genuine E3D hotend. After that the prints were much improved. I have read this <em>countless</em> times, in blogs, threads, etc., so I presume that it is not possible.</p>
<p>I realise that if the parts are not finished correctly, and end up with burring on the inside of the throat, nozzle, etc., then the filament will not extrude correctly. See <a href="https://3dprinting.stackexchange.com/questions/3985/how-long-is-an-extruders-nozzles-life/3988#3988">tbm0115's answer</a> to <a href="https://3dprinting.stackexchange.com/questions/3985/how-long-is-an-extruders-nozzles-life/">How long is an extruder's/nozzle's life?</a> However, assuming that the parts that I receive are machined, and finished, correctly then there should not be a problem, right?</p>
<p>Has anyone actually done this? Is tinkering with hotends a done thing? Does anyone have any good pointers and/or tips?</p>
<p>NOTE: This question is not really after opinionated answers, in order to stay within SE rules - although opinions are always welcome - but I just want to know if anyone has first hand (positive or negative) experience of this.</p>
|
<p>Hard to say for sure - my whole printer is cheap parts bought as a kit in China by a Chinese student who abandoned it in the US (I resurrected it after it was abandoned.) It includes all the parts you list, and I think we finally sorted out what the thermistor actually is so the temperatures are more accurate now.</p>
<p>It prints. </p>
<p>Could it print better? - Probably, but at some point replacing all the various cheap parts starts to look foolish .vs. just build a new printer with better parts all around, leaving the original functional. I doubt I've ever met a "E3D V6" and I'd have to google it to see what sort of paragon of printing it's supposed to be. The only thing I'm actually considering replacing is the nozzle itself, partly because I'm just guessing what size it is (mostly based on the way it prints when set to various sizes.) I'm also contemplating adding some sort of insulation for the heater block, having squnched some aluminum foil around it as a first stop-gap.</p>
<p>Likewise, if your concern is with burrs, etc. a degree of fettling by you can sort that sort of thing out, if you know to do it and how to do it (i.e. you need to be somewhat mechanically ept.) But of course "parts from China" are not a monolithic entity - there are good parts and bad parts that both come from China - given the state of internet sales, you may well have (unknown to you) the choice of parts that passed quality control, parts that failed quality control, and parts that quality control never looked at (some of which might pass, some of which might fail), from the same production facility, available to you from various vendors at various price points. And then there are many different production facilities as well.</p>
<p>Production in the US or Europe is no magic bullet either - competing with imports on price is difficult, so one hopes that superior quality is on offer, but it may or may not actually be from a given vendor, or a given batch of parts.</p>
|
<p><em>Sorry for digging up the topic, but I'd like to share my experience with cheap Chinese parts obtained from those obvious auction sites.</em></p>
<hr>
<p>For my <a href="https://www.thingiverse.com/thing:2254103" rel="nofollow noreferrer">Hypercube Evolution</a> I have ordered all parts from Chinese suppliers except for the Aluminium extrusion profiles. This includes belts, screws, nuts, electric cables, printer board, steppers and drivers, hotend parts, you name it. </p>
<p>I do not own, or have ever owned, an official E3D hotend, so I cannot compare the clone E3D hotends to the official directly. However, I do own an Ultimaker 3 Extended (UM3E) that I manage for a group of printing enthusiasts to promote building your own printer and produce spare parts that are not sold commercially or sold at ridiculous prices. The quality of the products produced by the UM3E are very good, as expected from this quality brand, so I can compare the products from my own printer with the ones from the UM3E. </p>
<p>It is often said <strong>by others</strong> that the prints I have created with my HyperCube Evolution are at least as good as the products produced on the UM3E, or sometimes even better. In that respect, it is very hard to see any differences in the products. The UM3E is known for the simplicity of use and it's relative low need to tinker to get or keep it working, but my own creation does not require a lot of tinkering either. E.g. I have never had any clogs (several kilometers of 2.85 mm filament printed) while I use a relative high retraction length (the same as on the UM3E as default in Cura). In this respect I have never had the need to upgrade to an official E3D hotend, and most likely will never do need to.</p>
<p>So <strong>to answer your question</strong> if it is possible to build a hotend, using separate parts, sourced from China, to achieve a high quality print (while maintaining a low need for tinkering), I can vouch <strong>that it is indeed possible</strong>.</p>
<hr>
<p><em>Sidemark:
Note that if you source your materials locally, e.g. local webshops, you probably also end up with imported Chinese parts! (usually <strong>at much higher costs</strong>; but at least they <strong>arrive sooner</strong>!)</em></p>
| 620
|
<p>I would like a batch file to launch two separate programs then have the command line window close. Actually, to clarify, I am launching Internet Explorer with two different URLs.</p>
<p>So far I have something like this:</p>
<pre><code>start "~\iexplore.exe" "url1"
start "~\iexplore.exe" "url2"
</code></pre>
<p>What I get is one instance of Internet Explorer with only the second URL loaded. Seems the second is replacing the second. I seem to remember a syntax where I would load a new command line window and pass the command to execute on load, but can't find the reference.</p>
<p>As a second part of the question: what is a good reference URL to keep for the times you need to write a quick batch file?</p>
<p>Edit: I have marked an answer, because it does work. I now have two windows open, one for each URL. (thanks!) The funny thing is that without the /d approach using my original syntax I get different results based on whether I have a pre-existing Internet Explorer instance open. </p>
<ul>
<li>If I do I get two new tabs added for
my two URLs (sweet!) </li>
<li>If not I get only one final tab for the second URL I passed in.</li>
</ul>
|
<p>Try this in your batch file:</p>
<pre><code>@echo off
start /d "C:\Program Files\Internet Explorer" IEXPLORE.EXE www.google.com
start /d "C:\Program Files\Internet Explorer" IEXPLORE.EXE www.yahoo.com
</code></pre>
|
<p>There is a setting in the IE options that controls whether it should open new links in an existing window or in a new window. I'm not sure if you can control it from the command line but maybe changing this option would be enough for you.</p>
<p>In IE7 it looks like the option is "Reuse windows for launching shortcuts (when tabbed browsing is disabled)".</p>
| 22,903
|
<p>I thought that if a c pointer pointing to a char array was incremented then it would point to the next element in that array. But when I tried this I found that I had to increment it twice. Trying the increment using sizeof(char) I found that adding the size of a char was too much so it had to be divided by two. </p>
<pre><code>#include <stdio.h>
int main(int argc, char * argv[]){
char *pi;
int i;
pi = argv[1];
printf("%d args.\n",argc-1);
printf("input: ");
for(i=0;i<argc-1;i++){
printf("%c, ",*pi);
/*The line below increments pi by 1 char worth of bytes */
//pi+=sizeof(pi)/2;
/* An alternative to the above line is putting pi++ twice - why? */
pi++;
pi++;
}
printf("\n");
return 0;
}
</code></pre>
<p>Am I doing something wrong? or am I misunderstanding the method of incrementing pointers?</p>
|
<p>sizeof(char) is guaranteed to be 1, but sizeof(char*) isn't.</p>
<p>Nevertheless, your function <strong>only works by accident</strong>.</p>
<p>For example, try calling it with the following parameters:</p>
<pre><code>abc defg
</code></pre>
<p>This will yield:</p>
<pre><code>2 args.
input: a, c,
</code></pre>
<p>which is plain wrong. The problem is you are incrementing a pointer to the element 1 of argv instead of a pointer to argv.</p>
<p>Try this:</p>
<pre><code>#include <stdio.h>
int main(int argc, char * argv[]){
char **pi;
int i;
pi = argv + 1;
printf("%d args.\n",argc-1);
printf("input: ");
for(i=0;i<argc-1;i++){
printf("%c, ",**pi);
pi++;
}
printf("\n");
return 0;
}
</code></pre>
<p>This will print the first character of every argument:</p>
<pre><code>2 args.
input: a, d,
</code></pre>
|
<p>If you have a pointer <code>ptr</code> of type <code>T*</code> and you add <code>N</code>, then the pointer will be advanced by <code>N * sizeof (*ptr)</code> or equivalent <code>N * sizeof (T)</code> bytes. You simply forgot to dereference <code>pi</code>. So what you got with <code>sizeof (pi)</code> was the sizeof of the <code>char*</code>, but not the sizeof of a <code>char</code>. Your line was equivalent to <code>pi+=sizeof(char*)/2;</code> Pointers on your platform are 4 bytes big. Thus in effect you did <code>pi+=2;</code>. Write <code>pi+=2</code> if you want to increment 2 times. Note that <code>char</code> has an sizeof of 1 by definition. You don't need to do <code>sizeof (char)</code>, it is always 1.</p>
| 40,296
|
<p>Building on <a href="https://stackoverflow.com/questions/318553/getting-emacs-to-untabify-when-saving-files">Getting Emacs to untabify when saving certain file types (and only those file types)</a> , I'd like to run a hook to untabify my C++ files when I start modifying the buffer. I tried adding hooks to untabify the buffer on load, but then it untabifies all my writable files that are autoloaded when emacs starts.</p>
<p>(For those that wonder why I'm doing this, it's because where I work enforces the use of tabs in files, which I'm happy to comply with. The problem is that I mark up my files to tell me when lines are too long, but the regexp matches the number of characters in the line, not how much space the line takes up. 4 tabs in a line can push it far over my 132 character limit, but the line won't be marked appropriately. Thus, I need a way to tabify and untabify automatically.)</p>
|
<p>Take a look at the variable "before-change-functions".</p>
<p>Perhaps something along this line (warning: code not tested):</p>
<pre><code>(add-hook 'before-change-functions
(lambda (&rest args)
(if (not (buffer-modified-p))
(untabify (point-min) (point-max)))))
</code></pre>
|
<p>This answer is tangential, but may be of use.</p>
<p>The package wide-column.el <a href="http://homepages.cs.ncl.ac.uk/phillip.lord/download/emacs/wide-column.el" rel="nofollow noreferrer">link text</a> changes the cursor color when the cursor is past a given column - and actually the cursor colors can vary depending on the settings. This sounds like a less intrusive a solution than your regular expression code, but it may not suit your needs.</p>
| 47,011
|
<p>When reviewing, I sometimes encounter this kind of loop:</p>
<pre><code>i = begin
while ( i != end ) {
// ... do stuff
if ( i == end-1 (the one-but-last element) ) {
... do other stuff
}
increment i
}
</code></pre>
<p>Then I ask the question: would you write this?</p>
<pre><code>i = begin
mid = ( end - begin ) / 2 // (the middle element)
while ( i != end ) {
// ... do stuff
if ( i > mid ) {
... do other stuff
}
increment i
}
</code></pre>
<p>In my opinion, this beats the intention of writing a loop: you loop because there is something common to be done for each of the elements. Using this construct, for some of the elements you do something different. So, I conclude, you need a separate loop for those elements:</p>
<pre><code>i = begin
mid = ( end - begin ) / 2 //(the middle element)
while ( i != mid ) {
// ... do stuff
increment i
}
while ( i != end ) {
// ... do stuff
// ... do other stuff
increment i
}
</code></pre>
<p>Now I even saw a <a href="https://stackoverflow.com/questions/151046/c-last-loop-iteration-stl-map-iterator">question</a> on SO on how to write the <code>if</code>-clause in a nice way... And I got sad: something isn't right here.</p>
<p>Am I wrong? If so, what's so good about cluttering the loop body with special cases, which you are aware of upfront, at coding time?</p>
|
<p>I don't think this question should be answered by a principle (e.g. "in a loop, treat every element equally"). Instead, you can look at two factors to evaluate if an implementation is good or bad:</p>
<ol>
<li>Runtime effectivity - does the compiled code run fast, or would it be faster doing it differently?</li>
<li>Code maintainability - Is it easy (for another developer) to understand what is happening here? </li>
</ol>
<p>If it is faster and the code is more readable by doing everything in one loop, do it that way. If it is slower and less readable, do it another way. </p>
<p>If it is faster and less readably, or slower but more readable, find out which of the factors matters more in your specific case, and then decide how to loop (or not to loop).</p>
|
<p>The special case should be done outside the loop if it is only to be performed once.</p>
<p>However, there may be an index or some other variable(s) that are just easier to keep inside the loop due to scoping. There may also be a contextual reason for keeping all the operations on the datastructure together inside the loop control structure, though I think that is a weak argument on its own.</p>
| 18,951
|
<p>I want to know if people here typically disable SELinux on installations where it is on by default? If so can you explain why, what kind of system it was, etc?</p>
<p>I'd like to get as many opinions on this as possible.</p>
|
<p>I did, three or four years ago when defined policies had many pitfalls and creating policies was too hard and I had 'no time' to learn. This was on not critical machines, of course.</p>
<p>Nowadays with all the work done to ship distros with sensible policies, and the <a href="http://seedit.sourceforge.net/index.html" rel="noreferrer">tools</a> and <a href="http://www.redhatmagazine.com/2007/08/21/a-step-by-step-guide-to-building-a-new-selinux-policy-module/" rel="noreferrer">tutorials</a> that exist which help you create, fix and define policies there's no excuse to disable it.</p>
|
<p>Under Red-hat, you can edit <code>/etc/sysconfig/selinux</code> and set <code>SELINIX=disabled</code>.</p>
<p>I think under all versions of Linux you can add <code>selinux=0 noselinux</code> to the boot line in lilo.conf or grub.conf.</p>
| 12,329
|
<p>I need to schedule several different pages on several different sites to be run at certain times, usually once a night. Is there any software out there to do this? it would be nice if it called the page and then recorded the response and whether the called page was successful run or not. I was using Helm on a different box and it had a nice Web Scheduler module but Helm is not an option for this machine. This is a Window Server 2008 box.</p>
|
<p>We use standard scheduled tasks that call a bat file that calls a VBS file. I know it is not the most elegant solution ever, but it consistently works.</p>
<p>BAT:</p>
<pre><code>webrun.vbs http://website.com/page.aspx
</code></pre>
<p>VBS:</p>
<pre><code>dim URL, oArgs
Set oArgs = WScript.Arguments
if oArgs.Count = 0 then
msgbox("Error: Must supply URL")
wscript.quit 1
end if
URL = oArgs(0)
on error resume next
Set objXML = CreateObject("MSXML2.ServerXMLHTTP")
if err then
msgbox("Error: " & err.description)
wscript.quit 1
end if
' Call the remote machine the request
objXML.open "GET", URL, False
objXML.send()
' return the response
'msgbox objXML.responSetext
' clean up
Set objXML = Nothing
</code></pre>
<p>The code in the VBS file is almost assuredly both overkill and underwritten, but functional none-the-less.</p>
|
<p>If it's not a requirement to schedule them from the same box, have a look to <a href="http://site24x7.com" rel="nofollow noreferrer">Zoho's site24x7</a>.</p>
<p>It is initially designed to monitor web sites but it has an option to record expected answers and compare them so you can use it for your purpose with the added security of an external site. It's not free however except for few urls. </p>
<p>They are other similar providers but they looked pretty good last time I searched the web on this topic. </p>
| 32,142
|
<blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/114149/const-correctness-in-c-sharp">“const correctness” in C#</a> </p>
</blockquote>
<p>I have programmed C++ for many years but am fairly new to C#. While learning C# I found that the use of the <a href="http://en.csharp-online.net/const,_static_and_readonly" rel="nofollow noreferrer">const</a> keyword is much more limited than in C++. AFAIK, there is, <a href="http://andymcm.com/csharpfaq.htm#6.8" rel="nofollow noreferrer">for example</a>, no way to declare arguments to a function const. I feel uncomfortable with the idea that I may make inadvertent changes to my function arguments (which may be complex data structures) that I can only detect by testing. </p>
<p>How do you deal with this situation?</p>
|
<p><a href="https://stackoverflow.com/q/132618/16800">Stephen Denne</a> has a Metro implementation that satisfies your requirement. My answer is provided below after a short explination as to why that is the case.</p>
<p>Most Web Service implementations that are built using HTTP as the message protocol are REST compliant, in that they only allow simple send-receive patterns and nothing more. This greatly improves interoperability, as all the various platforms can understand this simple architecture (for instance a Java web service talking to a .NET web service).</p>
<p>If you want to maintain this you could provide chunking.</p>
<pre><code>boolean uploadFile(String username, String password, String fileName, int currentChunk, int totalChunks, byte[] chunk);
</code></pre>
<p>This would require some footwork in cases where you don't get the chunks in the right order (Or you can just require the chunks come in the right order), but it would probably be pretty easy to implement.</p>
|
<p>One way to do it is to add a <strong>uploadFileChunk</strong>(byte[] chunkData, int size, int offset, int totalSize) method (or something like that) that uploads parts of the file and the servers writes it the to disk. </p>
| 16,077
|
<p>Are there any good libraries for cool text animation effects for use in Actionscript (for use in an intro screen or banner).</p>
<p>I've given up tryin to use Flash itself because that takes forever, and I dont know which of the many flash text animation tools to choose from.</p>
<p>I'd like to be able to dynamically product cool text effects with different messages.</p>
|
<p>There is <a href="http://www.txeff.com/" rel="nofollow noreferrer">http://www.txeff.com/</a> which is pretty awesome although a little expensive. It even has an <a href="http://www.txeff.com/#/edit/null/" rel="nofollow noreferrer">effect editor</a>.</p>
|
<p>txeff is definitely the best thing out there.</p>
<p>In October they have a promotion for their new version which is only $99 and has some great new features. You can use it in actionscript or flash.</p>
<p>Of course i bought it yesterday for $179! ahh</p>
| 22,943
|
<p>I have a block of JSP code that needs to be used in several places (basically a widget that several pages use). What's a good way to modularize this? I'd rather not put it in an object since string manipulation of HTML gets ugly. Using <code><%@ include file="foo.jsp"%></code> is problematic because we wind up having implicit global vars.</p>
|
<p>You can create a simple <em>tag</em> and use it anywhere you want your widget. A tag is a reusable object that you can use in any of your JSP's.</p>
<p>Please see <a href="http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/JSPTags.html" rel="nofollow noreferrer">http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/JSPTags.html</a>.</p>
|
<ol>
<li><p>Separate the JSP out into its own file and include it (JSP Includes, Tiles Includes, etc)</p></li>
<li><p>Can you create a Tag Lib incorporating the functionality?</p></li>
</ol>
| 35,643
|
<p>For my own project at home, I'm using the rather excellent managed subversion hosting from <a href="http://cvsdude.com/" rel="nofollow noreferrer">CVSDude</a>. As it's only me working on the code right now, I'm not using CruiseControl.net, however I expect this will change in the next couple of months and will want a full build process to kick off upon check-in.</p>
<p>Has anyone managed to get CruiseControl.net working with CVSDude? My collegue Mike has this <a href="http://mikehadlow.blogspot.com/2008/01/more-on-source-repository-hosting-what.html" rel="nofollow noreferrer">blog post</a> where someone from CVSDude said: </p>
<blockquote>
<p>"Your can use our post-commit call back facility to call a URL on your
server, which passes variables relating to the last checkin (variables
detailed in our specification). Your CGI script will these variables and
perform whatever tasks are required i.e. updating Cruise Control, etc."</p>
</blockquote>
<p>Sounds lovely. But has anyone <em>actually done it</em> with cruisecontrol?</p>
|
<p>Use a subrange of <code>[\u0000-\uFFFF]</code> for what you want.</p>
<p>You can also use the <code>re.UNICODE</code> compile flag. <a href="http://docs.python.org/lib/re-syntax.html" rel="nofollow noreferrer">The docs</a> say that if <code>UNICODE</code> is set, <code>\w</code> will match the characters <code>[0-9_]</code> plus whatever is classified as alphanumeric in the Unicode character properties database. </p>
<p>See also <a href="http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-05/2560.html" rel="nofollow noreferrer">http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-05/2560.html</a>.</p>
|
<p>\X seems to be available as a generic word-character in some languages, it allows you to match a single character disregarding of how many bytes it takes up. Might be useful.</p>
| 3,518
|
<p>Is it necessary to set large objects to <code>null</code> when implementing a <code>Dispose()</code> method?</p>
|
<p>Not usually.</p>
<p>The garbage collector looks for rooted objects, and circular dependencies don't prevent collection if neither object is rooted.</p>
<p>There is a caveat: if object A has a reference to object B, and object B is being disposed, you may want to clean up that relationship or else you could end up with a leak. The most common place this surfaces is in event handlers (the reference from A->B is one that B controls, because it subscribed to an event on A). In this case, if A is still rooted, B cannot be collected even though it's been disposed.</p>
|
<p>Think about the purpose of Disposable methods for a bit: it's usually because you're holding some resource that won't be released during garbage collection. This is usually something like a database connection or a file handle. Thus, once the Dispose method has been called, all those resources have been released.</p>
<p>I'd argue that having nulls floating around is more harmful that having "zombie" objects floating around.</p>
| 7,257
|
<p>In python do you generally use <a href="http://www.python.org/dev/peps/pep-0008/" rel="noreferrer">PEP 8 -- Style Guide for Python Code</a> as your coding standards/guidelines? Are there any other formalized standards that you prefer?</p>
|
<blockquote>
<p>"In python do you generally use PEP 8 -- Style Guide for Python Code as your coding standards/guidelines? Are there any other formalized standards that you prefer?"</p>
</blockquote>
<p>As mentioned by you follow <a href="http://www.python.org/dev/peps/pep-0008/" rel="noreferrer">PEP 8</a> for the main text, and <a href="http://www.python.org/dev/peps/pep-0257/" rel="noreferrer">PEP 257</a> for docstring conventions</p>
<p>Along with Python Style Guides, I suggest that you refer the following:</p>
<ol>
<li><a href="http://python.net/~goodger/projects/pycon/2007/idiomatic/" rel="noreferrer">Code Like a Pythonista: Idiomatic Python</a></li>
<li><a href="http://learnpython.pbwiki.com/PythonTricks" rel="noreferrer">Common mistakes and Warts</a></li>
<li><a href="http://eikke.com/how-not-to-write-python-code/" rel="noreferrer">How not to write Python code</a></li>
<li><a href="http://eikke.com/python-gotcha/" rel="noreferrer">Python gotcha</a></li>
</ol>
|
<p>I follow the PEP8, it is a great piece of coding style.</p>
| 46,436
|
<p>I've used <a href="http://upx.sourceforge.net/" rel="noreferrer">UPX</a> before to reduce the size of my Windows executables, but I must admit that I am naive to any negative side effects this could have. What's the downside to all of this packing/unpacking?</p>
<p>Are there scenarios in which anyone would recommend NOT UPX-ing an executable (e.g. when writing a DLL, Windows Service, or when targeting Vista or Win7)? I write most of my code in Delphi, but I've used UPX to compress C/C++ executables as well.</p>
<p>On a side note, I'm <strong>not</strong> running UPX in some attempt to protect my exe from disassemblers, only to reduce the size of the executable and prevent cursory tampering.</p>
|
<blockquote>
<p>... there are downsides to
using EXE compressors. Most notably:</p>
<ul>
<li><p>Upon startup of a compressed EXE/DLL, all of the code is
decompressed from the disk image into
memory in one pass, which can cause
disk thrashing if the system is low on
memory and is forced to access the
swap file. In contrast, with
uncompressed EXE/DLLs, the OS
allocates memory for code pages on
demand (i.e. when they are executed).</p>
</li>
<li><p>Multiple instances of a compressed EXE/DLL create multiple
instances of the code in memory. If
you have a compressed EXE that
contains 1 MB of code (before
compression) and the user starts 5
instances of it, approximately 4 MB of
memory is wasted. Likewise, if you
have a DLL that is 1 MB and it is used
by 5 running applications,
approximately 4 MB of memory is
wasted. With uncompressed EXE/DLLs,
code is only stored in memory once and
is shared between instances.</p>
</li>
</ul>
</blockquote>
<p><a href="http://www.jrsoftware.org/striprlc.php#execomp" rel="nofollow noreferrer">http://www.jrsoftware.org/striprlc.php#execomp</a></p>
|
<p>I believe there is a possibility that it might not work on computers that have <a href="http://en.wikipedia.org/wiki/Data_Execution_Prevention" rel="nofollow noreferrer">DEP</a> (Data Execution Prevention) turned on. </p>
| 46,066
|
<p>So I'm getting really sick of E*TRADE and, being a developer, would love to find an online broker that offers an API. It would be great to be able to write my own trading tools, and maybe even modify existing ones.</p>
<p>Based on my research so far, I've only found one option. Interactive Brokers offers a multi-language API (Java/C++/ActiveX/DDE) and has some fairly decent commission rates to boot. I want to make sure there aren't any other options out there I should be considering. Any ideas?</p>
<p>Update: Based on answers so far, here's a quick list...</p>
<ul>
<li><a href="http://www.interactivebrokers.com/" rel="noreferrer">Interactive Brokers</a>
<ul>
<li>Java</li>
<li>C++</li>
<li>ActiveX</li>
<li>DDE for Excel</li>
</ul></li>
<li><a href="http://www.pcmtrading.com" rel="noreferrer">Pinnacle Trading</a>
<ul>
<li>C++</li>
<li>Perl</li>
<li>VB.NET</li>
<li>Excel</li>
</ul></li>
<li><a href="http://www.mbtrading.com/developersMain.aspx?page=sdk" rel="noreferrer">MB Trading</a></li>
</ul>
|
<p>I vote for IB(Interactive Brokers). I've used them in the past as was quite happy. Pinnacle Capital Markets trading also has an API (pcmtrading.com) but I haven't used them.</p>
<p><strong>Interactive Brokers:</strong></p>
<p><a href="https://www.interactivebrokers.com/en/?f=%2Fen%2Fsoftware%2Fibapi.php" rel="noreferrer">https://www.interactivebrokers.com/en/?f=%2Fen%2Fsoftware%2Fibapi.php</a></p>
<p><strong>Pinnacle Capital Markets:</strong></p>
<p><a href="http://www.pcmtrading.com/es/technology/api.html" rel="noreferrer">http://www.pcmtrading.com/es/technology/api.html</a></p>
|
<p>Only related with currency trading (Forex), but many Forex brokers are offering MetaTrader which let you code in MQL. The main problem with it (aside that it's limited to Forex) is that you've to code in MQL which might not be your preferred language.</p>
| 8,390
|
<p>I'm creating a really complex dynamic sql, it's got to return one row per user, but now I have to join against a one to many table. I do an outer join to make sure I get at least one row back (and can check for null to see if there's data in that table) but I have to make sure I only get one row back from this outer join part if there's multiple rows in this second table for this user.
So far I've come up with this: (sybase)</p>
<pre><code>SELECT a.user_id
FROM table1 a
,table2 b
WHERE a.user_id = b.user_id
AND a.sub_id = (
SELECT min(c.sub_id)
FROM table2 c
WHERE b.sub_id = c.sub_id
)
</code></pre>
<p>The subquery finds the min value in the one to many table for that particular user.</p>
<p>This works but I fear nastiness from doing correlated subqueries when table 1 and 2 get very large.
Is there a better way? I'm trying to dream up a way to get joins to do it, but I'm not seeing it.
Also saying "where rowcount=1" or "top 1" doesn't help me, because I'm not trying to fix the above query, I'm ADDING the above to an already complex query.</p>
|
<p>In MySql you can ensure that any query returns at most X rows using</p>
<pre><code>select *
from foo
where bar = 1
limit X;
</code></pre>
<p>Unfortunately, I'm fairly sure this is a MySQL-specific extension to SQL. However, a Google search for something like "mysql sybase limit" might turn up an equivalent for Sybase.</p>
|
<p>Well, you already have a query that works. If you are concerned about the speed you could</p>
<ul>
<li><p>Add a field to table2 which
identifies which sub_id is the
'first one' or</p></li>
<li><p>Keep track of table2's primary key in table1, or in another table</p></li>
</ul>
| 29,699
|
<p>Is it possible to read the data in the php $_SESSION array in the .htaccess file in Apache? So say I have the following:</p>
<pre><code>$_SESSION['foo'] = 'bar';
</code></pre>
<p>could I then in .htaccess do something like:</p>
<pre><code>RewriteRule bla.png folder/{the php session var foo}/file.png
</code></pre>
<p>Is that possible?</p>
<p>I already have a working workaround but if this is possible it would be way nicer.</p>
|
<p>I'm not aware that its possible.</p>
<p>But I can think of a few workarounds involving rewriting to a PHP script.</p>
|
<p>You can't do that the way you want.</p>
<p>If you are really using the $_SESSION variable maybe there's an Apache environmental variable that you can use that will have the same value as the $_SESSION one.</p>
<p>Look at the following list and see if any of them helps:<br/>
<a href="http://www.zytrax.com/tech/web/env_var.htm" rel="nofollow noreferrer">http://www.zytrax.com/tech/web/env_var.htm</a></p>
<p>You'll have to use it like this:</p>
<blockquote>
<p>RewriteRule bla.png
folder/%{VAR_NAME}/file.png</p>
</blockquote>
| 44,528
|
<p>I have something that is driving me absolutely crazy...</p>
<pre><code> Public Function GetAccountGroups() As IList(Of AccountGroup)
Dim raw_account_groups As IList(Of AccountGroup)
raw_account_groups = _repository.GetAccountGroups().ToList()
Dim parents = (From ag In raw_account_groups _
Where ag.parent_id = 0 _
Select ag).ToList()
parents(0).sub_account_groups = (From sag In raw_account_groups _
Where sag.parent_id = 0 _
Select sag).ToList()
Dim sql_func As Func(Of AccountGroup, List(Of AccountGroup)) = Function(p) _
(From sag In raw_account_groups _
Where sag.parent_id = p.id _
Select sag).ToList()
parents.ForEach(Function(p) p.sub_account_groups = sql_func(p))
Return parents
End Function
</code></pre>
<p>The line <code>parents.ForEach(Function(p) p.sub_account_groups = sql_func(p))</code> has this error...</p>
<blockquote>
<p>Operator '=' is not defined for types 'System.Collections.Generic.IList(Of st.data.AccountGroup)' and 'System.Collections.Generic.List(Of st.data.AccountGroup)'. </p>
</blockquote>
<p>but I really can't see how it is any different from this code from Rob Connery</p>
<pre><code>public IList<Category> GetCategories() {
IList<Category> rawCategories = _repository.GetCategories().ToList();
var parents = (from c in rawCategories
where c.ParentID == 0
select c).ToList();
parents.ForEach(p =>
{
p.SubCategories = (from subs in rawCategories
where subs.ParentID == p.ID
select subs).ToList();
});
return parents;
}
</code></pre>
<p>which compiles perfectly... what am I doing incorrectly?</p>
|
<p>Lambda's in VB.Net have to return a value, so your equal sign ('=') is being intepreted as a comparison (so that the lambda returns a boolean), rather than an assignment.</p>
|
<p>I haven't used VB.NET since moving to C# 3.0, but it seems like it could be a type inference issue. The error is a bit odd since List implements IList, so the assignment should work. You can say "p.ID = 123" for the lambda and things seem to work. </p>
<p>For anyone else interested in looking into it, here is code that you can paste into a new VB.NET console project to demonstrate this issue:</p>
<pre><code>Module Module1
Sub Main()
End Sub
End Module
Class AccountGroup
Public parent_id As Integer
Public id As Integer
Public sub_account_groups As List(Of AccountGroup)
End Class
Class AccountRepository
Private _repository As AccountRepository
Public Function GetAccountGroups() As IList(Of AccountGroup)
Dim raw_account_groups As IList(Of AccountGroup)
raw_account_groups = _repository.GetAccountGroups().ToList()
Dim parents = (From ag In raw_account_groups _
Where ag.parent_id = 0 _
Select ag).ToList()
parents(0).sub_account_groups = (From sag In raw_account_groups _
Where sag.parent_id = 0 _
Select sag).ToList()
Dim sql_func As Func(Of AccountGroup, List(Of AccountGroup)) = Function(p) _
(From sag In raw_account_groups _
Where sag.parent_id = p.id _
Select sag).ToList()
parents.ForEach(Function(p) p.sub_account_groups = sql_func(p))
Return parents
End Function
End Class
</code></pre>
| 9,346
|
<p>I have a model class:</p>
<pre><code>class Person(db.Model):
first_name = db.StringProperty(required=True)
last_name = db.StringProperty(required=True)
</code></pre>
<p>I have an instance of this class in <code>p</code>, and string <code>s</code> contains the value <code>'first_name'</code>. I would like to do something like:</p>
<pre><code>print p[s]
</code></pre>
<p>and </p>
<pre><code>p[s] = new_value
</code></pre>
<p>Both of which result in a <code>TypeError</code>.</p>
<p>Does anybody know how I can achieve what I would like?</p>
|
<p>If the model class is sufficiently intelligent, it should recognize the standard Python ways of doing this.</p>
<p>Try:</p>
<pre><code>getattr(p, s)
setattr(p, s, new_value)
</code></pre>
<p>There is also hasattr available.</p>
|
<p>p.first_name = "New first name"
p.put()</p>
<p>or p = Person(first_name = "Firsty",
last_name = "Lasty" )
p.put()</p>
| 11,727
|
<p>What is the easiest way to test (using reflection), whether given method (i.e. java.lang.Method instance) has a return type, which can be safely casted to List<String>?</p>
<p>Consider this snippet:</p>
<pre><code>public static class StringList extends ArrayList<String> {}
public List<String> method1();
public ArrayList<String> method2();
public StringList method3();
</code></pre>
<p>All methods 1, 2, 3 fulfill the requirement. It's quite easy to test it for the method1 (via getGenericReturnType(), which returns instance of ParameterizedType), but for methods2 and 3, it's not so obvious. I imagine, that by traversing all getGenericSuperclass() and getGenericInterfaces(), we can get quite close, but I don't see, how to match the TypeVariable in List<E> (which occurs somewhere in the superclass interfaces) with the actual type parameter (i.e. where this E is matched to String).</p>
<p>Or maybe is there a completely different (easier) way, which I overlook?</p>
<p><strong>EDIT:</strong> For those looking into it, here is method4, which also fulfills the requirement and which shows some more cases, which have to be investigated:</p>
<pre><code>public interface Parametrized<T extends StringList> {
T method4();
}
</code></pre>
|
<p>I tried this code and it returns the actual generic type class so it seems the type info can be retrieved. However this only works for method 1 and 2. Method 3 does not seem to return a list typed String as the poster assumes and therefore fails.</p>
<pre><code>public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
try{
Method m = Main.class.getDeclaredMethod("method1", new Class[]{});
instanceOf(m, List.class, String.class);
m = Main.class.getDeclaredMethod("method2", new Class[]{});
instanceOf(m, List.class, String.class);
m = Main.class.getDeclaredMethod("method3", new Class[]{});
instanceOf(m, List.class, String.class);
m = Main.class.getDeclaredMethod("method4", new Class[]{});
instanceOf(m, StringList.class);
}catch(Exception e){
System.err.println(e.toString());
}
}
public static boolean instanceOf (
Method m,
Class<?> returnedBaseClass,
Class<?> ... genericParameters) {
System.out.println("Testing method: " + m.getDeclaringClass().getName()+"."+ m.getName());
boolean instanceOf = false;
instanceOf = returnedBaseClass.isAssignableFrom(m.getReturnType());
System.out.println("\tReturn type test succesfull: " + instanceOf + " (expected '"+returnedBaseClass.getName()+"' found '"+m.getReturnType().getName()+"')");
System.out.print("\tNumber of generic parameters matches: ");
Type t = m.getGenericReturnType();
if(t instanceof ParameterizedType){
ParameterizedType pt = (ParameterizedType)t;
Type[] actualGenericParameters = pt.getActualTypeArguments();
instanceOf = instanceOf
&& actualGenericParameters.length == genericParameters.length;
System.out.println("" + instanceOf + " (expected "+ genericParameters.length +", found " + actualGenericParameters.length+")");
for (int i = 0; instanceOf && i < genericParameters.length; i++) {
if (actualGenericParameters[i] instanceof Class) {
instanceOf = instanceOf
&& genericParameters[i].isAssignableFrom(
(Class) actualGenericParameters[i]);
System.out.println("\tGeneric parameter no. " + (i+1) + " matches: " + instanceOf + " (expected '"+genericParameters[i].getName()+"' found '"+((Class) actualGenericParameters[i]).getName()+"')");
} else {
instanceOf = false;
System.out.println("\tFailure generic parameter is not a class");
}
}
} else {
System.out.println("" + true + " 0 parameters");
}
return instanceOf;
}
public List<String> method1() {
return null;
}
public ArrayList<String> method2() {
return new ArrayList<String>();
}
public StringList method3() {
return null;
}
public <T extends StringList> T method4() {
return null;
}
</code></pre>
<p>This outputs:</p>
<pre>
Testing method: javaapplication2.Main.method1
Return type test succesfull: true (expected 'java.util.List' found 'java.util.List')
Number of generic parameters matches: true (expected 1, found 1)
Generic parameter no. 1 matches: true (expected 'java.lang.String' found 'java.lang.String')
Testing method: javaapplication2.Main.method2
Return type test succesfull: true (expected 'java.util.List' found 'java.util.ArrayList')
Number of generic parameters matches: true (expected 1, found 1)
Generic parameter no. 1 matches: true (expected 'java.lang.String' found 'java.lang.String')
Testing method: javaapplication2.Main.method3
Return type test succesfull: false (expected 'java.util.List' found 'com.sun.org.apache.xerces.internal.xs.StringList')
Number of generic parameters matches: true 0 parameters
Testing method: javaapplication2.Main.method4
Return type test succesfull: true (expected 'com.sun.org.apache.xerces.internal.xs.StringList' found 'com.sun.org.apache.xerces.internal.xs.StringList')
Number of generic parameters matches: true 0 parameters
</pre>
|
<p><a href="http://forums.java.net/jive/thread.jspa?threadID=47527&tstart=0" rel="nofollow noreferrer" title="Generics and getting the actual type ...">This thread</a> on the java.net forums might be helpful (although I have to admit I didn't understand everything they said).</p>
| 22,096
|
<p>I'm trying to use Exchange Web Services to update a calendar item. I'm creating an ItemChangeType, and then an ItemIdType. I have a unique ID to use for ItemIdType.Id, but I have nothing to use for the ChangeKey. When I leave it out, I get an ErrorChangeKeyRequiredForWriteOperations. But when i try to just put something in there, I get an ErrorInvalidChangeKey. </p>
<p>What can I use for this to get it to work?</p>
<p>I'm also trying to determine what is the best implementation of BaseItemIdType to use for ItemChangeType.Item. So far, I'm using ItemIdType, and I'm guessing that's correct, but I haven't been able to find any particularly helpful documentation on this.</p>
|
<p>To be a bit more explicit on Hauge's answer: the ChangeKey is stored in Exchange and identifies the current state of the item. Any change to that item creates a new ChangeKey.</p>
<p>This allows Exchange to "know" that your update is being applied to the same item state as when you looked at the item - it hasn't changed since you checked it.</p>
<p>Some code available at:
<a href="http://msdn.microsoft.com/en-us/library/aa563020.aspx" rel="noreferrer"><a href="http://msdn.microsoft.com/en-us/library/aa563020.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/aa563020.aspx</a></a></p>
|
<p>If you know ID only, you can get ChangeKey easily, for example for folder:</p>
<pre><code> private FolderIdType GetFullFolderID(string folderID)
{
GetFolderType request = new GetFolderType();
request.FolderIds = new BaseFolderIdType[1];
FolderIdType id = new FolderIdType();
id.Id = folderID;
request.FolderIds[0] = id;
request.FolderShape = new FolderResponseShapeType();
request.FolderShape.BaseShape = DefaultShapeNamesType.IdOnly;
GetFolderResponseType response = _binding.GetFolder(request);
FailOnError(response);
FolderInfoResponseMessageType firmt = (FolderInfoResponseMessageType)response.ResponseMessages.Items[0];
FolderType ft = (FolderType)firmt.Folders[0];
id.ChangeKey = ft.FolderId.ChangeKey;
return id;
}
</code></pre>
| 18,119
|
<p>Is it possible to do pseudo-streaming(eg start playback at any point) with wmv files and silverlight? </p>
<p>This is possible using Flash in a progressive download setup but can it be done on the Microsoft track?</p>
|
<p>You can <strong>use <a href="http://www.microsoft.com/windows/windowsmedia/forpros/server/version.aspx" rel="nofollow noreferrer">Windows Media Services 2008</a></strong>. It enables you to actually stream WMV to Silverlight interface.</p>
|
<p>No reason you couldn't stream it like any other HTTP video; it basically just expects the file to be a correct WMV file. You would need to have a server that supports the seeking, though.</p>
| 10,795
|
<p>I just want to know how I can start derby in network server mode and still be able to get an embedded connection?</p>
<p>Thank you.</p>
|
<p>The <a href="http://publib.boulder.ibm.com/infocenter/cscv/v10r1/index.jsp?topic=/com.ibm.cloudscape.doc/radminembeddedserverex.html" rel="nofollow noreferrer">Embedded Server mode</a> sounds like what you are asking for. It allows you to start a network server when you start the embedded database.</p>
|
<p>It sounds contradictory that you want to start derby in network server mode and get the embedded driver. Even if this might be possible, it is definitely discouraged. You should decide on whether you want to use Apache Derby in the network mode using the DRDA or as an embedded driver and stick to that decision.</p>
<p>Here you'll find a tutorial on how to use the network driver:
<a href="http://db.apache.org/derby/papers/DerbyTut/ns_intro.html" rel="nofollow noreferrer">http://db.apache.org/derby/papers/DerbyTut/ns_intro.html</a></p>
| 49,037
|
<p>How can I find the high water mark (the historical maximum number of concurrent users) in an <strong>oracle database (9i)</strong>.</p>
|
<p>This should do the trick:</p>
<pre><code>SELECT sessions_highwater FROM v$license;
</code></pre>
|
<pre><code>select max_utilization from v$resource_limit where resource_name = 'sessions';
</code></pre>
<p>A good overview of Oracle system views can be found <a href="http://www.adp-gmbh.ch/ora/misc/dynamic_performance_views.html" rel="nofollow noreferrer">here</a>.</p>
| 2,963
|
<p>Is it possible to see the history of changes to a particular line of code in a Subversion repository?</p>
<p>I'd like, for instance, to be able to see when a particular statement was added or when that statement was changed, even if its line number is not the same any more.</p>
|
<p>I don't know a method for tracking statements through time in Subversion.</p>
<p>It is simple however to see when any particular line in a file was last changed using <code>svn blame</code>. Check the SVNBook: <a href="http://svnbook.red-bean.com/en/1.7/svn.ref.svn.c.blame.html" rel="noreferrer"><code>svn blame</code> reference</a>:</p>
<p><strong>Synopsis</strong></p>
<pre><code>svn blame TARGET[@REV]...
</code></pre>
<p><strong>Description</strong></p>
<p>Show author and revision information in-line for the specified files or URLs. Each line of text is annotated at the beginning with the author (username) and the revision number for the last change to that line.</p>
|
<p>The command you're looking for is <a href="http://svnbook.red-bean.com/en/1.7/svn.ref.svn.c.blame.html" rel="nofollow noreferrer"><code>svn blame</code></a>.</p>
| 7,716
|
<p>I want to explicitly call a view from my controller.</p>
<p>Right now I have:</p>
<pre><code>def some_action
.. do something ...
respond_to do |format|
format.xml
end
end
</code></pre>
<p>... then it calls my some_action.xml.builder view. How can I call some other view? Is there a parameter in respond_to I'm missing?</p>
<p>Thanks,</p>
<p>JP</p>
|
<p>You could do something like the following using render:</p>
<pre><code>respond_to do |format|
format.html { render :template => "weblog/show" }
end
</code></pre>
|
<p>Use render</p>
<p><a href="http://api.rubyonrails.com/classes/ActionController/Base.html#M000474" rel="nofollow noreferrer">http://api.rubyonrails.com/classes/ActionController/Base.html#M000474</a></p>
| 34,299
|
<p>Do you attach the images? </p>
<p>Use absolute urls? </p>
<p>How do you best avoid getting flagged as spam? </p>
|
<p>One of the biggest causes, that I have found, for email to be flagged as spam is DNS. Make sure the domain / MX records from which you are sending the email actually resolve correctly back from the server used for sending.</p>
<p>As for images, you could attach them, but the most common way is to host them and use absolute urls. Primarily this is a bandwidth issue - you have to figure you're going to get an open rate of 10 - 15%: if you have to attach all the assets to every email, 85% of the bandwidth you'll use will be wasted.</p>
|
<p>Campaign Monitor is a great resources for html email:
<a href="http://www.campaignmonitor.com/resources/#building" rel="nofollow noreferrer">http://www.campaignmonitor.com/resources/#building</a></p>
<p>Also <a href="http://www.email-standards.org/" rel="nofollow noreferrer">http://www.email-standards.org/</a>, but seems down right now.</p>
| 6,631
|
<p>In postgis, is the <code>ST_GeomFromText</code> call very expensive? I ask mostly because I have a frequently called query that attempts to find the point that is nearest another point that matches some criteria, and which is also within a certain distance of that other point, and the way I currently wrote it, it's doing the same <code>ST_GeomFromText</code> twice:</p>
<pre><code> $findNearIDMatchStmt = $postconn->prepare(
"SELECT internalid " .
"FROM waypoint " .
"WHERE id = ? AND " .
" category = ? AND ".
" (b.category in (1, 3) OR type like ?) AND ".
" ST_DWithin(point, ST_GeomFromText(?," . SRID .
" ),". SMALL_EPSILON . ") " .
" ORDER BY ST_Distance(point, ST_GeomFromText(?,", SRID .
" )) " .
" LIMIT 1");
</code></pre>
<p>Is there a better way to re-write this?</p>
<p>Slightly OT: In the preview screen, all my underscores are being rendered as <code>& # 9 5 ;</code> - I hope that's not going to show up that way in the post.</p>
|
<p>Go to about:ubiquity in Firefox. Under the section "subscribed feeds" there should be an option to unsubscribe to command feeds you no longer desire.</p>
<p>Also, if you clear your entire browser history, it will delete all command feeds (this will be fixed by 0.2)</p>
|
<p>Check this out:
<a href="http://getsatisfaction.com/mozilla/topics/how_do_you_edit_delete_the_default_ubiquity_commands_verbs" rel="nofollow noreferrer">http://getsatisfaction.com/mozilla/topics/how_do_you_edit_delete_the_default_ubiquity_commands_verbs</a></p>
<p>Also, you can find a utility to reset your ubiquity to default in \extensions\ubiquity@labs.mozilla.com\chrome\content\reset.html
EDIT1: The above file does nothing, please ignore.</p>
<p>EDIT2 (answer?): You can use the ffx addon SQLite Manager to open the \ubiquity_ann.sqlite database and remove all rows for the command you want to delete (there will be several rows, but they are identified by the url the script came from and so easy to identify). When you restart firefox, the command will be gone.
(The code that populates the Commands page uses javascript to create an instance of UbiquitySetup object, and executes the method .createServices().commandSource which reads that SQLite database directly for a list of commands (returning an object or array of objects/commands to iterate through). This seems to delete the command itself, since it will no longer be found in ubiquity or the command list.)</p>
<p>Good luck.</p>
| 5,686
|
<p>A couple of the options are:</p>
<pre><code>$connection = {my db connection/object};
function PassedIn($connection) { ... }
function PassedByReference(&$connection) { ... }
function UsingGlobal() {
global $connection;
...
}
</code></pre>
<p>So, passed in, passed by reference, or using global. I'm thinking in functions that are only used within 1 project that will only have 1 database connection. If there are multiple connections, the definitely passed in or passed by reference.</p>
<p>I'm thining passed by reference is not needed when you are in PHP5 using an object, so then passed in or using global are the 2 possibilities.</p>
<p>The reason I'm asking is because I'm getting tired of always putting in $connection into my function parameters.</p>
|
<p>I use a Singleton ResourceManager class to handle stuff like DB connections and config settings through a whole app:</p>
<pre><code>class ResourceManager {
private static $DB;
private static $Config;
public static function get($resource, $options = false) {
if (property_exists('ResourceManager', $resource)) {
if (empty(self::$$resource)) {
self::_init_resource($resource, $options);
}
if (!empty(self::$$resource)) {
return self::$$resource;
}
}
return null;
}
private static function _init_resource($resource, $options = null) {
if ($resource == 'DB') {
$dsn = 'mysql:host=localhost';
$username = 'my_username';
$password = 'p4ssw0rd';
try {
self::$DB = new PDO($dsn, $username, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
} elseif (class_exists($resource) && property_exists('ResourceManager', $resource)) {
self::$$resource = new $resource($options);
}
}
}
</code></pre>
<p>And then in functions / objects / where ever:</p>
<pre><code>function doDBThingy() {
$db = ResourceManager::get('DB');
if ($db) {
$stmt = $db->prepare('SELECT * FROM `table`');
etc...
}
}
</code></pre>
<p>I use it to store messages, error messages and warnings, as well as global variables. There's an interesting question <a href="https://stackoverflow.com/questions/228164/on-design-patterns-when-to-use-the-singleton">here</a> on when to actually use this type of class.</p>
|
<pre><code>function usingFunc() {
$connection = getConnection();
...
}
function getConnection() {
static $connectionObject = null;
if ($connectionObject == null) {
$connectionObject = connectFoo("whatever","connection","method","you","choose");
}
return $connectionObject;
}
</code></pre>
<p>This way, the static $connectionObject is preserved between getConnection calls.</p>
| 28,286
|
<p>I have recently started printing with Polymaker's PolyMax PETG on my Ender 3 v2. I have not been able to get the layer adhesion anywhere near as strong as it should be. I would guess it is around 20-25 % of the strength in the XY direction. The parts snap easily along the layer lines under loads that PLA and nylon hold up to just fine.</p>
<p>Print settings:</p>
<ul>
<li>0.15 mm layers @ 35-20 mm/s</li>
<li>Hotend temp 245 °C</li>
<li>4 mm retraction @ 40 mm/s</li>
<li>combing on</li>
<li>jerk control on</li>
<li>no cooling</li>
</ul>
<p>I made sure to use a nickel-plated brass 0.4 mm nozzle. I have calibrated my E-steps and tried printing in an enclosure, but nothing seems to help with layer adhesion. I have made sure there is no debris getting on the filament as it comes out of the drybox and even tried taping around the heater block so there is absolutely no part cooling.</p>
<p>Any ideas as to what I could be doing wrong?</p>
|
<p>I had this problem with my Ender 3 until I changed to a different extruder and now PETG never has adhesion problems. Even 100 % fan is fine at 245 °C. I think the stock hobbed gear just slips on PETG really badly, giving underextrusion. Go slow, increase the flow to compensate, and possibly increase temperature slightly more. Or buy a decent extruder.</p>
|
<p>The layer adhesion with Polymax PETG at 260 °C was great so I didn't go any higher.</p>
| 1,961
|
<p>For example, if I wanted to do it from the command line I would use "a.exe > out.txt". Is it possible to do something similar in Visual Studio when I debug (F5)?</p>
|
<p>In project properties:</p>
<ul>
<li>enter command line arguments "> out.txt"</li>
<li>Disable the hosting process</li>
</ul>
|
<p>Just checking, you are not looking for outputting within Visual Studio using stuff like</p>
<blockquote>
<p>System.Diagnostics.Debug.WriteLine("this goes into the Output window");</p>
</blockquote>
<p>right?</p>
| 42,347
|
<p>The follow code (running in ASP.Net 2.0) displays the contents of the requested URL <strong>twice</strong>. I only want it to display the contents of the requested URL once. I can't figure out what I'm doing wrong. The URL requested is returning XML and if I visit the URL directly, it works fine.</p>
<pre><code>HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
byte[] postDataBytes = Encoding.UTF8.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/xml";
request.ContentLength = postDataBytes.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(postDataBytes, 0, postDataBytes.Length);
requestStream.Close();
// get response and write to console
response = (HttpWebResponse) request.GetResponse();
StreamReader responseReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
try {
Response.Write(responseReader.ReadToEnd());
}
finally {
responseReader.Close();
}
response.Close();
</code></pre>
|
<p>There really aren't any true "private" attributes or methods in Python. One thing you can do is simply override the method you don't want in the subclass, and raise an exception:</p>
<pre><code>>>> class Foo( object ):
... def foo( self ):
... print 'FOO!'
...
>>> class Bar( Foo ):
... def foo( self ):
... raise AttributeError( "'Bar' object has no attribute 'foo'" )
...
>>> b = Bar()
>>> b.foo()
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
File "<interactive input>", line 3, in foo
AttributeError: 'Bar' object has no attribute 'foo'
</code></pre>
|
<p>This is the cleanest way I know to do it.</p>
<p>Override the methods and have each of the overridden methods call your disabledmethods() method. Like this:</p>
<pre><code>class Deck(list):
...
@staticmethod
def disabledmethods():
raise Exception('Function Disabled')
def pop(self): Deck.disabledmethods()
def sort(self): Deck.disabledmethods()
def reverse(self): Deck.disabledmethods()
def __setitem__(self, loc, val): Deck.disabledmethods()
</code></pre>
| 28,699
|
<p>I am running Ruby and MySQL on a Windows box.</p>
<p>I have some Ruby code that needs to connect to a MySQL database a perform a select. To connect to the database I need to provide the password among other things. </p>
<p>The Ruby code can display a prompt requesting the password, the user types in the password and hits the Enter key. What I need is for the password, as it is typed, to be displayed as a line of asterisks.</p>
<p>How can I get Ruby to display the typed password as a line of asterisks in the 'dos box'?</p>
|
<p>To answer my own question, and for the benefit of anyone else who would like to know, there is a Ruby gem called <a href="http://rubydoc.info/gems/highline/frames" rel="noreferrer">HighLine</a> that you need.</p>
<pre><code>require 'rubygems'
require 'highline/import'
def get_password(prompt="Enter Password")
ask(prompt) {|q| q.echo = false}
end
thePassword = get_password()
</code></pre>
|
<p>The fancy_gets gem has a password thing that works fine with jruby:</p>
<p><a href="https://github.com/lorint/fancy_gets" rel="nofollow">https://github.com/lorint/fancy_gets</a></p>
<p>Code ends up like:</p>
<pre><code>require 'fancy_gets'
include FancyGets
puts "Password:"
pwd = gets_password
# ...
</code></pre>
| 16,186
|
<p>I've got to do some significant development in a large, old, spaghetti-ridden ASP system. I've been away from ASP for a long time, focusing my energies on Rails development.</p>
<p>One basic step I've taken is to refactor pages into subs and functions with meaningful names, so that at least it's easy to understand @ the top of the file what's generally going on.</p>
<p>Is there a worthwhile MVC framework for ASP? Or a best practice at how to at least get business logic out of the views? (I remember doing a lot of includes back in the day -- is that still the way to do it?)</p>
<p>I'd love to get some unit testing going for business logic too, but maybe I'm asking too much?</p>
<h3>Update:</h3>
<p>There are over 200 ASP scripts in the project, some thousands of lines long ;) UGH!</p>
<p>We may opt for the "big rewrite" but until then, when I'm in changing a page, I want to spend a little extra time cleaning up the spaghetti.</p>
|
<p><strong>Assumptions</strong></p>
<p>The documentation for the Classic ASP system is rather light.</p>
<p>Management is not looking for a rewrite.</p>
<p>Since you have been doing ruby on rails, your (VB/C#) ASP.NET is passable at best.</p>
<p><strong>My experience</strong></p>
<p>I too inherited a classic ASP system that was slapped together willy-nilly by ex excel-vba types. There was a lot of this stuff <code><font size=3>crap</font></code> (and sometimes missing closing tags; Argggh!). Over the course of 2.5 years I added a security system, a common library, CSS+XHTML and was able to coerce the thing to validate xhtml1.1 (sans proper mime type, unfortunately) and built a fairly robust and ajaxy reporting system that's being used daily by 80 users. </p>
<p>I used jEdit, with cTags (as mentioned by <a href="https://stackoverflow.com/users/2639/jamting">jamting</a> above), and a bunch of other plugins.</p>
<p><strong>My Advice</strong>
Try to create a master include file from which to import all the stuff that's commonly used. Stuff like login/logout, database access, web services, javascript libs, etc.</p>
<p>Do use classes. They are ultra-primitive (no inheritance) but as jamting said, they can be convenient.</p>
<p>Indent the scripts properly.</p>
<p>Comment</p>
<p>Write an external architecture document. I personally use LyX, because it's brain-dead to produce a nicely formatted pdf, but you can use whatever you like. If you use a wiki, get the graphviz add-in installed and use it. It's super easy to make quick diagrams that can be easily modified.</p>
<p>Since I have no idea how substantial the enhancements need to be, I suggest having a good high-level to mid-level architecture document will be quite useful in planning the enhancements.</p>
<p>On the business logic unit tests, the only thing I found that works is setting up an xml-rpc listener in asp that imports the main library and exposes the functions (not subroutines though) in any of the main library's sub-includes, and then build, separately, a unit test system in a language with better support for the stuff that calls the ASP functions through xml-rpc. I use python, but I think Ruby should do the trick. (Does that make sense?). The cool thing is that the person writing the unit-test part of the software does not need to even look at the ASP code, as long as they have decent descriptions of the functions to call, so they can be someone beside you. </p>
<p>There is a project called <a href="http://aspunit.sourceforge.net/" rel="nofollow noreferrer">aspunit</a> at sourceforge but the last release was in 2004 and it's marked as inactive. Never used it but it's pure vbscript. A cursory look at the code tells me it looks like the authors knew what they were doing.</p>
<p>Finally, if you need help, I have some availability to do contract telecommuting work (maybe 8 hours/week max). Follow the link trail for contact info.</p>
<p>Good luck! HTH.</p>
|
<p>This is very old, but couldn't resist adding my two cents. If you must rewrite, and must continue to use classic ASP:</p>
<ul>
<li>use JScript! much more powerful, you get inheritance, and there some good side benefits like using the same methods for server-side validation as you use for client-side</li>
<li>you can absolutely do MVC - I wrote an MVC framework, and it was not that many lines of code</li>
<li>you can also generate your model classes automatically with a bit of work. I have some code for this that worked quite well</li>
<li>make sure you are doing parameterized queries, and always returning disconnected recordsets</li>
</ul>
| 4,369
|
<p>Okay, I've looked all over the internet for a good solution to get PHP and MySQL working on IIS7.0. It's nearly impossible, I've tried it so many times and given up in vain. Please please help by linking some great step-by-step tutorial to adding PHP and MySQL on IIS7.0 from scratch. PHP and MySQL are essential for installing any CMS.</p>
|
<p>Have you taken a look at this:</p>
<p><a href="http://learn.iis.net/page.aspx/246/using-fastcgi-to-host-php-applications-on-iis7/" rel="nofollow noreferrer">http://learn.iis.net/page.aspx/246/using-fastcgi-to-host-php-applications-on-iis7/</a></p>
<p>MySQL should be pretty straight forward.</p>
<p>Let us know what problems you're encountering...</p>
|
<p>It's supposed to work via FastCGI. But I haven't had great success (using Vista). I can get PHP to run, but it crashes after a page loads (FastCGI does). So I'm modding you up. I'd like to see a reliable answer myself.</p>
| 3,303
|
<p>I'd like my .exe to have access to a resource string with my svn version. I can type this in by hand, but I'd prefer an automated way to embed this at compile time. Is there any such capability in Visual Studio 2008?</p>
|
<p>I wanted a similar availability and found $Rev$ to be insufficient because it was only updated for a file if that file's revision was changed (which meant it would have to be edited and committed very time: not something I wanted to do.) Instead, I wanted something that was based on the repository's revision number.</p>
<p>For the project I'm working on now, I wrote a Perl script that runs <code>svnversion -n</code> from the top-most directory of my working copy and outputs the most recent revision information to a .h file (I actually compare it to a saved reversion in a non-versioned file in my working copy so that I'm not overwriting current revision information at every compile but whether you chose to do so is up to you.) This .h file (or a number of files if necessary, depending on your approach) is referenced both in my application code and in the resource files to get the information where I'd like it.</p>
<p>This script is run as a pre-build step so that everything is up-to-date before the build kicks off and the appropriate files are automatically rebuilt by your build tool.</p>
|
<p>You can get <a href="http://svnbook.red-bean.com/nightly/en/svn.advanced.props.special.keywords.html" rel="nofollow noreferrer">SVN to embed it for you</a>, if that will solve the problem. See the $Rev$ keyword on that page.</p>
| 18,237
|
<p>I've got an NSBrowser hooked up to an NSTreeController bound to an array of NSTreeNode objects. It's easy enough to get the text portion working by setting the Content and Content Value bindings to properly reference the tree controller, but how do I set the image for each cell using bindings?</p>
|
<p>The following worked well:</p>
<pre><code>NSData *d = (NSData *)CFHTTPMessageCopySerializedMessage(messageRef);
NSLog(@"%@",[[[NSString alloc] initWithBytes:[d bytes] length:[d length] encoding:NSUTF8StringEncoding] autorelease]);
</code></pre>
<p>Hope this is helpful to others.</p>
|
<p>The only reason why you should be getting an EXC_BAD_ACCESS when accessing the bytes is if the messageData is NULL (no HTTP body) and you're dereferencing it.</p>
<p>Point to remember: the HTTP body isn't the "raw request". It doesn't include the headers or the actual HTTP instruction (GET/POST/ETC). If you haven't actually set body content, it will be nil.</p>
<p>It is possible (but less likely) that your CFHTTPMessageRef value isn't properly initialized. Check this in the debugger by setting a breakpoint on your CFHTTPMessageCopyBody line, going to the Debugger Console window, setting the text input cursor to the last line in this window and typing "po messageRef". It should give you a CFTypeID message if validly initialized.</p>
| 45,365
|
<p>Port was filtered by ISP.</p>
<p>The problem is that HTTPS 443 port isn't accessible from internet, but it is open in our local network.
Our iSeries v5r4 is connected to inet via L2TP withot IPSec.
If no packet filters are active, nmap shows that ports 25, 80, 110 and even 10322 (WAS admin console) have state 'open' on internet IP address.
443 have state 'filtered'.</p>
<p>If I activate the following packet rules:</p>
<pre><code># -----------------------------------------------
# Statements to permit inbound HTTP over STATICIP
# -----------------------------------------------
INCLUDE FILE = /QIBM/UserData/OS400/TCPIP/PacketRules/Services.i3p
FILTER SET HTTP_INBOUND ACTION = PERMIT DIRECTION = OUTBOUND SRCADDR = * DSTADDR = * SERVICE = HTTP_80_FS JRN = OFF
FILTER SET HTTP_INBOUND ACTION = PERMIT DIRECTION = INBOUND SRCADDR = * DSTADDR = * SERVICE = HTTP_80_FC JRN = OFF
FILTER SET HTTP_INBOUND ACTION = PERMIT DIRECTION = OUTBOUND SRCADDR = * DSTADDR = * SERVICE = HTTP_443_FS JRN = OFF
FILTER SET HTTP_INBOUND ACTION = PERMIT DIRECTION = INBOUND SRCADDR = * DSTADDR = * SERVICE = HTTP_443_FC JRN = OFF
FILTER_INTERFACE INTERFACE = STATICIP SET = HTTP_INBOUND
# -----------------------------------------------
</code></pre>
<p>port 80 is 'open', 443 is 'filtered'.</p>
<p>How can I make it 'open'?</p>
|
<p>Some ISPs filter specific ports, like RoadRunner used to filter my webserver. It'd be odd since 80 isn't filtered, but it's a possibility. </p>
|
<p>You should configure your firewall to open and close TCP/IP ports.</p>
<p>Each firewall has a list of ports (or port ranges) that are open or closed for trafic. PLease consult you firewall/router documentation or consult your system administrator.</p>
| 40,457
|
<p>I am implementing a HttpRequestValidationException in my Application_Error Handler, and if possible, I want to display a custom message.</p>
<p>Now, I'm thinking about the StatusCode. In my current example, it sends a 200, which I think should not be done. I would like to send the (IMHO) more appropriate 400 Bad Request instead. However, at the same time, I would like to use Response.Write to enter a custom message. Firefox displays it properly, but IE7 gives me the Default unhelpful Internet Explorer Error Page.</p>
<p>On one side, I guess that Internet Explorer just assumes that everything <> 200 is simply not having any "good" content, and the <a href="https://www.rfc-editor.org/rfc/rfc2616#section-10.4.1" rel="nofollow noreferrer">RFC is not really clear</a> here.</p>
<p>So I just wonder, is sending a HTTP 200 for an Error Page caused by a HttpRequestValidationException good practice or not? Are there good alternatives?</p>
|
<p>An HTTP 200 Response Code does not indicate an error. It indicates that everything was OK. You should not use a 200 response code for an error. </p>
<p>Internet Explorer shows its "Friendly Errors" page if the response is less than 512 bytes. Here's more on this issue: <a href="http://weblogs.asp.net/scottgu/archive/2006/04/09/442332.aspx" rel="nofollow noreferrer">http://weblogs.asp.net/scottgu/archive/2006/04/09/442332.aspx</a>,</p>
|
<p>No, it's certainly not a good practice. 2XX status codes mean (among other things) that the <strong>request is valid</strong>. Which is just the contrary to raising a HttpRequestValidationException.</p>
<p>I don't know how to make IE behave correctly, sadly. A slightly better way than to send a 200 would be to redirect it to an error page, but still far from perfect.</p>
| 7,352
|
<p>What is the difference between a <strong>Snapshot</strong> Repository and <strong>Release</strong> Repository?</p>
<p>This is with reference to setting up Repositories (like Artifactory, Nexus etc)</p>
|
<p>Release repositories hold releases and Snapshot repositories hold snapshots. In maven a snapshot is defined as an artifact with a version ending in -SNAPSHOT. When deployed, the snapshot is turned into a timestamp. By definition, snapshots are mutable, releases are immutable. This is why Nexus makes you store them separately because usually you don't care if you lose snapshots, but you will care if you lose releases. It makes snapshot cleanup much easier to deal with that way.</p>
|
<p>SNAPSHOT here doesn't really mean ONE snapshot which is frozen and won't change, SNAPSHOT covers several snapshots whose modifications are not big enough for being represented by a new version number</p>
| 34,736
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.