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 |
|---|---|---|---|---|---|
60,102,602 | Puppeteer check through website content/elements | <p>I need to check through the elements of the website for my code, but I can't understand how to do it with puppeteer on Node.JS
<br>Here's the code I tried:</p>
<pre><code>if(page.content('input[data-kwimpalaid="1580983806648-1"]'))
found = true
if(found = true)
console.log("I found it")
if(found = false)
console.log("I didn't found it")
</code></pre>
<p>So what I need basically, I have a website with element ID's ending in 1 to 20, and it can be random, and consecutive. For example it may start at 1, then has 6 ids (1,2,3,4,5,6) or it can start at 5 (5,6,7,8,9,10). I want to check for every ID, and if it exists then change the value of ''found'' to <code>true</code>. If the page doesn't have id 1, try id 2, id 3, id 4, etc.. until it finds an input with that ID/CLASS that exists on that website.</p>
<p><br><br>Shortly, I need to check if the selector element I use exists on the website or not (content).</p>
| <javascript><node.js><puppeteer> | 2020-02-06 19:56:20 | LQ_CLOSE |
60,103,350 | What does * and ** mean in a C++ function declaration? | <p>In this function declaration:</p>
<pre><code>long * multiply(long ** numbers){
</code></pre>
<p>What do the * and ** mean? I'm somewhat of a beginner and haven't come across this before, so any explanation would be appreciated.</p>
| <c++> | 2020-02-06 20:53:07 | LQ_CLOSE |
60,103,844 | Please help, guys | <p>Its app / site like brain trainer </p>
<pre><code> <body style="text-align: center;">
<h3 id="num1"></h3>
<h3 id="num2"></h3>
<input type="text" id="ans" />
<button id="myBtn" onclick="clickFunction()">Button</button>
<p id="ind"></p>
<script>
var i = 0;
var number1 = Math.floor(Math.random() * 20);
var number2 = Math.floor(Math.random() * 20);
var result = number1 * number2;
document.getElementById("num1").innerHTML = number1;
document.getElementById("num2").innerHTML = number2;
let answer = document.getElementById("ans");
if (result == answer) {
document.getElementById("ind").innerHTML =
"Indicator : Right " + i++ + "times.";
} else {
document.getElementById("ind").innerHTML =
"Indicator : Right " + i-- + " times.";
}
answer.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("myBtn").click();
}
});
</script>
</code></pre>
<p>Please help, I need to add the button which submit the text in input and check,if it right.</p>
| <javascript> | 2020-02-06 21:32:13 | LQ_CLOSE |
60,104,689 | finding the position of an element within a numpy array in python | <p>I want to ask a question about finding the position of an element within an array in Python's numpy package. </p>
<p>I am using Jupyter Notebook for Python 3 and have the following code illustrated below:</p>
<pre><code>concentration_list = array([172.95, 173.97, 208.95])
</code></pre>
<p>and I want to write a block of code that would be able to return the position of an element within the array. </p>
<p>For this purpose, I wanted to use <code>172.95</code> to demonstrate. </p>
<p>Initially, I attempted to use <code>.index()</code>, passing in <code>172.95</code> inside the parentheses but this did not work as numpy does not recognise the <code>.index()</code> method -</p>
<pre><code>concentration_position = concentration_list.index(172.95)
AttributeError: 'numpy.ndarray' object has no attribute 'index'
</code></pre>
<p>The Sci.py documentation did not mention anything about such a method being available when I accessed the site. </p>
<p>Is there any function available (that I may not have discovered) to solve the problem?</p>
| <python><numpy> | 2020-02-06 22:47:15 | LQ_CLOSE |
60,106,653 | What does ^= do in python | <p>I have seen the operator ^= in code now once and I dont know what it does. This was used to find a single occurrence of a number in an array. So A = [1,1,2,3,3] it should return 2. This is how it was used</p>
<pre><code>def solution(A):
lone_num = 0
for number in A:
lone_num ^= number
return lone_num
</code></pre>
<p>Not particularly sure what it does. </p>
| <python><arrays> | 2020-02-07 03:22:18 | LQ_CLOSE |
60,109,166 | How do I change an Iframe from a text form? | <p>I am trying to have an iframe in which you can change the url of it with a text box.</p>
<pre><code><form action="/action_page.php">
URL: <input type="text" name="firstname" value="test.com"> <input type="submit" value="Visit">
</form>
<iframe width="560" height="315" src="https://www.example.com"></iframe>
</code></pre>
<p>How would I go on doing this?</p>
| <javascript><html><css><iframe><textbox> | 2020-02-07 07:50:25 | LQ_CLOSE |
60,110,342 | Finding the index position of an array | <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 cars = ["BMW", "BENZ", "LAMB", "AUDI"];
var abc = cars.indexOf("BMW");
document.getElementById("demo").innerHTML = abc;</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="demo"></p></code></pre>
</div>
</div>
</p>
<p>This is the code where it displays the position but I want reverse of this that is if I enter a position it should display the array value. How to get that?</p>
| <javascript> | 2020-02-07 09:12:17 | LQ_CLOSE |
60,111,866 | c# identifier expected in controller | <p>When i type this in my controller page I am getting the error message "Identifier expected" after "loginViewModel". Any idea on how to fix this? </p>
<pre><code>public IActionResult Login(LoginViewModel, string Email, string Password)
{
return View();
}
</code></pre>
| <c#><asp.net-mvc> | 2020-02-07 10:45:39 | LQ_CLOSE |
60,112,833 | I does not know why it is 25 | <p>[enter image description here][1]</p>
<p>[1]: <a href="https://i.stack.imgur.com/gg6E1.jpg" rel="nofollow noreferrer">https://i.stack.imgur.com/gg6E1.jpg</a> Please tell me why it is 25.</p>
| <garbage-collection><v8> | 2020-02-07 11:44:57 | LQ_CLOSE |
60,113,051 | JAVA: You have an error in your SQL syntax; check the manual that corresponds? | <p>I'm using <strong>Java + MySQL</strong> for a game server project of mine. I'm having a problem though -</p>
<pre><code>MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(connection) (`uuid`, `name`, `join_date`, `group`) VALUES (5dcd14f9 at line 1
</code></pre>
<p>The uuid should be 5dcd14f9-....-.....-...
Dots are characters that should exist there, and the dashes are just dashes.
For some reason I'm having a problem where it only gets the first part of the uuid.
Am I missing something, or is there actually something wrong with my syntax?
That's my code which is basically the error:</p>
<pre><code>PreparedStatement addPlayer = mySQL.getConnection().prepareStatement("INSERT INTO " + mySQL.getConnection() + " (uuid, name, join_date, group) VALUES (?,?,?,?)");
</code></pre>
<p>I of course cast the uuid to a string and add it as a value to the first column.
I've looked at other solutions and tried them but they didn't seem to work.</p>
| <java><mysql><sql><syntax> | 2020-02-07 11:57:13 | LQ_CLOSE |
60,122,877 | how to print function-returned values in python | I have the following function:
import pandas as pd
def foo():
d1 = {'data1': ['A', 'B', 'C']}
d2 = {'data2': [20, 30, 40]}
df1 = pd.DataFrame(d1)
df2 = pd.DataFrame(d2)
return df1, df2
df1, df2 = foo()
I am trying to get the following:
Results for df1:
data1
A
B
C
Results for df2:
data2
20
30
40
I tried some code below but didn't get me what I want (shows index, datatype and not very well aligned):
c = {'results for df1': df1,
'results for df2': df2
}
for a, b in c.items():
print(a, b) | <python><pandas><dataframe> | 2020-02-08 00:34:26 | LQ_EDIT |
60,123,788 | Comparing Text Fields Value | <p>using the Internet, Android Studio, and your current knowledge of Android app development, create an Android app project that has two (2) text fields and one (1) button. The button will compare the input from the text fields and display a response (SAME if values are the same and NOT THE SAME if they are not) if it is clicked. You may need to create a new activity for this</p>
| <android><android-studio><compare><textfield> | 2020-02-08 03:55:13 | LQ_CLOSE |
60,124,217 | python not understanding simple math question | <p>I am making mortgage calculator, I have provided information for variables p, i, n, but get error in the equation.</p>
<pre><code>p[i(1 + i) ^ n] / [(1 + i) ^ n – 1]
</code></pre>
| <python><variables><math> | 2020-02-08 05:33:28 | LQ_CLOSE |
60,124,384 | Infinite loop while traversing through linked list | <p>Deleting and viewing entire queue causes the problem- I'm assuming it is an infinite loop case for traversing. It works perfectly fine for adding the element but execution stops right after 2 or 3 are selected by the user.</p>
<p>I'm just adding some lines of random text before the code because stack isn't allowing such a big code with a small explanation.</p>
<p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?</p>
<pre><code>#include<iostream>
using namespace std;
class linkedlist
{
struct node
{
int number;
node *next;
}*HEAD;
public:
void addelement(int num);
void exitelement();
void displayqueue();
};
void linkedlist::addelement(int num)
{
node *t;
t= new node;
t -> number=num;
t -> next=HEAD;
HEAD=t;
cout<<num<<"has successfully been added to the queue /n";
}
void linkedlist::exitelement()
{
node *t;
t=HEAD;
while(t -> next !=NULL)
{
t=t -> next;
}
cout<<t->number;
delete t;
}
void linkedlist::displayqueue()
{
node *t;
t=HEAD;
while(t->next !=NULL)
{
cout<<t -> number<<"\t";
t=t->next;
}
cout<<" \n that's the end of the list \n";
}
int main()
{
int lol;
linkedlist m;
int rpt=1;
while(rpt==1)
{
int c;
cout<<"\n please select 1 to add an element, 2 to remove an element from the queue and 3 to display the entire queue \n";
cin>>c;
cout<<"/n";
if(c==1)
{
cout<<"enter the number: ";
cin>>lol;
m.addelement(lol);
}
else if(c==2)
{
m.exitelement();
}
else if(c==3)
{
m.displayqueue();
}
else
{
cout<<"you have entered an invalid input. Sorry \n";
}
cout<<"\n Do you wish to start the queue again??? \n";
cin>>rpt;
}
}
</code></pre>
| <c++><linked-list> | 2020-02-08 06:05:16 | LQ_CLOSE |
60,124,794 | How to stop the closing of date-picker of pickadate.js on blur? | I want to remain open my date-picker calendar on click outside the calendar. Please tell me the exact solution. Thanks in Advance. | <javascript><jquery><html><pickadate> | 2020-02-08 07:23:56 | LQ_EDIT |
60,125,184 | Year Part Update in sql DateTime Column | [![Table_Data][1]][1]
[1]: https://i.stack.imgur.com/o2Fxq.png
Need to change only the year part of every ChangedDate Column to 2017.
i.e
**2017**-02-08 13:55:30.193
**2017**-02-08 13:55:30.193
**2017**-02-08 13:55:30.193 | <sql-server><datetime> | 2020-02-08 08:32:54 | LQ_EDIT |
60,125,310 | how to convert string to date or date to string | <p>I have a tableview cell with a Date type Date, it shows me the following error and I don't know how to fix it:</p>
<blockquote>
<p>Error: Cannot assign value of type 'Date' to type 'String?'</p>
</blockquote>
<pre><code>cell.Resum_Controls_Data_txt.text = control.data
</code></pre>
<p>control.data (is type Date)</p>
| <swift><date><cell> | 2020-02-08 08:56:10 | LQ_CLOSE |
60,125,810 | Is there any reason why you would need to use `Environment.NewLine` instead of `backslash n` in Xamarin code? | Here's an example of my code:
Shell.Current.DisplayAlert($"Stop Quiz {Settings.Quiz}",
$"{Environment.NewLine}You tapped the {target} icon at the bottom of this page. The quiz will be stopped and you will be taken to the {target} screen.{Environment.NewLine}{Environment.NewLine}Please confirm{Environment.NewLine}",
"OK", "Cancel") == true)
What I am wondering, is why use `Environment.NewLine` instead of `backslash n`
| <xamarin><xamarin.forms> | 2020-02-08 10:14:39 | LQ_EDIT |
60,126,372 | How to create a blog with only index.html, style.css and script.js files? | <p>Inspiration for blog listing pages:
<a href="https://blog.hubspot.com/marketing" rel="nofollow noreferrer">https://blog.hubspot.com/marketing</a></p>
<p><a href="https://www.igomoon.com/blog" rel="nofollow noreferrer">https://www.igomoon.com/blog</a></p>
<p>I only want to know from where should I start? from the beginning of the first line code? or Can import sample codes and edit them? </p>
<p>Should I develop index.html and style.css first? and after that script.js?</p>
| <javascript><html><css><blogs> | 2020-02-08 11:34:38 | LQ_CLOSE |
60,127,736 | Is colorama the only way to change the python shell output colour? | <p>So I have been trying to change the colour of the output in the shell, but it just ends up returning boxes. I am using python 3.7.4.</p>
<p><a href="https://i.stack.imgur.com/qPF6C.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qPF6C.png" alt="The code and the output"></a></p>
| <python> | 2020-02-08 14:27:28 | LQ_CLOSE |
60,127,901 | Can someone please explain this recursion question the problem is solved? | <blockquote>
<p>Given base and n that are both 1 or more, compute recursively (no
loops) the value of base to the n power, so powerN(3, 2) is 9 (3
squared).</p>
</blockquote>
<p>The answer is </p>
<pre><code>public int powerN(int base, int n) {
if(n == 1)
return base;
return base * powerN(base, n - 1);
}
</code></pre>
<p>I am confused because when I look at this because is this not saying multiply the base against the returned number of <code>powerN()</code>?</p>
<blockquote>
<p>powerN(3,3);</p>
<p>= 3</p>
<p>= 3*powerN(base, n-1) = 6</p>
<p>= 3*powerN(base, n-1) = 9</p>
</blockquote>
<p>Which would multiply 9*6*3?</p>
<p>I do not see why we would have to multiply the base by the function? </p>
<p>Should the method not just return the answer as the base never changes and once <code>n==1</code> the base case executes </p>
| <java><recursion> | 2020-02-08 14:48:18 | LQ_CLOSE |
60,127,991 | Simple JSON parsing with Jackson | <p>I did not write a lot in Java yet, but I wonder if there is a simple way, to parse JSON and work with the results into a map just like we would do it in other modern languages:</p>
<pre><code>string = loadFromSomeWhere(URI)
dictionary = JSON.parse(string)
// do something with the dictionary
</code></pre>
<p>I do not want to define a POJO first, nor will I deal with the deepness of the JSON structure. And I can assume, that the file will stay small enought, so event driven parsing is not necessary.</p>
<p>I need to use Jackson and found only way to complicated approaches.</p>
| <java><json><jackson> | 2020-02-08 14:58:56 | LQ_CLOSE |
60,128,142 | Why is the select not visible entirely? | using MaterializeCSS, there is a modal window with a form. It is expected that there will be a lot of option in select, however, as you can see in the screenshot, the modal window "overlaps" the option part. How to win?
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/AfiLv.png | <css><select><modal-dialog><dropdown><materialize> | 2020-02-08 15:16:50 | LQ_EDIT |
60,128,152 | tweepy : ow get more than 100 different record per day per query using Twitter Standard API? | I'm trying to download a list of tweet using the standard API but what I get are always the same records.
i.e. this is my request:
```
ApiSearch = api.search(q="#immigration", lang="en", result_type="mixed", count=100, until=untilDate, include_entities=False)
```
but if I run it now and then between 1 hour the result I get is the same.
Is there something wrong in the settings of my "api.search", or did I misunderstood the limits of the Twitter Standard API?
This is my code:
```
conn_str = ("DRIVER={PostgreSQL Unicode};"
"DATABASE=TwitterLCL;"
"UID=postgres;"
"PWD=pswd;"
"SERVER=localhost;"
"PORT=5432;")
consumer_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
consumer_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
access_token = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
access_token_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth, wait_on_rate_limit=True)
col_db_tweetTable01 = ['CREATED_AT', 'TWEET_ID', 'TEXT', 'USER_ID']
i = 0
while i <= 10000:
time.sleep(2)
i += 1
ApiSearch = api.search(q="#immigration", lang="en", result_type="mixed", count=100, until=None, include_entities=False)
time.sleep(2)
for res in range(0, len(ApiSearch)):
db_tweetTable01DB = pd.DataFrame(columns = col_db_tweetTable01) #creates a new dataframe that's empty
TWEET = ApiSearch[res]._json
Created_At = None
Created_At = TWEET.get("created_at")
print("Created_At : "+Created_At)
Tweet_Id = None
Tweet_Id = TWEET.get("id_str")
Text = None
Text = TWEET.get("text")
User_Id = TWEET.get("user").get("id_str")
db_tweetTable01DB = db_tweetTable01DB.append({'CREATED_AT' : Created_At, 'TWEET_ID' : Tweet_Id, 'TEXT' : Text, 'USER_ID' : User_Id}, ignore_index=True)
try:
connStr = pyodbc.connect(conn_str)
cursor = connStr.cursor()
for index, row in db_tweetTable01DB.iterrows():
#print(row)
cursor.execute("INSERT INTO public.db_tweettable01(CREATED_AT, TWEET_ID, TEXT, USER_ID) values (?, ?, ?, ?)", row['CREATED_AT'], row['TWEET_ID'], row['TEXT'], row['USER_ID'])
connStr.commit()
cursor.close()
connStr.close()
except pyodbc.Error as ex:
sqlstate = ex.args[1]
print(sqlstate)
print("Tweet_Id : "+Tweet_Id)
print("User_Id : "+User_Id)
```
Thanks for your help, | <python><twitter><tweepy> | 2020-02-08 15:17:51 | LQ_EDIT |
60,129,244 | while in not working in nested list PYTHON | <p>The first section of code prints 1 but the second doesn't, why and how to produce the above effect?</p>
<pre><code>while [1] in k:
print(1)
k=[[0],[1,1,1],[0]]
while [1] in k:
print(1)
</code></pre>
| <python> | 2020-02-08 17:23:18 | LQ_CLOSE |
60,130,922 | can anyone solve it for me | <hr>
<p>IndexError Traceback (most recent call last)
in
----> 1 print('the {2} {1} {3}'.format('brown', 'fat', 'fox',))</p>
<p>IndexError: tuple index out of range<strong>strong text</strong></p>
| <python><jupyter-notebook><anaconda> | 2020-02-08 20:31:28 | LQ_CLOSE |
60,131,733 | How can you create a command to run other applications in Windows Batch? | <p>My goal is to run other programs through the command of one in Windows Batch. <a href="https://i.stack.imgur.com/IdkDW.png" rel="nofollow noreferrer">Here are the files I would like to run through a single command if possible.</a> </p>
<p>However the code that I have attempted at best is this</p>
<pre><code>start "C:\users\excre\OneDrive\Desktop\Coding Files\GTA Chinatown\Terms & Conditions.html"
start "C:\users\excre\OneDrive\Desktop\Coding Files\GTA Chinatown\Audio_Synthesis-Program.vbs"
start "C:\users\excre\OneDrive\Desktop\Coding Files\GTA Chinatown\test3.bat"
</code></pre>
<p><a href="https://i.stack.imgur.com/cUcks.png" rel="nofollow noreferrer">This resulted in a simple location CMD tab as shown here</a></p>
<hr>
<p>If anyone has a potential solution to this please mention below</p>
| <html><batch-file><vbscript> | 2020-02-08 22:17:09 | LQ_CLOSE |
60,133,085 | How to give canvas an id | <p>How can i give these canvas' in JS/html an id?</p>
<p>I want to make multiple flashing images on a single page and when I do only one image displays as there is no way to know which canvas to display, below is a link to my project.</p>
<p><a href="https://glitch.com/edit/#!/join/4cb25634-5dc4-45b8-8e28-060e6b1a98aa" rel="nofollow noreferrer">My project on glitch</a></p>
| <javascript><canvas><id> | 2020-02-09 02:52:58 | LQ_CLOSE |
60,133,426 | Date matching in Swift not working code there | <p>iam trying to send some string dates to one method and if its matching the date format then return true,</p>
<p>my input paramters look like "4325/353/53" this is fail case and success case "09/25/2020"</p>
<p>my methode, but this is returning fail for everything. pls help</p>
<pre><code>func isValidDate(dateString: String) -> Bool {
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "dd/MM/yyyy"
if let _ = dateFormatterGet.date(from: dateString) {
//date parsing succeeded, if you need to do additional logic, replace _ with some variable name i.e date
return true
} else {
// Invalid date
return false
}
}
</code></pre>
| <ios><swift> | 2020-02-09 04:21:48 | LQ_CLOSE |
60,134,531 | How do you handle collection and storage of new data in an existing system? | <p>I am new to system design and have been asked to solve a problem.</p>
<p>Given a car rental service website, I need to work on a new feature.</p>
<p>The company has come up with some more data that they would like to capture and analyze along with the data that they already have.</p>
<p>This new data can be something like time and cost to assemble a car. </p>
<p>I need to understand the following:</p>
<p>1: How should I approach the problem, from API design perspective?</p>
<p>2: Is changing the schema of your tables going to do any good, if that is an option?</p>
<p>3: Which databases can be used?</p>
<p>The values once stored can be changed. For example, the time to assemble can reduce or increase, hence the users should be able to update the values.</p>
| <database><database-design><architecture> | 2020-02-09 07:50:04 | LQ_CLOSE |
60,135,318 | Filling user card with the information from the form | <p>I need to create the card which is filled with the information as soon as the user types something into the form. For example, he enters his name and the name appears on the card. The page shouldn't be reloaded, the info on the card must appear instantly. </p>
| <javascript><html> | 2020-02-09 09:50:47 | LQ_CLOSE |
60,135,694 | i got this error in androidStudio : java.lang.NumberFormatException: For input string: " " | for example i want to create contacts that only has two fields name and age, but only name is important for me.
public class Contact {
public String name;
public int age;
public Contact(String name) {
this.name = name;
}
public Contact() {
}
public Contact(String name,int age) {
this.name = name;
this.age=age
}
}
in the part of code for some reason i need user add new Contact and its not important to insert age.
after user submit i expect get new Contact.
EditText editName=findviewByid(r.id.edit_name);
EditText editAge=findviewByid(r.id.edit_age);
.
.
.
when user click the submit button :
String name = editName.getText().toString().trim();
String age = editAge.getText().toString().trim();
Contact contact =new (name,Integer.parseInt(age));
if user didn't input age we got this error
java.lang.NumberFormatException: For input string: ""
| <android> | 2020-02-09 10:37:08 | LQ_EDIT |
60,136,357 | Display numbers from 0 to X vis versa | <p>i need your help in this puzzle:
i want to take an input from the user as X and display numbers from 0 to X and from X to 0.
the trick is to use only one variable.
how could i solve this in java</p>
| <java> | 2020-02-09 11:58:39 | LQ_CLOSE |
60,138,318 | Swift development pods | <p>is there some good tutorial where I can follow, is there a good tutorial for better understanding, the ones I find i just create the pod and them publish, there is no implementation for me start to develop my own</p>
| <swift><cocoapods> | 2020-02-09 15:42:25 | LQ_CLOSE |
60,138,452 | dotnet run is not a recognized command line | <p>I have a very simple service. I'm able to start it normally through Visual Studio if I run my service on a debug mode. But I'm trying to run this service while I'm running my project normally locally.</p>
<p>If I do a dotnet.run through my command prompt I get this error: dotnet is not a recognized and internal or external command line.</p>
<p>I have all the framework installed since there is no issue running this on a debug mode. Any ideas?</p>
<p><a href="https://i.stack.imgur.com/TEKxs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TEKxs.png" alt="enter image description here"></a></p>
| <c#><asp.net><visual-studio> | 2020-02-09 15:54:26 | LQ_CLOSE |
60,138,465 | Reading integers from a text file containing integers and strings | So here is my code and the only options I have in the chapter we are on are the while (!scan.hasNextInt()). This is my code and it works until I try to read a file with strings. The file looks like this:
1
2
John
3
4
Black
5
Jason
7
8
I do not understand how to use this method.
My code:
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
int number;
int temp;
int i;
boolean isPrime = true;
double count = 0.0;
double total = 0.0;
File inputFile = new File("Values.txt");
Scanner file = new Scanner(inputFile);
while (file.hasNext())
{
if (!file.hasNextInt()) {
String s = file.nextLine();
}
else {
number = file.nextInt();
}
for (i = 2; i <= (number / 2); i++)
{
temp = number % i;
if (temp == 0)
{
isPrime = false;
break;
}
}
if (isPrime) {
//System.out.println(number);
total = total + number;
count = count + 1.0;
}
isPrime = true;
}
//System.out.println(total);
//System.out.println(count);
System.out.println(total / count);
System.out.println("File is Empty");
file.close();
}
}
| <java> | 2020-02-09 15:56:06 | LQ_EDIT |
60,138,563 | Scope Issue in java | <pre><code>public class Calculator {
private int total;
private int value;
public Calculator(int startingValue){
int total = startingValue;
value = 0;
}
public int add(int value){
int total = total + value;
return total;
}
/**
* Adds the instance variable value to the total
*/
public int add(){
int total += value;
return total;
}
public int multiple(int value){
int total *= value;
return total;
}
public void setValue(int value){
value = value;
}
public int getValue(){
return value;
}
}
</code></pre>
<p>The assignment says "For this exercise, we are going to take a look at an alternate Calculator class, but this one is broken. There are several scope issues in the calculator class that are preventing it from running.</p>
<p>Your task is to fix the Calculator class so that it runs and prints out the correct results. The CalculatorTester is completed and should function correctly once you fix the Calculator class."</p>
<p>I thought i did it right but it keeps telling me its wrong and the code will not run, how do i fix this scope issue?</p>
| <java><scope> | 2020-02-09 16:06:35 | LQ_CLOSE |
60,140,123 | Extract strings from a list element of a certain size, | Say I have a list of names:
names = ["David", "Lee", "Sara", "Daniel", "Nick"]
I want to move the list elements that have a character count of less than 5 (not including 5) into a new list called short_names that would look like this:
short_name ["Lee", "Sara", "Nick"]
How can I do this with a for loop? Where I am struggling with is how to find the length of characters within each list element. | <python><string><list> | 2020-02-09 18:49:09 | LQ_EDIT |
60,146,978 | I want to print a string multiple time but in a new line | print('python'*5,sep='\n')
[][1]
[1]: https://i.stack.imgur.com/zB3HT.png
how to print it in new line
Ex: python
python
python | <python><python-3.x> | 2020-02-10 08:58:20 | LQ_EDIT |
60,149,360 | How to put text on top of image when images arranged in list and heavily styled | Link to HTML + CSS:
https://jsfiddle.net/babis95/zdhne95u/
I have some HTML and CSS setup for a simple image gallery.
I've been trying to add white text on top of each of the images in the center.
I researched different ways but none seem to work with they way i set up my code:
```
.section-images p
{
color: white;
margin: 0;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
```
This code seem to work on single image in a div, but not when multiple images are used.
| <html><css> | 2020-02-10 11:23:12 | LQ_EDIT |
60,149,450 | How to make the encoded value in format | YTo2OntpOjA7czo0OiIyMDY3IjtpOjE7czo0OiIyMDY4IjtpOjI7czo0OiIyMDY5IjtpOjM7czo0OiIyMDcwIjtpOjQ7czo0OiIyMDcxIjtpOjU7czo0OiIyMDcyIjt9
Above mention is my encoded value.
When iam trying to decode it iam getting the output in this format
a:6:{i:0;s:4:"2067";i:1;s:4:"2068";i:2;s:4:"2069";i:3;s:4:"2070";i:4;s:4:"2071";i:5;s:4:"2072";}
Now how to convert into
["2067","2068","2069","2070","2071","2072"] OR (2067,2068,2069,2070,2071,2072) | <php> | 2020-02-10 11:28:56 | LQ_EDIT |
60,152,799 | How can i fix the terminated console | I am trying to do cipher game. Our teacher said it will be 2 mode. First mode will be normal mode which is one of the quote will be choosen randomly. Second mode is the test mode which is you will choose a quote. In the test mode i cant go further because it says terminated i dont know what is the problem.
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Random random = new Random();
char plainText[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'r', 'x', 'y', 'z'};
char cipherText[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'r', 'x', 'y', 'z'};
System.out.println("Please choose a mod: ");
System.out.println("1.Normal Mode");
System.out.println("2.Test Mode");
int user = in.nextInt();
String[] strings = {
"So many books so little time ",
"Be the change that you wish to see in the world ",
"No one can make you feel inferior without your consent",
"Love for all hatred for none ",
"Die with memories not dreams",
"Aspire to inspire before we expire",
"Whatever you do do it well",
"What we think we become ",
"Be so good they cant ignore you ",
};
String randomString = strings[random.nextInt(strings.length)];
if (user==1) {
System.out.println(randomString);
for (int a=0;a<randomString.length();a++) {
for (int i=0; i<plainText.length;i++) {
if(plainText[i] == (randomString.charAt(a))) {
System.out.print(cipherText[i]);
}
}
}
}
else if(user==2) {
System.out.println("Please choose one quote: ");
String islemler = "1. So many books so little time\n" +
"2. Be the change that you wish to see in the world\n" +
"3. No one can make you feel inferior without your consent\n" +
"4. Love for all hatred for none\n" +
"5. Die with memories not dreams\n" +
"6. Aspire to inspire before we expire\n" +
"7. Whatever you do do it well\n" +
"8. What we think we become\n" +
"9. Be so good they cant ignore you\n";
System.out.println(islemler);
String islem = in.nextLine();
switch(islem) {
case "1":
System.out.println("So many books so little time");
case "2":
System.out.println("Be the change that you wish to see in the world");
case "3":
System.out.println(" No one can make you feel inferior without your consent");
case "4":
System.out.println(" Love for all hatred for none");
case "5":
System.out.println("Die with memories not dreams");
case "6":
System.out.println("Aspire to inspire before we expire");
case "7":
System.out.println("Whatever you do do it well");
case "8":
System.out.println("What we think we become");
case "9":
System.out.println(" Be so good they cant ignore you");
}
}
else {
System.out.println("Please restart the game");
}
}
}
| <java><arrays> | 2020-02-10 14:47:07 | LQ_EDIT |
60,153,820 | ER Diagram Design: Should every entity have a primary key? And can we have sub entity? | **Problem: Design a ER diagram such as:**
- An item has the attribute: description.
- An item can be sold by a company or a person.
- A person has the attributes: name, phone and email.
- A company has the attributes: company name, address and a contact person who is one from the person entity set.
- A contact person cannot sell the same item with the company he works for.
**This is my design:**
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/rSzPQ.png
I'm learning and I know this is a stupid question. But please correct and point out what are wrong in my design.
- I'm not sure that I should remove the primary key SellerID in Seller entity and add companyID to Company entity and personID entity.
- Is the Contact Person entity connected to Person entity correctly?
- How can I demonstrate the constraint: a contact person cannot sell the items (distinguished by item ID) his company is selling.
Thank you. | <database><database-design><entity-relationship><erd> | 2020-02-10 15:46:39 | LQ_EDIT |
60,161,316 | Create a program that asks the user for an age. It tells them their grade (9, 10, 11 or 12) based on their response. Python | age = (int(input("How old are you?")))
if (age == 14 or age ==15):
print ("you are in grade 9")
if (age == 15):
print("or")
if (age == 15 or age == 16):
print ("you are in grade 10")
if (age == 16):
print("or")
if (age == 16 or age == 17):
print ("you are in grade 11")
if (age == 17):
print ("or")
if (age == 17 or age == 18):
print ("you are in grade 12") | <python><python-3.x><if-statement> | 2020-02-11 02:52:37 | LQ_EDIT |
60,161,742 | Why is "parameters" is not defined | I am following the tutorial at https://www.dataquest.io/blog/python-api-tutorial/. It is saying that "parameters" is not defined. the URL has params=parameters, I have used both in the coding and still getting error. Not sure how to correct it.
This is the code:
<code>
import requests
import json
response = requests.get("http://api.open-notify.org/astros.json")
response = requests.get("http://api.open-notify.org/iss-pass.json", params=parameters)
def jprint(obj):
# create a formatted string of the Python JSON object
text = json.dumps(obj, sort_keys=True, indent=4)
print(text)
parameters = {
"lat":27.8006,
"lon":97.3864
}
jprint(response.json())
</code> | <python><python-requests> | 2020-02-11 03:50:12 | LQ_EDIT |
60,163,916 | No such external account . Stripe Payout not working using php? | **I am transferring fund from stripe account to connect account using payout api **
my code is:
$payout = \Stripe\Payout::create([
'amount' => 500,
'currency' => 'aud',
'description' => 'first payout payment transfer on stripe',
'destination' => 'bank_id',
'method' => 'instant',
'source_type' => 'bank_account',
'statement_descriptor' => 'first payout payment transfer on stripe ',
]);
after hit this api show error:
Stripe\Exception\InvalidRequestException: No such external account: ba_1G497bAoBoRegJgCC1jj2UE2 in file /var/www/html/ultimateFitness/app/Stripe/lib/Exception/ApiErrorException.php on line 38
Also i am follow stripe documentation:
[https://stripe.com/docs/api/payouts/creat][1]e
[1]: https://stripe.com/docs/api/payouts/create | <php><laravel><stripe-payments> | 2020-02-11 07:31:00 | LQ_EDIT |
60,169,005 | How upload multiple files angular 7/8 using Queue with progress bar and create main progress bar for all files | I need multiple files to upload in angular 7/8 using queue with creating one progress bar to upload all files. | <javascript><angular> | 2020-02-11 12:40:52 | LQ_EDIT |
60,169,679 | Create a folder and subfolder when selecting a cell in excel (VBA) | I am a total newbie in VBA so I hope you could help me with this.
I want to create a folder inside a given path. Inside the folder, I want a subfolder. The name of the folder will be indicated in column A and of the subfolder in column B of an excel worksheet. The path will be in column C.
[enter image description here][1]
I would like to be able to click on a cell on column D which would activate a macro who will then create the folder and subfolder. I was hoping to be able to achieve this by using this code:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Not Application.Intersect(Target, Range("c2:c10000")) Is Nothing Then Call CreatePath
End Sub
So I need the function CreatePath. When a cell is selected on Column D, the CreatePath function should identify the row of the selected cell from column D, take from that row the corresponding name of the folder, subfolder and the path and create the folder and subfolder.
Any idea how this function should look like? Please keep in mind that I have started to "play" two days ago with VBA so my know-how is very limited.
Thank you all for your support.
[1]: https://i.stack.imgur.com/nOluY.png | <vba><button><subdirectory><create-directory> | 2020-02-11 13:13:21 | LQ_EDIT |
60,169,709 | Remove strings from a list that starts with '0' | My code
----------
l=['99','08','096']
for i in l:
if i.startswith('0'):
i.replace('0','')
print(l)
Output
---------
l=['99','08','096']
| <python><python-3.x><string><list><for-loop> | 2020-02-11 13:14:50 | LQ_EDIT |
60,182,022 | why I got UnicodeDecodeError when i use python3 readlines to read a file which contains Chinese characters? | ```
>>> path = 'name.txt'
>>> content = None
>>> with open(path, 'r') as file:
... content = file.readlines()
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "/mnt/lustre/share/miniconda3/lib/python3.6/encodings/ascii.py", line 26, in decode
return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 163: ordinal not in range(128)
```
When I run this code to read a file which contains Chinese characters, I got an error. The file is saved by using UTF-8. My python version is 3.6.5. But it runs ok in python2.7. | <python><encoding> | 2020-02-12 05:59:21 | LQ_EDIT |
60,199,187 | How to Replace text partially in linux using sed | I have an xml tag that I need to manipulate on linux
<m1:PayloadId>TESTCASE01_0000123456</m1:PayloadId>
I need to change the text from "TESTCASE01_0000123456" to "TESTCASE01_1234567890" between the tags
I used the sed command in my code:"**sed -i 's/PayloadId>.*</m1:PayloadId>'0000123456'</g' t1.xml**"
but it replaces the entire text. I need to retain "TESTCASE01_"
Appreciate any help
| <awk><sed><xmlstarlet> | 2020-02-13 01:22:36 | LQ_EDIT |
60,202,155 | Why, when I print a derefrenced pointer in main that points to a variable declared in a function, does it not print junk memory. (GOLANG) | package main
2
3 import "fmt"
4
5
6 func point(x int) *int {
7
8 y := x
9 return &y
10
11 }
12
13
14 func main() {
15
16 x := 10
17
18 pointer := point(x)
19
20 fmt.Println(*pointer)
21
22
23
24
25 }
Shouldn't the memory for Y be junk after the function has been called?
It prints 10 just fine.
~ | <go> | 2020-02-13 07:02:31 | LQ_EDIT |
60,209,931 | How to branch recursion into returning only a list of lists (Python) | I'm having a problem where I what I need returning should be a list of lists, with each nested list being a list of 2 strings. I can't find a way to flatten this list effectively, or to return just the list of lists, as the number of nested lists is undeterminable. This is happening in my recursive function, where I branch into 3 different paths of recursion for each recursive loop.
What I have so far is:
```
def f(used, sequences):
if sequences[0] == '' or sequences[1] == '':
if sequences[0] == '' and sequences[1] == '':
return [used[0], used[1]]
elif sequences[0] != '':
return [used[0] + sequences[0], used[1] + '-' * len(sequences[0])]
elif sequences[1] != '':
return [used[0] + '-' * len(sequences[1]), used[1] + sequences[1]]
else:
return [f([sequences[0][-1] + used[0], sequences[1][-1] + used[1]], [sequences[0][:-1], sequences[1][:-1]]),
f([sequences[0][-1] + used[0], '-' + used[1]], [sequences[0][:-1], sequences[1]]),
f(['-' + used[0], sequences[1][-1] + used[1]], [sequences[0], sequences[1][:-1]])]
```
which will generate something like `[[[['str', 'str'], ['str', 'str'], ['str', 'str']], [['str, 'str']... ` when I want it to come out as `[['str', 'str'], ['str', 'str'], ['str', 'str']...`
Is there a way to fix my recursion so that this is the case, or a function I can write to flatten it the way I want? | <python><python-3.x><list><recursion><nested-lists> | 2020-02-13 14:17:36 | LQ_EDIT |
60,210,417 | i want to code this button in pictures with the following animation if possible | i am trying to create this button in html with a little animation as below
how can i achieve this ?
i have tried some ideas but failed as usual :D
~~~
<div class="skew-btn">
<div class="btn">
<div class="main">
<a href="#hire">Hire me</a>
</div>
</div>
</div>
~~~
here is how i see it in html **you can change this**
[![enter image description here][1]][1]
animate to this on hover
[![enter image description here][2]][2]
[1]: https://i.stack.imgur.com/HPLd7.png
[2]: https://i.stack.imgur.com/aWE0y.png | <javascript><html><css> | 2020-02-13 14:43:59 | LQ_EDIT |
60,210,610 | I'm just beginning to learn C: Can someone explain what the pointers and typecasting are doing in this code? | <p>//Beginning of a Function:</p>
<pre><code>char *encrypt(char *string, size_t length) {
}
</code></pre>
<p>I am beginning a simple encryption function, and I'm wondering what exactly the above code is carrying out? I am assuming I'm initializing an encrypt function as char pointer, with a memory destination 'string' and size of 'length'</p>
<p>Am I correct?</p>
| <c><pointers> | 2020-02-13 14:53:53 | LQ_CLOSE |
60,211,237 | HTML - Text/Button Alignment (CSS Media) | <blockquote>
<p><a href="https://jsfiddle.net/5d401nso/1/" rel="nofollow noreferrer">https://jsfiddle.net/5d401nso/1/</a></p>
</blockquote>
<pre><code>#mobileview{
/*background-image:url("");
background-size:100% 100%;*/
width:auto;
height:auto;
}
@media(max-width: 768px){
#mobileview{
width:411px;
height:411px;
}
}
@media(max-width: 500px){
#mobileview{
width:411px;
height:411px;
}
}
</code></pre>
<p>Above is the jsfiddle that i have created.</p>
<blockquote>
<p>Current Problem: Not Supporting Mobile View and looking a ways to
change the text and button alignment from center to "left" when in
mobile view</p>
</blockquote>
<p>Solution That i wanted: When in mobile view ( max width 768px or 500px ), the text and button will align to left side instead of center.</p>
| <html><css> | 2020-02-13 15:26:36 | LQ_CLOSE |
60,212,780 | Is `string.assign(string.data(), 5)` well-defined or UB? | <p>A coworker wanted to write this:</p>
<pre><code>std::string_view strip_whitespace(std::string_view sv);
std::string line = "hello ";
line = strip_whitespace(line);
</code></pre>
<p>I said that returning <code>string_view</code> made me uneasy <em>a priori</em>, and furthermore, the aliasing here looked like UB to me.</p>
<p>I can say with certainty that <code>line = strip_whitespace(line)</code> in this case is equivalent to <code>line = std::string_view(line.data(), 5)</code>. I believe that will call <a href="http://eel.is/c++draft/basic.string#string.cons-itemdecl:16" rel="noreferrer"><code>string::operator=(const T&) [with T=string_view]</code></a>, which is defined to be equivalent to <a href="http://eel.is/c++draft/basic.string#string.assign-itemdecl:4" rel="noreferrer"><code>line.assign(const T&) [with T=string_view]</code></a>, which is defined to be equivalent to <a href="http://eel.is/c++draft/basic.string#string.assign-itemdecl:6" rel="noreferrer"><code>line.assign(line.data(), 5)</code></a>, which is defined to do this:</p>
<pre><code>Preconditions: [s, s + n) is a valid range.
Effects: Replaces the string controlled by *this with a copy of the range [s, s + n).
Returns: *this.
</code></pre>
<p>But this doesn't say what happens when there's aliasing.</p>
<p>I asked this question on the cpplang Slack yesterday and got mixed answers. Looking for super authoritative answers here, and/or empirical analysis of real library vendors' implementations.</p>
<hr>
<p><a href="https://godbolt.org/z/y_R8-9" rel="noreferrer">I wrote test cases</a> for <code>string::assign</code>, <code>vector::assign</code>, <code>deque::assign</code>, <code>list::assign</code>, and <code>forward_list::assign</code>.</p>
<ul>
<li>Libc++ makes all of these test cases work.</li>
<li>Libstdc++ makes them all work except for <code>forward_list</code>, which segfaults.</li>
<li>I don't know about MSVC's library.</li>
</ul>
<p>The segfault in libstdc++ gives me hope that this is UB; but I also see both libc++ and libstdc++ going to great effort to make this work at least in the common cases.</p>
| <c++><stl><undefined-behavior> | 2020-02-13 16:44:35 | HQ |
60,213,364 | Xcode 11.4 Circular Reference errors | <p>When compiling project on Xcode 11.4 (on previous Xcode project is building fine) I get following 999+ errors (Did clean build and deleted derived data):</p>
<pre><code><unknown>:0: error: circular reference
<unknown>:0: error: circular reference
<unknown>:0: note: through reference here
<unknown>:0: error: circular reference
<unknown>:0: error: circular reference
<unknown>:0: note: through reference here
<unknown>:0: note: through reference here
<unknown>:0: error: circular reference
<unknown>:0: note: through reference here
<unknown>:0: error: circular reference
<unknown>:0: error: circular reference
<unknown>:0: note: through reference here
</code></pre>
<p>Is this a problem with Xcode 11.4? Is it possible to disable <code>circular reference</code> checking option when compiling a project?.</p>
| <ios><swift><xcode> | 2020-02-13 17:21:49 | HQ |
60,213,604 | automatically convert string to appropriate type | <p>I am trying to find a function to have python automatically convert a string to the "simplest" type. Some examples:</p>
<pre><code>conversion_function("54") -> returns an int 54
conversion_function("6.34") -> returns a float 6.34
conversion_function("False") -> returns a boolean False
conversion_function("text") -> returns a str "text"
</code></pre>
<p>R has a function called <a href="https://stat.ethz.ch/R-manual/R-devel/library/utils/html/type.convert.html" rel="nofollow noreferrer">type.convert</a> that does this. What is the way to do this in python? Is there an existing function or does one need to create a custom one?</p>
| <python> | 2020-02-13 17:37:51 | LQ_CLOSE |
60,214,641 | PHP quotes in SQL | <p>Why does this code produce an error</p>
<pre><code> $sql = "INSERT INTO accountlist VALUES ("", "$user", "'$pwd", "$mail", "$date")";
</code></pre>
<p>and this one doesn't?</p>
<pre><code> $sql = "INSERT INTO accountlist VALUES ('', '$user', '$pwd', '$mail', '$date')";
</code></pre>
<p>I know that double quotes process variables while single quotes doesn't, so the first option should be the right one, but it is the opposite!</p>
| <php><mysql><sql><quotes> | 2020-02-13 18:50:28 | LQ_CLOSE |
60,215,841 | $_POST is not what I expect it to be | <p>I want to write a very simple web page. There is only one button which triggers a POST method which is called on a PHP file. But the $_POST variable in the PHP file remains empty when the button is clicked.
Here are my codes:</p>
<p>index.html:</p>
<pre><code><!doctype html>
<html lang="en">
<head>
<script src="script.js" type="text/javascript"></script>
<script src="jquery-3.4.1.min.js" type="text/javascript"></script>
<meta charset="utf-8">
</head>
<body>
<button type="button" onclick="mypost();">POST</button>
</body>
</html>
</code></pre>
<p>script.js:</p>
<pre><code>function mypost(){
$.post("test.php","Hello World!");
}
</code></pre>
<p>test.php:</p>
<pre><code><?php
print_r ($_POST);
</code></pre>
| <php><jquery> | 2020-02-13 20:20:20 | LQ_CLOSE |
60,216,317 | Is go evaluation order between member invocations guaranteed? | <p>Let's say I have a struct with state, and a few member functions on that struct.
Let's say that the struct member returns an instance of its own type, and I call additional functions on that instance, and pass the result of calling some other member on the initial instance as an argument.
Is the order of invocation between the first invocation, and the argument invocation, guaranteed?</p>
<p>(This pattern comes up a lot when trying to build "builder" type objects that have some internal state, like an expression stack.)</p>
<pre><code>package main
import (
"fmt"
)
type q struct {
val int
}
func (s *q) getVal() int {
return s.val
}
func (s *q) a() *q {
s.val += 1
return s
}
func (s *q) b(i int) int {
return i + s.val
}
func main() {
s := &q{}
// this currently prints 2
// but is that guaranteed?
fmt.Println(s.a().b(s.getVal()))
}
</code></pre>
<p>Specifically, is the relative invocation order of <code>s.a()</code> versus <code>s.getVal()</code> guaranteed?
Golang defines the "lexical left-to-right order," but only for an individual expression, and <code>s.a().b()</code> seems like it's technically a different expression than <code>s.getVal()</code>.</p>
<p>The behavior it currently has is the behavior I'd want and expect, but I can't tell whether it's also a behavior I can rely on "forever."</p>
| <go><expression-evaluation> | 2020-02-13 20:55:25 | LQ_CLOSE |
60,217,910 | how can I simplify my if-else statement in java? | In my code I have a method `size(MyData)` that returns size of data - it can be 0 or greater.
I also have a flag `exclude` that can be `true` or `false`. The point of my algorithm is to do some operation on data based on its size and the value of the flag.
- If the size is greater than 0, I want to do operation on data.
- If the size is 0, then I need to check the value of the flag `excluded`. In that case, if the flag `excluded` is set to true, I don't want to do operation on data. But if the flag is set to false, I need to do operation on data.
This is my algorithm so far:
int numberOfKids = size(MyData); //this can be 0 or greater
if (numberOfKids != 0) {
//do operation
}
else {
if (!exclude) {
//do operation
}
}
is there a better way of writing this algorithm?
Thanks! | <java><if-statement> | 2020-02-13 23:19:41 | LQ_EDIT |
60,217,930 | java, best API jar | <p>I'm building one API using javax.ws.rs-api(2.1.1) and com.sun.jersey (1.18.1) but it causes one Exception. Reading some threads it seems like one of both includes one class that is part of the other and this raises this Exception.
After some tries I'm still stucked on find how to fix it but then another question came to my brain, Is this the best API class for building servlets? So my question is if somebody can provide his experience and can say that continue using those libraries is the best option (and then fight for fixing this Exception) or can suggest better options.</p>
<p>I'm not using Spring neither Hibernate and those are not the option, I build my own Servlet from scratch ... yes ... I have my reasons ....</p>
<p>Thanks in advance
Regards</p>
| <java><api><servlets> | 2020-02-13 23:21:55 | LQ_CLOSE |
60,220,258 | how to Send automated SMS using API? | I have this condition to scheduled my sms.(ERROR) but the sms im using is POST method I need to be automated. and send sms to the number of the current id. i dont know how to get the number of the current id and send the message. here is my code:
I NEED HELP
$duedate = "";
$date_now=date("Y-m-d");
date_default_timezone_set('Asia/Manila');
$date_now = strtotime($date_now);
$duedate= strtotime($duedate);
if ($duedate<=$date_now) {
function itexmo($number,$message,$apicode) {
$url = 'https://www.itexmo.com/php_api/api.php';
$itexmo = array('1' => $number, '2' => $message, '3' => $apicode);
$param = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($itexmo),
),
);
$context = stream_context_create($param);
return file_get_contents($url, false, $context);}
if ($_POST){
$number = $number;
$name = $name;
$api = "API";
$text = $name." : ".$number;
if(!empty($_POST['name']) && ($_POST['number']) && ($_POST['msg'])){
$result = itexmo($number,$text,$api);
if ($result == ""){
echo "iTexMo: No response from server!!!
Please check the METHOD used (CURL or CURL-LESS). If you are using CURL then try CURL-LESS and vice versa.
Please CONTACT US for help. ";
}else if ($result == 0){
echo "Message Sent!";
}
else{
echo "Error Num ". $result . " was encountered!";
}
}
}
} | <php><sms> | 2020-02-14 05:01:28 | LQ_EDIT |
60,223,024 | Nested function returning a variable through the outer function in python | <p>I have a requirement which I am going to try an explain through the below example:</p>
<p>Suppose we have a segment of code like this:</p>
<pre><code>def a:
def b:
x = 2
</code></pre>
<p>Now I want to return x through the function a. Is there any way to do it in python?</p>
| <python><python-3.x> | 2020-02-14 09:00:48 | LQ_CLOSE |
60,223,729 | How to insert a character at a certain position in a number without converting it into a string? | <p>I have to insert "/" between 2020 and 0001 in the number 20200001. I know how to do it by converting the number to string, but I am unable to do it by not converting it.</p>
| <javascript> | 2020-02-14 09:43:52 | LQ_CLOSE |
60,226,927 | python replace value if it starts with certain character | I have a following list and I am trying to replace any value which starts with ```23:``` to ```00:00:00.00```
```tc = ['00:00:00.360', '00:00:00.920', '00:00:00.060', '00:00:02.600', '23:59:55.680', '00:00:05.960', '00:00:01.040', '00:00:01.140', '00:00:01.060', '00:00:01.480', '00:00:00.140', '00:00:00.280', '23:59:59.800', '00:00:01.200', '00:00:00.400', '23:59:59.940', '00:00:01.220', '00:00:00.380']```
I am able to get what I need using regex,
```tc = [re.sub(r'(\b23:)(.*)',r'00:00:00.00', item) for item in tc]```
and it gives me expected result as per below,
```['00:00:00.360', '00:00:00.920', '00:00:00.060', '00:00:02.600', '00:00:00.00', '00:00:05.960', '00:00:01.040', '00:00:01.140', '00:00:01.060', '00:00:01.480', '00:00:00.140', '00:00:00.280', '00:00:00.00', '00:00:01.200', '00:00:00.400', '00:00:00.00', '00:00:01.220', '00:00:00.380']```
But if I use the below method without using regex, then the result is not what I expect,
```tc = [item.replace(item, '00:00:00.00') for item in tc if item.startswith('23:')]```
Result: ```['00:00:00.00', '00:00:00.00', '00:00:00.00']```
The resultant list is only with replaced items and not the whole list. How to I use the above method to get complete list?
| <python><list><if-statement><list-comprehension><conditional-operator> | 2020-02-14 13:05:33 | LQ_EDIT |
60,227,720 | random numbers from to C++ | I want it to display random numbers from to the value it writes but something is not working properly there is code
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int draw(int from_to, int to_from)
{
return (rand()%to_from)+from_to;
}
int main()
{
srand(time(NULL));
int start,stop;
cout << "First number: " << endl;
cin >> start;
cout << "Last number: " << endl;
cin >> stop;
int x=20;
do
{
cout << draw(start,stop) << endl;
x--;
} while(x>0);
return 0;
}
| <c++><random> | 2020-02-14 13:55:14 | LQ_EDIT |
60,228,096 | Which is the best option? Use an unupdated component in React or try to implement the library in react without the component? | <p>I have found some components that are not updated with the last React version, however, those components work. But I was wondering if those components are not updated would be the best option or a good practice to try to implement the libraries in React without the npm packages?</p>
<p>Thanks. </p>
| <reactjs><npm> | 2020-02-14 14:17:37 | LQ_CLOSE |
60,228,185 | Waiting until a variables value isset to display it php | <p>I have a variable $infoCollectedAndSold that is being set inside a form (its values are whatever is being checked in the checkbox).
I want to display this variable, once its values are set. Currently the echo is displaying nothing until i submit the form and then the values are displayed from the variable. Is it possible to display the information inside the variable without submitting the form?</p>
<pre><code>//Set variable to the form inputs
$infoCollectedAndSold = "";
if (!empty($_POST['infoCollectedAndSold'])) {
foreach ($_POST['infoCollectedAndSold'] as $value) {
$infoCollectedAndSold .= $value . ', ';
}
}
//Display variable content (Does not display until form is submitted)
<?php
if(isset($infoCollectedAndSold)){
echo '<h3>'.$infoCollectedAndSold.'</h3>';
}
?>
</code></pre>
| <php> | 2020-02-14 14:23:29 | LQ_CLOSE |
60,229,879 | How to calculate exact average using arrays in Java | <p>Regardless of what I try, the program outputs the average as the integer "4" when the average should be "4.78". I have tried changing the integers to doubles, but to no avail. </p>
<p>The rest of the program works as intended, though. It is supposed to print how many times each value in the text files appears by putting an asterisk next to it and it is supposed to indicate when a number is larger than the average by having a ">" appear next to it in the output.</p>
<pre><code>import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String args[]) throws IOException {
int i = 0, count = 0, sum = 0;
Scanner file = new Scanner(new File("input3.txt"));
int[] frequency = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
int[] arr = new int[50];
int current_num;
while (file.hasNext()) {
current_num = file.nextInt();
sum += current_num;
arr[i++] = current_num;
count++;
frequency[current_num]++;
}
int average = sum / count;
for(i=0; i<arr.length; i++){
if(arr[i] > average){
System.out.print(arr[i] + " > " );
}
else{
System.out.print(arr[i] + " ");
}
if(i%5==4){
System.out.println();
}
}
System.out.println("\n***** Frequency Graph *****\n");
for(i=0; i<frequency.length; i++){
System.out.print(i + " = ");
for(int j=0; j<frequency[i]; j++){
System.out.print("*");
}
System.out.println();
}
System.out.println("\nAverage of the numbers in the text file is : " + average);
}
}
</code></pre>
<p>The numbers in the "input3.txt" file are: </p>
<pre><code>5
8
8
1
5
0
6
6
5
3
4
0
6
8
5
4
9
5
8
0
4
7
4
2
0
9
8
3
5
5
5
7
5
7
1
4
4
0
7
4
8
4
2
4
9
8
8
2
3
4
</code></pre>
<p>Any help would be appreciated!</p>
| <java><arrays> | 2020-02-14 16:12:08 | LQ_CLOSE |
60,229,970 | aws cli: ERROR:root:code for hash md5 was not found | <p>When trying to run the AWS CLI, I am getting this error:</p>
<pre><code>aws
ERROR:root:code for hash md5 was not found.
Traceback (most recent call last):
File "/usr/local/Cellar/python@2/2.7.15_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module>
globals()[__func_name] = __get_hash(__func_name)
File "/usr/local/Cellar/python@2/2.7.15_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor
raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type md5
ERROR:root:code for hash sha1 was not found.
Traceback (most recent call last):
File "/usr/local/Cellar/python@2/2.7.15_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module>
globals()[__func_name] = __get_hash(__func_name)
File "/usr/local/Cellar/python@2/2.7.15_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor
raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha1
ERROR:root:code for hash sha224 was not found.
Traceback (most recent call last):
File "/usr/local/Cellar/python@2/2.7.15_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module>
globals()[__func_name] = __get_hash(__func_name)
File "/usr/local/Cellar/python@2/2.7.15_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor
raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha224
ERROR:root:code for hash sha256 was not found.
Traceback (most recent call last):
File "/usr/local/Cellar/python@2/2.7.15_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module>
globals()[__func_name] = __get_hash(__func_name)
File "/usr/local/Cellar/python@2/2.7.15_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor
raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha256
ERROR:root:code for hash sha384 was not found.
Traceback (most recent call last):
File "/usr/local/Cellar/python@2/2.7.15_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module>
globals()[__func_name] = __get_hash(__func_name)
File "/usr/local/Cellar/python@2/2.7.15_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor
raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha384
ERROR:root:code for hash sha512 was not found.
Traceback (most recent call last):
File "/usr/local/Cellar/python@2/2.7.15_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module>
globals()[__func_name] = __get_hash(__func_name)
File "/usr/local/Cellar/python@2/2.7.15_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor
raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha512
Traceback (most recent call last):
File "/usr/local/bin/aws", line 19, in <module>
import awscli.clidriver
File "/usr/local/lib/python2.7/site-packages/awscli/clidriver.py", line 17, in <module>
import botocore.session
File "/usr/local/lib/python2.7/site-packages/botocore/session.py", line 29, in <module>
import botocore.configloader
File "/usr/local/lib/python2.7/site-packages/botocore/configloader.py", line 19, in <module>
from botocore.compat import six
File "/usr/local/lib/python2.7/site-packages/botocore/compat.py", line 25, in <module>
from botocore.exceptions import MD5UnavailableError
File "/usr/local/lib/python2.7/site-packages/botocore/exceptions.py", line 15, in <module>
from botocore.vendored import requests
File "/usr/local/lib/python2.7/site-packages/botocore/vendored/requests/__init__.py", line 58, in <module>
from . import utils
File "/usr/local/lib/python2.7/site-packages/botocore/vendored/requests/utils.py", line 26, in <module>
from .compat import parse_http_list as _parse_list_header
File "/usr/local/lib/python2.7/site-packages/botocore/vendored/requests/compat.py", line 7, in <module>
from .packages import chardet
File "/usr/local/lib/python2.7/site-packages/botocore/vendored/requests/packages/__init__.py", line 3, in <module>
from . import urllib3
File "/usr/local/lib/python2.7/site-packages/botocore/vendored/requests/packages/urllib3/__init__.py", line 10, in <module>
from .connectionpool import (
File "/usr/local/lib/python2.7/site-packages/botocore/vendored/requests/packages/urllib3/connectionpool.py", line 31, in <module>
from .connection import (
File "/usr/local/lib/python2.7/site-packages/botocore/vendored/requests/packages/urllib3/connection.py", line 45, in <module>
from .util.ssl_ import (
File "/usr/local/lib/python2.7/site-packages/botocore/vendored/requests/packages/urllib3/util/__init__.py", line 5, in <module>
from .ssl_ import (
File "/usr/local/lib/python2.7/site-packages/botocore/vendored/requests/packages/urllib3/util/ssl_.py", line 2, in <module>
from hashlib import md5, sha1, sha256
ImportError: cannot import name md5
</code></pre>
<p>I tried the solution from <a href="https://stackoverflow.com/questions/59269208/errorrootcode-for-hash-md5-was-not-found-not-able-to-use-any-hg-mercurial-co">this issue</a> but they do not work:</p>
<pre><code>brew reinstall python@2
==> Reinstalling python@2
Error: An exception occurred within a child process:
FormulaUnavailableError: No available formula with the name "/usr/local/opt/python@2/.brew/python@2.rb"
</code></pre>
<p>I thought it might not be installed, but it already is:</p>
<pre><code>brew install python@2
Warning: python@2 2.7.15_1 is already installed and up-to-date
To reinstall 2.7.15_1, run `brew reinstall python@2`
</code></pre>
<p>Running <code>brew doctor</code> shows that <code>python</code> is unliked, but running <code>brew link python</code> fails because of a symlink belonging to <code>python@2</code>.</p>
<pre><code>brew link python
Linking /usr/local/Cellar/python/3.7.6_1...
Error: Could not symlink Frameworks/Python.framework/Headers
Target /usr/local/Frameworks/Python.framework/Headers
is a symlink belonging to python@2. You can unlink it:
brew unlink python@2
To force the link and overwrite all conflicting files:
brew link --overwrite python
To list all files that would be deleted:
brew link --overwrite --dry-run python
</code></pre>
<p>The commands recommended seem to go in circle and none of them manage to solve the issue. I am a bit stuck - how do I recover from these errors?</p>
| <python><macos><python-2.7><homebrew> | 2020-02-14 16:18:06 | HQ |
60,230,041 | Flutter json Decoding _TypeError (type 'List<dynamic>' is not a subtype of type 'Map<dynamic, dynamic>') | <p>So this error I understand kind of what it is, and WHAT I need to do, but I don't understands HOW to do what I'm trying to do.</p>
<p>So I'm using an html api server-call, which returns a jsonEncoded List of Map objects.</p>
<p>The size of each list CAN (and will) change, so I cannot have a function that just checks and decodes the first few or something. Also each Map object may contain different information, so I can't go making it parse statically. I need to jsonDecode the entire list, and convert it BACK into a list of separate Map objects so I can use the information contained within the Map objects within the rest of my program.</p>
<p>For privacy reasons, I CANNOT provide an example of the type of object I'm receiving, (Or anything similar) and I apologize for the inconvenience, and increased difficulty of attempting to answer the question.</p>
<p>That said, I do know I just need to have a function that checks how many objects are in the list, splits the response.body into that many pieces, decodes each into a Map object, and adds it to a list, or array. </p>
<p>Any information you can provide (Even if not specific code) would help, even if just telling me what commands I should look into. (Preferably with an example of their syntax, but not mandatory of course).</p>
<p>If you need any information that I CAN provide, I'll be happy to do so. Thank you in advance.</p>
| <arrays><json><api><flutter><decode> | 2020-02-14 16:22:01 | LQ_CLOSE |
60,233,495 | Choosing DB pool_size for a Flask-SQLAlchemy app running on Gunicorn | <p>I have a Flask-SQLAlchmey app running in Gunicorn connected to a PostgreSQL database, and I'm having trouble finding out what the <code>pool_size</code> value should be and how many database connections I should expect.</p>
<p>This is my understanding of how things work:</p>
<ul>
<li>Processes in Python 3.7 DON'T share memory</li>
<li>Each Gunicorn worker is it's own process</li>
<li>Therefore, each Gunicorn worker will get it's own copy of the database connection pool and it won't be shared with any other worker</li>
<li>Threads in Python DO share memory</li>
<li>Therefore, any threads within a Gunicorn worker WILL share a database connection pool</li>
</ul>
<p>Is that correct so far? If that is correct, then for a synchronous Flask app running in Gunicorn: </p>
<ul>
<li>Is the maximum number of database connections = (number of workers) * (number of threads per worker)?</li>
<li>And within a worker, will it ever use more connections from a pool than there are workers?</li>
</ul>
<p>Is there a reason why <code>pool_size</code> should be larger than the number of threads? So, for a gunicorn app launched with <code>gunicorn --workers=5 --threads=2 main:app</code> should <code>pool_size</code> be 2? And if I am only using workers, and not using threads, is there any reason to have a <code>pool_size</code> greater than 1?</p>
| <python><database><sqlalchemy><flask-sqlalchemy><gunicorn> | 2020-02-14 21:03:24 | HQ |
60,234,099 | Passing data between a method and an event function | <p>Hello I have been struggling trying to get the event to trigger based on the object that it is passed.... I am not sure if that's how it should be worded but you guys can take a look at the book and give me some insight</p>
<p>I am making a datagrid form, inside this form, there's a function</p>
<pre><code>private void (List<string> listProducts>
{
foreach (aProduct in listProducts)
{
// reset row data
rowProduct = new string[10];
// add the row
this.dataDisplay.Tables["ProductData"].Rows.Add(rowProduct);
double checkingresult;
checkingresult = checkDiameter(aProduct);
}
</code></pre>
<p>Inside this form there's a function that would check the validity of the test product, so checkingresult would return 0 or 1</p>
<p>Then I created an event button to click on to change the color of the cell in the datagrid when it is clicked</p>
<pre><code>
private void bttnChecking_Click(object sender, EventArgs e)
{
DataGridViewCellStyle style = new DataGridViewCellStyle();
style.Font = new Font(datagridProductData.Font, FontStyle.Bold);
style.BackColor = Color.Red;
style.ForeColor = Color.White;
foreach (aProduct in ListProducts)
{
}
for (int i = 0; i < RowCount - 1; i++)
{
Rows[i].Cells[5].Style = style;
}
}
}
</code></pre>
<p>my question is, how do I pass the "checkingresult" into the event to change the color when it returns 0 or 1. Pls halp </p>
| <c#> | 2020-02-14 22:04:15 | LQ_CLOSE |
60,235,508 | How to hide string from C# | <p>I'm trying to hide an important text from being seen I have already tried the SecureString stuff but I failed, I don't know If I am doing it wrong but some help would be appreciated or a source code that i could learn from since i am new to c#<a href="https://i.stack.imgur.com/5eUHe.png" rel="nofollow noreferrer">Screenshot 1</a> <a href="https://i.stack.imgur.com/BpSmA.png" rel="nofollow noreferrer">Screenshot 2</a></p>
<p>Thanks in advance.</p>
| <c#> | 2020-02-15 02:24:28 | LQ_CLOSE |
60,235,569 | How to un-obfuscate JavaScript starting with const and a bunch of vars | <p>Hi i found this extension and would like to see the contents of the script itself to check what is actually does. I tried putting the script through all sort of javascript de/un-obfuscators and none worked.</p>
<p>Please tell me one that works or send me the de-obfuscated JS.</p>
<p><strong><a href="https://skidlamer.github.io/js/skid.js" rel="nofollow noreferrer">CODE HERE</a></strong></p>
| <javascript><web><deobfuscation> | 2020-02-15 02:40:00 | LQ_CLOSE |
60,235,614 | What is the Time Complexity of my algorithim? | This algorithm was written for LeetCode's climbing stairs problem and it ran at 20ms. I believe the time complexity is O(n), because this link https://towardsdatascience.com/understanding-time-complexity-with-python-examples-2bda6e8158a7 said O(n) is when the running time increases linearly as the size of the input gets bigger, which is what I think is going on here. I was wondering if someone could explain to me the the time complexity here and why it would be that. Any additional info on how I could get it to linear time if I'm not there already would help too.
Here is my code:
```
class Solution:
def climbStairs(self, n: int) -> int:
#n is the step I need to reach
cells = n
if cells == 0: return 1
else:
result = []
for i in range(0, 1*cells + 1):
result.append(i)
if result[i] == 0:
result[i] = 1
else:
if result[i] > 1:
result[i] = result[i-1] + result[i-2]
return result[-1]
``` | <python><python-3.x><time-complexity> | 2020-02-15 02:51:16 | LQ_EDIT |
60,235,631 | JPG to PNG converter code not working. Please help me with my code | I have used the below code to [![enter image description here][1]][1]convert JPG into PNG file:
But when i am running this code from the command line terminal using: python a.py "C:\Users\nishant.gupta2\PycharmProjects\jpgtopngconverter\photo" new
The system is giving me the error: PermissionError: [Errno 13] Permission denied: 'C:\\Users\\nishant.gupta2\\PycharmProjects\\jpgtopngconverter\\photo'
please help
My code is below:
import sys
import os
from PIL import Image
image_folder=sys.argv[1]
output_folder=sys.argv[2]
if not os.path.exists(output_folder):
os.mkdir(output_folder)
for items in os.listdir(image_folder):
im= Image.open(f'{image_folder}')
im.save(f'{output_folder}.png','png')
[1]: https://i.stack.imgur.com/CFpUL.png | <python><python-3.x><python-imaging-library><sys> | 2020-02-15 02:55:57 | LQ_EDIT |
60,236,709 | How to change the values of cv2.boundingRect | <p>is there a way to change the values of cv2.boundingRect </p>
<p><a href="https://i.stack.imgur.com/RDv2J.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RDv2J.jpg" alt="enter image description here"></a></p>
<p>I want to adjust so I can get the accurate cv2.drawContours
<a href="https://i.stack.imgur.com/jzlTx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jzlTx.png" alt="enter image description here"></a></p>
<pre><code>import cv2
# Load image, grayscale, Gaussian blur, Otsu's threshold
image = cv2.imread("5.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5,5), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
# Find bounding box
x,y,w,h = cv2.boundingRect(thresh)
cv2.rectangle(image, (x, y), (x + w, y + h), (36,255,12), 2)
cv2.putText(image, "w={},h={}".format(w,h), (x,y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (36,255,12), 2)
cv2.imshow("thresh", thresh)
cv2.imshow("image", image)
cv2.waitKey()
</code></pre>
| <python><opencv> | 2020-02-15 07:19:32 | LQ_CLOSE |
60,237,477 | Python: Unexpected behaviour with dict and a colon. ( my_dict['key']: None ) what does the colon ( : ) do? | <p>I have encountered some <em>unexpected</em> behavior with dicts in python.<br>
It might be because of annotations, but i'm not sure.<br>
Please see the snippet below: </p>
<pre><code>>>> d = {} # lets create a dictionary and add something to it.
>>> d['a'] = 'a'
>>> d
{'a': 'a'}
>>> d['a']
'a'
>>> # ok all well and good, we know how dicts work, right ?
...
>>> d['z']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'z'
>>>
>>> # yea no key 'z' was inserted. Lets add a colon (:) in the mix
...
>>> d['z']: d
>>>
>>> # nothing happend! weird...
...
>>> d['z']: d['z']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'z'
>>> # again 'z' was not added to the dict, but what did the colon ???
...
>>> d['z']: d['z']: None
File "<stdin>", line 1
d['z']: d['z']: None
^
SyntaxError: invalid syntax
>>>
>>> # NOW the colon gives an SyntaxError !?!
>>> # Lets try to directly use a colon after the dict
...
>>> {'a': 'a'}: ()
File "<stdin>", line 1
SyntaxError: illegal target for annotation
>>>
>>> # so annotation huh ?
>>> # is it possible to annotate on the fly ?
...
>>> def func(x): return x
...
>>> d = {'f': func} # overwrite previous dict
>>> d['f']: callable
>>> d['f'].__annotations__
{}
>>> # doesn't look like it was taken over
... # lets check if d['f'] returns the callable function: func
...
>>>
>>> def func(x: str) -> callable: return x
...
>>> d = {'f': func}
>>> d['f'].__annotations__ # lets check for annotations !!
{'x': <class 'str'>, 'return': <built-in function callable>}
>>>
>>> # I'm confused, what does the colon do?
...
>>>
</code></pre>
<p>I'm curious why the dict syntax doesn't always react on the given colon (:).<br>
Also the annotations doesn't seem to be the case (or my conclusion is wrong)</p>
<p>So dear readers, what is the purpose of the colon used in the context described above?</p>
| <python><python-3.x><dictionary><syntax><colon> | 2020-02-15 09:33:18 | LQ_CLOSE |
60,237,488 | Python - Replace only exact word in string | <p>I want to replace only specific word in one string. However, some other words have that word inside but I don't want them to be changed.</p>
<p>For example, for the below string I only want to replace <code>x</code> with <code>y</code> in <code>z</code> string. how to do that?</p>
<pre><code>x = "the"
y = "a"
z = "This is the thermometer"
</code></pre>
| <python><regex> | 2020-02-15 09:34:32 | LQ_CLOSE |
60,237,808 | 1. Why do we need to override the method public boolean equals(Object ob) in any class? | <ol>
<li><p>Why do we need to override the method public boolean equals(Object ob) in any class?</p></li>
<li><p>Is public boolean equals(Object ob) is same as public boolean equals(Circle ob)?</p></li>
</ol>
| <java> | 2020-02-15 10:20:34 | LQ_CLOSE |
60,239,053 | Finding sum of geometric sequence with modulo 10^9+7 | The problem is given as:
Output the answer of (A^1+A^2+A^3+...+A^K) modulo 1,000,000,007, where 1≤ A, K ≤ 10^9, and A and K must be an integer.
I am trying to write a program to compute the above question. I have tried using the formula for geometric sequence, then applying the modulo on the answer. Since the results must be an integer as well, finding modulo inverse is not required. | <algorithm><math><pascal> | 2020-02-15 13:07:32 | LQ_EDIT |
60,240,644 | How can i count only 'Yes' entities in my column of a dataframe? | [In Input[96] I tried many things but couldnot do anything, always getting both 'yes, and 'no values'][1]
[1]: https://i.stack.imgur.com/svTFy.png | <python><dataframe><matplotlib><count><data-visualization> | 2020-02-15 16:20:15 | LQ_EDIT |
60,240,925 | How to find the variance between two groups in python pandas? | <p>I have a dataframe like this,</p>
<pre><code>ID total_sec is_weekday
1 300 1
1 200 0
2 280 1
2 260 0
3 190 1
4 290 0
5 500 1
5 520 0
</code></pre>
<p>I want to find the ID with the largest variance between weekdays and weekends. If we missed the records for either weekdays or weekends, we calculate the variance as 0.
My expected output will be,</p>
<pre><code>ID variance
1 100
2 20
3 0
4 0
5 20
</code></pre>
| <python><pandas><numpy><dataframe> | 2020-02-15 16:48:59 | LQ_CLOSE |
60,241,484 | Finding the limit of a sequence in python, jupyter notebook | <p>I’ve got a sequence a(n)=(5-77sin(n)+8n^2)/(1-4n^2) and I’m trying to find a candidate for the limit of this sequence. How do I do this? I’ve tried using a code below but that didn’t work so any ideas?<a href="https://i.stack.imgur.com/zUd3V.jpg" rel="nofollow noreferrer">enter image description here</a></p>
| <python><jupyter-notebook><sequence><limit> | 2020-02-15 17:50:18 | LQ_CLOSE |
60,241,757 | Change array elements to objects with key, value | <p>Can anyone tell me how to change this array in javaScript to the following one with objects having the same key 'name' ?</p>
<pre><code>const myArray = ['mark', 'david', 'monica'];
</code></pre>
<p>Desired Output:</p>
<pre><code>const myArray = [{name: 'mark'}, {name: 'david'}, {name: 'monica'}];
</code></pre>
| <javascript><arrays><object><key-value> | 2020-02-15 18:19:38 | LQ_CLOSE |
60,241,994 | Passing an *os.File as an *io.Reader | <p>If there's a function that takes a *io.Reader, how would one pass an *io.File? This doesn't work:</p>
<pre><code>func somefunc(r *io.Reader){
}
func Test_FileReader(t *testing.T){
f, err := os.Open("xyz")
assert.NoError(t, err)
somefunc(&f)
}
</code></pre>
<p>It gives this error:</p>
<blockquote>
<p>Cannot use '&f' (type **File) as type *io.Reader</p>
</blockquote>
<p>Then, changing <code>*io.Reader</code>-><code>io.Reader</code> and <code>&f</code>-><code>f</code>, it compiles just fine:</p>
<pre><code>func somefunc(r io.Reader){
}
func Test_FileReader(t *testing.T){
f, err := os.Open("xyz")
assert.NoError(t, err)
somefunc(f)
}
</code></pre>
<p>Is it even possible to pass an *os.File as an *io.Reader??</p>
| <pointers><go> | 2020-02-15 18:44:33 | LQ_CLOSE |
60,242,562 | Division with if condition | <p>I just start learning ruby with an online course and in my very first exercise, I can't complete the challenge. I have to create functions to sum, subtract, multiply and divide that meet the specs conditions.</p>
<p>For the division, I need to check if it will divide per 0 or not, give the result or a warning. My code is </p>
<pre><code>def divisao(primeiro_numero, segundo_numero)
if segundo_numero > 0
primeiro_numero / segundo_numero
else
puts 'Opa! Zero como divisor'
end
</code></pre>
<p>But when I run the specs, I get the following warning</p>
<pre><code>0 examples, 0 failures, 1 error occurred outside of examples
</code></pre>
<p>I have changed all the functions, but this one doesn't seem to work.
I added the complete functions and specs file here:<a href="https://gist.github.com/isafloriano/86c170400b2f5fc63dc5e8edd8913525" rel="nofollow noreferrer">https://gist.github.com/isafloriano/86c170400b2f5fc63dc5e8edd8913525</a></p>
<p>Can anyone give me a clue why this doesn't work?</p>
| <ruby> | 2020-02-15 19:54:42 | LQ_CLOSE |
60,243,111 | Re-run the current function when the function is a variable | <p>I have a function named <code>test</code> which is inside the main func.</p>
<pre><code>//stuff
func main() {
var test = func() {
if (/*some condition from main*/) {
return test()
}
}
val := test()
}
</code></pre>
<p>When i run this it says:</p>
<blockquote>
<p>undefined: test</p>
</blockquote>
<p>and it is referencing the <code>return test()</code> inside the test func.
How can i fix this?</p>
| <function><go> | 2020-02-15 21:02:57 | LQ_CLOSE |
60,243,537 | how to updaload image twice with diffrent sizes | <p>hello i have project i work on , it have some issues ,</p>
<p>the problem here i need to get file twice once to move it and one with resizing </p>
<p>this is my code , what should i do here</p>
<pre><code> public function update_image(Request $request)
{
$ad = Ad::where('id',$request->ad_id)->first();
$photos= explode('||',$ad->photos);
$thumbnails= explode('||',$ad->thumbnails);
$number = count($photos);
$length = strlen($photos[$number-1]);
$last_image_number = $photos[$number-1][$length - 5];
// dd($photos[$number-1][$length - 5]);
$last_image_number++;
$image = $request->file('image');
$image_name = 'preview_'.$last_image_number.'.'.$image->getClientOriginalExtension();
$previews_path = public_path().'/uploads/images/'.$ad->ad_id.'/previews/';
$thumbs_path = public_path().'/uploads/images/'.$ad->ad_id.'/thumbnails/';
// $im = Image::make($image->getFullPath());
chmod($previews_path,0777);
$image->move($previews_path,$image_name);
$photos[]= '/'.$ad->ad_id.'/previews/'.$image_name;
$ad->photos = implode('||',$photos);
$photo_path = basename($previews_path . $image_name);
$ad->save();
list($width, $heigh) = getimagesize($previews_path.$photo_path);
$photo_path->move($thumbs_path,'ddd.jpg');
dd($photo_path);
// dd($width);
$ratio = $width/ $heigh;
$target_width = $width / $ratio;
$target_height = $target_width / $ratio;
$photo_path->resize($target_width,$target_height);
$thumb_name= 'thumbnail_'.$last_image_number.'.'.$image->getClientOriginalExtension();
$image->move($thumbs_path , $thumb_name);
$thumbnails [] = '/'.$ad->ad_id.'/thumbnails/'.$thumb_name;
$ad->thumbnails = implode('||',$thumbnails);
$ad->save();
// dd($image_name);
return response()->json(['success'=>true]);
</code></pre>
| <php><laravel> | 2020-02-15 22:03:54 | LQ_CLOSE |
60,244,718 | Couldn't understand this SWIFT Fucntion | <p>Hope you are doing well. Would anyone please explain this code to me? I am still not getting how we got 120 here. When the parameters were passed to the function, where was it saved? How did it determine max and min before calculating? </p>
<p>Would be really appreciated if anyone could explain it for me please..</p>
<p><a href="https://i.stack.imgur.com/eGNB1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eGNB1.png" alt="Function"></a></p>
| <swift><function> | 2020-02-16 01:39:39 | LQ_CLOSE |
60,244,907 | How to assign a variable to the output of a return statement in Python | <p>I have a function with a return statement that returns a list. I would like to store this list in a variable so I can use it in another following function. How would i do this?</p>
| <python> | 2020-02-16 02:30:16 | LQ_CLOSE |
60,245,493 | how Fix this Error Operand type clash: date is incompatible with int | INSERT INTO Buy SELECT Title,Type1,Tedat,DATEADD(DAY,-2,DATEADD(YEAR,-1,Tarikh)),Descrip FROM Buy
WHERE(Tarikh BETWEEN 2019-03-21 AND 2020-03-19 ) | <c#><sql><sql-server><visual-studio> | 2020-02-16 04:44:48 | LQ_EDIT |
60,248,137 | I have a problem when I install angular on terminal macOs | <p>I would like to install angular but when I type the command these error messages appear. Could someone help me? Thank you in advance. <a href="https://i.stack.imgur.com/RDxRm.png" rel="nofollow noreferrer">enter image description here</a></p>
| <angular><macos><npm><terminal> | 2020-02-16 11:48:27 | LQ_CLOSE |
60,248,151 | Is there any other purpose of "dictionary.get" function in Python with two elements in it, apart from checking for a variable in the list? | <p>I thougt it could store the answer for the case when user inputs a wrong key in it, like this:</p>
<pre><code>month_conversion.get("Git", "Not a valid key")
month_conversion = input()
</code></pre>
<p>So, if user input "Git" it would print out "Not a valid key"
But it doesn't store it and just prints out "None"</p>
| <python><dictionary> | 2020-02-16 11:50:33 | LQ_CLOSE |
60,248,689 | Is there a way to log in to discord using a python script? | <p>My goal is to be able to loging to Discord using a script and then be able to send messages to channels. I need it to communicate with a music bot automatically but if I write a bot for discord other bot's will ignore it so thats not an option. Does anyone know how to do it?</p>
<p>Thanks!</p>
| <python><discord><discord.js><discord.py-rewrite> | 2020-02-16 12:59:05 | LQ_CLOSE |
60,250,569 | i keep geting eror "Uncaught SyntaxError: Unexpected token ';' " in javascript switch statement | <p>i have tried to <em>delete</em> ';' and retype <strong>case</strong> command but nothing happen and still just getting uncaught error. iam get this from tutorial please help iam so new for programming :)
can somebody tell me why the eror still poppin??
heres the code</p>
<pre><code>//SWITCH STATEMMENT
var job = 'teacher';
switch (job) {
case 'teacher';
case 'instructor';
console.log(firstName + ' teachs kids how to code.');
break;
case 'driver';
console.log(firstName + ' drives an uber in Bekasi.');
break;
case 'designer';
console.log(firstName + ' design beautiiful website.');
break;
default;
console.log(firstName + ' does something else');
}
</code></pre>
<p><a href="https://i.stack.imgur.com/SDkNd.png" rel="nofollow noreferrer">this is the code and the error on the console</a></p>
| <javascript> | 2020-02-16 16:23:34 | LQ_CLOSE |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.