Saturday, November 20, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Why I am getting error while concatenating variables in output in C++?

Posted: 20 Nov 2021 10:52 AM PST

I am trying to concatenate output variables in C++ In my code there are some calculations and when I am printing the output of the variables I am getting error.

My code:

#include<iostream>  #include<string>  #include<math.h>   using namespace std;    int main()  {              string name;         cout<<"Enter the name of the borrower: ";         cin>>name;           float mortage_blanace;         cout<<"Enter the mortage balance: ";         cin>>mortage_blanace;           float interest_rate;         cout<<"Enter the annual interest rate: ";         cin>>interest_rate;           float current_monthly_payment;         cout<<"Enter the current monthly payment: ";         cin>>current_monthly_payment;           float extra_monthly_payment;         cout<<"Enter the extra monthly payment: ";         cin>>extra_monthly_payment;           cout<<"\n";            int new_payment = current_monthly_payment+extra_monthly_payment;         float i = (interest_rate/100)/12;         int current_duration_in_months =  (log(current_monthly_payment/(current_monthly_payment/i)-mortage_blanace))/(log(1+i));         int new_duration_in_months = (log(new_payment/(new_payment/i)-mortage_blanace))/(log(1+i));         float current_interest = (current_monthly_payment*new_duration_in_months)-mortage_blanace;         float new_interest = (new_payment*new_duration_in_months)-mortage_blanace;         int current_duration_years = current_duration_in_months/12;         int current_duration_months = current_duration_in_months%12;         int new_duration_years = new_duration_in_months/12;         int new_duration_months = new_duration_in_months%12;         float savings = current_interest-new_interest;         string fees;                  cout<<mortage_blanace + "      " + mortage_blanace;         cout<<"\n";       }              return 0;  }  

But I am getting following error:

Untitled1.cpp: In function 'int main()':  Untitled1.cpp:58:30: error: invalid operands of types 'float' and 'const char [7]' to binary 'operator+'          cout<<mortage_blanace + "      " + mortage_blanace;  

How can I get concatenated output in C++ like the one I want?!

Any help is appreciated.

JavaFX TextField to allow only Doubles

Posted: 20 Nov 2021 10:52 AM PST

I've searched for a while now and couldn't find anything for my exact problem. I am trying to force the User to only put double values e.g 0.35, 4.35, 44.35, 444.35, 4444.35 into a TextField. For simple Numbers I already found a working solution.

public class IntegerTextField extends TextField {  private static Pattern integerPattern = Pattern.compile("[0-9]*");  @Override  public void replaceText(int start, int end, String text) {      if (validate(text)) {          super.replaceText(start, end, text);      }  }  @Override  public void replaceSelection(String text) {      if (validate(text)) {          super.replaceSelection(text);      }  }  private boolean validate(String text) {      return integerPattern.matcher(text).matches();  }  

}

Now I am trying to do the same for double values, but I don't know how to adjust this to work for doubles too. What I am trying to do now, was to add a Listener on the TextField and check if the regex matches the text.

myTxtField.textProperty().addListener((observable, oldValue, newValue) -> {          if (!newValue.matches("some regex here")) {              myTxtField.setText(oldValue);          }      });  }  

I've tried multiple regex that I've found on stackoverflow but the problem with all of them were either I couldn't clear the TextField completely, e.g if the User makes a wrong input on the first number, it needs to be deleted, to put a completely new number in. Or they were just not matching the exact numbers I need to.

I hope this is clear enough, thank you for your help. I am working with Java 8.

AttributeError: 'SQLAlchemy' object has no attribute 'connection'.How to connect sqlalchemy to mysql?

Posted: 20 Nov 2021 10:51 AM PST

if request.method == 'POST' and 'username' in request.form and 'password' in request.form:      # Create variables for easy access      username = request.form['username']      password = request.form['password']      # Check if account exists using MySQL                  cursor = db.connection.cursor(db.cursors.DictCursor)      cursor.execute('SELECT * FROM accounts WHERE username = %s AND password = %s', (username, password,))      # Fetch one record and return result      account = cursor.fetchone()  

Error: cursor = db.connection.cursor(db.cursors.DictCursor) AttributeError: 'SQLAlchemy' object has no attribute 'connection'

lua 5.1 package.loadlib and require. gcc building windows dll

Posted: 20 Nov 2021 10:51 AM PST

I am currently working on a mod for Noita, therefore I am using this

I am a software developer, but c, gcc and lua is new for me.

I build lua-enet on my own with the following command using msys2 (to be clear I used mingw32) on windows 10 inside of the current master github folder:

gcc -O -shared -o enet.dll enet.c -lenet -llua5.1 -lws2_32 -lwinm --verbose  

Additionally I had to add the necessary files like the header files: enter image description here

and

enter image description here

I did this several times, because I had errors like

The specified module could not be found.

enet is not a valid Win32 application

But the gcc command above worked then while running Noita in DevBuild / Debug mode. I was able to debug it with Decoda and saw the library was loaded.

But when I run Noita via Steam I get the following error:

