id
int64 4
73.8M
| title
stringlengths 10
150
| body
stringlengths 17
50.8k
| accepted_answer_id
int64 7
73.8M
| answer_count
int64 1
182
| comment_count
int64 0
89
| community_owned_date
stringlengths 23
27
⌀ | creation_date
stringlengths 23
27
| favorite_count
int64 0
11.6k
⌀ | last_activity_date
stringlengths 23
27
| last_edit_date
stringlengths 23
27
⌀ | last_editor_display_name
stringlengths 2
29
⌀ | last_editor_user_id
int64 -1
20M
⌀ | owner_display_name
stringlengths 1
29
⌀ | owner_user_id
int64 1
20M
⌀ | parent_id
null | post_type_id
int64 1
1
| score
int64 -146
26.6k
| tags
stringlengths 1
125
| view_count
int64 122
11.6M
| answer_body
stringlengths 19
51k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2,226,227 |
Embedded C++ : to use exceptions or not?
|
<p>I realize this may be subjective, so will ask a concrete question, but first, background: </p>
<p>I have always been an embedded software engineer, but usually at Layer 3 or 2 of the OSI stack. I am not really a hardware guy. I have generally always done telecoms products, usually hand/cell-phones, which generally means something like an ARM 7 processor.</p>
<p>Now I find myself in a more generic embedded world, in a small start-up, where I might move to "not so powerful" processors (there's the subjective bit) - I cannot predict which.</p>
<p>I have read quite a bit about debate about exception handling in C++ in embedded systems and there is no clear cut answer. There are some small worries about portability and a few about run-time, but it mostly seems to come down to code size (or am i reading the wrong debates?).</p>
<p>Now I have to make the decision whether to use or forego exception handling - for the whole company, for ever (it's going into some very core s/w).</p>
<p>That may sound like "how long is a piece of string", but someone might reply "if your piece of string is an 8051, then don't. If, OTOH, it is ...".</p>
<p>Which way do I jump? Super-safe & lose a good feature, or exceptional code and maybe run into problems later?</p>
| 2,226,262 | 5 | 9 | null |
2010-02-09 01:46:56.687 UTC
| 18 |
2022-07-30 16:09:17.313 UTC
|
2010-02-09 01:50:33.97 UTC
| null | 59,111 | null | 192,910 | null | 1 | 48 |
c++|exception|exception-handling|embedded
| 17,414 |
<p>In terms of performance, my understanding is that exceptions actually reduce the size and increase the performance of the <em>normal</em> execution paths of code, but make the exceptional/error paths more expensive. (often a <em>lot</em> more expensive). </p>
<p>So if your only concern is performance, I would say don't worry about later. If today's CPU can handle it, then tomorrows will as well.</p>
<p><em>However</em>. In my opinion, exceptions are one of those features that require programmers to be smarter <em>all of the time</em> than programmers can be reasonably be expected to be. So I say - if you <em>can</em> stay away from exception based code. Stay away.</p>
<p>Have a look at Raymond Chen's <a href="https://devblogs.microsoft.com/oldnewthing/20050114-00/?p=36693" rel="noreferrer">Cleaner, more elegant, and harder to recognize</a>. He says it better than I could.</p>
|
1,641,580 |
What is data oriented design?
|
<p>I was reading <a href="http://gamesfromwithin.com/data-oriented-design" rel="noreferrer">this article</a>, and this guy goes on talking about how everyone can greatly benefit from mixing in data oriented design with OOP. He doesn't show any code samples, however.</p>
<p>I googled this and couldn't find any real information as to what this is, let alone any code samples. Is anyone familiar with this term and can provide an example? Is this maybe a different word for something else?</p>
| 2,021,868 | 6 | 3 | null |
2009-10-29 04:13:33.353 UTC
| 133 |
2022-08-22 20:16:00.36 UTC
|
2017-02-03 00:14:30.53 UTC
| null | 792,066 | null | 49,018 | null | 1 | 208 |
data-oriented-design
| 94,869 |
<p>First of all, don't confuse this with data-driven design.</p>
<p>My understanding of Data-Oriented Design is that it is about organizing your data for efficient processing. Especially with respect to cache misses etc. Data-Driven Design on the other hand is about letting data control a lot of the behavior of your program (described very well by <a href="https://stackoverflow.com/questions/1641580/what-is-data-oriented-design/1641615#1641615">Andrew Keith's answer</a>).</p>
<p>Say you have ball objects in your application with properties such as color, radius, bounciness, position, etc.</p>
<h3 id="object-oriented-approach-beay">Object Oriented Approach</h3>
<p>In OOP you would describe balls like this:</p>
<pre class="lang-cpp prettyprint-override"><code>class Ball {
Point position;
Color color;
double radius;
void draw();
};
</code></pre>
<p>And then you would create a collection of balls like this:</p>
<pre class="lang-cpp prettyprint-override"><code>vector<Ball> balls;
</code></pre>
<h3 id="data-oriented-approach-jbux">Data-Oriented Approach</h3>
<p>In Data Oriented Design, however, you are more likely to write the code like this:</p>
<pre class="lang-cpp prettyprint-override"><code>class Balls {
vector<Point> position;
vector<Color> color;
vector<double> radius;
void draw();
};
</code></pre>
<p>As you can see there is no single unit representing one Ball anymore. Ball objects only exist implicitly.</p>
<p>This can have many advantages, performance-wise. Usually, we want to do operations on many balls at the same time. The hardware usually wants large contiguous chunks of memory to operate efficiently.</p>
<p>Secondly, you might do operations that affect only part of the properties of a ball. For E.g. if you combine the colors of all the balls in various ways, then you want your cache to only contain color information. However, when all ball properties are stored in one unit you will pull in all the other properties of a ball as well. Even though you don't need them.</p>
<h3 id="cache-usage-example-k8ek">Cache Usage Example</h3>
<p>Say each ball takes up 64 bytes and a Point takes 4 bytes. A cache slot takes, say, 64 bytes as well. If I want to update the position of 10 balls, I have to pull in 10 x 64 = 640 bytes of memory into cache and get 10 cache misses. If however, I can work the positions of the balls as separate units, that will only take 4 x 10 = 40 bytes. That fits in one cache fetch. Thus we only get 1 cache miss to update all the 10 balls. These numbers are arbitrary - I assume a cache block is bigger.</p>
<p>But it illustrates how memory layout can have a severe effect on cache hits and thus performance. This will only increase in importance as the difference between CPU and RAM speed widens.</p>
<h3 id="how-to-layout-the-memory-qg4l">How to layout the memory</h3>
<p>In my ball example, I simplified the issue a lot, because usually for any normal app you will likely access multiple variables together. E.g. position and radius will probably be used together frequently. Then your structure should be:</p>
<pre class="lang-cpp prettyprint-override"><code>class Body {
Point position;
double radius;
};
class Balls {
vector<Body> bodies;
vector<Color> color;
void draw();
};
</code></pre>
<p>The reason you should do this is that if data used together are placed in separate arrays, there is a risk that they will compete for the same slots in the cache. Thus loading one will throw out the other.</p>
<p>So compared to Object-Oriented programming, the classes you end up making are not related to the entities in your mental model of the problem. Since data is lumped together based on data usage, you won't always have sensible names to give your classes in Data-Oriented Design.</p>
<h3 id="relation-to-relational-databases-bzcd">Relation to relational databases</h3>
<p>The thinking behind Data-Oriented Design is very similar to how you think about relational databases. Optimizing a relational database can also involve using the cache more efficiently, although in this case, the cache is not CPU cache but pages in memory. A good database designer will also likely split out infrequently accessed data into a separate table rather than creating a table with a huge number of columns where only a few of the columns are ever used. He might also choose to denormalize some of the tables so that data don't have to be accessed from multiple locations on disk. Just like with Data-Oriented Design these choices are made by looking at what the data access patterns are and where the performance bottleneck is.</p>
|
1,420,724 |
cobertura on maven multi module project
|
<p>I have a Maven project with 4 modules - 3 of them contain code and some tests (testing equals and hashcode of the classes) whereas the 4th module is for testing the 3 other modules.</p>
<p>Now I want to run the cobertura code coverage tool to get an overview which classes are well tested and which are not. I did some investigations on that topic and it seems that cobertura is not aware of generating the right code coverage percentages and line coverages, if some sources which are tested are located within other modules.</p>
<p>I have read over some links like <a href="http://seamframework.org/Documentation/SeamTestCoverageWithCobertura" rel="noreferrer" title="SeamTestCoverageWithCobertura">SeamTestCoverageWithCobertura</a> and <a href="http://foobar.lacoctelera.net/post/2008/09/15/uso-del-plugin-cobertura-dentro-un-proyecto-multi-modulo-en" rel="noreferrer">Using the plugin Coverage within a multi-module Maven 2</a> but there has to be an out of the box solution. Can anybody report some new directions on this topic? Or are there bether tools like cobertura? I've stumbled upon emma but this tool does not offer line coverage...</p>
| 18,282,605 | 7 | 0 | null |
2009-09-14 10:21:54.143 UTC
| 5 |
2019-05-30 12:45:22.493 UTC
|
2012-05-31 09:53:12.87 UTC
| null | 65,542 | null | 65,542 | null | 1 | 30 |
maven-2|cobertura
| 19,792 |
<p>As of version 2.6, there is an aggregate option that can be set to true in the parent pom:</p>
<pre><code><reporting>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
<version>2.6</version>
<configuration>
<outputDirectory>./target/tmpCobertura</outputDirectory>
<formats>
<format>html</format>
</formats>
<aggregate>true</aggregate>
</configuration>
</plugin>
</plugins>
</reporting>
</code></pre>
|
1,543,481 |
How to convert String object to Date object?
|
<p>How can I convert a String object to a Date object?</p>
<p>I think I need to do something like this:</p>
<pre><code>Date d=(some conversion ) "String "
</code></pre>
<p>Any help would be greatly appreciated.</p>
| 1,543,487 | 8 | 0 | null |
2009-10-09 12:28:27.737 UTC
| 2 |
2017-05-22 12:17:27.897 UTC
|
2011-11-08 05:41:54.867 UTC
|
user166390
| null | null | 96,180 | null | 1 | 10 |
java|date
| 38,576 |
<pre><code> SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
Date date = dateFormat.parse("1.1.2001");
</code></pre>
<p>For details refer to: <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html" rel="nofollow noreferrer">SimpleDateFormat documentation</a></p>
|
2,227,702 |
PHP mailer error
|
<p>I tried to use php mailer but errors as follows.</p>
<pre><code>SMTP -> FROM SERVER:
SMTP -> FROM SERVER:
SMTP -> ERROR: EHLO not accepted from server:
SMTP -> FROM SERVER:
SMTP -> ERROR: HELO not accepted from server:
SMTP -> ERROR: AUTH not accepted from server:
SMTP -> NOTICE: EOF caught while checking if connectedSMTP Error: Could not authenticate. Message could not be sent.
Mailer Error: SMTP Error: Could not authenticate.
</code></pre>
<p>and my code </p>
<pre><code> <?php
require("class.phpmailer.php")
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Host = "smtp.gmail.com";
$mail->Port = 465;
$mail->SMTPAuth = true;
$mail->SMTPDebug = 2;
$mail->Username = "admin@xxxxxxxxxxxx.in";
$mail->Password = "xxxxxxxx";
$mail->From = "admin@xxxxxxxxxxxx.in";
$mail->FromName = "Mailer";
$mail->AddAddress("xxxx@yahoo.co.in", "mine");
$mail->WordWrap = 50;
$mail->IsHTML(true);
$mail->Subject = "Here is the subject"
$mail->Body = "This is the HTML message body <b>in bold!</b>";
$mail->AltBody = "This is the body in plain text for non-HTML mail clients";
if(!$mail->Send()) {
echo "Message could not be sent. <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
echo "Message has been sent";
?>
</code></pre>
| 2,228,063 | 9 | 1 | null |
2010-02-09 08:32:21.67 UTC
| 3 |
2015-11-06 06:36:36.133 UTC
|
2013-04-20 05:37:34.987 UTC
| null | 166,476 | null | 166,476 | null | 1 | 10 |
php|phpmailer
| 58,283 |
<p>Some servers (especially shared hosting) will block you from using SSL with SMTP, I had the same problem once.</p>
<p>Either change host if you can, try using the default PHP mail() function or send through another mail server that does not require SSL e.g. port 25 not 465.</p>
<p>Something like <a href="http://www.authsmtp.com/" rel="noreferrer">AuthSMTP</a> would be your best bet for an alternate mail server.</p>
|
2,007,357 |
How to set DOM element as first child?
|
<p>I have an element E and I'm appending some elements to it. All of a sudden, I find out that the next element to append should be the first child of E. What's the trick, how to do it? Method unshift doesn't work because E is an object, not array.</p>
<p>Long way would be to iterate through E's children and to move'em key++, but I'm sure that there is a prettier way.</p>
| 2,007,473 | 9 | 1 | null |
2010-01-05 16:19:40.37 UTC
| 49 |
2022-06-17 04:17:03.923 UTC
|
2022-06-17 04:17:03.923 UTC
| null | 1,402,846 | null | 83,910 | null | 1 | 356 |
javascript|jquery|arrays|dom|element
| 298,474 |
<pre><code>var eElement; // some E DOM instance
var newFirstElement; //element which should be first in E
eElement.insertBefore(newFirstElement, eElement.firstChild);
</code></pre>
|
1,602,451 |
C++ valarray vs. vector
|
<p>I like vectors a lot. They're nifty and fast. But I know this thing called a valarray exists. Why would I use a valarray instead of a vector? I know valarrays have some syntactic sugar, but other than that, when are they useful?</p>
| 1,602,594 | 9 | 3 | null |
2009-10-21 17:53:31.017 UTC
| 57 |
2022-04-02 16:22:05.83 UTC
|
2016-07-22 19:21:39.55 UTC
| null | 2,411,320 | null | 72,631 | null | 1 | 180 |
c++|stl|stdvector|c++-standard-library|valarray
| 62,888 |
<p>Valarrays (value arrays) are intended to bring some of the speed of Fortran to C++. You wouldn't make a valarray of pointers so the compiler can make assumptions about the code and optimise it better. (The main reason that Fortran is so fast is that there is no pointer type so there can be no pointer aliasing.)</p>
<p>Valarrays also have classes which allow you to slice them up in a reasonably easy way although that part of the standard could use a bit more work. Resizing them is destructive and <s>they lack iterators</s> they have iterators since C++11.</p>
<p>So, if it's numbers you are working with and convenience isn't all that important use valarrays. Otherwise, vectors are just a lot more convenient.</p>
|
1,903,453 |
What disadvantages are there to the <button> tag?
|
<p>I started using a diagnostic css stylesheet, e.g.
<a href="http://snipplr.com/view/6770/css-diagnostics--highlight-deprecated-html-with-css--more/" rel="nofollow noreferrer">http://snipplr.com/view/6770/css-diagnostics--highlight-deprecated-html-with-css--more/</a></p>
<p>One of the suggested rules highlights input tags with the type submit, with the recommendation to use <code><button></code> as a more semantic solution. What are the advantages or disadvantages of <code><button></code> with type submit (such as with browser compatibility) that you have run across?</p>
<p>Just to be clear, I understand the spec of <code><button></code>, it has a defined start and end, it can contain various elements, whereas input is a singlet and can't contain stuff. What I want to know essentially is whether it's broken or not. I'd like to know how usable button is at the current time. The first answer below does seem to imply that it is broken for uses except outside of forms, unfortunately.</p>
<p><strong>Edit for 2015</strong></p>
<p>The landscape has changed! I have 6 more years experience of dealing with button now, and browsers have somewhat moved on from IE6 and IE7. So I'll add an answer that details what I found out and what I suggest.</p>
| 2,205,598 | 11 | 7 | null |
2009-12-14 20:59:07.383 UTC
| 15 |
2019-01-17 03:25:07.75 UTC
|
2018-12-30 03:22:55.527 UTC
| null | 69,993 | null | 69,993 | null | 1 | 64 |
css|button|tags|internet-explorer-7|diagnostics
| 33,516 |
<p>Answering from an ASP.NET perspective.</p>
<p>I was excited when I found <a href="https://stackoverflow.com/questions/187482/how-can-i-use-the-button-tag-with-asp-net">this question</a> and some code for a ModernButton control, which, in the end, is a <code><button></code> control.</p>
<p>So I started adding all sorts of these buttons, decorated with <code><img /></code> tags inside of them to make them stand out. And it all worked great... in Firefox, and Chrome.</p>
<p>Then I tried IE6 and got the "a potentially dangerous Request.Form value was detected", because IE6 submits the html inside of the button, which, in my case, has html tags in it. I don't want to disable the validateRequest flag, because I like this added bit of data validation.</p>
<p>So then I wrote some javascript to disable that button before the submit occurred. Worked great in a test page, with one button, but when I tried it out on a real page, that had other <code><button></code> tags, it blew up again. Because IE6 submits ALL of the buttons' html. So now I have all sorts of code to disable buttons before submit.</p>
<p>Same problems with IE7. IE8 thankfully has this fixed.</p>
<p>Yikes. I'd recommend not going down this road IF you are using ASP.NET.</p>
<p><strong>Update:</strong></p>
<p>I found a library out there that looks promising to fix this.</p>
<p>If you use the ie8.js script from this library: <a href="http://code.google.com/p/ie7-js/" rel="nofollow noreferrer" title="http://code.google.com/p/ie7-js/">http://code.google.com/p/ie7-js/</a></p>
<p>It might work out just fine. The IE8.js brings IE5-7 up to speed with IE8 with the button tag. It makes the submitted value the real value and only one button gets submitted.</p>
|
1,861,294 |
How to Calculate Execution Time of a Code Snippet in C++
|
<p>I have to compute execution time of a C++ code snippet in seconds. It must be working either on Windows or Unix machines.</p>
<p>I use code the following code to do this. (import before)</p>
<pre><code>clock_t startTime = clock();
// some code here
// to compute its execution duration in runtime
cout << double( clock() - startTime ) / (double)CLOCKS_PER_SEC<< " seconds." << endl;
</code></pre>
<p>However for small inputs or short statements such as a = a + 1, I get "0 seconds" result. I think it must be something like 0.0000001 seconds or something like that.</p>
<p>I remember that <code>System.nanoTime()</code> in Java works pretty well in this case. However I can't get same exact functionality from <code>clock()</code> function of C++.</p>
<p>Do you have a solution?</p>
| 1,861,337 | 18 | 7 | null |
2009-12-07 16:56:07.237 UTC
| 62 |
2021-03-09 20:37:39.58 UTC
|
2014-08-03 13:09:59.433 UTC
| null | 1,009,479 | null | 54,929 | null | 1 | 127 |
c++|benchmarking
| 175,753 |
<p>You can use this function I wrote. You call <code>GetTimeMs64()</code>, and it returns the number of milliseconds elapsed since the unix epoch using the system clock - the just like <code>time(NULL)</code>, except in milliseconds.</p>
<p>It works on both windows and linux; it is thread safe.</p>
<p>Note that the granularity is 15 ms on windows; on linux it is implementation dependent, but it usually 15 ms as well.</p>
<pre><code>#ifdef _WIN32
#include <Windows.h>
#else
#include <sys/time.h>
#include <ctime>
#endif
/* Remove if already defined */
typedef long long int64; typedef unsigned long long uint64;
/* Returns the amount of milliseconds elapsed since the UNIX epoch. Works on both
* windows and linux. */
uint64 GetTimeMs64()
{
#ifdef _WIN32
/* Windows */
FILETIME ft;
LARGE_INTEGER li;
/* Get the amount of 100 nano seconds intervals elapsed since January 1, 1601 (UTC) and copy it
* to a LARGE_INTEGER structure. */
GetSystemTimeAsFileTime(&ft);
li.LowPart = ft.dwLowDateTime;
li.HighPart = ft.dwHighDateTime;
uint64 ret = li.QuadPart;
ret -= 116444736000000000LL; /* Convert from file time to UNIX epoch time. */
ret /= 10000; /* From 100 nano seconds (10^-7) to 1 millisecond (10^-3) intervals */
return ret;
#else
/* Linux */
struct timeval tv;
gettimeofday(&tv, NULL);
uint64 ret = tv.tv_usec;
/* Convert from micro seconds (10^-6) to milliseconds (10^-3) */
ret /= 1000;
/* Adds the seconds (10^0) after converting them to milliseconds (10^-3) */
ret += (tv.tv_sec * 1000);
return ret;
#endif
}
</code></pre>
|
17,833,674 |
Sass ampersand, select immmediate parent?
|
<p>Is there a way in Sass to use the ampersand to select the immediate parent, rather than the parent selector of the entire group? For example:</p>
<pre><code>.wrapper{
background-color: $colour_nav_bg;
h1{
color: $colour_inactive;
.active &{
color: red;
}
}
}
</code></pre>
<p>compiles to:</p>
<pre><code>.wrapper h1{
color: grey;
}
.active .wrapper h1{
color: red
}
</code></pre>
<p>but what I actually want is:</p>
<pre><code>.wrapper .active h1{
color: red;
}
</code></pre>
<p>Is the only option to write the SCSS like so?</p>
<pre><code>.wrapper{
background-color: $colour_nav_bg;
h1{
color: $colour_inactive;
}
.active h1{
color: red;
}
}
</code></pre>
<p>The HTML looks like this:</p>
<pre><code><ul class="wrapper">
<li class="active">
<h1>blah</h1>
</li>
</ul>
</code></pre>
| 17,842,684 | 6 | 3 | null |
2013-07-24 12:11:11.643 UTC
| 6 |
2021-01-16 07:07:49.65 UTC
|
2013-07-24 13:47:37.477 UTC
| null | 1,026,353 | null | 963,903 | null | 1 | 39 |
sass
| 22,788 |
<p>As of this writing, there is no Sass selector for the direct parent instead of the root parent of an element. There is <code>&</code> which (as you know) selects the root parent. There are also <code>%</code> <a href="http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#placeholder_selectors_" rel="noreferrer">placeholder selectors</a> which hides a rule until it's been <a href="http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#extend" rel="noreferrer">extended</a>. </p>
<p>Sass is <a href="http://sass-lang.com/development.html" rel="noreferrer">open-sourced</a>, so you could contribute a new "direct parent" selector.</p>
|
6,642,599 |
How to add new button to order view in Magento admin panel?
|
<p>How to add custom button to order view page near "Back" and "Edit"?</p>
| 25,565,340 | 4 | 0 | null |
2011-07-10 17:21:13.647 UTC
| 9 |
2014-08-29 09:22:12.907 UTC
| null | null | null | null | 748,779 | null | 1 | 24 |
magento|button|admin
| 30,818 |
<p>Instead of core hacks or rewrites, just use an observer to add the button to the order:</p>
<pre><code><adminhtml>
<events>
<adminhtml_widget_container_html_before>
<observers>
<your_module>
<class>your_module/observer</class>
<type>singleton</type>
<method>adminhtmlWidgetContainerHtmlBefore</method>
</your_module>
</observers>
</adminhtml_widget_container_html_before>
</events>
</adminhtml>
</code></pre>
<p>Then just check in the observer if the type of the block matches the order view:</p>
<pre><code>public function adminhtmlWidgetContainerHtmlBefore($event)
{
$block = $event->getBlock();
if ($block instanceof Mage_Adminhtml_Block_Sales_Order_View) {
$message = Mage::helper('your_module')->__('Are you sure you want to do this?');
$block->addButton('do_something_crazy', array(
'label' => Mage::helper('your_module')->__('Export Order'),
'onclick' => "confirmSetLocation('{$message}', '{$block->getUrl('*/yourmodule/crazy')}')",
'class' => 'go'
));
}
}
</code></pre>
<p>The "getUrl" function of the block will automatically append the current order id to the controller call.</p>
|
11,172,956 |
How do I know if a specific twitter user is online or not?
|
<p>How do I know if a specific twitter user is currently online by writing programs? Is there any API or data field in the web page showing this information? Both browsing Twitter webpage and using Twitter app are considered "online".</p>
| 11,173,464 | 4 | 0 | null |
2012-06-23 21:01:59.57 UTC
| 1 |
2020-02-21 19:15:26.217 UTC
|
2012-06-23 21:11:39.627 UTC
| null | 1,042,359 | null | 1,042,359 | null | 1 | 2 |
twitter
| 72,253 |
<p>Although this information is not readily available, you can do a work around. Make use of Twitter's Streaming API: <a href="https://dev.twitter.com/docs/streaming-apis/streams/public" rel="nofollow">https://dev.twitter.com/docs/streaming-apis/streams/public</a> (have a read through this document).</p>
<p>You'll most likely be using the <code>POST Statuses/filter</code> functionality (read the doc here: <a href="https://dev.twitter.com/docs/api/1/post/statuses/filter" rel="nofollow">https://dev.twitter.com/docs/api/1/post/statuses/filter</a> ), which will give you a JSON object with tweets based on your filters.</p>
<p>Make use of the parameters you'll need to specify in the URL to filter the stream (have a look through this document to learn more about it: <a href="https://dev.twitter.com/docs/streaming-apis/parameters" rel="nofollow">https://dev.twitter.com/docs/streaming-apis/parameters</a> ), in your case it'll be the <code>follow</code> parameter. You basically specify the twitter ID of the user you want to follow. Here's a sample JSON result of the streaming API in action <a href="https://stream.twitter.com/1/statuses/filter.json?follow=25365536" rel="nofollow">https://stream.twitter.com/1/statuses/filter.json?follow=25365536</a> - this one in particular is following Kim Kardashian. Keep in mind that this will give you:</p>
<ul>
<li>Tweets created by the user.</li>
<li>Tweets which are retweeted by the user.</li>
<li>Replies to any Tweet created by the user.</li>
<li>Retweets of any Tweet created by the user.</li>
</ul>
<p>So in order to just stream the tweets of your desired user, you'll have to use a programming language of your choice to parse through the JSON object to find the <code>user</code> that actually sent the tweet (this is a little tricky, you'll have to look through the properties of the JSON object to figure it out). Once you narrow the streaming tweets to just the ones from the user though, you can then have an alert on when new tweets by this user stream and that will tell you if the user is online/using twitter at the moment.</p>
|
23,603,735 |
attempting to reference a deleted function
|
<p>I'm trying to learn about the fstream class and I'm having some trouble. I created a couple of txt files, one with a joke and the other with a punchline (joke.txt) and (punchline.txt) just for the sake of reading in and displaying content. I ask the user for the file name and if found it should open it up, clear the flags then read the content in. but I cant even test what it reads in because I'm currently getting errors regarding a deleted function but I don't know what that means</p>
<p>error 1:</p>
<pre><code>"IntelliSense: function "std::basic_ifstream<_Elem, _Traits>::basic_ifstream(const std::basic_ifstream<_Elem, _Traits>::_Myt &) [with _Elem=char, _Traits=std::char_traits<char>]" (declared at line 818 of "C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\fstream") cannot be referenced -- it is a deleted function
</code></pre>
<p>the second error is the exact same but for the 2nd function (displayLastLine())</p>
<p>and error 3:</p>
<pre><code>Error 1 error C2280: 'std::basic_ifstream<char,std::char_traits<char>>::basic_ifstream(const std::basic_ifstream<char,std::char_traits<char>> &)' : attempting to reference a deleted function
</code></pre>
<p>and here's my code:</p>
<pre><code>#include "stdafx.h"
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
void displayAllLines(ifstream joke);
void displayLastLine(ifstream punchline);
int main()
{
string fileName1, fileName2;
ifstream jokeFile, punchlineFile;
// Desribe the assigned project to the User
cout << "This program will print a joke and its punch line.\n\n";
cout << "Enter the name of the joke file (ex. joke.txt): ";
cin >> fileName1;
jokeFile.open(fileName1.data());
if (!jokeFile)
{
cout << " The file " << fileName1 << " could not be opened." << endl;
}
else
{
cout << "Enter name of punch line file (ex. punchline.txt): ";
cin >> fileName2;
punchlineFile.open(fileName2.data());
if (!punchlineFile)
{
cout << " The file " << fileName2 << " could not be opened." << endl;
jokeFile.close();
}
else
{
cout << endl << endl;
displayAllLines(jokeFile);
displayLastLine(punchlineFile);
cout << endl;
jokeFile.close();
punchlineFile.close();
}
}
// This prevents the Console Window from closing during debug mode
cin.ignore(cin.rdbuf()->in_avail());
cout << "\nPress only the 'Enter' key to exit program: ";
cin.get();
return 0;
}
void displayAllLines(ifstream joke)
{
joke.clear();
joke.seekg(0L, ios::beg);
string jokeString;
getline(joke, jokeString);
while (!joke.fail())
{
cout << jokeString << endl;
}
}
void displayLastLine(ifstream punchline)
{
punchline.clear();
punchline.seekg(0L, ios::end);
string punchString;
getline(punchline, punchString);
while (!punchline.fail())
{
cout << punchString << endl;
}
}
</code></pre>
| 23,603,847 | 1 | 3 | null |
2014-05-12 07:55:27.443 UTC
| 2 |
2019-07-14 10:01:58.2 UTC
|
2018-02-21 20:37:10.757 UTC
| null | 2,881,149 | null | 2,881,149 | null | 1 | 21 |
c++|string|function|fstream|ifstream
| 87,122 |
<p>You do call a deleted function, being the copy constructor of the class <code>std::ifstream</code>.</p>
<p>If you take a look <a href="http://www.cplusplus.com/reference/fstream/ifstream/ifstream/">at the reference</a> you notice, that the copy constructor is not allowed.</p>
<p>so instead of using:</p>
<pre><code>void displayAllLines(ifstream joke);
void displayLastLine(ifstream punchline);
</code></pre>
<p>you should work with calls by reference:</p>
<pre><code>void displayAllLines(ifstream& joke);
void displayLastLine(ifstream& punchline);
</code></pre>
<p>Using a reference will behave just like calling the method with a copy, but in fact you are operating on the original object instead of a new copy-constructed object. Keep that in mind for further use of the call by reference.</p>
|
18,338,908 |
Determining proxy server/port
|
<p>I apologize if this is a simplistic question, I am not familiar with this kind of thing.</p>
<p>I am trying to determine my proxy server ip and port number in order to use a google calendar syncing program. I downloaded the proxy.pac file using google chrome. The last line reads:</p>
<pre><code>return "PROXY proxyhost:1081";
</code></pre>
<p>I believe that means the port number is 1081, but for the proxy server, I was expecting something with the format "proxy.example.com" Any advice?</p>
<p>Thank you</p>
| 21,248,806 | 2 | 1 | null |
2013-08-20 15:20:53.667 UTC
| 1 |
2017-03-28 06:02:24.673 UTC
| null | null | null | null | 2,700,426 | null | 1 | 2 |
proxy|pac
| 38,209 |
<p>Are you using the Windows operating system? </p>
<p>You can press <kbd>Win</kbd>+<kbd>R</kbd>, input "cmd" in the run box, you will get the "command Prompt", then input the following command and press <kbd>Enter</kbd>.</p>
<p>command 1</p>
<pre><code>ipconfig /all | find /i "Dns Suffix"
</code></pre>
<p>it will show something like this.</p>
<blockquote>
<p>Primary Dns Suffix . . . . . . . : xxx.xxx.xxx</p>
</blockquote>
<p>command 2</p>
<pre><code>ping proxyhost
</code></pre>
<p>it will show something like this.</p>
<blockquote>
<p>Pinging proxyhost.xxx.xxx.xxx [yyy.yyy.yyy.yyy] with 32 bytes of data:
Reply from yyy.yyy.yyy.yyy: bytes=32 time=1ms TTL=60</p>
</blockquote>
<p>Then maybe "proxyhost.xxx.xxx.xxx" is what you want.</p>
|
15,812,191 |
Set JFrame to center of Screen in NetBeans
|
<p>I am developing a java swing desktop application
with NetBeans and I want to set the JFrame to the centre of the screen.</p>
<p>from the net I understand that I can use </p>
<pre><code>setLocationRelativeTo(null);
</code></pre>
<p>to set the frame to the centre
But i am unable to insert the code into the NetBeans IDE
because both the <code>frame.pack()</code>
and <code>frame.setVisible()</code> are generated codes of the NetBeans 7 IDE
and it will not permit any code insertion between the two methods.</p>
<p>I need to to obtain the following :</p>
<pre><code>frame.pack()
setLocationRelativeTo(null);
frame.setVisible()
</code></pre>
<p>Any suggestion on how to fix the problem?</p>
| 15,812,361 | 9 | 2 | null |
2013-04-04 13:09:55.607 UTC
| 2 |
2018-08-01 18:52:59.87 UTC
|
2018-08-01 18:52:59.87 UTC
| null | 9,991,599 | null | 2,213,170 | null | 1 | 9 |
java|swing|jframe|netbeans-7
| 80,662 |
<p>Is <code>setVisible()</code> on generated code? Strange. Anyway, you can right click the <code>JFrame</code> in <code>Navigator</code> and select <code>Properties</code>. Go to <code>Code</code> and select it to do nothing. Then manually insert you code after <code>initComponents()</code> in the <code>JFrame</code> constructor.</p>
|
19,284,012 |
Python SQLAlchemy Query: AttributeError: 'Connection' object has no attribute 'contextual_connect'
|
<p>I am trying to follow this <a href="http://docs.sqlalchemy.org/en/rel_0_8/orm/tutorial.html" rel="noreferrer">tutorial</a> from <code>SQLAlchemy</code> on how to create entries in and query a MYSQL database in python. When I try and query the database for the first time following along in their <a href="http://docs.sqlalchemy.org/ru/latest/orm/tutorial.html#adding-new-objects" rel="noreferrer">adding new objects</a> section to test whether an object has been added to the database (see large code block below), I get the following error: <code>AttributeError: 'Connection' object has no attribute 'contextual_connect'</code></p>
<p>I can query the database. For example, if I change the final line of code to <code>our_user = session.query(User).filter_by(name='ed')</code> it successfully returns a query object, but I cannot figure out how to get the object I entered into the database out of this query result. </p>
<p>Similarly, if I try to loop over the results as they suggest in their <a href="http://docs.sqlalchemy.org/ru/latest/orm/tutorial.html#querying" rel="noreferrer">querying</a>
section:</p>
<pre><code>for instance in session.query(User).order_by(User.id):
print instance.name, instance.fullname
</code></pre>
<p>I get the same error. How can I fix this particular error and are there any other tutorials on using MYSQL in Python with SQLAlchemy that you could point me to?</p>
<p>My code:</p>
<pre><code>import MySQLdb
from sqlalchemy import create_engine
db1 = MySQLdb.connect(host="127.0.0.1",
user="root",
passwd="****",
db="mydata")
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
from sqlalchemy import Column, Integer, String
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
fullname = Column(String)
password = Column(String)
def __init__(self, name, fullname, password):
self.name = name
self.fullname = fullname
self.password = password
def __repr__(self):
return "<User('%s','%s', '%s')>" % (self.name, self.fullname, self.password)
ed_user = User('ed', 'Ed Jones', 'edspassword')
from sqlalchemy.orm import sessionmaker
Session = sessionmaker()
Session.configure(bind=db1)
session = Session()
session.add(ed_user)
our_user = session.query(User).filter_by(name='ed').first()
</code></pre>
<p><strong>Update/Working Code:</strong></p>
<p>(1) Change to SQLAlchemy engine as discussed by codeape below.</p>
<p>(2) Remember to create the table: <code>Base.metadata.create_all(engine)</code></p>
<p>(3) Use the "foolproof" version of the <code>User</code> class from SQLAlchemy's tutorial. Note to SQLAlchemy, we (at least I) feel like a fool and would like you to use to always use the foolproof version in the main body of your tutorial and not as an aside that a busy reader might skip over.</p>
<p>All that yields working code:</p>
<pre><code>import MySQLdb
from sqlalchemy import create_engine
engine = create_engine("mysql://user:password@host/database")
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
from sqlalchemy import Column, Integer, String, Sequence
class User(Base):
__tablename__ = 'users'
id = Column(Integer, Sequence('user_id_seq'), primary_key=True)
name = Column(String(50))
fullname = Column(String(50))
password = Column(String(12))
def __init__(self, name, fullname, password):
self.name = name
self.fullname = fullname
self.password = password
def __repr__(self):
return "<User('%s','%s', '%s')>" % (self.name, self.fullname, self.password)
Base.metadata.create_all(engine)
ed_user = User('ed', 'Ed Jones', 'edspassword')
from sqlalchemy.orm import sessionmaker
Session = sessionmaker()
Session.configure(bind=engine)
session = Session()
session.add(ed_user)
our_user = session.query(User).filter_by(name='ed').first()
print(our_user is ed_user)
</code></pre>
| 19,284,123 | 2 | 2 | null |
2013-10-09 22:36:49.38 UTC
| 1 |
2019-03-11 12:37:56.54 UTC
|
2013-10-09 23:35:45.263 UTC
| null | 2,327,821 | null | 2,327,821 | null | 1 | 12 |
python|mysql|database|orm|sqlalchemy
| 38,811 |
<p>You must bind the session to a SQLAlchemy engine, not directly to a MySQLDb connection object.</p>
<pre><code>engine = create_engine("mysql://user:password@host/dbname")
Session.configure(bind=engine)
</code></pre>
<p>(You can remove your <code>db1</code> variable.)</p>
<p>From the tutorial:</p>
<blockquote>
<p>The return value of create_engine() is an instance of Engine, and it represents the core interface to the database, adapted through a dialect that handles the details of the database and DBAPI in use.</p>
</blockquote>
<p>See also <a href="https://docs.sqlalchemy.org/en/latest/orm/tutorial.html" rel="noreferrer">https://docs.sqlalchemy.org/en/latest/orm/tutorial.html</a></p>
|
40,167,038 |
Using Realm in React Native app with Redux
|
<p>I am about to undertake the development of a React Native app and am thoroughly convinced of the benefits of managing the app's state using Redux, however I'd like to make the app's data available whilst offline by using Realm for persistent storage. What I'm wondering is how Redux will play with Realm?</p>
<p>The app I'm developing will pull a large amount of JSON data via a RESTful API and then I'd like to persist this data to local storage - Realm seems to be an excellent option for this. What I'm unsure of however is how the Realm database will exist within the Redux store? Will it have to exist external to the store? Is using Realm within a Redux based app somehow a contradiction?</p>
<p>I've had a good search for articles describing the use of Realm, or other storage options (Asyncstorage or SQLite) for large datasets with Redux and could find little information.</p>
| 42,073,959 | 1 | 4 | null |
2016-10-21 01:38:19.28 UTC
| 3 |
2017-02-06 17:49:17.773 UTC
| null | null | null | null | 2,987,737 | null | 1 | 29 |
sqlite|react-native|redux|realm|asyncstorage
| 7,528 |
<p>The redux store is good when you have only react components dealing with the data. The store is a good way to maintain your application's state. For example, you do not need Realm to store the current login status or flags indicating whether the user has skipped login. The redux store wins the game here.</p>
<p>On the other hand, Realm is the best when you have to deal with complex queries or a large amount of data to be stored. The advantage of having Realm is that the data can be accessed within your react components as well as non-react components/classes easily. Realm gives you the advantage to monitor your data with the Realm Browser and build relationships between your models. Realm also wins the race if you have to do any offline sync. </p>
<p>Will it have to exist external to the store - <strong>Yes</strong>. </p>
<p>Is using Realm within a Redux based app somehow a contradiction - <strong>It depends upon what you are using the storage for.</strong></p>
|
27,474,764 |
Changing fontsize in python subplots
|
<p>I have made a phase plot of a bistable stable, with the nulclines on the main graph and have added a subplot with the trajectories overlaying it. However, no matter what I try, I cannot seem to get the x and y labels to increase in font size to 20.</p>
<p>Any help would be greatly appreciated.</p>
<p>Although there are similar questions, the answers to said queries don't seem to apply to this particular problem.</p>
<p>Thanks again!</p>
<pre><code>import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid.axislines import SubplotZero
from matplotlib import pylab
from pylab import linspace
from numpy import meshgrid
from numpy import hypot
a1 = 1.0 #(Rate constant)
g1 = 4.0 # Hill number for cdc2
b1 = 200.0 # Rate Constant
k1 = 30.0 #Michaelis Constant
v =1 #coefficient that reflects the strangth of the influence of Wee1 on Cdc2
a2 = 1.0# Rate Constant
g2 = 4.0 #Hill number for Wee1
b2 = 10.0 # Rate Constant
k2 = 1.0# Michaelis constant
# Function for calculating the phase plot
def Function(u,t=0,mu=.1):
x1 = u[0]
y1 = u[1]
dv = (a2* (1.0 - y1) - (b2 * y1 * x1**g2) /(k2 + (x1**g2))) # Model of Cdc2
dx = (a1* (1.0 - x1) - (b1 * x1 * ((v * y1)**g1)) / (k1 + ((v*y1) **g1))) # Model of Wee1
return (dx,dv)
t = linspace(0,1,1) #Return list from 0 to 1 in 25 intervals
u0 = np.array([1,1]) # Creates array for odeint function
mu = [1,10] #call mu for 2
for m in mu:#Get u (differentiation function )
u = odeint(Function,u0,t,args=(m,))
# ax.plot(u[0:,0],u[0:,1])
x = linspace(0,1,17) #Creates values for x
y = linspace(0,1,18)#Creates values for y to plot
x,y = meshgrid(x,y)# creates a grid of x by y
X,Y = Function([x,y])# Applies funciton to grid
M = (hypot(X,Y))# Get hypotenuse of X by Y
X,Y = X/M, Y/M# Calculate length(strength) of arrows
#Calculate Nulclines-----------------------------------------------------------
Nulclinevalues = np.arange(0, 1+0.001, 0.001)#Calulate values to set nulcineto
NulclineXX = []# set to an array
NulclineYY = []#set to an array
# Following 2 formulas show the calculation fo the nullclines
def calcnulclineyy(xx1):
oa2 = 1.0#RAte constant
og2 = 4.0 #Hill number for Wee1
ob2 = 10.0#Rate constant
ok2 = 1.0#Michaelis constant
YY = (oa2*((xx1)**og2) + ok2) / (oa2*((xx1**og2)+ok2)+(ob2*(xx1**og2)))
return YY
def calcnulclinexx(yy1):
oa1 = 1.0 #Rate constant
og1 = 4.0 # Hill number for cdc2
ob1 = 200.0 #Rate constant
ok1 = 30.0#Michaelis constant
ov = 1##coefficient that reflects the strength of the influence of Wee1 on Cdc2
og2 = 4.0 #Hill number for Wee1
XX = (oa1*(ok1+(ov*yy1)**og2)) / (oa1*(ok1+(ov*yy1)**og1)+ob1*(ov*yy1)**og1)
return XX
for YY in Nulclinevalues:
# print Y
NulclineXX.append(calcnulclinexx(YY))
for XX in Nulclinevalues:
#Print X
NulclineYY.append(calcnulclineyy(XX))
fig = plt.figure(figsize=(6,6)) # 6x6 image
ax = SubplotZero(fig,111,) #Plot arrows over figure
fig.add_subplot(ax) # Plot arrows over figure
# Plot both nulcines on same graph
plt.axis((0,1,0,1))
ax.set_title('v = 1',fontweight="bold", size=20) # Title
ax.set_ylabel('Active Wee1', fontsize = 20.0) # Y label
ax.set_xlabel('Active Cdc2-cyclin B', fontsize = 20) # X label
plt.plot (NulclineXX,Nulclinevalues, label = " Cdc2 nulcline",c = 'r', linewidth = '2')
plt.plot (Nulclinevalues,NulclineYY, label = "Wee1 nulcline",c = '#FF8C00', linewidth = '2')
ax.quiver(x,y,X,Y,M) # plot quiver plot on graph
ax.grid(True) # Show major ticks
ax.legend(handletextpad=0,loc='upper right') # Plot legend
plt.show() # Show plot
</code></pre>
| 27,475,301 | 2 | 2 | null |
2014-12-14 22:16:29.403 UTC
| 4 |
2014-12-14 23:34:03.517 UTC
|
2014-12-14 23:25:25.643 UTC
| null | 95,852 | null | 4,132,451 | null | 1 | 15 |
python|matplotlib|font-size|subplot
| 76,993 |
<p>Here are the changes I made to the last bit of your code:</p>
<pre><code>fig = plt.figure(figsize=(6,6)) # 6x6 image
ax = plt.gca() #SubplotZero(fig,111,) #Plot arrows over figure
#fig.add_subplot(ax) # Plot arrows over figure
# Plot both nulcines on same graph
plt.axis((0,1,0,1))
ax.set_title('v = 1',fontweight="bold", size=20) # Title
ax.set_ylabel('Active Wee1', fontsize = 20.0) # Y label
ax.set_xlabel('Active Cdc2-cyclin B', fontsize = 20) # X label
plt.plot (NulclineXX,Nulclinevalues, label = " Cdc2 nulcline",c = 'r')
plt.plot (Nulclinevalues,NulclineYY, label = "Wee1 nulcline",c = '#FF8C00')
ax.quiver(x,y,X,Y,M) # plot quiver plot on graph
ax.grid(True) # Show major ticks
ax.legend(handletextpad=0,loc='upper right') # Plot legend
plt.show() # Show plot
</code></pre>
<p>I changed the way you defined ax, and removed the call adding it to the figure. (I also did 2 other changes that you probably don't need - for some reason my installation didn't like the linewidth instructions when I tried to show it, so I took them out - it looks like something wrong with my installation).</p>
|
51,159,010 |
How do I upgrade "keras" from 1.2.0 to 2.0.0?
|
<p>I am running an image classifier but it keeps producing the error </p>
<blockquote>
<p>Keras loaded from keras Python module v1.2.0, however version 2.0.0 is required. Please update the keras Python package.
Error in py_call_impl(callable, dots$args, dots$keywords) :
TypeError: <strong>init</strong>() got an unexpected keyword argument 'data_format'</p>
</blockquote>
<p>I have tried to remove and re-install keras through using python command <strong><em>"pip install keras --upgrade"</em></strong> and also through R using "<strong><em>install.packages("keras")</em></strong>" but all in vain.</p>
<p>Some one please advise me on how to get past that. When I try to update keras from python, it gives;
<a href="https://i.stack.imgur.com/jPH2v.jpg" rel="nofollow noreferrer">enter image description here</a></p>
| 51,159,501 | 5 | 6 | null |
2018-07-03 16:10:39.17 UTC
| 0 |
2020-09-06 11:44:18.66 UTC
|
2018-07-03 16:24:22.053 UTC
| null | 10,027,843 | null | 10,027,843 | null | 1 | 3 |
python|r|keras
| 42,222 |
<p>Try to uninstall the keras first:</p>
<pre><code>pip uninstall keras
</code></pre>
<p>then install it :</p>
<pre><code>pip install keras==version_number
</code></pre>
|
4,985,917 |
cocos2d-iOS - Gesture recognisers
|
<p>Has anyone managed to get the gesture recognition working in cocos-2d?</p>
<p>I have read a post here that claimed to have achieved it, here: <a href="http://www.cocos2d-iphone.org/forum/topic/8929" rel="noreferrer">http://www.cocos2d-iphone.org/forum/topic/8929</a></p>
<p>I patched from the git hub here: <a href="https://github.com/xemus/cocos2d-GestureRecognizers/blob/master/README" rel="noreferrer">https://github.com/xemus/cocos2d-GestureRecognizers/blob/master/README</a></p>
<p>I made a subclass of <code>CCSprite</code> (which is a subclass of <code>CCNode</code>):</p>
<pre><code>-(id) initWithTexture:(CCTexture2D*)texture rect:(CGRect)rect {
if( (self=[super initWithTexture:texture rect:rect]) )
{
CCGestureRecognizer* recognizer;
recognizer = [CCGestureRecognizer
CCRecognizerWithRecognizerTargetAction:[[[UITapGestureRecognizer alloc]init] autorelease]
target:self
action:@selector(tap:node:)];
[self addGestureRecognizer:recognizer];
}
return self;
}
</code></pre>
<p>Delegate method:</p>
<pre><code>- (void) swipe:(UIGestureRecognizer*)recognizer node:(CCNode*)node
{
NSLog(@" I never get called :( ");
}
</code></pre>
<p>My tap event never gets called. </p>
<p>Has anyone got this working? How difficult is it to do gesture recognition manually for swipe detection?</p>
| 5,019,536 | 2 | 0 | null |
2011-02-13 18:13:06.61 UTC
| 12 |
2012-03-15 09:15:20.223 UTC
| null | null | null | null | 296,446 | null | 1 | 9 |
iphone|cocos2d-iphone
| 14,788 |
<p>You need to attach the gesture recognizer to something "up the chain". Don't attach them to the individual nodes; attach them to the UIView (i.e., [[CCDirector sharedDirector] openGLView]).</p>
<p>Here's what I did:</p>
<pre><code>- (UIPanGestureRecognizer *)watchForPan:(SEL)selector number:(int)tapsRequired {
UIPanGestureRecognizer *recognizer = [[[UIPanGestureRecognizer alloc] initWithTarget:self action:selector] autorelease];
recognizer.minimumNumberOfTouches = tapsRequired;
[[[CCDirector sharedDirector] openGLView] addGestureRecognizer:recognizer];
return recognizer;
}
- (void)unwatch:(UIGestureRecognizer *)gr {
[[[CCDirector sharedDirector] openGLView] removeGestureRecognizer:gr];
}
</code></pre>
<p>This particular code is used in a superclass for scene controllers, so the target for the selector is hard-coded to "self", but you could easily abstract that to a passed-in object. Also, you could extrapolate the above to easily create gesture recognizers for taps, pinches, etc.</p>
<p>In the subclass for the controller, then, I just do this:</p>
<pre><code>- (MyController *)init {
if ((self = [super init])) {
[self watchForPan:@selector(panning:) number:1];
}
return self;
}
- (void)panning:(UIPanGestureRecognizer *)recognizer {
CGPoint p;
CGPoint v;
switch( recognizer.state ) {
case UIGestureRecognizerStatePossible:
case UIGestureRecognizerStateBegan:
p = [recognizer locationInView:[CCDirector sharedDirector].openGLView];
(do something when the pan begins)
break;
case UIGestureRecognizerStateChanged:
p = [recognizer locationInView:[CCDirector sharedDirector].openGLView];
(do something while the pan is in progress)
break;
case UIGestureRecognizerStateFailed:
break;
case UIGestureRecognizerStateEnded:
case UIGestureRecognizerStateCancelled:
(do something when the pan ends)
(the below gets the velocity; good for letting player "fling" things)
v = [recognizer velocityInView:[CCDirector sharedDirector].openGLView];
break;
}
}
</code></pre>
|
5,292,184 |
Merging multiple branches with git
|
<p>I have 2 local branches called "develop" and "master"; they are similar. On my company's server there's one "main" repo (production) and several branches that were made by other developers:</p>
<pre>
$ git branch -a
* develop
master
remotes/origin/HEAD -> origin/master
remotes/origin/some-test
remotes/origin/feature1
remotes/origin/feature2
remotes/origin/master
</pre>
<p>How can I merge <code>remotes/origin/feature1</code> and <code>remotes/origin/feature2</code> into my local "master" branch, copy that all into "develop" and start working with actual code in my "develop" branch?</p>
| 5,292,267 | 2 | 0 | null |
2011-03-13 20:33:11.523 UTC
| 17 |
2018-10-03 02:04:40.563 UTC
|
2018-10-03 02:04:40.563 UTC
| null | 9,598,095 | null | 598,717 | null | 1 | 30 |
git|merge|rebase
| 55,698 |
<ol>
<li><code>git checkout master</code></li>
<li><code>git pull origin feature1 feature2</code></li>
<li><code>git checkout develop</code></li>
<li><code>git pull . master</code> (or maybe <code>git rebase ./master</code>)</li>
</ol>
<p>The first command changes your current branch to <code>master</code>.</p>
<p>The second command pulls in changes from the remote <code>feature1</code> and <code>feature2</code> branches. This is an "octopus" merge because it merges more than 2 branches. You could also do two normal merges if you prefer.</p>
<p>The third command switches you back to your <code>develop</code> branch.</p>
<p>The fourth command pulls the changes from local <code>master</code> to <code>develop</code>.</p>
<p>Hope that helps.</p>
<p>EDIT: Note that <code>git pull</code> will automatically do a <code>fetch</code> so you don't need to do it manually. It's pretty much equivalent to <code>git fetch</code> followed by <code>git merge</code>.</p>
|
1,088,752 |
How to programmatically discover mapped network drives on system and their server names?
|
<p>I'm trying to find out how to programmatically (I'm using C#) determine the name (or i.p.) of servers to which my workstation has current maps. In other words, at some point in Windows Explorer I mapped a network drive to a drive letter (or used "net use w: " to map it). I know how to get the network drives on the system:</p>
<pre><code>DriveInfo[] allDrives = DriveInfo.GetDrives();
foreach (DriveInfo d in allDrives)
{
if (d.IsReady && d.DriveType == DriveType.Network)
{
}
}
</code></pre>
<p>But the DriveInfo class does not have properties that tell me what server and shared folder the mapped drive is associated with. Is there somewhere else I should be looking? </p>
| 1,088,905 | 7 | 1 | null |
2009-07-06 19:14:03.78 UTC
| 16 |
2015-10-21 10:38:50.157 UTC
| null | null | null | null | 16,964 | null | 1 | 28 |
c#|.net|windows
| 51,974 |
<p>Have you tried to use WMI to do it?</p>
<pre><code>using System;
using System.Management;
using System.Windows.Forms;
public static void Main()
{
try
{
var searcher = new ManagementObjectSearcher(
"root\\CIMV2",
"SELECT * FROM Win32_MappedLogicalDisk");
foreach (ManagementObject queryObj in searcher.Get())
{
Console.WriteLine("-----------------------------------");
Console.WriteLine("Win32_MappedLogicalDisk instance");
Console.WriteLine("-----------------------------------");
Console.WriteLine("Access: {0}", queryObj["Access"]);
Console.WriteLine("Availability: {0}", queryObj["Availability"]);
Console.WriteLine("BlockSize: {0}", queryObj["BlockSize"]);
Console.WriteLine("Caption: {0}", queryObj["Caption"]);
Console.WriteLine("Compressed: {0}", queryObj["Compressed"]);
Console.WriteLine("ConfigManagerErrorCode: {0}", queryObj["ConfigManagerErrorCode"]);
Console.WriteLine("ConfigManagerUserConfig: {0}", queryObj["ConfigManagerUserConfig"]);
Console.WriteLine("CreationClassName: {0}", queryObj["CreationClassName"]);
Console.WriteLine("Description: {0}", queryObj["Description"]);
Console.WriteLine("DeviceID: {0}", queryObj["DeviceID"]);
Console.WriteLine("ErrorCleared: {0}", queryObj["ErrorCleared"]);
Console.WriteLine("ErrorDescription: {0}", queryObj["ErrorDescription"]);
Console.WriteLine("ErrorMethodology: {0}", queryObj["ErrorMethodology"]);
Console.WriteLine("FileSystem: {0}", queryObj["FileSystem"]);
Console.WriteLine("FreeSpace: {0}", queryObj["FreeSpace"]);
Console.WriteLine("InstallDate: {0}", queryObj["InstallDate"]);
Console.WriteLine("LastErrorCode: {0}", queryObj["LastErrorCode"]);
Console.WriteLine("MaximumComponentLength: {0}", queryObj["MaximumComponentLength"]);
Console.WriteLine("Name: {0}", queryObj["Name"]);
Console.WriteLine("NumberOfBlocks: {0}", queryObj["NumberOfBlocks"]);
Console.WriteLine("PNPDeviceID: {0}", queryObj["PNPDeviceID"]);
if(queryObj["PowerManagementCapabilities"] == null)
Console.WriteLine("PowerManagementCapabilities: {0}", queryObj["PowerManagementCapabilities"]);
else
{
UInt16[] arrPowerManagementCapabilities = (UInt16[])(queryObj["PowerManagementCapabilities"]);
foreach (UInt16 arrValue in arrPowerManagementCapabilities)
{
Console.WriteLine("PowerManagementCapabilities: {0}", arrValue);
}
}
Console.WriteLine("PowerManagementSupported: {0}", queryObj["PowerManagementSupported"]);
Console.WriteLine("ProviderName: {0}", queryObj["ProviderName"]);
Console.WriteLine("Purpose: {0}", queryObj["Purpose"]);
Console.WriteLine("QuotasDisabled: {0}", queryObj["QuotasDisabled"]);
Console.WriteLine("QuotasIncomplete: {0}", queryObj["QuotasIncomplete"]);
Console.WriteLine("QuotasRebuilding: {0}", queryObj["QuotasRebuilding"]);
Console.WriteLine("SessionID: {0}", queryObj["SessionID"]);
Console.WriteLine("Size: {0}", queryObj["Size"]);
Console.WriteLine("Status: {0}", queryObj["Status"]);
Console.WriteLine("StatusInfo: {0}", queryObj["StatusInfo"]);
Console.WriteLine("SupportsDiskQuotas: {0}", queryObj["SupportsDiskQuotas"]);
Console.WriteLine("SupportsFileBasedCompression: {0}", queryObj["SupportsFileBasedCompression"]);
Console.WriteLine("SystemCreationClassName: {0}", queryObj["SystemCreationClassName"]);
Console.WriteLine("SystemName: {0}", queryObj["SystemName"]);
Console.WriteLine("VolumeName: {0}", queryObj["VolumeName"]);
Console.WriteLine("VolumeSerialNumber: {0}", queryObj["VolumeSerialNumber"]);
}
}
catch (ManagementException ex)
{
MessageBox.Show("An error occurred while querying for WMI data: " + ex.Message);
}
}
</code></pre>
<p>to make it a little easier to get started download <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=2cc30a64-ea15-4661-8da4-55bbc145c30e&displaylang=en" rel="noreferrer">WMI Code Creater</a></p>
|
244,183 |
How to display a loading screen while site content loads
|
<p>I'm working on a site which contains a whole bunch of mp3s and images, and I'd like to display a loading gif while all the content loads. </p>
<p>I have no idea how to achieve this, but I do have the animated gif I want to use. </p>
<p>Any suggestions?</p>
| 244,190 | 7 | 0 | null |
2008-10-28 17:52:25.167 UTC
| 34 |
2017-04-14 15:27:29.497 UTC
|
2014-04-25 14:06:45.63 UTC
| null | 1,366,033 | null | 27,171 | null | 1 | 31 |
javascript|html|css|loading|pageload
| 175,507 |
<p>Typically sites that do this by loading content via ajax and listening to the <code>readystatechanged</code> event to update the DOM with a loading GIF or the content.</p>
<p>How are you currently loading your content?</p>
<p>The code would be similar to this:</p>
<pre class="lang-js prettyprint-override"><code>function load(url) {
// display loading image here...
document.getElementById('loadingImg').visible = true;
// request your data...
var req = new XMLHttpRequest();
req.open("POST", url, true);
req.onreadystatechange = function () {
if (req.readyState == 4 && req.status == 200) {
// content is loaded...hide the gif and display the content...
if (req.responseText) {
document.getElementById('content').innerHTML = req.responseText;
document.getElementById('loadingImg').visible = false;
}
}
};
request.send(vars);
}
</code></pre>
<p>There are plenty of 3rd party javascript libraries that may make your life easier, but the above is really all you need.</p>
|
475,804 |
SVG Word Wrap - Show stopper?
|
<p>For fun I am trying to see how far I can get at implementing an SVG browser client for a RIA I'm messing around with in my spare time.</p>
<p>But have hit what appears to be a HUGE stumbling block. There is no word wrap!!</p>
<p>Does anyone know of any work around (I'm thinking some kind of JavaScript or special tag I don't know)?</p>
<p>If not I'm either going to have to go the xhtml route and start sticking HTML elements in my SVG (ouch), or just come back again in ten years when SVG 1.2 is ready.</p>
| 475,813 | 8 | 0 | null |
2009-01-24 09:44:36.287 UTC
| 12 |
2022-02-26 20:54:50.097 UTC
|
2011-07-14 07:31:58.22 UTC
| null | 213,269 |
ChrisInCambo
| 37,196 | null | 1 | 24 |
svg|word-wrap
| 35,328 |
<p>Per this <a href="http://apike.ca/prog_svg_text.html" rel="noreferrer">document</a>, it appears that <b>tspan</b> can give the illusion of word wrap:</p>
<blockquote>
<p>The tspan tag is identical to the text tag but can be nested inside text tags and inside itself. Coupled with the 'dy' attribute this allows the illusion of word wrap in SVG 1.1. Note that 'dy' is relative to the last glyph (character) drawn.</p>
</blockquote>
|
647,074 |
How to make Linux C++ GUI apps
|
<p>What is the easiest way to make Linux C++ GUI apps? I'm using GNOME and ubuntu 8.10.</p>
| 647,075 | 8 | 0 | null |
2009-03-15 01:27:29.263 UTC
| 13 |
2011-02-09 15:25:54.423 UTC
|
2010-02-16 00:35:50.89 UTC
| null | 56,555 |
Lucas Aardvark
| 56,555 | null | 1 | 24 |
c++|user-interface|ubuntu|gnome
| 54,445 |
<p>I personally prefer QT as I prefer working with the signal/slots mechanism and just find it easy to develop applications quickly with it. Some of your other options would be wxWidgets and GTK+.</p>
|
942,251 |
In C/C++ why does the do while(expression); need a semi colon?
|
<p>My guess is it just made parsing easier, but I can't see exactly why.</p>
<p>So what does this have ...</p>
<pre><code>do
{
some stuff
}
while(test);
more stuff
</code></pre>
<p>that's better than ...</p>
<pre><code>do
{
some stuff
}
while(test)
more stuff
</code></pre>
| 942,261 | 8 | 0 | null |
2009-06-02 22:31:17.47 UTC
| 9 |
2014-06-09 18:42:37.347 UTC
| null | null | null | null | 53,120 | null | 1 | 34 |
c++|c|language-design
| 13,155 |
<p>Because you're ending the statement. A statement ends either with a block (delimited by curly braces), or with a semicolon. "do this while this" is a single statement, and can't end with a block (because it ends with the "while"), so it needs a semicolon just like any other statement.</p>
|
531,621 |
How to make a simple hyperlink in XAML?
|
<p>All I want to do is make a little hyperlink in XAML. I've tried everything. I give up.</p>
<p>What is the syntax for this?</p>
<pre><code><StackPanel Width="70" HorizontalAlignment="Center">
<Hyperlink Click="buttonClose_Click" Cursor="Hand"
Foreground="#555" Width="31" Margin="0 0 0 15"
HorizontalAlignment="Right">Close</Hyperlink>
<Button Width="60" Margin="0 0 0 3">Test 1</Button>
<Button Width="60" Margin="0 0 0 3">Test 2</Button>
<Button Width="60" Margin="0 0 0 3">Test 3</Button>
<Button Width="60" Margin="0 0 0 3">Test 4</Button>
</StackPanel>
</code></pre>
<p><em>Visual Studio Team: In Visual Studio 2010 I want Clippy to pop up and say "It seems you are trying to make a hyperlink" and tell me how to do it. Can't you do that with MEF? It would be retro cool, and these little "how do I do what I already know how to do in HTML" issues burn up so much time during the learning process with XAML.</em></p>
| 536,559 | 8 | 3 | null |
2009-02-10 09:22:02.43 UTC
| 13 |
2018-10-15 00:42:29.703 UTC
|
2009-02-10 09:28:13.867 UTC
|
Edward Tanguay
| 4,639 |
Edward Tanguay
| 4,639 | null | 1 | 58 |
wpf|xaml|hyperlink
| 89,943 |
<p>You can use a Button with a custom control template, the code below is a limited hyperlink style button (for example it only support textual hyperlinks) but maybe it'll point you in the right direction.</p>
<pre><code><Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Page.Resources>
<Style x:Key="Link" TargetType="Button">
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="HorizontalAlignment" Value="Center"/>
<Setter Property="Cursor" Value="Hand"/>
<Setter Property="Foreground" Value="Blue"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<TextBlock TextDecorations="Underline"
Text="{TemplateBinding Content}"
Background="{TemplateBinding Background}"/>
<ControlTemplate.Triggers>
<Trigger Property="IsPressed" Value="True">
<Setter Property="Foreground" Value="Red"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Page.Resources>
<Button Content="Click Me!" Style="{StaticResource Link}"/>
</Page>
</code></pre>
|
1,094,269 |
What's the purpose of git-mv?
|
<p>From what I understand, Git doesn't really need to track <em>file</em> rename/move/copy operations, so what's the real purpose
of <a href="https://git-scm.com/docs/git-mv" rel="noreferrer"><code>git mv</code></a>? The man page isn't specially descriptive...</p>
<p>Is it obsolete? Is it an internal command, not meant to be used by regular users?</p>
| 1,094,392 | 8 | 0 | null |
2009-07-07 19:22:06.633 UTC
| 70 |
2021-08-08 05:37:44.007 UTC
|
2021-01-16 09:23:47.557 UTC
| null | 1,108,305 | null | 21,239 | null | 1 | 373 |
git|git-mv
| 160,607 |
<pre><code>git mv oldname newname
</code></pre>
<p>is just shorthand for:</p>
<pre><code>mv oldname newname
git add newname
git rm oldname
</code></pre>
<p>i.e. it updates the index for both old and new paths automatically.</p>
|
37,030 |
How to best implement software updates on windows?
|
<p>I want to implement an "automatic update" system for a windows application.
Right now I'm semi-manually creating an <a href="http://connectedflow.com/appcasting/" rel="noreferrer">"appcast"</a> which my program checks, and notifies the user that a new version is available. (I'm using
<a href="http://nsis.sourceforge.net/Main_Page" rel="noreferrer">NSIS</a> for my installers).</p>
<p>Is there software that I can use that will handle the "automatic" part of the updates, perhaps similar to <a href="http://sparkle.andymatuschak.org/" rel="noreferrer">Sparkle</a> on the mac? Any issues/pitfalls that I should be aware of?</p>
| 37,035 | 9 | 0 | null |
2008-08-31 18:57:29.05 UTC
| 24 |
2013-03-04 06:38:45.843 UTC
| null | null | null |
dF
| 3,002 | null | 1 | 23 |
windows|installation
| 7,885 |
<p>There is no solution quite as smooth as Sparkle (that I know of).</p>
<p>If you need an easy means of deployment and updating applications, <a href="http://en.wikipedia.org/wiki/ClickOnce" rel="noreferrer">ClickOnce</a> is an option. Unfortunately, it's inflexible (e.g., no per-machine installation instead of per-user), opaque (you have very little influence and clarity and control over how its deployment actually works) and non-standard (the paths it stores the installed app in are unlike anything else on Windows).</p>
<p>Much closer to what you're asking would be <a href="http://wix.sourceforge.net/clickthrough.html" rel="noreferrer">ClickThrough</a>, a side project of <a href="http://wix.sourceforge.net/" rel="noreferrer">WiX</a>, but I'm not sure it's still in development (if it is, they should be clearer about that…) — and it would use MSI in any case, not NSIS.</p>
<p>You're likely best off rolling something on your own. I'd love to see a Sparkle-like project for Windows, but nobody seems to have given it a shot thus far.</p>
|
1,151,658 |
Python hashable dicts
|
<p>As an exercise, and mostly for my own amusement, I'm implementing a backtracking packrat parser. The inspiration for this is i'd like to have a better idea about how hygenic macros would work in an algol-like language (as apposed to the syntax free lisp dialects you normally find them in). Because of this, different passes through the input might see different grammars, so cached parse results are invalid, unless I also store the current version of the grammar along with the cached parse results. (<em>EDIT</em>: a consequence of this use of key-value collections is that they should be immutable, but I don't intend to expose the interface to allow them to be changed, so either mutable or immutable collections are fine)</p>
<p>The problem is that python dicts cannot appear as keys to other dicts. Even using a tuple (as I'd be doing anyways) doesn't help.</p>
<pre><code>>>> cache = {}
>>> rule = {"foo":"bar"}
>>> cache[(rule, "baz")] = "quux"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'
>>>
</code></pre>
<p>I guess it has to be tuples all the way down. Now the python standard library provides approximately what i'd need, <code>collections.namedtuple</code> has a very different syntax, but <em>can</em> be used as a key. continuing from above session:</p>
<pre><code>>>> from collections import namedtuple
>>> Rule = namedtuple("Rule",rule.keys())
>>> cache[(Rule(**rule), "baz")] = "quux"
>>> cache
{(Rule(foo='bar'), 'baz'): 'quux'}
</code></pre>
<p>Ok. But I have to make a class for each possible combination of keys in the rule I would want to use, which isn't so bad, because each parse rule knows exactly what parameters it uses, so that class can be defined at the same time as the function that parses the rule. </p>
<p>Edit: An additional problem with <code>namedtuple</code>s is that they are strictly positional. Two tuples that look like they should be different can in fact be the same: </p>
<pre><code>>>> you = namedtuple("foo",["bar","baz"])
>>> me = namedtuple("foo",["bar","quux"])
>>> you(bar=1,baz=2) == me(bar=1,quux=2)
True
>>> bob = namedtuple("foo",["baz","bar"])
>>> you(bar=1,baz=2) == bob(bar=1,baz=2)
False
</code></pre>
<p>tl'dr: How do I get <code>dict</code>s that can be used as keys to other <code>dict</code>s?</p>
<p>Having hacked a bit on the answers, here's the more complete solution I'm using. Note that this does a bit extra work to make the resulting dicts vaguely immutable for practical purposes. Of course it's still quite easy to hack around it by calling <code>dict.__setitem__(instance, key, value)</code> but we're all adults here.</p>
<pre><code>class hashdict(dict):
"""
hashable dict implementation, suitable for use as a key into
other dicts.
>>> h1 = hashdict({"apples": 1, "bananas":2})
>>> h2 = hashdict({"bananas": 3, "mangoes": 5})
>>> h1+h2
hashdict(apples=1, bananas=3, mangoes=5)
>>> d1 = {}
>>> d1[h1] = "salad"
>>> d1[h1]
'salad'
>>> d1[h2]
Traceback (most recent call last):
...
KeyError: hashdict(bananas=3, mangoes=5)
based on answers from
http://stackoverflow.com/questions/1151658/python-hashable-dicts
"""
def __key(self):
return tuple(sorted(self.items()))
def __repr__(self):
return "{0}({1})".format(self.__class__.__name__,
", ".join("{0}={1}".format(
str(i[0]),repr(i[1])) for i in self.__key()))
def __hash__(self):
return hash(self.__key())
def __setitem__(self, key, value):
raise TypeError("{0} does not support item assignment"
.format(self.__class__.__name__))
def __delitem__(self, key):
raise TypeError("{0} does not support item assignment"
.format(self.__class__.__name__))
def clear(self):
raise TypeError("{0} does not support item assignment"
.format(self.__class__.__name__))
def pop(self, *args, **kwargs):
raise TypeError("{0} does not support item assignment"
.format(self.__class__.__name__))
def popitem(self, *args, **kwargs):
raise TypeError("{0} does not support item assignment"
.format(self.__class__.__name__))
def setdefault(self, *args, **kwargs):
raise TypeError("{0} does not support item assignment"
.format(self.__class__.__name__))
def update(self, *args, **kwargs):
raise TypeError("{0} does not support item assignment"
.format(self.__class__.__name__))
# update is not ok because it mutates the object
# __add__ is ok because it creates a new object
# while the new object is under construction, it's ok to mutate it
def __add__(self, right):
result = hashdict(self)
dict.update(result, right)
return result
if __name__ == "__main__":
import doctest
doctest.testmod()
</code></pre>
| 1,151,705 | 9 | 2 |
2009-07-21 00:08:46.513 UTC
|
2009-07-20 04:04:30.27 UTC
| 51 |
2015-04-16 12:37:02.353 UTC
|
2015-04-13 10:47:03.087 UTC
| null | 336,527 | null | 65,696 | null | 1 | 115 |
python
| 82,569 |
<p>Here is the easy way to make a hashable dictionary. Just remember not to mutate them after embedding in another dictionary for obvious reasons.</p>
<pre><code>class hashabledict(dict):
def __hash__(self):
return hash(tuple(sorted(self.items())))
</code></pre>
|
154,185 |
What is object marshalling?
|
<p>I have heard this concept used frequently, but I don't have a really good grasp of what it is.</p>
| 154,201 | 10 | 1 | null |
2008-09-30 17:49:10.907 UTC
| 18 |
2021-02-19 11:23:56.45 UTC
|
2013-01-08 14:47:16.297 UTC
|
Rich B
| 527,702 |
Brian G
| 3,208 | null | 1 | 64 |
marshalling|terminology|glossary
| 32,941 |
<p>Converting an object in memory into a format that can be written to disk, or sent over the wire, etc. </p>
<p><a href="http://en.wikipedia.org/wiki/Marshalling_(computer_science)" rel="noreferrer">Wikipedia's description</a>.</p>
|
779,016 |
Is it possible to specify a starting number for an ordered list?
|
<p>I have a ordered list where I would like the initial number to be 6. I found that this was <a href="http://www.w3schools.com/TAGS/tag_ol.asp" rel="noreferrer">supported</a> (now deprecated) in HTML 4.01. In this specification they say that you can specify the starting integer by using CSS. (instead of the <code>start</code> attribute)</p>
<p>How would you specify the starting number with CSS?</p>
| 779,052 | 10 | 1 | null |
2009-04-22 20:19:52.717 UTC
| 13 |
2022-02-16 21:34:50.167 UTC
|
2015-06-30 10:08:51.88 UTC
| null | 502,381 | null | 72,113 | null | 1 | 134 |
html|css|html-lists
| 111,566 |
<p>If you need the functionality to start an ordered list (OL) at a specific point, you'll have to specify your doctype as HTML 5; which is:</p>
<pre><code><!doctype html>
</code></pre>
<p>With that doctype, it is valid to set a <code>start</code> attribute on an ordered list. Such as:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><ol start="6">
<li>Lorem</li>
<li>Ipsum</li>
<li>Dolor</li>
</ol></code></pre>
</div>
</div>
</p>
|
227,545 |
How can I get "Copy to Output Directory" to work with Unit Tests?
|
<p>When I build a unit test project before the tests are executed the test output is copied to a TestResults folder and then the tests are executed. The issue I'm having is that not all the files in the Debug/bin directory are copied to the TestResults project.</p>
<p>How can I get a file that is copied to the Debug/bin directory to also be copied to the TestResults folder?</p>
| 227,713 | 11 | 0 | null |
2008-10-22 21:06:27.767 UTC
| 29 |
2018-10-27 19:38:14.503 UTC
|
2015-09-30 08:55:58.067 UTC
|
spoon16
| 411,718 |
spoon16
| 3,957 | null | 1 | 128 |
c#|.net|visual-studio-2008|unit-testing|mstest
| 73,886 |
<p>The standard way to do this is by specifying the <a href="http://msdn.microsoft.com/en-us/library/ms182473.aspx" rel="noreferrer" title="MSDN: Team System Test Deployment">deployment items</a> in the <em><code>.testrunconfig</code></em> file, which can be accessed via the <em>Edit Test Run Configurations</em> item in the Visual Studio <strong><em>Test</em></strong> menu or in the <em>Solution Items</em> folder. </p>
|
722,980 |
Is there a better Windows command-line shell?
|
<p>CMD.EXE is posing lots of problems for me. I have Cygwin installed and use bash regularly, and I also have the mingwin bash shell that comes with mSysGit, but sometimes I really do need to run things from the Windows shell.</p>
<p>Is there a replacement for the Windows shell that:</p>
<ul>
<li>has a persistent command-line history, available in my next session after I close a session? (as in bash HISTFILE)</li>
<li>remembers what directory I was just in so that I can toggle between two directories? (as in bash cd -)</li>
</ul>
<p>(Or is there a way to enable these features in CMD.EXE?)</p>
<p>I see some has asked about <a href="https://stackoverflow.com/questions/5724/better-windows-command-line-shells">a better windows shell before</a>, but they were asking about cut and paste which is lower in priority for me at this point. It's not the console that's killing me, it's the command-line interpreter.</p>
| 723,181 | 12 | 3 | null |
2009-04-06 20:06:11.977 UTC
| 15 |
2013-05-23 04:17:20.937 UTC
|
2017-05-23 12:33:18.493 UTC
| null | -1 | null | 18,103 | null | 1 | 33 |
windows|shell|cmd
| 30,722 |
<p>I've always liked 4NT (haven't used it for a while now).</p>
<p>It's an enhanced command interpreter for windows, and it's mostly backwards compatible (meaning you can run normal windows batchfiles). The only reason not to use it is that it doesn't ship with Windows like the default command.exe does.</p>
<p>Compared to the default windows commandline interpreter, it has better flow control mechanisms. All standard windows commandline tools are available, but with extra options and parameters.</p>
<p>Basically it's what CMD.exe should've been.</p>
<p><strong>Update</strong>: looks like it's not called 4NT anymore, but TakeCommand:
<a href="http://jpsoft.com/products.htm" rel="noreferrer">http://jpsoft.com/products.htm</a></p>
|
517,355 |
String formatting in Python
|
<p>I want to do something like <code>String.Format("[{0}, {1}, {2}]", 1, 2, 3)</code> which returns:</p>
<pre><code>[1, 2, 3]
</code></pre>
<p>How do I do this in Python?</p>
| 517,471 | 14 | 1 | null |
2009-02-05 18:53:29.103 UTC
| 11 |
2022-06-27 17:28:52.837 UTC
|
2022-06-27 17:15:39.127 UTC
|
Niyaz
| 8,172,439 |
Joan Venge
| 51,816 | null | 1 | 42 |
python|python-3.x|string|formatting|python-2.x
| 100,456 |
<p>The previous answers have used % formatting, which is being phased out in Python 3.0+. Assuming you're using Python 2.6+, a more future-proof formatting system is described here:</p>
<p><a href="http://docs.python.org/library/string.html#formatstrings" rel="noreferrer">http://docs.python.org/library/string.html#formatstrings</a></p>
<p>Although there are more advanced features as well, the simplest form ends up looking very close to what you wrote:</p>
<pre><code>>>> "[{0}, {1}, {2}]".format(1, 2, 3)
[1, 2, 3]
</code></pre>
|
472,000 |
Usage of __slots__?
|
<p>What is the purpose of <a href="https://docs.python.org/3/reference/datamodel.html#slots" rel="noreferrer"><code>__slots__</code></a> in Python — especially with respect to when I would want to use it, and when not?</p>
| 28,059,785 | 14 | 0 | null |
2009-01-23 05:37:23.087 UTC
| 513 |
2022-09-11 06:46:47.553 UTC
|
2019-05-02 11:23:24.527 UTC
|
Roger Pate
| 2,956,066 |
Jeb
| 31,830 | null | 1 | 1,104 |
python|oop|python-internals|slots
| 320,070 |
<blockquote>
<h1>In Python, what is the purpose of <code>__slots__</code> and what are the cases one should avoid this?</h1>
</blockquote>
<h2>TLDR:</h2>
<p>The special attribute <a href="https://docs.python.org/3/reference/datamodel.html#slots" rel="noreferrer"><code>__slots__</code></a> allows you to explicitly state which instance attributes you expect your object instances to have, with the expected results:</p>
<ol>
<li><strong>faster</strong> attribute access.</li>
<li><strong>space savings</strong> in memory.</li>
</ol>
<p>The space savings is from</p>
<ol>
<li>Storing value references in slots instead of <code>__dict__</code>.</li>
<li>Denying <a href="https://docs.python.org/3/library/stdtypes.html#object.__dict__" rel="noreferrer"><code>__dict__</code></a> and <a href="https://stackoverflow.com/questions/36787603/what-exactly-is-weakref-in-python"><code>__weakref__</code></a> creation if parent classes deny them and you declare <code>__slots__</code>.</li>
</ol>
<h3>Quick Caveats</h3>
<p>Small caveat, you should only declare a particular slot one time in an inheritance tree. For example:</p>
<pre><code>class Base:
__slots__ = 'foo', 'bar'
class Right(Base):
__slots__ = 'baz',
class Wrong(Base):
__slots__ = 'foo', 'bar', 'baz' # redundant foo and bar
</code></pre>
<p>Python doesn't object when you get this wrong (it probably should), problems might not otherwise manifest, but your objects will take up more space than they otherwise should. Python 3.8:</p>
<pre class="lang-py prettyprint-override"><code>>>> from sys import getsizeof
>>> getsizeof(Right()), getsizeof(Wrong())
(56, 72)
</code></pre>
<p>This is because the Base's slot descriptor has a slot separate from the Wrong's. This shouldn't usually come up, but it could:</p>
<pre class="lang-py prettyprint-override"><code>>>> w = Wrong()
>>> w.foo = 'foo'
>>> Base.foo.__get__(w)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: foo
>>> Wrong.foo.__get__(w)
'foo'
</code></pre>
<p>The biggest caveat is for multiple inheritance - multiple "parent classes with nonempty slots" cannot be combined.</p>
<p>To accommodate this restriction, follow best practices: Factor out all but one or all parents' abstraction which their concrete class respectively and your new concrete class collectively will inherit from - giving the abstraction(s) empty slots (just like abstract base classes in the standard library).</p>
<p>See section on multiple inheritance below for an example.</p>
<h3>Requirements:</h3>
<ul>
<li><p>To have attributes named in <code>__slots__</code> to actually be stored in slots instead of a <code>__dict__</code>, a class must inherit from <code>object</code> (automatic in Python 3, but must be explicit in Python 2).</p>
</li>
<li><p>To prevent the creation of a <code>__dict__</code>, you must inherit from <code>object</code> and all classes in the inheritance must declare <code>__slots__</code> and none of them can have a <code>'__dict__'</code> entry.</p>
</li>
</ul>
<p>There are a lot of details if you wish to keep reading.</p>
<h2>Why use <code>__slots__</code>: Faster attribute access.</h2>
<p>The creator of Python, Guido van Rossum, <a href="http://python-history.blogspot.com/2010/06/inside-story-on-new-style-classes.html" rel="noreferrer">states</a> that he actually created <code>__slots__</code> for faster attribute access.</p>
<p>It is trivial to demonstrate measurably significant faster access:</p>
<pre><code>import timeit
class Foo(object): __slots__ = 'foo',
class Bar(object): pass
slotted = Foo()
not_slotted = Bar()
def get_set_delete_fn(obj):
def get_set_delete():
obj.foo = 'foo'
obj.foo
del obj.foo
return get_set_delete
</code></pre>
<p>and</p>
<pre><code>>>> min(timeit.repeat(get_set_delete_fn(slotted)))
0.2846834529991611
>>> min(timeit.repeat(get_set_delete_fn(not_slotted)))
0.3664822799983085
</code></pre>
<p>The slotted access is almost 30% faster in Python 3.5 on Ubuntu.</p>
<pre><code>>>> 0.3664822799983085 / 0.2846834529991611
1.2873325658284342
</code></pre>
<p>In Python 2 on Windows I have measured it about 15% faster.</p>
<h2>Why use <code>__slots__</code>: Memory Savings</h2>
<p>Another purpose of <code>__slots__</code> is to reduce the space in memory that each object instance takes up.</p>
<p><a href="https://docs.python.org/3/reference/datamodel.html#slots" rel="noreferrer">My own contribution to the documentation clearly states the reasons behind this</a>:</p>
<blockquote>
<p>The space saved over using <code>__dict__</code> can be significant.</p>
</blockquote>
<p><a href="http://docs.sqlalchemy.org/en/rel_1_0/changelog/migration_10.html#significant-improvements-in-structural-memory-use" rel="noreferrer">SQLAlchemy attributes</a> a lot of memory savings to <code>__slots__</code>.</p>
<p>To verify this, using the Anaconda distribution of Python 2.7 on Ubuntu Linux, with <code>guppy.hpy</code> (aka heapy) and <code>sys.getsizeof</code>, the size of a class instance without <code>__slots__</code> declared, and nothing else, is 64 bytes. That does <em>not</em> include the <code>__dict__</code>. Thank you Python for lazy evaluation again, the <code>__dict__</code> is apparently not called into existence until it is referenced, but classes without data are usually useless. When called into existence, the <code>__dict__</code> attribute is a minimum of 280 bytes additionally.</p>
<p>In contrast, a class instance with <code>__slots__</code> declared to be <code>()</code> (no data) is only 16 bytes, and 56 total bytes with one item in slots, 64 with two.</p>
<p>For 64 bit Python, I illustrate the memory consumption in bytes in Python 2.7 and 3.6, for <code>__slots__</code> and <code>__dict__</code> (no slots defined) for each point where the dict grows in 3.6 (except for 0, 1, and 2 attributes):</p>
<pre><code> Python 2.7 Python 3.6
attrs __slots__ __dict__* __slots__ __dict__* | *(no slots defined)
none 16 56 + 272† 16 56 + 112† | †if __dict__ referenced
one 48 56 + 272 48 56 + 112
two 56 56 + 272 56 56 + 112
six 88 56 + 1040 88 56 + 152
11 128 56 + 1040 128 56 + 240
22 216 56 + 3344 216 56 + 408
43 384 56 + 3344 384 56 + 752
</code></pre>
<p>So, in spite of smaller dicts in Python 3, we see how nicely <code>__slots__</code> scale for instances to save us memory, and that is a major reason you would want to use <code>__slots__</code>.</p>
<p>Just for completeness of my notes, note that there is a one-time cost per slot in the class's namespace of 64 bytes in Python 2, and 72 bytes in Python 3, because slots use data descriptors like properties, called "members".</p>
<pre><code>>>> Foo.foo
<member 'foo' of 'Foo' objects>
>>> type(Foo.foo)
<class 'member_descriptor'>
>>> getsizeof(Foo.foo)
72
</code></pre>
<h2>Demonstration of <code>__slots__</code>:</h2>
<p>To deny the creation of a <code>__dict__</code>, you must subclass <code>object</code>. Everything subclasses <code>object</code> in Python 3, but in Python 2 you had to be explicit:</p>
<pre><code>class Base(object):
__slots__ = ()
</code></pre>
<p>now:</p>
<pre><code>>>> b = Base()
>>> b.a = 'a'
Traceback (most recent call last):
File "<pyshell#38>", line 1, in <module>
b.a = 'a'
AttributeError: 'Base' object has no attribute 'a'
</code></pre>
<p>Or subclass another class that defines <code>__slots__</code></p>
<pre><code>class Child(Base):
__slots__ = ('a',)
</code></pre>
<p>and now:</p>
<pre><code>c = Child()
c.a = 'a'
</code></pre>
<p>but:</p>
<pre><code>>>> c.b = 'b'
Traceback (most recent call last):
File "<pyshell#42>", line 1, in <module>
c.b = 'b'
AttributeError: 'Child' object has no attribute 'b'
</code></pre>
<p>To allow <code>__dict__</code> creation while subclassing slotted objects, just add <code>'__dict__'</code> to the <code>__slots__</code> (note that slots are ordered, and you shouldn't repeat slots that are already in parent classes):</p>
<pre><code>class SlottedWithDict(Child):
__slots__ = ('__dict__', 'b')
swd = SlottedWithDict()
swd.a = 'a'
swd.b = 'b'
swd.c = 'c'
</code></pre>
<p>and</p>
<pre><code>>>> swd.__dict__
{'c': 'c'}
</code></pre>
<p>Or you don't even need to declare <code>__slots__</code> in your subclass, and you will still use slots from the parents, but not restrict the creation of a <code>__dict__</code>:</p>
<pre><code>class NoSlots(Child): pass
ns = NoSlots()
ns.a = 'a'
ns.b = 'b'
</code></pre>
<p>And:</p>
<pre><code>>>> ns.__dict__
{'b': 'b'}
</code></pre>
<p>However, <code>__slots__</code> may cause problems for multiple inheritance:</p>
<pre><code>class BaseA(object):
__slots__ = ('a',)
class BaseB(object):
__slots__ = ('b',)
</code></pre>
<p>Because creating a child class from parents with both non-empty slots fails:</p>
<pre><code>>>> class Child(BaseA, BaseB): __slots__ = ()
Traceback (most recent call last):
File "<pyshell#68>", line 1, in <module>
class Child(BaseA, BaseB): __slots__ = ()
TypeError: Error when calling the metaclass bases
multiple bases have instance lay-out conflict
</code></pre>
<p>If you run into this problem, You <em>could</em> just remove <code>__slots__</code> from the parents, or if you have control of the parents, give them empty slots, or refactor to abstractions:</p>
<pre><code>from abc import ABC
class AbstractA(ABC):
__slots__ = ()
class BaseA(AbstractA):
__slots__ = ('a',)
class AbstractB(ABC):
__slots__ = ()
class BaseB(AbstractB):
__slots__ = ('b',)
class Child(AbstractA, AbstractB):
__slots__ = ('a', 'b')
c = Child() # no problem!
</code></pre>
<h3>Add <code>'__dict__'</code> to <code>__slots__</code> to get dynamic assignment:</h3>
<pre><code>class Foo(object):
__slots__ = 'bar', 'baz', '__dict__'
</code></pre>
<p>and now:</p>
<pre><code>>>> foo = Foo()
>>> foo.boink = 'boink'
</code></pre>
<p>So with <code>'__dict__'</code> in slots we lose some of the size benefits with the upside of having dynamic assignment and still having slots for the names we do expect.</p>
<p>When you inherit from an object that isn't slotted, you get the same sort of semantics when you use <code>__slots__</code> - names that are in <code>__slots__</code> point to slotted values, while any other values are put in the instance's <code>__dict__</code>.</p>
<p>Avoiding <code>__slots__</code> because you want to be able to add attributes on the fly is actually not a good reason - just add <code>"__dict__"</code> to your <code>__slots__</code> if this is required.</p>
<p>You can similarly add <code>__weakref__</code> to <code>__slots__</code> explicitly if you need that feature.</p>
<h3>Set to empty tuple when subclassing a namedtuple:</h3>
<p>The namedtuple builtin make immutable instances that are very lightweight (essentially, the size of tuples) but to get the benefits, you need to do it yourself if you subclass them:</p>
<pre><code>from collections import namedtuple
class MyNT(namedtuple('MyNT', 'bar baz')):
"""MyNT is an immutable and lightweight object"""
__slots__ = ()
</code></pre>
<p>usage:</p>
<pre><code>>>> nt = MyNT('bar', 'baz')
>>> nt.bar
'bar'
>>> nt.baz
'baz'
</code></pre>
<p>And trying to assign an unexpected attribute raises an <code>AttributeError</code> because we have prevented the creation of <code>__dict__</code>:</p>
<pre><code>>>> nt.quux = 'quux'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'MyNT' object has no attribute 'quux'
</code></pre>
<p>You <em>can</em> allow <code>__dict__</code> creation by leaving off <code>__slots__ = ()</code>, but you can't use non-empty <code>__slots__</code> with subtypes of tuple.</p>
<h2>Biggest Caveat: Multiple inheritance</h2>
<p>Even when non-empty slots are the same for multiple parents, they cannot be used together:</p>
<pre><code>class Foo(object):
__slots__ = 'foo', 'bar'
class Bar(object):
__slots__ = 'foo', 'bar' # alas, would work if empty, i.e. ()
>>> class Baz(Foo, Bar): pass
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Error when calling the metaclass bases
multiple bases have instance lay-out conflict
</code></pre>
<p>Using an empty <code>__slots__</code> in the parent seems to provide the most flexibility, <strong>allowing the child to choose to prevent or allow</strong> (by adding <code>'__dict__'</code> to get dynamic assignment, see section above) <strong>the creation of a <code>__dict__</code></strong>:</p>
<pre><code>class Foo(object): __slots__ = ()
class Bar(object): __slots__ = ()
class Baz(Foo, Bar): __slots__ = ('foo', 'bar')
b = Baz()
b.foo, b.bar = 'foo', 'bar'
</code></pre>
<p>You don't <em>have</em> to have slots - so if you add them, and remove them later, it shouldn't cause any problems.</p>
<p><strong>Going out on a limb here</strong>: If you're composing <a href="https://stackoverflow.com/questions/860245/mixin-vs-inheritance/27907511#27907511">mixins</a> or using <a href="https://stackoverflow.com/questions/372042/difference-between-abstract-class-and-interface-in-python/31439126#31439126">abstract base classes</a>, which aren't intended to be instantiated, an empty <code>__slots__</code> in those parents seems to be the best way to go in terms of flexibility for subclassers.</p>
<p>To demonstrate, first, let's create a class with code we'd like to use under multiple inheritance</p>
<pre><code>class AbstractBase:
__slots__ = ()
def __init__(self, a, b):
self.a = a
self.b = b
def __repr__(self):
return f'{type(self).__name__}({repr(self.a)}, {repr(self.b)})'
</code></pre>
<p>We could use the above directly by inheriting and declaring the expected slots:</p>
<pre><code>class Foo(AbstractBase):
__slots__ = 'a', 'b'
</code></pre>
<p>But we don't care about that, that's trivial single inheritance, we need another class we might also inherit from, maybe with a noisy attribute:</p>
<pre><code>class AbstractBaseC:
__slots__ = ()
@property
def c(self):
print('getting c!')
return self._c
@c.setter
def c(self, arg):
print('setting c!')
self._c = arg
</code></pre>
<p>Now if both bases had nonempty slots, we couldn't do the below. (In fact, if we wanted, we could have given <code>AbstractBase</code> nonempty slots a and b, and left them out of the below declaration - leaving them in would be wrong):</p>
<pre><code>class Concretion(AbstractBase, AbstractBaseC):
__slots__ = 'a b _c'.split()
</code></pre>
<p>And now we have functionality from both via multiple inheritance, and can still deny <code>__dict__</code> and <code>__weakref__</code> instantiation:</p>
<pre><code>>>> c = Concretion('a', 'b')
>>> c.c = c
setting c!
>>> c.c
getting c!
Concretion('a', 'b')
>>> c.d = 'd'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Concretion' object has no attribute 'd'
</code></pre>
<h2>Other cases to avoid slots:</h2>
<ul>
<li>Avoid them when you want to perform <code>__class__</code> assignment with another class that doesn't have them (and you can't add them) unless the slot layouts are identical. (I am very interested in learning who is doing this and why.)</li>
<li>Avoid them if you want to subclass variable length builtins like long, tuple, or str, and you want to add attributes to them.</li>
<li>Avoid them if you insist on providing default values via class attributes for instance variables.</li>
</ul>
<p>You may be able to tease out further caveats from the rest of the <code>__slots__</code> <a href="https://docs.python.org/3.7/reference/datamodel.html#slots" rel="noreferrer">documentation (the 3.7 dev docs are the most current)</a>, which I have made significant recent contributions to.</p>
<h2>Critiques of other answers</h2>
<p>The current top answers cite outdated information and are quite hand-wavy and miss the mark in some important ways.</p>
<h3>Do not "only use <code>__slots__</code> when instantiating lots of objects"</h3>
<p>I quote:</p>
<blockquote>
<p>"You would want to use <code>__slots__</code> if you are going to instantiate a lot (hundreds, thousands) of objects of the same class."</p>
</blockquote>
<p>Abstract Base Classes, for example, from the <code>collections</code> module, are not instantiated, yet <code>__slots__</code> are declared for them.</p>
<p>Why?</p>
<p>If a user wishes to deny <code>__dict__</code> or <code>__weakref__</code> creation, those things must not be available in the parent classes.</p>
<p><code>__slots__</code> contributes to reusability when creating interfaces or mixins.</p>
<p>It is true that many Python users aren't writing for reusability, but when you are, having the option to deny unnecessary space usage is valuable.</p>
<h3><code>__slots__</code> doesn't break pickling</h3>
<p>When pickling a slotted object, you may find it complains with a misleading <code>TypeError</code>:</p>
<pre><code>>>> pickle.loads(pickle.dumps(f))
TypeError: a class that defines __slots__ without defining __getstate__ cannot be pickled
</code></pre>
<p>This is actually incorrect. This message comes from the oldest protocol, which is the default. You can select the latest protocol with the <code>-1</code> argument. In Python 2.7 this would be <code>2</code> (which was introduced in 2.3), and in 3.6 it is <code>4</code>.</p>
<pre><code>>>> pickle.loads(pickle.dumps(f, -1))
<__main__.Foo object at 0x1129C770>
</code></pre>
<p>in Python 2.7:</p>
<pre><code>>>> pickle.loads(pickle.dumps(f, 2))
<__main__.Foo object at 0x1129C770>
</code></pre>
<p>in Python 3.6</p>
<pre><code>>>> pickle.loads(pickle.dumps(f, 4))
<__main__.Foo object at 0x1129C770>
</code></pre>
<p>So I would keep this in mind, as it is a solved problem.</p>
<h2>Critique of the (until Oct 2, 2016) accepted answer</h2>
<p>The first paragraph is half short explanation, half predictive. Here's the only part that actually answers the question</p>
<blockquote>
<p>The proper use of <code>__slots__</code> is to save space in objects. Instead of having a dynamic dict that allows adding attributes to objects at anytime, there is a static structure which does not allow additions after creation. This saves the overhead of one dict for every object that uses slots</p>
</blockquote>
<p>The second half is wishful thinking, and off the mark:</p>
<blockquote>
<p>While this is sometimes a useful optimization, it would be completely unnecessary if the Python interpreter was dynamic enough so that it would only require the dict when there actually were additions to the object.</p>
</blockquote>
<p>Python actually does something similar to this, only creating the <code>__dict__</code> when it is accessed, but creating lots of objects with no data is fairly ridiculous.</p>
<p>The second paragraph oversimplifies and misses actual reasons to avoid <code>__slots__</code>. The below is <em>not</em> a real reason to avoid slots (for <em>actual</em> reasons, see the rest of my answer above.):</p>
<blockquote>
<p>They change the behavior of the objects that have slots in a way that can be abused by control freaks and static typing weenies.</p>
</blockquote>
<p>It then goes on to discuss other ways of accomplishing that perverse goal with Python, not discussing anything to do with <code>__slots__</code>.</p>
<p>The third paragraph is more wishful thinking. Together it is mostly off-the-mark content that the answerer didn't even author and contributes to ammunition for critics of the site.</p>
<h1>Memory usage evidence</h1>
<p>Create some normal objects and slotted objects:</p>
<pre><code>>>> class Foo(object): pass
>>> class Bar(object): __slots__ = ()
</code></pre>
<p>Instantiate a million of them:</p>
<pre><code>>>> foos = [Foo() for f in xrange(1000000)]
>>> bars = [Bar() for b in xrange(1000000)]
</code></pre>
<p>Inspect with <code>guppy.hpy().heap()</code>:</p>
<pre><code>>>> guppy.hpy().heap()
Partition of a set of 2028259 objects. Total size = 99763360 bytes.
Index Count % Size % Cumulative % Kind (class / dict of class)
0 1000000 49 64000000 64 64000000 64 __main__.Foo
1 169 0 16281480 16 80281480 80 list
2 1000000 49 16000000 16 96281480 97 __main__.Bar
3 12284 1 987472 1 97268952 97 str
...
</code></pre>
<p>Access the regular objects and their <code>__dict__</code> and inspect again:</p>
<pre><code>>>> for f in foos:
... f.__dict__
>>> guppy.hpy().heap()
Partition of a set of 3028258 objects. Total size = 379763480 bytes.
Index Count % Size % Cumulative % Kind (class / dict of class)
0 1000000 33 280000000 74 280000000 74 dict of __main__.Foo
1 1000000 33 64000000 17 344000000 91 __main__.Foo
2 169 0 16281480 4 360281480 95 list
3 1000000 33 16000000 4 376281480 99 __main__.Bar
4 12284 0 987472 0 377268952 99 str
...
</code></pre>
<p>This is consistent with the history of Python, from <a href="https://www.python.org/download/releases/2.2.2/descrintro/" rel="noreferrer">Unifying types and classes in Python 2.2</a></p>
<blockquote>
<p>If you subclass a built-in type, extra space is automatically added to the instances to accomodate <code>__dict__</code> and <code>__weakrefs__</code>. (The <code>__dict__</code> is not initialized until you use it though, so you shouldn't worry about the space occupied by an empty dictionary for each instance you create.) If you don't need this extra space, you can add the phrase "<code>__slots__ = []</code>" to your class.</p>
</blockquote>
|
360,643 |
Is it a bad practice to have multiple classes in the same file?
|
<p>I used to have one class for one file. For example <em>car.cs</em> has the class <em>car</em>. But as I program more classes, I would like to add them to the same file. For example <em>car.cs</em> has the class <em>car</em> and the <em>door</em> class, etc.</p>
<p>My question is good for Java, C#, PHP or any other programming language. Should I try not having multiple classes in the same file or is it ok?</p>
| 360,656 | 15 | 0 | null |
2008-12-11 19:50:37.303 UTC
| 13 |
2018-02-03 23:16:24.55 UTC
|
2018-02-03 23:16:24.55 UTC
|
mdb
| 4,389,437 |
Pokus
| 21,386 | null | 1 | 89 |
file|class|oop|language-agnostic
| 54,064 |
<p>I think you should try to keep your code to 1 class per file.</p>
<p>I suggest this because it will be easier to find your class later. Also, it will work better with your source control system (if a file changes, then you know that a particular class has changed). </p>
<p>The only time I think it's correct to use more than one class per file is when you are using internal classes... but internal classes are inside another class, and thus can be left inside the same file. The inner classes roles are strongly related to the outer classes, so placing them in the same file is fine.</p>
|
1,309,728 |
Best way to do a PHP switch with multiple values per case?
|
<p>How would you do this PHP switch statement?</p>
<p>Also note that these are much smaller versions, the 1 I need to create will have a lot more values added to it.</p>
<p>Version 1: </p>
<pre><code>switch ($p) {
case 'home':
case '':
$current_home = 'current';
break;
case 'users.online':
case 'users.location':
case 'users.featured':
case 'users.new':
case 'users.browse':
case 'users.search':
case 'users.staff':
$current_users = 'current';
break;
case 'forum':
$current_forum = 'current';
break;
}
</code></pre>
<p>Version 2: </p>
<pre><code>switch ($p) {
case 'home':
$current_home = 'current';
break;
case 'users.online' || 'users.location' || 'users.featured' || 'users.browse' || 'users.search' || 'users.staff':
$current_users = 'current';
break;
case 'forum':
$current_forum = 'current';
break;
}
</code></pre>
<p><strong>UPDATE - Test Results</strong> </p>
<p>I ran some speed test on 10,000 iterations, </p>
<p>Time1: 0.0199389457703 // If statements<br>
Time2: 0.0389049446106 //switch statements<br>
Time3: 0.106977939606 // Arrays </p>
| 1,309,872 | 16 | 3 | null |
2009-08-21 01:52:38.023 UTC
| 24 |
2021-09-08 19:29:23.957 UTC
|
2012-02-06 15:39:07.25 UTC
| null | 143,030 | null | 143,030 | null | 1 | 76 |
php|switch-statement
| 213,479 |
<p>For any situation where you have an unknown string and you need to figure out which of a bunch of <em>other</em> strings it matches up to, the only solution which doesn't get slower as you add more items is to use an array, but have all the possible strings as keys. So your switch can be replaced with the following:</p>
<pre><code>// used for $current_home = 'current';
$group1 = array(
'home' => True,
);
// used for $current_users = 'current';
$group2 = array(
'users.online' => True,
'users.location' => True,
'users.featured' => True,
'users.new' => True,
'users.browse' => True,
'users.search' => True,
'users.staff' => True,
);
// used for $current_forum = 'current';
$group3 = array(
'forum' => True,
);
if(isset($group1[$p]))
$current_home = 'current';
else if(isset($group2[$p]))
$current_users = 'current';
else if(isset($group3[$p]))
$current_forum = 'current';
else
user_error("\$p is invalid", E_USER_ERROR);
</code></pre>
<p>This doesn't look as clean as a <code>switch()</code>, but it is the only <em>fast</em> solution which doesn't include writing a small library of functions and classes to keep it tidy. It is still very easy to add items to the arrays.</p>
|
424,800 |
What is the best way to get the minimum or maximum value from an Array of numbers?
|
<p>Let's say I have an Array of numbers: <code>[2,3,3,4,2,2,5,6,7,2]</code></p>
<p>What is the best way to find the minimum or maximum value in that Array?</p>
<p>Right now, to get the maximum, I am looping through the Array, and resetting a variable to the value if it is greater than the existing value:</p>
<pre><code>var myArray:Array /* of Number */ = [2,3,3,4,2,2,5,6,7,2];
var maxValue:Number = 0;
for each (var num:Number in myArray)
{
if (num > maxValue)
maxValue = num;
}
</code></pre>
<p>This just doesn't seem like the best performing way to do this (I try to avoid loops whenever possible).</p>
| 426,538 | 17 | 3 | null |
2009-01-08 15:57:19.57 UTC
| 20 |
2018-10-24 16:27:47.257 UTC
|
2012-11-24 08:39:07.193 UTC
|
Aryabhatta
| 184,572 |
Eric Belair
| 31,298 | null | 1 | 41 |
algorithm|actionscript-3|apache-flex|actionscript|complexity-theory
| 163,553 |
<p>The theoretical answers from everyone else are all neat, but let's be pragmatic. ActionScript provides the tools you need so that you don't even have to write a loop in this case!</p>
<p>First, note that <code>Math.min()</code> and <code>Math.max()</code> can take any number of arguments. Also, it's important to understand the <code>apply()</code> method available to <code>Function</code> objects. It allows you to pass arguments to the function using an <code>Array</code>. Let's take advantage of both:</p>
<pre><code>var myArray:Array = [2,3,3,4,2,2,5,6,7,2];
var maxValue:Number = Math.max.apply(null, myArray);
var minValue:Number = Math.min.apply(null, myArray);
</code></pre>
<p>Here's the best part: the "loop" is actually run using native code (inside Flash Player), so it's faster than searching for the minimum or maximum value using a pure ActionScript loop.</p>
|
191,364 |
Quick unix command to display specific lines in the middle of a file?
|
<p>Trying to debug an issue with a server and my only log file is a 20GB log file (with no timestamps even! Why do people use <code>System.out.println()</code> as logging? In production?!)</p>
<p>Using grep, I've found an area of the file that I'd like to take a look at, line 347340107.</p>
<p>Other than doing something like</p>
<pre><code>head -<$LINENUM + 10> filename | tail -20
</code></pre>
<p>... which would require <code>head</code> to read through the first 347 million lines of the log file, is there a quick and easy command that would dump lines 347340100 - 347340200 (for example) to the console?</p>
<p><strong>update</strong> I totally forgot that grep can print the context around a match ... this works well. Thanks!</p>
| 191,385 | 19 | 2 | null |
2008-10-10 13:51:18.32 UTC
| 88 |
2022-05-30 10:02:24.833 UTC
|
2016-04-27 09:11:46.14 UTC
|
matt b
| 7,028 |
matt b
| 4,249 | null | 1 | 240 |
linux|bash|unix|text
| 420,919 |
<p>with GNU-grep you could just say </p>
<pre>grep --context=10 ...</pre>
|
215,548 |
What's the hardest or most misunderstood aspect of LINQ?
|
<p>Background: Over the next month, I'll be giving three talks about or at least including <code>LINQ</code> in the context of <code>C#</code>. I'd like to know which topics are worth giving a fair amount of attention to, based on what people may find hard to understand, or what they may have a mistaken impression of. I won't be specifically talking about <code>LINQ</code> to <code>SQL</code> or the Entity Framework except as examples of how queries can be executed remotely using expression trees (and usually <code>IQueryable</code>).</p>
<p>So, what have you found hard about <code>LINQ</code>? What have you seen in terms of misunderstandings? Examples might be any of the following, but please don't limit yourself!</p>
<ul>
<li>How the <code>C#</code> compiler treats query expressions</li>
<li>Lambda expressions</li>
<li>Expression trees</li>
<li>Extension methods</li>
<li>Anonymous types</li>
<li><code>IQueryable</code></li>
<li>Deferred vs immediate execution</li>
<li>Streaming vs buffered execution (e.g. OrderBy is deferred but buffered)</li>
<li>Implicitly typed local variables</li>
<li>Reading complex generic signatures (e.g. <a href="http://msdn.microsoft.com/en-us/library/bb549267.aspx" rel="nofollow noreferrer">Enumerable.Join</a>)</li>
</ul>
| 215,562 | 42 | 11 |
2009-06-04 12:12:37.373 UTC
|
2008-10-18 20:47:40.003 UTC
| 261 |
2011-08-04 08:50:01.047 UTC
|
2009-06-27 13:50:26.3 UTC
|
John Sheehan
| 16,853 |
Jon Skeet
| 22,656 | null | 1 | 282 |
c#|linq|c#-3.0
| 50,490 |
<p>Delayed execution</p>
|
6,424,301 |
Using a SELECT statement within a WHERE clause
|
<pre><code>SELECT * FROM ScoresTable WHERE Score =
(SELECT MAX(Score) FROM ScoresTable AS st WHERE st.Date = ScoresTable.Date)
</code></pre>
<p>Is there a name to describe using a SELECT statement within a WHERE clause? Is this good/bad practice?</p>
<p>Would this be a better alternative?</p>
<pre><code>SELECT ScoresTable.*
FROM ScoresTable INNER JOIN
(SELECT Date, MAX(Score) AS MaxScore
FROM ScoresTable GROUP BY Date) SubQuery
ON ScoresTable.Date = SubQuery.Date
AND ScoresTable.Score = SubQuery.MaxScore
</code></pre>
<p>It is far less elegant, but appears to run more quickly than my previous version. I dislike it because it is not displayed very clearly in the GUI (and it needs to be understood by SQL beginners). I could split it into two separate queries, but then things begin to get cluttered...</p>
<p>N.B. I need more than just Date and Score (e.g. name)</p>
| 6,424,322 | 7 | 5 | null |
2011-06-21 11:09:12.063 UTC
| 3 |
2016-03-02 03:42:51.213 UTC
|
2011-06-21 12:51:15.937 UTC
| null | 808,261 | null | 808,261 | null | 1 | 14 |
sql|select|where-clause
| 118,025 |
<p>It's called correlated subquery. It has it's uses.</p>
|
6,687,580 |
Header changes as you scroll down (jQuery)
|
<p>TechCrunch recently redesigned their site and they have a sweet header that minifies into a thinner version of their branding as you scroll down.</p>
<p>You can see what I mean here: <a href="http://techcrunch.com/" rel="noreferrer">http://techcrunch.com/</a></p>
<p>How would I go about creating something like this? Is there a tutorial anywhere and if not, can one you kind souls give me some tips on where to start? :)</p>
| 6,687,664 | 7 | 0 | null |
2011-07-14 01:41:53.18 UTC
| 16 |
2014-09-12 14:42:15.513 UTC
| null | null | null | null | 843,750 | null | 1 | 20 |
jquery
| 40,798 |
<p>It's not too hard, it's just a simple <a href="http://api.jquery.com/scroll/"><code>.scroll()</code></a> event. <strike>I can't seem to do it in fiddle because of the way the panels are positioned</strike> <strong>Check EDIT!</strong>. But basically what you have is have a <code>div</code> on the top that is <code>position: absolute</code> so it's always on top, then use <code>.scroll()</code></p>
<pre><code>$("body").scroll( function() {
var top = $(this).scrollTop();
// if statement to do changes
});
</code></pre>
<p>The <a href="http://api.jquery.com/scrollTop/"><code>scrollTop()</code></a> method is used to determine how much the <code>body</code> has scrolled.</p>
<p>And depending on where you would like to change your header div, you can have your <code>if</code> statement do many things. In the case of the example you provided, it would be something like </p>
<pre><code>if ( top > 147 )
// add the TechCrunch div inside the header
else
// hide the TechCrunch div so that space is transparent and you can see the banner
</code></pre>
<p><strong>EDIT</strong> </p>
<p>Yay! I was able to make <a href="http://jsfiddle.net/KEjfe/">this fiddle</a> to demonstrate the example! :)</p>
<p>Good luck!</p>
|
41,370,560 |
In Javadocs, how should I write plural forms of singular Objects in <code> tags?
|
<p>I have a class named <code>Identity</code>. In my javadoc comments I am referencing it as a plural. I can think of two solutions: change the reference to <code><code>Identities</code></code> or <code><code>Identity</code></code>s. Neither of these feel correct, and I'm wondering if there's a better solution.</p>
<p>Here is an example for clarity:</p>
<pre><code>/**
* Returns an <code>IdentityBank</code> of <code>Identity</code>s with the given sex.
*/
</code></pre>
<p>or</p>
<pre><code>/**
* Returns an <code>IdentityBank</code> of <code>Identities</code> with the given sex.
*/
</code></pre>
| 41,370,725 | 5 | 1 | null |
2016-12-28 22:24:00.087 UTC
| 6 |
2020-06-10 09:27:06.267 UTC
|
2016-12-29 00:55:23.247 UTC
| null | 2,518,200 | null | 4,756,763 | null | 1 | 41 |
java|javadoc|grammar
| 2,724 |
<p>Use a "...(s)" style plural label, with a <a href="http://docs.oracle.com/javase/7/docs/technotes/tools/windows/javadoc.html#link" rel="noreferrer"><code>{@link}</code></a> to the class:</p>
<pre><code>/**
* Returns an {@link IdentityBank} of {@link Identity Identity(s)} with the given sex.
*/
</code></pre>
<p>This will render as:</p>
<blockquote>
<p>Returns an <a href="http://example.com/javadoc/com/example/myproject/mypackage/IdentityBank.html" rel="noreferrer"><code>IdentityBank</code></a> of <a href="http://example.com/javadoc/com/example/myproject/mypackage/Identity.html" rel="noreferrer"><code>Identity(s)</code></a> with the given sex.</p>
</blockquote>
<p>It's easy and more natural to read, and obvious and clear what you are saying.</p>
<p>You should be using <code>{@link}</code> anyway for classes. It takes care of <code><code></code> style formatting, <em>and</em> provides an HTML link to the actual class.</p>
<hr>
<p>You could code the "(s)" <em>after</em> the link, ie <code>{@link Identity}(s)</code>, meaning a completely conventional usage of <code>{@link}</code>, but there would be a font change mid-word:</p>
<blockquote>
<p>Returns an <a href="http://example.com/javadoc/com/example/myproject/mypackage/IdentityBank.html" rel="noreferrer"><code>IdentityBank</code></a> of <a href="http://example.com/javadoc/com/example/myproject/mypackage/Identity.html" rel="noreferrer"><code>Identity</code></a>(s) with the given sex.</p>
</blockquote>
<p>which IMHO reduces clarity and could cause confusion.</p>
|
15,884,309 |
PostgreSQL Full Text Search and Trigram Confusion
|
<p>I'm a little bit confused with the whole concept of PostgreSQL, full text search and Trigram. In my full text search queries, I'm using tsvectors, like so:</p>
<pre><code>SELECT * FROM articles
WHERE search_vector @@ plainto_tsquery('english', 'cat, bat, rat');
</code></pre>
<p>The problem is, this method doesn't account for misspelling. Then I started to read about <a href="http://www.postgresql.org/docs/current/interactive/pgtrgm.html">Trigram and <code>pg_trgm</code></a>: </p>
<p>Looking through other examples, it seems like trigram is used or vectors are used, but never both. So my questions are: Are they ever used together? If so, how? Does trigram replace full text? Are trigrams more accurate? And how are trigrams on performance?</p>
| 15,884,833 | 1 | 0 | null |
2013-04-08 16:30:33.377 UTC
| 12 |
2013-04-08 18:55:14.71 UTC
|
2013-04-08 18:55:14.71 UTC
| null | 939,860 | null | 456,850 | null | 1 | 46 |
postgresql|full-text-search|pattern-matching
| 9,142 |
<p>They serve very different purposes. </p>
<ul>
<li>Full Text Search is used to return documents that match a search query of stemmed words.</li>
<li>Trigrams give you a method for comparing two strings and determining how similar they look.</li>
</ul>
<p>Consider the following examples:</p>
<pre><code>SELECT 'cat' % 'cats'; --true
</code></pre>
<p>The above returns true because <code>'cat'</code> is quite similar to <code>'cats'</code> (as dictated by the pg_trgm limit).</p>
<pre><code>SELECT 'there is a cat with a dog' % 'cats'; --false
</code></pre>
<p>The above returns <code>false</code> because <code>%</code> is looking for similarily between the two entire strings, not looking for the word <code>cats</code> <em>within</em> the string.</p>
<pre><code>SELECT to_tsvector('there is a cat with a dog') @@ to_tsquery('cats'); --true
</code></pre>
<p>This returns <code>true</code> becauase tsvector transformed the string into a list of stemmed words and ignored a bunch of common words (stop words - like 'is' & 'a')... then searched for the stemmed version of <code>cats</code>.</p>
<p>It sounds like you want to use trigrams to <strong>auto-correct</strong> your <code>ts_query</code> but that is not really possible (not in any efficient way anyway). They do not really <em>know</em> a word is misspelt, just how similar it might be to another word. They <em>could</em> be used to search a table of words to try and find similar words, allowing you to implement a "did you mean..." type feature, but this word require maintaining a separate table containing all the words used in your <code>search</code> field.</p>
<p>If you have some commonly misspelt words/phrases that you want the text-index to match you might want to look at <a href="http://www.postgresql.org/docs/current/static/textsearch-dictionaries.html#TEXTSEARCH-SYNONYM-DICTIONARY">Synonym Dictorionaries</a></p>
|
35,402,862 |
This certificate has an invalid issuer : Keychain marks all certificates as "Invalid Issuer"
|
<p>Keychain shows all the certificates as Invalid in my keychain suddenly, as it working before 2 days and i also check in Developer portal and it shows valid there. It marks each and every certificate in Keychain as <strong>"This certificate has invalid issuer"</strong> . As message suggesting that it must be problem from issuer side and and our issuer is Apple. So how to fix it ?</p>
<p>This certificate has an invalid issuer</p>
<p>Here i posting image of keychain. I need quick help.</p>
<p><a href="https://i.stack.imgur.com/2QglP.png" rel="noreferrer"><img src="https://i.stack.imgur.com/2QglP.png" alt="enter image description here"></a></p>
| 35,403,096 | 1 | 5 | null |
2016-02-15 06:32:21.94 UTC
| 15 |
2016-08-10 20:05:03 UTC
|
2016-02-15 17:56:26.463 UTC
| null | 3,045,336 | null | 3,045,336 | null | 1 | 70 |
ios|xcode|certificate|ssl-certificate|keychain
| 47,350 |
<p>In Keychain access,
-> View -> Show Expired Certificates, then in your login keychain click on expired certificate and delete it. I also had the same expired certificate in my System keychain, so I deleted it from there too.</p>
<p>-> After deleting the expired cert from the login and System keychains,download certificate from below link and open with keychain.</p>
<p>Download <a href="https://developer.apple.com/certificationauthority/AppleWWDRCA.cer">https://developer.apple.com/certificationauthority/AppleWWDRCA.cer</a> and add it to Keychain access > certificates (which expires on 2023)</p>
|
22,856,635 |
How do I make a div link open in a new tab Javascript onClick="window.location
|
<p>I created a range of social media buttons which when the mouse hovers it switches to a different image (giving it a highlight effect). The images work as I want them to, however, I can't seem to figure out how to load the page into a new tab/screen. I need to implement the equivalent of . </p>
<p>Assuming I have to change something in the onClick.... ?</p>
<p>Here is code: </p>
<pre><code><div id="insidefooter">
<ul>
<li>
<div id="facebook" style="cursor:pointer;" onClick="window.location='https://www.facebook.com';"></div>
</li>
<li>
<div id="youtube" style="cursor:pointer;" onClick="window.location='https://www.youtube.com';"></div>
</li>
<li>
<div id="twitter" style="cursor:pointer;" onClick="window.location='https://twitter.com/';"></div>
</li>
</ul>
</div>
</code></pre>
<p>Here is CSS:</p>
<pre><code>#facebook {
height: 40px;
position: relative;
top: 0px;
left: 260px;
width: 40px;
background-image:url(/img/index/footer/facebook-button.jpg);
}
#facebook:hover {
height: 40px;
width: 40px;
background-image:url(/img/index/footer/facebook-button2.jpg);
top: 0;
left: 260px;
width: 40px;
position: relative;
}
#youtube {
height: 40px;
position: relative;
top: -62px;
left: 360px;
width: 40px;
background-image:url(/img/index/footer/youtube-button.jpg);
}
#youtube:hover {
height: 40px;
width: 40px;
background-image:url(/img/index/footer/youtube-button2.jpg);
top: -62px;
left: 360px;
width: 40px;
position: relative;
</code></pre>
<p>I left out some CSS code to make it simpler, but here is a demo <a href="http://fiddle.jshell.net/3Bsyd/2/" rel="noreferrer">http://fiddle.jshell.net/3Bsyd/2/</a></p>
<p>Thank you!</p>
| 22,856,728 | 2 | 3 | null |
2014-04-04 07:45:43.167 UTC
| 2 |
2019-08-21 07:44:48.027 UTC
| null | null | null | null | 3,249,472 | null | 1 | 14 |
javascript|html|css
| 47,560 |
<p><code>onclick="window.open('http://google.pl', '_blank');"</code></p>
|
13,503,840 |
What is the code to exit/ stop VBscript from running in the event of a condition not being met?
|
<p>I have looked on Google and the answer is not there! </p>
<p>First things first. WScript.Quit DOES NOT WORK! I have no idea what "WScript" is but it clearly has nothing to do with client side scripting for a web page. I have seen this "WScript" thing somewhere before and it just produces errors (maybe obsolete or something) so please do not suggest it...</p>
<p>Anyway... all I wish to do is completely stop the script in the event of a condition not being met. Obviously I don't want "Exit Sub" because the code would then carry on running if that sub is embedded!</p>
<p>I am aware of the "stop" command but I am under the impression that it is only used for debugging. </p>
<p>Hopefully a very simple question.</p>
<p>UPDATE and Conclusion: Before I close this subject I will just expand a little on what I was trying to do...</p>
<p>I had a number of main subs that were being started by a button click. In order to make it so that I did not have to edit each individual sub I embedded a universal sub within each one that did a preliminary check. </p>
<p>Part of that preliminary check was to stop the program in the case of an incorrect user input. If an error was detected I wanted to halt all progress from that point on. An "exit sub" would obviously just skip the rest of that preliminary sub and the main sub would carry on executing. </p>
<p>In the end it was just a case of writing in an error flag (that is checked in the main subs) or incorporating the error condition operation in each main procedure. In that way you exit the main sub and the problem is solved. </p>
<p>It was not laziness - I just wanted to reduce the amount of code. Thank you for the responses anyway. </p>
| 13,631,660 | 5 | 3 | null |
2012-11-21 23:40:14.79 UTC
| 2 |
2020-07-17 10:06:48.273 UTC
|
2012-11-22 21:04:16.4 UTC
| null | 1,778,482 | null | 1,778,482 | null | 1 | 8 |
vbscript
| 78,354 |
<p>You can use something like this:</p>
<pre><code>Sub MyFunc
----------
My Code
----------
End Sub
Function Main
On Error Resume Next
MyFunc
If Err.Number <> 0
Exit Function
End Function
</code></pre>
<p>It'll stop executing the code, the point it finds an exception or throws an error.</p>
|
13,617,843 |
"unary operator expected" error in Bash if condition
|
<p>This script is getting an error:</p>
<pre><code>elif [ $operation = "man" ]; then
if [ $aug1 = "add" ]; then # <- Line 75
echo "Man Page for: add"
echo ""
echo "Syntax: add [number 1] [number 2]"
echo ""
echo "Description:"
echo "Add two different numbers together."
echo ""
echo "Info:"
echo "Added in v1.0"
echo ""
elif [ -z $aug1 ]; then
echo "Please specify a command to read the man page."
else
echo "There is no manual page for that command."
fi
</code></pre>
<p>I get this error:</p>
<pre><code>calc_1.2: line 75: [: =: unary operator expected
</code></pre>
| 13,618,376 | 6 | 3 | null |
2012-11-29 02:22:47.243 UTC
| 69 |
2022-07-05 23:33:57.647 UTC
|
2021-05-14 16:52:43.633 UTC
| null | 3,474,146 | null | 1,832,837 | null | 1 | 314 |
bash|shell
| 523,486 |
<p>If you know you're always going to use Bash, it's much easier to always use the double bracket conditional compound command <code>[[ ... ]]</code>, instead of the POSIX-compatible single bracket version <code>[ ... ]</code>. Inside a <code>[[ ... ]]</code> compound, word-splitting and pathname expansion are not applied to words, so you can rely on</p>
<pre><code>if [[ $aug1 == "and" ]];
</code></pre>
<p>to compare the value of <code>$aug1</code> with the string <code>and</code>.</p>
<p>If you use <code>[ ... ]</code>, you always need to remember to double quote variables like this:</p>
<pre><code>if [ "$aug1" = "and" ];
</code></pre>
<p>If you don't quote the variable expansion and the variable is undefined or empty, it vanishes from the scene of the crime, leaving only</p>
<pre><code>if [ = "and" ];
</code></pre>
<p>which is not a valid syntax. (It would also fail with a different error message if <code>$aug1</code> included white space or shell metacharacters.)</p>
<p>The modern <code>[[</code> operator has lots of other nice features, including regular expression matching.</p>
|
13,242,414 |
Passing A List Of Objects Into An MVC Controller Method Using jQuery Ajax
|
<p>I'm trying to pass an array of objects into an MVC controller method using
jQuery's ajax() function. When I get into the PassThing() C# controller method,
the argument "things" is null. I've tried this using a type of List for
the argument, but that doesn't work either. What am I doing wrong?</p>
<pre><code><script type="text/javascript">
$(document).ready(function () {
var things = [
{ id: 1, color: 'yellow' },
{ id: 2, color: 'blue' },
{ id: 3, color: 'red' }
];
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Xhr/ThingController/PassThing',
data: JSON.stringify(things)
});
});
</script>
public class ThingController : Controller
{
public void PassThing(Thing[] things)
{
// do stuff with things here...
}
public class Thing
{
public int id { get; set; }
public string color { get; set; }
}
}
</code></pre>
| 13,255,459 | 16 | 4 | null |
2012-11-06 00:01:08.24 UTC
| 50 |
2022-06-28 11:00:05.743 UTC
|
2012-11-06 00:56:25.127 UTC
| null | 727,208 | null | 705,132 | null | 1 | 129 |
c#|asp.net-mvc|jquery
| 354,600 |
<p>Using NickW's suggestion, I was able to get this working using <code>things = JSON.stringify({ 'things': things });</code> Here is the complete code.</p>
<pre><code>$(document).ready(function () {
var things = [
{ id: 1, color: 'yellow' },
{ id: 2, color: 'blue' },
{ id: 3, color: 'red' }
];
things = JSON.stringify({ 'things': things });
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Home/PassThings',
data: things,
success: function () {
$('#result').html('"PassThings()" successfully called.');
},
failure: function (response) {
$('#result').html(response);
}
});
});
public void PassThings(List<Thing> things)
{
var t = things;
}
public class Thing
{
public int Id { get; set; }
public string Color { get; set; }
}
</code></pre>
<p>There are two things I learned from this:</p>
<ol>
<li><p>The contentType and dataType settings are absolutely necessary in the ajax() function. It won't work if they are missing. I found this out after much trial and error. </p></li>
<li><p>To pass in an array of objects to an MVC controller method, simply use the JSON.stringify({ 'things': things }) format.</p></li>
</ol>
<p>I hope this helps someone else!</p>
|
51,656,838 |
__attribute__((weak)) and static libraries
|
<p>I wanted to introduce a weak symbol into my code, however, I am unable to comprehend its behavior when *.a files are used. </p>
<p>This is my minimal example:</p>
<p><i>file a.h:</i></p>
<pre><code>void foo() __attribute__((weak));
</code></pre>
<p><i>file a.c:</i></p>
<pre><code>#include "a.h"
#include <stdio.h>
void foo() { printf("%s\n", __FILE__); }
</code></pre>
<p><i>file b.c:</i></p>
<pre><code>#include <stdio.h>
void foo() { printf("%s\n", __FILE__); }
</code></pre>
<p><i>file main.cpp:</i></p>
<pre><code>#include "a.h"
#include <stdio.h>
int main() { if (foo) foo(); else printf("no foo\n"); }
</code></pre>
<p>Now, depending if I use *.o files (<code>make -c a.c</code> and <code>make -c b.c</code>) or *.a files (<code>ar cr a.o</code> and <code>ar cr b.o</code>) the output is different:<p>
1) <code>g++ main.cpp a.o b.o</code> prints <i>b.c</i><br>
2) <code>g++ main.cpp b.o a.o</code> prints <i>b.c</i><br>
3) <code>g++ main.cpp a.a b.a</code> prints <i>no foo</i><br>
4) <code>g++ main.cpp b.a a.a</code> prints <i>no foo</i>
<p>
<i>1)</i>, <i>2)</i> work just fine but the output for <i>3)</i>, <i>4)</i> seems to be a little unexpected.
<p></p>
<p>I was desperately trying to make this example work with archives so I made few changes:</p>
<p><i>file a.h:</i></p>
<pre><code>void foo();
</code></pre>
<p><i>file a.c:</i></p>
<pre><code>#include "a.h"
#include <stdio.h>
void __attribute__((weak)) foo() { printf("%s\n", __FILE__); }
</code></pre>
<p>After this modification:
<p>
1) <code>g++ main.cpp a.a b.a</code> prints <i>a.c</i><br>
2) <code>g++ main.cpp b.a a.a</code> prints <i>b.c</i>
<p></p>
<p>So it works a bit better. After running <code>nm a.a</code> shows <code>W _Z3foov</code> so there is no violation of ODR. However, I don't know if this is a correct usage of <i>weak</i> attribute. According to gcc documentation:</p>
<blockquote>
<p>The weak attribute causes the <strong><em>declaration</em></strong> to be emitted as a weak symbol rather than a global. This is primarily useful in defining library functions which can be overridden in user code, though it can also be used with non-function declarations. Weak symbols are supported for ELF targets, and also for a.out targets when using the GNU assembler and linker. </p>
</blockquote>
<p>Yet I use <i>weak</i> attribute on the function definition not the declaration.</p>
<p>So the question is why <i>weak</i> doesn't work with *.a files? Is usage of <i>weak</i> attribute on a definition instead of a declaration correct? </p>
<p><strong>UPDATE</strong></p>
<p>It has dawned on me that <i>weak</i> attribute used with <em>foo()</em> method definition had no impact on the symbol resolution. Without the attribute final binary generates the same:
<p>
1) <code>g++ main.cpp a.a b.a</code> prints <i>a.c</i><br>
2) <code>g++ main.cpp b.a a.a</code> prints <i>b.c</i>
<p>
So simply the first definition of the symbol is used and this is consisten with default gcc behaviour. Even though <code>nm a.a</code> shows that a weak symbol was emitted, it doesn't seem to affect static linking. </p>
<p>Is it possible to use <i>weak</i> attribute with static linking at all?</p>
<p><strong>DESCRIPTION OF THE PROBLEM I WANT TO SOLVE</strong></p>
<p>I have a library that is used by >20 clients, let's call it library A. I also provide a library B which contains testing utils for A. Somehow I need to know that library A is used in testing mode, so the simplest solution seems to be replacing a symbol during linking with B (because clients are already linking with B).</p>
<p>I know there are cleaner solutions to this problem, however I absolutely can't impact clients' code or their build scripts (adding parameter that would indicate testing for A or some DEFINE for compilation is out of option). </p>
| 51,970,423 | 2 | 5 | null |
2018-08-02 15:04:30.633 UTC
| 15 |
2020-02-14 07:41:26.29 UTC
|
2018-08-17 09:59:12.853 UTC
| null | 9,702,768 | null | 9,702,768 | null | 1 | 22 |
c++|g++
| 28,764 |
<p>To explain what's going on here, let's talk first about your original source files, with</p>
<p><strong>a.h (1)</strong>:</p>
<pre><code>void foo() __attribute__((weak));
</code></pre>
<p>and:</p>
<p><strong>a.c (1)</strong>:</p>
<pre><code>#include "a.h"
#include <stdio.h>
void foo() { printf("%s\n", __FILE__); }
</code></pre>
<p>The mixture of <code>.c</code> and <code>.cpp</code> files in your sample code is irrelevant to the
issues, and all the code is C, so we'll say that <code>main.cpp</code> is <code>main.c</code> and
do all compiling and linking with <code>gcc</code>:</p>
<pre><code>$ gcc -Wall -c main.c a.c b.c
ar rcs a.a a.o
ar rcs b.a b.o
</code></pre>
<p>First let's review the differences between a weakly declared symbol, like
your:</p>
<pre><code>void foo() __attribute__((weak));
</code></pre>
<p>and a strongly declared symbol, like</p>
<pre><code>void foo();
</code></pre>
<p>which is the default:</p>
<ul>
<li><p>When a weak reference to <code>foo</code> (i.e. a reference to weakly declared <code>foo</code>) is linked in a program, the
linker need not find a definition of <code>foo</code> anywhere in the linkage: it may remain
undefined. If a strong reference to <code>foo</code> is linked in a program,
the linker needs to find a definition of <code>foo</code>.</p></li>
<li><p>A linkage may contain at most one strong definition of <code>foo</code> (i.e. a definition
of <code>foo</code> that declares it strongly). Otherwise a multiple-definition error results.
But it may contain multiple weak definitions of <code>foo</code> without error.</p></li>
<li><p>If a linkage contains one or more weak definitions of <code>foo</code> and also a strong
definition, then the linker chooses the strong definition and ignores the weak
ones.</p></li>
<li><p>If a linkage contains just one weak definition of <code>foo</code> and no strong
definition, inevitably the linker uses the one weak definition.</p></li>
<li><p>If a linkage contains multiple weak definitions of <code>foo</code> and no strong
definition, then the linker chooses one of the weak definitions <em>arbitrarily</em>.</p></li>
</ul>
<p>Next, let's review the differences between inputting an object file in a linkage
and inputting a static library.</p>
<p>A static library is merely an <code>ar</code> archive of object files that we may offer to
the linker from which to select the ones it <em>needs</em> to carry on the linkage.</p>
<p>When an object file is input to a linkage, the linker unconditionally links it
into the output file.</p>
<p>When static library is input to a linkage, the linker examines the archive to
find any object files within it that provide definitions <em>it needs</em> for unresolved symbol references
that have accrued from input files already linked. If it finds any such object files
in the archive, it extracts them and links them into the output file, exactly as
if they were individually named input files and the static library was not mentioned at all.</p>
<p>With these observations in mind, consider the compile-and-link command:</p>
<pre><code>gcc main.c a.o b.o
</code></pre>
<p>Behind the scenes <code>gcc</code> breaks it down, as it must, into a compile-step and link
step, just as if you had run:</p>
<pre><code>gcc -c main.c # compile
gcc main.o a.o b.o # link
</code></pre>
<p>All three object files are linked unconditionally into the (default) program <code>./a.out</code>. <code>a.o</code> contains a
weak definition of <code>foo</code>, as we can see:</p>
<pre><code>$ nm --defined a.o
0000000000000000 W foo
</code></pre>
<p>Whereas <code>b.o</code> contains a strong definition:</p>
<pre><code>$ nm --defined b.o
0000000000000000 T foo
</code></pre>
<p>The linker will find both definitions and choose the strong one from <code>b.o</code>, as we can
also see:</p>
<pre><code>$ gcc main.o a.o b.o -Wl,-trace-symbol=foo
main.o: reference to foo
a.o: definition of foo
b.o: definition of foo
$ ./a.out
b.c
</code></pre>
<p>Reversing the linkage order of <code>a.o</code> and <code>b.o</code> will make no difference: there's
still exactly one strong definition of <code>foo</code>, the one in <code>b.o</code>.</p>
<p>By contrast consider the compile-and-link command:</p>
<pre><code>gcc main.cpp a.a b.a
</code></pre>
<p>which breaks down into:</p>
<pre><code>gcc -c main.cpp # compile
gcc main.o a.a b.a # link
</code></pre>
<p>Here, only <code>main.o</code> is linked unconditionally. That puts an undefined weak reference
to <code>foo</code> into the linkage:</p>
<pre><code>$ nm --undefined main.o
w foo
U _GLOBAL_OFFSET_TABLE_
U puts
</code></pre>
<p>That weak reference to <code>foo</code> <em>does not need a definition</em>. So the linker will
not attempt to find a definition that resolves it in any of the object files in either <code>a.a</code> or <code>b.a</code> and
will leave it undefined in the program, as we can see:</p>
<pre><code>$ gcc main.o a.a b.a -Wl,-trace-symbol=foo
main.o: reference to foo
$ nm --undefined a.out
w __cxa_finalize@@GLIBC_2.2.5
w foo
w __gmon_start__
w _ITM_deregisterTMCloneTable
w _ITM_registerTMCloneTable
U __libc_start_main@@GLIBC_2.2.5
U puts@@GLIBC_2.2.5
</code></pre>
<p>Hence:</p>
<pre><code>$ ./a.out
no foo
</code></pre>
<p>Again, it doesn't matter if you reverse the linkage order of <code>a.a</code> and <code>b.a</code>,
but this time it is because neither of them contributes anything to the linkage.</p>
<p>Let's turn now to the different behavior you discovered by changing <code>a.h</code> and <code>a.c</code>
to:</p>
<p><strong>a.h (2)</strong>:</p>
<pre><code>void foo();
</code></pre>
<p><strong>a.c (2)</strong>:</p>
<pre><code>#include "a.h"
#include <stdio.h>
void __attribute__((weak)) foo() { printf("%s\n", __FILE__); }
</code></pre>
<p>Once again:</p>
<pre><code>$ gcc -Wall -c main.c a.c b.c
main.c: In function ‘main’:
main.c:4:18: warning: the address of ‘foo’ will always evaluate as ‘true’ [-Waddress]
int main() { if (foo) foo(); else printf("no foo\n"); }
</code></pre>
<p>See that warning? <code>main.o</code> now contains a <em>strongly</em> declared reference to <code>foo</code>:</p>
<pre><code>$ nm --undefined main.o
U foo
U _GLOBAL_OFFSET_TABLE_
</code></pre>
<p>so the code (when linked) <em>must have</em> a non-null address for <code>foo</code>. Proceeding:</p>
<pre><code>$ ar rcs a.a a.o
$ ar rcs b.a b.o
</code></pre>
<p>Then try the linkage:</p>
<pre><code>$ gcc main.o a.o b.o
$ ./a.out
b.c
</code></pre>
<p>And with the object files reversed:</p>
<pre><code>$ gcc main.o b.o a.o
$ ./a.out
b.c
</code></pre>
<p>As before, the order makes no difference. All the object files are linked. <code>b.o</code> provides
a strong definition of <code>foo</code>, <code>a.o</code> provides a weak one, so <code>b.o</code> wins.</p>
<p>Next try the linkage:</p>
<pre><code>$ gcc main.o a.a b.a
$ ./a.out
a.c
</code></pre>
<p>And with the order of the libraries reversed:</p>
<pre><code>$ gcc main.o b.a a.a
$ ./a.out
b.c
</code></pre>
<p>That <em>does</em> make a difference. Why? Let's redo the linkages with diagnostics:</p>
<pre><code>$ gcc main.o a.a b.a -Wl,-trace,-trace-symbol=foo
/usr/bin/x86_64-linux-gnu-ld: mode elf_x86_64
/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/Scrt1.o
/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/crti.o
/usr/lib/gcc/x86_64-linux-gnu/7/crtbeginS.o
main.o
(a.a)a.o
libgcc_s.so.1 (/usr/lib/gcc/x86_64-linux-gnu/7/libgcc_s.so.1)
/lib/x86_64-linux-gnu/libc.so.6
(/usr/lib/x86_64-linux-gnu/libc_nonshared.a)elf-init.oS
/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2
/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2
libgcc_s.so.1 (/usr/lib/gcc/x86_64-linux-gnu/7/libgcc_s.so.1)
/usr/lib/gcc/x86_64-linux-gnu/7/crtendS.o
/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/crtn.o
main.o: reference to foo
a.a(a.o): definition of foo
</code></pre>
<p>Ignoring the default libraries, the only object files of <em>ours</em> that get
linked were:</p>
<pre><code>main.o
(a.a)a.o
</code></pre>
<p>And the definition of <code>foo</code> was taken from the archive member <code>a.o</code> of <code>a.a</code>:</p>
<pre><code>a.a(a.o): definition of foo
</code></pre>
<p>Reversing the library order:</p>
<pre><code>$ gcc main.o b.a a.a -Wl,-trace,-trace-symbol=foo
/usr/bin/x86_64-linux-gnu-ld: mode elf_x86_64
/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/Scrt1.o
/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/crti.o
/usr/lib/gcc/x86_64-linux-gnu/7/crtbeginS.o
main.o
(b.a)b.o
libgcc_s.so.1 (/usr/lib/gcc/x86_64-linux-gnu/7/libgcc_s.so.1)
/lib/x86_64-linux-gnu/libc.so.6
(/usr/lib/x86_64-linux-gnu/libc_nonshared.a)elf-init.oS
/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2
/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2
libgcc_s.so.1 (/usr/lib/gcc/x86_64-linux-gnu/7/libgcc_s.so.1)
/usr/lib/gcc/x86_64-linux-gnu/7/crtendS.o
/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/crtn.o
main.o: reference to foo
b.a(b.o): definition of foo
</code></pre>
<p>This time the object files linked were:</p>
<pre><code>main.o
(b.a)b.o
</code></pre>
<p>And the definition of <code>foo</code> was taken from <code>b.o</code> in <code>b.a</code>:</p>
<pre><code>b.a(b.o): definition of foo
</code></pre>
<p>In the first linkage, the linker had an unresolved strong reference to
<code>foo</code> for which it needed a definition when it reached <code>a.a</code>. So it
looked in the archive for an object file that provides a definition,
and found <code>a.o</code>. That definition was a weak one, but that didn't matter. No
strong definition had been seen. <code>a.o</code> was extracted from <code>a.a</code> and linked,
and the reference to <code>foo</code> was thus resolved. Next <code>b.a</code> was reached, where
a strong definition of <code>foo</code> <em>would</em> have been found in <code>b.o</code>, if the linker still needed one
and looked for it. But it didn't need one any more and didn't look. The linkage:</p>
<pre><code>gcc main.o a.a b.a
</code></pre>
<p>is <em>exactly the same</em> as:</p>
<pre><code>gcc main.o a.o
</code></pre>
<p>And likewise the linkage:</p>
<pre><code>$ gcc main.o b.a a.a
</code></pre>
<p>is exactly the same as:</p>
<pre><code>$ gcc main.o b.o
</code></pre>
<p><strong>Your real problem...</strong></p>
<p>... emerges in one of your comments to the post:</p>
<blockquote>
<p>I want to override [the] original function implementation when linking with a testing framework.</p>
</blockquote>
<p>You want to link a program inputting some static library <code>lib1.a</code>
which has some member <code>file1.o</code> that defines a symbol <code>foo</code>, and you want to knock out
that definition of <code>foo</code> and link a different one that is defined in some other object
file <code>file2.o</code>.</p>
<p><code>__attribute__((weak))</code> isn't applicable to that problem. The solution is more
elementary. <em>You just make sure to input</em> <code>file2.o</code> <em>to the linkage before you input</em>
<code>lib1.a</code> (and before any other input that provides a definition of <code>foo</code>).
Then the linker will resolve references to <code>foo</code> with the definition provided in <code>file2.o</code> and will not try to find any other
definition when it reaches <code>lib1.a</code>. The linker will not consume <code>lib1.a(file1.o)</code> at all. It might as well not exist.</p>
<p>And what if you have put <code>file2.o</code> in another static library <code>lib2.a</code>? Then inputting
<code>lib2.a</code> before <code>lib1.a</code> will do the job of linking <code>lib2.a(file2.o)</code> before
<code>lib1.a</code> is reached and resolving <code>foo</code> to the definition in <code>file2.o</code>.</p>
<p>Likewise, of course, <em>every</em> definition provided by members of <code>lib2.a</code> will be linked in
preference to a definition of the same symbol provided in <code>lib1.a</code>. If that's not what
you want, then don't like <code>lib2.a</code>: link <code>file2.o</code> itself.</p>
<p><strong>Finally</strong></p>
<blockquote>
<p>Is it possible to use [the] weak attribute with static linking at all?</p>
</blockquote>
<p>Certainly. Here is a first-principles use-case:</p>
<p><strong>foo.h (1)</strong></p>
<pre><code>#ifndef FOO_H
#define FOO_H
int __attribute__((weak)) foo(int i)
{
return i != 0;
}
#endif
</code></pre>
<p><strong>aa.c</strong></p>
<pre><code>#include "foo.h"
int a(void)
{
return foo(0);
}
</code></pre>
<p><strong>bb.c</strong></p>
<pre><code>#include "foo.h"
int b(void)
{
return foo(42);
}
</code></pre>
<p><strong>prog.c</strong></p>
<pre><code>#include <stdio.h>
extern int a(void);
extern int b(void);
int main(void)
{
puts(a() ? "true" : "false");
puts(b() ? "true" : "false");
return 0;
}
</code></pre>
<p>Compile all the source files, requesting a seperate ELF section for each function:</p>
<pre><code>$ gcc -Wall -ffunction-sections -c prog.c aa.c bb.c
</code></pre>
<p>Note that the <em>weak</em> definition of <code>foo</code> is compiled via <code>foo.h</code> into <em>both</em>
<code>aa.o</code> and <code>bb.o</code>, as we can see:</p>
<pre><code>$ nm --defined aa.o
0000000000000000 T a
0000000000000000 W foo
$ nm --defined bb.o
0000000000000000 T b
0000000000000000 W foo
</code></pre>
<p>Now link a program from all the object files, requesting the linker to
discard unused sections (and give us the map-file, and some diagnostics):</p>
<pre><code>$ gcc prog.o aa.o bb.o -Wl,--gc-sections,-Map=mapfile,-trace,-trace-symbol=foo
/usr/bin/x86_64-linux-gnu-ld: mode elf_x86_64
/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/Scrt1.o
/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/crti.o
/usr/lib/gcc/x86_64-linux-gnu/7/crtbeginS.o
prog.o
aa.o
bb.o
libgcc_s.so.1 (/usr/lib/gcc/x86_64-linux-gnu/7/libgcc_s.so.1)
/lib/x86_64-linux-gnu/libc.so.6
(/usr/lib/x86_64-linux-gnu/libc_nonshared.a)elf-init.oS
/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2
/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2
libgcc_s.so.1 (/usr/lib/gcc/x86_64-linux-gnu/7/libgcc_s.so.1)
/usr/lib/gcc/x86_64-linux-gnu/7/crtendS.o
/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/crtn.o
aa.o: definition of foo
</code></pre>
<p>This linkage is no different from:</p>
<pre><code>$ ar rcs libaabb.a aa.o bb.o
$ gcc prog.o libaabb.a
</code></pre>
<p>Despite the fact that both <code>aa.o</code> and <code>bb.o</code> were loaded, and each contains
a definition of <code>foo</code>, no multiple-definition error results, because each definition
is <em>weak</em>. <code>aa.o</code> was loaded before <code>bb.o</code> and the definition of <code>foo</code> was linked from <code>aa.o</code>.</p>
<p>So what happened to the definition of <code>foo</code> in <code>bb.o</code>? The mapfile shows us:</p>
<p><strong>mapfile (1)</strong></p>
<pre><code>...
...
Discarded input sections
...
...
.text.foo 0x0000000000000000 0x13 bb.o
...
...
</code></pre>
<p>The linker discarded the function section that contained the definition
in <code>bb.o</code></p>
<p>Let's reverse the linkage order of <code>aa.o</code> and <code>bb.o</code>:</p>
<pre><code>$ gcc prog.o bb.o aa.o -Wl,--gc-sections,-Map=mapfile,-trace,-trace-symbol=foo
...
prog.o
bb.o
aa.o
...
bb.o: definition of foo
</code></pre>
<p>And now the opposite thing happens. <code>bb.o</code> is loaded before <code>aa.o</code>. The
definition of <code>foo</code> is linked from <code>bb.o</code> and:</p>
<p><strong>mapfile (2)</strong></p>
<pre><code>...
...
Discarded input sections
...
...
.text.foo 0x0000000000000000 0x13 aa.o
...
...
</code></pre>
<p>the definition from <code>aa.o</code> is chucked away.</p>
<p>There you see how the linker <em>arbitrarily</em> chooses one of multiple
weak definitions of a symbol, in the absence of a strong definition. It simply
picks the first one you give it and ignores the rest.</p>
<p>What we've just done here is effectively what the GCC C++ compiler does for us when we
define a <em>global inline function</em>. Rewrite:</p>
<p><strong>foo.h (2)</strong></p>
<pre><code>#ifndef FOO_H
#define FOO_H
inline int foo(int i)
{
return i != 0;
}
#endif
</code></pre>
<p>Rename our source files <code>*.c</code> -> <code>*.cpp</code>; compile and link:</p>
<pre><code>$ g++ -Wall -c prog.cpp aa.cpp bb.cpp
</code></pre>
<p>Now there is a weak definition of <code>foo</code> (C++ mangled) in each of <code>aa.o</code> and <code>bb.o</code>:</p>
<pre><code>$ nm --defined aa.o bb.o
aa.o:
0000000000000000 T _Z1av
0000000000000000 W _Z3fooi
bb.o:
0000000000000000 T _Z1bv
0000000000000000 W _Z3fooi
</code></pre>
<p>The linkage uses the first definition it finds:</p>
<pre><code>$ g++ prog.o aa.o bb.o -Wl,-Map=mapfile,-trace,-trace-symbol=_Z3fooi
...
prog.o
aa.o
bb.o
...
aa.o: definition of _Z3fooi
bb.o: reference to _Z3fooi
</code></pre>
<p>and throws away the other one:</p>
<p><strong>mapfile (3)</strong></p>
<pre><code>...
...
Discarded input sections
...
...
.text._Z3fooi 0x0000000000000000 0x13 bb.o
...
...
</code></pre>
<p>And as you may know, every instantiation of the C++ function template in
global scope (or instantiation of a class template member function) is
an <em>inline global function</em>. Rewrite again:</p>
<pre><code>#ifndef FOO_H
#define FOO_H
template<typename T>
T foo(T i)
{
return i != 0;
}
#endif
</code></pre>
<p>Recompile:</p>
<pre><code>$ g++ -Wall -c prog.cpp aa.cpp bb.cpp
</code></pre>
<p>Again:</p>
<pre><code>$ nm --defined aa.o bb.o
aa.o:
0000000000000000 T _Z1av
0000000000000000 W _Z3fooIiET_S0_
bb.o:
0000000000000000 T _Z1bv
0000000000000000 W _Z3fooIiET_S0_
</code></pre>
<p>each of <code>aa.o</code> and <code>bb.o</code> has a weak definition of:</p>
<pre><code>$ c++filt _Z3fooIiET_S0_
int foo<int>(int)
</code></pre>
<p>and the linkage behaviour is now familiar. One way:</p>
<pre><code>$ g++ prog.o aa.o bb.o -Wl,-Map=mapfile,-trace,-trace-symbol=_Z3fooIiET_S0_
...
prog.o
aa.o
bb.o
...
aa.o: definition of _Z3fooIiET_S0_
bb.o: reference to _Z3fooIiET_S0_
</code></pre>
<p>and the other way:</p>
<pre><code>$ g++ prog.o bb.o aa.o -Wl,-Map=mapfile,-trace,-trace-symbol=_Z3fooIiET_S0_
...
prog.o
bb.o
aa.o
...
bb.o: definition of _Z3fooIiET_S0_
aa.o: reference to _Z3fooIiET_S0_
</code></pre>
<p>Our program's behavior is unchanged by the rewrites:</p>
<pre><code>$ ./a.out
false
true
</code></pre>
<p>So the application of the <em>weak</em> attribute to symbols in the linkage of ELF objects -
whether static or dynamic - enables the GCC implementation of C++ templates
for the GNU linker. You could fairly say it enables the GCC implementation of modern C++.</p>
|
23,974,639 |
Bootstrap 3 modal responsive
|
<p>I have a modal but it's not resizing on smaller screens ( tablets, etc ). Is there a way to make it responsive ? Couldn't find any information on bootstrap docs. Thanks</p>
<p>I update my html code: ( its inside a django for loop )</p>
<pre><code> <div class="modal fade " id="{{ p.id }}" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" >
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
<h4 class="modal-title" id="myModalLabel">Producto</h4>
</div>
<div class="modal-body">
<h5>Nombre : {{ p.name}}</h5>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
</div>
</div>
</div>
</div>
</code></pre>
<p>I have these css settings:</p>
<pre><code>.modal-lg {
max-width: 900px;
}
@media (min-width: 768px) {
.modal-lg {
width: 100%;
}
}
@media (min-width: 992px) {
.modal-lg {
width: 900px;
}
}
</code></pre>
| 30,873,219 | 6 | 4 | null |
2014-05-31 21:27:20.613 UTC
| 3 |
2021-04-19 16:20:14.333 UTC
|
2020-02-25 13:02:56.01 UTC
| null | 1,438,038 | null | 1,579,883 | null | 1 | 25 |
html|css|twitter-bootstrap-3
| 104,986 |
<p>I had the same issue I have resolved by adding a media query for @screen-xs-min in less version under Modals.less</p>
<pre><code>@media (max-width: @screen-xs-min) {
.modal-xs { width: @modal-sm; }
}
</code></pre>
|
3,491,721 |
LINQ to Entities - Where IN clause in query
|
<blockquote>
<p><strong>Possible Duplicates:</strong><br>
<a href="https://stackoverflow.com/questions/857973/linq-to-entities-sql-in-clause">Linq to Entities - Sql “IN” clause</a><br>
<a href="https://stackoverflow.com/questions/2973755/how-to-implement-sql-in-in-entity-framework-4-0">How to implement SQL “in” in Entity framework 4.0</a> </p>
</blockquote>
<p>how can I add WHERE IN statement like...</p>
<pre><code>SELECT * FROM myTable WHERE ID IN (1,2,3,4,5)
</code></pre>
<p>in entity framework</p>
| 3,491,736 | 2 | 0 | null |
2010-08-16 08:49:08.31 UTC
| 4 |
2010-08-16 08:52:47.75 UTC
|
2017-05-23 10:30:46.267 UTC
| null | -1 | null | 97,010 | null | 1 | 18 |
c#|sql|entity-framework
| 57,543 |
<p>Use <code>Contains</code>:</p>
<pre><code>int[] ids = { 1, 2, 3, 4, 5};
var query = db.myTable.Where(item => ids.Contains(item.ID));
</code></pre>
<p>or in query syntax:</p>
<pre><code>int[] ids = { 1, 2, 3, 4, 5};
var query = from item in db.myTable
where ids.Contains(item.ID)
select item;
</code></pre>
|
3,689,925 |
struct sockaddr_un vs. sockaddr
|
<p>How is <code>struct sockaddr</code> different from <code>struct sockaddr_un</code> ?</p>
<p>I know that we use these structures in client-server modules, for binding the socket to the socket address. And we use a cast operator for it to accept struct <code>sockaddr_un</code>.</p>
<p>I want to know how different/similar they are, and why the cast operator?</p>
| 3,689,966 | 2 | 0 | null |
2010-09-11 05:32:48.307 UTC
| 8 |
2018-12-19 09:48:14.727 UTC
|
2018-12-19 09:48:14.727 UTC
| null | 72,882 | null | 425,094 | null | 1 | 38 |
c|linux|sockets|struct|client-server
| 36,647 |
<p>"struct sockaddr" is a generic definition. It's used by any socket function that requires an address.</p>
<p>"struct sockaddr_un" (a "Unix sockets" address) is a specific kind of address family.</p>
<p>The more commonly seen "struct sockaddr_in" (an "Internet socket" address) is another specific kind of address family.</p>
<p>The cast is what allows the sockets APIs to accept a common parameter type that will actually be any one of several different actual types.</p>
<p>Here's a good link that shows several different address family definitions:</p>
<p><a href="http://www.cas.mcmaster.ca/~qiao/courses/cs3mh3/tutorials/socket.html" rel="noreferrer">http://www.cas.mcmaster.ca/~qiao/courses/cs3mh3/tutorials/socket.html</a></p>
|
3,549,713 |
Controller helper_method
|
<p>I was wondering why someone should use helper_method inside a controller to create a helper method, instead of creating the "normal" way, which is inside the helper file. What the pros and cons of that?</p>
| 3,549,739 | 2 | 0 | null |
2010-08-23 16:43:48.75 UTC
| 13 |
2013-07-31 13:33:33.2 UTC
| null | null | null | null | 370,927 | null | 1 | 44 |
ruby-on-rails|ruby-on-rails-3
| 23,350 |
<p><code>helper_method</code> is useful when the functionality is something that's used between both the controller and the view. A good example is something like <code>current_user</code>.</p>
<p>If the method deals more with controller logic and not formatting then it belongs in the controller. Something like <code>current_user</code> would be shared between all controllers so it should be defined in the <code>ApplicationController</code>.</p>
<p>True "helper" methods deal with the view and handle things like formatting and template logic. These are seldom needed in the controller and they belong in their own module under app/helpers. You can include these in your controller when needed, but you end up with the whole module worth of view helper methods available to your controller.</p>
|
9,182,428 |
Force Internet Explorer 9 to use IE 9 Mode
|
<p>I'm using the HTML5 doctype with X-UA-Compatible meta tag near the top:</p>
<pre><code><!DOCTYPE html>
<!--[if lt IE 7]> <html lang="en-us" class="ie6"> <![endif]-->
<!--[if IE 7]> <html lang="en-us" class="ie7"> <![endif]-->
<!--[if IE 8]> <html lang="en-us" class="ie8"> <![endif]-->
<!--[if gt IE 8]><!--> <html lang="en-us"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
...
</code></pre>
<p>But Internet Explorer 9 for some users is rendering the page in compatibility view. I suspect it's because they have the "Display all websites in Compatibility View" setting turned on. Is there a way to force IE9 to use IE9 Browser and Document Mode?</p>
| 9,182,704 | 7 | 2 | null |
2012-02-07 19:18:07.53 UTC
| 10 |
2014-12-15 13:44:26.343 UTC
| null | null | null | null | 188,740 | null | 1 | 19 |
internet-explorer|internet-explorer-9|cross-browser|doctype
| 54,279 |
<p>It turns out that the solution is to set X-UA-Compatible in the HTTP header and not in the HTML:</p>
<pre><code> X-UA-Compatible: IE=edge,chrome=1
</code></pre>
<p>This will force Internet Explorer to use the latest rendering engine, even if "Display all websites in Compatibility View" is turned on.</p>
|
9,055,015 |
Difference between accessing cell elements using curly braces and parentheses
|
<p>What is the difference between accessing elements in a cell array using parentheses <code>()</code> and curly braces <code>{}</code>?</p>
<p>For example, I tried to use <code>cell{4} = []</code> and <code>cell(4) = []</code>. In the first case it sets the 4<sup>th</sup> element to <code>[]</code>, but in the second case it wiped out the cell element, that is, reduced the cell element count by 1.</p>
| 9,055,336 | 2 | 2 | null |
2012-01-29 17:12:19.3 UTC
| 16 |
2018-05-22 09:38:02.19 UTC
|
2018-05-22 09:38:02.19 UTC
| null | 3,924,118 | null | 729,294 | null | 1 | 29 |
matlab|cell-array
| 25,766 |
<p>Think of cell array as a regular homogenic array, whose elements are all <code>cell</code>s. Parentheses (<code>()</code>) simply access the <code>cell</code> wrapper object, while accessing elements using curly bracers (<code>{}</code>) gives the actual object contained within the cell.</p>
<p>For example, </p>
<pre><code>A={ [5,6], 0 , 0 ,0 };
</code></pre>
<p>Will look like this:</p>
<p><img src="https://i.stack.imgur.com/ZNy3u.png" alt="enter image description here"></p>
<p>The syntax of making an element equal to <code>[]</code> <strong>with parentheses</strong> is actually a request to delete that element, so when you ask to do <code>foo(i) = []</code> you remove the <em>i</em>-th cell. It is not an assignment operation, but rather a <code>RemoveElement</code> operation, which uses similar syntax to assignment.</p>
<p>However, when you do <code>foo{i} = []</code> you are assigning to the i-th cell a new value (which is an empty array), thus clearing the contents of that cell.</p>
|
29,424,944 |
RecyclerView itemClickListener in Kotlin
|
<p>I'm writing my first app in Kotlin after 3 years of experience with Android.
Just confused as to how to utilize itemClickListener with a RecyclerView in Kotlin.</p>
<p>I have tried the trait (edit: now interface) approach, very Java-like</p>
<pre><code>public class MainActivity : ActionBarActivity() {
protected override fun onCreate(savedInstanceState: Bundle?) {
// set content view etc go above this line
class itemClickListener : ItemClickListener {
override fun onItemClick(view: View, position: Int) {
Toast.makeText(this@MainActivity, "TEST: " + position, Toast.LENGTH_SHORT).show()
}
}
val adapter = DrawerAdapter(itemClickListener())
mRecyclerView.setAdapter(adapter)
}
trait ItemClickListener {
fun onItemClick(view: View, position: Int)
}
}
</code></pre>
<p>That seemed very redundant so I tried the inner class approach:</p>
<pre><code>inner class ItemClickListener {
fun onItemClick(view: View, position: Int) {
startActivityFromFragmentForResult<SelectExerciseActivity>(SELECT_EXERCISES)
}
}
</code></pre>
<p>And then just setting the adapter's click listener like this:</p>
<pre><code>val adapter = WorkoutsAdapter(ItemClickListener())
</code></pre>
<p>But I'm still not satisfied with this because I think there might be a better, cleaner way. I'm trying to essentially achieve something like this:
<a href="https://stackoverflow.com/questions/24471109/recyclerview-onclick/26196831#26196831">RecyclerView onClick</a></p>
<p>Any suggestions?</p>
<p><strong>Ended up going with a variation of the approved answer</strong></p>
<p>Defined the function in the activity:</p>
<pre><code>val itemOnClick: (View, Int, Int) -> Unit = { view, position, type ->
Log.d(TAG, "test")
}
</code></pre>
<p>Passed the function itself on to the adapter like this:</p>
<pre><code>class ExercisesAdapter(val itemClickListener: (View, Int, Int) -> Unit) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
// other stuff up here
val vhExercise = ExerciseVH(view) // view holder
// on to the view holder through the extension function
vhExercise.onClick(itemClickListener)
}
}
</code></pre>
<p>Extension function by Loop in the approved answer below.</p>
<pre><code>fun <T : RecyclerView.ViewHolder> T.onClick(event: (view: View, position: Int, type: Int) -> Unit): T {
itemView.setOnClickListener {
event.invoke(it, getAdapterPosition(), getItemViewType())
}
return this
}
</code></pre>
| 29,428,715 | 24 | 3 | null |
2015-04-03 01:19:33.037 UTC
| 22 |
2022-09-09 11:03:57.807 UTC
|
2018-02-06 16:23:36.527 UTC
| null | 507,142 | null | 507,142 | null | 1 | 85 |
android|android-recyclerview|kotlin
| 152,797 |
<p>I have a little bit different approach. You can create an extension for your ViewHolder</p>
<pre><code>fun <T : RecyclerView.ViewHolder> T.listen(event: (position: Int, type: Int) -> Unit): T {
itemView.setOnClickListener {
event.invoke(getAdapterPosition(), getItemViewType())
}
return this
}
</code></pre>
<p>Then use it in adapter like this</p>
<pre><code>class MyAdapter : RecyclerView.Adapter<MyAdapter.MyViewHolder>() {
val items: MutableList<String> = arrayListOf()
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): MyViewHolder? {
val inflater = LayoutInflater.from(parent!!.getContext())
val view = inflater.inflate(R.layout.item_view, parent, false)
return MyViewHolder(view).listen { pos, type ->
val item = items.get(pos)
//TODO do other stuff here
}
}
override fun onBindViewHolder(holder: MyViewHolder?, position: Int) {
}
override fun getItemCount(): Int {
return items.size()
}
class MyViewHolder(view: View) : RecyclerView.ViewHolder(view) {
}
}
</code></pre>
<p>I am working with my colleagues on <a href="https://github.com/Schibsted-Tech-Polska/kotlin-kit" rel="noreferrer">library</a> providing such extensions.</p>
|
16,440,661 |
Declaration is incompatible with type
|
<p>header file:</p>
<pre><code>#ifndef H_bankAccount;
#define H_bankAccount;
class bankAccount
{
public:
string getAcctOwnersName() const;
int getAcctNum() const;
double getBalance() const;
virtual void print() const;
void setAcctOwnersName(string);
void setAcctNum(int);
void setBalance(double);
virtual void deposit(double)=0;
virtual void withdraw(double)=0;
virtual void getMonthlyStatement()=0;
virtual void writeCheck() = 0;
private:
string acctOwnersName;
int acctNum;
double acctBalance;
};
#endif
</code></pre>
<p>cpp file:</p>
<pre><code>#include "bankAccount.h"
#include <string>
#include <iostream>
using std::string;
string bankAccount::getAcctOwnersName() const
{
return acctOwnersName;
}
int bankAccount::getAcctNum() const
{
return acctNum;
}
double bankAccount::getBalance() const
{
return acctBalance;
}
void bankAccount::setAcctOwnersName(string name)
{
acctOwnersName=name;
}
void bankAccount::setAcctNum(int num)
{
acctNum=num;
}
void bankAccount::setBalance(double b)
{
acctBalance=b;
}
void bankAccount::print() const
{
std::cout << "Name on Account: " << getAcctOwnersName() << std::endl;
std::cout << "Account Id: " << getAcctNum() << std::endl;
std::cout << "Balance: " << getBalance() << std::endl;
}
</code></pre>
<p>Please help i get an error under getAcctOwnersName, and setAcctOwnersName stating that the declaration is incompatible with "< error-type > bankAccount::getAcctOwnersName() const".</p>
| 16,440,705 | 3 | 2 | null |
2013-05-08 12:26:45.09 UTC
| 2 |
2022-03-22 17:16:44.36 UTC
| null | null | null | null | 2,362,280 | null | 1 | 15 |
c++|string|types
| 61,798 |
<p>You need to </p>
<pre><code>#include <string>
</code></pre>
<p>in your <code>bankAccount</code> header file, and refer to the strings as <code>std::string</code>.</p>
<pre><code>#ifndef H_bankAccount;
#define H_bankAccount;
#include <string>
class bankAccount
{
public:
std::string getAcctOwnersName() const;
....
</code></pre>
<p>once it is included in the header, you no longer need to include it in the implementation file.</p>
|
16,552,710 |
How do you get the start and end addresses of a custom ELF section?
|
<p>I'm working in C on Linux. I've seen the usage of of the gcc <a href="http://gcc.gnu.org/onlinedocs/gcc/Variable-Attributes.html" rel="noreferrer"><code>__section__</code> attribute</a> (especially in the Linux kernel) to collect data (usually function pointers) into custom ELF sections. How is the "stuff" that gets put in those custom sections retrieved and used?</p>
| 16,552,711 | 5 | 2 | null |
2013-05-14 20:57:00.44 UTC
| 12 |
2022-03-30 10:40:17.227 UTC
|
2019-03-09 03:53:21.693 UTC
| null | 608,639 | null | 209,050 | null | 1 | 23 |
c|gcc|elf
| 18,866 |
<p>As long as the section name results in a valid C variable name, <code>gcc</code> (<code>ld</code>, rather) generates two magic variables: <code>__start_SECTION</code> and <code>__stop_SECTION</code>. Those can be used to retrieve the start and end addresses of a section, like so:</p>
<pre><code>/**
* Assuming you've tagged some stuff earlier with:
* __attribute((__section__("my_custom_section")))
*/
struct thing *iter = &__start_my_custom_section;
for ( ; iter < &__stop_my_custom_section; ++iter) {
/* do something with *iter */
}
</code></pre>
<p>I couldn’t find any formal documentation for this feature, only a few obscure mailing list references. If you know where the docs are, drop a comment!</p>
<p>If you're using your own linker script (as the Linux kernel does) you'll have to add the magic variables yourself (see <code>vmlinux.lds.[Sh]</code> and <a href="https://stackoverflow.com/questions/4152018/initialize-global-array-of-function-pointers-at-either-compile-time-or-run-time/4152185#4152185">this SO answer</a>).</p>
<p>See <a href="https://mgalgs.io/2013/05/10/hacking-your-ELF-for-fun-and-profit.html" rel="nofollow noreferrer">here</a> for another example of using custom ELF sections.</p>
|
16,377,432 |
benefit of using angular js on top of asp.net mvc
|
<p>Is there much point to using angular js on top of asp.net mvc since they're kind of both doing the same thing? What are the advantages to using angular over asp.net mvc + jquery? What kind of scenario would you pick angular in? If you do pick angular in a microsoft environment, what would you run on the server side? Would it be something like Web API? Or is there still benefit of using traditional asp.net mvc?</p>
| 16,381,080 | 3 | 5 | null |
2013-05-04 18:11:30.913 UTC
| 10 |
2013-09-12 06:41:33.367 UTC
| null | null | null | null | 155,909 | null | 1 | 46 |
asp.net-mvc|angularjs
| 15,766 |
<p>On my site <a href="http://www.reviewstoshare.com">http://www.reviewstoshare.com</a>, I am using AngularJS along with ASP.NET MVC. <strong>The main reason I did not go all the way with AngularJS was that SEO is not easily achieved with AngularJS.</strong>
Keep in mind that my site was already built using ASP.MVC + Jquery for in page interaction as needed.</p>
<p>On the other hand there is still some "Ajaxy" nature to the site like comments, voting, flagging etc. Not too different than Stackoverflow itself. Before AngularJS it was a mess of Jquery plugins and functions within <code>$(document).ready()</code> callback, not to mention the JS code was not testable much. </p>
<p>In the end, I went with both. </p>
|
16,205,778 |
What are Maven goals and phases and what is their difference?
|
<p>What is the difference/relation between Maven goals and phases? How they are related to each other?</p>
| 16,205,812 | 8 | 2 | null |
2013-04-25 03:16:23.603 UTC
| 181 |
2020-10-12 07:37:05.06 UTC
|
2016-08-31 19:13:06.83 UTC
| null | 1,743,880 | null | 1,031,863 | null | 1 | 373 |
maven
| 299,293 |
<p>Goals are executed in phases which help determine the order goals get executed in. The best understanding of this is to look at the <a href="http://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html#Built-in_Lifecycle_Bindings" rel="noreferrer">default Maven lifecycle bindings</a> which shows which goals get run in which phases by default. The <code>compile</code> phase goals will always be executed before the <code>test</code> phase goals, which will always be executed before the <code>package</code> phase goals and so on.</p>
<p>Part of the confusion is exacerbated by the fact that when you execute Maven you can specify a goal or a phase. If you specify a phase then Maven will run all phases up to the phase you specified in order (e.g. if you specify package it will first run through the compile phase and then the test phase and finally the package phase) and for each phase it will run all goals attached to that phase.</p>
<p>When you create a plugin execution in your Maven build file and you only specify the goal then it will bind that goal to a given default phase. For example, the <code>jaxb:xjc</code> goal binds by default to the <code>generate-resources</code> phase. However, when you specify the execution you can also explicitly specify the phase for that goal as well.</p>
<p>If you specify a goal when you execute Maven then it will run that goal and only that goal. In other words, if you specify the <code>jar:jar</code> goal it will only run the <code>jar:jar</code> goal to package your code into a jar. If you have not previously run the compile goal or prepared your compiled code in some other way this may very likely fail.</p>
|
24,880,430 |
Azure Blob Storage vs. File Service
|
<p>Please correct my wrongs. From my reading on the topic so far, it appears to me that both, Azure Blob Storage and File Service offer the ability to store file(s) and folder(s) (I understand that blobs can store any binary object, but any serialized binary stream is just a file at the end of the day) in a hierarchical structure that mimics a file system.</p>
<p>Only the API to access them are slightly different in that the File Service allows you to query the source using Win32 File I/O like functions as well in addition to using the REST API.</p>
<p>Why would you choose one over another if you wanted your application to store some files owned by your application's users?</p>
| 24,880,544 | 3 | 7 | null |
2014-07-22 06:36:21.917 UTC
| 34 |
2017-09-28 00:31:34.66 UTC
| null | null | null | null | 303,685 | null | 1 | 157 |
azure|azure-storage|azure-blob-storage
| 71,742 |
<p>A few items for your question:</p>
<ol>
<li>You can't mount Azure Blob Storage as a native share on a virtual machine.</li>
<li>Azure Blob Storage isn't hierarchical beyond containers. You can add files that have / or \ characters in them that are interpreted as folders by many apps that read blob storage.</li>
<li>Azure File Service provides a SMB protocol interface to Azure Blob Storage which solves the problem with (1).</li>
</ol>
<p>If you are developing a new application then leverage the native Azure API directly into Blob Storage.</p>
<p>If you are porting an existing application that needs to share files then use Azure File Service.</p>
<p>Note that there are a few SMB protocol features that <a href="http://msdn.microsoft.com/en-us/library/azure/dn744326.aspx" rel="noreferrer">Azure File Service doesn't support</a>.</p>
|
22,317,951 |
Export html table data to Excel using JavaScript / JQuery is not working properly in chrome browser
|
<p>I have a HTML table in velocity template. I want to export the html table data to excel using either java script or jquery, comatibale with all browser.
I am using below script </p>
<pre><code><script type="text/javascript">
function ExportToExcel(mytblId){
var htmltable= document.getElementById('my-table-id');
var html = htmltable.outerHTML;
window.open('data:application/vnd.ms-excel,' + encodeURIComponent(html));
}
</script>
</code></pre>
<p>This script works fine in <strong>Mozilla Firefox</strong>,it pops-up with a dialog box of excel and ask for open or save options. But when I tested same script in <strong>Chrome browser it is not working</strong> as expected,when clicked on button there is no pop-up for excel. Data gets downloaded in a file with "file type : file" , no extension like <strong>.xls</strong>
There are no errors in chrome console.</p>
<p>Jsfiddle example :</p>
<p><a href="http://jsfiddle.net/insin/cmewv/" rel="noreferrer">http://jsfiddle.net/insin/cmewv/</a></p>
<p>This works fine in mozilla but not in chrome. </p>
<p>Chrome browser Test Case :</p>
<p>First Image:I click on Export to excel button </p>
<p><img src="https://i.stack.imgur.com/Mj5Hb.png" alt="First Image:I click on Export to excel button "> </p>
<p>and result : </p>
<p><img src="https://i.stack.imgur.com/PaFZl.png" alt="Result"></p>
| 24,081,343 | 16 | 2 | null |
2014-03-11 06:22:13.867 UTC
| 78 |
2022-08-02 05:09:53.363 UTC
|
2019-05-16 06:31:23.24 UTC
| null | 3,980,621 | null | 2,085,703 | null | 1 | 121 |
javascript|jquery|html|excel|google-chrome
| 685,645 |
<p>Excel export script works on IE7+, Firefox and Chrome.</p>
<pre><code>function fnExcelReport()
{
var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>";
var textRange; var j=0;
tab = document.getElementById('headerTable'); // id of table
for(j = 0 ; j < tab.rows.length ; j++)
{
tab_text=tab_text+tab.rows[j].innerHTML+"</tr>";
//tab_text=tab_text+"</tr>";
}
tab_text=tab_text+"</table>";
tab_text= tab_text.replace(/<A[^>]*>|<\/A>/g, "");//remove if u want links in your table
tab_text= tab_text.replace(/<img[^>]*>/gi,""); // remove if u want images in your table
tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // If Internet Explorer
{
txtArea1.document.open("txt/html","replace");
txtArea1.document.write(tab_text);
txtArea1.document.close();
txtArea1.focus();
sa=txtArea1.document.execCommand("SaveAs",true,"Say Thanks to Sumit.xls");
}
else //other browser not tested on IE 11
sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));
return (sa);
}
</code></pre>
<p>Just create a blank iframe:</p>
<pre><code><iframe id="txtArea1" style="display:none"></iframe>
</code></pre>
<p>Call this function on:</p>
<pre><code><button id="btnExport" onclick="fnExcelReport();"> EXPORT </button>
</code></pre>
|
26,852,922 |
Inspect webkit-input-placeholder with developer tools
|
<p>It's possible to style a text input's placeholder with the following:</p>
<pre class="lang-css prettyprint-override"><code>-webkit-input-placeholder {
color: red;
}
</code></pre>
<p>I am looking at a website online and I would like to use the same placeholder color as they do. Is it possible to figure out what color they used? I would like to include any alpha values, so I can't just sample the color with an image editor.</p>
<p>When I inspect the element with Chrome Dev Tools, I see:</p>
<p><img src="https://i.stack.imgur.com/qaWat.png" alt="enter image description here" /></p>
<p>Dev tools does not provide information regarding the placeholder element when inspecting the input element. Is there another way?</p>
| 26,853,319 | 2 | 3 | null |
2014-11-10 21:01:16.953 UTC
| 51 |
2022-01-07 18:22:01.46 UTC
|
2022-01-07 18:22:01.46 UTC
| null | 1,526,037 | null | 633,438 | null | 1 | 321 |
html|css
| 77,087 |
<p>I figured it out.</p>
<p>The trick is to enable 'Show user agent shadow DOM' in the Settings panel of Chrome Developer Tools:</p>
<p><img src="https://i.imgur.com/bVq5voX.png" alt="enter image description here" /></p>
<p>To get to settings, click the Gear icon at the top right of your Dev Tools panel, then make sure Preferences tab on the left-hand side is selected, find the Elements heading, and check "Show user agent shadow DOM" checkbox below that heading.</p>
<p>With that, you can now see it:</p>
<p><img src="https://i.stack.imgur.com/7Y0C0.png" alt="enter image description here" /></p>
|
19,485,004 |
Android app Key Hash doesn't match any stored key hashes
|
<p>I have an application on production on Play Store which uses a login with the Facebook SDK.
When I debug the application from Eclipse there is no problem, but when its on production it gives me the following error after Facebook asks me for the permissions.
I have added on my app page on developers.facebook.com the key hash generated with keytool using this command: </p>
<blockquote>
<p>keytool -exportcert -alias diego -keystore
"C:\Users\Diego\Desktop\CeluChat.KeyStore" |
"C:\openssl\bin\openssl.exe" sha1 -binary |
"C:\openssl\bin\openssl.exe" base64</p>
</blockquote>
<p>CeluChat.KeyStore is the keystore I used when I exported the signed application, and when keytool promts me for the password, I entered the same when exported.</p>
<p>But the error that gives me on production (downloaded from Play Store) is:</p>
<blockquote>
<p>10-20 22:21:10.752: W/fb4a(:):BlueServiceQueue(5872):
com.facebook.http.protocol.ApiException: Key hash
VQ3XhZb5_tBH9oGe2WW32DDdNS0 does not match any stored key hashes.</p>
</blockquote>
<p>The Key Hash that is on the exception is different from the key hash generated with keytool. Anyway I added the Key Hash on Facebook, but it is still not working.</p>
| 19,499,368 | 14 | 4 | null |
2013-10-21 01:39:55.477 UTC
| 15 |
2021-10-05 07:22:54.503 UTC
|
2017-04-16 04:29:34.303 UTC
| null | 1,033,581 | null | 799,979 | null | 1 | 33 |
android|facebook-android-sdk
| 53,059 |
<p>Facebook some how replaces +,- and / with _</p>
<p>So just try replacing _ with +, - and / and add that hash-key.</p>
<p>Hopefully it should work.</p>
|
21,506,195 |
Prevent overlapping elements in CSS
|
<p>This question has been asked before, however each situation is unique. I have a screenshot of a website that has a login box (registration box) with a sticky note on the side to tell the users what information to enter. </p>
<p>Screenshot below:</p>
<p><img src="https://i.stack.imgur.com/1AQgO.png" alt="enter image description here"></p>
<p>The registration box is over lapping the sticky note when the user resizes his browser window. Also the login box is overlapping the logo on the top. A solution that is cross compatible with many browsers would be nice (if possible). </p>
<p>Here is my CSS:</p>
<pre><code> .box
{
background:#fefefe;
border: 1px solid #C3D4DB;
border-top:1px;
-webkit-border-radius:5px;
-moz-border-radius:5px;
border-radius:5px;
-moz-box-shadow:rgba(0,0,0,0.15) 0 0 1px;
-webkit-box-shadow:rgba(0,0,0,0.15) 0 0 1px;
box-shadow:rgba(0,0,0,0.15) 0 0 1px;
color:#444;
font:normal 12px/14px Arial, Helvetica, Sans-serif;
margin:0 auto 30px;
overflow:hidden;
}
.box.login
{
height:480px;
width:332px;
position:absolute;
left:50%;
top:37%;
margin:-130px 0 0 -166px;
}
.boxBody
{
background:#fefefe;
border-top:1px solid #dde0e8;
padding:10px 20px;
}
.box footer
{
background:#eff4f6;
border-top:1px solid #dde0e8;
padding:22px 26px;
overflow:hidden;
height:32px;
}
.box label
{
display:block;
font:14px/22px Arial, Helvetica, Sans-serif;
margin:10px 0 0 6px;
}
.box footer label{
float:left;
margin:4px 0 0;
}
.box footer input[type=checkbox]{
vertical-align:sub;
*vertical-align:middle;
margin-right:10px;
.sticky {
/* General */
margin: 0 auto;
padding: 8px 24px;
/*width: 370px; */
max-width: 370px;
height: auto;
width: auto\9;
position: fixed;
left: 3%;
top: 35%;
/* Font */
font-family: 'Nothing You Could Do', cursive;
font-size: 1.4em;
/* Border */
border:1px #E8Ds47 solid;
/* Shadow */
-moz-box-shadow:0px 0px 6px 1px #333333;
-webkit-box-shadow:0px 0px 6px 1px #333333;
box-shadow:0px 0px 6px 1px #333333;
/* Background */
background: #fefdca; /* Old browsers */
background: -moz-linear-gradient(top, #fefdca 0%, #f7f381 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#fefdca), c$
background: -webkit-linear-gradient(top, #fefdca 0%,#f7f381 100%); /* Chrome10+,Safar$
background: -o-linear-gradient(top, #fefdca 0%,#f7f381 100%); /* Opera11.10+ */
background: -ms-linear-gradient(top, #fefdca 0%,#f7f381 100%); /* IE10+ */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fefdca', endColor$
background: linear-gradient(top, #fefdca 0%,#f7f381 100%); /* W3C; A catch-all for ev$
}
.sticky ol {
margin: 12px;
}
.sticky p {
text-align: center;
}
</code></pre>
<p>And here is my HTML: </p>
<pre><code><!DOCTYPE HTML>
<html>
<head>
<title>Secure Customer Login</title>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0$
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<link rel="stylesheet" type="text/css" href="css/reset.css">
<link rel="stylesheet" type="text/css" href="css/structure_register.css">
<link href='https://fonts.googleapis.com/css?family=Nothing+You+Could+Do' rel='styleshe$
<script>document.createElement('footer');</script>
</head>
<center><img src="/images/logo.png"></center>
<body>
<div class="sticky">
<p>
<strong>Please Note</strong>
<br />
</p>
<ol>
<li>Please use your real name (your information is secure and will NOT be shared)$
<li>Capitalize the first letter of your first name and last name (i.e. John Doe)<$
<li>Use your email address for the username, otherwise you will not be able to ac$
<li>Use a secure password that cannot be easily guessed</li>
</ol>
</div>
<form class="box login" name="register" action="<?php echo $_SERVER['PHP_SELF']; ?>" meth$
<fieldset class="boxBody">
<label>First Name</label>
<input type="text" name="firstname" maxlength="50" tabindex="1" placeholder="First Na$
<label>Last Name</label>
<input type="text" name="lastname" maxlength="50" tabindex="2" placeholder="Last Name$
<label>Username</label>
<input type="email" name="username" maxlength="50" tabindex="3" placeholder="Email" r$
<label>Password</label>
<input type="password" placeholder="Password" name="pass1" tabindex="4" />
<label>Repeat Password</label>
<input type="password" placeholder="Repeat Password" name="pass2" tabindex="5" />
</fieldset>
<footer>
<center><input type="submit" name="submit" value="Register" class="btnLogin" /></cent$
</footer>
</form>
<footer id="main">
&copy; 2014 Rye High Group. All rights reserved.</a>
</footer>
</body>
</html>
</code></pre>
<p>Your help is very much appreciated, I love this community!</p>
<p>Thanks,</p>
<p>Fixnode</p>
| 21,506,858 | 3 | 13 | null |
2014-02-02 02:04:43.643 UTC
| null |
2014-02-02 04:00:00.967 UTC
|
2014-02-02 02:43:18.273 UTC
| null | 1,614,936 | null | 1,614,936 | null | 1 | 2 |
html|css
| 57,071 |
<p>Try this <a href="http://jsfiddle.net/ab5KN/" rel="nofollow">http://jsfiddle.net/ab5KN/</a></p>
<p>HTML:</p>
<pre><code><body>
<div class="img">
<img src="http://rye-high.ca/images/logo.png" />
</div>
<div class="sticky">
<p> <strong>Please Note</strong>
<br />
</p>
<ol>
<li>Please use your real name (your information is secure and will NOT be shared) </li>
<li>Capitalize the first letter of your first name and last name (i.e. John Doe)</li>
<li>Use your email address for the username, otherwise you will not be able to access your account</li>
<li>Use a secure password that cannot be easily guessed</li>
</ol>
</div>
<div class="box">
<form class="login" name="register" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<fieldset class="boxBody">
<label>First Name</label>
<input type="text" name="firstname" maxlength="50" tabindex="1" placeholder="First Name" required />
<label>Last Name</label>
<input type="text" name="lastname" maxlength="50" tabindex="2" placeholder="Last Name" required />
<label>Username</label>
<input type="email" name="username" maxlength="50" tabindex="3" placeholder="Email" required />
<label>Password</label>
<input type="password" placeholder="Password" name="pass1" tabindex="4" />
<label>Repeat Password</label>
<input type="password" placeholder="Repeat Password" name="pass2" tabindex="5" />
</fieldset>
<footer>
<center>
<input type="submit" name="submit" value="Register" class="btnLogin" />
</center>
</footer>
</form>
</div>
<footer id="main">&copy; 2014 Rye High Group. All rights reserved.</a>
</footer>
</body>
</code></pre>
<p>CSS:</p>
<pre><code>body {
background:#eff3f6;
width: 1000px;
}
.img {
/*display: block;*/
width:300px;
margin: 0 auto;
}
.box {
width:332px;
margin: 5px auto;
background:#fefefe;
border: 1px solid #C3D4DB;
border-top:1px;
-webkit-border-radius:5px;
-moz-border-radius:5px;
border-radius:5px;
-moz-box-shadow:rgba(0, 0, 0, 0.15) 0 0 1px;
-webkit-box-shadow:rgba(0, 0, 0, 0.15) 0 0 1px;
box-shadow:rgba(0, 0, 0, 0.15) 0 0 1px;
color:#444;
font:normal 12px/14px Arial, Helvetica, Sans-serif;
/*margin:0 auto 30px;*/
overflow:hidden;
position: block;
z-index: -1;
padding-top: 3px;
}
.box.login {
height:480px;
width:150px;
margin: 0 auto;
}
.login fieldset{
border: 0px;
}
.boxBody {
background:#fefefe;
border-top:1px solid #dde0e8;
padding:10px 20px;
}
.box footer {
background:#eff4f6;
border-top:1px solid #dde0e8;
padding:22px 26px;
overflow:hidden;
height:32px;
}
.box label {
display:block;
font:14px/22px Arial, Helvetica, Sans-serif;
margin:10px 0 0 6px;
}
.box footer label {
float:left;
margin:4px 0 0;
}
.box footer input[type=checkbox] {
vertical-align:sub;
*vertical-align:middle;
margin-right:10px;
}
/*Alert Box*/
.alert {
background: #fff6bf url(../images/exclamation.png) center no-repeat;
background-position: 15px 50%;
text-align: center;
padding: 5px 20px 5px 45px;
border-top: 2px solid #ffd324;
border-bottom: 2px solid #ffd324;
}
.info {
background: #CDFECD url(../images/information.png) center no-repeat;
background-position: 15px 50%;
text-align: center;
padding: 5px 20px 5px 45px;
border-top: 2px solid #90EE90;
border-bottom: 2px solid #90EE90;
}
.error {
background: #FFBFBF url(../images/error.png) center no-repeat;
background-position: 15px 50%;
text-align: center;
padding: 5px 20px 5px 45px;
border-top: 2px solid #FF2424;
border-bottom: 2px solid #FF2424;
}
.box input[type=email], .box input[type=password], .box input[type=text], .txtField, .cjComboBox {
border:6px solid #F7F9FA;
-webkit-border-radius:3px;
-moz-border-radius:3px;
border-radius:3px;
-moz-box-shadow:2px 3px 3px rgba(0, 0, 0, 0.06) inset, 0 0 1px #95a2a7 inset;
-webkit-box-shadow:2px 3px 3px rgba(0, 0, 0, 0.06) inset, 0 0 1px #95a2a7 inset;
box-shadow:2px 3px 3px rgba(0, 0, 0, 0.06) inset, 0 0 1px #95a2a7 inset;
margin:3px 0 4px;
padding:8px 6px;
width:270px;
display:block;
}
.box input[type=email]:focus, .box input[type=password]:focus, .box input[type=text]:focus, .txtField:focus, .cjComboBox:focus {
border:6px solid #f0f7fc;
-moz-box-shadow:2px 3px 3px rgba(0, 0, 0, 0.04) inset, 0 0 1px #0d6db6 inset;
-webkit-box-shadow:2px 3px 3px rgba(0, 0, 0, 0.04) inset, 0 0 1px #0d6db6 inset;
box-shadow:2px 3px 3px rgba(0, 0, 0, 0.04) inset, 0 0 1px #0d6db6 inset;
color:#333;
}
.cjComboBox {
width:294px;
}
.cjComboBox.small {
padding:3px 2px 3px 6px;
width:100px;
border-width:3px !important;
}
.txtField.small {
padding:3px 6px;
width:200px;
border-width:3px !important;
}
.rLink {
padding:0 6px 0 0;
font-size:11px;
float:right;
}
.box a {
color:#999;
}
.box a:hover, .box a:focus {
text-decoration:underline;
}
.box a:active {
color:#f84747;
}
.btnLogin {
-moz-border-radius:2px;
-webkit-border-radius:2px;
border-radius:15px;
background:#a1d8f0;
background:-moz-linear-gradient(top, #badff3, #7acbed);
background:-webkit-gradient(linear, left top, left bottom, from(#badff3), to(#7acbed));
-ms-filter:"progid:DXImageTransform.Microsoft.gradient(startColorStr='#badff3', EndColorStr='#7acbed')";
border:1px solid #7db0cc !important;
cursor: pointer;
padding:11px 16px;
font:bold 11px/14px Verdana, Tahomma, Geneva;
text-shadow:rgba(0, 0, 0, 0.2) 0 1px 0px;
color:#fff;
-moz-box-shadow:inset rgba(255, 255, 255, 0.6) 0 1px 1px, rgba(0, 0, 0, 0.1) 0 1px 1px;
-webkit-box-shadow:inset rgba(255, 255, 255, 0.6) 0 1px 1px, rgba(0, 0, 0, 0.1) 0 1px 1px;
box-shadow:inset rgba(255, 255, 255, 0.6) 0 1px 1px, rgba(0, 0, 0, 0.1) 0 1px 1px;
margin-left:12px;
padding:7px 21px;
}
.btnLogin:hover, .btnLogin:focus, .btnLogin:active {
background:#a1d8f0;
background:-moz-linear-gradient(top, #7acbed, #badff3);
background:-webkit-gradient(linear, left top, left bottom, from(#7acbed), to(#badff3));
-ms-filter:"progid:DXImageTransform.Microsoft.gradient(startColorStr='#7acbed', EndColorStr='#badff3')";
}
.btnLogin:active {
text-shadow:rgba(0, 0, 0, 0.3) 0 -1px 0px;
}
footer#main {
/*position:fixed;*/
left:0;
bottom:10px;
text-align:center;
font:normal 11px/16px Arial, Helvetica, sans-serif;
width:100%;
}
.sticky {
/* General */
margin: 0 auto;
padding: 8px 4px;
/*width: 370px; */
max-width: 300px;
height: auto;
width: auto\9;
position: absolute;
left: 3%;
top: 250px;
/* Font */
font-family:'Nothing You Could Do', cursive;
font-size: 1em;
/* Border */
border:1px #E8Ds47 solid;
/* Shadow */
-moz-box-shadow:0px 0px 6px 1px #333333;
-webkit-box-shadow:0px 0px 6px 1px #333333;
box-shadow:0px 0px 6px 1px #333333;
/* Background */
background: #fefdca;
/* Old browsers */
background: -moz-linear-gradient(top, #fefdca 0%, #f7f381 100%);
/* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #fefdca), color-stop(100%, #f7f381));
/* Chrome,Safari4+ */
background: -webkit-linear-gradient(top, #fefdca 0%, #f7f381 100%);
/* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top, #fefdca 0%, #f7f381 100%);
/* Opera11.10+ */
background: -ms-linear-gradient(top, #fefdca 0%, #f7f381 100%);
/* IE10+ */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fefdca', endColorstr='#f7f381', GradientType=0);
/* IE6-9 */
background: linear-gradient(top, #fefdca 0%, #f7f381 100%);
/* W3C; A catch-all for everything else */
}
/*.sticky ol {
margin: 12px;
}*/
.sticky p {
text-align: center;
}
</code></pre>
<p>Basically I added a width to the body, or else adjusting the size of the window will always cause something to overlap. I also added in div wrappers around the image and form (not sure if really needed but added for what I consider better structure). Took out some of the positioning css as well as it causes undue pain when trying to do things.</p>
|
17,567,176 |
How to call a function inside $(document).ready
|
<p>Im trying to debug my web app that uses <code>jQuery.</code></p>
<p>In firebug im calling functions inside the $(document).ready..</p>
<pre><code> function val() { console.log('validated outside doc.ready'); }
$(document).ready(function()
{
console.log('document ready...');
function validate() { console.log('validated!'); }
}
</code></pre>
<p>In firebug console I type <code>validate()</code> and it says its not a function</p>
<p>If i type <code>val()</code> it works fine.</p>
<p>How do i call validate from the console ?</p>
| 17,567,235 | 4 | 2 | null |
2013-07-10 09:33:59.453 UTC
| 5 |
2021-10-15 01:02:49.167 UTC
| null | null | null | null | 692,228 | null | 1 | 35 |
jquery|debugging|firebug
| 106,707 |
<p>You are not calling a function like that, you just <strong>define</strong> the function.</p>
<p>The correct approach is to define the function outside <code>document.ready</code> and call it inside:</p>
<pre><code>// We define the function
function validate(){
console.log('validated!');
}
$(document).ready(function(){
// we call the function
validate();
});
</code></pre>
<p>Another option is to <strong>self invoke</strong> the function like that:</p>
<pre><code>$(document).ready(function(){
// we define and invoke a function
(function(){
console.log('validated!');
})();
});
</code></pre>
|
17,490,716 |
Lifetimes in Rust
|
<p>Occasionally I've found myself wanting to write functions that can be called in either of two ways:</p>
<pre><code>// With a string literal:
let lines = read_file_lines("data.txt");
// With a string pointer:
let file_name = ~"data.txt";
let lines = read_file_lines(file_name);
</code></pre>
<p>My first guess was to use a borrowed pointer (<code>&str</code>) for the parameter type, but when that didn't work (it only allowed me to use <code>@str</code> and <code>~str</code>), I tried the following (by copying the Rust libraries), which did work.</p>
<pre><code>fn read_file_lines<'a>(path: &'a str) -> ~[~str] {
let read_result = file_reader(~Path(path));
match read_result {
Ok(file) => file.read_lines(),
Err(e) => fail!(fmt!("Error reading file: %?", e))
}
}
</code></pre>
<p>The problem is that I don't understand what I'm doing. From what I can gather (mostly from compiler errors), I'm declaring a lifetime on which there is no restriction, and using it to describe the path parameter (meaning that any lifetime can be passed as the parameter).</p>
<p>So:</p>
<ul>
<li>Is my understanding vaguely accurate?</li>
<li>What is a lifetime? Where can I learn more about them?</li>
<li>What is the difference between a parameter of type <code>&str</code> and a parameter of type <code>&'a str</code> in the example above?</li>
<li>And while I'm at it, what is <code>'self</code>?</li>
</ul>
<p>(I'm using Rust 0.7, if it makes a difference to the answer)</p>
| 17,493,553 | 1 | 1 | null |
2013-07-05 14:00:43.117 UTC
| 15 |
2016-09-08 14:22:12.917 UTC
|
2016-09-08 14:22:12.917 UTC
| null | 1,870,153 | null | 259,747 | null | 1 | 68 |
rust|lifetime
| 13,424 |
<p><em>Update 2015-05-16</em>: the code in the original question applied to an old version of Rust, but the concepts remain the same. This answer has been updated to use modern Rust syntax/libraries. (Essentially changing <code>~[]</code> to <code>Vec</code> and <code>~str</code> to <code>String</code> and adjusting the code example at the end.)</p>
<blockquote>
<p>Is my understanding vaguely accurate?<br>
[...]<br>
What is the difference between a parameter of type &str and a parameter of type &'a str in the example above?</p>
</blockquote>
<p>Yes, a lifetime like that says essentially "no restrictions", sort of. Lifetimes are a way to connect output values with inputs, i.e. <code>fn foo<'a, T>(t: &'a T) -> &'a T</code> says that <code>foo</code> returns a pointer that has the same lifetime as <code>t</code>, that is, the data it points to is valid for the same length of time as <code>t</code> (well, strictly, at least as long as). This basically implies that the return value points to some subsection of the memory that <code>t</code> points to. </p>
<p>So, a function like <code>fn<'a>(path: &'a str) -> Vec<String></code> is very similar to writing <code>{ let x = 1; return 2; }</code>... it's an unused variable.</p>
<p>Rust assigns default lifetimes when writing <code>&str</code>, and this is exactly equivalent to writing the unused-variable lifetime. i.e. <code>fn(path: &str) -> Vec<String></code> is no different to the version with <code>'a</code>s. The only time leaving off a lifetime is different to including it is if you need to enforce a global pointer (i.e. the special <code>'static</code> lifetime), or if you want to return a reference (e.g. <code>-> &str</code>) which is only possible if the return value has a lifetime (and this must be either the lifetime of one-or-more of the inputs, or <code>'static</code>).</p>
<blockquote>
<p>What is a lifetime? Where can I learn more about them?</p>
</blockquote>
<p>A lifetime is how long the data a pointer points to is guaranteed to exist, e.g. a global variable is guarantee to last "forever" (so it's got the special lifetime <code>'static</code>). One neat way to look at them is: lifetimes connect data to the stack frame on which their owner is placed; once that stack frame exits, the owner goes out of scope and any pointers to/into that value/data-structure are no longer valid, and the lifetime is a way for the compiler to reason about this. (With the stack frame view, it is as if <code>@</code> has a special stack frame associated with the current task, and <code>static</code>s have a "global" stack frame).</p>
<p>There's also a <a href="http://doc.rust-lang.org/stable/book/lifetimes.html">lifetimes chapter of the book</a>, and <a href="https://gist.github.com/Aatch/5734372">this gist</a> (NB. the code is now outdated but the concepts are still true) is a neat little demonstration of how one can use lifetimes to avoid having to copy/allocate (with a strong safety guarantee: no possibility of dangling pointers).</p>
<blockquote>
<p>And while I'm at it, what is <code>'self</code>?</p>
</blockquote>
<p>Literally nothing special, just certain places require types to have lifetimes (e.g. in struct/enum defintions and in <code>impl</code>s), and currently <code>'self</code> and <code>'static</code> are the only accepted names. <code>'static</code> for global always-valid pointers, <code>'self</code> for something that can have any lifetime. It's a bug that calling that (non-<code>static</code>) lifetime anything other than <code>self</code> is an error.</p>
<hr>
<p>All in all, I'd write that function like:</p>
<pre><code>use std::fs::File;
use std::io::prelude::*;
use std::io::BufReader;
use std::path::Path;
fn read_file_lines(path: &Path) -> Vec<String> {
match File::open(path) {
Ok(file) => {
let read = BufReader::new(file);
read.lines().map(|x| x.unwrap()).collect()
}
Err(e) => panic!("Error reading file: {}", e)
}
}
fn main() {
let lines = read_file_lines(Path::new("foo/bar.txt"));
// do things with lines
}
</code></pre>
|
17,493,738 |
What is a TypeScript Map file?
|
<p>I have seen <code>.map</code> files for TypeScript. What I want to know is what these files are for. Do they contain references to other files referenced in the .ts file?</p>
| 17,493,808 | 3 | 0 | null |
2013-07-05 17:00:55.073 UTC
| 7 |
2020-07-28 11:57:36.8 UTC
|
2013-12-27 15:33:12.497 UTC
| null | 913,707 | null | 991,788 | null | 1 | 104 |
typescript
| 45,166 |
<p>.map files are source map files that let tools map between the emitted JavaScript code and the TypeScript source files that created it. Many debuggers (e.g. Visual Studio or Chrome's dev tools) can consume these files so you can debug the TypeScript file instead of the JavaScript file.</p>
<p>This is the same source map format being produced by some minifiers and other compiled-to-JS languages like <a href="http://coffeescript.org/">CoffeeScript</a>.</p>
|
26,063,877 |
Python multiprocessing module: join processes with timeout
|
<p>I'm doing an optimization of parameters of a complex simulation. I'm using the multiprocessing module for enhancing the performance of the optimization algorithm. The basics of multiprocessing I learned at <a href="http://pymotw.com/2/multiprocessing/basics.html" rel="nofollow noreferrer">http://pymotw.com/2/multiprocessing/basics.html</a>.
The complex simulation lasts different times depending on the given parameters from the optimization algorithm, around 1 to 5 minutes. If the parameters are chosen very badly, the simulation can last 30 minutes or more and the results are not useful. So I was thinking about build in a timeout to the multiprocessing, that terminates all simulations that last more than a defined time. Here is an abstracted version of the problem:</p>
<pre><code>import numpy as np
import time
import multiprocessing
def worker(num):
time.sleep(np.random.random()*20)
def main():
pnum = 10
procs = []
for i in range(pnum):
p = multiprocessing.Process(target=worker, args=(i,), name = ('process_' + str(i+1)))
procs.append(p)
p.start()
print('starting', p.name)
for p in procs:
p.join(5)
print('stopping', p.name)
if __name__ == "__main__":
main()
</code></pre>
<p>The line <code>p.join(5)</code> defines the timeout of 5 seconds. Because of the for-loop <code>for p in procs:</code> the program waits 5 seconds until the first process is finished and then again 5 seconds until the second process is finished and so on, but i want the program to terminate all processes that last more than 5 seconds. Additionally, if none of the processes last longer than 5 seconds the program must not wait this 5 seconds.</p>
| 26,064,238 | 3 | 2 | null |
2014-09-26 16:12:20.963 UTC
| 6 |
2021-09-14 15:07:21.293 UTC
|
2021-09-14 15:05:58.15 UTC
| null | 6,630,397 | null | 4,083,929 | null | 1 | 16 |
python|timeout|python-multiprocessing
| 38,301 |
<p>You can do this by creating a loop that will wait for some timeout amount of seconds, frequently checking to see if all processes are finished. If they don't all finish in the allotted amount of time, then terminate all of the processes:</p>
<pre class="lang-py prettyprint-override"><code>TIMEOUT = 5
start = time.time()
while time.time() - start <= TIMEOUT:
if not any(p.is_alive() for p in procs):
# All the processes are done, break now.
break
time.sleep(.1) # Just to avoid hogging the CPU
else:
# We only enter this if we didn't 'break' above.
print("timed out, killing all processes")
for p in procs:
p.terminate()
p.join()
</code></pre>
|
5,054,057 |
PHP include in a cron job
|
<p>I'm trying to setup a PHP file as a cron job, where that PHP file includes other PHP files.</p>
<p>The file itself is located at /var/www/vhosts/domain.com/httpdocs/app/protected/classes/cron/runner.php</p>
<p>The include file is at
/var/www/vhosts/domain.com/httpdocs/app/protected/config.php</p>
<p>How do I include that config file from runner.php? I tried doing require_once('../../config.php') but it said the file didn't exist.. I presume the cron runs PHP from a different location or something.</p>
<p>The cron job is the following..</p>
<p>/usr/bin/php -q /var/www/vhosts/domain.com/httpdocs/app/protected/classes/cron/runner.php</p>
<p>Any thoughts?</p>
| 5,054,064 | 4 | 1 | null |
2011-02-19 22:51:55.17 UTC
| 9 |
2017-07-01 09:50:59.553 UTC
| null | null | null | null | 471,628 | null | 1 | 7 |
php|cron
| 11,611 |
<p>Your cron should change the working directory before running PHP:</p>
<pre><code>cd /var/www/vhosts/domain.com/httpdocs/app/protected/classes/cron/ && /usr/bin/php -q runner.php
</code></pre>
<p>Note that if the directory does not exist, PHP will not run runner.php.</p>
|
43,274,925 |
Development server of create-react-app does not auto refresh
|
<p>I am following a <a href="https://egghead.io/courses/react-fundamentals" rel="noreferrer">tutorial</a> on React using create-react-app.
The application is created by <a href="https://github.com/facebookincubator/create-react-app" rel="noreferrer">create-react-app</a> v1.3.0</p>
<pre><code>create-react-app my-app
</code></pre>
<p>The dev server is run by</p>
<pre><code>npm start
</code></pre>
<p>After changing the code several times, the browser is not updated live / hot reload with the changes. Refreshing the browser does not help. Only stopping the dev server and starting it over again capture the new changes to the code.</p>
| 43,281,575 | 32 | 3 | null |
2017-04-07 09:47:25.723 UTC
| 37 |
2022-09-15 08:03:55.973 UTC
| null | null | null | null | 3,625,171 | null | 1 | 127 |
javascript|reactjs|create-react-app
| 164,199 |
<p>Have you seen the “Troubleshooting” section of the User Guide?<br />
It describes <a href="https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md#npm-start-doesnt-detect-changes" rel="noreferrer">a few common causes of this problem</a>:</p>
<blockquote>
<p>When you save a file while <code>npm start</code> is running, the browser should refresh with the updated code.<br></p>
<p>If this doesn’t happen, try one of the following workarounds:</p>
<ul>
<li>If your project is in a Dropbox folder, try moving it out.</li>
<li>If the watcher doesn’t see a file called <code>index.js</code> and you’re referencing it by the folder name, you <a href="https://github.com/facebookincubator/create-react-app/issues/1164" rel="noreferrer">need to restart the watcher</a> due to a Webpack bug.</li>
<li>Some editors like Vim and IntelliJ have a “safe write” feature that currently breaks the watcher. You will need to disable it. Follow the instructions in <a href="https://stackoverflow.com/questions/821902/disabling-swap-files-creation-in-vim">“Disabling swap files creation in vim”</a>.</li>
<li>If your project path contains parentheses, try moving the project to a path without them. This is caused by a <a href="https://github.com/webpack/watchpack/issues/42" rel="noreferrer">Webpack watcher bug</a>.</li>
<li>On Linux and macOS, you might need to <a href="https://webpack.github.io/docs/troubleshooting.html#not-enough-watchers" rel="noreferrer">tweak system settings</a> to allow more watchers.</li>
<li>If the project runs inside a virtual machine such as (a Vagrant provisioned) VirtualBox, create an <code>.env</code> file in your project directory if it doesn’t exist, and add <code>CHOKIDAR_USEPOLLING=true</code> to it. This ensures that the next time you run <code>npm start</code>, the watcher uses the polling mode, as necessary inside a VM.</li>
</ul>
<p>If none of these solutions help please leave a comment <a href="https://github.com/facebookincubator/create-react-app/issues/659" rel="noreferrer">in this thread</a>.</p>
</blockquote>
<p>I hope this helps!</p>
|
9,363,827 |
Building GPL C program with CUDA module
|
<p>I am attempting to modify a GPL program written in C. My goal is to replace one method with a CUDA implementation, which means I need to compile with nvcc instead of gcc. I need help building the project - not implementing it (You don't need to know anything about CUDA C to help, I don't think).</p>
<p>This is my first time trying to change a C project of moderate complexity that involves a .configure and Makefile. Honestly, this is my first time doing anything in C in a long time, including anything involving gcc or g++, so I'm pretty lost.</p>
<p>I'm not super interested in learning configure and Makefiles - this is more of an experiment. I would like to see if the project implementation goes well before spending time creating a proper build script. (Not unwilling to learn as necessary, just trying to give an idea of the scope). </p>
<p>With that said, what are my options for building this project? I have a myriad of questions...</p>
<ul>
<li><p>I tried adding "CC=nvcc" to the configure.in file after AC_PROG_CC. This appeared to work - output from running configure and make showed nvcc as the compiler. However make failed to compile the source file with the CUDA kernel, not recognizing the CUDA specific syntax. I don't know why, was hoping this would just work.</p></li>
<li><p>Is it possible to compile a source file with nvcc, and then include it at the linking step in the make process for the main program? If so, how? (This question might not make sense - I'm really rusty at this)</p></li>
<li><p>What's the correct way to do this?</p></li>
<li><p>Is there a quick and dirty way I could use for testing purposes?</p></li>
<li><p>Is there some secret tool everyone uses to setup and understand these configure and Makefiles? This is even worse than the Apache Ant scripts I'm used to (Yeah, I'm out of my realm)</p></li>
</ul>
| 9,369,408 | 1 | 4 | null |
2012-02-20 15:39:24.227 UTC
| 9 |
2018-10-24 21:55:00.57 UTC
| null | null | null | null | 124,593 | null | 1 | 12 |
cuda|makefile|nvcc
| 7,296 |
<p>You don't need to compile everything with nvcc. Your guess that you can just compile your CUDA code with NVCC and leave everything else (except linking) is correct. Here's the approach I would use to start. </p>
<ol>
<li><p>Add a 1 new header (e.g. myCudaImplementation.h) and 1 new source file (with .cu extension, e.g. myCudaImplementation.cu). The source file contains your kernel implementation <em>as well as</em> a (host) C wrapper function that invokes the kernel with the appropriate execution configuration (aka <code><<<>>></code>) and arguments. The header file contains the prototype for the C wrapper function. Let's call that wrapper function <code>runCudaImplementation()</code></p></li>
<li><p>I would also provide another host C function in the source file (with prototype in the header) that queries and configures the GPU devices present and returns true if it is successful, false if not. Let's call this function <code>configureCudaDevice()</code>.</p></li>
<li><p>Now in your original C code, where you would normally call your CPU implementation you can do this.</p>
<pre><code>// must include your new header
#include "myCudaImplementation.h"
// at app initialization
// store this variable somewhere you can access it later
bool deviceConfigured = configureCudaDevice;
...
// then later, at run time
if (deviceConfigured)
runCudaImplementation();
else
runCpuImplementation(); // run the original code
</code></pre></li>
<li><p>Now, since you put all your CUDA code in a new .cu file, you only have to compile that file with nvcc. Everything else stays the same, except that you have to link in the object file that nvcc outputs. e.g.</p>
<pre><code>nvcc -c -o myCudaImplementation.o myCudaImplementation.cu <other necessary arguments>
</code></pre></li>
</ol>
<p>Then add myCudaImplementation.o to your link line (something like:)
g++ -o myApp myCudaImplementation.o</p>
<p>Now, if you have a complex app to work with that uses configure and has a complex makefile already, it may be more involved than the above, but this is the general approach. Bottom line is you don't want to compile all of your source files with nvcc, just the .cu ones. Use your host compiler for everything else.</p>
<p>I'm not expert with configure so can't really help there. You may be able to run configure to generate a makefile, and then edit that makefile -- it won't be a general solution, but it will get you started.</p>
<p>Note that in some cases you may also need to separate compilation of your <code>.cu</code> files from linking them. In this case you need to use NVCC's separate compilation and linking functionality, for which <a href="https://devblogs.nvidia.com/separate-compilation-linking-cuda-device-code/" rel="nofollow noreferrer">this blog post might be helpful</a>.</p>
|
9,575,122 |
Can I assume that calling realloc with a smaller size will free the remainder?
|
<p>Let’s consider this very short snippet of code:</p>
<pre><code>#include <stdlib.h>
int main()
{
char* a = malloc(20000);
char* b = realloc(a, 5);
free(b);
return 0;
}
</code></pre>
<p>After reading the man page for realloc, I was not entirely sure that the second line would cause the 19995 extra bytes to be freed. To quote the man page: <code>The realloc() function changes the size of the memory block pointed to by ptr to size bytes.</code>, but from that definition, can I be sure the rest will be freed? </p>
<p>I mean, the block pointed by <code>b</code> certainly contains 5 free bytes, so would it be enough for a lazy complying allocator to just not do anything for the realloc line?</p>
<p>Note: The allocator I use seems to free the 19 995 extra bytes, as shown by valgrind when commenting out the <code>free(b)</code> line : </p>
<pre><code>==4457== HEAP SUMMARY:
==4457== in use at exit: 5 bytes in 1 blocks
==4457== total heap usage: 2 allocs, 1 frees, 20,005 bytes allocated
</code></pre>
| 9,575,348 | 5 | 4 | null |
2012-03-05 22:36:53.14 UTC
| 9 |
2014-03-21 00:50:39.103 UTC
|
2012-03-05 22:46:27.44 UTC
| null | 748,175 | null | 748,175 | null | 1 | 35 |
c|malloc|free|realloc
| 29,383 |
<p>Yes, guaranteed by the C Standard if the new object can be allocated.</p>
<blockquote>
<p>(C99, 7.20.3.4p2) "The realloc function deallocates the old object pointed to by ptr and returns a pointer to a new object that has the size specified by size."</p>
</blockquote>
|
9,073,148 |
glibc detected free(): invalid next size (fast)
|
<p>This code generates random numbers and then produces a histogram based on input to the functions regarding the intervals. "bins" represents the histogram intervals and "bin_counts" holds the number of random numbers in a given interval.</p>
<p>I've reviewed several of the posts dealing with similiar issues and I understand that I'm out of bounds in the memory somewhere but GBD only points me to the "free(bins);" at the end of the code. I've double-checked my array lengths and I think they are all correct in terms of not accessing elements that don't exist/writing to memory not allocated. The weird thing is that the code works as intended, it produces an accuarate histogram, now I just need helping cleaning up this free() invalid next size error. If anybody has any suggestions I would be much obliged. The whole output is : </p>
<p><strong>glibc detected</strong> ./file: free(): invalid next size (fast): 0x8429008</p>
<p>followed by a bunch of addresses in memory, seperated by Backtrace and Memory Map.
The Backtrace only points me towards line 129, which is "free(bins);". Thanks in advance</p>
<pre><code> #include "stdio.h"
#include "string.h"
#include "stdlib.h"
void histo(int N, double m, double M, int nbins, int *bin_counts, double *bins);
int main(int argc, char* argv[])
{
int *ptr_bin_counts;
double *ptr_bins;
histo(5,0.0,11.0,4, ptr_bin_counts, ptr_bins);
return 0;
}
void histo(int N, double m, double M, int nbins, int *bin_counts, double *bins)
{
srand(time(NULL));
int i,j,k,x,y;
double interval;
int randoms[N-1];
int temp_M = (int)M;
int temp_m = (int)m;
interval = (M-m) /((double)nbins);
//allocating mem to arrays
bins =(double*)malloc(nbins * sizeof(double));
bin_counts =(int*)malloc((nbins-1) * sizeof(int));
//create bins from intervals
for(j=0; j<=(nbins); j++)
{
bins[j] = m + (j*interval);
}
//generate "bin_counts[]" with all 0's
for(y=0; y<=(nbins-1); y++)
{
bin_counts[y] = 0;
}
//Generate "N" random numbers in "randoms[]" array
for(k =0; k<=(N-1); k++)
{
randoms[k] = rand() % (temp_M + temp_m);
printf("The random number is %d \n", randoms[k]);
}
//histogram code
for(i=0; i<=(N-1); i++)
{
for(x=0; x<=(nbins-1); x++)
{
if( (double)randoms[i]<=bins[x+1] && (double)randoms[i]>=bins[x] )
{
bin_counts[x] = bin_counts[x] + 1;
}
}
}
free(bins);
free(bin_counts);
}
</code></pre>
| 9,073,290 | 1 | 5 | null |
2012-01-31 01:08:32.57 UTC
| null |
2012-01-31 01:28:01.13 UTC
| null | null | null | null | 1,179,234 | null | 1 | 5 |
c|linux|free|glibc
| 39,613 |
<pre><code>bins =(double*)malloc(nbins * sizeof(double));
bin_counts =(int*)malloc((nbins-1) * sizeof(int));
//create bins from intervals
for(j=0; j<=(nbins); j++)
{
bins[j] = m + (j*interval);
}
//generate "bin_counts[]" with all 0's
for(y=0; y<=(nbins-1); y++)
{
bin_counts[y] = 0;
}
</code></pre>
<p>You are overstepping your arrays, you allocate place for <code>nbins</code> doubles but write to <code>nbins+1</code> locations, and use <code>nbins</code> locations for <code>bin_counts</code> but have only allocated <code>nbins-1</code>.</p>
|
18,605,563 |
href must not reload
|
<p>I am testing the following link:</p>
<pre><code><a href="#">Link</a>
</code></pre>
<p>But, as expected, it reloads my current page. How can I prevent it from reloading the page, but maintaining the <em>-a-</em> tag assigned to it?</p>
<p>Thanks ;)</p>
| 18,605,588 | 5 | 1 | null |
2013-09-04 04:46:00.98 UTC
| 8 |
2021-12-24 13:23:48.48 UTC
| null | null | null | null | 2,714,670 | null | 1 | 46 |
html|hyperlink
| 100,255 |
<p>If you don't want it to behave like a link, then don't use a link tag. Doing so hurt accessibility of a page, and you don't want that. There are other ways of browsing a website than a browser (think about the screen readers), which relies on the semantics of the page elements. Use a <code>span</code> if you simply want to apply a style.</p>
<p>If you still want to use an anchor, you can use this - </p>
<pre><code><a href="#" onclick="return false;">Link</a>
</code></pre>
<p>This will prevent your page reloading.</p>
|
27,582,757 |
Catch duplicate entry Exception
|
<p>How can i catch this Exception : </p>
<pre><code>com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:
Duplicate entry '22-85' for key 'ID_CONTACT'
</code></pre>
| 27,583,544 | 9 | 5 | null |
2014-12-20 17:48:03.713 UTC
| 9 |
2021-04-04 11:33:13.273 UTC
|
2018-04-05 10:05:52.89 UTC
| null | 3,128,926 | null | 1,383,538 | null | 1 | 35 |
java|mysql|hibernate|jpa|sqlexception
| 115,975 |
<p>I use spring so we resolve it by <code>org.springframework.dao.DataIntegrityViolationException</code></p>
<pre><code>try {
ao_history_repository.save(new AoHistory(..));
} catch (DataIntegrityViolationException e) {
System.out.println("history already exist");
}
</code></pre>
<p>But as <a href="https://stackoverflow.com/a/58239601/1383538">@KevinGuancheDarias</a> mention it:</p>
<blockquote>
<p>Please note that while this works. <strong>I suggest to solve the problem by
issuing a findBy before the save</strong>, as this is messy, and I think it's
not warranted that it will work in future versions, may even break
without notification.</p>
</blockquote>
|
15,047,775 |
Do Hask or Agda have equalisers?
|
<p>I was somewhat undecided as to whether this was a math.SE question or an SO one, but I suspect that mathematicians in general are fairly unlikely to know or care much about this category in particular, whereas Haskell programmers might well do.</p>
<p>So, we know that <strong>Hask</strong> has products, more or less (I'm working with idealised-Hask, here, of course). I'm interested in whether or not it has equalisers (in which case it would have all finite limits).</p>
<p>Intuitively it seems not, since you can't do separation like you can on sets, and so subobjects seem hard to construct in general. But for any specific case you'd like to come up with, it seems like you'd be able to hack it by working out the equaliser in <strong>Set</strong> and counting it (since after all, every Haskell type is countable and every countable set is isomorphic either to a finite type or the naturals, both of which Haskell has). So I can't see how I'd go about finding a counterexample.</p>
<p>Now, Agda seems a bit more promising: there it <em>is</em> relatively easy to form subobjects. Is the obvious sigma type <code>Σ A (λ x → f x == g x)</code> an equaliser? If the details don't work, is it <em>morally</em> an equaliser?</p>
| 15,136,620 | 2 | 3 | null |
2013-02-24 01:44:19 UTC
| 13 |
2013-02-28 14:26:40.697 UTC
| null | null | null | null | 812,053 | null | 1 | 36 |
haskell|agda|category-theory
| 1,615 |
<p><strong>tl;dr the proposed candidate is not quite an equaliser, but its irrelevant counterpart is</strong></p>
<p>The candidate for an equaliser in Agda looks good. So let's just try it. We'll need some basic kit. Here are my refusenik ASCII dependent pair type and homogeneous intensional equality.</p>
<pre><code>record Sg (S : Set)(T : S -> Set) : Set where
constructor _,_
field
fst : S
snd : T fst
open Sg
data _==_ {X : Set}(x : X) : X -> Set where
refl : x == x
</code></pre>
<p>Here's your candidate for an equaliser for two functions</p>
<pre><code>Q : {S T : Set}(f g : S -> T) -> Set
Q {S}{T} f g = Sg S \ s -> f s == g s
</code></pre>
<p>with the <code>fst</code> projection sending <code>Q f g</code> into <code>S</code>.</p>
<p>What it says: an element of <code>Q f g</code> is an element <code>s</code> of the source type, together with a proof that <code>f s == g s</code>. But is this an equaliser? Let's try to make it so.</p>
<p>To say what an equaliser is, I should define function composition.</p>
<pre><code>_o_ : {R S T : Set} -> (S -> T) -> (R -> S) -> R -> T
(f o g) x = f (g x)
</code></pre>
<p>So now I need to show that any <code>h : R -> S</code> which identifies <code>f o h</code> and <code>g o h</code> must factor through the candidate <code>fst : Q f g -> S</code>. I need to deliver both the other component, <code>u : R -> Q f g</code> and the proof that indeed <code>h</code> factors as <code>fst o u</code>. Here's the picture: <code>(Q f g , fst)</code> is an equalizer if whenever the diagram commutes without <code>u</code>, there is a unique way to add <code>u</code> with the diagram still commuting.</p>
<p><img src="https://i.stack.imgur.com/odrtv.jpg" alt="equaliser diagram"></p>
<p>Here goes existence of the mediating <code>u</code>.</p>
<pre><code>mediator : {R S T : Set}(f g : S -> T)(h : R -> S) ->
(q : (f o h) == (g o h)) ->
Sg (R -> Q f g) \ u -> h == (fst o u)
</code></pre>
<p>Clearly, I should pick the same element of <code>S</code> that <code>h</code> picks.</p>
<pre><code>mediator f g h q = (\ r -> (h r , ?0)) , ?1
</code></pre>
<p>leaving me with two proof obligations</p>
<pre><code>?0 : f (h r) == g (h r)
?1 : h == (\ r -> h r)
</code></pre>
<p>Now, <code>?1</code> can just be <code>refl</code> as Agda's definitional equality has the eta-law for functions. For <code>?0</code>, we are blessed by <code>q</code>. Equal functions respect application</p>
<pre><code>funq : {S T : Set}{f g : S -> T} -> f == g -> (s : S) -> f s == g s
funq refl s = refl
</code></pre>
<p>so we may take <code>?0 = funq q r</code>.</p>
<p>But let us not celebrate prematurely, for the existence of a mediating morphism is not sufficient. We require also its uniqueness. And here the wheel is likely to go wonky, because <code>==</code> is <em>intensional</em>, so uniqueness means there's only ever one way to <em>implement</em> the mediating map. But then, our assumptions are also intensional...</p>
<p>Here's our proof obligation. We must show that any other mediating morphism is equal to the one chosen by <code>mediator</code>.</p>
<pre><code>mediatorUnique :
{R S T : Set}(f g : S -> T)(h : R -> S) ->
(qh : (f o h) == (g o h)) ->
(m : R -> Q f g) ->
(qm : h == (fst o m)) ->
m == fst (mediator f g h qh)
</code></pre>
<p>We can immediately substitute via <code>qm</code> and get</p>
<pre><code>mediatorUnique f g .(fst o m) qh m refl = ?
? : m == (\ r -> (fst (m r) , funq qh r))
</code></pre>
<p>which looks good, because Agda has eta laws for records, so we know that</p>
<pre><code>m == (\ r -> (fst (m r) , snd (m r)))
</code></pre>
<p>but when we try to make <code>? = refl</code>, we get the complaint</p>
<pre><code>snd (m _) != funq qh _ of type f (fst (m _)) == g (fst (m _))
</code></pre>
<p>which is annoying, because identity proofs are unique (in the standard configuration). Now, you can get out of this by postulating extensionality and using a few other facts about equality</p>
<pre><code>postulate ext : {S T : Set}{f g : S -> T} -> ((s : S) -> f s == g s) -> f == g
sndq : {S : Set}{T : S -> Set}{s : S}{t t' : T s} ->
t == t' -> _==_ {Sg S T} (s , t) (s , t')
sndq refl = refl
uip : {X : Set}{x y : X}{q q' : x == y} -> q == q'
uip {q = refl}{q' = refl} = refl
? = ext (\ s -> sndq uip)
</code></pre>
<p>but that's overkill, because the only problem is the annoying equality proof mismatch: the computable parts of the implementations match on the nose. So the fix is to work with <em>irrelevance</em>. I replace <code>Sg</code> by the <code>Ex</code>istential quantifier, whose second component is marked as irrelevant with a dot. Now it matters not which proof we use that the witness is good.</p>
<pre><code>record Ex (S : Set)(T : S -> Set) : Set where
constructor _,_
field
fst : S
.snd : T fst
open Ex
</code></pre>
<p>and the new candidate equaliser is</p>
<pre><code>Q : {S T : Set}(f g : S -> T) -> Set
Q {S}{T} f g = Ex S \ s -> f s == g s
</code></pre>
<p>The entire construction goes through as before, except that in the last obligation</p>
<pre><code>? = refl
</code></pre>
<p>is accepted!</p>
<p>So yes, even in the intensional setting, eta laws and the ability to mark fields as irrelevant give us equalisers.</p>
<p><strong>No undecidable typechecking was involved in this construction.</strong></p>
|
38,270,661 |
Displaying a YouTube video with iframe full width of page
|
<p>I've put a video in my site using an <code>iframe</code> from YouTube, while the <code>iframe</code> is full width (<code>100%</code>) the video is very small (height) within the frame. How do I make it fit the width of the container? </p>
<p>Code: </p>
<pre><code><iframe width="100%" height="100%" src="https://www.youtube.com/embed/5m_ZUQTW13I" frameborder="0" allowfullscreen></iframe>
</code></pre>
<p>See screenshot</p>
<p><a href="https://i.stack.imgur.com/4dzZt.png" rel="noreferrer"><img src="https://i.stack.imgur.com/4dzZt.png" alt="enter image description here"></a></p>
| 38,270,745 | 3 | 5 | null |
2016-07-08 15:42:11.313 UTC
| 10 |
2021-04-23 02:13:22.743 UTC
|
2017-07-05 00:24:44.973 UTC
| null | 5,526,060 | null | 2,953,989 | null | 1 | 45 |
html|css|iframe|youtube
| 91,494 |
<p>To make a You Tube Video full width and preserve the height (and keep it responsive) you can use the following setup.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.videoWrapper {
position: relative;
padding-bottom: 56.25%;
/* 16:9 */
padding-top: 25px;
height: 0;
}
.videoWrapper iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="videoWrapper">
<!-- Copy & Pasted from YouTube -->
<iframe width="560" height="349" src="https://www.youtube.com/embed/n_dZNLr2cME?rel=0&hd=1" frameborder="0" allowfullscreen></iframe>
</div></code></pre>
</div>
</div>
</p>
|
8,217,742 |
One to Many MySQL
|
<blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/8216865/mysql-relationships">MySQL Relationships</a> </p>
</blockquote>
<p>I am trying to create a one to many relationship in MySQL with foreign keys.</p>
<p>Two tables, <code>user</code> and <code>location</code>. Each <code>user</code> can have many <code>location</code>s, but each <code>location</code> can have only one <code>user</code>. </p>
<p>How do I configure this? I am using HeidiSQL if that helps, though I can input code as well.</p>
| 8,217,964 | 2 | 3 | null |
2011-11-21 19:57:58.577 UTC
| 4 |
2020-12-11 11:02:32.87 UTC
|
2017-05-23 12:09:33.837 UTC
| null | -1 | null | 801,858 | null | 1 | 19 |
mysql|database-design|foreign-keys|foreign-key-relationship
| 86,713 |
<p>MySQL does not know, nor does it need to know if a relationship is 1-1, or 1-many.<br />
No SQL supports many-many relationships, all require a intermediate table which splits a many-many relationship into 2 separate 1-many.</p>
<p>The difference is in the logic that controls the relationships, which is in the code that you write.<br />
A 1-1 relationship is maintained by having the tables share the same primary key (PK).<br />
With the secondary table declaring that PK as a foreign key pointing to the other tables PK.</p>
<pre><code>Table chinese_mother (
id integer primary key,
name....
Table chinese_child (
id integer primary key,
name ....
....,
foreign key (id) references chinese_mother.id
</code></pre>
<p>The direction of the relationship <code>1 -> many</code> vs <code>many <- 1</code> is determined by the location of the link field.</p>
<p>Usually every table has a unique <code>id</code> and the link field is called <code>tablename_id</code>.<br />
The table that has the link field in it is the <code>many</code> side of the relationship, the other table is on the <code>1</code> side.</p>
<blockquote>
<p>Each user can have many locations, but each location can have only one user.</p>
</blockquote>
<pre><code>Table user
id: primary key
name......
.....
Table location
id: primary key
user_id foreign key references (user.id)
x
y
.......
</code></pre>
<p>By placing the link field in the <code>location</code> table, you force things so that a location can only have 1 user. However a user can have many locations.</p>
|
23,594,266 |
r package KernSmooth copyright
|
<p>I am new to R. Was able to install a package called KernSmooth using R console. Is there a place where I can figure out the copyright info for KernSmooth? Below is what I did. </p>
<pre><code>> install.packages("KernSmooth")
--- Please select a CRAN mirror for use in this session ---
trying URL 'http://mirrors.nics.utk.edu/cran/bin/macosx/mavericks/contrib/3.1/KernSmooth_2.23-12.tgz'
Content type 'application/x-gzip' length 91267 bytes (89 Kb)
opened URL
==================================================
downloaded 89 Kb
The downloaded binary packages are in
/var/folders/yd/y63jsdgn2sx1jf9b7vl7ksqc0000gn/T//RtmpE1vO1I/downloaded_packages
</code></pre>
| 25,799,293 | 4 | 12 | null |
2014-05-11 15:10:52.213 UTC
| 3 |
2018-06-26 19:54:48.547 UTC
|
2016-05-22 07:33:49.353 UTC
| null | 4,533,771 | null | 3,621,202 | null | 1 | 15 |
r
| 70,979 |
<p>If you just want to view the copyright, after you install the package, do a library() call</p>
<pre><code>> library(KernSmooth)
KernSmooth 2.23 loaded
Copyright M. P. Wand 1997-2009
</code></pre>
<p><a href="https://youtu.be/xzvGA2zKLDc" rel="noreferrer">video explanation</a> (if needed)</p>
|
5,046,100 |
Prevent access to files in a certain folder
|
<p>I have a folder with a lot of <code>.php</code> files. I would like to deny access to them (using <code>.htaccess</code>). I know an option is to move this folder outside <code>public_html</code>, but this is not possible in this situation.</p>
<p>Is is possible to block access to a whole folder?</p>
| 5,046,130 | 4 | 0 | null |
2011-02-18 20:17:45.957 UTC
| 2 |
2019-12-03 19:48:34.637 UTC
|
2016-04-12 22:36:49.683 UTC
| null | 5,299,236 | null | 618,622 | null | 1 | 26 |
apache|.htaccess
| 60,065 |
<p>Add this to the <code>.htaccess</code> file:</p>
<pre><code>order deny,allow
deny from all
</code></pre>
|
5,465,245 |
Create a nullable column using SQL Server SELECT INTO?
|
<p>When I create a temp table using a <code>select into</code> in SQL Server, is there a way to specify that a column should be nullable? I have a multi-step process where I'm making a temp table by selecting a lot of columns (which is why I'm not doing a <code>create table #tmp (...)</code>). After I make that temp table, I'm updating some columns and some of those updates might null out a field.</p>
<p>I know I could do an <code>alter table alter column</code> statement to achieve what I want, but I'm curious about whether there's a way to specify this in the <code>select</code> itself. I know you can inline <code>cast</code> your columns to get the desired datatype, but I can't see how you specify nullability.</p>
| 5,465,288 | 5 | 0 | null |
2011-03-28 21:23:49.697 UTC
| 4 |
2020-06-15 15:01:16.57 UTC
| null | null | null | null | 83,144 | null | 1 | 36 |
sql-server|tsql
| 67,251 |
<p>Nullability is inherited from the source column.</p>
<p>You can lose or gain nullability with an expression:</p>
<p>Example (constant literals appear to be problematic - need a good NOOP function which can return NULL):</p>
<pre><code>CREATE TABLE SO5465245_IN
(
a INT NOT NULL
,b INT NULL
) ;
GO
SELECT COALESCE(a, NULL) AS a
,ISNULL(b, 0) AS b
,COALESCE(10, NULL) AS c1
,COALESCE(ABS(10), NULL) AS c2
,CASE WHEN COALESCE(10, NULL) IS NOT NULL THEN COALESCE(10, NULL) ELSE NULL END AS c3
INTO SO5465245_OUT
FROM SO5465245_IN ;
GO
SELECT TABLE_NAME
,COLUMN_NAME
,IS_NULLABLE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME LIKE 'SO5465245%'
ORDER BY TABLE_NAME
,ORDINAL_POSITION ;
GO
DROP TABLE SO5465245_IN ;
GO
DROP TABLE SO5465245_OUT ;
GO
</code></pre>
|
5,404,342 |
ASP.NET XML Parsing Error: no element found Line Number 1, Column 1 Error
|
<p>Hey I found a weird temperamental page which randomly gives me the following error</p>
<pre>XML Parsing Error: no element found
Location: http://kj2011/site_2011/nonprofit-database/overview.aspx
Line Number 1, Column 1:</pre>
<p>This page was fine for like 2 weeks but as of yesterday I randomly get the above error. I was to delete the pages and recreate the error is gone but would come back again few hours later. I have some other templates</p>
<p>i.e <code>http://kj2011/site_2011/nonprofit-database/financial.aspx</code></p>
<p>Which has the same Master File and User Controls but never gets the error just the overview.aspx page.</p>
<p>Any Ideas ?</p>
| 5,553,459 | 12 | 1 | null |
2011-03-23 11:13:01.623 UTC
| 2 |
2020-07-14 08:51:24.247 UTC
|
2011-03-29 15:47:33.08 UTC
| null | 102,112 | null | 215,541 | null | 1 | 11 |
asp.net|xml
| 50,358 |
<p>This was an issue with an external DLL, which created a page called view.aspx in the same folder which caused an issue with our overview.aspx. We just renamed the page and the issue went away.</p>
|
5,129,624 |
Convert JS date time to MySQL datetime
|
<p>Does anyone know how to convert JS dateTime to MySQL datetime? Also is there a way to add a specific number of minutes to JS datetime and then pass it to MySQL datetime?</p>
| 11,150,727 | 23 | 0 | null |
2011-02-26 20:44:53.363 UTC
| 59 |
2022-09-10 10:04:10.227 UTC
| null | null | null | null | 382,906 | null | 1 | 173 |
javascript|mysql
| 290,104 |
<pre class="lang-js prettyprint-override"><code>var date;
date = new Date();
date = date.getUTCFullYear() + '-' +
('00' + (date.getUTCMonth()+1)).slice(-2) + '-' +
('00' + date.getUTCDate()).slice(-2) + ' ' +
('00' + date.getUTCHours()).slice(-2) + ':' +
('00' + date.getUTCMinutes()).slice(-2) + ':' +
('00' + date.getUTCSeconds()).slice(-2);
console.log(date);
</code></pre>
<p>or even shorter:</p>
<pre class="lang-js prettyprint-override"><code>new Date().toISOString().slice(0, 19).replace('T', ' ');
</code></pre>
<p>Output:</p>
<pre class="lang-js prettyprint-override"><code>2012-06-22 05:40:06
</code></pre>
<p>For more advanced use cases, including controlling the timezone, consider using <a href="http://momentjs.com/">http://momentjs.com/</a>:</p>
<pre class="lang-js prettyprint-override"><code>require('moment')().format('YYYY-MM-DD HH:mm:ss');
</code></pre>
<p>For a lightweight alternative to <a href="/questions/tagged/momentjs" class="post-tag" title="show questions tagged 'momentjs'" rel="tag">momentjs</a>, consider <a href="https://github.com/taylorhakes/fecha">https://github.com/taylorhakes/fecha</a></p>
<pre class="lang-js prettyprint-override"><code>require('fecha').format('YYYY-MM-DD HH:mm:ss')
</code></pre>
|
16,683,944 |
AndroidAnnotations Nothing Generated, Empty Activity
|
<p>I am trying to create a project using AndroidAnnotations in Android Studio. When I build and run the project, everything seems to compile fine, yet I get nothing but a blank activity for the app. In addition, it does not appear that anything is generated by AndroidAnnotations. </p>
<p>I have added <code>androidannotations-api-2.7.1.jar</code> as a dependency for my project, and enabled annotation processing with the processor path the path to <code>androidannotations-2.7.1.jar</code>, which is in a separate folder from <code>androidannotations-api-2.7.1.jar</code>. I have checked store generated sources relative to module content root, and tried many different directories for the sources -- from <code>generated</code>, to <code>gen/aa</code>, to (currently) <code>build/source/aa</code> to match where it seems the generated files are created in Android Studio. Nothing has worked. I have changed the activity name in the manifest to <code>Activity_</code>, and set the configuration to launch this when the project is run. </p>
<p>The only other dependencies I have are android-support-v4 and ActionBarSherlock. I have tried with both of these disabled, to no result. I initially planned to use Roboguice in conjunction with AndroidAnnotations, but have disabled it for the time being to try to focus on this issue. </p>
<p>I am also using, or trying to use, Gradle. This is currently my <code>build.gradle</code>: </p>
<pre><code>buildscript {
repositories {
maven { url 'http://repo1.maven.org/maven2' }
}
dependencies {
classpath 'com.android.tools.build:gradle:0.4'
}
}
apply plugin: 'android'
dependencies {
compile files('libs/android-support-v4.jar')
compile files('libs/actionbarsherlock-4.3.1.jar')
compile files('libs/androidannotations-api-2.7.1.jar')
}
android {
compileSdkVersion 17
buildToolsVersion "17.0.0"
defaultConfig {
minSdkVersion 7
targetSdkVersion 17
}
}
</code></pre>
<p>However, I haven't really figured out how Gradle works, so I mostly just manually added the dependencies as you would a normal project, then put the compile lines in Gradle so the project would compile properly. I know this is probably not the correct way to use it.</p>
<p>My activity and its layout are fairly standard, I just copied them from the official guide to get started with AndroidAnnotations.</p>
<p>UPDATE: So I just went back to Maven to test the build with that, and I noticed something strange. It seems that even with how I have it set up in Maven, nothing is generated. However, with the Maven build I can run the project without changing the activity name in the manifest to <code>Activity_</code> and the project will compile and run correctly. This is very odd and seems like it could either further confuse the problem, or simplify it if it is indicative of something with Gradle as well.</p>
| 16,802,216 | 6 | 1 | null |
2013-05-22 05:16:03.787 UTC
| 21 |
2014-01-31 23:07:41.217 UTC
|
2013-05-24 06:13:08.077 UTC
| null | 1,277,679 | null | 1,277,679 | null | 1 | 10 |
android|gradle|android-studio|android-annotations
| 12,986 |
<p>This is similar to robotoaster's response, but it works in 0.4.1 and it places the generated java source files in a new directory (consistent with the other generated source folders), which allows Android Studio to see the source and stop complaining. It also works with more annotation processors. Just add your annotation processors to the "apt" configuration.</p>
<pre><code>buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.4.1'
}
}
apply plugin: 'android'
repositories {
mavenCentral()
}
ext.daggerVersion = '1.0.0';
ext.androidAnnotationsVersion = '2.7.1';
configurations {
apt
}
dependencies {
apt "com.googlecode.androidannotations:androidannotations:${androidAnnotationsVersion}"
compile "com.googlecode.androidannotations:androidannotations-api:${androidAnnotationsVersion}"
apt "com.squareup.dagger:dagger-compiler:${daggerVersion}"
compile "com.squareup.dagger:dagger:${daggerVersion}"
}
android {
compileSdkVersion 17
buildToolsVersion "17.0.0"
defaultConfig {
minSdkVersion 10
targetSdkVersion 17
}
}
android.applicationVariants.all { variant ->
aptOutput = file("${project.buildDir}/source/apt_generated/${variant.dirName}")
println "****************************"
println "variant: ${variant.name}"
println "manifest: ${variant.processResources.manifestFile}"
println "aptOutput: ${aptOutput}"
println "****************************"
variant.javaCompile.doFirst {
println "*** compile doFirst ${variant.name}"
aptOutput.mkdirs()
variant.javaCompile.options.compilerArgs += [
'-processorpath', configurations.apt.getAsPath(),
'-AandroidManifestFile=' + variant.processResources.manifestFile,
'-s', aptOutput
]
}
}
</code></pre>
<p><b>UPDATE</b>: This still works to compile, but with Android Studio 0.1.1 you can no longer edit your project structure with the UI<s>, so you can't tell AS to look at the new source folder. I'd like to add the folder to a sourceSet, but variants don't seem to actually have their own sourceSets so I'm not sure yet where to put it</s>.</p>
<p><b>UPDATE 2</b>: You can get Android Studio 0.1.1 to recognize the apt-generated source files by right-clicking on build/source/apt_generated/debug in the project browser and selecting <i>Mark Directory As->Source Root</i></p>
<p><b>UPDATE 3</b>: Since gradle plugin 0.5.5 the <code>android.applicationVariants.each</code> does not work anymore. Use <code>android.applicationVariants.all</code> instead. See the changelog at <a href="http://tools.android.com/tech-docs/new-build-system" rel="noreferrer">android.com</a>:
<em>access to the variants container don't force creating the task.
This means android.[application|Library|Test]Variants will be empty during the evaluation phase. To use it, use .all instead of .each</em></p>
|
29,699,451 |
Appending element into an array of strings in C
|
<p>I have an array of strings with a given size, without using any memory allocation, how do I append something into it?</p>
<p>Say I run the code, its waiting for something you want to enter, you enter <code>"bond"</code>, how do I append this into an array ? A[10] ? </p>
| 29,699,688 | 5 | 5 | null |
2015-04-17 12:37:33.86 UTC
| 4 |
2022-02-20 17:44:51.74 UTC
|
2022-02-20 17:44:51.74 UTC
| null | 2,877,241 | null | 3,928,326 | null | 1 | 9 |
c|append|c-strings|strcpy|strcat
| 61,657 |
<p>If the array declared like</p>
<pre><code>char A[10];
</code></pre>
<p>then you can assign string "bond" to it the following way</p>
<pre><code>#include <string.h>
//...
strcpy( A, "bond" );
</code></pre>
<p>If you want to append the array with some other string then you can write</p>
<pre><code>#include <string.h>
//...
strcpy( A, "bond" );
strcat( A, " john" );
</code></pre>
|
12,470,156 |
AutoMapper Custom Type Converter not working
|
<p>I am using <a href="https://github.com/TroyGoode/PagedList">Troy Goode's PagedList</a> to provide paging information in my WebApi. His package returns an IPagedList that implements IEnumerable but also contains custom properties such as IsLastPage, PageNumber, PageCount, etc.</p>
<p>When you try to return this class from a WebApi controller method (such as the GET), the Enumerable is serialized, but the custom properties are not. So, I thought I would use AutoMapper and write a custom type converter to convert to a class such as this:</p>
<pre><code>public class PagedViewModel<T>
{
public int FirstItemOnPage { get; set; }
public bool HasNextPage { get; set; }
public bool HasPreviousPage { get; set; }
public bool IsFirstPage { get; set; }
public bool IsLastPage { get; set; }
public int LastItemOnPage { get; set; }
public int PageCount { get; set; }
public int PageNumber { get; set; }
public int PageSize { get; set; }
public int TotalItemCount { get; set; }
public IEnumerable<T> rows { get; set; }
}
</code></pre>
<p>Since I move the Enumerable into a distinct property, the serialization handles it perfectly. So, I sat down and wrote a custom type converter like this:</p>
<pre><code>public class PagedListTypeConverter<T> : ITypeConverter<IPagedList<T>, PagedViewModel<T>>
{
public PagedViewModel<T> Convert(ResolutionContext context)
{
var source = (IPagedList<T>)context.SourceValue;
return new PagedViewModel<T>()
{
FirstItemOnPage = source.FirstItemOnPage,
HasNextPage = source.HasNextPage,
HasPreviousPage = source.HasPreviousPage,
IsFirstPage = source.IsFirstPage,
IsLastPage = source.IsLastPage,
LastItemOnPage = source.LastItemOnPage,
PageCount = source.PageCount,
PageNumber = source.PageNumber,
PageSize = source.PageSize,
TotalItemCount = source.TotalItemCount,
rows = source
};
}
}
</code></pre>
<p>And then set it up in my configuration like this:</p>
<pre><code>Mapper.CreateMap<IPagedList<Department>, PagedViewModel<Department>>().ConvertUsing(new PagedListTypeConverter<Department>());
</code></pre>
<p>But, when I try to call it like this:</p>
<pre><code>var x = Mapper.Map<IPagedList<Department>, PagedViewModel<Department>>(departments);
</code></pre>
<p>I get this error:</p>
<blockquote>
<p>Missing type map configuration or unsupported mapping.</p>
<p>Mapping types: IPagedList<code>1 -> PagedViewModel</code>1
PagedList.IPagedList<code>1[[Provision.DomainObjects.Department,
Provision.DomainObjects, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null]] ->
Provision.DomainObjects.PagedViewModel</code>1[[Provision.DomainObjects.Department,
Provision.DomainObjects, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null]]</p>
<p>Destination path: PagedViewModel`1</p>
<p>Source value:
PagedList.StaticPagedList`1[Provision.DomainObjects.Department]</p>
</blockquote>
<p>How can I make this work?</p>
| 12,538,611 | 1 | 0 | null |
2012-09-18 03:54:32.117 UTC
| 8 |
2012-09-21 21:47:43.537 UTC
|
2012-09-20 13:28:44.227 UTC
| null | 332,022 | null | 332,022 | null | 1 | 9 |
automapper|automapper-2
| 2,842 |
<p>After pulling my hair out, I finally figured this one out. There isn't anything at all wrong with the code. It turned out to be a threading issue where the configured mappings were getting cleared out. The code above is the proper way to do what I wanted. I am leaving this here so that I can point another question to it for others who need to do the same thing.</p>
|
12,345,292 |
How do enable a .Net web-API to accept g-ziped posts
|
<p>I have a fairly bog standard .net MVC 4 Web API application. </p>
<pre><code> public class LogsController : ApiController
{
public HttpResponseMessage PostLog(List<LogDto> logs)
{
if (logs != null && logs.Any())
{
var goodLogs = new List<Log>();
var badLogs = new List<LogBad>();
foreach (var logDto in logs)
{
if (logDto.IsValid())
{
goodLogs.Add(logDto.ToLog());
}
else
{
badLogs.Add(logDto.ToLogBad());
}
}
if (goodLogs.Any())
{
_logsRepo.Save(goodLogs);
}
if(badLogs.Any())
{
_logsBadRepo.Save(badLogs);
}
}
return new HttpResponseMessage(HttpStatusCode.OK);
}
}
</code></pre>
<p>This all work fine, I have devices that are able to send me their logs and it works well. However now we are starting to have concerns about the size of the data being transferred, and we want to have a look at accepting post that have been compressed using GZIP?</p>
<p>How would I go about do this? Is it setting in IIS or could I user Action Filters?</p>
<p><strong>EDIT 1</strong></p>
<p>Following up from Filip's answer my thinking is that I need to intercept the processing of the request before it gets to my controller. If i can catch the request before the Web api framework attempts to parse the body of the request into my business object, which fails because the body of the request is still compressed. Then I can decompress the body of the request and then pass the request back into the processing chain, and hopefully the Web Api framework will be able to parse the (decompressed) body into my business objects. </p>
<p>It looks Like using the DelagatingHandler is the way to go. It allows me access to the request during the processing, but before my controller. So I tried the following? </p>
<pre><code> public class gZipHandler : DelegatingHandler
{
protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
string encodingType = request.Headers.AcceptEncoding.First().Value;
request.Content = new DeCompressedContent(request.Content, encodingType);
return base.SendAsync(request, cancellationToken);
}
}
public class DeCompressedContent : HttpContent
{
private HttpContent originalContent;
private string encodingType;
public DeCompressedContent(HttpContent content, string encodType)
{
originalContent = content;
encodingType = encodType;
}
protected override bool TryComputeLength(out long length)
{
length = -1;
return false;
}
protected override Task<Stream> CreateContentReadStreamAsync()
{
return base.CreateContentReadStreamAsync();
}
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
Stream compressedStream = null;
if (encodingType == "gzip")
{
compressedStream = new GZipStream(stream, CompressionMode.Decompress, leaveOpen: true);
}
return originalContent.CopyToAsync(compressedStream).ContinueWith(tsk =>
{
if (compressedStream != null)
{
compressedStream.Dispose();
}
});
}
}
</code></pre>
<p>}</p>
<p>This seems to be working ok. The SendAsync method is being called before my controller and the constructor for the DecompressedContent is being called. However the SerializeToStreamAsync is never being called so I added the CreateContentReadStreamAsync to see if that's where the decompressing should be happening, but that's not being called either. </p>
<p>I fell like I am close to the solution, but just need a little bit extra to get it over the line. </p>
| 14,990,735 | 4 | 1 | null |
2012-09-10 04:18:32.5 UTC
| 9 |
2017-03-31 01:47:23.103 UTC
|
2013-02-20 22:12:09.95 UTC
| null | 123,378 | null | 507,669 | null | 1 | 16 |
c#|asp.net-web-api
| 13,435 |
<p>I had the same requirement to POST gzipped data to a .NET web api controller. I came up with this solution:</p>
<pre><code>public class GZipToJsonHandler : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
CancellationToken cancellationToken)
{
// Handle only if content type is 'application/gzip'
if (request.Content.Headers.ContentType == null ||
request.Content.Headers.ContentType.MediaType != "application/gzip")
{
return base.SendAsync(request, cancellationToken);
}
// Read in the input stream, then decompress in to the outputstream.
// Doing this asynronously, but not really required at this point
// since we end up waiting on it right after this.
Stream outputStream = new MemoryStream();
Task task = request.Content.ReadAsStreamAsync().ContinueWith(t =>
{
Stream inputStream = t.Result;
var gzipStream = new GZipStream(inputStream, CompressionMode.Decompress);
gzipStream.CopyTo(outputStream);
gzipStream.Dispose();
outputStream.Seek(0, SeekOrigin.Begin);
});
// Wait for inputstream and decompression to complete. Would be nice
// to not block here and work async when ready instead, but I couldn't
// figure out how to do it in context of a DelegatingHandler.
task.Wait();
// This next section is the key...
// Save the original content
HttpContent origContent = request.Content;
// Replace request content with the newly decompressed stream
request.Content = new StreamContent(outputStream);
// Copy all headers from original content in to new one
foreach (var header in origContent.Headers)
{
request.Content.Headers.Add(header.Key, header.Value);
}
// Replace the original content-type with content type
// of decompressed data. In our case, we can assume application/json. A
// more generic and reuseable handler would need some other
// way to differentiate the decompressed content type.
request.Content.Headers.Remove("Content-Type");
request.Content.Headers.Add("Content-Type", "application/json");
return base.SendAsync(request, cancellationToken);
}
}
</code></pre>
<p>Using this approach, the existing controller, which normally works with JSON content and automatic model binding, continued to work without any changes.</p>
<p>I'm not sure why the other answer was accepted. It provides a solution for handling the responses (which is common), but not requests (which is uncommon). The Accept-Encoding header is used to specify acceptable response encodings, and is not related to request encodings.</p>
|
12,586,132 |
Java Regex matching between curly braces
|
<p>I need to parse a log file and get the times and associated function call string
This is stored in the log file as so: {"time" : "2012-09-24T03:08:50", "message" : "Call() started"}</p>
<p>There will be multiple logged time function calls in between other string characters, so hence I am hoping to use regex to go through the file and grab all of these</p>
<p>I would like to grab the entire logged information including the curly brackets</p>
<p>I have tried the following</p>
<pre><code>Pattern logEntry = Pattern.compile("{(.*?)}");
Matcher matchPattern = logEntry.matcher(file);
</code></pre>
<p>and</p>
<pre><code>Pattern.compile("{[^{}]*}");
Matcher matchPattern = logEntry.matcher(file);
</code></pre>
<p>I keep getting illegal repetition errors, please help! Thanks.</p>
| 12,586,201 | 5 | 0 | null |
2012-09-25 15:25:02.03 UTC
| 7 |
2016-03-02 06:57:21.397 UTC
| null | null | null | null | 1,224,079 | null | 1 | 19 |
java|regex
| 58,827 |
<p>you need to escape '{' & '}' with a '\'</p>
<p>so: <code>"{(.*?)}"</code> becomes: <code>"\\{(.*?)\\}"</code></p>
<p>where you have to escape the '\' with another '\' first</p>
<p>see: <a href="http://www.regular-expressions.info/reference.html" rel="noreferrer">http://www.regular-expressions.info/reference.html</a> for a comprehensive list of characters that need escaping...</p>
|
12,427,449 |
ElasticSearch -- boosting relevance based on field value
|
<p>Need to find a way in ElasticSearch to boost the relevance of a document based on a particular value of a field. Specifically, there is a special field in all my documents where the higher the field value is, the more relevant the doc that contains it should be, regardless of the search.</p>
<p>Consider the following document structure:</p>
<pre><code>{
"_all" : {"enabled" : "true"},
"properties" : {
"_id": {"type" : "string", "store" : "yes", "index" : "not_analyzed"},
"first_name": {"type" : "string", "store" : "yes", "index" : "yes"},
"last_name": {"type" : "string", "store" : "yes", "index" : "yes"},
"boosting_field": {"type" : "integer", "store" : "yes", "index" : "yes"}
}
}
</code></pre>
<p>I'd like documents with a higher boosting_field value to be <strong>inherently more relevant</strong> than those with a lower boosting_field value. This is just a starting point -- the matching between the query and the other fields will also be taken into account in determining the final relevance score of each doc in the search. But, <strong>all else being equal, the higher the boosting field, the more relevant the document</strong>. </p>
<p>Anyone have an idea on how to do this?</p>
<p>Thanks a lot!</p>
| 12,430,664 | 4 | 1 | null |
2012-09-14 15:20:42.87 UTC
| 27 |
2019-09-19 13:39:27.05 UTC
|
2012-09-14 15:25:48.997 UTC
| null | 84,131 | null | 943,184 | null | 1 | 67 |
search|elasticsearch
| 48,267 |
<p>You can either boost at index time or query time. I usually prefer query time boosting even though it makes queries a little bit slower, otherwise I'd need to reindex every time I want to change my boosting factors, which usally need fine-tuning and need to be pretty flexible.</p>
<p>There are different ways to apply query time boosting using the elasticsearch query DSL: </p>
<ul>
<li><a href="http://www.elasticsearch.org/guide/reference/query-dsl/boosting-query.html">Boosting Query</a></li>
<li><a href="http://www.elasticsearch.org/guide/reference/query-dsl/custom-filters-score-query.html">Custom Filters Score Query</a></li>
<li><a href="http://www.elasticsearch.org/guide/reference/query-dsl/custom-boost-factor-query.html">Custom Boost Factor Query</a></li>
<li><a href="http://www.elasticsearch.org/guide/reference/query-dsl/custom-score-query.html">Custom Score Query</a></li>
</ul>
<p>The first three queries are useful if you want to give a specific boost to the documents which match specific queries or filters. For example, if you want to boost only the documents published during the last month. You could use this approach with your boosting_field but you'd need to manually define some boosting_field intervals and give them a different boost, which isn't that great. </p>
<p>The best solution would be to use a <a href="http://www.elasticsearch.org/guide/reference/query-dsl/custom-score-query.html">Custom Score Query</a>, which allows you to make a query and customize its score using a script. It's quite powerful, with the script you can directly modify the score itself. First of all I'd scale the boosting_field values to a value from 0 to 1 for example, so that your final score doesn't become a big number. In order to do that you need to predict what are more or less the minimum and the maximum values that the field can contain. Let's say minimum 0 and maximum 100000 for instance. If you scale the boosting_field value to a number between 0 and 1, then you can add the result to the actual score like this:</p>
<pre><code>{
"query" : {
"custom_score" : {
"query" : {
"match_all" : {}
},
"script" : "_score + (1 * doc.boosting_field.doubleValue / 100000)"
}
}
}
</code></pre>
<p>You can also consider to use the boosting_field as a boost factor (<code>_score *</code> rather than <code>_score +</code>), but then you'd need to scale it to an interval with minimum value 1 (just add a +1). </p>
<p>You can even tune the result in order the change its importance adding a weight to the value that you use to influence the score. You are going to need this even more if you need to combine multiple boosting factors together in order to give them a different weight. </p>
|
12,453,160 |
Remove empty lines in text using Visual Studio or VS Code
|
<p>How to remove empty lines in Visual Studio?</p>
| 12,453,161 | 13 | 3 | null |
2012-09-17 04:32:48.307 UTC
| 77 |
2022-04-09 17:29:05.267 UTC
|
2022-02-18 14:23:33.77 UTC
| null | 510,558 | null | 510,558 | null | 1 | 170 |
regex|visual-studio|visual-studio-2010|visual-studio-code|line
| 120,278 |
<p>It's very useful especially if you want to arrange or compare codes, thanks to the people who answer this question, I've got the answer from <a href="http://wblo.gs/VGx" rel="noreferrer">here</a> and would like to share it with Stackoverflow:</p>
<p><strong>Visual Studio</strong> (Visual Studio Code) has the ability to delete empty lines in replace operation using regular expressions.</p>
<ul>
<li><p>Click <kbd>Ctrl</kbd>-<kbd>H</kbd> (quick replace)</p>
</li>
<li><p>Tick "Use Regular Expressions"</p>
</li>
<li><p>In Find specify <code>^$\n</code></p>
</li>
<li><p>In Replace box delete everything.</p>
</li>
<li><p>Click "Replace All"</p>
</li>
</ul>
<p>All empty lines will be deleted.</p>
<p>Regular expression for empty line consists of</p>
<p>Beginning of line <code>^</code></p>
<p>End of line <code>$</code></p>
<p>Line break <code>\n</code></p>
<p>Note that normally in Windows an end of line indicated by 2 characters <a href="/questions/tagged/crlf" class="post-tag" title="show questions tagged 'crlf'" rel="tag">crlf</a> - Carriage Return (CR, ASCII 13, <code>\r</code>) Line Feed (LF, ASCII 10, <code>\n</code>).</p>
<p>A regex to remove blank lines that are/aren't <em>really</em> blank (i.e. they do/don't have spaces): <code>^:b*$\n</code></p>
<p>To remove double lines: <code>^:b*\n:b*\n</code> replace with: <code>\n</code></p>
<p>*** for Visual Studio 2013 and above:***</p>
<pre><code>^\s*$\n
</code></pre>
<p>and for double lines:</p>
<pre><code>^(?([^\r\n])\s)*\r?\n(?([^\r\n])\s)*\r?\n
</code></pre>
<p>See the regular expression syntax updates for VS2012 and above in @lennart's answer below</p>
|
19,151,940 |
git remove trailing whitespace in new files before commit
|
<p>I know removing trailing whitespace can be done with a pre-commit hook. I am interested in doing it manually. I read the question here:<br>
<a href="https://stackoverflow.com/questions/591923/make-git-automatically-remove-trailing-whitespace-before-committing">Make git automatically remove trailing whitespace before committing - Stack Overflow</a><br>
The answer closest to what I want is <a href="https://stackoverflow.com/a/15398512/894506">the "automatic version" from ntc2</a>:
<Br><br></p>
<pre><code>(export VISUAL=: && git -c apply.whitespace=fix add -ue .) && git checkout . && git reset
</code></pre>
<p><br>
That command works well except it seems to be only for changes on files that are already in the repo, not new files. I have a bunch of files that are new, meaning they aren't yet in the repo. I want to remove whitespace from those files so I tried add -A instead of -u but that didn't make a difference.</p>
| 19,156,679 | 4 | 4 | null |
2013-10-03 06:05:42.193 UTC
| 10 |
2014-03-06 00:14:15.917 UTC
|
2017-05-23 12:03:05.607 UTC
| null | -1 | null | 4,704,515 | null | 1 | 16 |
git|whitespace|removing-whitespace
| 22,796 |
<p>To manually clean up whitespace from your last 3 commits, you can do this:</p>
<p><code>git rebase --whitespace=fix HEAD~3</code></p>
<p>When I work on a topic branch, I track the upstream branch (usually by creating it like this)</p>
<p><code>git checkout -b topic -t</code></p>
<p>Which allows me to drop the last argument from <code>git rebase</code>. So once I'm done & ready to merge, I can clean the whole topic branch quickly with:</p>
<p><code>git ws</code> # aliased to rebase --whitespace=fix</p>
<p>Note that, unlike the HEAD~3 example, this will actually rebase your changes upon the upstream branch if it's changed! (But that's also what I want, in my workflow.)</p>
|
3,548,635 |
Python + JSON, what happened to None?
|
<p>Dumping and loading a dict with <a href="https://docs.python.org/3/library/constants.html#None" rel="noreferrer"><code>None</code></a> as key, results in a <a href="https://docs.python.org/3.7/tutorial/datastructures.html#dictionaries" rel="noreferrer">dictionary</a> with <code>'null'</code> as the key.</p>
<p>Values are un-affected, but things get even worse if a string-key <code>'null'</code> actually exists.</p>
<p>What am I doing wrong here? Why can't I serialize/deserialize a <a href="https://docs.python.org/3.7/library/stdtypes.html#dict" rel="noreferrer"><code>dict</code></a> with <code>None</code> keys?</p>
<h1>Example</h1>
<pre><code>>>> json.loads(json.dumps({'123':None, None:'What happened to None?'}))
{u'123': None, u'null': u'What happened to None?'}
>>> json.loads(json.dumps({'123':None, None:'What happened to None?', 'null': 'boom'}))
{u'123': None, u'null': u'boom'}
</code></pre>
| 3,548,740 | 3 | 1 | null |
2010-08-23 14:44:32.357 UTC
| 7 |
2019-09-16 08:15:05.583 UTC
|
2018-07-25 06:40:47.743 UTC
|
user8554766
| null | null | 294,585 | null | 1 | 30 |
python|json|dictionary
| 88,173 |
<p>JSON objects are maps of <em>strings</em> to values. If you try to use another type of key, they'll get converted to strings.</p>
<pre><code>>>> json.loads(json.dumps({123: None}))
{'123': None}
>>> json.loads(json.dumps({None: None}))
{'null': None}
</code></pre>
|
3,842,616 |
Organizing Python classes in modules and/or packages
|
<p>I like the Java convention of having one public class per file, even if there are sometimes good reasons to put more than one public class into a single file. In my case I have alternative implementations of the same interface. But if I would place them into separate files, I'd have redundant names in the import statements (or misleading module names):</p>
<pre><code>import someConverter.SomeConverter
</code></pre>
<p>whereas <code>someConverter</code> would be the file (and module) name and <code>SomeConverter</code> the class name. This looks pretty inelegant to me. To put all alternative classes into one file would lead to a more meaningful import statement:</p>
<pre><code>import converters.SomeConverter
</code></pre>
<p>But I fear that the files become pretty large, if I put all related classes into a single module file. What is the Python best practise here? Is one class per file unusual? </p>
| 3,842,687 | 3 | 1 | null |
2010-10-01 19:58:31.987 UTC
| 22 |
2020-10-10 06:58:11.937 UTC
|
2010-10-02 08:47:43.073 UTC
| null | 238,134 | null | 238,134 | null | 1 | 60 |
python|class|module|package
| 35,453 |
<p>A lot of it is personal preference. Using python modules, you do have the option to keep each class in a separate file and still allow for <code>import converters.SomeConverter</code> (or <code>from converters import SomeConverter</code>)</p>
<p>Your file structure could look something like this:</p>
<pre><code>* converters
- __init__.py
- baseconverter.py
- someconverter.py
- otherconverter.py
</code></pre>
<p>and then in your <code>__init__.py</code> file:</p>
<pre><code>from baseconverter import BaseConverter
from otherconverter import OtherConverter
</code></pre>
|
3,266,524 |
How to get user password for database
|
<p>I am using phpMyAdmin; I created a database; now I want to locate the username and password for this new database I created. Note, I am not sys admin, I am only the developer, but I do have access to create db on MySQL in phpMyAdmin. Does my sys admin needs to tell me the username and password to access this db, or I can telnet and get it?</p>
| 3,266,546 | 4 | 0 | null |
2010-07-16 15:38:42.387 UTC
| 1 |
2022-01-21 09:37:30.77 UTC
|
2022-01-21 09:37:30.77 UTC
| null | 1,839,439 | null | 255,391 | null | 1 | 10 |
php|mysql|phpmyadmin
| 111,078 |
<p>In MySQL creating a database doesn't automatically create a user to go with it.
You must explicitly create the user and grant acess.</p>
<p><a href="http://dev.mysql.com/doc/refman/5.1/en/adding-users.html" rel="noreferrer">http://dev.mysql.com/doc/refman/5.1/en/adding-users.html</a></p>
|
24,270,036 |
Listening to all scroll events on a page
|
<p><strong>Background:</strong></p>
<p>I'm writing a component that opens up a sub-menu on click. I can't know where this component will be placed on the page or how far it will be nested in areas that may have the <code>overflow</code> property set.</p>
<p>Given that the overflow may clip the sub-menu I am instead making the sub-menu itself be attached to the <code>body</code> giving it an absolute position and linking it via code to the original component. This takes care of the overflow issue.</p>
<p><strong>Problem:</strong></p>
<p>However if a user scrolls the sub-menu remains in place, rather than moving with its linked component, <strong>so I need to be able to listen to any and all scroll events that occur on the page</strong> so I can reposition the sub-menu appropriately.</p>
<p>If there's an easy way to listen to all scroll events or if there's another better way to do this component I would appreciate any input.</p>
<p>I've played around with JSFiddle and set up a <a href="http://jsfiddle.net/wAadt/" rel="noreferrer">sandbox</a> but I haven't had any success nor have I found an answer on this site or anywhere else for that matter; though perhaps I was using the wrong search terms, I can't imagine that I'm the first to have this question.</p>
<p><strong><em>EDIT</em></strong></p>
<p>To address the close vote, I'm not asking help to debug an issue without providing code nor am I asking something that won't help anyone in the future. I'm asking how I would go about listening to all event of a certain type not matter where the may occur, which I find globally applicable, though perhaps that's subjective.</p>
<p><strong><em>EDIT</em></strong></p>
<p><code>$(window).on('scroll', function(){ /**/ });</code>
is not an option as it only listens to the window scroll, not any nested scrolls.</p>
<p><code>$('#ex1 #ex2').on('scroll', function(){ /**/ });</code> is not an option as it requires the person who is implementing the code to be aware of any current or possible future areas on the page that may scroll.</p>
| 30,723,677 | 4 | 11 | null |
2014-06-17 17:34:51.037 UTC
| 4 |
2015-06-09 18:59:33.143 UTC
|
2014-06-17 17:45:19.827 UTC
| null | 573,634 | null | 573,634 | null | 1 | 28 |
javascript|jquery
| 15,258 |
<p>You should be able to attach a document-level listener with a third parameter of <code>true</code> to capture the scroll events on all elements. Here's what that looks like:</p>
<pre><code>document.addEventListener('scroll', function(e){ }, true);
</code></pre>
<p>The <code>true</code> at the end is the important part, it tells the browser to capture the event on dispatch, even if that event does not normally bubble, like change, focus, and scroll.</p>
<p>Here's an example: <a href="http://jsbin.com/sayejefobe/1/edit?html,js,console,output">http://jsbin.com/sayejefobe/1/edit?html,js,console,output</a></p>
|
19,252,777 |
.Net Remoting versus WCF
|
<p>I am wondering that I can do same thing from both .net remoting and WCF, then why WCF is more preferred over .Net remoting. Where can I choose (or in which situation) .Net remoting or WCF?</p>
| 19,252,815 | 2 | 12 | null |
2013-10-08 16:04:23.857 UTC
| 12 |
2016-02-19 04:19:17.59 UTC
|
2013-10-09 04:24:26.007 UTC
| null | 1,501,794 | null | 2,779,561 | null | 1 | 24 |
c#|wcf|.net-remoting
| 18,864 |
<p><strong>.NET Remoting</strong> applications can use the HTTP, TCP, and SMTP protocols whereas <strong>WCF</strong> can use named pipes and MSMQ as well along with all these protocols.</p>
<p>You may find the best answer here: <a href="http://msdn.microsoft.com/en-us/library/aa730857%28v=vs.80%29.aspx" rel="noreferrer">From .NET Remoting to the Windows Communication Foundation</a></p>
<blockquote>
<p><strong>Conclusion</strong></p>
<p>As you have seen, a migration from .NET Remoting to WCF is not a task
you have to be afraid of. For most applications, a simple three-step
process can bring your application to the new platform. In most cases,
you will only have to mark your interface contracts with
[ServiceContract] and [OperationContract], your data structures with
[DataContract] and [DataMember] and maybe change some parts of your
activation model to be based on sessions instead of client-activated
objects.</p>
<p>If you decide that you want to take advantage of the features
of the Windows Communication Foundation, the complete migration from
.NET Remoting to WCF should therefore be a rather easy task for the
majority of applications.</p>
</blockquote>
<p>You may also find the performance difference between the two in <a href="http://msdn.microsoft.com/en-us/library/bb310550.aspx" rel="noreferrer">A Performance Comparison of Windows Communication Foundation (WCF) with Existing Distributed Communication Technologies</a></p>
<blockquote>
<p>When migrating distributed applications written with ASP.NET Web
Services, WSE, .NET Enterprise Services and .NET Remoting to WCF, the
performance is at least comparable to the other existing Microsoft
distributed communication technologies. <strong>In most cases, the performance
is significantly better for WCF over the other existing technologies.
Another important characteristic of WCF is that the throughput
performance is inherently scalable from a uni processor to quad
processor.</strong></p>
<p><strong>To summarize the results, WCF is 25%—50% faster than ASP.NET Web
Services, and approximately 25% faster than .NET Remoting</strong>. Comparison
with .NET Enterprise Service is load dependant, as in one case WCF is
nearly 100% faster but in another scenario it is nearly 25% slower.
For WSE 2.0/3.0 implementations, migrating them to WCF will obviously
provide the most significant performance gains of almost 4x.</p>
</blockquote>
|
8,650,463 |
groupby multiple columns in a F# 3.0 query
|
<p>Just trying out F# 3.0 and hit a bit of a wall when it comes to grouping by multiple columns. The obvious thing to try was</p>
<pre><code>query {
for d in context.table do
groupBy (d.col1,d.col2) into g
select (g.Key)
}
</code></pre>
<p>But I get a "Only parameterless constructors and initializers are supported in LINQ to Entities." exception.</p>
<p>I can't seem to find an example on msdn</p>
<p><a href="http://msdn.microsoft.com/en-us/library/hh225374(v=vs.110).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/hh225374(v=vs.110).aspx</a></p>
<p><a href="http://msdn.microsoft.com/en-us/library/hh361035(v=vs.110).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/hh361035(v=vs.110).aspx</a></p>
<p>And I realize my question is similar to
" <a href="https://stackoverflow.com/q/8546823/926042">Entity Framework and Anonymous Types in F#</a>" but it seems to be powerpack/F#2.x focused and I'm hoping F# 3.0 has an elegant answer... Any ideas?</p>
<p><strong>UPDATE:</strong></p>
<p>I came across the CLIMutable attribute from reading Brian's post at:</p>
<p><a href="http://blogs.msdn.com/b/fsharpteam/archive/2012/07/19/more-about-fsharp-3.0-language-features.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/b/fsharpteam/archive/2012/07/19/more-about-fsharp-3.0-language-features.aspx</a></p>
<p>I was pretty optimistic so I tried</p>
<pre><code>[<CLIMutable>]
type MyRecord = { Column1 : int; Column2 : int }
query {
for d in context.table do
groupBy {Column1 = col1; Column2 = col2} into g
select (g.Key)
}
</code></pre>
<p>Unfortunately I get the exact same exception.</p>
| 16,826,263 | 8 | 8 | null |
2011-12-27 23:49:09.967 UTC
| 8 |
2019-04-10 06:38:23.47 UTC
|
2017-05-23 12:16:43.803 UTC
| null | -1 | null | 926,042 | null | 1 | 38 |
f#|f#-3.0
| 3,045 |
<p>The following is an example of multiple columns being used for grouping in c# and converted to f# (overly paranoid management has made me rename everything, but I believe I have been consistent):</p>
<p>(TheDatabase was generated by SqlMetal, GetSummedValuesResult is a F# record type)</p>
<p>c#</p>
<pre><code>public static class Reports
{
public static IReadOnlyList<GetSummedValuesResult> GetSummedValues(TheDatabase db, DateTime startDate, DateTime? endDate)
{
var query =
from sv in db.SomeValues
where (sv.ADate >= startDate && sv.ADate <= (endDate ?? startDate))
group sv by new { sv.ADate, sv.Owner.Name } into grouping
select new GetSummedValuesResult(
grouping.Key.ADate,
grouping.Key.Name,
grouping.Sum(g => g.Value)
);
return query.ToList();
}
}
</code></pre>
<p>f#</p>
<pre><code>type Reports() =
static member GetSummedValues (db:TheDatabase) startDate (endDate:Nullable<DateTime>) =
let endDate = if endDate.HasValue then endDate.Value else startDate
let q = query {
for sv in db.SomeValues do
where (sv.ADate >= startDate && sv.ADate <= endDate)
let key = AnonymousObject<_,_>(sv.ADate, sv.Owner.Name)
groupValBy sv key into grouping
select {
ADate = grouping.Key.Item1;
AName = grouping.Key.Item2;
SummedValues = grouping.Sum (fun (g:TheDatabaseSchema.SomeValues) -> g.Value)
}
}
List(q) :> IReadOnlyList<GetSummedValuesResult>
</code></pre>
<p>So the thing to use is <code>Microsoft.FSharp.Linq.RuntimeHelpers.AnonymousObject</code></p>
<p><strong>Note that you should not use the Seq module for aggregation functions!!</strong></p>
<pre><code>SummedValues = grouping |> Seq.sumBy (fun g -> g.SomeValues)
</code></pre>
<p>Although this WILL WORK, it does the aggregation on the client side, rather than formulating appropriate SQL.</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.