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 |
|---|---|---|---|---|---|
55,054,567 | How to get back fo first element in list after reaching the end? | <p>For instance: </p>
<p>If I am iterating through a Python list ['a','b','c'] how do I get back to element 'a' once I have reached 'c'?</p>
| <python><python-3.x> | 2019-03-07 23:40:37 | LQ_CLOSE |
55,055,521 | CSS line inside a container | <p>Imagine having a box</p>
<pre><code>a b
----------
| |
| |
c----------d
</code></pre>
<p>The box have point a,b,c and d. I need to have a line from point b to point c, and I will have my data lets say <code>100%</code> in point a and point d.</p>
<p>is this possible? I tried to look using <code>fr</code> but I still have the problem of drawing a line</p>
| <html><css> | 2019-03-08 01:39:38 | LQ_CLOSE |
55,058,754 | C# - Launch Task periodically | I want to launch a method in a separated thread periodically (every minute). I was using `System.Timers.Timer` but I realize that Timers cause memory leaks.
I need to remove Timers and use task. The first idea is launch a Task in the following way:
_taskWork = Task.Factory.StartNew( DoWork );
And in the DoWork method:
private void DoWork()
{
While(true)
{
// Stuff here
Thread.Sleep(60000);
}
}
Is there any way to launch a task avoiding this approach?
Thanks | <c#><.net><multithreading> | 2019-03-08 07:42:25 | LQ_EDIT |
55,059,258 | Bootsrap Custom nav bar shapes | I want make a custom nav bar shapes like below attached images.
[Design image][1]
I have use below css for this shape.
```
.navbar-nav.nav-bar-custom{
transform: skew(-21deg);
border: 1px solid black;
}
```
But when use this. all my text looks like italic shape. see attached image.
[After add above css][2]
Any one can help me to resolve this issue?
[1]: https://i.stack.imgur.com/G7iIV.png
[2]: https://i.stack.imgur.com/yC7sY.png | <css><html><bootstrap-4> | 2019-03-08 08:24:36 | LQ_EDIT |
55,059,307 | Time count - from frontend to backend | <p>I'm thinking to make a simple timer, so when the timer is clicked, the time starts to count and then I can stop it and the time passed will be saved into the DB.</p>
<p>But there's some tricks to it, as I figured out:</p>
<p>1) When the tab(of the current timer) is switched to another, the time count isn't trusty, due the low priority on the inactive tabs.</p>
<p>2) How can I varify the time passed with PHP in backend? (I've thought of making AJAX call every XX seconds to varify it with backend, but how can I make counter like this in my backend with PHP? Is this even possible using PHP?</p>
<p>P.S. I don't mind to drop legacy browsers, but I want to support all the modern ones(except the Edge :) )</p>
| <javascript><php><jquery> | 2019-03-08 08:27:40 | LQ_CLOSE |
55,061,028 | When I want to access sms this error appear please help me | I tried to retrive sms and then added to the firebase realtime database and change the balance of specific account but this error is appear when I want to change the balance :
> E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.nouraalqahtani.debrah2, PID: 4500
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.trim()' on a null object reference
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1838)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.lang.Double.parseDouble(Double.java:539)
at com.example.nouraalqahtani.debrah2.accesssms$3.onDataChange(accesssms.java:304)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database@@16.0.6:75)
at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database@@16.0.6:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@16.0.6:55)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
and this accesssms class
package com.example.nouraalqahtani.debrah2;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
public class accesssms extends AppCompatActivity {
private static accesssms inst;
ArrayList<String> smsMessagesList = new ArrayList<String>();
ListView smsListView;
ArrayAdapter arrayAdapter;
DatabaseReference myRef;
String day;
String updatebalance;
String accounting;
String accountnumber;
String smsbody;
int count;
int childrencount;
double balance;
double amount;
int childrencountinflow;
String type;
String bank;
String amountstr;
public static accesssms instance() {
return inst;
}
@Override
public void onStart() {
super.onStart();
inst = this;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_accesssms);
myRef=
FirebaseDatabase.getInstance().getReference("user_account").child(" .
(username)").child("bank_accounts");
day = new SimpleDateFormat("yyyy-MM-dd",
Locale.getDefault()).format(new Date());
smsListView = (ListView) findViewById(R.id.SMSList);
arrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, smsMessagesList);
smsListView.setAdapter(arrayAdapter);
// Add SMS Read Permision At Runtime
// Todo : If Permission Is Not GRANTED
if(ContextCompat.checkSelfPermission(getBaseContext(),"android.permission.READ_SMS") ==PackageManager.PERMISSION_GRANTED) {
// Todo : If Permission Granted Then Show SMS
refreshSmsInbox();
} else {
// Todo : Then Set Permission
final int REQUEST_CODE_ASK_PERMISSIONS = 123;
ActivityCompat.requestPermissions(accesssms.this, new String[]
{"android.permission.READ_SMS"}, REQUEST_CODE_ASK_PERMISSIONS);
}
}
public void refreshSmsInbox() {
ContentResolver contentResolver = getContentResolver();
Cursor smsInboxCursor = contentResolver.query(Uri.parse("content://sms/inbox"), null, null, null, null);
int indexBody = smsInboxCursor.getColumnIndex("body");
int indexAddress = smsInboxCursor.getColumnIndex("address");
if (indexBody < 0 || !smsInboxCursor.moveToFirst()) return;
arrayAdapter.clear();
do {
String str = "SMS From: " + smsInboxCursor.getString(indexAddress) +
"\n" + smsInboxCursor.getString(indexBody) + "\n";
arrayAdapter.add(str);
//if it samba bank
if (smsInboxCursor.getString(indexAddress).equals(".Samba")) {
smsbody = smsInboxCursor.getString(indexBody);
int ende = smsbody.indexOf(' ');
final String transaction = smsbody.substring(0, ende);
//to check if it outflow or inflow
//if it outflow
if (transaction.equals("دفع")) {
type = "outflow";
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
//Take last three number card number
int accountnumberstart = smsbody.lastIndexOf(".");
count = accountnumberstart +5;
accountnumber = smsbody.substring(accountnumberstart+2 , count);
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String dataaccountOUT = ds.child("account_no").getValue(String.class);
if (Integer.parseInt(accountnumber)==Integer.parseInt(dataaccountOUT)) {
childrencount=(int)ds.child("outflow").getChildrenCount();
bank=ds.getKey();
addoutflow();
} } }
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}}); }
else if (transaction.equals("تم")) {
type = "inflow";
//take account number
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
//Take the last four numbers of account number
int accountnumberstart = smsbody.indexOf("حساب");
count = accountnumberstart+15 ;
accountnumber = smsbody.substring(accountnumberstart +11, count);
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String dataaccount = ds.child("fourfirstdigit").getValue(String.class);
if (Integer.parseInt(accountnumber)==Integer.parseInt(dataaccount)){
childrencountinflow=(int)ds.child("inflow").getChildrenCount();
bank=ds.getKey();
addinflow();
}
}}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
}} while (smsInboxCursor.moveToNext());
blanacechange();
}
public void updateList(final String smsMessage) {
arrayAdapter.insert(smsMessage, 0);
arrayAdapter.notifyDataSetChanged();
}
public void toastMessage(String message){
Toast.makeText(this,message,Toast.LENGTH_SHORT).show();
}
public void addoutflow(){
// counter=counter+1;
// String co=Integer.toString(counter);
int accounttotalstart = smsbody.lastIndexOf("بقيمة");
int accounttotalend = smsbody.lastIndexOf("ريال");
accounting = smsbody.substring(accounttotalstart + 6, accounttotalend);
amountstr=arabicToenglish(accounting);
myRef.child(bank).child("outflow").child("6").child("amount").setValue(amountstr);
//change the balance
//take vendor name
int vendorstart = smsbody.lastIndexOf("*", count + 1);
int vendorend = smsbody.lastIndexOf(",");
String vendor = smsbody.substring(vendorstart + 3, vendorend);
//add vendor name to database
myRef.child(bank).child("outflow").child("6").child("vendor").setValue(vendor);
//add current time
int timstart = smsbody.lastIndexOf(",");
int timend = smsbody.lastIndexOf("/");
String date = smsbody.substring(timstart + 1, timend + 4);
myRef.child(bank).child("outflow").child("6").child("date").setValue(arabicToenglish(date));
int ti = smsbody.lastIndexOf(" ");
String time = smsbody.substring(timend + 4, ti);
// myRef.child(bank).child("outflow").child("6").child("time").setValue(arabicToenglish(time));
//to check if it AM OR PM
String AMorPM = smsbody.substring(ti + 1);
if (AMorPM.equals("صباحاً")) {
myRef.child(bank).child("outflow").child("6").child("time").setValue(arabicToenglish(time) + " AM");
} else
myRef.child(bank).child("outflow").child("6").child("time").setValue(arabicToenglish(time) + " PM");
}
public void addinflow(){
int accounttotalstart = smsbody.lastIndexOf("مبلغ");
int accounttotalend = smsbody.indexOf(" ");
accounting = smsbody.substring(accounttotalstart + 4, accounttotalend);
amountstr=arabicToenglish(accounting);
myRef.child(bank).child("inflow").child("2").child("amount")
.setValue(amountstr);
//change the balance
int timstart = smsbody.lastIndexOf("في");
int timend = smsbody.lastIndexOf("-");
String date = smsbody.substring(timstart + 2, timend + 5);
myRef.child(bank).child("inflow").child("2").child("date").setValue(arabicToenglish(date));
int ti = smsbody.lastIndexOf(" ");
String time = smsbody.substring(timend + 4, ti);
myRef.child(bank).child("inflow").child("2").child("time").setValue(arabicToenglish(time));
//to check if it AM OR PM
String AMorPM = smsbody.substring(ti + 1);
if (AMorPM.equals("صباحاً")) {
myRef.child(bank).child("inflow").child("2").child("time").setValue(time + " AM");
} else
myRef.child(bank).child("inflow").child("2").child("time").setValue(time + " PM");
}
private static String arabicToenglish(String number)
{
char[] chars = new char[number.length()];
for(int i=0;i<number.length();i++) {
char ch = number.charAt(i);
if (ch >= 0x0660 && ch <= 0x0669)
ch -= 0x0660 - '0';
else if (ch >= 0x06f0 && ch <= 0x06F9)
ch -= 0x06f0 - '0';
chars[i] = ch;
}
return new String(chars);
}
public void blanacechange() {
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
String databa = dataSnapshot.child(bank).child("balance").getValue(String.class);
String am = dataSnapshot.child(bank).child("6").child("amount").getValue(String.class);
balance=Double.parseDouble(databa);
amount=Double.parseDouble(am);
if (type.equals("outflow")){
balance = balance - amount;
myRef.child(bank).child("balance").setValue(Double.toString(balance));}
if (type.equals("inflow")){
balance=balance+amount;
myRef.child(bank).child("balance").setValue(Double.toString(balance));
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
}
And this my database
[enter image description here][1]
[1]: https://i.stack.imgur.com/Gu7lL.png | <android><firebase-realtime-database><sms> | 2019-03-08 10:15:34 | LQ_EDIT |
55,061,524 | Parse error: syntax error, unexpected 'if' (T_IF) in D:\Xampp\htdocs\profile\new\view.php on line 29 | <p>I am getting parse error unexpected IF (T_IF). please help me correcting my code
i have session_start() before tag and using session username for selecting row from database. please help me my code is not working properly</p>
<p><strong>PHP CODE</strong></p>
<pre><code><?php
// connect to the database
include('connect-db.php');
$username = $_SESSION['username']
// get the records from the database
if ($result = $mysqli->query("SELECT * FROM user WHERE username = '$username'"))
{
// display records if there are records to display
if ($result->num_rows > 0)
{
// display records in a table
echo "<table border='1' cellpadding='10'>";
// set table headers
echo "<tr><th>ID</th><th>First Name</th><th>Last Name</th><th></th><th></th></tr>";
while ($row = $result->fetch_object())
{
// set up a row for each record
echo "<tr>";
echo "<td>" . $row->id . "</td>";
echo "<td>" . $row->firstname . "</td>";
echo "<td>" . $row->lastname . "</td>";
echo "<td><a href='records.php?id=" . $row->id . "'>Edit</a></td>";
echo "<td><a href='delete.php?id=" . $row->id . "'>Delete</a></td>";
echo "</tr>";
}
echo "</table>";
}
// if there are no records in the database, display an alert message
else
{
echo "No results to display!";
}
}
// show an error if there is an issue with the database query
else
{
echo "Error: " . $mysqli->error;
}
// close database connection
$mysqli->close();
?>
</code></pre>
| <php><mysql> | 2019-03-08 10:45:04 | LQ_CLOSE |
55,063,328 | I wanna rander a browser on the AR rendering object. Can three.js makes it? | <p>There is a AR object and I want to Put a browser on it , so users can See that browser on the AR object. Can three.js makes it?</p>
| <three.js> | 2019-03-08 12:32:23 | LQ_CLOSE |
55,065,072 | How to share a very specific android application | I’m currently working on an android application.
I’m developing this application for a small company of cleaning, they need the application to coordinates in a better way the work.
I was wondering which one is the best way to let the final user install the application, like for example:
-Publish it on the play store
-Send to each user the .apk
Also keep in mind that the app will be updated in the future so must be easy to apply the updates.
In the end I’d like to know which kind of approach can suit my situation and which one is the best way to proceed, thanks to everyone. | <android> | 2019-03-08 14:17:31 | LQ_EDIT |
55,066,386 | Golang to iterate over N files concurrently inorder to count occurence of unique word | This is my code written in Golang to count the occurrence of all the unique word in a file:
`package main
import (
"bufio"
"fmt"
"log"
"os"
)
func main(){
file, err := os.Open("file1.txt")
if err != nil {
log.Fatal(err)
}
words := make(map[string]int)
/*asking scanner to split into words*/
scanner := bufio.NewScanner(file)
scanner.Split(bufio.ScanWords)
count := 0
//scan the inpurt
for scanner.Scan() {
//get input token - in our case a word and update it's frequence
words[scanner.Text()]++
count++
}
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "reading input:", err)
}
for k, v := range words {
fmt.Printf("%s:%d\n", k, v)
}
}
`
**I have to iterate this map over N files concurrently in order to calculate the occurrence of all the unique words...(PS: NOOB at Golang and this is my first program)** | <go><file-handling> | 2019-03-08 15:33:25 | LQ_EDIT |
55,069,495 | i am getting very good output in training set and very bad output in test set | <p>i am training a model using keras with 4500 image belong to a seven classes, i build a neural network with one input layer and one hidden layer and one output layer then when a training started i am getting high accuracy and low loss in the training test but in the validation test the val_loss is increasing with high percentage from the beginning, and val_acc is increasing slowly.
i am using softmax activation function and catgorical_crossintroby for the loss
can you help me to find the problem please?</p>
| <python><keras> | 2019-03-08 19:07:49 | LQ_CLOSE |
55,069,648 | How an IoT sensor based device communicates with the cloud? | <p>So, how does an IoT sensor based device communicates with the cloud?
Does it uses Google Cloud Internet of Things or WSO2 or something similar and where is this API running from?</p>
<p>Thanks in advance</p>
| <cloud><device><iot><communication> | 2019-03-08 19:19:17 | LQ_CLOSE |
55,071,283 | How to install Cargo on a Linux server? | I tried installing cargo on RHEL server with:
curl https://sh.rustup.rs -sSf | sh
but after finishing - got response:
cargo
-bash: cargo: command not found
Is there a different way to install?
| <linux><rust><centos><rhel><rust-cargo> | 2019-03-08 21:31:20 | LQ_EDIT |
55,072,505 | How do i make it so that a drop-down menu only shows at half or quarter window size | Like on <a href="https://uk.ign.com/">IGN</a> i would like to make it so that within my E-Magazine i can change the top tabs from the line layout, to a drop down menu, like IGN does when the website window is made too small. Any help you can give would make me extremely helpful as i am new to web development and coding. | <javascript><php><html> | 2019-03-08 23:41:15 | LQ_EDIT |
55,075,843 | C# Windows Mouse Control | <p>I am coding an application for a school project that said "Make something you are proud of without any prior knowledge or experience", and have encountered a situation where my lack of information counts as a roadblock.</p>
<p>I do not know and could not find any useful information on how the windows mouse wheel works, and how to include it in my program.</p>
<p>To simplify the issue: I need to control the mouse with code, the buttons work well, but I do not have a clue on how the mouse wheel works, and how I should implement it's movement.</p>
<p>The method I use for mouse events:</p>
<pre><code>[DllImport("user32.dll")]
private static extern void mouse_event(int dwFlags, int dx, int dy, int dwData, int dwExtraInfo);
</code></pre>
<p>If anyone could explain how the mouse wheel works in general, or how I should use the method to control it I would be very thankful.</p>
| <c#><.net><windows><mouse><theory> | 2019-03-09 09:24:39 | LQ_CLOSE |
55,075,980 | Push Notification of update in Article in android | I have Converted Article Website to Android App using WebView. Now I want to use push notification for any update of Article in Android. Kindly help me out in an stuck on it.
Waiting for Answers. | <android><push-notification> | 2019-03-09 09:42:39 | LQ_EDIT |
55,076,036 | question on Linked List implementation concept and how it is traverse from node to node | I just started to learn the concept of Linked List recently, and having some problem on how is the else statement work in the below code? How it is traverse to next node until it found a null value in Node.next? please see the code below:
public class LinkedList {
Node head;
public void insert(int data) {
Node node = new Node(data);
node.data = data;
if(head == null) {
head = node;
}else{
Node temp = head;
while(temp.next != null) {
temp = temp.next;
}
temp.next = node;
}
}
} | <java><linked-list> | 2019-03-09 09:49:07 | LQ_EDIT |
55,076,092 | How to convert w/ or w/o decimal numbers to words // Python | <p>What I am going to add/improve to this code? Can it be done without importing num2words or inflect module? I've tried to mix some code with this code but none of them are working.</p>
<p>This is my improved code from <a href="https://codereview.stackexchange.com/questions/173971/converting-number-to-words">this original code.</a> Thank you in advance!</p>
<pre><code>one = ['', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine']
tenp = ['Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen']
tenp2 = ['', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety']
def once(num):
word = one[int(num)]
word = word.strip()
return word
def ten(num):
if num[0] == '1':
word = tenp[int(num[1])]
else:
text = once(num[1])
word = tenp2[int(num[0])]
word = word + " " + text
word = word.strip()
return word
def hundred(num):
word = ''
text = ten(num[1:])
word = one[int(num[0])]
if num[0] != '0':
word = word + " Hundred "
word = word + text
word = word.strip()
return word
def thousand(num):
word = ''
pref = ''
text = ''
length = len(num)
if length == 6:
text = hundred(num[3:])
pref = hundred(num[:3])
if length == 5:
text = hundred(num[2:])
pref = ten(num[:2])
if length == 4:
text = hundred(num[1:])
word = one[int(num[0])]
if num[0] != '0' or num[1] != '0' or num[2] != '0':
word = word + " Thousand "
word = word + text
if length == 6 or length == 5:
word = pref + word
word = word.strip()
return word
test = int(input("Enter number(0-999,999):"))
a = str(test)
leng = len(a)
if leng == 1:
if a == '0':
num = 'Zero'
else:
num = once(a)
if leng == 2:
num = ten(a)
if leng == 3:
num = hundred(a)
if leng > 3 and leng < 7:
num = thousand(a)
print(num)
</code></pre>
<p>This is the output of this code</p>
<pre><code>Enter number(0-999,999):123456
One Hundred Twenty Three Thousand Four Hundred Fifty Six
</code></pre>
<p>And I want it to be like this</p>
<pre><code>Enter number(0-999,999):123456.25
One Hundred Twenty Three Thousand Four Hundred Fifty Six and 25/100
</code></pre>
| <python><python-3.x><numbers><word> | 2019-03-09 09:56:02 | LQ_CLOSE |
55,076,163 | Is it necessary to use Class in Python every time You write a complex Program | <p>I have a like 50 lines code of python program converted into exe using pyinstaller</p>
<p>So is it necessary for me to use class in my python program ? because it works perfectly fine without class</p>
| <python><python-3.x> | 2019-03-09 10:03:35 | LQ_CLOSE |
55,077,207 | Onclick Word Replacement not working correctly with PHP | <p>I have this code:</p>
<p><code><a class='show' data-id='".$random."' href='javascript:void(0)' onclick='if(this.innerHTML == 'Click Here to Read More'){this.innerHTML = 'Click Here to Read Less'}else{this.innerHTML = 'Click Here to Read More'}'>Click Here to Read More</a></code></p>
<p>When the page is returned though everything is returned weird and items are missing in source code like so:</p>
<pre><code><a class="show" onclick="if(this.innerHTML == " href="javascript:void(0)" data-id="23272317" }'="" }else{this.innerhtml="Click Here to Read More" more'){this.innerhtml="Click Here to Read Less" read="" to="" here="" click="">Click Here to Read More</a>
</code></pre>
<p>Im sure its as simple as a quotes issue but im stuck. Anyone able to point me in the right direction or explain how or why this happens with only javascript?</p>
| <javascript><php><quotes> | 2019-03-09 12:10:38 | LQ_CLOSE |
55,078,645 | How do I make a JavaScript login form? | <p>I have a regular HTML form with a text field, which is for a password. The idea is that every user logs in with the same password, therefore there is only one password for the site.</p>
<p>I'm trying to make some JavaScript to check this password, and if it's the correct password, redirect to another page, meaning that anyone who knew their way around basic JavaScript/had common sense could figure out the password by looking at the source code (it's weird I know).</p>
<p>It's really hard to find a tutorial for this, probably because nobody would want to create a password that anyone could easily find out.</p>
<p>Thanks in advance for your help. Also, I know the title is a bit misleading; I couldn't figure out how to describe it in less than three sentences.</p>
| <javascript> | 2019-03-09 15:03:10 | LQ_CLOSE |
55,078,858 | where to get oracle database vm without oracle account? | <p>I want to install Oracle database either 11g or 12c but since I am on Ubuntu 18.04 and since I neither have oracle account nor able to have one I was looking for virtual box image that contain the database.
note : I was thinking to create windows VM and then install Oracle database inside it but I can not find 32 bit version of the database for that purpose.
Please take into consideration I neither have oracle account nor able to have one and I need the database just for educational purposes.</p>
| <oracle><oracle11g> | 2019-03-09 15:25:54 | LQ_CLOSE |
55,079,490 | how to remove duplicate record from results doing left join in sql | I have three tables User Table,Enquiry table and Activity Table .when I do a inner and LEFT JOIN, I am getting duplicate records because of NULL values.
User Table -1
user_id | user_firstName | user_lastName
1 | Joe | Smith
2 | John | Doe
3 | Robert | Smith
Enquiry Table -2
EnquiryID | CreatedBy| |
1 | 1 |
2 | 1 |
Activiy Table - 3
ActivityID | CreatedBy| AssignedBy| AssignedTO|
1 | 1 | null | null |
2 | 1 | 2 | 3 |
Expected Output of all three combining result is
Enquiry ID | | CreatedBy| AssignedBy| AssignedTO|
1 | Joe | null | null |
2 | Joe | John | Rober |
SQL:
SELECT DISTINCT E.EnquirdID as Enquiry,U.FirstName as CreatedBY ,U1.FirstName as AssignedBY , U2,FirstName as AssignedTO
FROM Enquiry E inner join User U on E.UserID = U.UserID
inner join Activity A on E.Enquiry = A.EnquiryID
Left Join User U1 on A.AssignedBY = U1.UserID
Left Join User U2 on A.AssignedTO = U2.UserID
I am getting duplicate Enquiry record from above query even though using Distinct for EnquiryID
END RESULT: My plan is to use the SQL to select the data and display it in PHP on a website. It's a Enquiry management website. I want to be able to have PHP pull the variables from SQL so I can use them however I feel fit.
| <sql><duplicates><left-join><inner-join> | 2019-03-09 16:34:19 | LQ_EDIT |
55,079,666 | Why I get “System.Data.DataRowView” instead of real values in my drop down list | i try to get data in drop down list and its not work i dont understand whats the problem.
string connString = @" Data Source=(LocalDB)\v11.0;AttachDbFilename='C:\Users\oshri\Documents\Stock scores.mdf';Integrated Security=True;Connect Timeout=30";
string queryLecturer = "select name_student from student";
SqlConnection conn = new SqlConnection(connString);
//SqlCommand cmdL = new SqlCommand(queryLecturer, conn);
conn.Open();
//SqlCommand SQLCommand = new SqlCommand();
//cmdL.CommandType = CommandType.Text;
//SQLCommand.CommandText = queryLecturer;
//conn.Close();
SqlDataAdapter adapter = new SqlDataAdapter(queryLecturer, conn);
adapter.Fill(subjects);
DropDownListID.DataSource = subjects;
DropDownListID.DataBind();
DropDownListID.DataBind();
conn.Close();
enter code here | <c#> | 2019-03-09 16:50:42 | LQ_EDIT |
55,080,206 | regex numbers like 1.1k | <p>in regex <code>\d+</code> match all numbers, but it doesn't match numbers like <code>1k</code> or <code>1.4k</code> how should I make a regex to count that numbers too?</p>
<p>What i want:</p>
<p>VALID:</p>
<ul>
<li>1.1K</li>
<li>1.2K</li>
<li>1.0K</li>
<li>1K</li>
</ul>
<p>INVALID:</p>
<ul>
<li>1.1</li>
</ul>
<p>I am new to regex and I don't know how to start</p>
| <php><regex> | 2019-03-09 17:44:15 | LQ_CLOSE |
55,080,815 | Installing odoo-12 on ubuntu-16.04 | <p>** ERROR ? werkzeug: Error on request:
Traceback (most recent call last):
File "/home/eslammofreh/.local/lib/python3.5/site-packages/werkzeug/serving.py", line 270, in run_wsgi
execute(self.server.app)
File "/home/eslammofreh/.local/lib/python3.5/site-packages/werkzeug/serving.py", line 258, in execute
application_iter = app(environ, start_response)
File "/home/workplace/odoo/odoo/service/server.py", line 350, in app
return self.app(e, s)
File "/home/workplace/odoo/odoo/service/wsgi_server.py", line 128, in application
return application_unproxied(environ, start_response)
File "/home/workplace/odoo/odoo/service/wsgi_server.py", line 117, in application_unproxied
result = odoo.http.root(environ, start_response)
File "/home/workplace/odoo/odoo/http.py", line 1318, in <strong>call</strong>
return self.dispatch(environ, start_response)
File "/home/workplace/odoo/odoo/http.py", line 1291, in <strong>call</strong>
return self.app(environ, start_wrapped)
File "/home/eslammofreh/.local/lib/python3.5/site-packages/werkzeug/wsgi.py", line 766, in <strong>call</strong>
return self.app(environ, start_response)
File "/home/workplace/odoo/odoo/http.py", line 1451, in dispatch
self.setup_db(httprequest)
File "/home/workplace/odoo/odoo/http.py", line 1374, in setup_db
httprequest.session.db = db_monodb(httprequest)
File "/home/workplace/odoo/odoo/http.py", line 1535, in db_monodb
dbs = db_list(True, httprequest)
File "/home/workplace/odoo/odoo/http.py", line 1502, in db_list
dbs = odoo.service.db.list_dbs(force)
File "/home/workplace/odoo/odoo/service/db.py", line 375, in list_dbs
with closing(db.cursor()) as cr:
File "/home/workplace/odoo/odoo/sql_db.py", line 657, in cursor
return Cursor(self.<strong>pool, self.dbname, self.dsn, serialized=serialized)
File "/home/workplace/odoo/odoo/sql_db.py", line 171, in __init</strong>
self._cnx = pool.borrow(dsn)
File "/home/workplace/odoo/odoo/sql_db.py", line 540, in _locked
return fun(self, *args, <strong>kwargs)
File "/home/workplace/odoo/odoo/sql_db.py", line 608, in borrow
**connection_info)
File "/home/eslammofreh/.local/lib/python3.5/site-packages/psycopg2/__init__.py", line 130, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError: FATAL: role "eslammofreh" does not exist - - -
2019-03-09 18:18:59,091 1892 INFO ? odoo.sql_db: Connection to the database failed
2019-03-09 18:18:59,093 1892 INFO ? werkzeug: 127.0.0.1 - - [09/Mar/2019 18:18:59] "GET /favicon.ico HTTP/1.1" 500 - 0 0.000 0.005
2019-03-09 18:18:59,098 1892 ERROR ? werkzeug: Error on request:
Traceback (most recent call last):
File "/home/eslammofreh/.local/lib/python3.5/site-packages/werkzeug/serving.py", line 270, in run_wsgi
execute(self.server.app)
File "/home/eslammofreh/.local/lib/python3.5/site-packages/werkzeug/serving.py", line 258, in execute
application_iter = app(environ, start_response)
File "/home/workplace/odoo/odoo/service/server.py", line 350, in app
return self.app(e, s)
File "/home/workplace/odoo/odoo/service/wsgi_server.py", line 128, in application
return application_unproxied(environ, start_response)
File "/home/workplace/odoo/odoo/service/wsgi_server.py", line 117, in application_unproxied
result = odoo.http.root(environ, start_response)
File "/home/workplace/odoo/odoo/http.py", line 1318, in __call__
return self.dispatch(environ, start_response)
File "/home/workplace/odoo/odoo/http.py", line 1291, in __call__
return self.app(environ, start_wrapped)
File "/home/eslammofreh/.local/lib/python3.5/site-packages/werkzeug/wsgi.py", line 766, in __call__
return self.app(environ, start_response)
File "/home/workplace/odoo/odoo/http.py", line 1451, in dispatch
self.setup_db(httprequest)
File "/home/workplace/odoo/odoo/http.py", line 1374, in setup_db
httprequest.session.db = db_monodb(httprequest)
File "/home/workplace/odoo/odoo/http.py", line 1535, in db_monodb
dbs = db_list(True, httprequest)
File "/home/workplace/odoo/odoo/http.py", line 1502, in db_list
dbs = odoo.service.db.list_dbs(force)
File "/home/workplace/odoo/odoo/service/db.py", line 375, in list_dbs
with closing(db.cursor()) as cr:
File "/home/workplace/odoo/odoo/sql_db.py", line 657, in cursor
return Cursor(self.__pool, self.dbname, self.dsn, serialized=serialized)
File "/home/workplace/odoo/odoo/sql_db.py", line 171, in __init__
self._cnx = pool.borrow(dsn)
File "/home/workplace/odoo/odoo/sql_db.py", line 540, in _locked
return fun(self, *args, **kwargs)
File "/home/workplace/odoo/odoo/sql_db.py", line 608, in borrow
**connection_info)
File "/home/eslammofreh/.local/lib/python3.5/site-packages/psycopg2/__init__.py", line 130, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError: FATAL: role "eslammofreh" does not exist -</strong></p>
| <ubuntu-16.04><odoo-12> | 2019-03-09 18:47:33 | LQ_CLOSE |
55,080,962 | html css absolute position overlay problem | I got 2 blocks, top and bottom. Bottom block has: position: absolute; bottom: 0 styles. In bottom block there is an image that should overlay top block in one place. it overlays Ok but I can't click on element from top block cause browser think i click on bottom. How can it be resolved? Maybe z-index or something else? | <html><css> | 2019-03-09 19:07:48 | LQ_EDIT |
55,081,407 | Migrate Laravel 4.0 to 5.7 | Actually , I have a System done in Laravel 4.0.
It’s possible migrate to Laravel 5.7? What are the impact of this on the system and how I could do it?
É possível migrar o Laravel 4.0 para 0 5.6 e qual o passo a passo para fazer da maneira certa? | <laravel><laravel-5><laravel-4><migrate> | 2019-03-09 19:59:35 | LQ_EDIT |
55,081,603 | Regular expression to find string inside curly brackets while keeping curly brackets | <p>Hi I am only starting out with Regexs, and am trying to write a regular expression to find string inside curly brackets while keeping curly brackets</p>
<pre><code>Text: "This is a {nice} text to search for a {cool} substring".
Answer I want: {nice} and {cool}
</code></pre>
<p>I have already looked through the answer here:
<a href="https://stackoverflow.com/questions/30483613/regular-expression-to-find-string-inside-curly-brackets-javascript">Regular expression to find string inside curly brackets Javascript</a></p>
<p>This almost does what I want, except that it only returns what's inside the curly brackets. I want to keep the curl brackets.</p>
| <regex> | 2019-03-09 20:21:26 | LQ_CLOSE |
55,082,107 | Attempting to change the BackColor of a Form by a button that is located on a seperate Form | <p>Title says it all. </p>
<p>but this is the code I used </p>
<pre><code>Form1 f1 = new Form1();
private void button2_Click(object sender, EventArgs e)
{
{
f1.BackColor = Color.White;
}
</code></pre>
<p>For example, the button is on Form4, and when I click that button, I want the BackColor of Form1 to change to white, but it doesn't.</p>
| <c#> | 2019-03-09 21:24:55 | LQ_CLOSE |
55,082,588 | Can't create php register form | <p><a href="https://i.stack.imgur.com/5tNTV.png" rel="nofollow noreferrer">Image URL</a></p>
<p>Error:
Parse error: syntax error, unexpected end of file in D:\OSPanel\domains\register\signup.php on line 47</p>
| <php> | 2019-03-09 22:28:45 | LQ_CLOSE |
55,083,196 | Challenge:: palindrome words | <p>A palindrome is a word that reads the same backward or forward.
Write a function that checks if a given word is a palindrome. Character case should be ignored.
function isPalindrome(word)
For example, isPalindrome("Deleveled") should return true as character case should be ignored, resulting in "deleveled", which is a palindrome since it reads the same backward and forward.</p>
<pre><code>function isPalindrome(word)
{
// Please write your code here.
}
var word = readline()
print(isPalindrome(word))
</code></pre>
| <javascript> | 2019-03-10 00:01:28 | LQ_CLOSE |
55,084,430 | Take Text from an EntryBox and then write it to a txt file | <p>All,
I have attempted this a few different ways and am still struggling here. </p>
<p>I want to have someone write in this Entry Box and then once submit is hit, it should write the text to the .txt file. I'm obviously not very good. </p>
<pre><code>import datetime
from tkinter import *
def save():
with open("text.txt", "a") as f:
now = datetime.datetime.now()
test = TxtComplaint.get()
test = str(test)
f.write(test)
f.write(now)
window = Tk()
window.title("Documentation Window")
lbl = Label(window, text = "Enter In The Employee's Information")
TxtComplaint = Text(window, height = '10', width = '30')
benter = Button(window, text="Submit", command = save())
TxtComplaint.pack()
ee = Entry(window)
eelbl = Label(window, text = "Whats the name of the employee?")
eename = str(lbl)
lbl.pack()
benter.pack()
ee.pack()
eelbl.pack()
window.mainloop()
</code></pre>
| <python><tkinter> | 2019-03-10 04:27:54 | LQ_CLOSE |
55,085,943 | Can you help me how to change the password in MVC PHP | this is my MODEL:
public function editNewPassword($data){
// $user_name = $data['user_name'];
$user_id = $data['id'];
$user_oldpass = $data['password'];
$user_newpass = $data['newpass'];
$sql = "UPDATE user SET password = '".md5($user_newpass)."' WHERE password = 'md5($user_oldpass)' ";
$query = $this->db->prepare($sql);
$query->execute();
}
public function getUser(){
return $this->db->select("SELECT * FROM 'users'");
}
This is my CONTROLLER:
function changePassword(){
if(isset ($_POST['edit_password'])){
$user_oldpass = ($_POST['user_oldpass']);
$user_id = ($_POST['user_id']);
$user_name = ($_POST['user_name']);
$user_newpass = ($_POST['user_newpass']);
$this->model->editNewPassword($data);
}
}
this is for my VIEW code:
<form role="form">
<!-- <input typ e="text" name="username" id="username" placeholder="Enter Your Username"><br> -->
<input type="text" name="old_password" id="old_password" placeholder="Enter Your Old Password"><br>
<input type="text" name="new_password" id="new_password" placeholder="Enter Your New Password"><br>
<input type="text" name="con_newpassword" id="con_newmpassword" placeholder="Enter Confirm Password"><br>
<span id='message'></span>
<input type="hidden" id="edit_password_id">
<button id="edit_password" style="background-color:#008000">Submit</button>
</form>
This is my javascript code:
$('#edit_password').on('click', function(){
// alert('Password changed successfully!')
var
user_id = $('#edit_password_id').val();
user_name = $('#username').val();
user_oldpass = $('#oldpassword').val();
user_newpass = $('#newpassword').val();
$.ajax({
url: URL+'changepassword/changePassword',
type: "post",
data: {
id : id,
name : name,
password : password,
newpass : newpass
},
success: function(response){
$('#edit_password_id').modal('toggle');
location.reload();
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
My problem is my password won't change even no error and I don't know where is the error to my code. if anyone know to solve this please help me
PS: I am new to this ;-) | <javascript><php><jquery> | 2019-03-10 08:44:19 | LQ_EDIT |
55,087,210 | Testing an IF statement with respect to state with Jest doesn't work | I am trying to test this method which is responsible for editing but am able to the lines which replace the **old title** and the **old body** with the new title and body.
This is located in the IF section. Below is the code which implements editing :
onEditNote = (event) => {
const { target: { value: id } } = event;
const obj = {
title: this.state.title,
body: this.state.body,
};
// clear the errors while submitting
this.setState({ titleError: '', bodyError: '' });
if (obj.title === '') {
this.setState({ titleError: 'Title empty, please add title' });
} else if (obj.body === '') {
this.setState({ bodyError: 'Body empty, please add body' });
} else if (obj.title.length > 20) {
this.setState({ titleError: 'Title is too long.' });
} else {
this.setState((state) => {
const list = state.notesArray.map((item) => {
if (item.id === id) {
// eslint-disable-next-line no-param-reassign
item.title = obj.title;
// eslint-disable-next-line no-param-reassign
item.body = obj.body;
}
return item;
});
localStorage.setItem('items', JSON.stringify(list));
// eslint-disable-next-line no-undef
$('#editModal').modal('close');
this.onSuccessToast('Noted edited successfully.');
return {
list,
title: '',
body: '',
};
});
}
};
These are the lines in the above code which are not covered by the test I implemented :
> if (item.id === id) {
> // eslint-disable-next-line no-param-reassign
> item.title = obj.title;
> // eslint-disable-next-line no-param-reassign
> item.body = obj.body;
> }
And below is my test I am implementing which doesn't cover the IF statement, yet I see I have covered it :
it('should edit a Note.', () => {
wrapper = shallow(<App />);
$.fn.modal = jest.fn();
wrapper.instance().onEditNote({ target: { value: '0' } });
wrapper.instance().setState({
title: 'huxy 12',
body: 'hey huxy this is not great.',
notesArray: [{ title: 'hey', body: 'its good', id: '0' }],
});
wrapper.instance().setState((state) => {
state.notesArray.map((item) => {
if (item.id === '0') {
// eslint-disable-next-line no-param-reassign
item.title = state.title;
// eslint-disable-next-line no-param-reassign
item.body = state.body;
}
return item;
});
});
});
What am I missing in my test?
| <reactjs><jestjs><enzyme> | 2019-03-10 11:31:04 | LQ_EDIT |
55,087,262 | How can i speed up my Android App testing | if have an app release in the playstore and whenever i am working on updates, my testcycles take way too long.
The problem is, if i want to copy my own built apk to my phone, it recognizes it as may apk from the playstore and asks if i want to update it. If i try to update, it stops and says it could not be installed.
So what i have to do is upload my app to google dev console als intern test track and wait until it is there as an update on my phone. This can take nearly an hour. So if i want to test simple stuff, i have to wait nearly an hour to see the results. That is not practicable.
Is there any way to fasten my testing workflow up?
I think i am missing a really simple thing right now.
Currently i am working with some google play game services. Maybe that makes any difference. | <android><testing><workflow> | 2019-03-10 11:38:08 | LQ_EDIT |
55,087,280 | Restrict some JS to work on specific websites | <p>This is more of a conceptual question. I have a JS that I need to run when user is accessing only specific website(s). Is there any approach to make sure that my particular JS is invoked from some specific website(s)?</p>
<p>Thank you!</p>
| <javascript><frontend> | 2019-03-10 11:40:13 | LQ_CLOSE |
55,088,454 | How can i convert double? to double. Math.Sqrt operations | <p>i would like to ask for some help to this code right below this question... i am encountering some error that says "Argument 1: cannot convert double? to double". How can i fix this what should i add?</p>
<pre><code>private void Calculate(string newOperator = null)
{
double? result = null;
double? first = numbers[0] == null ? null : (double?)double.Parse(numbers[0]);
double? second = numbers[1] == null ? null : (double?)double.Parse(numbers[1]);
switch (@operator)
{
case "÷":
result = first / second;
break;
case "×":
result = first * second;
break;
case "+":
result = first + second;
break;
case "-":
result = first - second;
break;
case "√":
result = Math.Sqrt(first);
break;
case "SIN":
result = Math.Sin(first);
break;
case "COS":
result = Math.Cos(first);
break;
case "TAN":
result = Math.Tan(first);
break;
}
</code></pre>
| <c#> | 2019-03-10 14:02:14 | LQ_CLOSE |
55,088,481 | how to fix qr scanner is not scanning qr codes | Hello guys can someone help me.
Im trying to create an android app that can scan qr codes. But the problem is, it only autofocus on the qr code but not returning any results. Is there a way to fix this?
Im using zxing libraries | <android><qr-code><zxing> | 2019-03-10 14:06:10 | LQ_EDIT |
55,089,328 | C - array aloccation | I have following code and i need to allocate memory for char data[]. I tryed many things, but it still doesnt work. Can someone help me ? I know my malloc wont allocate anything for data, but how to repair this.
//img->data = malloc(sizeof(char)*(img->xsize * img->ysize * 3)); need data allocate like this
```
struct ppm {
unsigned xsize;
unsigned ysize;
char data[];
};
struct ppm *img = malloc(sizeof(struct ppm));
if (!img)
fprintf(stderr, "Chyba alokace pameti.\n");
exit(1);
}
if (fscanf(fp, "%x %x", &img->xsize, &img->ysize) != 2) {
fprintf(stderr, "Spatna velikost obrazku '%s'\n", filename);
exit(1);
}
if (fread(img->data, 3 * img->xsize, img->ysize, fp))
fprintf(stderr, "Nepodarilo se nacist pixely z '%s'\n", filename);
exit(1);
}
``` | <c> | 2019-03-10 15:36:02 | LQ_EDIT |
55,090,611 | How can I run an executable and take input from a text file on Linux? | <p>How can I run an executable and take input from a text file on Linux?
I was trying to use:
./(name of my executable) TextFile.txt but it does not work.</p>
| <c++> | 2019-03-10 17:50:38 | LQ_CLOSE |
55,091,779 | How do you implement Horizontal-Scrolling in Android Studio with LibGDX? | right now I am trying to program an Android Game to further educate myself in App Developement. I want to program a game that is like the old "Warfare 1917" browser games. Right now I am stuck on the scrolling part. I am using Java and LibGDX. <br><br>I'll try to explain what I want to with a gif.<br><br>
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/rvZqA.gif
I have searched and tried everything the hole day but I am not able to find any real solutions to this. I hope you can understand what I am trying to do. | <java><android><libgdx><horizontal-scrolling> | 2019-03-10 19:55:49 | LQ_EDIT |
55,092,157 | Java script )) Questions about random quiz game | <p>I'm making a simple random quiz game</p>
<p>I wrote some scripts for the game </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 Playerfirstname = prompt("Enter your first name");
var Playerlastname = prompt("Enter your last name");
alert(`Hello ${Playerfirstname} ${Playerlastname}!`);
console.log("Player name is :",Playerfirstname +","+ Playerlastname);
var round1quiz = [
['Whats is 2 + 2', '4'],
['What is 3 * 3', '9'],
['What is 5 * 5', '25']
];
var round2quiz = [
['Whats my name', 'Ian'],
['Where am i from', 'India'],
['My favorite Food', 'Idly']
];
var round3quiz = [
['Whats my name', 'Ian'],
['Where am i from', 'India'],
['My favorite Food', 'Idly']
];
score = 0;
var questions = 0;
function round1()
{
shuffle(round1quiz)
var round1 = prompt("If you want to start Quiz game, enter 'yes'");
if (round1 == 'yes' || round1 == 'y')
{
alert("Let's start Quiz game!");
alert("Round 1");
questions = round1quiz;
}
else
{
alert("sorry, try again");
var round1 = prompt("If you want to start Quiz game, enter 'yes' or 'y' ");
}
}
round1();
function round2()
{
}
function randomQuestions() {
return [rq(), rq(), rq()]
}
function rq() {
var a = getRandomInt(0, 100),
b = getRandomInt(0, 100),
operator = "+-*" [getRandomInt(0, 3)],
answer = operator === "+" ? a + b : operator === "-" ? a - b : operator === "*" ? a * b:0;
return ["what is " + a + operator + b, answer]
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
function askQ(ans) {
var answer = prompt(ans[0], '');
if (answer == ans[1]) {
score++;
alert('Your are right!, you get money');
} else {
alert('Sorry, It is wrong answer');
}
}
// the loop that will ask all the questionseasy
function startquiz() {
for (var i = 0; i < questions.length; i++) {
askQ(questions[i]);
}
}
startquiz();
alert(score);
function shuffle(array) { //
var currentIndex = array.length,
temporaryValue, randomIndex;
while (0 !== currentIndex) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}</code></pre>
</div>
</div>
</p>
<p>I wanna put round2 and round3 in my code</p>
<p>If the player entered all correct answer and choose to play round2, round2questions will display.</p>
<p>However, if the player chooses to stop playing the game, the game will be over
How can I put that code in my script?</p>
| <javascript> | 2019-03-10 20:36:57 | LQ_CLOSE |
55,092,257 | store jason values in javascript var | i have this code for my geolocation and i am trying to get the address values and store them in to javascript var
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.watchPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
var lat = position.coords.latitude;
var lag = position.coords.longitude;
$("#latit").val(lat);
$("#lang").val(lag);
var settings = {
"async": true,
"crossDomain": true,
"url": "https://us1.locationiq.com/v1/reverse.php?key=//////////&lat="+lat+"&lon="+lag+"&format=json",
"method": "POST"
}
$.ajax(settings).done(function (response) {
console.log(response);
});
}
and this is the result i get from the json response in my console:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
{place_id: "192741603", licence: "https://locationiq.com/attribution", osm_type: "way", osm_id: "548559489", lat: "32.2814427", …}
address:
city: "קדימה - צורן"
country: "ישראל"
country_code: "il"
postcode: "NO"
state: "מחוז המרכז"
suburb: "שיכון יציב"
__proto__: Object
boundingbox: (4) ["32.2808557", "32.2814427", "34.9092769", "34.9114099"]
display_name: "שיכון יציב, קדימה - צורן, מחוז המרכז, NO, ישראל"
lat: "32.2814427"
licence: "https://locationiq.com/attribution"
lon: "34.9094007"
osm_id: "548559489"
osm_type: "way"
place_id: "192741603"
__proto__: Object
<!-- end snippet -->
how can i get values from the address and store them in javascript var? | <javascript><json> | 2019-03-10 20:47:27 | LQ_EDIT |
55,093,074 | How can I get something specific from json in node.js | <p>I am trying to get a youtube subscriber count using googles node.js API <a href="https://github.com/googleapis/google-api-nodejs-client" rel="nofollow noreferrer">https://github.com/googleapis/google-api-nodejs-client</a> and I am also using the youtube data api from google <a href="https://developers.google.com/youtube/v3/" rel="nofollow noreferrer">https://developers.google.com/youtube/v3/</a> I am trying to get subscriberCount from here <a href="https://www.googleapis.com/youtube/v3/channels?part=statistics&id=channel_id&key=api_key" rel="nofollow noreferrer">https://www.googleapis.com/youtube/v3/channels?part=statistics&id=channel_id&key=api_key</a> and here's what I have
here is my code and what I am getting <a href="https://hastebin.com/sotejijole.js" rel="nofollow noreferrer">https://hastebin.com/sotejijole.js</a>, subscriberCount is in statistics: [Object] but I don't know how I can get to it.</p>
| <node.js><json><youtube> | 2019-03-10 22:33:08 | LQ_CLOSE |
55,095,311 | How to concate string using strcat() | <p>This code want to concate the string but it do not show the output</p>
<pre><code>#include<stdio.h>
#include<string.h>
main( )
{
char *str1 = "United" ;
char *str2 = "Front" ;
char *str3 ;
str3 = strcat ( str1, str2 ) ;
printf ( "\n%s", *str3 ) ;
}
</code></pre>
| <c> | 2019-03-11 04:40:01 | LQ_CLOSE |
55,096,237 | how to split length list in python | <p>question</p>
<pre><code>my_list = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,...,50]
</code></pre>
<p>answer</p>
<pre><code>listOne = [0,1,2,....,9
listTwo = [10,11,12,...,19]
listThree = [20,21,22,...,29]
listFour = [30,31,32,...,39]
listFive = [40,41,42,...,49]
listSix = [50,51,52,...,59]
</code></pre>
<p>answer</p>
<p>If we do not know the number to show in my list how to split list</p>
| <python><list> | 2019-03-11 06:23:47 | LQ_CLOSE |
55,096,723 | How to Group by json array by two same key | <p>How to group by based on two json key which is f and b
My json array </p>
<pre><code>var json=[
{ s:'s', f:1, b:1, q:2 },
{ s:'s', f:1, b:1, q:3 },
{ s:'s', f:2, b:1, q:2 },
{ s:'s', f:2, b:1, q:2 },
{ s:'s', f:1, b:2, q:2 },
{ s:'s', f:1, b:2, q:2 },
{ s:'s', f:0, b:1, q:2 },
{ s:'s', f:0, b:1, q:2 },
{ s:'s', f:1, b:0, q:2 },
{ s:'s', f:1, b:0, q:2 },
{ s:'s', f:0, b:0, q:2 },
{ s:'s', f:0, b:0, q:2 },
</code></pre>
<p>];</p>
<p>Expected Output</p>
<pre><code> var op=[
{ s:'s', f:1, b:1, q:5 },
{ s:'s', f:2, b:1, q:4 },
{ s:'s', f:1, b:2, q:4 },
{ s:'s', f:0, b:1, q:4 },
{ s:'s', f:1, b:0, q:4 },
{ s:'s', f:0, b:0, q:4 },
</code></pre>
<p>];</p>
| <javascript><jquery> | 2019-03-11 07:06:09 | LQ_CLOSE |
55,097,007 | Most efficient method of finding the number of common factors of two numbers using Golang | I have two numbers for example the numbers are 12 and 16.
> factors of 12 are 1, 2, 3, 4, 6, 12
>
> factors of 16 are 1, 2, 4, 8, 16
>
> common factors of these two numbers are 1, 2 and 4.
So the number of common factors are 3. I need to build a Golang program for finding the number common factors of two numbers. But the program should be efficient and with minimum number of loops or without loops. | <go><math> | 2019-03-11 07:28:28 | LQ_EDIT |
55,097,313 | Having trouble with "Rectangles" (am a simpleton) | I recently got back into coding and have forgotten most things (am a simpleton), tried warming up with a simple question ":Create a class Rectangle with instance variables length and width to have default value of 1 for both of them. The class should have suitable set and get methods for accessing its instance variables. The set methods should verify that length and width are assigned a value that is larger than 0.0 and is lesser than 20.0, Provide suitable public methods to calculate the rectangle’s perimeter and area. Write a suitable class "RectangleTest" to test the Rectangle class.
What i came up with:
package rectangle;
public class Rectangle
{
private double width;
private double length;
public Rectangle()
{
width=1;
length=1;
}
public Rectangle(double width, double length)
{
this.width = width;
this.length = length;
}
public void setWidth(float width)
{
this.width = width;
}
public float getWidth()
{
return (float) width;
}
public void setLength(float length)
{
this.length = length;
}
public float getLength()
{
return (float) length;
}
public double getPerimeter()
{
return 2 * (width + length);
}
public double getArea()
{
return width * length;
}
}
----------
package rectangle;
import java.util.Scanner;
public class RectangleTest extends Rectangle
{
public static void main(String[] args)
{
Scanner RectangleTest = new Scanner(System.in);
System.out.print("Length: ");
float lengthInput = RectangleTest.nextFloat();
System.out.print("Width: ");
float widthInput = RectangleTest.nextFloat();
Rectangle rectangle = new Rectangle (lengthInput, widthInput);
System.out.printf("Perimeter: %f%n",
rectangle.getPerimeter());
System.out.printf("Area: %f%n",
rectangle.getArea());
}
}
code is fine, it's just i am not sure how to implement the between 0 - 20 without breaking everything and have tried different things, is it actually pretty easy?
| <java> | 2019-03-11 07:50:39 | LQ_EDIT |
55,097,555 | Replace string array in a JSON to integer array | <p>Please see the json below for highcharts
{"chart": {"type": "column"},"credits": {"enabled": true,"href": "#","position": {"align": "right","verticalAlign": "bottom","y": 0},"text": "www.midasplus.com"},"series": [{"color": {"linearGradient": {"x1": 1,"x2": 0,"y1": 0,"y2": 1},"stops": [[0,"#9a1919"],["0.25","#9a1919"],["0.5","#9a7319"],["0.75","#9a1919"],[1,"#9a1919"]]},"data": ["-1.03","-3.01","-2.25","0.63","-1.07","1.14","-0.38","2.03","-2.07","-3.55","-3.99","-0.41"],"negativeColor": {"linearGradient": {"x1": -1,"x2": 0,"y1": 0,"y2": -1},"stops": [[0,"#199A19"],["0.25","#199A19"],["0.5","#00CC00"],["0.75","#199A19"],[1,"#199A19"]]},"showInLegend": "false"}],"title": {"text": "Control Chart"},"xAxis": {"categories": ["Q3 2013","Q4 2013","Q1 2014","Q2 2014","Q3 2014","Q4 2014","Q1 2015","Q2 2015","Q3 2015","Q4 2015","Q1 2016","Q2 2016"]} } </p>
<p>In this, i need to change the "data": ["-1.03","-3.01","-2.25","0.63","-1.07","1.14","-0.38","2.03","-2.07","-3.55","-3.99","-0.41"] string array values into integer array in the same json using javascript.</p>
| <javascript><arrays><json><highcharts> | 2019-03-11 08:07:58 | LQ_CLOSE |
55,100,898 | cant turn on acer switch 10 ; black screen | <p>the problem is interesting. i have instaled windows 10 32bit on this tablet and touch screen didnt work. so i troubleshoted hardware and it said the problem is with cpu core. it said thad it musts reinstall the driver. ok, i did it. while it was doing this proces it sudently turned off. i presed power on button and it started runing but it cant go to windows, even acer logo doesnt shows up(cant go to bios). there is only black screen. also i cant turn it off right now.</p>
<p>where is the problem, and how to fix it?</p>
| <windows><touchscreen> | 2019-03-11 11:30:05 | LQ_CLOSE |
55,101,190 | PHP: How to know if number is in a interval of int? | <p>I have a variable of int type called <code>myNumber</code> and I need to know if it is in the interval [100, 200].</p>
<p>Example:</p>
<pre><code>if (myNumber in (100, 200)) {
echo 'Yes';
}
</code></pre>
<p>I wonder if PHP has a <code>in</code> function or similar.</p>
| <php><int><set> | 2019-03-11 11:48:03 | LQ_CLOSE |
55,101,427 | My if and else if are running at the same time | <p>I've got a program measuring distance from a rocket to the moon, so when the distance is >250, only the if runs. However when the else runs and the distance <=250, the if continues to run while the else runs. If anyone can help me fix it I would be very thankful. </p>
<pre><code>do
{
if (distance >250)
{
time += 1;
y_pos = initial_y_pos - (vel_y * time)/2;
x_pos = initial_x_pos + (vel_x * time)/2;
//Sets the new x and y position when time is flowing so the rocket can move
GFX_DrawLineTo(x_pos, y_pos, 3);
GFX_UpdateDisplay();
distance = sqrt(pow((y_pos-(y+312)),2)+(pow((x_pos-(x+440)),2)));
mars_dist = sqrt(pow((y_pos-150),2)+pow((x_pos-1150),2));
//distance calculation from the rocket to the moon. Needed for sphere of influence
printf("%f\n",distance);
}
else if (distance <=250)
{
y_pos = initial_y_pos - ((vel_y * time) - ((gravity * time)/2));
x_pos = initial_x_pos + ((vel_x * time) - ((gravity * time)/2));
GFX_DrawLineTo(x_pos, y_pos, 3);
GFX_UpdateDisplay();
distance = sqrt(pow((y_pos-(y+312)),2)+(pow((x_pos-(x+440)),2)));
mars_dist = sqrt(pow((y_pos-150),2)+pow((x_pos-1150),2));
//printf("%f\n",distance);
printf("%f\n", x_pos);
}
if (distance <= 50)
//If the rocket either hits moon or mars, this is responsible for recognising that
{
printf("Unlucky! Your rocket crashed into the moon!");
return 0;
}
}
//while (distance > 250);
while ((0 <= x_pos && x_pos <= 1280) || (0 <= y_pos && y_pos <= 1024));
</code></pre>
| <c> | 2019-03-11 12:00:54 | LQ_CLOSE |
55,102,241 | checking substrings in Array and replacing them in ruby | I'm studying code and part of the course asks me to write a program that filters out words in the array test_tweets that match words in banned_phrases array, but can't figure out what method achieves this. This is what I've got so far:
`test_tweets = [
"This politician sucks!",
"I hate this Government!",
"I can't believe we're living with such a bad politician. We were so foolish",
"Politicianname is a danger to society. I hate that he's so bad – it sucks."
]
banned_phrases = ["sucks", "bad", "hate", "foolish", "danger to society"]` | <arrays><ruby><string> | 2019-03-11 12:51:05 | LQ_EDIT |
55,105,647 | Something is wrong with my pyhton write to interact game code | so here is the code. and when i try to run it nothing happens. Please help. Code:
def game() :
import time
import random
print ("you whake up in a forest. you see a stick next to you. What do you do?")
time.sleep(1)
print ("(go north)|(go west)|(pick up stick(recomended))|(go east)")
a = str(input("your move: "))
if a == "go north" :
print ("you went north")
time.sleep (1)
print ("a wolf aproaches you")
time.sleep (1)
b = str(input("what do you do?: "))
if b == "run" :
print ("you tried, but the wolf was faster. You died ")
c= str(input("Try again? (Yes/No)"))
if c == "yes" :
game() | <python> | 2019-03-11 15:50:50 | LQ_EDIT |
55,105,911 | Why do js files sometins load with errors? | I use several script libraries on [this site][1], including Amcharts for instance.
I have noticed that sometimes they don't load properly and there can be no table oк no chart. I have tried to place them both in head and footer, but it doesn't change anything. Is there a way to make it correct?
[1]: https://quanthill.ru/ | <javascript><json><amcharts> | 2019-03-11 16:04:23 | LQ_EDIT |
55,106,739 | Google Sheets: Split rows based in cell wiht comma separated values | I need to Split two rows based in the Color cell value. Each comma separated value should generate a new row.
Google Sheet link: https://docs.google.com/spreadsheets/d/1rwtSxDn_gf60xy0w63mp8Dj4bMUH9tNKJjtnsbqGzTw/edit?usp=sharing
The formula should create the rows E5:G8 form the rows A5:C6.
The formula should work with any number of rows.
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/qYHC5.jpg | <google-apps-script><google-sheets> | 2019-03-11 16:52:51 | LQ_EDIT |
55,107,325 | Can we declare a object inside the if-else statement? | <p>This code is the main function for the implementation of queues using arrays also using template class. </p>
<pre><code>int main(){
int choice, n;
cout<<"Enter 1 for integer 2 for double\n";
cin >> choice;
cout<<"Enter the size of queue\n";
cin>>n;
if (choice == 1)
queue<int> obj(n);
else
queue<double> obj(n);
for(;;){
cout<<"1:Insertrear 2:Deletefront 3:Display 4:Exit\n";
cin >> choice;
switch(choice){
case 1:obj.insertRear();break;
case 2:obj.deleteFront(); break;
case 3:obj.display();break;
default: return 0;
}
}
return 0;
}
</code></pre>
<p>The thing that I could not understand is, why I got error <code>'obj' was not declared in this scope</code> in the line below the <code>switch</code> statement.</p>
<p>Any help will be well appreciated.</p>
| <c++> | 2019-03-11 17:28:37 | LQ_CLOSE |
55,107,381 | How can I use both /g and /i in regex to make my search repeat through the entire search as well as ignore case sensitivity in javaScript? | <p>I want to remove white space, comma, and digits from my string as well as ignore case sensitivity.
Below is my regex to this I am not able to use /i(to remove case sensitivity) and /g(repeat search) together in my expression.</p>
<blockquote>
<p>Regex expression</p>
</blockquote>
<pre><code>var str = "My age is 0, 0 si ega ym."
str.replace(/[,\s\d.]+/g,'')
</code></pre>
<p>Where shall I put /i in the above expression?</p>
| <javascript><regex> | 2019-03-11 17:32:18 | LQ_CLOSE |
55,107,691 | Javascript Regex: Return number of the last occurrence of a pattern | I'm trying, with no sucess, to get a number inside of the **last occurence** of a pattern inside of a HTML code. The pattern is **data\\[\d{1,3}\\]**. How can i get the number "03" in the below example?
<body>
<h2>JavaScript Regular Expressions</h2>
<p>TEST</p>
<p>data[01]</p>
<button onclick="myFunction()">Try it</button>
<p>data[02]</p>
<p>TEST</p>
<p id="demo" test=data[03]></p>
</body>
I tried many combinations with $, but i could not make it work. | <javascript><regex> | 2019-03-11 17:53:46 | LQ_EDIT |
55,107,789 | How to compare a two files line by line and then word by word. Also we need to highlight the mismatched words in output | <p>How to compare a two files line by line and then word by word. Also we need to highlight the mismatched words in output.</p>
<p>I need to write this in Java and create a HTML file.</p>
| <java> | 2019-03-11 18:00:21 | LQ_CLOSE |
55,107,908 | How to update a struct property in a map | <p>Currently trying to learn Go.</p>
<p>I have the following function, but it only works when the team doesn't exist in the map already and it creates a new record in the map. It will not update the values if the team already has a struct in the map.</p>
<pre><code>func AddLoss(teamMap map[string]TeamRow, teamName string) {
if val, ok := teamMap[teamName]; ok {
val.Wins++
val.GamesPlayed++
} else {
newTeamRow := TeamRow{Losses: 1}
teamMap[teamName] = newTeamRow
}
}
</code></pre>
<p>I have updated the function to just replace the existing record with a brand new struct with the values I want, but that seems odd that I can't update the values in a map.</p>
<p>Can someone explain this to me, or point me in the right direction?</p>
| <dictionary><go> | 2019-03-11 18:08:25 | LQ_CLOSE |
55,108,822 | Python sorting two lists together? | <p>I'm having some problems with my code below. I have my two lists names and scores. These lists, correspond with each other as seen below. My goal is to print out the first three greatest items in both lists. I've attempted to sort them together from greatest to least and then print out the first three items, but I'm getting some unbounderror. Any thoughts? Thanks. </p>
<pre><code>names = ['Xander', 'Spec', 'Meng', 'Sparc', 'Jones', 'Nick', 'Link']
scores = [120, 450, 300, 200, 66, 183, 80]
scores, names = (list(t) for t in zip(*sorted(zip(scores, names))))
print(names[:3] + " " + scores[:3])
</code></pre>
<p>Example Output:</p>
<pre><code>Spec 450
Meng 300
Sparc 200
</code></pre>
| <python><python-3.x><list><sorting> | 2019-03-11 19:13:42 | LQ_CLOSE |
55,109,273 | can any one explain this example step by step its abot getting prime numbers |
> function to show primes
function showPrimes(n) {
for (let i = 2; i < n; i++) {
if (!isPrime(i)) continue;
alert(i); // a prime
}
}
> function to check prime
function isPrime(n) {
for (let i = 2; i < n; i++) {
if ( n % i == 0) return false;
}
return true;
}
> trigger to run the function and put the value of (n)
showPrimes(10);
| <javascript> | 2019-03-11 19:47:05 | LQ_EDIT |
55,109,666 | SyntaxError - expected an indented block | <p>when i run this i get "SyntaxError - expected an indented block" popup. I have no idea how to fix it and I need help.</p>
<pre><code>solved_places ={
"a1": False, "a2": False, "a3": False, "a4": False, "a5": False, "a6": False, "a7": False, "a8": False, "a9": False, "a10": False,
"b1": False, "b2": False, "b3": False, "b4": False, "b5": False, "b6": False, "b7": False, "b8": False, "b9": False, "b10": False,
"c1": False, "c2": False, "c3": False, "c4": False, "c5": False, "c6": False, "c7": False, "c8": False, "c9": False, "c10": False,
"d1": False, "d2": False, "d3": False, "d4": False, "d5": False, "d6": False, "d7": False, "d8": False, "d9": False, "d10": False,
"e1": False, "e2": False, "e3": False, "e4": False, "e5": False, "e6": False, "e7": False, "e8": False, "e9": False, "e10": False,
"f1": False, "f2": False, "f3": False, "f4": False, "f5": False, "f6": False, "f7": False, "f8": False, "f9": False, "f10": False,
"g1": False, "g2": False, "g3": False, "g4": False, "g5": False, "g6": False, "g7": False, "g8": False, "g9": False, "g10": False,
"h1": False, "h2": False, "h3": False, "h4": False, "h5": False, "h6": False, "h7": False, "h8": False, "h9": False, "h10": False,
"i1": False, "i2": False, "i3": False, "i4": False, "i5": False, "i6": False, "i7": False, "i8": False, "i9": False, "i10": False,
"j1": False, "j2": False, "j3": False, "j4": False, "j5": False, "j6": False, "j7": False, "j8": False, "j9": False, "j10": False,
}
</code></pre>
| <python><syntax-error><indentation> | 2019-03-11 20:12:21 | LQ_CLOSE |
55,111,562 | how to add markers on navigationlauncher of mapbox? | Im using mapbox for map navigation.. is it possible to add markers on navigation view on mapbox like the waze app.. when you start navigating markers is still shown on navigation | <android><mapbox><mapbox-android> | 2019-03-11 22:51:48 | LQ_EDIT |
55,111,584 | How can I get the values of multiple inputs by numbered ids and insert them into MySQL | <p>I tried to create a multi insert form where you can insert as many tiles and related languages as you want by filling in a number. The display of the Titles and language works fine, but I'm not able to get the different values and insert them into db. My aim is it that every Title with its Lang gets a unique ID in the db.</p>
<pre><code><form method="POST" action="" enctype="multipart/form-data">
<table>
<tr>
<th>Title</th>
<th>Language</th>
</tr>
</table>
<input id="count" type="number" placeholder="Number of Titles">
<input type="button" id="plus" value="+">
<input type="submit" id="save" name="save" value="Save">
<script type="text/javascript">
$('#plus').on('click', function(){
var queryString = "";
var count = $('#count').val();
var i;
for(i = 1; i <= count; i++){
$('table').append('<tr><td><input name="title" type="text" placeholder="Title" id="Title_'+i+'" autocomplete="off" class="title"></td><td><select name="lang" id="Lang_'+i+'"><option value="0">Romaji</option><option value="ja">Japanese</option><option value="en">English</option><option value="de">German</option><option value="ru">Russian</option></select></td></tr>');
}
});
$('#save').on('click', function(){
var Title = $('#Title_'+i).val();
console.log(Title);
queryString ='title='+Title+'&lang='+Lang;
jQuery.ajax({
url: "action/insert.php",
data: queryString,
type: "POST",
success:function(data){
location.reload();
},
});
});
</script>
</form>
</code></pre>
<p>I also tried to get the value of the inputs via Jquery and send them with Jquery Ajax to the PHP file but I only get the output "undefined" when I tried to show the values in console</p>
<p>The insert.php</p>
<pre><code><?php
require "../config.php";
$title= $_POST['title'];
$lang= $_POST["lang"];
$sql = "INSERT INTO MyGuests (title, lang) VALUES ('".$_POST['']."', '".$_POST['']."');";
$sql .= "INSERT INTO MyGuests (title, lang) VALUES ('".$_POST['']."', '".$_POST['']."');";
$sql .= "INSERT INTO MyGuests (title, lang) VALUES ('".$_POST['']."', '".$_POST['']."')";
...
mysqli_multi_query($conn, $sql);
?>
</code></pre>
| <javascript><php><jquery><mysqli> | 2019-03-11 22:53:55 | LQ_CLOSE |
55,112,065 | http GET command in pyhton | I really need some help. Im new in python and programming.
Im trying to run an experiment in Open Sesame and get some data from Neulog device. Neulog gives me the API option to interact with the device. The API is based on HTTP protocol so my question is:
how does the python code needs to look contact the NeuLog API via the http “GET” command? | <python> | 2019-03-11 23:50:57 | LQ_EDIT |
55,113,360 | Daily notification on xamarin c# | <p>What is the best way to give the user an option to select time in the day in app and then they will receive a repeated notification on their phone at that time every day. I know there is a way to push notifications with app center and firebase but I just wanted to see if there is an easy way to set up repeated daily notifications with xamarin whether thats with forms or separate for ios and android and let the user choose when. Please let me know if there is a guide, tutorial, or anything I can use for this. I have experience with c# but I am fairly new to xamarin, so I appreciate any help.</p>
<p>Thank you!</p>
| <c#><xamarin.forms><xamarin.ios> | 2019-03-12 02:45:27 | LQ_CLOSE |
55,114,112 | Golang : passing int[] to function but function returning empty array | I am passing in a string array and an empty integer array into a function. The point of the function is to convert each element of the string array to an integer and store that into the integer array. When I print the integer array from within the function itself, everything is fine. However, when I try to print the integer array outside of the function, it prints an empty array.
`employeeDataInt` is the integer array, and `employeeDataString` is the string array.
I apologize if this is a dumb question but I am new to go. Thanks
package main
import (
"fmt"
"os"
"log"
"strings"
"bufio"
"strconv"
)
func strToInt(employeeDataString []string, emplyoeeDataInt[]int) []int{
for _, i := range employeeDataString[2:] {
j, err := strconv.Atoi(i)
if err != nil {
panic(err)
}
employeeDataInt = append(employeeDataInt, j)
fmt.Println(employeeDataInt) //this prints out the appropriate array
}
return employeeDataInt;
}
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter file name: ")
fileName, err := reader.ReadString('\n')
if err != nil {
log.Fatalf("failed opening file: %s", err)
}
fileName = strings.TrimSuffix(fileName, "\n")
file, err := os.Open(fileName)
scanner := bufio.NewScanner(file)
scanner.Split(bufio.ScanLines)
var employeeLine []string
for scanner.Scan() {
employeeLine = append(employeeLine, scanner.Text())
}
file.Close()
var employeeDataString = []int{}
for _, employee := range employeeLine {
employeeDataString := strings.Split(employee, " ")
strToInt(employeeDataString, employeeDataInt)
fmt.Println(playerData2) //this is outputting just `[]`
}
} | <arrays><go> | 2019-03-12 04:20:50 | LQ_EDIT |
55,117,115 | Neo4j: How to match realtionship? | For example:
I know a person A who is connected to another person B
and person B is connected to person C
How can i show that person A is indirectly connected to person C?
| <database><facebook-graph-api><graph><neo4j><graph-databases> | 2019-03-12 08:35:16 | LQ_EDIT |
55,117,549 | What is the simplest way to make a button press to start a method repeatedly (infinite time) in JavaFX? | <p>It would be nice, if I could use a simple timer (seconds or milliseconds) for the repeated method invocation. </p>
<p>If it is possible, I would use another button to stop this method if necessary.</p>
<pre><code>@FXML
private void handleinfiniteActionButton(ActionEvent event) {
methodToRunInfiniteTime();
}
</code></pre>
| <java><button><javafx> | 2019-03-12 09:01:19 | LQ_CLOSE |
55,120,006 | Write in a txt file in PYTHON with class name which varie (0 to N) | I have a class name myClass which contain some attributes (attribute0, attibute1...).
I have create N myClass (myClass0, myClass1...).
To write in a .txt file myClass0.attribute0:
fichier = open("myFile.txt", "a")
fichier.write("{}".format(myClass0.attribute0))
I want to write in the file myFile.txt myClassN.attribute0 with N for 0 to 9:
fichier = open("myFile.txt", "a")
fichier.write("{}".format(myClass0.attribute0))
fichier.write("{}".format(myClass1.attribute0))
.
.
.
fichier.write("{}".format(myClass9.attribute0))
How to do it in a loop ?
Thanks a lot. | <python> | 2019-03-12 11:06:36 | LQ_EDIT |
55,123,264 | How to get time and date after certain milliseconds in moment.js? | <p><strong>Problem Statement:</strong>
I am trying to get the time and date after certain milliseconds using moment.js
<strong>Example:</strong> </p>
<pre><code>const expiresIn = 30000 // milliseconds
const issuedAt = moment().toString();
const expiresAt = // I need to get the time and date after "expiresIn"(milliseconds) so i can set the "expiresAt" as time and date
</code></pre>
| <javascript><datetime><time><momentjs> | 2019-03-12 13:57:20 | LQ_CLOSE |
55,124,085 | scala replace if else with state pattern | here is my if statement code in scala:
def handle(): Unit = {
if (calculator.num == 0.0){
calculator.num = number
}
else{
calculator.num = calculator.num * 10 + number
}
}
How do I replace the if else with state pattern? | <scala><if-statement><state> | 2019-03-12 14:35:33 | LQ_EDIT |
55,124,128 | how to remove the particular string from the url and update it | <p>I want to remove the string from the url and update as it after the removal.</p>
<p>example: <code>www.abc.com/xyz</code></p>
<p>I need to remove xyz and update it as <code>www.abc.com</code></p>
<p>Thank you</p>
| <javascript><jquery> | 2019-03-12 14:37:42 | LQ_CLOSE |
55,125,252 | Prepared statement in PHP/HTML website doesn't write to database but works in php-myAdmin | I have to write a html/php News-Website where you can add news if you're logged in, the news get sent to a MySQL Database and from there I want them to be displayed on the website. The problem right now is that although my prepared statement is beeing executed and all the variables are filled with the right values, the data doesn't get written to the SQL table. I tried using the same query as the prepared statement but not as a prepared statement but with the values typed out and it worked perfectly. I am very confused an would love some help from you guys.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
<!DOCTYPE html>
<html>
<head>
<title>News hinzufügen</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<script src="https://cloud.tinymce.com/5/tinymce.min.js"></script>
<script>tinymce.init({ selector:'textarea' });</script>
</head>
<body>
<form action="add_news.php" method="POST" enctype="multipart/form-data">
<input type="text" name="title" placeholder="Titel" class="titlestyle" required="required">
<select name="kategorie" class="kategoriestyle">
<option value="1">Kategorie 1</option>
<option value="2">Kategorie 2</option>
<option value="3">Kategorie 3</option>
</select>
Gültig von <input type="date" name="vondate"> bis <input type="date" name="bisdate" required="required">
<textarea name="news" class="textareastyle" required="required">
</textarea>
<input type="file" name="imageUpload" id="imageUpload">
<input type="text" name="bildbeschreibung" placeholder="Beschreiben Sie Ihr Bild"> <br>
<input type="text" name="link" placeholder="Link">
<input type="text" name="linkbeschreibung" placeholder="Beschreiben Sie Ihren Link" > <br>
<input type="submit" name="submit" value="Fertigstellen" class="submitstyle">
</form>
</body>
</html>
<!-- end snippet -->
And here is the PHP-Code:
<?php session_start(); ?>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<?php
$dbserver = 'localhost';
$dbusername = 'root';
$dbpassword = '';
$dbname = 'm151db';
$titel = "";
$text = "";
$kategorie;
$vondatum = "";
$bidatum = "";
$bild = "";
$bildbeschr = "";
$link = "";
$linkbeschr = "";
$autor = $_SESSION["username"];
$error = "";
if (isset($_POST['submit'])) {
$conn = mysqli_connect($dbserver, $dbusername, $dbpassword, $dbname);
if ($conn->connect_error) {
die('Connection Error: Es gab ein Problem mit dem Verbindungsaufbau. ('.$conn->connect_errno.')'.$conn->connect_error);
}
$stmt = $conn->prepare("INSERT INTO news (name, beschreibung, kategorie_id, von, bis, bild, bildbeschreibung, link, linkbeschreibung, author) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("ssssssssss", $titel, $text, $kategorie, $vondatum, $bisdatum, $bild, $bildbeschr, $link, $linkbeschr, $autor);
if(isset($_POST['title'])) {
$titel = trim($_POST['title']);
echo "$titel";
}
if(isset($_POST['news'])) {
$text = trim($_POST['news']);
echo "$text";
}
if(isset($_POST['kategorie'])) {
$katerorie = $_POST['kategorie'];
echo "$kategorie";
}
if(isset($_POST['vondate'])) {
$vondatum = $_POST['vondate'];
echo "$vondatum";
}
if(isset($_POST['bisdate'])) {
$bisdatum = $_POST['bisdate'];
echo "$bisdatum";
}
if(isset($_POST['bildbeschreibung'])) {
$bildbeschr = trim($_POST['bildbeschreibung']);
echo "$bildbeschr";
}
if(isset($_POST['link'])) {
$link = trim($_POST['link']);
echo "$link";
}
if(isset($_POST['linkbeschreibung'])) {
$linkbeschr = trim($_POST['linkbeschreibung']);
echo "$linkbeschr";
}
if(isset($_FILES['imageUpload'])) {
echo "0";
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["imageUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
$check = getimagesize($_FILES["imageUpload"]["tmp_name"]);
if($check == true) {
$uploadOk = 1;
echo "1";
}
else { ?>
<div class="alertbox">
<span class="closebtn"onclick="this.parentElement.style.display='none';">×</span>
Es können nur Bilddateien hochgeladen werden.
</div>
<?php $uploadOk = 0;
}
if(file_exists($target_file)) { ?>
<div class="alertbox">
<span class="closebtn"onclick="this.parentElement.style.display='none';">×</span>
Dieses Bild wurde bereits hochgeladen.
</div>
<?php $uploadOk = 0;
}
if($_FILES["imageUpload"]["size"] > 500000) { ?>
<div class="alertbox">
<span class="closebtn"onclick="this.parentElement.style.display='none';">×</span>
Das Bild ist zu gross. Wähle ein Bild unter 500kb aus.
</div>
<?php $uploadOk = 0;
}
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg") { ?>
<div class="alertbox">
<span class="closebtn"onclick="this.parentElement.style.display='none';">×</span>
Wähle ein PNG-/JPG-/JPEG-Bild aus.
</div>
<?php $uploadOk = 0;
}
if($uploadOk == 0) { ?>
<div class="alertbox">
<span class="closebtn"onclick="this.parentElement.style.display='none';">×</span>
Es ist ein Fehler beim hochladen ihres Bildes aufgetreten. Versuchen sie es erneut.
</div>
<?php
}
else {
if(move_uploaded_file($_FILES["imageUpload"]["tmp_name"], $target_file)) {
//echo "The file has been uploaded.";
}
else { ?>
<div class="alertbox">
<span class="closebtn"onclick="this.parentElement.style.display='none';">×</span>
Es ist ein Fehler beim hochladen ihres Bildes aufgetreten. Versuchen sie es erneut.
</div>
<?php }
$bild = $target_file;
echo "$bild";
}
$stmt->execute();
if ($stmt == true) {
echo "stmt executed";
}
else {
echo "stmt not executed";
}
}
}
?>
PS: The echos are just checkpoints so that I see what was executed and what wasn't. | <php><mysql> | 2019-03-12 15:30:09 | LQ_EDIT |
55,126,546 | Random True or false using math.random | <p>How to return true or false, only using Math.random(), without creating a new method or using java.util.random?</p>
| <java><math><random><boolean> | 2019-03-12 16:37:38 | LQ_CLOSE |
55,126,805 | Get 2 Least Significant Bits from an uint16_t in C | I want to get the 2 least significant bits of an uint16_t(X) in C.
Example:
20544 = 0x5040
0x40 = 64
I tried, (X & ((1<<2) - 1)). This doesn't work for me. | <c><bit><lsb> | 2019-03-12 16:52:41 | LQ_EDIT |
55,127,356 | proc SQL SAS Basic | Hi all I want an answer for this,
the input i have is
ABC123
The output i want is 123ABC
how to print the output in this format (ie BackwardS) using Proc SQL??
Thanks in advance | <sas><proc-sql> | 2019-03-12 17:23:16 | LQ_EDIT |
55,127,632 | OVERLOADING IN INHERITANCE | So I came across this concept of overloading resolution while studying Dynamic programming but I am having trouble understanding this. The statement goes like this-
"If the compiler cannot find any method with matching parameter type or if multiple methods all match after applying conversions(casts) the compiler reports an error"
I tried verifying the statement with help of an example and it goes like following-
public class OverloadingResolution{
public static void main(String[] args){
ClassB b= new ClassB();
b.check(3);
ClassB c=new ClassC();
c.check(3)
}
}
class ClassA{
public void check(float a){
System.out.println("Inside ClassA----> value of a is"+a);
}
}
class ClassB extends ClassA{
public void check(float a){
System.out.println("Inside ClassB----> value of a is"+a);
}
}
class ClassC extends ClassB{
public void check(short a){
System.out.println("Inside ClassC----> value of a is"+a);
}
}
outcome was
Inside ClassB value--->value of a is 3.0
Inside ClassB value--->value of a is 3.0
My doubt is I expected a compile time error as
ClassB b= new ClassB();
b has multiple methods with matching paramters
| <java> | 2019-03-12 17:41:30 | LQ_EDIT |
55,129,809 | Are there any way to make implementation for abstact class which is multipely inheriting from other abstract classes in c++? | I have two 'interface' classes : AbstractAccess and AbstractPrint, and AbstractRun class inheriting from them and using their methods.
Also I have two implementation of interfaces: Accessor for AbstractAccess and Print for Abstract Print
#include <iostream>
using namespace std;
class AbstractAccess {
public:
virtual string access (void) = 0;
};
class AbstractPrint {
public:
virtual void print (string) = 0;
};
class AbstractRun : virtual public AbstractAccess, virtual public AbstractPrint {
public:
void run (void) {
print(access());
}
};
class Accessor : virtual public AbstractAccess {
public:
string access (void){
return name;
}
void setName(string name) {
this->name = name;
}
private:
string name;
};
class Print: public virtual AbstractPrint {
public:
void print (string s) {
cout << s << endl;
}
};
Are there any ways to cast interfaces in AbstractRun to their implementations or to create implementation class Run that will only use AbstractRun's 'run' method but with implemented interfaces?
| <c++><abstract-class><multiple-inheritance> | 2019-03-12 20:01:42 | LQ_EDIT |
55,133,656 | MS SQL SERVER MAX function on one column, return all columns | I'm using MS SQL Server and I'm trying to get the MAX of Res when Res is a varchar, and I want to group by pID, but also keep the aID in the final result.
aID | Res | pID
1 | Yes | 94 <br>
2 | Yes | 32 <br>
3 | No | 32 <br>
4 | Yes | 94
SELECT aID, max(Res), pID
FROM Table1
GROUP BY pID
My final result should be:
aID | Res | pID
1 | Yes | 94 <br>
2 | Yes | 32 <br>
or <br>
aID | Res | pID
4 | Yes | 94 <br>
2 | Yes | 32 <br>
The whole issue is that I can't include aID in the final result. I've tried a sub query where Res is = to max(Res), but with over 50,000 records, it's taking over 20 minutes to run this thing. There's got to be a better way. Is there? | <sql><sql-server><max><common-table-expression> | 2019-03-13 02:56:51 | LQ_EDIT |
55,136,375 | Converting Negative integer number into positive using if_abs | <p>After prompting a user to enter an integer and printing the absolute value of it, how do you convert a negative input integer into positive using if statements.</p>
| <python> | 2019-03-13 07:18:53 | LQ_CLOSE |
55,138,415 | On hover on the parent div, Change the color of all the child div as well as parent background color | <p>I need to change the button color and text color on hover on the parent div.</p>
<p>I am getting the output and on hover, I have to change the color.</p>
<p><a href="https://i.stack.imgur.com/GUbzh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GUbzh.png" alt="enter image description here"></a>
<a href="https://i.stack.imgur.com/dWmlX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dWmlX.png" alt="enter image description here"></a></p>
<p>Would you help me out?
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.Set {
background-color: #fff;
padding: 35px;
box-sizing: border-box;
min-height: 450px;
z-index: 2;
position: relative;
width: 300px;
border: 1px solid #ccc;
}
.btn {
padding: 10px 30px;
font-size: 16px;
}
.btn_bg {
background-color: #000;
color: #fff;
}
.Set:hover {
background-color: #000;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="Set">
<h2 class="textMe">adasdsad asdas d</h2>
<div class="bigtextMe">
<p>asdsa asdsd asd asd sd sd sd </p>
<a href="" class="btn btn_bg">njkndkajnsdkja</a>
</div></code></pre>
</div>
</div>
</p>
| <html><css> | 2019-03-13 09:32:07 | LQ_CLOSE |
55,139,180 | Target parent li only not child with css | <p>I want to target the parent li, not the child li with css selecter only.</p>
<pre><code><ul>
<li>{Target the li of this ul only}</li>
<li>{Target the li of this ul only}</li>
<li>
<ul>
<li>{it would be different styling}</li>
<li>{it would be different styling}</li>
<li>{it would be different styling}</li>
</ul>
</li>
</ul>
</code></pre>
| <css><css-selectors> | 2019-03-13 10:07:20 | LQ_CLOSE |
55,139,328 | Optional value returning nil with ?? operator | <p>I'm trying to convert an optional string to a Double, but when I unwrap my value is not taken:</p>
<pre><code>let currentSwimDistanceTravelled = defaults.string(forKey: "SwimTotal") ?? "0.0"
</code></pre>
<p>After this code is run currentSwimDistanceTravelled is assigned a String value of "" as opposed to "0.0".</p>
<p>Sorry if I've missed something basic here, but I thought ?? was the best way to unwrap an optional.</p>
| <swift> | 2019-03-13 10:14:40 | LQ_CLOSE |
55,140,126 | swift 4 multiple picker view not working? |
##
1. multiple picker views are not showing the data in the picker view in swift 4, I already read many tutorials but no one solve my problem please check and answer me.
2.when I implemented 3 picker views the data is showing only of the first picker view i.e , (strblood) but not the other arrays
----------
the code below is working properly but there is one error regarding showing the array in the picker view when clciked on the other labels ("lblblood"."lblcountry")
##
------------------------------------------------------------------------
** *
import UIKit
import Foundation
class RegisterViewController: UIViewController {
var strBlood = ["O+","O-","O","A","B+"]
var strcountry = ["India","Canada","USA"]
var strgender = ["Male","Female"]
var selectedBlood: String?
var selectedCountry: String?
var selectedGender: String?
@IBOutlet weak var txtGender: UITextField!
@IBOutlet weak var txtCountry: UITextField!
@IBOutlet weak var lblBloodGroup: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
self.chooseCountry()
self.chooseBlood()
self.choosGender()
}
func chooseBlood(){
let bloodPicker = UIPickerView()
bloodPicker.delegate = self
self.lblBloodGroup.inputView = bloodPicker
}
func chooseCountry(){
let countryname = UIPickerView()
countryname.delegate = self
self.txtCountry.inputView = countryname
}
func choosGender() {
let gender1 = UIPickerView()
gender1.delegate = self
self.txtGender.inputView = gender1
}
}
extension RegisterViewController : UIPickerViewDelegate , UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if lblBloodGroup.isEnabled {
print("BLOOD SELECTED")
return strBlood.count
}
else if txtCountry.isEnabled{
print("COUNTRY SELECTED")
return strcountry.count
}else {
print("GENDER SELECTED")
return strgender.count
}
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if lblBloodGroup.isEnabled{
print("BLOOD SELECTED1")
return strBlood[row]
}else if txtCountry.isEnabled{
return strcountry[row]
}else {
return strgender[row]
}
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if lblBloodGroup.isEnabled{
selectedBlood = strBlood[row]
lblBloodGroup.text = selectedBlood
}else if txtCountry.isEnabled{
selectedCountry = strcountry[row]
txtCountry.text = selectedCountry
}else {
selectedGender = strgender[row]
txtGender.text = selectedGender
}
}
} | <ios><swift><uipickerview> | 2019-03-13 10:52:17 | LQ_EDIT |
55,140,475 | Ruby simple bar graph challenge using arrays | I am really new to Ruby and am trying to solve the following challenge, which is to create a simple bar graph program using Ruby:
[Challenge picture][1]
[1]: https://i.stack.imgur.com/y6h3i.png
This is a challenge that comes as part of a tutorial on Arrays, so I think that the aim is to use an array. My thinking is to convert the user's input into an array, iterate over each number and print the corresponding number of dashes for each number. I can't work out how to do this however. Any advice would be appreciated.
Thanks :)
| <arrays><ruby> | 2019-03-13 11:09:19 | LQ_EDIT |
55,142,131 | how to remove lines in OpenCV | I want to remove lines and keypoints. I just want to remain a green rectangular.
Is there a function except for drawMatches or can I make lines and keypoints invisible in drawMatches?
Mat img_matches;
drawMatches( img_object, keypoints_object, img_scene, keypoints_scene,
good_matches, img_matches, Scalar::all(-1), Scalar::all(-1),
std::vector<char>(), DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS );
[![A picture][1]][1]
[1]: https://i.stack.imgur.com/srZni.jpg | <c++><opencv> | 2019-03-13 12:38:18 | LQ_EDIT |
55,145,555 | vba quarterly retuns | Can anybody tell me a VBA Function or button that would calculate quarterly returns only on a quarterly basis (i.e., first quarter return is based on January till March returns) without overlapping observations. The function that I'm using now is just the AVERAGE of, for example, returns from January until March, but the actual calculation cell is in April. An example of what I'm asking is in the picture link. I would like the function to run for the time period that I choose.
https://i.stack.imgur.com/dw0BU.png
Thank you very much!
| <excel><vba><finance> | 2019-03-13 15:28:01 | LQ_EDIT |
55,146,338 | Empty new template iOS single view project crashes due to basic layout constraints? | I created a new iOS project based off of Xcode's Single View iOS app template and was very surprised to find that adding a label and 4 basic constraints for the top, right, bottom, left position results in an immediate launch crash.
There is literally nothing else in the project, it is empty, I'm curious what is going on, has anyone else experienced something like this or am I missing something obvious?
`Assertion failure in -[UIView _nsis_center:bounds:inEngine:forLayoutGuide:],
/BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKitCore_Sim/UIKit-3698.93.8/NSLayoutConstraint_UIKitAdditions.m:3588
2019-03-13 09:59:07.873433-0600 test[5480:349128]
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException',
reason: 'Error in compatibility flow'`
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/e9Goh.png | <ios><xcode><autolayout> | 2019-03-13 16:05:11 | LQ_EDIT |
55,146,819 | How to find degree on a circle that is tangent to a point outside of that circle? | - I know the (x,y) of a point, P, outside of a circle.
- I know the (x,y) for the origin of a circle, O.
- I know the radius, r, of that circle.
How would I find what degree (i.e. 20 degrees, 270 degrees) is tangent to the point outside of the circle ?
[click here for an image][1]
[1]: https://i.stack.imgur.com/eVbc1.png
Many thanks in advance!
-joe | <geometry><trigonometry><point> | 2019-03-13 16:29:40 | LQ_EDIT |
55,147,542 | WINDOWS API: GetCurrentThread(); in C | <p>I just started my college "adventures", and one of them is subject called operating systems. I must admit that the subject is the most boring ever. Last week, we got our first homework, and i do not know what to do as this is the first time ever i come up with Windows API functions or this topic in general. The task is very simple, we need to write very basic code in C that shows how does GetCurrentThread() work!!!???? I tried looking for solution online, but I could not find anything and our professor is not doing anything to help us. I found the use of functions like GetCurrentThreadID() but that is not what i need. Can somebody write simple program ( 20-30 lines of code ) which contains the use of this function (in C)?</p>
| <windows><operating-system> | 2019-03-13 17:05:11 | LQ_CLOSE |
55,148,648 | Why the if statment will not run? | So I am trying to make a chess game (The board is 64 buttons) and I need to check if the button that was first pressed is a certain button but for some reason the code in the if will not run.
public void button_click(object sender, EventArgs e)
{
if (partOfTurn == false)
{
//code
previousButton = (Button)sender;
partOfTurn = true;
}
else if (partOfTurn == true)
{
//code
click();
partOfTurn = false;
}
void click()
{
if (turn == true)
{
if (previousButton.BackgroundImage == Properties.Resources.White_Pown)
{
//unreachable code
}
}
}
} | <c#> | 2019-03-13 18:09:38 | LQ_EDIT |
55,149,627 | Multiple android apps | <p>I need to make around 1000 android apps with same code base but different names, logos, splash screens,images . using android library will solve the issue? One google developer account is sufficient? </p>
| <android> | 2019-03-13 19:13:37 | LQ_CLOSE |
55,150,161 | Python: My for loop gets a syntax error after 1 cycle inside of loop | I am in a low-level coding class, and I have to create a program where the user enters an integer. The program then runs a series of loops to determine the smallest and largest values of the series entered by the user as well as the count of even and odd numbers entered by the user, while also keeping a running total of all integers that have been entered. A blank line entered tells the program to stop and outputs the previously stated information. As the question states, I am not sure how to fix the syntax error after the program enters the loop and runs one cycle. Here is the code so far:
counte=0
counto=0
sum=0
num=(input("Enter an integer (blank line to quit):"))
max=0
min=0
value=0
if(num==''):
print("No input values were provided.\nQuitting the program!!!")
while (num!=''):
value=int(input("Enter an integer (blank line to quit):"))
if(num%2==0):
counte+=1
else:
counto+=1
sum+=value
if(value>max):
max=value
if(value<min):
min=value
num=int(input("Enter an integer (blank line to quit:"))
print("The smallest value is",min, "and the larges value is",max,".")
print("The user entered",counte,"even, and",counto,"odd values.")
print("The cumulative total is",total,".")
The syntax error that I am returned when running the program is:
Traceback (most recent call last):
File "*sensitive information*", line 12, in <module>
if(num%2==0):
TypeError: not all arguments converted during string formatting | <python> | 2019-03-13 19:50:54 | LQ_EDIT |
55,150,939 | Laravel find all data from child_category table using Eloquent ORM with related category & subcategory name? | I have three table:
category
subcategory
child_category
need all data from child_category table using Eloquent ORM with related category & subcategory name.
| <laravel><eloquent><eloquent--relationship><laravel-datatables> | 2019-03-13 20:45:47 | LQ_EDIT |
55,151,688 | How to sort an array that includes NaN's C++ | Have been trying to implement my code as a means to sort all integers including NaNs. However can not seem to find a function that would sort NaNs into my program. Code is able to sort other integers including infinities, however when a nan is entered the program recognizes the input but does not sort it to the start of the list. Any help would be appreciated.
#include <stdio.h>
#include <math.h>
int main()
{
float array[100], swap;
int c, d, n;
printf("Enter the size of array\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%f", &array[c]);
for (c = 0; c < (n - 1); c++)
{
for (d = 0; d < n - c - 1; d++)
{
if (array[d] > array[d + 1])
{
swap = array[d];
array[d] = array[d + 1];
array[d + 1] = swap;
}
}
}
printf("Sorted array in ascending order:\n");
for (c = 0; c < n; c++)
printf("%f\n", array[c]);
return 0;
} | <c><nan><bubble-sort> | 2019-03-13 21:47:39 | LQ_EDIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.