问:
Add to backstack
I’m using Navigation component as my navigation stack.

I would like to build following back stack as I want my users to land back on screen B on back press on Screen C.

```<code>A -> B -> C
</code>```

Currently I’m doing

fun navigateToScreenC() {
   findNavController().navigate(R.id.nav_B)
   findNavController().navigate(R.id.nav_C)
}
```
<p>This causes a visual flicker/glitch where screen B is temporarily visible.<br />
Functionally however it does work!</p>
<p>Another option is to navigate to screen C and override the back button.<br />
While this might work, I don’t wish to couple screen C’s back navigation to a forward navigation to Screen B.</p>
<p>I also saw the <code>backQueue</code> on the <code>NavController</code> is public and can be mutated in code.<br />
However I was not successful in injecting a custom <code>NavBackStackEntry</code> and could not find any reference in the documentation on how to do so.</p>
<pre class="lang-kotlin prettyprint-override"><code>/**
 * Retrieve the current back stack.
 *
 * @return The current back stack.
 * @hide
 */
@get:RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public open val backQueue: ArrayDeque<NavBackStackEntry> = ArrayDeque()
</code>```

What is the correct way to programmatically add items to the backstack with Jetpack’s Navigation Library?

Title: Add to backstack

Body:
I’m using Navigation component as my navigation stack.

I would like to build following back stack as I want my users to land back on screen B on back press on Screen C.

A -> B -> C

Currently I’m doing

fun navigateToScreenC() {
   findNavController().navigate(R.id.nav_B)
   findNavController().navigate(R.id.nav_C)
}

This causes a visual flicker/glitch where screen B is temporarily visible.

Functionally however it does work!

Another option is to navigate to screen C and override the back button.

While this might work, I don’t wish to couple screen C’s back navigation to a forward navigation to Screen B.

I also saw the backQueue on the NavController is public and can be mutated in code.

However I was not successful in injecting a custom NavBackStackEntry and could not find any reference in the documentation on how to do so.

/**
 * Retrieve the current back stack.
 *
 * @return The current back stack.
 * @hide
 */
@get:RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public open val backQueue: ArrayDeque<NavBackStackEntry> = ArrayDeque()

What is the correct way to programmatically add items to the backstack with Jetpack’s Navigation Library?


来源: stackexchange

问:
NotImplementedError: Cannot convert a symbolic tf.Tensor to a numpy array
I have a tensorflow custom layer that I want to use with functional API for training. But I get a weird error that I don't know how to fix. Here is the code:

import math
import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import Input
from tensorflow.keras.models import Model

def scaled_dot_product_attention(query, key, value, mask=None):
  key_dim = tf.cast(tf.shape(key)[-1], tf.float32)
  scaled_scores = tf.matmul(query, key, transpose_b=True) / np.sqrt(key_dim)

  if mask is not None:
    scaled_scores = tf.where(mask==0, -np.inf, scaled_scores)

  softmax = tf.keras.layers.Softmax()
  weights = softmax(scaled_scores)
  return tf.matmul(weights, value), weights

class MultiHeadSelfAttention(tf.keras.layers.Layer):
  def __init__(self, d_model, num_heads):
    super(MultiHeadSelfAttention, self).__init__()
    self.d_model = d_model
    self.num_heads = num_heads

    self.d_head = self.d_model // self.num_heads

    self.wq = tf.keras.layers.Dense(self.d_model)
    self.wk = tf.keras.layers.Dense(self.d_model)
    self.wv = tf.keras.layers.Dense(self.d_model)

    # Linear layer to generate the final output.
    self.dense = tf.keras.layers.Dense(self.d_model)

  def split_heads(self, x):

    split_inputs = tf.reshape(x, (-1, self.num_heads, self.d_head))
    return tf.transpose(split_inputs, perm=[1,0,2])

  def merge_heads(self, x):

    merged_inputs = tf.transpose(x, perm=[1,0,2])
    return tf.reshape(merged_inputs, (-1, self.d_model))

  def call(self, q, k, v, mask):
    qs = self.wq(q)
    ks = self.wk(k)
    vs = self.wv(v)

    qs = self.split_heads(qs)
    ks = self.split_heads(ks)
    vs = self.split_heads(vs)

    output, attn_weights = scaled_dot_product_attention(qs, ks, vs, mask)
    output = self.merge_heads(output)

    return self.dense(output)

# -------- Model Building -----------
values = Input(shape=(3,12))
values_emb = MultiHeadSelfAttention(12, 3)(values,values,values, mask = None)
model = Model(values, values_emb)
model.summary()
```
<p>The <code>MultiHeadSelfAttention</code> class successfully works if you give it a random input and it generates an output. But it throws an error when you want to put it in a model. The error is:</p>
```NotImplementedError: Cannot convert a symbolic tf.Tensor (multi_head_self_attention_4/Cast:0) to a numpy array. This error may indicate that you're trying to pass a Tensor to a NumPy call, which is not supported.
```

Does anyone know how to fix this issue?

ContentLicense: CC BY-SA 4.0

Body:
I have a tensorflow custom layer that I want to use with functional API for training. But I get a weird error that I don't know how to fix. Here is the code:

import math
import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import Input
from tensorflow.keras.models import Model

def scaled_dot_product_attention(query, key, value, mask=None):
  key_dim = tf.cast(tf.shape(key)[-1], tf.float32)
  scaled_scores = tf.matmul(query, key, transpose_b=True) / np.sqrt(key_dim)

  if mask is not None:
    scaled_scores = tf.where(mask==0, -np.inf, scaled_scores)

  softmax = tf.keras.layers.Softmax()
  weights = softmax(scaled_scores)
  return tf.matmul(weights, value), weights

class MultiHeadSelfAttention(tf.keras.layers.Layer):
  def __init__(self, d_model, num_heads):
    super(MultiHeadSelfAttention, self).__init__()
    self.d_model = d_model
    self.num_heads = num_heads

    self.d_head = self.d_model // self.num_heads

    self.wq = tf.keras.layers.Dense(self.d_model)
    self.wk = tf.keras.layers.Dense(self.d_model)
    self.wv = tf.keras.layers.Dense(self.d_model)

    # Linear layer to generate the final output.
    self.dense = tf.keras.layers.Dense(self.d_model)

  def split_heads(self, x):

    split_inputs = tf.reshape(x, (-1, self.num_heads, self.d_head))
    return tf.transpose(split_inputs, perm=[1,0,2])

  def merge_heads(self, x):

    merged_inputs = tf.transpose(x, perm=[1,0,2])
    return tf.reshape(merged_inputs, (-1, self.d_model))

  def call(self, q, k, v, mask):
    qs = self.wq(q)
    ks = self.wk(k)
    vs = self.wv(v)

    qs = self.split_heads(qs)
    ks = self.split_heads(ks)
    vs = self.split_heads(vs)

    output, attn_weights = scaled_dot_product_attention(qs, ks, vs, mask)
    output = self.merge_heads(output)

    return self.dense(output)

# -------- Model Building -----------
values = Input(shape=(3,12))
values_emb = MultiHeadSelfAttention(12, 3)(values,values,values, mask = None)
model = Model(values, values_emb)
model.summary()

The MultiHeadSelfAttention class successfully works if you give it a random input and it generates an output. But it throws an error when you want to put it in a model. The error is:

NotImplementedError: Cannot convert a symbolic tf.Tensor (multi_head_self_attention_4/Cast:0) to a numpy array. This error may indicate that you're trying to pass a Tensor to a NumPy call, which is not supported.

Does anyone know how to fix this issue?


问:
How to create a C++ file that will insert text then remove it if the user doesn't insert further text
The title's a bit confusing so I'll explain here. The program will output an underscore line and then the date of entry to an existing text file, then allow the user to input whatever. Next time the program is run, a new underscore line and date will be put underneath the text from the user. I want to have the code read if text was actually input, and if not, delete the date and underscore line as to avoid having a blank input.

```<code>#include <iostream>
#include <fstream>
#include <string>
#include <ctime>

using namespace std;

string underscoreDiv (int lengthText){

    string underscores;

    for(int i{}; i<lengthText; i++)
    {
        underscores += "_";
    }

    return underscores + "\n";
}

struct Date
{
    int year;
    int month;
    int day;

    Date()
    {
        time_t t = time(0);
        tm* now = localtime(&t);

        year = now->tm_year + 1900;
        month = now->tm_mon + 1;
        day = now->tm_mday;
    }
};

int main(){

    fstream fileApp("C:\\Users\\trist\\OneDrive\\Documents\\Notes_application\\Notes_app.txt", ios::in | ios::app);

    if(fileApp.is_open()){

        string line;
        string underscore;
        Date date;

        underscore=underscoreDiv (80);

        fileApp.clear();

        fileApp<<"\n";
        fileApp<<underscore<<"\n";
        fileApp<<date.month<<"/"<<date.day<<"/"<<date.year<<" : ";

        fileApp.close();

    }
    else{
        cout<<"Text file not found";
    }

    return 0;
}
</code>```

Here, I'm trying to count the lines input, and read it back to me to make sure it's being counted right.

```<code>#include <iostream>
#include <fstream>
#include <string>
#include <ctime>

using namespace std;

string underscoreDiv (int lengthText){

    string underscores;

    for(int i{}; i<lengthText; i++)
    {
        underscores += "_";
    }

    return underscores + "\n";
}

struct Date
{
    int year;
    int month;
    int day;

    Date()
    {
        time_t t = time(0);
        tm* now = localtime(&t);

        year = now->tm_year + 1900;
        month = now->tm_mon + 1;
        day = now->tm_mday;
    }
};