Lua (DoFile) error at 'mods/noita-mp/init.lua': error loading module 'enet1317_lua-enet-master21-10-2015_lua5-1_32bit' from file 'mods\noita-mp\files\libs\enet1317_lua-enet-master21-10-2015_lua5-1_32bit.dll': Das angegebene Modul wurde nicht gefunden.

enter image description here

Additional printing:

Mod enabled: noita-mp 0  LUA: file_util.lua | Noitas root absolute path set to C:\Program Files (x86)\Steam\steamapps\common\Noita     LUA: ;.\?.lua;C:\Program Files (x86)\Steam\steamapps\common\Noita\lua\?.lua;C:\Program Files (x86)\Steam\steamapps\common\Noita\lua\?\init.lua;;C:\Program Files (x86)\Lua\5.1\lua\?.luac;mods\noita-mp\files\libs\?.lua;C:\Program Files (x86)\Steam\steamapps\common\Noita\mods\noita-mp\files\libs\?.lua;      LUA: .\?.dll;C:\Program Files (x86)\Steam\steamapps\common\Noita\?.dll;C:\Program Files (x86)\Steam\steamapps\common\Noita\loadall.dll;mods\noita-mp\files\libs\?.dll;C:\Program Files (x86)\Steam\steamapps\common\Noita\mods\noita-mp\files\libs\?.dll;     LUA: Trying to load enet c library by file name with 'enet1317_lua-enet-master21-10-2015_lua5-1_32bit.dll' loading.. Does file exists? false      LUA: nil      LUA: Trying to load enet c library by relative path with 'mods\noita-mp\files\libs\enet1317_lua-enet-master21-10-2015_lua5-1_32bit.dll' loading.. Does file exists? true      LUA: nil      LUA: Trying to load enet c library by absolute path with 'C:\Program Files (x86)\Steam\steamapps\common\Noita\mods\noita-mp\files\libs\enet1317_lua-enet-master21-10-2015_lua5-1_32bit.dll' loading.. Does file exists? true      LUA: nil      LUA: Trying to load enet c library by absolute path with 'C:\Program Files (x86)\Steam\steamapps\common\Noita\mods\noita-mp\files\libs\enet1317_lua-enet-master21-10-2015_lua5-1_32bit.dll' loading.. Does file exists? true      LUA: nil      LUA: enet c library 'enet1317_lua-enet-master21-10-2015_lua5-1_32bit.dll' was loaded by require load.     Lua (DoFile) error at 'mods/noita-mp/init.lua': error loading module 'enet1317_lua-enet-master21-10-2015_lua5-1_32bit' from file 'mods\noita-mp\files\libs\enet1317_lua-enet-master21-10-2015_lua5-1_32bit.dll':      Das angegebene Modul wurde nicht gefunden.  

init.lua

dofile("mods/noita-mp/files/scripts/util/util.lua")    SetNoitaRootAbsolutePath()    -- Need to add module package to package path, because relative paths are not working  package.path = package.path .. ";"  .. string.gsub(GetRelativePathOfRequiredLibs() .. "/?.lua;", "/", "\\")  .. string.gsub(GetAbsolutePathOfRequiredLibs() .. "/?.lua;", "/", "\\")  print(package.path)    package.cpath = package.cpath .. ";"  .. string.gsub(GetRelativePathOfRequiredLibs() .. "/?.dll;", "/", "\\")  .. string.gsub(GetAbsolutePathOfRequiredLibs() .. "/?.dll;", "/", "\\")  print(package.cpath)      ModMagicNumbersFileAdd("mods/noita-mp/files/data/magic_numbers.xml")    local enet = nil  if enet == nil then      local fileName = "enet1317_lua-enet-master21-10-2015_lua5-1_32bit.dll"      print("Trying to load enet c library by file name with '" .. fileName .. "' loading.. Does file exists? " .. tostring(FileExists(fileName)))      enet = package.loadlib(fileName, "luaopen_enet")        if not enet then          print(tostring(enet))          local rel_path = GetRelativePathOfRequiredLibs() .. "/" .. fileName          rel_path = string.gsub(rel_path, "/", "\\")          print("Trying to load enet c library by relative path with '" .. rel_path .. "' loading.. Does file exists? " .. tostring(FileExists(rel_path)))          enet = package.loadlib(rel_path, "luaopen_enet")      end        if not enet then          print(tostring(enet))          local abs_path = GetAbsolutePathOfRequiredLibs() .. "/" .. fileName          abs_path = string.gsub(abs_path, "/", "\\")          print("Trying to load enet c library by absolute path with '" .. abs_path .. "' loading.. Does file exists? " .. tostring(FileExists(abs_path)))          enet = package.loadlib(abs_path, "luaopen_enet")      end        if not enet then          print(tostring(enet))          local abs_path = [[C:\Program Files (x86)\Steam\steamapps\common\Noita\mods\noita-mp\files\libs\enet1317_lua-enet-master21-10-2015_lua5-1_32bit.dll]]          print("Trying to load enet c library by absolute path with '" .. abs_path .. "' loading.. Does file exists? " .. tostring(FileExists(abs_path)))          enet = package.loadlib(abs_path, "luaopen_enet")      end        if enet then          print("enet c library '" .. fileName .. "' was loaded by function load.")          enet()      else          print(tostring(enet))          print("enet c library '" .. fileName .. "' was loaded by require load.")          require("enet1317_lua-enet-master21-10-2015_lua5-1_32bit")      end  end  

