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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
10,227,692 | android: How to make settings navigation like native settings app | <p>How do I make the settings navigation for SwitchReference like Android native settings app?</p>
<p>Where when u click on WiFi region(not on the switch) it will navigate to a new screen:</p>
<p><img src="https://i.stack.imgur.com/hdQYu.png" alt="Click on WiFi"></p>
<p>My app only change the switch from ON to OFF and vice versa even when I'm not clicking on the switch.</p>
<p>I'm using <code>PreferenceFragment</code> and xml for the screen. And my preference is following the example from <a href="http://developer.android.com/reference/android/preference/PreferenceFragment.html" rel="noreferrer">Android PreferenceFragment documentation</a>. I develop my app on ICS 4.0 API 14.</p>
<p>Anyone know how to do this?</p>
<p><strong>Edited:</strong></p>
<p>My XML look like this:</p>
<pre><code><PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceCategory
android:layout="@layout/preference_category"
android:title="User Settings" >
<SwitchPreference
android:key="pref_autorun"
android:layout="@layout/preference"
android:summary="Autorun SMODE on boot"
android:title="Autorun SMODE" />
<SwitchPreference
android:key="pref_wifi_control"
android:layout="@layout/preference"
android:selectable="false"
android:summary="Controls your Wi-Fi radio automatically based on hotspot availability"
android:title="Wi-Fi Radio Control" />
</PreferenceCategory>
</PreferenceScreen>
</code></pre> | 11,220,049 | 3 | 1 | null | 2012-04-19 12:07:08.597 UTC | 8 | 2015-01-11 23:11:18.043 UTC | 2012-04-19 12:20:44.177 UTC | null | 809,909 | null | 809,909 | null | 1 | 8 | android|android-preferences | 4,885 | <p>By taking a look at the source of the stock Settings app, you can find how they did it. </p>
<p>Basically, they use a custom ArrayAdapter (much like you would do with a ListView) to display rows with Switch buttons. And for the second screen, they simply use the CustomView available in the ActionBar. </p>
<p>I wrote <a href="http://xgouchet.fr/android/index.php?article4/master-on-off-preferences-with-ice-cream-sandwich">an article with a sample code</a> to show how you can do it in your project. Be careful though, this can only wirk in API Level 14 or higher, so if you target older devices, keep an old style preference screen. </p> |
10,032,542 | Track a phone call duration | <p>Is it possible to utilize the users phone through their cell provider, and track the length of a phone call?</p>
<p>So the user presses a button in the app "Call Now". A call begins to a pre-determined number. We record the start time. When the call ends, we calculate how many minutes were used.</p>
<p>Possible?</p> | 10,032,910 | 2 | 4 | null | 2012-04-05 16:40:12.25 UTC | 9 | 2018-02-19 14:29:34.24 UTC | 2017-08-18 12:40:56.623 UTC | null | 1,000,551 | null | 591,016 | null | 1 | 8 | android|android-intent|broadcastreceiver|phone-call | 16,001 | <p>To calculate time talked for both incoming , outgoing calls use the following broadcast receiver :</p>
<pre><code>public class CallDurationReceiver extends BroadcastReceiver {
static boolean flag = false;
static long start_time, end_time;
@Override
public void onReceive(Context arg0, Intent intent) {
String action = intent.getAction();
if (action.equalsIgnoreCase("android.intent.action.PHONE_STATE")) {
if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
TelephonyManager.EXTRA_STATE_RINGING)) {
start_time = System.currentTimeMillis();
}
if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
TelephonyManager.EXTRA_STATE_IDLE)) {
end_time = System.currentTimeMillis();
//Total time talked =
long total_time = end_time - start_time;
//Store total_time somewhere or pass it to an Activity using intent
}
}
}
</code></pre>
<p>Register your receiver in your manifest file like this:</p>
<pre><code> <receiver android:name=".CallDurationReceiver">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
</code></pre>
<p>Also add the uses permission:</p>
<pre><code><uses-permission android:name="android.permission.READ_PHONE_STATE" />
</code></pre> |
10,142,583 | MySQL error: Unknown column in 'where clause' | <p>I have a table called <code>bank</code> with three columns: <code>uid</code>, <code>nick</code>, <code>balance</code>.</p>
<p>I am trying to create a query that will return the balance based on the nick, and I am getting an error <code>Unknown column 'Alex' in 'where clause'</code> when I use this query:</p>
<pre><code>SELECT b.balance FROM bank AS b WHERE b.nick=`Alex` LIMIT 1
</code></pre>
<p>Can anyone see what I am doing wrong here?</p> | 10,142,614 | 4 | 1 | null | 2012-04-13 14:20:21.677 UTC | 3 | 2018-05-09 06:39:58.783 UTC | null | null | null | null | 1,291,869 | null | 1 | 15 | mysql|sql|select | 75,347 | <p>backticks (`) are used for identifiers, like table names, column names, etc. Single quotes(') are used for string literals.</p>
<p>You want to do:</p>
<pre><code>SELECT b.balance FROM bank AS b WHERE b.nick='Alex' LIMIT 1
</code></pre>
<p>Or, to be more explicit:</p>
<pre><code>SELECT `b`.`balance` FROM `bank` AS b WHERE `b`.`nick`='Alex' LIMIT 1
</code></pre>
<p>When there is no chance of ambiguity, and when table/column names do not have special characters or spaces, then you can leave the ` off.</p>
<p>Here is some documentation that is dry and hard to read: <a href="http://dev.mysql.com/doc/refman/5.0/en/identifiers.html" rel="noreferrer">http://dev.mysql.com/doc/refman/5.0/en/identifiers.html</a></p>
<p>But here is a related question on dba.stackoverflow that is easier to read: <a href="https://dba.stackexchange.com/questions/23129/benefits-of-using-backtick-in-mysql-queries">https://dba.stackexchange.com/questions/23129/benefits-of-using-backtick-in-mysql-queries</a></p>
<p>And here is a very good page that I recommend everyone read: <a href="http://www.sitepoint.com/forums/showthread.php?408497-the-big-bad-thread-of-quot-MySQL-Best-Practices-and-Other-Useful-Information-quot" rel="noreferrer">http://www.sitepoint.com/forums/showthread.php?408497-the-big-bad-thread-of-quot-MySQL-Best-Practices-and-Other-Useful-Information-quot</a></p> |
9,798,623 | How to properly set run paths, search paths, and install names? | <p>I have a collection of projects that I'm compiling as dynamic libraries. Each of these .dylibs depend on other various .dylibs that I would like to place in various other directories (i.e. some at the executable path, some at the loader path, some at a fixed path).</p>
<p>When I run <code>otool -L</code> on the compiled libraries, I get a list of paths to those dependencies but I have know idea how those paths are being set/determined. They almost appear pseudo random. I've spent hours messing with the "Build Settings" in Xcode to try and change these paths (w/ @rpath, @executable_path, @loader_path, etc.) but I can't seem to change anything (as checked by running <code>otool -L</code>). I'm not even entirely sure where to add these flags and don't really understand the difference between the following or how to properly use them:</p>
<p>Linking - "Dynamic Library Install Name"<br>
Linking - "Runpath Search Paths"<br>
Linking - "Other Linking Flags"<br>
Search Paths - "Library Search Paths"</p>
<p>When I run <code>install_name_tool -change</code> on the various libraries, I am able to successfully change the run path search paths (again as verified by running <code>otool -L</code> to confirm).</p>
<p>I'm running Xcode 4.2 and I'm very close to giving up and just using a post-build script that runs install_tool_name to make the changes. But its a kludge hack fix and I'd prefer not to do it.</p>
<p>Where can I see how the search/run paths for the dylib dependencies are being set?<br>
Anyone have any ideas on what I might be doing wrong?</p> | 9,799,011 | 2 | 0 | null | 2012-03-21 04:32:57.893 UTC | 9 | 2016-09-28 06:48:56.373 UTC | 2015-12-17 21:00:12.357 UTC | null | 608,639 | null | 1,190,255 | null | 1 | 15 | xcode|macos|xcode4.2|dylib|dyld | 31,218 | <p>Typically, in my dylib's target, I set <code>INSTALL_PATH</code> aka "Installation Directory" to the prefix I want (e.g. <code>@executable_path/../Frameworks</code>). </p>
<p>I leave <code>LD_DYLIB_INSTALL_NAME</code> aka "Dynamic Library Install Name" set to its default value, which is <code>$(DYLIB_INSTALL_NAME_BASE:standardizepath)/$(EXECUTABLE_PATH)</code>. </p>
<p>Xcode expands that based on your target's name, so it might end up being <code>@executable_path/../Frameworks/MyFramework.framework/Versions/A/MyFramework</code>, for instance.</p>
<p>The important thing to realize is that the install path is <em>built into</em> the dylib, as part of its build process. Later on, when you link B.dylib that refers to A.dylib, A.dylib's install path is <em>copied into</em> B.dylib. (That's what <code>otool</code> is showing you -- those copied install paths.) So it's best to get the correct install path built into the dylib in the first place.</p>
<p>Before trying to get all the dylibs working together, check each one individually. Build it, then <code>otool -L</code> on the built dylib. The first line for each architecture should be what <code>LD_DYLIB_INSTALL_NAME</code> was showing you.</p>
<p>Once you have that organized, try to get the dylibs linking against each other. It should be much more straightforward.</p> |
9,696,660 | What is the difference between int, Int16, Int32 and Int64? | <p>What is the difference between <code>int</code>, <code>System.Int16</code>, <code>System.Int32</code> and <code>System.Int64</code> other than their sizes?</p> | 9,696,777 | 12 | 0 | null | 2012-03-14 05:55:29.13 UTC | 62 | 2021-08-14 12:56:05.383 UTC | 2015-10-05 15:17:18.303 UTC | null | 1,364,007 | null | 283,422 | null | 1 | 277 | c#|.net | 625,590 | <p>Each type of integer has a different range of storage capacity</p>
<pre><code> Type Capacity
Int16 -- (-32,768 to +32,767)
Int32 -- (-2,147,483,648 to +2,147,483,647)
Int64 -- (-9,223,372,036,854,775,808 to +9,223,372,036,854,775,807)
</code></pre>
<p>As stated by James Sutherland in <a href="https://stackoverflow.com/questions/62503/c-int-or-int32-should-i-care/62555#62555">his answer</a>:</p>
<blockquote>
<p><code>int</code> and <code>Int32</code> are indeed synonymous; <code>int</code> will be a little more
familiar looking, <code>Int32</code> makes the 32-bitness more explicit to those
reading your code. I would be inclined to use int where I just need
'an integer', <code>Int32</code> where the size is important (cryptographic code,
structures) so future maintainers will know it's safe to enlarge an
<code>int</code> if appropriate, but should take care changing <code>Int32</code> variables
in the same way.</p>
<p>The resulting code will be identical: the difference is purely one of
readability or code appearance.</p>
</blockquote> |
28,294,620 | What is the best smart pointer return type for a factory function? | <p>With respect to smart pointers and new C++11/14 features, I am wondering what the best-practice return values and function parameter types would be for classes that have these facilities:</p>
<ol>
<li><p>A factory function (outside of the class) that creates objects and returns them to users of the class. (For example opening a document and returning an object that can be used to access the content.)</p></li>
<li><p>Utility functions that accept objects from the factory functions, use them, but do not take ownership. (For example a function that counts the number of words in the document.)</p></li>
<li><p>Functions that keep a reference to the object after they return (like a UI component that takes a copy of the object so it can draw the content on the screen as needed.)</p></li>
</ol>
<p><strong>What would the best return type be for the factory function?</strong></p>
<ul>
<li>If it's a raw pointer the user will have to <code>delete</code> it correctly which is problematic.</li>
<li>If it returns a <code>unique_ptr<></code> then the user can't share it if they want to.</li>
<li>If it's a <code>shared_ptr<></code> then will I have to pass around <code>shared_ptr<></code> types everywhere? This is what I'm doing now and it's causing problems as I'm getting cyclic references, preventing objects from being destroyed automatically.</li>
</ul>
<p><strong>What is the best parameter type for the utility function?</strong></p>
<ul>
<li>I imagine passing by reference will avoid incrementing a smart pointer reference count unnecessarily, but are there any drawbacks of this? The main one that comes to mind is that it prevents me from passing derived classes to functions taking parameters of the base-class type.</li>
<li>Is there some way that I can make it clear to the caller that it will NOT copy the object? (Ideally so that the code will not compile if the function body does try to copy the object.)</li>
<li>Is there a way to make it independent of the type of smart pointer in use? (Maybe taking a raw pointer?)</li>
<li>Is it possible to have a <code>const</code> parameter to make it clear the function will not modify the object, without breaking smart pointer compatibility?</li>
</ul>
<p><strong>What is the best parameter type for the function that keeps a reference to the object?</strong></p>
<ul>
<li>I'm guessing <code>shared_ptr<></code> is the only option here, which probably means the factory class must return a <code>shared_ptr<></code> also, right?</li>
</ul>
<p>Here is some code that compiles and hopefully illustrates the main points.</p>
<pre><code>#include <iostream>
#include <memory>
struct Document {
std::string content;
};
struct UI {
std::shared_ptr<Document> doc;
// This function is not copying the object, but holding a
// reference to it to make sure it doesn't get destroyed.
void setDocument(std::shared_ptr<Document> newDoc) {
this->doc = newDoc;
}
void redraw() {
// do something with this->doc
}
};
// This function does not need to take a copy of the Document, so it
// should access it as efficiently as possible. At the moment it
// creates a whole new shared_ptr object which I feel is inefficient,
// but passing by reference does not work.
// It should also take a const parameter as it isn't modifying the
// object.
int charCount(std::shared_ptr<Document> doc)
{
// I realise this should be a member function inside Document, but
// this is for illustrative purposes.
return doc->content.length();
}
// This function is the same as charCount() but it does modify the
// object.
void appendText(std::shared_ptr<Document> doc)
{
doc->content.append("hello");
return;
}
// Create a derived type that the code above does not know about.
struct TextDocument: public Document {};
std::shared_ptr<TextDocument> createTextDocument()
{
return std::shared_ptr<TextDocument>(new TextDocument());
}
int main(void)
{
UI display;
// Use the factory function to create an instance. As a user of
// this class I don't want to have to worry about deleting the
// instance, but I don't really care what type it is, as long as
// it doesn't stop me from using it the way I need to.
auto doc = createTextDocument();
// Share the instance with the UI, which takes a copy of it for
// later use.
display.setDocument(doc);
// Use a free function which modifies the object.
appendText(doc);
// Use a free function which doesn't modify the object.
std::cout << "Your document has " << charCount(doc)
<< " characters.\n";
return 0;
}
</code></pre> | 28,295,213 | 4 | 8 | null | 2015-02-03 08:44:13.823 UTC | 24 | 2015-02-05 11:17:55.607 UTC | null | null | null | null | 308,237 | null | 1 | 45 | c++|c++11|smart-pointers|const-correctness | 15,983 | <p>I'll answer in reverse order so to begin with the simple cases.</p>
<blockquote>
<p>Utility functions that accept objects from the factory functions, use them, but do not take ownership. (For example a function that counts the number of words in the document.)</p>
</blockquote>
<p>If you are calling a factory function, you are always taking ownership of the created object by the very definition of a factory function. I think what you mean is that some <em>other</em> client first obtains an object from the factory and then wishes to pass it to the utility function that does not take ownership itself.</p>
<p>In this case, the utility function should not care at all how ownership of the object it operates on is managed. It should simply accept a (probably <code>const</code>) reference or – if “no object” is a valid condition – a non-owning raw pointer. This will minimize the coupling between your interfaces and make the utility function most flexible.</p>
<blockquote>
<p>Functions that keep a reference to the object after they return (like a UI component that takes a copy of the object so it can draw the content on the screen as needed.)</p>
</blockquote>
<p>These should take a <a href="http://en.cppreference.com/w/cpp/memory/shared_ptr"><code>std::shared_ptr</code></a> <em>by value</em>. This makes it clear from the function's signature that they take shared ownership of the argument.</p>
<p>Sometimes, it can also be meaningful to have a function that takes unique ownership of its argument (constructors come to mind). Those should take a <a href="http://en.cppreference.com/w/cpp/memory/unique_ptr"><code>std::unique_ptr</code></a> <em>by value</em> (or by rvalue reference) which will also make the semantics clear from the signature.</p>
<blockquote>
<p>A factory function (outside of the class) that creates objects and returns them to users of the class. (For example opening a document and returning an object that can be used to access the content.)</p>
</blockquote>
<p>This is the difficult one as there are good arguments for both, <code>std::unique_ptr</code> and <code>std::shared_ptr</code>. The only thing clear is that returning an owning raw pointer is no good.</p>
<p>Returning a <code>std::unique_ptr</code> is lightweight (no overhead compared to returning a raw pointer) and conveys the correct semantics of a factory function. Whoever called the function obtains exclusive ownership over the fabricated object. If needed, the client can construct a <code>std::shared_ptr</code> out of a <code>std::unique_ptr</code> at the cost of a dynamic memory allocation.</p>
<p>On the other hand, if the client is going to need a <code>std::shared_ptr</code> anyway, it would be more efficient to have the factory use <a href="http://en.cppreference.com/w/cpp/memory/shared_ptr/make_shared"><code>std::make_shared</code></a> to avoid the additional dynamic memory allocation. Also, there are situations where you simply must use a <code>std::shared_ptr</code> for example, if the destructor of the managed object is non-<code>virtual</code> and the smart pointer is to be converted to a smart pointer to a base class. But a <code>std::shared_ptr</code> has more overhead than a <code>std::unique_ptr</code> so if the latter is sufficient, we would rather avoid that if possible.</p>
<p>So in conclusion, I'd come up with the following guideline:</p>
<ul>
<li>If you need a custom deleter, return a <code>std::shared_ptr</code>.</li>
<li>Else, if you think that most of your clients are going to need a <code>std::shared_ptr</code> anyway, utilize the optimization potential of <code>std::make_shared</code>.</li>
<li>Else, return a <code>std::unique_ptr</code>.</li>
</ul>
<p>Of course, you could avoid the problem by providing <em>two</em> factory functions, one that returns a <code>std::unique_ptr</code> and one that returns a <code>std::shared_ptr</code> so each client can use what best fits its needs. If you need this frequently, I guess you can abstract most of the redundancy away with some clever template meta-programming.</p> |
9,984,748 | How do I get sed to read from standard input? | <p>I am trying</p>
<pre><code>grep searchterm myfile.csv | sed 's/replaceme/withthis/g'
</code></pre>
<p>and getting</p>
<pre><code>unknown option to `s'
</code></pre>
<p>What am I doing wrong?</p>
<p>Edit:</p>
<p>As per the comments the code is actually correct. My full code resembled something like the following</p>
<pre><code>grep searchterm myfile.csv | sed 's/replaceme/withthis/g'
# my comment
</code></pre>
<p>And it appears that for some reason my comment was being fed as input into sed. Very strange.</p> | 9,984,761 | 5 | 5 | null | 2012-04-02 22:32:03.643 UTC | 17 | 2019-05-10 15:50:08.587 UTC | 2012-04-02 22:49:38.14 UTC | null | 144,152 | null | 144,152 | null | 1 | 115 | linux|bash|shell | 138,648 | <p>use the --expression option</p>
<pre><code>grep searchterm myfile.csv | sed --expression='s/replaceme/withthis/g'
</code></pre> |
7,712,702 | Creating a View using stored procedure | <p>This questions have asked few times before, unfortunately I did not get an answer to my questions.</p>
<p>Well I have two SQL (<strong>SQL SERVER 2008</strong>) tables, Employee and Employee expens, where Employee Id is the Primary key and the foreign key respectively.</p>
<p>Employee table columns,
1. Employee Id (P Key) 2. Manager 3. Location 4. Join Date 5. Name</p>
<p>Employee Expense table columns,
1. Expense Id (P Key) 2. Employee Id (F key) 3. Expense Type 4. Expense Amount 5. Expense Date.</p>
<p>Question is, I want to create a view to be used in a SharePoint web part, where I will query both table, So my requirement is to create a view using following Columns, </p>
<p><strong>From Employee I need <em>Employee Id and Name</em>.
From Employee Expenses I need <em>Expense Type, Expense Amount, Expense Date</em>.</strong></p>
<p>Additional requirements.</p>
<p><strong>a. If I have multiple entries for an employee in the table Employee Expense, that many no of rows should be there in the View</strong></p>
<p><strong>b. Even If I have no entry in the Employee Expense table, then also I should get the row for that particular Employee in the view, with null for the Employee Expense table columns.</strong></p>
<p>Please help me to proceed ...</p>
<p><em><strong>Editing To add the required view code as the Stack Overflow members instructed !!</em></strong></p>
<pre><code>CREATE VIEW ExpenseView AS (
SELECT [Employee Expense].[Employee ID], Employee.[First Name], [Employee Expense].[Expense Type],[Employee Expense].[Expense Amount],[Employee Expense].[Expense Date]
FROM Employee,[Employee Expense]
WHERE [Employee Expense].[Employee ID] = Employee.[Employee ID])
</code></pre>
<p>Please help.</p> | 7,713,870 | 3 | 9 | null | 2011-10-10 12:25:09.117 UTC | null | 2015-12-07 20:24:59.17 UTC | 2011-10-10 13:18:55.84 UTC | null | 1,756,630 | null | 1,756,630 | null | 1 | 6 | sql|sql-server-2008|sql-view | 103,391 | <p>If you want to create a view from within a SP you need to use dynamic SQL.</p>
<p>Something like this.</p>
<pre><code>create procedure ProcToCreateView
as
exec ('create view MyView as select 1 as Col')
</code></pre>
<p>The <code>create view...</code> code has to be sent as a string parameter to <code>exec</code> and by the looks of it you already have the code you need for the view so just embed it in between the <code>'</code>.</p>
<p>I really have no idea why you need that. Perhaps you just need to know how to <strong>use</strong> a view from a SP</p>
<pre><code>create procedure ProcToUseView
as
select Col
from MyView
</code></pre> |
11,671,097 | JMeter use beanshell variable in HTTP Request | <p>I'm an absolute rookie here (JAVA i mean), spent hours looking for a solution, now i just want to shoot myself.<br>
I want to create a string in the beanshell assertion which is placed right above the HTTP Request.</p>
<ul>
<li><p>In the beanshell i wrote:</p>
<pre><code>String docid="abcd";
</code></pre>
<p>(in actuality i wish to concatenate a string with some variables)</p></li>
<li><p>In HTTP Request, send parameters i add <code>${docid}</code>.</p></li>
</ul> | 11,671,772 | 3 | 0 | null | 2012-07-26 14:07:27.443 UTC | 2 | 2020-09-21 21:09:04.993 UTC | 2020-09-21 21:09:04.993 UTC | null | 993,246 | null | 1,287,042 | null | 1 | 12 | java|jmeter|beanshell | 59,394 | <p>In <a href="http://jmeter.apache.org/usermanual/component_reference.html#BeanShell_Assertion">BeanShell Assertion description section</a> you can find the following:</p>
<pre><code> vars - JMeterVariables - e.g. vars.get("VAR1"); vars.put("VAR2","value"); vars.putObject("OBJ1",new Object());
props - JMeterProperties (class java.util.Properties) - e.g. props.get("START.HMS"); props.put("PROP1","1234");
</code></pre>
<p>So to set jmeter variable in beanshell code (BeanShell Assertion sampler in your case) use the following:</p>
<pre><code>String docid = "abcd";
vars.put("docid",docid);
</code></pre>
<p>or simply</p>
<pre><code>vars.put("docid","abcd");
</code></pre>
<p>and then you can refer it as ${docid}, as you've done in your HTTP Request.</p> |
11,582,286 | <form method="link" > or <a>? What's the difference? | <p>I <a href="http://www.htmlgoodies.com/tutorials/buttons/article.php/3478871">saw</a> that we can write:</p>
<pre><code><form method="link" action="foo.html" >
<input type="submit" />
</form>
</code></pre>
<p>To make a "link button".</p>
<p>But I know we can write:</p>
<pre><code><a href="foo.html" ><input type="button" /></a>
</code></pre>
<p>Which will do the same.</p>
<p>What's the difference? What's their browser compatibility?</p> | 11,582,427 | 5 | 3 | null | 2012-07-20 15:23:35.183 UTC | 4 | 2018-08-23 08:56:41.49 UTC | 2013-03-20 19:01:53.937 UTC | null | 760,706 | null | 1,344,937 | null | 1 | 15 | html|forms|get | 58,814 | <p>That page you link to is incorrect. There is no <code>link</code> value for the <code>method</code> attribute in HTML. This will cause the form to fall back to the default value for the method attribute, <code>get</code>, which is equivalent to an anchor element with a <code>href</code> attribute anyway, as both will result in a HTTP <code>GET</code> request. The only valid values of a form's <code>method</code> in HTML5 are "get" and "post".</p>
<pre><code><form method="get" action="foo.html">
<input type="submit">
</form>
</code></pre>
<p>This is the same as your example, but valid; and is equivalent to:</p>
<pre><code><a href="foo.html">
</code></pre>
<p>You should use semantics to determine which way to implement your form. Since there are no form fields for the user to fill in, this isn't really a form, and thus you need not use <code><form></code> to get the effect.</p>
<p>An example of when to use a <code>GET</code> form is a search box:</p>
<pre><code><form action="/search">
<input type="search" name="q" placeholder="Search" value="dog">
<button type="submit">Search</button>
</form>
</code></pre>
<p>The above allows the visitor to input their own search query, whereas this anchor element does not:</p>
<pre><code><a href="/search?q=dog">Search for "dog"</a>
</code></pre>
<p>Yet both will go to the same page when submitted/clicked (assuming the user doesn't change the text field in the first</p>
<hr>
<p>As an aside, I use the following CSS to get links that look like buttons:</p>
<pre><code>button,
.buttons a {
cursor: pointer;
font-size: 9.75pt; /* maximum size in WebKit to get native look buttons without using zoom */
-moz-user-select: none;
-webkit-user-select: none;
-webkit-tap-highlight-color: transparent;
}
.buttons a {
margin: 2px;
padding: 3px 6px 3px;
border: 2px outset buttonface;
background-color: buttonface;
color: buttontext;
text-align: center;
text-decoration: none;
-webkit-appearance: button;
}
button img,
.buttons a img {
-webkit-user-drag: none;
-ms-user-drag: none;
}
.buttons form {
display: inline;
display: inline-block;
}
</code></pre> |
11,623,157 | Enabling Camera Flash While Recording Video | <p>I need a way to control the camera flash on an Android device while it is recording video. I'm making a strobe light app, and taking videos with a flashing strobe light would result in the ability to record objects that are moving at high speeds, like a fan blade.</p>
<p>The flash can only be enabled by starting a video preview and setting FLASH_MODE_TORCH in the camera's parameters. That would look like this:</p>
<pre><code>Camera c = Camera.open();
Camera.Parameters p = c.getParameters();
p.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
c.setParameters(p);
c.startPreview();
</code></pre>
<p>Once the preview has started, I can flip that parameter back and forth to turn the light on and off. This works well until I try to record a video. The trouble is that in order to give the camera to the MediaRecorder, I first have to unlock it.</p>
<pre><code>MediaRecorder m = new MediaRecorder();
c.unlock(); // the killer
m.setCamera(c);
</code></pre>
<p>After that unlock, I can no longer change the camera parameters and therefore have no way to change the flash state.</p>
<p>I do not know if it is actually possible to do this since I'm not the best at java-hacking, but here is what I do know:</p>
<ul>
<li>Camera.unlock() is a native method, so I can't really see the mechanism behind the way it locks me out</li>
<li>Camera.Parameter has a HashMap that contains all of its parameters</li>
<li>Camera.setParameters(Parameters) takes the HashMap, converts it to a string, and passes it to a native method</li>
<li>I can eliminate all the parameters but TORCH-MODE from the HashMap and the Camera will still accept it</li>
</ul>
<p>So, I can still access the Camera, but it won't listen to anything I tell it. (Which is kind of the purpose of Camera.unlock())</p>
<p><strong>Edit:</strong></p>
<p>After examining the native code, I can see that in <a href="http://androidxref.com/2.3.6/xref/frameworks/base/services/camera/libcameraservice/CameraService.cpp" rel="nofollow noreferrer">CameraService.cpp</a> my calls to Camera.setParameters(Parameters) get rejected because my Process ID does not match the Process ID the camera service has on record. So it would appear that that is my hurdle.</p>
<p><strong>Edit2:</strong></p>
<p>It would appear that the <a href="http://androidxref.com/2.3.6/xref/frameworks/base/media/libmediaplayerservice/MediaPlayerService.cpp" rel="nofollow noreferrer">MediaPlayerService</a> is the primary service that takes control of the camera when a video is recording. I do not know if it is possible, but if I could somehow start that service in my own process, I should be able to skip the Camera.unlock() call.</p>
<p><strong>Edit3:</strong></p>
<p>One last option would be if I could somehow get a pointer to the CameraHardwareInterface. From the looks of it, this is a device specific interface and probably does not include the PID checks. The main problem with this though is that the only place that I can find a pointer to it is in CameraService, and CameraService isn't talking.</p>
<p><strong>Edit4: (several months later)</strong></p>
<p>At this point, I don't think it is possible to do what I originally wanted. I don't want to delete the question on the off chance that someone does answer it, but I'm not actively seeking an answer. (Though, receiving a valid answer would be awesome.)</p> | 14,855,668 | 4 | 2 | null | 2012-07-24 02:12:39.053 UTC | 5 | 2015-07-09 19:32:21.077 UTC | 2015-07-09 19:32:21.077 UTC | null | 15,882 | null | 915,148 | null | 1 | 29 | java|android|c++|process|android-camera | 8,563 | <p>I encountered a similar issue. The user should be able to change the flash mode during recording to meet their needs depending on the light situation. After some investigative research i came to the following solution:</p>
<p>I assume, that you've already set up a proper SurfaceView and a SurfaceHolder with its necessary callbacks. The first thing i did was providing this code (not declared variables are globals):</p>
<pre><code>public void surfaceCreated(SurfaceHolder holder) {
try {
camera = Camera.open();
parameters = camera.getParameters();
parameters.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(parameters);
camera.setPreviewDisplay(holder);
camera.startPreview();
recorder = new MediaRecorder();
} catch (IOException e) {
e.printStackTrace();
}
}
</code></pre>
<p>My next step was initializing and preparing the recorder:</p>
<pre><code>private void initialize() {
camera.unlock();
recorder.setCamera(camera);
recorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
recorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
recorder.setVideoFrameRate(20);
recorder.setOutputFile(filePath);
try {
recorder.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
finish();
} catch (IOException e) {
e.printStackTrace();
finish();
}
}
</code></pre>
<p>It's important to note, that camera.unlock() has to be called BEFORE the whole initialization process of the media recorder. That said also be aware of the proper order of each set property, otherwise you'll get an IllegalStateException when calling prepare() or start(). When it comes to recording, i do this. This will usually be triggered by a view element:</p>
<pre><code>public void record(View view) {
if (recording) {
recorder.stop();
//TODO: do stuff....
recording = false;
} else {
recording = true;
initialize();
recorder.start();
}
}
</code></pre>
<p>So now, i finally can record properly. But what's with that flash? Last but not least, here comes the magic behind the scenes:</p>
<pre><code>public void flash(View view) {
if(!recording) {
camera.lock();
}
parameters.setFlashMode(parameters.getFlashMode().equals(Parameters.FLASH_MODE_TORCH) ? Parameters.FLASH_MODE_OFF : Parameters.FLASH_MODE_TORCH);
camera.setParameters(parameters);
if(!recording) {
camera.unlock();
}
}
</code></pre>
<p>Everytime i call that method via an onClick action i can change the flash mode, even during recording. Just take care of properly locking the camera. Once the lock is aquired by the media recorder during recording, you don't have to lock/unlock the camera again. It doesn't even work. This was tested on a Samsung Galaxy S3 with Android-Version 4.1.2. Hope this approach helps.</p> |
11,830,979 | C++: strcpy Function copies null? | <p>While using string manipulation functions specificaly <code>strcpy</code> I did this small program.</p>
<pre><code>char s1[8]="Hellopo";
char s2[4]="sup";
strcpy(s1,s2);
cout<<s1<<endl;
</code></pre>
<p>When I printed out s1 It actually just printed out "sup". I expected it to print "suplopo".</p>
<p>Then I did this:</p>
<p><code>cout<<s1+4 << endl;</code></p>
<p>It printed out "opo";</p>
<p>And The output of this: <code>cout<<s1+3<<endl;</code> was nothing </p>
<p>So after thinking a bit about it. </p>
<p>I came to this conclusion. Since C++ stops outputing the string once it reaches the null terminator. Therefore the null must have been copied in the <code>strcpy</code> function. Resulting in this string:</p>
<p>s - u - p - \0 - o - p - o -\0;</p>
<p>Please tell me if this is correct or not. And if im not please correct me.</p>
<p>And if you have any more info to provide please do.</p> | 11,831,018 | 7 | 2 | null | 2012-08-06 15:10:38.057 UTC | 5 | 2019-07-08 10:51:04.197 UTC | null | null | null | null | 1,356,331 | null | 1 | 30 | c++|string|null | 65,190 | <p>Your reasoning is correct, and would have easily been confirmed by any decent <a href="http://linux.die.net/man/3/strcpy">manual</a>:</p>
<blockquote>
<p>The <code>strcpy()</code> function copies the string pointed to by <code>src</code>, including the terminating null byte (<code>'\0'</code>), to the buffer pointed to by <code>dest</code>.</p>
</blockquote> |
11,809,052 | Expression templates and C++11 | <p>Let's look at one particular benefit of expression templates: ETs can be used to avoid vector-sized temporaries in memory which occur in overloaded operators like:</p>
<pre><code>template<typename T>
std::vector<T> operator+(const std::vector<T>& a, const std::vector<T>& b)
{
std::vector<T> tmp; // vector-sized temporary
for_each(...);
return tmp;
}
</code></pre>
<p>In C++11 the return statement of this function applies move semantics. No copy of the vector. That's a win.</p>
<p>However, if I look at a simple expression like</p>
<pre><code>d = a + b + c;
</code></pre>
<p>I see that the above function gets called twice (for both <code>operator+</code>) while the final assignment can be done with move semantics.</p>
<p>In total 2 loops are executed. Means that I put out a temporary and read it back in right after. For big vectors this falls out of cache. That's worse than expression templates. They can do the whole thing in just 1 loop. ETs can execute the above code equivalent to:</p>
<pre><code>for(int i=0 ; i < vec_length ; ++i)
d[i] = a[i] + b[i] + c[i];
</code></pre>
<p>I was wondering whether lambdas together with move semantics or any other new feature can do as good as ETs. Any thoughts?</p>
<p><strong>Edit:</strong></p>
<p>Basically, using the ET technique the compiler builds a parse tree
that resembles the algebraic expression with it's
type system. This tree consists of inner nodes and leaf nodes. The
inner nodes represent operations (addition, multiplication, etc.) and
the leaf nodes represent references to the data objects.</p>
<p>I tried to think of the whole computation process in the fashion of a
stack machine: Take an operation from an operation stack and pull
the next arguments from the argument stack and evaluate the operation.
Put the result back on the stack waiting for the operation.</p>
<p>To represent these two different objects (operation stack and data
leaf stack) I bundled together a <code>std::tuple</code> for the operations and a
<code>std::tuple</code> for the data leaves into a <code>std::pair<></code>. Initially I
used a <code>std:vector</code> but that resulted in runtime overhead.</p>
<p>The whole process goes in two phases: Stack machine initialisation
where the operation and argument stack are initialised. And the
evaluation phase which is triggered by assigning the paired containers
to the vector.</p>
<p>I created a class <code>Vec</code> which holds a private <code>array<int,5></code> (the
payload) and which features an overloaded assignment operator that
takes the "expression".</p>
<p>The global <code>operator*</code> is overloaded for all combinations of taking
<code>Vec</code> and "expression" to enable the correct handling also in the case
where we have more than just <code>a*b</code>. (Notice, I switched for this
educational example to the multiplication - basically to quickly spot
the <code>imull</code> in the assembler.)</p>
<p>What is done first before the evaluation starts is "extracting" the
values out of the involved <code>Vec</code> objects and initializing the argument
stack. That was necessary to not have different kinds of objects lying
around: Indexable vectors and non-indexable results. This is what the
<code>Extractor</code> is for. Nice thing again: Variadic templates are used which
in this case results in no run-time overhead (all this is done at
compile time).</p>
<p>The whole thing works. The expression is nicely evaluated (I also
added the addition, but that is left out here to fit the code). Below
you can see the assembler output. Just raw compuation, exactly as you
want it to be: En-par with ET technique.</p>
<p>Upshot. The new language features of C++11 offer the variadic
templates which (along with template meta-programming) open up the
area of compile time computation. I showed here how the benefits of
variadic templates can be used to produce code as good as with the
traditional ET technique.</p>
<pre><code>#include<algorithm>
#include<iostream>
#include<vector>
#include<tuple>
#include<utility>
#include<array>
template<typename Target,typename Tuple, int N, bool end>
struct Extractor {
template < typename ... Args >
static Target index(int i,const Tuple& t, Args && ... args)
{
return Extractor<Target, Tuple, N+1,
std::tuple_size<Tuple>::value == N+1>::
index(i, t , std::forward<Args>(args)..., std::get<N>(t).vec[i] );
}
};
template < typename Target, typename Tuple, int N >
struct Extractor<Target,Tuple,N,true>
{
template < typename ... Args >
static Target index(int i,Tuple const& t,
Args && ... args) {
return Target(std::forward<Args>(args)...); }
};
template < typename ... Vs >
std::tuple<typename std::remove_reference<Vs>::type::type_t...>
extract(int i , const std::tuple<Vs...>& tpl)
{
return Extractor<std::tuple<typename std::remove_reference<Vs>::type::type_t...>,
std::tuple<Vs...>, 0,
std::tuple_size<std::tuple<Vs...> >::value == 0>::index(i,tpl);
}
struct Vec {
std::array<int,5> vec;
typedef int type_t;
template<typename... OPs,typename... VALs>
Vec& operator=(const std::pair< std::tuple<VALs...> , std::tuple<OPs...> >& e) {
for( int i = 0 ; i < vec.size() ; ++i ) {
vec[i] = eval( extract(i,e.first) , e.second );
}
}
};
template<int OpPos,int ValPos, bool end>
struct StackMachine {
template<typename... OPs,typename... VALs>
static void eval_pos( std::tuple<VALs...>& vals , const std::tuple<OPs...> & ops )
{
std::get<ValPos+1>( vals ) =
std::get<OpPos>(ops).apply( std::get<ValPos>( vals ) ,
std::get<ValPos+1>( vals ) );
StackMachine<OpPos+1,ValPos+1,sizeof...(OPs) == OpPos+1>::eval_pos(vals,ops);
}
};
template<int OpPos,int ValPos>
struct StackMachine<OpPos,ValPos,true> {
template<typename... OPs,typename... VALs>
static void eval_pos( std::tuple<VALs...>& vals ,
const std::tuple<OPs...> & ops )
{}
};
template<typename... OPs,typename... VALs>
int eval( const std::tuple<VALs...>& vals , const std::tuple<OPs...> & ops )
{
StackMachine<0,0,false>::eval_pos(const_cast<std::tuple<VALs...>&>(vals),ops);
return std::get<sizeof...(OPs)>(vals);
}
struct OpMul {
static int apply(const int& lhs,const int& rhs) {
return lhs*rhs;
}
};
std::pair< std::tuple< const Vec&, const Vec& > , std::tuple<OpMul> >
operator*(const Vec& lhs,const Vec& rhs)
{
return std::make_pair( std::tuple< const Vec&, const Vec& >( lhs , rhs ) ,
std::tuple<OpMul>( OpMul() ) );
}
template<typename... OPs,typename... VALs>
std::pair< std::tuple< const Vec&, VALs... > , std::tuple<OPs...,OpMul> >
operator*(const Vec& lhs,const std::pair< std::tuple< VALs... > , std::tuple<OPs...> >& rhs)
{
return std::make_pair( std::tuple_cat( rhs.first , std::tuple< const Vec& >(lhs) ) ,
std::tuple_cat( rhs.second , std::tuple<OpMul>( OpMul() ) ) );
}
template<typename... OPs,typename... VALs>
std::pair< std::tuple< const Vec&, VALs... > , std::tuple<OPs...,OpMul> >
operator*(const std::pair< std::tuple< VALs... > , std::tuple<OPs...> >& lhs,
const Vec& rhs)
{
return std::make_pair( std::tuple_cat( lhs.first , std::tuple< const Vec& >(rhs) ) ,
std::tuple_cat( lhs.second , std::tuple<OpMul>( OpMul() ) ) );
}
int main()
{
Vec d,c,b,a;
for( int i = 0 ; i < d.vec.size() ; ++i ) {
a.vec[i] = 10+i;
b.vec[i] = 20+i;
c.vec[i] = 30+i;
d.vec[i] = 0;
}
d = a * b * c * a;
for( int i = 0 ; i < d.vec.size() ; ++i )
std::cout << d.vec[i] << std::endl;
}
</code></pre>
<p>Assembler generated with <code>g++-4.6 -O3</code> (I had to put some runtime dependence into the vector initialization so that the compiler doesn't calculate the whole thing at compile time and you actually see the <code>imull</code> instaructions.)</p>
<pre><code>imull %esi, %edx
imull 32(%rsp), %edx
imull %edx, %esi
movl 68(%rsp), %edx
imull %ecx, %edx
movl %esi, (%rsp)
imull 36(%rsp), %edx
imull %ecx, %edx
movl 104(%rsp), %ecx
movl %edx, 4(%rsp)
movl 72(%rsp), %edx
imull %ecx, %edx
imull 40(%rsp), %edx
imull %ecx, %edx
movl 108(%rsp), %ecx
movl %edx, 8(%rsp)
movl 76(%rsp), %edx
imull %ecx, %edx
imull 44(%rsp), %edx
imull %ecx, %edx
movl 112(%rsp), %ecx
movl %edx, 12(%rsp)
movl 80(%rsp), %edx
imull %ecx, %edx
imull %eax, %edx
imull %ecx, %edx
movl %edx, 16(%rsp)
</code></pre> | 11,812,468 | 2 | 11 | null | 2012-08-04 13:32:35.083 UTC | 35 | 2013-10-18 10:13:14.233 UTC | 2012-08-06 19:14:40.123 UTC | null | 712,302 | null | 712,302 | null | 1 | 35 | c++|c++11|expression-templates | 12,587 | <blockquote>
<p>I was wondering whether lambdas together with move semantics or any other new feature can do as good as ETs. Any thoughts?</p>
</blockquote>
<p><strong>Quick Answer</strong></p>
<p>Move semantics are not a total panacea on their own --techniques such as expression templates (ETs) are still needed in C++11 to eliminate overheads such as moving data around! So, to answer your question quickly before diving into the rest of my answer, move semantics, etc. doesn't completely replace ETs as my answer illustrates below.</p>
<p><strong>Detailed Answer</strong></p>
<p>ETs typically return proxy objects to defer evaluation until later, so there is no immediate apparent benefit of C++11 language features until the code that triggers the computation. That said, one would not want to write ET code, however, that triggers run-time code generation during the building of the expression tree with the proxies. Nicely, C++11's move semantics and perfect forwarding can help avoid such overheads should that otherwise occur. (Such would not have been possible in C++03.)</p>
<p>Essentially, when writing ETs one wants to exploit the language features in a way to generate optimal code once the member function(s) of the involved proxy objects are invoked. In C++11 this will include using perfect forwarding, move semantics over copying, etc. if such is actually still needed over and above what the compiler can already do. The name of the game is to minimize the run-time code generated and/or maximize the run-time speed and/or minimize the run-time overhead.</p>
<p>I wanted to actually try some ETs with C++11 features to see if I could elide ALL intermediate temporary instance types with a <code>a = b + c + d;</code> expression. (As this was just a fun break from my normal activities so I did not compare it to or write ET code purely using C++03. Also I did not worry about all aspects of code polishing that appears below.)</p>
<p>To start with, I did not use lambdas --as I preferred to use explicit types and functions-- so I won't argue for/against lambdas with respect to your question. My guess is that they would be similar to using functors and performing no better than the non-ET code below (i.e., moves would be required) --at least until compilers can automatically optimize lambdas using their own internal ETs for such. The code I wrote, however, exploits move semantics and perfect forwarding. Here's what I did starting with the results and then finally presenting the code.</p>
<p>I created a <code>math_vector<N></code> class where <code>N==3</code> and it defines an internal private instance of <code>std::array<long double, N></code>. The members are a default constructor, copy and move constructors and assignments, an initializer list constructor, a destructor, a swap() member, operator [] to access elements of the vector and operator +=. Used without any expression templates, this code:</p>
<pre class="lang-cpp prettyprint-override"><code>{
cout << "CASE 1:\n";
math_vector<3> a{1.0, 1.1, 1.2};
math_vector<3> b{2.0, 2.1, 2.2};
math_vector<3> c{3.0, 3.1, 3.2};
math_vector<3> d{4.0, 4.1, 4.2};
math_vector<3> result = a + b + c + d;
cout << '[' << &result << "]: " << result << "\n";
}
</code></pre>
<p>outputs (when compiled with <code>clang++</code> 3.1 or <code>g++</code> 4.8 with -<code>std=c++11 -O3</code>):</p>
<pre class="lang-none prettyprint-override"><code>CASE 1:
0x7fff8d6edf50: math_vector(initlist)
0x7fff8d6edef0: math_vector(initlist)
0x7fff8d6ede90: math_vector(initlist)
0x7fff8d6ede30: math_vector(initlist)
0x7fff8d6edd70: math_vector(copy: 0x7fff8d6edf50)
0x7fff8d6edda0: math_vector(move: 0x7fff8d6edd70)
0x7fff8d6eddd0: math_vector(move: 0x7fff8d6edda0)
0x7fff8d6edda0: ~math_vector()
0x7fff8d6edd70: ~math_vector()
[0x7fff8d6eddd0]: (10,10.4,10.8)
0x7fff8d6eddd0: ~math_vector()
0x7fff8d6ede30: ~math_vector()
0x7fff8d6ede90: ~math_vector()
0x7fff8d6edef0: ~math_vector()
0x7fff8d6edf50: ~math_vector()
</code></pre>
<p>i.e., the four explicit constructed instances using initializer lists (i.e., the <code>initlist</code> items), the <code>result</code> variable (i.e., <code>0x7fff8d6eddd0</code>), and, also makes an additional three objects copying and moving.</p>
<p>To only focus on temporaries and moving, I created a second case that only creates <code>result</code> as a named variable --all others are rvalues:</p>
<pre class="lang-cpp prettyprint-override"><code>{
cout << "CASE 2:\n";
math_vector<3> result =
math_vector<3>{1.0, 1.1, 1.2} +
math_vector<3>{2.0, 2.1, 2.2} +
math_vector<3>{3.0, 3.1, 3.2} +
math_vector<3>{4.0, 4.1, 4.2}
;
cout << '[' << &result << "]: " << result << "\n";
}
</code></pre>
<p>which outputs this (again when ETs are NOT used):</p>
<pre class="lang-none prettyprint-override"><code>CASE 2:
0x7fff8d6edcb0: math_vector(initlist)
0x7fff8d6edc50: math_vector(initlist)
0x7fff8d6edce0: math_vector(move: 0x7fff8d6edcb0)
0x7fff8d6edbf0: math_vector(initlist)
0x7fff8d6edd10: math_vector(move: 0x7fff8d6edce0)
0x7fff8d6edb90: math_vector(initlist)
0x7fff8d6edd40: math_vector(move: 0x7fff8d6edd10)
0x7fff8d6edb90: ~math_vector()
0x7fff8d6edd10: ~math_vector()
0x7fff8d6edbf0: ~math_vector()
0x7fff8d6edce0: ~math_vector()
0x7fff8d6edc50: ~math_vector()
0x7fff8d6edcb0: ~math_vector()
[0x7fff8d6edd40]: (10,10.4,10.8)
0x7fff8d6edd40: ~math_vector()
</code></pre>
<p>which is better: only extra move objects are created.</p>
<p>But I wanted better: I wanted zero extra temporaries and to have the code as if I hard-coded it with the one normal coding caveat: all explicitly instantiated types would still be created (i.e., the four <code>initlist</code> constructors and <code>result</code>). To accomplish this I then added expression template code as follows:</p>
<ol>
<li>a proxy <code>math_vector_expr<LeftExpr,BinaryOp,RightExpr></code> class was created to hold an expression not computed yet,</li>
<li>a proxy <code>plus_op</code> class was created to hold the addition operation,</li>
<li>a constructor was added to <code>math_vector</code> to accept a <code>math_vector_expr</code> object, and,</li>
<li>"starter" member functions were added to trigger the creation of the expression template.</li>
</ol>
<p>The results using ETs are wonderful: no extra temporaries in either case! The previous two cases above now output:</p>
<pre class="lang-none prettyprint-override"><code>CASE 1:
0x7fffe7180c60: math_vector(initlist)
0x7fffe7180c90: math_vector(initlist)
0x7fffe7180cc0: math_vector(initlist)
0x7fffe7180cf0: math_vector(initlist)
0x7fffe7180d20: math_vector(expr: 0x7fffe7180d90)
[0x7fffe7180d20]: (10,10.4,10.8)
0x7fffe7180d20: ~math_vector()
0x7fffe7180cf0: ~math_vector()
0x7fffe7180cc0: ~math_vector()
0x7fffe7180c90: ~math_vector()
0x7fffe7180c60: ~math_vector()
CASE 2:
0x7fffe7180dd0: math_vector(initlist)
0x7fffe7180e20: math_vector(initlist)
0x7fffe7180e70: math_vector(initlist)
0x7fffe7180eb0: math_vector(initlist)
0x7fffe7180d20: math_vector(expr: 0x7fffe7180dc0)
0x7fffe7180eb0: ~math_vector()
0x7fffe7180e70: ~math_vector()
0x7fffe7180e20: ~math_vector()
0x7fffe7180dd0: ~math_vector()
[0x7fffe7180d20]: (10,10.4,10.8)
0x7fffe7180d20: ~math_vector()
</code></pre>
<p>i.e., exactly 5 constructor calls and 5 destructor calls in each case. In fact, if you ask the compiler to generate the assembler code between the 4 <code>initlist</code> constructor calls and the outputting of <code>result</code> one gets this beautiful string of assembler code:</p>
<pre><code>fldt 128(%rsp)
leaq 128(%rsp), %rdi
leaq 80(%rsp), %rbp
fldt 176(%rsp)
faddp %st, %st(1)
fldt 224(%rsp)
faddp %st, %st(1)
fldt 272(%rsp)
faddp %st, %st(1)
fstpt 80(%rsp)
fldt 144(%rsp)
fldt 192(%rsp)
faddp %st, %st(1)
fldt 240(%rsp)
faddp %st, %st(1)
fldt 288(%rsp)
faddp %st, %st(1)
fstpt 96(%rsp)
fldt 160(%rsp)
fldt 208(%rsp)
faddp %st, %st(1)
fldt 256(%rsp)
faddp %st, %st(1)
fldt 304(%rsp)
faddp %st, %st(1)
fstpt 112(%rsp)
</code></pre>
<p>with <code>g++</code> and <code>clang++</code> outputs similar (even smaller) code. No function calls, etc. --just a bunch of adds which is EXACTLY what one wants!</p>
<p>The C++11 code to achieve this follows. Simply <code>#define DONT_USE_EXPR_TEMPL</code> to not use ETs or don't define it at all to use ETs.</p>
<pre class="lang-cpp prettyprint-override"><code>#include <array>
#include <algorithm>
#include <initializer_list>
#include <type_traits>
#include <iostream>
//#define DONT_USE_EXPR_TEMPL
//===========================================================================
template <std::size_t N> class math_vector;
template <
typename LeftExpr,
typename BinaryOp,
typename RightExpr
>
class math_vector_expr
{
public:
math_vector_expr() = delete;
math_vector_expr(LeftExpr l, RightExpr r) :
l_(std::forward<LeftExpr>(l)),
r_(std::forward<RightExpr>(r))
{
}
// Prohibit copying...
math_vector_expr(math_vector_expr const&) = delete;
math_vector_expr& operator =(math_vector_expr const&) = delete;
// Allow moves...
math_vector_expr(math_vector_expr&&) = default;
math_vector_expr& operator =(math_vector_expr&&) = default;
template <typename RE>
auto operator +(RE&& re) const ->
math_vector_expr<
math_vector_expr<LeftExpr,BinaryOp,RightExpr> const&,
BinaryOp,
decltype(std::forward<RE>(re))
>
{
return
math_vector_expr<
math_vector_expr<LeftExpr,BinaryOp,RightExpr> const&,
BinaryOp,
decltype(std::forward<RE>(re))
>(*this, std::forward<RE>(re))
;
}
auto le() ->
typename std::add_lvalue_reference<LeftExpr>::type
{ return l_; }
auto le() const ->
typename std::add_lvalue_reference<
typename std::add_const<LeftExpr>::type
>::type
{ return l_; }
auto re() ->
typename std::add_lvalue_reference<RightExpr>::type
{ return r_; }
auto re() const ->
typename std::add_lvalue_reference<
typename std::add_const<RightExpr>::type
>::type
{ return r_; }
auto operator [](std::size_t index) const ->
decltype(
BinaryOp::apply(this->le()[index], this->re()[index])
)
{
return BinaryOp::apply(le()[index], re()[index]);
}
private:
LeftExpr l_;
RightExpr r_;
};
//===========================================================================
template <typename T>
struct plus_op
{
static T apply(T const& a, T const& b)
{
return a + b;
}
static T apply(T&& a, T const& b)
{
a += b;
return std::move(a);
}
static T apply(T const& a, T&& b)
{
b += a;
return std::move(b);
}
static T apply(T&& a, T&& b)
{
a += b;
return std::move(a);
}
};
//===========================================================================
template <std::size_t N>
class math_vector
{
using impl_type = std::array<long double, N>;
public:
math_vector()
{
using namespace std;
fill(begin(v_), end(v_), impl_type{});
std::cout << this << ": math_vector()" << endl;
}
math_vector(math_vector const& mv) noexcept
{
using namespace std;
copy(begin(mv.v_), end(mv.v_), begin(v_));
std::cout << this << ": math_vector(copy: " << &mv << ")" << endl;
}
math_vector(math_vector&& mv) noexcept
{
using namespace std;
move(begin(mv.v_), end(mv.v_), begin(v_));
std::cout << this << ": math_vector(move: " << &mv << ")" << endl;
}
math_vector(std::initializer_list<typename impl_type::value_type> l)
{
using namespace std;
copy(begin(l), end(l), begin(v_));
std::cout << this << ": math_vector(initlist)" << endl;
}
math_vector& operator =(math_vector const& mv) noexcept
{
using namespace std;
copy(begin(mv.v_), end(mv.v_), begin(v_));
std::cout << this << ": math_vector op =(copy: " << &mv << ")" << endl;
return *this;
}
math_vector& operator =(math_vector&& mv) noexcept
{
using namespace std;
move(begin(mv.v_), end(mv.v_), begin(v_));
std::cout << this << ": math_vector op =(move: " << &mv << ")" << endl;
return *this;
}
~math_vector()
{
using namespace std;
std::cout << this << ": ~math_vector()" << endl;
}
void swap(math_vector& mv)
{
using namespace std;
for (std::size_t i = 0; i<N; ++i)
swap(v_[i], mv[i]);
}
auto operator [](std::size_t index) const
-> typename impl_type::value_type const&
{
return v_[index];
}
auto operator [](std::size_t index)
-> typename impl_type::value_type&
{
return v_[index];
}
math_vector& operator +=(math_vector const& b)
{
for (std::size_t i = 0; i<N; ++i)
v_[i] += b[i];
return *this;
}
#ifndef DONT_USE_EXPR_TEMPL
template <typename LE, typename Op, typename RE>
math_vector(math_vector_expr<LE,Op,RE>&& mve)
{
for (std::size_t i = 0; i < N; ++i)
v_[i] = mve[i];
std::cout << this << ": math_vector(expr: " << &mve << ")" << std::endl;
}
template <typename RightExpr>
math_vector& operator =(RightExpr&& re)
{
for (std::size_t i = 0; i<N; ++i)
v_[i] = re[i];
return *this;
}
template <typename RightExpr>
math_vector& operator +=(RightExpr&& re)
{
for (std::size_t i = 0; i<N; ++i)
v_[i] += re[i];
return *this;
}
template <typename RightExpr>
auto operator +(RightExpr&& re) const ->
math_vector_expr<
math_vector const&,
plus_op<typename impl_type::value_type>,
decltype(std::forward<RightExpr>(re))
>
{
return
math_vector_expr<
math_vector const&,
plus_op<typename impl_type::value_type>,
decltype(std::forward<RightExpr>(re))
>(
*this,
std::forward<RightExpr>(re)
)
;
}
#endif // #ifndef DONT_USE_EXPR_TEMPL
private:
impl_type v_;
};
//===========================================================================
template <std::size_t N>
inline void swap(math_vector<N>& a, math_vector<N>& b)
{
a.swap(b);
}
//===========================================================================
#ifdef DONT_USE_EXPR_TEMPL
template <std::size_t N>
inline math_vector<N> operator +(
math_vector<N> const& a,
math_vector<N> const& b
)
{
math_vector<N> retval(a);
retval += b;
return retval;
}
template <std::size_t N>
inline math_vector<N> operator +(
math_vector<N>&& a,
math_vector<N> const& b
)
{
a += b;
return std::move(a);
}
template <std::size_t N>
inline math_vector<N> operator +(
math_vector<N> const& a,
math_vector<N>&& b
)
{
b += a;
return std::move(b);
}
template <std::size_t N>
inline math_vector<N> operator +(
math_vector<N>&& a,
math_vector<N>&& b
)
{
a += std::move(b);
return std::move(a);
}
#endif // #ifdef DONT_USE_EXPR_TEMPL
//===========================================================================
template <std::size_t N>
std::ostream& operator <<(std::ostream& os, math_vector<N> const& mv)
{
os << '(';
for (std::size_t i = 0; i < N; ++i)
os << mv[i] << ((i+1 != N) ? ',' : ')');
return os;
}
//===========================================================================
int main()
{
using namespace std;
try
{
{
cout << "CASE 1:\n";
math_vector<3> a{1.0, 1.1, 1.2};
math_vector<3> b{2.0, 2.1, 2.2};
math_vector<3> c{3.0, 3.1, 3.2};
math_vector<3> d{4.0, 4.1, 4.2};
math_vector<3> result = a + b + c + d;
cout << '[' << &result << "]: " << result << "\n";
}
cout << endl;
{
cout << "CASE 2:\n";
math_vector<3> result =
math_vector<3>{1.0, 1.1, 1.2} +
math_vector<3>{2.0, 2.1, 2.2} +
math_vector<3>{3.0, 3.1, 3.2} +
math_vector<3>{4.0, 4.1, 4.2}
;
cout << '[' << &result << "]: " << result << "\n";
}
}
catch (...)
{
return 1;
}
}
//===========================================================================
</code></pre> |
11,789,407 | Socket connections and Polling. Which is a better solution in terms of battery life? | <p>So... I'm making an application for Android. The application needs to send and receive realtime chat data (needs to be a socket) but it also needs to send commands (which don't as the client knows when it is sending something). </p>
<p>I need to know what is a better solution in terms of saving the user's battery.</p>
<p><strong>a)</strong> Opening and Closing the connection every time a command is sent, if the chat tab is opened then keep the connection constant. </p>
<p><strong>b)</strong> Keep the connection constant all the time. </p>
<p>I've taken a look around the internet but have gotten mixed answers, some say keeping a persistent connection is bad for battery life and others say that it isn't (Example: <em>"Are you asking if holding a TCP connection open will drain battery-life? Maybe I am WAY off here but, holding a connection open shouldn't waste battery life... If you think it will I would love to know where you got that information. It sounds SO strange to me."</em>)</p>
<p>Or if there is another solution that would be better. I don't think that Google's C2DM would be very useful at all in this situation either. </p>
<p>Basically, what drains the battery more: having a persistent connection, or opening and closing the connection unless the chat tab is open?</p>
<p>Thanks!</p> | 11,789,809 | 3 | 1 | null | 2012-08-03 04:44:55.55 UTC | 21 | 2016-05-10 01:52:05.693 UTC | 2016-05-10 01:52:05.693 UTC | null | 1,091,077 | null | 1,091,077 | null | 1 | 42 | android|sockets|tcp|polling|battery | 22,502 | <p>Keeping an idle TCP socket connection open (with no data being sent or received) will not (or at least, should not) consume any more battery than having it closed. That is because an idle TCP connection uses no bandwidth or CPU cycles(*).</p>
<p>That said, keeping a TCP connection open for extended periods may not be a good option for a mobile device, because TCP connections don't interact well with computers that go to sleep. The problem scenario would be this: your Android user puts his Android device to sleep while your app is running, and then the remote user's program (or whatever is at the other end of the TCP connection) sends some data over the TCP stream. The remote user's program never gets any ACKs back from the Android device, because of course the Android device is asleep, so the remote device's TCP stack assumes that the TCP packets it sent must have been lost, and it responds by increasing its timeout period, decreasing its TCP window size (aka number-of-TCP-packets-allowed-in-flight-at-once), and resending the TCP packets. But the Android device is still asleep, and thus the same thing happens again. The upshot is that a few minutes later, the remote end of the TCP connection has slowed down to the point where even if the Android device was to wake up, the TCP connection will likely be too slow to be usable -- at which point your program will need to close the bogged-down TCP connection and start up a fresh one anyway, so why bother trying to keep it open?</p>
<p>So my recommendation would be to go with option (a), with the stipulation that you close the TCP connection as part of your device-is-going-to-sleep-now routine.</p>
<p>One possible caveat would be if Android has a feature where keeping a TCP connection open causes the WiFi or cell-network hardware to remain powered up in a situation where it could otherwise be put to sleep -- if that is the case, then the Android device would pay a battery cost for powering the antenna, which it wouldn't otherwise have had to pay. I'm not aware of any Android logic like that, but I've only used Android a little so that might just be ignorance on my part. It might be worth testing for, at least.</p>
<p>(*) Well, technically TCP does send a "keepalive" packet every so often while a TCP connection is open, and that does use some CPU cycles and antenna power... but the default interval for sending keepalive packets on Android is <a href="https://stackoverflow.com/questions/6565667/how-to-set-the-keepalive-timeout-in-android">two hours</a>, so I doubt the power used for that would be noticeable.</p> |
11,662,295 | php.ini changes, but not effective on Ubuntu | <p>I want change the limit of PHP upload file's size</p>
<p>And this is some information of the output my <a href="https://www.php.net/manual/en/function.phpinfo.php" rel="nofollow noreferrer">phpinfo</a>:</p>
<pre class="lang-none prettyprint-override"><code>Configuration File (php.ini) Path /etc/php5/apache2
Loaded Configuration File /etc/php5/apache2/php.ini
</code></pre>
<p>And this is the content of my <em>php.ini</em> file:</p>
<pre class="lang-none prettyprint-override"><code>upload_max_filesize = 50M
post_max_size = 50M
memory_limit = 128M
</code></pre>
<p>Then I restart Apache 2, but the phpinfo shown is still:</p>
<pre class="lang-none prettyprint-override"><code>upload_max_filesize 2M
</code></pre> | 11,673,121 | 8 | 1 | null | 2012-07-26 04:20:44.097 UTC | 12 | 2021-11-04 23:58:15.583 UTC | 2021-10-26 17:12:05.19 UTC | null | 63,550 | null | 1,249,094 | null | 1 | 44 | php|linux|ubuntu|apache2 | 94,786 | <p>I have solved my question.</p>
<p>There is a syntax error in <em>php.ini</em> in line 109, so the next all syntax does not execute.</p> |
11,516,657 | C++ Structure Initialization | <p>Is it possible to initialize structs in C++ as indicated below:</p>
<pre><code>struct address {
int street_no;
char *street_name;
char *city;
char *prov;
char *postal_code;
};
address temp_address = { .city = "Hamilton", .prov = "Ontario" };
</code></pre>
<p>The links <a href="http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=/com.ibm.xlcpp8a.doc/language/ref/strin.htm" rel="noreferrer">here</a> and <a href="https://stackoverflow.com/questions/5790534/static-structure-initialization-with-tags-in-c">here</a> mention that it is possible to use this style only in C. If so why is this not possible in C++? Is there any underlying technical reason why it is not implemented in C++, or is it bad practice to use this style. I like using this way of initializing because my struct is big and this style gives me clear readability of what value is assigned to which member.</p>
<p>Please share with me if there are other ways through which we can achieve the same readability.</p>
<p>I have referred the following links before posting this question:</p>
<ol>
<li><a href="http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=/com.ibm.xlcpp8a.doc/language/ref/strin.htm" rel="noreferrer">C/C++ for AIX</a></li>
<li><a href="https://stackoverflow.com/questions/7700878/c-structure-initialization-with-variable">C Structure Initialization with Variable</a></li>
<li><a href="https://stackoverflow.com/questions/5790534/static-structure-initialization-with-tags-in-c">Static structure initialization with tags in C++</a></li>
<li><a href="https://stackoverflow.com/questions/9557464/c11-proper-structure-initialization">C++11 Proper Structure Initialization</a></li>
</ol> | 11,516,847 | 17 | 11 | null | 2012-07-17 05:46:22.74 UTC | 74 | 2022-08-09 13:51:23.473 UTC | 2022-08-09 13:51:23.473 UTC | null | 819,340 | null | 1,040,174 | null | 1 | 359 | c++|struct|initialization | 664,799 | <p>If you want to make it clear what each initializer value is, just split it up on multiple lines, with a comment on each:</p>
<pre><code>address temp_addres = {
0, // street_no
nullptr, // street_name
"Hamilton", // city
"Ontario", // prov
nullptr, // postal_code
};
</code></pre> |
20,326,356 | How to remove all the occurrences of a char in c++ string | <p>I am using following:</p>
<pre><code>replace (str1.begin(), str1.end(), 'a' , '')
</code></pre>
<p>But this is giving compilation error.</p> | 20,326,454 | 13 | 4 | null | 2013-12-02 10:46:52.1 UTC | 32 | 2021-11-02 19:27:39.623 UTC | null | null | null | null | 1,216,931 | null | 1 | 138 | c++|stl | 292,257 | <p>Basically, <code>replace</code> replaces a character with another and <code>''</code> is not a character. What you're looking for is <code>erase</code>.</p>
<p>See <a href="https://stackoverflow.com/questions/5891610/how-to-remove-characters-from-a-string">this question</a> which answers the same problem. In your case:</p>
<pre><code>#include <algorithm>
str.erase(std::remove(str.begin(), str.end(), 'a'), str.end());
</code></pre>
<p>Or use <code>boost</code> if that's an option for you, like:</p>
<pre><code>#include <boost/algorithm/string.hpp>
boost::erase_all(str, "a");
</code></pre>
<p>All of this is well-documented on <a href="http://www.cplusplus.com/" rel="noreferrer">reference</a> <a href="http://en.cppreference.com/w/" rel="noreferrer">websites</a>. But if you didn't know of these functions, you could easily do this kind of things by hand:</p>
<pre><code>std::string output;
output.reserve(str.size()); // optional, avoids buffer reallocations in the loop
for(size_t i = 0; i < str.size(); ++i)
if(str[i] != 'a') output += str[i];
</code></pre> |
3,671,522 | REGEX: Capture Filename from URL without file extension | <p>I am trying to create a Javascript Regex that captures the filename without the file extension. I have read the other posts here and <em>'goto this page:</em> <a href="http://gunblad3.blogspot.com/2008/05/uri-url-parsing.html" rel="nofollow noreferrer">http://gunblad3.blogspot.com/2008/05/uri-url-parsing.html</a>' seems to be the default answer. This doesn't seem to do the job for me. So here is how I'm trying to get the regex to work:</p>
<ol>
<li>Find the last forward slash '/' in the subject string.</li>
<li>Capture everything between that slash and the next period.</li>
</ol>
<p>The closest I could get was : <strong>/([^/]<em>).\w</em>$</strong> Which on the string <strong>'<a href="http://example.com/index.htm" rel="nofollow noreferrer">http://example.com/index.htm</a>'</strong> exec() would capture <strong>/index.htm</strong> and <strong>index</strong>. </p>
<p>I need this to only capture <em>index</em>.</p> | 3,671,574 | 5 | 0 | null | 2010-09-08 20:13:50.653 UTC | 13 | 2019-05-10 08:30:34.887 UTC | 2017-12-15 14:58:01.467 UTC | null | 1,033,581 | null | 77,358 | null | 1 | 12 | javascript|regex|url | 26,106 | <pre><code>var url = "http://example.com/index.htm";
var filename = url.match(/([^\/]+)(?=\.\w+$)/)[0];
</code></pre>
<p>Let's go through the regular expression:</p>
<pre><code>[^\/]+ # one or more character that isn't a slash
(?= # open a positive lookahead assertion
\. # a literal dot character
\w+ # one or more word characters
$ # end of string boundary
) # end of the lookahead
</code></pre>
<p>This expression will collect all characters that aren't a slash that are immediately followed (thanks to the <a href="http://www.regular-expressions.info/lookaround.html" rel="noreferrer">lookahead</a>) by an extension and the end of the string -- or, in other words, everything after the last slash and until the extension.</p>
<p>Alternately, you can do this without regular expressions altogether, by finding the position of the last <code>/</code> and the last <code>.</code> using <a href="http://www.w3schools.com/jsref/jsref_lastIndexOf.asp" rel="noreferrer"><code>lastIndexOf</code></a> and getting a <a href="http://www.w3schools.com/jsref/jsref_substring.asp" rel="noreferrer"><code>substring</code></a> between those points:</p>
<pre><code>var url = "http://example.com/index.htm";
var filename = url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf("."));
</code></pre> |
3,915,952 | How to save state during orientation change in Android if the state is made of my classes? | <p>I was looking at the way Android handles orientation change for my application (I discovered that it restarts the mainactivity on orientation change. I've seen that you can override the method </p>
<pre><code>protected void onSaveInstanceState(Bundle outState)
</code></pre>
<p>To save stuff, then have the in onStart. The problem is that I've my view with custom objects and a listview using a custom adapter. Everything is in a ArrayList of these objects, but I've noticed that you can't put arbitrary objects in the bundle! So how do I save the state? </p> | 3,916,068 | 6 | 0 | null | 2010-10-12 14:55:51.037 UTC | 25 | 2019-06-26 07:41:11.873 UTC | 2013-07-16 03:42:10.25 UTC | null | 815,724 | null | 138,606 | null | 1 | 56 | android | 94,836 | <p><strong>EDIT:</strong> On newer versions of Android and with the compatibility library, <a href="http://www.androiddesignpatterns.com/2013/04/retaining-objects-across-config-changes.html" rel="noreferrer">retained fragments</a> are usually the best way to handle keeping expensive-to-recreate data alive across activity destruction/creation. And as Dianne pointed out, retaining nonconfiguration data was for optimizing things like thumbnail generation that are nice to save for performance reasons but not critical to your activity functioning if they need to be redone - it's not a substitute for properly saving and restoring activity state.</p>
<p>But back when I first answered this in 2010:<br>
If you want to retain your own (non view-state) data, you can actually pass an arbitrary object specifically for orientation changes using <code>onRetainNonConfigurationInstance()</code>. See <a href="http://android-developers.blogspot.co.uk/2009/02/faster-screen-orientation-change.html" rel="noreferrer">this Android Developers blog post</a>. Just be careful not to put any Views or other references to the pre-rotation Context/Activity in the object you pass, or you'll prevent those objects from being garbage collected and may eventually run out of memory (this is called a <a href="http://android-developers.blogspot.com/2009/01/avoiding-memory-leaks.html" rel="noreferrer">context leak</a>).</p> |
3,865,335 | What is a lambda language? | <p>I was reading "JavaScript: The Good Parts" and the author mentions that JavaScript is the first of the lambda languages to be launched. </p>
<blockquote>
<p>JavaScript's functions are first class objects with (mostly) lexical scoping. JavaScript is the first <strong>lambda language</strong> to go mainstream. Deep down, JavaScript has more in common with Lisp and Scheme than with Java. It is Lisp in C's clothing. This makes JavaScript is remarkably powerful language.</p>
</blockquote>
<p>I didn't get what is a lambda language. What are the properties of such a language and how is it different from languages like Java, C, C++ and Php?</p> | 3,865,387 | 7 | 5 | null | 2010-10-05 15:45:20.913 UTC | 16 | 2017-10-26 06:03:25.047 UTC | 2014-03-28 14:09:01.79 UTC | null | 292,408 | null | 337,522 | null | 1 | 91 | javascript|lambda | 28,999 | <p>I've never heard anyone use the term "lambda language," and the only plausible definitions I can think of would exclude JavaScript as "the first."</p>
<p>That said, I suspect he may mean either:</p>
<ul>
<li>Functional languages: a class of languages in which computation is (or can be) modeled as a stateless composition of (possibly higher-order) functions. LISP, Scheme, ML, Haskell, etc. are frequently ascribed to this class, although several of these are more properly mixed paradigm or "functional optional" languages. Javascript arguably contains the necessary features to make a "functional style" of programming possible.</li>
<li>Languages which allow the creation of anonymous functions (using the <code>function</code> syntax in JavaScript; this is written <code>lambda</code> in many languages, hence possibly "lambda languages."</li>
</ul>
<p>Both usages are derived from the use of the greek letter lambda to denote function abstraction in the lambda calculus, the model of computation devised by Alonzo Church and upon which functional programming is based.</p>
<p>Edit: looked at Google Books result---"first to go mainstream"; well, that's arguable. I'd put forward that LISP was at one point at least reasonably mainstream. It's a fair point though, JavaScript's semantics are directly inspired by Scheme and it certainly reached a larger audience than any other language that can make similar claims.</p> |
3,912,204 | Why is there no PRODUCT aggregate function in SQL? | <p>Im looking for something like <code>SELECT PRODUCT(table.price) FROM table GROUP BY table.sale</code> similar to how <code>SUM</code> works.</p>
<p>Have I missed something on the documentation, or is there really no <code>PRODUCT</code> function?</p>
<p>If so, why not?</p>
<p>Note: I looked for the function in postgres, mysql and mssql and found none so I assumed all sql does not support it.</p> | 3,912,704 | 10 | 9 | null | 2010-10-12 06:42:11.16 UTC | 11 | 2021-12-07 10:18:17.24 UTC | 2012-01-13 16:27:30.56 UTC | null | 866,022 | null | 24,744 | null | 1 | 57 | sql|aggregate | 56,803 | <p>There is no <code>PRODUCT</code> set function in the SQL Standard. It would appear to be a worthy candidate, though (unlike, say, a <code>CONCATENATE</code> set function: it's not a good fit for SQL e.g. the resulting data type would involve multivalues and pose a problem as regards first normal form).</p>
<p>The SQL Standards aim to consolidate functionality across SQL products circa 1990 and to provide 'thought leadership' on future development. In short, they document what SQL does and what SQL should do. The absence of <code>PRODUCT</code> set function suggests that in 1990 no vendor though it worthy of inclusion and there has been no academic interest in introducing it into the Standard.</p>
<p>Of course, vendors always have sought to add their own functionality, these days usually as extentions to Standards rather than tangentally. I don't recall seeing a <code>PRODUCT</code> set function (or even demand for one) in any of the SQL products I've used. </p>
<p>In any case, the work around is fairly simple using <code>log</code> and <code>exp</code> scalar functions (and logic to handle negatives) with the <code>SUM</code> set function; see @gbn's answer for some sample code. I've never needed to do this in a business application, though.</p>
<p>In conclusion, my best guess is that there is no demand from SQL end users for a <code>PRODUCT</code> set function; further, that anyone with an academic interest would probably find the workaround acceptable (i.e. would not value the syntactic sugar a <code>PRODUCT</code> set function would provide).</p>
<p>Out of interest, there is indeed demand in SQL Server Land for new set functions but for those of the window function variety (and Standard SQL, too). For more details, including how to get involved in further driving demand, see <a href="http://www.sqlmag.com/blogs/puzzled-by-t-sql/tabid/1023/entryid/13085/Window-Functions-OVER-Clause-Help-Make-a-Difference.aspx" rel="noreferrer">Itzik Ben-Gan's blog</a>. </p> |
3,603,502 | Prevent creating new attributes outside __init__ | <p>I want to be able to create a class (in Python) that once initialized with <code>__init__</code>, does not accept new attributes, but accepts modifications of existing attributes. There's several hack-ish ways I can see to do this, for example having a <code>__setattr__</code> method such as</p>
<pre><code>def __setattr__(self, attribute, value):
if not attribute in self.__dict__:
print "Cannot set %s" % attribute
else:
self.__dict__[attribute] = value
</code></pre>
<p>and then editing <code>__dict__</code> directly inside <code>__init__</code>, but I was wondering if there is a 'proper' way to do this?</p> | 3,603,824 | 12 | 2 | null | 2010-08-30 19:20:36.11 UTC | 39 | 2022-07-11 18:01:55.547 UTC | 2018-01-08 09:50:55.55 UTC | null | 5,658,350 | null | 180,783 | null | 1 | 103 | python|python-3.x|class|oop|python-datamodel | 32,307 | <p>I wouldn't use <code>__dict__</code> directly, but you can add a function to explicitly "freeze" a instance:</p>
<pre><code>class FrozenClass(object):
__isfrozen = False
def __setattr__(self, key, value):
if self.__isfrozen and not hasattr(self, key):
raise TypeError( "%r is a frozen class" % self )
object.__setattr__(self, key, value)
def _freeze(self):
self.__isfrozen = True
class Test(FrozenClass):
def __init__(self):
self.x = 42#
self.y = 2**3
self._freeze() # no new attributes after this point.
a,b = Test(), Test()
a.x = 10
b.z = 10 # fails
</code></pre> |
3,608,411 | Python: How can I find all files with a particular extension? | <p>I am trying to find all the <code>.c</code> files in a directory using Python. </p>
<p>I wrote this, but it is just returning me all files - not just <code>.c</code> files.</p>
<pre><code>import os
import re
results = []
for folder in gamefolders:
for f in os.listdir(folder):
if re.search('.c', f):
results += [f]
print results
</code></pre>
<p>How can I just get the <code>.c</code> files?</p> | 3,608,468 | 15 | 2 | null | 2010-08-31 11:13:15.193 UTC | 10 | 2021-08-29 02:32:19.433 UTC | 2010-08-31 15:13:31.277 UTC | null | 19,020 | null | 182,448 | null | 1 | 28 | python | 65,566 | <p>try changing the inner loop to something like this</p>
<pre><code>results += [each for each in os.listdir(folder) if each.endswith('.c')]
</code></pre> |
7,759,200 | Is there any possibility to have JSON.stringify preserve functions? | <p>Take this object:</p>
<pre><code>x = {
"key1": "xxx",
"key2": function(){return this.key1}
}
</code></pre>
<p>If I do this:</p>
<pre><code>y = JSON.parse( JSON.stringify(x) );
</code></pre>
<p>Then y will return <code>{ "key1": "xxx" }</code>. Is there anything one could do to transfer functions via stringify? Creating an object with attached functions is possible with the "ye goode olde eval()", but whats with packing it?</p> | 7,759,285 | 10 | 5 | null | 2011-10-13 19:09:18.46 UTC | 11 | 2022-09-03 14:07:42.403 UTC | null | null | null | null | 988,957 | null | 1 | 32 | javascript|json|object | 25,184 | <p>You can't pack functions since the data they close over is not visible to any serializer.
Even Mozilla's <code>uneval</code> cannot pack closures properly.</p>
<p>Your best bet, is to use a reviver and a replacer.</p>
<p><a href="https://yuilibrary.com/yui/docs/json/json-freeze-thaw.html" rel="nofollow noreferrer">https://yuilibrary.com/yui/docs/json/json-freeze-thaw.html</a></p>
<blockquote>
<p>The reviver function passed to JSON.parse is applied to all key:value pairs in the raw parsed object from the deepest keys to the highest level. In our case, this means that the name and discovered properties will be passed through the reviver, and then the object containing those keys will be passed through.</p>
</blockquote> |
4,144,378 | How to find the Server Name of MySQL | <p>Where can I find the name of MySQL which I'll use at the connection string to connect to the database from c#?</p> | 4,146,194 | 3 | 4 | null | 2010-11-10 12:20:48.87 UTC | 0 | 2014-06-05 08:29:13.827 UTC | null | null | null | null | 132,640 | null | 1 | 8 | mysql|connection-string | 92,027 | <p>"Unhandled Exception: MySql.Data.MySqlClient.MySqlException: Access denied for user 'root'@'sfn-inkubator-70-61.hib.no' (using password: YES)" error means that you have setup connection address correctly. Client connects to server, but server rejects username and password combination.</p>
<p>So you need to check your server setup, create some user with known password and so on......</p> |
4,165,452 | How to efficiently manage frequent schema changes using sqlalchemy? | <p>I'm programming a web application using sqlalchemy. Everything was smooth during the first phase of development when the site was not in production. I could easily change the database schema by simply deleting the old sqlite database and creating a new one from scratch. </p>
<p>Now the site is in production and I need to preserve the data, but I still want to keep my original development speed by easily converting the database to the new schema. </p>
<p>So let's say that I have model.py at revision 50 and model.py a revision 75, describing the schema of the database. Between those two schema most changes are trivial, for example a new column is declared with a default value and I just want to add this default value to old records. </p>
<p>Eventually a few changes may not be trivial and require some pre-computation. </p>
<p>How do (or would) you handle fast changing web applications with, say, one or two new version of the production code per day ?</p>
<p>By the way, the site is written in Pylons if this makes any difference.</p> | 13,467,138 | 4 | 6 | null | 2010-11-12 14:08:55.487 UTC | 30 | 2018-10-08 14:17:51.87 UTC | 2013-10-10 11:40:53.88 UTC | null | 49,886 | null | 49,886 | null | 1 | 63 | python|sqlalchemy|pylons|data-migration|migrate | 33,453 | <p><a href="https://pypi.python.org/pypi/alembic" rel="noreferrer">Alembic</a> is a new database migrations tool, written by the author of SQLAlchemy. I've found it much easier to use than sqlalchemy-migrate. It also works seamlessly with Flask-SQLAlchemy.</p>
<p>Auto generate the schema migration script from your SQLAlchemy models:</p>
<pre><code>alembic revision --autogenerate -m "description of changes"
</code></pre>
<p>Then apply the new schema changes to your database:</p>
<pre><code>alembic upgrade head
</code></pre>
<p>More info here: <a href="http://readthedocs.org/docs/alembic/" rel="noreferrer">http://readthedocs.org/docs/alembic/</a></p> |
4,128,436 | Query String Manipulation in Java | <p>Does anyone have, or know of, a java class that I can use to manipulate query strings?</p>
<p>Essentially I'd like a class that I can simply give a query string to and then delete, add and modify query string KVP's.</p>
<p>Thanks in advance.</p>
<p><strong>EDIT</strong></p>
<p>In response to a comment made to this question, the query string will look something like this;</p>
<pre><code>N=123+456+112&Ntt=koala&D=abc
</code></pre>
<p>So I'd like to pass this class the query string and say something like;</p>
<pre><code>String[] N = queryStringClass.getParameter("N");
</code></pre>
<p>and then maybe</p>
<pre><code>queryStringClass.setParameter("N", N);
</code></pre>
<p>and maybe <code>queryStringClass.removeParameter("N");</code></p>
<p>Or something to that effect.</p> | 4,128,529 | 5 | 2 | null | 2010-11-08 21:51:24.72 UTC | 3 | 2017-09-08 10:08:30.567 UTC | 2010-11-08 22:52:16.767 UTC | null | 231,917 | null | 129,195 | null | 1 | 19 | java|string | 62,939 | <p>SOmething like this</p>
<pre><code> public static Map<String, String> getQueryMap(String query)
{
String[] params = query.split("&");
Map<String, String> map = new HashMap<String, String>();
for (String param : params)
{
String name = param.split("=")[0];
String value = param.split("=")[1];
map.put(name, value);
}
return map;
}
</code></pre>
<p>To iterate the map simply:</p>
<pre><code> String query = url.getQuery();
Map<String, String> map = getQueryMap(query);
Set<String> keys = map.keySet();
for (String key : keys)
{
System.out.println("Name=" + key);
System.out.println("Value=" + map.get(key));
}
</code></pre> |
4,542,536 | Is it Possible to Return a Reference to a Variable in C#? | <p>Can I return a reference to a double value for example?</p>
<p>This is what I want to do:</p>
<pre><code>ref double GetElement()
{
......
// Calculate x,y,z
return ref doubleArray[x,y,z];
}
</code></pre>
<p>To use it like this</p>
<pre><code>void func()
{
GetElement()=5.0;
}
</code></pre>
<p>It is like returning a double pointer in C++ ...
I know that the way I wrote it is wrong.. but is there a correct way for doing it?</p> | 4,542,601 | 5 | 12 | null | 2010-12-27 23:17:05.347 UTC | 9 | 2019-12-03 16:24:56.997 UTC | 2010-12-28 02:13:35 UTC | null | 76,337 | null | 279,691 | null | 1 | 34 | c#|reference|return-value | 34,292 | <h2>Update</h2>
<p>This feature has been added to C# 7. You can use syntax just like you posted in your question. For example:</p>
<pre><code>double[,,] doubleArray = new double[10,10,10];
ref double GetElement()
{
var (x,y,z) = (1,2,3);
return ref doubleArray[x, y, z];
}
</code></pre>
<p><a href="https://stackoverflow.com/a/4543089/120955">Eric Lippert's answer</a> goes into detail. I would probably delete this answer, but as it's the accepted answer I cannot delete it.</p>
<h2>Original Answer</h2>
<p>Value types in C# are always passed by value. Objects always have their reference passed by value. This changes in "unsafe" code as Axarydax points out.</p>
<p>The easiest, safest way to avoid this constraint is to make sure that your double is attached to an object somehow.</p>
<pre><code>public class MyObjectWithADouble {
public double Element {get; set;} // property is optional, but preferred.
}
...
var obj = new MyObjectWithADouble();
obj.Element = 5.0
</code></pre>
<p><strike>I also want to remark that I'm a little confused about how you anticipate assigning a double to a three-dimensional array. You might want to clarify what you're going for.</strike></p>
<p>I think I understand a little better what you're going for now. You want to return the location of the value in a given array, and then be able to change the value in that location. This pattern breaks some of the expected paradigms of C#, so I would suggest considering other ways to achieve what you're looking for. But if it really makes sense to do it, I'd do something more like this:</p>
<pre><code>public class 3dArrayLocation {public int X; public int Y; public int Z;}
...
public 3dArrayLocation GetElementLocation(...)
{
// calculate x, y, and z
return new 3dArrayLocation {X = x, Y = y, Z = z}
}
...
var location = GetElementLocation(...);
doubleArray[location.X, location.Y, location.Z] = 5.0;
</code></pre> |
4,162,398 | How to alignment the text of button to the left? | <p>Now I want to alignment the text of button to the left with code , how to do ?
and I code this : </p>
<pre><code>button.titleLabel.textAlignment = UITextAlignmentLeft;
</code></pre>
<p>but it doesn't work.</p> | 4,162,551 | 5 | 0 | null | 2010-11-12 07:15:20.617 UTC | 6 | 2021-05-24 18:28:22.147 UTC | 2015-12-02 13:13:29.95 UTC | null | 172,277 | null | 51,958 | null | 1 | 41 | iphone|ios | 29,592 | <p>You have to use <code>contentVerticalAlignment</code> and <code>contentHorizontalAlignment</code> of the button.</p> |
4,466,362 | for expressions versus foreach in Scala | <p>I'm working my way through <a href="http://www.artima.com/shop/programming_in_scala">Programming in Scala</a>, and though I'm tempted to look at things from the perspective of Python, I don't want to program "Python in Scala."</p>
<p>I'm not quite sure what to do as far as control flow goes: in Python, we use <code>for x in some_iterable</code> to death, and we love it. A very similar construct exists in Scala which Odersky calls a for <em>expression</em>, probably to distinguish it from the Java for loop. Also, Scala has a <code>foreach</code> attribute (I guess it would be an attribute, I don't know enough about Scala to name it correctly) for iterable data types. It doesn't seem like I can use <code>foreach</code> to do much more than call one function for each item in the container, though.</p>
<p>This leaves me with a few questions. First, are for expressions important/heavily used constructs in Scala like they are in Python, and second, when should I use <code>foreach</code> instead of a for expression (other than the obvious case of calling a function on each item of a container)?</p>
<p>I hope I'm not being terribly ambiguous or overbroad, but I'm just trying to grok some of the design/language fundamentals in Scala (which seems very cool so far).</p> | 4,467,577 | 5 | 0 | null | 2010-12-16 23:27:22.27 UTC | 15 | 2010-12-17 04:02:43.073 UTC | null | null | null | null | 399,815 | null | 1 | 55 | scala|loops|foreach | 51,575 | <p>python uses <code>for</code> in list comprehensions and generator expressions. Those are <em>very</em> similar to the scala <code>for</code> expression:</p>
<p><em>this is python</em></p>
<pre><code>>>> letters = ['a', 'b', 'c', 'd']
>>> ints = [0, 1, 2, 3]
>>> [l + str(i) for l in letters for i in ints if i % 2 == 0]
['a0', 'a2', 'b0', 'b2', 'c0', 'c2', 'd0', 'd2']
</code></pre>
<p><em>this is scala</em></p>
<pre><code>scala> val letters = List('a', 'b', 'c', 'd')
scala> val ints = List(0, 1, 2, 3)
scala> for (l <- letters; i <- ints if i % 2 == 0) yield l.toString + i
res0: List[java.lang.String] = List(a0, a2, b0, b2, c0, c2, d0, d2)
</code></pre>
<p>Each construct can take a number of generators/iterators, apply filters expressions and yield a combined expression. In python the <code>(expr for v1 in gen1 if expr1 for v2 in gen2 if expr2)</code> is roughly equivalent to:</p>
<pre><code>for v1 in gen1:
if expr1:
for v2 in gen2:
if expr2:
yield expr
</code></pre>
<p>In scala <code>for (v1 <- gen1 if expr1; v2 <- gen2 if expr2) yield expr</code> is roughly equivalent to:</p>
<pre><code>gen1.withFilter(expr1).flatMap(v1 => gen2.withFilter(expr2).map(v2 => expr))
</code></pre>
<p>If you love the python <code>for x in xs</code> syntax, you'll likely love the scala <code>for</code> expression.</p>
<p>Scala has some additional syntax and translation twists. Syntax wise <code>for</code> can be used with braces so that you can put statements on separate lines. You can also perform value assignments.</p>
<pre><code>val res = for {
i <- 1 to 20; i2 = i*i
j <- 1 to 20; j2 = j*j
k <- 1 to 20; k2 = k*k
if i2 + j2 == k2
} yield (i, j, k)
</code></pre>
<p>Also <code>v1 <- gen1</code> really performs a match <code>case v1 => gen1</code>. If there is no match those elements are ignored from the iteration. </p>
<pre><code>scala> val list = List(Some(1), None, Some(2))
scala> for (Some(i) <- list) yield i
res2: List[Int] = List(1, 2)
</code></pre>
<p>I think <code>for</code> has an important place in the language. I can tell from the fact there is a whole chapter (23) about it in the book you're reading!</p> |
4,671,819 | How to switch between visible buffers in emacs? | <p>If I am in split-screen viewing 2 different buffers on Emacs and the cursor is on the top buffer, what's a quick way to move the cursor to the bottom buffer?</p>
<p>Bonus question: if I know a command, is there an easy way to identify what key-combo it's bound to, if any?</p> | 4,671,868 | 5 | 0 | null | 2011-01-12 17:22:23.657 UTC | 16 | 2017-08-05 22:07:38.533 UTC | 2017-08-05 22:06:25.403 UTC | null | 3,924,118 | null | 5,056 | null | 1 | 60 | emacs|keyboard-shortcuts | 48,719 | <p>To switch to other buffer use: <code>C-x o</code>.</p>
<p>Describe key: <code>C-h k</code>.</p> |
4,087,280 | Approximate cost to access various caches and main memory? | <p>Can anyone give me the approximate time (in nanoseconds) to access L1, L2 and L3 caches, as well as main memory on Intel i7 processors?</p>
<p>While this isn't specifically a programming question, knowing these kinds of speed details is neccessary for some low-latency programming challenges. </p> | 4,087,331 | 5 | 6 | null | 2010-11-03 13:02:38.807 UTC | 184 | 2022-03-12 12:29:41.797 UTC | 2022-02-24 11:17:47.507 UTC | null | 3,666,197 | null | 170,255 | null | 1 | 207 | performance|memory|latency|cpu-cache|low-latency | 98,728 | <p><a href="https://web.archive.org/web/20160315021718/https://software.intel.com/sites/products/collateral/hpc/vtune/performance_analysis_guide.pdf" rel="nofollow noreferrer">Here is a Performance Analysis Guide</a> for the i7 and Xeon range of processors. I should stress, this has what you need and more (for example, check page 22 for some timings & cycles for example).</p>
<p>Additionally, <a href="http://software.intel.com/en-us/forums/showthread.php?t=77966" rel="nofollow noreferrer">this page</a> has some details on clock cycles etc. The second link served the following numbers:</p>
<pre><code>Core i7 Xeon 5500 Series Data Source Latency (approximate) [Pg. 22]
local L1 CACHE hit, ~4 cycles ( 2.1 - 1.2 ns )
local L2 CACHE hit, ~10 cycles ( 5.3 - 3.0 ns )
local L3 CACHE hit, line unshared ~40 cycles ( 21.4 - 12.0 ns )
local L3 CACHE hit, shared line in another core ~65 cycles ( 34.8 - 19.5 ns )
local L3 CACHE hit, modified in another core ~75 cycles ( 40.2 - 22.5 ns )
remote L3 CACHE (Ref: Fig.1 [Pg. 5]) ~100-300 cycles ( 160.7 - 30.0 ns )
local DRAM ~60 ns
remote DRAM ~100 ns
</code></pre>
<p><strong><code>EDIT2</code></strong>:
<br>The most important is the notice under the cited table, saying:<br></p>
<blockquote>
<p><sub>"NOTE: THESE VALUES ARE ROUGH APPROXIMATIONS. <strong>THEY DEPEND ON
CORE AND UNCORE FREQUENCIES, MEMORY SPEEDS, BIOS SETTINGS,
NUMBERS OF DIMMS</strong>, ETC,ETC..<strong>YOUR MILEAGE MAY VARY.</strong>"</sub></p>
</blockquote>
<p>EDIT: I should highlight that, as well as timing/cycle information, the above intel document addresses much more (extremely) useful details of the i7 and Xeon range of processors (from a performance point of view).</p> |
4,316,692 | How can I create raster plots with the same colour scale in R | <p>I'm creating some maps from raster files using the "raster" package in R. I'd like to create comparison rasters, showing several maps side by side. It's important for this that the colour scales used are the same for all maps, regardless of the values in each map. For example, if map 1 has values from 0-1, and map 2 has values from 0-0.5, cells with a value of 0.5 should have the same colour on both maps.</p>
<p>For example:</p>
<ul>
<li>map 1 has values from 0 to 1</li>
<li>map 2 has values from 0 to 0.5</li>
<li>the colour goes from red (lowest) to green (highest)</li>
</ul>
<p>I would like a value of 0.5 to have the same colour in both maps (i.e. yellow, as halfway between red and green). The current behaviour is that it is yellow in map 1, and green in map 2.</p>
<p>I can't find a way to make this work. I can't see any way to set the range of pixel values to use with the plotting function. setMinMax() doesn't help (as 'plot' always calculates the values). Even trying to set the values by hand (e.g. g1@data@max <- 10) doesn't work (these are ignored when plotting).</p>
<p>Finally, making a stack of the maps (which might be expected to plot everything on the same colour scale) doesn't work either - each map still has it's own colour scale.</p>
<p>Any thoughts on how to do this?</p>
<p>EDIT:</p>
<p>The solution I ended up using is:</p>
<pre><code>plot( d, col=rev( rainbow( 99, start=0,end=1 ) ), breaks=seq(min(minValue( d )),max(maxValue(d)),length.out=100) )
</code></pre> | 4,317,070 | 6 | 2 | null | 2010-11-30 17:40:48.643 UTC | 11 | 2020-02-15 15:17:29.097 UTC | 2010-11-30 18:59:26.327 UTC | null | 192,720 | null | 192,720 | null | 1 | 23 | r|maps|raster | 22,893 | <p>Since the image::raster function specifies that the image::base arguments can be passed (and suggests that image::base is probably used), wouldn't you just specify the same col= and breaks= arguments to all calls to image::raster? You <em>do</em> need to get the breaks and the col arguments "in sync". The number of colors needs to be one less than the number of breaks. The example below is based on the classic volcano data and the second version shows how a range of values can be excluded from an image:</p>
<pre><code> x <- 10*(1:nrow(volcano))
y <- 10*(1:ncol(volcano))
image(x, y, volcano, col = terrain.colors( length(seq(90, 200, by = 5))-1), axes = FALSE, breaks= seq(90, 200, by = 5) )
axis(1, at = seq(100, 800, by = 100))
axis(2, at = seq(100, 600, by = 100))
box()
title(main = "Maunga Whau Volcano", font.main = 4)
x <- 10*(1:nrow(volcano))
y <- 10*(1:ncol(volcano))
image(x, y, volcano, col = terrain.colors( length(seq(150, 200, by = 5))-1), axes = FALSE, breaks= seq(150, 200, by = 5) )
axis(1, at = seq(100, 800, by = 100))
axis(2, at = seq(100, 600, by = 100))
box()
title(main = "Maunga Whau Volcano Restricted to elevations above 150", font.main = 4)
</code></pre>
<p>A specific example would aid this effort.</p> |
4,324,037 | What are callback methods? | <p>I'm a programming noob and didn't quite understand the concept behind callback methods. Tried reading about it in wiki and it went over my head. Can somebody please explain this in simple terms? </p> | 4,324,112 | 7 | 0 | null | 2010-12-01 11:52:06.103 UTC | 13 | 2021-01-02 04:51:56.467 UTC | 2010-12-01 12:35:16.35 UTC | null | 526,482 | null | 526,482 | null | 1 | 27 | language-agnostic|methods|callback | 24,011 | <p>The callback is something that you pass to a function, which tells it what it should call at some point in its operation. The code in the function decides when to call the function (and what arguments to pass). Typically, the way you do this is to pass <strong>the function itself</strong> as the 'callback', in languages where functions are objects. In other languages, you might have to pass some kind of special thing called a "function pointer" (or similar); or you might have to pass the name of the function (which then gets looked up at runtime).</p>
<p>A trivial example, in Python:</p>
<pre><code>void call_something_three_times(what_to_call, what_to_pass_it):
for i in xrange(3): what_to_call(what_to_pass_it)
# Write "Hi mom" three times, using a callback.
call_something_three_times(sys.stdout.write, "Hi mom\n")
</code></pre>
<p>This example let us separate the task of repeating a function call, from the task of actually calling the function. That's not very useful, but it demonstrates the concept.</p>
<p>In the real world, callbacks are used a lot for things like threading libraries, where you call some thread-creation function with a callback that describes the work that the thread will do. The thread-creation function does the necessary work to set up a thread, and then arranges for the callback function to be called by the new thread.</p> |
4,163,964 | python: is it possible to attach a console into a running process | <p>I just want to see the state of the process, is it possible to attach a console into the process, so I can invoke functions inside the process and see some of the global variables.</p>
<p>It's better the process is running without being affected(of course performance can down a little bit)</p> | 4,164,088 | 8 | 4 | null | 2010-11-12 11:04:00.96 UTC | 47 | 2021-09-19 19:21:22.133 UTC | null | null | null | null | 197,036 | null | 1 | 90 | python | 67,391 | <p>If you have access to the program's source-code, you can add this functionality relatively easily. </p>
<p>See <a href="http://code.activestate.com/recipes/576515/">Recipe 576515</a>: <code>Debugging a running python process by interrupting and providing an interactive prompt (Python)</code></p>
<p>To quote:</p>
<blockquote>
<p>This provides code to allow any python
program which uses it to be
interrupted at the current point, and
communicated with via a normal python
interactive console. This allows the
locals, globals and associated program
state to be investigated, as well as
calling arbitrary functions and
classes.</p>
<p>To use, a process should import the
module, and call listen() at any point
during startup. To interrupt this
process, the script can be run
directly, giving the process Id of the
process to debug as the parameter.</p>
</blockquote>
<hr>
<p>Another implementation of roughly the same concept is provided by <a href="http://code.google.com/p/rfoo/">rconsole</a>. From the documentation:</p>
<blockquote>
<p>rconsole is a remote Python console
with auto completion, which can be
used to inspect and modify the
namespace of a running script.</p>
<p>To invoke in a script do:</p>
</blockquote>
<pre><code>from rfoo.utils import rconsole
rconsole.spawn_server()
</code></pre>
<blockquote>
<p>To attach from a shell do:</p>
</blockquote>
<pre><code>$ rconsole
</code></pre>
<blockquote>
<p>Security note: The rconsole listener
started with spawn_server() will
accept any local connection and may
therefore be insecure to use in shared
hosting or similar environments!</p>
</blockquote> |
4,287,941 | How can I list or discover queues on a RabbitMQ exchange using python? | <p>I need to have a python client that can discover queues on a restarted RabbitMQ server exchange, and then start up a clients to resume consuming messages from each queue. How can I discover queues from some RabbitMQ compatible python api/library? </p> | 4,288,304 | 9 | 0 | null | 2010-11-26 19:06:59.19 UTC | 7 | 2022-08-12 19:09:37.833 UTC | null | null | null | null | 337,657 | null | 1 | 43 | python|rabbitmq|amqp | 72,497 | <p>As far as I know, there isn't any way of doing this. That's nothing to do with Python, but because AMQP doesn't define any method of queue discovery.</p>
<p>In any case, in AMQP it's clients (consumers) that declare queues: publishers publish messages to an exchange with a routing key, and consumers determine which queues those routing keys go to. So it does not make sense to talk about queues in the absence of consumers.</p> |
4,341,178 | Getting the Last Insert ID with SQLite.NET in C# | <p>I have a simple problem with a not so simple solution... I am currently inserting some data into a database like this:</p>
<pre><code>kompenzacijeDataSet.KompenzacijeRow kompenzacija = kompenzacijeDataSet.Kompenzacije.NewKompenzacijeRow();
kompenzacija.Datum = DateTime.Now;
kompenzacija.PodjetjeID = stranka.id;
kompenzacija.Znesek = Decimal.Parse(tbZnesek.Text);
kompenzacijeDataSet.Kompenzacije.Rows.Add(kompenzacija);
kompenzacijeDataSetTableAdapters.KompenzacijeTableAdapter kompTA = new kompenzacijeDataSetTableAdapters.KompenzacijeTableAdapter();
kompTA.Update(this.kompenzacijeDataSet.Kompenzacije);
this.currentKompenzacijaID = LastInsertID(kompTA.Connection);
</code></pre>
<p>The last line is important. Why do I supply a connection? Well there is a SQLite function called <strong>last_insert_rowid()</strong> that you can call and get the last insert ID. Problem is it is bound to a connection and .NET seems to be reopening and closing connections for every dataset operation. I thought getting the connection from a table adapter would change things. But it doesn't.</p>
<p>Would anyone know how to solve this? Maybe where to get a constant connection from? Or maybe something more elegant?</p>
<p>Thank you.</p>
<p>EDIT:</p>
<p>This is also a problem with transactions, I would need the same connection if I would want to use transactions, so that is also a problem...</p> | 35,324,308 | 10 | 0 | null | 2010-12-02 23:42:19.383 UTC | 8 | 2022-02-17 21:26:01.98 UTC | 2020-10-08 15:20:48.887 UTC | null | 177,347 | null | 271,402 | null | 1 | 29 | c#|sql|sqlite | 52,534 | <p>Using C# (.net 4.0) with SQLite, the SQLiteConnection class has a property <code>LastInsertRowId</code> that equals the Primary Integer Key of the most recently inserted (or updated) element.</p>
<p>The rowID is returned if the table doesn't have a primary integer key (in this case the rowID is column is automatically created). </p>
<p>See <a href="https://www.sqlite.org/c3ref/last_insert_rowid.html">https://www.sqlite.org/c3ref/last_insert_rowid.html</a> for more.</p>
<p>As for wrapping multiple commands in a single transaction, any commands entered after the transaction begins and before it is committed are part of one transaction.</p>
<pre><code>long rowID;
using (SQLiteConnection con = new SQLiteConnection([datasource])
{
SQLiteTransaction transaction = null;
transaction = con.BeginTransaction();
... [execute insert statement]
rowID = con.LastInsertRowId;
transaction.Commit()
}
</code></pre> |
4,162,815 | How to read two inputs separated by space in a single line? | <p>I want to read two input values. First value should be an integer and the second value should be a float.</p>
<p>I saw <a href="https://stackoverflow.com/questions/1588058/python-read-two-variables-in-a-single-line">Read two variables in a single line with Python</a>, but it applies only if both the values are of same type. Do I have any other way?</p>
<p>Example input, first is int and second is float. The inputs should be on a single line:</p>
<pre><code>20 150.50
</code></pre>
<p><a href="http://www.codechef.com/problems/HS08TEST/" rel="noreferrer">http://www.codechef.com/problems/HS08TEST/</a></p>
<p>I'm very new to Python.</p> | 4,162,830 | 13 | 3 | null | 2010-11-12 08:32:42.707 UTC | 14 | 2022-01-23 05:31:30.467 UTC | 2017-05-23 10:30:59.483 UTC | Roger Pate | -1 | null | 270,190 | null | 1 | 21 | python | 128,221 | <p>Like this:</p>
<pre><code>In [20]: a,b = raw_input().split()
12 12.2
In [21]: a = int(a)
Out[21]: 12
In [22]: b = float(b)
Out[22]: 12.2
</code></pre>
<p>You can't do this in a one-liner (or at least not without some super duper extra hackz0r skills -- or semicolons), but python is not made for one-liners.</p> |
4,580,263 | How to open in default browser in C# | <p>I am designing a small C# application and there is a web browser in it. I currently have all of my defaults on my computer say google chrome is my default browser, yet when I click a link in my application to open in a new window, it opens internet explorer. Is there any way to make these links open in the default browser instead? Or is there something wrong on my computer?</p>
<p>My problem is that I have a webbrowser in the application, so say you go to google and type in "stack overflow" and right click the first link and click "Open in new window" it opens in IE instead of Chrome. Is this something I have coded improperly, or is there a setting not correct on my computer</p>
<p>===EDIT===</p>
<p>This is really annoying. I am already aware that the browser is IE, but I had it working fine before. When I clicked a link it opened in chrome. I was using sharp develop to make the application at that time because I could not get c# express to start up. I did a fresh windows install and since I wasn't too far along in my application, I decided to start over, and now I am having this problem. That is why I am not sure if it is my computer or not. Why would IE start up the whole browser when a link is clicked rather than simply opening the new link in the default browser?</p> | 4,580,324 | 20 | 2 | null | 2011-01-02 20:10:39.603 UTC | 55 | 2022-02-12 11:43:50.377 UTC | 2011-01-02 22:05:12.663 UTC | null | 560,816 | null | 560,816 | null | 1 | 335 | c#|browser|window|default|new-operator | 425,595 | <p>You can just write </p>
<pre><code>System.Diagnostics.Process.Start("http://google.com");
</code></pre>
<p><strong>EDIT</strong>: The <code>WebBrowser</code> control is an embedded copy of IE.<br>
Therefore, any links inside of it will open in IE.</p>
<p>To change this behavior, you can handle the <code>Navigating</code> event.</p> |
14,665,330 | pip - Requirement already satisfied? | <p>pip recognize global installed packages..?! :-(</p>
<p>I've used virtualenvwrapper preactivate hook to clean PYTHONPATH,</p>
<pre><code>export PYTHONPATH=""
</code></pre>
<p>then echo $PYTHONPATH returns empty string, but this didn't help.</p>
<p>What's wrong?</p>
<pre><code>bentzy@lama:~$ mkvirtualenv test
New python executable in test/bin/python
Installing setuptools............done.
Installing pip...............done.
virtualenvwrapper.user_scripts creating /home/bentzy/.virtualenvs/test/bin/predeactivate
virtualenvwrapper.user_scripts creating /home/bentzy/.virtualenvs/test/bin/postdeactivate
virtualenvwrapper.user_scripts creating /home/bentzy/.virtualenvs/test/bin/preactivate
virtualenvwrapper.user_scripts creating /home/bentzy/.virtualenvs/test/bin/postactivate
virtualenvwrapper.user_scripts creating /home/bentzy/.virtualenvs/test/bin/get_env_details
(test)bentzy@lama:~$ which pip
/home/bentzy/.virtualenvs/test/bin/pip
(test)bentzy@lama:~$ sudo pip install simplejson
Requirement already satisfied (use --upgrade to upgrade): simplejson in /usr/lib /python2.7/dist-packages
Cleaning up...
(test)bentzy@lama:~$ echo $PYTHONPATH
(test)bentzy@lama:~$ pip --version
pip 1.2.1 from /home/bentzy/.virtualenvs/test/lib/python2.7/site-packages/pip-1.2.1-py2.7.egg (python 2.7)
</code></pre> | 14,675,084 | 2 | 4 | null | 2013-02-02 18:58:56.41 UTC | 7 | 2022-08-12 11:24:28.213 UTC | 2013-02-02 19:15:55.907 UTC | null | 1,268,853 | null | 1,268,853 | null | 1 | 16 | virtualenv|pip|virtualenvwrapper | 103,027 | <p>You are using <code>sudo</code> to install simplejson, but if you use <code>sudo</code> your <code>$PATH</code> may be changed, and that seems to be the problem.</p>
<p>Just use <code>pip install simplejson</code> (no <code>sudo</code> included) and it is probably going to work.</p>
<p>Use <code>sudo</code> only when you want to affect your whole system.</p> |
14,767,174 | `MODIFY COLUMN` vs `CHANGE COLUMN` | <p>I know, we cannot rename a column using <code>MODIFY COLUMN</code> syntax, but we can using <code>CHANGE COLUMN</code> syntax.</p>
<p>My question is: what is the main usage of <code>modify syntax</code>?</p>
<p>For example:</p>
<pre><code>ALATER TABLE tablename CHANGE col1 col1 INT(10) NOT NULL;
</code></pre>
<p>instead of</p>
<pre><code>ALATER TABLE tablename MODIFY col1 INT(10) NOT NULL;
</code></pre>
<br />
<hr />
<h1>Edited (question replaced)</h1>
<ul>
<li>What is the main usage of <code>MODIFY</code> syntax?</li>
<li>Why we have to use <code>CHANGE COLUMN</code> instead of <code>MODIFYCOLUMN</code>?</li>
</ul> | 14,767,467 | 5 | 2 | null | 2013-02-08 06:47:09.653 UTC | 16 | 2022-08-25 09:41:14.01 UTC | 2022-08-25 09:37:27.477 UTC | user2053420 | 814,702 | user2053420 | null | null | 1 | 68 | mysql|alter-table | 51,838 | <h2><code>CHANGE COLUMN</code></h2>
<p>If you have already created your MySQL database, and decide after the fact that one of your columns is named incorrectly, you don't need to remove it and make a replacement, you can simply rename it using <strong>change column</strong>.</p>
<pre><code>ALTER TABLE MyTable CHANGE COLUMN foo bar VARCHAR(32) NOT NULL FIRST;
</code></pre>
<hr />
<h2><code>MODIFY COLUMN</code></h2>
<p>This command does everything <code>CHANGE COLUMN</code> can, but <strong>without renaming</strong> the column. You can use the <code>MODIFY</code> SQL command if you need to resize a column in MySQL. By doing this you can allow more or less characters than before. You can't rename a column using <code>MODIFY</code> and other.</p>
<pre><code>ALTER TABLE MyTable MODIFY COLUMN foo VARCHAR(32) NOT NULL AFTER baz;
</code></pre>
<hr />
<h3>Note</h3>
<p><code>ALTER TABLE</code> is used for <em>altering</em> a table in order to change column name, size, drop column etc. <code>CHANGE COLUMN</code> and <code>MODIFY COLUMN</code> commands cannot be used without help of <code>ALTER TABLE</code> command.</p> |
2,587,965 | Using a Generic Repository pattern with fluent nHibernate | <p>I'm currently developing a medium sized application, which will access 2 or more SQL databases, on different sites etc...</p>
<p>I am considering using something similar to this:
<a href="http://mikehadlow.blogspot.com/2008/03/using-irepository-pattern-with-linq-to.html" rel="noreferrer">http://mikehadlow.blogspot.com/2008/03/using-irepository-pattern-with-linq-to.html</a></p>
<p>However, I want to use fluent nHibernate, in place of Linq-to-SQL (and of course nHibernate.Linq)</p>
<p>Is this viable?</p>
<p>How would I go about configuring this?
Where would my mapping definitions go etc...?</p>
<p>This application will eventually have many facets - from a WebUI, WCF Library and Windows applications / services.</p>
<p>Also, for example on a "product" table, would I create a "ProductManager" class, that has methods like:</p>
<p>GetProduct, GetAllProducts etc...</p>
<p>Any pointers are greatly received.</p> | 2,588,642 | 2 | 1 | null | 2010-04-06 20:15:34.17 UTC | 12 | 2010-04-06 21:56:57.393 UTC | 2010-04-06 21:07:45.997 UTC | null | 62,024 | null | 131,809 | null | 1 | 13 | c#|nhibernate|repository-pattern | 18,906 | <p>In my opinion (and in some other peoples opinion as well), a repository should be an interface that hides data access in an interface that mimics a collection interface. That's why a repository should be an IQueryable and IEnumerable. </p>
<pre><code>public interface IRepository<T> : IQueryable<T>
{
void Add(T entity);
T Get(Guid id);
void Remove(T entity);
}
public class Repository<T> : IQueryable<T>
{
private readonly ISession session;
public Repository(ISession session)
{
session = session;
}
public Type ElementType
{
get { return session.Query<T>().ElementType; }
}
public Expression Expression
{
get { return session.Query<T>().Expression; }
}
public IQueryProvider Provider
{
get { return session.Query<T>().Provider; }
}
public void Add(T entity)
{
session.Save(entity);
}
public T Get(Guid id)
{
return session.Get<T>(id);
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
public IEnumerator<T> GetEnumerator()
{
return session.Query<T>().GetEnumerator();
}
public void Remove(T entity)
{
session.Delete(entity);
}
}
</code></pre>
<p>I do not implement a SubmitChanges like method in the repository itself, because I want to submit the changes of several repositories used by one action of the user at once. I hide the transaction management in a unit of work interface:</p>
<pre><code>public interface IUnitOfWork : IDisposable
{
void Commit();
void RollBack();
}
</code></pre>
<p>I use the session of an NHibernate specific unit of work implementation as session for the repositories:</p>
<pre><code>public interface INHiberanteUnitOfWork : IUnitOfWork
{
ISession Session { get; }
}
</code></pre>
<p>In a real application, I use a more complicated repository interface with methods for things like pagination, eager loading, specification pattern, access to the other ways of querying used by NHiberante instead of just linq. The linq implementation in the NHibernate trunk works good enough for most of the queries I need to do.</p> |
38,529,553 | Multiple Axios Requests Into ReactJS State | <p>So I have been placing the following code within my React JS component and I am basically trying to put both API calls into one state called <code>vehicles</code> however I am getting an error with the following code:</p>
<pre><code>componentWillMount() {
// Make a request for vehicle data
axios.all([
axios.get('/api/seat/models'),
axios.get('/api/volkswagen/models')
])
.then(axios.spread(function (seat, volkswagen) {
this.setState({ vehicles: seat.data + volkswagen.data })
}))
//.then(response => this.setState({ vehicles: response.data }))
.catch(error => console.log(error));
}
</code></pre>
<p>Now I am guessing I can't add two sources of data like I have <code>this.setState({ vehicles: seat.data + volkswagen.data })</code> however how else can this be done? I just want all of the data from that API request to be put into the one state.</p>
<p>This is the current error I am receiving:</p>
<pre><code>TypeError: Cannot read property 'setState' of null(…)
</code></pre>
<p>Thanks</p> | 38,529,764 | 4 | 0 | null | 2016-07-22 14:55:52.6 UTC | 9 | 2018-01-19 20:14:54.84 UTC | null | null | null | null | 5,929,529 | null | 1 | 14 | javascript|reactjs|axios | 24,592 | <p>You cannot "add" arrays together. Use the array.concat function (<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat</a>) to concatenate both arrays into one and then set that as the state.</p>
<pre><code>componentWillMount() {
// Make a request for vehicle data
axios.all([
axios.get('/api/seat/models'),
axios.get('/api/volkswagen/models')
])
.then(axios.spread(function (seat, volkswagen) {
let vehicles = seat.data.concat(volkswagen.data);
this.setState({ vehicles: vehicles })
}))
//.then(response => this.setState({ vehicles: response.data }))
.catch(error => console.log(error));
}
</code></pre> |
54,122,850 | How to read and write a text file in Flutter | <p>How do you read text from a file and write text to a file?</p>
<p>I've been learning about how to read and write text to and from a file. I found another question about <a href="https://stackoverflow.com/questions/44816042/flutter-read-text-file-from-assets">reading from assets</a>, but that is not the same. I will add my answer below from what I learned from the documentation.</p> | 54,122,851 | 4 | 0 | null | 2019-01-10 06:14:20.787 UTC | 5 | 2022-05-04 11:27:08.273 UTC | null | null | null | null | 3,681,880 | null | 1 | 27 | dart|flutter|text-files | 45,098 | <h1>Setup</h1>
<p>Add the following plugin in <code>pubspec.yaml</code>:</p>
<pre class="lang-yaml prettyprint-override"><code>dependencies:
path_provider: ^1.6.27
</code></pre>
<p>Update the version number to whatever is <a href="https://pub.dartlang.org/packages/path_provider" rel="noreferrer">current</a>.</p>
<p>And import it in your code.</p>
<pre class="lang-dart prettyprint-override"><code>import 'package:path_provider/path_provider.dart';
</code></pre>
<p>You also have to import <code>dart:io</code> to use the <code>File</code> class.</p>
<pre class="lang-dart prettyprint-override"><code>import 'dart:io';
</code></pre>
<h1>Writing to a text file</h1>
<pre class="lang-dart prettyprint-override"><code>_write(String text) async {
final Directory directory = await getApplicationDocumentsDirectory();
final File file = File('${directory.path}/my_file.txt');
await file.writeAsString(text);
}
</code></pre>
<h1>Reading from a text file</h1>
<pre class="lang-dart prettyprint-override"><code>Future<String> _read() async {
String text;
try {
final Directory directory = await getApplicationDocumentsDirectory();
final File file = File('${directory.path}/my_file.txt');
text = await file.readAsString();
} catch (e) {
print("Couldn't read file");
}
return text;
}
</code></pre>
<h1>Notes</h1>
<ul>
<li>You can also get the path string with <code>join(directory.path, 'my_file.txt')</code> but you need to import <code>'package:path/path.dart'</code>.</li>
<li><a href="https://flutter.io/docs/cookbook/persistence/reading-writing-files" rel="noreferrer">Flutter's Official Documentation of Reading and Writing Files</a></li>
<li>This works for iOS, Android, Linux and MacOS but not for web.</li>
</ul> |
38,691,334 | Spark Dataframe groupBy and sort results into a list | <p>I have a Spark Dataframe and I would like to group the elements by a key and have the results as a sorted list</p>
<p>Currently I am using:</p>
<p><code>df.groupBy("columnA").agg(collect_list("columnB"))</code></p>
<p>How do I make the items in the list sorted ascending order?</p> | 38,693,464 | 2 | 1 | null | 2016-08-01 05:04:11.923 UTC | 11 | 2019-01-29 17:49:45.78 UTC | 2019-01-06 19:30:48.017 UTC | null | -1 | null | 2,392,965 | null | 1 | 18 | apache-spark|dataframe|apache-spark-sql | 22,880 | <p>You could try the function <code>sort_array</code> available in the <a href="http://spark.apache.org/docs/latest/api/scala/index.html#org.apache.spark.sql.functions$@sort_array(e:org.apache.spark.sql.Column):org.apache.spark.sql.Column" rel="noreferrer">functions</a> package:</p>
<pre class="lang-scala prettyprint-override"><code>import org.apache.spark.sql.functions._
df.groupBy("columnA").agg(sort_array(collect_list("columnB")))
</code></pre> |
33,643,181 | How do I flip rows and columns in R | <p>I currently have:</p>
<pre><code>Country.Name 1995 1996 1997 ... 2013
Country1
Country2 (numeric data)
Country3
</code></pre>
<p>-This format makes it difficult to graph the data for each country, and compare them, since the header columns are individual years</p>
<p>I want:</p>
<pre><code>Year Country1 Country2 Country3
1995
1996
1997 (numeric data)
...
2013
</code></pre> | 33,646,864 | 2 | 0 | null | 2015-11-11 02:16:27.073 UTC | 4 | 2015-11-11 08:40:22.007 UTC | 2015-11-11 02:18:22.287 UTC | user3710546 | null | null | 5,548,988 | null | 1 | 15 | r | 81,982 | <p>Assuming you have this data frame <code>df</code>, see data below. </p>
<pre><code> Country.Name 1997 1998 1999 2000
1 Country1 1 1 1 1
2 Country2 2 4 7 10
3 Country3 4 2 1 5
</code></pre>
<p>First you have to transpose all data frame except the first column. The result being a matrix that we need to convert to a data frame. Finally, we assign as column names of <code>df2</code>the first column of the original data frame <code>df</code>.</p>
<pre><code>df2 <- data.frame(t(df[-1]))
colnames(df2) <- df[, 1]
</code></pre>
<p><strong>Output:</strong></p>
<pre><code> Country1 Country2 Country3
1997 1 2 4
1998 1 4 2
1999 1 7 1
2000 1 10 5
</code></pre>
<p><strong>Data:</strong></p>
<pre><code>df <- structure(list(Country.Name = c("Country1", "Country2", "Country3"
), `1997` = c(1L, 2L, 4L), `1998` = c(1L, 4L, 2L), `1999` = c(1L,
7L, 1L), `2000` = c(1L, 10L, 5L)), .Names = c("Country.Name",
"1997", "1998", "1999", "2000"), class = "data.frame", row.names = c(NA,
-3L))
</code></pre> |
30,060,534 | Ajax requests fail after upgrading to Cordova 5.0 + [email protected] | <p>I recently upgraded to Cordova 5.0 (and Cordova Android 4.0) and, since then, my app can no longer access external resources.</p>
<p>I still have <code><access origin="*" /></code> in config.xml (as before), and I still have <code><uses-permission android:name="android.permission.INTERNET" /></code> in AndroidManifest.xml (as before), but ajax calls are rejected with no explanation (the "textStatus" param is "error", the "errorThrown" param is null, and xhr.state() returns "rejected").</p>
<p>I've verified that no request is hitting the server, so it appears it is being stopped by Android, but the log doesn't give any explanation as to why...</p>
<p>I can access the URL in question fine from the Android browser, just not from the app.</p>
<p>The ajax request is made via a call to Backbone.sync() of <a href="http://backbonejs.org/">Backbone.js</a>, which ultimately calls jquery's $.ajax(). I haven't changed anything about how the call is made... just upgraded cordova.</p>
<p><strong>Are there new requirements/setup for network requests, in Cordova 5.0, or anything I need to do differently from previous Cordova versions?</strong></p>
<p>Does anyone know of a way I can get more information as to why Android and/or Cordova is rejecting the request?</p> | 30,066,390 | 5 | 0 | null | 2015-05-05 18:25:20.593 UTC | 12 | 2019-12-08 15:24:59.707 UTC | 2015-05-06 02:13:29.09 UTC | null | 1,354,350 | null | 1,354,350 | null | 1 | 30 | android|ajax|cordova | 18,451 | <p>I tracked the culprit down to the [email protected] cordova platform. It now requires the new <a href="https://github.com/apache/cordova-plugin-whitelist">cordova-plugin-whitelist</a> plugin.</p>
<p>It can be installed with </p>
<pre><code>cordova plugin add cordova-plugin-whitelist
</code></pre>
<p>or by adding</p>
<pre><code><plugin name="cordova-plugin-whitelist" spec="1" />
</code></pre>
<p>to config.xml, and then it is configured with</p>
<pre><code><allow-navigation href="*" />
</code></pre>
<p>in place of the old, <code><access origin="*" /></code> tag.</p>
<p>It's a little annoying that the log doesn't spit out the "whitelist rejection" error messages anymore when a problem like this comes up (that would have saved me a ton a time), but maybe that'll come later.</p> |
36,572,221 | How to find ngram frequency of a column in a pandas dataframe? | <p>Below is the input pandas dataframe I have.</p>
<p><a href="https://i.stack.imgur.com/ltSrD.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ltSrD.png" alt="enter image description here"></a></p>
<p>I want to find the frequency of unigrams & bigrams. A sample of what I am expecting is shown below<a href="https://i.stack.imgur.com/7NOKk.png" rel="noreferrer"><img src="https://i.stack.imgur.com/7NOKk.png" alt="enter image description here"></a></p>
<p>How to do this using nltk or scikit learn?</p>
<p>I wrote the below code which takes a string as input. How to extend it to series/dataframe?</p>
<pre><code>from nltk.collocations import *
desc='john is a guy person you him guy person you him'
tokens = nltk.word_tokenize(desc)
bigram_measures = nltk.collocations.BigramAssocMeasures()
finder = BigramCollocationFinder.from_words(tokens)
finder.ngram_fd.viewitems()
</code></pre> | 36,573,116 | 1 | 0 | null | 2016-04-12 11:39:29.41 UTC | 10 | 2022-07-12 08:37:57.453 UTC | 2016-07-19 14:52:34.877 UTC | null | 3,424,990 | null | 3,424,990 | null | 1 | 12 | pandas|nlp|scikit-learn|nltk|text-mining | 14,882 | <p>If your data is like</p>
<pre><code>import pandas as pd
df = pd.DataFrame([
'must watch. Good acting',
'average movie. Bad acting',
'good movie. Good acting',
'pathetic. Avoid',
'avoid'], columns=['description'])
</code></pre>
<p>You could use the <code>CountVectorizer</code> of the package <code>sklearn</code>:</p>
<pre><code>from sklearn.feature_extraction.text import CountVectorizer
word_vectorizer = CountVectorizer(ngram_range=(1,2), analyzer='word')
sparse_matrix = word_vectorizer.fit_transform(df['description'])
frequencies = sum(sparse_matrix).toarray()[0]
pd.DataFrame(frequencies, index=word_vectorizer.get_feature_names(), columns=['frequency'])
</code></pre>
<p>Which gives you :</p>
<pre><code> frequency
good 3
pathetic 1
average movie 1
movie bad 2
watch 1
good movie 1
watch good 3
good acting 2
must 1
movie good 2
pathetic avoid 1
bad acting 1
average 1
must watch 1
acting 1
bad 1
movie 1
avoid 1
</code></pre>
<p><strong>EDIT</strong></p>
<p><code>fit</code> will just "train" your vectorizer : it will split the words of your corpus and create a vocabulary with it. Then <code>transform</code> can take a new document and create vector of frequency based on the vectorizer vocabulary.</p>
<p>Here your training set is your output set, so you can do both at the same time (<code>fit_transform</code>). Because you have 5 documents, it will create 5 vectors as a matrix. You want a global vector, so you have to make a <code>sum</code>.</p>
<p><strong>EDIT 2</strong></p>
<p>For big dataframes, you can speed up the frequencies computation by using:</p>
<pre><code>frequencies = sum(sparse_matrix).data
</code></pre>
<p>or</p>
<pre><code>frequencies = sparse_matrix.sum(axis=0).T
</code></pre> |
36,556,709 | Angular 2 Module has no exported member | <p>Here I am again, hoping to find a quick solution to this:</p>
<p><a href="http://i.stack.imgur.com/j2tab.png" rel="noreferrer">Link <- Click on this link to see the folder structure</a></p>
<pre><code>//main.ts
import {bootstrap} from 'angular2/platform/browser';
import {AppComponent} from './home.main';
import {InputComponent} from './home.controller';
import {enableProdMode} from 'angular2/core';
bootstrap(InputComponent);
bootstrap(AppComponent);
</code></pre>
<p>This is my main.ts file where I import the AppComponent from home main, now the home.main looks like this:</p>
<pre><code>import {Component} from 'angular2/core';
@Component({
selector:'home',
templateUrl:'/index/index.ejs'
})
export class InputComponent {
name = 'test';
}
</code></pre>
<p>However, when I run this, I get: <code>error TS2305: Module '"controllers/home/home.main"' has no exported member 'AppComponent'. ( Same goes for home.controller ).</code></p>
<p>Thank you,
Alex S.</p> | 36,556,906 | 3 | 0 | null | 2016-04-11 18:42:32.883 UTC | 2 | 2019-02-11 03:45:23.85 UTC | 2019-02-11 03:45:23.85 UTC | user10747134 | null | null | 2,958,692 | null | 1 | 10 | angular|typescript | 50,273 | <p>You should have something like that in your home.main module:</p>
<pre><code>@Component({
(...)
})
export class AppComponent {
}
</code></pre> |
44,630,676 | How can I call an async function without await? | <p>I have a controller action in aiohttp application.</p>
<pre><code>async def handler_message(request):
try:
content = await request.json()
perform_message(x,y,z)
except (RuntimeError):
print("error in perform fb message")
finally:
return web.Response(text="Done")
</code></pre>
<p><code>perform_message</code> is async function. Now, when I call action I want that my action return as soon as possible and <code>perform_message</code> put in event loop.</p>
<p>In this way, <code>perform_message</code> isn't executed</p> | 44,630,895 | 3 | 0 | null | 2017-06-19 12:32:54.693 UTC | 7 | 2022-09-18 00:54:58.94 UTC | 2022-05-21 19:22:00.207 UTC | null | 4,621,513 | null | 2,422,021 | null | 1 | 49 | python|python-asyncio|aiohttp | 53,603 | <p>One way would be to use <a href="https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.AbstractEventLoop.create_task" rel="noreferrer"><code>create_task</code></a> function:</p>
<pre><code>import asyncio
async def handler_message(request):
...
loop = asyncio.get_event_loop()
loop.create_task(perform_message(x,y,z))
...
</code></pre>
<p>As per the <a href="https://docs.python.org/3/library/asyncio-eventloop.html" rel="noreferrer">loop documentation</a>, starting Python 3.10, <code>asyncio.get_event_loop()</code> is deprecated. If you're trying to get a loop instance from a coroutine/callback, you should use <code>asyncio.get_running_loop()</code> instead. This method will not work if called from the main thread, in which case a new loop must be instantiated:</p>
<pre><code>loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.create_task(perform_message(x, y, z))
loop.run_forever()
</code></pre>
<p>Furthermore, if the call is only made once throughout your program's runtime and no other loop needs to be is instantiated (unlikely), you may use:</p>
<pre><code>asyncio.run(perform_message(x, y, z))
</code></pre>
<p>This function creates an event loop and terminates it once the coroutine ends, therefore should only be used in the aforementioned scenario.</p> |
28,203,937 | Installing LLVM libraries along with Xcode | <p>So I just installed Xcode on my Mac and now I would like to install LLVM as well in order to play around a bit with LLVM itself. Currently the compiler can (obviously) not find the required header files. So what is the best way to install LLVM if you already have clang, packed with Xcode, on your system?</p>
<p>Thanks in advance.</p> | 28,208,691 | 2 | 0 | null | 2015-01-28 22:50:24.6 UTC | 9 | 2020-06-20 11:10:00.347 UTC | null | null | null | null | 1,655,527 | null | 1 | 14 | macos|xcode6|llvm | 13,358 | <p>If you do not need to read LLVM <em>implementation</em> source code(such as in <code>lib</code>/<code>tools</code> directories) and might only play with <code>libclang</code>, perhaps using <code>homebrew</code> is enough for you.</p>
<pre><code>brew install --with-clang --with-lld --with-python --HEAD llvm
</code></pre>
<p>Next you need to set <code>PATH</code>, <code>CPLUS_INCLUDE_PATH</code> and <code>LD_LIBRARY_PATH</code>. For me,</p>
<pre><code># export PATH=/usr/local/opt/llvm/bin:$PATH
# export CPLUS_INCLUDE_PATH=$(llvm-config --includedir):$CPLUS_INCLUDE_PATH
# export LD_LIBRARY_PATH=$(llvm-config --libdir):$LD_LIBRARY_PATH
</code></pre>
<p>You might configure the above information in your LLVM derived project with XCode.</p>
<p>However if you are also interested in <code>Compiler-RT</code>, <code>Clang-Tools-Extra</code>(see <a href="http://llvm.org/releases/download.html#svn">LLVM Download Page</a>) you probably have to make LLVM as your XCode project (download from that page or via SVN as said in <a href="http://llvm.org/docs/GettingStarted.html">Getting Started with the LLVM System</a>). After putting the sub-projects in <em>proper</em> directories, you can use XCode generator from CMake, the typical usage is:</p>
<pre><code>cd YOUR_LLVM_SRC_ROOT
mkdir build
cd build
cmake -G Xcode ..
</code></pre>
<p>Use XCode to open the project file <em>XXX.xcodeproj</em> and it should build the project.</p> |
40,406,418 | Cannot declare class Controller, because the name is already in use | <p>I recently migrated a laravel 4.2 project to 5.0. So far I have completed all the necessary steps but I keep getting an error. </p>
<blockquote>
<p>Cannot declare class Controller, because the name is already in use</p>
</blockquote>
<p>My Controller is changed as provided by laravel in the upgrade guide. </p>
<pre><code><?php
use Illuminate\Foundation\Bus\DispatchesCommands;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
abstract class Controller extends BaseController {
use DispatchesCommands, ValidatesRequests;
}
</code></pre>
<p>Also I have added it to the classmap directive of my composer.json. </p>
<pre><code>"autoload": {
"classmap": [
"database",
"app/Http/Controllers"
],
"psr-4": {
"App\\": "app/"
}
},
</code></pre>
<p>I couldn't find any solution so far so if you guys know what to do it would help me out a lot :) thanks in advance!</p> | 40,406,578 | 6 | 2 | null | 2016-11-03 16:14:14.14 UTC | 3 | 2022-06-23 13:53:41.093 UTC | null | null | null | null | 1,453,253 | null | 1 | 25 | laravel|laravel-5 | 93,536 | <p>Remove the <code>"app/Http/Controllers"</code> from your classmap.</p>
<p>Add <code>namespace App\Http\Controllers;</code> above your <code>use</code> blocks.</p>
<p>Then run <code>composer dump-auto</code></p> |
2,947,118 | WPF slow to start on x64 in .NET Framework 4.0 | <p>I've noticed that if I build my WPF application for Any CPU/x64, it takes MUCH longer to start (on the order of about 20 seconds) or to load new controls than it does if started on x86 (in release & debug modes, inside or outside of VS). This occurs with even the simplest WPF apps. The problem is discussed in <a href="http://social.msdn.microsoft.com/Forums/en/netfx64bit/thread/476e21c4-6b73-4f8e-bfab-a7aaae5b017f" rel="noreferrer">this MSDN thread</a>, but no answer was provided there. This happens only with .NET 4.0 -- in 3.5 SP1, x64 was just as fast as x86. Interestingly, Microsoft seems to know about this problem since the default for a new WPF project in VS2010 is x86.</p>
<p>Is this a real bug or am I just doing it wrong?</p>
<p><strong>EDIT:</strong> Possibly related to this: <a href="https://stackoverflow.com/questions/2788215/slow-databinding-setup-time-in-c-net-4-0">Slow Databinding setup time in C# .NET 4.0</a>. I'm using data binding heavily.</p> | 2,947,183 | 1 | 0 | null | 2010-06-01 03:23:38.217 UTC | 25 | 2016-04-02 01:18:56.467 UTC | 2017-05-23 12:02:39.663 UTC | null | -1 | null | 125,601 | null | 1 | 38 | .net|wpf|performance|64-bit|.net-4.0 | 20,502 | <p>Actually there's 2 main reasons that the default project type for WPF applications is x86.</p>
<ul>
<li>Intellitrace debugging only works with x86 and that would look pretty bad if the default project templates didn't work with one of their star features.</li>
<li>Many developers were still not aware of the fact that their AnyCPU exe's would run as x64 on 64 bit machines and were surprised to find that 32 bit DLL's they relied on did not exist in 64 bit varieties such as OLEDB drivers, certain native DLL's, etc.</li>
</ul>
<p>As for the startup time issues you're experiencing, it almost seems like an issue with NGEN. Since there are different NGEN caches for x64 and x86 processes, it could be that the 64 bit NGEN cache either needs to be rebuilt or updated. Try running the following from an elevated command prompt:</p>
<pre><code>CD C:\Windows\Microsoft.NET\Framework64\v4.0.30319
NGEN update
</code></pre>
<p>This is the command to re-build native images for assemblies that have already been marked for NGEN. It also probably won't do you any good to NGEN your application if the assemblies are not also in the GAC so I wouldn't bother trying to do that. But framework assemblies, toolkit assemblies, etc should all be NGEN'd.</p>
<p>(By the way, I did get several errors when I ran the above command about assemblies that could not be loaded. It was mostly SQL and Visual Studio assemblies.)</p> |
21,146,651 | What is the purpose of asynchronous JAX-RS | <p>I'm reading "RESTful Java with JAX-RS 2.0" book. I'm completely confused with asynchronous JAX-RS, so I ask all questions in one. The book writes asynchronous server like this:</p>
<pre><code>@Path("/customers")
public class CustomerResource {
@GET
@Path("{id}")
@Produces(MediaType.APPLICATION_XML)
public void getCustomer(@Suspended final AsyncResponse asyncResponse,
@Context final Request request,
@PathParam(value = "id") final int id) {
new Thread() {
@Override
public void run() {
asyncResponse.resume(Response.ok(new Customer(id)).build());
}
}.start();
}
}
</code></pre>
<p>Netbeans creates asynchronous server like this:</p>
<pre><code>@Path("/customers")
public class CustomerResource {
private final ExecutorService executorService = java.util.concurrent.Executors.newCachedThreadPool();
@GET
@Path("{id}")
@Produces(MediaType.APPLICATION_XML)
public void getCustomer(@Suspended final AsyncResponse asyncResponse,
@Context final Request request,
@PathParam(value = "id") final int id) {
executorService.submit(new Runnable() {
@Override
public void run() {
doGetCustomer(id);
asyncResponse.resume(javax.ws.rs.core.Response.ok().build());
}
});
}
private void doGetCustomer(@PathParam(value = "id") final int id) {
}
}
</code></pre>
<p>Those that do not create background threads use some locking methods to store response objects for further processing. This example is for sending stock quotes to clients:</p>
<pre><code>@Path("qoute/RHT")
public class RHTQuoteResource {
protected List<AsyncResponse> responses;
@GET
@Produces("text/plain")
public void getQuote(@Suspended AsyncResponse response) {
synchronized (responses) {
responses.add(response);
}
}
}
</code></pre>
<p><code>responses</code> object will be shared with some background jobs and it will send quote to all clients when it is ready.</p>
<p>My questions:</p>
<ol>
<li>In example 1 and 2 web server thread(the one that handle request) dies
and we create another background thread. The whole idea behind
asynchronous server is to reduce idle threads. These examples are
not reducing idle threads. One threads dies and another one born.</li>
<li>I thought creating unmanaged threads inside container is a bad idea.
We should only use managed threads using concurrency utilities in
Java EE 7.</li>
<li>Again one of ideas behind async servers is to scale. Example 3 does not scale, does it?</li>
</ol> | 21,148,332 | 3 | 0 | null | 2014-01-15 19:39:23.933 UTC | 10 | 2015-11-01 02:08:37.32 UTC | null | null | null | null | 654,269 | null | 1 | 13 | java|web-services|rest|asynchronous|jax-rs | 12,121 | <p><strong>Executive Summary:</strong> You're over-thinking this.</p>
<hr>
<blockquote>
<p>In example 1 and 2 web server thread(the one that handle request) dies and we create another background thread. The whole idea behind asynchronous server is to reduce idle threads. These examples are not reducing idle threads. One threads dies and another one born.</p>
</blockquote>
<p>Neither is particularly great, to be honest. In a production service, you wouldn't hold the executor in a private field like that but instead would have it as a separately configured object (e.g., its own Spring bean). On the other hand, such a sophisticated example would be rather harder for you to understand without a lot more context; applications that consist of systems of beans/managed resources have to be built to be that way from the ground up. It's also not very important for small-scale work to be very careful about this, and that's a <em>lot</em> of web applications.</p>
<p><a href="http://en.wikipedia.org/wiki/The_Gripping_Hand">The gripping hand</a> is that the recovery from server restart is actually not something to worry about too much in the first place. If the server restarts you'll probably lose all the connections anyway, and if those <code>AsyncResponse</code> objects aren't <code>Serializable</code> in some way (no guarantee that they are or aren't), you can't store them in a database to enable recovery. Best to not worry about it too much as there's not much you can do! (Clients are also going to time out after a while if they don't get any response back; you can't hold them indefinitely.)</p>
<blockquote>
<p>I thought creating unmanaged threads inside container is a bad idea. We should only use managed threads using concurrency utilities in Java EE 7.</p>
</blockquote>
<p>It's an example! Supply the executor from outside however you want for your fancy production system.</p>
<blockquote>
<p>Again one of ideas behind async servers is to scale. Example 3 does not scale, does it?</p>
</blockquote>
<p>It's just enqueueing an object on a list, which isn't a very slow operation at all, especially when compared with the cost of all the networking and deserializing/serializing going on. What it doesn't show is the other parts of the application which take things off that list, perform the processing, and yield the result back; they could be poorly implemented and cause problems, or they could be done carefully and the system work well.</p>
<p>If you can do it better in your code, <em>by all means do so</em>. (Just be aware that you can't store the work items in the database, or at least you can't know for sure that you can do that, even if it happens to be actually possible. I doubt it though; there's likely information about the TCP network connection in there, and that's never easy to store and restore fully.)</p> |
20,958,166 | What are the steps to implement Spring's Token Store as a MySQL file? | <p>I have an application that currently uses the Spring OAuth 2.0 In Memory Token Store. I need to convert the Spring Security OAuth 2.0 JAR to use a persisted file rather than an in memory to ensure the access tokens are valid over server restarts. The Spring OAuth 2.0 JAR provides routines to support a MYSQL database using the JdbcTokenStore method, but I am unable to find any documentation that tells how to change the default configuration (which uses the InMemoryTokenStore method) to utilize the supported Jdbc method.</p>
<p>I'd like to hear from someone who has implemented the Spring Security OAuth 2.0 JdbcTokenStore method and that can either provide an example of the configuration required to do so or can point me to documentation that describes the process. I've searched high and low on the internet, but cannot find any such documentation.</p>
<p>I've already found the Spring Security OAuth 2.0 schema file for the Token Store, which if anyone is interested is only found in the Test Resource directory. It's presence is NOT documented by any of the Pivotal documentation website. If necessary, I can read through the rest of the Pivotal source code, but am hoping some one can save me from having to use this path.</p>
<p>Thanks in advance for any help you can provide.</p> | 21,071,614 | 2 | 0 | null | 2014-01-06 19:57:40.27 UTC | 12 | 2018-10-17 16:34:52.653 UTC | null | null | null | null | 2,652,156 | null | 1 | 21 | access-token|spring-security-oauth2 | 29,277 | <p>You need to change the beans implementation class from InMemoryTokenStore to JdbcTokenStore. And with this change you'll also need to pass a datasource in the constructor.</p>
<p>I have already done this while fooling around with it. You can find it <a href="https://github.com/nareshbafna/oauth2/commit/51c97ba2c44ec245e3d93a6fed909f38ebc8f00e">here</a> </p>
<p>and the spring security config changes specifically <a href="https://github.com/nareshbafna/oauth2/commit/51c97ba2c44ec245e3d93a6fed909f38ebc8f00e">here</a>. The MySql schema is <a href="https://github.com/nareshbafna/oauth2/blob/master/oauthdb.sql">here</a></p> |
38,636,436 | How to uninstall a Haskell package installed with stack? | <p>How can I uninstall a Haskell package installed globally with stack tool?</p>
<p><code>stack --help</code> shows that uninstall command is deprecated.</p>
<pre><code> uninstall DEPRECATED: This command performs no actions, and is
present for documentation only
</code></pre> | 38,639,959 | 1 | 1 | null | 2016-07-28 12:30:27.15 UTC | 8 | 2017-01-03 20:43:33.447 UTC | 2017-01-03 20:43:33.447 UTC | null | 880,772 | null | 2,028,189 | null | 1 | 34 | haskell|haskell-stack | 14,505 | <p>As <code>stack --help</code> says, uninstall doesn't do anything. You can read about this <a href="https://github.com/commercialhaskell/stack/issues/361" rel="noreferrer">on the stack github</a> where this feature was requested, but it ended up being closed without the desire to add the behavior to stack, for various reasons. So, officially, there is no way to use stack to uninstall a package. </p>
<p>To remove a package that stack installed, you need to manually do so. This entails using ghc-pkg unregister and then finding the location of the package on your system and removing it via another tool or simply <code>rm</code>. For example, </p>
<pre><code>stack install <package name>
# Now remove the package
ghc-pkg unregister <pkg-id>
cd /path/to/stack/packages # This could be something like ~/.local/bin, but is configuration dependent
rm <package name>
</code></pre> |
24,852,116 | What exactly is a merge conflict? | <p>I have made a git repository and added a text file to it. This is 100% for learning purpose. </p>
<ol>
<li><p>I added "1" to the text file and committed it to master. </p></li>
<li><p>Created a new branch from master and appended "2". </p></li>
<li><p>Finally, created a branch from master and appended "3". </p></li>
</ol>
<p>Could you please explain how a conflict may occur in this, or any other, scenario?</p> | 24,852,167 | 3 | 0 | null | 2014-07-20 15:40:48.2 UTC | 19 | 2022-07-24 16:10:53.84 UTC | 2021-01-05 11:24:57.873 UTC | null | 3,257,186 | null | 3,693,167 | null | 1 | 58 | git|git-merge | 29,527 | <p>You will have a conflict if you merge:</p>
<ul>
<li><code>branch2</code> to <code>master</code> (no conflict)</li>
<li><code>branch3</code> to <code>master</code> (conflict):</li>
</ul>
<p>That is because:</p>
<ul>
<li>The common ancestor would be <code>master</code> (with a second line empty)</li>
<li>the source content is <code>branch3</code> (with a second line including "3")</li>
<li>the destination content is on latest of <code>master</code> (with a second line including "2", from the merge of <code>branch2</code> to <code>master</code>)</li>
</ul>
<p>Git will ask you to choose which content to keep ("3", "2", or both).</p>
<p>First, do the merges after:</p>
<pre><code>git config merge.conflictstyle diff3
</code></pre>
<p>See "<a href="https://stackoverflow.com/a/7589612/6309">Fix merge conflicts in Git?</a>".</p>
<hr />
<p>Notes:</p>
<ul>
<li><p><a href="https://stackoverflow.com/a/64950077/6309">With Git 2.30 (Q1 2021)</a>, a new default merge strategy is in place: <strong>ORT</strong> ("<strong>Ostensibly Recursive's Twin</strong>"), with <a href="https://stackoverflow.com/a/71330184/6309">clearer conflict messages</a> (Gti 2.36, Q2 2022)</p>
</li>
<li><p>you can <em>preview</em> those conflicts with (<a href="https://stackoverflow.com/a/73091924/6309">Git 2.38, Q3 2022</a>):</p>
<pre><code>git merge-tree --write-tree --no-messages branch1 branch2
</code></pre>
<p>(That would not touch the index or working tree!)</p>
</li>
</ul> |
24,688,716 | Transferring an app to another Firebase account | <p>I have a few apps under my personal firebase account for testing, but now need to transfer an app to a client's account for billing purposes. Is this possible?</p>
<p>Thanks!</p> | 39,525,119 | 9 | 0 | null | 2014-07-11 01:08:55.92 UTC | 55 | 2021-03-11 14:43:17.66 UTC | null | null | null | null | 414,605 | null | 1 | 187 | firebase | 88,947 | <p>I recently shifted ownership of one of my projects to another account. All you have to do is:</p>
<ol>
<li>Go to your Firebase console, and select the project you want to shift.</li>
<li>Select the cog icon besides the project name on top right.</li>
<li>Select Permissions from the flyout.</li>
<li>Select Advanced permission settings hyperlink.</li>
<li>You've reached the IAM & Admin page of Firebase.</li>
<li>Click on <code>+Add</code> button on top.</li>
<li>Enter the email ID of the account that you want to transfer the project to.</li>
<li>In the dropdown, Select a role > Project > Owner. Click add</li>
<li>You will receive a confirmation email. Click the link in the email to accept the invitation.</li>
<li>Accept the invitation, and go to IAM & Admin page of the transferred project.</li>
<li>Use remove button to delete the previous user</li>
</ol>
<p>Hope this helps.</p> |
52,980,370 | How to convert .p12 to .crt file? | <p>Can anyone tell me the correct way/command to extract/convert the certificate .crt file from a .p12 file? After I searched. I found the way how to convert .pem to .crt. but not found .p12 to .crt.</p> | 52,980,444 | 2 | 0 | null | 2018-10-25 02:15:53.273 UTC | null | 2021-05-22 17:14:16.28 UTC | 2019-06-21 12:19:27.773 UTC | null | 340,556 | null | 3,130,007 | null | 1 | 20 | openssl|certificate|keytool|p12 | 64,632 | <p>Try with given command</p>
<pre><code>openssl pkcs12 -in filename.p12 -clcerts -nokeys -out filename.crt
</code></pre> |
35,974,402 | Reading getline from cin into a stringstream (C++) | <p>So I'm trying to read input like this from the standard input (using <code>cin</code>):</p>
<blockquote>
<p>Adam English 85<br>
Charlie Math 76<br>
Erica History 82<br>
Richard Science 90</p>
</blockquote>
<p>My goal is to eventually store each data piece in its own cell in a data structure I have created, so basically I want to parse the input so each piece of data is individual. Since each row of input is inputted by the user one at a time, each time I get an entire row of input that I need to parse. Currently I am trying something like this:</p>
<pre><code>stringstream ss;
getline(cin, ss);
string name;
string course;
string grade;
ss >> name >> course >> grade;
</code></pre>
<p>The error I am having is that XCode is telling me there's no matching function call to <code>getline</code> which is confusing me. I have included the <code>string</code> library, so I'm guessing the error has to do with using <code>getline</code> to read in from <code>cin</code> to a <code>stringstream</code>? Any help here would be appreciated.</p> | 35,974,444 | 4 | 1 | null | 2016-03-13 18:58:11.923 UTC | 6 | 2017-08-30 11:05:25.51 UTC | 2016-03-13 19:04:25.18 UTC | null | 3,313,438 | null | 5,482,356 | null | 1 | 15 | c++|cin|getline|stringstream|ostream | 56,882 | <p>You are almost there, the error is most probably<sup>1</sup> caused because you are trying to call <code>getline</code> with second parameter <code>stringstream</code>, just make a slight modification and store the data within the <code>std::cin</code> in a <code>string</code> first and then used it to initialize a <code>stringstream</code>, from which you can extract the input: </p>
<pre><code>// read input
string input;
getline(cin, input);
// initialize string stream
stringstream ss(input);
// extract input
string name;
string course;
string grade;
ss >> name >> course >> grade;
</code></pre>
<hr>
<p><sup>1. Assuming you have included:</sup></p>
<pre><code>#include <iostream>
#include <sstream>
#include <string>
using namespace std;
</code></pre> |
7,034,060 | How do you check if an object exists in the Twig templating engine in Symfony2? | <p>I have a multidimensional array where some objects exist and others don't. I keep getting a</p>
<p><strong>Method "code" for object "stdClass" does not exist in...</strong>?</p>
<p>The code I am using in my template is:</p>
<pre><code>{% for item in items %}
<p>{% if item.product.code %}{{ item.product.code }}{% endif %}</p>
{% endfor %}
</code></pre>
<p>Some products do not have this code and unfortunately this data structure is provided via a feed, so I cannot change it.</p>
<p>When I looked at the Twig documentation I interpreted that if an object or method was not there it would just return null?</p> | 7,035,887 | 1 | 0 | null | 2011-08-11 23:17:39.827 UTC | 14 | 2017-07-20 15:35:45.377 UTC | null | null | null | null | 863,755 | null | 1 | 86 | symfony|twig | 72,675 | <p>Quickly did a lookup, hope this is works for you :p</p>
<p><a href="http://twig.sensiolabs.org/doc/tests/defined.html" rel="noreferrer">defined</a></p>
<p>defined checks if a variable is defined in the current context. This is very useful if you use the strict_variables option:</p>
<pre><code>{# defined works with variable names #}
{% if foo is defined %}
...
{% endif %}
{# and attributes on variables names #}
{% if foo.bar is defined %}
...
{% endif %}
</code></pre> |
8,648,841 | Simple way to remove escape characters from this JSON date | <p>In my android application, my JSON date is returned as this:</p>
<p><code>\/Date(1323752400000)\/</code></p>
<p>Is there a simple way to remove the escape characters? (This is being sent from a WCF service to an Android application). I am already using <code>StringEscapeUtils.unEscapeHtml4</code> to decode the entire serialized object.</p> | 8,651,639 | 3 | 0 | null | 2011-12-27 20:13:25.487 UTC | 1 | 2016-09-20 20:43:34.457 UTC | null | null | null | null | 783,284 | null | 1 | 2 | java|json|escaping | 40,751 | <p>On the receiving end, if you really want to, you could just do <code>myJsonString = myJsonString.replaceAll("\\","");</code></p>
<p>But do note that those escape characters in no way make the JSON invalid or otherwise semantically different -- the '/' character can be optionally escaped with '\' in JSON.</p> |
39,160,264 | How to pass value to a onclick function in (Jade)pug? | <p>I am new to jade and stuck on this issue. I think I have tried everything from the StackOverflow posts and still at nothing. </p>
<p>The things I have tried </p>
<pre><code>button(type='button' class=' c-btn-blue c-btn-circle c-btn-uppercase' value="Read More" onclick='gotoBlog( #{val.link} )')
</code></pre>
<p>Error </p>
<pre><code>1:8 Uncaught SyntaxError: Invalid or unexpected token
</code></pre>
<p>Changing it to <code>!{val.link}</code></p>
<p>Error </p>
<pre><code>Uncaught SyntaxError: Unexpected token .
</code></pre>
<p>Changing it to <code>"!{val.link}"</code> and <code>"#{val.link}"</code> just gives me string understandably so. BTW val.link is a string</p>
<p>Just giving val.link says <code>Uncaught ReferenceError: val is not defined</code></p>
<p>I am out of options now. Help will be appreciated.</p>
<p>Thanks </p> | 39,174,471 | 9 | 1 | null | 2016-08-26 07:05:00.163 UTC | 3 | 2021-12-20 22:08:33.67 UTC | null | null | null | null | 3,320,962 | null | 1 | 13 | javascript|pug | 38,181 | <p>When adding attributes to an html element, you are already within the scope of pug, so you can just use pug variables like regular js variables.</p>
<pre><code>button(type='button' class=' c-btn-blue c-btn-circle c-btn-uppercase' value="Read More" onclick='gotoBlog(' + val.link + ')')
</code></pre> |
11,550,879 | Detecting key presses in console | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/8898182/how-to-handle-key-press-event-in-console-application">how to handle key press event in console application</a> </p>
</blockquote>
<p>a simple question.</p>
<p>I am writing a simple text based adventure game for fun and I am stuck on the first part already! How can I make my console check for key presses I.E: press enter to continue!</p> | 11,550,964 | 4 | 4 | null | 2012-07-18 21:49:51.367 UTC | 1 | 2015-01-28 03:35:33.777 UTC | 2017-05-23 12:33:50.273 UTC | null | -1 | null | 1,412,593 | null | 1 | 0 | c# | 50,872 | <p>You can use</p>
<pre><code>Console.ReadKey();
</code></pre>
<p>To read 1 key. You could then do something like this:</p>
<pre><code>string key = Console.ReadKey().Key.ToString();
if(key.ToUpper() == "W")
Console.WriteLine("User typed 'W'!");
else
Console.WriteLine("User did not type 'W'");
</code></pre>
<p>Or:</p>
<pre><code>if(key == "")
Console.WriteLine("User pressed enter!");
else
Console.WriteLine("User did not press enter.");
</code></pre>
<p>And if you do not care if the user types anything but presses enter after, you could just do:</p>
<pre><code>// Some code here
Console.ReadLine();
// Code here will be run after they press enter
</code></pre> |
3,014,223 | PL/SQL pre-compile and Code Quality checks in an automated build environment? | <p>We build software using Hudson and Maven. We have C#, java and last, but not least PL/SQL sources (sprocs, packages, DDL, crud)</p>
<p>For C# and Java we do unit tests and code analysis, but we don't really know the health of our PL/SQL sources before we actually publish them to the target database.</p>
<h3>Requirements</h3>
<p>There are a couple of things we wan't to test in the following priority:</p>
<ol>
<li>Are the sources valid, hence "compilable"?</li>
<li>For packages, with respect to a certain database, would they compile?</li>
<li>Code Quality: Do we have code flaws like duplicates, too complex methods or other violations to a defined set of rules?</li>
</ol>
<p>Also,</p>
<ul>
<li>the tool must run head-less (commandline, ant, ...)</li>
<li>we want to do analysis on a partial code base (changed sources only)</li>
</ul>
<h3>Tools</h3>
<p>We did a little research and found the following tools that could potencially help:</p>
<ul>
<li><strong><a href="http://www.castsoftware.com/Product/Application-Intelligence-Platform.aspx" rel="nofollow noreferrer">Cast Application Intelligence Platform (AIP)</a>:</strong> Seems to be a server that grasps information about "anything". Couldn't find a console version that would export in readable format.</li>
<li><strong><a href="http://www.toadsoft.com/toad_oracle.htm" rel="nofollow noreferrer">Toad for Oracle</a>:</strong> The Professional version is said to include something called Xpert validates a set of rules against a code base.</li>
<li><strong><a href="http://www.sonarsource.com" rel="nofollow noreferrer">Sonar</a> + <a href="http://www.sonarsource.com/plugins/plugin-plsql/" rel="nofollow noreferrer">PL/SQL-Plugin</a>:</strong> Uses Toad for Oracle to display code-health the sonar-way. This is for browsing the current state of the code base.</li>
<li><strong><a href="http://www.semanticdesigns.com/Products/DMS/DMSToolkit.html?Home=PLSQLTools" rel="nofollow noreferrer">Semantic Designs DMSToolkit</a>:</strong> Quite general analysis of source code base. Commandline available?</li>
<li><strong><a href="http://www.semanticdesigns.com/Products/Clone/index.html?Home=PLSQLTools" rel="nofollow noreferrer">Semantic Designs Clones Detector</a>:</strong> Detects clones. But also via command line?</li>
<li><strong><a href="http://www.fortify.com/products/detect/in_development.jsp" rel="nofollow noreferrer">Fortify Source Code Analyzer</a>:</strong> Seems to be focussed on security issues. But maybe it is extensible? <em><a href="http://products.enterpriseitplanet.com/security/security/1101145596.html" rel="nofollow noreferrer">more...</a></em></li>
</ul>
<p>So far, Toad for Oracle together with Sonar seems to be an elegant solution. But may be we are missing something here?</p>
<p>Any ideas? Other products? Experiences?</p>
<h3>Related Questions on SO:</h3>
<ul>
<li><a href="https://stackoverflow.com/questions/531430/any-static-code-analysis-tools-for-stored-procedures">Any Static Code Analysis Tools for Stored Procedures?</a></li>
<li><a href="https://stackoverflow.com/questions/839707/any-code-quality-tool-for-pl-sql">https://stackoverflow.com/questions/839707/any-code-quality-tool-for-pl-sql</a></li>
<li><a href="https://stackoverflow.com/questions/956104/is-there-a-static-analysis-tool-for-python-ruby-sql-cobol-perl-and-pl-sql">Is there a static analysis tool for Python, Ruby, Sql, Cobol, Perl, and PL/SQL?</a></li>
</ul> | 3,475,758 | 3 | 0 | null | 2010-06-10 12:18:57.793 UTC | 13 | 2016-07-18 09:54:18.43 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 11,562 | null | 1 | 22 | oracle|plsql|continuous-integration|build-automation|code-analysis | 8,624 | <p>I think that this blog describes the needed process:</p>
<p><a href="http://www.theserverlabs.com/blog/?p=435" rel="nofollow noreferrer">http://www.theserverlabs.com/blog/?p=435</a></p>
<p>Please check and let me know what you think about it.</p> |
2,405,353 | Having a POST'able API and Django's CSRF Middleware | <p>I have a Django webapp that has both a front-end, web-accessible component and an API that is accessed by a desktop client. However, now with the new CSRF middleware component, API requests from the desktop client that are POST'ed get a 403.</p>
<p>I understand why this is happening, but what is the proper way to fix this without compromising security? Is there someway I can signal in the HTTP header that it's an API request and that Django shouldn't be checking for CSRF or is that a bad strategy?</p>
<p><strong><em>Edit--</em></strong></p>
<p>The method I'm using at the moment is that the desktop client sets a header, X-Requested-With: XMLHttpRequest. This is kinda hacky, but I'm not sure how this would be handled better.</p> | 2,405,780 | 3 | 2 | null | 2010-03-08 22:41:25.373 UTC | 8 | 2014-03-03 09:04:27.933 UTC | 2010-03-08 23:19:19.37 UTC | null | 111,375 | null | 111,375 | null | 1 | 32 | django|security|api|csrf | 20,448 | <p>How about just splitting off a view(s) for your desktop client and decorating them with <a href="https://docs.djangoproject.com/en/1.4/ref/contrib/csrf/#ref-contrib-csrf" rel="nofollow noreferrer">csrf_exempt</a>?</p> |
2,938,435 | COM(C++) programming tutorials? | <p>Are there any good sites for learning C++/COM from the ground up? I'm looking for something like a crash course with perhaps two weeks' worth of content.</p>
<p>The course can assume knowledge in standard C/C++, or at least not a complete dummy.</p> | 2,938,448 | 3 | 0 | null | 2010-05-30 11:38:24.46 UTC | 27 | 2015-09-09 22:04:28.92 UTC | 2015-09-09 22:04:28.92 UTC | null | 1,832,942 | null | 230,391 | null | 1 | 43 | c++|com | 51,642 | <p>Since you're asking for websites, you can try this <a href="http://www.codeproject.com/KB/COM/comintro.aspx" rel="noreferrer">introduction to COM</a> on The Code Project, and <a href="http://www.codeproject.com/KB/COM/com_in_c1.aspx" rel="noreferrer">how to handle COM in plain C</a> and <a href="http://www.codeproject.com/KB/COM/COM_from_scratch_1.aspx" rel="noreferrer">in C++</a> on the same site. And of course, you have <a href="http://msdn.microsoft.com/en-us/library/ms694363(VS.85).aspx" rel="noreferrer">MSDN</a>.</p> |
2,464,909 | Generate POCO classes in different project to the project with Entity Framework model | <p>I'm trying to use the Repository Pattern with EF4 using VS2010.</p>
<p>To this end I am using POCO code generation by right clicking on the entity model designer and clicking Add code generation item. I then select the POCO template and get my classes.</p>
<p>What I would like to be able to do is have my solution structured into separate projects for Entity (POCO) classes and another project for the entity model and repository code.</p>
<p>This means that my MVC project could use the POCO classes for strongly typed views etc and not have to know about the repository or have to have a reference to it.</p>
<p>To plug it all together I will have another separate project with interfaces and use IoC.</p>
<p>Sounds good in my head I just don't know how to generate the classes into their own project! I can copy them and then change the namespaces on them but I wanted to avoid manual work whenever I change the schema in the db and want to update my model.</p>
<p>Thanks</p> | 2,467,757 | 3 | 0 | null | 2010-03-17 18:36:44.39 UTC | 17 | 2019-05-07 08:35:37.437 UTC | null | null | null | null | 165,394 | null | 1 | 44 | .net|entity-framework|code-generation|repository-pattern|poco | 23,657 | <p>Actually the T4 templates in EF 4.0 were designed with this scenario in mind :)</p>
<p>There are 2 templates:</p>
<ul>
<li>One for the Entities themselves (i.e. ModelName.tt)</li>
<li>One for the ObjectContext (i.e. ModelName.Context.tt)</li>
</ul>
<p>You should put the ModelName.tt file in you POCO project, and just change the template to point to the EDMX file in the persistence aware project. </p>
<p>Sounds weird I know: There is now a dependency, but it is at T4 generation time, not at compile time! And that should be okay? Because the resulting POCO assembly is still completely persistence ignorant.</p>
<p>See steps 5 & 6 of this: <a href="http://blogs.msdn.com/adonet/pages/walkthrough-poco-template-for-the-entity-framework.aspx" rel="noreferrer">http://blogs.msdn.com/adonet/pages/walkthrough-poco-template-for-the-entity-framework.aspx</a> for more.</p>
<p>Hope this helps</p>
<p>Alex </p> |
2,608,528 | Spring Dependency Injection with TestNG | <p>Spring support JUnit quite well on that:
With the <code>RunWith</code> and <code>ContextConfiguration</code> annotation, things look very intuitive</p>
<pre><code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:dao-context.xml")
</code></pre>
<p>This test will be able to run both in Eclipse & Maven in correctly.
I wonder if there is similar stuff for TestNG. I'm considering moving to this "Next Generation" Framework but I didn't find a match for testing with Spring.</p> | 2,608,580 | 3 | 0 | null | 2010-04-09 15:06:08.243 UTC | 18 | 2020-07-22 10:51:29.713 UTC | null | null | null | null | 244,000 | null | 1 | 62 | junit|spring|testng | 34,571 | <p>It works with TestNG as well. Your <em>test</em> class needs to <strong><em>extend</em></strong> one of the following classes:</p>
<ul>
<li><a href="http://docs.spring.io/spring/docs/current/javadoc-api/index.html?org/springframework/test/context/testng/AbstractTestNGSpringContextTests.html" rel="noreferrer"><code>org.springframework.test.context.testng.AbstractTestNGSpringContextTests</code></a></li>
<li><a href="http://docs.spring.io/spring/docs/current/javadoc-api/index.html?org/springframework/test/context/testng/AbstractTransactionalTestNGSpringContextTests.html" rel="noreferrer"><code>org.springframework.test.context.testng.AbstractTransactionalTestNGSpringContextTests</code></a></li>
</ul> |
2,548,815 | Find file name from full file path | <p>Is there a way to extract the file name from the file full path (part of a file path) without the hassle of manipulating string?</p>
<p>The equivalent in Java would be:</p>
<pre><code>File f = new File ("C:/some_dir/a")
f.getName() //output a
f.getFullAbsolutePath() //output c:/some_dir/a
</code></pre> | 2,548,871 | 4 | 0 | null | 2010-03-30 21:16:37.59 UTC | 27 | 2022-05-24 02:18:21.857 UTC | 2016-09-30 08:15:28.893 UTC | null | 680,068 | null | 296,564 | null | 1 | 190 | file|r|path | 107,196 | <p>Use </p>
<pre><code>basename("C:/some_dir/a.ext")
# [1] "a.ext"
dirname("C:/some_dir/a.ext")
# [1] "C:/some_dir"
</code></pre> |
51,256,168 | Running unit tests with .NET Core MSTest: "The following TestContainer was not found..." | <p>I've searched high and low and can't find answer to this Exception. <a href="https://stackoverflow.com/q/5481120/8534588">This question</a> is the main one to come up when I search, but it doesn't address this issue. </p>
<pre><code>[7/8/2018 6:22:22 PM Informational] Executing test method 'CoreScraper.FlyerScraper.GetAllCurrentFlyers'
[7/8/2018 6:22:22 PM Error] System.InvalidOperationException: The following TestContainer was not found 'C:\Users\Username\Documents\Visual Studio 2017\Projects\ProductApp\CoreScraper\bin\Debug\netcoreapp2.0\CoreScraper.dll'
at Microsoft.VisualStudio.TestWindow.Controller.TestContainerProvider.<GetTestContainerAsync>d__61.MoveNext()
</code></pre>
<p>"CoreScraper" is the name of the project. When I look in that <code>...\netcoreapp2.0\</code> folder, the CoreScraper.dll is definitely in there. I am running the test by right-clicking in the test method and selecting "Run Tests". The test ran fine the very first time I ran it, but it has given me this error ever since. I've closed out of Visual Studio and reopened, deleted the contents of <code>bin\</code>, cleaned and rebuilt the project, etc.</p> | 51,268,434 | 12 | 0 | null | 2018-07-10 01:43:51.603 UTC | 4 | 2021-05-20 01:04:02.933 UTC | 2018-07-10 15:47:14.36 UTC | null | 8,534,588 | null | 8,534,588 | null | 1 | 42 | c#|selenium-webdriver|mstest|asp.net-core-2.1 | 15,098 | <p>The problem was that the NuGet package <code>Microsoft.NET.Test.Sdk</code> was not installed. Installing this package in the project via the NuGet Package Manager solved the problem.</p>
<p>This wasn't intuitive to me since I have another unit test project that runs fine without the <code>Microsoft.NET.Test.Sdk</code> package, but that project is .NET Framework 4.6.2.</p> |
545,790 | How to call web service using vbscript (synchronous)? | <p>Actually there many examples and I have used one of them. But it works asynchronous, I mean it is not waiting the function that I called to finish.</p>
<pre><code>function ProcessSend()
Set oXMLHTTP = CreateObject("MSXML2.XMLHTTP.4.0")
Set oXMLDoc = CreateObject("MSXML2.DOMDocument")
oXMLHTTP.onreadystatechange = getRef("HandleStateChange")
strEnvelope = "callNo="&callNo&"&exp="&exp
call oXMLHTTP.open("POST","http://localhost:11883/ServiceCall.asmx/"&posFirm,true)
call oXMLHTTP.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
call oXMLHTTP.send(strEnvelope)
end function
Sub HandleStateChange
if(oXMLHTTP.readyState = 4) then
dim szResponse: szResponse = oXMLHTTP.responseText
call oXMLDoc.loadXML(szResponse)
if(oXMLDoc.parseError.errorCode <> 0) then
'call msgbox("ERROR")
response = oXMLHTTP.responseText&" "&oXMLDoc.parseError.reason
'call msgbox(oXMLDoc.parseError.reason)
else
response = oXMLDoc.getElementsByTagName("string")(0).childNodes(0).text
end if
end if
End Sub
</code></pre>
<p>I call ProcessSend function in a javascript function. It connects to webservice, and returns the "response" variable. But my javascript function do not wait ProcessSend function result.
How can I make it synchronous?</p> | 545,817 | 2 | 1 | null | 2009-02-13 12:50:05.89 UTC | 3 | 2009-11-12 13:21:18.253 UTC | 2009-02-13 13:02:12.117 UTC | andynormancx | 46,354 | Alish | 66,018 | null | 1 | 8 | web-services|vbscript|synchronous|xmlhttprequest | 50,562 | <p>Here you go:</p>
<pre><code>function ProcessSend()
Set oXMLHTTP = CreateObject("MSXML2.XMLHTTP.4.0")
Set oXMLDoc = CreateObject("MSXML2.DOMDocument")
oXMLHTTP.onreadystatechange = getRef("HandleStateChange")
strEnvelope = "callNo="&callNo&"&exp="&exp
call oXMLHTTP.open("POST","http://localhost:11883/ServiceCall.asmx/"&posFirm,false)'<< changed true to false here.
call oXMLHTTP.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
call oXMLHTTP.send(strEnvelope)
end function
Sub HandleStateChange
if(oXMLHTTP.readyState = 4) then
dim szResponse: szResponse = oXMLHTTP.responseText
call oXMLDoc.loadXML(szResponse)
if(oXMLDoc.parseError.errorCode <> 0) then
'call msgbox("ERROR")
response = oXMLHTTP.responseText&" "&oXMLDoc.parseError.reason
'call msgbox(oXMLDoc.parseError.reason)
else
response = oXMLDoc.getElementsByTagName("string")(0).childNodes(0).text
end if
end if
End Sub
</code></pre>
<p>Why are you btw doing this in VBScript, if the rest of your code is in JScript? Like this:</p>
<pre><code>function ProcessSend(){
var oXMLHTTP = ActiveXObject("MSXML2.XMLHTTP.4.0")
strEnvelope = "callNo=" + callNo + " & exp=" + exp;
oXMLHTTP.open("POST", "http://localhost:11883/ServiceCall.asmx/" + posFirm, false);
oXMLHTTP.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
oXMLHTTP.send(strEnvelope);
if(oXMLHTTP.readyState == 4){
if(oXMLHTTP.responseXML.parseError.errorCode != 0){
response = oXMLHTTP.responseText & " " & oXMLHTTP.responseXML.parseError.reason;
}else{
response = oXMLHTTP.responseXML.getElementsByTagName("string")(0).childNodes(0).text;
}
}
}
</code></pre> |
444,627 | C# thread pool limiting threads | <p>Alright...I've given the site a fair search and have read over many posts about this topic. I found this question: <a href="https://stackoverflow.com/questions/435668/code-for-a-simple-thread-pool-in-c">Code for a simple thread pool in C#</a> especially helpful.</p>
<p>However, as it always seems, what I need varies slightly.</p>
<p>I have looked over the MSDN example and adapted it to my needs somewhat. The example I refer to is here: <a href="http://msdn.microsoft.com/en-us/library/3dasc8as(VS.80,printer).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/3dasc8as(VS.80,printer).aspx</a></p>
<p>My issue is this. I have a fairly simple set of code that loads a web page via the <code>HttpWebRequest</code> and <code>WebResponse</code> classes and reads the results via a <code>Stream</code>. I fire off this method in a thread as it will need to executed many times. The method itself is pretty short, but the number of times it needs to be fired (with varied data for each time) varies. It can be anywhere from 1 to 200.</p>
<p>Everything I've read seems to indicate the <code>ThreadPool</code> class being the prime candidate. Here is what things get tricky. I might need to fire off this thing say 100 times, but I can only have 3 threads at most running (for this particular task). </p>
<p>I've tried setting the <code>MaxThreads</code> on the <code>ThreadPool</code> via: </p>
<pre><code>ThreadPool.SetMaxThreads(3, 3);
</code></pre>
<p>I'm not entirely convinced this approach is working. Furthermore, I don't want to clobber other web sites or programs running on the system this will be running on. So, by limiting the # of threads on the <code>ThreadPool</code>, can I be certain that this pertains to my code and my threads only?</p>
<p>The MSDN example uses the event drive approach and calls <code>WaitHandle.WaitAll(doneEvents);</code> which is how I'm doing this. </p>
<p>So the heart of my question is, how does one ensure or specify a maximum number of threads that can be run for their code, but have the code keep running more threads as the previous ones finish up until some arbitrary point? Am I tackling this the right way?</p>
<p>Sincerely,</p>
<p>Jason</p>
<hr>
<p>Okay, I've added a semaphore approach and completely removed the <code>ThreadPool</code> code. It seems simple enough. I got my info from: <a href="http://www.albahari.com/threading/part2.aspx" rel="nofollow noreferrer">http://www.albahari.com/threading/part2.aspx</a></p>
<p>It's this example that showed me how:</p>
<p>[text below here is a copy/paste from the site]</p>
<p>A <code>Semaphore</code> with a capacity of one is similar to a <code>Mutex</code> or <code>lock</code>, except that the <code>Semaphore</code> has no "owner" – it's thread-agnostic. Any thread can call <code>Release</code> on a <code>Semaphore</code>, while with <code>Mutex</code> and <code>lock</code>, only the thread that obtained the resource can release it.</p>
<p>In this following example, ten threads execute a loop with a <code>Sleep</code> statement in the middle. A <code>Semaphore</code> ensures that not more than three threads can execute that <code>Sleep</code> statement at once: </p>
<pre><code>class SemaphoreTest
{
static Semaphore s = new Semaphore(3, 3); // Available=3; Capacity=3
static void Main()
{
for (int i = 0; i < 10; i++)
new Thread(Go).Start();
}
static void Go()
{
while (true)
{
s.WaitOne();
Thread.Sleep(100); // Only 3 threads can get here at once
s.Release();
}
}
}
</code></pre> | 444,677 | 2 | 0 | null | 2009-01-14 20:56:03.793 UTC | 18 | 2016-10-26 14:40:47.093 UTC | 2017-05-23 10:31:22.363 UTC | null | -1 | jason baisden | 50,947 | null | 1 | 36 | c#|multithreading|c#-2.0|threadpool | 47,645 | <p>Note: if you are limiting this to "3" just so you don't overwhelm the machine running your app, I'd make sure this is a problem first. The threadpool is supposed to manage this for you. On the other hand, if you don't want to overwhelm some other resource, then read on!</p>
<hr>
<p>You can't manage the size of the threadpool (or really much of anything about it).</p>
<p>In this case, I'd use a semaphore to manage access to your resource. In your case, your resource is running the web scrape, or calculating some report, etc.</p>
<p>To do this, in your static class, create a semaphore object:</p>
<pre><code>System.Threading.Semaphore S = new System.Threading.Semaphore(3, 3);
</code></pre>
<p>Then, in each thread, you do this:</p>
<pre><code>System.Threading.Semaphore S = new System.Threading.Semaphore(3, 3);
try
{
// wait your turn (decrement)
S.WaitOne();
// do your thing
}
finally {
// release so others can go (increment)
S.Release();
}
</code></pre>
<p>Each thread will block on the S.WaitOne() until it is given the signal to proceed. Once S has been decremented 3 times, all threads will block until one of them increments the counter.</p>
<p>This solution isn't perfect. </p>
<hr>
<p>If you want something a little cleaner, and more efficient, I'd recommend going with a BlockingQueue approach wherein you enqueue the work you want performed into a global Blocking Queue object.</p>
<p>Meanwhile, you have three threads (which you created--not in the threadpool), popping work out of the queue to perform. This isn't that tricky to setup and is very fast and simple.</p>
<p>Examples:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/346268/best-threading-queue-example-best-practice">Best threading queue example / best practice</a></li>
<li><a href="https://stackoverflow.com/questions/23950/best-method-to-get-objects-from-a-blockingqueue-in-a-concurrent-program">Best method to get objects from a BlockingQueue in a concurrent program?</a></li>
</ul> |
2,669,908 | Cheatsheet for Android programming? | <p>Is there any cheat sheet available for Android programming. Most commonly used classes with package description, just like a reference sheet would be nice.</p> | 2,672,044 | 5 | 5 | null | 2010-04-19 18:40:37.217 UTC | 22 | 2018-01-17 09:41:33.833 UTC | 2013-10-19 11:24:13.653 UTC | null | 100,297 | null | 165,375 | null | 1 | 33 | android | 25,977 | <p>For a concise list of Android recipes check out <a href="http://www.damonkohler.com/2009/02/android-recipes.html" rel="noreferrer">Damon Kohler's blog</a>. He covers Intents, Wifi, Notifications, Alerts, Location, SMS, and Sensors in less than four pages.</p> |
2,436,125 | C++ Access derived class member from base class pointer | <p>If I allocate an object of a class <code>Derived</code> (with a base class of <code>Base</code>), and store a pointer to that object in a variable that points to the base class, how can I access the members of the <code>Derived</code> class?</p>
<p>Here's an example:</p>
<pre><code>class Base
{
public:
int base_int;
};
class Derived : public Base
{
public:
int derived_int;
};
Base* basepointer = new Derived();
basepointer-> //Access derived_int here, is it possible? If so, then how?
</code></pre> | 2,436,147 | 5 | 0 | null | 2010-03-12 21:48:18.75 UTC | 28 | 2020-06-07 16:31:00.503 UTC | 2018-08-09 01:42:10.48 UTC | null | 5,231,607 | null | 292,688 | null | 1 | 46 | c++|inheritance|pointers|derived-class | 92,234 | <p>No, you cannot access <code>derived_int</code> because <code>derived_int</code> is part of <code>Derived</code>, while <code>basepointer</code> is a pointer to <code>Base</code>.</p>
<p>You can do it the other way round though:</p>
<pre><code>Derived* derivedpointer = new Derived;
derivedpointer->base_int; // You can access this just fine
</code></pre>
<p>Derived classes inherit the members of the base class, not the other way around.</p>
<p>However, if your <code>basepointer</code> was pointing to an instance of <code>Derived</code> then you could access it through a cast:</p>
<pre><code>Base* basepointer = new Derived;
static_cast<Derived*>(basepointer)->derived_int; // Can now access, because we have a derived pointer
</code></pre>
<p>Note that you'll need to change your inheritance to <code>public</code> first:</p>
<pre><code>class Derived : public Base
</code></pre> |
3,003,187 | Jquery JQGrid - How to set alignment of grid header cells? | <p>Is it possible to align grid column headers in jqgrid? eg align left right or center?</p>
<p>In the jqrid documents <a href="http://www.trirand.com/jqgridwiki/doku.php?id=wiki:colmodel_options" rel="noreferrer">http://www.trirand.com/jqgridwiki/doku.php?id=wiki:colmodel_options</a> it says:</p>
<pre><code>align: Defines the alignment of the cell in the Body layer, not in header cell.
Possible values: left, center, right.
</code></pre>
<p>Note that it says "not in the header cell". How can I do this for the header cell (grid title cell)? The documentation fails to mention this little detail....</p> | 3,006,853 | 6 | 0 | null | 2010-06-09 05:02:09.63 UTC | 10 | 2020-09-03 05:19:13.46 UTC | 2011-01-25 09:09:03.267 UTC | null | 325,727 | null | 325,727 | null | 1 | 26 | jquery|jqgrid | 61,314 | <p>The best documented way to change column header alignment is the usage of <code>setLabel</code> method of jqGrid (see <a href="http://www.trirand.com/jqgridwiki/doku.php?id=wiki:methods" rel="noreferrer">http://www.trirand.com/jqgridwiki/doku.php?id=wiki:methods</a>).</p>
<p>You can change alignment of the column identified by <code>'name': 'Name'</code> with the following code:</p>
<pre><code>grid.jqGrid ('setLabel', 'Name', '', {'text-align':'right'});
</code></pre>
<p>With the code </p>
<pre><code>grid.jqGrid ('setLabel', 'Name', 'Product Name', {'text-align':'right'},
{'title':'My ToolTip for the product name column header'});
</code></pre>
<p>you can change the header name to 'Product Name' and set 'My ToolTip for the product name column header' as a tool tip for the corresponding column header.</p>
<p>You can also define some classes in your CSS and set it for the column headers also with respect of <code>setLabel</code> method.</p>
<p>By the way the name of the function 'setLabel' is choosed because you can not define <code>colNames</code> parameter of the jqGrid, but use additional <code>'label'</code> option in the <code>colModel</code> to define a column header other as the <code>'name'</code> value.</p>
<p><strong>UPDATED</strong>: You can do able to use classes to define <code>'text-align'</code> or <code>'padding'</code>. Just try following</p>
<pre><code>.textalignright { text-align:right !important; }
.textalignleft { text-align:left !important; }
.textalignright div { padding-right: 5px; }
.textalignleft div { padding-left: 5px; }
</code></pre>
<p>and</p>
<pre><code>grid.jqGrid ('setLabel', 'Name', '', 'textalignright');
grid.jqGrid ('setLabel', 'Description', '', 'textalignleft');
</code></pre>
<p>(I defined 5px as the padding to see results better. You can choose the padding value which you will find better in your case).</p> |
2,399,753 | Select from table by knowing only date without time (ORACLE) | <p>I'm trying to retrieve records from table by knowing the date in column contains date and time.</p>
<p>Suppose I have table called <code>t1</code> which contains only two column <code>name</code> and <code>date</code> respectively.</p>
<p>The data stored in column date like this <code>8/3/2010 12:34:20 PM</code>.</p>
<p>I want to retrieve this record by this query for example (note I don't put the time):</p>
<pre><code>Select * From t1 Where date="8/3/2010"
</code></pre>
<p>This query give me nothing ! </p>
<p>How can I retrieve <code>date</code> by knowing only <code>date</code> without the time?</p> | 2,399,800 | 7 | 0 | null | 2010-03-08 06:56:11.007 UTC | 13 | 2019-11-08 04:44:48.217 UTC | 2016-09-12 07:19:55.007 UTC | null | 4,823,977 | null | 288,565 | null | 1 | 57 | sql|oracle|date | 203,367 | <p><code>DATE</code> is a reserved keyword in Oracle, so I'm using column-name <code>your_date</code> instead.</p>
<p>If you have an index on <code>your_date</code>, I would use</p>
<pre><code>WHERE your_date >= TO_DATE('2010-08-03', 'YYYY-MM-DD')
AND your_date < TO_DATE('2010-08-04', 'YYYY-MM-DD')
</code></pre>
<p>or <code>BETWEEN</code>:</p>
<pre><code>WHERE your_date BETWEEN TO_DATE('2010-08-03', 'YYYY-MM-DD')
AND TO_DATE('2010-08-03 23:59:59', 'YYYY-MM-DD HH24:MI:SS')
</code></pre>
<p>If there is no index or if there are not too many records</p>
<pre><code>WHERE TRUNC(your_date) = TO_DATE('2010-08-03', 'YYYY-MM-DD')
</code></pre>
<p>should be sufficient. <a href="http://download.oracle.com/docs/cd/B28359_01/olap.111/b28126/dml_functions_2127.htm" rel="noreferrer"><code>TRUNC</code></a> without parameter removes hours, minutes and seconds from a <code>DATE</code>.</p>
<hr>
<p>If performance really matters, consider putting a <a href="http://www.akadia.com/services/ora_function_based_index_2.html" rel="noreferrer"><code>Function Based Index</code></a> on that column:</p>
<pre><code>CREATE INDEX trunc_date_idx ON t1(TRUNC(your_date));
</code></pre> |
2,655,928 | SQL Management Studio - Execute current line | <p>In SQL Server 2008 Management studio, I can hit F5 to execute everything in the current query window. I can also highlight a query, and hit F5 to run that highlighted query. </p>
<p>Instead of having to highlight a query, is there a way I can run the single query my cursor is on, or run a query my cursor is on up to a the first ';'?</p> | 2,655,975 | 8 | 4 | null | 2010-04-16 20:31:34.89 UTC | 1 | 2019-02-05 14:59:00.08 UTC | null | null | null | null | 24,717 | null | 1 | 40 | ssms | 16,446 | <p>Unfortunately no there is no such keyboard shortcut in the <a href="http://msdn.microsoft.com/en-us/library/ms174205.aspx" rel="noreferrer">MSDN list of keyboard shortcuts for SMSS</a>, and I don't see any way of recording a macro to do so. The only solutions I've found require creating an add-in which is <strong>quite</strong> a bit of work for a little savings.</p> |
2,403,990 | HTML colspan in CSS | <p>I'm trying to construct a layout similar to the following:</p>
<pre><code>+---+---+---+
| | | |
+---+---+---+
| |
+-----------+
</code></pre>
<p>where the bottom is filling the space of the upper row.</p>
<p>If this were an actual table, I could easily accomplish this with <code><td colspan="3"></code>, but as I'm simply creating a table-like <em>layout</em>, I cannot use <code><table></code> tags. Is this possible using CSS?</p> | 2,579,484 | 16 | 8 | null | 2010-03-08 19:15:17.393 UTC | 36 | 2020-09-09 07:17:46.897 UTC | 2016-02-16 09:58:49.953 UTC | null | 106,224 | null | 283,055 | null | 1 | 282 | css | 474,219 | <p>There's no simple, elegant CSS analog for <code>colspan</code>.</p>
<p>Searches on this very issue will return a variety of solutions that include a bevy of alternatives, including absolute positioning, sizing, along with a similar variety of browser- and circumstance-specific caveats. Read, and make the best informed decision you can based on what you find. </p> |
25,102,101 | Spring Integration and TCP server socket - how can I send a message to a client? | <p>I'm trying to create a server in Spring that's listening on a TCP port and accepts connections.
I know how to route incoming requests to my service, and it can respond to those.
However I would like to send messages to certain clients without any request received. For example, sometimes I have to inform a client about that it has got a message.</p>
<p>To do this, I think I need a way to identify the clients, e.g. by letting them log in. Is there a way to have a "session" object for each active connection in which I can store login data?</p>
<p>How could I send a message to a client which has logged in with username X?</p>
<p>Is this possible in Spring at all?</p> | 25,105,134 | 1 | 0 | null | 2014-08-03 06:00:35.093 UTC | 8 | 2017-11-08 16:18:02.1 UTC | null | null | null | null | 1,370,376 | null | 1 | 17 | java|spring|sockets|tcp|spring-integration | 14,786 | <p>Starting with version 3.0; the frameworks now <a href="http://docs.spring.io/spring-integration/reference/html/ip.html#tcp-events" rel="noreferrer">emits connection events when there are connection state changes</a>. You can capture these events using an <code>ApplicationListener</code>, or using an <code><event:inbound-channel-adapter/></code>.</p>
<p>The <code>TcpConnectionOpenEvent</code> contains a <code>connectionId</code>; you can send arbitrary messages to any connection once you know its id, by populating the <code>IpHeaders.connectionId</code> header (<code>ip_connectionId</code>) in a message and sending it to a <code><tcp:outbound-channel-adapter/></code>.</p>
<p>If you need to support request/reply as well as sending arbitrary messages, you need to use a collaborating pair of channel adapters for all communication, not a gateway. </p>
<p><strong>EDIT</strong></p>
<p>Here's a simple Boot app...</p>
<pre><code>package com.example;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Socket;
import javax.net.SocketFactory;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.dsl.IntegrationFlow;
import org.springframework.integration.dsl.IntegrationFlows;
import org.springframework.integration.ip.IpHeaders;
import org.springframework.integration.ip.tcp.TcpReceivingChannelAdapter;
import org.springframework.integration.ip.tcp.TcpSendingMessageHandler;
import org.springframework.integration.ip.tcp.connection.TcpConnectionOpenEvent;
import org.springframework.integration.ip.tcp.connection.TcpNetServerConnectionFactory;
import org.springframework.integration.ip.tcp.connection.TcpServerConnectionFactory;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;
@SpringBootApplication
public class So25102101Application {
public static void main(String[] args) throws Exception {
ConfigurableApplicationContext context = new SpringApplicationBuilder(So25102101Application.class)
.web(false)
.run(args);
int port = context.getBean(TcpServerConnectionFactory.class).getPort();
Socket socket = SocketFactory.getDefault().createSocket("localhost", port);
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line = reader.readLine();
System.out.println(line);
context.close();
}
@Bean
public TcpReceivingChannelAdapter server(TcpNetServerConnectionFactory cf) {
TcpReceivingChannelAdapter adapter = new TcpReceivingChannelAdapter();
adapter.setConnectionFactory(cf);
adapter.setOutputChannel(inputChannel());
return adapter;
}
@Bean
public MessageChannel inputChannel() {
return new QueueChannel();
}
@Bean
public MessageChannel outputChannel() {
return new DirectChannel();
}
@Bean
public TcpNetServerConnectionFactory cf() {
return new TcpNetServerConnectionFactory(0);
}
@Bean
public IntegrationFlow outbound() {
return IntegrationFlows.from(outputChannel())
.handle(sender())
.get();
}
@Bean
public MessageHandler sender() {
TcpSendingMessageHandler tcpSendingMessageHandler = new TcpSendingMessageHandler();
tcpSendingMessageHandler.setConnectionFactory(cf());
return tcpSendingMessageHandler;
}
@Bean
public ApplicationListener<TcpConnectionOpenEvent> listener() {
return new ApplicationListener<TcpConnectionOpenEvent>() {
@Override
public void onApplicationEvent(TcpConnectionOpenEvent event) {
outputChannel().send(MessageBuilder.withPayload("foo")
.setHeader(IpHeaders.CONNECTION_ID, event.getConnectionId())
.build());
}
};
}
}
</code></pre>
<p>pom deps:</p>
<pre><code><dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-integration</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-ip</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</code></pre> |
25,180,148 | PHPunit result output on the CLI not showing test names | <p>I'm running a brand new test suite in PHPUnit, I'd like to see the result of each test with the test name next to it. It would make fixing broken tests and TDD easier.</p>
<p>PHPunit does output the broken messages afterwards but your eyes go wonky after a while going through all the errors and stacktraces.</p>
<p>The current <code>.......F...................</code> type output is great once your test suite is up and stable, but while you're creating a suite...</p>
<p>I've tried the <code>--verbose</code> param and it doesn't help.</p> | 25,180,149 | 2 | 0 | null | 2014-08-07 10:28:25.32 UTC | 11 | 2019-05-07 19:19:11.057 UTC | 2015-07-24 09:26:09.707 UTC | null | 341,156 | null | 341,156 | null | 1 | 52 | phpunit|command-line-interface | 18,418 | <p>Use <code>phpunit --testdox</code><br>
On the cli this will give you a very readable <a href="http://en.wikipedia.org/wiki/TestDox" rel="noreferrer">testdox</a> format and allow you to see and fix your multiple test suites easily e.g.</p>
<pre class="lang-sh prettyprint-override"><code>PHPUnit 3.7.37 by Sebastian Bergmann.
Configuration read from /home/badass-project/tests/phpunit.xml
AnalyticsViewers
[x] test getViewersForMonth throws for no valid date
[x] test getViewersForMonth limits correctly
[x] test getViewersForMonth only returns unprocessed records
[ ] test getViewersForMonth marks retrieved records as processed
[ ] test getViewersForMonth returns zero for no view data
[x] test getViewersForMonth returns valid data
Organisation
[x] test getOrganisation returns orgs
</code></pre>
<p>I use it in combination with the stack traces from a vanilla PHPUnit run to quickly setup.</p>
<p>It also has the added benefit of replacing underscores in your test function names with spaces. eg <code>test_getViewersForMonth_returns_valid_data</code> becomes <code>test getViewersForMonth returns zero for no view data</code> which is more human readable.<br>
<strong>N.B.</strong> Generally speaking if you're following the <a href="http://www.php-fig.org/psr/psr-1/" rel="noreferrer">PSR coding standards</a> you should be using camelCase for method names but for unit tests methods I break this rule to reduce <a href="http://en.wikipedia.org/wiki/Cognitive_load" rel="noreferrer">cognitive load</a> during TDD development.</p> |
40,250,381 | Module compiled with swift 3.0 cannot be imported in Swift 3.0.1 | <p>I upgraded Xcode to 8.1 GM and am now getting the below error for SwiftyJSON. Other imported frameworks seem to work. Is there a way to force this to work in Swift 3 until SwiftyJSON upgrades their framework? I used Carthage to import/update frameworks. I also tried changing <code>Use Legacy Swift language version</code> On and Off to no avail.</p>
<blockquote>
<p>Module compiled with Swift 3.0 cannot be imported in Swift 3.0.1:
Modules/SwiftyJSON.swiftmodule/arm64.swiftmodule</p>
</blockquote> | 40,339,551 | 9 | 0 | null | 2016-10-25 21:54:29.433 UTC | 21 | 2018-08-06 13:31:14.593 UTC | 2017-06-13 10:03:22.313 UTC | null | 4,613,212 | null | 2,452,063 | null | 1 | 87 | swift|swifty-json | 25,312 | <p>SwiftyJson is being downloaded precompiled by carthage. The precompiled download is with Swift Version 3.0. That makes the compiler complain that the version is not correct. Using the following command: </p>
<pre><code>carthage update --platform iOS --no-use-binaries
</code></pre>
<p>SwiftyJson (and all other frameworks within Carthage) will be compiled locally using the local version of Swift (3.0.1) and the compiler will not complain anymore.</p> |
10,587,814 | CSS: Why background-color breaks/removes the box-shadow? | <p>I have a pretty simple div structure - tree boxes with middle box highlighted with box-shadow:</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>.offerBox {
width: 300px;
margin: 10px;
}
.obOffer {
width: 33%;
float: left;
height: 100px;
text-align: center;
}
.obOfferPrice {
padding: 10px;
color: white;
background-color: #85AADD;
}
.obHiLight {
box-shadow: 0 0 25px rgba(0, 0, 0, 0.6);
-moz-box-shadow: 0 0 25px rgba(0, 0, 0, 0.6);
-webkit-box-shadow: 0 0 25px rgba(0, 0, 0, 0.6);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="offerBox">
<div class="obOffer">
<div class="obOfferTitle">Free</div>
<div class="obOfferPrice">Free</div>
</div>
<div class="obOffer obHiLight">
<div class="obOfferTitle">Title</div>
<div class="obOfferPrice">$10</div>
</div>
<div class="obOffer">
<div class="obOfferTitle">Title 2</div>
<div class="obOfferPrice">$10</div>
</div>
</div></code></pre>
</div>
</div>
</p>
<p>
One of the elements inside those boxes have a background-color property set. For some reasons this background-color removes the box-shadow from the right and only from the right.</p>
<p>Any ideas why and how to fix it?</p>
<p>Live Example of the problem:
<a href="http://jsfiddle.net/SqvUd/" rel="noreferrer">http://jsfiddle.net/SqvUd/</a></p> | 10,587,858 | 3 | 0 | null | 2012-05-14 16:58:07.097 UTC | 4 | 2020-09-21 19:16:07.46 UTC | 2020-09-21 19:16:07.46 UTC | null | 7,101,876 | null | 1,258,109 | null | 1 | 32 | html|css | 21,664 | <p>You just need to add z-index and position:relative; see the example. <a href="http://jsfiddle.net/SqvUd/2/">http://jsfiddle.net/SqvUd/2/</a></p> |
6,203,266 | cannot open source file "stdafx.h" | <p>I have two include file headers</p>
<pre><code>#include "stdafx.h"
#include "psapi.h"
</code></pre>
<p>However it gives a cannot open source file "stdafx.h" compile time error. I am using Visual Studios 2010. Is "stdafx.h" even necessary? I think so because the program cannot compile if i take it away.</p> | 6,203,316 | 2 | 0 | null | 2011-06-01 14:58:56.97 UTC | null | 2011-06-01 21:12:16.86 UTC | 2011-06-01 21:12:16.86 UTC | null | 654,891 | null | 501,600 | null | 1 | 6 | c++|visual-c++ | 38,931 | <p>Visual Studio uses it for "precompiled headers" feature. If you are not experienced with Visual Studio, I would recommend to keep the stdafx.h in the project.</p>
<p>And of course, if you #include it, you ought to have it.</p> |
31,251,342 | TextInputLayout and EditText double hint issue | <p>I want to set the hint with java in EditText(which is in TextInputLayout).</p>
<p><strong>Code used for setting hint:</strong></p>
<p><code>aET = (EditText) findViewById(R.id.aET);
aET.setHint("h?");
</code></p>
<p>But even when edittext is focused, Hint is displayed twice(inside edittext also).</p>
<p>Please let me know if anyone had faced and found some workaround</p>
<p><strong>when editText is focused...</strong></p>
<p><img src="https://i.stack.imgur.com/KqxVU.png" alt="Second"></p>
<p><strong>when editText is not focused..</strong></p>
<p><img src="https://i.stack.imgur.com/miEEj.png" alt="First"></p>
<p><strong>EDIT[10th July 2015]:</strong></p>
<pre><code><android.support.design.widget.TextInputLayout
android:id="@+id/aTIL"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/aET" />
</android.support.design.widget.TextInputLayout>
</code></pre> | 31,502,054 | 8 | 2 | null | 2015-07-06 16:47:12.953 UTC | 3 | 2022-01-25 12:27:48.177 UTC | 2015-07-10 11:55:48.893 UTC | null | 982,852 | null | 3,637,135 | null | 1 | 30 | android|android-edittext|android-appcompat|android-textinputlayout | 20,425 | <p>I found the solution !</p>
<p>In your EditText add </p>
<pre><code>android:textColorHint="@android:color/transparent"
</code></pre>
<p>And in the code set the hint from the EditText</p>
<pre><code>aET.setHint("h?");
</code></pre>
<p>The hint in your editText is hidden and the hint from the TextInputLayout is shown.</p>
<p><strong><em>EDIT :</em></strong></p>
<p><strong>Other solution (The best)</strong></p>
<p>Update Graddle with the new version of android:design</p>
<pre><code>compile 'com.android.support:design:22.2.1'
</code></pre> |
40,960,599 | How to set SwipeRefreshLayout refreshing property using android data binding? | <p>I am using android data binding library.
If I want to make a view visible I can write something like this:</p>
<pre><code><TextView
android:id="@+id/label_status"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="@{habitListViewModel.message}"
app:visibility="@{habitListViewModel.hasError ? View.VISIBLE : View.GONE}" />
</code></pre>
<p>Is there an option to bind to a refresh property of swipeRefreshLayout in a similar (xml) way? </p>
<p>Currently I am setting it in code by calling setRefreshing(true/false) but would love to make it in xml to be consistent. </p> | 40,961,880 | 4 | 0 | null | 2016-12-04 16:06:30.15 UTC | 9 | 2021-03-18 10:48:08.557 UTC | 2017-04-18 20:46:51.91 UTC | null | 563,904 | null | 1,642,126 | null | 1 | 39 | android|data-binding|swiperefreshlayout|android-layout | 18,593 | <p><strong>UPDATED:</strong>
As databinding maps from xml attribute name to <code>set{AttributeName}</code>, you can just use <code>app:refreshing</code>, as databinding will successfully supply the value to <code>setRefreshing</code> method of <code>SwipeRefreshLayout</code> (which luckily for us exists and is public):</p>
<pre><code><android.support.v4.widget.SwipeRefreshLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:refreshing="@{habitListViewModel.isLoading}">
...
//ListView,RecyclerView or something
</android.support.v4.widget.SwipeRefreshLayout>
</code></pre>
<p>That's it! Note, that you can simply use <code>@{true}</code> or <code>@{false}</code> instead of <code>@{habitListViewModel.isLoading}</code>. Hope that helps.</p> |
40,797,296 | Angular 2: How to handle *ngif in option select | <p>How to can i use *ngif for set a specific default selected option?</p>
<p>I need reload data from database for editing, when i retrieve data i need set the default value of option in base a stored value.</p>
<p>I have this:</p>
<pre><code><select class="form-control" id="deviceModel">
<option value="">Select a category</option>
<option *ngFor='let element of category'*ngIf="{{element}}==={{nameDevice}}" value="{{element}}">{{element}}</option>
</select>
</code></pre>
<p>Thanks in advance.</p> | 40,797,644 | 4 | 0 | null | 2016-11-25 03:30:58.433 UTC | 1 | 2019-09-25 12:31:05.383 UTC | null | null | null | null | 1,114,066 | null | 1 | 8 | angular | 50,368 | <p>ngIf is for structural manipulation, basically whether something is in the DOM, or removed. If you want to bind to the selected property, you could use:</p>
<pre><code><select class="form-control" id="deviceModel">
<option value="">Select a category</option>
<option *ngFor='let element of category' [selected]="element === nameDevice" [value]="element">{{element}}</option>
</select>
</code></pre>
<p>From <a href="https://angular.io/docs/ts/latest/api/forms/index/SelectControlValueAccessor-directive.html" rel="noreferrer">https://angular.io/docs/ts/latest/api/forms/index/SelectControlValueAccessor-directive.html</a>:</p>
<blockquote>
<p>If your option values are simple strings, you can bind to the normal
value property on the option. If your option values happen to be
objects (and you'd like to save the selection in your form as an
object), use ngValue instead.</p>
</blockquote>
<p>If you want to use <code>ngModel</code> binding, have a look at <a href="https://stackoverflow.com/questions/35945001/binding-select-element-to-object-in-angular-2">Binding select element to object in Angular 2</a></p>
<p>Note that when using property binding, you don't/shouldn't use string interpolation</p> |
21,053,988 | lambda function accessing outside variable | <p>I wanted to play around with anonymous functions so I decided to make a simple prime finder. Here it is:</p>
<pre class="lang-py prettyprint-override"><code>tests = []
end = int(1e2)
i = 3
while i <= end:
a = map(lambda f:f(i),tests)
if True not in a:
tests.append(lambda x:x%i==0)
print i
print tests
print "Test: "+str(i)
print str(a)
i+=2
</code></pre>
<p>What I find however, is that the <code>i</code> in the <code>lambda x:x%i==0</code> is accessed each time, while i want it to be a literal number. how can I get it to become <code>lambda x:x%3==0</code> instead?</p> | 21,054,087 | 3 | 1 | null | 2014-01-10 20:39:41.653 UTC | 9 | 2021-07-20 22:51:20.91 UTC | 2021-05-27 08:03:51.117 UTC | null | 12,385,184 | null | 2,133,137 | null | 1 | 34 | python|scope | 35,414 | <p>You can "capture" the <code>i</code> when creating the lambda</p>
<pre><code>lambda x, i=i: x%i==0
</code></pre>
<p>This will set the <code>i</code> in the lambda's context equal to whatever <code>i</code> was when it was created. you could also say <code> lambda x, n=i: x%n==0</code> if you wanted. It's not exactly capture, but it gets you what you need.</p>
<hr />
<p>It's an issue of lookup that's analogous to the following with defined functions:</p>
<pre><code>i = "original"
def print_i1():
print(i) # prints "changed" when called below
def print_i2(s=i): # default set at function creation, not call
print(s) # prints "original" when called below
i = "changed"
print_i1()
print_i2()
</code></pre> |
46,639,058 | Firebase Cloud Firestore : Invalid collection reference. Collection references must have an odd number of segments | <p>I have the following code and getting an error : </p>
<pre><code>Invalid collection reference. Collection references must have an odd number of segments
</code></pre>
<p><strong>And the code :</strong></p>
<pre><code>private void setAdapter() {
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("app/users/" + uid + "/notifications").get().addOnCompleteListener(task -> {
if (task.isSuccessful()) {
for (DocumentSnapshot document : task.getResult()) {
Log.d("FragmentNotifications", document.getId() + " => " + document.getData());
}
} else {
Log.w("FragmentNotifications", "Error getting notifications.", task.getException());
}
});
}
</code></pre> | 46,639,620 | 5 | 0 | null | 2017-10-09 04:53:30.973 UTC | 5 | 2022-01-15 17:25:47.857 UTC | null | null | null | null | 2,873,357 | null | 1 | 66 | java|android|firebase|google-cloud-firestore | 85,241 | <p>Hierarchical data structures and subcollections are described in <a href="https://firebase.google.com/docs/firestore/data-model#hierarchical-data" rel="noreferrer">the documentation</a>. A collection contains documents and a document may contain a subcollection. The structure is always an alternating pattern of collections and documents. The documentation contains this description of an example:</p>
<blockquote>
<p>Notice the alternating pattern of collections and documents. Your
collections and documents must always follow this pattern. You cannot
reference a collection in a collection or a document in a document.</p>
</blockquote>
<p>Thus, a valid path to a collection will always have an odd number of segments; a valid path to a document, an even number. Since your code is trying to query a collection, the path length of four is invalid.</p> |
25,707,222 | print python emoji as unicode string | <p>I've been trying to output <code>''</code> as <code>'\U0001f604'</code> instead of the smiley, but it doesn't seem to work.</p>
<p>I tried using <code>repr()</code> but it gives me this <code>'\xf0\x9f\x98\x84'</code>. Currently it outputs the smiley which is not what I wanted. <code>encode('unicode_escape')</code> gives me a <code>UnicodeDecodeError</code>.</p>
<p>The smiley was passed as a string to a class method in python. i.e. <code>"I am happy "</code></p> | 25,707,367 | 8 | 0 | null | 2014-09-07 05:00:45.47 UTC | 3 | 2022-08-24 09:45:31.313 UTC | 2021-01-02 23:03:54.947 UTC | null | 9,063,935 | null | 1,896,865 | null | 1 | 24 | python-2.7|unicode|emoji | 80,768 | <p>I found the solution to the problem.</p>
<p>I wrote the following code:</p>
<pre><code>#convert to unicode
teststring = unicode(teststring, 'utf-8')
#encode it with string escape
teststring = teststring.encode('unicode_escape')
</code></pre> |
8,931,612 | Do ALL virtual functions need to be implemented in derived classes? | <p>This may seem like a simple question, but I can't find the answer anywhere else.</p>
<p>Suppose I have the following:</p>
<pre><code>class Abstract {
public:
virtual void foo() = 0;
virtual void bar();
}
class Derived : Abstract {
public:
virtual void foo();
}
</code></pre>
<p>Is it ok that class Derived does not implement the bar() function?
What if not ALL of my derived classes need the bar() function, but some do.
Do all of the virtual functions of an abstract base class need to be implemented in the derived classes, or just the ones that are pure virtual?
Thanks</p> | 8,931,630 | 5 | 0 | null | 2012-01-19 18:51:12.39 UTC | 38 | 2017-06-20 18:13:31.377 UTC | null | null | null | null | 387,203 | null | 1 | 112 | c++|inheritance | 88,090 | <p>Derived classes do <strong>not</strong> have to implement <em>all</em> virtual functions themselves. They only need to implement the <em>pure</em> ones.<sup>1</sup> That means the <code>Derived</code> class in the question is correct. It <em>inherits</em> the <code>bar</code> implementation from its ancestor class, <code>Abstract</code>. (This assumes that <code>Abstract::bar</code> is implemented somewhere. The code in the question declares the method, but doesn't define it. You can define it inline as <a href="https://stackoverflow.com/a/8931719/33732">Trenki's answer</a> shows, or you can define it separately.)</p>
<hr>
<p><sup>1</sup> And even then, only if the derived class is going to be <em>instantiated</em>. If a derived class is not instantiated directly, but only exists as a base class of more derived classes, then it's <em>those</em> classes that are responsible for having all their pure virtual methods implemented. The "middle" class in the hierarchy is allowed to leave some pure virtual methods unimplemented, just like the base class. If the "middle" class <em>does</em> implement a pure virtual method, then its descendants will inherit that implementation, so they don't have to re-implement it themselves.</p> |
47,614,008 | Can I have a varying number of columns per row in a CSS grid? | <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>.grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: 100px;
grid-auto-rows: 60px;
grid-gap: 15px;
}
.col {
background-color: tomato;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid">
<div class="col"></div>
<div class="col"></div>
<div class="col"></div>
<div class="col"></div>
<div class="col"></div>
</div></code></pre>
</div>
</div>
</p>
<p>This creates 2 rows, first is 100px height, second is auto-created with <code>60px</code> height. 2 columns in the second row have <code>1fr</code> width.</p>
<p>Is this possible via CSS Grid/Flexbox to horizontally center 2 columns in the 2nd row? I.e. have a varying number of columns per row.</p>
<p>I am stuck trying to solve a trivial usecase for the CSS Grid framework in the browser. This is pretty nonproblematic to achieve if you build your grids with Flexbox.</p>
<p>But can I achieve it with CSS Grid?</p>
<p>Here is a <a href="https://codepen.io/anon/pen/yPZpBp" rel="noreferrer">CodePen demo</a> of what I am trying to achieve.</p> | 47,614,077 | 5 | 2 | null | 2017-12-03 00:23:17.523 UTC | 2 | 2021-07-30 19:59:55.347 UTC | 2017-12-03 01:18:09.57 UTC | null | 2,756,409 | null | 3,317,291 | null | 1 | 29 | css|css-grid | 31,957 | <p>If your rows have varying numbers of cells that aren't all laid out on a single two-dimensional (row and column) space, you don't have a grid. A grid by definition contains a fixed number of rows and columns, and cells that span one or more of each. Maybe you'd have multiple heterogeneous grids, one per row, but that just defeats the whole point of grids, really.</p>
<p>If your varying number of rows is symmetrical or follows some kind of pattern, you can follow Michael_B's suggestion of building a grid based on a common denominator and populating the grid areas mosaic-style. This is just about as non-trivial as a flexbox solution currently would be, but once more browsers implement <a href="https://www.w3.org/TR/css-flexbox-1/#pagination" rel="noreferrer">flexbox fragmentation</a>, flexbox should become the obvious choice over grid as it ought to be.</p> |
64,968,851 | Could not find tools.jar. Please check that /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home contains a valid JDK installation | <pre class="lang-none prettyprint-override"><code>FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':react-native-linear-gradient:compileDebugJavaWithJavac'.
> Could not find tools.jar. Please check that /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home contains a valid JDK installation.
</code></pre>
<p>When I upgraded to Mac os Big sur and run,</p>
<pre><code>npx react-native run-android
</code></pre>
<p>I got this error (Android). I have tried a lot of solutions from Stack Overflow, but none of them worked.</p>
<p>I have created a fresh project and it's working. Also some of the old projects are also working perfectly.</p>
<pre><code>*react-native Version: "0.63.3",*
</code></pre>
<p>Please help me to find a solution?</p> | 64,987,486 | 24 | 4 | null | 2020-11-23 12:56:06.89 UTC | 29 | 2022-07-05 05:39:29.447 UTC | 2020-12-12 14:05:53.94 UTC | null | 466,862 | null | 14,692,268 | null | 1 | 175 | android|react-native | 119,606 | <p>The problem is that with the update the built-in java took precedence and it doesn't have the SDK because it's just the runtime.</p>
<p>You just need to change your java home and add the java binary to your .zshrc
to find your java home execute:</p>
<pre><code>/usr/libexec/java_home -V | grep jdk
</code></pre>
<p>the output should be similar to the following:</p>
<pre><code>Matching Java Virtual Machines (1):
1.8.0_272 (x86_64) "AdoptOpenJDK" - "AdoptOpenJDK 8" /Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home
/Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home
</code></pre>
<p>you should take the path from the one that says SDK in my case</p>
<pre><code>/Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home
</code></pre>
<p>after that, you just add the following to the end of your .zshrc that should be in your home.</p>
<p>You can edit it with (if you decide to use vim you can exit writing :wq! and pressing enter)</p>
<pre><code>vim .zshrc
</code></pre>
<p>add the following:</p>
<pre><code>export JAVA_HOME=the/path/you/copied/before
export PATH=$JAVA_HOME/bin:$PATH
</code></pre>
<p>where the/path/you/copied/before in my case would be</p>
<pre><code>/Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home
</code></pre>
<p>save the file and close all your terminals and open them again.</p>
<p>If while editing .zshrc file getting error ".zshrc" E212: Can't open file for writing
then use sudo vim.zshrc and you'll be able to edit.</p>
<p>The error should be solved.</p>
<h3>Edit</h3>
<p>Instead of <code>~/.zshrc</code>, you could have <code>~/.bash_profile</code> or <code>~/.bash_rc</code> so edit yours accordingly</p> |
606,534 | Opening a remote machine's Windows C drive | <p>I'm trying to locally mount a machine's C drive that is on my LAN. I need to able to browse the contents of the other machine when tracing through code. I once saw a sys admin do some crazy windows incantation from the cmd prompt. Something like
$remote_machine/local_access/C</p>
<p>Is anyone familiar with how this is done?</p> | 606,544 | 3 | 2 | null | 2009-03-03 14:19:56.497 UTC | 12 | 2009-03-04 04:04:27.59 UTC | 2009-03-04 04:04:27.607 UTC | funkyworklehead | 20,712 | funkyworklehead | 20,712 | null | 1 | 26 | windows|windows-xp|sysadmin | 154,069 | <p>If it's not the Home edition of XP, you can use <code>\\servername\c$</code></p>
<p>Mark Brackett's comment:</p>
<blockquote>
<p>Note that you need to be an
Administrator on the local machine, as
the share permissions are locked down</p>
</blockquote> |
1,336,600 | CSS - Only Horizontal Overflow? | <p>Is it possible to achieve only horizontal overflow in CSS 2.1?</p>
<pre><code>overflow: auto;
</code></pre>
<p>Will cause a block element to have both horizontal and vertical scrollbars. I want a block element (let's say <code><div></code>) which will display only horizontal scrollbars. How do I do that?</p> | 1,336,605 | 3 | 0 | null | 2009-08-26 18:21:56.01 UTC | 3 | 2022-07-29 20:53:38.627 UTC | 2012-08-07 01:02:11.813 UTC | null | 1,113,772 | null | 95,944 | null | 1 | 32 | html|xhtml|overflow|css | 59,768 | <p>Try <code>overflow-x: auto;</code></p>
<p>It even works in IE6!</p> |
1,217,254 | Display a default DataTemplate in a ContentControl when its content is null or empty? | <p>I would think this is possible, but the obvious way isn't working. </p>
<p>Currently, I'm doing this:</p>
<pre><code><ContentControl
Content="{Binding HurfView.EditedPart}">
<ContentControl.Resources>
<Style
TargetType="ContentControl"
x:Key="emptytemplate">
<Style.Triggers>
<DataTrigger
Binding="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=Content}"
Value="{x:Null}">
<Setter
Property="ContentControl.Template">
<Setter.Value>
<ControlTemplate>
<Grid
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch">
<TextBlock>EMPTY!</TextBlock>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</ContentControl.Resources>
</ContentControl>
</code></pre>
<p>I'm not getting any binding errors and this compiles. However, it doesn't produce the expected result. I've also tried the obvious:</p>
<pre><code><DataTemplate DataType="{x:Null}"><TextBlock>Hurf</TextBlock></DataTemplate>
</code></pre>
<p>This won't compile. And attempting to set the content twice fails as well:</p>
<pre><code><ContentControl
Content="{Binding HurfView.EditedPart}">
<TextBlock>DEFAULT DISPLAY</TextBlock>
</ContentControl>
</code></pre>
<p>Can I do this without writing a custom template selector?</p> | 1,219,553 | 3 | 0 | null | 2009-08-01 19:08:45.16 UTC | 14 | 2016-12-23 08:52:25.633 UTC | null | null | null | user1228 | null | null | 1 | 46 | wpf|datatemplate|default-value|contentcontrol | 26,098 | <p>Simple, you have to bind the content property in the style. Styles won't overwrite a value on a control if there's a binding present, even if the value evaluates to Null. Try this.</p>
<pre><code><ContentControl>
<ContentControl.Style>
<Style TargetType="ContentControl">
<Setter Property="Content" Value="{Binding HurfView.EditedPart}" />
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=Content}" Value="{x:Null}">
<Setter Property="ContentControl.Template">
<Setter.Value>
<ControlTemplate>
<Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<TextBlock>EMPTY!</TextBlock>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</ContentControl.Style>
</ContentControl>
</code></pre> |
1,187,314 | How to write a Nginx module? | <p>I'm trying to find tutorials on how to build a module/plugin for Nginx web server.</p>
<p>Can someone help please, I just can't seem to find the appropriate tutorials.</p> | 21,499,329 | 3 | 0 | null | 2009-07-27 09:46:52.873 UTC | 31 | 2022-05-16 11:53:21.027 UTC | 2022-05-16 11:53:21.027 UTC | null | 7,121,513 | null | 63,898 | null | 1 | 50 | nginx|plugins|nginx-module | 41,066 | <p>Quoting from the documentation:</p>
<blockquote>
<p>Evan Miller has written the definitive <a href="http://www.evanmiller.org/nginx-modules-guide.html">guide to Nginx module development</a>.
But some parts of it are a little out of date. You've been warned.</p>
<p>A github search turned up the <a href="https://github.com/simpl/ngx_devel_kit">Nginx Development Kit</a>. It seems to be
more up to date.</p>
</blockquote>
<p>From my own personal experience, <a href="http://www.evanmiller.org/nginx-modules-guide.html">Evan Miller's guide</a> was of a great help. You must also have a deep understanding of how NGINX works. <a href="http://openresty.org/download/agentzh-nginx-tutorials-en.html">Agentzh's tutorial</a> can help you.</p>
<p>Reading the source code of <a href="https://github.com/agentzh">his modules</a> is always helpful too.</p>
<p>There is also a <a href="http://www.airpair.com/nginx/extending-nginx-tutorial">video tutorial</a> that I haven't check yet, but it seems nice.</p> |
769,843 | How do I use AND in a Django filter? | <p>How do I create an "AND" filter to retrieve objects in Django? e.g I would like to retrieve a row which has a combination of two words in a single field.</p>
<p>For example the following SQL query does exactly that when I run it on mysql database:</p>
<pre><code>select * from myapp_question
where ((question like '%software%') and (question like '%java%'))
</code></pre>
<p>How do you accomplish this in Django using filters?</p> | 769,849 | 3 | 0 | null | 2009-04-20 19:55:11.263 UTC | 21 | 2021-02-28 16:53:31.52 UTC | 2009-04-20 20:07:08.943 UTC | null | 33,226 | null | 26,143 | null | 1 | 84 | python|django | 90,699 | <p>(<strong>update</strong>: this answer will not work anymore and give the syntax error <code>keyword argument repeated</code>)</p>
<pre><code>mymodel.objects.filter(first_name__icontains="Foo", first_name__icontains="Bar")
</code></pre>
<p><strong>update</strong>: Long time since I wrote this answer and done some django, but I am sure to this days the best approach is to use the Q object method like David Berger shows here: <a href="http://stackoverflow.com/a/770078/63097">How do I use AND in a Django filter?</a></p> |
6,730,664 | Why doesn't C++ make the structure tighter? | <p>For example, I have a <code>class</code>,</p>
<pre>
class naive {
public:
char a;
long long b;
char c;
int d;
};
</pre>
<p>and according to my testing program, <code>a</code> to <code>d</code> are built one after another, like</p>
<pre>
a-------
bbbbbbbb
c---dddd
</pre>
<p><code>-</code> means unused.</p>
<p>Why does not C++ make it tighter, like</p>
<pre>
ac--dddd
bbbbbbbb
</pre> | 6,730,704 | 1 | 1 | null | 2011-07-18 09:05:03.54 UTC | 7 | 2013-05-30 14:50:18.613 UTC | 2011-07-18 16:12:33.577 UTC | null | 125,389 | null | 571,433 | null | 1 | 30 | c++|packing | 2,147 | <p>Class and struct members are required by the standard to be stored in memory in the same order in which they are declared. So in your example, it wouldn't be possible for <code>d</code> to appear before <code>b</code>.</p>
<p>Also, most architectures prefer that multi-byte types are aligned on 4- or 8-byte boundaries. So all the compiler can do is leave empty padding bytes between the class members. </p>
<p>You can minimize padding by reordering the members yourself, in increasing or decreasing size order. Or your compiler might have a <code>#pragma pack</code> option or something similar, which will seek to minimize padding at the possible expense of performance and code size. Read the docs for your compiler.</p> |
28,792,722 | OSX application without storyboard or xib files using Swift | <p>Unfortunately, I haven't found anything useful on the Internet - I wanted to know, what code I actually have to type for initializing an application without using storyboard or XIB files in Swift. I know I have to have a <code>.swift</code> file called <code>main</code>. But I don't know what to write in there (like do I need autoreleasepool or something like that?). For example, what would I do for initializing an <code>NSMenu</code> and how would I add a <code>NSViewController</code> to the active window (iOS's similar <code>.rootViewController</code> doesn't help). Thanks for any help ;)</p>
<p>Edit:
I actually don't want to use <code>@NSApplicationMain</code> in front of the <code>AppDelegate</code>. I'd rather know what exactly happens there and then do it myself.</p> | 28,793,059 | 4 | 1 | null | 2015-03-01 10:54:21.553 UTC | 24 | 2021-08-31 12:20:10.533 UTC | 2015-03-01 11:11:04.38 UTC | null | 2,846,416 | null | 2,846,416 | null | 1 | 32 | macos|cocoa|swift | 12,660 | <p>if you don't want to have the @NSApplicationMain attribute, do:</p>
<ol>
<li><p>have a file main.swift</p>
</li>
<li><p>add following top-level code:</p>
<pre><code> import Cocoa
let delegate = AppDelegate() //alloc main app's delegate class
NSApplication.shared.delegate = delegate //set as app's delegate
NSApplicationMain(CommandLine.argc, CommandLine.unsafeArgv) //start of run loop
// Old versions:
// NSApplicationMain(C_ARGC, C_ARGV)
// NSApplicationMain(Process.argc, Process.unsafeArgv);
</code></pre>
</li>
</ol>
<p>the rest should be inside your app delegate. e.g.:</p>
<pre><code>import Cocoa
class AppDelegate: NSObject, NSApplicationDelegate {
var newWindow: NSWindow?
var controller: ViewController?
func applicationDidFinishLaunching(aNotification: NSNotification) {
newWindow = NSWindow(contentRect: NSMakeRect(10, 10, 300, 300), styleMask: .resizable, backing: .buffered, defer: false)
controller = ViewController()
let content = newWindow!.contentView! as NSView
let view = controller!.view
content.addSubview(view)
newWindow!.makeKeyAndOrderFront(nil)
}
}
</code></pre>
<p>then you have a viewController</p>
<pre><code>import Cocoa
class ViewController : NSViewController {
override func loadView() {
let view = NSView(frame: NSMakeRect(0,0,100,100))
view.wantsLayer = true
view.layer?.borderWidth = 2
view.layer?.borderColor = NSColor.red.cgColor
self.view = view
}
}
</code></pre> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.