Saturday, October 2, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Detect if a game object instantiate inside a trigger

Posted: 02 Oct 2021 07:54 AM PDT

I create a cube with is trigger to simulate an elevator and there must be 4 players (player can instantiate copies of it pressing space) on this trigger to make it work. How can i do that script? Thanks.

DistributionWarning: discord.py is installed which is incompatible with nextcord

Posted: 02 Oct 2021 07:53 AM PDT

how to fix this, when I run my discord bot this appeared in terminal DistributionWarning: discord.py is installed which is incompatible with nextcord. Please remove this library by using `pip3 uninstall discord.py` warn(message, DistributionWarning, stacklevel=0)

how can i store List<object> in sharedpreferences using provider?

Posted: 02 Oct 2021 07:53 AM PDT

so basically this is my provider, what i want is how can i store the model data coming from provider to a shared preferences, and the how to decode it to show it in bookmark page?

class bookmark extends ChangeNotifier{    int _count = 0;    List<bookmarkModel> bookM = [];        void addCount(){      _count++;     notifyListeners();    }        void addItems(bookmarkModel i){     bookM.add(i);     notifyListeners();    }      int get  count => _count;    List<bookmarkModel> get  bookMList => bookM;    }  

here is my model:

import 'package:flutter/cupertino.dart';    class bookmarkModel{    String title;    String subtitle;    int ayahnum;      bookmarkModel({this.title, this.subtitle, this.ayahnum});      bookmarkModel.fromJson(Map<String,dynamic> json) :    title = json['title'],     subtitle = json['sutitle'],     ayahnum = json['ayahnum'];      Map<String, dynamic> toJson()=>{      'title':title,      'subtitle':subtitle,      'ayahnum': ayahnum    };   }  

How to import external js library (cdn) to react typescript project?

Posted: 02 Oct 2021 07:53 AM PDT

I need to import https://youglish.com/public/emb/widget.js to my React project and use its YG as a function. Basically, I need this widget in my React web app. I was able to use its tag. but I need to get the YG function into React app.

you may also consider https://youglish.com/api/doc/js-api

Methods I have tried so far!

1.