I already tried to put the enet*.dll to a different location like a separated ssd, in noitas root folder, but didnt change anything.

btw enet.dll is the 64bit version one.

Anyone out here with an idea to solve this?

Run Swin-Transformer on VS Code

Posted: 20 Nov 2021 10:51 AM PST

i really have an issue running this code on on VS Code https://github.com/microsoft/Swin-Transformer. i have all modules installed and some modules like torch, timm.loss doesn't seem to be resolved. kindly help

Do I need to include pooling layer in keras tuner?

Posted: 20 Nov 2021 10:51 AM PST

Is it necessary to add max-pooling layer while building Keras-tuner model? I want to find the kernel size, the number of layers and the dense units. Considering these three parameters, I define the model. Do I need to introduce poolig layer in between?

def build_model(hp):      model = keras.Sequential([      keras.layers.Conv2D(          filters=hp.Int('conv_1_filter', min_value=32, max_value=64, step=32),          kernel_size=hp.Choice('conv_1_kernel', values = [3,5]),          activation='relu',          input_shape=(28,28,1)      ),        keras.layers.Conv2D(          filters=hp.Int('conv_2_filter', min_value=32, max_value=128, step=32),          kernel_size=hp.Choice('conv_2_kernel', values = [3,5]),          activation='relu'      ),        keras.layers.Conv2D(          filters=hp.Int('conv_3_filter', min_value=32, max_value=128, step=32),          kernel_size=hp.Choice('conv_3_kernel', values = [3,5]),          activation='relu'      ),        keras.layers.Flatten(),      keras.layers.Dense(          units=hp.Int('dense_1_units', min_value=32, max_value=256, step=32),          activation='relu'      ),      keras.layers.Dense(10, activation='softmax')    ])      

Why is cache coherency important in multi-processor system?

Posted: 20 Nov 2021 10:50 AM PST

Multiprocessor systems have some kind of cache coherency protocols built into them e.g. MSI, MESI etc. The only case where cache coherency matters is when instructions executing in two different processors tries to write/read shared data. For the shared data to be practically valid, programmer anyway has to introduce memory barriers. If there is no memory barrier, the shared data is going to be "wrong" regardless of whether underlying processor implements cache coherence or not. Why then the need of cache coherence mechanisms at hardware level?

show database fetched values if present else show default text in ng-select angular

Posted: 20 Nov 2021 10:50 AM PST

I have 3 dropdowns for country,state,city in angular. I have used ng-select module for those dowpdowns. On country change states populates, and on state change city populate.

template HTML

<ng-select formControlName="country" (change)="onChangeCountry($event)" >      <ng-option value="dbCountryId ? dbCountryId : ''">{{dbCountryName ? dbCountryName : 'Select Country' }}</ng-option>      <ng-option *ngFor="let country of countryInfo" [value]="country.id">{{country.name}}</ng-option>   </ng-select>   <ng-select formControlName="state" (change)="onChangeState($event)">      <ng-option value="dbStateId ? dbStateId : ''">{{dbStateName ? dbStateName : 'Select State' }}</ng-option>      <ng-option *ngFor="let state of stateInfo" [value]="state.id">{{state.name}}</ng-option>   </ng-select>    <ng-select formControlName="city" >      <ng-option value="dbCityId ? dbCityId : ''">{{dbCityName ? dbCityName : 'Select City' }}</ng-option>      <ng-option *ngFor="let city of cityInfo" [value]="city.id">{{city.name}}</ng-option>   </ng-select>  

ts code

 this.userService.getUserDetails(userDetails.id).subscribe((results) => {    if (results['status'] === true) {       this.dbCountryName = results.data.country ? results.data.country : null;                this.dbCountryId = results.data.country_id                  ? results.data.country_id                  : null;              this.dbStateName = results.data.state ? results.data.state : null;              this.dbStateId = results.data.state_id                ? results.data.state_id                : null;              this.dbCityName = results.data.city ? results.data.city : null;              this.dbCityId = results.data.city_id ? results.data.city_id : null;                  this.form.patchValue({                country:                  results.data.country_id === null ? '' : results.data.country_id,                state:                  results.data.state_id === null ? '' : results.data.state_id,                city: results.data.city_id === null ? '' : results.data.city_id,      });  }   });  

I am using same form for add and edit data. I am storing id of country,state, city. In api response I get stored id, name of fields. I have patched id with respective form control.

I have 2 problems.

  1. 'Select country/state/city' like default text , it shows in dropdown not in inputbox enter image description here
  2. I am not able to show fetched data properly. its showing like below enter image description here

How I can solve these problems with ng-select in angular? please help and guide. Thanks.

CustomView not respecting constraint layout

Posted: 20 Nov 2021 10:50 AM PST

I have a CustomView that is a ConstraintLayout where it contains TextView RecyclerView Item

That's because I need to do something like this :

