Friday, July 16, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


How do I break the while statement?(java)

Posted: 16 Jul 2021 08:41 AM PDT

So this program asks for different areas of shapes, and it was requested that the user be able to control whether they want the program to continue or stop. I created an if statement, within the while loop that if the user entered "stop" the program would break. However, after testing the program is continuing to run. How do I break the while loop?

import java.util.Scanner;  public class assignmentu3b {  static int area;  static String stop;      public static void main(String[]args) {      Scanner sc=new Scanner(System.in);      System.out.println("Would you like to find the area of a rectangle,circle or triangle");      String inp=sc.next();      inp.toLowerCase();      while(true) {          System.out.println("Enter stop, to leave the program, or anythinng else to continue, the program will run once.");          stop=sc.next();          stop.toLowerCase();          if(stop=="stop") {              break;          }      switch(inp) {      case "circle":          area=circle(area);          System.out.println("The area of the circle is "+area);          break;      case "rectangle":          area=rectangle(area, area);          System.out.println("The area of the rectangle is "+area);      break;      case "triangle":          area=triangle(area, area);          System.out.println("The area of the triangle is "+area);          break;          default:              System.out.println("You didn't enter a shape");      }        }  }    public static int circle(int radius) {      Scanner sc= new Scanner(System.in);      System.out.println("Enter a radius:");      radius=sc.nextInt();      return (int) (Math.PI*Math.pow(radius,2));        }  public static int rectangle(int lenght,int width) {      Scanner sc= new Scanner(System.in);      System.out.println("Enter a lenght and width");      lenght=sc.nextInt();      width=sc.nextInt();      return lenght*width;  }    public static int triangle(int base,int height) {      Scanner sc= new Scanner(System.in);      System.out.println("Enter a base and height");      base=sc.nextInt();      height=sc.nextInt();      return (base*height)/2;        }  

}

Is there a way to calculate incremental area under the curve for each id subject?

Posted: 16 Jul 2021 08:41 AM PDT

I'm working in R and i'm trying to generate a data.frame with the incremental area under the curve of glucose values above baseline for each subject id (ID). In particular my dataset is like that:

ID  glucose Time  101 100     0  102 70      0  103 60      0  101 50      0.5  102 85      0.5  103 70      0.5  101 55      1  102 69      1  103 96      1  