int main(){

    fstream fileApp("C:\\Users\\trist\\OneDrive\\Documents\\Notes_application\\Notes_app.txt", ios::in | ios::app);

    if(fileApp.is_open()){

        string line;
        string underscore;
        Date date;
        int count[2]={0,0};

        underscore=underscoreDiv (80);

        while(getline(fileApp, line)){
           count[1]++;
        }

        fileApp.clear();

        fileApp<<"\n";
        fileApp<<underscore<<"\n";
        fileApp<<date.month<<"/"<<date.day<<"/"<<date.year<<" : ";

        fileApp.clear();

        cout<<count[1]<<endl;
        cout<<count[2]<<endl;

        fileApp.close();

    }
    else{
        cout<<"Text file not found";
    }

    return 0;
}
</code>```

count[1] seems to work right but count[2] will always output 2023.

1/3/2023 :  first test
____________________________________________________________>

1/3/2023 : second test
____________________________________________________________>

1/3/2023 : third test

1/3/2023 :  first test
____________________________________________________________>

1/3/2023 : second test
____________________________________________________________>

1/3/2023 : third test
____________________________________________________________>

1/5/2023 :

here is an example of the text file before and after running the program.

Body:
The title's a bit confusing so I'll explain here. The program will output an underscore line and then the date of entry to an existing text file, then allow the user to input whatever. Next time the program is run, a new underscore line and date will be put underneath the text from the user. I want to have the code read if text was actually input, and if not, delete the date and underscore line as to avoid having a blank input.

#include <iostream>
#include <fstream>
#include <string>
#include <ctime>

using namespace std;

string underscoreDiv (int lengthText){

    string underscores;

    for(int i{}; i<lengthText; i++)
    {
        underscores += "_";
    }

    return underscores + "\n";
}

struct Date
{
    int year;
    int month;
    int day;

    Date()
    {
        time_t t = time(0);
        tm* now = localtime(&t);

        year = now->tm_year + 1900;
        month = now->tm_mon + 1;
        day = now->tm_mday;
    }
};

int main(){

    fstream fileApp("C:\\Users\\trist\\OneDrive\\Documents\\Notes_application\\Notes_app.txt", ios::in | ios::app);

    if(fileApp.is_open()){

        string line;
        string underscore;
        Date date;

        underscore=underscoreDiv (80);

        fileApp.clear();

        fileApp<<"\n";
        fileApp<<underscore<<"\n";
        fileApp<<date.month<<"/"<<date.day<<"/"<<date.year<<" : ";

        fileApp.close();

    }
    else{
        cout<<"Text file not found";
    }

    return 0;
}

Here, I'm trying to count the lines input, and read it back to me to make sure it's being counted right.

#include <iostream>
#include <fstream>
#include <string>
#include <ctime>

using namespace std;

string underscoreDiv (int lengthText){

    string underscores;

    for(int i{}; i<lengthText; i++)
    {
        underscores += "_";
    }

    return underscores + "\n";
}

struct Date
{
    int year;
    int month;
    int day;

    Date()
    {
        time_t t = time(0);
        tm* now = localtime(&t);

        year = now->tm_year + 1900;
        month = now->tm_mon + 1;
        day = now->tm_mday;
    }
};

int main(){

    fstream fileApp("C:\\Users\\trist\\OneDrive\\Documents\\Notes_application\\Notes_app.txt", ios::in | ios::app);

    if(fileApp.is_open()){

        string line;
        string underscore;
        Date date;
        int count[2]={0,0};

        underscore=underscoreDiv (80);

        while(getline(fileApp, line)){
           count[1]++;
        }

        fileApp.clear();

        fileApp<<"\n";
        fileApp<<underscore<<"\n";
        fileApp<<date.month<<"/"<<date.day<<"/"<<date.year<<" : ";

        fileApp.clear();

        cout<<count[1]<<endl;
        cout<<count[2]<<endl;

        fileApp.close();

    }
    else{
        cout<<"Text file not found";
    }

    return 0;
}

count[1] seems to work right but count[2] will always output 2023.

1/3/2023 :  first test
____________________________________________________________>

1/3/2023 : second test
____________________________________________________________>

1/3/2023 : third test

1/3/2023 :  first test
____________________________________________________________>

1/3/2023 : second test
____________________________________________________________>

1/3/2023 : third test
____________________________________________________________>

1/5/2023 :

here is an example of the text file before and after running the program.


问:
What is causing the UnboundLocalError in my PyPDF2 cmap file?
I am trying to fix some broken python pdf splitting (PyPDF2) scripts that a coworker left behind.
I updated the PyPDF2 syntax in each script, but started running into an UnboundLocalError when trying to extract the text.

This error traces back to the cmap file within the PyPDF2 package:

```<code>Exception in thread Thread-1 (bill):
Traceback (most recent call last):
  File "C:\Python310\lib\threading.py", line 1009, in _bootstrap_inner
    self.run()
  File "C:\Python310\lib\threading.py", line 946, in run
    self._target(*self._args, **self._kwargs)
  File "<S: private info etc/1 - Split PDF DocumentsFIX.py>", line 26, in bill
    words = page.extract_text()
  File "C:\Python310\lib\site-packages\PyPDF2\_page.py", line 1851, in extract_text
    return self._extract_text(
  File "C:\Python310\lib\site-packages\PyPDF2\_page.py", line 1342, in _extract_text
    cmaps[f] = build_char_map(f, space_width, obj)
  File "C:\Python310\lib\site-packages\PyPDF2\_cmap.py", line 28, in build_char_map
    map_dict, space_code, int_entry = parse_to_unicode(ft, space_code)
  File "C:\Python310\lib\site-packages\PyPDF2\_cmap.py", line 194, in parse_to_unicode
    cm = prepare_cm(ft)
  File "C:\Python310\lib\site-packages\PyPDF2\_cmap.py", line 213, in prepare_cm
    if isinstance(cm, str):
UnboundLocalError: local variable 'cm' referenced before assignment
</code>```

Here is the code leading up to where the error is called in one of the files:

```<code>def bill(directory):
    start = time.time()
    for filename in os.listdir(directory):
        if filename.startswith('private info'):
            print(filename)
            main = open(directory+'\\'+filename,'rb')
        else:
            continue
    mainreader = PyPDF2.PdfReader(main)
    numpg = len(mainreader.pages)
    vault = []
    mthvault = []
    yrvault = []
    meow = datetime.datetime.now()
    lgnme = meow.strftime('%m%d%y_BillLog')
    print(lgnme)
    log = open('.\\'+lgnme+'.txt','w')
    dup = []
    for i in range(0,numpg,2):
        writer = PyPDF2.PdfWriter()
        page = mainreader.pages[i]
        words = page.extract_text()
</code>```

The workaround that I found is to open the _cmap.py file and declare the variable cm = "" on a new line within the prepare_cm function. The scripts execute as expected with the addition.

Manually updating the cmap file is pretty hacky, so I could use some help finding the actual source of the error.

Is this error occurring due to a dependency issue/bug, or is there an issue with the script itself?

Body:
I am trying to fix some broken python pdf splitting (PyPDF2) scripts that a coworker left behind.
I updated the PyPDF2 syntax in each script, but started running into an UnboundLocalError when trying to extract the text.

This error traces back to the cmap file within the PyPDF2 package:

Exception in thread Thread-1 (bill):
Traceback (most recent call last):
  File "C:\Python310\lib\threading.py", line 1009, in _bootstrap_inner
    self.run()
  File "C:\Python310\lib\threading.py", line 946, in run
    self._target(*self._args, **self._kwargs)
  File "<S: private info etc/1 - Split PDF DocumentsFIX.py>", line 26, in bill
    words = page.extract_text()
  File "C:\Python310\lib\site-packages\PyPDF2\_page.py", line 1851, in extract_text
    return self._extract_text(
  File "C:\Python310\lib\site-packages\PyPDF2\_page.py", line 1342, in _extract_text
    cmaps[f] = build_char_map(f, space_width, obj)
  File "C:\Python310\lib\site-packages\PyPDF2\_cmap.py", line 28, in build_char_map
    map_dict, space_code, int_entry = parse_to_unicode(ft, space_code)
  File "C:\Python310\lib\site-packages\PyPDF2\_cmap.py", line 194, in parse_to_unicode
    cm = prepare_cm(ft)
  File "C:\Python310\lib\site-packages\PyPDF2\_cmap.py", line 213, in prepare_cm
    if isinstance(cm, str):
UnboundLocalError: local variable 'cm' referenced before assignment

Here is the code leading up to where the error is called in one of the files:

def bill(directory):
    start = time.time()
    for filename in os.listdir(directory):
        if filename.startswith('private info'):
            print(filename)
            main = open(directory+'\\'+filename,'rb')
        else:
            continue
    mainreader = PyPDF2.PdfReader(main)
    numpg = len(mainreader.pages)
    vault = []
    mthvault = []
    yrvault = []
    meow = datetime.datetime.now()
    lgnme = meow.strftime('%m%d%y_BillLog')
    print(lgnme)
    log = open('.\\'+lgnme+'.txt','w')
    dup = []
    for i in range(0,numpg,2):
        writer = PyPDF2.PdfWriter()
        page = mainreader.pages[i]
        words = page.extract_text()

The workaround that I found is to open the _cmap.py file and declare the variable cm = "" on a new line within the prepare_cm function. The scripts execute as expected with the addition.

Manually updating the cmap file is pretty hacky, so I could use some help finding the actual source of the error.

Is this error occurring due to a dependency issue/bug, or is there an issue with the script itself?


问:
Need Explanation to a question related to pointers

```<code>int a[]={1,2,3,4}
int *p = a++;
cout<<*p<<endl;
</code>```

I wanted to know why the above code output will generate an error and which line will generate an error?

Body:
int a[]={1,2,3,4}
int *p = a++;
cout<<*p<<endl;

I wanted to know why the above code output will generate an error and which line will generate an error?


问:
suppressMessages() with read_excel() still prints empty line
I'm reading in data with read_excel() from the readxl package to avoid possible java issues when sharing my script with coworkers that have crept up using xlsx. I've been trying to suppress the output messages read_excel() produces with suppressMessages(), but while this doesn't print any of the messages, it still produces an empty line in the console. Is there a way to get rid of this empty line as well? Including appendLF=F (as per the help) did not work and produced an "unused argument" error.

```<code>> dat<-suppressMessages(as.data.frame(read_excel(file, sheet=1, skip=1, col_names=F)))

>
</code>```

I'm following this up with a cat() message, so possibly I could remove this empty line this way?

Edit: I just tested it on different computers and the superfluous empty line seems to only appear on mac, not on windows.

Body:
I'm reading in data with read_excel() from the readxl package to avoid possible java issues when sharing my script with coworkers that have crept up using xlsx. I've been trying to suppress the output messages read_excel() produces with suppressMessages(), but while this doesn't print any of the messages, it still produces an empty line in the console. Is there a way to get rid of this empty line as well? Including appendLF=F (as per the help) did not work and produced an "unused argument" error.

> dat<-suppressMessages(as.data.frame(read_excel(file, sheet=1, skip=1, col_names=F)))

>

I'm following this up with a cat() message, so possibly I could remove this empty line this way?

Edit: I just tested it on different computers and the superfluous empty line seems to only appear on mac, not on windows.


问:
secrets client of azure sdk for go returns empty secret even if rbac is set correctly (managed identity)
the response of the Get fkt of the secrets client from go azure sdk
("github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault")
returns an valid instance of
resp of type SecretsClientGetResponse,
but the property resp.Secret.Properties.Value is Null.
there i expect the wanted secret value.

i use the azure sdk from
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault"
in a container app with default credentials
-> env var AZURE_CLIENT_ID is set to corresponding managed identity client id
-> managed identity has "secrets user" access rights over the corresponding key vault
-> furthermore the managed identity has the requesting app as assigned ressource

i don't can find more specifications which must be set but it still dont works to get the content of a secret from the key vault

can anybody help?


问:
I am programming a simple bootloader that print messages to the screen but it's not working
Chatgpt says that my code is working, i passed it to the AI for the AI to troubleshoot but it's still not working, why can't i call the function like this?

I should clarify that when i run this insted of hello world some wierd symbols appear, at least it prints something.

PS: after 20 minutes or so i realized that the problem is with the push and pop that i use, i resolved it in a different way but it would be helpful if someone could explane to me why it doesn't work as intended if i use the stack in the way that i did.

```<code>[org 0x7c00]

mov bp, 0x7c00
mov sp, bp

push message
call printstring

printstring:
    pop bx

    mov ah,0x0e
    .loop:

        cmp [bx], byte 0
        je .Exit

        mov al, [bx]
        int 0x10
        inc bx

        jmp .loop
    .Exit:
    ret

message:
    db 'Hello World!',0

encomenda:
    db 'ENCOMENDA REAL!', 0

times 510-($-$$) db 0
dw 0x55aa
</code>```

I tried troubleshooting using ChatGPT but the AI didn't helped me at all.

Body:
Chatgpt says that my code is working, i passed it to the AI for the AI to troubleshoot but it's still not working, why can't i call the function like this?

I should clarify that when i run this insted of hello world some wierd symbols appear, at least it prints something.

PS: after 20 minutes or so i realized that the problem is with the push and pop that i use, i resolved it in a different way but it would be helpful if someone could explane to me why it doesn't work as intended if i use the stack in the way that i did.

[org 0x7c00]

mov bp, 0x7c00
mov sp, bp

push message
call printstring

printstring:
    pop bx

    mov ah,0x0e
    .loop:

        cmp [bx], byte 0
        je .Exit

        mov al, [bx]
        int 0x10
        inc bx

        jmp .loop
    .Exit:
    ret

message:
    db 'Hello World!',0

encomenda:
    db 'ENCOMENDA REAL!', 0

times 510-($-$$) db 0
dw 0x55aa

I tried troubleshooting using ChatGPT but the AI didn't helped me at all.


问:
Cleaning Chatbot Chat data Python
I have a chatbot data Something like this. I want to retrieve the customer data.

 Chat Started: Tuesday March 12 2022 12:00:00 Chatbot: How may I assist you ( 5s ) Chatbot: {Ask about product, ask about Product features}  Customer1: Product Features Chatbot: {Ask about on the Color, Ask about usages} Customer1: How can I use the Product when travelling Chatbot: You can use this Product XXXXXXXXXXXXXXX.  Chatbot: Is this helpful Chatbot: {"Yes" "No" "Return to MainMenu"} Customer1: Yes

If I have this Chat, I want to extract only Customer Conversation

Customer1: {'Product Features', 'How can I use the Product when travelling', 'Yes'} Time: {'12-Mar-2022 12:00:00'}

The chatbot conversation is in pure text without any format (I did the format).

Any faster way of retrieving will be really helpful. Since I have to hover through millions of Chat records.

Title: Cleaning Chatbot Chat data Python


问:
Terminating app due to uncaught exception 'NSInvalidArgumentException' [FIRAuthDataResult providerData]: selector sent to instance 0x28230ae60
In my flutter application, I have single sign on options using Facebook and Gmail. It's working as expected in Android. But in IOS when click the Single Sign on, both(Facebook and Gmail) application getting crashed and getting the below error.
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[FIRAuthDataResult providerData]: unrecognized selector sent to instance 0x28230ae60'
I changed this function to

```<code>[[FIRAuth auth] signInWithCredential:credential completion:^(FIRUser * _Nullable firUser, NSError * _Nullable error) {
}];
to this
[[FIRAuth auth] signInWithCredential:credential completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) {
<#code#>
}]
</code>```

I this is the issue,

Because FIRUser changed to FIRAuthDataResult

I changed the function because after pod install its shows me the below error

```<code>Incompatible block pointer types sending 'void (^)(FIRUser * _Nullable __strong, NSError * _Nullable __strong)' to parameter of type 'void (^ _Nullable)(FIRAuthDataResult * _Nullable __strong, NSError * _Nullable __strong)'
</code>```

Attaching my Info.plist files screen shot.

Body:
In my flutter application, I have single sign on options using Facebook and Gmail. It's working as expected in Android. But in IOS when click the Single Sign on, both(Facebook and Gmail) application getting crashed and getting the below error.
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[FIRAuthDataResult providerData]: unrecognized selector sent to instance 0x28230ae60'
I changed this function to

[[FIRAuth auth] signInWithCredential:credential completion:^(FIRUser * _Nullable firUser, NSError * _Nullable error) {
}];
to this
[[FIRAuth auth] signInWithCredential:credential completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) {
<#code#>
}]

I this is the issue,

Because FIRUser changed to FIRAuthDataResult

I changed the function because after pod install its shows me the below error

Incompatible block pointer types sending 'void (^)(FIRUser * _Nullable __strong, NSError * _Nullable __strong)' to parameter of type 'void (^ _Nullable)(FIRAuthDataResult * _Nullable __strong, NSError * _Nullable __strong)'

Attaching my Info.plist files screen shot.


问:
Unity3d, Spotlight doesn't work correctly all the time
There is a problem (most likely with Post Processing) when light hits objects, it illuminates a larger area than itself (as in 1 picture), but at the same moment it works normally in scene viewer (2 picture) and when paused, you can observe this problem.
How can I fix this problem so the light will render as it is on second picture?

If you increase the intensity of lighting, then it will work. Can it also be done at a lower intensity?


问:
how to add car back to inventory in car rental system when its return date is over?
so,i am making a car rental system as a semester project. it is almost completed but its has one problem.problem is if there are three same cars availabe and someone books two for a week. so after a week total cars availabe does not goes back to 3.i tried so many different things but could not do it. if anyone can quide me with some pseudo code that will be a great help.thanks.

this is the code i tried.in this i created a file in which the car name and return date gets saved when someone books a car.

```<code>int avCars(){
    string carName;
    time_t now = time(0);
    tm *ltm = localtime(&now);
    int d = ltm->tm_mday;
    int m = 1 + ltm->tm_mon;
    int year = 1900 + ltm->tm_year;
    int avCars[5][5]={{3,3,3,3,3},{3,3,3,3,3},{3,3,3,3,3},{3,3,3,3,3},{3,3,3,3,3}};
      for(int i=0;i<5;i++){
        for(int j=0;j<5;j++){
          ifstream avcheck("returnDates.txt");
          while( avcheck >> returnDate[0] >> returnDate[1]>> returnDate[2] >>carName>>carName){
            if((returnDate[0]==d) && (returnDate[1]==m) && (returnDate[2]==year)){
              avCars[i][j]++;
            }
          }
        }
      }
  return 0;
}
</code>```

this adds one value in each array value on finding the match.but i want to add one to that specific index where that car was removed

Body:
so,i am making a car rental system as a semester project. it is almost completed but its has one problem.problem is if there are three same cars availabe and someone books two for a week. so after a week total cars availabe does not goes back to 3.i tried so many different things but could not do it. if anyone can quide me with some pseudo code that will be a great help.thanks.

this is the code i tried.in this i created a file in which the car name and return date gets saved when someone books a car.

int avCars(){
    string carName;
    time_t now = time(0);
    tm *ltm = localtime(&now);
    int d = ltm->tm_mday;
    int m = 1 + ltm->tm_mon;
    int year = 1900 + ltm->tm_year;
    int avCars[5][5]={{3,3,3,3,3},{3,3,3,3,3},{3,3,3,3,3},{3,3,3,3,3},{3,3,3,3,3}};
      for(int i=0;i<5;i++){
        for(int j=0;j<5;j++){
          ifstream avcheck("returnDates.txt");
          while( avcheck >> returnDate[0] >> returnDate[1]>> returnDate[2] >>carName>>carName){
            if((returnDate[0]==d) && (returnDate[1]==m) && (returnDate[2]==year)){
              avCars[i][j]++;
            }
          }
        }
      }
  return 0;
}

this adds one value in each array value on finding the match.but i want to add one to that specific index where that car was removed


问:
Always getting all the records from child table in One to Many JPA Unidirectional Mapping
I have two entities

```<code>@Entity
@Table(name = "PARENT")
public class Parent {