enter image description here

I decided to create a CustomView that encapsulate all of this module, and then I have the TextView of the first "Text" that would act as a title Then I have the RecyclerView that if I have one item then I just fill the Item with all of the data, it works, but I'm trying to figure it out how do I resize the Item to make it look as the second image when there's more than one.

From now I'm having problems because the CustomView I'm using ViewBinding and I need to make the root view as merge to make it work with :

MyModuleViewBinding.inflate(LayoutInflater.from(context), this) // This is everything wrapped (Text + RecyclerView + Item)    

I have two problems here :

1.- If I add the Item as an include I can't put merge in the layout because they are not compatible but I wanted to put the code of Item in a different layout because is the same as the RecyclerView item and I didn't want to add duplicate code. And with this problem when I use the include I can't put this include view below the Text and it overlaps the Text I can not do ItemTopToBottom of title it doesn't do anything. 2.- When I add the recyclerView the items are not as the image they are both almost visible in the screen and I'd like to show the 100% of the first item and a 10 % more or less of the second one.

difference with/out & sign in subscript function (operator[]) inside class?

Posted: 20 Nov 2021 10:50 AM PST

I am starting out learning C++ programming and I just read about "operator[]". This is my example code:

#include <stdio.h>                                                                                                    #include <iostream>                                                                                                                                                                                                                                                                                                                                             class cls {                                                                                                           public:                                                                                                                   cls(int s) {                                                                                                                  elem = new double[s];                                                                                                     sz = s;                                                                                                                                                                                                                                                           for(int i = 0; i < s; i++) {                                                                                                         elem[i] = (double)i;                                                                                                                }                                                                                                                                                  }                                                                                                                                                                                                                                                                                                             double& operator[](int i) {                                                                                                                                 return elem[i];                                                                                                                                    }                                                                                                                                                                                                                                                                                                                   private:                                                                                                                                                        double* elem;                                                                                                                                               int sz;                                                                                                                                                 };                                                                                                                                                                                                                                                                                                                      int main() {                                                                                                                                                    cls some_class(5);                                                                                                                                                                                                                                                                                                      std::cout << some_class[2] << std::endl;                                                                                                                                                                                                                                                                                                              return 0;                                                                                                                                                                                                         }  

but it produces the same output as:

#include <stdio.h>                                                                                                    #include <iostream>                                                                                                                                                                                                                                                                                                                                               class cls {                                                                                                           public:                                                                                                                   cls(int s) {                                                                                                                  elem = new double[s];                                                                                                     sz = s;                                                                                                                                                                                                                                                           for(int i = 0; i < s; i++) {                                                                                                         elem[i] = (double)i;                                                                                                                }                                                                                                                                                  }                                                                                                                                                                                                                                                                                                             double operator[](int i) {                                                                                                                                 return elem[i];                                                                                                                                    }                                                                                                                                                                                                                                                                                                                   private:                                                                                                                                                        double* elem;                                                                                                                                               int sz;                                                                                                                                                 };                                                                                                                                                                                                                                                                                                                      int main() {                                                                                                                                                    cls some_class(5);                                                                                                                                                                                                                                                                                                      std::cout << some_class[2] << std::endl;                                                                                                                                                                                                                                                                                                              return 0;                                                                                                                                                                                                         }    

What difference does the '&' do after "double" and before "operator[]"? I get that it should return a reference of type double in the first example and just a double in the second, but why do I get the same answer? Shouldn't one of them fail? Or return a memory address?

Querydsl and unexpected end of subtree

Posted: 20 Nov 2021 10:52 AM PST

It seems that that query is composed in the right way. SomeId exists. However, I'm getting the following errors:

<AST>:0:0: unexpected end of subtree    Invalid path: 'Entity.id'    Invalid path: 'Entity.code'    left-hand operand of a binary operator was null  

The query code(uses as subquery in another part):

JPAQueryFactory entityElementJPA = entityElementDAO.getJpaFactory();                entityElementJPA                          .select(QEntity.Entity.id)                          .where(                                  QEntity.Entity.code.eq(                                                  entityElementJPA                                                          .select(                                                                  QEntity.Entity.code)                                                          .where(QEntity.Entity.id.eq(someId))                                          )                                          .and(QEntity.Entity.id.ne(someId))                          );  

I'm a newbie in java and querydsl, sorry if question is simple

Any clues?

Javascript timer/counter crashing browser

Posted: 20 Nov 2021 10:51 AM PST

This code is meant to start a timer when you type something into the text input, that will count every second until it reaches 5 seconds, and then stop. But it keeps spitting out 0 which is creating an endless while loop that crashes the browser. I'm sure I'm missing something obvious here :-/

var secondsPassed = 0;    function setTimer() {        while (secondsPassed <= 5) {      console.log(secondsPassed);      setInterval(function() { secondsPassed += 1; }, 1000);    }  }
<input type="text" onkeyup="setTimer()">

Why pandas dataframe doesn't change when i used it as a input of a function with multiprocessing

Posted: 20 Nov 2021 10:53 AM PST

I have a code like this:

df1 = pd.DataFrame(      {          "A": ["A0", "A1", "A2", "A3"],          "B": ["B0", "B1", "B2", "B3"],          "C": ["C0", "C1", "C2", "C3"],          "D": ["D0", "D1", "D2", "D3"],      }  )  df2 = pd.DataFrame(      {          "A": ["A4", "A5", "A6", "A7"],          "B": ["B4", "B5", "B6", "B7"],          "C": ["C4", "C5", "C6", "C7"],          "D": ["D4", "D5", "D6", "D7"],      }  )    def changeDF(df):      df['Signal'] = 0    changeDF(df1)  changeDF(df2)  

when I run above, (changeDf) function add a column to df1 and df2 named 'Signal' with 0 values. but instead of run (changeDf) directly using multiprocessing like below it doesn't change any dfs.

s = [df1, df2]  with multiprocessing.Pool(processes=2) as pool:      res = pool.map(changeDF, s)  

What's wrong with my code?

How could I get out of this Issue with char and char[], Java

Posted: 20 Nov 2021 10:50 AM PST

So I am running into this problem where I am trying to see if one input is the same as a pre defined group of variables for a class. It can be any of the variables, but I keep getting an error saying that char can not be converted to char[] the code is below. Would very much appreciate the help!

 {    Scanner reader = new Scanner(System.in);    int i;    int found = 0;    char[] letter;    char A, C, T, H;    char[] okaycodes = {A, C, T, H};    System.out.printf("A - air\nC - car\nT - truck\nH - hand deliver\n");    System.out.print("Enter shipping code:  ");    letter = reader.next().charAt(0);    for(i = 0; i < 5; i++)    {      if(letter == okaycodes)      {           System.out.println("Good code");  

Occurrence of dice faces

Posted: 20 Nov 2021 10:51 AM PST

I'm trying a dice throw application in c and I cant seem to make a way loop that tells me how many times each throw has been done. The user can decide how many faces and throws they want.

For some reason The occurrence output doesn't actually count how many times each face appears.

int occurred[25] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25 };  int count[25] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };    for (int i = 1; i <= throw; i++)  {      roll = rand() % faces + 1;      printf("Dice %d: %d\n", i, roll);      if (roll == occurred[i])      {            count[i]++;      }    }    printf("\n");  for (int i = 0; i < 25; i++)  {      printf("%u\n", count[i]);      printf("\n");  }    printf("\n");  for (int i = 0; i < 25; i++)  {      printf("%u\n", count[i]);      printf("\n");  }  

I'm using these code but, not understanding why using

Posted: 20 Nov 2021 10:52 AM PST

function themename_custom_header_setup() {      $defaults = array(          // Default Header Image to display          'default-image'         => get_template_directory_uri() . '/images/headers/default.jpg',          // Display the header text along with the image          'header-text'           => false,          // Header text color default          'default-text-color'        => 'FFFF00',          // Header image width (in pixels)          'width'             => 1000,          // Header image height (in pixels)          'height'            => 198,          // Header image random rotation default          'random-default'        => false,          // Enable upload of image file in admin           'uploads'       => false,          // function to be called in theme head section          'wp-head-callback'      => 'wphead_cb',          //  function to be called in preview page head section          'admin-head-callback'       => 'adminhead_cb',          // function to produce preview markup in the admin screen          'admin-preview-callback'    => 'adminpreview_cb',          );          add_theme_support('custom-header',$defaults);  }  add_action( 'after_setup_theme', 'themename_custom_header_setup' );  

Here why we use header-text, uploads. I changed this value, but not affect my theme, where I can see the changes?

How To Update All Class's Functions Which Inherits From The Base Class In A Game Engine

Posted: 20 Nov 2021 10:49 AM PST

Reference : C++ calling all update() functions in a program

Like In The Above One Of The Solution By Someone Gives This Code :

    class Updatable  {  public:      virtual void update() = 0;  };    class SomeClass : public Updatable  {  public:      virtual void update()      {          printf("update for SomeClass was called\n");      }  };    class AnotherClass : public Updatable  {  public:      virtual void update()      {          printf("update for AnotherClass was called\n");      }  };    int main()  {      Updatable* v[10];      int n = 0;      SomeClass a, b;      AnotherClass c, d;      v[n++] = &a;      v[n++] = &b;      v[n++] = &c;      v[n++] = &d;        for (int i = 0; i < n; i++)          v[i]->update();  }  

So How To Make Objects Automatically Without Hard Coding. And How Does The Program Know If A Class Is Inheriting From Base Class ( Because Thats Required For Creating A Object )

Thank You

Getting string literal from a generic object

Posted: 20 Nov 2021 10:52 AM PST

This function gives me a type with an index of [x:string] instead of myKey:

const myObj = {    key: "myKey",    otherStuff: {stuff:3}  }    type SomeObj<T extends string> = {key: T} & Record<string, any>    function makeObject<TKey extends string, TEntry extends SomeObj<TKey>>(entry: TEntry){ return {[entry.key]: entry}   }    const result = makeObject(myObj)    /// type of result is const result: {  ///    [x: string]: {  ///        key: string;  ///        otherStuff: {  ///            stuff: number;  ///        };  ///    };  /// }  

Same thing for the type of key in the result object. Why is it losing the type information and how can I get it back?

(I realize I can force it to read the literal by declaring key: "myKey" as const, but that's not what I want. I want to infer it in the function, if possible.)

Crash in CollectionView For Invalid Header

Posted: 20 Nov 2021 10:52 AM PST

I want to understand what this error means?

 *** Terminating app due to uncaught exception   'NSInternalInconsistencyException', reason:   'the view returned from -collectionView:viewForSupplementaryElementOfKind:atIndexPath: was not   retrieved by calling -dequeueReusableSupplementaryViewOfKind:withReuseIdentifier:forIndexPath:   for element kind 'UICollectionElementKindSectionHeader' at index path <NSIndexPath: 0x8aeb905cf5be0ed2>   {length = 2, path = 0 - 0}; supplementary view:   <UICollectionReusableView: 0x7f9236dc4ff0; frame = (0 0; 0 0); layer = <CALayer: 0x600001018620>>'  

I am using custom header for UICollectionView.I am getting this crash as soon as the view is loaded. even before cellforrowatindexpath is called.

func collectionView(_ collectionView: UICollectionView,   viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {            if kind == UICollectionView.elementKindSectionHeader  && indexPath.section == 2            {        return someCustomHeader      }            return UICollectionReusableView()  }        

How to sort a String and check for anagrams?

Posted: 20 Nov 2021 10:51 AM PST

I'm supposed to write an algorithm that tests two Strings to check if they're anagrams of each other and I have to use either BubbleSort, SelectionSort or InsertionSort. So I used SelectionSort to sort the Strings, which I converted to char arrays beforehand, but it doesn't work and I cannot find my mistake.

public static void selectionSort(char[] arr) {        for (int i = 0; i < arr.length - 1; i++) {          int least = i;          for (int j = i + 1; j < arr.length; j++) {              if (arr[j] < arr[least])                  least = j;              if (least != i) {                  int swap = arr[i];                  arr[i] = arr[least];                  arr[least] = (char) swap;                }          }      }  }    public static boolean anagramCheck(String x, String y) {        x.trim();      y.trim();        x.toLowerCase();      y.toLowerCase();        char xarr[] = x.toCharArray();      char yarr[] = y.toCharArray();        if (x.length() != y.length())          return false;        selectionSort(xarr);      System.out.println(xarr); // I used this to check if the Strings are sorted correctly      selectionSort(yarr);      System.out.println(yarr);        if (xarr == yarr) {          System.out.println("It's an anagram.");          return true;      } else {          return false;      }  }  

I'm supposed to ignore capital letters and spaces, that's why I used trim() and toLowerCase(). But it neither trims the spaces nor changes capital letters to lower case letters. Additionally, when I use more than 5 letters, it doesn't sort the given Strings alphabetically. Only one of both is sorted correctly, the other one is messed up. I am new to Java programming so I might need some help here. Thanks in advance

Can interpolation be done on print output and in the middle of the output, is it possible to use gets in Ruby? (expecting reply from Ruby folks)

Posted: 20 Nov 2021 10:52 AM PST

print """Input 1: (here I want *gets* to have some input)  Input 2:   """  

is it possible to get input in the middle of the printed 2 or more lines string in Ruby?

Check if elements in a list equal to the sum value of the list

Posted: 20 Nov 2021 10:50 AM PST

I am trying to figure out a more pythonic way of accepting a list and enumerating through the list, checking whether the sum of a sequence of elements == to the sum of the whole list, if so, it will create a return a sub list.

Note: A solution for checking any combination of elements would be interesting too.

For example:

example1 = [8, 9, 10, 10, 10, -20]  

Output = [8, 9, 10]

example2 = [-15, 6, 8, 2, 10, 10, -5]  

Output = [6, 8, 2]

Simple python histogram

Posted: 20 Nov 2021 10:53 AM PST

result1 = ["Progress","Progress(MT)","ModuleRT","Exclude"]  result2 = [3,4,3,5]      def histogram (list1,list2):      for i in range (len(list1)):          print(list1[i])          for j in range (list2[i]):              print("","*")  histogram(result1,result2)  

I'm trying to get the output like this, but I can't seem to get that.

Progress Progress(MT)  ModuleRT Excluded    *           *           *          *                *  

Referencing interface name as a variable before applying settings on it

Posted: 20 Nov 2021 10:52 AM PST

I want to apply the following line in my Ansible script to Cisco IOS devices:

ip ftp source-interface loopback {loobpback_interface_number}  

But the problem is that, the specific loopback interface on my devices has different IDs. Can anybody help me to accomplish this problem?

Thanks

Projectile null value

Posted: 20 Nov 2021 10:49 AM PST

I'm trying to make a shooter game but when I shoot while there are still bullets spawned I get these error codes:

ArgumentNullException: Value cannot be null.  Parameter name: source  UnityEngine.AudioSource.Play () (at <ec7b0cef068d42fea98bc6f00449b0e2>:0)  RayCastShootComplete+<ShotEffect>d__12.MoveNext () (at Assets/Let's Try   Shooter/Scripts/CompletedScripts/RayCastShootComplete.cs:87)  UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator,   System.IntPtr returnValueAddress) (at <7d87237cea3743d093e22c5b98f74fba>:0)  UnityEngine.MonoBehaviour:StartCoroutine(IEnumerator)  RayCastShootComplete:Update() (at Assets/Let's Try   Shooter/Scripts/CompletedScripts/RayCastShootComplete.cs:41)    NullReferenceException: Object reference not set to an instance of an object  RayCastShootComplete.Update () (at Assets/Let's Try   Shooter/Scripts/CompletedScripts/RayCastShootComplete.cs:44)  

Here is the code it is referencing:

using UnityEngine; using System.Collections;

public class RayCastShootComplete : MonoBehaviour {

public int gunDamage = 1;                                           // Set the number of hitpoints that this gun will take away from shot objects with a health script  public float fireRate = 0.25f;                                      // Number in seconds which controls how often the player can fire  public float weaponRange = 50f;                                     // Distance in Unity units over which the player can fire  public float hitForce = 100f;                                       // Amount of force which will be added to objects with a rigidbody shot by the player  public Transform gunEnd;                                            // Holds a reference to the gun end object, marking the muzzle location of the gun    private Camera fpsCam;                                              // Holds a reference to the first person camera  private WaitForSeconds shotDuration = new WaitForSeconds(0.07f);    // WaitForSeconds object used by our ShotEffect coroutine, determines time laser line will remain visible  private AudioSource gunAudio;                                       // Reference to the audio source which will play our shooting sound effect  private LineRenderer laserLine;                                     // Reference to the LineRenderer component which will display our laserline  private float nextFire;                                             // Float to store the time the player will be allowed to fire again, after firing      void Start ()   {      // Get and store a reference to our LineRenderer component      laserLine = GetComponent<LineRenderer>();        // Get and store a reference to our AudioSource component      gunAudio = GetComponent<AudioSource>();        // Get and store a reference to our Camera by searching this GameObject and its parents      fpsCam = GetComponentInParent<Camera>();  }      void Update ()   {      // Check if the player has pressed the fire button and if enough time has elapsed since they last fired      if (Input.GetButtonDown("Fire1") && Time.time > nextFire)       {          // Update the time when our player can fire next          nextFire = Time.time + fireRate;            // Start our ShotEffect coroutine to turn our laser line on and off          StartCoroutine (ShotEffect());            // Create a vector at the center of our camera's viewport          Vector3 rayOrigin = fpsCam.ViewportToWorldPoint (new Vector3(0.5f, 0.5f, 0.0f));            // Declare a raycast hit to store information about what our raycast has hit          RaycastHit hit;            // Set the start position for our visual effect for our laser to the position of gunEnd          laserLine.SetPosition (0, gunEnd.position);            // Check if our raycast has hit anything          if (Physics.Raycast (rayOrigin, fpsCam.transform.forward, out hit, weaponRange))          {              // Set the end position for our laser line               laserLine.SetPosition (1, hit.point);                // Get a reference to a health script attached to the collider we hit              ShootableBox health = hit.collider.GetComponent<ShootableBox>();                // If there was a health script attached              if (health != null)              {                  // Call the damage function of that script, passing in our gunDamage variable                  health.Damage (gunDamage);              }                // Check if the object we hit has a rigidbody attached              if (hit.rigidbody != null)              {                  // Add force to the rigidbody we hit, in the direction from which it was hit                  hit.rigidbody.AddForce (-hit.normal * hitForce);              }          }          else          {              // If we did not hit anything, set the end of the line to a position directly in front of the camera at the distance of weaponRange              laserLine.SetPosition (1, rayOrigin + (fpsCam.transform.forward * weaponRange));          }      }  }      private IEnumerator ShotEffect()  {      // Play the shooting sound effect      gunAudio.Play ();        // Turn on our line renderer      laserLine.enabled = true;        //Wait for .07 seconds      yield return shotDuration;        // Deactivate our line renderer after waiting      laserLine.enabled = false;  }  

}

Does anyone know what I should do?

For clarification it is a post-apocalyptic game where the protagonist is trying to find a new home.

NameError: name 'rec' is not defined

Posted: 20 Nov 2021 10:53 AM PST

@api.onchange('is_present')  def onchange_attendance(self):      '''Method to make absent false when student is present'''      if rec.is_present:          rec.is_absent = False    @api.onchange('is_absent')  def onchange_absent(self):      '''Method to make present false when student is absent'''      if rec.is_absent:          rec.is_present = False    @api.constrains('is_present', 'is_absent')  def check_present_absent(self):      if not rec.is_present and not rec.is_absent:          raise ValidationError(_('Check Present or Absent for all Employees!!'))  

Prevent fast click in BottomNavigationView

Posted: 20 Nov 2021 10:52 AM PST

This is an extended question from How to prevent view double click , but for bottom navigation. Especially one set up with setupWithNavController().

The usual way of using your own click listener and compare previous click time doesn't work since Android NavigationUI is now handling the click.

For example I have a BottomNavigationView set up in fragment:

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {          super.onViewCreated(view, savedInstanceState)            val navHostFragment = childFragmentManager.findFragmentById(R.id.content_nav_host) as NavHostFragment          val navController = navHostFragment.findNavController()          val bottomNavigationView = view.findViewById<BottomNavigationView>(R.id.bottom_navigation)          bottomNavigationView.setupWithNavController(navController)      }  

If swapping between the fragment too fast, I get this error:

E/AndroidRuntime: FATAL EXCEPTION: main      Process: com.example.project, PID: 11136      java.lang.IllegalArgumentException: No destination with ID 2131296272 is on the NavController's back stack. The current destination is Destination(com.example.project/page1) label=page1 class=com.example.project.features.main.page1.Page1Fragment          at androidx.navigation.NavController.getBackStackEntry(NavController.java:1358)  

enter image description here

Exception is from Fragment is still in the middle of onCreateView(), some navigation happened and changed the navController backstrack before the fragment viewModel is access for the first time.

I guess the easiest way is to prevent bottom navigation from being able to click too fast from the start.

Demo and stacktrace

https://github.com/yatw/QuickSwapBottomNav

GO (Golang) does not see other .go files inside the same dir

Posted: 20 Nov 2021 10:53 AM PST

PROBLEM: functions exported for other packages are undefined, invisible from inside of main.go

SOLUTION: Put main.go into a separate folder (name it app or main, doesn't matter). Only go.mod remains in root, with the folders "app" and "package1" "package2" etc. After this VSCode automatically added imports on save, I didn't even need to do anything. If I have main.go in root then it doesn't work (most of the time) as it doesn't "see" functions from other modules (undefined)

I found the solution HERE,(see post by davidbost). The solution on this page by Andrey Dyatlov worked too for a while and then stopped working.

It took me probably 10 hours of try and error and searching. Hopefully the above will help others. Thank you, everyone!

_______________________________________________________________________

Original Problem Description:

Windows 10, Go 1.17, VS Code with Go extension.

Hello, I am new to Go and I was not able to follow a single tutorial due to the following issue. When I create another .go file in the same directory (or inside a folder of the same directory) as the main.go, I receive error saying .\main.go:7:2: undefined: SayHi


main.go file:

package main    import "fmt"    func main() {      fmt.Println("1st")      SayHi()  }  

another .go file inside /something folder:

package something    import "fmt"    func SayHi() {      fmt.Println("Hi!")  }  

Running go run main.go results in the undefined SayHi error

I googled the issue with no luck.

$ go build // gives out the same error

$ go install // gives out the same error

without using functions from other files $ go run main.go runs just fine.

I also tried go init with adding my github directory with no luck (by following a tutorial). I also tried the official starting guide with go run init, and the exported Capitalized function is still undefined. What's worse is that autocomplete for the SayHi function works, yet it won't compile because undefined.

I have set PATH to C:\Users\xxx\go and put my files there, I also tried using C:\Go with no luck, it's still undefined. I'm about to give up on Go...

How do I add an onScroll handler to the menuList of a react-select component?

Posted: 20 Nov 2021 10:50 AM PST

I would like to add an onScroll handler to a react-select component's menuList, but the following isn't working. I suspect that I need to set the onScroll for one of the children rather than an element that contains the children, but I don't know how to do that.

import React from 'react';    import Select, { components, MenuListProps } from 'react-select';  import {    ColourOption,    colourOptions,    FlavourOption,    GroupedOption,    groupedOptions,  } from './docs/data';      const handleScroll = () =>{    console.log('scrolling')  }    const MenuList = (    props: MenuListProps<ColourOption | FlavourOption, false, GroupedOption>  ) => {    return (      <components.MenuList {...props}>        <div onScroll={handleScroll}>          {props.children}        </div>      </components.MenuList>    );  };    export default () => (    <Select<ColourOption | FlavourOption, false, GroupedOption>      defaultValue={colourOptions[1]}      menuIsOpen={true}      options={groupedOptions}      components={{ MenuList }}    />  );  

https://codesandbox.io/s/codesandboxer-example-forked-jr74k?file=/example.tsx:0-721

I had also tried using something like this

mySelectRef.current.menuListRef.addEventListener("scroll", handleScroll)  

but .current or .current.menuListRef was always undefined or null at the time when the command executed. I tried using React.useEffect and setTimeout, with poor results. I'm hoping that I can just accomplish this by setting onScroll of the right inner div.

SyntaxError + Invariant Violation

Posted: 20 Nov 2021 10:50 AM PST

React Native 0.66.2 works perfectly without Hermes.

When I'm enabling Hermes :hermes_enabled => true the packager doesn't happy.

I'm getting this error:

ERROR  SyntaxError: 5:1:invalid statement encountered., js engine: hermes  ERROR  Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication). A frequent cause of the error is that the application entry file path is incorrect.        This can also happen when the JS bundle is corrupt or there is an early initialization error when loading React Native., js engine: hermes  

enter image description here

enter image description here

I tried to link all native libraries again (as says here) but with no luck :(

Any help will be super welcome 🙏

No comments:

Post a Comment