I'm using the function by Brouns et al (2005):

    auc.fn <- function(x,y) {      auc <- ifelse(y[2] > y[1], (y[2]-y[1])*(x[2]-x[1])/2, 0)      seg.type <- 0      for (i in 3:length(x)) {          if (y[i] >= y[1] & y[i-1] >= y[1]) {              auc[i-1] <- (((y[i]-y[1])/2) + (y[i-1]-y[1])/2) * (x[i]-x[i-1])/2              seg.type[i-1] <- 1          } else if (y[i] >= y[1] & y[i-1] < y[1]) {              auc[i-1] <- ((y[i]-y[1])^2/(y[i]-y[i-1])) * (x[i]-x[i-1])/2              seg.type[i-1] <- 2          } else if (y[i] < y[1] & y[i-1] >= y[1]) {              auc[i-1] <- ((y[i-1]-y[1])^2/(y[i-1]-y[i])) * (x[i]-x[i-1])/2              seg.type[i-1] <- 3          } else if (y[i] < y[1] & y[i-1] < y[1]) {              auc[i-1] <- 0              seg.type[i-1] <- 4          } else {              # The above cases are exhaustive, so this should never happpen              return(cat("i:", i, "Error: No condition met\n"))          }      }      return(list(auc=sum(auc), segments=auc, seg.type=seg.type))  }  

However, this function returns only the whole AUC value. How can i change the function in order to have for each id subject an AUC value? Many thanks

Use explode on array?

Posted: 16 Jul 2021 08:41 AM PDT

What's the easiest way to turn the array

[      0 => "3.1"      1 => "2.1"  ]  

into

[      ['tag_id' => 3, 'contact_id' => 1],      ['tag_id' => 2, 'contact_id' => 1]  ]  

Is there something built-in with laravel/collections that I can use?

How can I loop this to run every 5 seconds?

Posted: 16 Jul 2021 08:41 AM PDT

I am not a programmer; I just found this code in a youtube video and I just want to spam my friend Here is the code:

time.sleep(10)  f = open("Noobovi ste", 'r')  for word in f:  pyautogui.typewrite(word)  pyautogui.press("enter")```      

Convert an array of object to a matrix javascript

Posted: 16 Jul 2021 08:40 AM PDT

I try to convert array of objects to a matrix of values.

I have tried:

var arrData = data.map(row => Object.keys(row).map(function(key){return row[key]}));  

but I get a syntax error.

How to record page loading time by click the link in page

Posted: 16 Jul 2021 08:40 AM PDT

I'm looking for a way to record page switching/loading time by clicking the hyperlink in another page, in chrome only

So lets say, I have added page B's hyperlink in page A, now I want to know how many seconds it takes from clicking the hyperlink to finishing loading page A.

I'm playing around development tool - performance tab but looks like it will not record the time across different tabs/ windows.

I've been tasked with finding out why our once successful outlook signature script is now throwing an "Invalid Outside Procedure Error" Please advise

Posted: 16 Jul 2021 08:40 AM PDT

When I try to run this code I get an error message that states "invalid outside procedure" Is there an issue with my format; is it too dated? I do not know how to proceed.

'''  On Error Resume Next    Const RTF = "6"  Const Text = "4"  Const HTML = "8"    'declare    Dim qQuery, objSysInfo, objuser  Dim FullName, PhoneNumber, MobileNumber, FaxNumber, Department  Dim web_address, FolderLocation, HTMFileString, StreetAddress, County, Company, Country  Dim UserDataPath, mail  Dim cert, vet    'check AD    Set objSysInfo = CreateObject("ADSystemInfo")  objSysInfo.RefreshSchemaCache  qQuery = "LDAP://" & objSysInfo.Username  Set objuser = GetObject(qQuery)    'Retrieve    SPACE = ""  cert = 0  vet = 0  

'''

How return "true" or "false" after checking if an element exists in a JSON file?

Posted: 16 Jul 2021 08:41 AM PDT

I have this function in my JavaScript file

function checkFrom(rootItems){      fetch("./../../../data_dragon/11.10.1/data/en_US/item.json")      .then(response => response.json())      .then(function(data){          const itemlist=data.data          console.log(itemlist[rootItems[0]])          for(const Item in rootItems){              if(typeof itemlist[Item].from != undefined){                  return true              }          }          return false      })  }  

The problem is that the two statements where I return "true" or "false" returns it for the function used to interact with the JSON file I use and not for the "checkFrom" function. So my question is how can I make it return the Boolean for this "checkFrom" function ? I tried to set the data of the JSON as a global variable (as var, const or let) but when I try to use this variable it's undefined.

Checking if all non-NA elements between two or more columns or vectors are identical

Posted: 16 Jul 2021 08:40 AM PDT

I have two columns in a dataframe that contain date information after a left outer join. Because of the style of join, one of the date columns now contains NAs. I want to check if all non-NA values are identical between these columns. An example is below:

date 1     date 2  1/1/21     NA   1/2/21     1/2/21  1/3/21     NA  1/4/21     1/4/21  

I don't need the second column if all non-NA values match

Before I did the left outer join, I did a outer join and this statement:

identical(df[['date 1']], df[['date 2']])  

returned a true

Is there a way to use this or a similar statement with just ignoring all rows that contain an "NA" in "date 2"?

Can anyone explain why the program is returning this error ?? The Process returned -1073741819 (0xC0000005)

Posted: 16 Jul 2021 08:40 AM PDT

Can anyone explain why the program is returning this error ?? (The Process returned -1073741819 (0xC0000005) )

#include <stdio.h>    void main()  {      void what(int A[])      {          int i=0,j=0; int temp=0;          for(int i=1;i<5;i++)          {              j=i-1;              while(j>=0 && A[j]>A[j+1])              {                  temp=A[j];                  A[j]=A[j+1];                  A[j+1]=temp;                  j+j-1;              }          }          for(int k=0;k<=4;k++)              printf(A[k]);      }      int S[5]={20,10,20,30,15};      what(S);  }  

Calculations on multiindex dataframe

Posted: 16 Jul 2021 08:40 AM PDT

I have a dataframe like this:

enter image description here

I would like to calculate the percent_change() in prices for each coin subset of data. Applying the below formula returns a value for row 1534 and I would like it to be 0 (as the coin identifier changes):

df['prices'].pct_change()

I would also like to run other rolling calculation functions on the data, so just replacing the odd value by 0 is not an option in this case.

thanks

Array initialization differences C++11

Posted: 16 Jul 2021 08:40 AM PDT

Is there a difference between using curly braces or the assignment operator while defining an array in C++11?

std::array<int, 2> a{1, 2}  // or  std::array<int, 2> b{{1, 2}}  

and

std::array<int, 2> = a{1, 2}  

How to connect to MongoDB standalone cluster from a different device on the internet?

Posted: 16 Jul 2021 08:40 AM PDT

So I have setup a MongoDB server on a PC and it is currently a standalone cluster, However I would like to connect to this data base from a different device over the internet. I am using MongoDB's Java driver to connect from the other device to the database, but it fails to connect. Is there anyway to configure the database so anyone with proper credentials could connect. I am struggling to find documentation on how to do this. Any help is appreciated, Thanks.

enter image description here

ScrollTo on click not scrolling to the correct list item

Posted: 16 Jul 2021 08:41 AM PDT

I have an SVG map and a list where if you click on a plot number on the map it highlights on the list.

As there are quite a few items, when you click on a plot number on the map its supposed to scroll the list on the right to the correct item.

However as you start clicking around on all different numbers you can see the scroll breaks and it no longer scrolls to the correct number.

Codepen here.

JS Code below:

$('.plot__list__item').click(function () {      $(this).toggleClass('selected');      $(this).siblings('li').removeClass('selected');      $('#' + $(this).data('map')).toggleClass('selected');      $('#' + $(this).data('map')).siblings('g').removeClass('selected');  });    $('.plot__map__item').click(function () {      $(this).toggleClass('selected');      $(this).siblings('g').removeClass('selected');      $('#' + $(this).data('list')).toggleClass('selected');      $('#' + $(this).data('list')).siblings('li').removeClass('selected');  });    $('.plot__map__item').click(function () {      let id = $(this).data('list');      let scrollPos = $('#' + id).position().top;      $('.plot__list').animate({          scrollTop: scrollPos      }, 400);  });  

User created instance

Posted: 16 Jul 2021 08:41 AM PDT

I am trying to complete a homework assignment about python classes that has a few requirements: Your program will prompt the user to create at least one object of each type (Car and Pickup). Using a menu system and capturing user input your program will allow the user the choice of adding a car or pickup truck and define the vehicle's attributes. The program will use user input to define the vehicle's attributes.

The options attribute in the parent class must be a python list containing a minimum of eight (8) options common to all vehicles.

The user will choose from a list of options to add to the vehicle's options list and must choose a minimum of one vehicle option per vehicle. When the user is finished adding vehicles to their virtual garage the program will output the vehicles in their garage and their attributes.

I haven't started on the child classes yet because I want to make sure the parent class works as needed before adding more.

My program kind of works but I have to create the instance manually.

My question is, how do I make a user-inputted instance so that I can make repeat entries?

class Vehicle:        def __init__(self, make, model, color, fuelType,options):          self.make = make          self.model = model          self.color = color          self.fuelType = fuelType          self.options = options                    def getMake(self):          self.make = input('Please enter the vehicle make: ')                  def getModel(self):          self.model = input('Please enter the vehicle model: ')                  def getColor(self):          self.color = input('Please enter the vehicle color: ')                  def getFuelType(self):          self.fuelType = input('Please enter the vehicle fuel type: ')                  def getOptions(self):          optionslist = []          print('\nEnter Y or N for the following options')          radio = input('Does your vehicle have a radio: ').lower()          bluetooth = input('Does your vehicle have bluetooth: ').lower()          cruise = input('Does your vehicle have cruise control: ').lower()          window = input('Does your vehicle have power windows: ').lower()          lock = input('Does your vehicle have power locks: ').lower()          mirror = input('Does your vehicle have power mirrors: ').lower()          rstart = input('Does your vehicle have remote start: ').lower()          bcamera = input('Does your vehicle have a back up camera: ').lower()            if radio == 'y':              optionslist.append('Radio')          if bluetooth == 'y':              optionslist.append('Bluetooth')          if cruise == 'y':              optionslist.append('Cruise Control')          if window == 'y':              optionslist.append('Power Windows')          if lock == 'y':              optionslist.append('Power Locks')          if mirror == 'y':              optionslist.append('Power Mirrors')          if rstart == 'y':              optionslist.append('Remote Start')          if bcamera == 'y':              optionslist.append('Backup Camera')            self.options = optionslist          #creates instance  selection1 = Vehicle('n','n','n','n','n')      Vehicle.getMake(selection1)  Vehicle.getModel(selection1)  Vehicle.getColor(selection1)  Vehicle.getFuelType(selection1)  Vehicle.getOptions(selection1)    #makes sure options list has at least one option  if not selection1.options:      print('\nYou need to select at least one option.')      Vehicle.getOptions(selection1)      print(f'Your vehicle is a {selection1.color} {selection1.make} {selection1.model} that runs on {selection1.fuelType}. The options are ' + ", ".join(selection1.options) +'.')      Outputs:  Please enter the vehicle make: ford  Please enter the vehicle model: f150  Please enter the vehicle color: grey  Please enter the vehicle fuel type: gas    Enter Y or N for the following options  Does your vehicle have a radio: y  Does your vehicle have bluetooth: y  Does your vehicle have cruise control: y  Does your vehicle have power windows: y  Does your vehicle have power locks: y  Does your vehicle have power mirrors: n  Does your vehicle have remote start: n  Does your vehicle have a back up camera: n  Your vehicle is a grey ford f150 that runs on gas. The options are Radio, Bluetooth, Cruise Control, Power Windows, Power Locks.  

I get this error when trying to run the app [closed]

Posted: 16 Jul 2021 08:40 AM PDT

I get this error when trying to run the app

Error: MissingPluginException(No implementation found for method getDatabasesPath on channel com.tekartik.sqflite) at Object.throw_ [as throw] (http://localhost:60709/dart_sdk.js:5041:11) at MethodChannel._invokeMethod (http://localhost:60709/packages/flutter/src/services/system_channels.dart.lib.js:943:21) at _invokeMethod.next () at http://localhost:60709/dart_sdk.js:37403:33 at _RootZone.runUnary (http://localhost:60709/dart_sdk.js:37274:59) at _FutureListener.thenAwait.handleValue (http://localhost:60709/dart_sdk.js:32530:29) at handleValueCallback (http://localhost:60709/dart_sdk.js:33057:49) at Function._propagateToListeners (http://localhost:60709/dart_sdk.js:33095:17) at _Future.new.[_completeWithValue] (http://localhost:60709/dart_sdk.js:32943:23) at async._AsyncCallbackEntry.new.callback (http://localhost:60709/dart_sdk.js:32964:35) at Object._microtaskLoop (http://localhost:60709/dart_sdk.js:37526:13) at _startMicrotaskLoop (http://localhost:60709/dart_sdk.js:37532:13) at http://localhost:60709/dart_sdk.js:33303:9

code : https://codeshare.io/zyy01D

jQuery form validation with checkbox / radio

Posted: 16 Jul 2021 08:40 AM PDT

The code is not working well at all. Where is the problem?

I want the Required Fields to show an error message when I click the Submit button (if there is no value in the checkbox). But if there is a value in the requested field, the error message will be hidden.

It's not working at all. I want to fix this by keeping my HTML structure straight.

$('form.trexcterc').on('submit', function () {    $('.checkbox_required').parent().next('.error').remove();   if (!$('.checkbox_required input[required')){      if (!$('.checkbox_required input:checkbox').is(':checked') || !$('.checkbox_required input:radio').is(':checked')) {    $(".checkbox_required").parent().after("<span class='error'>error message..</span>");    }   }  });
.trexcterc {    width: 100%;    margin: 0 auto;    padding: 0 30px;  }    .form_item label {    width: 100%;    }    .checkbox_heading {    margin: 0;  }    .checkbox_item{    display: flex;    margin: 15px 0;  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>      <form class="trexcterc">    <div class="form_item" id="form_item_checkbox" data-type="checkbox-group">      <!-- Checkbox Group 1 -->    <label for="after_shot" class="checkbox_heading">After Shot<span class="required_sign">*</span></label>      <div class="checkbox-group checkbox-inline checkbox_required ">        <div class="checkbox_item">        <input type="checkbox" name="checkbox-one" id="checkbox-one" class="" value="Item One" required="required" />                      <label for="checkbox-one"><span class="check_mark"></span>Item One</label>      </div>        <div class="checkbox_item">        <input type="checkbox" name="checkbox-two" id="checkbox-two" class="" value="Item Two" required="required" />                      <label for="checkbox-two"><span class="check_mark"></span>Item One</label>      </div>        <div class="checkbox_item">        <input type="checkbox" name="checkbox-three" id="checkbox-three" class="" value="Item Three" required="required" />                      <label for="checkbox-three"><span class="check_mark"></span>Item One</label>      </div>    </div>      <!-- Checkbox Group 2 -->    <div class="checkbox-group checkbox-inline checkbox_required ">        <label for="after_shot" class="checkbox_heading">Before Shot<span class="required_sign">*</span></label>        <div class="checkbox_item">        <input type="checkbox" name="checkbox-item-one" id="checkbox-item-one" class="" value="Item One" required="required" />                      <label for="checkbox-one"><span class="check_mark"></span>Item One</label>      </div>        <div class="checkbox_item">        <input type="checkbox" name="checkbox-two" id="checkbox-two" class="" value="Item Two" required="required" />                      <label for="checkbox-two"><span class="check_mark"></span>Item One</label>      </div>    </div>    </div>    <input type="submit" name="submit" value="submit" />    </form>

SAP table structure to proceed passing by table by XML

Posted: 16 Jul 2021 08:41 AM PDT

I've created Logic App in Azure which has some json data inside. I'd like to connect to SAP system and pass parameters to an ABAP Function Module via RFC.
Let me show you json file:

{    "InvoiceId": "WZ",    "InvoiceTotal": "34 656,60",    "Items": [      {        "type": "object",        "valueObject": {          "Description": {            "type": "string",            "valueString": "Rumen Yeast- metabolity drożdży dla przeżuwaczy",            "text": "Rumen Yeast- metabolity drożdży dla przeżuwaczy",            "boundingBox": [              0.7517,              3.9638,              2.0147,              3.9697,              2.0136,              4.2193,              0.7505,              4.2134            ],            "page": 1,            "confidence": 0.296,            "elements": [              "#/readResults/0/lines/35/words/0",              "#/readResults/0/lines/35/words/1",              "#/readResults/0/lines/35/words/2",              "#/readResults/0/lines/45/words/0",              "#/readResults/0/lines/45/words/1",              "#/readResults/0/lines/45/words/2"            ]          }        },        "text": "1 Rumen Yeast- metabolity 10.89.13.0 600,000 kg 11,59 23 6 954,00 1 599,42 8 553,42 LRMN1218 drożdży dla przeżuwaczy",        "boundingBox": [          0.4372,          3.95,          7.3096,          3.95,          7.3096,          4.2153,          0.4372,          4.2153        ],        "page": 1,        "confidence": 0.464,        "elements": [          "#/readResults/0/lines/34/words/0",          "#/readResults/0/lines/35/words/0",          "#/readResults/0/lines/35/words/1",          "#/readResults/0/lines/35/words/2",          "#/readResults/0/lines/36/words/0",          "#/readResults/0/lines/37/words/0",          "#/readResults/0/lines/38/words/0",          "#/readResults/0/lines/39/words/0",          "#/readResults/0/lines/40/words/0",          "#/readResults/0/lines/41/words/0",          "#/readResults/0/lines/41/words/1",          "#/readResults/0/lines/42/words/0",          "#/readResults/0/lines/42/words/1",          "#/readResults/0/lines/43/words/0",          "#/readResults/0/lines/43/words/1",          "#/readResults/0/lines/44/words/0",          "#/readResults/0/lines/45/words/0",          "#/readResults/0/lines/45/words/1",          "#/readResults/0/lines/45/words/2"        ]      },      ..... (other items)     ],     "TotalTax": null,  }  

RFC input parameters in XML:

<?xml version="1.0" encoding="utf-8"?>  <ZFM_MGR_RFC xmlns="http://Microsoft.LobServices.Sap/2007/03/Rfc/">     <INVOICE_ID>@{outputs('Faktura')['InvoiceId']}</INVOICE_ID>     <INVOICE_TOTAL>@{outputs('Faktura')['InvoiceTotal']}</INVOICE_TOTAL>     <ITEMS>@{outputs('Faktura')['Items']}</ITEMS>     <TOTAL_TAX>@{outputs('Faktura')['TotalTax']}</TOTAL_TAX>  </ZFM_MGR_RFC>    

I need to create a structure and table type in ABAP which will work with this data. Does anybody has an idea how can I deal with it?

Thanks in advance.

SQL window function and running total

Posted: 16 Jul 2021 08:40 AM PDT

I'm learning SQL and want to understand the window function better.

Let's say I have a set of data for a bank account containing:

  1. Latest balance (It only shows the latest balance and not historical ones)
  2. Transaction Date
  3. Deposit amount
  4. Withdrawal amount

Out of this data, I want to get a column that shows running total ('balance') at everey transaction as below:

<◎What it should look like>

account latest_balance date deposit withdrawal balance
XYZ 1 000 2021-07-16 100 1 000
XYZ 1 000 2021-07-15 200 900

Because the data does not contain the entire transaction history of this account and the available date is of the latest 1 year, one way to get 'balance' is to make a calculation based on the latest balance. I have tried using the window function for this. However I haven't been able to make it work the way I want to.

For example, if I write this part of the select statement like below:

SELECT  latest_balance  - (ISNULL (SUM(deposit) OVER(PARTITION BY account ORDER BY date DESC ROWS UNBOUNDED PRECEDING),0)     + ISNULL (SUM(withdrawal)) OVER(PARTITION BY account ORDER BY date DESC ROWS UNBOUNDED PRECEDING),0))  

This would return something like below:

<✖ How it looks now>

account latest_balance date deposit withdrawal balance
XYZ 1 000 2021-07-16 100 900
XYZ 1 000 2021-07-15 200 700

This is not what I would like to see as the balance for the first row should say 1 000 instead of 900. I tried different conbinations of ROWS, BETWEEN, UNBOUNDED, PRECEDING and FOLLOWING for this but I still can't figure out how to make it work.

Could anyone please share your knowledge and enlighten me? Many thanks! =)

How to retrieve data from Redux store using functional components and avoiding useSelector & useDispatch

Posted: 16 Jul 2021 08:40 AM PDT

I'm doing an attemp of Todo App in React- Redux; got store, actions, reducer & Addodo component running; but got stucked at showing todos:

if my initialState=[] how can i retrieve data from store?

Store:

import { createStore } from 'redux';  import rootReducer from '../reducer';    export const store = createStore(    rootReducer,     window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()    );     export default store    

My reducer:

const initialState = [];      const todos = (state = initialState, action) => {    switch(action.type) {      // Aca va tu codigo;            case 'AddTodo':               return [...state, action.payload];                   case 'RemoveTodo':          return state.filter(todo => todo.id  !== action.payload)                  case 'ToInProgress':                       return state.map((todo) =>            todo.id === action.payload ? { ...todo, status: "InProgress" } : todo          );                                  case 'ToDone':           return state.map((todo) =>            todo.id === action.payload ? { ...todo, status: "Done" } : todo          );                   default:           return state        }      }           export default todos;  

App.js:

import React from 'react'  import { Route } from "react-router-dom"  import {Provider} from 'react-redux'  import store from './store/index'    import Nav from '../src/components/Nav/Nav'  import Home from '../src/components/Home/Home'  import AddTodo from '../src/components/AddTodo/AddTodo'  import TodoDetail from '../src/components/TodoDetail/TodoDetail'  import './App.css';    export function App() {    return (      <React.Fragment>        <Provider store={store}>          <Nav />          <Route exact path="/" component={Home} />          <Route path="/add" component={AddTodo} />          <Route path="/edit/:id" component={TodoDetail} />        </Provider>      </React.Fragment>    );  }    export default App;  

Home.js:

import React from 'react';  import Todos from '../Todos/Todos'  import './home.css'    export function Home() {    return (          <div className="todosContainer">       <div>        <Todos status="Todo"/>        <label>TODO</label>      </div>      <div>        <Todos status='InProgress' />        <label>InProgress</label>      </div>      <div>        <Todos status='Done'/>        <label>Done</label>      </div>      </div>    )  };         export default Home;  

Here's AddTodo:

export function AddTodo() {     const [state,setState]=React.useState({       title:"",       description:"",       place:"",       date:"",     })      function handleChange(e){       const value=e.target.value;      setState({        ...state,        [e.target.name]:value      })    }      function handleSubmit(e){      e.preventDefault();      store.dispatch(addTodo({        place:state.place,        title:state.title,        date:state.date,        description:state.description      })) // parameters "id" & "status" loaded in Actions.      setState({title:"",      description:"",      place:"",      date:"",})    }      return (      <div className="todoContainer">        <form id="formulario"onSubmit={handleSubmit} >          <label>            Title            <input type="text" name="title" value={state.title} onChange={handleChange} />          </label>          <label>            Description            <textarea type="text" name="description" value={state.description} onChange= {handleChange}/>          </label>          <label>            Place            <input type="text" name="place" value={state.place} onChange={handleChange}/>          </label>          <label>            Date            <input type="text" name="date" value={state.date} onChange={handleChange}/>          </label>          <button className="boton" type="submit" onClick={addTodo}>Agregar</button>        </form>      </div>    )  };    function mapDispatchToProps(dispatch){    return{      addTodo: todo => dispatch(addTodo(todo))    }  }    export default connect(mapDispatchToProps)(AddTodo)    

Now, i want to show at Todos component, every Todos "title", still didn't know how to perform it:

export function Todos(data) {        return (      <div className="todoDetail">            <h4>{data.title}</h4>        </div>    )  };      function mapStateToProps(state) {    return {      data: state.title,       };      }     export default connect(mapStateToProps)(Todos)       

Changes in nested ObservedObject do not updated the UI

Posted: 16 Jul 2021 08:40 AM PDT

When I have a nested ObservedObject, changes in a published property of a nested object do not updated the UI until something happens to the parent object. Is this a feature, a bug (in SwiftUI) or a bug in my code?

Here is a simplified example. Clicking the On/Off button for the parent immediately updates the UI, but clicking the On/Off button for the child does not update until the parent is updated.

I am running Xcode 12.5.1.

import SwiftUI    class NestedObject: NSObject, ObservableObject {      @Published var flag = false  }  class StateObject: NSObject, ObservableObject {      @Published var flag = false      @Published var nestedState = NestedObject()  }    struct ContentView: View {      @ObservedObject var state = StateObject()      var body: some View {          VStack {              HStack {                  Text("Parent:")                  Button(action: {                      state.flag.toggle()                  }, label: {                      Text(state.flag ? "On" : "Off")                  })              }              HStack {                  Text("Child:")                  Button(action: {                      state.nestedState.flag.toggle()                  }, label: {                      Text(state.nestedState.flag ? "On" : "Off")                  })              }          }      }  }    struct ContentView_Previews: PreviewProvider {      static var previews: some View {          ContentView()      }  }  

SwiftUI: Display UIMenuController (or equivalent) on tap?

Posted: 16 Jul 2021 08:40 AM PDT

I have a SwiftUI Text view in my app, and I would like to display a UIMenuController or its SwiftUI equivalent whenever I tap on it. I can capture the tap action successfully by adding an onTapGesture block to my View, but I haven't been able to find any examples showing how to display the menu. Is there a SwiftUI equivalent to UIMenuController? Do I need to create the whole UIViewRepresentable thing for it?

Convert timestamp without timezone into timestamp with timezone

Posted: 16 Jul 2021 08:40 AM PDT

I have a column that is of type nullable timestamp without time zone. It is stored in my Postgres database in this format: 2021-06-24 11:00:00. And I would like to convert it to a nullable timestamp with time zone type such that it would be displayed as 2021-06-24 11:00:00.000-00. Notice that there is no timezone conversion.

The solution should also allow to convert from timestamp with time zone to timestamp without time zone. I did some research and was not able to find anything.

Aerial Attack on Godot

Posted: 16 Jul 2021 08:41 AM PDT

I'm new to Godot, and I'm making a personal project, a 2D platformer, a clone of Ninja Gaiden (1988), but I'm having trouble getting the aerial attack to work. The Player script is the following:

extends KinematicBody2D    onready var Animated_player = $AnimatedSprite  onready var Sword = $Sword/CollisionShape2D    export var Acceleration = 512  export var Max_speed = 64  export var Friction = 0.25  export var Air_resistance = 0.02  export var Gravity = 200  export var Jump_force = 100    var Is_attacking = false  var motion = Vector2.ZERO    func _physics_process(delta):      var x_input = Input.get_action_strength("ui_right") - Input.get_action_strength("ui_left")            if Input.is_action_just_pressed("Attack"):              Animated_player.play("Attack")              Sword.disabled = false              Is_attacking = true              motion.x = 0          if x_input != 0 and Is_attacking == false:          Sword.disabled = true          Animated_player.play("Walk")          motion.x += x_input * Acceleration * delta          motion.x = clamp(motion.x, -Max_speed, Max_speed )          Animated_player.flip_h = motion.x < 0                 else:          if Is_attacking == false:              Sword.disabled = true              Animated_player.play("Idle")              motion.x = lerp(motion.x, 0, Friction * delta)      motion.y += Gravity * delta        if test_move(transform, Vector2.DOWN):          if x_input == 0:              motion.x = lerp(motion.x, 0, Friction)                        if Input.is_action_just_pressed("Jump"):              motion.y = -Jump_force        else:          if Input.is_action_just_pressed("Attack"):              Sword.disabled = false              motion.x = lerp(motion.x, 0, Air_resistance)              Animated_player.play("Jump_Attack")              motion.x = lerp(motion.x, 0, Air_resistance)            if Is_attacking == false:              Sword.disabled = true              if motion.y < 0:                  Animated_player.play("Jump")              if motion.y > 0:                  Animated_player.play("Fall")              if Input.is_action_just_released("Jump") and motion.y < -Jump_force/2:                  motion.y = -Jump_force/2              if x_input == 0:                  motion.x = lerp(motion.x, 0, Air_resistance)        move_and_slide(motion)        motion = move_and_slide(motion, Vector2.UP)    func _on_AnimatedSprite_animation_finished():      if Animated_player.animation == "Attack" or Animated_player.animation == "Jump_Attack":           Is_attacking = false          Sword.disabled = true  

The Jump_Attack animation plays right, but I want the "Air resistance" to be true while you attack on the air, but if you attack on the ground I want motion.x to be zero.

but whenever I make motion.x = 0 inside the if Input.is_action_just_pressed: it stops your movement on the air as well.

How can I solve this?

Open Images from Google Drive using Colab

Posted: 16 Jul 2021 08:40 AM PDT

I am coding a Image Classificator using ResNet18. Train and Test phase work fine. But as a final I want to do a evaluation with 5-10 images. The classificator give out data, target and the images which are classified. Giving out data and target work fine too. But the classificator never shows the classified images to the user.

Running on my own GPU I used to use Show.img() .

I ve got my data on my Google Drive and mounted the data with from colab.google import drive etc.

Which code do I need to implement to show the images to the user.

Thanks for your help.

PS: I bet I missing a pretty easy answer, but I am running crazy.

Flutter - Prompt for TouchID/FaceID when opening app

Posted: 16 Jul 2021 08:40 AM PDT

I'm having an issue implementing TouchID/FaceID Authentication in a way where it will automatically prompt the user when they open the app. I am using the local_auth dependency for TouchID/FaceID.

In the code below, biometric authentication will pop up when the app resumes, but it is also impossible to dismiss. If you press the home button, it dismisses the TouchID prompt but immediately starts to try again, and causes an endless loop if you keep trying this. It will also randomly prompt twice, so even if you successfully log in with the first TouchID prompt, it will pop up again immediately afterwards. Does anyone know of a way to fix this? I also have a TouchID button on the login page that users can press to manually prompt TouchID, but I'd love to recreate how my banking apps and others work where TouchID prompts when you open the app automatically.

void initState() {    super.initState();      SystemChannels.lifecycle.setMessageHandler((msg) async {      if (msg==AppLifecycleState.resumed.toString()) {        // If can pop, app is not at login screen        // so don't prompt for authentication        if (!Navigator.canPop(context)) {          if (_useFingerprint) {            SharedPreferences prefs = await SharedPreferences.getInstance();            String password = prefs.getString('password');            biometricAuthentication(_username, password);          }       }    }  });    void biometricAuthentication(String user, String pass) async {    print("Biometric Authentication Called");    bool didAuthenticate = false;    try {      didAuthenticate = await localAuth.authenticateWithBiometrics(localizedReason: 'Please authenticate');    } on PlatformException catch (e) {      print(e);    }      if (!mounted) {      return;    }       if (!didAuthenticate) {      return;    }    else {      normalLogin(user, pass);       }  }  

Capture File Properties and Owner Details

Posted: 16 Jul 2021 08:41 AM PDT

I have two VBA codes. One loops through and prints the file properties, and the other grabs the owner of a file.

How do I merge the File Owner VBA code into File Properties to print the file name, modification date and owner onto a sheet?

File Properties - VBA

Sub MainList()      Application.ScreenUpdating = True      Set Folder = Application.FileDialog(msoFileDialogFolderPicker)      If Folder.Show <> -1 Then Exit Sub      xDir = Folder.SelectedItems(1)      Call ListFilesInFolder(xDir, True)      Application.ScreenUpdating = False  End Sub        Sub ListFilesInFolder(ByVal xFolderName As String, ByVal xIsSubfolders As Boolean)      Application.ScreenUpdating = True            Dim xFileSystemObject As Object      Dim xFolder As Object      Dim xSubFolder As Object      Dim xFile As Object      Dim rowIndex As Long            Set xFileSystemObject = CreateObject("Scripting.FileSystemObject")      Set xFolder = xFileSystemObject.GetFolder(xFolderName)            rowIndex = Application.ActiveSheet.Range("A65536").End(xlUp).Row + 1      For Each xFile In xFolder.Files        Application.ActiveSheet.Cells(rowIndex, 1).Formula = xFile.Path        Application.ActiveSheet.Cells(rowIndex, 2).Formula = xFile.Name        Application.ActiveSheet.Cells(rowIndex, 3).Formula = xFile.DateLastAccessed        Application.ActiveSheet.Cells(rowIndex, 4).Formula = xFile.DateLastModified        Application.ActiveSheet.Cells(rowIndex, 5).Formula = xFile.DateCreated        Application.ActiveSheet.Cells(rowIndex, 6).Formula = xFile.Type        Application.ActiveSheet.Cells(rowIndex, 7).Formula = xFile.Size        Application.ActiveSheet.Cells(rowIndex, 8).Formula = xFile.Owner        ActiveSheet.Cells(2, 9).FormulaR1C1 = "=COUNTA(C[-7])"        rowIndex = rowIndex + 1      Next xFile      If xIsSubfolders Then        For Each xSubFolder In xFolder.SubFolders          ListFilesInFolder xSubFolder.Path, True        Next xSubFolder      End If      Set xFile = Nothing      Set xFolder = Nothing      Set xFileSystemObject = Nothing      Application.ScreenUpdating = False  End Sub  

File Owner - VBA

Sub test()      Dim fName As String      Dim fDir As String      fName = "FileName.JPG"      fDir = "C:/FilePath"      Range("A1").Value = GetFileOwner(fDir, fName)  End Sub    Function GetFileOwner(fileDir As String, fileName As String) As String      Dim securityUtility As Object      Dim securityDescriptor As Object      Set securityUtility = CreateObject("ADsSecurityUtility")      Set securityDescriptor = securityUtility.GetSecurityDescriptor(fileDir & fileName, 1, 1)      GetFileOwner = securityDescriptor.Owner  End Function  

Why people don't do WSDL-first?

Posted: 16 Jul 2021 08:41 AM PDT

I'm currently making a presentation that deals with web services.

We created our service using WSDL+XSD-first approach, in which we first created (with the aid of tools) the XSD schema and WSDL and then compiled both to .NET and Java classes for interoperation.

I want to justify why we used this approach. I mentioned that it's more OOP-compliant (first define interface, then implementation, not vice versa) and that you have more control over interoperability constraints. Also, you can define namespaces explicitly and help reuse XSDs across applications

On the contrary, today, still many people prefer implementing the code in their IDE and generate WSDL from there. The question is, why?

How do I rename files using R?

Posted: 16 Jul 2021 08:40 AM PDT

I have over 700 files in one folder named as: files from number 1 to number9 are named for the first month:

water_200101_01.img    water_200101_09.img    

files from number 10 to number30 are named:

water_200101_10.img  water_200101_30.img  

And so on for the second month: files from number 1 to number9 are named:

water_200102_01.img    water_200102_09.img    

files from number 10 to number30 are named:

water_200102_10.img  water_200102_30.img   

How can I rename them without making any changes to the files. just change the nams, for example

water_1  water_2  ...till...  water_700  

Using accelerometer, gyroscope and compass to calculate device's movement in 3D world

Posted: 16 Jul 2021 08:40 AM PDT

I'm working on an android application which can calculate device's movement in 6 direction. I think I can use acceleration as;

"x=a.t^2" but a is not a constant. And this is the problem. How can I calculate the total movement??

No comments:

Post a Comment