Id int64 34.6M 60.5M | Title stringlengths 15 150 | Body stringlengths 33 36.7k | Tags stringlengths 3 112 | CreationDate stringdate 2016-01-01 00:21:59 2020-02-29 17:55:56 | Y stringclasses 3 values |
|---|---|---|---|---|---|
37,837,132 | How to wait for a stream to finish piping? (Nodejs) | <p>I have a for loop array of promises, so I used Promise.all to go through them and called then afterwards.</p>
<pre><code>let promises = [];
promises.push(promise1);
promises.push(promise2);
promises.push(promise3);
Promise.all(promises).then((responses) => {
for (let i = 0; i < promises.length; i++) {
if (promise.property === something) {
//do something
} else {
let file = fs.createWriteStream('./hello.pdf');
let stream = responses[i].pipe(file);
/*
I WANT THE PIPING AND THE FOLLOWING CODE
TO RUN BEFORE NEXT ITERATION OF FOR LOOP
*/
stream.on('finish', () => {
//extract the text out of the pdf
extract(filePath, {splitPages: false}, (err, text) => {
if (err) {
console.log(err);
} else {
arrayOfDocuments[i].text_contents = text;
}
});
});
}
}
</code></pre>
<p>promise1, promise2, and promise3 are some http requests, and if one of them is an application/pdf, then I write it to a stream and parse the text out of it. But this code runs the next iteration before parsing the test out of the pdf. Is there a way to make the code wait until the piping to the stream and extracting are finished before moving on to the next iteration?</p>
| <node.js><asynchronous><promise><pipe><pdftotext> | 2016-06-15 13:38:35 | HQ |
37,837,303 | How to create a chat program using php and mysqli for chatting | <p>I need to know that how i can create a chat program using php and mysqli
for chatting
Till now I created a Login & Registration form for my website you can visit and see the design and work of my website <a href="http://programmingvivek.twomini.com/" rel="nofollow">http://programmingvivek.twomini.com/</a>
So please help me I am new in PHP
And How to refresh messages using ajax</p>
| <php><mysql><ajax><login><registration> | 2016-06-15 13:45:38 | LQ_CLOSE |
37,837,732 | what is the difference between ruby hash construction with => and :? | What is the difference between the below two examples?
I am confused with this
a = {'a' : 'b'}
a = {'a' => 'b'} | <ruby> | 2016-06-15 14:02:53 | LQ_EDIT |
37,838,012 | C# How to divide a number by another and get the result in the format hh:mm:ss:<remainder> | I want the value of division by the following format:
hh:mm:ss:ff
where ff is the reminder
eg:
63 divide by 25
00:00:02:13
How to achieve this?
Thanks | <c#> | 2016-06-15 14:15:06 | LQ_EDIT |
37,838,273 | Evaluating bash "&&" exit codes behaviour | <p>We had a recent experience with bash that even we found a solution, it keeps twisting my mind. How does bash evaluates the <code>&&</code> expression in terms of return codes?</p>
<p>Executing this script, that should fail because <code>myrandomcommand</code> does not exist:</p>
<pre><code>#!/bin/bash
set -e
echo "foo"
myrandomcommand
echo "bar"
</code></pre>
<p>The result is the expected one:</p>
<pre><code>~ > bash foo.sh
foo
foo.sh: line 6: myrandomcommand: command not found
[exited with 127]
~ > echo $?
127
</code></pre>
<p>But changing slightly the code using the <code>&&</code> expression:</p>
<pre><code>#!/bin/bash
set -e
echo "foo"
myrandomcommand && ls
echo "bar"
</code></pre>
<p>The <code>ls</code> statement is not executed (since the first statement fails and does not evaluate the second statement), but the script behaves very different:</p>
<pre><code>~ > bash foo.sh
foo
foo.sh: line 6: myrandomcommand: command not found
bar # ('bar' is printed now)
~ > echo $?
0
</code></pre>
<p>We found out that using the expression between parenthesis <code>(myrandomcommand && ls)</code> it works as expected (like the first example), but I would like to know why.</p>
| <bash><return><return-value> | 2016-06-15 14:26:58 | HQ |
37,838,297 | Trying to convert the value of a textbox to an int C# .NET | <p>I am currently trying to use the value of a textbox as the value of an integer in a Timer so its like this</p>
<p>User inputs a value
my application reads it and uses the input as a value of interval in a timer
but its giving me this error, whats going on?
<a href="http://i.stack.imgur.com/uow8s.png" rel="nofollow">Here is what it looks like</a></p>
| <c#><.net><string><timer><int> | 2016-06-15 14:28:04 | LQ_CLOSE |
37,838,430 | Detect if page is load from back button | <p>Is there any way to detect if current page came from back button?</p>
<p>I want to load data from cookie only if current page came from back button. </p>
| <javascript><internet-explorer><firefox> | 2016-06-15 14:33:36 | HQ |
37,838,532 | JavaScript split string with .match(regex) | <p>From the Mozilla Developer Network for function <code>split()</code>:</p>
<blockquote>
<p>The split() method returns the new array.</p>
<p>When found, separator is removed from the string and the substrings
are returned in an array. If separator is not found or is omitted, the
array contains one element consisting of the entire string. If
separator is an empty string, str is converted to an array of
characters.</p>
<p>If separator is a regular expression that contains capturing
parentheses, then each time separator is matched, the results
(including any undefined results) of the capturing parentheses are
spliced into the output array. However, not all browsers support this
capability.</p>
</blockquote>
<p>Take the following example:</p>
<pre><code>var string1 = 'one, two, three, four';
var splitString1 = string1.split(', ');
console.log(splitString1); // Outputs ["one", "two", "three", "four"]
</code></pre>
<p>This is a really clean approach. I tried the same with a regular expression and a somewhat different string:</p>
<pre><code>var string2 = 'one split two split three split four';
var splitString2 = string2.split(/\ split\ /);
console.log(splitString2); // Outputs ["one", "two", "three", "four"]
</code></pre>
<p>This works just as well as the first example. In the following example, I have altered the string once more, with 3 different delimiters:</p>
<pre><code>var string3 = 'one split two splat three splot four';
var splitString3 = string3.split(/\ split\ |\ splat\ |\ splot\ /);
console.log(splitString3); // Outputs ["one", "two", "three", "four"]
</code></pre>
<p>However, the regular expression gets relatively messy right now. I can group the different delimiters, however the result will then include these delimiters:</p>
<pre><code>var string4 = 'one split two splat three splot four';
var splitString4 = string4.split(/\ (split|splat|splot)\ /);
console.log(splitString4); // Outputs ["one", "split", "two", "splat", "three", "splot", "four"]
</code></pre>
<p>So I tried removing the spaces from the regular expression while leaving the group, without much avail:</p>
<pre><code>var string5 = 'one split two splat three splot four';
var splitString5 = string5.split(/(split|splat|splot)/);
console.log(splitString5);
</code></pre>
<p>Although, when I remove the parentheses in the regular expression, the delimiter is gone in the split string:</p>
<pre><code>var string6 = 'one split two splat three splot four';
var splitString6 = string6.split(/split|splat|splot/);
console.log(splitString6); // Outputs ["one ", " two ", " three ", " four"]
</code></pre>
<p>An alternative would be to use <code>match()</code> to filter out the delimiters, except I don't really understand how reverse lookaheads work:</p>
<pre><code>var string7 = 'one split two split three split four';
var splitString7 = string7.match(/((?!split).)*/g);
console.log(splitString7); // Outputs ["one ", "", "plit two ", "", "plit three ", "", "plit four", ""]
</code></pre>
<p>It doesn't match the whole word to begin with. And to be honest, I don't even know what's going on here exactly.</p>
<hr>
<p>How do I properly split a string using regular expressions without having the delimiter in my result?</p>
| <javascript><regex><split> | 2016-06-15 14:37:56 | HQ |
37,838,875 | PostMessage from a sandboxed iFrame to the main window, origin is always null | <p>There's something I don't get about the event origin with javascript postMessage event.</p>
<p>Here is my main page:</p>
<pre><code><html>
<body>
<h1>Test</h1>
<h2>Outside</h2>
<iframe src="iframe-include.html"
width="100%" height="100"
sandbox="allow-scripts"></iframe>
<script type="text/javascript">
window.addEventListener('message', function (event) {
console.log(event);
}, false);
</script>
</body>
</html>
</code></pre>
<p>And my iFrame content</p>
<pre><code><html>
<body>
<h3>Inside</h3>
<script type="text/javascript">
var counter = 1,
domain = window.location.protocol + '//' + window.location.host,
send = function () {
window.setTimeout(function () {
console.log('iframe says:', domain);
window.parent.postMessage(counter, domain);
counter += 1;
send();
}, 3000);
};
send();
</script>
</body>
</html>
</code></pre>
<p>Looking at the console, the origin property of the event object is always null, even if the domain variable in the iFrame is correct.</p>
<p>My console says:</p>
<pre><code>iframe-include.html:11 iframe says: http://127.0.0.1:8181
iframe.html:11 MessageEvent {isTrusted: true, data: 2, origin: "null", lastEventId: "", source: Window…}
</code></pre>
<p>In every doc, it says that it's important to check on event.origin inside de "message" event listener. But how to do that if it's always null?</p>
<p>Thanks for the help</p>
| <javascript><html><postmessage> | 2016-06-15 14:52:30 | HQ |
37,839,244 | Color gamut in Xcode 8 | <p>Today I have installed Xcode 8(beta) and exploring Storyboards. Here we can now set background and tintColor for different traits. That's good news.</p>
<p>But here with trait collection(for example any height X any width) there is another selection of <code>gamuts</code></p>
<p>Here is the screenshot<a href="https://i.stack.imgur.com/LN8Um.png" rel="noreferrer"><img src="https://i.stack.imgur.com/LN8Um.png" alt="enter image description here"></a></p>
<p>As I have searched for <code>gamut</code>, I found that it is related with color.
I have tried with different combination of <code>gamuts</code> but I am unable to see any difference.</p>
<p>The <a href="https://developer.apple.com/library/prerelease/content/samplecode/ColorGamutShowcase/Listings/README_md.html#//apple_ref/doc/uid/TP40017308-README_md-DontLinkElementID_8" rel="noreferrer">documentation</a> is also not helpful. </p>
<p>The question is how the developers get the benefit of this feature?</p>
| <ios><xcode8><gamut> | 2016-06-15 15:07:37 | HQ |
37,839,365 | Simple HTTP/TCP health check for MongoDB | <p>I need to create a Health Check for a MongoDB instance inside a Docker container.</p>
<p>Although I can make a workaround and use the Mongo Ping using the CLI, the best option is to create a simple HTTP or TCP testing. There is no response in the default 27017 port in standard ping testings.</p>
<p>Is there any trustworthy way to do it?</p>
| <mongodb><http><tcp> | 2016-06-15 15:13:13 | HQ |
37,840,142 | How to avoid flake8's "F821 undefined name '_'" when _ has been installed by gettext? | <h2>Problem overview:</h2>
<p>In my project's main script, <code>gettext</code> installs the function <code>_()</code> that is used in other modules for translations (like in <code>print(_('Something to translate'))</code>).</p>
<p>As stated by <a href="https://docs.python.org/3/library/gettext.html#gettext.install" rel="noreferrer">the doc</a>:</p>
<blockquote>
<p>the _() function [is] installed in Python’s builtins namespace, so it is easily accessible in all modules of your application.</p>
</blockquote>
<p>So, everything runs fine.</p>
<p><em>Only problem</em>: <code>flake8</code> shows errors (actually returned by PyFlakes):</p>
<pre><code>$ flake8 *.py
lib.py:2:12: F821 undefined name '_'
main_script.py:8:7: F821 undefined name '_'
</code></pre>
<p>This is normal, as <code>_</code> is indeed not defined in main_script.py nor lib.py.</p>
<h2>Simple structure that reproduces the problem:</h2>
<pre><code>.
├── lib.py
├── locale
│ └── de
│ └── LC_MESSAGES
│ ├── myapp.mo
│ └── myapp.po
└── main_script.py
</code></pre>
<p>Where lib.py contains this:</p>
<pre><code>def fct(sentence):
return _(sentence)
</code></pre>
<p>and main_script.py this:</p>
<pre><code>#!/usr/bin/env python3
import gettext
import lib
gettext.translation('myapp', 'locale', ['de']).install()
print(_('A sentence'))
print(lib.fct('A sentence'))
</code></pre>
<p>and myapp.po contains:</p>
<pre><code>msgid ""
msgstr ""
"Project-Id-Version: myapp\n"
msgid "A sentence"
msgstr "Ein Satz"
</code></pre>
<p>(was compiled by poedit to produce the mo file).</p>
<p>As stated above, the main script does work:</p>
<pre><code>$ ./main_script.py
Ein Satz
Ein Satz
</code></pre>
<p><strong>Important note: I'm looking for a solution working both for the script where <code>gettext.install()</code> is called <em>and</em> all other modules that <em>do not need to call</em> <code>gettext.install()</code>.</strong> Otherwise, the structure could be even more simple, because calling <code>_()</code> from main_script.py is enough to trigger F821.</p>
<h2>Solutions to solve the situation that look bad (or worse):</h2>
<ul>
<li>add a <code># noqa</code> comment at the end of each line using <code>_()</code></li>
<li><code>--ignore</code> F821 (don't want to do that because this is useful in other situations)</li>
</ul>
| <python><python-3.x><gettext><pyflakes><flake8> | 2016-06-15 15:47:54 | HQ |
37,840,671 | Is creating Equilateral responsinve triangle with backgroung image in css even possibe? | And it also should work in IE11.
I've tried:
- Usuall triangle-crating techinces using border - **Failed**, no background image.
- Clip-path - **Failed** no ie support (damn)
- Triangles with skewing and transfroming have to war of having proper percedt-based lenghts. After ~3 hours of trying to fugure it out - **Failed**
My last desperate effort will probbaly be creating an SVG mask with triangle cutted in it and placing it on top of the <div> with desiered image. But it feels so damn hacky.
And no, it is not my wish to complicate my life so much, its a test task ive got, and i've allready burned away whole day of time, and shitton amount of nerves. Please help! | <html><css><svg> | 2016-06-15 16:13:35 | LQ_EDIT |
37,841,439 | Running SonarQube against an ASP.Net Core solution/project | <p>SonarQube has an MSBuild runner but .NET Core uses dotnet.exe to compile and msbuild just wraps that. I have tried using the MSBuild runner with no success against my ASP.NET Core solution. Using SonarQube Scanner works kind of.</p>
<p>Any suggestions on how I can utilize SonarQube with .NET Core? The static code analysis is what I am looking for.</p>
| <sonarqube><asp.net-core><.net-core> | 2016-06-15 16:56:37 | HQ |
37,842,525 | How to convert 2016-06-14 21:40:53 to today in php | <p>How to convert 2016-06-14 21:40:53 as yesterday, 2016-06-15 21:40:53 as today and 2016-06-16 21:40:53 as tomorrow in php</p>
| <php><mysql><datetime> | 2016-06-15 17:56:46 | LQ_CLOSE |
37,842,913 | Tensorflow: Confusion regarding the adam optimizer | <p>I'm confused regarding as to how the adam optimizer actually works in tensorflow.</p>
<p>The way I read the <a href="https://www.tensorflow.org/versions/r0.9/api_docs/python/train.html#AdamOptimizer" rel="noreferrer">docs</a>, it says that the learning rate is changed every gradient descent iteration. </p>
<p>But when I call the function I give it a learning rate. And I don't call the function to let's say, do one epoch (implicitly calling # iterations so as to go through my data training). I call the function for each batch explicitly like</p>
<pre><code>for epoch in epochs
for batch in data
sess.run(train_adam_step, feed_dict={eta:1e-3})
</code></pre>
<p>So my eta cannot be changing. And I'm not passing a time variable in. Or is this some sort of generator type thing where upon session creation <code>t</code> is incremented each time I call the optimizer?</p>
<p>Assuming it is some generator type thing and the learning rate is being invisibly reduced: How could I get to run the adam optimizer without decaying the learning rate? It seems to me like <a href="https://www.tensorflow.org/versions/r0.9/api_docs/python/train.html#RMSPropOptimizer" rel="noreferrer">RMSProp</a> is basically the same, the only thing I'd have to do to make it equal (learning rate disregarded) is to change the hyperparameters <code>momentum</code> and <code>decay</code> to match <code>beta1</code> and <code>beta2</code> respectively. Is that correct?</p>
| <python><tensorflow> | 2016-06-15 18:17:40 | HQ |
37,843,049 | Xcode 8 / Swift 3: "Expression of type UIViewController? is unused" warning | <p>I've got the following function which compiled cleanly previously but generates a warning with Xcode 8.</p>
<pre><code>func exitViewController()
{
navigationController?.popViewController(animated: true)
}
</code></pre>
<blockquote>
<p>"Expression of type "UIViewController?" is unused".</p>
</blockquote>
<p>Why is it saying this and is there a way to remove it?</p>
<p>The code executes as expected.</p>
| <ios><swift> | 2016-06-15 18:24:57 | HQ |
37,843,132 | Generically derive Arbitrary for massive algebraic data types? | <p>I've got a protocol that I've typed like so:</p>
<pre><code>data ProtocolPacket
= Packet1 Word8 Text Int8
| Packet2 Text
| Packet3 Int Text Text Text Text
| Packet4 Int Double Double Double Int16 Int16 Int16
...
deriving (Show,Eq)
</code></pre>
<p>In addition, I've implemented serialization/deserialization code for each packet. Naturally, I would like to test this protocol in Quickcheck and make sure that serializing and deserializing any packet for any combination of inputs will give me back exactly what I put in. So I go ahead and implement these packets for the <code>Arbitrary</code> type class like so:</p>
<pre><code>instance Arbitrary ProtocolPacket where
arbitrary = do
packetID <- choose (0x00,...) :: Gen Word8
case packetID of
0x00 -> do
a <- arbitrary
b <- arbitrary
c <- arbitrary
return $ Packet1 a b c
0x01 -> do
a <- arbitrary
return $ Packet2 a
0x02 -> do
a <- arbitrary
b <- arbitrary
c <- arbitrary
d <- arbitrary
e <- arbitrary
return $ Packet3 a b c d e
0x03 -> do
a <- arbitrary
b <- arbitrary
c <- arbitrary
d <- arbitrary
e <- arbitrary
f <- arbitrary
g <- arbitrary
return $ Packet4 a b c d e f g
...
</code></pre>
<p>Assume that I've gone ahead and defined <code>Arbitrary</code> for all relevant data constructor arguments that don't have <code>Arbitrary</code> defined out of the box, such code needs to be hand-written by me in order for the packet fields to be populated with meaningful data. But that's it.</p>
<p>But as you can see, I'm repeating myself <em>a lot</em> for something that is just grunt work. And this is a small sample of what I'm actually dealing with. Ideally, I would like to be able to just do this:</p>
<pre><code>{-# LANGUAGE DeriveGeneric #-}
import GHC.Generics
data ProtocolPacket
= Packet1 Word8 Text Int8
| Packet2 Text
| Packet3 Int Text Text Text Text
| Packet4 Int Double Double Double Int16 Int16 Int16
...
deriving (Show,Eq,Generic)
instance Arbitrary ProtocolPacket
</code></pre>
<p>like I can do with <code>FromJSON</code> and <code>ToJSON</code>, but this doesn't work. Is there there a method that does?</p>
| <haskell><generics><quickcheck> | 2016-06-15 18:29:13 | HQ |
37,843,292 | Finding missing entries between two Dictionaries in C# | Suppose that I have two dictionaries as such:
Dictionary<int, int> a = new Dictionary<int, int>(), b = new Dictionary<int, int>();
a.Add(1, 1);
a.Add(2, 2);
a.Add(3, 3);
b.Add(1, 1);
b.Add(2, 2);
What's the best way to extract the difference here, returning a type `Dictionary<int, int>`? | <c#><.net><dictionary> | 2016-06-15 18:37:56 | LQ_EDIT |
37,843,322 | try - catch with syntax error | <pre><code>try {
$stmt = $db->query('SELECT title FROM never-ending-book');
while($row = $stmt->fetch()){
echo '<div class="lev3">'.$row['title'].'</div>';
}
}catch(PDOException $e) {
echo $e->getMessage();
};
</code></pre>
<p>result: </p>
<pre><code>SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '-ending-book' at line 1
</code></pre>
<p>Where is the syntax error and why is <code>never-ending-book</code> become <code>near'-ending-book</code>?</p>
| <php><mysql> | 2016-06-15 18:39:38 | LQ_CLOSE |
37,843,398 | get all items in a list of strings in Python | I got the following code:
import re
dump_final = re.findall(r"\btext=[\w]*", dump5)
Which returns me a list. E.g: Apple, Banana, Lemon
Turns out I need to get all elements of this list and call another function using those elements.
To scan all list, I used:
for index in range(len(dump_final)):
dump_final[index] = dump_final[index].replace("_"," ")
But it returns me characters one by one. I need Apple. Not A, P, P, L, E
how can I get them using loop?
Thank you. | <python><python-2.7> | 2016-06-15 18:43:53 | LQ_EDIT |
37,843,418 | Symbol to signify the root of a project | <p>Is there a well accepted symbol in the programming world for the root of a project?</p>
<p>For example, the tilde ~ is the user's home directory, but this not just convention, but part of UNIX. </p>
<p>I am looking for a symbol that is merely convention.</p>
| <java><node.js><windows><unix><filesystems> | 2016-06-15 18:45:12 | HQ |
37,844,092 | How do I programmatically set an Angular 2 form control to dirty? | <p>How do I mark an Angular 2 Control as dirty in my code?</p>
<p>When I do it like this:</p>
<pre><code>control.dirty = true;
</code></pre>
<p>I get this error:</p>
<pre><code>Cannot set property dirty of #<AbstractControl> which has only a getter
</code></pre>
| <javascript><angular> | 2016-06-15 19:23:28 | HQ |
37,844,414 | I believe my scraper got blocked, but I can access the website via a regular browser, how can they do this? | <p>I recently wrote a rather simple scraper using requests and BeautifulSoup. The scraper worked perfectly until one day, I ran it and received a "Connection reset by peer, Error 54". Despite there being multiple questions about getting around Error 54's that is not what I am wondering. </p>
<p>To test whether or not the blocked my specific IP or computer, I ran the code on a different machine and IP address and it worked fine. The troubling thing however, is that even on my old machine, I can access the site on a regular browser perfectly. </p>
<p>I am wondering both how the website was able to do this without blocking my IP outright and if anyone has any tips for avoiding this in the future.</p>
| <python><web-scraping><ip-address><user-agent> | 2016-06-15 19:43:39 | LQ_CLOSE |
37,844,961 | Why does VBA exist? | I have this function (which I based off a function [here][1]):
Function Foo(ByVal r As range) As String
MsgBox "WHAT. The function worked? Wow!"
End Function
I have tried calling it like so:
Let max_row = cells.CurrentRegion.Columns.Count
Set r = range(cells(2, ID_COL), cells(max_row, ID_COL))
Foo r
And I Always Get the Error: "run-time error 13, type mismatch" once the code hits the call to Foo.
Additionally, putting parentheses around the "r"
Foo(r)
Auto corrects to:
Foo (r)
Which gives the error: "Object Expected"
I assume this means that parentheses deference a pointer to its value, and are not meant for function calls, because VBA was not designed to be a good or even adequate language.
I have also tried writing the function as:
Function Foo(r As range) As String
MsgBox "WHAT. The function worked? Wow!"
End Function
But with no success.
Any ideas?
[1]: http://stackoverflow.com/questions/15888353/concatenate-multiple-ranges-using-vba | <.net><vba><excel><type-mismatch> | 2016-06-15 20:16:16 | LQ_EDIT |
37,845,125 | Custom location for .pypirc file | <p>Does <code>setuptools</code> allow for the <code>.pypirc</code> file to be specified in a custom location rather than <code>$HOME/.pypirc</code>? I'm setting up a jenkins job to publish to an internal repository, and want the <code>.pypirc</code> file to be inside the job's workspace.</p>
| <python><jenkins><setuptools><pypi> | 2016-06-15 20:24:59 | HQ |
37,845,295 | How to List all 32(2^5) combination of binary in C# | <p>How generate all binary combination from 00000 -> 11111 using C# with the easiest way, Thank you.</p>
| <c#><.net><algorithm><sorting><visual-studio-2015> | 2016-06-15 20:36:23 | LQ_CLOSE |
37,846,161 | Haskell program aborts with "loop" but I think it shouldn't | <p>I have this Haskell code which when compiled with GHC and run, aborts with a loop detected.</p>
<pre><code>data Foo = Foo ()
deriving (Eq,Show)
type Foop = Foo -> ((),Foo)
noOp :: Foop
noOp st = ((),st)
someOp :: Foop
someOp st@(Foo x) = ((),st)
(<+>) :: Foop -> Foop -> Foop
(<+>) f g st = let ((_,st'),(_,st'')) = ((f st),(g st')) in ((),st'')
main = print $ (noOp <+> someOp) $ Foo ()
</code></pre>
<p>I think it shouldn't, and here are some modifications. Each of them makes the loop go away:</p>
<ul>
<li>change <code>data Foo</code> to <code>newtype Foo</code></li>
<li>change <code>(noOp <+> someOp)</code> to <code>(someOp <+> noOp)</code></li>
<li>remove the deconstruction <code>@(Foo x)</code></li>
</ul>
<p>Is this a bug in GHC or is it my lack of understanding the evaluation process?</p>
| <haskell> | 2016-06-15 21:33:32 | HQ |
37,847,018 | How can I use Swift 2.3 in XCode 8 Playgrounds? | <p>I have my playground project written in Swift 2.2 and I want take advantage of timeline visuals and try new debug features introduced in Xcode 8 beta. By default, Xcode 8 beta is using Swift 3 in Playgrounds and I cannot find a way to change that. Updating my code to Swift 3 is not an option unfortunately, because my code will be compiled on server with Swift 2.2 environment.</p>
| <swift><swift-playground><xcode8> | 2016-06-15 22:41:12 | HQ |
37,847,097 | HTML - Calling Javascript Function with variable? | <p>So I am trying to do a button and if you click on it then it calls a function called <code>order()</code>. So, If I'm trying to do something like this <code>order("+<script>blablabla</script>+")</code> then it shows me a error if I type into something between the <code>"+HERE+"</code> Why that? Is there any way around it?</p>
| <javascript><html> | 2016-06-15 22:49:10 | LQ_CLOSE |
37,847,271 | Is it possible to dump the AST while building an Xcode project? | <p>I've been doing some work on analyzing Swift projects using their ASTs, and I would like to know if it is possible to generate it somehow when building a Swift project with Xcode.</p>
<p>Right now, I am able to print the AST on the terminal when running the <code>swiftc -dump-ast</code> command for single files and simple projects. However, it becomes harder when using it for more complex projects. </p>
<p>For this reason, I'd like to use xcode. I already tried to pass the <code>-dump-ast</code> flag to the compiler in Build Settings > Swift Compiler - Custom Flags > Other Swift Flags. The flag was indeed passed to the compiler (the output does report calling swiftc with the -dump-ast flag when building). I tried to build the project both with xcode and through the <code>xcodebuild</code>command below, but neither dumped the ast. </p>
<pre><code>xcodebuild -target 'CompilingTest.xcodeproj' -scheme 'CompilingTest' -
configuration "Debug" -sdk iphoneos -arch "armv7"
CONFIGURATION_BUILD_DIR="TestBuild" ONLY_ACTIVE_ARCH=NO
</code></pre>
<p>Now, I'm reasoning that either Xcode's build process redirects swiftc's output to some file, or it silences it somehow. Any thoughts?</p>
<p>Any help would be greatly appreciated.</p>
| <xcode><swift> | 2016-06-15 23:05:56 | HQ |
37,847,338 | Beginner trying to program simple change calculator | <p>I'm new to coding and need to write a program for C#
the goal is to write a program that prompts the user to enter an amount including decimals. and the program gives the user back the remander as money. ie...</p>
<p>quater dimes nickle pennie</p>
| <c#><visual-studio> | 2016-06-15 23:12:52 | LQ_CLOSE |
37,847,425 | CORS not working with route | <p>I have an issue with an endpoint on my web api. I have a POST method that is not working due to:</p>
<blockquote>
<p>Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin '<a href="http://localhost:3000">http://localhost:3000</a>' is therefore not allowed
access. The response had HTTP status code 405.</p>
</blockquote>
<p>I cannot see why that is not working since I have plenty of methods that are working indeed with the same COSR configuration. The only difference is that this method has a specified route, as you can see below:</p>
<pre><code>// POST: api/Clave
[EnableCors(origins: "*", headers: "*", methods: "*", SupportsCredentials = true)]
[Route("{id:int}/clave")]
[HttpPost]
public HttpResponseMessage Post(int id, [FromBody]CambioClaveParameters parametros)
{
UsuarioModel usuario = SQL.GetUsuario(id);
if (Hash.CreateMD5(parametros.ViejaClave) != usuario.Clave.ToUpper())
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
else if (Hash.CreateMD5(parametros.ViejaClave) == usuario.Clave.ToUpper())
{
SQL.ModificarClaveUsuario(id, Hash.CreateMD5(parametros.NuevaClave));
return Request.CreateResponse(HttpStatusCode.OK);
}
else
{
return Request.CreateResponse(HttpStatusCode.InternalServerError);
}
}
</code></pre>
<p>Any Ideas of why this is happening?.</p>
<p>Thanks!.</p>
| <c#><asp.net><asp.net-web-api><cors> | 2016-06-15 23:21:48 | HQ |
37,848,103 | Renaming a List Of Files #1 by another List Of Files #2 | **Renaming a list of files (in one folder) contained in a text file (e.g. MyList1.txt) by another list of files contained in another text file (e.g. MyList2.txt)**
I would like to use a DOS batch (not powershell, script, etc,) who rename a list of files in one folder, contain in a text file, by another list of files contain in another text file.<br/>
**Suppose I have a list of files inside a text file:**<br/>
These files are in one folder (for example ***D:\Librarian***)<br/>
***D:\Test\MyList1.txt***<br/>
Inside this file:<br/>
Directory.zip <br/>
Subject.zip<br/>
Penny.zip<br/>
Car.zip<br/>
Auto.zip<br/>
One_Upon_A_time.zip<br/>
All is relative.zip<br/>
Zen of graphics programming – Corilolis.zip<br/>
PC Magazine – July 1999 No.22.zip<br/>
Bytes is over with quantum.zip<br/>
And I want to replace them by:<br/>
***D:\Test\MyList2.txt***<br/>
Inside this file:<br/>
Patatoes.zip<br/>
Chips.zip<br/>
Hot Dogs Sweet.zip<br/>
Ice Cream_Very – Good.zip<br/>
We must eat to live.zip<br/>
Ketchup on potatoes is a muxt.zip<br/>
The Magazine are owned by few guys.zip<br/>
Desert are not necessary_in life.zip<br/>
Sugar_is_a_legal_drug.zip<br/>
People-who_don’t-like_pizzas_don’t like bread.zip<br/>
**So**<br/>
Directory.zip will come Patatoes.zip<br/>
Subject.zip will come Chips.zip<br/>
Penny.zip will come Hot Dogs Sweet.zip<br/>
Etc.<br/>
Both MyList1.txt and MyList2.txt have same number of lines (same number of filenames)<br/> | <list><file><batch-file><rename> | 2016-06-16 00:47:07 | LQ_EDIT |
37,848,161 | What should be the logic of hashfunction() in order to check that two strings are anagrams or not ? | I want to write a function that takes string as a parameter and returns a number corresponding to that string.
Integer hashfunction(String a)
{
//logic
}
Actually the question im solving is as follows :
Given an array of strings, return all groups of strings that are anagrams. Represent a group by a list of integers representing the index in the original list.
Input : cat dog god tca
Output : [[1, 4], [2, 3]]
Here is my implementation :-
public class Solution {
Integer hashfunction(String a)
{
int i=0;int ans=0;
for(i=0;i<a.length();i++)
{
ans+=(int)(a.charAt(i)); //Adding all ASCII values
}
return new Integer(ans);
}
**Obviously this approach is incorrect**
public ArrayList<ArrayList<Integer>> anagrams(final List<String> a) {
int i=0;
HashMap<String,Integer> hashtable=new HashMap<String,Integer>();
ArrayList<Integer> mylist=new ArrayList<Integer>();
ArrayList<ArrayList<Integer>> answer=new ArrayList<ArrayList<Integer>>();
if(a.size()==1)
{
mylist.add(new Integer(1));
answer.add(mylist);
return answer;
}
int j=1;
for(i=0;i<a.size()-1;i++)
{
hashtable.put(a.get(i),hashfunction(a.get(i)));
for(j=i+1;j<a.size();j++)
{
if(hashtable.containsValue(hashfunction(a.get(j))))
{
mylist.add(new Integer(i+1));
mylist.add(new Integer(j+1));
answer.add(mylist);
mylist.clear();
}
}
}
return answer;
}
}
| <java><hash><hashmap><anagram> | 2016-06-16 00:54:38 | LQ_EDIT |
37,848,437 | Any Way Around Facebook Bots Button Template Limit? | <p>It appears (undocumented) that for a button message type in the Facebook Bots chat system, there is a max of 3 buttons. This seems arbitrary and limiting. Does anyone know if there is a way to have more than 3 buttons? </p>
<p>To be clear, I'm referring to the following message JSON:</p>
<pre><code>{
"recipient":{
"id":"USER_ID"
},
"message":{
"attachment":{
"type":"template",
"payload":{
"template_type":"button",
"text":"What do you want to do next?",
"buttons":[
{
"type":"web_url",
"url":"https://petersapparel.parseapp.com",
"title":"Show Website"
},
{
"type":"postback",
"title":"Start Chatting",
"payload":"USER_DEFINED_PAYLOAD"
}
]
}
}
}
}
</code></pre>
| <facebook><button><chat><bots><messenger> | 2016-06-16 01:28:34 | HQ |
37,848,815 | sqlalchemy postgresql enum does not create type on db migrate | <p>I develop a web-app using Flask under Python3. I have a problem with postgresql enum type on db migrate/upgrade.</p>
<p>I added a column "status" to model:</p>
<pre><code>class Banner(db.Model):
...
status = db.Column(db.Enum('active', 'inactive', 'archive', name='banner_status'))
...
</code></pre>
<p>Generated migration by <code>python manage.py db migrate</code> is:</p>
<pre><code>from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('banner', sa.Column('status', sa.Enum('active', 'inactive', 'archive', name='banner_status'), nullable=True))
def downgrade():
op.drop_column('banner', 'status')
</code></pre>
<p>And when I do <code>python manage.py db upgrade</code> I get an error:</p>
<pre><code>...
sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) type "banner_status" does not exist
LINE 1: ALTER TABLE banner ADD COLUMN status banner_status
[SQL: 'ALTER TABLE banner ADD COLUMN status banner_status']
</code></pre>
<p><strong>Why migration does not create a type "banner_status"?</strong></p>
<p><strong>What am I doing wrong?</strong></p>
<pre><code>$ pip freeze
alembic==0.8.6
Flask==0.10.1
Flask-Fixtures==0.3.3
Flask-Login==0.3.2
Flask-Migrate==1.8.0
Flask-Script==2.0.5
Flask-SQLAlchemy==2.1
itsdangerous==0.24
Jinja2==2.8
Mako==1.0.4
MarkupSafe==0.23
psycopg2==2.6.1
python-editor==1.0
requests==2.10.0
SQLAlchemy==1.0.13
Werkzeug==0.11.9
</code></pre>
| <flask><sqlalchemy><flask-sqlalchemy><flask-migrate><sqlalchemy-migrate> | 2016-06-16 02:17:44 | HQ |
37,849,191 | In javascript, can I use the modulus operator (%) on variables instead of integers? | <p>I'm working on a Euler problem and am trying to build a function that checks a number to see if its a prime. I get error messages about the line:</p>
<pre><code>if (a)%(b)==0{
</code></pre>
<p>Is my syntax wrong or is it impossible to use % on a variable rather on an integer?</p>
<pre><code>var x = Math.sqrt(600851475143);
var y = Math.round(x);
y++;
console.log(y);
//find all of the prime numbers up to the square root number. Put them in an array.
//Check each ascending number against the prime numbers in the array to see if %=0
var primes = [2,3];
var a =(3);
while (a<y){
a++;
isPrime(a)
}
function isPrime(arr){
for (var i = 0; i < arr.length; i++){
var b = primes[i];
//next line is a problem
if (a)%(b)==0{
break
}else{
primes.push(a);
}
}
}
</code></pre>
| <javascript><operators><modulus> | 2016-06-16 03:03:10 | LQ_CLOSE |
37,849,401 | Reverse the scale of the x axis in a plot | <p>I have created a plot in R and my own custom x and y axes. I would like the x axis to be displayed in a reverse order (1-0 by -.02). I have read numerous posts and threads that suggest using xlim and reverse range but I just can't seem to make it work. Once plotted I am also converting the axes labels to percentages by multiplying by 100 (as you will see in the code). Here is what I have so far;</p>
<pre><code>plot(roc.val, xlab = "Specificity (%)", ylab = "Sensitivity (%)", axes = FALSE)
axis(2, at = seq(0,1,by=.2), labels = paste(100*seq(0,1, by=.2)), tick = TRUE)
axis(1, at = seq(0,1,by=.2), labels = paste(100*seq(0,1, by=.2)), tick = TRUE)
</code></pre>
<p>How can I reverse the x axis scale so that the values begin at 100 and end at 0 with increments of 20?</p>
| <r><data-visualization> | 2016-06-16 02:51:00 | HQ |
37,849,433 | Google App Engine multiple regions | <p>Is it possible for my GAE to be balanced accross regions? Like US and Europe.<br>
<a href="https://cloud.google.com/about/locations/" rel="noreferrer">https://cloud.google.com/about/locations/</a><br>
Reading the link above it says that it scales automatically within or accross multi-regional locations.<br>
What does that mean? Do I have to enable automatic scaling across regions? If so, how do I do that?<br>
And secondly, if it does handle automatic scaling across regions, the choice one makes for <code>App engine location</code> when creating a new project, is that irrelevant for a Google App Engine instance?</p>
| <google-app-engine> | 2016-06-16 03:30:09 | HQ |
37,849,771 | Can git be made to mostly auto-merge XML order-insensitive files? | <p>When merging Lightswitch branches, often colleagues will add properties to an entity I also modified, which will result in a merge conflict, as the new XML entries are added to the same positions in the lsml file.</p>
<p>I can effectively always solve these by accepting left and right in no particular order, so one goes above the other, as order isn't important in these particular instances. On the rare instances this isn't valid, this would produce an error in the project anyway, which I accept as a risk (but haven't encountered).</p>
<p>Is there a way (preferably for the file extension) to get git to automatically accept source and target changes for the same position and simply place one beneath the other?</p>
| <xml><git> | 2016-06-16 04:12:33 | HQ |
37,850,054 | number to be printed in a format using java | I am using java script to print a 10 digit number. example 1234567891. But i want that number to be printed in a particular format link 123.456.789-1. Can somebody please help me to sort this.
| <javascript> | 2016-06-16 04:45:01 | LQ_EDIT |
37,850,299 | Android signature verification | <p>I have got lot of doubts to be cleared in the case of Android signature verification and its vulnerability. </p>
<p>Once we generate apk for an application we can unpack the apk and edit resource files using apktool. As we repack the edited apk back it loses its signature. I can resign the unsigned apk using the jarsigner with my own private key that i used while generating the apk. I found an application named zipsigner in playstore which can be used to sign such kind of unsigned apk. </p>
<p>So when this zipsigner signs the unsigned apk, whether the apk is signed with my same private key or with a different key? Because my META-INF folder still holds the XXX.SF and XXX.RSA files which holds the information of my private key. If it is with my same private key then the new apk will be an upgrade for my application or if it is a different key i will be having two different applications with same name. </p>
<p>From the above situations there are possibilities that malware could be included in my apk while repacking. There seems to be a loophole in Android's signature verification mechanism where the message digest of the files inside the META-INF folder are not included in the MANIFEST.MF as well as in the XXX.SF file. This creates a possibility for anyone to include malware codes inside these folders, repack the apk and resign it with the zipsigner application. </p>
<p>I was searching for a solution where i can prevent files being added into the META-INF folder and i found one from the below blog. But I'm unable to get the point of the solution. This looks like more of a research topic so there is not much information available in the internet. Can someone try and figure out the solution specified in the blog. The blog link is specified below the question. </p>
<p><a href="http://blog.trustlook.com/2015/09/09/android-signature-verification-vulnerability-and-exploitation/">http://blog.trustlook.com/2015/09/09/android-signature-verification-vulnerability-and-exploitation/</a></p>
| <java><android><apk> | 2016-06-16 05:07:25 | HQ |
37,850,672 | how to display the link content as hyperlink link text name using html code. | how to display the link content as hyperlink link text name using html code.
example
<a href="file:///C:\Users\jy\Documents\data.xlsx">textname</a>
i want the text name to show the value or data follow cell C9 value in the data.xlsx file
thanks | <html> | 2016-06-16 05:38:12 | LQ_EDIT |
37,851,622 | What SQL Statement can be used to access this information? | <p>I'm trying to write an <code>SQL</code> statement that can be used in <code>PHP</code> for a website, but am having trouble comprehending how to access the information.</p>
<p>I have the following tables..
<a href="https://i.stack.imgur.com/Yvypl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Yvypl.png" alt="enter image description here"></a>
<strong>Please Note:</strong> <code>ACADEMIC_ID</code> & <code>STUDENT_ID</code> are just foreign keys for <code>USER_ID</code>.</p>
<p>My desired result is..
<a href="https://i.stack.imgur.com/df7ez.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/df7ez.png" alt="enter image description here"></a></p>
<p>As I am trying to gain access to the information from the Students View of the website in <code>PHP</code>, I only have the following information to work with..</p>
<ol>
<li>The <code>USER_ID</code> of the student. </li>
<li>The <code>DEBATE_ID</code> for each of the debates the student is currently enrolled in.</li>
</ol>
<p>Therefore..</p>
<blockquote>
<p><em>What SQL statement can be used to give the desired result?</em></p>
</blockquote>
| <php><mysql><database-design> | 2016-06-16 06:40:06 | LQ_CLOSE |
37,852,478 | to all coders whether beginners or experiences please help me with this c code | "please give me quite an explaination so that i can understand my query properly...thank you :) "
i am a beginner and was learning to code using k&r's c programming book. now there is this example of "a program to input set of text lines and print the longest"
i am giving you the whole code......
#define MAXLINE 1000
int getline(char line[], int maxline);
void copy(char to[], char from[]);
int main()
{
int len;
int max;
char line[MAXLINE];
char longest[MAXLINE];
max=0;
while((len=getline(line,MAXLINE))>0)
if(len>max)
{
max=len;
copy(longest,line);
}
if(max>0)
printf("%s",longest);
return 0;
}
int getline(char s[], int lim)
{
int c,i;
for(i=0;i<lim-1&&(c=getchar())!=EOF&&c!='\n';i++)
{
s[i]=c;
if(c=='\n')
{
s[i]='\n';
i++;
}
s[i]='\0';
return i;
}
void copy(char to[], char from[])
{
int i;
i=0;
while((to[i]=from[i])!='\0')
i++;
}
now tell me....
in getline function....
in the statement
for(i=0;i<lim-1&&(c=getchar())!=EOF&&c!='\n';i++)
why do we use " c!='\n' "
and
what is the meaning of code after this for statement
i.e.
s[i]=c;
if(c=='\n)
{
s[i]=c;
i++;
}
s[i]='\0'
why have we used s[i]='\0' in this
and i++; statement in if(c=='\n') condition
| <c> | 2016-06-16 07:23:37 | LQ_EDIT |
37,852,752 | How to use glyphicons in this code below | <?php
$data = array(
'class'=>'btn btn-primary btn-lg btn-myblock',
'name'=>'signin',
'value'=>'Sign In'
);
?>
<?php echo form_submit($data); ?> | <php><codeigniter> | 2016-06-16 07:38:39 | LQ_EDIT |
37,852,968 | How to reload a page in angular2 | <p>How to reload a page in angular2.<br>
While searching through net, i got a code <code>"this._router.renavigate()"</code> to reload the page but looks like its not working with latest release of angular2.<br>
Another way is <code>'window.location.reload()'</code> but this is not the angular way of doing it.</p>
| <angular><angular2-routing> | 2016-06-16 07:49:08 | HQ |
37,854,547 | I need the application to detect what operating system is being run on? | <p>I was going over forums yesterday as my issue is that i need my application to detect what operating system it is using and depending on the operating system, the app does a different function.</p>
<p>The best information i found was the Path.PathSeperator. Can anyone confirm if it is correct and tell me how to use it to detect which operating system is being used?</p>
<p>Thank You Very Much! :)</p>
| <c#><path><operating-system> | 2016-06-16 09:02:15 | LQ_CLOSE |
37,854,710 | Is it possible to update a hash key in amazon dynamo db | <p>I want to update hash key value in amazon dynamo db table.I also have a range key in the same table.Is it possible to do this?</p>
| <database><amazon><amazon-dynamodb> | 2016-06-16 09:09:15 | HQ |
37,856,155 | mysql_upgrade failed - innodb tables doesn't exist? | <p>I am upgrading my mysql-5.5 docker container database to mysql-5.6 docker container. I was able to fix all other problems. Finally my server is running with 5.6. But when i run mysql_upgrade i am getting the following error.</p>
<p>ERROR:</p>
<pre><code>root@17aa74cbc5e2# mysql_upgrade -uroot -password
Warning: Using a password on the command line interface can be insecure.
Looking for 'mysql' as: mysql
Looking for 'mysqlcheck' as: mysqlcheck
Running 'mysqlcheck' with connection arguments: '--port=3306' '--socket=/var/run/mysqld/mysqld.sock'
Warning: Using a password on the command line interface can be insecure.
Running 'mysqlcheck' with connection arguments: '--port=3306' '--socket=/var/run/mysqld/mysqld.sock'
Warning: Using a password on the command line interface can be insecure.
mysql.columns_priv OK
mysql.db OK
mysql.event OK
mysql.func OK
mysql.general_log OK
mysql.help_category OK
mysql.help_keyword OK
mysql.help_relation OK
mysql.help_topic OK
mysql.innodb_index_stats
Error : Table 'mysql.innodb_index_stats' doesn't exist
status : Operation failed
mysql.innodb_table_stats
Error : Table 'mysql.innodb_table_stats' doesn't exist
status : Operation failed
mysql.ndb_binlog_index OK
mysql.plugin OK
mysql.proc OK
mysql.procs_priv OK
mysql.proxies_priv OK
mysql.servers OK
mysql.slave_master_info
Error : Table 'mysql.slave_master_info' doesn't exist
status : Operation failed
mysql.slave_relay_log_info
Error : Table 'mysql.slave_relay_log_info' doesn't exist
status : Operation failed
mysql.slave_worker_info
Error : Table 'mysql.slave_worker_info' doesn't exist
status : Operation failed
mysql.slow_log OK
mysql.tables_priv OK
mysql.time_zone OK
mysql.time_zone_leap_second OK
mysql.time_zone_name OK
mysql.time_zone_transition OK
mysql.time_zone_transition_type OK
mysql.user OK
Repairing tables
mysql.innodb_index_stats
Error : Table 'mysql.innodb_index_stats' doesn't exist
status : Operation failed
mysql.innodb_table_stats
Error : Table 'mysql.innodb_table_stats' doesn't exist
status : Operation failed
mysql.slave_master_info
Error : Table 'mysql.slave_master_info' doesn't exist
status : Operation failed
mysql.slave_relay_log_info
Error : Table 'mysql.slave_relay_log_info' doesn't exist
status : Operation failed
mysql.slave_worker_info
Error : Table 'mysql.slave_worker_info' doesn't exist
status : Operation failed
Running 'mysql_fix_privilege_tables'...
Warning: Using a password on the command line interface can be insecure.
ERROR 1146 (42S02) at line 62: Table 'mysql.innodb_table_stats' doesn't exist
ERROR 1243 (HY000) at line 63: Unknown prepared statement handler (stmt) given to EXECUTE
ERROR 1243 (HY000) at line 64: Unknown prepared statement handler (stmt) given to DEALLOCATE PREPARE
ERROR 1146 (42S02) at line 66: Table 'mysql.innodb_index_stats' doesn't exist
ERROR 1243 (HY000) at line 67: Unknown prepared statement handler (stmt) given to EXECUTE
ERROR 1243 (HY000) at line 68: Unknown prepared statement handler (stmt) given to DEALLOCATE PREPARE
ERROR 1146 (42S02) at line 81: Table 'mysql.slave_relay_log_info' doesn't exist
ERROR 1243 (HY000) at line 82: Unknown prepared statement handler (stmt) given to EXECUTE
ERROR 1243 (HY000) at line 83: Unknown prepared statement handler (stmt) given to DEALLOCATE PREPARE
ERROR 1146 (42S02) at line 110: Table 'mysql.slave_master_info' doesn't exist
ERROR 1243 (HY000) at line 111: Unknown prepared statement handler (stmt) given to EXECUTE
ERROR 1243 (HY000) at line 112: Unknown prepared statement handler (stmt) given to DEALLOCATE PREPARE
ERROR 1146 (42S02) at line 128: Table 'mysql.slave_worker_info' doesn't exist
ERROR 1243 (HY000) at line 129: Unknown prepared statement handler (stmt) given to EXECUTE
ERROR 1243 (HY000) at line 130: Unknown prepared statement handler (stmt) given to DEALLOCATE PREPARE
ERROR 1146 (42S02) at line 1896: Table 'mysql.slave_master_info' doesn't exist
ERROR 1146 (42S02) at line 1897: Table 'mysql.slave_master_info' doesn't exist
ERROR 1146 (42S02) at line 1898: Table 'mysql.slave_master_info' doesn't exist
ERROR 1146 (42S02) at line 1899: Table 'mysql.slave_worker_info' doesn't exist
ERROR 1146 (42S02) at line 1900: Table 'mysql.slave_relay_log_info' doesn't exist
ERROR 1146 (42S02) at line 1904: Table 'mysql.innodb_table_stats' doesn't exist
ERROR 1146 (42S02) at line 1908: Table 'mysql.innodb_index_stats' doesn't exist
FATAL ERROR: Upgrade failed
</code></pre>
| <mysql><docker><innodb><mysqlupgrade> | 2016-06-16 10:10:23 | HQ |
37,856,539 | com.android.ddmlib.AdbCommandRejectedException: device offline (Even when device is connected) | <p>After update of Android Studio to 2.1.2 I've been getting the following error too many times when i make a change.</p>
<blockquote>
<p>com.android.ddmlib.AdbCommandRejectedException: device offline</p>
<p>Error while Installing APK</p>
</blockquote>
<p><strong>The problem is device was never connected and is not offline</strong></p>
<p>If i unplug and re-plug the device it starts working fine again. This never happened in the previous version of AS.</p>
<p>Question: Is there a setting to be changed in AS for this to stop happening or it is a bug?</p>
| <android><android-studio><build> | 2016-06-16 10:27:46 | HQ |
37,856,729 | chart js 2 how to set bar width | <p>I'm using Chart js version: 2.1.4 and I'm not able to limit the bar width. I found two options on stackoverflow</p>
<pre><code>barPercentage: 0.5
</code></pre>
<p>or</p>
<pre><code>categorySpacing: 0
</code></pre>
<p>but neither of one works with the mentioned version. Is there a way to solve this issue without manually modifying the chart.js core library?</p>
<p>thanks</p>
| <javascript><jquery><chart.js> | 2016-06-16 10:35:42 | HQ |
37,856,781 | Why the javascript console does not throw error on creating object recursively? | <pre><code>var main = function() {
this.first = this;
}
console.log(new main().first);
</code></pre>
<p>The code is here :
Object is creating recursively ,I didnot understand why the console not throwing any error.
Please tell me if there is any concept behind this.</p>
| <javascript><recursion> | 2016-06-16 10:38:36 | LQ_CLOSE |
37,857,149 | Is the "files" property necessary in package.json? | <p>It looks like the package will include all files (that are not ignored), even if the <code>package.json</code> has no <code>"files"</code> array.</p>
<p>Is that property necessary?</p>
| <npm><package.json> | 2016-06-16 10:55:30 | HQ |
37,857,327 | Should I still set ConnectionRequestTimeout on Apache HttpClient if I don't use a custom connection manager? | <p>I am using <a href="https://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/config/RequestConfig.html">Apache RequestConfig</a> to configure some timeouts on my <code>HttpClient</code>.</p>
<pre><code>RequestConfig config = RequestConfig.custom()
.setConnectTimeout(timeout)
.setSocketTimeout(timeout)
.setConnectionRequestTimeout(timeout) // Can I leave this out..
.build();
CloseableHttpClient httpClient = HttpClients.custom()
//.setConnectionManager(connectionManager) // ..if I don't use this
.setDefaultRequestConfig(config)
.build();
</code></pre>
<p>Does it make any sense to call <code>setConnectionRequestTimeout(timeout)</code> even I don't have a custom Connection Manager / Pool set up? </p>
<p>As far as I understand, <code>setConnectionRequestTimeout(timeout)</code> is used to set the time to wait for a connection from the connection manager/pool.</p>
<p>Note that I am not setting a Connection Manager on the <code>httpClient</code> (see commented line). </p>
| <java><timeout><apache-httpclient-4.x> | 2016-06-16 11:03:37 | HQ |
37,857,444 | Okay so I am trying to deploy my site | I am running PHPStorm, bought the Droplet on DigitalOcean.com and have the domain on 123.reg. Please help, I really need it I would really appreciate if you could talk to me in simple terms and guide me through the process, this is also my first site. | <php><deployment> | 2016-06-16 11:09:06 | LQ_EDIT |
37,857,695 | Is there a way to sync data between devices without saving on the server? | <p>I want to make my own music player website and app and I want to make it so whenever I add a new song anywhere it will update on the other platform.</p>
<p>How can I do this without actually saving all the songs on a server? I can use a server to pass the data through for syncing but I wanna do it without saving because my host limits my data.</p>
<p>Here's what I thought about but I'm not sure: Maybe every hour or so both types of clients would connect to the server and share differences (although this would be hard if I add new songs both on the website and on the app). Or I could have a manual sync button and just use it on both the phone and the app to sync. Are my ideas practical? And if not is this even possible? </p>
<p>(I can only use PHP with my host and I will use accounts i.e. username and password for the syncing)</p>
| <php><android><synchronization> | 2016-06-16 11:21:28 | LQ_CLOSE |
37,858,336 | HAproxy domain name to backend mapping for path(url) based routing | <p>Does HAProxy support domain name to backend mapping for path based routing. </p>
<p>Currently it does support maps for vhost:</p>
<pre><code>frontend xyz
<other_lines>
use_backend backend1 if { hdr(Host) -i myapp.domain1.com }
use_backend backend2 if { hdr(Host) -i myapp.domain2.com }
</code></pre>
<p>Can be rewritten using maps as:</p>
<pre><code>frontend xyz
<other_lines>
use_backend %[req.hdr(host),lower,map_dom(/path/to/map,default)]
</code></pre>
<p>With the contents of map file as:</p>
<pre><code>#domainname backendname
myapp.domain1.com backend1
myapp.domain2.com backend2
</code></pre>
<p>But if the routing is based on paths as shown in the example below:</p>
<pre><code>frontend xyz
acl host_server_myapp hdr(host) -i myapp.domain.com
acl path_path1 path_beg /path1
acl path_path2 path_beg /path2
use_backend backend1 if host_server_myapp path_path1
use_backend backend2 if host_server_myapp path_path2
</code></pre>
<p>Is it possible to have mapping for this usecase? Using <code>base</code> instead of hdr(host) might give the entire path but it will not have the flexibility of domains since <code>base</code> is string comparison. Is there an other way to convert this to haproxy maps.</p>
| <haproxy> | 2016-06-16 11:49:29 | HQ |
37,858,833 | spring-configuration-metadata.json file is not generated in IntelliJ Idea for Kotlin @ConfigurationProperties class | <p>I'm trying to generate spring-configuration-metadata.json file for my Spring Boot based project. If I use Java <strong>@ConfigurationProperties</strong> class it is generated correctly and automatically:</p>
<pre><code>@ConfigurationProperties("myprops")
public class MyProps {
private String hello;
public String getHello() {
return hello;
}
public void setHello(String hello) {
this.hello = hello;
}
}
</code></pre>
<p>But if I use Kotlin class the <strong>spring-configuration-metadata.json</strong> file is not generated (I've tried both <strong>gradle build</strong> and Idea <strong>Rebuild Project</strong>).</p>
<pre><code>@ConfigurationProperties("myprops")
class MyProps {
var hello: String? = null
}
</code></pre>
<p>AFAIK Kotlin generates the same class with constructor, getters and setters and should act as regular Java bean.</p>
<p>Any ideas why <strong>spring-boot-configuration-processor</strong> doesn't work with Kotlin classes?</p>
| <spring><intellij-idea><gradle><spring-boot><kotlin> | 2016-06-16 12:10:23 | HQ |
37,859,059 | In Xamarin XAML, how do I set a Constraint on a RelativeLayout using a Style? | <p>I am struggling to work out the XAML syntax to apply constraints to a <code>RelativeLayout</code> using a <code>Style</code>.</p>
<p>The first piece of Xamarin XAML below shows a pair of nested <code>RelativeLayout</code> elements used to construct a simple layout (the inner element simply puts a margin around an area to which I can add other content). This version of the code builds and runs fine on iOS and Android.</p>
<pre><code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="App2.Page1">
<RelativeLayout BackgroundColor="Gray">
<RelativeLayout BackgroundColor="Maroon"
RelativeLayout.HeightConstraint="{ConstraintExpression Type=RelativeToParent,Property=Height,Factor=0.9,Constant=0}"
RelativeLayout.WidthConstraint="{ConstraintExpression Type=RelativeToParent,Property=Width,Factor=0.9,Constant=0}"
RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToParent,Property=Height,Factor=0.05,Constant=0}"
RelativeLayout.XConstraint="{ConstraintExpression Type=RelativeToParent,Property=Width,Factor=0.05,Constant=0}">
<BoxView Color="Yellow"
RelativeLayout.HeightConstraint="{ConstraintExpression Type=RelativeToParent,Property=Height,Factor=0.25,Constant=0}"
RelativeLayout.WidthConstraint="{ConstraintExpression Type=RelativeToParent,Property=Width,Factor=0.25,Constant=0}"
RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToParent,Property=Height,Factor=0.25,Constant=0}"
RelativeLayout.XConstraint="{ConstraintExpression Type=RelativeToParent,Property=Width,Factor=0.25,Constant=0}"/>
</RelativeLayout>
</RelativeLayout>
</ContentPage>
</code></pre>
<p>What I would like to do it use the same layout on multiple pages, so I want to put the <code>RelativeLayout</code> constraints into a <code>Style</code>. This second piece of code does not parse or run, but I hope it shows what I am trying to achieve. If I can get the right syntax for this, the idea is that the <code>Style</code> can then be moved out into a shared file, so I can easily re-use it across multiple instances of <code>ContentPage</code>.</p>
<pre><code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="App2.Page2">
<ContentPage.Resources>
<ResourceDictionary>
<Style x:Key="LayoutStyle" TargetType="RelativeLayout">
<Setter Property="BackgroundColor" Value="Maroon"/>
<Setter Property="HeightConstraint">
<Setter.Value>"Type=RelativeToParent,Property=Height,Factor=0.9,Constant=0"</Setter.Value>
</Setter>
<Setter Property="WidthConstraint">
<Setter.Value>"Type=RelativeToParent,Property=Width,Factor=0.9,Constant=0"</Setter.Value>
</Setter>
<Setter Property="YConstraint">
<Setter.Value>"Type=RelativeToParent,Property=Height,Factor=0.05,Constant=0</Setter.Value>
</Setter>
<Setter Property="XConstraint">
<Setter.Value>"Type=RelativeToParent,Property=Width,Factor=0.05,Constant=0</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
</ContentPage.Resources>
<RelativeLayout BackgroundColor="Gray">
<RelativeLayout Style="LayoutStyle">
<BoxView Color="Yellow"
RelativeLayout.HeightConstraint="{ConstraintExpression Type=RelativeToParent,Property=Height,Factor=0.25,Constant=0}"
RelativeLayout.WidthConstraint="{ConstraintExpression Type=RelativeToParent,Property=Width,Factor=0.25,Constant=0}"
RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToParent,Property=Height,Factor=0.25,Constant=0}"
RelativeLayout.XConstraint="{ConstraintExpression Type=RelativeToParent,Property=Width,Factor=0.25,Constant=0}"/>
</RelativeLayout>
</RelativeLayout>
</ContentPage>
</code></pre>
<p>Please can anyone help me out with the syntax for doing this?</p>
<p>This is a link to a complete example (which obviously requires Xamarin to be installed and needs the nuget packages to be restored): <a href="https://drive.google.com/file/d/0Bz__vXtiMe03bTFTb3owaWtfV00/view?usp=sharing">XAML Layout Example</a></p>
| <xaml><xamarin.forms> | 2016-06-16 12:20:27 | HQ |
37,859,563 | onitemclick listener not working in list view,i want toast msg at position where i clicked,but toast msg of each position is shown | /**
* Created by Sonu on 09-Jun-16.
*/
public class EastContent extends AppCompatActivity implements AdapterView.OnItemClickListener{
public static ArrayList j;
ListView listView;
String s="sonu";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.east_content);
Intent iin= getIntent();
Bundle b = iin.getExtras();
String[] array={"sonu","monu","ronu","sone"};
ArrayList<String> list=new ArrayList();
list.addAll(Arrays.asList(array));
j=b.getStringArrayList("name");
listView= (ListView) findViewById(R.id.listview);
ArrayAdapter adapter=new ArrayAdapter(this,R.layout.customtextview,R.id.textViewcustom,array);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position){
case 0:
Toast.makeText(getApplication(),"good hai",Toast.LENGTH_SHORT).show();
case 1:
Toast.makeText(getApplication(),"achha nahi hai",Toast.LENGTH_SHORT).show();
case 2:
Toast.makeText(getApplication(),"achha cool hai",Toast.LENGTH_SHORT).show();
case 3:
Toast.makeText(getApplication(),"sdvvgsgvrsg",Toast.LENGTH_SHORT).show();
}
}}
enter code here**strong text** | <android><android-studio> | 2016-06-16 12:41:01 | LQ_EDIT |
37,860,746 | WPF MVV Command not working | i develop a app in WPF using prism 6 i try to update the date time with this command , i try to update the code without any successes
you can find the code in this URL:[code sample ][1]
[1]: https://1drv.ms/t/s!AuT6bv-RfbiewjVcmWMW45ndgf3s
any help ? | <c#><wpf><mvvm> | 2016-06-16 13:29:20 | LQ_EDIT |
37,860,811 | Do mutexes guarantee ordering of acquisition? | <p>A coworker had an issue recently that boiled down to what we believe was the following sequence of events in a C++ application with two threads:</p>
<ul>
<li><p>Thread A holds a mutex.</p></li>
<li><p>While thread A is holding the mutex, thread B attempts to lock it. Since it is held, thread B is suspended.</p></li>
<li><p>Thread A finishes the work that it was holding the mutex for, thus releasing the mutex.</p></li>
<li><p>Very shortly thereafter, thread A needs to touch a resource that is protected by the mutex, so it locks it again.</p></li>
<li><p>It appears that thread A is given the mutex again; thread B is still waiting, even though it "asked" for the lock first.</p></li>
</ul>
<p>Does this sequence of events fit with the semantics of, say, C++11's <code>std::mutex</code> and/or pthreads? I can honestly say I've never thought about this aspect of mutexes before.</p>
| <multithreading><c++11> | 2016-06-16 13:32:04 | HQ |
37,860,855 | How does a game-app works with views | <p>I'm new in this field, and I have a question -<br>
How do regular game-apps work with views? doesn't they use one big view in implement things in them? What do they do?<br>
Thanks in advance!</p>
| <java><android> | 2016-06-16 13:33:42 | LQ_CLOSE |
37,860,856 | Catch error if retryWhen:s retries runs out | <p>In the <a href="http://reactivex.io/documentation/operators/retry.html" rel="noreferrer">documentation for RetryWhen</a> the example there goes like this: </p>
<pre><code>Observable.create((Subscriber<? super String> s) -> {
System.out.println("subscribing");
s.onError(new RuntimeException("always fails"));
}).retryWhen(attempts -> {
return attempts.zipWith(Observable.range(1, 3), (n, i) -> i).flatMap(i -> {
System.out.println("delay retry by " + i + " second(s)");
return Observable.timer(i, TimeUnit.SECONDS);
});
}).toBlocking().forEach(System.out::println);
</code></pre>
<p>But how do I propagate the Error if the retries runs out?</p>
<p>Adding <code>.doOnError(System.out::println)</code> <em>after</em> the <code>retryWhen</code> clause does not catch the error. Is it even emitted? </p>
<p>Adding a <code>.doOnError(System.out::println)</code> <em>before</em> retryWhen displays <code>always fails</code> for all retries. </p>
| <rx-java><reactive-programming> | 2016-06-16 13:33:48 | HQ |
37,861,223 | Install Atom for Python on Windows 10 - Solved | So I just encountered this issue and wanted to share my experience in how to solve the problem.
A lot of posts are about setting the paths etc. which will sometimes not work for everybody.
If this does not work guys uninstall Python and Atom. While reinstalling Python make sure you click on "Add Python to Path" so you will not have any problems with setting the paths at all!
[Problem solved][1]
[1]: http://i.stack.imgur.com/CCXQG.jpg | <python><windows><variables><path><atom-editor> | 2016-06-16 13:49:24 | LQ_EDIT |
37,861,262 | Create multiple Postgres instances on same machine | <p>To test streaming replication, I would like to create a second Postgres instance on the same machine. The idea is that if it can be done on the test server, then it should be trivial to set it up on the two production servers.</p>
<p>The instances should use different configuration files and different data directories. I tried following the instructions here <a href="http://ubuntuforums.org/showthread.php?t=1431697" rel="noreferrer">http://ubuntuforums.org/showthread.php?t=1431697</a> but I haven't figured out how to get Postgres to use a different configuration file. If I copy the init script, the scripts are just aliases to the same Postgres instance.</p>
<p>I'm using Postgres 9.3 and the Postgres help pages say to specify the configuration file on the <code>postgres</code> command line. I'm not really sure what this means. Am I supposed to install some client for this to work? Thanks.</p>
| <postgresql> | 2016-06-16 13:51:19 | HQ |
37,861,279 | How to index a pdf file in Elasticsearch 5.0.0 with ingest-attachment plugin? | <p>I'm new to Elasticsearch and I read here <a href="https://www.elastic.co/guide/en/elasticsearch/plugins/master/mapper-attachments.html">https://www.elastic.co/guide/en/elasticsearch/plugins/master/mapper-attachments.html</a> that the mapper-attachments plugin is deprecated in elasticsearch 5.0.0.</p>
<p>I now try to index a pdf file with the new ingest-attachment plugin and upload the attachment. </p>
<p>What I've tried so far is</p>
<pre><code>curl -H 'Content-Type: application/pdf' -XPOST localhost:9200/test/1 -d @/cygdrive/c/test/test.pdf
</code></pre>
<p>but I get the following error:</p>
<pre><code>{"error":{"root_cause":[{"type":"mapper_parsing_exception","reason":"failed to parse"}],"type":"mapper_parsing_exception","reason":"failed to parse","caused_by":{"type":"not_x_content_exception","reason":"Compressor detection can only be called on some xcontent bytes or compressed xcontent bytes"}},"status":400}
</code></pre>
<p>I would expect that the pdf file will be indexed and uploaded. What am I doing wrong?</p>
<p>I also tested Elasticsearch 2.3.3 but the mapper-attachments plugin is not valid for this version and I don't want to use any older version of Elasticsearch.</p>
| <pdf><elasticsearch><plugins><attachment><elasticsearch-plugin> | 2016-06-16 13:52:21 | HQ |
37,861,500 | BigQuery: convert epoch to TIMESTAMP | <p>I'm trying to range-join two tables, like so</p>
<pre><code>SELECT *
FROM main_table h
INNER JOIN
test.delay_pairs d
ON
d.interval_start_time_utc < h.visitStartTime
AND h.visitStartTime < d.interval_end_time_utc
</code></pre>
<p>where <code>h.visitStartTime</code> is an <code>INT64</code> epoch and <code>d.interval_start_time_utc</code> and <code>d.interval_end_time_utc</code> are proper <code>TIMESTAMP</code>s.</p>
<p>The above fails with</p>
<pre><code>No matching signature for operator < for argument types: TIMESTAMP, INT64. Supported signature: ANY < ANY
</code></pre>
<p>Neither wrapping <code>h.visitStartTime</code> in <code>TIMESTAMP()</code> nor <code>CAST(d.interval_start_time_utc AS INT64)</code> work. How do I make the two comparable in BigQuery's Standard SQL dialect?</p>
| <google-bigquery> | 2016-06-16 14:02:20 | HQ |
37,861,600 | What language standards allow ignoring null terminators on fixed size arrays? | <p>We are transitioning C code into C++.<br>
I noticed that the following code is well defined in C, </p>
<pre><code>int main(){
//length is valid. '\0' is ignored
char str[3]="abc";
}
</code></pre>
<p>as it is stated in <a href="http://en.cppreference.com/w/c/language/array_initialization">Array initialization</a> that: </p>
<blockquote>
<p>"If the size of the array is known, it may be one less than the size of
the string literal, in which case the terminating null character is
ignored."</p>
</blockquote>
<p>However, if I were to build the same code in C++, I get the following C++ error: </p>
<pre><code>error: initializer-string for array of chars is too long
[-fpermissive] char str[3]="abc";
</code></pre>
<p>I'm hoping someone can expound on this. </p>
<p><strong>Questions:</strong><br>
Is the code example valid in all C language standards?<br>
Is it invalid in all C++ language standards?<br>
Is there a reason that is valid in one language but not another?</p>
| <c++><c><arrays><c-strings><array-initialization> | 2016-06-16 14:06:46 | HQ |
37,862,098 | Regex expressions | <p>What's the regex expression for:</p>
<ul>
<li>Begins with a certain String? such as: begins with "/retour,merci"</li>
<li>Ends with a certain String? such as: ends with "/blog-accueils.html"</li>
<li>And Contains String? such as: contains "data/"</li>
</ul>
| <java><regex><mongodb> | 2016-06-16 14:28:03 | LQ_CLOSE |
37,862,409 | Laravel unit tests - changing a config value depending on test method | <p>I have an application with a system to verify accounts (register -> get email with link to activate -> account verified). That verification flow is optional and can be switched off with a configuration value:</p>
<pre><code>// config/auth.php
return [
// ...
'enable_verification' => true
];
</code></pre>
<p>I want to test the registration controller: </p>
<ul>
<li>it should redirect to home page in both cases</li>
<li>when verification is ON, home page should show message 'email sent'</li>
<li>when verification is OFF, home page should show message 'account created'</li>
<li>etc.</li>
</ul>
<p>My test methods:</p>
<pre><code>public function test_UserProperlyCreated_WithVerificationDisabled()
{
$this->app['config']->set('auth.verification.enabled', false);
$this
->visit(route('frontend.auth.register.form'))
->type('Test', 'name')
->type('test@example.com', 'email')
->type('123123', 'password')
->type('123123', 'password_confirmation')
->press('Register');
$this
->seePageIs('/')
->see(trans('auth.registration.complete'));
}
public function test_UserProperlyCreated_WithVerificationEnabled()
{
$this->app['config']->set('auth.verification.enabled', true);
$this
->visit(route('frontend.auth.register.form'))
->type('Test', 'name')
->type('test@example.com', 'email')
->type('123123', 'password')
->type('123123', 'password_confirmation')
->press('Register');
$this
->seePageIs('/')
->see(trans('auth.registration.needs_verification'));
}
</code></pre>
<p>When debugging, I noticed that the configuration value when inside the controller method is always set to the value in the config file, no matter what I set with my <code>$this->app['config']->set...</code></p>
<p>I have other tests on the user repository itself to check that it works both when validation is ON or OFF. And there the tests behave as expected.</p>
<p><strong>Any idea why it fails for controllers and how to fix that?</strong></p>
| <php><unit-testing><laravel><phpunit> | 2016-06-16 14:41:52 | HQ |
37,862,414 | MediaCodec getInputImage return null on Some Devices | <p>I want to encode using MediaCodec by setting color format to <code>COLOR_FormatYUV420Flexible</code>.
My Input buffer's is yuv420p.When I input buffer like this :</p>
<pre><code> int inputBufferIndex = mEncoder.dequeueInputBuffer(-1);
mCurrentBufferIndex = inputBufferIndex;
if (inputBufferIndex >= 0) {
ByteBuffer inputBuffer = inputBuffers[inputBufferIndex];
//if(VERBOSE)
Log.i(TAG,"pos:"+inputBuffer.position()+"\tlimit:"+inputBuffer.limit());
inputBuffer.clear();
return inputBuffer;
}
</code></pre>
<p>But some devices get wrong color.
So I try this :</p>
<pre><code> int inputBufferIndex = mEncoder.dequeueInputBuffer(-1);
mCurrentBufferIndex = inputBufferIndex;
if (inputBufferIndex >= 0) {
Image img = mEncoder.getInputImage(inputBufferIndex);
if(img==null)
return null;
//mCurrentInputPlanes = img.getPlanes();
ByteBuffer buffers[]={img.getPlanes()[0].getBuffer(),
img.getPlanes()[1].getBuffer(),
img.getPlanes()[2].getBuffer()};
</code></pre>
<p>I fill the buffer to YUV channels .It work on some devices. But moto X pro and huawei P7 get null when calling getInputImage.
The documentation say the image doesn't contains raw data.
But it also mentions <code>COLOR_FormatYUV420Flexible</code> is supported since API 21.So how should I fix this.</p>
| <android><encode><android-mediacodec> | 2016-06-16 14:42:03 | HQ |
37,863,093 | exception 'NSInvalidArgumentException' NSHealthUpdateUsageDescritption | <p>Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'NSHealthUpdateUsageDescription must be set in the app's Info.plist in order to request write authorization.'</p>
<p>Info.plist has this entry</p>
<pre><code><key>NSHealthShareUsageDescription</key>
<string>some string value stating the reason</string>
</code></pre>
| <ios> | 2016-06-16 15:12:35 | HQ |
37,863,163 | Specific questions about gunDB as a standalone DB for a Cordova project | <p>I just found out about gunDB and the concept seems very interesting and I'd like to find out more about it before starting to evaluate it further.</p>
<ul>
<li>If I wanted to build a chat app like the tutorial but implement chat <strong>rooms</strong>. Would there be a way for clients to only "subscribe" to certain chat rooms only, and avoid transferring the content of every other chat room? How does that affect persistence, if not all data is sync'd to all clients? Do we need to run a special client (ie a server?) that will make sure all data is kept alive at all times?</li>
<li>For that same chat room tutorial, if I want to subscribe to multiple chat rooms, would I need to instantiate multiple Gun instances, with each one using "peer" storage?</li>
<li>How should user management/passwords/etc be dealt with in gunDB?
Sending every client a copy of the user DB is interesting from a
replication stand point, but from a security aspect, it seems counter
intuitive.</li>
<li>Is there a way to ask gun to only sync under certain circumstances such as when a WiFi connection is available (think Cordova)?</li>
<li>What about data that's temporal? Is there a way in the chat app, for
instance to tell gunDB that I'm only interested in future messages
and ignore anything that was created prior to a certain
state/timestamp (again to avoid transferring huge amounts of data on
an expensive data plan)?</li>
<li>How do you persist to disk (potentially circular) data in a gunDB and
load the data back in the DB should the need arise?</li>
<li>Can you ask gun to monitor two keys simultaneously? For example if a client needs to display chat data and todo list (both 'keys' from the tutorial) assuming both are 'peered'.</li>
<li>Is there a tutorial for how to use my own server for storage?</li>
</ul>
| <cordova><gun> | 2016-06-16 15:16:03 | HQ |
37,863,178 | onSave() (for any Entity saved with Hibernate/Spring Data Repositories) | <p>If my Entity has calculated fields should be update before saving to database (db <code>insert</code> or <code>update</code>)
How can I hook a method call before Hibernate or Spring Data Repository <code>save()</code></p>
| <java><spring><hibernate><spring-data> | 2016-06-16 15:16:42 | HQ |
37,863,388 | How to give user input for array of arraylist? | <p>I would like to use input an array of arraylist, where the first input is the number of arrays of arraylist and the next line represents the input for each array. Please let me know where am going wrong. Please find below the code for the same:</p>
<pre><code>public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int a = input.nextInt();
ArrayList[] al = new ArrayList[a];
for( int i =0; i<a; i++){
while(input.hasNextLine())
{
al[i].add(input.nextInt());
}
}
System.out.print("result is"+al[0]);
}
</code></pre>
| <java><arrays><arraylist> | 2016-06-16 15:26:24 | LQ_CLOSE |
37,863,885 | GetOpt Long processing similar input names | <p>I'm running a perl script with a lot of input options, one of them being:</p>
<pre><code> 'errorcode=s{1,}' => \@ecodes,
</code></pre>
<p>I have a die at the end of the GetOptions if anything entered doesn't match the input. However if I input '--ecode 500' the program runs. </p>
<p>Why isn't the script dying? If I try something else like '--testing 123' it does die.</p>
| <perl> | 2016-06-16 15:50:30 | LQ_CLOSE |
37,864,081 | Tensorflow: executing an ops with a specific core of a CPU | <p>It is currently possible to specify which CPU or GPU to use with the tf.device(...) function for specific ops, but is there anyway where you can specify a <em>core</em> of a CPU?</p>
| <graph><cpu><device><tensorflow> | 2016-06-16 15:58:53 | HQ |
37,864,134 | Case statements: sql server | id date value
1 1 null
1 2 a
1 3 b
1 4 null
2 1 null
2 2 null
2 3 null
2 4 null
2 5 null
if value is null in all id's then max of date of that id and if we have value then max of date with value id.
required like this:
id date value
1 3 b
2 5 null
| <sql><sql-server-2008><sql-server-2012> | 2016-06-16 16:01:12 | LQ_EDIT |
37,864,195 | getting info trough 3 tables | I'm following the SQL tutorial from w3schools.
I want to get the value of all orders delivered by a shipper. I don't have any idea about how I can get these details as the info are in different tables and the INNER JOIN didn't worked for me.
Database: http://www.w3schools.com/sql/trysql.asp?filename=trysql_select_groupby
By now, I managed to get the number of orders by each shipper.
SELECT Shippers.ShipperName,COUNT(Orders.OrderID) AS NumberOfOrders FROM Orders
LEFT JOIN Shippers
ON Orders.ShipperID=Shippers.ShipperID
GROUP BY ShipperName;
How could I get the value of those?
| <mysql><sql> | 2016-06-16 16:04:29 | LQ_EDIT |
37,864,562 | how to pass value into CGFloat - | I have a the following code which is cocoa touch class, which draws a simple pie chart, and with the value CGFloat I can adjust the image to show the correct information.
how can i pass a value for example from a slider in the main view controler.swift to it, instead of having it fixed?
public class PieChart : NSObject {
public class func drawCanvas1(ratio ratio: CGFloat = 0.75) {
//// Variable Declarations
let expression: CGFloat = 90 + ratio * 360
let ovalPath = UIBezierPath(ovalInRect: CGRect(x: 0, y: -0, width: 112, height: 112))
UIColor.blackColor().setFill()
ovalPath.fill()
let oval2Rect = CGRect(x: 4, y: 4, width: 104, height: 104)
let oval2Path = UIBezierPath()
oval2Path.addArcWithCenter(CGPoint(x: oval2Rect.midX, y: oval2Rect.midY), radius: oval2Rect.width / 2, startAngle: -expression * CGFloat(M_PI)/180, endAngle: -90 * CGFloat(M_PI)/180, clockwise: true)
oval2Path.addLineToPoint(CGPoint(x: oval2Rect.midX, y: oval2Rect.midY))
oval2Path.closePath()
UIColor.redColor().setFill()
oval2Path.fill()
}
}
| <ios><xcode><swift> | 2016-06-16 16:22:20 | LQ_EDIT |
37,864,999 | Referencing Other Environment Variables in Systemd | <p>Is is possible to reference other environment variables when setting new ones in systemd?</p>
<pre><code>[Service]
EnvironmentFile=/etc/environment
Environment=HOSTNAME=$COREOS_PRIVATE_IPV4
Environment=IP=$COREOS_PRIVATE_IPV4
Environment=FELIX_FELIXHOSTNAME=$COREOS_PRIVATE_IPV4
</code></pre>
<p>The above code does not seem to be working.</p>
| <systemd> | 2016-06-16 16:46:46 | HQ |
37,865,482 | Firebase Storage Video Streaming | <p>I'm working on an app that has video streaming functionality. I'm using firebase database and firebase storage. I'm trying to find some documentation on how firebase storage handles video files, but can't really find much.</p>
<p>There's mentioning in the docs that firebase storage works with other google app services to allow for CDN and video streaming, but all searches seem to lead to a dead end. Any advice? </p>
| <firebase><video-streaming><google-cloud-platform><firebase-storage> | 2016-06-16 17:12:37 | HQ |
37,866,468 | How to use php in html coding to reduce no. Of .html files? | <p>I have made the structure of a website. I have made three .html files named index.html, blog.html, posts.html. index.html is the home page and on that page their is a link for blog.html on the blog.html page thier are some posts heading and i have connected one post to posts.html. But now i'm in trouble that if i have to made one .html file for each post then it would be very difficult so what should i do so that i have to make only one posts.html and anyhow connect it to a php file or something else so that i don't have to make many .html file for every post.
Can i use php for it, is their any command that--> if you click on this post then this page will open and if you click on another post then another page will open. By this i will give the command for all the posts and it will help me alot.</p>
<p>Thank you</p>
| <php><html> | 2016-06-16 18:10:15 | LQ_CLOSE |
37,866,554 | How to delete everything in node redis? | <p>I want to be able to delete all the keys. Is there a way to flush all in node redis? </p>
<p>Redis client:</p>
<pre><code>client = redis.createClient(REDIS_PORT, REDIS_HOST);
</code></pre>
| <node.js><redis><node-redis> | 2016-06-16 18:16:24 | HQ |
37,867,354 | In numpy, what does selection by [:,None] do? | <p>I'm taking the Udacity course on deep learning and I came across the following code:</p>
<pre><code>def reformat(dataset, labels):
dataset = dataset.reshape((-1, image_size * image_size)).astype(np.float32)
# Map 0 to [1.0, 0.0, 0.0 ...], 1 to [0.0, 1.0, 0.0 ...]
labels = (np.arange(num_labels) == labels[:,None]).astype(np.float32)
return dataset, labels
</code></pre>
<p>What does <code>labels[:,None]</code> actually do here?</p>
| <python><numpy> | 2016-06-16 18:58:33 | HQ |
37,867,517 | JavaScript functions fire in codepen but not JSFiddle. Why? | <p>I'm trying to run a basic JavaScript function from an external file but I'm getting inconsistent results. Basically, I can't get a button's "onclick" event to fire when I put the script in an external JS page. I can get it work in CodePen:</p>
<p><a href="http://codepen.io/ThatsIsJustCrazy/pen/ezzLyK" rel="nofollow">CodePen</a></p>
<pre><code>nonsense code
</code></pre>
<p>but NOT in JSFiddle:</p>
<p><a href="https://jsfiddle.net/m7ca8sns/" rel="nofollow">JS Fiddle Examlple</a></p>
<p>I can always get it work when the script is part of the HTML page but I don't want to do that. Can you help? Thanks!</p>
| <javascript><html> | 2016-06-16 19:09:04 | LQ_CLOSE |
37,867,753 | Change Carthage Swift version | <p>Is it possible to change Carthage Swift version used to build the frameworks?</p>
<p>I'm trying to migrate my project to swift 3 (on Xcode 8 beta), and the third party libraries are the only thing that stops my project from compiling.
While using specific branches for swift 3, Carthage throws errors about the new Swift syntax.</p>
<p>Any help will be appreciated!</p>
| <ios><swift><carthage><swift3><xcode8> | 2016-06-16 19:22:32 | HQ |
37,868,175 | Mockito verify other function gets called with right parameter,when we call some function. | If i have 2 functions. Function1 which calls function2. I need to write test case for them. I am using mockito. Trait.
[Just a mimic of the stuff][1]
[1]: http://i.stack.imgur.com/PhJeO.png | <scala><mockito><scalatest> | 2016-06-16 19:47:00 | LQ_EDIT |
37,868,384 | In python argparse, is there a use case for nargs=1? | <p>It seems as though it would always make more sense to use the default action of <code>store</code> without specifying <code>nargs</code> so the output is always as expected, instead of sometimes being a <code>list</code> and sometimes not. I'm just curious if I missed something..</p>
<p>example</p>
<pre><code>>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo')
_StoreAction(option_strings=['--foo'], dest='foo', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None)
>>> parser.add_argument('--bar', nargs=1)
_StoreAction(option_strings=['--bar'], dest='bar', nargs=1, const=None, default=None, type=None, choices=None, help=None, metavar=None)
>>> parser.parse_args('--foo 1 --bar 1'.split())
Namespace(bar=['1'], foo='1')
>>> parser.parse_args('')
Namespace(bar=None, foo=None)
</code></pre>
| <python><argparse> | 2016-06-16 20:00:14 | HQ |
37,868,673 | Edge on Windows 10 32-Bit blocking ajax call to localhost with Network Error 0x2efd | <p>We have an app that uses SignalR to talk to scanner drivers locally that has been in production for a couple of years working on IE, Chrome and Firefox, which do not have a problem pulling down the hubs js header file for SignalR. Once Edge came out we saw an issue with talking to localhost and after long efforts of finding a setting to allow it to communicate (and many hours with a Microsoft ticket that they found no solution), we settled on adding headers to allow Edge to grant access to domain:</p>
<p><code>Access-Control-Allow-Origin: https://localhost:11000</code></p>
<p>This seemed to work, but little did we notice that it worked for a 64-Bit Windows 10 Edge, but did not on 32-Bit Windows 10 Edge. I have spent hours lowering all security settings for all zones and disabling Protected Mode, trying different ajax tricks to pull the file, but continue to get the error:</p>
<p><code>SCRIPT7002: XMLHttpRequest: Network Error 0x2efd, Could not complete the operation due to error 00002efd.</code></p>
<p>The following pseudo code fails:</p>
<pre><code>$.ajax({
url: "https://localhost:11000/signalr/hubs",
crossDomain: true,
success: function (data) {
console.log("success");
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("error:");
console.log(jqXHR);
}
});
</code></pre>
<p>I'm looking for any insight into settings or anything else to try, or if anyone else has seen this issue. One other piece of information, fiddler doesn't show any traffic for the call so it is being blocked by the browser it would seem. Also on the same computer that fails with Edge - IE, Chrome and FF will succeed.</p>
| <javascript><jquery><ajax><signalr><microsoft-edge> | 2016-06-16 20:20:07 | HQ |
37,868,777 | Microsoft access form view | <p>I am creating a Microsoft access application, and I designed a login form, where the user inputs username and password. I want the form view of the form to be showing above the access window, as a pop-up... how do I achieve that? </p>
| <ms-access-2010><ms-access-2016> | 2016-06-16 20:27:39 | LQ_CLOSE |
37,868,952 | Selecting all strings from database that starts with a lowercase letter | <p>I'm trying to select all strings in my database that starts with a lowercase letter with regexp, but for some reason it's selecting all the strings that starts with a uppercase letter too. What am I doing wrong?</p>
<pre><code>SELECT *
FROM `allData`
WHERE response REGEXP '^[a-z]'
LIMIT 0 , 30
</code></pre>
| <php><mysql><sql> | 2016-06-16 20:39:38 | HQ |
37,869,201 | How does doze mode affect background/foreground services, with/without partial/full wakelocks? | <p>This is a simple question, seeing that there is a huge post about this on G+ (<a href="https://plus.google.com/+AndroidDevelopers/posts/94jCkmG4jff"><strong>here</strong></a>), and lack of information on official docs (<a href="https://developer.android.com/training/monitoring-device-state/doze-standby.html"><strong>here</strong></a> ):</p>
<p>What happens to the app's services when the device goes to "doze" mode?</p>
<p>What does it do to background/foreground services (bound/unbound, started/not-started), with/without partial/full wakelocks?</p>
<p>What would you do, for example, in order to create a service that plays an audio stream while the device's screen is turned off? What if the audio stream is not from a local file, but from the network? </p>
<p>Seeing that there was a claim by Google developer:</p>
<blockquote>
<p>Apps that have been running foreground services (with the associated
notification) are not restricted by doze.</p>
</blockquote>
<p>-yet a lot of discussion after that, claiming this is not entirely true, I think it's quite confusing to know what special background-operations apps should do.</p>
| <android><android-service><android-doze><android-doze-and-standby> | 2016-06-16 20:56:10 | HQ |
37,869,963 | How to use AVCapturePhotoOutput | <p>I have been working on using a custom camera, and I recently upgraded to Xcode 8 beta along with Swift 3. I originally had this:</p>
<pre><code>var stillImageOutput: AVCaptureStillImageOutput?
</code></pre>
<p>However, I am now getting the warning:</p>
<blockquote>
<p>'AVCaptureStillImageOutput' was deprecated in iOS 10.0: Use AVCapturePhotoOutput instead</p>
</blockquote>
<p>As this is fairly new, I have not seen much information on this. Here is my current code:</p>
<pre><code>var captureSession: AVCaptureSession?
var stillImageOutput: AVCaptureStillImageOutput?
var previewLayer: AVCaptureVideoPreviewLayer?
func clickPicture() {
if let videoConnection = stillImageOutput?.connection(withMediaType: AVMediaTypeVideo) {
videoConnection.videoOrientation = .portrait
stillImageOutput?.captureStillImageAsynchronously(from: videoConnection, completionHandler: { (sampleBuffer, error) -> Void in
if sampleBuffer != nil {
let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer)
let dataProvider = CGDataProvider(data: imageData!)
let cgImageRef = CGImage(jpegDataProviderSource: dataProvider!, decode: nil, shouldInterpolate: true, intent: .defaultIntent)
let image = UIImage(cgImage: cgImageRef!, scale: 1, orientation: .right)
}
})
}
}
</code></pre>
<p>I have tried to look at <code>AVCapturePhotoCaptureDelegate</code>, but I am not quite sure how to use it. Does anybody know how to use this? Thanks.</p>
| <ios><swift><camera><avfoundation><swift3> | 2016-06-16 21:53:37 | HQ |
37,870,921 | When should we define fields as "volatile"? When is it unnecessary? | <p>I understand <code>volatile</code> should be used on a class field to prevent the JVM from caching the value so when it will always be the latest value when it's read.</p>
<p>If my understanding is correct, doesn't it mean we should define all fields with <code>volatile</code> when working in a multithread thread-safe environment? When is it unnecessary to define a field as <code>volatile</code>? </p>
| <java><multithreading><concurrency> | 2016-06-16 23:22:54 | LQ_CLOSE |
37,871,194 | How to tune spark executor number, cores and executor memory? | <p>Where do you start to tune the above mentioned params. Do we start with executor memory and get number of executors, or we start with cores and get the executor number. I followed the <a href="http://blog.cloudera.com/blog/2015/03/how-to-tune-your-apache-spark-jobs-part-2/" rel="noreferrer">link</a>. However got a high level idea, but still not sure how or where to start and arrive to a final conclusion.</p>
| <apache-spark> | 2016-06-17 00:03:12 | HQ |
37,872,554 | How to make condition if sim card is absent then show dialog if not do something in android? | <p>I have an app in which I have to check whether sim card is inserted in device or not and make some condition if sim is not inserted then show dialog else do something ,how can I do that</p>
| <android> | 2016-06-17 03:19:37 | LQ_CLOSE |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.