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 |
|---|---|---|---|---|---|
38,724,102 | how to parse this in uiimageview this data | `enter code here` photos = (
{
height = 2988;
"html_attributions" = (
"<a href=\"https://maps.google.com/maps/contrib/109461257917544660371/photos\">Marie-Claude Brousseau</a>"
);
"photo_reference" = "CoQBdwAAAD1yAyXPTuN2ZyRD4VZGAqVTT3ZCWSLe_RHSLx_ea-GLe0TsaRSpqIsHhvTj82GljPJG5y-Lrk6809jI5KzvcUjXroCcaAlEkgDLhQma5xsvA0vF4DwdoEZ0wWUZxXHs01BxedzegpQSgB4zVnzbUaAZaN_D5dEr0UOp4awIExe2EhAISA1lOL6VARBNLg9a1r1tGhQf3RgXpVfnPBtYPH6RY5pqmJE0mQ";
width = 5312;
}
); | <ios><objective-c><google-places> | 2016-08-02 15:03:43 | LQ_EDIT |
38,724,220 | How to create my specific MySLQ select? | i have 2 DB tables
Table1
[US_name1 : US]
[US_name2 : US]
[US_name3 : US]
[UK_name1 : UK]
[UK_name2 : UK]
[DE_name1 : DE]
[DE_name2 : DE]
...
and the Table2
...
[2014-05-01 : US_name1 : 150]
[2014-05-01 : US_name2 : 300]
[2014-05-01 : US_name3 : 12.2]
[2014-05-01 : UK_name1 : 18]
[2014-05-01 : UK_name2 : 24]
...
how can i get result from specific date (for example: all from 2014-04-30) in next data-format:
{[US] -> [name]=US_name1, [last]=150, [2014-05-01]=150, [2014-04-30]=103}
{[US] -> [name]=US_name2, [last]=300, [2014-05-01]=300, [2014-04-30]=786}
{[UK] -> [name]=UK_name1, [last]=18, [2014-05-01]=18, [2014-04-30]=362}
my query is incorrect:
SELECT t1.Country, t1.Name, t2.Date, t2.Name, t2.Value FROM t1, t2 WHERE t2.Date >='".$start."' ORDER BY `Date` DESC
if($res){
while($row=mysql_fetch_array($res, MYSQL_ASSOC)){
if(!isset($rez[$row['Name']]['last'])){$rez[$row['Name']]['last']=$row['Value'];}
if(!isset($rez[$row['Name']]['country'])){$rez[$row['Name']]['country']=$row['Country'];}
$rez[$row['Name']][$row['Date']]=$row['Value'];
}
}
| <mysql><select> | 2016-08-02 15:09:24 | LQ_EDIT |
38,724,365 | Why elif statement instead of if statement? | <p>Why should I use an elif instead of using if statements over and over again.
I can't find any documentation on the matter. Thank you in advance.</p>
| <python> | 2016-08-02 15:15:47 | LQ_CLOSE |
38,724,981 | Switch to linux root account in executing c++ binary with password, POSSIBLE? | To All,
I am trying to copy some files to a root user from a user with very low (almost no privileges). I need to allow someone with access to the low account copy some files onto the higher account. I have thought about using a bin/bash script, but don't want any password in the file to be viewed.
I decided to create a c++ application that has the password of the account I would like pass to the su/setuid commands. I do know the password can be viewed in the binary, but is not a concern. The password not in plain text is sufficient.
My problem is that I cannot figure out how to "login" as the user I need to update files for a service running in that account. I have the user account name, which is localadmin, and the password for that account. But how do I pass these to linux to copy the files to the localadmin account home/subdirectory from the c++ application?
I have tried in c++:
**system("su localadmin");** // This prompts for password, but not sure how to pass the password.
**setuid(0);** // Again, where do I pass the password to get the account privileges? All I get is an "operation not permitted".
I apologize if this is an easy question. Just trying to run the commands as localadmin and be done.
Thanks for any help you can provide. | <c++><linux><shell><setuid> | 2016-08-02 15:41:52 | LQ_EDIT |
38,725,102 | How to add custom git command to zsh completion? | <p>I've read a few guides on zsh completion, but I am still confused. In our development environment we have a custom Git command called <code>git new-branch</code>. I'd like zsh to auto-complete it for me after typing just <code>git ne</code> and a <kbd>Tab</kbd>. How can I do that?</p>
| <git><zsh-completion> | 2016-08-02 15:47:09 | HQ |
38,726,002 | Using if else statement with json values in jsoncpp | <p>I am trying to do something similar using <code>jsoncpp</code> inside a function which returns json values as strings.</p>
<pre><code>std::string some_function(std::string val){
.
.
.
if(val=="date")
{
Json::Value my=root["data"]["date"];
std::cout<<"Date";
}
else if(val=="id")
{
Json::Value my=root["data"]["id"];
std::cout<<"ID";
}
else if(val=="art")
{
Json::Value my=root["data"]["article"];
std::cout<<"Article";
}
else
{
return "Error";
}
//Json::Value my=root["data"]["date"]; //this works
return my.toStyledString();
}
</code></pre>
<p>I am able to successfully run json values example: <code>Json::Value my=root["data"]["date"];</code> outside the if else statement(comment out code) but when i tried to run these json values inside an if-else-if statment it shows this error</p>
<blockquote>
<p>warning: control reaches end of non-void function [-Wreturn-type]</p>
</blockquote>
| <c++><codeblocks><jsoncpp> | 2016-08-02 16:34:04 | LQ_CLOSE |
38,726,310 | Mongodb : why show dbs does not show my databases? | <p>I have setup mongodb 64bits on Windows. I ran server and client successfully.</p>
<p>But when I type:</p>
<pre><code>show dbs
</code></pre>
<p>Output is</p>
<pre><code>local 0.000GB
</code></pre>
<p>Why ? show dbs is supposed to list all databases at least the default one "test"
am I wrong ?</p>
| <mongodb> | 2016-08-02 16:50:58 | HQ |
38,726,476 | Unuses Argument error R code | I have a Problem with the following code for a Sampling Importance Resampling Algorithm. It Returns "log=True: unused Argument" for the declaration of Theta. Hope u can help me!
Thanks
CODE:
T = 1e5
theta <- runif(T,0,1, log=TRUE)
log.p <- function(x) dbeta(x, 3000+711, 17000+2201-711)
log.s <- function(x) dunif(x, 0, 1,)
w <- function(t) log.p(t) / log.s(t)
HA <- sum(w(theta)%*%theta)/T | <r><arguments> | 2016-08-02 17:01:02 | LQ_EDIT |
38,727,705 | Learn to manipulate the DOM using JavaScript | <p>I am currently attempting to get into Web Development. I would like to be a Full Stack Developer. I had knowledge of HTML/CSS from 5 years ago but I recently did a refresh on <a href="http://codecademy.com" rel="nofollow">Codecademy</a>. I also completed the JavaScript course but that only teaches you the basic building blocks that are needed. I decided to start reading a series of books called <em><a href="https://github.com/getify/You-Dont-Know-JS" rel="nofollow">You Don't Know JS</a></em> on GitHub. My question is, should I read the entire series to be able to learn how to work with DOM or should basic knowledge be enough to start going down that path? Thank you!</p>
| <javascript><html><dom> | 2016-08-02 18:13:50 | LQ_CLOSE |
38,727,800 | ld linker error "cpu model hidden symbol" | <p>I'm getting an ld error when attempting to compile an sfml program on ubuntu 16.04. This is apparently a known issue, and there is supposed to be a workaround, but I don't understand what is it...</p>
<p><a href="http://web.archive.org/web/20160509014317/https://gitlab.peach-bun.com/pinion/SFML/commit/3383b4a472f0bd16a8161fb8760cd3e6333f1782.patch" rel="noreferrer">http://web.archive.org/web/20160509014317/https://gitlab.peach-bun.com/pinion/SFML/commit/3383b4a472f0bd16a8161fb8760cd3e6333f1782.patch</a></p>
<p>The error spat out by ld is</p>
<pre><code>hidden symbol `__cpu_model' in /usr/lib/gcc/x86_64-linux-gnu/4.9/libgcc.a(cpuinfo.o) is referenced by DSO
</code></pre>
<p>There is no relevant code to this - as I understand it this error is produced on all ubuntu 16.04 systems with g++ 5, if the program to be linked contains objects such as <code>sf::Texture</code> and <code>sf::Sprite</code>. (I don't know any more detail than this.)</p>
<p>I have tried also compiling with g++ 4.9, but the same error occurs.</p>
<p>My compile line is <code>g++-4.9 --std=c++11 -Wall main.cpp -lsfml-graphics -lsfml-window -lsfml-system -o a.out</code></p>
<p>Has anyone else experienced this error and resolved it successfully?</p>
| <c++><linker><sfml><ubuntu-16.04><g++-5> | 2016-08-02 18:19:08 | HQ |
38,728,176 | Can you use a service worker with a self-signed certificate? | <p>I have developer server that are used for testing. They have SSL self-signed certificates, which allow us to test the web application over HTTPS, but with prominent warnings that the certificates are not verifiable.</p>
<p>That's fine, but I have a Service Worker that throws an error with the <code>navigator.serviceWorker.register</code></p>
<blockquote>
<p>SecurityError: Failed to register a ServiceWorker: An SSL certificate error occurred when fetching the script.</p>
</blockquote>
<p>How do I use a Service Worker with an intranet testing server which has a self-signed certificate?</p>
| <ssl><https><self-signed><service-worker> | 2016-08-02 18:41:54 | HQ |
38,728,267 | Understanding SQL in depth | <p>at first i want to say sorry for the bad gramar, i dont speak or write in english with regularity.
But here is the purpose of the question ,</p>
<p>Im a newbie programer currently working in a company that develops heavy data-base oriented products, and due to these reasons im currently working on my knowledge to achieve more results and grow inside of the company and also get more close to achieve the excellence while coding.
Most of my work actually focus on import some data from a data-base to another, having to treat these datas so it can fit the data base that will get the data.
Since it normaly have a lot of rows and even archives data-bases that does requires very efficient query's to not lose any time , more and more often im seeing myself in a situation that i require more knowledge.</p>
<p>Few weeks ago i started to understand a little more of how SQL works, and it does took off that beginner feelings of CRUD being a static sentence, specially after i started to put subquerys on the FROM and making some functions inside of select and prepared statements BUT STILL, it lacks of something to give the true enlightment to the coding art to understand NOT how it is writen but how and why it works .</p>
<p>Its a very complicated question even for who asks and i cant even imagine how it is for who answers .
If there is someone that understood my point of view and has pacience to answer this , i really believe that it will help a lot of peoples that got inside of SQL programing.
Thank you.</p>
| <mysql><sql> | 2016-08-02 18:47:49 | LQ_CLOSE |
38,728,884 | How to properly make REST calls from ReactJS + Redux application? | <p>I'm using ReactJS + Redux, along with Express and Webpack. There is an API built, and I want to be able to make REST calls -- GET, POST, PUT, DELETE -- from the client-side. </p>
<p>How and what is the properly way to go about doing so with the Redux architecture? Any good example of the flow, in terms of reducers, action creators, store, and react routes, would be extremely helpful. </p>
<p>Thank you in advance!</p>
| <javascript><html><reactjs><redux><react-jsx> | 2016-08-02 19:24:33 | HQ |
38,728,905 | Implementing Search in Sitecore 8.1 | <p>I have been doing research on how to implement search in my website. It looks like Sitecore is recommending Solr over Lucene based on this <a href="https://doc.sitecore.net/sitecore_experience_platform/setting_up__maintaining/search_and_indexing/indexing/using_solr_or_lucene" rel="nofollow">article</a>. I'm also using Glass.Mapper as the ORM and have seen this <a href="http://glass.lu/Mapper/Sc/Tutorials/Tutorial25" rel="nofollow">article</a>, but am still not exactly sure on how to implement it. Does anyone know of a good tutorial on getting started with search in a Sitecore 8.1 website?</p>
<p>Thank you!</p>
| <c#><asp.net><solr><sitecore><glass-mapper> | 2016-08-02 19:25:56 | LQ_CLOSE |
38,729,285 | Flexbox: Two elements on top of each other in flex-direction: row | <p>I am trying to achieve the following:</p>
<p><img src="https://i.stack.imgur.com/5qoEy.jpg" alt=""></p>
<hr>
<p>My first attempt was to use a helper div (green):</p>
<p><img src="https://i.stack.imgur.com/BTKTg.jpg" alt=""></p>
<p><a href="https://jsfiddle.net/89z21rq3/7/" rel="noreferrer">JSFiddle</a></p>
<p>What I could do here, is using JavaScript to move the puple and orange elements out of the helper on mobile screens. <strong>But there has to be a plain css way.</strong></p>
<hr>
<p>My second attempt was to remove the helper and build the Mobile Layout:</p>
<p><img src="https://i.stack.imgur.com/U4iwQ.jpg" alt=""></p>
<p><a href="https://jsfiddle.net/umq3L2wL/1/" rel="noreferrer">JSFiddle</a></p>
<hr>
<p>Is there a way to place two elements on top of each other in <code>flex-direction: row</code>? (<a href="https://jsfiddle.net/umq3L2wL/1/" rel="noreferrer">second attempt</a>)</p>
| <css><flexbox> | 2016-08-02 19:49:31 | HQ |
38,729,398 | Can't find the bug/probleem in my program | <p>I'm making my first project c++. It's a simple temperature converter.</p>
<p>I made a test section [code 1] with if statements. the if statement would compare the user input. for example if you user typed c and then k(Celsius-Kelvin). it should run the function[code 2] CtoK(); but i doesn't it runs all function why does it do this?</p>
<p>It try to use return but i didn't(it also didn't gave a error so i kept it)</p>
<p>If you guys see something else pls say it <a href="http://pastebin.com/5sGZVKhu" rel="nofollow">Code on pastebin</a></p>
<p>Also thinks to keep it mind:
Just stated to learn C++
Not native English so if there are spelling and grammar mistakes please say it so i can learn form it</p>
<p>[code 1]</p>
<pre><code>void whatToWhat(char firstDegrees, char secondDegrees) {
if (firstDegrees == 'C' || 'c') {// tests if the user want form c to f
if (secondDegrees == 'F' || 'f') {
CtoF();
}
}if (firstDegrees == 'C' || 'c') {// tests if the user want form c to k
if (secondDegrees == 'K' || 'k') {
CtoK();
}
}if (firstDegrees == 'F' || 'f') {// tests if the user want form f to c
if (secondDegrees == 'C' || 'c') {
FtoC();
}
}if (firstDegrees == 'F' || 'f') {// tests if the user want form f to k
if (secondDegrees == 'K' || 'k') {
FtoK();
}
}if (firstDegrees == 'K' || 'k') {// tests if the user want form k to f
if (secondDegrees == 'F' || 'f') {
KtoF();
}
}if (firstDegrees == 'K' || 'k') {// tests if the user want form k to c
if (secondDegrees == 'C' || 'c') {
KtoC();
}
}
}
</code></pre>
<p>[code 2]</p>
<pre><code> void CtoF() {// c to f furmula
double input;
cout << "Enter a number[Celsius-Fahrenheit]" << endl;
cin >> input;
cout << "it's " << input * 1.8 + 32 << " Fahrenheit " << endl;
return;
}
void CtoK() {// c to k furmula
double input;
cout << "Enter a number[Celsius-Kelvin]" << endl;
cin >> input;
cout << "it's " << input + 273.15 << " Kelvin " << endl;
return;
}
void FtoC() {//f to c furmula
double input;
cout << "Enter a number[Fahrenheit-Celsius]" << endl;
cin >> input;
cout << "it's " << input / 1.8 - 32 << " Celsius " << endl;
}
void FtoK() {//f to k furmula
double input;
cout << "Enter a number[Fahrenheit-Kelvin]" << endl;
cin >> input;
cout << "it's " << input / 1.8 - 32 + 273.15 << " Kelvin " << endl;
return;
}
void KtoF() {// k to f furmula
double input;
cout << "Enter a number[Kelvin-Fahrenheit]" << endl;
cin >> input;
cout << "it's " << (input - 273.15) * 1.8 + 32 << " Fahrenheit " << endl;
}
void KtoC() {// k to c furmula
double input;
cout << "Enter a number[Kelvin-Celsius]" << endl;
cin >> input;
cout << "it's " <<273.15 - input << " Celsius " << endl;
return;
}
</code></pre>
| <c++><visual-studio> | 2016-08-02 19:58:03 | LQ_CLOSE |
38,729,713 | How to create a self contained .Net core application? | <p>I created an asp.net core on .Net core and planned to publish it on a Windows server. I don't want to install anything on the server so I want the application be self contained. </p>
<p>I selected the menu "Build-> Publish MyApp" and then created File system based method. It generated the following files in the folder and I copied it to the server. However, how to run it on the server which doesn't have .Net core installed?</p>
<pre><code>Name
----
refs
runtimes
appsettings.json
MyService.deps.json
MyService.dll
MyService.pdb
MyService.runtimeconfig.json
Microsoft.ApplicationInsights.AspNetCore.dll
Microsoft.ApplicationInsights.dll
Microsoft.AspNetCore.Antiforgery.dll
Microsoft.AspNetCore.Authorization.dll
Microsoft.AspNetCore.Cors.dll
Microsoft.AspNetCore.Cryptography.Internal.dll
Microsoft.AspNetCore.DataProtection.Abstractions.dll
Microsoft.AspNetCore.DataProtection.dll
Microsoft.AspNetCore.Diagnostics.Abstractions.dll
Microsoft.AspNetCore.Hosting.Abstractions.dll
Microsoft.AspNetCore.Hosting.dll
Microsoft.AspNetCore.Hosting.Server.Abstractions.dll
Microsoft.AspNetCore.Html.Abstractions.dll
Microsoft.AspNetCore.Http.Abstractions.dll
Microsoft.AspNetCore.Http.dll
Microsoft.AspNetCore.Http.Extensions.dll
Microsoft.AspNetCore.Http.Features.dll
Microsoft.AspNetCore.HttpOverrides.dll
Microsoft.AspNetCore.JsonPatch.dll
Microsoft.AspNetCore.Localization.dll
Microsoft.AspNetCore.Mvc.Abstractions.dll
Microsoft.AspNetCore.Mvc.ApiExplorer.dll
Microsoft.AspNetCore.Mvc.Core.dll
Microsoft.AspNetCore.Mvc.Cors.dll
Microsoft.AspNetCore.Mvc.DataAnnotations.dll
Microsoft.AspNetCore.Mvc.dll
Microsoft.AspNetCore.Mvc.Formatters.Json.dll
Microsoft.AspNetCore.Mvc.Localization.dll
Microsoft.AspNetCore.Mvc.Razor.dll
Microsoft.AspNetCore.Mvc.Razor.Host.dll
Microsoft.AspNetCore.Mvc.TagHelpers.dll
Microsoft.AspNetCore.Mvc.ViewFeatures.dll
Microsoft.AspNetCore.Razor.dll
Microsoft.AspNetCore.Razor.Runtime.dll
Microsoft.AspNetCore.Routing.Abstractions.dll
Microsoft.AspNetCore.Routing.dll
Microsoft.AspNetCore.Server.IISIntegration.dll
Microsoft.AspNetCore.Server.Kestrel.dll
Microsoft.AspNetCore.WebUtilities.dll
Microsoft.DotNet.InternalAbstractions.dll
Microsoft.EntityFrameworkCore.dll
Microsoft.EntityFrameworkCore.Relational.dll
Microsoft.EntityFrameworkCore.SqlServer.dll
Microsoft.Extensions.Caching.Abstractions.dll
Microsoft.Extensions.Caching.Memory.dll
Microsoft.Extensions.Configuration.Abstractions.dll
Microsoft.Extensions.Configuration.Binder.dll
Microsoft.Extensions.Configuration.dll
Microsoft.Extensions.Configuration.EnvironmentVariables.dll
Microsoft.Extensions.Configuration.FileExtensions.dll
Microsoft.Extensions.Configuration.Json.dll
Microsoft.Extensions.DependencyInjection.Abstractions.dll
Microsoft.Extensions.DependencyInjection.dll
Microsoft.Extensions.DependencyModel.dll
Microsoft.Extensions.DiagnosticAdapter.dll
Microsoft.Extensions.FileProviders.Abstractions.dll
Microsoft.Extensions.FileProviders.Composite.dll
Microsoft.Extensions.FileProviders.Physical.dll
Microsoft.Extensions.FileSystemGlobbing.dll
Microsoft.Extensions.Globalization.CultureInfoCache.dll
Microsoft.Extensions.Localization.Abstractions.dll
Microsoft.Extensions.Localization.dll
Microsoft.Extensions.Logging.Abstractions.dll
Microsoft.Extensions.Logging.Console.dll
Microsoft.Extensions.Logging.Debug.dll
Microsoft.Extensions.Logging.dll
Microsoft.Extensions.Logging.Filter.dll
Microsoft.Extensions.Logging.TraceSource.dll
Microsoft.Extensions.ObjectPool.dll
Microsoft.Extensions.Options.ConfigurationExtensions.dll
Microsoft.Extensions.Options.dll
Microsoft.Extensions.PlatformAbstractions.dll
Microsoft.Extensions.Primitives.dll
Microsoft.Extensions.WebEncoders.dll
Microsoft.Net.Http.Headers.dll
Newtonsoft.Json.dll
NLog.config
NLog.dll
NLog.Extensions.Logging.dll
Remotion.Linq.dll
System.Collections.NonGeneric.dll
System.Collections.Specialized.dll
System.ComponentModel.Primitives.dll
System.ComponentModel.TypeConverter.dll
System.Data.Common.dll
System.Diagnostics.Contracts.dll
System.Interactive.Async.dll
System.Net.WebSockets.dll
System.Runtime.Serialization.Primitives.dll
System.Text.Encodings.Web.dll
web.config
</code></pre>
| <asp.net-core><.net-core> | 2016-08-02 20:18:19 | HQ |
38,730,323 | PHP Updatable Variable | <p>I am working on a site that has a variable for the current year. This variable is used throughout the website. The variable needs to be manually updated every year in the middle of the summer. I want to allow the admin to update that variable but it seems wasteful to create an entire table for one value.</p>
<p>The site is written in php and so I was wondering, is there anyway to update a variable with PHP through a form or something like that?</p>
| <php><html><scope> | 2016-08-02 20:58:46 | LQ_CLOSE |
38,730,787 | Sources to Teach .net Developing | <p>My IT Director asked that I get together (For Next Week!!!!) a lesson plan to teach him and our other developer .Net programming pretty much from the ground up in 6 two hour courses. Up until I was hired 5 years ago, all of our software solutions were in an older technology, namely VBA in MS Access, and the plan is to convert to .Net Web Applications. They are very intelligent, just have not had the time to dive into .Net.</p>
<p>So I'm asking for advice or ideas on how to structure these 6 courses and any sources you think I can turn to. I need to fit in Css Styling, C#, Jquery/Javascript/Ajax, Browser Debugging, Unit tests, etc...</p>
<p>Thank you!!!</p>
| <javascript><c#><jquery><css><.net> | 2016-08-02 21:29:59 | LQ_CLOSE |
38,731,723 | How to use DynamoDB fine grained access control with Cognito User Pools? | <p>I'm having trouble understanding how to use fine-grained access control on DynamoDB when logged in using Cognito User Pools. I've followed the docs and googled around, but for some reason I can't seem to get it working.</p>
<p>My AWS setup is listed below. If I remove the condition in the role policy, I can get and put items no problem, so it seems likely that the condition is the problem. But I can't figure out how or where to debug policies that depend on authenticated identities - what variables are available, what are their values, etc etc.</p>
<p>Any help would be greatly appreciated!</p>
<p><strong>DynamoDB table</strong></p>
<ul>
<li>Table name: documents</li>
<li>Primary partition key: userID (String)</li>
<li>Primary sort key: docID (String)</li>
</ul>
<p><strong>DynamoDB example row</strong></p>
<pre><code>{
"attributes": {},
"docID": "0f332745-f749-4b1a-b26d-4593959e9847",
"lastModifiedNumeric": 1470175027561,
"lastModifiedText": "Wed Aug 03 2016 07:57:07 GMT+1000 (AEST)",
"type": "documents",
"userID": "4fbf0c06-03a9-4cbe-b45c-ca4cd0f5f3cb"
}
</code></pre>
<p><strong>Cognito User Pool User</strong></p>
<ul>
<li>User Status: Enabled / Confirmed</li>
<li>MFA Status: Disabled</li>
<li>sub: 4fbf0c06-03a9-4cbe-b45c-ca4cd0f5f3cb</li>
<li>email_verified: true</li>
</ul>
<p><strong>Role policy for "RoleName"</strong></p>
<pre><code>{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"dynamodb:GetItem",
"dynamodb:PutItem"
],
"Resource": [
"arn:aws:dynamodb:ap-southeast-2:NUMBER:table/documents"
],
"Condition": {
"ForAllValues:StringEquals": {
"dynamodb:LeadingKeys": [
"${cognito-identity.amazonaws.com:sub}"
]
}
}
}
]
}
</code></pre>
<p><strong>Login information returned from cognitoUser.getUserAttributes()</strong></p>
<pre><code>attribute sub has value 4fbf0c06-03a9-4cbe-b45c-ca4cd0f5f3cb
attribute email_verified has value true
attribute email has value ****@****com
</code></pre>
<p><strong>Error message</strong></p>
<pre><code>Code: "AccessDeniedException"
Message: User: arn:aws:sts::NUMBER:assumed-role/ROLE_NAME/CognitoIdentityCredentials is not authorized to perform: dynamodb:GetItem on resource: arn:aws:dynamodb:ap-southeast-2:NUMBER:table/documents
</code></pre>
| <amazon-web-services><amazon-dynamodb><amazon-iam><amazon-cognito> | 2016-08-02 22:54:12 | HQ |
38,731,852 | How can I pass a string to another jsp page? What's wrong in mysql query to select a table, String query ="select * from " + table + ""; | Why mysql query string query ="select * from " + table + "";` is not working the table name is coming from another jsp page.
And why session. setAttribute ("", "table");` is not working to import string from jsp to jsp?
I have two jsp file in my code one is for selection of table for username and password to get login the file name is statement.jsp and other file statement is for showing data in a table that is selected in statement3.jsp. I want to use table string in another jsp page to show that table.
**error**
String query ="select * from " + table + ""; //for selection of table
session.setAttribute("", "table"); //To pass String table from statement.jsp to statement3.jsp to show table.
**[![enter image description here][1]][1]statement3.jsp**
<%
ResultSet rs = null;
session.setAttribute("", "table");
String query ="select * from " + table + "";
rs=st.executeQuery(query);
%>
-------------------------------------
**statement.jsp**
<%
ResultSet rs = null;
String name=request.getParameter("username");
String abc=request.getParameter("password");
String gender = request.getParameter("gender");
if (gender != null) {
String table = gender.equals("teacher") ? "teacher2" : "student";
out.println(table);
String query ="select * from " + table + " where username='"+name+"' AND password='"+abc+"'";
rs=st.executeQuery(query);
out.println(rs);
if(rs.next())
{
response.sendRedirect("statement3.jsp");
}
else
{
response.sendRedirect("index.jsp");
}}
%>
`Stacktrace:
org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:93)
org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:330)
org.apache.jasper.compiler.JDTCompiler.generateClass(JDTCompiler.java:435)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:298)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:277)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:265)
org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:564)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:302)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:329)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:265)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)`
[1]: http://i.stack.imgur.com/1zAt8.jpg | <java><jsp> | 2016-08-02 23:07:52 | LQ_EDIT |
38,732,191 | How to add a data from textarea in database without refresh page | <p>I was developing a system of Login and Register with PHP, HTML, MySql etc, so, i have a problem with my chat!</p>
<p>I want to get data from textarea, and if the button was clicked, empty the textarea, and send the text to database without refresh a page! I have a system that refresh the data from the database and refresh the div "chat" in index.php !</p>
<p>Help me!</p>
| <javascript><php><jquery><html><mysql> | 2016-08-02 23:45:46 | LQ_CLOSE |
38,732,650 | How to watch the slice of array value in VS while debugging? | I want to debug multi dimension array like intel fortran in VS.
In Intel Fortran( integrated in VS), assume arr is a 2 dimension array, and I can use "arr(2:5,3:8)" to see the slice of the array.
[Debugging Intel Fortran in VS][1]
in vs2010, Intel Fortran has already can do this. How can i achieve the same goal if i write a self define class (like CMultiDimensionArray) in c++
Thank you!
[1]: http://i.stack.imgur.com/w1dG3.png | <c++><visual-studio><fortran> | 2016-08-03 00:46:55 | LQ_EDIT |
38,732,946 | Does Elm have a debugging function that can print an object to the console? | <p>I would like to be able to examine a runtime javascript object. Can I print an object to the console instead of a string?</p>
| <elm> | 2016-08-03 01:33:34 | HQ |
38,732,990 | What does "using var_name = data_type;" in c/c++ means? | I found a piece of code that uses the following statement:
using var_name = data_type;
This is the first time that I encountered it. What does it mean or do? | <c++><alias><using> | 2016-08-03 01:38:48 | LQ_EDIT |
38,733,461 | Native Ads In React Native | <p>How do you implement AdMob's Native Ads in React Native? The best I've found is <a href="https://github.com/sbugert/react-native-admob" rel="noreferrer">react-native-admob</a>, but it only does fixed banners and full screen interstitials. How could I implement native ads <em>inside</em> my React Native app with AdMob or any other native ad provider?</p>
| <react-native><admob><native-ads> | 2016-08-03 02:36:11 | HQ |
38,733,546 | How to remove date format from a line in a txt files using a java scrip | I have a .txt file with thousands of line. Each line starts with a different date e.g. 07/23/1999.
I want to write a program to be able to delete the date from each line.
I'll be using a BufferedReader/writer and scanner. How can I find this type of date and deleted? Thanks in advance. | <java> | 2016-08-03 02:45:28 | LQ_EDIT |
38,733,719 | Efficient way to get the unique values from 2 or more columns in a Dataframe | <p>Given a matrix from an <code>SFrame</code>:</p>
<pre><code>>>> from sframe import SFrame
>>> sf =SFrame({'x':[1,1,2,5,7], 'y':[2,4,6,8,2], 'z':[2,5,8,6,2]})
>>> sf
Columns:
x int
y int
z int
Rows: 5
Data:
+---+---+---+
| x | y | z |
+---+---+---+
| 1 | 2 | 2 |
| 1 | 4 | 5 |
| 2 | 6 | 8 |
| 5 | 8 | 6 |
| 7 | 2 | 2 |
+---+---+---+
[5 rows x 3 columns]
</code></pre>
<p>I want to get the unique values for the <code>x</code> and <code>y</code> columns and I can do it as such:</p>
<pre><code>>>> sf['x'].unique().append(sf['y'].unique()).unique()
dtype: int
Rows: 7
[2, 8, 5, 4, 1, 7, 6]
</code></pre>
<p>This way I get the unique values of x and unique values of y then append them and get the unique values of the appended list.</p>
<p>I could also do it as such:</p>
<pre><code>>>> sf['x'].append(sf['y']).unique()
dtype: int
Rows: 7
[2, 8, 5, 4, 1, 7, 6]
</code></pre>
<p>But that way, if my x and y columns are huge with lots of duplicates, I would be appending it into a very huge container before getting the unique.</p>
<p><strong>Is there a more efficient way to get the unique values of a combined columns created from 2 or more columns in an SFrame?</strong></p>
<p><strong>What is the equivalence in pandas of the efficent way to get unique values from 2 or more columns in <code>pandas</code>?</strong></p>
| <python><csv><pandas><dataframe><sframe> | 2016-08-03 03:07:31 | HQ |
38,733,750 | jQuery $(this).data() is returning old values | <p>I have the following code:</p>
<pre><code>updateColors = function() {
$(".color-preview").each(function() {
return $(this).css('background-color', $(this).data('color'));
});
return null;
};
</code></pre>
<p>I put a breakpoint on the 3rd line, and type the following into the console:</p>
<pre><code>> this
<div class="color-preview" data-observer="{"attr":"data-color", "observe":"btn_col"}" data-color="#ffff00" style="background-color: rgb(153, 0, 255);"></div>
> $(this).data('color')
"#9900ff"
</code></pre>
<p>As you can see, the actual element's <code>data-color</code> is <code>#ffff00</code>. However, jQuery's <code>.data()</code> method is returning <code>#9900ff</code>, which <em>was</em> the value of the element's <code>data-color</code>, but has been changed (and using the breakpoint, I can see that yes it has already changed).</p>
| <javascript><jquery> | 2016-08-03 03:11:05 | HQ |
38,735,102 | Edit text Password Toggle Android | <p>I am trying to show user the typed password in edit text whose input type is text Password.</p>
<p>I implemented gesturelistener over the toggle icon like this-</p>
<pre><code>public boolean onTouch(View view, MotionEvent motionEvent) {
switch (view.getId())
{
case R.id.ivPasswordToggle:
switch ( motionEvent.getAction() ) {
case MotionEvent.ACTION_DOWN:
Toast.makeText(getContext(),"show",Toast.LENGTH_SHORT).show();
etPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
break;
case MotionEvent.ACTION_UP:
etPassword.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD | InputType.TYPE_CLASS_TEXT);
Toast.makeText(getContext(),"hide",Toast.LENGTH_SHORT).show();
break;
}
break;
}
return true;
}
</code></pre>
<p>i dont know what is wrong, any help will be appreciated.</p>
| <android><android-edittext><gesturelistener> | 2016-08-03 05:29:08 | HQ |
38,735,276 | How to make YouTube and Vimeo Videos Responsive? | <p>I want to make embedded video from youtube and vimeo responsive.</p>
| <jquery><html><css><iframe> | 2016-08-03 05:41:34 | LQ_CLOSE |
38,735,306 | AWS Cloudfront redirecting to S3 bucket | <p>I have created a cloudfront distribution to serve the static website. S3 is origin server.
Now if we access cloudfront url, it redirects to S3 location.</p>
<p>d2s18t7gwlicql.cloudfront.net
or
test.telekha.in</p>
<p>In the browser it is showing
<a href="https://telekha-test-www.s3.ap-south-1.amazonaws.com/index.html#/dashboard" rel="noreferrer">https://telekha-test-www.s3.ap-south-1.amazonaws.com/index.html#/dashboard</a></p>
<p>i am expecting <a href="https://test.telekha.in/#/dashboard" rel="noreferrer">https://test.telekha.in/#/dashboard</a></p>
<p>If I access <a href="https://test.telekha.in" rel="noreferrer">https://test.telekha.in</a> through curl it returns my index.html document</p>
<p>If I access <a href="http://test.telekha.in" rel="noreferrer">http://test.telekha.in</a> through curl it returns</p>
<pre><code><html>
<head><title>301 Moved Permanently</title></head>
<body bgcolor="white">
<center><h1>301 Moved Permanently</h1></center>
<hr><center>CloudFront</center>
</body>
</html>
</code></pre>
<p>But in browser both http and https are redirecting to <a href="https://telekha-test-www.s3.ap-south-1.amazonaws.com/index.html#/" rel="noreferrer">https://telekha-test-www.s3.ap-south-1.amazonaws.com/index.html#/</a></p>
<p>Please let me know how to resolve this issue.</p>
| <amazon-web-services><amazon-s3><amazon-cloudfront><amazon-route53> | 2016-08-03 05:43:48 | HQ |
38,735,417 | Python - String and int variable concat followed by value substitution | <p>I have a list of variables in Python with below values.</p>
<p>I am trying to print the values of these variables in the following manner, but this is unsuccessful. Can someone please help with a solution ?</p>
<pre><code>a1=1
a2=2
a3=3
for i in range(1,4):
temp="a"+str(i)
print(temp)
</code></pre>
<p>I want the output in 'temp' print the values(viz) 1,2,3 whereas the output seen are the variables (viz) a1,a2,a3</p>
| <python> | 2016-08-03 05:52:05 | LQ_CLOSE |
38,736,423 | AppCompatSpinner vs android.widget.Spinner for app with min SDK version 14 | <p>I am developing application with minimum SDK version 14 Ice-cream sandwitch and targeted version is Android Marshmallow.</p>
<p>DO I need to use AppCompatSpinner or normal spinner will work on ICS devices with all material look and feel?</p>
| <android><spinner><android-support-library><android-spinner><android-appcompat> | 2016-08-03 06:53:42 | HQ |
38,737,254 | vmhgfs-fuse at boot with VMware Windows 8.1 host and Ubuntu 16.04 guest | <p>I am using the VMware Player with a Windows 8.1 host and an Ubuntu 16.04 guest and I have a shared folder <code>shared_folder</code> that I want to mount to a specific location at boot: <code>/shared_folder</code>. I can manually do that using the command</p>
<p><code>vmhgfs-fuse .host:/shared_folder /shared_folder</code></p>
<p>Now I would like to do that automatically during boot. Since I am a beginner with Ubuntu, maybe someone can point me to the solution of my problem. Thanks</p>
| <ubuntu><shared-directory><vmware-player> | 2016-08-03 07:36:11 | HQ |
38,737,412 | BroadcastReciever(To check internet connectivity) getting called at the start of activity | I am using BroadcastReciever to check internet connectivity but it is getting called at the start of activity.This is my BroadcastReceiver` public BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(final Context context, Intent intent) {
connectivityManager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE );
activeNwInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
boolean isWifiConnected = activeNwInfo != null && activeNwInfo.isConnectedOrConnecting();
activeNwInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
boolean isMobileNwConnected = activeNwInfo != null && activeNwInfo.isConnectedOrConnecting();
try {
if (isWifiConnected || isMobileNwConnected) {
Snackbar.make(cordinatorlayout, "Connection established", Snackbar.LENGTH_INDEFINITE)
.setAction("GO ONLINE", new View.OnClickListener() {
@Override
public void onClick(View view) {
//Toast.makeText(context, "clicked", Toast.LENGTH_SHORT).show();
finish();
startActivity(getIntent());
}
}).show();
}else {
Snackbar.make(cordinatorlayout, "You are Offline", Snackbar.LENGTH_INDEFINITE).show();
}
}catch (Exception e){
e.printStackTrace();
}
}
};
` and I have registered BroadcastReceiver inside oncreate() of MainActivity. My BroadcastReceiver is getting called but it is getting called at the start of activity. | <android><broadcastreceiver> | 2016-08-03 07:44:17 | LQ_EDIT |
38,737,442 | How to make multiple array into a single array in ruby | Hiii,
I am trying to make a multiple array in single array in ruby, but in a different format. I given my idea below, please try to help me. I need it
Suppose i have array like this `aa = [1,2,3,[5,6,7],8]` . Now i want to change the code like this `[1,2,3,5,8],[1,2,3,6,8],[1,2,3,7,8]` . if any one get the idea please pass here
| <ruby> | 2016-08-03 07:46:22 | LQ_EDIT |
38,737,658 | Database suggestion for chat app Java | <p>I am building p2p Chat in Java and I need a DB for accounts, friendlists and whoIsOnline. My idea is to create a server, which is receiving periodicly KeepAlive messages and updates whoIsOnline list, then sends back to clients this list only for their friendlists. Any suggestion what DB should I use?</p>
| <java><database> | 2016-08-03 07:56:52 | LQ_CLOSE |
38,737,792 | Spring Cloud Feign: Is Feign efficient enough compared with RestTemplate? | <p>I quickly browsed the source code of Feign, I found that Feign uses JDK's <code>HttpUrlConnection</code> to issue HTTP request and close it when request finished without using a connection pool. I doubt the efficiency of this kind of manner. Then I read the document of Spring's <code>RestTemplate</code> which says <code>RestTemplate</code> can switch to Apache Http Client or OKHttp to send HTTP request:</p>
<blockquote>
<p>Note: by default the RestTemplate relies on standard JDK facilities to establish HTTP connections. You can switch to use a different HTTP library such as Apache HttpComponents, Netty, and OkHttp through the HttpAccessor.setRequestFactory(org.springframework.http.client.ClientHttpRequestFactory) property.</p>
</blockquote>
<p>Does it mean RestTemplate is better than Feign at the view of performance?</p>
| <spring-cloud><spring-cloud-feign> | 2016-08-03 08:02:34 | HQ |
38,737,847 | How to set up URL of ASP.NET Core Web Application in Visual Studio 2015 | <p>I've create a ASP.NET Core Web Application in Visual Studio 2015 named "HelloASPNETCore", with the default template which has one controller "Home" and several actions "Index", "Contact".....etc; now I want to launch it on IIS Express with the root URL as</p>
<pre><code>http://localhost:29492/HelloASPNETCore
</code></pre>
<p>but the default URL that Visual Studio set up to me is</p>
<pre><code>http://localhost:29492
</code></pre>
<p>In the classic ASP.NET MVC Web Application Project I just specified the Project URL in the Project Properties and it works, but it's not work on the ASP.NET Core Web Application Project. I input the URL <a href="http://localhost:29492/Home/Index" rel="noreferrer">http://localhost:29492/Home/Index</a> on browser and got the correct content respond, but <a href="http://localhost:29492/HelloASPNETCore/Home/Index" rel="noreferrer">http://localhost:29492/HelloASPNETCore/Home/Index</a> gave me the empty content, without any error information.</p>
| <visual-studio-2015><asp.net-core><asp.net-core-mvc><iis-express> | 2016-08-03 08:05:06 | HQ |
38,737,920 | Swift NSAttributedString Trim | <p>I want to get ride of the white spaces in front and at the end of my NSAttributedString(Trimming it). I can't simply convert it to string and do trimming because there are images(attachments) in it.
How can i do it?</p>
| <ios><swift><cocoa-touch> | 2016-08-03 08:09:02 | HQ |
38,738,245 | C# with windows form application | How can u add data to a specific row in a database from a windows form using the where clause
I used
"Insert into table1 (name, address) values ('"+textbox1.Text+"', '"+textbox2.Text+"') where (name ='"+textbox1.Text+"')", con
Thus did not work | <c#><sql><database><where-clause> | 2016-08-03 08:24:13 | LQ_EDIT |
38,738,548 | Python enumerate reverse index only | <p>I am trying to reverse the index given by <code>enumerate</code> whilst retaining the original order of the list being enumerated.</p>
<p>Assume I have the following:</p>
<pre><code>>> range(5)
[0, 1, 2, 3, 4]
</code></pre>
<p>If I enumerate this I would get the following:</p>
<pre><code>>> list(enumerate(range(5)))
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
</code></pre>
<p>However I want to reverse the index provided by enumerate so that I get:</p>
<pre><code>[(4, 0), (3, 1), (2, 2), (1, 3), (0, 4)]
</code></pre>
<p>So far I have the following code:</p>
<pre><code>reversed(list(enumerate(reversed(range(5)))))
</code></pre>
<p>I was just wondering if there was a neater way to do this?</p>
| <python><python-3.x><reverse><enumerate> | 2016-08-03 08:38:41 | HQ |
38,738,760 | Android Rxjava subscribe to a variable change | <p>I am learning Observer pattern, I want my observable to keep track of a certain variable when it changes it's value and do some operations, I've done something like :</p>
<pre><code>public class Test extends MyChildActivity {
private int VARIABLE_TO_OBSERVE = 0;
Observable<Integer> mObservable = Observable.just(VARIABLE_TO_OBSERVE);
protected void onCreate() {/*onCreate method*/
super();
setContentView();
method();
changeVariable();
}
public void changeVariable() {
VARIABLE_TO_OBSERVE = 1;
}
public void method() {
mObservable.map(value -> {
if (value == 1) doMethod2();
return String.valueOf(value);
}).subScribe(string -> System.out.println(string));
}
public void doMethod2() {/*Do additional operations*/}
}
</code></pre>
<p>But doMethod2() doesn't get called</p>
| <android><rx-java><observer-pattern> | 2016-08-03 08:48:58 | HQ |
38,738,953 | SQL query ORDER BY with DESC LIMIT 1 and WHERE clause | Trying to create a query that gets the most recent record related to the user. Here's my attempt
"SELECT *
FROM (
SELECT *
FROM simplex_list
ORDER BY id
DESC LIMIT 1)
WHERE userid = $userID"; | <php><mysql><sql> | 2016-08-03 08:57:57 | LQ_EDIT |
38,739,827 | How can I share files between a raspberry pi and windows? | <p>How can I share files between a raspberry pi and a windows computer?
(Like in a public folder or something like that)</p>
| <windows><raspberry-pi><share> | 2016-08-03 09:36:20 | LQ_CLOSE |
38,739,837 | I am trying to build a tree in php from an xml file | I am trying to read this xml file, but the code I am trying to make should work for any xml-file: [xml-file][1]
I am using these two [functions][2] to turn the xml-file into an array and turn that array into a tree. I am trying to keep the parent child relationship of the xml file. All I am getting back from the second function is an array with all the tags in the xml-file.
Can someone please help me?
[1]: http://i.stack.imgur.com/4g6pt.png
[2]: http://i.stack.imgur.com/ADO3n.png | <php><xml> | 2016-08-03 09:36:58 | LQ_EDIT |
38,740,388 | calculate Azimuth between tow points given in lat/long with VBA | Please i have to calculate the azimuth between tow points given in lat/long
but this function isn't correct
please can someone help me !!!!!
----------------------------------------------------
Function azimut(lat1, lat2, lon1, lon2)
azimut = WorksheetFunction.Degrees(WorksheetFunction.Atan2(Cos(Application.WorksheetFunction.Radians(lat1)) * Sin(Application.WorksheetFunction.Radians(lat2)) - Sin(Application.WorksheetFunction.Radians(lat1)) * Cos(Application.WorksheetFunction.Radians(lat2)) * Cos(Application.WorksheetFunction.Radians(lon2 - lon1)), Sin(Application.WorksheetFunction.Radians(lon2 - lon1)) * Cos(Application.WorksheetFunction.Radians(lat2))))
End Function | <vba><function><excel> | 2016-08-03 10:01:34 | LQ_EDIT |
38,740,638 | Convert NSString (eg: "2300") to NSDate (iOS) | <p>I'm trying to convert an <code>NSString</code> like this one "2300" to <code>NSDate</code> format. (Note: there is no colon after 23).</p>
<p>I get the string from an external web service. I need to display this time in my app in 12hr format.</p>
<p>Thank You :)</p>
| <ios><objective-c><nsdate><nsdateformatter> | 2016-08-03 10:11:32 | LQ_CLOSE |
38,741,257 | Random selection in reservoir samplig | My question is related to sample code in 'Alogarithm R' section of this link [https://en.m.wikipedia.org/wiki/Reservoir_sampling][1]
[1]: https://en.m.wikipedia.org/wiki/Reservoir_sampling
// I copied below code snippet from that section
// why this code is replacing elements with gradually decreasing probability? According to the problem each item in the input should have same probability right?
for i = k+1 to n
j := random(1, i)
if j <= k
R[j] := S[i]
For example compare Random function call for below three inputs with my reservoir size 10
1) random (1,15) chances are high for getting random numbers below 10
2) random (1, 100) chances are very low for getting random numbers below 10
3) random (1, 1000) chances are very very low for getting random numbers below 10
So chances of replacing items are very very less as input grows then how can we say that reservoir sampling algorithm is the solution for selecting random samples with equal probability on each Item? Mayou be I am missing some thing please explain.
| <algorithm><random><sampling><data-science> | 2016-08-03 10:40:13 | LQ_EDIT |
38,742,938 | How to make this Block of python code short and efficient | <p>I am total newbie to programming and python. I was solving a problem. I found the solution but it seems like too slow.</p>
<pre><code> if n % 2 == 0 and n % 3 == 0 and\
n % 4 == 0 and n % 5 == 0 and\
n % 6 == 0 and n % 7 == 0 and\
n % 8 == 0 and n % 9 == 0 and\
n % 10 == 0 and n % 11 == 0 and\
n % 12 == 0 and n % 13 == 0 and\
n % 14 == 0 and n % 15 == 0 and\
n % 16 == 0 and n % 17 == 0 and\
n % 18 == 0 and n % 19 == 0 and\
n % 20 == 0:
</code></pre>
<p>This is the piece the code to check whether <code>n</code> is divisible by all numbers from 2 to 20 or not.</p>
<p>How I can make it short and efficient.</p>
| <python><performance><python-2.7><if-statement> | 2016-08-03 11:56:13 | HQ |
38,743,402 | Android “Only the original thread that created a view hierarchy can touch its views.” error in for loop | <p>I am trying to run the for loop in every half second.The loop is changing something in the view every time it is called,but the changes are made by another class i.e Speedometer.</p>
<pre><code>Thread thread=new Thread(){
@Override
public void run() {
float i;
try {
for ( i = 0; i <= 100; i++) {
Speedometer1.onSpeedChanged(Speedometer1.getCurrentSpeed(i) + 8);
Speedometer2.onSpeedChanged(Speedometer2.getCurrentSpeed(i) + 8);
Speedometer3.onSpeedChanged(Speedometer3.getCurrentSpeed(i) + 8);
Speedometer4.onSpeedChanged(Speedometer4.getCurrentSpeed(i) + 8);
Speedometer5.onSpeedChanged(Speedometer5.getCurrentSpeed(i) + 8);
Speedometer6.onSpeedChanged(Speedometer6.getCurrentSpeed(i) + 8);
sleep(500);
}
}
catch (InterruptedException e)
{e.printStackTrace();}
}
};thread.start();
</code></pre>
| <java><android><multithreading> | 2016-08-03 12:15:36 | HQ |
38,744,071 | i am stuck in very bad situation. help pls | <p>Last month i bought my new huawei g630-u20.. Everything was working cool until i thought to have my device rooted 😱😱. I googled and found this kingo root app to root my device . it rooted my device but after that everything went wrong.. I cannot access my android internal storage all folders are gone 😭😭 even i cannot start camera now it says unable to connect to camera.. I am now using sd card storage as primary but most of the apps are not working .. Please help me .. I google and found that bloody app has put my android internal storage to read-only without telling me.. What can i do now help me... 😭😭</p>
| <android> | 2016-08-03 12:44:34 | LQ_CLOSE |
38,744,441 | PHP equivalent of Python's requests.get | <p>I'm trying to access an API using PHP but for which the tutorial is only written in Python. The tutorial shows how to retrieve the data from a URL using</p>
<p>res = requests.get(API_URL, auth=(UID, SECRET))</p>
<p>Please can someone tell me what the equivalent statement would be in PHP, thanks.</p>
| <php><python> | 2016-08-03 13:01:28 | LQ_CLOSE |
38,744,657 | ionic 2 error cordova not available | <p>I am trying to use the cordova GooglePlus plugin in a new ionic 2 project (latest ionic2 version) but I always run into errors regarding cordova.
The plugin is properly installed and shows up in the plugin folder.</p>
<p>One approach I tried is this:</p>
<pre><code>import { GooglePlus } from "ionic-native";
</code></pre>
<p>and then</p>
<pre><code>GooglePlus.login().then(...)
</code></pre>
<p>The login method executes but always throws an error saying <code>"cordova_not_available"</code></p>
<p>I want to test the app with <code>ionic serve</code> on my windows system first before deploying it to my android phone.
How can I make cordova available in the localhost server? From searching I understand that cordova.js is generated and always included in the deploy package for the device.</p>
<p>Another approach I tried is using</p>
<pre><code>window.plugins.googleplus.login(...)
</code></pre>
<p>But this approach does not go through the typescript compiler who does not know anything about a plugins property on the windows object.</p>
<p>How can I fix this?</p>
| <cordova-plugins><ionic2> | 2016-08-03 13:10:43 | HQ |
38,744,874 | Find usages of lombok generated constructor in Intellij | <p>I have a class with lombok annotation (either <code>@Value</code> or <code>@Data</code>) and I am looking for an easy way to find usages of the auto generated constructor.</p>
<p>What I can do now is to find a one use of the constructor, put the cursor there and run 'Find usages' command and I get the results I want.</p>
<p>However I would like to do this directly from the class declaration. Is there a way to do that?</p>
| <intellij-idea><lombok><intellij-lombok-plugin> | 2016-08-03 13:21:20 | HQ |
38,745,000 | Composer - specify `composer.json` path | <p>Is it possible to specify the path to the <code>composer.json</code> file using the cli commands? Even better, is it possible to user a file with a different name?</p>
| <php><dependencies><composer-php> | 2016-08-03 13:27:06 | HQ |
38,745,141 | R.java file cannot be resolved in application in android studio. Give me suggestions that what are the things I should check for this issue. | <p>R.java file cannot be resolved in application in android studio. Give me suggestions that what are the things I should check for this issue. Thank you for advance.</p>
| <android> | 2016-08-03 13:32:34 | LQ_CLOSE |
38,745,370 | Multipeer Connectivity Not Connecting Programmatically | <p>I am creating an iOS/macOS app that uses remote control functionality via the Multipeer Connectivity Framework. Since the device to be remotely monitored and controlled will run over an extended period of time, it's not viable to use the automatic view controller methods since the monitoring device may be locked or go to sleep and then disconnect the connection. So I'm using the programatic approach so that when the monitoring devices lose connection, they will automatically pair up when they are unlocked/woken up and the app is started again. My connection works fine using the ViewController method but not the programatic delegate approach. The advertising, browsing and inviting works fine, but when the invitation is accepted on the remote side I get several errors and then a failed connection. What's weird is that several of the errors are GCKSession errors. </p>
<p>So why is it trying to use the GameCenter framework? And why is it failing after accepting the invitation? Could it just be a bug in the Xcode 8 / Swift 3 /iOS 10 / macOS Sierra Beta SDKs?</p>
<pre><code>[ViceroyTrace] [ICE][ERROR] ICEStopConnectivityCheck() found no ICE check with call id (2008493930)
[GCKSession] Wrong connection data. Participant ID from remote connection data = 6FBBAE66, local participant ID = 3A4C626C
[MCSession] GCKSessionEstablishConnection failed (FFFFFFFF801A0020)
Peer Changing
Failed
[GCKSession] Not in connected state, so giving up for participant [77B72F6A] on channel [0]
</code></pre>
<p>Here is the code from my connection class</p>
<pre><code>func startAdvertisingWithoutUI () {
if advertiserService == nil {
advertiserService = MCNearbyServiceAdvertiser (peer: LMConnectivity.peerID, discoveryInfo: nil, serviceType: "mlm-timers")
advertiserService?.delegate = self
session.delegate = self
}
advertiserService?.startAdvertisingPeer()
}
func browserForNearbyDevices () {
if browserService == nil {
browserService = MCNearbyServiceBrowser (peer: LMConnectivity.peerID, serviceType: "mlm-timers")
browserService?.delegate = self
session.delegate = self
}
browserService?.startBrowsingForPeers()
}
func sendInvitation(to peer: MCPeerID) {
browserService?.invitePeer(peer, to: session, withContext: nil, timeout: 60)
}
func advertiser(_ advertiser: MCNearbyServiceAdvertiser, didReceiveInvitationFromPeer peerID: MCPeerID, withContext context: Data?, invitationHandler: (Bool, MCSession?) -> Void) {
let trustedNames = GetPreferences.trustedRemoteDevices
for name in trustedNames {
if name == peerID.displayName {
invitationHandler(true,session)
return
}
}
invitationHandler (false, session)
}
</code></pre>
| <swift3><multipeer-connectivity><ios10><macos-sierra><xcode8-beta4> | 2016-08-03 13:41:55 | HQ |
38,746,336 | Proper configuration for Jenkins GitHub Pull Request Builder downstream | <p>I'm trying to create two Jenkins jobs that both leverage the <a href="https://github.com/janinko/ghprb" rel="noreferrer" title="GitHub Pull Request Builder">GitHub Pull Request Builder plugin</a> in order to run multiple status checks, but I'm having trouble getting the status check from my downstream job to show up in my GitHub project.</p>
<p>Here's the summarized CI flow I'd like to setup:</p>
<ol>
<li>A pull request is opened against my git repository which triggers <strong>Upstream</strong> job to run in Jenkins</li>
<li><strong>Upstream</strong> reports its status based on the build and, if <code>SUCCESS</code>, should invoke <strong>Downstream</strong> job via a post-build action</li>
<li><strong>Downstream</strong> runs and reports its own status check</li>
</ol>
<p>Step 3 is where I'm having issues. <strong>Downstream</strong> runs properly, but it does not post a status. The status is not even available under the <strong>Branches</strong> section of my GitHub project's settings. I'm not sure how <a href="https://github.com/janinko/ghprb" rel="noreferrer" title="GitHub Pull Request Builder">GHPRB</a> does the initial creation of the status check, but there are references to the context messaging in the Console Output:</p>
<pre><code>14:58:23 Started by upstream project "upstream" build number 209
14:58:23 originally caused by:
14:58:23 GitHub pull request #114 of commit f1ff2819a5308f7819275e732cf44a2cc2ec31dc, no merge conflicts.
14:58:23 [EnvInject] - Loading node environment variables.
14:58:23 Building on master in workspace /store/jenkins/jobs/downstream/workspace
14:58:23 > git rev-parse --is-inside-work-tree # timeout=10
14:58:23 Fetching changes from the remote Git repository
14:58:23 > git config remote.origin.url <removed for privacy> # timeout=10
14:58:23 Fetching upstream changes from <removed for privacy>
14:58:23 > git --version # timeout=10
14:58:23 > git -c core.askpass=true fetch --tags --progress <removed for privacy> +refs/pull/*:refs/remotes/origin/pr/*
14:58:24 > git rev-parse refs/remotes/origin/master^{commit} # timeout=10
14:58:24 > git rev-parse refs/remotes/origin/origin/master^{commit} # timeout=10
14:58:24 Checking out Revision eac390c51a1b8b591bfe879421bd5fad0421a1ec (refs/remotes/origin/master)
14:58:24 > git config core.sparsecheckout # timeout=10
14:58:24 > git checkout -f eac390c51a1b8b591bfe879421bd5fad0421a1ec
14:58:24 First time build. Skipping changelog.
14:58:24 [build] $ /store/jenkins/tools/hudson.tasks.Ant_AntInstallation/ant_1.8.2/bin/ant -DghprbStatusUrl= "-DghprbSUCCESSMessage=Packaging organization successfully cleaned" -DghprbStartedStatus=Undeploying -DghprbAddTestResults=false "-DghprbCommitStatusContext=Cleaning Packaging" "-DghprbERRORMessage=An error occurred during undeployment" -DghprbUpstreamStatus=true "-DghprbTriggeredStatus=Preparing destructive changes" "-DghprbFAILUREMessage=Packaging organization failed to clean properly" -DghprbShowMatrixStatus=false
</code></pre>
<p>Here are the relevant configuration sections for both Jenkins jobs:</p>
<hr>
<h2>Upstream Job</h2>
<h3>Source Code Management: Git</h3>
<ul>
<li>Name: <code>origin</code></li>
<li>Refspec: <code>+refs/pull/*:refs/remotes/origin/pr/*</code></li>
<li>Branch Specifier: <code>${sha1}</code></li>
</ul>
<h3>Build Triggers</h3>
<ul>
<li>GitHub Pull Request Builder
<ul>
<li>Use github hooks for build triggering <code>✔︎</code></li>
<li>Display build errors on downstream builds? <code>✔︎</code></li>
<li><strong>Trigger Setup</strong> is populated with custom context messaging</li>
</ul></li>
</ul>
<h3>Post-build Actions</h3>
<ul>
<li>Build other projects: <code>Downstream</code></li>
</ul>
<hr>
<h2>Downstream Job</h2>
<h3>Source Code Management: Git</h3>
<ul>
<li>Name: <code>origin</code></li>
<li>Refspec: <code>+refs/pull/*:refs/remotes/origin/pr/*</code></li>
<li>Branch Specifier: <code>*/master</code></li>
</ul>
<h3>Build Triggers</h3>
<ul>
<li>GitHub Pull Request Builder
<ul>
<li><strong>Trigger Setup</strong> is populated with custom context messaging</li>
</ul></li>
</ul>
<h3>Build Environment</h3>
<ul>
<li>Set GitHub commit status with custom context and message (Must configure upstream job using GHPRB trigger) <code>✔︎</code>
<ul>
<li>Custom context messaging fields mirror those listed under the <strong>Trigger Setup</strong> section (I doubt both of these are required, but neither seem to be working currently)</li>
</ul></li>
</ul>
<hr>
<p>What am I missing? <strong>It should be noted</strong> that I do not have the Jobs DSL plugin installed so I cannot leverage <a href="https://github.com/janinko/ghprb#job-dsl-support" rel="noreferrer">the extension that GHPRB provides</a>.</p>
| <git><github><jenkins><ghprb> | 2016-08-03 14:23:04 | HQ |
38,748,182 | 2 simple "unresolved identitier" errors that I can't fix in Swift | <p>I am a Swift beginner currently following an Apple Intro to Developing iOS Apps in Swift tutorial. I have the follow error codes " Use of unresolved identifier 'UIImagePickerController' " and "Use of unresolved identifier 'imagePickController' " on lines 3 and 4 respectively. Thanks in advance! </p>
<pre><code>@IBAction func selectionImageFromPhotoLibrary(sender: UITapGestureRecognizer) {
nameTextField.resignFirstResponder()
let imagePickerController = UIIMagePickerController()
imagePickController.sourceType = .PhotoLibrary
imagePickerController.delegate=self
presentViewController(imagePickerController, animated: true, completion: nil)
}
</code></pre>
| <swift><xcode> | 2016-08-03 15:43:58 | LQ_CLOSE |
38,748,201 | Open source Test Data Tool for Oracle | <p>Is there any open source test data generator tool to populate oracle database?
I did some searches and came across devart, datanamic but these are paid ones.</p>
| <oracle><testing><automation><open-source><test-data> | 2016-08-03 15:44:54 | LQ_CLOSE |
38,748,257 | Disable autouse fixtures on specific pytest marks | <p>Is it possible to prevent the execution of "function scoped" fixtures with <code>autouse=True</code> on specific marks only?</p>
<p>I have the following fixture set to autouse so that all outgoing requests are automatically mocked out:</p>
<pre><code>@pytest.fixture(autouse=True)
def no_requests(monkeypatch):
monkeypatch.setattr("requests.sessions.Session.request", MagicMock())
</code></pre>
<p>But I have a mark called <code>endtoend</code> that I use to define a series of tests that are allowed to make external requests for more robust end to end testing. I would like to inject <code>no_requests</code> in all tests (the vast majority), but not in tests like the following:</p>
<pre><code>@pytest.mark.endtoend
def test_api_returns_ok():
assert make_request().status_code == 200
</code></pre>
<p>Is this possible?</p>
| <python><pytest><pytest-django> | 2016-08-03 15:47:56 | HQ |
38,748,294 | Making a Snackbar Without a View? | <p>I want to show a snackbar as soon as the user opens the Google Maps activity, but the thing is that there's no views in the activity to use as the first parameter of the activity (in the <code>findViewById()</code> of <code>Snackbar.make()</code>). What do I put there?
Here's the java class code:</p>
<pre><code>public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setBuildingsEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
float cameraZoom = 17;
LatLng location = new LatLng(43.404032, -80.478184);
mMap.addMarker(new MarkerOptions().position(location).title("49 McIntyre Place #18, Kitchener, ON N2R 1G3"));
CameraUpdateFactory.newLatLngZoom(location, cameraZoom);
Snackbar.make(findViewById(/*WHAT DO I PUT HERE?*/), "Click the pin for more options", Snackbar.LENGTH_LONG).show();
}
}
</code></pre>
<p>Also, here is the activity xml code:</p>
<pre><code><fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="ca.davesautoservice.davesautoservice.MapsActivity" />
</code></pre>
<p>And lastly, here's the stacktrace error:</p>
<pre><code>08-03 11:42:21.333 3901-3901/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: ca.davesautoservice.davesautoservice, PID: 3901
java.lang.NullPointerException
at android.support.design.widget.Snackbar.<init>(Snackbar.java:183)
at android.support.design.widget.Snackbar.make(Snackbar.java:215)
at ca.davesautoservice.davesautoservice.MapsActivity.onMapReady(MapsActivity.java:48)
at com.google.android.gms.maps.SupportMapFragment$zza$1.zza(Unknown Source)
at com.google.android.gms.maps.internal.zzo$zza.onTransact(Unknown Source)
at android.os.Binder.transact(Binder.java:361)
at xz.a(:com.google.android.gms.DynamiteModulesB:82)
at maps.ad.u$5.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5333)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:828)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:644)
at dalvik.system.NativeStart.main(Native Method)
</code></pre>
<p>Thanks for the help! :)</p>
| <java><android><xml><crash><android-snackbar> | 2016-08-03 15:49:43 | HQ |
38,748,297 | Default code folding by individual chunk in rmarkdown | <p>I am writing up a lesson in HTML using rmarkdown to demonstrate how to implement analytic methods in R, and because of this the document has a lot of code that is needed to understand those methods, but also a lot of code that is used only for generating plots and figures. I would like to show the first sort of code by default, and leave the plotting code available for students to view but hidden by default.</p>
<p>I know that rmarkdown has recently added support for code folding by setting the <code>code_folding</code> html_document argument to either <code>show</code> or <code>hide</code>. However, this either leaves all code chunks unfolded or folded by default -- is there any way to indicate whether <strong>individual</strong> code chunks should be shown or folded by default while allowing code folding?</p>
<p>Thank you!</p>
| <r-markdown> | 2016-08-03 15:49:44 | HQ |
38,748,736 | Basic Ruby: what is the difference between these 2 codes? i get false for one and true for another | I got these 2 codes from 2 websites defining the longest word in a string but one code gives me true and one gives me false. Can someone tell me why?
def longest_word(sentence)
words = sentence.split(" ")
longest_word = nil
word_idx = 0
while word_idx < words.length
current_word = words[word_idx]
if longest_word == nil
longest_word = current_word
elsif longest_word.length < current_word.length
longest_word = current_word
end
word_idx += 1
end
return longest_word
end
AND
def LongestWord(sen)
arr = sen.split.map do |w|
/[a-zA-Z0-9\s]+/.match(w)
end
longest = arr.max_by do |w|
w.to_s.length
end
return longest
end
| <ruby> | 2016-08-03 16:10:46 | LQ_EDIT |
38,749,179 | Spark DataFrame mapPartitions | <p>I need to proceed distributed calculation on Spark DataFrame invoking some arbitrary (not SQL) logic on chunks of DataFrame.
I did:</p>
<pre><code>def some_func(df_chunk):
pan_df = df_chunk.toPandas()
#whatever logic here
df = sqlContext.read.parquet(...)
result = df.mapPartitions(some_func)
</code></pre>
<p>Unfortunatelly it leads to:</p>
<blockquote>
<p>AttributeError: 'itertools.chain' object has no attribute 'toPandas'</p>
</blockquote>
<p>I expected to have spark DataFrame object within each map invocation, instead I got 'itertools.chain'. Why? And how to overcome this?</p>
| <python><apache-spark><pyspark><apache-spark-sql> | 2016-08-03 16:34:03 | HQ |
38,749,273 | Latest builds from Angular2 complain with: NgModule DynamicModule uses HomeComponent via "entryComponents" | <p>Since switching to the latest builds of Angular 2 (i.e. on github, master), I get warnings as follows about all my components:</p>
<blockquote>
<p>NgModule DynamicModule uses HomeComponent via "entryComponents" but it
was neither declared nor imported! This warning will become an error
after final.</p>
</blockquote>
<p>I get the same error message for all my components, in addition to <code>HomeComponent</code>.</p>
<p>Can anyone please provide information about those?</p>
| <angular> | 2016-08-03 16:39:23 | HQ |
38,749,403 | Python: No Module named Zlib, Mac OS X El Capitan 10.11.6 | <p>I'm trying to convert my python command line application to an app with py2app.
Everytime I try to import zlib or try to install setuptools , I get an error : no module named zlib.</p>
<p>Python was installed with brew.
I searched every corner of the internet and stack overflow, I have reinstalled python with brew , I have installed all Xcode CLI related stuff with :</p>
<pre><code>xcode-select --install
</code></pre>
<p>I also ran :</p>
<pre><code>ls /usr/include/zlib.h
</code></pre>
<p>and I can see that zlib is there where it is supposed to be.</p>
<p>Reinstalled with:</p>
<pre><code>brew reinstall python
</code></pre>
<p>Unfortunately that didn't work for me. I can't get what is wrong.</p>
<p>Any ideas?</p>
| <python><macos><homebrew><zlib> | 2016-08-03 16:47:37 | HQ |
38,749,789 | how to get string from a struct in C? | <p>I was curious if anyone has gone about doing this before.</p>
<p>I'm having an issue with getting a string from a struct. What I'm trying to do is get the string from the specific struct i'm working with, then put that string into fprintf("%s", whateverstring);</p>
<pre><code>FILE* outfile = fopen("Z:\\NH\\instructions.txt","wb");
if ((dir = opendir ("Z:\\NH\\sqltesting\\")) != NULL) {// open directory and if it exists
while ((ent = readdir (dir)) != NULL) { //while the directory isn't null
printf("%s\n", ent->d_name); //I can do THIS okay
fprintf("%s\n",ent->d_name); //but I can't do this
fclose(outfile);
}
}
closedir (dir);
//else {
//
// perror (""); //print error and panic
// return EXIT_FAILURE;
//}
}
</code></pre>
<p>am I taking the wrong approach here? I was thinking about in some way using something like <code>char[80] =ent.d_name;</code>
however obviously that doesn't work. Is there some way I can get that string from the struct and throw it into fprintf? </p>
| <c><string><struct><char> | 2016-08-03 17:08:50 | LQ_CLOSE |
38,750,612 | crop image using coordinates | <p>I am trying to crop image and send the cropped data to server side. I am using imgareaselect plugin. I get the coordinates of selection but could not crop the image. All the solutions available on internet is to preview cropped image using css. But how can I get the cropped data? No need of preview the cropped image. My code is</p>
<pre><code>cropw = $('#cropimg').imgAreaSelect({
maxWidth: 300, maxHeight: 300,
aspectRatio: '1:1',
instance: true,
handles: true,
onSelectEnd: function (img, selection) {
x1 = selection.x1;
y1 = selection.y1;
x2 = selection.x2;
y2 = selection.y2;
}
});
</code></pre>
| <javascript><jquery><html> | 2016-08-03 17:56:33 | HQ |
38,750,691 | Key Commands must all have a Title, Key and Selector | <p>I am receiving and error when trying to build, Xcode 8.0 Beta 4, and when I'm building it says "error: Illegal Configuration: Key Commands must all have a Title, Key, and Selector. Select each row in the table to check its configuration."</p>
<p>It isn't on a TableView or anything, its a UIView with a Stack View inside it and some buttons, thats about it.</p>
<p>And this is on a Storyboard file I'm getting the error</p>
<p>I can't figure out what that might be?</p>
| <ios><swift><beta> | 2016-08-03 18:01:26 | HQ |
38,751,255 | Can't figure out NullPointerException when I run my tests | <p>I keep getting a null pointer exception and I can't seem to figure out why. I'm running some tests and that is when I get the null pointer exception, however, when I run it from Pangrams main(), I get no problems whatsoever. I've included the code, tests and stack trace below. Any help would be greatly appreciated and thanks in advance!</p>
<pre><code>import java.util.Map;
import java.util.TreeMap;
public class Pangrams {
private static TreeMap<Character, Integer> letterCount;
public static void main(String[] args) {
Pangrams pan = new Pangrams();
System.out.println(pan.isPangram("the quick brown fox jumps over the lazy dog"));
pan.getLetterCount();
}
public Pangrams() {
letterCount = new TreeMap<>();
populateMap();
}
public static boolean isPangram(String text) {
if(text.length() < 26) return false;
addToMap(text);
for(Map.Entry<Character, Integer> entry : letterCount.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
if(!(entry.getValue() >= 1)) {
return false;
}
}
return true;
}
public static void populateMap() {
for(char x = 'a'; x <= 'z'; x++) {
letterCount.put(Character.valueOf(x), 0);
}
}
public static void addToMap(String text) {
char[] textArray = text.toLowerCase().replace(" ", "").toCharArray();
// System.out.println(textArray.length);
for(char letter : textArray) {
if(letterCount.containsKey(letter)) {
int count = letterCount.get(letter);
letterCount.put(letter, ++count);
System.out.println(letterCount.get(letter));
}
else if(!Character.isWhitespace(letter)) {
letterCount.put(letter, 1);
}
}
}
public static void getLetterCount() {
for(Map.Entry<Character, Integer> entry : letterCount.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
</code></pre>
<p>Here are the tests:</p>
<pre><code>import org.junit.Test;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
public class PangramTest {
@Test
public void emptySentence() {
assertFalse(Pangrams.isPangram(""));
}
@Test
public void testLowercasePangram() {
assertTrue(Pangrams.isPangram("the quick brown fox jumps over the lazy dog"));
}
@Test
public void missingCharacterX() {
assertFalse(Pangrams.isPangram("a quick movement of the enemy will jeopardize five gunboats"));
}
@Test
public void mixedCaseAndPunctuation() {
assertTrue(Pangrams.isPangram("\"Five quacking Zephyrs jolt my wax bed.\""));
}
@Test
public void nonAsciiCharacters() {
assertTrue(Pangrams.isPangram("Victor jagt zwölf Boxkämpfer quer über den großen Sylter Deich."));
}
}
</code></pre>
<p>Here is the full stack trace:</p>
<pre><code>java.lang.NullPointerException
at Pangrams.addToMap(Pangrams.java:47)
at Pangrams.isPangram(Pangrams.java:24)
at PangramTest.testLowercasePangram(PangramTest.java:15)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:117)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:253)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:84)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
</code></pre>
| <java><collections><nullpointerexception> | 2016-08-03 18:36:05 | LQ_CLOSE |
38,751,558 | How to use Or operator in javascript | <p>I am trying to use an if statement and the or || operator to test if the value of the select box option for type of room is either single King, single Double Queen, or single two twins and then execute some code. I keep getting the message "uncaught syntax error unidentified token ||" right where the || operator is in the if statement.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var hotel = {
name:"Benson hotel",
rooms:500,
jsuites:10,
ssuites:10,
booked:100,
checkAvailability: function(){
return this.rooms - this.booked;
}
};
hotel.name = "Bonton";
var elName = document.getElementById("hotelN");
elName.textContent = hotel.name;
function checkin(){
var nRooms = document.getElementById("numRooms").value * 1;
var tRoom = document.getElementById("typeRoom");
if (tRoom.value = "singleK")||(tRoom.value ="singleQ")||(tRoom.value = "singleT") { //*I am getting the following message about above line of code in the console. "uncaught syntax error unidentified token ||" Obviously the above if statement with || operator is not correct//
hotel.booked = numRooms + hotel.booked;
if hotel.checkAvailability() < 0 {
var rAvail = nRooms + (hotel.checkAvailability());
if rAvail <= 0 {
var noSay = document.getElementById("say");
noSay.textContent = "We have no rooms available";
}
else {
var yesSay = document.getElementById("say");
yesSay.textContent = "We have" + rAvail + "rooms available";
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
<div id="wrapper">
<div id="heading">
<h1 id="hotelN"></h1>
/div>
<div id="main">
<form id="myForm">
<fieldset>
<legend>Book a Room</legend><p>
<label for="rm1">Number of Rooms:</label>
<input type="number" max="10" min="1" value="1"name="rm" id="numRooms">
Type of room: <select type="text" maxlength="14" id="typeRoom">
<option value="singleK">Single King Bed</option>
<option value="singleQ">Single Queen Bed</option>
<option value="singleT">Single Two Twins</option>
<option value="jsuite">Junior One Bedroom Suite</option>
<option value="srsuite">Senior Two Bedroom Suite</option>
</select></p>
Occupancy:<select type="text">
<option>One adult</option>
<option>Two adults</option>
<option>One adult and Child</option>
</select>
Check In Date: <input type="date"name="checkin" id="cInDate">
Check Out Date: <input type="date" name="checkout" id="cOutDate">
<button type="button" onclick="checkin()">Submit</button>
</fieldset>
</form>
<H1 class="al">Hotel Room Availability</H1>
<p class="al" ><span id="say"></span> and check out on July <span id="dateOut"></span></p>
<p id="first">jjjj</p>
<p id="second"></p>
</div>
</div></code></pre>
</div>
</div>
</p>
| <javascript><logical-operators> | 2016-08-03 18:53:57 | LQ_CLOSE |
38,751,830 | create-react-app, installation error ("command not found") | <p>I have installed create-react-app exactly as instructed on the facebook instruction page (<a href="https://facebook.github.io/react/blog/2016/07/22/create-apps-with-no-configuration.html" rel="noreferrer">https://facebook.github.io/react/blog/2016/07/22/create-apps-with-no-configuration.html</a>):</p>
<blockquote>
<p>First, install the global package:</p>
<p><code>npm install -g create-react-app</code></p>
</blockquote>
<p>I did this. It appeared to work fine - the file was installed to </p>
<pre><code>users/*name*/.node_modules_global/lib/node_modules/create-react-app
</code></pre>
<p>I'm not really sure why global install takes it to this path, but there you have it.</p>
<p>Next instruction:</p>
<blockquote>
<p>Now you can use it to create a new app:</p>
<p><code>create-react-app hello-world</code></p>
</blockquote>
<p>Couldn't be simpler, right? But Terminal spits out this at me:</p>
<pre><code>-bash: create-react-app: command not found
</code></pre>
<p>It's probably something very simple I'm missing but I don't really know where to look. If anyone can help I'd really appreciate it!</p>
<p>Thanks in advance.</p>
<p><strong>Note: I'm using Node v6.3.1, and npm v3.10.3</strong></p>
| <node.js><facebook><reactjs><npm> | 2016-08-03 19:10:11 | HQ |
38,751,924 | what does 'in' mean in javascript if statement | <p>Hi i'm following a tutorial learning to use javascript. </p>
<pre><code>function move(keyclick) {
if(40 in keyclick) {}
playerMove.x++;
render(); }
</code></pre>
<p>What does the 'in' word mean? I understand what the function is doing, but why not just use ==
?</p>
<p>Thanks </p>
| <javascript> | 2016-08-03 19:16:00 | LQ_CLOSE |
38,751,944 | HTML True or false in editor? | <p>I'm creating a helpful HTML template and would like to do something where you can toggle tags on and off.</p>
<p>I would like to make it simple like ="true" where you change true or false to whatever you want.</p>
<p>Is there a way i could do this within one html file?</p>
| <html> | 2016-08-03 19:16:59 | LQ_CLOSE |
38,752,066 | Responsive replacement for Semantic UI's navigation menu | <p>Semantic UI has some problems when it comes to it's menu collection. In short, <strong>it's not responsive at all</strong>, and the closest thing to it is their "stackable" implementation to simply show the menu as a stack.</p>
<p>Can anyone here recommend a good navigation menu that integrates well with semantic ui?</p>
<p>Thanks for any input.</p>
| <jquery><css><menu><navigationbar><semantic-ui> | 2016-08-03 19:25:27 | HQ |
38,752,568 | SQL request with JOUN and COUNT | [I cant make a database query, as in this picture][1]
[1]: http://i.stack.imgur.com/5o6lv.png | <sql><join><count> | 2016-08-03 19:59:07 | LQ_EDIT |
38,752,620 | Promise vs setTimeout | <p>I've observed that in the following code:</p>
<pre><code>setTimeout(function(){console.log('setTimeout')});
Promise.resolve(1).then(function(){console.log('promise resolve')})
</code></pre>
<p>No matter how many times I execute this, the promise callback always logs before the setTimeout.</p>
<p>My understanding is that both callbacks are scheduled to be executed to the next tick, and I don't really understand what is going on that makes the promise always take precendence over the timeout.</p>
| <javascript><asynchronous> | 2016-08-03 20:01:40 | HQ |
38,752,936 | Stream object directly into a std::string | <p>Given some type that is streamable:</p>
<pre><code>struct X {
int i;
friend std::ostream& operator<<(std::ostream& os, X const& x) {
return os << "X(" << x.i << ')';
}
};
</code></pre>
<p>I want to append this onto a <code>std::string</code>. I can implement this as:</p>
<pre><code>void append(std::string& s, X const& x) {
std::ostringstream os;
os << x;
s.append(os.str());
}
</code></pre>
<p>But this seems lame since I'm writing data into one stream just to then allocate a new string just for the purposes of appending it onto a different one. Is there a more direct route? </p>
| <c++><string> | 2016-08-03 20:21:37 | HQ |
38,753,439 | Macking onClick event on Cascaded DIVs | Im really trying to do some cascading html DIVs but was not able yet... If anybody could help that would be so <3!
<i>======Concept======</i><br><br>
1 - How should it be at first:<br>
<b>| ParentDiv |</b><br><br>
2 - After user clicks on ParentDiv:<br>
<b>| ParentDiv |</b><br>
<b>| ChildDiv1 | | ChildDiv2 | | ChildDiv3 |</b><br><br>
<i>======Concept ENDS======</i><br><br>
<i>======Code until now======</i><br>
<div class="Year" type="button" onClick="showMonths2016()"><p>2016</p</div>
<div class="Month"><p>January</p></div>
<div class="Month"><p>February</p></div>
<div class="Month"><p>March</p></div>
<script type="text/javascript">
function = showMonths2016(){
document.getElementsByClassName("Month").style.display = "inline-block";
}
</script>
<body>
<i>======Code until now ENDS======</i><br>
So, basically, Im setting class Month` display to "none" (have not past the css, sorry, no idea how to format it as code here) and once user clicks the "Div button"(class year), it changes the stated display value to "inline-block", exposing the Month Divs:
1. User Clicks on Year Div;
2. onClick event evokes the function "showMonths2016";
3. The stated function changes the Month Divs´ display value from "none" to "inline-block";
4. Month Divs are now visible and aligned inline.
I have tested changind the pre-setted value(display:none) manually to "inline-block" and it works like magic! But when I reset it to "none" and try to trigger it by onClick event.... fail! | <html><cascade><jscript> | 2016-08-03 20:54:24 | LQ_EDIT |
38,753,739 | ffmpeg: overlay a png image on a video with custom transparency? | <p>Suppose I have a video <code>foo.mkv</code> and an image <code>bar.png</code> (which happens to contains an alpha channel). I can blend this image over the video like this:</p>
<pre><code>ffmpeg
-i foo.mkv
-i bar.png
-filter_complex "[0:v][1:v]overlay"
-vcodec libx264
myresult.mkv
</code></pre>
<p>(using multiple lines here for readability, normally this is one command line).</p>
<p>Now, besides the png image having an alpha channel of its own, I would also apply a custom <em>overall transparency</em> when blending this image over the video.</p>
<p>In the above example, the image would be visible 100% on top of the video — or at least the parts where its alpha channel is fully opaque.</p>
<p>Is there a way to add a custom overall opacity or transparency blend factor, something like <code>opacity=0.5</code> or whatever, which would make the image only 50% visible?</p>
| <video><filter><ffmpeg><transparency><alpha> | 2016-08-03 21:13:27 | HQ |
38,754,029 | How can I call a class method inside a promise in Angular 2? | <p>If I have an Angular 2 component and I get data from a service that returns an async promise or observable how can I then call a method in the component to display that data?</p>
<pre><code>@Component({
moduleId: module.id,
selector: 'charts',
templateUrl: 'charts.component.html',
providers: [DataService]
})
export class ChartsComponent implements OnInit {
constructor(private dataService:DataService)
ngOnInit() {
this.getData();
}
getData(){
this.dataService.getData().then(function (data) {
this.drawChart(data);
});
}
drawChart(){
//implement drawing chart
}
}
</code></pre>
<p>The problem is that inside a promise "this" in "this.drawChart()" no longer refers to the ChartsComponent class. How can I call a class method post promise?</p>
<p>Also, I cant put drawChart() inside the promise because it needs to use other class properties.</p>
| <javascript><angular><promise> | 2016-08-03 21:35:42 | HQ |
38,754,131 | Firefox redirects localhost to HTTPS | <p>There is a similar question about the same issue on Chrome, with an answer that solves it in Chrome. </p>
<p>When I try to go to <code>http://localhost:8000/</code>, Firefox redirects me to <code>https://localhost/</code> . Why? If I open an incognito window, this doesn't happen. I can't continue developing until I solve this. Please help.</p>
| <firefox><https> | 2016-08-03 21:43:57 | HQ |
38,754,889 | Conflict between Pandas and Unittest? | <p>Consider the following block of code (developed inside a Jupyter notebook), for which it is expected that an <code>AssertionError</code> is raised because a <code>UserWarning</code> is not triggered:</p>
<pre><code>%%writefile Game/tests/tests.py
import unittest
import pandas as pd
class TestGame(unittest.TestCase):
def test_getters(self):
print('Just before the critical line.')
with self.assertWarns(UserWarning):
print('Just testing...')
suite = unittest.TestLoader().loadTestsFromTestCase(TestGame)
unittest.TextTestRunner().run(suite)
</code></pre>
<p>For those unfamiliar with jupyter notebooks, the first line simply exports all following lines into the specified file.</p>
<p>Now if I execute the command:</p>
<pre><code>python3 tests.py
</code></pre>
<p>from the terminal (I am using Python 3.5.1 on Ubuntu 14.04), I get a <code>Runtime Error</code> - the stack trace follows:</p>
<pre><code>Just before the critical line:
E
======================================================================
ERROR: test_getters (__main__.TestGame)
----------------------------------------------------------------------
Traceback (most recent call last):
File "tests.py", line 8, in test_getters
with self.assertWarns(UserWarning):
File "/opt/anaconda3/lib/python3.5/unittest/case.py", line 225, in __enter__
for v in sys.modules.values():
RuntimeError: dictionary changed size during iteration
----------------------------------------------------------------------
Ran 1 test in 0.004s
FAILED (errors=1)
</code></pre>
<p>Obviously the results are not as expected. However, I notice that either of the following options gets the expected results.</p>
<ol>
<li>Commenting out the first line with <code>%%writefile ...</code> and running the code snippet with the Jupyter notebook (which uses the same python interpreter).</li>
<li>Commenting out the <code>import pandas as pd</code> line and running from terminal with the previously given command.</li>
</ol>
<p>Does anyone understand what's going on here?</p>
<p>For reference, the relevant lines in <code>case.py</code> in the <code>unittest</code> module are</p>
<pre><code>for v in sys.modules.values():
if getattr(v, '__warningregistry__', None):
v.__warningregistry__ = {}
</code></pre>
<p>which would seem to be benign code (which I would also presume is tested enough to say that it's not the source of the problem).</p>
| <python-3.x><pandas><python-unittest> | 2016-08-03 22:50:52 | HQ |
38,755,210 | Python3 strange float rounding | <p>Can someone explain me why i do not get 166.9 (i know there is a round() function) i just would like to understand. :)</p>
<pre><code>>>> 165.0 + 1.45 + 0.45
166.89999999999998
</code></pre>
| <python-3.x><math> | 2016-08-03 23:28:11 | LQ_CLOSE |
38,755,214 | Send SMS with AWS Javascript SDK | <p>I want to send an SMS with the AWS javascript sdk with a verification code.</p>
<pre><code>var AWS = require('aws-sdk');
AWS.config.region = 'us-east-1';
var sns = new AWS.SNS();
var params = {
Message: 'this is a test message',
MessageStructure: 'string',
PhoneNumber: '+12346759845'
};
sns.publish(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
</code></pre>
<p>I keep getting "Unexpected key \'PhoneNumber\' found in params".</p>
<p>I have followed the examples in the documentation and it seems what I have is valid as far as I can tell. Apparently, I do not need to create a topic to send individual text messages.</p>
| <javascript><node.js><amazon-web-services><amazon-sns> | 2016-08-03 23:28:24 | HQ |
38,755,254 | "no newline at end of file" C | <p>I'm using this command to compile:</p>
<p><code>gcc –Werror –std=c99 client.c –o client</code> </p>
<p>CODE:</p>
<pre><code>#include <string.h>
#include <stdio.h>
#include <strings.h>
#include <stdlib.h>
#include <unistd.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define BUFFER_SIZE 1000
#define PORT_NUM 8888
void error(char *msg)
{
perror(msg);
exit(0);
}
int main(int argc, char *argv[])
{
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;
char buffer[BUFFER_SIZE];
if (argc < 3) {
fprintf(stderr,"usage %s hostname port\n", argv[0]);
exit(0);
}
portno = atoi(argv[2]);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
server = gethostbyname(argv[1]);
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
error("ERROR connecting");
while (1)
{
bzero(buffer, BUFFER_SIZE);
fgets(buffer, BUFFER_SIZE, stdin);
if((strncmp(buffer,"close",5) == 0 ))
break;
printf("Please enter the message: ");
bzero(buffer, BUFFER_SIZE);
n = write(sockfd,buffer,strlen(buffer));
if (n < 0)
error("ERROR writing to socket");
bzero(buffer, BUFFER_SIZE);
n = read(sockfd,buffer, BUFFER_SIZE-1);
if (n < 0)
error("ERROR reading from socket");
printf("%s\n",buffer);
}
close(sockfd);
return 0;
}
</code></pre>
<p>Trying to compile it in a shell on VM whos OS is linux
This error is driving me crazy, I don't understand what to do inorder to fix this.
I thought the client.c file is damaged, so I copied and pasted into a new .c file. When that failed, I wrote it from 0 and still getting this error.</p>
<p>Thanks in advance!</p>
| <c><sockets><virtual-machine> | 2016-08-03 23:33:43 | LQ_CLOSE |
38,757,014 | group by average in R | <p>I have data structure (data frame), which contains 3 column, age (integer), weight (float) and height (float), I want to calculate average and median weight/height in each age group (e.g. average weight/height in age 10, average weight/height in age 11, average weight/height in age 12, etc.). Wondering if there are any reference code examples?</p>
<p>Currently, I am doing group-by alike function outside R using Python numpy/pandas package. If there is R built-in solution for group-by, it will be great.</p>
<p>regards,
Lin</p>
| <r><statistics> | 2016-08-04 01:14:43 | LQ_CLOSE |
38,757,235 | express: how to send html together with css using sendFile? | <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var app = require('express')();
app.get('/', function(req, res) {
res.sendFile(__dirname + "/" + "index.html");
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="style.css"></code></pre>
</div>
</div>
</p>
<p>I used the above node.js code to send a html file. To get the html file formatted I need to send another css file(style.css).<br/>
My question is: how can I send both of these two files(index.html and style.css) using sendFile() and integrate them together in the client side? </p>
| <html><css><node.js><express><sendfile> | 2016-08-04 01:49:26 | HQ |
38,757,462 | 'None' is being displayed in the output of quotient and remiander in python | **Writing a program to print quotient and remainder, but everywhere change the quotientProblem function into one called quotientString that merely returns the string rather than printing the string directly. Have the main function print the result of each call to the quotientString function.**
def value():
a=int(input("Enter a number: "))
b=int(input("Enter next number: "))
z=print("When",a,"is divided by",b,"the remainder is",a%b,"and the quotient is",a//b,".")
print (division(a,b,z))
def division(x,y,z):
return z
value()
////When I executed///
>>>Enter a number: 5
>>>Enter next number: 3
When 5 is divided by 3 the remainder is 2 and the quotient is 1 .
None
Here 'None' keeps displaying. | <python><python-3.x> | 2016-08-04 02:16:18 | LQ_EDIT |
38,757,668 | sql convert datetime to day name | i want convert form datetime formate to day name but i have problem failed convert.
"Conversion failed when converting date and/or time from character string."
`SELECT DATENAME(dw, date) as date , name, date FROM kkpsurabaya` | <sql> | 2016-08-04 02:40:31 | LQ_EDIT |
38,757,728 | using an enviroment variable for local sequelize configuration | <p>I'm looking to use an environment variable inside of the config.json file of my project using sequelize. I'm using dotenv to set environment variables locally. My config.json file looks like this</p>
<pre><code>{
"development": {
"username": process.env.DB_USER,
"password": process.env.DB_PASS,
"database": process.env.DB_DATABASE,
"host": process.env.DB_HOST,
"dialect": "mysql"
},
"test": {
"username": "root",
"password": null,
"database": "database_test",
"host": "127.0.0.1",
"dialect": "mysql"
},
"production": {
"use_env_variable": "JAWSDB_URL",
"dialect": "mysql"
}
}
</code></pre>
<p>The issue I'm having is that I can't use variables inside the config.json file. It looks like for production I can use the "use_env_varable" key and use the env variable for my connection string. So I guess I either need a way to figure out the combined connection string for my local mysql db or a way to use variables inside the config.json. Any solutions?</p>
| <mysql><json><node.js><environment-variables><sequelize.js> | 2016-08-04 02:47:58 | HQ |
38,758,269 | Java - Generate 2 Number In Specific Numbers | I want generate 2 numbers in specified numbers, I wrote this code and not work, can anybody suggest a better solution ?
==========================================
public class l{
public static void main(String[] args) {
int[] lottery = new int[2];
int randomNum;
for (int i = 0; i < 3; i++) {
randomNum = (int) (Math.random() * (3,9,25,41,43,50,68)); // Random number created here.
for (int x = 0; x < i; x++) {
if (lottery[x] == randomNum) // Here, code checks if same random number generated before.
{
randomNum = (int) (Math.random() * (3,9,25,41,43,50,68));// If random number is same, another number generated.
x = -1; // restart the loop
}
}
lottery[i] = randomNum;
}
for (int i = 0; i < lottery.length; i++)
System.out.print(lottery[i] + " ");
}
}
Thanks | <java><random><collections> | 2016-08-04 03:59:22 | LQ_EDIT |
38,758,307 | How can i Creating Custom Routes in ASP MVC? | I Want to Send a parametr to a Defult Action in a Defult Controller Just Like This:
Domain.com/**parametr**
**parametr** it's just an id tha i want to sent to an action
| <asp.net-mvc><web> | 2016-08-04 04:04:03 | LQ_EDIT |
38,758,361 | "Create React App" with Docker | <p>I was wondering if anyone had any experience using create-react-app with docker. I was able to get it set up with a Dockerfile like:</p>
<pre><code>from node
RUN mkdir /src
WORKDIR /src
ADD package.json /src/package.json
RUN npm install
EXPOSE 3000
CMD [ "npm", "start" ]
</code></pre>
<p>And then used a docker-compose file like: </p>
<pre><code>app:
volumes:
- "./app:/src"
ports:
- "3000:3000"
- "35729:35729"
build: ./app
</code></pre>
<p>This allowed me to start up the container and view the app. However livereload didn't work when saving files in the mounted volume and webpack created several .json.gzip files in the src directory.</p>
<p>Any suggestions for getting this working correctly?</p>
| <reactjs><docker><webpack><docker-compose><livereload> | 2016-08-04 04:11:49 | HQ |
38,758,647 | calculate BMI and update BMI Column and update BMI in to range in php mysql |
[database view][1]
i need to calculate BMI and put that value to catagarize in that into range as( < 18, 18-24.9 )
below shows my quries but it is incorrect
my program is in php mysql
mysql_query("UPDATE ncd SET BMI =WeightKG/(HightM*HightM)");
mysql_query("UPDATE ncd SET BMIrage =2 WHERE BMI >18 AND BMI <25 ");
mysql_query("UPDATE ncd SET BMIrage = 3 WHERE BMI >=25 AND BMI<= 30");
[1]: http://i.stack.imgur.com/D5aWq.png | <php><mysql> | 2016-08-04 04:46:36 | LQ_EDIT |
38,758,873 | Looking for a regex that matches apostrophe within string and not outside | I'm looking for a python regex that can match `'didn't'` returning only `'t` and not `'d` and `t'` | <python><regex> | 2016-08-04 05:07:42 | LQ_EDIT |
38,759,428 | When is `new Error()` better than `Error()`? | <p>The ES5 language spec <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-15.11.1" rel="noreferrer">clearly states</a> that <code>Error(foo)</code> does the same thing as <code>new Error(foo)</code>.</p>
<p>But I notice that in the wild, the longer <code>new Error(foo)</code> form is much more common.</p>
<p>Is there some reason for this?</p>
<p>Is there any situation where using <code>new Error(foo)</code> is preferable to using <code>Error(foo)</code>?</p>
| <javascript><error-handling><idiomatic> | 2016-08-04 05:53:51 | HQ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.