    @Id
    @Column(name = "ID", nullable = false)
    private Long id;

    @Column(name= "NAME", nullable = false)
    private String name;

    @OneToMany(cascade = CascadeType.ALL)
    @JoinColumn(name="parentid", referencedColumnName = "id")
    private Set<Child> child = new HashSet<>();

}

@Entity
@Table(name = "Child")
public class Child {

    @Id
    @Column(name = "ID", nullable = false)
    private Long id;

    @Column(name= "childname", nullable = false)
    private String childName;

    @Column(name= "Age", nullable = false)
    private Integer childAge;

}
</code>```

ParentRepository :

```<code>List<Parent> findByNameAndChildChildName(String parentName, String childName);
</code>```

Tables Data:
Parent

id | name

Test1

Test2

Child

id |  parentid |  childname  | age

```<code>1       Test1First   20
</code>```

```<code>1       Test1Second  15
</code>```

```<code>2       Test2First   25
</code>```

```<code>2       Test2Second  21
</code>```

So while fetching with above JPA repository always getting data of both child's

But expectation is to get the child data only for which condition satisfied as name/Age is provided.

Is there any way to implement it, we need to implement unidirectional relationship and there is no static where clause and data needs to be picked dynamically.

Body:
I have two entities

@Entity
@Table(name = "PARENT")
public class Parent {

    @Id
    @Column(name = "ID", nullable = false)
    private Long id;

    @Column(name= "NAME", nullable = false)
    private String name;

    @OneToMany(cascade = CascadeType.ALL)
    @JoinColumn(name="parentid", referencedColumnName = "id")
    private Set<Child> child = new HashSet<>();

}

@Entity
@Table(name = "Child")
public class Child {

    @Id
    @Column(name = "ID", nullable = false)
    private Long id;

    @Column(name= "childname", nullable = false)
    private String childName;

    @Column(name= "Age", nullable = false)
    private Integer childAge;

}

ParentRepository :

List<Parent> findByNameAndChildChildName(String parentName, String childName);

Tables Data:
Parent

id | name

Test1

Test2

Child

id |  parentid |  childname  | age

1       Test1First   20

1       Test1Second  15

2       Test2First   25

2       Test2Second  21

So while fetching with above JPA repository always getting data of both child's

But expectation is to get the child data only for which condition satisfied as name/Age is provided.

Is there any way to implement it, we need to implement unidirectional relationship and there is no static where clause and data needs to be picked dynamically.


问:
CI/CD - How to perform a variable substitution for an appsettings.json file in Google Run?
I've an application c# dotnetcore. I use the file appsettings.json to connect my application in database.

Now I want to change my connection string during CI/CD.

This is my local connection:

This is my variable in Google Cloud Run:

How can I change the value of Connectionstrings:connection local to variable _DATA_BASE_CONNECTION?


问:
<class> not a constructor error at runtime
I am using following classes:
I got a root class :

```<code>class BasePage {
    constructor() {
        this.root = "rootbase";
    }
}
module.exports = BasePage;
</code>```

Extended by 2 subclasses:

```<code>const Page2 = require('./page2')
const BasePage = require("./basePage")

class Page1 extends BasePage {
    constructor() {
        super();
        this.root = "root1";
    }
    open2() {
        global.plop = new Page2()
    }
}

module.exports = Page1;
</code>```
```<code>const Page1 = require('./page1')
const BasePage = require("./basePage")

class Page2 extends BasePage {
    constructor() {
        super();
        this.root = "root2";
    }
    open1() {
        global.plop = new Page1()
    }
}

module.exports = Page2;
</code>```

When I am running

```<code>    global.plop = new BasePage();
    global.plop = new Page1();
    plop.open2();
    plop.open1();