import 'https://youglish.com/public/emb/widget.js'    const Widget = () => {      const widget = new YG.Widget("widget-1");      widget.fetch("courage", "english");    };      return (      <>        <Widget />    .....  
import YG from "YG";     useEffect(() => {      const script = document.createElement("script");      script.src = "https://youglish.com/public/emb/widget.js";      script.async = true;      document.body.appendChild(script);    }, []);    const Widget = () => {      const widget = new YG.Widget("widget-1");      widget.fetch("courage", "english");    };      return (      <>        <Widget />    .....    added in index.html dody  <script        async        src="https://youglish.com/public/emb/widget.js"        charset="utf-8"      ></script>    errors:   Failed to compile.    ./src/App.tsx  Module not found: Can't resolve 'YG' in '/Users/.../Documents/Apps/Projects/.../src'  

Spring Boot, NamedParameterJdbcTemplate query and get generated PID from the postgres database

Posted: 02 Oct 2021 07:53 AM PDT

I'm using postgres and need to get the process identifier from postgres. Every running query in postgres has it's own PID which we can get via -> pg_stat_activity.

SELECT * FROM pg_catalog.pg_stat_activity;

This returns pid, which we can use to stop executing queries in database using

SELECT pg_terminate_backend();

The application is Spring Boot / Java and I make some huge queries using NamedParameterJdbcTemplate. They can take long time and in some cases I need to terminate executing queries.

The question is how can I get the PID from the generated sql query ?

How to fix Mongo saving integer as a double value

Posted: 02 Oct 2021 07:53 AM PDT

so im trying to save a userid of a user in discord using mongo and everytime i save it with some other data it saves it as a double type and in a different number from what i have sent and i made sure to give an integer to save but it still saves it different, do anyone know how to fix, the rest are saved correctly only the first value, i couldnot find anything online that can help me it just doesnot save reference image

Can someone help me with this

Posted: 02 Oct 2021 07:53 AM PDT

David Phillips is an American civil engineer and professor at the University of California (Davis, USA). He is best known as The Pudding Guy for accumulating many frequent-flyer miles by taking advantage of a promotion by Healthy Choice in 1999.

Phillips was pushing his shopping cart down the frozen-food aisle of his local supermarket when a promotion on a Healthy Choice frozen entree caught his eye. The company was offering frequent-flyer miles to customers who bought its products and submitted the UPCs back to the company. The details of the promotion included a bonus if the UPCs were mailed during the month of May 1999 (the mileage earned would double from 500 miles to 1000 miles for every 10 UPCs submitted). Phillips calculated that the return on a mail-in food promotion outweighed the price of the Healthy Choice frozen entrees, which were selling for $2.

A few aisles away Phillips found boxes containing four Healthy Choice soup cans at 70 dollar cents. Because he did not need a freezer to store the soups, he immediately decided to purchase 200 boxes of soup cans. At home he first had some trouble explaining the hoarding behaviour to his wife, but during a subsequent visit to the supermarket they discovered together an aisle display of Healthy Choice Pudding. Normally, the pudding was sold in 4-cup packs, but the display had been intended to introduce the new pudding and the single sample cups — originally 39 cents — were on sale at just 25 cents each! A 25-cent pudding having its own barcode would thus bring 100 miles. Over the next few weeks he purchased a total of 12,000 pudding cups, claiming he was stocking up for Y2K.

pudding Phillips and his wife had thus spent $3,140 in total for 800 soup cans and 12,000 pudding cups, but they had a problem. Not only could the family never consume this much soup and pudding, but more important they would not be able to remove the UPCs before the double certificate offer expired. After giving it some thought they enlisted the Salvation Army to help them peel off the UPC codes, in exchange for donating the pudding. He then mailed his submission to Healthy Choice, and to their credit they awarded him 1.25 million frequent-flyer miles — enough for 31 round trips to Europe, 42 to Hawaii, 21 to Australia, or 50 anywhere in the United States.

There's no downside. Phillips also got Advantage Gold status for life with American Airlines, which brings a special reservations number, priority boarding, upgrades and bonus miles. And he got an $815 tax write off for donating the soup and the pudding.

Input The following four numbers, each on a separate line:

total number of items purchased of a certain product (integer)

cost per item of the product (float)

number of UPCs needed for a frequent-flyer coupon (integer)

number of miles earned per frequent-flyer coupon (integer)

Output A sentence describing the amount in dollars spent by Phillips to purchase all items of the product and the number of frequent-flyer miles he earned with this purchase. Use the output as given in the examples below as a template to format the sentence. The amount of money spent should be output as a floating point number and the number of frequent-flyer miles received as an integer.

Example Input:

200 0.70 12 550 Output:

Phillips spent $140.0 for 8800 frequent-flyer miles. Example Input:

12000 0.25 10 1000 Output:

Phillips spent $3000.0 for 1200000 frequent-flyer miles.

Sending http request from multiple threads using boost::asio. How to handle responses serially

Posted: 02 Oct 2021 07:53 AM PDT

For a client side application, I wish to serialize http post requests using strand, in order to avoid overlapping writes/ responses to/from the server.

Serialization is made using boost::asio, by calling the method as a callback from strand.post as shown below. Notice that inside each http session (write request and read it's response, is made in a separated callback. (Notice that within the post, the http is made synchronously.

boost::asio::io_context::strand strand_;    void Send(     boost::beast::http::request<boost::beast::http::string_body> &req) {    strand_.post([=]() {        boost::beast::http::request<boost::beast::http::string_body> req;        // prepare request ...        boost::beast::http::write(stream_, req);        ...        boost::beast::http::response<boost::beast::http::dynamic_body> res;        boost::beast::flat_buffer buffer;        boost::beast::error_code ec;        boost::beast::http::read(stream_.socket(), buffer, res, ec);    }    

As can be seen from my example, the response reading is also made within the post callback. My question is whether this is actually required if I don't care about the ordering of reading the responses. can I assume that after each http request sent to the server boost::beast::http::write(stream_, req);, the data is already waiting in the rx buffer queue, so another thread may read the responses one-by-one ?

thanks !

Variable not being set in class using inheritance

Posted: 02 Oct 2021 07:52 AM PDT

I have an issue with the class below called ProjectileWeapon. It is based on an abstract class called Weapon, and that class inherits MonoBehaviour.

Weapon has two abstract functions called BeginCycle and EndCycle which are implemented in the ProjectileWeapon class. Those functions set a variable called "firing".

The problem is, "firing" doesn't ever seem to be set despite the functions being called correctly. I know the functions are called because I can see the prints in the console.

Also, when I use that variable in the update function, it doesn't do anything because the variable never changes.

The OnGUI function is working and is displaying text on screen, however the "firing" variable is never updated.

Am I misunderstanding how to use inheritance?

public class ProjectileWeapon : Weapon  {        private bool firing;      private float firingTimer;        void Start()      {          print("ProjectileWeapon start");      }      void OnGUI()      {          GUI.Label(new Rect(0,100,100,100), "ProjectileWeapon firing: " + firing);      }        void Update()      {          // this function is called but "firing" is not updated      }        public override void BeginCycle()      {          print("projectile begin cycle");          firing = true;      }        public override void EndCycle()      {          print("projectile end cycle");          firing = false;      }  }  

Here's the base class:

public abstract class Weapon : MonoBehaviour  {      public abstract void BeginCycle();      public abstract void EndCycle();  }  

Count rows that have same value in all columns

Posted: 02 Oct 2021 07:52 AM PDT

If I have a dataframe like this:

A  B  C  D  E  F        ------------------  1  2  3  4  5  6  1  1  1  1  1  1  0  0  0  0  0  0  1  1  1  1  1  1  

How can I get the number of rows that have value 1 in every column? In this case, 2 rows have 1 in every field.

I know one way, for example if we only take columns A and B:

count = df2.query("A == 1 & B == 1").shape[0]  

But I have to put the name of every column, is there a more fancy approach?

Thanks in advance

BeautifulSoup tag unwrap failing due to string

Posted: 02 Oct 2021 07:52 AM PDT

I am struggling to unwrap an HTML tag in BeautifulSoup with it giving me the error "AttributeError: 'str' object has no attribute 'next_element'". Any ideas on what is causing this?

The code is:

text = BeautifulSoup('<p>only <span class="xref"><span class="xrefout" id="SRC27"><a href="/handbook/IFPRU/7/#DES1">IFPRU 7</a></span></span> (Liquidity) and <span class="xref"><span class="xrefout" id="SRC28"><a href="/handbook/Note/9/#DES1">Note 9</a></span></span> (disclosure) apply to an <a class="autodeftext" href="/handbook/glossary/G30.html">exempt firm</a> and <span class="xref"><span class="xrefout" id="SRC29"><a href="/handbook/Note/8/1.html#DES2">Note 8.1</a></span></span> (consolidation) may apply subject to the conditions in that section; and</p>','html.parser')    #text = BeautifulSoup(text_src,'html.parser')    #print(type(text))    for tag in text.select('*'):      tag.unwrap()    print(text.get_text())   

An unhandled exception occurred during the execution of the current web request. Server Error in '/' Application

Posted: 02 Oct 2021 07:51 AM PDT

using System;  using System.Collections.Generic;  using System.Linq;  using System.Web;  using System.Web.UI;  using System.Web.UI.WebControls;  using System.IO;  using System.Data;  using System.Data.SqlClient;  using System.Drawing;    namespace WebApplication2  {      public partial class WebForm3 : System.Web.UI.Page      {          SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|Akanksha.mdf;Integrated Security=True");          protected void Page_Load(object sender, EventArgs e)          {              if (con.State == ConnectionState.Open)              {                  con.Close();              }              con.Open();              if(!IsPostBack)              {                  Calendar1.Visible = false;              }          }            protected void TextBox6_TextChanged(object sender, EventArgs e)          {            }            protected void Calendar1_SelectionChanged(object sender, EventArgs e)          {            }            protected void Button1_Click(object sender, EventArgs e)          {              SqlCommand cmd = con.CreateCommand();              cmd.CommandType = CommandType.Text;              cmd.CommandText = "insert into Tabel values('" + Studentname + "','" + email + "','" + phone + "','" + DOB + "','" + marks + "')";              cmd.ExecuteNonQuery();              Studentname.Text = " ";              email.Text = " ";              phone.Text = " ";              id.Text = " ";              DOB.Text = " ";              marks.Text = " ";                if (FileUpload1.HasFile)              {                  string Fileext = System.IO.Path.GetExtension(FileUpload1.FileName);                  if (Fileext.ToLower() == ".doc" || Fileext.ToLower() == ".docx")                  {                      FileUpload1.SaveAs(Server.MapPath("~/upload/" + FileUpload1.FileName));                      Label7.Text = "File is uploaded";                  }                    else                  {                      Label7.Text = ".docx,.doc format accepted only";                  }              }              else              {                  Label7.Text = "file not attached";              }          }            protected void ImageButton1_Click(object sender, ImageClickEventArgs e)          {            }            protected void Button4_Click(object sender, EventArgs e)          {              Calendar1.Visible = true;          }            protected void Calendar1_SelectionChanged1(object sender, EventArgs e)          {              DOB.Text = Calendar1.SelectedDate.ToShortDateString();          }      }            }    
              <asp:Label ID="Label1" runat="server" Text="id"></asp:Label>              <asp:TextBox ID="id" runat="server"></asp:TextBox>              <br />              <asp:Label ID="Label2" runat="server" Text="Studentname"></asp:Label>              <asp:TextBox ID="Studentname" runat="server"></asp:TextBox>              <br />              <asp:Label ID="Label3" runat="server" Text="email"></asp:Label>              <asp:TextBox ID="email" runat="server"></asp:TextBox>              <br />              <asp:Label ID="Label4" runat="server" Text="phone"></asp:Label>              <asp:TextBox ID="phone" runat="server"></asp:TextBox>              <br />              <asp:Label ID="Label5" runat="server" Text="hsc marks"></asp:Label>              <asp:TextBox ID="marks" runat="server"></asp:TextBox>              <br />              <asp:Label ID="Label6" runat="server" Text="Date of Birth"></asp:Label>              <br />              <asp:TextBox ID="DOB" runat="server"></asp:TextBox>              <asp:Button ID="Button4" runat="server" ForeColor="#66FF33" Height="16px" OnClick="Button4_Click" Text="Button" Width="36px" />              <asp:Calendar ID="Calendar1" runat="server" OnSelectionChanged="Calendar1_SelectionChanged1"></asp:Calendar>              <asp:Label ID="Label7" runat="server" Text="Marksheet "></asp:Label>              <br />              <asp:FileUpload ID="FileUpload1" runat="server" />            </div>          <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" />          <asp:Button ID="Button2" runat="server" Text="clear" />          <asp:Button ID="Button3" runat="server" Text="Update" />      </form>  

i have been trying very hard to insert data into sql server database c# in asp.net but it keeps on giving me error such as invalid object Tabel even though the tabel name is Tabel and red colour highlightes the cmd.ExecuteNonQuery saying exception was not handled

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Data.SqlClient.SqlException: Invalid object name 'Tabel'.

enter image description here

there might be some other mistakes do let me know i am newbie

How to read a file contained in same module as __main__.py from outside the module?

Posted: 02 Oct 2021 07:53 AM PDT

Here is my file tree:

foo    |-- bar    |-- |-- __main__.py    `-- `-- some_file.txt    

Here's __main__.py:

with open('some_file.txt', 'r') as f:      print(f.read())  

When the current working directory is bar/ and I run

$ python __main__.py

the result is to print whatever content is in some_file.txt to console.

When I change the current working directory to foo/ and run

$ python bar/

I get this:

Traceback (most recent call last):    File "/data/data/com.termux/files/home/foo/bar/__main__.py", line 1, in <module>      with open('some_file.txt', 'r') as f:  FileNotFoundError: [Errno 2] No such file or directory: 'some_file.txt'  

How do I fix this?

Using Scanner to add to empty Object

Posted: 02 Oct 2021 07:51 AM PDT

Trying to add user input to an empty object, but am getting Null. I think I set the scanner up properly, but not sure on that also. Not sure how the scanner should be set up to be linked to the empty object. I have setters and getters set up on another Class.

import java.util.Scanner;    public class StudentRecordTestHarness       {            public static void main (String []args)            {                 StudentRecord sr1 = new StudentRecord ("Tim", "Lost", 12345, 75);                       System.out.println("First Name: " + sr1.getFirstName());                 System.out.println("Last Name: " + sr1.getLastName());                 System.out.println("Student ID: " + sr1.getStudentID());                 System.out.println("Number Grade for Course: " + sr1.getGradeCourseOne());                 System.out.println("Grade Converted to Letter: " +                            sr1.GradeLetter(+sr1.getGradeCourseOne()));                       StudentRecord sr2 = new StudentRecord();                 Scanner userInput = new Scanner (System.in);                 System.out.println("Please Enter Student's First Name: ");                 String setFirstName = userInput.nextLine();                       System.out.println("New Student First Name: " + sr2.getFirstName());            }       }  

Pretty new to all this, so any guidance is a big help. Thanks!

How i can fix Wordpress woocommerce error php

Posted: 02 Oct 2021 07:52 AM PDT

Hello i have these problem in qwery monitor :

Constant WP_DEBUG already defined
Constant WP_DEBUG_LOG already defined
Constant WP_DEBUG_DISPLAY already defined

How to fix ?

discord.js displaying pinged user banner

Posted: 02 Oct 2021 07:52 AM PDT

i wanna make it display the pinged user banner heres my code. it only shows the user thats using the command banner.

const Discord = require('discord.js');    module.exports = {      name: 'banner',      category: "utility",      description: "Get a user's/your banner",      run: async(client, message, args) => {          if (!args[0]) {            async function getUserBannerUrl(userId) {              const user = await client.api.users(userId).get();              return user.banner ? `https://cdn.discordapp.com/banners/${userId}/${user.banner}?size=512` : null;          }          const bannerUrl = await getUserBannerUrl(message.author.id, { size: 4096 });          if (bannerUrl) {              const embed = new Discord.MessageEmbed()                  .setTitle(`${users.username}'s banner`)                  .setColor('#2f3136')                  .setImage(bannerUrl);              message.channel.send(embed);          } else {              message.channel.send("buy discord boost you peasant");          }      }      }  }```  

React setState() not update the state

Posted: 02 Oct 2021 07:51 AM PDT

State

state = {      likedPosts: [{movie: '5b21ca3eeb7f6fbccd471816', down: true}],    };  

function

  handleLike(movieId) {      if (this.state.likedPosts.filter((e) => e.movie === movieId).length > 0) {        const likedPosts = this.state.likedPosts.filter(function (l) {          if (l.movie !== movieId) {            return l;          }        });        console.log(likedPosts); // this returns the expected object        this.setState({ likedPosts }); // this not work      } else {        this.state.likedPosts.push({ movie: movieId, down: true }); // this works      }    }  

I want push new object if object not in this.state.likedPosts array or remove the object if that object in array.

When object exist in this.state.likedPosts, console.log(likedPosts) returns the expected new array. But this.setState({ likedPosts }) does not update the state. What is the problem in here?

How to restrict user from entering number in to an input field with type as text?

Posted: 02 Oct 2021 07:51 AM PDT

How to disable the user from entering a number in to input field . When we use type as number we are restricted from entering text in to the input .The same way how to achieve the vice versa . Someone help i need this to complete my assignment.

<input type="text" name="name" />  

C++ using switch-case return value as a condition for if statement

Posted: 02 Oct 2021 07:54 AM PDT

May one write something like this in c++:

// ...  if(value <= switch(secValue){     case First:        return 1;     case Second:        return 2;     return -1;  }){     //... do some logic ...  } // end if  

Thanks

Div not occupying the rest of the space with Position: Fixed (Not resolved)

Posted: 02 Oct 2021 07:52 AM PDT

I have 2 divs inside a container class. One div is having a fixed width and I want the other div to occupy the rest of the available space. ** It's working properly when I don't have position: fixed in the CSS** When I have a position: fixed in the test class, it's overlapping with the other element and not accounting there is already a div there. Can someone help me solve this?

Just Imagine 10 as a right sidebar. So the position of 10 is fixed (position: fixed)and I want the red box to fill the remaining space to the left.

.container {    border: 2px dotted yellow;    display: flex;    flex-wrap: wrap;    flex-direction: column;    width: 100%;    height: auto;  }    .test {    width: 100px;    position: fixed;  }    .area {    width: 1fr;    border: 3px solid red;  }
<div class="container">    <div class="test">10</div>    <div class="area">container</div>  </div>

Image reference of my problem

Adding a normal curve on frequency histogram in R

Posted: 02 Oct 2021 07:51 AM PDT

I decided to go through my statistics courses, which are taught in SPSS, but do in R, as I would like to learn to do stats there. I am currently doing histograms for two numerical continuous varables data$alcohol (alcohol misuse scale score) and data$age but got stuck on the first one.

The main issues are:

  1. My histogram looks different from the picture in the answer sheet
  2. I cannot add a normal curve unless I change the aes to density, which I do not want to do, as the exercise asks for frequency

Here is what I wrote:

data <- read_excel("~/Dropbox/My Mac (jmbp.local)/Desktop/Kings College London/2021:2022/Statistics/Week 1 stats/cleandata.xlsx")    mean_alc <- mean(data$alcohol)  sd_alc <- sd(data$alcohol)     p <- ggplot(data= data) +     geom_histogram(mapping = aes(x = alcohol, y=..count..),                   breaks=seq(0, 20, by=1),                    col="black",                    fill="white",                    alpha = 1) +     labs(title="Alcohol Misuse Score", x="Alcohol Misuse Score", y="Frequency") +     xlim(c(0,20)) +     ylim(c(0,20)) +    stat_function(fun = dnorm, colour = "red", args=list(mean = mean(data$alcohol), sd = sd(data$alcohol))) +    plot(density(data$alcohol, bw = 0.05))  p  

my histogram looks like this:

My histogram

the picture included in the solutions (done in SPSS) looks like this:

Histogram in the answer sheet

My first question is why the bars in my histogram look different than the ones in the answer sheet? is there some fundamanetal difference in how SPSS does histograms and how R does it? Secondly, is there a way to add a normal curve to the frequency histogram in ggplot 2? For reference this is how this can be done in SPSS:

Frequency histogram with normal curve in SPSS

the data$alcohol has the following values:

alcohol = c(15.78121, 17, 17.61943, 17.61943, 14.67395, 17.61943, 17, 17, 13.72413, 13.72664, 17, 15.86039, 17, 15.78121, 11.48049, 14.61672, 12.73437, 8, 17, 15.86039, 14.59133, 15.78121, 14.61672, 17, 17, 18, 15.78121, 10, 14.67395, 9, 7.033369, 17, 17, 15.86039, 15.78121, 18, 13.07577, 18, 8, 17.61943, 15.86039, 11.53364, 11.4323, 18, 6.390277, 17, 14.59133, 18, 14.9238, 15.78121, 14.61672, 17, 17.61943, 14.67395, 8, 18, 8, 17.61943, 14.4069, 6.477451, 7.02489, 18, 18, 13.09201, 15.78121, 14.59133, 18, 5.451102, 9, 4.801972, 15.86039, 15.86039, 17, 17, 17)  

Android studio got stuck at creating flutter project

Posted: 02 Oct 2021 07:52 AM PDT

After upgrading my flutter, when i try to create a new flutter project it get stuck showing creating flutter project for hours without any change And when i run flutter doctor -v, i have no issues.

[√] Android toolchain - develop for Android devices (Android SDK version 30.0.2)      • Android SDK at C:\Users\USER\Documents\Sdk      • Platform android-30, build-tools 30.0.2      • ANDROID_HOME = C:\Users\USER\Documents\Sdk      • Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java      • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b01)      • All Android licenses accepted.    [√] Chrome - develop for the web      • Chrome at C:\Program Files\Google\Chrome\Application\chrome.exe    [√] Android Studio (version 4.1)      • Android Studio at C:\Program Files\Android\Android Studio      • Flutter plugin can be installed from:         https://plugins.jetbrains.com/plugin/9212-flutter      • Dart plugin can be installed from:         https://plugins.jetbrains.com/plugin/6351-dart      • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b01)    [√] VS Code (version 1.60.0)      • VS Code at C:\Users\USER\AppData\Local\Programs\Microsoft VS Code      • Flutter extension version 3.23.0    [√] Connected device (1 available)      • Chrome (web) • chrome • web-javascript • Google Chrome 92.0.4515.107    • No issues found!  

enter image description here

Typescript: Is it possible to ensure the key and an inner value are the same string?

Posted: 02 Oct 2021 07:53 AM PDT

I have a Record of data that could become large. I'm wondering if is it possible to enforce the key of the Record to be the same as the inner name value?.

interface Person<T> {    name: T    title: string    description: string  }    type People = Record<string, Person<string>>    // example data    const data: People = {    sarah: {      name: 'sarah',      title: 'Sarah',      description: 'Hello',    }  }    const badData: People = {    adam: {      name: 'john', // This would cause a typescript error ideally.      ...    }  }  

I've tried setting up People with a generic but it would require me to add all the keys to a union type which I would rather avoid. keyof doesn't work as the object isn't defined where the keyof is needed.

type People<T> = Record<T, Person<T>>    const people: People<keyof typeof people> = {} // Block-scoped variable 'people' used before its declaration.ts(2448)  

How to compare struct keys from nested json in Golang

Posted: 02 Oct 2021 07:52 AM PDT

I am new to go , I am trying to compare keys from the json structure as below.

{      "cluster_name": "escluster",      "nodes": {          "node1": {              "timestamp": 1460624696217,              "name": "master1",              "transport_address": "10.0.0.1:9300",              "host": "10.0.0.1:9300",              "ip": [                  "10.0.0.1:9300",                  "NONE"              ],              "attributes": {                  "data": "false",                  "master": "true"              },              "os": {                  "timestamp": 1460624696217,                  "cpu_percent": 0,                  "load_average": 0,                  "swap": {                      "total_in_bytes": 0,                      "free_in_bytes": 0,                      "used_in_bytes": 0                  }              }          },          "node2": {              "timestamp": 1460624696217,              "name": "master2",              "transport_address": "10.0.0.1:9300",              "host": "10.0.0.1:9300",              "ip": [                  "10.0.0.1:9300",                  "NONE"              ]              "os": {                  "timestamp": 1460624696217,                  "cpu_percent": 0,                  "load_average": 0,                  "mem": {                      "free_percent": 84,                      "used_percent": 16                  }              }          },          "nodesData":[            {               "nodeId": ["node1","node2"]               "timestamp": 1460624696217,               "name": "master1",               "transport_address": "10.0.0.1:9300",               "host": "10.0.0.1:9300"             }          ]  }  

Question:

Is it possible to check and generate the final config that is if key exist on both struct ignore else add ?

Output

since there are 2 id present it will first add "nodesData" to "tempData" then compare node 1 data in "tempData" and then "node2" data will be compared to "tempData" here "attributes" and "mem" doesn't exist so add to "tempData" and then add temp node to "nodesData"

How to execute this having trouble converting this to code ?

{      "cluster_name": "escluster",           "nodesData":{               "timestamp": 1460624696217,              "name": "master1",              "transport_address": "10.0.0.1:9300",              "host": "10.0.0.1:9300",               "ip": [                  "10.0.0.1:9300",                  "NONE"              ],              "attributes": {                  "data": "false",                  "master": "true"              },              "os": {                  "timestamp": 1460624696217,                  "cpu_percent": 0,                  "load_average": 0,                  "swap": {                      "total_in_bytes": 0,                      "free_in_bytes": 0,                      "used_in_bytes": 0                  },                  "mem": {                      "free_percent": 84,                      "used_percent": 16                  }              }          }          }  }  

Tried marshal and unmarshalling but it overrides data if same key exist in case multiple ids are passed in nodeid

Above approach https://play.golang.org/p/yXjf_htKJ3c

Invoking API Gateway Endpoint from AWS Amplify gives CORS error

Posted: 02 Oct 2021 07:53 AM PDT

I am attempting to call an API endpoint in API gateway using a HTML website hosted in AWS Amplify. When I make the request:

var xhrHeaders = new Headers();      xhrHeaders.append("Content-Type","application/json");      var requestOptions = {        method: 'POST',        headers: xhrHeaders,        body: formData,        redirect: 'follow',      };        fetch("MyAPIGURL",requestOptions)      .then(response => response.text())      .then(result => alert(JSON.parse(result).body))      .catch(error=>console.log('error', error))  

I am consistently getting a CORS error:

Access to fetch at 'XXXX' from origin 'https://XXXX.amplifyapp.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.  

However, I have gone into the API gateway and enabled CORS. I can see an OPTIONS endpoint has been created and a header mapping has been set:

Access-Control-Allow-Origin '*'  

I can see that coming back in the browser too:

1.  access-control-allow-headers:   Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token  2.  access-control-allow-methods:   OPTIONS,POST  3.  access-control-allow-origin:   *  4.  content-length:   0  5.  content-type:   application/json  6.  date:   Fri, 01 Oct 2021 10:41:07 GMT  

Yet it will not work and it is blocked at the browser. I have also tried adding

mode: "no-cors"

to my requestOptions but that does nothing. I can send requests via Postman as you'd expect but I'm a bit lost as to what to try next.

Any ideas?

Thanks

Angular- Prevent selection of same options from a dropdown

Posted: 02 Oct 2021 07:53 AM PDT

I made this dropdown with a textarea for input in angular material dialog. There I have only three options in the dropdown(so far)-'English','French' and 'Canadian French'. I have already disabled 'English' by default. Now, for the rest of the remaining options, when I click 'Add new Language' button and select an option(french ; say) and add text I am able to disable the selected option so that when the user adds the third language they cannot select it again. It works fine. Like this (This is without hitting the save button) enter image description here Now the problem starts here. When I select 'French'(say) and hit the save button. And again open the dialog-box. I am again seeing 'French' along with 'Canadian French' in the options for the adding a third language. What do I do to make it inactive and grey-ish like 'English'?enter image description here

This the ts code:

export class ModalAllComponent implements OnInit {      dialogData: DialogDataModel;      languages: any[];      rows: any[];      item!:any[];      constructor(       public dialogRef:MatDialogRef<ModalAllComponent>,       @Inject(MAT_DIALOG_DATA) public data: DialogDataModel) {        this.dialogData = data;        this.rows = this.dialogData.localisedEntities.filter(lang => lang.value,)        this.languages = this.dialogData.localisedEntities.map(item => ({ code: item.code, title: item.title, canEdit: item.canEdit }))        console.log(this.dialogData)      }      ngOnInit(): void {    }      addNewLanguage() {      this.rows.push({        code: '',        title: '',        value: '',        canEdit: true      });    }      onChangeValue(ev: any){      this.rows = this.rows.map(row => {        if (row.code == ev.value) {          const lang = this.languages.find(lang => lang.code == ev.value);          row.title =lang.title;        }        return row;      })        console.log(this.rows)        this.languages = this.languages.map(lang => {        if (lang.code == ev.value) {          lang.canEdit = false;          console.log(lang);        }        return lang;      });      this.isDisabled()    }      isDisabled(){      return this.rows.filter((item) => item.value == '' || item.code == '')          .length > 0          ? true          : false;    }      submit(ev:any){      this.dialogRef.close({data: this.rows});    }      back(){      this.dialogRef.close()    }      removeBtn(index:number){      this.rows.splice(index, 1);    }  }  

I was console-logging at a lot of places and finally manage to draw down to these place where the problem might be happening. In console.log(lang), I saw that, when I selected 'French',the flag canEdit turned to false.But in console.log(this.rows), when I selected 'French',the flag canEdit did not turned to false

How to solve the issue?

The HTML code:

<div>    <table class="justify-content-between">      <tr *ngFor="let entity of rows; let i = index">        <td class="col-1" *ngIf="entity.value!=null">          <mat-select [(ngModel)]="entity.code" [disabled]="!entity.canEdit"  (selectionChange)="onChangeValue($event)">            <mat-option *ngFor="let lang of languages" [disabled]="!lang.canEdit" [value]="lang.code">{{ lang.title }}</mat-option>          </mat-select>          <!-- <mat-error *ngIf="entity.code.hasError('required')">Please choose an language</mat-error> -->        </td>        <td class="col-1" *ngIf="entity.value!=null">          <textarea style="height: 2rem" class="pl-5" [disabled]="!entity.canEdit" [(ngModel)]="entity.value">{{ entity.value }}</textarea>          <mat-icon class="pl-2" style="color: red;font-size: 2rem;cursor: pointer;" (click)="removeBtn(i)">close</mat-icon>        </td>      </tr>    </table>    <div class="d-flex flex-column align-items-center mt-2">      <button class="form-control" (click)="addNewLanguage()" *ngIf="rows.length < dialogData.localisedEntities.length" [disabled]="isDisabled()">Add new language</button>        <div class="d-flex pt-2">          <button class="form-control" [disabled]="isDisabled()" (click)="back()">Discard</button>          <button class="form-control ml-4 pl-4 pr-4" [disabled]="isDisabled()" (click)="submit($event)">Save</button>        </div>    </div>  </div>  

This is where the modal is opening:

localiseFoodName() {      const dialogData = < DialogDataModel > {        localisedEntities: this.foodModel.localisedName.map((item: any) => {          if (item.code == 'en') {            item.canEdit = false;          } else {            item.canEdit = true;          }          return item;        }),      };        let dialogRef = this.dialog.open(ModalAllComponent, { width: '26.5rem', data: dialogData });        dialogRef.afterClosed().subscribe(res => {          if (res && res.data) {          console.log(res)          console.log(res.data)          let temp:any          this.foodModel.localisedName.map((item:any)=>{            temp = res.data.find((element:any)=> element.code === item.code);            if(temp){              item.value = temp.value              item.canEdit = temp.canEdit = false            }            //console.log(temp)          })          const food  = this.foodModel.localisedName          console.log(food)        }      })    }  

When I console.log(food) I could see the canEdit:false. But when I open the modal again, in console.log(this.dialogData) the canEdit is again "True" for the selected item enter image description here

Thanks in advance for the help!

Is there a way to disallow creating a git branch with a particular name, locally?

Posted: 02 Oct 2021 07:51 AM PDT

I have some projects which use "master" and others which use "main" and I am constantly accidentally checking out one or the other. The big problem is when on a project that uses "main" and also heroku, which uses "master", so git checkout master succeeds and seems normal.

Is there a way to configure something locally so that creating this branch will blow up?

Installing keras in R: WARNING: pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available

Posted: 02 Oct 2021 07:52 AM PDT

I am new to keras and was trying to install keras and tensorflow in R on my computer running Windows 10 using this guide but get the error in the title:

install_keras()    Collecting package metadata (current_repodata.json): ...working... done  Solving environment: ...working... done    All requested packages already installed.    WARNING: pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.  WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/tensorflow/  WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/tensorflow/  WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/tensorflow/  WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/tensorflow/  WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/tensorflow/  Could not fetch URL https://pypi.org/simple/tensorflow/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/tensorflow/ (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.")) - skipping  ERROR: Could not find a version that satisfies the requirement tensorflow==2.6.* (from versions: none)  ERROR: No matching distribution found for tensorflow==2.6.*  WARNING: pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.  Could not fetch URL https://pypi.org/simple/pip/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/pip/ (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.")) - skipping  Error: Error installing package(s): "\"tensorflow==2.6.*\"", "\"tensorflow-hub\"", "\"scipy\"", "\"requests\"", "\"Pillow\"", "\"h5py\"", "\"pandas\""  

I tried installing OpenSSL due to this question and also tried copying dll's as described here, but nothing works.

Any suggestions?

Separate scripts from .GlobalEnv: Source script that source scripts

Posted: 02 Oct 2021 07:52 AM PDT

This question is similar to Source script to separate environment in R, not the global environment, but with a key twist.

Consider a script that sources another script:

# main.R  source("funs.R")  x <- 1  
# funs.R  hello <- function() {message("Hi")}  

I want to source the script main.R and keep everything in a "local" environment, say env <- new.env(). Normally, one could call source("main.R", local = env) and expect everything to be in the env environment. However, that's not the case here: x is part of env, but the function hello is not! It is in .GlobalEnv.

Question: How can I source a script to a separate environment in R, even if that script itself sources other scripts, and without modifying the other scripts being sourced?

Thanks for helping, and let me know if I can clarify anything.

EDIT 1: Updated question to be explicit that scripts being source cannot be modified (assume they are not under your control).

Angular 2 'component' is not a known element

Posted: 02 Oct 2021 07:52 AM PDT

I'm trying to use a component I created inside the AppModule in other modules. I get the following error though:

"Uncaught (in promise): Error: Template parse errors:

'contacts-box' is not a known element:

  1. If 'contacts-box' is an Angular component, then verify that it is part of this module.
  2. If 'contacts-box' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.

My project structure is quite simple: Overall project structure

I keep my pages in pages directory, where each page is kept in different module (e.g. customers-module) and each module has multiple components (like customers-list-component, customers-add-component and so on). I want to use my ContactBoxComponent inside those components (so inside customers-add-component for example).

As you can see I created the contacts-box component inside the widgets directory so it's basically inside the AppModule. I added the ContactBoxComponent import to app.module.ts and put it in declarations list of AppModule. It didin't work so I googled my problem and added ContactBoxComponent to export list as well. Didn't help. I also tried putting ContactBoxComponent in CustomersAddComponent and then in another one (from different module) but I got an error saying there are multiple declarations.

What am I missing?

No comments:

Post a Comment