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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1,206,275 | Creating messages (ie drafts) in Gmail with IMAP/SMTP? | <p>I've done quite a bit of inbox manipulation with Gmail via IMAP functions in PHP, but one thing I haven't found is a way to create messages. I'm not sure if IMAP or SMTP is required, but I would like to use PHP to create a new message (specifically a draft) that is stored in my inbox with everything ready to hit send at a later date. How do I go about this?</p> | 1,206,465 | 1 | 0 | null | 2009-07-30 12:27:55.18 UTC | 11 | 2009-07-30 13:29:15.793 UTC | null | null | null | null | 143,455 | null | 1 | 12 | php|smtp|gmail|imap | 5,848 | <p>You might want to look at <a href="http://php.net/imap_mail_compose" rel="noreferrer"><code>imap_mail_compose()</code></a></p>
<p><strong>Edit</strong>
This doesn't create the message on the server. You need to use imap_append() also.</p>
<p><strong>Further Edit</strong>
This seems to work ok:</p>
<pre><code><?php
$rootMailBox = "{imap.gmail.com:993/imap/ssl}";
$draftsMailBox = $rootMailBox . '[Google Mail]/Drafts';
$conn = imap_open ($rootMailBox, "sdfsfd@gmail.com", "password") or die("can't connect: " . imap_last_error());
$envelope["to"] = "test@test.com";
$envelope["subject"] = "Test Draft";
$part["type"] = TYPETEXT;
$part["subtype"] = "plain";
$part["description"] = "part description";
$part["contents.data"] = "Testing Content";
$body[1] = $part;
$msg = imap_mail_compose($envelope, $body);
if (imap_append($conn, $draftsMailBox, $msg) === false) {
die( "could not append message: " . imap_last_error() ) ;
}
</code></pre> |
49,291,057 | Difference between flatMap and compactMap in Swift | <p>It seems like in <strong>Swift 4.1</strong> <code>flatMap</code> is deprecated. However there is a new method in <strong>Swift 4.1</strong> <code>compactMap</code> which is doing the same thing?
With <code>flatMap</code> you can transform each object in a collection, then remove any items that were nil.
<br>
<strong>Like flatMap</strong></p>
<pre><code>let array = ["1", "2", nil]
array.flatMap { $0 } // will return "1", "2"
</code></pre>
<p><strong>Like compactMap</strong>
<br></p>
<pre><code>let array = ["1", "2", nil]
array.compactMap { $0 } // will return "1", "2"
</code></pre>
<p><code>compactMap</code> is doing the same thing.</p>
<p>What are the differences between these 2 methods? Why did Apple decide to rename the method?</p> | 52,367,951 | 3 | 0 | null | 2018-03-15 03:21:25.783 UTC | 6 | 2022-08-24 18:31:03.9 UTC | 2018-08-29 18:23:51.733 UTC | null | 1,032,372 | null | 4,142,753 | null | 1 | 30 | swift|swift4|swift4.1 | 13,850 | <p>The Swift standard library defines 3 overloads for <code>flatMap</code> function:</p>
<pre><code>Sequence.flatMap<S>(_: (Element) -> S) -> [S.Element]
Optional.flatMap<U>(_: (Wrapped) -> U?) -> U?
Sequence.flatMap<U>(_: (Element) -> U?) -> [U]
</code></pre>
<p>The last overload function can be misused in two ways:<br />
Consider the following struct and array:</p>
<pre><code>struct Person {
var age: Int
var name: String
}
let people = [
Person(age: 21, name: "Osame"),
Person(age: 17, name: "Masoud"),
Person(age: 20, name: "Mehdi")
]
</code></pre>
<p><strong>First Way: Additional Wrapping and Unwrapping:</strong><br />
If you needed to get an array of ages of persons included in <code>people</code> array you could use two functions :</p>
<pre><code>let flatMappedAges = people.flatMap({$0.age}) // prints: [21, 17, 20]
let mappedAges = people.map({$0.age}) // prints: [21, 17, 20]
</code></pre>
<p>In this case the <code>map</code> function will do the job and there is no need to use <code>flatMap</code>, because both produce the same result. Besides, there is a useless wrapping and unwrapping process inside this use case of flatMap.(The closure parameter wraps its returned value with an Optional and the implementation of flatMap unwraps the Optional value before returning it)</p>
<p><strong>Second Way - String conformance to Collection Protocol:</strong><br />
Think you need to get a list of persons' name from <code>people</code> array. You could use the following line :</p>
<pre><code>let names = people.flatMap({$0.name})
</code></pre>
<p>If you were using a swift version prior to 4.0 you would get a transformed list of</p>
<pre><code>["Osame", "Masoud", "Mehdi"]
</code></pre>
<p>but in newer versions <code>String</code> conforms to <code>Collection</code> protocol, So, your usage of <code>flatMap()</code> would match the first overload function instead of the third one and would give you a flattened result of your transformed values:</p>
<pre><code>["O", "s", "a", "m", "e", "M", "a", "s", "o", "u", "d", "M", "e", "h", "d", "i"]
</code></pre>
<p><strong>Conclusion: They deprecated third overload of flatMap()</strong><br />
Because of these misuses, swift team has decided to deprecate the third overload to flatMap function. And their solution to the case where you need to to deal with <code>Optional</code>s so far was to introduce a new function called <code>compactMap()</code> which will give you the expected result.</p> |
32,602,644 | Difference between ASP.NET WebHooks and Signal-R | <p>What is the difference between the newly release <a href="http://blogs.msdn.com/b/webdev/archive/2015/09/15/sending-webhooks-with-asp-net-webhooks-preview.aspx">ASP.NET WebHooks</a> and Signal-R? What are the advantages or disadvantages? What are the use cases for each technology?</p> | 32,621,664 | 2 | 0 | null | 2015-09-16 07:46:54.453 UTC | 16 | 2016-02-28 20:57:04.783 UTC | 2016-02-28 20:57:04.783 UTC | null | 1,215,507 | null | 1,212,017 | null | 1 | 57 | asp.net|signalr|webhooks|asp.net-webhooks | 13,880 | <p>SignalR is for notification within an ASP.NET app using <strong>WebSockets</strong>. You can exchange event notifications through WebSockets, however it requires a constant network connection. </p>
<p><strong>WebHooks</strong> are for event notification across other web applications and other external services. (Think B2B communication). For instance, you can receive a WebHook when someone sends you money to your PayPal account. PayPal fires off a POST request to your predefined URL handler and then your app does something with that notification. You pre-configure everything on the PayPal side first. You also set up an application to handle the incoming POST request. The event notification is "pushed" to you in (near) real-time. No need to hold open a network connection while waiting for events. </p>
<p>The two can be complementary. For example, when you receive the WebHook from PayPal, you can notify a logged in user on your webapp (using SignalR/WebSockets) that money has been received successfully. </p>
<p>TLDR: Event notification across different web applications</p> |
33,186,123 | npm install errors on vagrant/homestead/windows: EPROTO: protocol error, symlink | <p>I'm building my first project in Laravel and trying to use Elixir, using homestead on Windows 8.1. I've hit the known npm/vagrant issue of too-long-path-names:
<a href="https://harvsworld.com/2015/how-to-fix-npm-install-errors-on-vagrant-on-windows-because-the-paths-are-too-long/" rel="noreferrer">https://harvsworld.com/2015/how-to-fix-npm-install-errors-on-vagrant-on-windows-because-the-paths-are-too-long/</a></p>
<p>So I made the one line edit recommended in that article (thank god for that guy), and then ran (with and without sudo):
npm install --no-bin-links</p>
<p>It's moved me ahead so now I get two different kinds of errors: some 'Missing write access' errors, and a bunch of "EACCES" errors:</p>
<p>The error output gives me my next clue in the scavenger hunt (I think):
Please try running this command again as root/Administrator</p>
<p>That brings me to <a href="https://stackoverflow.com/questions/16151018/npm-throws-error-without-sudo">this post</a>, but the difference for me is there's no change even after I use sudo (or update my user permissions like so):</p>
<p>sudo chown -R $USER /usr/local</p>
<p>sudo chown -R $(whoami) ~/.npm</p>
<p><strong>Update: then after the suggestion below</strong> I get EPROTO and EXTXTBSY errors (even after following the prompted suggestion to rename the npm-debug.log back:
<a href="https://i.stack.imgur.com/X9Yv2.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/X9Yv2.jpg" alt="enter image description here" /></a></p>
<p>So I tried running gulp to see if it would give me clues, and error output had me do:</p>
<pre><code>sudo npm rebuild node-sass
</code></pre>
<p>Running that gives me the same EPROTO and ETXTBSY errors, and the npm-debug.log file shows:
error EPROTO: protocol error, symlink '../node-sass/bin/node-sass' -> '/home/vagrant/Code/Family-laravel/node_modules/laravel-elixir/node_modules/gulp-sass/node_modules/.bin/node-sass'</p>
<p>Then after working on some other stuff for an hour I came back fresh and redid these steps, this time getting way fewer errors:</p>
<ul>
<li><p>sudo npm -g install npm@latest (fine)</p>
</li>
<li><p>sudo npm install --no-bin-links (just the ETXTBSY error and an error in plugin 'run sequence', in task 'sass')</p>
</li>
<li><p>sudo npm rebuild node-sass --no-bin-links (no errors!)</p>
</li>
<li><p>gulp (just one error: not found: notify-send)</p>
</li>
</ul>
<p>Getting closer!</p> | 33,188,475 | 6 | 0 | null | 2015-10-17 11:32:43.647 UTC | 13 | 2020-09-02 23:02:01.243 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 4,418,293 | null | 1 | 25 | laravel|npm|symlink|homestead | 20,826 | <p>I have been trying to figure out this problem for weeks. Here is what I did to make it work without using my host environment:</p>
<p>I updated node to the latest version in homestead according to nodesource.com:</p>
<pre><code>sudo apt-get install --yes nodejs
curl --silent --location https://deb.nodesource.com/setup_4.x | sudo bash -
</code></pre>
<p>I updated npm to the latest version in homestead. This should be done after updating node:</p>
<pre><code>sudo npm -g install npm@latest
</code></pre>
<p>I ran npm install in the laravel project directory. I also had to use force to get all of the dependencies to install:</p>
<pre><code>sudo npm install --no-bin-links
sudo npm cache clear
sudo npm install --force --no-bin-links
</code></pre>
<p>I rebuilt node-sass according to a gulp error:</p>
<pre><code>sudo npm rebuild node-sass --no-bin-links
</code></pre>
<p>During this whole process if something fails or after each install, i used:</p>
<pre><code>sudo npm cache clear
</code></pre>
<p>My host is windows 10, with latest virtualbox, latest vagrant, latest homestead. I used git bash as administrator and ssh into vagrant using git bash.</p>
<p>So far I have only tested and confirmed that my gulp works. It is possible that other dependencies need to be rebuilt.</p>
<p>Hope this helps!</p> |
41,239,781 | Conversion failed when converting the varchar value to data type int - but I'm not converting anything | <p>I am trying to write a stored procedure that takes two parameters: table name and record ID. </p>
<p>It must return a record with a specified ID (<code>@FormID</code>) from the table with the specified name (<code>@TableName</code>). </p>
<p>I get this error: </p>
<blockquote>
<p>Conversion failed when converting the varchar value 'SELECT * FROM [Form12_AuditLog] WHERE [FormID] = ' to data type int."</p>
</blockquote>
<p>I can't really understand the issue because I'm not trying to convert anything to data type int.</p>
<p>The parameters passed to the SQL are: </p>
<pre><code>@FormID = 88
@TableName = Form12_AuditLog
</code></pre>
<p>SQL:</p>
<pre><code>USE [MyDatabase]
GO
/****** Object: StoredProcedure [dbo].[GetAuditLogByFormID] Script Date: 20/12/2016 5:50:53 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[GetAuditLogByFormID]
@TableName varchar(50),
@FormID integer
AS
BEGIN
SET NOCOUNT ON;
DECLARE @ActualTableName AS varchar(255)
SELECT @ActualTableName = QUOTENAME( TABLE_NAME )
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = @TableName
DECLARE @sql AS NVARCHAR(MAX)
SELECT @sql = 'SELECT * FROM ' + @ActualTableName + ' WHERE [FormID] = ' + @FormID + ';'
EXEC(@sql)
END
</code></pre> | 41,239,853 | 3 | 0 | null | 2016-12-20 10:11:53.34 UTC | null | 2016-12-20 10:45:42.21 UTC | null | null | null | user6269864 | null | null | 1 | 6 | sql|sql-server | 51,006 | <p>Try:</p>
<pre><code>SELECT @sql = 'SELECT * FROM ' + @ActualTableName + ' WHERE [FormID] = ' + CONVERT(NVARCHAR,@FormID) + ';'
</code></pre>
<p>SQL is trying to convert all of the strings you're attempting to concatenate into <code>INT</code> values because <code>@FormID</code> is an <code>INT</code> and you're using the <code>+</code> operator - this is quite common when concatenating values which are a mixture of string and non-string types. You therefore need to explicitly tell SQL that the <code>INT</code> value should be treated as a string-type value for the purposes of the concatenation.</p> |
41,623,515 | Received "ValueError: Found wrong number (0) of constraints for ..." during Django migration | <p>While using Django 1.7 migrations, I came across a migration that worked in development, but not in production:</p>
<p><code>ValueError: Found wrong number (0) of constraints for table_name(a, b, c, d)</code></p>
<p>This is caused by an <code>AlterUniqueTogether</code> rule:</p>
<pre><code> migrations.AlterUniqueTogether(
name='table_name',
unique_together=set([('a', 'b')]),
)
</code></pre>
<p>Reading up on bugs and such in the Django bug DB it seems to be about the existing <code>unique_together</code> in the db not matching the migration history. </p>
<p>How can I work around this error and finish my migrations?</p> | 41,623,516 | 9 | 0 | null | 2017-01-12 21:44:04.693 UTC | 2 | 2022-09-22 06:13:12.007 UTC | 2017-01-12 22:12:20.847 UTC | null | 2,077,386 | null | 2,077,386 | null | 1 | 35 | django|django-migrations | 18,765 | <p>(Postgres and MySQL Answer)</p>
<p>If you look at your actual table (use <code>\d table_name</code>) and look at the indexes, you'll find an entry for your unique constraint. This is what Django is trying to find and drop. But it can't find an exact match.</p>
<p>For example,</p>
<pre><code>"table_name_...6cf2a9c6e98cbd0d_uniq" UNIQUE CONSTRAINT, btree (d, a, b, c)
</code></pre>
<p>In my case, the order of the keys <code>(d, a, b, c)</code> did not match the constraint it was looking to drop <code>(a, b, c, d)</code>.</p>
<p>I went back into my migration history and changed the original <code>AlterUniqueTogether</code> to match the <em>actual</em> order in the database.</p>
<p>The migration then completed successfully.</p> |
33,789,586 | Disable Prev Control on first slide and disable Next control on last slide | <p>using Slick and looking for a way to have the prev control disabled and hidden until the user clicks the next arrow. Similarly I want the Next control to become disabled and hidden once the user reaches the last slide. </p>
<p>A good illustration of what I'm trying to accomplish is <a href="http://www.asla.org/sustainablelandscapes/index.html" rel="noreferrer">here</a></p>
<p>Does slick have an attribute already for this that I have overlooked? Is this something that maybe can be accomplished using CSS by adding a disabled class?</p>
<p>The only thing similar I have found is this </p>
<pre><code>$('.pages .slider').slick({
autoplay: true,
autoplaySpeed: 5000,
infinite: false,
onAfterChange: function(slide, index) {
if(index == 4){
$('.pages .slider').slickPause();
</code></pre>
<p>But its not exactly what I am looking for.</p> | 33,790,040 | 9 | 0 | null | 2015-11-18 20:19:15.103 UTC | 5 | 2020-10-09 08:25:16.747 UTC | 2015-11-18 20:21:36.203 UTC | null | 887,539 | null | 2,938,557 | null | 1 | 16 | javascript|jquery|slick.js | 53,454 | <h3>Solution</h3>
<p>You can add the css <code>pointer-events: none</code> to your button. That css property disable all event on an element. So something like that.</p>
<pre><code>// Slick stuff
...
onAfterChange: function(slide, index) {
if(index === 4) {
$('.slick-next').css('pointer-events', 'none')
}
else {
$('.slick-next').css('pointer-events', 'all')
}
}
</code></pre>
<p>And something on the same guideline for <code>.slick-prev</code> element.</p>
<p>In that solution you should get the <em>function out of the config</em> and only put a reference to it with something like this.</p>
<pre><code>// Inside slick config
onAfterChange: afterChange
// Below somewhere
var afterChange = function(slide, index) { //stuff here }
</code></pre>
<p>Also check to see if there is a way to get the length of the slider and verify it instead of hardcoding <code>4</code> in the <code>if</code> statement. You can probably do something like <code>$('.slide').length</code></p>
<hr />
<h3>Edit</h3>
<p>Here's how to implement the <code>afterChange()</code> function.</p>
<pre><code>$(document).ready(function(){
$('.scrollable').slick({
dots: false,
slidesToShow: 1,
slidesToScroll: 3,
swipeToSlide: true,
swipe: true,
arrows: true,
infinite: false,
});
$('.scrollable').on('afterChange', function (event, slick, currentSlide) {
if(currentSlide === 2) {
$('.slick-next').addClass('hidden');
}
else {
$('.slick-next').removeClass('hidden');
}
if(currentSlide === 0) {
$('.slick-prev').addClass('hidden');
}
else {
$('.slick-prev').removeClass('hidden');
}
})
});
</code></pre>
<p>And some CSS, If you wanna do animation you should do it here.</p>
<pre><code>.slick-prev.hidden,
.slick-next.hidden {
opacity: 0;
pointer-events:none;
}
</code></pre> |
23,235,200 | How to matches anything except space and new line? | <p>I have a string, I just want to match string for any character except for space and new line. What must be regular expression for this?</p>
<p>I know regular expressions for anything but space i.e. <code>[^ ]+</code> and regular expression for anything but new line <code>[^\n]+</code> (I'm on Windows). I am not able to figure how to club them together.</p> | 23,235,232 | 3 | 0 | null | 2014-04-23 05:08:10.617 UTC | 3 | 2021-06-05 04:48:56.167 UTC | 2014-04-23 05:26:50.31 UTC | null | 1,673,391 | null | 1,643,128 | null | 1 | 28 | python|regex | 41,022 | <p>You can add the space character to your character class to be excluded.</p>
<pre><code>^[^\n ]*$
</code></pre>
<p>Regular expression</p>
<pre><code>^ # the beginning of the string
[^\n ]* # any character except: '\n' (newline), ' ' (0 or more times)
$ # before an optional \n, and the end of the string
</code></pre> |
21,475,828 | Creating WSDL file for SOAP server | <p>I am new to the whole web service thing so I will try to explain my problem as much as I can understand it so far. </p>
<p>I created Soap server in PHP:</p>
<pre><code>try {
$server = new SOAPServer(
'webservice.wsdl',
array(
'uri' => 'http://example.com/soap/server.php'
)
);
$server->setClass('soap');
$server->handle();
} catch (SOAPFault $f) {
print $f->faultstring;
}
</code></pre>
<p>Then I have a Soap class for the server:</p>
<pre><code>class soap
{
public function sendOrders($sXml)
{
$oXml = new SimpleXMLElement($sXml);
$sOrder = $oXml->children();
$sResult = '';
foreach ($sOrder as $OrderRow) {
$sOrderNr = $OrderRow->ORDERNR;
$sState = $OrderRow->STATE;
$sTimestamp = $OrdeRow->TIMESTAMP;
$oOrder = new Order;
$oOrder->load($sOrderNr);
if ($sState == 1) {
$oOrder->checkStatusChange('Approved', $oOrder);
$oOrder->{$oOrder->getCoreTableName() . '__status'} = new Field('Approved');
$sResult .= $sOrderNr . " 1 | ";
} elseif ($sState == 0) {
$oOrder->checkStatusChange('Declined', $oOrder);
$oOrder->{$oOrder->getCoreTableName() . '__status'} = new Field('Declined');
$sResult .= $sOrderNr . " 0 | ";
}
$oOrder->save();
}
return $sResult;
}
}
</code></pre>
<p>I have a test client that sends simple XML with this format:</p>
<pre><code><xml>
<ORDER>
<ORDERNR>9nmf997d997701e15e30edac107b3664</ORDERNR>
<STATE>1</STATE>
<TIMESTAMP>123456789</TIMESTAMP>
</ORDER>
<ORDER>
<ORDERNR>9nmb1c3d4dfb067c04497ea51bd50d06</ORDERNR>
<STATE>0</STATE>
<TIMESTAMP>987654321</TIMESTAMP>
</ORDER>
</xml>
</code></pre>
<p>Now, what I need to do is create simple WSDL file for "description" of the service. I must say I have a little knowledge about this whole Web Service area so I would be grateful for any help.</p>
<p>I am familiar with W3C documentation <a href="http://www.w3schools.com/webservices/ws_wsdl_documents.asp" rel="noreferrer">http://www.w3schools.com/webservices/ws_wsdl_documents.asp</a></p>
<p>Thank you in advance.</p>
<p><strong>Update:</strong> I tried to seach for some WSDL generators, none seem to be working.</p> | 21,547,188 | 1 | 0 | null | 2014-01-31 08:55:30.487 UTC | 1 | 2016-08-01 14:27:51.693 UTC | 2016-08-01 14:27:51.693 UTC | null | 4,662,836 | null | 2,111,274 | null | 1 | 11 | php|web-services|soap|wsdl | 42,496 | <p><strong>Solved</strong></p>
<p>A simple library called PhpWsdl did the trick.</p>
<p><a href="https://code.google.com/p/php-wsdl-creator/" rel="noreferrer">https://code.google.com/p/php-wsdl-creator/</a></p> |
19,100,536 | What is the use of __iomem in linux while writing device drivers? | <p>I have seen that <code>__iomem</code> is used to store the return type of <code>ioremap()</code>, but I have used <code>u32</code> in ARM architecture for it and it works well.</p>
<p>So what difference does <code>__iomem</code> make here? And in which circumstances should I use it exactly?</p> | 19,102,506 | 1 | 0 | null | 2013-09-30 17:46:54.707 UTC | 11 | 2018-11-21 15:38:28.87 UTC | 2015-03-08 04:14:07.003 UTC | null | 610,505 | null | 2,711,374 | null | 1 | 27 | linux|memory-management|linux-kernel|linux-device-driver | 22,345 | <p>Lots of type casts are going to just "work well". However, this is not very strict. Nothing stops you from casting a <code>u32</code> to a <code>u32 *</code> and dereference it, but this is not following the kernel API and is prone to errors.</p>
<p><code>__iomem</code> is a cookie used by <a href="http://en.wikipedia.org/wiki/Sparse" rel="noreferrer">Sparse</a>, a tool used to find possible coding faults in the kernel. If you don't compile your kernel code with Sparse enabled, <code>__iomem</code> will be ignored anyway.</p>
<p>Use Sparse by first installing it, and then adding <code>C=1</code> to your <code>make</code> call. For example, when building a module, use:</p>
<pre><code>make -C $KPATH M=$PWD C=1 modules
</code></pre>
<hr>
<p><code>__iomem</code> is defined like this:</p>
<pre class="lang-c prettyprint-override"><code># define __iomem __attribute__((noderef, address_space(2)))
</code></pre>
<p>Adding (and requiring) a cookie like <code>__iomem</code> for all I/O accesses is a way to be stricter and avoid programming errors. You don't want to read/write from/to I/O memory regions with absolute addresses because you're usually using virtual memory. Thus,</p>
<pre class="lang-c prettyprint-override"><code>void __iomem *ioremap(phys_addr_t offset, unsigned long size);
</code></pre>
<p>is usually called to get the virtual address of an I/O physical address <code>offset</code>, for a specified length <code>size</code> in bytes. <code>ioremap()</code> returns a pointer with an <code>__iomem</code> cookie, so this <em>may now</em> be used with inline functions like <code>readl()</code>/<code>writel()</code> (although it's now preferable to use the more explicit macros <code>ioread32()</code>/<code>iowrite32()</code>, for example), which accept <code>__iomem</code> addresses.</p>
<p>Also, the <code>noderef</code> attribute is used by Sparse to make sure you don't dereference an <code>__iomem</code> pointer. Dereferencing should work on some architecture where the I/O is really memory-mapped, but other architectures use special instructions for accessing I/Os and in this case, dereferencing won't work.</p>
<p>Let's look at an example:</p>
<pre class="lang-c prettyprint-override"><code>void *io = ioremap(42, 4);
</code></pre>
<p>Sparse is not happy:</p>
<pre><code>warning: incorrect type in initializer (different address spaces)
expected void *io
got void [noderef] <asn:2>*
</code></pre>
<p>Or:</p>
<pre class="lang-c prettyprint-override"><code>u32 __iomem* io = ioremap(42, 4);
pr_info("%x\n", *io);
</code></pre>
<p>Sparse is not happy either:</p>
<pre><code>warning: dereference of noderef expression
</code></pre>
<p>In the last example, the first line is correct, because <code>ioremap()</code> returns its value to an <code>__iomem</code> variable. But then, we deference it, and we're not supposed to.</p>
<p>This makes Sparse happy:</p>
<pre class="lang-c prettyprint-override"><code>void __iomem* io = ioremap(42, 4);
pr_info("%x\n", ioread32(io));
</code></pre>
<p>Bottom line: always use <code>__iomem</code> where it's required (as a return type or as a parameter type), and use Sparse to make sure you did so. Also: do not dereference an <code>__iomem</code> pointer.</p>
<p><strong>Edit</strong>: Here's a great <a href="http://lwn.net/Articles/102232/" rel="noreferrer">LWN article</a> about the inception of <code>__iomem</code> and functions using it.</p> |
18,160,953 | Disable latex symbol conversion in vim | <p>The vim editor on my Kubuntu 13.04 laptop seems to have some
advance feature for latex edting, i.e. it can convert latex
symbols to unicode chars on the fly and hide the source code when the cursor
is not on the line.</p>
<p>This may be a great function to some people, but I find it
a bit annoying. I am not sure whether this is built-in or provided by
some extension, but I hope I can find out a way to disable it.</p>
<p>My vim version is 7.4b, the list of extensions installed:</p>
<pre><code>clang_complete
emmet-vim
HTML-AutoCloseTag
neocomplete.vim
neosnippet
tabular
tagbar
tlib_vim
unite.vim
vim-addon-mw-utils
vim-airline
vim-colorschemes
vim-colors-solarized
vim-commentary
vim-easymotion
vim-eunuch
vim-fugitive
vim-repeat
VimRepress
Vim-R-plugin
vim-snippets
vim-surround
vim-table-mode
vim-unimpaired
vundle
</code></pre>
<p><img src="https://i.stack.imgur.com/azDLb.png" alt="cursor not on math line">
<img src="https://i.stack.imgur.com/3FTKC.png" alt="cursor on math line"></p> | 18,161,073 | 1 | 0 | null | 2013-08-10 10:20:04.397 UTC | 8 | 2013-08-10 10:40:25.257 UTC | null | null | null | null | 562,222 | null | 1 | 22 | vim|latex | 6,187 | <p>This functionality is provided by Vim's "conceal" feature.</p>
<p>Vim's TeX plugin takes advantage of "conceal" if you have set <a href="http://vimdoc.sourceforge.net/htmldoc/options.html#%27conceallevel%27"><code>'conceallevel'</code></a> to 2. See <a href="http://vimdoc.sourceforge.net/htmldoc/syntax.html#ft-tex-syntax"><code>:h ft-tex-syntax</code></a>.</p>
<p>Leave <code>'conceallevel'</code> at its default value of 0 to disable concealing.</p>
<p>Alternatively, put the following line in your vimrc.</p>
<pre><code>let g:tex_conceal = ""
</code></pre> |
26,536,572 | NSTextField, Change text in Swift | <p>I can't seem to be able to change the text Label in a Mac app that I am trying to make.
I am using swift. Here is the code I am using:</p>
<pre><code>@IBOutlet var sumlab: NSTextField!
sumlab.text = "\(result.sum)" // result.sum is the result of a function I made
// I also tried this:
sumlab.text("\(result.sum)")
// and this:
sumlab.insertText("\(result.sum)")
</code></pre>
<p>None of these seem to work and this is the only problem I need to solve to finish my program.
P.S. when i write sumlab.text it says NSTextField does not have a member named text</p> | 26,537,804 | 1 | 0 | null | 2014-10-23 20:11:55.85 UTC | 11 | 2015-01-05 20:38:18.58 UTC | 2015-01-05 20:38:18.58 UTC | null | 8,047 | null | 4,175,399 | null | 1 | 32 | swift|nstextfield | 24,835 | <p>NSTextField is different from a UITextField. It doesn't have a <code>text</code> property. It does however inherit from NSControl which has a stringValue property.</p>
<pre><code>sumlab.stringValue = "\(result.sum)"
</code></pre> |
42,876,278 | When to use multiindexing vs. xarray in pandas | <p>The <a href="http://pandas.pydata.org/pandas-docs/stable/reshaping.html" rel="noreferrer">pandas pivot tables documentation</a> seems to recomend dealing with more than two dimensions of data by using multiindexing: </p>
<pre><code>In [1]: import pandas as pd
In [2]: import numpy as np
In [3]: import pandas.util.testing as tm; tm.N = 3
In [4]: def unpivot(frame):
...: N, K = frame.shape
...: data = {'value' : frame.values.ravel('F'),
...: 'variable' : np.asarray(frame.columns).repeat(N),
...: 'date' : np.tile(np.asarray(frame.index), K)}
...: return pd.DataFrame(data, columns=['date', 'variable', 'value'])
...:
In [5]: df = unpivot(tm.makeTimeDataFrame())
In [6]: df
Out[6]:
date variable value value2
0 2000-01-03 A 0.462461 0.924921
1 2000-01-04 A -0.517911 -1.035823
2 2000-01-05 A 0.831014 1.662027
3 2000-01-03 B -0.492679 -0.985358
4 2000-01-04 B -1.234068 -2.468135
5 2000-01-05 B 1.725218 3.450437
6 2000-01-03 C 0.453859 0.907718
7 2000-01-04 C -0.763706 -1.527412
8 2000-01-05 C 0.839706 1.679413
9 2000-01-03 D -0.048108 -0.096216
10 2000-01-04 D 0.184461 0.368922
11 2000-01-05 D -0.349496 -0.698993
In [7]: df['value2'] = df['value'] * 2
In [8]: df.pivot('date', 'variable')
Out[8]:
value value2 \
variable A B C D A B
date
2000-01-03 -1.558856 -1.144732 -0.234630 -1.252482 -3.117712 -2.289463
2000-01-04 -1.351152 -0.173595 0.470253 -1.181006 -2.702304 -0.347191
2000-01-05 0.151067 -0.402517 -2.625085 1.275430 0.302135 -0.805035
variable C D
date
2000-01-03 -0.469259 -2.504964
2000-01-04 0.940506 -2.362012
2000-01-05 -5.250171 2.550861
</code></pre>
<p>I thought that xarray was made for handling multidimensional datasets like this:</p>
<pre><code>In [9]: import xarray as xr
In [10]: xr.DataArray(dict([(var, df[df.variable==var].drop('variable', 1)) for var in np.unique(df.variable)]))
Out[10]:
<xarray.DataArray ()>
array({'A': date value value2
0 2000-01-03 0.462461 0.924921
1 2000-01-04 -0.517911 -1.035823
2 2000-01-05 0.831014 1.662027, 'C': date value value2
6 2000-01-03 0.453859 0.907718
7 2000-01-04 -0.763706 -1.527412
8 2000-01-05 0.839706 1.679413, 'B': date value value2
3 2000-01-03 -0.492679 -0.985358
4 2000-01-04 -1.234068 -2.468135
5 2000-01-05 1.725218 3.450437, 'D': date value value2
9 2000-01-03 -0.048108 -0.096216
10 2000-01-04 0.184461 0.368922
11 2000-01-05 -0.349496 -0.698993}, dtype=object)
</code></pre>
<p>Is one of these approaches better than the other? Why hasn't xarray completely replaced multiindexing?</p> | 45,172,361 | 1 | 0 | null | 2017-03-18 15:35:03.623 UTC | 11 | 2020-07-08 17:09:29.773 UTC | null | null | null | null | 3,474,956 | null | 1 | 22 | python|pandas|data-structures|multi-index|xarray | 6,024 | <p>There does seem to be a transition to xarray for doing work on multi-dimensional arrays. Pandas will be depreciating the support for the 3D Panels data structure and in the <a href="https://pandas.pydata.org/pandas-docs/stable/dsintro.html#deprecate-panel" rel="noreferrer">documentation even suggest using xarray for working with multidemensional arrays</a>:</p>
<blockquote>
<p>'Oftentimes, one can simply use a MultiIndex DataFrame for easily
working with higher dimensional data.</p>
<p>In addition, the xarray package was built from the ground up,
specifically in order to support the multi-dimensional analysis that
is one of Panel s main use cases. Here is a link to the xarray
panel-transition documentation.'</p>
</blockquote>
<p>From the <a href="http://xarray.pydata.org/en/stable/why-xarray.html" rel="noreferrer">xarray documentation</a> they state their aims and goals:</p>
<blockquote>
<p>xarray aims to provide a data analysis toolkit as powerful as pandas
but designed for working with homogeneous N-dimensional arrays instead
of tabular data...</p>
<p>...Our target audience is anyone who needs N-dimensional labelled
arrays, but we are particularly focused on the data analysis needs of
physical scientists – especially geoscientists who already know and
love netCDF</p>
</blockquote>
<p>The main advantage of xarray over using straight numpy is that it makes use of labels in the same way pandas does over multiple dimensions.
If you are working with 3-dimensional data using multi-indexing or xarray might be interchangeable. As the number of dimensions grows in your data set xarray becomes much more manageable.
I cannot comment on how each performs in terms of efficiency or speed. </p> |
44,934,641 | GLib-GIO-Message: Using the 'memory' GSettings backend. Your settings will not be saved or shared with other applications | <p>I am working on python project with opencv on Ubuntu OS</p>
<pre><code>import numpy as np
import cv2
img = cv2.imread("LillyBellea.png", 1)
img = cv2.imwrite("LillyBellea.jpeg", img)
cv2.imshow("original", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
</code></pre>
<p>when i am running this program then i am getting error</p>
<pre><code>GLib-GIO-Message: Using the 'memory' GSettings backend. Your settings will not be saved or shared with other applications.
</code></pre>
<p>can any one please help here,
I have follow <a href="https://askubuntu.com/questions/558446/my-dconf-gsettings-installation-is-broken-how-can-i-fix-it-without-ubuntu-reins">this</a> answer but its not working for me</p> | 45,223,897 | 2 | 0 | null | 2017-07-05 19:38:01.027 UTC | 10 | 2020-11-06 11:16:04.147 UTC | 2017-07-06 05:48:07.333 UTC | null | 4,884,334 | null | 4,884,334 | null | 1 | 23 | python|linux|opencv|ubuntu | 22,442 | <p>This fixed the issue for me:</p>
<pre><code>export GIO_EXTRA_MODULES=/usr/lib/x86_64-linux-gnu/gio/modules/
</code></pre>
<p>See: <a href="https://github.com/conda-forge/glib-feedstock/issues/19" rel="noreferrer">https://github.com/conda-forge/glib-feedstock/issues/19</a> for more info.</p> |
27,423,485 | Java check if Checkbox is checked | <p>I use:</p>
<pre><code> CheckboxGroup cg = new CheckboxGroup();
Checkbox c1 = new Checkbox("A", false, cg);
Checkbox c2 = new Checkbox("B", false, cg);
Checkbox c3 = new Checkbox("C", true, cg);
</code></pre>
<p>To create a group of three checkboxes. Now, I want to check which one of them is checked. I use:</p>
<pre><code>if (c1.isSelected()) { }
</code></pre>
<p>but this gives <code>The method isSelected() is undefined for the type Checkbox</code>... Recommended solution is add cast to c1, I do so and it gives <code>Cannot cast from Checkbox to AbstractButton</code>... Again, how can I just check if a Checkbox if checked?</p> | 27,423,526 | 6 | 2 | null | 2014-12-11 12:58:16.877 UTC | 1 | 2019-12-29 04:56:07.507 UTC | 2014-12-11 14:41:15.663 UTC | user3265784 | null | user3265784 | null | null | 1 | 8 | java|checkbox|awt | 84,065 | <p>Use getState()</p>
<pre><code>boolean checked = c1.getState();
if(c1.getState()) {
//c1 is checked
} else if (c2.getState()) {
//
}
</code></pre>
<p><strong>OR</strong></p>
<pre><code>Checkbox cb = cg.getSelectedCheckbox();
if(null != cb) {
//not checked
} else {
System.out.println(cb.getLabel() + " is checked");
}
</code></pre> |
44,612,400 | How to pass the index value of a ngFor loop into the component? | <p>I have a ngFor loop in my code.
and inside this ngFor loop I have a div, on clicking this div I want to pass the index value to the type script file.</p>
<p>I am new to Anglular 2 any help will be appreciated.</p>
<p>Eg:</p>
<pre><code>`<div *ngFor="let y of characters;let i = index">
<div (click)="passIndexValue()">
</div>
<div>`
</code></pre> | 44,612,438 | 1 | 1 | null | 2017-06-18 06:38:36.573 UTC | 5 | 2019-03-27 21:33:15.093 UTC | null | null | null | null | 8,178,094 | null | 1 | 9 | angular|typescript|angular2-services | 43,892 | <pre><code><div *ngFor="let y of characters;let i = index">
<div (click)="passIndexValue(i)">
</div>
<div>`
passIndexValue(index){
console.log(index);//clicked index
}
</code></pre>
<p>You could also pass the value to the component like so (assuming below use of @Input)</p>
<pre><code><div *ngFor="let y of characters;let i = index">
<childComponent [index]="i">
</childComponent>
<div>`
</code></pre>
<p>And then pick up the value on the component object:</p>
<pre><code>@Input() index: number;
</code></pre>
<p>And use it directly in the template of the child component like so:</p>
<pre><code><div id="mydivinstance_{{index}}"></div>
</code></pre>
<p>Thereby allowing a component to have a unique ID based on the *ngFor loop.</p> |
9,129,214 | CakePHP 2.0 with Twitter Bootstrap | <p>Is there a way to configure CakePHP for it to work well with Twitter Bootstrap?
I realize this question has already been asked <a href="https://stackoverflow.com/questions/8049715/cakephp-with-bootstrap-from-twitter">here</a>, but the answer wasn't really complete.</p>
<p>There are also quite a few tutorials out there, but they are all either outdated or just not working, example: <a href="http://stenbom.me/?p=9" rel="nofollow noreferrer">Build a PHP application using CakePHP and (twitter) Bootstrap, Part 1</a>.</p>
<p>Thanks!</p> | 9,507,651 | 11 | 0 | null | 2012-02-03 13:14:16.087 UTC | 12 | 2014-07-11 06:19:47.34 UTC | 2017-05-23 12:34:01.78 UTC | null | -1 | null | 988,302 | null | 1 | 23 | cakephp|cakephp-2.0|twitter-bootstrap | 22,595 | <p>Assuming that the css file is included in your layout in your view for forms you can use the follwoing:</p>
<pre><code><?php echo $this->Form->create('User', array(
'inputDefaults' => array(
'div' => 'control-group',
'label' => array('class' => 'control-label'),
'between' => '<div class="controls">',
'after' => '</div>',
'class' => 'span3',
'error' => array('attributes' => array('wrap' => 'div', 'class' => 'alert alert-error'))
) ));
echo $this->Form->input('password',array(
'after' => '<span class = \'help-inline\'>Minimum of 5 characters.</span></div>'));
?>
</code></pre>
<p>I found this method to work perfectly with cake2.0 and bootstrap 2.0</p>
<p>This will produce the following</p>
<pre><code><div class="control-group required error">
<label for="UserPassword">Password</label>
<div class="controls">
<input name="data[User][password]" class="span3 form-error" type="password" value="" id="UserPassword">
<span class="help-inline">Minimum of 5 characters.</span></div>
<div class="alert alert-error">You must provide a password.</div>
</div>
</code></pre>
<p>The html above is after the form has been submitted and an error has been returned.</p> |
9,243,816 | How to build Google's protobuf in Windows using MinGW? | <p>I'm using Codeblocks as my IDE with MingGW.
I'm trying to use google protocol buffers,
but I'm having trouble building the protobuf.</p>
<p>The readme file for protobuf says:</p>
<blockquote>
<p>If you are using Cygwin or MinGW,
follow the Unix installation instructions, above.</p>
</blockquote>
<p>The Unix instructions says:</p>
<blockquote>
<p>To build and install the C++ Protocol Buffer runtime and the Protocol
Buffer compiler (protoc) execute the following:<code>
$ ./configure
$ make
$ make check
$ make install</code></p>
</blockquote>
<p>I don't know how to perform these in Windows
because "configure" is a Unix script and
I don't know how to execute it, or the rest of the commands.</p>
<p>Can someone explain in more detail how
I can build protobuf using MinGW on Windows?</p> | 9,244,456 | 4 | 0 | null | 2012-02-11 20:33:00.75 UTC | 9 | 2022-08-09 06:30:19.803 UTC | 2015-09-14 06:45:59.16 UTC | null | 506,624 | null | 1,162,522 | null | 1 | 23 | c++|mingw|protocol-buffers | 23,741 | <p>Here's what worked for me:</p>
<ol>
<li><p>You need to install MSYS with mingw. This is a minimal unix-like shell environment that lets you configure/make most unix packages. Read the mingw docs on how to install that (either with mingw-get or the GUI installer).</p></li>
<li><p>Once you have installed MSYS, you should have a shortcut in your start menu, named "MinGW Shell". That opens a console with a bash.</p></li>
<li><p>Extract the source tarball to your MSYS home directory. I have mingw installed in "D:\prog", so the directory was "D:\prog\MinGW\msys\1.0\home\<username>". You can tell your MSYS username from the shell prompt. When done, you should have a directory "D:\prog\MinGW\msys\1.0\home\<username>\protobuf-2.4.1".</p></li>
<li><p>At the shell prompt, change to the protobuf directory:</p>
<p><code>cd protobuf-2.4.1</code></p></li>
<li><p>Run the configure script (note the backquotes):</p>
<p><code>./configure --prefix=`cd /mingw; pwd -W`</code></p>
<p>The <code>--prefix</code> paramater makes sure protobuf is installed in the mingw directory tree instead of the MSYS directories, so you can build outside the MSYS shell (e.g. with CodeBlocks...)</p></li>
<li><p>Run make:</p>
<p><code>make</code></p></li>
<li><p>Install:</p>
<p><code>make install</code></p></li>
<li><p>That's it. You should now be able to compile your project with protobuf.<br>
You should be able to:</p>
<ul>
<li>call <code>protoc</code> from your project/makefiles</li>
<li><code>#include <google/protobuf/message.h></code> etc.</li>
<li>link with <code>-lprotobuf</code> or <code>-lprotobuf-lite</code></li>
</ul></li>
</ol>
<p>HTH<br>
Peter</p>
<p>Edit:
Bringing this a bit more up to date. I tried setting up a new PC with current versions of MinGW and protobuf 2.5.0, and these are the problems I had:</p>
<ol>
<li><p>There is no "MinGW Shell" shortcut in the start menu.<br>
For some reason current MinGW installations fail to install that.<br>
But there is a <code>msys.bat</code> in <code><Mingw home>\msys\1.0</code> which brings up a console with a bash. Create a shortcut to that batch file somewhere.</p></li>
<li><p>gcc does not work from the MSYS shell.<br>
I had to run a post-installation batch file manually and answer the questions there. This sets up fstab entries that mount the mingw directories in the MSYS environment.<br>
You need to run <code><Mingw home>\msys\1.0\postinstall\pi.bat</code></p></li>
<li><p>My Avira antivirus interfered with the protobuf compilation.<br>
It complained about the generated protoc.exe being a "TR/Crypt.XPACK.Gen" trojan and blocked acces to that file, resulting in a corrupted build.<br>
I got error messages saying something like <code>protoc:./.libs/lt-protoc.c:233: FATAL: couldn't find protoc.</code> when trying to start protoc.<br>
I had to disable the Avira realtime scanner and <code>make clean && make && make install</code> again</p></li>
</ol>
<p>Edit #2:</p>
<p>This post has aged quite a bit, and mingw does not equal mingw anymore.
In this day and age, I would rather recommend MSYS2 which comes with a port of ArchLinux's pacman package manager, a recent, better-working (c++11 std::thread support!) mingw fork for both 32 and 64 bit, and a protobuf package that you just need to install and be good.</p>
<p><a href="https://sourceforge.net/projects/msys2/" rel="nofollow noreferrer">Go here</a> to download!</p>
<p>Hope this helps!<br>
Peter</p> |
9,241,922 | Easy 'create table from view' syntax in mysql? | <p>I want to create a table that's a cache of results from a view. Is there an easy way to automatically define the table from the view's definition, or will I have to cobble it together from <code>show create table view</code>?</p> | 9,241,946 | 2 | 0 | null | 2012-02-11 16:39:32.14 UTC | 9 | 2015-06-04 22:25:19.017 UTC | null | null | null | null | 151,841 | null | 1 | 42 | mysql|syntax | 36,456 | <p>You can do <code>CREATE TABLE SELECT</code> from the view to build it. That should duplicate the view's structure as a new table containing all the view's rows. Here's the <a href="http://dev.mysql.com/doc/refman/5.0/en/create-table-select.html">MySQL syntax reference</a> for this statement.</p>
<pre><code>CREATE TABLE tbl_from_view AS
SELECT
col1,
col2,
col3,
col4,
col5
FROM your_view;
</code></pre>
<p>Note that you will want to be very explicit in your column selections. It isn't advisable to do a <code>SELECT *</code> from the source view. Make sure as well that you have aliases for any calculated or aggregate columns like <code>COUNT(*), MAX(*), (col1 + col2)</code>, etc.</p> |
9,132,772 | Lazy loading in node.js | <p>I was wondering if using <code>require()</code> in node.js was the equivalent to lazy loading?</p>
<p>For example if I had a function that required a specific node.js package that wasn't needed anywhere else in my code am I best to use <code>require()</code> inside of that function to include the needed package only when that function is called.</p>
<p>I'm also unsure if this will provide any performance improvements given my lack of understanding around the node.js architecture? I presume it will use less memory per connection to my server. However will it increase I/O to the disk when it has to read the package, or will this be a one off to get it in memory?</p>
<p>If this is the case how far should I take this, should I be trying to write node.js packages for as much code as I can?</p> | 9,139,419 | 2 | 0 | null | 2012-02-03 17:25:21.413 UTC | 10 | 2019-05-07 12:51:23.917 UTC | 2012-02-04 03:23:09.38 UTC | null | 930,675 | null | 930,675 | null | 1 | 50 | node.js | 28,640 | <p><code>require()</code> is on-demand loading. Once a module has been loaded it won't be reloaded if the require() call is run again. By putting it inside a function instead of your top level module code, you can delay its loading or potentially avoid it if you never actually invoke that function. However, <code>require()</code> is synchronous and loads the module from disk so best practice is to load any modules you need at application start before your application starts serving requests which then ensures that only asynchronous IO happens while your application is operational.</p>
<p>Node is single threaded so the memory footprint of loading a module is not per-connection, it's per-process. Loading a module is a one-off to get it into memory.</p>
<p>Just stick with the convention here and require the modules you need at the top level scope of your app before you start processing requests. I think this is a case of, if you have to ask whether you need to write your code in an unusual way, you don't need to write your code in an unusual way.</p> |
9,602,022 | Chrome extension - retrieving global variable from webpage | <p>I am working on an extension for Chrome. I wish parse the content of the "original" Gmail message (the currently viewed message).</p>
<p>I tried to utilize the jQuery.load() as follows</p>
<pre><code>$(windows).load(function() { alert(GLOBALS); });
</code></pre>
<p>and place it at the content script, but it does not work either. I am using Chrome's developer tools, which returns the following error on the invocation of the <code>alert(GLOBALS);</code></p>
<blockquote>
<p>Uncaught ReferenceError: GLOBALS is not defined</p>
</blockquote>
<p>Although, when using the developers tools' console, typing into the console <code>GLOBALS</code> it returns an array. </p>
<p>Any clue how to access the GLOBALS from the content script?</p> | 9,636,008 | 5 | 0 | null | 2012-03-07 13:01:48.887 UTC | 56 | 2019-05-29 17:05:27.43 UTC | 2018-01-20 21:00:24.263 UTC | null | 555,121 | null | 1,184,717 | null | 1 | 54 | javascript|html|dom|google-chrome-extension | 47,152 | <p><a href="https://developer.chrome.com/extensions/content_scripts" rel="noreferrer">Content scripts</a> run in an isolated environment. To get access to the any global properties (of the page's <code>window</code>), you have to either inject a new <code><script></code> element, or use event listeners for passing data.</p>
<p>See <a href="https://stackoverflow.com/a/9517879/938089?building-a-chrome-extension-with-youtube-events">this answer</a> for example on injecting a <code><script></code> element in the context of the page.</p>
<h2>Example</h2>
<p><strong>contentscript.js</strong> (<code>"run_at": "document_end"</code> in manifest):</p>
<pre><code>var s = document.createElement('script');
s.src = chrome.extension.getURL('script.js');
(document.head||document.documentElement).appendChild(s);
s.onload = function() {
s.remove();
};
// Event listener
document.addEventListener('RW759_connectExtension', function(e) {
// e.detail contains the transferred data (can be anything, ranging
// from JavaScript objects to strings).
// Do something, for example:
alert(e.detail);
});
</code></pre>
<p><strong><code>script.js</code></strong> - Located in the extension directory, this will be injected into the page itself:</p>
<pre><code>setTimeout(function() {
/* Example: Send data from the page to your Chrome extension */
document.dispatchEvent(new CustomEvent('RW759_connectExtension', {
detail: GLOBALS // Some variable from Gmail.
}));
}, 0);
</code></pre>
<p>Since this file is being loaded via a chrome-extension: URL from within the DOM, "script.js" must be added to the web_accessible_resources section of the manifest file. Otherwise Chrome will refuse to load the script file.</p>
<p>You should run as little logic as possible in the web page, and handle most of your logic in the content script. This has multiple reasons. First and foremost, any script injected in the page runs in the same context as the web page, so the web page can (deliberately or inadvertently) modify JavaScript/DOM methods in such a way that your extension stops working. Secondly, content script have access to extra features, such a limited subset of the chrome.* APIs and cross-origin network requests (provided that the extension has declared permissions for those).</p> |
9,643,603 | Modifying the color of an android drawable | <p>I would like to be able to use the same drawable to represent both:</p>
<p><img src="https://i.stack.imgur.com/81xak.png" alt="Blue icon"> and <img src="https://i.stack.imgur.com/nQ1ez.png" alt="Red icon"> </p>
<p>as the same drawable, and re-color the drawable based on some programmatic values, so that the end user could re-theme the interface. </p>
<p>What is the best way to do this? I have tried (and reused the icons from) <a href="https://stackoverflow.com/questions/4354939/understanding-the-use-of-colormatrix-and-colormatrixcolorfilter-to-modify-a-draw">this previous S.O. question</a> but I can't represent the change as a simple change of hue, since it also varies in saturation and value..</p>
<p>Is it best to store the icon as all white in the area I want changed? or transparent? or some other solid color?</p>
<p>Is there some method that allows you to figure out the matrix based on the difference between Color of red_icon and Color of blue_icon?</p> | 9,855,270 | 6 | 0 | null | 2012-03-10 03:07:50.043 UTC | 40 | 2017-12-15 03:58:08.917 UTC | 2017-11-11 01:14:22.657 UTC | null | 3,681,880 | null | 697,151 | null | 1 | 67 | android|themes|drawable | 70,234 | <p>So after a lot of trial and error, reading different articles, and most importantly, going through the API Demos (ColorFilters.java -- found in com.example.android.apis.graphics) I found the solution.</p>
<p>For solid images, I have found it is best to use the color filter PorterDuff.Mode.SRC_ATOP because it will overlay the color on top of the source image, allowing you to change the color to the exact color you are looking for.</p>
<p>For images that are more complex, like the one above, I have found the best thing to do is to color the entire image WHITE (FFFFFF) so that when you do PorterDuff.Mode.MULTIPLY, you end up with the correct colors, and all of the black (000000) in your image will remain black.</p>
<p>The colorfilters.java shows you how it's done if your drawing on a canvas, but if all you need is to color a drawable then this will work:</p>
<pre><code>COLOR2 = Color.parseColor("#FF"+getColor());
Mode mMode = Mode.SRC_ATOP;
Drawable d = mCtx.getResources().getDrawable(R.drawable.image);
d.setColorFilter(COLOR2,mMode)
</code></pre>
<p>I created a demo activity using some of the API Demo code to swap between every color filter mode to try them out for different situations and have found it to be invaluable, so I thought I would post it here.</p>
<pre><code>public class ColorFilters extends GraphicsActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new SampleView(this));
}
private static class SampleView extends View {
private Activity mActivity;
private Drawable mDrawable;
private Drawable[] mDrawables;
private Paint mPaint;
private Paint mPaint2;
private float mPaintTextOffset;
private int[] mColors;
private PorterDuff.Mode[] mModes;
private int mModeIndex;
private Typeface futura_bold;
private AssetManager assets;
private static void addToTheRight(Drawable curr, Drawable prev) {
Rect r = prev.getBounds();
int x = r.right + 12;
int center = (r.top + r.bottom) >> 1;
int h = curr.getIntrinsicHeight();
int y = center - (h >> 1);
curr.setBounds(x, y, x + curr.getIntrinsicWidth(), y + h);
}
public SampleView(Activity activity) {
super(activity);
mActivity = activity;
Context context = activity;
setFocusable(true);
/**1. GET DRAWABLE, SET BOUNDS */
assets = context.getAssets();
mDrawable = context.getResources().getDrawable(R.drawable.roundrect_gray_button_bg_nine);
mDrawable.setBounds(0, 0, mDrawable.getIntrinsicWidth(), mDrawable.getIntrinsicHeight());
mDrawable.setDither(true);
int[] resIDs = new int[] {
R.drawable.roundrect_gray_button_bg,
R.drawable.order_button_white,
R.drawable.yellowbar
};
mDrawables = new Drawable[resIDs.length];
Drawable prev = mDrawable;
for (int i = 0; i < resIDs.length; i++) {
mDrawables[i] = context.getResources().getDrawable(resIDs[i]);
mDrawables[i].setDither(true);
addToTheRight(mDrawables[i], prev);
prev = mDrawables[i];
}
/**2. SET Paint for writing text on buttons */
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setTextSize(16);
mPaint.setTextAlign(Paint.Align.CENTER);
mPaint2 = new Paint(mPaint);
/** Calculating size based on font */
futura_bold = Typeface.createFromAsset(assets,
"fonts/futurastd-bold.otf");
//Determine size and offset to write text in label based on font size.
mPaint.setTypeface(futura_bold);
Paint.FontMetrics fm = mPaint.getFontMetrics();
mPaintTextOffset = (fm.descent + fm.ascent) * 0.5f;
mColors = new int[] {
0,
0xFFA60017,//WE USE THESE
0xFFC6D405,
0xFF4B5B98,
0xFF656565,
0xFF8888FF,
0xFF4444FF,
};
mModes = new PorterDuff.Mode[] {
PorterDuff.Mode.DARKEN,
PorterDuff.Mode.DST,
PorterDuff.Mode.DST_ATOP,
PorterDuff.Mode.DST_IN,
PorterDuff.Mode.DST_OUT,
PorterDuff.Mode.DST_OVER,
PorterDuff.Mode.LIGHTEN,
PorterDuff.Mode.MULTIPLY,
PorterDuff.Mode.SCREEN,
PorterDuff.Mode.SRC,
PorterDuff.Mode.SRC_ATOP,
PorterDuff.Mode.SRC_IN,
PorterDuff.Mode.SRC_OUT,
PorterDuff.Mode.SRC_OVER,
PorterDuff.Mode.XOR
};
mModeIndex = 0;
updateTitle();
}
private void swapPaintColors() {
if (mPaint.getColor() == 0xFF000000) {
mPaint.setColor(0xFFFFFFFF);
mPaint2.setColor(0xFF000000);
} else {
mPaint.setColor(0xFF000000);
mPaint2.setColor(0xFFFFFFFF);
}
mPaint2.setAlpha(0);
}
private void updateTitle() {
mActivity.setTitle(mModes[mModeIndex].toString());
}
private void drawSample(Canvas canvas, ColorFilter filter) {
/** Create a rect around bounds, ensure size offset */
Rect r = mDrawable.getBounds();
float x = (r.left + r.right) * 0.5f;
float y = (r.top + r.bottom) * 0.5f - mPaintTextOffset;
/**Set color filter to selected color
* create canvas (filled with this color)
* Write text using paint (new color)
*/
mDrawable.setColorFilter(filter);
mDrawable.draw(canvas);
/** If the text doesn't fit in the button, make the text size smaller until it does*/
final float size = mPaint.measureText("Label");
if((int) size > (r.right-r.left)) {
float ts = mPaint.getTextSize();
Log.w("DEBUG","Text size was"+ts);
mPaint.setTextSize(ts-2);
}
canvas.drawText("Sausage Burrito", x, y, mPaint);
/** Write the text and draw it onto the drawable*/
for (Drawable dr : mDrawables) {
dr.setColorFilter(filter);
dr.draw(canvas);
}
}
@Override protected void onDraw(Canvas canvas) {
canvas.drawColor(0xFFCCCCCC);
canvas.translate(8, 12);
for (int color : mColors) {
ColorFilter filter;
if (color == 0) {
filter = null;
} else {
filter = new PorterDuffColorFilter(color,
mModes[mModeIndex]);
}
drawSample(canvas, filter);
canvas.translate(0, 55);
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
// update mode every other time we change paint colors
if (mPaint.getColor() == 0xFFFFFFFF) {
mModeIndex = (mModeIndex + 1) % mModes.length;
updateTitle();
}
swapPaintColors();
invalidate();
break;
}
return true;
}
}
}
</code></pre>
<p>The two other dependencies, GraphicsActivity.java and PictureLayout.java, can be copied directly from the API Demos activity if you would like to test it out.</p> |
22,440,430 | Accessing Android Studio properties window? | <p>I have recently started using Android Studio and cannot work out how to access the properties window.</p>
<p>The following screenshot was taken from Google and shows <strong><em>exactly</em></strong> what I'm trying to access denoted by the red rectangle around the properties window.</p>
<p><img src="https://i.stack.imgur.com/4mTRB.png" alt="enter image description here"></p>
<p>Can anyone please tell me how I can access this?</p> | 22,740,482 | 7 | 1 | null | 2014-03-16 17:43:38.387 UTC | 3 | 2020-10-13 21:35:34.4 UTC | 2016-04-15 21:30:57.813 UTC | null | 1,352,057 | null | 1,352,057 | null | 1 | 31 | android|ide|android-studio | 71,392 | <p><a href="https://i.stack.imgur.com/IwRtj.png" rel="noreferrer"><img src="https://i.stack.imgur.com/IwRtj.png" alt="enter image description here"></a>Switch to design view. Click "Design" tab at bottom-left work area.</p> |
7,222,332 | R will plot but won't draw abline | <pre><code>> head(returnee)
[1] 1.3936536 -0.6730667 2.3584725 2.3477308 3.2841443 1.3168157
> head(vixee)
[1] 14.75 15.45 17.59 17.74 17.75 18.35
> class(returnee)
[1] "numeric"
> class(vixee)
[1] "numeric"
> plot(returnee, vixee)
> abline(lm(returnee ~ vixee))
</code></pre>
<p>When I run this, it gives the plot, but there is no abline. Any suggestions? Thanks.</p> | 7,222,413 | 2 | 0 | null | 2011-08-28 16:48:53.773 UTC | 2 | 2011-08-30 04:56:31.1 UTC | 2011-08-30 04:56:31.1 UTC | null | 709,619 | null | 914,308 | null | 1 | 19 | r|plot | 61,085 | <p>It should be <code>abline(lm(vixee ~ returnee))</code> to match the coordinates of the plot.</p> |
19,255,289 | for loop object names iterate | <p>I am working on a project where I have to do a lot of repeating and life would be a lot easier if i could address multiple objects in a for loop. To elleborate my question i have come up with a (silly) example</p>
<p>For instance if have done this to create my data:</p>
<pre><code>for (i in 1:10)
{
assign(paste("Season",i, sep = ""),rnorm(10,0,1))
}
</code></pre>
<p>So I have Season1, Season2,..,Season10.
Is it possible to change the first number of the 10 objects to zero <strong>using a for loop</strong>. Semi pseudocode looks like this. But of course this does not work. </p>
<pre><code>for (i in 1:10)
{
Seasoni[1]<-0
}
</code></pre>
<p>Anyone with a solution?</p>
<p>Stefan</p> | 19,255,608 | 2 | 1 | null | 2013-10-08 18:17:08.097 UTC | 3 | 2013-10-08 18:46:21.277 UTC | 2013-10-08 18:41:42.253 UTC | null | 1,968 | null | 2,859,748 | null | 1 | 6 | r | 46,244 | <p>The direct solution to your question would be to use <code>get</code> with <code>paste</code></p>
<pre><code>for(i in 1:10)
{
Object = get(paste0("Season", i))
Object[1] = 0
assign(paste0("Season", i), Object)
}
</code></pre>
<p><strong>But don't do this</strong>. </p>
<p>It's a horrible use of R. As suggested in the comments, store results in lists:</p>
<pre><code>Seasons = lapply(rep(10,10), rnorm) #Generate data
Seasons
</code></pre>
<p>Then apply functions:</p>
<pre><code>Seasons = lapply(Seasons, replace, list=1, values=0)
</code></pre> |
19,204,048 | Returning JsonObject using @ResponseBody in SpringMVC | <p>I am using the new Java API (JSR 353) for JSON in a SpringMVC project.</p>
<p>The idea is to generate some piece of Json data and have it returned to the client. The controller I have look somewhat like this:</p>
<pre><code>@RequestMapping("/test")
@ResponseBody
public JsonObject test() {
JsonObject result = Json.createObjectBuilder()
.add("name", "Dade")
.add("age", 23)
.add("married", false)
.build();
return result;
}
</code></pre>
<p>And when I access this, instead of getting the expected representation of the JSON, I get these instead:</p>
<pre><code>{"name":{"chars":"Dade","string":"Dade","valueType":"STRING"},"age":{"valueType":"NUMBER","integral":true},"married":{"valueType":"FALSE"}}
</code></pre>
<p>Why is this? What is going on? And how do I make it returned the expected JSON properly? </p> | 19,205,116 | 2 | 1 | null | 2013-10-06 00:16:05.94 UTC | 7 | 2016-12-09 19:02:46.883 UTC | 2013-10-06 00:28:19.937 UTC | null | 371,082 | null | 371,082 | null | 1 | 17 | java|json|spring-mvc | 79,020 | <p>The answer is pretty simple when you realize there is no special <code>HandlerMethodReturnValueHandler</code> for the new JSR 353 API. Instead, in this case, the <code>RequestResponseBodyMethodProcessor</code> (for <code>@ResponseBody</code>) uses a <code>MappingJackson2HttpMessageConverter</code> to serialize the return value of your handler method.</p>
<p>Internally, the <code>MappingJackson2HttpMessageConverter</code> uses an <code>ObjectMapper</code>. By default, the <code>ObjectMapper</code> uses the getters of a class to serialize an object to JSON.</p>
<p>Assuming you are using <code>Glassfish</code>'s provider implementation of the JSR 353, those classes are <code>org.glassfish.json.JsonObjectBuilderImpl$JsonObjectImpl</code>, <code>org.glassfish.json.JsonStringImpl</code>, and
<code>org.glassfish.json.JsonNumberImpl</code>, and <code>javax.json.JsonValue$3</code> (an anonymous class for the value <code>FALSE</code>).</p>
<p>Because <code>JsonObjectImpl</code> (your result, ie. root, object) is a <code>Map</code> (special type), <code>ObjectMapper</code> serializes the map's entries as JSON key-value pair elements, where the Map key is the JSON key, and the Map value is the JSON value. For the key, it works fine, serializing as <code>name</code>, <code>age</code>, and <code>married</code>. For the value, it uses the classes I mentioned above and their respective getters. For example, <code>org.glassfish.json.JsonStringImpl</code> is implemented as</p>
<pre><code>final class JsonStringImpl implements JsonString {
private final String value;
public JsonStringImpl(String value) {
this.value = value;
}
@Override
public String getString() {
return value;
}
@Override
public CharSequence getChars() {
return value;
}
@Override
public ValueType getValueType() {
return ValueType.STRING;
}
...
}
</code></pre>
<p><code>ObjectMapper</code> therefore uses the Java Bean getters to serialize the <code>JsonStringImpl</code> object (that is the Map Entry's value), as</p>
<pre><code>{"chars":"Dade","string":"Dade","valueType":"STRING"}
</code></pre>
<p>The same applies for the other fields.</p>
<p>If you want to correctly write the JSON, simply return a <code>String</code>.</p>
<pre><code>@RequestMapping("/test", produces="application/json")
@ResponseBody
public String test() {
JsonObject result = Json.createObjectBuilder()
.add("name", "Dade")
.add("age", 23)
.add("married", false)
.build();
return result.toString();
}
</code></pre>
<p>Or make your own <code>HandlerMethodReturnValueHandler</code>, a little more complicated, but more rewarding.</p> |
58,579,774 | Convert an existing Flutter Kotlin project to Flutter Java project | <p>I created a Flutter project using default values, which are Kotlin for Android and Swift for iOS. Halfway through the project I needed to integrate a 3rd party Android SDK that requires Java. Can I convert a Flutter project to Java for Android after creation?</p>
<p>I know I will need yo use Platform Channels to integrate native code with my Flutter app, this is not my concern.</p> | 58,602,076 | 7 | 2 | null | 2019-10-27 13:20:32.107 UTC | 5 | 2021-01-21 16:53:31.51 UTC | null | null | null | null | 2,268,140 | null | 1 | 31 | java|android|kotlin|flutter | 15,706 | <p>I had the same problem, for me this solution works. </p>
<ol>
<li>Move folder com.example.test_app (any name you have) from android/app/src/main/kotlin -> android/app/src/main/java</li>
<li><p>Replace MainActivity.kt with Java version, or copy down here</p>
<pre><code>package com.example.test_app;
import androidx.annotation.NonNull;
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugins.GeneratedPluginRegistrant;
public class MainActivity extends FlutterActivity {
@Override
public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
GeneratedPluginRegistrant.registerWith(flutterEngine);
}
}
</code></pre></li>
<li><p>Remove following code android/app/build.grandle</p>
<pre><code>...
apply plugin: 'kotlin-android'
...
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}
</code></pre></li>
<li><p>In the same place replace following:</p>
<pre><code>dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.1.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0'
}
</code></pre>
<p>to</p>
<pre><code>dependencies {
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
</code></pre></li>
</ol> |
17,688,232 | Does Vim load plugins after loading vimrc? | <p>I'm trying to override the highlight set in a plugin. The plugin does this: </p>
<pre><code>highlight! link WordUnderTheCursor Underlined
</code></pre>
<p>Firstly, I'm not aware that <code>!</code> added to <code>highlight</code> does anything. But that's irrelevant. </p>
<p>Doing stuff like this in the vimrc</p>
<pre><code>highlight clear WordUnderTheCursor
highlight WordUnderTheCursor cterm=bold ctermfg=254 ctermbg=160
</code></pre>
<p>Does not appear to affect the behavior.</p>
<p>Only when I directly modify the <code>Underlined</code> style (which feels wrong) in the vimrc, does the change apply. </p>
<p>Is this proof that the plugin is being run <em>after</em> the vimrc runs? </p>
<p>How might I unlink the style? I can't really tell if this is just the plugin doing something creative and unsupported, or if this is normal Vim behavior.</p> | 17,688,716 | 2 | 0 | null | 2013-07-16 22:45:21.703 UTC | 9 | 2019-03-25 05:45:42.727 UTC | 2019-03-25 05:45:42.727 UTC | null | 2,566,838 | null | 340,947 | null | 1 | 24 | vim | 8,369 | <p>Yes. vimrc is loaded before plugins.</p>
<p>If you look at <a href="http://vimdoc.sourceforge.net/htmldoc/starting.html#initialization"><code>:h initialization</code></a> you will find that step 3 is load vimrc and step 4 is load plugins.</p>
<p>You can also see that vimrc is loaded before plugins by looking at the output of <code>:scriptnames</code>. scriptnames lists all sourced scripts in the order they were sourced and vimrc is the first thing sourced. (Take a look at <a href="http://vimdoc.sourceforge.net/htmldoc/repeat.html#%3ascriptnames"><code>:h :scriptnames</code></a>).</p>
<hr>
<p>To fix the highlighting you just need to run the highlight commands after the plugin gets sourced. To do this you put files in the <code>after</code> directory of your <code>.vim</code> directory. (Take a look at <a href="http://vimdoc.sourceforge.net/htmldoc/options.html#after-directory"><code>:h after-directory</code></a>)</p>
<p>So create the file <code>.vim/after/plugin/hicursorwords.vim</code> with the following contents</p>
<pre><code>highlight clear WordUnderTheCursor
highlight WordUnderTheCursor cterm=bold ctermfg=254 ctermbg=160
</code></pre>
<p>This will cause the plugin to be sourced before you change the settings of the plugin.</p>
<p>(This of course assumes you don't want to edit the plugin)</p> |
35,744,901 | How to change the active configuration profile in gcloud? | <p>I have created a new configuration profile using command: </p>
<pre><code>gcloud init
</code></pre>
<p>and now I don't know how to switch to old configuration profile without override it. </p>
<p>Using <code>gcloud config</code> I can't switch to another configuration only set a property of the current configuration. </p>
<p>any idea?</p> | 35,750,001 | 2 | 2 | null | 2016-03-02 10:43:49.523 UTC | 16 | 2020-02-23 19:04:10.793 UTC | 2016-03-02 22:32:26.497 UTC | null | 372,128 | null | 2,270,262 | null | 1 | 63 | google-compute-engine|gcloud|gcloud-cli | 36,402 | <p>You can see your configurations (created via gcloud init) via</p>
<pre><code>gcloud config configurations list
</code></pre>
<p>You can switch to a different configuration via</p>
<pre><code>gcloud config configurations activate MY_OLD_CONFIG
</code></pre>
<p>Once activated you can</p>
<pre><code>gcloud config list
</code></pre>
<p>to see its settings.</p>
<p>You can also do this without activation by running</p>
<pre><code>gcloud config list --configuration CONFIGURATION_NAME
</code></pre> |
35,552,874 | Get first letter of a string from column | <p>I'm fighting with pandas and for now I'm loosing. I have source table similar to this:</p>
<pre><code>import pandas as pd
a=pd.Series([123,22,32,453,45,453,56])
b=pd.Series([234,4353,355,453,345,453,56])
df=pd.concat([a, b], axis=1)
df.columns=['First', 'Second']
</code></pre>
<p>I would like to add new column to this data frame with first digit from values in column 'First':
a) change number to string from column 'First'
b) extracting first character from newly created string
c) Results from b save as new column in data frame</p>
<p>I don't know how to apply this to the pandas data frame object. I would be grateful for helping me with that.</p> | 35,552,899 | 2 | 2 | null | 2016-02-22 11:50:18.617 UTC | 17 | 2019-04-05 10:11:34.79 UTC | null | null | null | null | 5,528,782 | null | 1 | 71 | python|pandas | 167,283 | <p>Cast the <code>dtype</code> of the col to <code>str</code> and you can perform vectorised slicing calling <code>str</code>:</p>
<pre><code>In [29]:
df['new_col'] = df['First'].astype(str).str[0]
df
Out[29]:
First Second new_col
0 123 234 1
1 22 4353 2
2 32 355 3
3 453 453 4
4 45 345 4
5 453 453 4
6 56 56 5
</code></pre>
<p>if you need to you can cast the <code>dtype</code> back again calling <code>astype(int)</code> on the column</p> |
21,237,495 | Create Custom Big Notifications | <p>I wanted to create a Notification including some controls. Since text and controls are small with default notification size (64dp), i wanted have it larger than default size.<br>
It is possible to create larger notifications, and I think it is possible to have a custom layout, too, but I don't know how.</p>
<p>To be more specific, the following screenshot shows the notification from spotify (image take from <a href="http://androidauthority.com/spotify-android-notifications-controls-233010/" rel="noreferrer">here</a>): <img src="https://i.stack.imgur.com/XEfAQ.jpg" alt="Spotify notification"> </p>
<p>As you can see, the size is bigger than default. Further, it has some kind of ImageButtons without text - if you use <a href="http://developer.android.com/reference/android/app/Notification.Builder.html#addAction%28int,%20java.lang.CharSequence,%20android.app.PendingIntent%29" rel="noreferrer"><em>Notification.Builder.addAction()</em></a>, you may provide an icon but also need to provide a CharSequence as a description - if you leave the description empty, there will still be space reserved for the text and if you pass <em>null</em>, it will crash.</p>
<p>Can anybody tell me how to create a big notification with a custom layout? </p>
<p>Thanks</p> | 21,283,668 | 2 | 2 | null | 2014-01-20 15:14:09.38 UTC | 19 | 2019-10-31 11:57:45.743 UTC | null | null | null | null | 1,798,304 | null | 1 | 23 | android|android-layout|android-notifications | 39,659 | <p><strong>Update due to API changes:</strong> </p>
<p>From API 24 on, the <code>Notification.Builder</code> contains a <a href="https://developer.android.com/reference/android/app/Notification.Builder.html#setCustomBigContentView(android.widget.RemoteViews)">setCustomBigContentView(RemoteViews)</a>-method. Also the <a href="https://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html">NotificationCompat.Builder</a> (which is part of the support.v4 package) contains this method.<br>
Please note, that the documentation for the <a href="https://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html#setCustomBigContentView(android.widget.RemoteViews)">NotificationCompat.Builder.setCustomBigContentView</a> states: </p>
<blockquote>
<p>Supply custom RemoteViews to use instead of the platform template in the expanded form. This will override the expanded layout that would otherwise be constructed by this Builder object. No-op on versions prior to JELLY_BEAN. </p>
</blockquote>
<p>Therefore, this will also only work for API >= 16 (JELLY_BEAN).</p>
<hr>
<p><strong>Original Answer</strong></p>
<p>So after excessive google usage, I found <a href="http://codeversed.com/expandable-notifications-android/">this tutorial</a> explaining how to use custom big layouts. The trick is not to use <code>setStyle()</code> but manually set the <code>bigContentView</code> field of the <code>Notification</code> <strong>after building it</strong>. Seems a bit hacky, but this is what I finally came up with: </p>
<p>notification_layout_big.xml:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="100dp" <!-- This is where I manually define the height -->
android:orientation="horizontal" >
<!-- some more elements.. -->
</LinearLayout>
</code></pre>
<p>Building <code>Notification</code> in code:</p>
<pre><code>Notification foregroundNote;
RemoteViews bigView = new RemoteViews(getApplicationContext().getPackageName(),
R.layout.notification_layout_big);
// bigView.setOnClickPendingIntent() etc..
Notification.Builder mNotifyBuilder = new Notification.Builder(this);
foregroundNote = mNotifyBuilder.setContentTitle("some string")
.setContentText("Slide down on note to expand")
.setSmallIcon(R.drawable.ic_stat_notify_white)
.setLargeIcon(bigIcon)
.build();
foregroundNote.bigContentView = bigView;
// now show notification..
NotificationManager mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotifyManager.notify(1, foregroundNote);
</code></pre>
<p><strong>Edit</strong><br>
As noted by chx101, this only works for API >= 16. I did not mention it in this answer, yet it was mentioned in the given linked tutorial above: </p>
<blockquote>
<p>Expanded notifications were first introduced in Android 4.1 JellyBean [API 16].</p>
</blockquote> |
41,071,976 | I am confused about using static method in Multithreading java? | <p>something about static:</p>
<ul>
<li>instances of class share static method</li>
</ul>
<p>the similar questions:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/2671496/java-when-to-use-static-methods">Java: when to use static methods</a></li>
<li><a href="https://stackoverflow.com/questions/413898/what-does-the-static-keyword-do-in-a-class">What does the 'static' keyword do in a class?</a></li>
</ul>
<p>I am confusing about:</p>
<ul>
<li>static method just have only one memory block?</li>
<li>if i use static method in multithreading, will it block?</li>
</ul> | 41,072,067 | 4 | 1 | null | 2016-12-10 03:52:32.86 UTC | 9 | 2021-12-03 17:03:28.217 UTC | 2017-05-23 10:29:50.883 UTC | null | -1 | null | 6,707,607 | null | 1 | 27 | java|multithreading|static|static-methods | 34,907 | <blockquote>
<p>I am confusing about:</p>
<p>static method just have only one memory block? if i use static method
in multithreading, will it block?</p>
</blockquote>
<p>The <code>static</code> keyword in Java simply means "without regard or knowledge of any particular instance of an object."</p>
<p>An instance method can use <code>this</code> to access the fields of its associated instance, but a static method has no associated instance and so <code>this</code> makes no sense.</p>
<p>In multithreading, thread safety involves protecting the consistency and integrity of mutable data. Because objects encapsulate the state of their instance fields, instance methods only need to be concerned about thread safety in those circumstances in which more than one thread will be accessing the same object.</p>
<p>So while thread confinement of an object is a valid thread safety policy for instances of a class, this same reasoning is invalid for static methods because they have no instance. </p>
<p>This has nothing to do with memory blocks at all. It just has to do with access. An object instance is accessed through a reference. If the reference is thread confined, then the object to which that reference points will always be thread safe. But any thread anywhere that can access your class can potentially get to its static members because no reference to an instance is needed to use them.</p>
<p>Static methods are non-blocking by default. You can implement your own synchronization/thread safety policy and have your static method block if you wish.</p> |
1,620,072 | In Django, how to clear all the memcached keys and values? | <p>I don't want to restart the memcached server!</p> | 1,620,084 | 3 | 2 | null | 2009-10-25 05:11:27.95 UTC | 12 | 2020-04-29 09:26:17.07 UTC | null | null | null | null | 179,736 | null | 1 | 21 | python|django|caching|memcached | 13,218 | <pre><code>from django.core.cache import cache
cache._cache.flush_all()
</code></pre>
<p>Also see this ticket, it has a patch (that I haven't tested) to flush any type of cache backend: <a href="http://code.djangoproject.com/ticket/11503" rel="noreferrer">http://code.djangoproject.com/ticket/11503</a></p> |
1,468,111 | How do I jump to the matching tag, when editing HTML in Emacs? | <p>Suppose I'm editing a very long and messy HTML file. With my cursor at an open tag, is there a way to jump to its closing tag?</p> | 1,468,142 | 3 | 0 | null | 2009-09-23 19:30:57.787 UTC | 10 | 2016-03-24 21:26:03.773 UTC | 2012-02-26 07:08:05.607 UTC | null | 20,972 | null | 21,456 | null | 1 | 39 | html|emacs | 11,060 | <p>Assuming you're using nxml-mode:</p>
<pre><code>C-M-n runs the command nxml-forward-element, which is an interactive
compiled Lisp function in `nxml-mode.el'.
It is bound to C-M-n.
(nxml-forward-element &optional ARG)
Move forward over one element.
With ARG, do it that many times.
Negative ARG means move backward.
</code></pre> |
1,357,798 | How to center cell contents of a LaTeX table whose columns have fixed widths? | <p>Consider the following piece of LaTeX code:</p>
<pre><code>\begin{tabular}{p{1in}p{1in}}
A & B\\
C & D\\
\end{tabular}
</code></pre>
<p>How can I make the contents of each cell aligned in the center of the cell rather than the left?
Note that I want to make sure that the widths of my columns are fixed, so I cannot use the "c" position attribute instead of "p{.1in}" to center my cell contents.</p> | 1,358,166 | 3 | 1 | null | 2009-08-31 14:41:27.597 UTC | 24 | 2022-05-26 12:54:14.727 UTC | 2016-12-31 22:48:58.7 UTC | null | 4,370,109 | null | 130,224 | null | 1 | 72 | alignment|latex|tabular | 173,230 | <p><code>\usepackage{array}</code> in the preamble</p>
<p>then this:</p>
<pre><code>\begin{tabular}{| >{\centering\arraybackslash}m{1in} | >{\centering\arraybackslash}m{1in} |}
</code></pre>
<p>note that the "m" for fixed with column is provided by the array package, and will give you vertical centering (if you don't want this just go back to "p"</p> |
8,616,146 | eventlisteners using hibernate 4.0 with spring 3.1.0.release? | <p>These jars are both new released and have the latest solutions for Java EE applications. But I have a problem on specifiying hibernate listeners in hibernate.cfg.xml. </p>
<p>Before spring 3.1.0, <code>LocalSessionFactroyBean</code> was holding an attribute that keeps eventlisteners. But with 3.1.0.release there is no eventlisteners map. Now I fail keeping the track of modal objects on saveorupdate, postload etc. because they are not configured by Spring. Do you have an idea to solve this issue?</p> | 9,011,451 | 4 | 1 | null | 2011-12-23 12:35:34.463 UTC | 11 | 2019-06-26 18:54:44.773 UTC | 2019-06-26 18:54:44.773 UTC | null | 1,281,433 | null | 706,589 | null | 1 | 20 | java|event-listener|spring-3|hibernate-4.x | 30,721 | <p>I had the same frustrating problem. Hibernate 4 appears to have fundamentally changed the way you register for events and the Spring group has not yet caught up. Here's my annotation-based solution using an init method to register a listener:</p>
<pre><code>@Component
public class HibernateEventWiring {
@Autowired
private SessionFactory sessionFactory;
@Autowired
private SomeHibernateListener listener;
@PostConstruct
public void registerListeners() {
EventListenerRegistry registry = ((SessionFactoryImpl) sessionFactory).getServiceRegistry().getService(
EventListenerRegistry.class);
registry.getEventListenerGroup(EventType.POST_COMMIT_INSERT).appendListener(listener);
registry.getEventListenerGroup(EventType.POST_COMMIT_UPDATE).appendListener(listener);
}
}
</code></pre>
<p>An interceptor would be another fine approach, but support for interceptors was mistakenly dropped: <a href="https://jira.springsource.org/browse/SPR-8940">https://jira.springsource.org/browse/SPR-8940</a></p> |
8,683,922 | How can I pass my context variables to a javascript file in Django? | <p>This question must be obvious but I can't figure it out.</p>
<p>In a template, I link to a js file in my media directory. From that file, I would like to access a context variable like <code>{{my_chart}}</code>.</p>
<p>But is the syntax different?? Thank you!!</p> | 8,684,032 | 4 | 1 | null | 2011-12-30 20:45:38.553 UTC | 16 | 2021-06-14 20:31:07.997 UTC | 2021-06-14 07:39:07.62 UTC | null | 7,451,109 | null | 963,936 | null | 1 | 38 | javascript|django|templates | 40,069 | <p>I don't think it's possible this way. If you want to access some data provided by the view, you have to pass it to the js function.</p>
<p>Example</p>
<p>js file:</p>
<pre><code>my_cool_js_function(some_param){
// do some cool stuff
}
</code></pre>
<p>view</p>
<pre><code>// some html code
my_cool_js_function({{param}})
</code></pre>
<p>hope this helps :)</p> |
887,189 | Fuzzy Date Time Picker Control in C# .NET? | <p>I am implementing a Fuzzy Date control in C# for a winforms application. The Fuzzy Date should be able to take fuzzy values like</p>
<ul>
<li>Last June</li>
<li>2 Hours ago</li>
<li>2 Months ago</li>
<li>Last week</li>
<li>Yesterday </li>
<li>Last year</li>
</ul>
<p>and the like </p>
<p>Are there any sample implementations of "Fuzzy" Date Time Pickers? </p>
<p>Any ideas to implement such a control would be appreciated </p>
<p><strong>PS</strong>:
I am aware of the fuzzy date algorithm spoken about <a href="https://stackoverflow.com/questions/822124/fuzzy-date-algorithm">here</a> and <a href="https://stackoverflow.com/questions/11/how-do-i-calculate-relative-time">here</a>, I am really looking for any ideas and inspirations for developing such a control</p> | 894,365 | 4 | 2 | null | 2009-05-20 10:27:23.89 UTC | 9 | 2016-06-29 12:12:44.007 UTC | 2017-05-23 11:52:28.823 UTC | null | -1 | null | 64,497 | null | 1 | 9 | c#|winforms|datetime|user-controls|fuzzy | 7,465 | <p>The parsing is quite easy. It can be implemented as bunch of regexps and some date calculations.</p>
<p>The sample below can be easily extended to suit your needs.
I've roughly tested it and it works at least for the following strings:</p>
<ul>
<li>next month, next year,</li>
<li>next 4 months, next 3 days</li>
<li>3 days ago, 5 hours ago</li>
<li>tomorrow, yesterday</li>
<li>last year, last month,</li>
<li>last tue, next fri</li>
<li>last june, next may, </li>
<li>jan 2008, 01 january 2009,</li>
<li>june 2019, 2009/01/01</li>
</ul>
<p>The helper class:</p>
<pre><code>class FuzzyDateTime
{
static List<string> dayList = new List<string>() { "sun", "mon", "tue", "wed", "thu", "fri", "sat" };
static List<IDateTimePattern> parsers = new List<IDateTimePattern>()
{
new RegexDateTimePattern (
@"next +([2-9]\d*) +months",
delegate (Match m) {
var val = int.Parse(m.Groups[1].Value);
return DateTime.Now.AddMonths(val);
}
),
new RegexDateTimePattern (
@"next +month",
delegate (Match m) {
return DateTime.Now.AddMonths(1);
}
),
new RegexDateTimePattern (
@"next +([2-9]\d*) +days",
delegate (Match m) {
var val = int.Parse(m.Groups[1].Value);
return DateTime.Now.AddDays(val);
}
),
new RegexDateTimePattern (
@"([2-9]\d*) +months +ago",
delegate (Match m) {
var val = int.Parse(m.Groups[1].Value);
return DateTime.Now.AddMonths(-val);
}
),
new RegexDateTimePattern (
@"([2-9]\d*) days +ago",
delegate (Match m) {
var val = int.Parse(m.Groups[1].Value);
return DateTime.Now.AddDays(-val);
}
),
new RegexDateTimePattern (
@"([2-9]\d*) *h(ours)? +ago",
delegate (Match m) {
var val = int.Parse(m.Groups[1].Value);
return DateTime.Now.AddMonths(-val);
}
),
new RegexDateTimePattern (
@"tomorrow",
delegate (Match m) {
return DateTime.Now.AddDays(1);
}
),
new RegexDateTimePattern (
@"today",
delegate (Match m) {
return DateTime.Now;
}
),
new RegexDateTimePattern (
@"yesterday",
delegate (Match m) {
return DateTime.Now.AddDays(-1);
}
),
new RegexDateTimePattern (
@"(last|next) *(year|month)",
delegate (Match m) {
int direction = (m.Groups[1].Value == "last")? -1 :1;
switch(m.Groups[2].Value)
{
case "year":
return new DateTime(DateTime.Now.Year+direction, 1,1);
case "month":
return new DateTime(DateTime.Now.Year, DateTime.Now.Month+direction, 1);
}
return DateTime.MinValue;
}
),
new RegexDateTimePattern (
String.Format(@"(last|next) *({0}).*", String.Join("|", dayList.ToArray())), //handle weekdays
delegate (Match m) {
var val = m.Groups[2].Value;
var direction = (m.Groups[1].Value == "last")? -1 :1;
var dayOfWeek = dayList.IndexOf(val.Substring(0,3));
if (dayOfWeek >= 0) {
var diff = direction*(dayOfWeek - (int)DateTime.Today.DayOfWeek);
if (diff <= 0 ) {
diff = 7 + diff;
}
return DateTime.Today.AddDays(direction * diff);
}
return DateTime.MinValue;
}
),
new RegexDateTimePattern (
@"(last|next) *(.+)", // to parse months using DateTime.TryParse
delegate (Match m) {
DateTime dt;
int direction = (m.Groups[1].Value == "last")? -1 :1;
var s = String.Format("{0} {1}",m.Groups[2].Value, DateTime.Now.Year + direction);
if (DateTime.TryParse(s, out dt)) {
return dt;
} else {
return DateTime.MinValue;
}
}
),
new RegexDateTimePattern (
@".*", //as final resort parse using DateTime.TryParse
delegate (Match m) {
DateTime dt;
var s = m.Groups[0].Value;
if (DateTime.TryParse(s, out dt)) {
return dt;
} else {
return DateTime.MinValue;
}
}
),
};
public static DateTime Parse(string text)
{
text = text.Trim().ToLower();
var dt = DateTime.Now;
foreach (var parser in parsers)
{
dt = parser.Parse(text);
if (dt != DateTime.MinValue)
break;
}
return dt;
}
}
interface IDateTimePattern
{
DateTime Parse(string text);
}
class RegexDateTimePattern : IDateTimePattern
{
public delegate DateTime Interpreter(Match m);
protected Regex regEx;
protected Interpreter inter;
public RegexDateTimePattern(string re, Interpreter inter)
{
this.regEx = new Regex(re);
this.inter = inter;
}
public DateTime Parse(string text)
{
var m = regEx.Match(text);
if (m.Success)
{
return inter(m);
}
return DateTime.MinValue;
}
}
</code></pre>
<p>Usage example:</p>
<pre><code>var val = FuzzyDateTime.Parse(textBox1.Text);
if (val != DateTime.MinValue)
label1.Text = val.ToString();
else
label1.Text = "unknown value";
</code></pre> |
39,990,788 | Achieve "npm run x" behavior without a "scripts" entry? | <p>To run a node command within the "context" of your installed <code>node_modules</code>, you can make an entry in the <code>scripts</code> field of <code>package.json</code>. Eg:</p>
<pre><code>...
"scripts": {
"test": "mocha --recursive test/**/*.js --compilers js:babel-register"
}
...
</code></pre>
<p>and then I can type <code>npm run test</code> in my project root, and the mocha tests will run (by calling the mocha binary installed in <code>node_modules/mocha/bin</code>).</p>
<p>Is there a way to achieve precisely the same behavior but without creating a scripts entry? Eg, for a one-off "script"?</p>
<p>I'm imagining something like the following, as an equivalent to <code>npm run test</code>:</p>
<pre><code>npm cmd mocha --recursive test/**/*.js --compilers js:babel-register
</code></pre>
<p>Is there any way to achieve this?</p>
<p>NOTE: I should clarify that I'm looking for true equivalence. That is, my command should be able to access other script commands, etc. I know you can always call the binaries using node and the path to the binary within node_modules, but that's not an adequate solution.</p> | 39,991,116 | 3 | 1 | null | 2016-10-12 04:56:49.627 UTC | 9 | 2016-12-19 19:16:18.377 UTC | 2016-12-19 19:16:18.377 UTC | null | 769,871 | null | 438,615 | null | 1 | 32 | javascript|node.js|npm|command-line-interface | 8,145 | <p><sup>Note: This answer addresses the OP's specific use case: calling the CLIs of <em>dependent packages in the context of a given project</em>; it is <em>not</em> about making CLIs <em>globally available</em> - see bottom for a discussion.</sup> </p>
<p><strong>tl;dr:</strong></p>
<p><strong>On <em>Unix</em>-like platforms</strong>, <strong>prepend <code>npm run env --</code> to your command</strong>; e.g.:</p>
<pre><code>npm run env -- mocha --recursive test/**/*.js --compilers js:babel-register
</code></pre>
<p>This <strong>not only enables calling of dependent CLIs by mere name, but fully replicates the environment that <code>npm</code> sets</strong> behind the scenes when you use <code>npm test</code> or <code>npm run-script <script-defined-in-package.json></code>.</p>
<p>Sadly, this approach doesn't work on Windows.</p>
<p>For Windows solutions, convenience aliases (including once-per-session environment-configuration commands), and background information, read on.</p>
<hr>
<p>There are two (not mutually exclusive) <strong>approaches to making an npm project's dependencies' CLIs callable by mere name from the shell</strong>:</p>
<ul>
<li>(a) Use a <strong><em>per-invocation</em> helper command that you pass your commands to</strong>.</li>
<li>(b) Run a <strong><em>once-per-session</em> command that (temporarily) modifies your environment</strong>.</li>
</ul>
<p><a href="https://stackoverflow.com/a/39990838/45375">Frxstrem's helpful answer</a> provides an <em>incomplete</em> solution for (a) on Unix-like platforms; it <em>may</em>, however, be sufficient, depending on your specific needs.<br>
It is incomplete in that it merely prepends the directory containing (symlinks to) the dependent CLIs to the <code>$PATH</code>, without performing all other environment modifications that happen when you invoke <code>npm test</code> or <code>npm run-script <script-defined-in-package.json</code>.</p>
<hr>
<h2>Unix convenience and Windows solutions</h2>
<p>Note that <strong>all solutions below are based on <code>npm run env</code></strong>, which ensures that all necessary environment variables are set, just as they are when your run scripts predefined in the project's <code>package.json</code> file with <code>npm test</code> or <code>npm run-script <script></code>.<br>
These environment modifications include:</p>
<ul>
<li>Prepending <code>$(npm prefix -g)/node_modules/npm/bin/node-gyp-bin</code> and the project directory's <code>./node_modules/.bin</code> subdirectory, which is where symlinks to the dependencies' CLIs are located, (temporarily) to the <code>$PATH</code> environment variable.</li>
<li>Defining numerous <code>npm_*</code> environment variables that reflect the project's settings, such as <code>npm_package_version</code> as well as the <code>npm</code> / <code>node</code> environment.</li>
</ul>
<hr>
<h3>Convenience solutions for Unix-like platforms:</h3>
<p>Both solutions below are <strong><em>alias</em>-based</strong>, which in the case of (a) is a more light-weight alternative to using a <em>script</em>, and in the case of (b) is a prerequisite to allow modification of the current shell's environment (although a shell function could be used too).</p>
<p>For convenience, <strong>add these aliases to your shell profile/initialization
file</strong>.</p>
<p><strong>(a) Per-invocation helper:</strong></p>
<p>Defining</p>
<pre class="lang-sh prettyprint-override"><code>alias nx='npm run-script env --'
</code></pre>
<p>allows you to invoke your commands ad-hoc simply by prepending <code>nx</code>; e.g.:</p>
<pre class="lang-sh prettyprint-override"><code>nx mocha --recursive test/**/*.js --compilers js:babel-register
</code></pre>
<p><strong>(b) Once-per-session configuration command:</strong></p>
<pre class="lang-sh prettyprint-override"><code>alias npmenv='npm run env -- $SHELL'
</code></pre>
<p>Run <code>npmenv</code> to enter a <em>child shell</em> with the the npm environment set, allowing direct (by-name-only) invocation of dependent CLIs in that child shell.<br>
In other words, use this as follows:</p>
<pre class="lang-sh prettyprint-override"><code>cd ~/some-npm-project
npmenv # after this, you can run dependent CLIs by name alone; e.g., `mocha ...`
# ... run your project-specific commands
exit # exit the child shell before you switch to a different project
</code></pre>
<hr>
<h3>Windows solutions:</h3>
<p><strong>(a) <em>and</em> (b)</strong>: Note that Windows (unlike POSIX-like shells on Unix-like platforms) doesn't (directly) support passing environment variables scoped to a single command only, so the commands below, even when passed a specific command to execute (case (a)), invariably also modify the session's environment (case (b)).</p>
<p><strong>PowerShell</strong> (also works in the Unix versions):</p>
<p>Add the following function to your <code>$PROFILE</code> (user-specific profile script):</p>
<pre class="lang-sh prettyprint-override"><code>function npmenv($commandIfAny) {
npm run env -- |
? { $_ -and $_ -notmatch '^>' -and $_ -match '^[a-z_][a-z0-9_]+=' } |
% { $name, $val = $_ -split '='; set-item -path "env:$name" -value $val }
if ($?) {
if ($commandIfAny) {
& $commandIfAny $Args
}
}
}
</code></pre>
<p><strong><code>cmd.exe</code> (regular command prompt, often mistakenly called the "DOS prompt"):</strong></p>
<p>Create a batch file named <code>npmenv.cmd</code>, place it in a folder in your <code>%PATH%</code>, and define it as follows:</p>
<pre class="lang-sh prettyprint-override"><code>@echo off
:: Set all environment variables that `npm run env` reports.
for /f "delims==; tokens=1,*" %%i in ('npm run env ^| findstr /v "^>"') do set "%%i=%%j"
:: Invoke a specified command, if any.
%*
</code></pre>
<p><strong>Usage</strong> (both <code>cmd.exe</code> and PowerShell):</p>
<p>For use case (b), invoke simply as <code>npmenv</code> <em>without arguments</em>; after that, you can call dependent CLIs by mere name (<code>mocha ...</code>).</p>
<p>For use case (a), prepend <code>npmenv</code> to your command; e.g.:</p>
<pre class="lang-sh prettyprint-override"><code> npmenv mocha --recursive test/**/*.js --compilers js:babel-register
</code></pre>
<p>Caveat: As noted, the <em>first</em> invocation of <code>npmenv</code> - whether with or without arguments - invariably modifies the <code>%PATH%</code> / <code>$env:PATH</code> variable for the remainder of the session. </p>
<p>If you switch to a different project in the same session, be sure to run <code>npmenv</code> (at least once) again, but note that this prepends <em>additional</em> directories to <code>%PATH%</code>, so you you could still end up accidentally running a previous project's executable if it isn't an installed dependency of the now-current project.</p>
<p>From PowerShell, you could actually <em>combine</em> the two solutions to get distinct (a) and (b) functionality after all: define the <code>*.cmd</code> file above as a distinct command (using a different name such as <code>nx.cmd</code>) that you only use <em>with arguments</em> (a), and redefine the PowerShell function to serve as the argument-less environment modification-only complement (b).<br>
This works, because PowerShell invariably runs <code>*.cmd</code> files in a <em>child</em> process that cannot affect the current PowerShell session's environment.</p>
<hr>
<p><strong>Notes on the scope of the question and this answer:</strong></p>
<p>The OP's question is about calling the CLIs of <em>already-installed dependent packages in the context of a given project</em> ad-hoc, by mere executable name - just as <code>npm</code> allows you to do in the commands added to the <code>scripts</code> key in the <code>package.json</code> file.</p>
<p>The question is <em>not</em> about making CLIs <em>globally available</em> (by installing them with <code>npm install -g</code>).</p>
<p>In fact, if you want to author modular, self-contained packages, do <em>not</em> depend on globally installed packages. Instead, make all dependent packages <em>part of your project</em>: use <code>npm install --save</code> (for runtime dependencies) and <code>npm install --save-dev</code> (for development time-only dependencies) - see <a href="https://docs.npmjs.com/cli/install" rel="noreferrer">https://docs.npmjs.com/cli/install</a></p>
<p>In particular, if a given CLI is already installed as a <em>dependency</em>, installing it globally <em>as well</em> (potentially a different version) is not only redundant, but asking for confusion over which version is executed when.</p> |
23,725,040 | How do i solve this error? Deprecated: mysql_escape_string(): This function is deprecated; use mysql_real_escape_string() instead | <p>I get stuck on the following:</p>
<p>Deprecated: mysql_escape_string(): This function is deprecated; use mysql_real_escape_string() instead. in /home/xtremeso/public_html/mp3/includes/class/_class_mysql.php on line 116</p>
<pre><code> function safesql( $source )
{
if ($this->db_id) return mysqli_real_escape_string ($this->db_id, $source);
else return mysql_escape_string($source);
}
</code></pre>
<p>I already tried to mysql_escape_real_string but that doesnt solve the issue.
And ignoring php error messages via .htacces file doesnt work either</p> | 23,725,057 | 2 | 2 | null | 2014-05-18 17:48:48.95 UTC | 0 | 2014-05-18 18:01:46.233 UTC | null | null | null | null | 3,473,927 | null | 1 | 3 | php|mysql|sql|string|escaping | 40,236 | <p>the error message clearly said it .</p>
<p>change this</p>
<pre><code> else return mysql_escape_string($source); // you are using mysql here
</code></pre>
<p>to</p>
<pre><code> else return mysqli_real_escape_string($source); //will be mysqli
</code></pre>
<p>OBS: you should switch to PDO or MYSQLI as MYSQL <code>mysql_real_escape_string</code> <strong>will also be deprecated :)</strong></p>
<p>you are mixing Between mysqli and mysql .</p>
<p>EDIT: from your second error.</p>
<pre><code> mysqli_real_escape_string ($link ,$source ) // $link is your connection variable
</code></pre>
<p><a href="http://www.php.net/manual/en/mysqli.real-escape-string.php" rel="noreferrer">ref</a></p> |
32,360,687 | Connect to Docker MySQL container from localhost? | <p>I have a docker mysql image running, following is what the docker-compose.yml file looks like:</p>
<pre><code>db:
image: mysql
environment:
MYSQL_ROOT_PASSWORD: ""
MYSQL_ALLOW_EMPTY_PASSWORD: yes
ports:
- "3306:3306"
</code></pre>
<p>This works fine.</p>
<p>My question is: How can I connect to the MySQL instance running on that container from the command line mysql client on my the host (my macbook)?</p>
<p>To clarify:</p>
<ul>
<li>I have a macbook with Docker installed</li>
<li>I have a docker container with mysql</li>
<li>I want to connect to the mysql instance running on the aforementioned container from the Terminal on my macbook</li>
<li>I do NOT want to user a <code>docker</code> command to make this possible. Rather, I want to use the <code>mysql</code> client directly from the Terminal (without tunneling in through a docker container).</li>
</ul>
<p>I don't have MySQL running locally, so port 3306 should be open and ready to use.</p>
<p>The command I am using to start the container is: <code>docker-compose run</code></p> | 32,361,238 | 8 | 3 | null | 2015-09-02 18:34:18.94 UTC | 18 | 2021-01-07 07:22:15.477 UTC | 2015-09-04 22:34:54.073 UTC | null | 507,151 | null | 507,151 | null | 1 | 89 | mysql|macos|docker|docker-compose | 123,478 | <h1>Using <code>docker-compose up</code></h1>
<p>Since you published port <code>3306</code> on your <strong>docker host</strong>, from that host itself you would connect to <code>127.0.0.1:3306</code>. </p>
<h1>Using <code>docker-compose run</code></h1>
<p>In that case the port mapping section of the <code>docker-compose.yml</code> file is ignored. To have the port mapping section considered, you have to add the <a href="https://docs.docker.com/compose/reference/run/#/run"><code>--service-ports</code></a> option: </p>
<pre><code>docker-compose run --service-ports db
</code></pre>
<h1>Additional note</h1>
<p>Beware that by default, the mysql client tries to connect using a unix socket when you tell it to connect to <code>localhost</code>. So do use <code>127.0.0.1</code> and not <code>localhost</code>:</p>
<pre><code> $ mysql -h 127.0.0.1 -P 3306 -u root
</code></pre>
<blockquote>
<p>Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 1
Server version: 5.6.26 MySQL Community Server (GPL)</p>
<p>Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.</p>
<p>Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.</p>
<p>Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.</p>
<p>mysql></p>
</blockquote>
<pre><code>$ mysql -h localhost -P 3306 -u root
</code></pre>
<blockquote>
<p>ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)</p>
</blockquote> |
36,500,968 | OpenJDK 64-Bit Server VM warning: ignoring option MaxPermSize=350m; | <p>When I'mtrying to open Intellij IDE using command line in linux like this <code>./phpstorm.sh</code> both android studio and PHPStorm I always got this message : </p>
<blockquote>
<p>OpenJDK 64-Bit Server VM warning: ignoring option MaxPermSize=350m;
support was removed in 8.0</p>
</blockquote>
<p>and I was wondering if google find solution <a href="https://stackoverflow.com/a/22634689/2652524">here</a> but I was kinda lost here since I'm newbie in ubuntu 14.04. my question is what is the cause of this message to diplay? and how to resolve this?</p>
<p>I've tried using this command <code>export MAVEN_OPTS="-Xmx512m"</code> but it's not resolve the issue.
and I'm using <code>java 1.8.0_73</code> downloaded from <a href="http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html" rel="noreferrer">here</a>. any useful help would be appreciated, thank you.</p> | 36,501,309 | 4 | 3 | null | 2016-04-08 13:33:24.893 UTC | 2 | 2022-06-13 09:09:49.253 UTC | 2017-05-23 11:51:35.887 UTC | null | -1 | null | 2,652,524 | null | 1 | 11 | java|linux|intellij-idea | 112,206 | <p>This is only a warning saying the option has been ignored - so it should not cause any issues.</p>
<p>The JVM options should be located in {IntelliJ folder}/bin/idea64.exe.vmoptions (on windows - probably something similar on linux). You can edit that file and delete the maxpermsize option.</p> |
31,453,681 | Mongo update array element (.NET driver 2.0) | <p>EDIT:
Not looking for the javascript way of doing this. I am looking for the MongoDB C# 2.0 driver way of doing this (I know it might not be possible; but I hope somebody knows a solution).</p>
<p>I am trying to update the value of an item embedded in an array on the primary document in my mongodb.</p>
<p>I am looking for a strongly typed way to do this. I am using the <a href="http://mongodb.github.io/mongo-csharp-driver/2.0/" rel="noreferrer">Mongodb c# 2.0 driver</a></p>
<p>I can do it by popping the element, updating the value, then reinserting. This just doesn't feel right; since I am overwriting what might have been written in the meantime.</p>
<p>Here is what I have tried so far but with no luck:</p>
<pre><code>private readonly IMongoCollection<TempAgenda> _collection;
void Main()
{
var collectionName = "Agenda";
var client = new MongoClient("mongodb://localhost:27017");
var db = client.GetDatabase("Test");
_collection = db.GetCollection<TempAgenda>(collectionName);
UpdateItemTitle(1, 1, "hello");
}
public void UpdateItemTitle(string agendaId, string itemId, string title){
var filter = Builders<TempAgenda>.Filter.Eq(x => x.AgendaId, agendaId);
var update = Builders<TempAgenda>.Update.Set(x => x.Items.Single(p => p.Id.Equals(itemId)).Title, title);
var result = _collection.UpdateOneAsync(filter, update).Result;
}
</code></pre> | 33,720,549 | 3 | 7 | null | 2015-07-16 12:05:44.463 UTC | 8 | 2018-05-28 17:15:02.28 UTC | 2015-07-16 12:14:41.857 UTC | null | 1,387,545 | null | 1,387,545 | null | 1 | 27 | c#|.net|mongodb | 27,158 | <p>Took me a while to figure this out as it doesn't appear to be mentioned in any of the official documentation (or anywhere else). I did however find <a href="https://jira.mongodb.org/browse/CSHARP-531">this</a> on their issue tracker, which explains how to use the positional operator <code>$</code> with the C# 2.0 driver.</p>
<p>This should do what you want:</p>
<pre><code>public void UpdateItemTitle(string agendaId, string itemId, string title){
var filter = Builders<TempAgenda>.Filter.Where(x => x.AgendaId == agendaId && x.Items.Any(i => i.Id == itemId));
var update = Builders<TempAgenda>.Update.Set(x => x.Items[-1].Title, title);
var result = _collection.UpdateOneAsync(filter, update).Result;
}
</code></pre>
<p>Notice that your <code>Item.Single()</code> clause has been changed to <code>Item.Any()</code> and moved to the filter definition.</p>
<p><code>[-1]</code> or <code>.ElementAt(-1)</code> is apparently treated specially (actually everything < 0) and will be replaced with the positional operator <code>$</code>.</p>
<p>The above will be translated to this query:</p>
<pre><code>db.Agenda.update({ AgendaId: 1, Items.Id: 1 }, { $set: { Items.$.Title: "hello" } })
</code></pre> |
69,855,485 | React hooks: Why do several useState setters in an async function cause several rerenders? | <p>This following onClick callback function will cause 1 re-render:</p>
<pre class="lang-js prettyprint-override"><code>const handleClickSync = () => {
// Order of setters doesn't matter - React lumps all state changes together
// The result is one single re-rendering
setValue("two");
setIsCondition(true);
setNumber(2);
};
</code></pre>
<p>React lumps all three state changes together and causes 1 rerender.</p>
<p>The following onClick callback function, however, will cause 3 re-renderings:</p>
<pre class="lang-js prettyprint-override"><code>const handleClickAsync = () => {
setTimeout(() => {
// Inside of an async function (here: setTimeout) the order of setter functions matters.
setValue("two");
setIsCondition(true);
setNumber(2);
});
};
</code></pre>
<p>It's one re-render for every <code>useState</code> setter. Furthermore the order of the setters influences the values in each of these renderings.</p>
<p><strong>Question</strong>: Why does the fact that I make the function async (here via <code>setTimeout</code>) cause the state changes to happen one after the other and thereby causing 3 re-renders. Why does React lump these state changes together if the function is synchronous to only cause one rerender?</p>
<p>You can play around with <a href="https://codesandbox.io/s/react-usestate-setter-in-timeout-1ls9y?file=/src/App.js" rel="noreferrer">this CodeSandBox</a> to experience the behavior.</p> | 69,855,770 | 3 | 2 | null | 2021-11-05 15:15:58.883 UTC | 10 | 2022-08-31 16:32:14.323 UTC | null | null | null | null | 3,210,677 | null | 1 | 30 | javascript|reactjs|react-hooks | 4,218 | <p>In react 17, if code execution starts inside of react (eg, an <code>onClick</code> listener or a <code>useEffect</code>), then react can be sure that after you've done all your state-setting, execution will return to react and it can continue from there. So for these cases, it can let code execution continue, wait for the return, and then synchronously do a single render.</p>
<p>But if code execution starts randomly (eg, in a <code>setTimeout</code>, or by resolving a promise), then code isn't going to return to react when you're done. So from react's perspective, it was quietly sleeping and then you call <code>setState</code>, forcing react to be like "ahhh! they're setting state! I'd better render". There are async ways that react could wait to see if you're doing anything more (eg, a timeout 0 or a microtask), but there isn't a synchronous way for react to know when you're done.</p>
<p>You can tell react to batch multiple changes by using <code>unstable_batchedUpdates</code>:</p>
<pre><code>import { unstable_batchedUpdates } from "react-dom";
const handleClickAsync = () => {
setTimeout(() => {
unstable_batchedUpdates(() => {
setValue("two");
setIsCondition(true);
setNumber(2);
});
});
};
</code></pre>
<p>In version 18 this isn't necessary, since the changes they've made to rendering for concurrent rendering make batching work for all cases.</p> |
57,419,127 | Flutter - How create Container with width match parent? | <p>I use this simple widget in my Flutter app:</p>
<pre><code> FlatButton(
child: Column(
children: <Widget>[
Image.asset(assets, height: 40, width: 40),
Text('Title'),
//my color line
Container(
height: 5,
width: ?,
color: Colors.blue[800],
)
],
)
)
</code></pre>
<p>I need color line (in buttom), with width match parent. but I don’t know how to do it.</p> | 57,421,620 | 4 | 2 | null | 2019-08-08 18:59:09.07 UTC | 2 | 2020-09-23 10:23:52.27 UTC | null | null | null | null | 631,843 | null | 1 | 40 | flutter|dart | 61,670 | <p>Use <a href="https://api.flutter.dev/flutter/widgets/IntrinsicWidth-class.html" rel="noreferrer">IntrinsicWidth</a></p>
<pre><code> FlatButton(
child: IntrinsicWidth(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Image.asset(assets, height: 40, width: 40),
Text('Title'),
//my color line
Container(
height: 5,
width: ?,
color: Colors.blue[800],
)
],
))
)
</code></pre>
<p><a href="https://medium.com/flutter-community/flutter-layout-cheat-sheet-5363348d037e" rel="noreferrer">Some cheatsheet</a></p> |
7,419,194 | What is the best way of adding a greater than 0 validator on the client-side using MVC and data annotation? | <p>I'd like to be able to only allow a form to submit if the value in a certain field is greater than 0. I thought maybe the Mvc Range attribute would allow me to enter only 1 value to signify only a greater than test, but no luck there as it insists on Minimum AND Maximum values.</p>
<p>Any ideas how this can be achieved?</p> | 7,419,330 | 4 | 1 | null | 2011-09-14 15:47:27.517 UTC | 5 | 2022-03-04 16:26:45.58 UTC | null | null | null | null | 306,098 | null | 1 | 128 | asp.net-mvc|unobtrusive-validation | 119,784 | <p>You can't store a number bigger than what your underlying data type could hold so that fact that the Range attribute requires a max value is a very good thing. Remember that <code>∞</code> doesn't exist in the real world, so the following should work:</p>
<pre><code>[Range(1, int.MaxValue, ErrorMessage = "Please enter a value bigger than {1}")]
public int Value { get; set; }
</code></pre> |
7,907,067 | Difference between Action(arg) and Action.Invoke(arg) | <pre><code>static void Main()
{
Action<string> myAction = SomeMethod;
myAction("Hello World");
myAction.Invoke("Hello World");
}
static void SomeMethod(string someString)
{
Console.WriteLine(someString);
}
</code></pre>
<p>The output for the above is:</p>
<pre><code>Hello World
Hello World
</code></pre>
<p>Now my question(s) is</p>
<ul>
<li><p>What is the difference between the two ways to call the Action, if any? </p></li>
<li><p>Is one better than the other? </p></li>
<li><p>When use which?</p></li>
</ul>
<p>Thanks </p> | 7,907,079 | 1 | 0 | null | 2011-10-26 18:19:57.437 UTC | 4 | 2011-10-26 18:20:53.557 UTC | null | null | null | null | 321,035 | null | 1 | 38 | c# | 8,192 | <p>All delegate types have a compiler-generated <code>Invoke</code> method.<br>
C# allows you to call the delegate itself as a shortcut to calling this method.</p>
<p>They both compile to the same IL:</p>
<h3>C#:</h3>
<pre><code>Action<string> x = Console.WriteLine;
x("1");
x.Invoke("2");
</code></pre>
<h3>IL:</h3>
<pre><code>IL_0000: ldnull
IL_0001: ldftn System.Console.WriteLine
IL_0007: newobj System.Action<System.String>..ctor
IL_000C: stloc.0
IL_000D: ldloc.0
IL_000E: ldstr "1"
IL_0013: callvirt System.Action<System.String>.Invoke
IL_0018: ldloc.0
IL_0019: ldstr "2"
IL_001E: callvirt System.Action<System.String>.Invoke
</code></pre>
<p>(The <code>ldnull</code> is for the <code>target</code> parameter in an <a href="http://blog.slaks.net/2011/06/open-delegates-vs-closed-delegates.html" rel="noreferrer">open delegate</a>)</p> |
1,543,652 | Python gzip: is there a way to decompress from a string? | <p>I've read this <a href="https://stackoverflow.com/questions/1313845/if-i-have-the-contents-of-a-zipfile-in-a-python-string-can-i-decompress-it-witho">SO post</a> around the problem to no avail.</p>
<p>I am trying to decompress a .gz file coming from an URL.</p>
<pre><code>url_file_handle=StringIO( gz_data )
gzip_file_handle=gzip.open(url_file_handle,"r")
decompressed_data = gzip_file_handle.read()
gzip_file_handle.close()
</code></pre>
<p>... but I get <em>TypeError: coercing to Unicode: need string or buffer, cStringIO.StringI found</em></p>
<p>What's going on?</p>
<pre><code>Traceback (most recent call last):
File "/opt/google/google_appengine-1.2.5/google/appengine/tools/dev_appserver.py", line 2974, in _HandleRequest
base_env_dict=env_dict)
File "/opt/google/google_appengine-1.2.5/google/appengine/tools/dev_appserver.py", line 411, in Dispatch
base_env_dict=base_env_dict)
File "/opt/google/google_appengine-1.2.5/google/appengine/tools/dev_appserver.py", line 2243, in Dispatch
self._module_dict)
File "/opt/google/google_appengine-1.2.5/google/appengine/tools/dev_appserver.py", line 2161, in ExecuteCGI
reset_modules = exec_script(handler_path, cgi_path, hook)
File "/opt/google/google_appengine-1.2.5/google/appengine/tools/dev_appserver.py", line 2057, in ExecuteOrImportScript
exec module_code in script_module.__dict__
File "/home/jldupont/workspace/jldupont/trunk/site/app/server/tasks/debian/repo_fetcher.py", line 36, in <module>
main()
File "/home/jldupont/workspace/jldupont/trunk/site/app/server/tasks/debian/repo_fetcher.py", line 30, in main
gziph=gzip.open(fh,'r')
File "/usr/lib/python2.5/gzip.py", line 49, in open
return GzipFile(filename, mode, compresslevel)
File "/usr/lib/python2.5/gzip.py", line 95, in __init__
fileobj = self.myfileobj = __builtin__.open(filename, mode or 'rb')
TypeError: coercing to Unicode: need string or buffer, cStringIO.StringI found
</code></pre> | 1,543,665 | 4 | 3 | null | 2009-10-09 13:09:12.133 UTC | 6 | 2020-11-03 08:37:25.767 UTC | 2017-05-23 12:32:13.693 UTC | Roger Pate | -1 | null | 171,461 | null | 1 | 36 | python|gzip | 53,158 | <p><code>gzip.open</code> is a shorthand for opening a file, what you want is <code>gzip.GzipFile</code> which you can pass a fileobj</p>
<pre><code>open(filename, mode='rb', compresslevel=9)
#Shorthand for GzipFile(filename, mode, compresslevel).
</code></pre>
<p>vs</p>
<pre><code>class GzipFile
__init__(self, filename=None, mode=None, compresslevel=9, fileobj=None)
# At least one of fileobj and filename must be given a non-trivial value.
</code></pre>
<p>so this should work for you</p>
<pre><code>gzip_file_handle = gzip.GzipFile(fileobj=url_file_handle)
</code></pre> |
2,046,741 | The requested Performance Counter is not a custom counter, it has to be initialized as ReadOnly | <p>I am getting repeated errors about the ReadOnly property on performance counters whenever I try to debug a .NET windows service app. This app works fine on x86 windows vista, or x86 windows 2003. It's just stopped working on my new 64bit dev machine. </p>
<p>I've run the relevant InstallUtil invocations on 64bit and 32bit command line VCVARS.bat, in admin mode. I get <strong><em>no errors setting up the category and each perf counter</em></strong>. But, regardless of whether I set the perf ctrs as readonly or not, I get this:</p>
<blockquote>
<p>The requested Performance Counter is
not a custom counter, it has to be
initialized as ReadOnly.</p>
</blockquote>
<p><strong>UPDATE</strong></p>
<p>I re-installed the machine with a 32bit version of Windows 7, and bizarrely I still get this error. The only thing that has changed is moving from Windows Vista Business to Windows 7 Professional. Does this ring any bells?</p> | 2,081,976 | 4 | 2 | null | 2010-01-12 04:35:22.043 UTC | 9 | 2019-01-05 05:58:27.347 UTC | 2010-01-15 01:30:00.43 UTC | null | 101,260 | null | 101,260 | null | 1 | 40 | .net|windows-7|.net-3.5|performancecounter | 44,506 | <p>This is due to the performance counter (or category) <a href="http://rengberg.blogspot.com/2007/05/requested-performance-counter-is-not.html" rel="noreferrer">not existing</a>,
but with a horrible error message.</p>
<p>Take a look in perfmon for the counter, it should be missing on the relevant machines.</p>
<p>I find this happens to the .Net perf counters sometimes (no idea why) but <a href="http://blogs.msdn.com/mikedodd/archive/2004/10/17/243799.aspx" rel="noreferrer">using lodctr</a><sup>1</sup> gets them back. If you indicate which perf counter you are trying to get at we might be able to give you more help.</p>
<ol>
<li>Note that the example lined is for .Net 1.1, adjust for different frameworks accordingly.</li>
</ol> |
10,332,546 | Truncate a float and a double in java | <p>I want to truncate a float and a double value in java.</p>
<p>Following are my requirements:
1. if i have 12.49688f, it should be printed as 12.49 without rounding off
2. if it is 12.456 in double, it should be printed as 12.45 without rounding off
3. In any case if the value is like 12.0, it should be printed as 12 only.</p>
<p>condition 3 is to be always kept in mind.It should be concurrent with truncating logic.</p> | 10,332,818 | 6 | 2 | null | 2012-04-26 11:33:33.157 UTC | 5 | 2017-08-18 09:45:37.307 UTC | 2012-05-15 13:21:40.183 UTC | null | 44,390 | null | 1,211,036 | null | 1 | 13 | java|floating-point|double|truncate | 58,120 | <p>try this out-</p>
<pre><code>DecimalFormat df = new DecimalFormat("##.##");
df.setRoundingMode(RoundingMode.DOWN);
System.out.println(df.format(12.49688f));
System.out.println(df.format(12.456));
System.out.println(df.format(12.0));
</code></pre>
<p>Here, we are using decimal formatter for formating. The roundmode is set to DOWN, so that it will not auto-round the decimal place.</p>
<p>The expected result is:</p>
<pre><code>12.49
12.45
12
</code></pre> |
10,766,900 | Is there a REPL for C programming? | <p>I am on osx. I found this
<a href="http://neugierig.org/software/c-repl/" rel="noreferrer">http://neugierig.org/software/c-repl/</a>
but the links on that page for code seem to be broken.</p> | 10,766,935 | 3 | 2 | null | 2012-05-26 14:02:31.977 UTC | 25 | 2020-07-17 15:37:10.553 UTC | null | null | null | null | 70,551 | null | 1 | 55 | c|read-eval-print-loop | 27,940 | <p>Seems like the code of <em>c-repl</em> can now be found at a <a href="https://github.com/martine/c-repl" rel="noreferrer">Github repository</a>. It seems to be a dead project, though (last commit was 3 years ago), so I'd suggest looking into alternatives as well:</p>
<ul>
<li>CINT <a href="https://web.archive.org/web/20200504034257/http://root.cern.ch/cint" rel="noreferrer">Archived old official page from web.archive.org</a> or <a href="http://www.hanno.jp/gotom/Cint.html" rel="noreferrer">"Masaharu Goto" CINT page</a></li>
<li>ccons <a href="https://github.com/asvitkine/ccons" rel="noreferrer">Github</a> or <a href="http://code.google.com/p/ccons/" rel="noreferrer">code.google</a></li>
<li><a href="https://root.cern/cling/" rel="noreferrer">Cling</a>, successor of CINT, but only supports C++ (which might or might not be a problem, depending on what features you need)</li>
</ul> |
72,843,016 | "if" statement syntax differences between C and C++ | <pre class="lang-cpp prettyprint-override"><code>if (1) int a = 2;
</code></pre>
<p>This line of code is valid C++ code (it compiles at the very least) yet invalid C code (doesn't compile). I know there are differences between the languages but this one was unexpected.</p>
<p>I always thought the grammar was</p>
<pre><code>if (expr) statement
</code></pre>
<p>but this would make it valid in both.</p>
<p>My questions are:</p>
<ol>
<li>Why doesn't this compile in C?</li>
<li>Why does this difference exist?</li>
</ol> | 72,843,033 | 4 | 9 | null | 2022-07-02 23:17:27.42 UTC | 8 | 2022-08-01 06:41:41.92 UTC | 2022-07-26 18:45:21.167 UTC | null | 5,784,757 | null | 9,513,499 | null | 1 | 93 | c++|c|language-lawyer|cross-language | 7,927 | <p>This is a subtle and important difference between C and C++. In C++ <em>any</em> statement may be a <em>declaration-statement</em>. In C, there is no such thing as a <em>declaration-statement</em>; instead, a <em>declaration</em> can appear instead of a <em>statement</em> within any <em>compound-statement</em>.</p>
<p>From the C grammar (C17 spec):</p>
<blockquote>
<p><em>compound-statement</em>: "{" <em>block-item-list</em><sub>opt</sub> "}"<br/>
<em>block-item-list</em>: <em>block-item</em> | <em>block-item-list</em> <em>block-item</em><br/>
<em>block-item</em>: <em>declaration</em> | <em>statement</em></p>
</blockquote>
<p>From the C++ grammar (C++14 spec):</p>
<blockquote>
<p><em>compound-statement</em>:
"{" <em>statement-seq</em><sub>opt</sub> "}"<br/>
<em>statement-seq</em>:
<em>statement</em> |
<em>statement-seq</em> <em>statement</em><br/>
<em>statement</em>: ... | <em>declaration-statement</em> | ...</p>
</blockquote>
<p>It is not clear <em>why</em> this difference exists, it is just the way the languages evolved. The C++ syntax dates all the way back to (at least) C++85. The C syntax was introduced sometime between C89 and C99 (in C89, declarations had to be at the beginning of a block)</p>
<hr />
<p>In the original 85 and 89 versions of C++, the scope of a variable defined in a <em>declaration-statement</em> was "until the end of the enclosing <em>block</em>"). So a declaration in an <code>if</code> like this would not immediately go out of scope (as it does in more recent versions) and instead would be in scope for statements following the if in the same block scope. This could lead to problems with accessing uninitialized data when the condition is false. Worse, if the var had a non-trivial destructor, that would be called when the scope ended, even if it had never been initialized! I suspect trying to avoid these kinds of problems is what led to C adopting a different syntax.</p> |
26,158,916 | Filter by regex example | <p>Could anyone provide an example of a regex filter for the Google Chrome Developer toolbar?</p>
<p>I especially need exclusion. I've tried many regexes, but somehow they don't seem to work:</p>
<p><img src="https://i.stack.imgur.com/u9Ipx.png" alt="enter image description here"></p> | 34,276,348 | 4 | 1 | null | 2014-10-02 10:27:26.957 UTC | 16 | 2020-03-10 14:38:00.557 UTC | 2018-07-26 21:35:17.733 UTC | null | 3,359,687 | null | 1,731,095 | null | 1 | 86 | regex|google-chrome-devtools | 32,231 | <p>It turned out that Google Chrome actually didn't support this until early 2015, <a href="https://code.google.com/p/chromium/issues/detail?can=2&q=375633&colspec=ID%20Pri%20M%20Iteration%20ReleaseBlock%20Cr%20Status%20Owner%20Summary%20OS%20Modified&id=375633" rel="noreferrer">see Google Code issue</a>. With newer versions it works great, for example excluding everything that contains <code>banners</code>:</p>
<pre><code>/^(?!.*?banners)/
</code></pre> |
7,632,126 | Maximum size of HashSet, Vector, LinkedList | <p>What is the maximum size of <code>HashSet</code>, <code>Vector</code>, <code>LinkedList</code>? I know that <code>ArrayList</code> can store more than 3277000 numbers.</p>
<p>However the size of list depends on the memory (heap) size. If it reaches maximum the JDK throws an <code>OutOfMemoryError</code>.</p>
<p>But I don't know the limit for the number of elements in <code>HashSet</code>, <code>Vector</code> and <code>LinkedList</code>.</p> | 7,632,240 | 5 | 0 | null | 2011-10-03 07:25:47.833 UTC | 17 | 2020-06-26 08:47:41.037 UTC | 2011-10-22 09:42:42.383 UTC | null | 40,342 | null | 827,583 | null | 1 | 31 | java|collections | 52,032 | <p>There is no specified maximum size of these structures.</p>
<p>The actual practical size limit is probably somewhere in the region of <code>Integer.MAX_VALUE</code> (i.e. 2147483647, roughly 2 billion elements), as that's the maximum size of an array in Java.</p>
<ul>
<li>A <code>HashSet</code> uses a <code>HashMap</code> internally, so it has the same maximum size as that
<ul>
<li>A <code>HashMap</code> uses an array which always has a size that is a power of two, so it can be at most 2<sup>30</sup> = 1073741824 elements big (since the next power of two is bigger than <code>Integer.MAX_VALUE</code>).</li>
<li><em>Normally</em> the number of elements is at most the number of buckets multiplied by the load factor (0.75 by default). <em>However</em>, when the <code>HashMap</code> stops resizing, then it will <em>still</em> allow you to add elements, exploiting the fact that each bucket is managed via a linked list. Therefore the only limit for elements in a <code>HashMap</code>/<code>HashSet</code> is memory.</li>
</ul></li>
<li>A <code>Vector</code> uses an array internally which has a maximum size of exactly <code>Integer.MAX_VALUE</code>, so it can't support more than that many elements</li>
<li>A <code>LinkedList</code> <em>doesn't</em> use an array as the underlying storage, so that doesn't limit the size. It uses a classical doubly linked list structure with no inherent limit, so its size is <em>only</em> bounded by the available memory. Note that a <code>LinkedList</code> will report the size wrongly if it is bigger than <code>Integer.MAX_VALUE</code>, because it uses a <code>int</code> field to store the size and the return type of <code>size()</code> is <code>int</code> as well.</li>
</ul>
<p>Note that while the <a href="http://download.oracle.com/javase/7/docs/api/java/util/Collection.html" rel="noreferrer"><code>Collection</code></a> API <em>does</em> define how a <code>Collection</code> with more than <code>Integer.MAX_VALUE</code> elements should behave. Most importantly it states this <a href="http://download.oracle.com/javase/7/docs/api/java/util/Collection.html#size%28%29" rel="noreferrer">the <code>size()</code> documentation</a>:</p>
<blockquote>
<p>If this collection contains more than <code>Integer.MAX_VALUE</code> elements, returns <code>Integer.MAX_VALUE</code>.</p>
</blockquote>
<p>Note that while <code>HashMap</code>, <code>HashSet</code> and <code>LinkedList</code> <em>seem</em> to support more than <code>Integer.MAX_VALUE</code> elements, <em>none</em> of those implement the <code>size()</code> method in this way (i.e. they simply let the internal <code>size</code> field overflow).</p>
<p>This leads me to believe that other operations <em>also</em> aren't well-defined in this condition.</p>
<p>So I'd say it's <strong>safe</strong> to use those general-purpose collections with <em>up to</em> <code>Integer.MAX_VLAUE</code> elements. If you <em>know</em> that you'll need to store more than that, then you should switch to dedicated collection implementations that actually support this.</p> |
7,266,596 | Why avoid subtyping? | <p>I have seen many people in the Scala community advise on avoiding subtyping "like a plague". What are the various reasons against the use of subtyping? What are the alternatives?</p> | 8,352,969 | 8 | 0 | null | 2011-09-01 06:03:33.627 UTC | 25 | 2014-09-01 19:52:54.563 UTC | null | null | null | null | 192,247 | null | 1 | 35 | oop|scala|programming-languages|functional-programming | 4,411 | <p>Types determine the granularity of composition, i.e. of extensibility.</p>
<p>For example, an interface, e.g. Comparable, that combines (thus conflates) equality and relational operators. Thus it is impossible to compose on just one of the equality or relational interface.</p>
<p>In general, the <a href="https://stackoverflow.com/a/8279878">substitution principle</a> of inheritance is undecidable. Russell's paradox implies that any set that is extensible (i.e. does not enumerate the type of every possible member or subtype), can include itself, i.e. is a subtype of itself. But in order to identify (decide) what is a subtype and not itself, the invariants of itself must be completely enumerated, thus it is no longer extensible. This is the paradox that subtyped extensibility makes inheritance undecidable. This paradox must exist, else knowledge would be static and thus <a href="https://stackoverflow.com/a/8279878">knowledge formation wouldn't exist</a>.</p>
<p>Function composition is the surjective substitution of subtyping, because the input of a function can be substituted for its output, i.e. any where the output type is expected, the input type can be substituted, by wrapping it in the function call. But composition does not make the bijective contract of subtyping-- accessing the interface of the output of a function, does not access the input instance of the function.</p>
<p>Thus composition does not have to maintain the <strong>future</strong> (i.e. unbounded) invariants and thus can be both extensible and decidable. Subtyping can be <strong>MUCH</strong> more powerful where it is provably decidable, because it maintains this bijective contract, e.g. a function that sorts a immutable list of the supertype, can operate on the immutable list of the subtype.</p>
<p>So the conclusion is to enumerate all the invariants of each type (i.e. of its interfaces), make these types orthogonal (maximize granularity of composition), and then use function composition to accomplish extension where those invariants would not be orthogonal. Thus a subtype is appropriate only where it provably models the invariants of the supertype interface, and the additional interface(s) of the subtype are provably orthogonal to the invariants of the supertype interface. Thus the invariants of interfaces should be orthogonal.</p>
<p>Category theory <a href="https://stackoverflow.com/a/7397388">provides rules for the model</a> of the invariants of each subtype, i.e. of Functor, Applicative, and Monad, which <a href="https://stackoverflow.com/a/2704795">preserve function composition on lifted types</a>, i.e. see the aforementioned example of the power of subtyping for lists.</p> |
7,668,047 | How can I get jQuery DataTables to sort on hidden value, but search on displayed value? | <p>I have a simple DataTables grid which contains date columns. I have provided two values for the date in my JSON data set, one for display and one specifically designed so that DataTables can sort it. My web application allows users to choose a bunch of different date formats, so it needs to be flexible.</p>
<p>This is my JSON data that DataTables gets from from the web server via <code>sAjaxSource</code>.</p>
<pre><code>{
Reports : [
{ Date: { Sort = "20101131133000", Display : "11/31/2010 1:30 PM" } },
{ Date: { Sort = "20100912120000", Display : "1200 EST 2010-09-12" } },
]
}
</code></pre>
<p>It is easy to tell DataTables to sort based on the <code>Date.SortValue</code> property and to make the <code>Display</code> property visible to the user by using <code>fnRender()</code>. So this gets me halfway to my goal.</p>
<pre><code>var dataTableConfig = {
sAjaxSource: "/getreports",
sAjaxDataProp: "Reports",
aoColumns: [
{ mDataProp: "User" },
{ mDataProp: "Date.Sort",
bSortable: true,
sName: "Date",
bUseRendered: false,
fnRender: function (oObj) {
return oObj.aData[oObj.oSettings.aoColumns[oObj.iDataColumn].sName].Display;
}
}
]
};
</code></pre>
<p><em><strong>Here's my problem.</em></strong> I want to allow the user to enter a filter (using the built-in filter input that DataTables provides) based on the displayed value, but they cannot.</p>
<p>For example. If a user entered "EST", they would get zero results because datatables filters based on the value specified in <code>mDataProp</code> not based on the value returned from <code>fnRender</code>.</p>
<p>Can anyone help me figure out how to sort AND filter a date column? Thanks.</p> | 19,783,592 | 9 | 4 | null | 2011-10-05 21:37:13.98 UTC | 9 | 2019-09-18 06:32:09.117 UTC | 2011-10-05 22:05:29.89 UTC | null | 5,651 | null | 5,651 | null | 1 | 42 | jquery|jquery-plugins|datatables | 53,414 | <p>This is an old post, but hopefully this will help someone else that comes here.</p>
<p>In a more recent version of DataTables, <code>bUseRendered</code> and <code>fnRender</code> are deprecated.</p>
<p><a href="http://datatables.net/reference/option/columns.render"><code>mRender</code></a> is the new way of doing this sort of thing and has a slightly different approach.</p>
<p>You can solve your issue with something along the lines of:</p>
<pre><code>...
{ mDataProp: "Date.Sort"
bSortable: true,
sName: "Date",
// this will return the Display value for everything
// except for when it's used for sorting,
// which then it will use the Sort value
mRender: function (data, type, full) {
if(type == 'sort') return data.Sort;
return data.Display
}
}
...
</code></pre> |
7,253,803 | How to get everything after last slash in a URL? | <p>How can I extract whatever follows the last slash in a URL in Python? For example, these URLs should return the following:</p>
<pre><code>URL: http://www.test.com/TEST1
returns: TEST1
URL: http://www.test.com/page/TEST2
returns: TEST2
URL: http://www.test.com/page/page/12345
returns: 12345
</code></pre>
<p>I've tried urlparse, but that gives me the full path filename, such as <code>page/page/12345</code>.</p> | 7,253,830 | 14 | 5 | null | 2011-08-31 07:23:22.423 UTC | 31 | 2022-01-09 07:22:29.37 UTC | 2015-12-21 04:01:41.327 UTC | null | 5,299,236 | null | 348,496 | null | 1 | 148 | python|parsing|url | 151,548 | <p>You don't need fancy things, just see <a href="http://docs.python.org/py3k/library/stdtypes.html#str.rsplit" rel="noreferrer">the string methods in the standard library</a> and you can easily split your url between 'filename' part and the rest:</p>
<pre><code>url.rsplit('/', 1)
</code></pre>
<p>So you can get the part you're interested in simply with:</p>
<pre><code>url.rsplit('/', 1)[-1]
</code></pre> |
14,053,885 | Integer Partition (algorithm and recursion) | <p>Finding how many combinations of a sum number (the variable <strong>n</strong> in code). For ex.:</p>
<blockquote>
<p>3 = 1+1+1 = 2+1 = 3 => ANS is 3</p>
<p>5 = 5 = 4+1 = 3+2 = 3+1+1 = 2+2+1 = 2+1+1+1 = 1+1+1+1+1 => ANS is 7</p>
</blockquote>
<p>In the following example, <strong>m</strong> is the max number and <code>n</code> is sum,
the aim is to find how many (sum) combination does it have.</p>
<p>I just want to know why do <code>p(n, m) = p(n, m - 1) + p(n - m, m)</code> ?</p>
<p>The code here:</p>
<pre><code>int p (int n, int m)
{
if (n == m)
return 1 + p(n, m - 1);
if (m == 0 || n < 0)
return 0;
if (n == 0 || m == 1)
return 1;
return p(n, m - 1) + p(n - m, m);
}
</code></pre>
<p>Appreciated!</p> | 18,367,427 | 4 | 5 | null | 2012-12-27 11:23:48.433 UTC | 10 | 2021-05-05 05:42:14.81 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 1,778,681 | null | 1 | 25 | algorithm|recursion|integer-partition | 23,305 | <p>Consider all ways of resulting <code>n</code> by adding some numbers less than or equal to <code>m</code>. As you said, we call this <code>p(n,m)</code>. For example, p(7,3)=8 because there are 8 ways to make 7 out of numbers less than 3 as listed below: (For simplicity we can assume that always we add numbers in order from greatest to least)</p>
<ul>
<li>3+3+1</li>
<li>3+2+2</li>
<li>3+2+1+1</li>
<li>3+1+1+1+1</li>
<li>2+2+2+1</li>
<li>2+2+1+1+1</li>
<li>2+1+1+1+1+1</li>
<li>1+1+1+1+1+1+1</li>
</ul>
<p>Now we can split these combinations in two groups:</p>
<ol>
<li><p>Combinations whose first element is equal to <code>m</code>(=3 in our example:)</p>
<ul>
<li>3+3+1</li>
<li>3+2+2</li>
<li>3+2+1+1</li>
<li>3+1+1+1+1</li>
</ul></li>
<li><p>Combinations whose first element is less than <code>m</code>:</p>
<ul>
<li>2+2+2+1</li>
<li>2+2+1+1+1</li>
<li>2+1+1+1+1+1</li>
<li>1+1+1+1+1+1+1</li>
</ul></li>
</ol>
<p>Because every member of combinations of <code>p(n,m)</code> will be either in Group1 or in Group2, we can say <code>p(n,m)=size(Group1) + size(Group2)</code>. Now if we prove that <code>size(Group1)=p(n-m, m)</code> and <code>size(Group2)=p(n,m-1)</code> by substitution we reach <code>p(n,m)=p(n-m,m)+p(n,m-1)</code></p>
<h3>Prove for <code>size(Group1)=p(n-m, m)</code>:</h3>
<p>By aforementioned definition <code>p(n-m, m)</code> is number of ways of resulting <code>n-m</code> by adding some numbers less than or equal to <code>m</code>.</p>
<ul>
<li>If you append <code>m</code> to each combination of <code>p(n-m, m)</code>, it will result a member of Group1. so <code>p(n-m, m) <= size(Group1)</code></li>
<li>If you remove first <code>m</code> of each member of Group1, it will result a combination for <code>p(n-m, m)</code>. so <code>size(Group1) <= p(n-m, m)</code></li>
</ul>
<p><code>=> size(Group1) = p(n-m, m)</code>. In our example:</p>
<p>Group1 <===correspondence===> p(4, 3) :</p>
<ul>
<li>7=3+<code>3+1</code> <===========> <code>3+1</code>=4</li>
<li>7=3+<code>2+2</code> <===========> <code>2+2</code>=4</li>
<li>7=3+<code>2+1+1</code> <=======> <code>2+1+1</code>=4</li>
<li>7=3+<code>1+1+1+1</code> <===> <code>1+1+1+1</code>=4</li>
</ul>
<p>So there is one to one correspondence between any member of <code>p(n-m,m)</code> and Group1 and their size is equal.</p>
<h3>Prove for <code>size(Group2)=p(n, m-1)</code>:</h3>
<p>By definition, <code>p(n,m-1)</code> is the number of ways to result <code>n</code> by adding some numbers less than or equal to <code>m-1</code> (less than <code>m</code>). If you re-read the definition of Group2, you will see that these two definitions are same as each other. <code>=> size(Group2) = p(n, m-1)</code></p> |
13,819,734 | Unable to get a generic ResponseEntity<T> where T is a generic class "SomeClass<SomeGenericType>" | <p>Please help me to get a <code>ResponseEntity<T></code> where <code>T</code> is itself a generic type. As I see it of now, this is not supported nowdays by spring RestTemplate. I'm using Spring MVC version 3.1.2</p>
<p>Here is my code, that I want to use:
Code:</p>
<pre><code>ResponseEntity<CisResponse<CisResponseEntity>> res =
this.restTemplate.postForEntity(
this.rootURL, myRequestObj, CisResponse.class);
</code></pre>
<p>I'm getting this error:</p>
<pre><code>Type mismatch: cannot convert from ResponseEntity<CisResponse> to
ResponseEntity<CisResponse<CisResponseEntity>>
</code></pre>
<p>It's obvious error, but how I can workaround it today?</p>
<p>Than I do want to get my generic response type:</p>
<pre><code>CisResponse<CisResponseEntity> myResponse= res.getBody();
CisResponseEntity entity = myResponse.getEntityFromResponse();
</code></pre>
<p>For now, I use this solution, with <code>postForObject()</code> and not <code>postForEntity()</code>:</p>
<pre><code>CisResponse<CisResponseEntity> response =
this.restTemplate.postForObject(
this.rootURL,myRequestObj, CisResponse.class);
</code></pre> | 13,820,584 | 1 | 0 | null | 2012-12-11 11:47:31.977 UTC | 8 | 2015-08-18 12:55:43.27 UTC | 2012-12-11 12:49:59.273 UTC | null | 315,306 | null | 1,476,774 | null | 1 | 30 | java|spring|rest|generics|spring-mvc | 20,490 | <p>This was <a href="https://jira.springsource.org/browse/SPR-7023">a known issue</a>. Now it's fixed with the introduction of <code>ParameterizedTypeReference</code>, which is a parameterized type that you explicitely <strong>inherit</strong> to supply type information at runtime. This is called a <em>super-type token</em>, and works around type erasure because subclasses (anoniymous in this case) keep the <strong>type arguments of the generic supertype</strong> at runtime.</p>
<p>However you can't use <code>postForObject</code>, because the API only supports <a href="http://static.springsource.org/spring/docs/3.2.0.BUILD/api/org/springframework/web/client/RestTemplate.html"><code>exchange()</code></a>:</p>
<pre><code>ResponseEntity<CisResponse<CisResponseEntity>> res = template.exchange(
rootUrl,
HttpMethod.POST,
null,
new ParameterizedTypeReference<CisResponse<CisResponseEntity>>() {});
</code></pre>
<p>Note that the last line demonstrates the idea of <a href="http://gafter.blogspot.it/2006/12/super-type-tokens.html">super type tokens</a>: you don't supply the literal <code>CisResponse.class</code>, but an anonymous instantiation of the parameterized type <code>ParameterizedTypeReference<T></code>, which at runtime can be expected to extract subtype information. You can think of super type tokens as <em>hacks</em> for achieving <code>Foo<Bar<Baz>>.class</code></p>
<p>BTW, in Java you don't need to prefix access to instance variable with <code>this</code>: if your object defines a <code>url</code> and <code>template</code> members, just access them with their simple name, and not by prefixing like you do <code>this.url</code> and <code>this.template</code></p> |
14,241,900 | Should an Angular service have state? | <p>Recently some co-workers and I were having a discussion as to whether or not AngularJS services should have state or not. We came up with some arguments for and against it and I wanted to get additional thoughts and feedback on the subject. In my searching I found <a href="https://groups.google.com/forum/#!msg/angular/k3FSnv8IJNU/zptmyFWoRsQJ">this</a> but there doesn't seem to be any clear best-practice mentioned. In the none client-side world a service should never hold state, but I am starting to think that it might be acceptable client-side because its a different problem. </p>
<p><strong>Reasons for services holding state:</strong></p>
<ol>
<li>The service isn't going to be accessed by multiple threads. Each browser will have its own instance of the service.</li>
<li>Allows the service to hold the state only it cares about instead of storing it in the rootScope. encapsulates</li>
</ol>
<p><strong>Reasons for services to not hold state:</strong></p>
<ol>
<li>Services are no longer idempotent. Calling functions may change state and therefore may have different results when calling it based upon the state of the service.</li>
<li>I would think that overall this would be easier to test.</li>
</ol>
<p>One way that might address #2 in the "for services holding state" section would be to have an appState object set on the rootScope that contains the current state of the application. Then all the state would be gathered in one location and then you just pull what you need out of it in your service. I found this and wondered</p> | 14,243,586 | 4 | 0 | null | 2013-01-09 16:35:11.357 UTC | 3 | 2014-12-17 07:57:56.827 UTC | null | null | null | null | 379,122 | null | 1 | 30 | service|angularjs|state | 13,724 | <p>In AngularJS, services <a href="http://code.angularjs.org/1.2.16/docs/guide/services" rel="nofollow noreferrer">are passed in via factory function</a>. And basically they are objects that can contain some state (e.g. for caching or storing data needed for performing their actions).</p>
<p>One good solution that can take both cons of having/not having state is when service (that could be actually function) that return object that contain state.</p>
<p>Take a look at the <code>$http</code> service: you can get instance of this service calling</p>
<pre><code>var x = $http({url:'...'});
</code></pre>
<p>And then call by</p>
<pre><code>var result = x.get() //actually `$http.get` is shortcut of this operation
</code></pre>
<p>Same with <code>ngResource</code>: using service you get object with some state that can perform desired actions.</p>
<p>So basically I think that is the best option: from one point you avoid 'side effects' by moving state that could be modified by actions into separate object, not stored in service itself, but can have specific state in that object to be able to store custom info (like auth information etc). </p> |
13,811,889 | Cannot find libcrypto in Ubuntu | <p>I want to try one program which have makefile on it but when I put <code>make</code> in the shell the error was:</p>
<pre><code> g++ -g -DaUNIX -I../../acroname/aInclude -I../../acroname/aSource -Wl,-rpath,. unix_aLaserDemo_Data/aLaserDemo.o unix_aLaserDemo_Data/acpLaser.o -lpthread -lcrypto -lssl -o ../../acroname/aBinary/aLaserDemo
/usr/bin/ld: cannot find -lcrypto
collect2: ld returned 1 exit status
</code></pre>
<p>Here is the makefile:</p>
<pre><code> CC = g++
CFLAGS = -DaUNIX -I../../acroname/aInclude -I../../acroname/aSource
LFLAGS = -Wl,-rpath,.
SRC = ../../acroname/aSource
BIN = ../../acroname/aBinary
LIBS = -lpthread -lcrypto -lssl \
#LIBS = -lpthread\
-L../../acroname/aBinary -l aUtil -l aIO
OBJ = unix_aLaserDemo_Data
.PHONY : app
app : $(OBJ) $(BIN)/aLaserDemo
$(OBJ) :
mkdir $(OBJ)
$(BIN)/aLaserDemo : $(OBJ)/aLaserDemo.o $(OBJ)/acpLaser.o
$(CC) -g $(CFLAGS) $(LFLAGS) $^ $(LIBS) -o $@
$(OBJ)/aLaserDemo.o : aLaserDemo.cpp
$(CC) -c $(CFLAGS) $< -o $@
$(OBJ)/acpLaser.o : $(SRC)/acpLaser.cpp $(SRC)/acpLaser.h
$(CC) -c $(CFLAGS) $< -o $@
.PHONY : clean
clean :
rm -rf $(OBJ)
rm -f $(BIN)/aLaserDemo
</code></pre>
<p>I try to locate the crypto library:</p>
<pre><code> /usr/lib/i486/libcrypto.so.0.9.8
/usr/lib/i586/libcrypto.so.0.9.8
/usr/lib/i686/cmov/libcrypto.so.0.9.8
/usr/lib/libcrypto.so.0.9.8
</code></pre>
<p>What should I do to fix it?</p> | 14,364,669 | 2 | 7 | null | 2012-12-11 00:50:28.93 UTC | 8 | 2016-11-14 06:53:30.18 UTC | 2012-12-11 01:01:19.893 UTC | null | 15,168 | null | 1,811,267 | null | 1 | 51 | c|gcc|ubuntu | 146,630 | <p>I solved this on 12.10 by installing libssl-dev.</p>
<pre><code>sudo apt-get install libssl-dev
</code></pre> |
13,895,390 | What does the ic_launcher-web.png in my project root do? | <p>Unbelievably enough, I couldn't find an answer when Googling for this very basic question!</p>
<p>I noticed that since I upgraded from Eclipse Helios to Eclipse Juno and updated the Android SDK, Eclipse places a file called ic_launcher-web.png in the project root whenever I create a new Android project. The file is the same as the application icon selected in the project creation dialog, but what does it do? As mentioned, it's in the project root, not in any of the /res/ folders. So is it included in the finished .apk file, and what is it's purpose? </p> | 13,895,404 | 4 | 0 | null | 2012-12-15 19:24:48.78 UTC | 3 | 2019-05-24 16:22:07.907 UTC | null | null | null | null | 930,640 | null | 1 | 81 | android|eclipse|icons|project | 26,244 | <p>It's for the Play Store, which accepts 512x512 high-resolution icons:</p>
<blockquote>
<ul>
<li>High Resolution Application Icon (Required):
<ul>
<li>Use: In various locations in Google Play.</li>
<li>Specs: 512x512, 32-bit PNG with alpha; Max size of 1024KB.</li>
</ul></li>
</ul>
<p><a href="http://support.google.com/googleplay/android-developer/bin/answer.py?hl=en&answer=1078870" rel="noreferrer">-- Google Support</a></p>
</blockquote>
<p>(A more tutorial like explanation can be found <a href="https://web.archive.org/web/20140616162825/http://developer.xamarin.com/guides/android/deployment,_testing,_and_metrics/publishing_an_application/part_2_-_publishing_an_application_on_google_play/#High_Resolution_Application_Icon" rel="noreferrer">here</a>.)</p>
<p>It is not used in your actual app or the launcher, so it is not packaged in the APK.</p> |
29,058,323 | How to move to previous caret position in Android Studio | <p>How can one move to previous caret position(s) in android studio?
It was possible in Eclipse.</p> | 36,601,757 | 14 | 2 | null | 2015-03-15 07:33:11.597 UTC | 12 | 2022-02-05 06:02:25.76 UTC | 2021-01-12 15:48:25.393 UTC | null | 5,925,259 | null | 305,135 | null | 1 | 104 | android|android-studio|keyboard-shortcuts | 34,231 | <p>Use <kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>Left</kbd> and <kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>Right</kbd></p>
<p>For Mac, use <kbd>Command</kbd> + <kbd>Option</kbd> + <kbd>Left</kbd> and <kbd>Command</kbd> + <kbd>Option</kbd> + <kbd>Right</kbd></p>
<p>If these don't work for you, it is possible that these keys are assigned for some of the functions of your OS/video drivers, you can either disable the shortcuts that are using these keys from operating system settings/video driver settings or change shortcuts from Android Studio itself by going to:</p>
<pre><code>File > Settings > Keymap > Main menu > Navigate > Back/Forward
</code></pre>
<p><a href="https://i.stack.imgur.com/T8rvd.png" rel="noreferrer"><img src="https://i.stack.imgur.com/T8rvd.png" alt="Move to previous caret position Android Studio"></a></p>
<p>Mac users can find this dialog by going to Android Studio's: <code>App Menu -> Preferences</code></p> |
43,787,006 | TypeError: Attempted to assign to readonly property - when typing in a text field | <p>I recently updated my Angular from 1.5.x to 1.6.4 and now, when I go to a form, I get the below error message whenever I try to type something up in the form/textbox:</p>
<pre><code>TypeError: Attempted to assign to readonly property.
</code></pre>
<p>This is my controller:</p>
<pre><code>mainApp.controller('newPostController', ['$scope', '$http', function($scope, $http){
$scope.post = '';
$scope.postCreated = false;
$scope.makeNewPost = function() {
$http.post('/api/post', {
title: $scope.post.title,
})
.then(function(res){
$scope.postCreated = true;
//extra code not related to the form itself...
};
}]);
</code></pre>
<p>My HTML looks like this:</p>
<pre><code><form ng-submit="makeNewPost()">
<div class="form-group">
<label for="title" class="control-label">Title</label>
<input type="text" autocomplete="off" class="form-control" ng-model="post.title" id="title" required="required">
</div>
<input type="submit" value="Submit">
</form>
</code></pre>
<p>I looked this error up and everything I am seeing has nothing to do with what my set up is like.</p>
<p>Please help me out on this. I don't know where to go from here.</p>
<p>Thanks</p> | 43,787,170 | 1 | 1 | null | 2017-05-04 15:23:37.947 UTC | 0 | 2017-05-04 15:31:17.76 UTC | null | null | null | null | 1,539,640 | null | 1 | 8 | javascript|angularjs | 39,392 | <p>Try this...</p>
<p>you have initialized <code>$scope.post = '';</code> as a string. But that should be <code>$scope.post = {};</code> an object.</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-js lang-js prettyprint-override"><code>var mainApp = angular.module('app', []);
mainApp.controller('newPostController', ['$scope', '$http', function($scope, $http) {
$scope.post = {};
$scope.postCreated = false;
$scope.makeNewPost = function() {
console.log($scope.post.title);
$http.post('/api/post', {
title: $scope.post.title,
})
.then(function(res) {
$scope.postCreated = true;
//extra code not related to the form itself...
});
}
}]);</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app='app' ng-controller='newPostController'>
<form ng-submit="makeNewPost()">
<div class="form-group">
<label for="title" class="control-label">Title</label>
<input type="text" autocomplete="off" class="form-control" ng-model="post.title" id="title" required="required">
</div>
<input type="submit" value="Submit">
</form>
</div></code></pre>
</div>
</div>
</p> |
29,943,075 | Scrapy pipeline to export csv file in the right format | <p>I made the improvement according to the suggestion from alexce below. What I need is like the picture below. However each row/line should be one review: with date, rating, review text and link.</p>
<p>I need to let item processor process each review of every page.<br>
Currently TakeFirst() only takes the first review of the page. So 10 pages, I only have 10 lines/rows as in the picture below.</p>
<p><img src="https://i.stack.imgur.com/2e3lb.jpg" alt="enter image description here"></p>
<p>Spider code is below:</p>
<pre><code>import scrapy
from amazon.items import AmazonItem
class AmazonSpider(scrapy.Spider):
name = "amazon"
allowed_domains = ['amazon.co.uk']
start_urls = [
'http://www.amazon.co.uk/product-reviews/B0042EU3A2/'.format(page) for page in xrange(1,114)
]
def parse(self, response):
for sel in response.xpath('//*[@id="productReviews"]//tr/td[1]'):
item = AmazonItem()
item['rating'] = sel.xpath('div/div[2]/span[1]/span/@title').extract()
item['date'] = sel.xpath('div/div[2]/span[2]/nobr/text()').extract()
item['review'] = sel.xpath('div/div[6]/text()').extract()
item['link'] = sel.xpath('div/div[7]/div[2]/div/div[1]/span[3]/a/@href').extract()
yield item
</code></pre> | 29,971,406 | 2 | 12 | null | 2015-04-29 11:58:36.383 UTC | 15 | 2016-03-19 19:32:15.807 UTC | 2016-03-19 19:32:15.807 UTC | null | -1 | null | 4,345,535 | null | 1 | 18 | python|csv|scrapy|pipeline | 25,433 | <p>I started from scratch and the following spider should be run with</p>
<p><code>scrapy crawl amazon -t csv -o Amazon.csv --loglevel=INFO</code></p>
<p>so that opening the CSV-File with a spreadsheet shows for me</p>
<p><img src="https://i.stack.imgur.com/p76Oq.png" alt="enter image description here"></p>
<p>Hope this helps :-)</p>
<pre><code>import scrapy
class AmazonItem(scrapy.Item):
rating = scrapy.Field()
date = scrapy.Field()
review = scrapy.Field()
link = scrapy.Field()
class AmazonSpider(scrapy.Spider):
name = "amazon"
allowed_domains = ['amazon.co.uk']
start_urls = ['http://www.amazon.co.uk/product-reviews/B0042EU3A2/' ]
def parse(self, response):
for sel in response.xpath('//table[@id="productReviews"]//tr/td/div'):
item = AmazonItem()
item['rating'] = sel.xpath('./div/span/span/span/text()').extract()
item['date'] = sel.xpath('./div/span/nobr/text()').extract()
item['review'] = sel.xpath('./div[@class="reviewText"]/text()').extract()
item['link'] = sel.xpath('.//a[contains(.,"Permalink")]/@href').extract()
yield item
xpath_Next_Page = './/table[@id="productReviews"]/following::*//span[@class="paging"]/a[contains(.,"Next")]/@href'
if response.xpath(xpath_Next_Page):
url_Next_Page = response.xpath(xpath_Next_Page).extract()[0]
request = scrapy.Request(url_Next_Page, callback=self.parse)
yield request
</code></pre> |
9,405,610 | How to change navbar collapse threshold using Twitter bootstrap-responsive? | <p>I'm using Twitter Bootstrap 2.0.1 in a Rails 3.1.2 project, implemented with bootstrap-sass. I'm loading both the <code>bootstrap.css</code> and the <code>bootstrap-responsive.css</code> files, as well as the <code>bootstrap-collapse.js</code> Javascript.</p>
<p>I have a fluid layout with a navbar similar to the <a href="http://twitter.github.com/bootstrap/examples/fluid.html" rel="noreferrer">example</a>. This follows the navbar "responsive variation" instructions <a href="http://twitter.github.com/bootstrap/components.html#navbar" rel="noreferrer">here</a>. It works fine: if the page is narrower than about 940px, the navbar collapses and displays a "button" that I can click on to expand.</p>
<p>However my navbar looks good down to about 550px wide, i.e. it doesn't need to be collapsed unless the screen is very narrow.</p>
<p>How do I tell Bootstrap to only collapse the navbar if the screen is less than 550px wide?</p>
<p>Note that at this point I do <em>not</em> want to modify the other responsive behaviors, e.g. stacking elements instead of displaying them side by side.</p> | 9,405,698 | 14 | 1 | null | 2012-02-23 00:56:38.9 UTC | 26 | 2019-03-15 18:46:36.513 UTC | 2012-02-25 01:42:20.347 UTC | null | 550,712 | null | 550,712 | null | 1 | 94 | css|ruby-on-rails-3|twitter-bootstrap | 113,530 | <p>You are looking for line 239 of <code>bootstrap-responsive.css</code></p>
<pre class="lang-css prettyprint-override"><code>@media (max-width: 979px) {...}
</code></pre>
<p>Where the <code>max-width</code> value triggers the responsive nav. Change it to 550px or so and it should resize fine.</p> |
32,718,870 | How to get All input of POST in Laravel | <p>I am using Laravel 5 and trying to get all input of POST variable in controller like this-</p>
<pre><code>public function add_question()
{
return Request::all();
}
</code></pre>
<p>So, I am getting this errors-</p>
<p><a href="https://i.stack.imgur.com/VNGJk.png" rel="noreferrer"><img src="https://i.stack.imgur.com/VNGJk.png" alt="enter image description here"></a></p>
<p>What I am doing wrong?</p> | 32,719,142 | 8 | 3 | null | 2015-09-22 13:56:51.293 UTC | 8 | 2021-03-30 11:48:31.39 UTC | 2020-03-05 09:22:59.02 UTC | null | 2,193,439 | null | 2,193,439 | null | 1 | 70 | php|laravel|laravel-5 | 216,464 | <p>Try this :</p>
<pre><code>use Illuminate\Support\Facades\Request;
public function add_question(Request $request)
{
return $request->all();
}
</code></pre> |
32,683,599 | R ifelse to replace values in a column | <p>I have a column in my dataframe as follows: </p>
<pre><code>Private
Private
Private
?
Private
</code></pre>
<p>I want to replace this " ?" with Private. I have a solution as follows:</p>
<pre><code># Only replacing ? with Private
df$var <- ifelse(df$var == " ?", " Private", df$var)
</code></pre>
<p>However when I print out the <code>df$var</code> column after the ifelse statement, these values don't seem correct. This is what I got: </p>
<pre><code>3
3
3
Private
3
</code></pre>
<p>I don't know what went wrong here. </p> | 32,684,389 | 3 | 3 | null | 2015-09-20 19:48:58.487 UTC | 6 | 2018-12-05 08:02:30.007 UTC | null | null | null | null | 4,056,023 | null | 1 | 8 | r | 51,937 | <p>This should work, using the working example:</p>
<pre><code>var <- c("Private", "Private", "?", "Private")
df <- data.frame(var)
df$var[which(df$var == "?")] = "Private"
</code></pre>
<p>Then this will replace the values of "?" with "Private"</p>
<p>The reason your replacement isn't working (I think) is as if the value in <code>df$var</code> isn't <code>"?"</code> then it replaces the element of the vector with the whole <code>df$var</code> column, not just reinserting the element you want. </p> |
19,317,493 | PHP preg_replace: Case insensitive match with case sensitive replacement | <p>I'm using preg_replace in PHP to find and replace specific words in a string, like this:</p>
<pre><code>$subject = "Apple apple";
print preg_replace('/\bapple\b/i', 'pear', $subject);
</code></pre>
<p>Which gives the result 'pear pear'.</p>
<p>What I'd like to be able to do is to match a word in a case insensitive way, but respect it's case when it is replaced - giving the result 'Pear pear'.</p>
<p>The following works, but seems a little long winded to me:</p>
<pre><code>$pattern = array('/Apple\b/', '/apple\b/');
$replacement = array('Pear', 'pear');
$subject = "Apple apple";
print preg_replace($pattern, $replacement, $subject);
</code></pre>
<p>Is there a better way to do this?</p>
<p>Update: Further to an excellent query raised below, for the purposes of this task I only want to respect 'title case' - so whether or not the first letter of a word is a capital.</p> | 19,317,811 | 4 | 2 | null | 2013-10-11 11:52:31.337 UTC | 7 | 2021-11-25 15:19:49.567 UTC | 2013-10-11 12:00:45.833 UTC | null | 1,647,085 | null | 1,647,085 | null | 1 | 29 | php|regex|preg-replace | 28,806 | <p>I have in mind this implementation for common case:</p>
<pre><code>$data = 'this is appLe and ApPle';
$search = 'apple';
$replace = 'pear';
$data = preg_replace_callback('/\b'.$search.'\b/i', function($matches) use ($replace)
{
$i=0;
return join('', array_map(function($char) use ($matches, &$i)
{
return ctype_lower($matches[0][$i++])?strtolower($char):strtoupper($char);
}, str_split($replace)));
}, $data);
//var_dump($data); //"this is peaR and PeAr"
</code></pre>
<p>-it's more complicated, of course, but fit original request for any position. If you're looking for only first letter, this could be an overkill (see @Jon's answer then)</p> |
19,488,658 | Get last day of Month | <p>For getting last date of month I have written this function</p>
<pre><code>/**
* @param month integer value of month
* @param year integer value of month
* @return last day of month in MM/dd/YYYY format
*/
private static String getDate(int month, int year) {
Calendar calendar = Calendar.getInstance();
// passing month-1 because 0-->jan, 1-->feb... 11-->dec
calendar.set(year, month - 1, 1);
calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));
Date date = calendar.getTime();
DateFormat DATE_FORMAT = new SimpleDateFormat("MM/dd/YYYY");
return DATE_FORMAT.format(date);
}
</code></pre>
<p>for all the inputs its working fine with one exception when the month is December, i.e. getDate(12, 2012) returns 12/31/2013 but it should return 12/31/2012.
Please explain the behavior and solution too. </p> | 19,488,731 | 9 | 3 | null | 2013-10-21 07:38:07.127 UTC | 3 | 2018-03-28 10:15:30.307 UTC | null | null | null | null | 1,568,380 | null | 1 | 24 | java|date|calendar | 49,488 | <p>Change <code>YYYY</code> to <code>yyyy</code> </p>
<pre><code>DateFormat DATE_FORMAT = new SimpleDateFormat("MM/dd/yyyy");
</code></pre>
<p><code>YYYY</code> is wrong <code>dateformat</code></p> |
34,252,640 | What is the purpose of the ConcurrencyStamp column in the AspNetUsers table in the new ASP.NET MVC 6 identity? | <p>What is the purpose of the <code>ConcurrencyStamp</code> column in the <code>AspNetUsers</code> table in the new ASP.NET MVC 6 identity?</p>
<p>This is the database schema of the <code>AspNetUsers</code> table:</p>
<p><a href="https://i.stack.imgur.com/Zr319.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Zr319.png" alt="enter image description here"></a></p>
<p>It is also there in the <code>AspNetRoles</code> table:</p>
<p><a href="https://i.stack.imgur.com/6Lbwx.png" rel="noreferrer"><img src="https://i.stack.imgur.com/6Lbwx.png" alt="enter image description here"></a></p>
<p>As I remember it wasn't there in the ASP.NET MVC 5 identity.</p>
<p>What I've noticed so far is that it seems to have GUID values as it is defined with the following code:</p>
<pre><code>/// <summary>
/// A random value that must change whenever a user is persisted to the store
/// </summary>
public virtual string ConcurrencyStamp { get; set; } = Guid.NewGuid().ToString();
</code></pre>
<p>But this documentation is not sufficient for me to understand in which situations it is used.</p> | 39,001,084 | 4 | 4 | null | 2015-12-13 15:18:46.257 UTC | 16 | 2021-04-27 09:58:30.72 UTC | null | null | null | null | 1,862,812 | null | 1 | 91 | asp.net-mvc|concurrency|database-schema|identity|asp.net-core-mvc | 41,418 | <p>As the name state, it's used to prevent concurrency update conflict.</p>
<p>For example, there's a <code>UserA</code> named Peter in the database
2 admins open the editor page of <code>UserA</code>, want to update this user.</p>
<ol>
<li><code>Admin_1</code> opened the page, and saw user called Peter.</li>
<li><code>Admin_2</code> opened the page, and saw user called Peter (obviously).</li>
<li><code>Admin_1</code> updated user name to Tom, and save data. Now <code>UserA</code> in the db named Tom.</li>
<li><code>Admin_2</code> updated user name to Thomas, and try to save it.</li>
</ol>
<p>What would happen if there's no ConcurrencyStamp is Admin_1's update will be overwritten by Admin_2's update.
But since we have <code>ConcurrencyStamp</code>, when <code>Admin_1</code>/<code>Admin_2</code> loads the page, the stamp is loaded. When updating data this stamp will be changed too.
So now step 5 would be system throw exception telling Admin_2 that this user has already been updated, since he <code>ConcurrencyStamp</code> is different from the one he loaded.</p> |
45,006,727 | Split a list into sublists based on a condition with Stream api | <p>I have a specific question. There are some similar questions but these are either with Python, not with Java, or the requirements are different even if the question sounds similar. </p>
<p>I have a list of values.</p>
<pre><code>List1 = {10, -2, 23, 5, -11, 287, 5, -99}
</code></pre>
<p>At the end of the day, I would like to split lists based on their values. I mean if the value is bigger than zero, it will be stay in the original list and the corresponding index in the negative values list will be set zero. If the value is smaller than zero, it will go to the negative values list and the negative values in the original list will be replaced with zero.</p>
<p>The resulting lists should be like that;</p>
<pre><code>List1 = {10, 0, 23, 5, 0, 287, 5, 0}
List2 = {0, -2, 0, 0, -11, 0, 0, -99}
</code></pre>
<p>Is there any way to solve this with Stream api in Java?</p> | 45,007,405 | 8 | 3 | null | 2017-07-10 08:03:33.483 UTC | 5 | 2020-06-25 12:12:05.803 UTC | null | null | null | null | 5,873,039 | null | 1 | 30 | java|java-stream | 40,237 | <p>If you want to do it in a single Stream operation, you need a custom collector:</p>
<pre><code>List<Integer> list = Arrays.asList(10, -2, 23, 5, -11, 287, 5, -99);
List<List<Integer>> result = list.stream().collect(
() -> Arrays.asList(new ArrayList<>(), new ArrayList<>()),
(l,i) -> { l.get(0).add(Math.max(0, i)); l.get(1).add(Math.min(0, i)); },
(a,b) -> { a.get(0).addAll(b.get(0)); a.get(1).addAll(b.get(1)); });
System.out.println(result.get(0));
System.out.println(result.get(1));
</code></pre> |
35,310,078 | How to write to a file in .NET Core? | <p>I want to use the Bluetooth LE functions in .NET Core (specifically, BluetoothLEAdvertisementWatcher) to write a scanner which logs information to a file. This is to run as a desktop application and preferably as a command line app.</p>
<p>Constructors like System.IO.StreamWriter(string) are not available, apparently. How do I create a file and write to it?</p>
<p>I would be just as happy to be able to do a System.Console.WriteLine(string) but that doesn't seem to be available under .NET Core either.</p>
<p>Update: To clarify, if I could have a program that looks like this run without error, I'll be off to the races.</p>
<pre><code>using System;
using Windows.Devices.Bluetooth.Advertisement;
namespace ConsoleApplication
{
public class Program
{
public static void Main(string[] args)
{
BluetoothLEAdvertisementWatcher watcher = new BluetoothLEAdvertisementWatcher();
Console.WriteLine("Hello, world!");
}
}
}
</code></pre>
<p>Update 2: Here's the project.json file:</p>
<pre><code>{
"dependencies": {
"Microsoft.NETCore.UniversalWindowsPlatform": "5.0.0"
},
"frameworks": {
"uap10.0": {}
},
"runtimes": {
"win10-arm": {},
"win10-arm-aot": {},
"win10-x86": {},
"win10-x86-aot": {},
"win10-x64": {},
"win10-x64-aot": {}
}
}
</code></pre>
<p>The output of the command <code>dotnet -v run</code> contains this error message:</p>
<pre><code>W:\src\dotnet_helloworld>dotnet -v run
...
W:\src\dotnet_helloworld\Program.cs(2,15): error CS0234: The type or namespace name 'Devices' does not exist in the namespace 'Windows' (are you missing an assembly reference?)
...
</code></pre> | 35,400,949 | 7 | 3 | null | 2016-02-10 08:27:25.197 UTC | 9 | 2022-05-18 19:04:49.267 UTC | 2016-02-12 07:53:54.903 UTC | null | 80,309 | null | 80,309 | null | 1 | 60 | c#|.net|bluetooth|coreclr | 84,016 | <p>This code is the skeleton I was looking for when I posed the question. It uses only facilities available in .NET Core.</p>
<pre><code>var watcher = new BluetoothLEAdvertisementWatcher();
var logPath = System.IO.Path.GetTempFileName();
var logFile = System.IO.File.Create(logPath);
var logWriter = new System.IO.StreamWriter(logFile);
logWriter.WriteLine("Log message");
logWriter.Dispose();
</code></pre> |
1,071,407 | How to set multiple selections in ASP.NET ListBox? | <p>I can't find a way to select multiple items in an ASP.NET ListBox in the code behind? Is this something needs to be done in Javascript?</p> | 1,071,426 | 5 | 0 | null | 2009-07-01 21:09:27.853 UTC | null | 2017-08-02 08:10:45.493 UTC | null | null | null | null | 129,001 | null | 1 | 9 | asp.net|listbox | 41,068 | <p>this is the VB code to do so...</p>
<pre><code>myListBox.SelectionMode = Multiple
For each i as listBoxItem in myListBox.Items
if i.Value = WantedValue Then
i.Selected = true
end if
Next
</code></pre> |
104,520 | WPF Validation for the whole form | <p>I have been seriously disappointed with WPF validation system. Anyway! How can I validate the complete form by clicking the "button"? </p>
<p>For some reason everything in WPF is soo complicated! I can do the validation in 1 line of code in ASP.NET which requires like 10-20 lines of code in WPF!!</p>
<p>I can do this using my own ValidationEngine framework: </p>
<pre><code>Customer customer = new Customer();
customer.FirstName = "John";
customer.LastName = String.Empty;
ValidationEngine.Validate(customer);
if (customer.BrokenRules.Count > 0)
{
// do something display the broken rules!
}
</code></pre> | 182,330 | 5 | 0 | null | 2008-09-19 18:54:18.467 UTC | 12 | 2014-01-13 15:43:18.697 UTC | 2014-01-13 15:43:18.697 UTC | null | 743 | azamsharp | 3,797 | null | 1 | 15 | wpf|validation | 29,823 | <p>A WPF application should disable the button to submit a form iff the entered data is not valid. You can achieve this by implementing the <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.idataerrorinfo.aspx" rel="noreferrer">IDataErrorInfo</a> interface on your business object, using Bindings with <a href="http://msdn.microsoft.com/en-us/library/system.windows.data.binding.validatesondataerrors.aspx" rel="noreferrer"><code>ValidatesOnDataErrors</code></a><code>=true</code>. For customizing the look of individual controls in the case of errors, set a <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.validation.errortemplate.aspx" rel="noreferrer"><code>Validation.ErrorTemplate</code></a>.</p>
<h3>XAML:</h3>
<pre><code><Window x:Class="Example.CustomerWindow" ...>
<Window.CommandBindings>
<CommandBinding Command="ApplicationCommands.Save"
CanExecute="SaveCanExecute"
Executed="SaveExecuted" />
</Window.CommandBindings>
<StackPanel>
<TextBox Text="{Binding FirstName, ValidatesOnDataErrors=true, UpdateSourceTrigger=PropertyChanged}" />
<TextBox Text="{Binding LastName, ValidatesOnDataErrors=true, UpdateSourceTrigger=PropertyChanged}" />
<Button Command="ApplicationCommands.Save" IsDefault="True">Save</Button>
<TextBlock Text="{Binding Error}"/>
</StackPanel>
</Window>
</code></pre>
<p>This creates a <code>Window</code> with two <code>TextBox</code>es where you can edit the first and last name of a customer. The "Save" button is only enabled if no validation errors have occurred. The <code>TextBlock</code> beneath the button shows the current errors, so the user knows what's up.</p>
<p>The default <code>ErrorTemplate</code> is a thin red border around the erroneous Control. If that doesn't fit into you visual concept, look at <a href="http://www.codeproject.com/KB/WPF/wpfvalidation.aspx" rel="noreferrer">Validation in Windows Presentation Foundation</a> article on CodeProject for an in-depth look into what can be done about that.</p>
<p>To get the window to actually work, there has to be a bit infrastructure in the Window and the Customer.</p>
<h3>Code Behind</h3>
<pre><code>// The CustomerWindow class receives the Customer to display
// and manages the Save command
public class CustomerWindow : Window
{
private Customer CurrentCustomer;
public CustomerWindow(Customer c)
{
// store the customer for the bindings
DataContext = CurrentCustomer = c;
InitializeComponent();
}
private void SaveCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = ValidationEngine.Validate(CurrentCustomer);
}
private void SaveExecuted(object sender, ExecutedRoutedEventArgs e)
{
CurrentCustomer.Save();
}
}
public class Customer : IDataErrorInfo, INotifyPropertyChanged
{
// holds the actual value of FirstName
private string FirstNameBackingStore;
// the accessor for FirstName. Only accepts valid values.
public string FirstName {
get { return FirstNameBackingStore; }
set {
FirstNameBackingStore = value;
ValidationEngine.Validate(this);
OnPropertyChanged("FirstName");
}
}
// similar for LastName
string IDataErrorInfo.Error {
get { return String.Join("\n", BrokenRules.Values); }
}
string IDataErrorInfo.this[string columnName]
{
get { return BrokenRules[columnName]; }
}
}
</code></pre>
<p>An obvious improvement would be to move the <code>IDataErrorInfo</code> implementation up the class hierarchy, since it only depends on the <code>ValidationEngine</code>, but not the business object.</p>
<p>While this is indeed more code than the simple example you provided, it also has quite a bit more of functionality than only checking for validity. This gives you fine grained, and automatically updated indications to the user about validation problems and automatically disables the "Save" button as long as the user tries to enter invalid data.</p> |
385,335 | How to use PHP for large projects? | <p>The question has been asked: <a href="https://stackoverflow.com/questions/385203/no-php-for-large-projects-why-not">No PHP for large projects? Why not?</a> It's a recurring theme and PHP developers--with some cause--are forced to <a href="https://stackoverflow.com/questions/309300/defend-php-convince-me-it-isnt-horrible">defend PHP</a>.</p>
<p>All of these questions are valid and there have been some responses but this got me thinking. Based on the principle that you can write good code in any language and bad code in any language, I thought it worth asking a positive rather than negative question. Rather than <strong>why you can't</strong>, I wanted to ask <strong>how you can</strong> use PHP for large projects.</p>
<p>So, how do you write a large, complex, scalable, secure and robust PHP application?</p>
<p>EDIT: While I appreciate that the organizational aspects are important, they apply to <strong>any</strong> large project. What I'm primarily aiming for here is technical guidance and how to deal with common issues of scalability. Using an opcode cache like APC is an obvious starter. Cluster-aware sessions would be another. That's the sort of thing I'm getting at.</p> | 385,353 | 5 | 0 | null | 2008-12-22 01:37:44.897 UTC | 21 | 2020-02-15 07:18:09.453 UTC | 2017-05-23 10:28:07.11 UTC | Rich B | -1 | cletus | 18,393 | null | 1 | 25 | php | 6,430 | <p>For the most part, the problems with php are not so much with the language. The problems come from the coupling of a low barrier of entry and the lack of any infrastructure to avoid common programming problems or security problems. Its a language that, by itself, is pretty quick-and-dirty. Nevertheless, it still has many advantages for large-scale web apps. You'll just need to know how to add in some level of infrastructure to avoid a lot of the common web programming blunders. See - <a href="https://stackoverflow.com/questions/72394/what-should-a-developer-know-before-building-a-public-web-site">What should a developer know <em>before</em> building a public web site</a> for help with this.</p>
<p>You need to learn about the reasons php can make your web app to be insecure or problematic and learn to mitigate those problems. You should learn about how to use php to securely access your database. You should learn about avoiding SQL injection. You should learn about evil things like register_globals and why you should never ever use them. In short, you should <strong>do your homework</strong> about your tool before just diving in for a real-world, large-scale, web app.</p>
<p>Once you are educated, it comes down to you'll probably want to build a framework or use a preexisting framework that will mitigate these problems. Popular frameworks include PEAR and Zend.</p>
<p>Also, useful questions that might help:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/306497/what-should-every-php-programmer-know">What should every php programmer know?</a></li>
<li><a href="https://stackoverflow.com/questions/72394/what-should-a-developer-know-before-building-a-public-web-site">What should a developer know <em>before</em> building a public web site</a></li>
</ul> |
1,079,985 | NLS_LANG setting for JDBC thin driver? | <p>I am using the thin Oracle JDBC driver ver 10.2.0 (ojdbc14.jar). I would like to configure its NLS_LANG setting manually. Is there a way?</p>
<p>Currently it fetches this setting from the VM variable user.language (which is set automatically by setting the current locale, or on startup from the system environment).</p>
<p>This is a problem when the users switch the application locale to a one that is unsupported by the Oracle JDBC driver (e.g. mk_MK). In this case, the next time I fetch a connection I get the following exception:</p>
<pre>
ORA-00604: error occurred at recursive SQL level 1
ORA-12705: Cannot access NLS data files or invalid environment specified
</pre>
<p>I can change the locale on the fly just before I fetch the connection and switch back to the user's selected one back and forth, but this seems unelegant and unefficient.</p> | 1,306,042 | 5 | 0 | null | 2009-07-03 16:06:54.227 UTC | 9 | 2012-10-03 08:12:30.64 UTC | 2012-03-07 11:09:15.277 UTC | null | 21,234 | null | 31,155 | null | 1 | 27 | oracle|jdbc|nls|ora-12705 | 71,477 | <p>The NLS_LANG settings are derived from the java.util.Locale . Therefore, you will need to make a call similar to this before connecting:</p>
<pre><code>Locale.setDefault(Locale.<your locale here>);
</code></pre> |
176,931 | How can I get MSBUILD to evaluate and print the full path when given a relative path? | <p>How can I get MSBuild to evaluate and print in a <code><Message /></code> task an absolute path given a relative path?</p>
<p><strong>Property Group</strong></p>
<pre><code><Source_Dir>..\..\..\Public\Server\</Source_Dir>
<Program_Dir>c:\Program Files (x86)\Program\</Program_Dir>
</code></pre>
<p><strong>Task</strong></p>
<pre><code><Message Importance="low" Text="Copying '$(Source_Dir.FullPath)' to '$(Program_Dir)'" />
</code></pre>
<p><strong>Output</strong></p>
<blockquote>
<p>Copying '' to 'c:\Program Files (x86)\Program\'</p>
</blockquote> | 1,251,198 | 5 | 3 | null | 2008-10-07 01:45:44.087 UTC | 10 | 2012-09-02 15:10:40.1 UTC | 2010-08-12 05:26:56.78 UTC | null | 11,635 | spoon16 | 3,957 | null | 1 | 61 | msbuild|relative-path|absolute-path | 37,966 | <p><strong>In MSBuild 4.0</strong>, the easiest way is the following:</p>
<pre><code>$([System.IO.Path]::GetFullPath('$(MSBuildThisFileDirectory)\your\path'))
</code></pre>
<p>This method works even if the script is <code><Import></code>ed into another script; the path is relative to the file containing the above code.</p>
<p>(consolidated from <a href="https://stackoverflow.com/a/4894456/33080">Aaron's answer</a> as well as the last part of <a href="https://stackoverflow.com/a/2421596/33080">Sayed's answer</a>)</p>
<hr>
<p><strong>In MSBuild 3.5</strong>, you can use the <a href="http://msdn.microsoft.com/en-us/library/bb882668.aspx" rel="noreferrer" title="ConvertToAbsolutePath">ConvertToAbsolutePath</a> task:</p>
<pre><code><Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"
DefaultTargets="Test"
ToolsVersion="3.5">
<PropertyGroup>
<Source_Dir>..\..\..\Public\Server\</Source_Dir>
<Program_Dir>c:\Program Files (x86)\Program\</Program_Dir>
</PropertyGroup>
<Target Name="Test">
<ConvertToAbsolutePath Paths="$(Source_Dir)">
<Output TaskParameter="AbsolutePaths" PropertyName="Source_Dir_Abs"/>
</ConvertToAbsolutePath>
<Message Text='Copying "$(Source_Dir_Abs)" to "$(Program_Dir)".' />
</Target>
</Project>
</code></pre>
<p>Relevant output:</p>
<pre><code>Project "P:\software\perforce1\main\XxxxxxXxxx\Xxxxx.proj" on node 0 (default targets).
Copying "P:\software\Public\Server\" to "c:\Program Files (x86)\Program\".
</code></pre>
<p>A little long-winded if you ask me, but it works. This will be relative to the "original" project file, so if placed inside a file that gets <code><Import></code>ed, this won't be relative to that file.</p>
<hr>
<p><strong>In MSBuild 2.0</strong>, there is an approach which doesn't resolve "..". It does however behave just like an absolute path:</p>
<pre><code><PropertyGroup>
<Source_Dir_Abs>$(MSBuildProjectDirectory)\$(Source_Dir)</Source_Dir_Abs>
</PropertyGroup>
</code></pre>
<p>The <a href="http://msdn.microsoft.com/en-us/library/ms164309%28VS.80%29.aspx" rel="noreferrer">$(MSBuildProjectDirectory)</a> reserved property is always the directory of the script that contains this reference.</p>
<p>This will also be relative to the "original" project file, so if placed inside a file that gets <code><Import></code>ed, this won't be relative to that file.</p> |
148,074 | Is the sorting algorithm used by .NET's `Array.Sort()` method a stable algorithm? | <p>Is the sorting algorithm used by .NET's <code>Array.Sort()</code> method a <a href="http://en.wikipedia.org/wiki/Stable_sort#Classification" rel="noreferrer">stable</a> algorithm?</p> | 148,081 | 5 | 4 | null | 2008-09-29 09:22:39.183 UTC | 6 | 2014-06-12 09:38:09.563 UTC | 2009-07-06 16:46:16.59 UTC | null | 5,640 | Pop Catalin | 4,685 | null | 1 | 71 | c#|.net | 25,142 | <p>From <a href="http://msdn.microsoft.com/en-us/library/6tf1f0bc.aspx" rel="noreferrer">MSDN</a>:</p>
<blockquote>
<p>This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. In contrast, a stable sort preserves the order of elements that are equal.</p>
</blockquote>
<p>The sort uses introspective sort. (Quicksort in version 4.0 and earlier of the .NET framework).</p>
<p>If you need a stable sort, you can use <a href="http://msdn.microsoft.com/en-us/library/bb534966.aspx" rel="noreferrer">Enumerable.OrderBy</a>.</p> |
1,058,433 | Exporting result of select statement to CSV format in DB2 | <p>Is there any way by which we can export the result of a select statment to CSV file, just like in MySQL.</p>
<p>MySQL Command;</p>
<pre><code>SELECT col1,col2,coln into OUTFILE 'result.csv'
FIELDS TERMINATED BY ',' FROM testtable t;
</code></pre> | 1,059,588 | 6 | 0 | null | 2009-06-29 13:49:35.737 UTC | 11 | 2019-11-11 09:42:35.693 UTC | 2019-11-09 19:06:51.373 UTC | null | 456,274 | null | 94,813 | null | 1 | 27 | csv|db2|export | 143,934 | <p>You can run this command from the DB2 command line processor (CLP) or from inside a SQL application by calling the <code>ADMIN_CMD</code> stored procedure</p>
<pre><code>EXPORT TO result.csv OF DEL MODIFIED BY NOCHARDEL
SELECT col1, col2, coln FROM testtable;
</code></pre>
<p>There are lots of options for <code>IMPORT</code> and <code>EXPORT</code> that you can use to create a data file that meets your needs. The <code>NOCHARDEL</code> qualifier will suppress double quote characters that would otherwise appear around each character column.</p>
<p>Keep in mind that any <code>SELECT</code> statement can be used as the source for your export, including joins or even recursive SQL. The export utility will also honor the sort order if you specify an <code>ORDER BY</code> in your <code>SELECT</code> statement.</p> |
555,705 | Character Translation using Python (like the tr command) | <p>Is there a way to do character translation / transliteration (kind of like the <a href="https://perldoc.perl.org/functions/tr" rel="nofollow noreferrer"><code>tr</code></a> command) using <strong>Python</strong>?</p>
<p>Some examples in Perl would be:</p>
<pre class="lang-perl prettyprint-override"><code>my $string = "some fields";
$string =~ tr/dies/eaid/;
print $string; # domi failed
$string = 'the cat sat on the mat.';
$string =~ tr/a-z/b/d;
print "$string\n"; # b b b. (because option "d" is used to delete characters not replaced)
</code></pre> | 555,724 | 6 | 3 | null | 2009-02-17 06:33:06.78 UTC | 3 | 2021-09-10 19:58:57.133 UTC | 2021-09-10 14:11:49.023 UTC | null | 967,621 | hhafez | 42,303 | null | 1 | 54 | python|perl|tr|transliteration | 35,945 | <p>See <a href="http://docs.python.org/library/stdtypes.html#str.translate" rel="noreferrer"><code>string.translate</code></a></p>
<pre><code>import string
"abc".translate(string.maketrans("abc", "def")) # => "def"
</code></pre>
<p>Note the doc's comments about subtleties in the translation of unicode strings.</p>
<p>And for Python 3, you can use directly:</p>
<pre class="lang-py prettyprint-override"><code>str.translate(str.maketrans("abc", "def"))
</code></pre>
<p>Edit: Since <code>tr</code> is a bit more advanced, also consider using <code>re.sub</code>.</p> |
31,057,746 | What's the default color for placeholder text in UITextField? | <p>Does anyone know what color a <code>UITextField</code>'s placeholder text is, by default? I'm trying to set a <code>UITextView</code>'s text to the same color. I've read elsewhere that it is <code>UIColor.lightGrayColor()</code> but it is actually a little lighter.</p> | 43,346,157 | 13 | 3 | null | 2015-06-25 18:12:48.243 UTC | 19 | 2019-10-19 08:30:40.243 UTC | 2015-06-25 18:36:57.19 UTC | null | 3,633,534 | null | 4,996,707 | null | 1 | 70 | ios|uitextfield|uicolor | 37,991 | <p>You can get this colour from inspecting the <code>attributedPlaceholder</code> from the <code>UITextField</code>. </p>
<p>The default seems to be: <code>NSColor = "UIExtendedSRGBColorSpace 0 0 0.0980392 0.22";</code></p>
<p>You could add an extension (or category) on <code>UIColor</code>:</p>
<pre><code>extension UIColor {
static var placeholderGray: UIColor {
return UIColor(colorLiteralRed: 0, green: 0, blue: 0.0980392, alpha: 0.22)
}
}
</code></pre>
<hr>
<p>2018, latest syntax is just:</p>
<pre><code>extension UIColor {
static var officialApplePlaceholderGray: UIColor {
return UIColor(red: 0, green: 0, blue: 0.0980392, alpha: 0.22)
}
}
</code></pre>
<p><code>#colorLiteralRed</code> was deprecated. Be aware of <a href="https://stackoverflow.com/a/46350529/294884">this</a> in some cases.</p> |
32,398,314 | Android data binding - 'No resource identifier found for attribute' | <p>My layout file:</p>
<pre><code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:text="@string/hello_world"
android:layout_width="wrap_content"
app:fontName="Roboto-Regular.ttf"
android:layout_height="wrap_content"/>
</RelativeLayout>
</code></pre>
<p>My binding adapter method:</p>
<pre><code>public class FontBinding {
@BindingAdapter("bind:fontName")
public static void setFontName(TextView view, @NonNull String fontName) {
String fontPath = "/fonts/" + fontName;
Typeface typeface = Typeface.createFromAsset(view.getContext().getAssets(), fontPath);
view.setTypeface(typeface);
}
}
</code></pre>
<p>The error I'm getting:</p>
<pre><code>Error:(8) No resource identifier found for attribute 'fontName' in package 'com.example.databindingproject'
</code></pre>
<p>Followed the tutorial from <a href="https://developer.android.com/tools/data-binding/guide.html">https://developer.android.com/tools/data-binding/guide.html</a> .
Any ideas of what I might be doing wrong?</p> | 32,406,200 | 5 | 6 | null | 2015-09-04 12:39:30.73 UTC | 1 | 2021-03-07 08:34:27.46 UTC | 2015-09-04 13:00:04.46 UTC | null | 1,100,249 | null | 1,100,249 | null | 1 | 38 | android|data-binding | 11,441 | <p>You must use the data binding syntax. It should be:</p>
<pre><code><TextView
android:text="@string/hello_world"
android:layout_width="wrap_content"
app:fontName='@{"Roboto-Regular.ttf"}'
android:layout_height="wrap_content"/>
</code></pre> |
17,765,265 | Difference between Intent.ACTION_GET_CONTENT and Intent.ACTION_PICK | <p>I'm trying to let the user choose any image that they want on their device to use as a wallpaper in this wallpaper application I'm building. For some reason when I write:</p>
<pre><code>Intent myIntent = new Intent(Intent.ACTION_PICK);
myIntent.setType("image/*");
startActivityForResult(myIntent, 100);
</code></pre>
<p>I go straight into the gallery, but when I write:</p>
<pre><code>Intent myIntent = new Intent(Intent.ACTION_GET_CONTENT, null);
myIntent.setType("image/*");
startActivityForResult(myIntent, 100);
</code></pre>
<p>I get to choose from Gallery, or Google Drive. What is the best way to let the user choose what app to retrieve the picture from every time? Or why do those two different intent constants make a difference?</p> | 17,765,424 | 3 | 0 | null | 2013-07-20 18:19:44.227 UTC | 22 | 2016-04-29 13:51:50.487 UTC | 2016-04-29 13:51:50.487 UTC | null | 140,752 | null | 1,193,321 | null | 1 | 74 | java|android|android-intent|android-camera-intent | 50,914 | <p>Your first <code>Intent</code> is invalid. The <a href="http://developer.android.com/reference/android/content/Intent.html#ACTION_PICK" rel="noreferrer">protocol for <code>ACTION_PICK</code></a> requires you to supply a <code>Uri</code> indicating the collection you are picking from. </p>
<blockquote>
<p>What is the best way to let the user choose what app to retrieve the picture from every time?</p>
</blockquote>
<p>If you want the user to choose something based on MIME type, use <code>ACTION_GET_CONTENT</code>.</p>
<p>If you have some specific collection (identified by a <code>Uri</code>) that you want the user to pick from, use <code>ACTION_PICK</code>.</p>
<p>In case of a tie, go with <code>ACTION_GET_CONTENT</code>. While <code>ACTION_PICK</code> is not formally deprecated, <a href="https://stackoverflow.com/a/6486827/115145">Dianne Hackborn recommends <code>ACTION_GET_CONTENT</code></a>.</p> |
47,042,483 | How to build and distribute a Python/Cython package that depends on third party libFoo.so | <p>I've written a Python module that depends on some C extensions. Those C extensions depend in turn on several compiled C libraries. I'd like to be able to distribute this module bundled with all the dependencies.</p>
<p>I've put together a minimal example (<a href="https://github.com/AppliedBiomath/cython-example" rel="noreferrer">it can be found on GitHub in its entirety</a>).</p>
<p>The directory structure is:</p>
<pre><code>$ tree .
.
├── README.md
├── poc
│ ├── __init__.py
│ ├── cython_extensions
│ │ ├── __init__.py
│ │ ├── cvRoberts_dns.c
│ │ ├── cvRoberts_dns.h
│ │ ├── helloworld.c
│ │ ├── helloworld.pxd
│ │ ├── helloworld.pyx
│ │ ├── test.c
│ │ └── test.h
│ ├── do_stuff.c
│ └── do_stuff.pyx
└── setup.py
</code></pre>
<p>setup.py builds the extensions, and links against the necessary libraries (<code>libsundials_cvode</code>, <code>libsundials_nvectorserial</code> in this case):</p>
<pre><code>from setuptools import setup, find_packages
from setuptools.extension import Extension
from Cython.Build import cythonize
ext_module_dostuff = Extension(
'poc.do_stuff',
['poc/do_stuff.pyx'],
)
ext_module_helloworld = Extension(
'poc.cython_extensions.helloworld',
['poc/cython_extensions/helloworld.pyx', 'poc/cython_extensions/test.c', 'poc/cython_extensions/cvRoberts_dns.c'],
include_dirs = ['/usr/local/include'],
libraries = ['m', 'sundials_cvodes', 'sundials_nvecserial'],
library_dirs = ['/usr/local/lib'],
)
cython_ext_modules = [
ext_module_dostuff,
ext_module_helloworld
]
setup (
name = "poc",
ext_modules = cythonize(cython_ext_modules),
packages=['poc', 'poc.cython_extensions'],
)
</code></pre>
<p>This is all well and good, but it does require that the end user first install sundials (and, in the actual case, several other libraries that are extremely finicky to get up and running).</p>
<p>Ideally, I'd like to be able to set this up only on development machines, create a distribution that includes the appropriate shared libraries, and ship some sort of bundle.</p>
<p>Given the various tutorials, examples and SO posts I've found so far. I'm led to believe I'm on the right track. However, there's some sort of final step that I'm just not groking.</p>
<p>Any help is appreciated :-).</p> | 47,182,945 | 3 | 3 | null | 2017-10-31 18:41:52.89 UTC | 9 | 2017-11-10 22:34:17.36 UTC | null | null | null | null | 577,666 | null | 1 | 24 | python|setuptools|python-extensions|python-packaging | 8,674 | <p>As you probably know, the recommended way of distributing a Python module with compiled components is to use the <a href="https://pypi.python.org/pypi/wheel" rel="noreferrer">wheel format</a>. There doesn't appear to be any standard cross-platform way of bundling third-party native libraries into a wheel. However, there are platform-specific tools for this purpose.</p>
<h2>On Linux, use <code>auditwheel</code>.</h2>
<p><a href="https://github.com/pypa/auditwheel" rel="noreferrer"><code>auditwheel</code></a> modifies an existing Linux wheel file to add any third-party libraries which are not included in the basic "<a href="https://github.com/pypa/manylinux" rel="noreferrer">manylinux</a>" standard. Here's an walkthrough of how to use it with your project on a clean install of Ubuntu 17.10:</p>
<p>First, install basic Python development tools, and the third-party library with its headers:</p>
<pre class="lang-none prettyprint-override"><code>root@ubuntu-17:~# apt-get install cython python-pip unzip
root@ubuntu-17:~# apt-get install libsundials-serial-dev
</code></pre>
<p>Then build your project into a wheel file:</p>
<pre class="lang-none prettyprint-override"><code>root@ubuntu-17:~# cd cython-example/
root@ubuntu-17:~/cython-example# python setup.py bdist_wheel
[...]
root@ubuntu-17:~/cython-example# cd dist/
root@ubuntu-17:~/cython-example/dist# ll
total 80
drwxr-xr-x 2 root root 4096 Nov 8 11:28 ./
drwxr-xr-x 7 root root 4096 Nov 8 11:28 ../
-rw-r--r-- 1 root root 70135 Nov 8 11:28 poc-0.0.0-cp27-cp27mu-linux_x86_64.whl
root@ubuntu-17:~/cython-example/dist# unzip -l poc-0.0.0-cp27-cp27mu-linux_x86_64.whl
Archive: poc-0.0.0-cp27-cp27mu-linux_x86_64.whl
Length Date Time Name
--------- ---------- ----- ----
62440 2017-11-08 11:28 poc/do_stuff.so
2 2017-11-08 11:28 poc/__init__.py
116648 2017-11-08 11:28 poc/cython_extensions/helloworld.so
2 2017-11-08 11:28 poc/cython_extensions/__init__.py
10 2017-11-08 11:28 poc-0.0.0.dist-info/DESCRIPTION.rst
211 2017-11-08 11:28 poc-0.0.0.dist-info/metadata.json
4 2017-11-08 11:28 poc-0.0.0.dist-info/top_level.txt
105 2017-11-08 11:28 poc-0.0.0.dist-info/WHEEL
167 2017-11-08 11:28 poc-0.0.0.dist-info/METADATA
793 2017-11-08 11:28 poc-0.0.0.dist-info/RECORD
--------- -------
180382 10 files
</code></pre>
<p>The wheel file can now be installed locally and tested:</p>
<pre class="lang-none prettyprint-override"><code>root@ubuntu-17:~/cython-example/dist# pip install poc-0.0.0-cp27-cp27mu-linux_x86_64.whl
[...]
root@ubuntu-17:~/cython-example/dist# python -c "from poc.do_stuff import hello; hello()"
hello cython
0.841470984808
trying to load the sundials program
3-species kinetics problem
At t = 2.6391e-01 y = 9.899653e-01 3.470564e-05 1.000000e-02
rootsfound[] = 0 1
At t = 4.0000e-01 y = 9.851641e-01 3.386242e-05 1.480205e-02
[...]
</code></pre>
<p>Now we install the <code>auditwheel</code> tool. It requires Python 3, but it's capable of processing wheels for Python 2 or 3.</p>
<pre class="lang-none prettyprint-override"><code>root@ubuntu-17:~/cython-example/dist# apt-get install python3-pip
root@ubuntu-17:~/cython-example/dist# pip3 install auditwheel
</code></pre>
<p><code>auditwheel</code> uses another tool called <code>patchelf</code> to do its job. Unfortunately, the version of <code>patchelf</code> included with Ubuntu 17.10 is missing <a href="https://github.com/NixOS/patchelf/issues/84" rel="noreferrer">a bugfix</a> without which <a href="https://github.com/pypa/auditwheel/pull/25" rel="noreferrer">auditwheel will not work</a>. So we'll have to build it from source (script taken from <a href="https://github.com/pypa/manylinux/blob/6eae41b6988f34401d87d22fcb78970df2c3a06d/docker/build_scripts/build.sh#L114" rel="noreferrer">the manylinux Docker image</a>):</p>
<pre class="lang-none prettyprint-override"><code>root@ubuntu-17:~# apt-get install autoconf
root@ubuntu-17:~# PATCHELF_VERSION=6bfcafbba8d89e44f9ac9582493b4f27d9d8c369
root@ubuntu-17:~# curl -sL -o patchelf.tar.gz https://github.com/NixOS/patchelf/archive/$PATCHELF_VERSION.tar.gz
root@ubuntu-17:~# tar -xzf patchelf.tar.gz
root@ubuntu-17:~# (cd patchelf-$PATCHELF_VERSION && ./bootstrap.sh && ./configure && make && make install)
</code></pre>
<p>Now we can check which third-party libraries the wheel requires:</p>
<pre class="lang-none prettyprint-override"><code>root@ubuntu-17:~/cython-example/dist# auditwheel show poc-0.0.0-cp27-cp27mu-linux_x86_64.whl
poc-0.0.0-cp27-cp27mu-linux_x86_64.whl is consistent with the
following platform tag: "linux_x86_64".
The wheel references external versioned symbols in these system-
provided shared libraries: libc.so.6 with versions {'GLIBC_2.4',
'GLIBC_2.2.5', 'GLIBC_2.3.4'}
The following external shared libraries are required by the wheel:
{
"libblas.so.3": "/usr/lib/x86_64-linux-gnu/blas/libblas.so.3.7.1",
"libc.so.6": "/lib/x86_64-linux-gnu/libc-2.26.so",
"libgcc_s.so.1": "/lib/x86_64-linux-gnu/libgcc_s.so.1",
"libgfortran.so.4": "/usr/lib/x86_64-linux-gnu/libgfortran.so.4.0.0",
"liblapack.so.3": "/usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.7.1",
"libm.so.6": "/lib/x86_64-linux-gnu/libm-2.26.so",
"libpthread.so.0": "/lib/x86_64-linux-gnu/libpthread-2.26.so",
"libquadmath.so.0": "/usr/lib/x86_64-linux-gnu/libquadmath.so.0.0.0",
"libsundials_cvodes.so.2": "/usr/lib/libsundials_cvodes.so.2.0.0",
"libsundials_nvecserial.so.0": "/usr/lib/libsundials_nvecserial.so.0.0.2"
}
In order to achieve the tag platform tag "manylinux1_x86_64" the
following shared library dependencies will need to be eliminated:
libblas.so.3, libgfortran.so.4, liblapack.so.3, libquadmath.so.0,
libsundials_cvodes.so.2, libsundials_nvecserial.so.0
</code></pre>
<p>And create a new wheel which bundles them:</p>
<pre class="lang-none prettyprint-override"><code>root@ubuntu-17:~/cython-example/dist# auditwheel repair poc-0.0.0-cp27-cp27mu-linux_x86_64.whl
Repairing poc-0.0.0-cp27-cp27mu-linux_x86_64.whl
Grafting: /usr/lib/libsundials_nvecserial.so.0.0.2 -> poc/.libs/libsundials_nvecserial-42b4120e.so.0.0.2
Grafting: /usr/lib/libsundials_cvodes.so.2.0.0 -> poc/.libs/libsundials_cvodes-50fde5ee.so.2.0.0
Grafting: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.7.1 -> poc/.libs/liblapack-549933c4.so.3.7.1
Grafting: /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.7.1 -> poc/.libs/libblas-52fa99c8.so.3.7.1
Grafting: /usr/lib/x86_64-linux-gnu/libgfortran.so.4.0.0 -> poc/.libs/libgfortran-2df4b07d.so.4.0.0
Grafting: /usr/lib/x86_64-linux-gnu/libquadmath.so.0.0.0 -> poc/.libs/libquadmath-0d7c3070.so.0.0.0
Setting RPATH: poc/cython_extensions/helloworld.so to "$ORIGIN/../.libs"
Previous filename tags: linux_x86_64
New filename tags: manylinux1_x86_64
Previous WHEEL info tags: cp27-cp27mu-linux_x86_64
New WHEEL info tags: cp27-cp27mu-manylinux1_x86_64
Fixed-up wheel written to /root/cython-example/dist/wheelhouse/poc-0.0.0-cp27-cp27mu-manylinux1_x86_64.whl
root@ubuntu-17:~/cython-example/dist# unzip -l wheelhouse/poc-0.0.0-cp27-cp27mu-manylinux1_x86_64.whl
Archive: wheelhouse/poc-0.0.0-cp27-cp27mu-manylinux1_x86_64.whl
Length Date Time Name
--------- ---------- ----- ----
167 2017-11-08 11:28 poc-0.0.0.dist-info/METADATA
4 2017-11-08 11:28 poc-0.0.0.dist-info/top_level.txt
10 2017-11-08 11:28 poc-0.0.0.dist-info/DESCRIPTION.rst
211 2017-11-08 11:28 poc-0.0.0.dist-info/metadata.json
1400 2017-11-08 12:08 poc-0.0.0.dist-info/RECORD
110 2017-11-08 12:08 poc-0.0.0.dist-info/WHEEL
62440 2017-11-08 11:28 poc/do_stuff.so
2 2017-11-08 11:28 poc/__init__.py
131712 2017-11-08 12:08 poc/cython_extensions/helloworld.so
2 2017-11-08 11:28 poc/cython_extensions/__init__.py
230744 2017-11-08 12:08 poc/.libs/libsundials_cvodes-50fde5ee.so.2.0.0
7005072 2017-11-08 12:08 poc/.libs/liblapack-549933c4.so.3.7.1
264024 2017-11-08 12:08 poc/.libs/libquadmath-0d7c3070.so.0.0.0
2039960 2017-11-08 12:08 poc/.libs/libgfortran-2df4b07d.so.4.0.0
17736 2017-11-08 12:08 poc/.libs/libsundials_nvecserial-42b4120e.so.0.0.2
452432 2017-11-08 12:08 poc/.libs/libblas-52fa99c8.so.3.7.1
--------- -------
10206026 16 files
</code></pre>
<p>If we uninstall the third-party libraries, the previously-installed wheel will stop working:</p>
<pre class="lang-none prettyprint-override"><code>root@ubuntu-17:~/cython-example/dist# apt-get remove libsundials-serial-dev && apt-get autoremove
[...]
root@ubuntu-17:~/cython-example/dist# python -c "from poc.do_stuff import hello; hello()"
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "poc/do_stuff.pyx", line 1, in init poc.do_stuff
ImportError: libsundials_cvodes.so.2: cannot open shared object file: No such file or directory
</code></pre>
<p>But the wheel with the bundled libraries will work fine:</p>
<pre class="lang-none prettyprint-override"><code>root@ubuntu-17:~/cython-example/dist# pip uninstall poc
[...]
root@ubuntu-17:~/cython-example/dist# pip install wheelhouse/poc-0.0.0-cp27-cp27mu-manylinux1_x86_64.whl
[...]
root@ubuntu-17:~/cython-example/dist# python -c "from poc.do_stuff import hello; hello()"
hello cython
0.841470984808
trying to load the sundials program
3-species kinetics problem
At t = 2.6391e-01 y = 9.899653e-01 3.470564e-05 1.000000e-02
rootsfound[] = 0 1
At t = 4.0000e-01 y = 9.851641e-01 3.386242e-05 1.480205e-02
[...]
</code></pre>
<h2>On OSX, use <code>delocate</code>.</h2>
<p><a href="https://github.com/matthew-brett/delocate" rel="noreferrer"><code>delocate</code></a> for OSX apparently works very similarly to <code>auditwheel</code>. Unfortunately I don't have an OSX machine available to provide a walkthrough. </p>
<h2>Combined example:</h2>
<p>One project which uses both tools is SciPy. <a href="https://github.com/MacPython/scipy-wheels" rel="noreferrer">This repository</a>, despite its name, contains the official SciPy build process for all platforms, not just Mac. Specifically, compare the <a href="https://github.com/matthew-brett/multibuild/blob/e6ebbfa42588c26579eff99c50e84326dd9f6b3e/manylinux_utils.sh" rel="noreferrer">Linux build script</a> (which uses <code>auditwheel</code>), with the <a href="https://github.com/matthew-brett/multibuild/blob/e6ebbfa42588c26579eff99c50e84326dd9f6b3e/osx_utils.sh" rel="noreferrer">OSX build script</a> (which uses <code>delocate</code>). </p>
<p>To see the result of this process, you might want to download and unzip some of the <a href="https://pypi.python.org/pypi/scipy" rel="noreferrer">SciPy wheels from PyPI</a>. For example, <code>scipy-1.0.0-cp27-cp27m-manylinux1_x86_64.whl</code> contains the following:</p>
<pre class="lang-none prettyprint-override"><code> 38513408 2017-10-25 06:02 scipy/.libs/libopenblasp-r0-39a31c03.2.18.so
1023960 2017-10-25 06:02 scipy/.libs/libgfortran-ed201abd.so.3.0.0
</code></pre>
<p>While <code>scipy-1.0.0-cp27-cp27m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl</code> contains this:</p>
<pre class="lang-none prettyprint-override"><code> 273072 2017-10-25 07:03 scipy/.dylibs/libgcc_s.1.dylib
1550456 2017-10-25 07:03 scipy/.dylibs/libgfortran.3.dylib
279932 2017-10-25 07:03 scipy/.dylibs/libquadmath.0.dylib
</code></pre> |
11,968,210 | Powershell Get-WmiObject Access is denied | <p>I have a Powershell script containing the following line: </p>
<pre><code>$package = Get-WmiObject -Class Win32_Product -ComputerName $TargetServer -Filter ("Name='{0}'" -f $ApplicationName)
</code></pre>
<p>I followed the steps on this answer in order to enable Powershell Remoting between the servers: <a href="https://stackoverflow.com/questions/8362057/what-security-setting-is-preventing-remote-powershell-2-0-from-accessing-unc-pat">remoting security steps</a> </p>
<p>When I run the script from the Powershell ISE (in an elevated admin window) then I get the following error: </p>
<pre><code>Get-WmiObject : Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
At line:1 char:14
+ Get-WmiObject <<<< win32_bios -computername d-vasbiz01
+ CategoryInfo : NotSpecified: (:) [Get-WmiObject], UnauthorizedAccessException
+ FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.GetWmiObjectCommand
</code></pre>
<p>I need to be able to run the script in the ISE so that I can troubleshoot other problems.</p>
<p>Can anyone please suggest what I need to do to fix this security error?</p> | 12,092,961 | 5 | 4 | null | 2012-08-15 11:05:41.507 UTC | 2 | 2022-08-04 00:21:44.25 UTC | 2017-05-23 12:29:32.687 UTC | null | -1 | null | 41,169 | null | 1 | 2 | powershell|tfs | 40,488 | <p>I needed to pass credentials to the Get-WmiObject cmdlet.</p>
<p>I found the answer here:<a href="http://powershellmasters.blogspot.co.uk/2009/04/powershell-and-remote-wmi.html" rel="nofollow">Powershell Masters</a></p> |
46,977,267 | com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex - Android Studio 3.0 stable | <p>I made:</p>
<ul>
<li>In "Settings"->"Android SDK"->"SDK Tools" Google Play services is checked and installed v.46</li>
<li>Removed folder /.gradle</li>
<li>"Clean Project"</li>
<li>"Rebuild Project</li>
</ul>
<p>Error is:</p>
<pre><code>Error:Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
> java.lang.RuntimeException: java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex
</code></pre>
<p><strong>Project build.gradle</strong></p>
<pre><code>buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.0'
classpath 'com.google.gms:google-services:3.1.0'
}
}
allprojects {
repositories {
jcenter()
google()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
</code></pre>
<p><strong>App build.gradle</strong></p>
<pre><code>apply plugin: 'com.android.application'
android {
compileSdkVersion 26
buildToolsVersion '26.0.2'
defaultConfig {
applicationId "com.asanquran.mnaum.quranasaanurdutarjuma"
minSdkVersion 15
targetSdkVersion 26
versionCode 3
versionName "1.3"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:26.+'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.google.android.gms:play-services-ads:11.4.2'
compile 'com.github.barteksc:android-pdf-viewer:2.3.0'
compile 'org.apache.commons:commons-io:1.3.2'
compile 'com.google.firebase:firebase-ads:11.4.2'
compile 'com.google.firebase:firebase-messaging:11.4.2'
compile 'com.google.firebase:firebase-storage:11.4.2'
apply plugin: 'com.google.gms.google-services'
testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'
</code></pre> | 59,004,954 | 9 | 9 | null | 2017-10-27 14:20:53.887 UTC | 7 | 2021-01-16 17:04:31.567 UTC | 2019-12-14 19:34:39.5 UTC | null | 6,936,929 | null | 8,002,684 | null | 1 | 39 | android|gradle|merge|dex|android-studio-3.0 | 68,189 | <p>I think it was due to Android Studio's latest version (at that time).
I tried it after a long time then the issue gone.</p> |
2,031,577 | Can memory be cleaned up? | <p>I am working in Delphi 5 (with FastMM installed) on a Win32 project, and have recently been trying to drastically reduce the memory usage in this application. So far, I have cut the usage nearly in half, but noticed something when working on a separate task. When I minimized the application, the memory usage shrunk from 45 megs down to 1 meg, which I attributed to it paging out to disk. When I restored it and restarted working, the memory went up only to 15 megs. As I continued working, the memory usage slowly went up again, and a minimize and restore flushed it back down to 15 megs. So to my thinking, when my code tells the system to release the memory, it is still being held on to according to Windows, and the actual garbage collection doesn't kick in until a lot later. </p>
<p>Can anyone confirm/deny this sort of behavior? Is it possible to get the memory cleaned up programatically? If I keep using the program without doing this manual flush, I get an out of memory error after a while, and would like to eliminate that. Thanks.</p>
<p>Edit: I found an article on <a href="http://delphi.about.com/od/windowsshellapi/ss/setprocessworkingsetsize-delphi-program-memory-optimize.htm" rel="noreferrer">about.com</a> that gives a lot of this as well as some links and data for other areas of memory management.</p> | 2,033,393 | 7 | 4 | null | 2010-01-08 23:44:41.547 UTC | 21 | 2014-02-08 15:26:45.213 UTC | 2010-04-07 22:44:03.217 UTC | null | 34,504 | null | 34,504 | null | 1 | 30 | delphi|garbage-collection|memory-management | 10,008 | <p>This is what we use in <a href="http://17slon.com/gp/gp/dsiwin32.htm" rel="noreferrer">DSiWin32</a>:</p>
<pre><code>procedure DSiTrimWorkingSet;
var
hProcess: THandle;
begin
hProcess := OpenProcess(PROCESS_SET_QUOTA, false, GetCurrentProcessId);
try
SetProcessWorkingSetSize(hProcess, $FFFFFFFF, $FFFFFFFF);
finally CloseHandle(hProcess); end;
end; { DSiTrimWorkingSet }
</code></pre> |
1,573,548 | How does Python know where the end of a function is? | <p>I'm just learning python and confused when a "def" of a function ends?</p>
<p>I see code samples like:</p>
<pre><code>def myfunc(a=4,b=6):
sum = a + b
return sum
myfunc()
</code></pre>
<p>I know it doesn't end because of the return (because I've seen if statements... if FOO than return BAR, else return FOOBAR). How does Python know this isn't a recursive function that calls itself? When the function runs does it just keep going through the program until it finds a return? That'd lead to some interesting errors.</p>
<p>Thanks</p> | 1,573,555 | 8 | 6 | null | 2009-10-15 16:32:53.44 UTC | 14 | 2022-08-13 13:38:38.863 UTC | 2022-08-13 13:38:38.863 UTC | null | 523,612 | null | 110,797 | null | 1 | 53 | python|syntax|indentation | 183,587 | <p>In Python whitespace is significant. The function ends when the indentation becomes smaller (less).</p>
<pre><code>def f():
pass # first line
pass # second line
pass # <-- less indentation, not part of function f.
</code></pre>
<p>Note that one-line functions can be written without indentation, on one line:</p>
<pre><code>def f(): pass
</code></pre>
<p>And, then there is the use of semi-colons, but this is <strong>not recommended</strong>:</p>
<pre><code>def f(): pass; pass
</code></pre>
<p>The three forms above show how the end of a function is defined <em>syntactically</em>. As for the <em>semantics</em>, in Python there are three ways to exit a function:</p>
<ul>
<li><p>Using the <code>return</code> statement. This works the same as in any other imperative programming language you may know.</p></li>
<li><p>Using the <code>yield</code> statement. This means that the function is a generator. Explaining its semantics is beyond the scope of this answer. Have a look at <a href="https://stackoverflow.com/questions/231767/can-somebody-explain-me-the-python-yield-statement"><em>Can somebody explain me the python yield statement?</em></a></p></li>
<li><p>By simply executing the last statement. If there are no more statements and the last statement is not a <code>return</code> statement, then the function exists as if the last statement were <code>return None</code>. That is to say, without an explicit <code>return</code> statement a function returns <code>None</code>. This function returns <code>None</code>:</p>
<pre><code>def f():
pass
</code></pre>
<p>And so does this one:</p>
<pre><code>def f():
42
</code></pre></li>
</ul> |
1,525,672 | Determine a table's primary key using TSQL | <p>I'd like to determine the primary key of a table using TSQL (stored procedure or system table is fine). Is there such a mechanism in SQL Server (2005 or 2008)?</p> | 1,525,708 | 10 | 0 | null | 2009-10-06 13:42:03.66 UTC | 10 | 2020-11-13 22:26:20.737 UTC | 2009-10-06 14:47:37.957 UTC | null | 135,152 | null | 100,142 | null | 1 | 56 | sql|sql-server|tsql|primary-key | 61,867 | <p>This should get you started:</p>
<pre><code>SELECT
*
FROM
INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
JOIN
INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ccu
ON tc.CONSTRAINT_NAME = ccu.Constraint_name
WHERE
tc.TABLE_NAME = 'TableName' AND
tc.CONSTRAINT_TYPE = 'Primary Key'
</code></pre> |
2,268,417 | Expire a view-cache in Django? | <p>The <code>@cache_page decorator</code> is awesome. But for my blog I would like to keep a page in cache until someone comments on a post. This sounds like a great idea as people rarely comment so keeping the pages in memcached while nobody comments would be great. I'm thinking that someone must have had this problem before? And this is different than caching per url.</p>
<p>So a solution I'm thinking of is:</p>
<pre><code>@cache_page( 60 * 15, "blog" );
def blog( request ) ...
</code></pre>
<p>And then I'd keep a list of all cache keys used for the blog view and then have way of expire the "blog" cache space. But I'm not super experienced with Django so I'm wondering if someone knows a better way of doing this?</p> | 2,363,690 | 15 | 0 | null | 2010-02-15 19:33:39.64 UTC | 19 | 2021-07-08 06:14:43.1 UTC | 2016-07-22 22:54:38.293 UTC | null | 1,245,190 | null | 109,472 | null | 1 | 59 | python|django|caching | 24,072 | <p><em>This solution works for django versions before 1.7</em></p>
<p>Here's a solution I wrote to do just what you're talking about on some of my own projects:</p>
<pre><code>def expire_view_cache(view_name, args=[], namespace=None, key_prefix=None):
"""
This function allows you to invalidate any view-level cache.
view_name: view function you wish to invalidate or it's named url pattern
args: any arguments passed to the view function
namepace: optioal, if an application namespace is needed
key prefix: for the @cache_page decorator for the function (if any)
"""
from django.core.urlresolvers import reverse
from django.http import HttpRequest
from django.utils.cache import get_cache_key
from django.core.cache import cache
# create a fake request object
request = HttpRequest()
# Loookup the request path:
if namespace:
view_name = namespace + ":" + view_name
request.path = reverse(view_name, args=args)
# get cache key, expire if the cached item exists:
key = get_cache_key(request, key_prefix=key_prefix)
if key:
if cache.get(key):
# Delete the cache entry.
#
# Note that there is a possible race condition here, as another
# process / thread may have refreshed the cache between
# the call to cache.get() above, and the cache.set(key, None)
# below. This may lead to unexpected performance problems under
# severe load.
cache.set(key, None, 0)
return True
return False
</code></pre>
<p>Django keys these caches of the view request, so what this does is creates a fake request object for the cached view, uses that to fetch the cache key, then expires it. </p>
<p>To use it in the way you're talking about, try something like:</p>
<pre><code>from django.db.models.signals import post_save
from blog.models import Entry
def invalidate_blog_index(sender, **kwargs):
expire_view_cache("blog")
post_save.connect(invalidate_portfolio_index, sender=Entry)
</code></pre>
<p>So basically, when ever a blog Entry object is saved, invalidate_blog_index is called and the cached view is expired. NB: haven't tested this extensively, but it's worked fine for me so far. </p> |
18,090,481 | how to replace characters in hive? | <p>I have a string column <code>description</code> in a hive table which may contain tab characters <code>'\t'</code>, these characters are however messing some views when connecting hive to an external application.
is there a simple way to get rid of all tab characters in that column?. I could run a simple python program to do it, but I want to find a better solution for this.</p> | 18,098,996 | 5 | 0 | null | 2013-08-06 21:05:47.02 UTC | 7 | 2018-09-13 14:05:18.593 UTC | 2013-08-06 21:15:19.783 UTC | null | 2,540,455 | null | 1,745,713 | null | 1 | 31 | hadoop|hive | 186,019 | <p><code>regexp_replace</code> UDF performs my task. Below is the definition and usage from apache Wiki.</p>
<pre><code>regexp_replace(string INITIAL_STRING, string PATTERN, string REPLACEMENT):
</code></pre>
<p>This returns the string resulting from replacing all substrings in <code>INITIAL_STRING</code>
that match the java regular expression syntax defined in <code>PATTERN</code> with instances of <code>REPLACEMENT</code>, </p>
<p>e.g.: <code>regexp_replace("foobar", "oo|ar", "")</code> returns <code>fb</code></p> |
17,997,228 | What is a dangling pointer? | <p>I know this is pretty common question, but still new for me!</p>
<p>I don't understand concept of dangling pointer, was googling around, and writing test methods to find one.</p>
<p>I just wonder is this a dangling pointer? As whatever example I found was returning something, here I'm trying something similar!</p>
<p>Thanks!</p>
<pre class="lang-cxx prettyprint-override"><code>void foo(const std::string name)
{
// will it be Dangling pointer?!, with comments/Answer
// it could be if in new_foo, I store name into Global.
// Why?! And what is safe then?
new_foo(name.c_str());
}
void new_foo(const char* name)
{
// print name or do something with name...
}
</code></pre> | 17,997,314 | 7 | 7 | null | 2013-08-01 14:45:21.163 UTC | 32 | 2020-08-10 14:19:48.067 UTC | 2018-11-13 19:43:21.72 UTC | null | 4,618,308 | null | 1,337,514 | null | 1 | 66 | c++|pointers|dangling-pointer | 88,349 | <p>A dangling pointer is a pointer that points to invalid data or to data which is not valid anymore, for example:</p>
<pre><code>Class *object = new Class();
Class *object2 = object;
delete object;
object = nullptr;
// now object2 points to something which is not valid anymore
</code></pre>
<p>This can occur even in stack allocated objects:</p>
<pre><code>Object *method() {
Object object;
return &object;
}
Object *object2 = method();
// object2 points to an object which has been removed from stack after exiting the function
</code></pre>
<p>The pointer returned by <code>c_str</code> may become invalid if the string is modified afterwards or destroyed. In your example you don't seem to modify it, but since it's not clear what you are going to do with <code>const char *name</code> it's impossible to know it your code is inherently safe or not.</p>
<p>For example, if you store the pointer somewhere and then the corresponding string is destroyed, the pointer becomes invalid. If you use <code>const char *name</code> just in the scope of <code>new_foo</code> (for example, for printing purposes) then the pointer will remain valid.</p> |
17,812,566 | Count words and spaces in string C# | <p>I want to count words and spaces in my string. String looks like this:</p>
<pre><code>Command do something ptuf(123) and bo(1).ctq[5] v:0,
</code></pre>
<p>I have something like this so far</p>
<pre><code>int count = 0;
string mystring = "Command do something ptuf(123) and bo(1).ctq[5] v:0,";
foreach(char c in mystring)
{
if(char.IsLetter(c))
{
count++;
}
}
</code></pre>
<p>What should I do to count spaces also?</p> | 17,812,655 | 10 | 4 | null | 2013-07-23 14:07:09.493 UTC | 3 | 2021-06-22 08:22:35.057 UTC | null | null | null | null | 2,592,968 | null | 1 | 12 | c#|winforms|visual-studio-2010 | 58,778 | <pre><code>int countSpaces = mystring.Count(Char.IsWhiteSpace); // 6
int countWords = mystring.Split().Length; // 7
</code></pre>
<p>Note that both use <a href="http://msdn.microsoft.com/en-us/library/t809ektx.aspx" rel="noreferrer"><code>Char.IsWhiteSpace</code></a> which assumes other characters than <code>" "</code> as white-space(like <code>newline</code>). Have a look at the remarks section to see which exactly .</p> |
6,810,581 | How to center the text in a JLabel? | <p>despite many tries I can't get the result that I would like to see - text centered within the JLabel and the JLabel somewhat centered in the BorderLayout. I said "somewhat" because there should be also another label "status" in the bottom-right corner of the window. Here the bit of code responsible for that: </p>
<pre><code>setLayout(new BorderLayout());
JPanel area = new JPanel();
JLabel text = new JLabel(
"<html>In early March, the city of Topeka," +
" Kansas,<br>temporarily changed its name to Google..." +
"<br><br>...in an attempt to capture a spot<br>" +
"in Google's new broadband/fiber-optics project." +
"<br><br><br>source: http://en.wikipedia.org/wiki/Google_server" +
"#Oil_Tanker_Data_Center</html>", SwingConstants.CENTER);
text.setVerticalAlignment(SwingConstants.CENTER);
JLabel status = new JLabel("status", SwingConstants.SOUTH_EAST);
status.setVerticalAlignment(SwingConstants.CENTER);
Font font = new Font("SansSerif", Font.BOLD, 30);
text.setFont(font);
area.setBackground(Color.darkGray);
text.setForeground(Color.green);
// text.setAlignmentX(CENTER_ALIGNMENT);
// text.setAlignmentY(CENTER_ALIGNMENT);
// text.setHorizontalAlignment(JLabel.CENTER);
// text.setVerticalAlignment(JLabel.CENTER);
Font font2 = new Font("SansSerif", Font.BOLD, 20);
status.setFont(font2);
status.setForeground(Color.green);
area.add(text, BorderLayout.CENTER);
area.add(status, BorderLayout.EAST);
this.add(area);
</code></pre>
<p>Thanks for any help provided.</p> | 6,810,590 | 3 | 1 | null | 2011-07-25 00:00:37.593 UTC | 8 | 2018-05-03 18:10:51.607 UTC | 2015-06-15 09:36:05.477 UTC | null | 4,112,664 | null | 852,892 | null | 1 | 48 | java|swing|user-interface|jlabel|htmltext | 178,000 | <pre><code>String text = "In early March, the city of Topeka, Kansas," + "<br>" +
"temporarily changed its name to Google..." + "<br>" + "<br>" +
"...in an attempt to capture a spot" + "<br>" +
"in Google's new broadband/fiber-optics project." + "<br>" + "<br>" +"<br>" +
"source: http://en.wikipedia.org/wiki/Google_server#Oil_Tanker_Data_Center";
JLabel label = new JLabel("<html><div style='text-align: center;'>" + text + "</div></html>");
</code></pre> |
6,594,649 | How to split string into paragraphs using first comma? | <p>I have string: <code>@address = "10 Madison Avenue, New York, NY - (212) 538-1884"</code>
What's the best way to split it like this?</p>
<pre><code><p>10 Madison Avenue,</p>
<p>New York, NY - (212) 538-1884</p>
</code></pre> | 6,594,749 | 4 | 0 | null | 2011-07-06 10:02:44.56 UTC | 5 | 2018-02-21 12:55:58.897 UTC | 2018-02-21 12:55:58.897 UTC | null | 480,410 | null | 480,410 | null | 1 | 36 | ruby-on-rails|ruby|string|split | 16,245 | <p>String#split has a second argument, the maximum number of fields returned in the result array:
<a href="http://ruby-doc.org/core/classes/String.html#M001165">http://ruby-doc.org/core/classes/String.html#M001165</a></p>
<p><code>@address.split(",", 2)</code> will return an array with two strings, split at the first occurrence of ",".</p>
<p>the rest of it is simply building the string using interpolation or if you want to have it more generic, a combination of <code>Array#map</code> and <code>#join</code> for example</p>
<pre><code>@address.split(",", 2).map {|split| "<p>#{split}</p>" }.join("\n")
</code></pre> |
35,907,642 | Custom header to HttpClient request | <p>How do I add a custom header to a <code>HttpClient</code> request? I am using <code>PostAsJsonAsync</code> method to post the JSON. The custom header that I would need to be added is </p>
<pre><code>"X-Version: 1"
</code></pre>
<p>This is what I have done so far:</p>
<pre><code>using (var client = new HttpClient()) {
client.BaseAddress = new Uri("https://api.clickatell.com/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "xxxxxxxxxxxxxxxxxxxx");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.PostAsJsonAsync("rest/message", svm).Result;
}
</code></pre> | 43,780,538 | 8 | 3 | null | 2016-03-10 04:32:18.777 UTC | 23 | 2022-08-26 07:56:37.003 UTC | 2020-07-16 14:16:07.003 UTC | null | 271,200 | null | 2,556,858 | null | 1 | 206 | c#|asp.net|http-headers|dotnet-httpclient | 289,848 | <pre><code>var request = new HttpRequestMessage {
RequestUri = new Uri("[your request url string]"),
Method = HttpMethod.Post,
Headers = {
{ "X-Version", "1" } // HERE IS HOW TO ADD HEADERS,
{ HttpRequestHeader.Authorization.ToString(), "[your authorization token]" },
{ HttpRequestHeader.ContentType.ToString(), "multipart/mixed" },//use this content type if you want to send more than one content type
},
Content = new MultipartContent { // Just example of request sending multipart request
new ObjectContent<[YOUR JSON OBJECT TYPE]>(
new [YOUR JSON OBJECT TYPE INSTANCE](...){...},
new JsonMediaTypeFormatter(),
"application/json"), // this will add 'Content-Type' header for the first part of request
new ByteArrayContent([BINARY DATA]) {
Headers = { // this will add headers for the second part of request
{ "Content-Type", "application/Executable" },
{ "Content-Disposition", "form-data; filename=\"test.pdf\"" },
},
},
},
};
</code></pre> |
52,277,629 | Remove Gutenberg CSS | <p>I have Gutenberg plugin installed in WordPress v4.9.8 and am trying to remove the CSS that comes with it so I can supply my own.</p>
<p>This is the sheet that gets included: </p>
<pre><code><link rel='stylesheet' id='wp-block-library-css' href='/wp-content/plugins/gutenberg/build/block-library/style.css?ver=1535795173' type='text/css' media='all' />
</code></pre>
<p>I have tried the following:</p>
<pre><code>add_action( 'wp_print_styles', 'wps_deregister_styles', 100 );
function wps_deregister_styles() {
wp_dequeue_style( 'wp-block-library-css' );
wp_deregister_style( 'wp-block-library-css' );
}
</code></pre>
<p>As well as variations of this, but the file persists. How can I remove it?</p> | 52,280,110 | 11 | 8 | null | 2018-09-11 13:55:16.243 UTC | 5 | 2022-01-14 09:48:03.263 UTC | 2019-05-29 05:46:21.597 UTC | null | 2,674,937 | null | 874,691 | null | 1 | 32 | css|wordpress|wordpress-gutenberg | 34,032 | <p>I'm adding this as a more complete answer than my comment:</p>
<p>You need to remove the <code>-css</code> when trying to dequeue the script. That's added to the HTML markup and not the actual tag for the css file.</p>
<p>If you search the code (the location of the enqueue may change as Gutenberg gets rolled into core), you can find:</p>
<pre><code>wp_enqueue_style( 'wp-block-library' );
</code></pre>
<p>As you can see, there is no <code>-css</code>. This solution may work for other plugins that people have trouble dequeuing styles.</p>
<p><strong>Edit:</strong>
Since this still gets some traction, here is the code to handle it:</p>
<pre><code>add_action( 'wp_print_styles', 'wps_deregister_styles', 100 );
function wps_deregister_styles() {
wp_dequeue_style( 'wp-block-library' );
}
</code></pre> |
18,294,726 | Calling order of link function in nested and repeated angularjs directives | <p>I'm fairly new to Javascript programming and I have only touched upon AngularJS. In order to evaluate it I decided to write a simple note application. The model is really simple, a list of notes where each note has a label, a text and a list of tags. However I ran into problem passing data between isolated scopes of nested directives. </p>
<p>I have three directives, notes, note and tagger (defining new elements with the same names). Each of them using an isolated scope.</p>
<p>The notes directive uses ng-repeat to "render" each one of its notes with the note element. </p>
<p>The note directive uses the tagger element to "render" the list of tags.</p>
<p>The note directive defines scope: { getNote: "&", ... } in order to pass a note instance from the list of notes to the note controller/directive. The getNote(index) function is called in the link function of the note directive. This works fine!</p>
<p>The tagger directive defines scope: { getTags: "&", ... } in order to pass a list of tags for a given note to the tagger controller/directive. The getTags function is called in the link function of the tagger directive. This does not work!</p>
<p>As I understand it, the problem is that the link functions of the directives are called in an inconsistent order. Debugging the application shows that the link functions are called in the following order:</p>
<ol>
<li><p>link function in the notes directive
(adding the getNote function to the notes scope) </p></li>
<li><p>link function in the tagger directive of the first note
(calling getTags in the parent note scope) function</p></li>
<li><p>link function in the first note directive
(adding the getTags to the scope)
(calling getNote in the parent notes scope) </p></li>
<li><p>link function in the tagger directive of the second note
(calling getTags in the parent note scope) function</p></li>
<li><p>link function in the second note directive
(adding the getTags to the scope)
(calling getNote in the parent notes scope) </p></li>
</ol>
<p>This will not work since in #2 the scope of the first note has not yet an getTags function.</p>
<p>A simplistic example can be found in <a href="http://plnkr.co/wq4Z0Z5iBvYRT5LqiDoy" rel="noreferrer">Plunker</a>.</p>
<p>Hence, my question boils down to: What determines the order in which link functions are called in nested directives.</p>
<p>(I solved to the problem using $watch on getTags in the tagger directive...) </p>
<p>regards</p> | 18,491,502 | 2 | 1 | null | 2013-08-18 00:55:59.473 UTC | 10 | 2013-08-28 14:59:27.053 UTC | null | null | null | null | 1,158,228 | null | 1 | 10 | angularjs|angularjs-directive|angularjs-scope|angularjs-ng-repeat | 6,343 | <p>Quoting Josh D. Miller who had kindly responded to a similar question I had : </p>
<p>" Just a couple of technical notes. Assume that you have this markup:</p>
<pre><code><div directive1>
<div directive2>
<!-- ... -->
</div>
</div>
</code></pre>
<p>Now AngularJS will create the directives by running directive functions in a certain order:</p>
<blockquote>
<p>directive1: compile</p>
<blockquote>
<blockquote>
<p>directive2: compile</p>
</blockquote>
</blockquote>
<p>directive1: controller</p>
<p>directive1: pre-link</p>
<blockquote>
<blockquote>
<p>directive2: controller</p>
<p>directive2: pre-link</p>
<p>directive2: post-link</p>
</blockquote>
</blockquote>
<p>directive1: post-link</p>
</blockquote>
<p>By default a straight "link" function is a post-link, so your outer directive1's link function will not run until after the inner directive2's link function has ran. That's why we say that it's only safe to do DOM manipulation in the post-link. "</p> |
15,557,450 | Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON' Possible Connection String Issue? | <p>I'm attempting to deploy my first MVC application and I keep running into issues revolving around connecting to my sql server database. My current problem is that when I try to publish the site, I'm greeted with: SqlException (0x80131904): Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'. What I'm not sure of however, is if this is my main issue or just a symptom of a different problem all together. I think the issue has to do with my connection strings (although I certainly could be wrong about that), which I've tweaked about 20 different ways. My most recent attampt to get it to work looks like this:</p>
<pre><code><add name="DefaultConnection"
connectionString="Data Source=*ip address*;AttachDbFilename=C:\*full path*\aspnet-SourceMvc-20130301025953.mdf;Initial Catalog=aspnet-SourceMvc-20130301025953;Integrated Security=True"
providerName="System.Data.SqlClient" />
<add name="StqmContext"
connectionString="Data Source=*ip address*;AttachDbFilename=C:\*full path*\Quotes.mdf;Initial Catalog=Quotes;Integrated Security=True"
providerName="System.Data.SqlClient" />
</code></pre>
<p>I've spent all day researching the issue, which seems pretty common, but they all seem to offer different solutions...non of which have worked so far. </p>
<p>Some additional information about the application: It's an ASP.NET MVC 4 application. The database was constructed using the Entity Framework Code-First method and I'm running SQl Server 2012, Enterprise ed. on Windows Server 2008 R2. The application was originally developed on my Windows 8 machine using Visual Studio 2012 Ultimate, and once I finished it, I moved it to my work machine with Windows Server 2008 R2 and am trying to publish it in Visual Studio Express 2012 Web Developer ed.</p>
<p>On a side note, how do you open a database that was created using code first in the sql server management studio?</p>
<p>Thanks in advance to anyone who can help.</p>
<pre><code>Stack Trace:
[SqlException (0x80131904): Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'.]
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +6676046
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +810
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +4403
System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +84
System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK) +55
System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover) +368
System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout) +6704814
System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance) +6705315
System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions) +610
System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) +1049
System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) +74
System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnectionOptions userOptions) +6707883
System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnectionOptions userOptions) +78
System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) +2192
System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) +116
System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) +1012
System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +6712511
System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) +152
System.Data.SqlClient.SqlConnection.Open() +229
System.Data.SqlClient.SqlProviderServices.UsingConnection(SqlConnection sqlConnection, Action`1 act) +134
System.Data.SqlClient.SqlProviderServices.UsingMasterConnection(SqlConnection sqlConnection, Action`1 act) +3805003
System.Data.SqlClient.SqlProviderServices.GetDbProviderManifestToken(DbConnection connection) +10955690
System.Data.Common.DbProviderServices.GetProviderManifestToken(DbConnection connection) +91
[ProviderIncompatibleException: The provider did not return a ProviderManifestToken string.]
System.Data.Common.DbProviderServices.GetProviderManifestToken(DbConnection connection) +10955761
System.Data.Entity.ModelConfiguration.Utilities.DbProviderServicesExtensions.GetProviderManifestTokenChecked(DbProviderServices providerServices, DbConnection connection) +48
[ProviderIncompatibleException: An error occurred while getting provider information from the database. This can be caused by Entity Framework using an incorrect connection string. Check the inner exceptions for details and ensure that the connection string is correct.]
System.Data.Entity.ModelConfiguration.Utilities.DbProviderServicesExtensions.GetProviderManifestTokenChecked(DbProviderServices providerServices, DbConnection connection) +242
System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection) +82
System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext) +88
System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input) +248
System.Data.Entity.Internal.LazyInternalContext.InitializeContext() +524
System.Data.Entity.Internal.InternalContext.CreateObjectContextForDdlOps() +23
System.Data.Entity.Database.Exists() +40
SourceMvc.Filters.SimpleMembershipInitializer..ctor() +128
[InvalidOperationException: The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588]
SourceMvc.Filters.SimpleMembershipInitializer..ctor() +461
[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +159
System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +256
System.Activator.CreateInstance(Type type, Boolean nonPublic) +127
System.Activator.CreateInstance(Type type) +11
System.Threading.LazyHelpers`1.ActivatorFactorySelector() +72
System.Threading.LazyInitializer.EnsureInitializedCore(T& target, Boolean& initialized, Object& syncLock, Func`1 valueFactory) +241
System.Threading.LazyInitializer.EnsureInitialized(T& target, Boolean& initialized, Object& syncLock) +139
System.Web.Mvc.Async.AsyncControllerActionInvoker.InvokeActionMethodFilterAsynchronously(IActionFilter filter, ActionExecutingContext preContext, Func`1 nextInChain) +145
System.Web.Mvc.Async.AsyncControllerActionInvoker.InvokeActionMethodFilterAsynchronously(IActionFilter filter, ActionExecutingContext preContext, Func`1 nextInChain) +840201
System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__31(AsyncCallback asyncCallback, Object asyncState) +266
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +146
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout) +202
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag) +112
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__1e(AsyncCallback asyncCallback, Object asyncState) +839055
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +146
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout) +166
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag) +27
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__17(AsyncCallback asyncCallback, Object asyncState) +50
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +146
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout) +166
System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +826145
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +146
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout) +166
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate endDelegate, Object tag) +27
System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +401
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__2(AsyncCallback asyncCallback, Object asyncState) +786250
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +146
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout) +166
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate endDelegate, Object tag) +27
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +343
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +12550291
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +288
</code></pre> | 15,557,494 | 3 | 0 | null | 2013-03-21 20:29:44.677 UTC | 1 | 2022-05-31 17:46:02.913 UTC | null | null | null | null | 1,815,527 | null | 1 | 6 | iis|asp.net-mvc-4|ef-code-first|sql-server-2012|web-deployment | 39,432 | <p>If you intend to use integrated security you need to turn <a href="http://msdn.microsoft.com/en-us/library/72wdk8cc%28v=vs.71%29.aspx" rel="noreferrer">impersonation</a> on:</p>
<pre><code><identity impersonate="true" />
</code></pre>
<p>Otherwise add username and password to the <a href="http://connectionstrings.com/sql-server-2012" rel="noreferrer">connection string</a>:</p>
<pre><code>Data Source=myServerAddress;Initial Catalog=myDataBase;User ID=xxx;Password=yyy;
</code></pre> |