</code>```

I get

```<code>ncaught TypeError TypeError: Page1 is not a constructor
    at open1 (c:\Users\Amira\Projects\nodetemp\page2.js:10:17)
    at main (c:\Users\Amira\Projects\nodetemp\index.js:11:10)
    at <anonymous> (c:\Users\Amira\Projects\nodetemp\index.js:15:1)
    at Module._compile (internal/modules/cjs/loader:1159:14)
    at Module._extensions..js (internal/modules/cjs/loader:1213:10)
    at Module.load (internal/modules/cjs/loader:1037:32)
    at Module._load (internal/modules/cjs/loader:878:12)
    at executeUserEntryPoint (internal/modules/run_main:81:12)
    at <anonymous> (internal/main/run_main_module:23:47)
</code>```

What I am missing ? Is there any workaround ?

no workaround found ...
also tried with Reflect.construct() instead of new unsuccessfully

Body:
I am using following classes:
I got a root class :

class BasePage {
    constructor() {
        this.root = "rootbase";
    }
}
module.exports = BasePage;

Extended by 2 subclasses:

const Page2 = require('./page2')
const BasePage = require("./basePage")

class Page1 extends BasePage {
    constructor() {
        super();
        this.root = "root1";
    }
    open2() {
        global.plop = new Page2()
    }
}

module.exports = Page1;

const Page1 = require('./page1')
const BasePage = require("./basePage")

class Page2 extends BasePage {
    constructor() {
        super();
        this.root = "root2";
    }
    open1() {
        global.plop = new Page1()
    }
}

module.exports = Page2;

When I am running

    global.plop = new BasePage();
    global.plop = new Page1();
    plop.open2();
    plop.open1();

I get

ncaught TypeError TypeError: Page1 is not a constructor
    at open1 (c:\Users\Amira\Projects\nodetemp\page2.js:10:17)
    at main (c:\Users\Amira\Projects\nodetemp\index.js:11:10)
    at <anonymous> (c:\Users\Amira\Projects\nodetemp\index.js:15:1)
    at Module._compile (internal/modules/cjs/loader:1159:14)
    at Module._extensions..js (internal/modules/cjs/loader:1213:10)
    at Module.load (internal/modules/cjs/loader:1037:32)
    at Module._load (internal/modules/cjs/loader:878:12)
    at executeUserEntryPoint (internal/modules/run_main:81:12)
    at <anonymous> (internal/main/run_main_module:23:47)

What I am missing ? Is there any workaround ?

no workaround found ...
also tried with Reflect.construct() instead of new unsuccessfully


问:
django mysql connection don't respect databases settings in settings.py
This is my database connection string in settings.py.

```<code>DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.mysql",
        "HOST": "127.0.0.1",
        "PORT": os.getenv("DB_PORT", '3306'),
        "NAME": os.getenv("DB_DATABASE", 'sm'),
        "USER": os.getenv("DB_USER", 'root'),
        "PASSWORD": os.getenv("DB_PASSWORD", ''),
    }
}
</code>```

As above the host specified 127.0.0.1

but when I run python manage.py runserver database connection error with the wrong hostname.

django.db.utils.OperationalError: (1045, "Access denied for user
'root'@'172.18.0.1' (using password: NO)")

As you can see I wrote hostname 127.0.0.1 but in the project, it is connecting 172.18.0.1

I really appreciate, it if someone gives me an answer to this issue.

Thank you.

Body:
This is my database connection string in settings.py.

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.mysql",
        "HOST": "127.0.0.1",
        "PORT": os.getenv("DB_PORT", '3306'),
        "NAME": os.getenv("DB_DATABASE", 'sm'),
        "USER": os.getenv("DB_USER", 'root'),
        "PASSWORD": os.getenv("DB_PASSWORD", ''),
    }
}

As above the host specified 127.0.0.1

but when I run python manage.py runserver database connection error with the wrong hostname.

django.db.utils.OperationalError: (1045, "Access denied for user
'root'@'172.18.0.1' (using password: NO)")

As you can see I wrote hostname 127.0.0.1 but in the project, it is connecting 172.18.0.1

I really appreciate, it if someone gives me an answer to this issue.

Thank you.


问:
instagram-private-api throwing an error while trying to post an image on Instagram
```<code>const IgApiClient = require('instagram-private-api').IgApiClient;
const fs = require('fs');
const config = require('./config.json');

const ig = new IgApiClient();
ig.state.generateDevice(config.instagramUsername);
ig.state.proxyUrl = config.igProxy;

async function uploadImage(imageBuffer) {
  const imageUrl = await ig.upload.photo(
    {
        file: imageBuffer
    }
  );
  console.log(`URL: ${imageUrl}`);
}

(async () => {
  await ig.simulate.preLoginFlow();
  const loggedInUser = await ig.account.login(config.instagramUsername, config.instagramPassword);
  process.nextTick(async () => await ig.simulate.postLoginFlow());

  const imageBuffer = fs.readFileSync('output.png');

  uploadImage(imageBuffer);
})();
</code>```

Error:

C:\Users\PC\Desktop\spotted\node_modules\instagram-private-api\dist\core\request.js:126
return new errors_1.IgResponseError(response);
^

IgResponseError: POST /rupload_igphoto/1672943340753_0_8268117741 - 400 Bad Request;
at Request.handleResponseError (C:\Users\PC\Desktop\spotted\node_modules\instagram-private-api\dist\core\request.js:126:16)
at Request.send (C:\Users\PC\Desktop\spotted\node_modules\instagram-private-api\dist\core\request.js:54:28)
at async UploadRepository.photo (C:\Users\PC\Desktop\spotted\node_modules\instagram-private-api\dist\repositories\upload.repository.js:18:26)
at async uploadImage (C:\Users\PC\Desktop\spotted\bomba.js:10:20)

Node.js v19.2.0

Hello, I've been trying to create an app, which will automatically post generated images on instagram, but there's a problem, it doesn't work even if i do it as it is intended in documentation (probably). Does anyone have any ideas?

Body:
const IgApiClient = require('instagram-private-api').IgApiClient;
const fs = require('fs');
const config = require('./config.json');

const ig = new IgApiClient();
ig.state.generateDevice(config.instagramUsername);
ig.state.proxyUrl = config.igProxy;

async function uploadImage(imageBuffer) {
  const imageUrl = await ig.upload.photo(
    {
        file: imageBuffer
    }
  );
  console.log(`URL: ${imageUrl}`);
}

(async () => {
  await ig.simulate.preLoginFlow();
  const loggedInUser = await ig.account.login(config.instagramUsername, config.instagramPassword);
  process.nextTick(async () => await ig.simulate.postLoginFlow());

  const imageBuffer = fs.readFileSync('output.png');

  uploadImage(imageBuffer);
})();

Error:

C:\Users\PC\Desktop\spotted\node_modules\instagram-private-api\dist\core\request.js:126
return new errors_1.IgResponseError(response);
^

IgResponseError: POST /rupload_igphoto/1672943340753_0_8268117741 - 400 Bad Request;
at Request.handleResponseError (C:\Users\PC\Desktop\spotted\node_modules\instagram-private-api\dist\core\request.js:126:16)
at Request.send (C:\Users\PC\Desktop\spotted\node_modules\instagram-private-api\dist\core\request.js:54:28)
at async UploadRepository.photo (C:\Users\PC\Desktop\spotted\node_modules\instagram-private-api\dist\repositories\upload.repository.js:18:26)
at async uploadImage (C:\Users\PC\Desktop\spotted\bomba.js:10:20)

Node.js v19.2.0

Hello, I've been trying to create an app, which will automatically post generated images on instagram, but there's a problem, it doesn't work even if i do it as it is intended in documentation (probably). Does anyone have any ideas?


问:
fgetcsv() returns strings that have wrong length and don't match with regex (invisible characters I can't find?)
So this one let me doubt my sanity - I'm currently working on a simple script that should read URLs from a csv file and than perform a regex but my pattern kept on failing. Upon close inspection I noticed something strange: The strings that fgetcsv returns showing a completely wrong length when displayed with var_dump(). Any idea what is going on here and how to sanitize this string?

Sample-Code:

```<code><?php
$read = fopen("input.csv","r");
while($data = fgetcsv($read,null,",","\"","\\")){
    var_dump($data[0]);
    echo mb_detect_encoding($data[0]);
    echo "\n";
}
?>
</code>```

And the response looks like this:

```<code>string(25) "/index.html"
ASCII
string(23) "/login.html"
ASCII
string(15) "/insta/"
ASCII
</code>```

The strings are the same that are in my csv-file, but as you see the string length reported isn't right. What is going on here? Are there invisible characters I'm not seeing? Is it some strange encoding problem? How can I fix this?

Body:
So this one let me doubt my sanity - I'm currently working on a simple script that should read URLs from a csv file and than perform a regex but my pattern kept on failing. Upon close inspection I noticed something strange: The strings that fgetcsv returns showing a completely wrong length when displayed with var_dump(). Any idea what is going on here and how to sanitize this string?

Sample-Code:

<?php
$read = fopen("input.csv","r");
while($data = fgetcsv($read,null,",","\"","\\")){
    var_dump($data[0]);
    echo mb_detect_encoding($data[0]);
    echo "\n";
}
?>

And the response looks like this:

string(25) "/index.html"
ASCII
string(23) "/login.html"
ASCII
string(15) "/insta/"
ASCII

The strings are the same that are in my csv-file, but as you see the string length reported isn't right. What is going on here? Are there invisible characters I'm not seeing? Is it some strange encoding problem? How can I fix this?


问:
How to determine a Fun from a CallExpr is user defined function or built-in function in golang
Consider the case

```<code>package main

import "fmt"

func len(s []int) string {
    return "xyz"
}

func main() {
    s := []int{1, 2, 3}
    fmt.Println(len(s))
}

</code>```

Here output will be 'xyz' as len([]int) function is declared by user.
My question is how to determine this len function is built-in or user defined from ast.
I've ast.CallExpr node of len(s)

How can I determine an ast.CallExpr is user defined function call or built-in function call in golang?

Body:
Consider the case

package main

import "fmt"

func len(s []int) string {
    return "xyz"
}

func main() {
    s := []int{1, 2, 3}
    fmt.Println(len(s))
}

Here output will be 'xyz' as len([]int) function is declared by user.
My question is how to determine this len function is built-in or user defined from ast.
I've ast.CallExpr node of len(s)

How can I determine an ast.CallExpr is user defined function call or built-in function call in golang?


问:
How to customize a label focus using css?
I am hoping you can help. I am trying to have the label focus be the same color as the input focus, but whenever I try to test focus + label, it doesn't work.

label{
  display:block;
  position:relative;
  bottom:-10px;
  width:fit-content;
  left:10px;
  padding:0px 5px;
  background-color:white;
  color: rgb(56, 56, 56);
  font-size: 0.8em;
}

input{
  border:2px solid #707070;
  height: 30px;
  width:300px;
  padding:5px 10px;
  font-weight:bold;
  border-radius: 5px;
}
input:focus-within{
  outline:none;
  border:2px solid #0890EB;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div className='form-group'>
        <label>
          Email/username
          </label>
          <input type="email" value={email} onChange={handleEmailChange} />

        <br />
        </div>
        <div className='form-group'>
        <label>
          Password: </label>
          <input
            type="password"
            value={password}
            onChange={handlePasswordChange}
          />

        </div></code>```

I am expecting the label and the input focus to have the same color when focused.
see wireframe

I hope you can help. Thank you!

Body:
I am hoping you can help. I am trying to have the label focus be the same color as the input focus, but whenever I try to test focus + label, it doesn't work.

label{
  display:block;
  position:relative;
  bottom:-10px;
  width:fit-content;
  left:10px;
  padding:0px 5px;
  background-color:white;
  color: rgb(56, 56, 56);
  font-size: 0.8em;
}

input{
  border:2px solid #707070;
  height: 30px;
  width:300px;
  padding:5px 10px;
  font-weight:bold;
  border-radius: 5px;
}
input:focus-within{
  outline:none;
  border:2px solid #0890EB;
}

          Email/username

          <input type="email" value={email} onChange={handleEmailChange} />

          Password:
          <input
            type="password"
            value={password}
            onChange={handlePasswordChange}
          />

I am expecting the label and the input focus to have the same color when focused.
see wireframe

I hope you can help. Thank you!


问:
Graph bars stacked and I need them separated into individual bars
I have the following code, which almost does what I need it to do. I am graphing the importance of each feature for two different models on the same graph for comparison. I can't seem to get them to show side by side as two separate bars. I am fairly new to python and brand new to this forum. here is the code:

def plot_importances1(model1, feature_names1, label1, model2=None,feature_names2=None, label2=None):
    if model2 is None:
        importances1 = model1.feature_importances_
        indices1 = np.argsort(importances1)

        plt.figure(figsize=(8, 8))  # Set figure size

        # plot the first list of feature importances as a horizontal bar chart
        plt.barh(range(len(indices1)), importances1[indices1], color="violet", align="center", label=label1)

        # set the y-axis tick labels to be the feature names
        plt.yticks(range(len(indices1)), [feature_names1[i] for i in indices1])
    else:
        importances1 = model1.feature_importances_
        indices1 = np.argsort(importances1)

        importances2 = model2.feature_importances_
        indices2 = np.argsort(importances2)

        plt.figure(figsize=(8, 8))  # Set figure size

        # plot the first list of feature importances as a horizontal bar chart
        plt.barh(range(len(indices1)), importances1[indices1], color="violet", align="center", label=label1)

        # plot the second list of feature importances as a horizontal bar chart
        plt.barh(range(len(indices2)), importances2[indices2], color="orange", align="center", label=label2)
        # set the y-axis tick labels to be the feature names
        plt.yticks(range(len(indices1)), [feature_names1[i] for i in indices1])

        # add a title and x- and y-axis labels
        plt.title("Feature Importances")
        plt.xlabel("Relative Importance")
        plt.ylabel("Feature")

        # add a legend to the plot
        plt.legend()

        # set the tick locations and labels for the first bar graph
        plt.gca().tick_params(axis='x', which='both', length=0)
        plt.gca().xaxis.set_ticks_position('top')
        plt.gca().xaxis.set_label_position('top')

        # set the tick locations and labels for the second bar graph
        plt.twinx()
        plt.gca().tick_params(axis='x', which='both', length=0)
        plt.gca().xaxis.set_ticks_position('bottom')
        plt.gca().xaxis.set_label_position('bottom')

        plt.show()
```
<p>Then I call the function:</p>
<pre class="lang-py prettyprint-override"><code>plot_importances1(
    dTree_treat_out,
    list(X1_train),
    "Outliers present",
    dTree,
    list(X_train),
    "No outliers",
)
</code>```

The two bars are both showing, but I can't get them to separate completely and I am getting this error:
Output for the code

I have ran several version of this, including one that does not return the matplotlib error. The problem with the other function definitions that I have is that the bars are stacked and I can't see both of them. If I knew how to make one less opaque? I am super stuck. I so not want them stacked, I need the first one to be its own graph with the second one NEXT to it, not overlaying or stacked on top, similar to the image I uploaded, but the bars need to be completely separated.

Any input to fix this issue will be greatly appreciated.

Body:
I have the following code, which almost does what I need it to do. I am graphing the importance of each feature for two different models on the same graph for comparison. I can't seem to get them to show side by side as two separate bars. I am fairly new to python and brand new to this forum. here is the code:

def plot_importances1(model1, feature_names1, label1, model2=None,feature_names2=None, label2=None):
    if model2 is None:
        importances1 = model1.feature_importances_
        indices1 = np.argsort(importances1)

        plt.figure(figsize=(8, 8))  # Set figure size

        # plot the first list of feature importances as a horizontal bar chart
        plt.barh(range(len(indices1)), importances1[indices1], color="violet", align="center", label=label1)

        # set the y-axis tick labels to be the feature names
        plt.yticks(range(len(indices1)), [feature_names1[i] for i in indices1])
    else:
        importances1 = model1.feature_importances_
        indices1 = np.argsort(importances1)

        importances2 = model2.feature_importances_
        indices2 = np.argsort(importances2)

        plt.figure(figsize=(8, 8))  # Set figure size

        # plot the first list of feature importances as a horizontal bar chart
        plt.barh(range(len(indices1)), importances1[indices1], color="violet", align="center", label=label1)

        # plot the second list of feature importances as a horizontal bar chart
        plt.barh(range(len(indices2)), importances2[indices2], color="orange", align="center", label=label2)
        # set the y-axis tick labels to be the feature names
        plt.yticks(range(len(indices1)), [feature_names1[i] for i in indices1])

        # add a title and x- and y-axis labels
        plt.title("Feature Importances")
        plt.xlabel("Relative Importance")
        plt.ylabel("Feature")

        # add a legend to the plot
        plt.legend()

        # set the tick locations and labels for the first bar graph
        plt.gca().tick_params(axis='x', which='both', length=0)
        plt.gca().xaxis.set_ticks_position('top')
        plt.gca().xaxis.set_label_position('top')

        # set the tick locations and labels for the second bar graph
        plt.twinx()
        plt.gca().tick_params(axis='x', which='both', length=0)
        plt.gca().xaxis.set_ticks_position('bottom')
        plt.gca().xaxis.set_label_position('bottom')

        plt.show()

Then I call the function:

plot_importances1(
    dTree_treat_out,
    list(X1_train),
    "Outliers present",
    dTree,
    list(X_train),
    "No outliers",
)

The two bars are both showing, but I can't get them to separate completely and I am getting this error:
Output for the code

I have ran several version of this, including one that does not return the matplotlib error. The problem with the other function definitions that I have is that the bars are stacked and I can't see both of them. If I knew how to make one less opaque? I am super stuck. I so not want them stacked, I need the first one to be its own graph with the second one NEXT to it, not overlaying or stacked on top, similar to the image I uploaded, but the bars need to be completely separated.

Any input to fix this issue will be greatly appreciated.


问:
C++ Problem with Pointers in subclass objects
I have a class touchButton in a separate header files below. This is as i need to create an object of Adafruit's RA8875 display in my main file, as i also need it there. Thats no problem, works out fine with the pointers like this. See example below.

touchButton.h

#ifndef TOUCHBUTTON_H
#define TOUCHBUTTON_H
#include "Adafruit_RA8875.h"

// Class for a touch button
class Button {
  protected:
    Adafruit_RA8875* tft;
    uint16_t *tx;
    uint16_t *ty;
    uint16_t width, height, radius;
    uint16_t x, y, color;
  public:
    // set Button values (x, y, width, height, radius, color)
    void setButton(Adafruit_RA8875* tft, uint16_t* tx, uint16_t* ty, uint16_t _x, uint16_t _y, uint16_t _width, uint16_t _height, uint16_t _radius, uint16_t _color);

    // prints button with corresponding values of setButton function
    void printButton();

};

#endif

```
<p><strong>touchButton.cpp</strong></p>
<pre class="lang-cpp prettyprint-override"><code>#include "touchButton.h"
#include "GENERAL.h"

// set Button  (x, y, width, height, radius, color)
void Button::setButton(Adafruit_RA8875* tft, uint16_t* tx, uint16_t* ty,uint16_t _x, uint16_t _y, uint16_t _width, uint16_t _height, uint16_t _radius, uint16_t _color) {
  this->tft = tft;
  this->tx = tx;
  this->ty = ty;
  x = _x;
  y = _y;
  width = _width;
  height = _height;
  radius = _radius;
  color = _color;
}

// prints button with corresponding values of setButton function
void Button::printButton(){
  tft->graphicsMode();
  tft->drawRoundRect(x, y, width, height, radius, color);
}
</code>```

example for main file:

#include "Adafruit_GFX.h"
#include "Adafruit_RA8875.h"
#include "GENERAL.h"
#include "touchButton.h"

// touch coordinates
uint16_t tx, ty;

// 800x480 TFT DISPLAY
Adafruit_RA8875 tft = Adafruit_RA8875(RA8875_CS, RA8875_RESET);

Button channel[18];
Button sceneLoad[6];

class Scenes {
  public:
  int number;             // numer of scene and buttons
  int textCoordinate_x;   // x coordinate of load button (for displaying some text)
  int textCoordinate_y;   // y coordinate of load button (for displaying some text)

 Scenes(int numberA, int x, int y){
    number = numberA;
    textCoordinate_x = x;
    textCoordinate_y = y;
 }

 void printSceneBlock(){
   tft.graphicsMode();
   sceneLoad[number].printButton();
 }

};

scene[2] = {Scenes(0,25,150), Scenes(1, 165,150)};

void setup(){
 // set Button
 channel[0].setButton(&tft,&tx,&ty,20,100,760,40,5, RA8875_WHITE);
}

void loop() {

 channel[0].printButton();
 scene[0].printSceneBlock();

}

```

But when using in the scenes class, my program crashes. This is only when i use the scene.printSceneBlock() function.

Before i changed this code in the separate header files, i used tft and tx and ty and passed it via reference in each function in the main file. this worked great, but used these passes in each function in the main file. now i changed the code so i just need to pass tft etc. in the .setButton function. As im not so experienced with pointers I'm not finding any answer that i understand. Would be much appreciated if somebody could help me explain what the problem here is. I am really stuck with this...

Body:
I have a class touchButton in a separate header files below. This is as i need to create an object of Adafruit's RA8875 display in my main file, as i also need it there. Thats no problem, works out fine with the pointers like this. See example below.

touchButton.h

#ifndef TOUCHBUTTON_H
#define TOUCHBUTTON_H
#include "Adafruit_RA8875.h"

// Class for a touch button
class Button {
  protected:
    Adafruit_RA8875* tft;
    uint16_t *tx;
    uint16_t *ty;
    uint16_t width, height, radius;
    uint16_t x, y, color;
  public:
    // set Button values (x, y, width, height, radius, color)
    void setButton(Adafruit_RA8875* tft, uint16_t* tx, uint16_t* ty, uint16_t _x, uint16_t _y, uint16_t _width, uint16_t _height, uint16_t _radius, uint16_t _color);

    // prints button with corresponding values of setButton function
    void printButton();

};

#endif

touchButton.cpp

#include "touchButton.h"
#include "GENERAL.h"

// set Button  (x, y, width, height, radius, color)
void Button::setButton(Adafruit_RA8875* tft, uint16_t* tx, uint16_t* ty,uint16_t _x, uint16_t _y, uint16_t _width, uint16_t _height, uint16_t _radius, uint16_t _color) {
  this->tft = tft;
  this->tx = tx;
  this->ty = ty;
  x = _x;
  y = _y;
  width = _width;
  height = _height;
  radius = _radius;
  color = _color;
}

// prints button with corresponding values of setButton function
void Button::printButton(){
  tft->graphicsMode();
  tft->drawRoundRect(x, y, width, height, radius, color);
}

example for main file:

#include "Adafruit_GFX.h"
#include "Adafruit_RA8875.h"
#include "GENERAL.h"
#include "touchButton.h"

// touch coordinates
uint16_t tx, ty;

// 800x480 TFT DISPLAY
Adafruit_RA8875 tft = Adafruit_RA8875(RA8875_CS, RA8875_RESET);

Button channel[18];
Button sceneLoad[6];

class Scenes {
  public:
  int number;             // numer of scene and buttons
  int textCoordinate_x;   // x coordinate of load button (for displaying some text)
  int textCoordinate_y;   // y coordinate of load button (for displaying some text)

 Scenes(int numberA, int x, int y){
    number = numberA;
    textCoordinate_x = x;
    textCoordinate_y = y;
 }

 void printSceneBlock(){
   tft.graphicsMode();
   sceneLoad[number].printButton();
 }

};

scene[2] = {Scenes(0,25,150), Scenes(1, 165,150)};

void setup(){
 // set Button
 channel[0].setButton(&tft,&tx,&ty,20,100,760,40,5, RA8875_WHITE);
}

void loop() {

 channel[0].printButton();
 scene[0].printSceneBlock();

}

But when using in the scenes class, my program crashes. This is only when i use the scene.printSceneBlock() function.

Before i changed this code in the separate header files, i used tft and tx and ty and passed it via reference in each function in the main file. this worked great, but used these passes in each function in the main file. now i changed the code so i just need to pass tft etc. in the .setButton function. As im not so experienced with pointers I'm not finding any answer that i understand. Would be much appreciated if somebody could help me explain what the problem here is. I am really stuck with this...


问:
Issue importing Type getting Can't use namespace as a type error
I'm working on creating a common package with TS Types to share across code bases.

I have an NPM package with /src/index.ts exporting my type.

```<code>export interface CreateCustomer {
    "email": string,
    "firstname": string,
    "lastname": string,
    "entityid"?: string,
    "stage": string
};
</code>```

Building this and publishing it to our local NPM repo.

tsconfig

```<code>{
  "compilerOptions": {
      "allowUnreachableCode": false,
      "esModuleInterop": true,
      "target": "ES2021",
      "module": "commonjs",
      "lib": [
          "es2021",
          "DOM"
      ],
      "resolveJsonModule": true,
      "noEmitOnError": true,
      "declaration": true,
      "strict": true,
      "noImplicitAny": true,
      "strictNullChecks": true,
      "noImplicitThis": true,
      "alwaysStrict": true,
      "noUnusedLocals": true,
      "noUnusedParameters": true,
      "noImplicitReturns": true,
      "noFallthroughCasesInSwitch": true,
      "inlineSourceMap": true,
      "inlineSources": true,
      "experimentalDecorators": true,
      "strictPropertyInitialization": true,
      "skipLibCheck": true,
      "stripInternal": true,
      "outDir": "./dist",
      "rootDir": "./src",
      "typeRoots": [
          "./node_modules/@types"
      ]
  },
  "include": [
    "**/src/*.ts"]
}
</code>```

package.json

```<code>{
  "name": "@company/common",
  "version": "1.0.7",
  "description": "common library ",
  "main": "./dist/index.js",
  "types": "./dist/index.d.ts",
  "scripts": {
    "build": "tsc"
  },
  "devDependencies": {
    "@aws-lambda-powertools/logger": "^1.1.0",
    "@aws-lambda-powertools/tracer": "^1.1.0",
    "@aws-sdk/client-secrets-manager": "^3.50.0",
    "@types/aws-lambda": "^8.10.108",
    "axios": "^1.1.3",
    "netsuite-rest": "^1.1.0",
    "nsrestlet": "^2.0.1"
  },
  "files": [
    "dist"
  ],
  "keywords": [],
  "author": "",
  "license": "ISC"
}

</code>```

This gives me a file structure

```<code>company
│
└───common
│   │   package.json
│   │   readme.md
│   │
│   └───dist
│       │   index.js
│       │   index.d.ts
</code>```

Now down stream I'm importing this library into a project like so and trying to use it.

```<code>import {CreateCustomer} from '@company/common';
let restLet: CreateCustomer= {...}
</code>```

This produces the error

```<code>Cannot use namespace 'CreateCustomer' as a type.ts(2709)
</code>```

If any one has an idea what I'm screwing up please let me know.

If I change the import to import {CreateCustomer} from '@company/common/' the error goes away. From reading documentation on TS it appears that for some reason, likely a stupid one, the interface is getting wrapped up in an extra module/namespace, but for the life of me I can't see it.

Body:
I'm working on creating a common package with TS Types to share across code bases.

I have an NPM package with /src/index.ts exporting my type.

export interface CreateCustomer {
    "email": string,
    "firstname": string,
    "lastname": string,
    "entityid"?: string,
    "stage": string
};

Building this and publishing it to our local NPM repo.

tsconfig

{
  "compilerOptions": {
      "allowUnreachableCode": false,
      "esModuleInterop": true,
      "target": "ES2021",
      "module": "commonjs",
      "lib": [
          "es2021",
          "DOM"
      ],
      "resolveJsonModule": true,
      "noEmitOnError": true,
      "declaration": true,
      "strict": true,
      "noImplicitAny": true,
      "strictNullChecks": true,
      "noImplicitThis": true,
      "alwaysStrict": true,
      "noUnusedLocals": true,
      "noUnusedParameters": true,
      "noImplicitReturns": true,
      "noFallthroughCasesInSwitch": true,
      "inlineSourceMap": true,
      "inlineSources": true,
      "experimentalDecorators": true,
      "strictPropertyInitialization": true,
      "skipLibCheck": true,
      "stripInternal": true,
      "outDir": "./dist",
      "rootDir": "./src",
      "typeRoots": [
          "./node_modules/@types"
      ]
  },
  "include": [
    "**/src/*.ts"]
}

package.json

{
  "name": "@company/common",
  "version": "1.0.7",
  "description": "common library ",
  "main": "./dist/index.js",
  "types": "./dist/index.d.ts",
  "scripts": {
    "build": "tsc"
  },
  "devDependencies": {
    "@aws-lambda-powertools/logger": "^1.1.0",
    "@aws-lambda-powertools/tracer": "^1.1.0",
    "@aws-sdk/client-secrets-manager": "^3.50.0",
    "@types/aws-lambda": "^8.10.108",
    "axios": "^1.1.3",
    "netsuite-rest": "^1.1.0",
    "nsrestlet": "^2.0.1"
  },
  "files": [
    "dist"
  ],
  "keywords": [],
  "author": "",
  "license": "ISC"
}

This gives me a file structure

company
│
└───common
│   │   package.json
│   │   readme.md
│   │
│   └───dist
│       │   index.js
│       │   index.d.ts

Now down stream I'm importing this library into a project like so and trying to use it.

import {CreateCustomer} from '@company/common';
let restLet: CreateCustomer= {...}

This produces the error

Cannot use namespace 'CreateCustomer' as a type.ts(2709)

If any one has an idea what I'm screwing up please let me know.

If I change the import to import {CreateCustomer} from '@company/common/' the error goes away. From reading documentation on TS it appears that for some reason, likely a stupid one, the interface is getting wrapped up in an extra module/namespace, but for the life of me I can't see it.


问:
WebGL fade-out does not work for white color
I am trying to adapt a webgl code that generates firework explositions, where projectiles fade out from canvas by means of painting over with 0.1 alpha (as I understand it).
However, this technique somehow doesn't work for the explosition of white color.

You can see that white projectiles leave traces and never fully disappear, while other colors work fine (or maybe they also don't work, but I don't see the traces on black background).
Can somebody help me understand what is happening here?

// from https://codepen.io/towc/pen/oBvYEL

var gl = c.getContext('webgl2', {preserveDrawingBuffer: true})
    , w = c.width = window.innerWidth
    , h = c.height = window.innerHeight

    , webgl = {}
    , opts = {
    projectileAlpha: .8,
    projectileLineWidth: 2,
    fireworkAngleSpan: .5,
    baseFireworkVel: 3,
    gravity: .02,
    xFriction: .995,
    baseShardVel: 1,
    addedShardVel: .2,
    fireworks: 1, // 1 firework for each 10x10 pixels,
    baseShardsParFirework: 10,
    addedShardsParFirework: 10,
    shardFireworkVelMultiplier: .3
}

// updated to use WebGL2 and GL ES 3.0
// pass full color instead of just hue
// remove moving projectile, keep only the explosion

webgl.vertexShaderSource = `#version 300 es
uniform int u_mode;
uniform vec2 u_res;
in vec4 a_data;
out vec4 v_color;

vec3 c2rgb(int color_int){
    int r = color_int >> 16;
    int g = color_int >> 8 & 0xff;
    int b = color_int & 0xff;
    return vec3(r/255, g/255, b/255);
}

void clear(){
    gl_Position = vec4( a_data.xy, 0, 1 );
    v_color = vec4( 0, 0, 0, a_data.w );
}
void draw(){
    gl_Position = vec4( vec2( 1, -1 ) * ( ( a_data.xy / u_res ) * 2. - 1. ), 0, 1 );
    v_color = vec4( 1, 1, 1, a_data.w );
}
void main(){
    if( u_mode == 0 )
        draw();
    else
        clear();
}
`;
webgl.fragmentShaderSource = `#version 300 es
precision mediump float;
in vec4 v_color;
out vec4 fragColor;

void main(){
    fragColor = v_color;
}
`;

webgl.vertexShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(webgl.vertexShader, webgl.vertexShaderSource);
gl.compileShader(webgl.vertexShader);
if (!gl.getShaderParameter(webgl.vertexShader, gl.COMPILE_STATUS))
    console.log(gl.getShaderInfoLog(webgl.vertexShader));

webgl.fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(webgl.fragmentShader, webgl.fragmentShaderSource);
gl.compileShader(webgl.fragmentShader);
if (!gl.getShaderParameter(webgl.fragmentShader, gl.COMPILE_STATUS))
    console.log(gl.getShaderInfoLog(webgl.fragmentShader));

webgl.shaderProgram = gl.createProgram();
gl.attachShader(webgl.shaderProgram, webgl.vertexShader);
gl.attachShader(webgl.shaderProgram, webgl.fragmentShader);

gl.linkProgram(webgl.shaderProgram);
gl.useProgram(webgl.shaderProgram);

webgl.dataAttribLoc = gl.getAttribLocation(webgl.shaderProgram, 'a_data');
webgl.dataBuffer = gl.createBuffer();

gl.enableVertexAttribArray(webgl.dataAttribLoc);
gl.bindBuffer(gl.ARRAY_BUFFER, webgl.dataBuffer);
gl.vertexAttribPointer(webgl.dataAttribLoc, 4, gl.FLOAT, false, 0, 0);

webgl.resUniformLoc = gl.getUniformLocation(webgl.shaderProgram, 'u_res');
webgl.modeUniformLoc = gl.getUniformLocation(webgl.shaderProgram, 'u_mode');

gl.viewport(0, 0, w, h);
gl.uniform2f(webgl.resUniformLoc, w, h);

gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
gl.enable(gl.BLEND);

gl.lineWidth(opts.projectileLineWidth);

webgl.data = [];

webgl.clear = function () {

    gl.uniform1i(webgl.modeUniformLoc, 1);
    let a = .1;
    webgl.data = [
        -1, -1, 0, 0.1,
        1, -1, 0, 0.1,
        -1, 1, 0, 0.1,
        -1, 1, 0, 0.1,
        1, -1, 0, 0.1,
        1, 1, 0, 0.1
    ];
    webgl.draw(gl.TRIANGLES);
    gl.uniform1i(webgl.modeUniformLoc, 0);
    webgl.data.length = 0;
}
webgl.draw = function (glType) {

    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(webgl.data), gl.STATIC_DRAW);
    gl.drawArrays(glType, 0, webgl.data.length / 4);
}

let fireworks = []
    , tick = 0
    , sins = []
    , coss = []
    , maxShardsParFirework = opts.baseShardsParFirework + opts.addedShardsParFirework
    , tau = 6.283185307179586476925286766559;

for (let i = 0; i < maxShardsParFirework; ++i) {
    sins[i] = Math.sin(tau * i / maxShardsParFirework);
    coss[i] = Math.cos(tau * i / maxShardsParFirework);
}

function Firework() {
    this.reset();
    this.shards = [];
    for (let i = 0; i < maxShardsParFirework; ++i)
        this.shards.push(new Shard(this));
}

Firework.prototype.reset = function () {

    let angle = -Math.PI / 2 + (Math.random() - .5) * opts.fireworkAngleSpan
        , vel = opts.baseFireworkVel * Math.random();

    this.mode = 0;
    this.vx = vel * Math.cos(angle);
    this.vy = vel * Math.sin(angle);

    this.x = Math.random() * w;
    this.y = Math.random() * h;

    this.hue = 0;
    let ph = this.hue
        , px = this.x
        , py = this.y;

    webgl.data.push(
        px, py, ph, opts.projectileAlpha * .2,
        this.x, this.y, this.hue, opts.projectileAlpha * .2);

}
Firework.prototype.step = function () {

    if (this.mode === 0) {
        this.mode = 1;
        this.shardAmount = opts.baseShardsParFirework + opts.addedShardsParFirework * Math.random() | 0;
        let baseAngle = Math.random() * tau
            , x = Math.cos(baseAngle)
            , y = Math.sin(baseAngle)
            , sin = sins[this.shardAmount]
            , cos = coss[this.shardAmount];

        for (let i = 0; i < this.shardAmount; ++i) {
            let vel = opts.baseShardVel + opts.addedShardVel * Math.random();
            this.shards[i].reset(x * vel, y * vel)
            let X = x;
            x = x * cos - y * sin;
            y = y * cos + X * sin;
        }
    }
    if (this.mode === 1) {

        this.ph = this.hue
        this.hue = 0;

        let allDead = true;
        for (let i = 0; i < this.shardAmount; ++i) {
            let shard = this.shards[i];
            if (!shard.dead) {
                shard.step();
                allDead = false;
            }
        }

        if (allDead)
            this.reset();
    }

}

function Shard(parent) {
    this.parent = parent;
}

Shard.prototype.reset = function (vx, vy) {
    this.x = this.parent.x;
    this.y = this.parent.y;
    this.vx = this.parent.vx * opts.shardFireworkVelMultiplier + vx;
    this.vy = this.parent.vy * opts.shardFireworkVelMultiplier + vy;
    this.starty = this.y;
    this.dead = false;
    this.tick = 1;
}
Shard.prototype.step = function () {

    this.tick += .05;

    let px = this.x
        , py = this.y;

    this.x += this.vx *= opts.xFriction;
    this.y += this.vy += opts.gravity;

    var proportion = 1 - (this.y - this.starty) / (h - this.starty);

    webgl.data.push(
        px, py, this.parent.ph, opts.projectileAlpha / this.tick,
        this.x, this.y, this.parent.hue, opts.projectileAlpha / this.tick);

    if (this.y > h)
        this.dead = true;
}

function anim() {

    window.requestAnimationFrame(anim);

    webgl.clear();

    ++tick;

    if (fireworks.length < opts.fireworks)
        fireworks.push(new Firework);

    fireworks.map(function (firework) {
        firework.step();
    });

    webgl.draw(gl.LINES);
}
anim();

window.addEventListener('resize', function () {

    w = c.width = window.innerWidth;
    h = c.height = window.innerHeight;

    gl.viewport(0, 0, w, h);
    gl.uniform2f(webgl.resUniformLoc, w, h);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
    overflow: hidden;
    margin:0;
}

#c {
    position: absolute;
    top: 0;
    left: 0;
    background-color: #111;
}</code>```

<canvas id="c"> </canvas>```

Body:
I am trying to adapt a webgl code that generates firework explositions, where projectiles fade out from canvas by means of painting over with 0.1 alpha (as I understand it).
However, this technique somehow doesn't work for the explosition of white color.

You can see that white projectiles leave traces and never fully disappear, while other colors work fine (or maybe they also don't work, but I don't see the traces on black background).
Can somebody help me understand what is happening here?

// from https://codepen.io/towc/pen/oBvYEL

var gl = c.getContext('webgl2', {preserveDrawingBuffer: true})
    , w = c.width = window.innerWidth
    , h = c.height = window.innerHeight

    , webgl = {}
    , opts = {
    projectileAlpha: .8,
    projectileLineWidth: 2,
    fireworkAngleSpan: .5,
    baseFireworkVel: 3,
    gravity: .02,
    xFriction: .995,
    baseShardVel: 1,
    addedShardVel: .2,
    fireworks: 1, // 1 firework for each 10x10 pixels,
    baseShardsParFirework: 10,
    addedShardsParFirework: 10,
    shardFireworkVelMultiplier: .3
}

// updated to use WebGL2 and GL ES 3.0
// pass full color instead of just hue
// remove moving projectile, keep only the explosion

webgl.vertexShaderSource = `#version 300 es
uniform int u_mode;
uniform vec2 u_res;
in vec4 a_data;
out vec4 v_color;

vec3 c2rgb(int color_int){
    int r = color_int >> 16;
    int g = color_int >> 8 & 0xff;
    int b = color_int & 0xff;
    return vec3(r/255, g/255, b/255);
}

void clear(){
    gl_Position = vec4( a_data.xy, 0, 1 );
    v_color = vec4( 0, 0, 0, a_data.w );
}
void draw(){
    gl_Position = vec4( vec2( 1, -1 ) * ( ( a_data.xy / u_res ) * 2. - 1. ), 0, 1 );
    v_color = vec4( 1, 1, 1, a_data.w );
}
void main(){
    if( u_mode == 0 )
        draw();
    else
        clear();
}
`;
webgl.fragmentShaderSource = `#version 300 es
precision mediump float;
in vec4 v_color;
out vec4 fragColor;

void main(){
    fragColor = v_color;
}
`;

webgl.vertexShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(webgl.vertexShader, webgl.vertexShaderSource);
gl.compileShader(webgl.vertexShader);
if (!gl.getShaderParameter(webgl.vertexShader, gl.COMPILE_STATUS))
    console.log(gl.getShaderInfoLog(webgl.vertexShader));

webgl.fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(webgl.fragmentShader, webgl.fragmentShaderSource);
gl.compileShader(webgl.fragmentShader);
if (!gl.getShaderParameter(webgl.fragmentShader, gl.COMPILE_STATUS))
    console.log(gl.getShaderInfoLog(webgl.fragmentShader));

webgl.shaderProgram = gl.createProgram();
gl.attachShader(webgl.shaderProgram, webgl.vertexShader);
gl.attachShader(webgl.shaderProgram, webgl.fragmentShader);

gl.linkProgram(webgl.shaderProgram);
gl.useProgram(webgl.shaderProgram);

webgl.dataAttribLoc = gl.getAttribLocation(webgl.shaderProgram, 'a_data');
webgl.dataBuffer = gl.createBuffer();

gl.enableVertexAttribArray(webgl.dataAttribLoc);
gl.bindBuffer(gl.ARRAY_BUFFER, webgl.dataBuffer);
gl.vertexAttribPointer(webgl.dataAttribLoc, 4, gl.FLOAT, false, 0, 0);

webgl.resUniformLoc = gl.getUniformLocation(webgl.shaderProgram, 'u_res');
webgl.modeUniformLoc = gl.getUniformLocation(webgl.shaderProgram, 'u_mode');

gl.viewport(0, 0, w, h);
gl.uniform2f(webgl.resUniformLoc, w, h);

gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
gl.enable(gl.BLEND);

gl.lineWidth(opts.projectileLineWidth);

webgl.data = [];

webgl.clear = function () {

    gl.uniform1i(webgl.modeUniformLoc, 1);
    let a = .1;
    webgl.data = [
        -1, -1, 0, 0.1,
        1, -1, 0, 0.1,
        -1, 1, 0, 0.1,
        -1, 1, 0, 0.1,
        1, -1, 0, 0.1,
        1, 1, 0, 0.1
    ];
    webgl.draw(gl.TRIANGLES);
    gl.uniform1i(webgl.modeUniformLoc, 0);
    webgl.data.length = 0;
}
webgl.draw = function (glType) {

    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(webgl.data), gl.STATIC_DRAW);
    gl.drawArrays(glType, 0, webgl.data.length / 4);
}

let fireworks = []
    , tick = 0
    , sins = []
    , coss = []
    , maxShardsParFirework = opts.baseShardsParFirework + opts.addedShardsParFirework
    , tau = 6.283185307179586476925286766559;

for (let i = 0; i < maxShardsParFirework; ++i) {
    sins[i] = Math.sin(tau * i / maxShardsParFirework);
    coss[i] = Math.cos(tau * i / maxShardsParFirework);
}

function Firework() {
    this.reset();
    this.shards = [];
    for (let i = 0; i < maxShardsParFirework; ++i)
        this.shards.push(new Shard(this));
}

Firework.prototype.reset = function () {

    let angle = -Math.PI / 2 + (Math.random() - .5) * opts.fireworkAngleSpan
        , vel = opts.baseFireworkVel * Math.random();

    this.mode = 0;
    this.vx = vel * Math.cos(angle);
    this.vy = vel * Math.sin(angle);

    this.x = Math.random() * w;
    this.y = Math.random() * h;

    this.hue = 0;
    let ph = this.hue
        , px = this.x
        , py = this.y;

    webgl.data.push(
        px, py, ph, opts.projectileAlpha * .2,
        this.x, this.y, this.hue, opts.projectileAlpha * .2);

}
Firework.prototype.step = function () {

    if (this.mode === 0) {
        this.mode = 1;
        this.shardAmount = opts.baseShardsParFirework + opts.addedShardsParFirework * Math.random() | 0;
        let baseAngle = Math.random() * tau
            , x = Math.cos(baseAngle)
            , y = Math.sin(baseAngle)
            , sin = sins[this.shardAmount]
            , cos = coss[this.shardAmount];

        for (let i = 0; i < this.shardAmount; ++i) {
            let vel = opts.baseShardVel + opts.addedShardVel * Math.random();
            this.shards[i].reset(x * vel, y * vel)
            let X = x;
            x = x * cos - y * sin;
            y = y * cos + X * sin;
        }
    }
    if (this.mode === 1) {

        this.ph = this.hue
        this.hue = 0;

        let allDead = true;
        for (let i = 0; i < this.shardAmount; ++i) {
            let shard = this.shards[i];
            if (!shard.dead) {
                shard.step();
                allDead = false;
            }
        }

        if (allDead)
            this.reset();
    }

}

function Shard(parent) {
    this.parent = parent;
}

Shard.prototype.reset = function (vx, vy) {
    this.x = this.parent.x;
    this.y = this.parent.y;
    this.vx = this.parent.vx * opts.shardFireworkVelMultiplier + vx;
    this.vy = this.parent.vy * opts.shardFireworkVelMultiplier + vy;
    this.starty = this.y;
    this.dead = false;
    this.tick = 1;
}
Shard.prototype.step = function () {

    this.tick += .05;

    let px = this.x
        , py = this.y;

    this.x += this.vx *= opts.xFriction;
    this.y += this.vy += opts.gravity;

    var proportion = 1 - (this.y - this.starty) / (h - this.starty);

    webgl.data.push(
        px, py, this.parent.ph, opts.projectileAlpha / this.tick,
        this.x, this.y, this.parent.hue, opts.projectileAlpha / this.tick);

    if (this.y > h)
        this.dead = true;
}

function anim() {

    window.requestAnimationFrame(anim);

    webgl.clear();

    ++tick;

    if (fireworks.length < opts.fireworks)
        fireworks.push(new Firework);

    fireworks.map(function (firework) {
        firework.step();
    });

    webgl.draw(gl.LINES);
}
anim();

window.addEventListener('resize', function () {

    w = c.width = window.innerWidth;
    h = c.height = window.innerHeight;

    gl.viewport(0, 0, w, h);
    gl.uniform2f(webgl.resUniformLoc, w, h);
});

body {
    overflow: hidden;
    margin:0;
}

#c {
    position: absolute;
    top: 0;
    left: 0;
    background-color: #111;
}

<canvas id="c"> </canvas>


问:
import app.activity not found capacitor ionic framework error in ionic-camera
I am getting an error import app.activity not found when I build the application with ionic framework (vue) in android studio / capacitor

Try to turn on jetifier, i don't know how to solve this problem


问:
my signup page in reactjs is not saving the data to the firebase firestore
in this signup page the user enters username email and password and photo but the user data doesn't store in the firestore firebase. the photo is saving in the storage and the authentication is happening but the user data is not saving in the database.please help

import Helmet from "../components/Helmet/Helmet";
import { Container, Row, Col, Form, FormGroup } from "reactstrap";
import React, { useState } from "react";

import { Link } from "react-router-dom";
import "../styles/login.css";
import { setDoc, doc } from "firebase/firestore";
import { db } from "../firebase.config";
import { useNavigate } from "react-router-dom";
import { createUserWithEmailAndPassword, updateProfile } from "firebase/auth";
import { ref, uploadBytesResumable, getDownloadURL } from "firebase/storage";
import { auth } from "../firebase.config";
import { storage } from "../firebase.config";
import { toast } from "react-toastify";
import "../styles/login.css";

const Signup = () => {
  const [username, setUsername] = useState("");
  const [email, setEmail] = useState("");
  const [password, Setpassword] = useState("");
  const [file, setFile] = useState(null);
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();

  const signup = async (e) => {

    e.preventDefault();

    setLoading(true);

    try {

      const userCredential = await createUserWithEmailAndPassword(

        auth,

        email,

        password

      );

      const user = userCredential.user;

      const storageRef = ref(storage, `images/${Date.now() + username}`);

      const uploadTask = uploadBytesResumable(storageRef, file);

      uploadTask.on(

        (error) => {

          toast.error(error.message);

        },

        () => {

          getDownloadURL(uploadTask.snapshot.ref).then(async (downloadURl) => {

            await updateProfile(user, {

              displayName: username,

              photoURL: downloadURl,

            });

            await setDoc(doc(db, "users", user.uid), {

              uid: user.uid,

              displayName: username,

              email,

              photoURL: downloadURl,

            });

          });

        }

      );

      console.log(user);

      setLoading(false);

      navigate("/login");

      toast.success("signup successfull");

    } catch (error) {

      setLoading(false);

      toast.error("something went wrong");

    }

  };

  return (

    <Helmet title="Signup">

        <Container>

          <Row>

            {loading ? (

              <Col lg="12" className="text-center">

Loading.....

              </Col>

            ) : (

              <Col lg="6" className="m-auto text-center">

SignUp

                <Form className="auth__form " onSubmit={signup}>

                  <FormGroup className="signup__form">

                    <input

                      type="text"

                      placeholder="username"

                      value={username}

                      onChange={(e) => setUsername(e.target.value)}

                    />

                  </FormGroup>

                  <FormGroup className="signup__form">

                    <input

                      type="email"

                      placeholder="enter your email"

                      value={email}

                      onChange={(e) => setEmail(e.target.value)}

                    />

                  </FormGroup>

                  <FormGroup className="signup__form">

                    <input

                      type="password"

                      placeholder="enter your password"

                      value={password}

                      onChange={(e) => Setpassword(e.target.value)}

                    />

                  </FormGroup>

                  <FormGroup className="file__group">

                    <input

                      type="file"

                      onChange={(e) => setFile(e.target.file[0])}

                    />

                  </FormGroup>

                  <button type="submit" className="buy_btn auth__btn">

                    Create an Account

                  </button>

                    already have an account?

                    <Link to="/login">Login</Link>

                </Form>

              </Col>

            )}

          </Row>

        </Container>

    </Helmet>

  );

};

export default Signup;
```


问:
Godot: Position2D node not sending proper location
I am new to Godot and am currently making a roguelike game. It's in the very beginning stages, but I am stuck on one specific part. I have a system set up so that when you click on a certain space, the player will move to the position 2D node associated with that space. However, whenever I actually try it out, after clicking in the area the player moves to what appears to be a set area instead of where I want.

With this problem, I have no real idea how to fix it or what to search for on the internet because I am new to Godot and game development. I was hoping someone could answer my question directly here.


问:
limit size issue for Loading pyspark Dataframe into Dynamo DB
My Glue is reading multiple files then transform and join the input data set and final data frame goes to Dynamo DB, there is a limitation size for loading Items in to DynamoDB if Item size is greater than 400k job fails and I am getting error which "Item size is more than 400k"
how can I split each record or Items to the smaller chunk then load it into DB?
is there any solution for this issue with Glue job and pyspark?

```<code>dynamo_dydf = DynamicFrame.fromDF(final_df, glueContext, "test_nest") glueContext.write_dynamic_frame_from_options( frame=dynamo_dydf, connection_type="dynamodb", connection_options={ "dynamodb.output.tableName": dynamodb_table, "dynamodb.throughput.write.percent": "1.0"})
</code>```

Here is sample code for loading into DB

Body:
My Glue is reading multiple files then transform and join the input data set and final data frame goes to Dynamo DB, there is a limitation size for loading Items in to DynamoDB if Item size is greater than 400k job fails and I am getting error which "Item size is more than 400k"
how can I split each record or Items to the smaller chunk then load it into DB?
is there any solution for this issue with Glue job and pyspark?

dynamo_dydf = DynamicFrame.fromDF(final_df, glueContext, "test_nest") glueContext.write_dynamic_frame_from_options( frame=dynamo_dydf, connection_type="dynamodb", connection_options={ "dynamodb.output.tableName": dynamodb_table, "dynamodb.throughput.write.percent": "1.0"})

Here is sample code for loading into DB


问:
Can not connect to Pushshift.io despite correctly creating reddit praw instance
I followed the instruction on how to connect to pushshift in the psaw documentation but it doesn't seem to be working. An example of how you are able to use pushshift would be useful.

When I run the following code:

```<code>from psaw import PushshiftAPI
import praw
reddit_ = praw.Reddit(client_id='something', client_secret='something', user_agent='something')
api = PushshiftAPI(reddit_)
</code>```

I get the following error:
"Unable to connect to pushshift.io. Retrying after backoff."

I believe I created the praw reddit instance properly so I do not know what the error is.

Body:
I followed the instruction on how to connect to pushshift in the psaw documentation but it doesn't seem to be working. An example of how you are able to use pushshift would be useful.

When I run the following code:

from psaw import PushshiftAPI
import praw
reddit_ = praw.Reddit(client_id='something', client_secret='something', user_agent='something')
api = PushshiftAPI(reddit_)

I get the following error:
"Unable to connect to pushshift.io. Retrying after backoff."

I believe I created the praw reddit instance properly so I do not know what the error is.


问:
Problems With Interactive Viewers Running R in VSCode
I am getting started with running R scripts in VSCode.  Things are generally running fine, except for unexpected results with some of the viewers.  I'm running Mac OS Mojave 10.14.6.

First, any table / list  I try to view (using the View() command) generates this error:

```<code>Error in check_for_XQuartz(file.path(R.home("modules"), "R_de.so")) :
  X11 library is missing: install XQuartz from www.xquartz.org
</code>```

So I went ahead and installed XQuartz.  Viewing dataframes then worked, but it spawned a separate window, rather than a VSCode tab, that was very primitive: slow to render, without any interactivity (no sorting of columns or searching, etc. of the type shown at https://github.com/REditorSupport/vscode-R/wiki/Interactive-viewers).

Second, I'm having similar problems with rendering plots.  Plotting works, but it spawns a separate window, titled "Quartz 2 (*)", rather rendering in VSCode.

I have installed httpgd, and enabled r.plot.useHttpgd in VSCode settings.

Any advice, anyone?  Big thanks in advance.

Body:
I am getting started with running R scripts in VSCode.  Things are generally running fine, except for unexpected results with some of the viewers.  I'm running Mac OS Mojave 10.14.6.

First, any table / list  I try to view (using the View() command) generates this error:

Error in check_for_XQuartz(file.path(R.home("modules"), "R_de.so")) :
  X11 library is missing: install XQuartz from www.xquartz.org

So I went ahead and installed XQuartz.  Viewing dataframes then worked, but it spawned a separate window, rather than a VSCode tab, that was very primitive: slow to render, without any interactivity (no sorting of columns or searching, etc. of the type shown at https://github.com/REditorSupport/vscode-R/wiki/Interactive-viewers).

Second, I'm having similar problems with rendering plots.  Plotting works, but it spawns a separate window, titled "Quartz 2 (*)", rather rendering in VSCode.

I have installed httpgd, and enabled r.plot.useHttpgd in VSCode settings.

Any advice, anyone?  Big thanks in advance.