问:
Workaround to pause and resume THREE.Clock() not working as intended
For a project, I'm setting the rotation of a mesh in UseFrame() like this

```<code>center.current.rotation.z = Math.cos(clock.getElapsedTime()/2) * 0.3
</code>```

I did it this way as an easy way to clamp the z rotation. But I need the rotation to stop when the cursor is hovered over it and restart at the same rotation when the cursor leaves.

So this is what I tried to do

```<code>    const clock = new THREE.Clock()
    const center = useRef(null)
    const [hovered, hover] = useState(false)
    let previousTime = 1.0

    useCursor(hovered)

    useFrame(() => {
        if(hovered) {
            if(clock.running) {
                previousTime = clock.getElapsedTime()
                clock.stop()
                clock.running = false
            }
        } else {
            if(!clock.running) {
                clock.start()
                clock.elapsedTime = previousTime
            }
            center.current.rotation.z = Math.cos(clock.getElapsedTime()/2) * 0.3
        }
    })
</code>```

I'm using a separate clock because there are other meshes that rely on the global?/system? clock that you get with the state. With this, when I unhover over the mesh, the position just jumps back to if elapsedTime got set to 1.0. It feels as if either previousTime isn't getting updated or clock.stop() isn't working. I don't really know what I'm doing wrong or what I'm not understanding about THREE.Clock. Any help would be appreciated.

Body:
For a project, I'm setting the rotation of a mesh in UseFrame() like this

center.current.rotation.z = Math.cos(clock.getElapsedTime()/2) * 0.3

I did it this way as an easy way to clamp the z rotation. But I need the rotation to stop when the cursor is hovered over it and restart at the same rotation when the cursor leaves.

So this is what I tried to do

    const clock = new THREE.Clock()
    const center = useRef(null)
    const [hovered, hover] = useState(false)
    let previousTime = 1.0

    useCursor(hovered)

    useFrame(() => {
        if(hovered) {
            if(clock.running) {
                previousTime = clock.getElapsedTime()
                clock.stop()
                clock.running = false
            }
        } else {
            if(!clock.running) {
                clock.start()
                clock.elapsedTime = previousTime
            }
            center.current.rotation.z = Math.cos(clock.getElapsedTime()/2) * 0.3
        }
    })

I'm using a separate clock because there are other meshes that rely on the global?/system? clock that you get with the state. With this, when I unhover over the mesh, the position just jumps back to if elapsedTime got set to 1.0. It feels as if either previousTime isn't getting updated or clock.stop() isn't working. I don't really know what I'm doing wrong or what I'm not understanding about THREE.Clock. Any help would be appreciated.


来源: stackexchange

问:
How can I convert a number from base10 to base 2 binary in JavaScript?
I want to write a loop with while/for to get a num from user and convert it from base 10 to base 2 binary do you know how can I do this?

I want to get number from user.

then specify 2 % Number == 0 or 2 % Number != 0

if it's equal to 0 console.log(0) and if it isn't equal to 0 console.log(1)

I want to if 2 % Number != 0 convert the answer to Int and then repeat steps 2 and 3!

ContentLicense: CC BY-SA 4.0


问:
Image Trail Effect in Nextjs not working after page changed
I want to create Image Trail Effect like https://github.com/codrops/ImageTrailEffects/ in Nextjs

This my page

```<code>const CaseStudy: NextPage = () => (
  <div>
    <Head>
      <title>Example Title</title>
      <meta name="description" content="Generated by create next app" />
      <link rel="icon" href="/favicon.ico" />
    </Head>
    <HeaderImageTrail textTitle="Case Studies" count="8" />
    <div>CaseStudy</div>
    <Footer />
  </div>
)
</code>```

and this code of HeaderImageTrail component

```<code>interface HeaderImageTrailInterface {
  textTitle?: string
  count?: string
}

const HeaderImageTrail = ({ textTitle, count }: HeaderImageTrailInterface) => (
  <HeaderWrapper className="content">
    <Navbar />
    <div>
      <img className="content__img" src="img/1.jpg" alt="Some image" />
      <img className="content__img" src="img/2.jpg" alt="Some image" />
      <img className="content__img" src="img/3.jpg" alt="Some image" />
      <img className="content__img" src="img/4.jpg" alt="Some image" />
      <img className="content__img" src="img/5.jpg" alt="Some image" />
    </div>
    <TextHero>
      {textTitle}
      <span>({count})</span>
    </TextHero>
    <ScrollLine />
    <Script type="text/javascript" src="js/imagesloaded.pkgd.min.js" />
    <Script type="text/javascript" src="js/TweenMax.min.js" />
    <Script type="text/javascript" src="js/demo.js" />
  </HeaderWrapper>
)
</code>```

We are experiencing an issue when we first access page '/' and then go to page '/case-study' where it works fine. However, if we go to another page and then come back to page '/case-study', the image trail effect does not work. No errors appear,

how can we solve this problem?

Body:
I want to create Image Trail Effect like https://github.com/codrops/ImageTrailEffects/ in Nextjs

This my page

const CaseStudy: NextPage = () => (

      <title>Example Title</title>
      <meta name="description" content="Generated by create next app" />
      <link rel="icon" href="/favicon.ico" />

    <HeaderImageTrail textTitle="Case Studies" count="8" />

CaseStudy

)

and this code of HeaderImageTrail component

interface HeaderImageTrailInterface {
  textTitle?: string
  count?: string
}

const HeaderImageTrail = ({ textTitle, count }: HeaderImageTrailInterface) => (
  <HeaderWrapper className="content">
    <Navbar />

    <TextHero>
      {textTitle}
      ({count})
    </TextHero>
    <ScrollLine />


问:
Start a interactive login shell from Node.js
I need to open interactive login shell from my electron application, after reading some other topic I found that we can set options.stdio to inherit from spawn method to open interactive shell
https://nodejs.org/api/child_process.html#optionsstdio

but I can't found anything about login shell. I also tried adding options.shell like this (I'm just trying)

```<code>{ shell: 'C:\\msys64\\usr\\bin\\bash.exe --login' }
</code>```

Is this possible to do?

Body:
I need to open interactive login shell from my electron application, after reading some other topic I found that we can set options.stdio to inherit from spawn method to open interactive shell
https://nodejs.org/api/child_process.html#optionsstdio

but I can't found anything about login shell. I also tried adding options.shell like this (I'm just trying)

{ shell: 'C:\\msys64\\usr\\bin\\bash.exe --login' }

Is this possible to do?


问:
How to set output sound device with selenium in c#
I have 30 virtual audio devices and I need to get output from each browser to process audio in real time. To get audio output I am using c# library (naudio) that connects to audio device and gets audio stream. Basically, I need to get sound stream from every browser. How can I set audio device? Or maybe use different way to capture output stream?

I tried using use-file-for-fake-audio-capture to get audio stream from file, but it can not be done for real time processing.

I am using seleium to control browser to get to websites which audio I want to process (eg. youtube or facebook). But I have like 30 browsers running at the same time. I think I can use NAudio library to capture stream from a specific application but I didn't find some information about it.


问:
Chat between specific users using SignalR and Angular client
I'm trying to make a chat between two clients that you can choose from the connected clients list. So far everything is working good - I have the list and I succeeded to send messages to all clients by using Clients.All.SendAsync.

The problem starts when I'm trying to use

```<code>Clients.Client(connectionId).
</code>```

In my client side (Angular), where I'm displaying the connected clients list, I've added a button to each client so you can send him a message:

I have click event to send the connectionId to the server, so it will know who to send a message to. I debugged the program and saw that I'm reaching to the server with the right data (the connectionId to send him a message) and when I'm getting back to the client no message is printed. Also I'm not getting any error on the console. What am I doing wrong?

Server side:

Controller-

```<code> [HttpPost("SendMessageToUser")]
    public Task<IActionResult> SendMessageToUser([FromBody] ChatMessageDto chatMessageDto)
    {
        IActionResult actionResult;
        if (chatMessageDto.Validate())
        {
            Response response=_signalrService.SendMessageToUser(chatMessageDto.ConnectionId,chatMessageDto.Message);
            actionResult=Ok(response);
        }
        else
        {
            actionResult = BadRequest();
        }
        return Task.FromResult(actionResult);
    }
</code>```

Service-

```<code>    public Response SendMessageToUser(string connectionId, string message)
    {
        Response response;

        UserHub hub = new UserHub(_userHubContext);
        hub.SendMessageToUser(message, connectionId);

        response = new Response
        {
            Message = message,
            IsSuccess = true
        };

        return response;
    }
</code>```

Hub-

```<code>    public void  SendMessageToUser(string message, string connectionId)
    {
        _hubContext.Clients.Client(connectionId).SendAsync("GetMessage", message).Wait();
    }
</code>```

Client side:

user.ts component - only partial code that relevant (there is continuance in my computer)

```<code>startSignalrConnection(): void {
this.signalRService
  .startSignalrConnection(this.signalrConnectionUrl)
  .then((signalrHubConnectionId) => {
    firstValueFrom(
      this.http.post(
        this.addClientUrl,
        //get user name from local storage
        buildNewChatClientConnectionModel(
          this.chatClientId,
          signalrHubConnectionId,
          this.userName!
        )
      )
    )
      .then((response) => {
        this.signalRService.addListenersMsg();
        // Add function call for getting all connected users
        this.userService.getConnectedUsers().subscribe((users) => {
          this.users = users;
        });
</code>```

user.html component-

```<code><div *ngFor="let user of users">
    <div class="users-list">
        <div><strong>Id: </strong>{{user?.chatClientId}}</div>
        <div><strong>ConnectionId: </strong>{{user?.connectionId}}</div>
        <div><strong>Name: </strong>{{user?.name}}</div>
        <button class="button" [disabled]="chatMessage.length==0" (click)="sendMessageToUser(user?.connectionId)">Send Message</button>
        <hr>
    </div>
</div>
</code>```

sendMessageToUser (on the same component)-

```<code>sendMessageToUser(sendToConnId: any): void {
  this.sendToConnId=sendToConnId;
  this.signalRService.sendMessageToUser(
  this.sendMessageToUserUrl,
  this.chatMessage,
  this.sendToConnId,
   );
}
</code>```

SignalR service-

```<code>public addListenersMsg() {
this.hubConnection.on("GetMessage", (message: string, connectionId: string) => {
  this.messages.push(buildDisplayChatMessageModel(new Date(), message));
});
}

public sendMessageToUser(sendMessageToUserUrl: string, message: string, sendToConnId: any){
firstValueFrom(this.http.post(sendMessageToUserUrl, buildChatMessageModel(sendToConnId, message)))
  .then((response) => {
    console.log(response);
  })
  .catch((error) => {
    console.log("Failed to send message: ", error);
    alert("Failed to send message: "+ error);
  })
}
</code>```

Body:
I'm trying to make a chat between two clients that you can choose from the connected clients list. So far everything is working good - I have the list and I succeeded to send messages to all clients by using Clients.All.SendAsync.

The problem starts when I'm trying to use

Clients.Client(connectionId).

In my client side (Angular), where I'm displaying the connected clients list, I've added a button to each client so you can send him a message:

I have click event to send the connectionId to the server, so it will know who to send a message to. I debugged the program and saw that I'm reaching to the server with the right data (the connectionId to send him a message) and when I'm getting back to the client no message is printed. Also I'm not getting any error on the console. What am I doing wrong?

Server side:

Controller-

 [HttpPost("SendMessageToUser")]
    public Task<IActionResult> SendMessageToUser([FromBody] ChatMessageDto chatMessageDto)
    {
        IActionResult actionResult;
        if (chatMessageDto.Validate())
        {
            Response response=_signalrService.SendMessageToUser(chatMessageDto.ConnectionId,chatMessageDto.Message);
            actionResult=Ok(response);
        }
        else
        {
            actionResult = BadRequest();
        }
        return Task.FromResult(actionResult);
    }

Service-

    public Response SendMessageToUser(string connectionId, string message)
    {
        Response response;

        UserHub hub = new UserHub(_userHubContext);
        hub.SendMessageToUser(message, connectionId);

        response = new Response
        {
            Message = message,
            IsSuccess = true
        };

        return response;
    }

Hub-

    public void  SendMessageToUser(string message, string connectionId)
    {
        _hubContext.Clients.Client(connectionId).SendAsync("GetMessage", message).Wait();
    }

Client side:

user.ts component - only partial code that relevant (there is continuance in my computer)

startSignalrConnection(): void {
this.signalRService
  .startSignalrConnection(this.signalrConnectionUrl)
  .then((signalrHubConnectionId) => {
    firstValueFrom(
      this.http.post(
        this.addClientUrl,
        //get user name from local storage
        buildNewChatClientConnectionModel(
          this.chatClientId,
          signalrHubConnectionId,
          this.userName!
        )
      )
    )
      .then((response) => {
        this.signalRService.addListenersMsg();
        // Add function call for getting all connected users
        this.userService.getConnectedUsers().subscribe((users) => {
          this.users = users;
        });

user.html component-

Id: {{user?.chatClientId}}

ConnectionId: {{user?.connectionId}}

Name: {{user?.name}}

        <button class="button" [disabled]="chatMessage.length==0" (click)="sendMessageToUser(user?.connectionId)">Send Message</button>

sendMessageToUser (on the same component)-

sendMessageToUser(sendToConnId: any): void {
  this.sendToConnId=sendToConnId;
  this.signalRService.sendMessageToUser(
  this.sendMessageToUserUrl,
  this.chatMessage,
  this.sendToConnId,
   );
}

SignalR service-

public addListenersMsg() {
this.hubConnection.on("GetMessage", (message: string, connectionId: string) => {
  this.messages.push(buildDisplayChatMessageModel(new Date(), message));
});
}

public sendMessageToUser(sendMessageToUserUrl: string, message: string, sendToConnId: any){
firstValueFrom(this.http.post(sendMessageToUserUrl, buildChatMessageModel(sendToConnId, message)))
  .then((response) => {
    console.log(response);
  })
  .catch((error) => {
    console.log("Failed to send message: ", error);
    alert("Failed to send message: "+ error);
  })
}


问:
has anyone got any solution for heroicons version conflict?
I tried to go through this convo, but none of the solutions seem to work. the following is how i imported hero icons   import { MenuIcon, MagnifyingGlassIcon, ShoppingCartIcon, } from "@heroicons/react/outline";

and tried to put a search icon like <MagnifyingGlassIcon className=" h-12 p-4" />. I get this on my browser,errorMsg. I tried to install v1 like npm install @heroicons/react@v1 and the result in the terminal is enter image description here I also tried <SearchIcon/> and <MagnifyingGlassIcon /> yet none of them seem to work. and also tried to import as v2 ...@heroicons/react/24/outline


问:
Caused by NewConnectionError : Failed to establish a new connection:
```<code>df = pd.read_excel('Input.xlsx', nrows=114)

# Define a function to extract the URL and URL_ID from a row
def extract_url_id(row):
  return row['URL'], row['URL_ID']

# Apply the function to each row and extract the URL and URL_ID

urls, url_ids = zip(*df.apply(extract_url_id, axis=1))

print(urls)
print(url_ids)

# Extract the URLs from the DataFrame
urls = df['URL'].tolist()

# Iterate over the URLs
for url in urls:

 # Make a request to the URL

 r = requests.get(url)

  # Extract the HTML from the response

  html = r.text
</code>```

Im trying to get the text from a list of URLs presnt in an input file 'Input.xlsx'
For each of the articles, given in the input.xlsx file, extract the article text and save the extracted article in a text file with URL_ID as its file name.
error typically indicates that there was an issue establishing a connection ..

Body:
df = pd.read_excel('Input.xlsx', nrows=114)

# Define a function to extract the URL and URL_ID from a row
def extract_url_id(row):
  return row['URL'], row['URL_ID']

# Apply the function to each row and extract the URL and URL_ID

urls, url_ids = zip(*df.apply(extract_url_id, axis=1))

print(urls)
print(url_ids)

# Extract the URLs from the DataFrame
urls = df['URL'].tolist()

# Iterate over the URLs
for url in urls:

 # Make a request to the URL

 r = requests.get(url)

  # Extract the HTML from the response

  html = r.text

Im trying to get the text from a list of URLs presnt in an input file 'Input.xlsx'
For each of the articles, given in the input.xlsx file, extract the article text and save the extracted article in a text file with URL_ID as its file name.
error typically indicates that there was an issue establishing a connection ..


问:
Google search console not discovering urls
we have 3 eshops for different countrier which every one is on different URL and the products are automatically pairing stock and translating.
We have aroung 6000 products now and the google search console has discovered most of the pages on 1st and 2nd eshop, but somehow it has discovered only 6 pages on our latest eshop which we started few months ago already. Last load of the sitemap was on 14.8.2022.
There is 19 indexed URLs and only only 145 non-indexed right now.
Where can be the problem? Can I somehow load the sitemap again manually some hard way? The sitemap is in the same format as for the other eshops and it is generated the same way.
I haven't find a way how to contact google with this issue.

here is the link to our sitemap https://www.super-parts.eu/sitemap.xml

enter image description here

I have tried to contact our eshop provider and they told me that the feed is okey and that there is no problem with it.
Also I have tried deleting the sitemap from search console but it was not loaded again, it just says that it was loaded succesfully already and the last load stays on 14.8.2022


问:
How to evaluate conditionally modeled distribution(uncertainty) with pymc3
I'm a newbie to pymc3 and bayesian analysis.
What I want to analyze is as follows:

data schema: (with 60000 rows)

x_1, x_2, survival_duration

I want to model how 'amazing' a certain case is, with features x_1 and x_2(Not the exact prediction points from the model).

My modeling assumption is:

```<code>mu = a * x_1 + b * x_2 + c

survival_duration ~ Exp(1/mu)
</code>```

My code is as follows:

```<code>"""
x_1, x_2, survival_duration: 60000 values for each
a = pm.Normal("a", mu=0, sigma=1)
b = pm.Normal("b", mu=0, sigma=1)
c = pm.Normal("c", mu=0, sigma=1)
mu = a * x_1 + b * x_2 + c

survival_duration ~ Exponential(mu)
"""

model = pm.Model()
with model:
    a = pm.Exponential("a", lam=1)
    b = pm.Exponential("b", lam=1)
    c = pm.Uniform("c", lower=0, upper=100)
    mu = pm.Deterministic("mu", a * x_1 + b * x_2 + c)
    likelihood = pm.Exponential("survival_duration", lam=1/mu, observed=survival_duration)
    trace = pm.sample(1000, chains=4)
</code>```

And I got some reasonable posteriors for a, b, and c.

Then how can I evaluate that this properly models distributions conditioned by x_1 and x_2?

Any scalar values for evaluations? or any visualizations available?

Thank you.!

Body:
I'm a newbie to pymc3 and bayesian analysis.
What I want to analyze is as follows:

data schema: (with 60000 rows)

x_1, x_2, survival_duration

I want to model how 'amazing' a certain case is, with features x_1 and x_2(Not the exact prediction points from the model).

My modeling assumption is:

mu = a * x_1 + b * x_2 + c

survival_duration ~ Exp(1/mu)

My code is as follows:

"""
x_1, x_2, survival_duration: 60000 values for each
a = pm.Normal("a", mu=0, sigma=1)
b = pm.Normal("b", mu=0, sigma=1)
c = pm.Normal("c", mu=0, sigma=1)
mu = a * x_1 + b * x_2 + c

survival_duration ~ Exponential(mu)
"""

model = pm.Model()
with model:
    a = pm.Exponential("a", lam=1)
    b = pm.Exponential("b", lam=1)
    c = pm.Uniform("c", lower=0, upper=100)
    mu = pm.Deterministic("mu", a * x_1 + b * x_2 + c)
    likelihood = pm.Exponential("survival_duration", lam=1/mu, observed=survival_duration)
    trace = pm.sample(1000, chains=4)

And I got some reasonable posteriors for a, b, and c.

Then how can I evaluate that this properly models distributions conditioned by x_1 and x_2?

Any scalar values for evaluations? or any visualizations available?

Thank you.!


问:
How to store tasks that can edit/add/delete without impact the history of the documents in sql?
It maybe seems a trivial question, but how to design the problem to SQL?

I have a document containing tasks inside.

Each document is per day and each task the have description, complete properties.

I want to be able to provide a page to the user where he can see the tasks of the document and be able to mark if it's complete.

Also, I want to provide the user the ability to edit/add or delete tasks without impacting the previous documents.

Of course, I start from the basic create a tasks table and docs table and docs_tasks for the relationship, but how to design the edit/add or delete without impact the previous docs (for search and archive purposes)?


问:
Updating modelValue in Headless UI Listbox component when options array change
I have a SelectField Vue Single File Component which relies on Headless UI Listbox.
It receives current modelValue as a prop and emits update:modelValue event to update parent's state, as normal:

```<code>// Selectfield.vue
<script setup>
import {Listbox, ListboxButton, ListboxLabel, ListboxOption, ListboxOptions} from "@headlessui/vue";
...
const emit = defineEmits(['update:modelValue']);
const props = defineProps({
    modelValue: [ Array, String ],
    options: { type: Object }
    ...
</script>

<template>
    <!-- Listbox -->
    <Listbox as="div" :modelValue="modelValue" @update:modelValue="value => $emit('update:modelValue', value)">
    ...
    </Listbox>
</template>
</code>```

As you can see, options list is another prop, dynamic from the outside.

I need to keep updated modelValue value when options change, but I do not know the standard way of doing this. Perhaps using a watcher on options? Or how could it be made?

Thanks in advance.

Body:
I have a SelectField Vue Single File Component which relies on Headless UI Listbox.
It receives current modelValue as a prop and emits update:modelValue event to update parent's state, as normal:

// Selectfield.vue

<template>

    <Listbox as="div" :modelValue="modelValue" @update:modelValue="value => $emit('update:modelValue', value)">
    ...
    </Listbox>
</template>

As you can see, options list is another prop, dynamic from the outside.

I need to keep updated modelValue value when options change, but I do not know the standard way of doing this. Perhaps using a watcher on options? Or how could it be made?

Thanks in advance.


问:
In react-table I want to apply sorting only on arrow icon not on whole table header
I am new to react-table.Currently,My sorting is working fine,but it is apply in whole header..But i Want to apply it only on arrow.

```<code>My code is like this:-

</code>```
```<code><th
{...headerProps}
{...attributes}
ref={setNodeRef}
style={{...headerProps.style, ...style}}
>
{id !== 'row-drag-handle' && id !== 'expander' && allowColumnReorder && (
 <div {...listeners} className='columnDragHandle'>
    <DragHandle />
 </div>
)}{' '}
<div style={{padding: '0.4em'}}>
 {render('Header')}
 {canResize && onColumnResize && (
  <div {...getResizerProps()} className='resizer' />
 )}
 {Boolean(onSortChange) && canSort && (
  <span>
  {isSorted ? (
    <Arrow
    fill='white'
    width='10px'
    />
    ) : (
    ''
    )}
  </span>
 )}
 </div>
</th>
</code>```
```<code>
</code>```

Body:
I am new to react-table.Currently,My sorting is working fine,but it is apply in whole header..But i Want to apply it only on arrow.

My code is like this:-

{id !== 'row-drag-handle' && id !== 'expander' && allowColumnReorder && (

    <DragHandle />

)}{' '}

 {render('Header')}
 {canResize && onColumnResize && (

 )}
 {Boolean(onSortChange) && canSort && (

  {isSorted ? (
    <Arrow
    fill='white'
    width='10px'
    />
    ) : (
    ''
    )}

 )}


问:
When Voice Over is enable list is not scrolling
I have problem with app when VO is enabled IOS not scrolling list and VO read only visible element. Function onSelectedItemChanged is not invoke, but on Android everything works correctly.

What is the reason for this difference and how to fix it?

```<code>ListWheelScrollView.useDelegate(
  controller: minuteController,
  physics: FixedExtentScrollPhysics(),
  itemExtent: 40,
  childDelegate: ListWheelChildLoopingListDelegate(
    children: List.generate(
      6,
      (index) => Container(
        decoration: BoxDecoration(border: Border(top: BorderSide(color: getPlannerHintColor(brightness), width: 1))),
        child: Center(
          child: Text(
            (index * 10).toString(),
            semanticsLabel: '${index * 10} Minut',
            style: TextStyle(
              fontSize: 16.0,
              fontWeight: FontWeight.bold,
              color: index * 10 == currentMinute ? getStandardTextColor(brightness) : getPlannerHintColor(brightness),
            ),
          ),
        ),
      ),
    ),
  ),
  onSelectedItemChanged: (int value) {
    setState(() {
      currentMinute = value * 10;
      minuteController = FixedExtentScrollController(initialItem: currentMinute);
    });
  },
)
</code>```

Edit 1.

The gesture I use is swipe right.

How list look:

Body:
I have problem with app when VO is enabled IOS not scrolling list and VO read only visible element. Function onSelectedItemChanged is not invoke, but on Android everything works correctly.

What is the reason for this difference and how to fix it?

ListWheelScrollView.useDelegate(
  controller: minuteController,
  physics: FixedExtentScrollPhysics(),
  itemExtent: 40,
  childDelegate: ListWheelChildLoopingListDelegate(
    children: List.generate(
      6,
      (index) => Container(
        decoration: BoxDecoration(border: Border(top: BorderSide(color: getPlannerHintColor(brightness), width: 1))),
        child: Center(
          child: Text(
            (index * 10).toString(),
            semanticsLabel: '${index * 10} Minut',
            style: TextStyle(
              fontSize: 16.0,
              fontWeight: FontWeight.bold,
              color: index * 10 == currentMinute ? getStandardTextColor(brightness) : getPlannerHintColor(brightness),
            ),
          ),
        ),
      ),
    ),
  ),
  onSelectedItemChanged: (int value) {
    setState(() {
      currentMinute = value * 10;
      minuteController = FixedExtentScrollController(initialItem: currentMinute);
    });
  },
)

Edit 1.

The gesture I use is swipe right.

How list look:


问:
Cannot create a new object and assign new values using spread operator
So i tried to create a new object as a solution for an issue that I had in my code. But when I tried to create a new object with the updated values it doesn't return the old values. just the updated value. what could be the issue?
Had to create a new object instead of modifying the existing one because some values are read only.

Here is the function that check for duplicate files,

```<code> const beforeUpload = (event: any) => {
  const file: any = event?.target?.files[0];
  const duplicateFile= fileList.find((files)=>{
    return files.name==file?.name;
  })
  if(duplicateFile){
    console.log(duplicateFile);

    const updatedFile={
      ...duplicateFile,
      name:`${duplicateFile.name}(${duplicateCount})`
    };
    console.log(updatedFile);
    setDuplicateCount(duplicateCount+1);

  }

  if (!file) {
    return;
  }
</code>```

takes a file and checks whether the file name already exists or not. And add a number to the end of the file name. i want to create a new object with the update name. Thats where I get the issue.

Here is the console output,
The object on the top is what function receiving and the bottom one is the output. TIA.

Body:
So i tried to create a new object as a solution for an issue that I had in my code. But when I tried to create a new object with the updated values it doesn't return the old values. just the updated value. what could be the issue?
Had to create a new object instead of modifying the existing one because some values are read only.

Here is the function that check for duplicate files,

 const beforeUpload = (event: any) => {
  const file: any = event?.target?.files[0];
  const duplicateFile= fileList.find((files)=>{
    return files.name==file?.name;
  })
  if(duplicateFile){
    console.log(duplicateFile);

    const updatedFile={
      ...duplicateFile,
      name:`${duplicateFile.name}(${duplicateCount})`
    };
    console.log(updatedFile);
    setDuplicateCount(duplicateCount+1);

  }

  if (!file) {
    return;
  }

takes a file and checks whether the file name already exists or not. And add a number to the end of the file name. i want to create a new object with the update name. Thats where I get the issue.

Here is the console output,
The object on the top is what function receiving and the bottom one is the output. TIA.


问:
flutter run: Error: Activity class {com.example.x/com.example.x.MainActivity} does not exist
Computer: Debian Sid, Flutter 3.3.10, Dart 2.18.6
Mobile: Google Pixel 3a, GrapheneOS last update (Android 12)

When I run my app with command line or vscode, I have an error:

```<code>...
[ +424 ms] Running Gradle task 'assembleDebug'... (completed in 3,9s)
[  +65 ms] calculateSha: LocalDirectory:
'/home/romain/documents/flutter/drissas-flutter/app_musique/build/app/outputs/flutter-apk'/app.apk
[+1147 ms] ✓  Built build/app/outputs/flutter-apk/app-debug.apk.
[   +3 ms] executing: /home/romain/Android/Sdk/build-tools/33.0.0/aapt dump xmltree
/home/romain/documents/flutter/drissas-flutter/app_musique/build/app/outputs/flutter-apk/app.apk AndroidManifest.xml
[   +7 ms] Exit code 0 from: /home/romain/Android/Sdk/build-tools/33.0.0/aapt dump xmltree
/home/romain/documents/flutter/drissas-flutter/app_musique/build/app/outputs/flutter-apk/app.apk AndroidManifest.xml
[        ] N: android=http://schemas.android.com/apk/res/android
             E: manifest (line=2)
               A: android:versionCode(0x0101021b)=(type 0x10)0x1
               A: android:versionName(0x0101021c)="1.0.0" (Raw: "1.0.0")
               A: android:compileSdkVersion(0x01010572)=(type 0x10)0x1f
               A: android:compileSdkVersionCodename(0x01010573)="12" (Raw: "12")
               A: package="com.example.app_musique" (Raw: "com.example.app_musique")
               A: platformBuildVersionCode=(type 0x10)0x1f
               A: platformBuildVersionName=(type 0x10)0xc
               E: uses-sdk (line=7)
                 A: android:minSdkVersion(0x0101020c)=(type 0x10)0x10
                 A: android:targetSdkVersion(0x01010270)=(type 0x10)0x1f
               E: uses-permission (line=15)
                 A: android:name(0x01010003)="android.permission.INTERNET" (Raw: "android.permission.INTERNET")
               E: application (line=17)
                 A: android:label(0x01010001)="app_musique" (Raw: "app_musique")
                 A: android:icon(0x01010002)=@0x7f080000
                 A: android:name(0x01010003)="android.app.Application" (Raw: "android.app.Application")                 A: android:debuggable(0x0101000f)=(type 0x12)0xffffffff
                 A: android:appComponentFactory(0x0101057a)="androidx.core.app.CoreComponentFactory" (Raw:
                 "androidx.core.app.CoreComponentFactory")
                 E: activity (line=23)
                   A: android:theme(0x01010000)=@0x7f0a0000
                   A: android:name(0x01010003)="com.example.app_musique.MainActivity" (Raw: "com.example.app_musique.MainActivity")
                   A: android:exported(0x01010010)=(type 0x12)0xffffffff
                   A: android:launchMode(0x0101001d)=(type 0x10)0x1
                   A: android:configChanges(0x0101001f)=(type 0x11)0x40003fb4
                   A: android:windowSoftInputMode(0x0101022b)=(type 0x11)0x10
                   A: android:hardwareAccelerated(0x010102d3)=(type 0x12)0xffffffff
                   E: meta-data (line=38)
                     A: android:name(0x01010003)="io.flutter.embedding.android.NormalTheme" (Raw:
                     "io.flutter.embedding.android.NormalTheme")
                     A: android:resource(0x01010025)=@0x7f0a0001
                   E: intent-filter (line=42)
                     E: action (line=43)
                       A: android:name(0x01010003)="android.intent.action.MAIN" (Raw: "android.intent.action.MAIN")
                     E: category (line=45)
                       A: android:name(0x01010003)="android.intent.category.LAUNCHER" (Raw: "android.intent.category.LAUNCHER")
                 E: meta-data (line=52)
                   A: android:name(0x01010003)="flutterEmbedding" (Raw: "flutterEmbedding")
                   A: android:value(0x01010024)=(type 0x10)0x2
                 E: uses-library (line=56)
                   A: android:name(0x01010003)="androidx.window.extensions" (Raw: "androidx.window.extensions")
                   A: android:required(0x0101028e)=(type 0x12)0x0
                 E: uses-library (line=59)
                   A: android:name(0x01010003)="androidx.window.sidecar" (Raw: "androidx.window.sidecar")
                   A: android:required(0x0101028e)=(type 0x12)0x0
[   +1 ms] Stopping app 'app.apk' on Pixel 3a.
[        ] executing: /home/romain/Android/Sdk/platform-tools/adb -s 05SAY1Y50D shell am force-stop com.example.app_musique
[ +137 ms] executing: /home/romain/Android/Sdk/platform-tools/adb -s 05SAY1Y50D shell pm list packages com.example.app_musique
[  +79 ms] Installing APK.
[   +1 ms] Installing build/app/outputs/flutter-apk/app.apk...
[        ] executing: /home/romain/Android/Sdk/platform-tools/adb -s 05SAY1Y50D install -t -r
/home/romain/documents/flutter/drissas-flutter/app_musique/build/app/outputs/flutter-apk/app.apk
[+3324 ms] Performing Streamed Install
                    Success
[        ] Installing build/app/outputs/flutter-apk/app.apk... (completed in 3,3s)
[   +3 ms] executing: /home/romain/Android/Sdk/platform-tools/adb -s 05SAY1Y50D shell echo -n ce3a5b315fa9f958146cb18d5103c9f27f04354c
> /data/local/tmp/sky.com.example.app_musique.sha1
[  +63 ms] executing: /home/romain/Android/Sdk/platform-tools/adb -s 05SAY1Y50D shell -x logcat -v time -t 1
[  +97 ms] --------- beginning of system
           01-03 10:26:20.118 W/ActivityManager( 1214): Skipping broadcast of Intent { act=android.intent.action.MY_PACKAGE_REPLACED
           flg=0x4000010 pkg=com.example.app_musique (has extras) }: user 11 and its parent (if any) are stopped
[  +13 ms] executing: /home/romain/Android/Sdk/platform-tools/adb -s 05SAY1Y50D shell am start -a android.intent.action.MAIN -c
android.intent.category.LAUNCHER -f 0x20000000 --ez enable-dart-profiling true --ez enable-checked-mode true --ez verify-entry-points
true com.example.app_musique/com.example.app_musique.MainActivity
[ +159 ms] Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x20000000
cmp=com.example.app_musique/.MainActivity (has extras) }

                    Error type 3
                    Error: Activity class {com.example.app_musique/com.example.app_musique.MainActivity} does not exist.
[        ] Waiting for observatory port to be available...
</code>```

I haven't programmed in 1 or 2 months. I have tested: System update, flutter update, GrapheneOS update. Tested with my Google Pixel 6 is good but my setup for dev is with my Google Pixel 3a.

An idea? thank you!

Body:
Computer: Debian Sid, Flutter 3.3.10, Dart 2.18.6
Mobile: Google Pixel 3a, GrapheneOS last update (Android 12)

When I run my app with command line or vscode, I have an error:

...
[ +424 ms] Running Gradle task 'assembleDebug'... (completed in 3,9s)
[  +65 ms] calculateSha: LocalDirectory:
'/home/romain/documents/flutter/drissas-flutter/app_musique/build/app/outputs/flutter-apk'/app.apk
[+1147 ms] ✓  Built build/app/outputs/flutter-apk/app-debug.apk.
[   +3 ms] executing: /home/romain/Android/Sdk/build-tools/33.0.0/aapt dump xmltree
/home/romain/documents/flutter/drissas-flutter/app_musique/build/app/outputs/flutter-apk/app.apk AndroidManifest.xml
[   +7 ms] Exit code 0 from: /home/romain/Android/Sdk/build-tools/33.0.0/aapt dump xmltree
/home/romain/documents/flutter/drissas-flutter/app_musique/build/app/outputs/flutter-apk/app.apk AndroidManifest.xml
[        ] N: android=http://schemas.android.com/apk/res/android
             E: manifest (line=2)
               A: android:versionCode(0x0101021b)=(type 0x10)0x1
               A: android:versionName(0x0101021c)="1.0.0" (Raw: "1.0.0")
               A: android:compileSdkVersion(0x01010572)=(type 0x10)0x1f
               A: android:compileSdkVersionCodename(0x01010573)="12" (Raw: "12")
               A: package="com.example.app_musique" (Raw: "com.example.app_musique")
               A: platformBuildVersionCode=(type 0x10)0x1f
               A: platformBuildVersionName=(type 0x10)0xc
               E: uses-sdk (line=7)
                 A: android:minSdkVersion(0x0101020c)=(type 0x10)0x10
                 A: android:targetSdkVersion(0x01010270)=(type 0x10)0x1f
               E: uses-permission (line=15)
                 A: android:name(0x01010003)="android.permission.INTERNET" (Raw: "android.permission.INTERNET")
               E: application (line=17)
                 A: android:label(0x01010001)="app_musique" (Raw: "app_musique")
                 A: android:icon(0x01010002)=@0x7f080000
                 A: android:name(0x01010003)="android.app.Application" (Raw: "android.app.Application")                 A: android:debuggable(0x0101000f)=(type 0x12)0xffffffff
                 A: android:appComponentFactory(0x0101057a)="androidx.core.app.CoreComponentFactory" (Raw:
                 "androidx.core.app.CoreComponentFactory")
                 E: activity (line=23)
                   A: android:theme(0x01010000)=@0x7f0a0000
                   A: android:name(0x01010003)="com.example.app_musique.MainActivity" (Raw: "com.example.app_musique.MainActivity")
                   A: android:exported(0x01010010)=(type 0x12)0xffffffff
                   A: android:launchMode(0x0101001d)=(type 0x10)0x1
                   A: android:configChanges(0x0101001f)=(type 0x11)0x40003fb4
                   A: android:windowSoftInputMode(0x0101022b)=(type 0x11)0x10
                   A: android:hardwareAccelerated(0x010102d3)=(type 0x12)0xffffffff
                   E: meta-data (line=38)
                     A: android:name(0x01010003)="io.flutter.embedding.android.NormalTheme" (Raw:
                     "io.flutter.embedding.android.NormalTheme")
                     A: android:resource(0x01010025)=@0x7f0a0001
                   E: intent-filter (line=42)
                     E: action (line=43)
                       A: android:name(0x01010003)="android.intent.action.MAIN" (Raw: "android.intent.action.MAIN")
                     E: category (line=45)
                       A: android:name(0x01010003)="android.intent.category.LAUNCHER" (Raw: "android.intent.category.LAUNCHER")
                 E: meta-data (line=52)
                   A: android:name(0x01010003)="flutterEmbedding" (Raw: "flutterEmbedding")
                   A: android:value(0x01010024)=(type 0x10)0x2
                 E: uses-library (line=56)
                   A: android:name(0x01010003)="androidx.window.extensions" (Raw: "androidx.window.extensions")
                   A: android:required(0x0101028e)=(type 0x12)0x0
                 E: uses-library (line=59)
                   A: android:name(0x01010003)="androidx.window.sidecar" (Raw: "androidx.window.sidecar")
                   A: android:required(0x0101028e)=(type 0x12)0x0
[   +1 ms] Stopping app 'app.apk' on Pixel 3a.
[        ] executing: /home/romain/Android/Sdk/platform-tools/adb -s 05SAY1Y50D shell am force-stop com.example.app_musique
[ +137 ms] executing: /home/romain/Android/Sdk/platform-tools/adb -s 05SAY1Y50D shell pm list packages com.example.app_musique
[  +79 ms] Installing APK.
[   +1 ms] Installing build/app/outputs/flutter-apk/app.apk...
[        ] executing: /home/romain/Android/Sdk/platform-tools/adb -s 05SAY1Y50D install -t -r
/home/romain/documents/flutter/drissas-flutter/app_musique/build/app/outputs/flutter-apk/app.apk
[+3324 ms] Performing Streamed Install
                    Success
[        ] Installing build/app/outputs/flutter-apk/app.apk... (completed in 3,3s)
[   +3 ms] executing: /home/romain/Android/Sdk/platform-tools/adb -s 05SAY1Y50D shell echo -n ce3a5b315fa9f958146cb18d5103c9f27f04354c
> /data/local/tmp/sky.com.example.app_musique.sha1
[  +63 ms] executing: /home/romain/Android/Sdk/platform-tools/adb -s 05SAY1Y50D shell -x logcat -v time -t 1
[  +97 ms] --------- beginning of system
           01-03 10:26:20.118 W/ActivityManager( 1214): Skipping broadcast of Intent { act=android.intent.action.MY_PACKAGE_REPLACED
           flg=0x4000010 pkg=com.example.app_musique (has extras) }: user 11 and its parent (if any) are stopped
[  +13 ms] executing: /home/romain/Android/Sdk/platform-tools/adb -s 05SAY1Y50D shell am start -a android.intent.action.MAIN -c
android.intent.category.LAUNCHER -f 0x20000000 --ez enable-dart-profiling true --ez enable-checked-mode true --ez verify-entry-points
true com.example.app_musique/com.example.app_musique.MainActivity
[ +159 ms] Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x20000000
cmp=com.example.app_musique/.MainActivity (has extras) }

                    Error type 3
                    Error: Activity class {com.example.app_musique/com.example.app_musique.MainActivity} does not exist.
[        ] Waiting for observatory port to be available...

I haven't programmed in 1 or 2 months. I have tested: System update, flutter update, GrapheneOS update. Tested with my Google Pixel 6 is good but my setup for dev is with my Google Pixel 3a.

An idea? thank you!


问:
Using task queue versus using nodeJS events module for long running function in web API built using express.js
I generally using RabbitMQ for running long running function call in my api build using express.js

Like this

var express = require('express')
var rabbitMQ = require('rabbitmq')

var myApi = async function(req, res) {
    try {
        let { city, country } = req.body

        var channel = await rabbitMQ.connection
        var payload = {city, country}
        var result = channel.publish('rabbitMQxchange', 'myQueue', new Buffer(JSON.stringify(payload)), { persistent: true })

        res.json({success: true})
    } catch(error) {
        res.json({success: false, "Some Error"})
    }
}
```
<p>I can use Node's events module also for executing long running function calls</p>
<p>Like this</p>
<pre class="lang-js prettyprint-override"><code>var express = require('express')
var events = require('events');
var eventEmitter = new events.EventEmitter();

eventEmitter.on('myTask', myLongRunningFunction);

function myLongRunningFunction(city, country) {

}

var myApi = async function(req, res) {
    try {
        let { city, country } = req.body

        // This should run in background
        eventEmitter.emit('myTask');

        res.json({success: true})
    } catch(error) {
        res.json({success: false, "Some Error"})
    }
}
</code>```

If I consider to use events based approach then what would be side effects?

or What are pro and cons of both the approaches?

Body:
I generally using RabbitMQ for running long running function call in my api build using express.js

Like this

var express = require('express')
var rabbitMQ = require('rabbitmq')

var myApi = async function(req, res) {
    try {
        let { city, country } = req.body

        var channel = await rabbitMQ.connection
        var payload = {city, country}
        var result = channel.publish('rabbitMQxchange', 'myQueue', new Buffer(JSON.stringify(payload)), { persistent: true })

        res.json({success: true})
    } catch(error) {
        res.json({success: false, "Some Error"})
    }
}

I can use Node's events module also for executing long running function calls

Like this

var express = require('express')
var events = require('events');
var eventEmitter = new events.EventEmitter();

eventEmitter.on('myTask', myLongRunningFunction);

function myLongRunningFunction(city, country) {

}

var myApi = async function(req, res) {
    try {
        let { city, country } = req.body

        // This should run in background
        eventEmitter.emit('myTask');

        res.json({success: true})
    } catch(error) {
        res.json({success: false, "Some Error"})
    }
}

If I consider to use events based approach then what would be side effects?

or What are pro and cons of both the approaches?


问:
How can I run python script in node.js project
What I want to do:

I would want to create 2 endpoints /servers and /items. Both endpoints should send json from GET request, but for /servers endpoint, I have python script that scrapes data from the website and outputs json file and here is a problem, because I can't run this python script as I don't have required imports and don't really know how to add them using node.js.

server.js

```<code>const app = require('express')();
const { dirname } = require('path');
const appDir = dirname(require.main.filename);
const fs = require('fs');
const { exec } = require('child_process');
const { PythonShell } = require('python-shell');

const PORT = 8080;

const options = {
  pythonPath: process.env.PYTHONPATH
};

app.get('/servers', (req, res) => {
  // Run the serversScrapper.py script and update the serversList.json file
  PythonShell.run(`${appDir}/serverScrapper.py`, options, (err, results) => {
    if (err) {
      console.error(err);
      res.sendStatus(500);
      return;
    }

    // Send the updated serversList.json file as the response
    res.sendFile(`${appDir}/serversList.json`, (err) => {
      if (err) {
        res.status(500).send(err);
      }
    });
  });
});

app.get('/items', (req, res) => {
  res.sendFile(`${appDir}/itemsList.json`, (err) => {
    if (err) {
      res.status(500).send(err);
    }
  });
});

// Run the script every 2 minutes
setInterval(() => {
  PythonShell.run(`${appDir}/serverScrapper.py`, null, (err, results) => {
    if (err) {
      console.error(err);
    }
  });
}, 2 * 60 * 1000);

app.listen(PORT, () => console.log('Server up at 8000'))
</code>```

I've copied and pasted only script file to the project folder, so that might be an issue, but I think there should be a way for node.js to automatically start python script and import required libraries (bs4, requests, json)

error log:

```<code>PythonShellError: ModuleNotFoundError: No module named 'bs4'
    at PythonShell.parseError (/rbd/pnpm-volume/eb08c55a-3afc-4775-99f3-8543de0493fc/node_modules/python-shell/index.js:295:21)
    at terminateIfNeeded (/rbd/pnpm-volume/eb08c55a-3afc-4775-99f3-8543de0493fc/node_modules/python-shell/index.js:190:32)
    at ChildProcess.<anonymous> (/rbd/pnpm-volume/eb08c55a-3afc-4775-99f3-8543de0493fc/node_modules/python-shell/index.js:182:13)
    at ChildProcess.emit (events.js:400:28)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:282:12)
    ----- Python Traceback -----
File "/app/serverScrapper.py", line 2, in <module>
      from bs4 import BeautifulSoup {
  traceback: 'Traceback (most recent call last):\n' +
'  File "/app/serverScrapper.py", line 2, in <module>\n' +
    '    from bs4 import BeautifulSoup\n' +
    "ModuleNotFoundError: No module named 'bs4'\n",
  executable: 'python3',
  options: null,
script: '/app/serverScrapper.py',
  args: null,
  exitCode: 1
}
</code>```

Body:
What I want to do:

I would want to create 2 endpoints /servers and /items. Both endpoints should send json from GET request, but for /servers endpoint, I have python script that scrapes data from the website and outputs json file and here is a problem, because I can't run this python script as I don't have required imports and don't really know how to add them using node.js.

server.js

const app = require('express')();
const { dirname } = require('path');
const appDir = dirname(require.main.filename);
const fs = require('fs');
const { exec } = require('child_process');
const { PythonShell } = require('python-shell');

const PORT = 8080;

const options = {
  pythonPath: process.env.PYTHONPATH
};

app.get('/servers', (req, res) => {
  // Run the serversScrapper.py script and update the serversList.json file
  PythonShell.run(`${appDir}/serverScrapper.py`, options, (err, results) => {
    if (err) {
      console.error(err);
      res.sendStatus(500);
      return;
    }

    // Send the updated serversList.json file as the response
    res.sendFile(`${appDir}/serversList.json`, (err) => {
      if (err) {
        res.status(500).send(err);
      }
    });
  });
});

app.get('/items', (req, res) => {
  res.sendFile(`${appDir}/itemsList.json`, (err) => {
    if (err) {
      res.status(500).send(err);
    }
  });
});

// Run the script every 2 minutes
setInterval(() => {
  PythonShell.run(`${appDir}/serverScrapper.py`, null, (err, results) => {
    if (err) {
      console.error(err);
    }
  });
}, 2 * 60 * 1000);

app.listen(PORT, () => console.log('Server up at 8000'))

I've copied and pasted only script file to the project folder, so that might be an issue, but I think there should be a way for node.js to automatically start python script and import required libraries (bs4, requests, json)

error log:

PythonShellError: ModuleNotFoundError: No module named 'bs4'
    at PythonShell.parseError (/rbd/pnpm-volume/eb08c55a-3afc-4775-99f3-8543de0493fc/node_modules/python-shell/index.js:295:21)
    at terminateIfNeeded (/rbd/pnpm-volume/eb08c55a-3afc-4775-99f3-8543de0493fc/node_modules/python-shell/index.js:190:32)
    at ChildProcess.<anonymous> (/rbd/pnpm-volume/eb08c55a-3afc-4775-99f3-8543de0493fc/node_modules/python-shell/index.js:182:13)
    at ChildProcess.emit (events.js:400:28)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:282:12)
    ----- Python Traceback -----
File "/app/serverScrapper.py", line 2, in <module>
      from bs4 import BeautifulSoup {
  traceback: 'Traceback (most recent call last):\n' +
'  File "/app/serverScrapper.py", line 2, in <module>\n' +
    '    from bs4 import BeautifulSoup\n' +
    "ModuleNotFoundError: No module named 'bs4'\n",
  executable: 'python3',
  options: null,
script: '/app/serverScrapper.py',
  args: null,
  exitCode: 1
}


问:
NETSUITE - Error INVALID_KEY_OR_REF when I try to enter the Unit of Measure when creating a sales Order
Netsuite gives me an error when I try to enter the Unit of Measure when creating a sales order from SuiteScript with a Client Script.

PART OF CODE:

```<code>so.setCurrentSublistValue({
      sublistId:'item',
      fieldId:'units',
      value:'Each', //resultRange[i].getValue({name: 'units'}),
      ignoreFieldChange: true,
      forceSyncSourcing: true
});
</code>```

Error message:

I have tried with Name, Plural Name, etc.

I need to know how I should load this field, to possibly bring it with SuiteQL from Units Type records, but I can't get it to accept anything by testing.

can someone please help me?

Body:
Netsuite gives me an error when I try to enter the Unit of Measure when creating a sales order from SuiteScript with a Client Script.

PART OF CODE:

so.setCurrentSublistValue({
      sublistId:'item',
      fieldId:'units',
      value:'Each', //resultRange[i].getValue({name: 'units'}),
      ignoreFieldChange: true,
      forceSyncSourcing: true
});

Error message:

I have tried with Name, Plural Name, etc.

I need to know how I should load this field, to possibly bring it with SuiteQL from Units Type records, but I can't get it to accept anything by testing.

can someone please help me?


问:
How to fetch records from mongoDB on the basis of duplicate data in multiple fields
The requirement is to fetch the document with some field having the same values in the particular collection..

For Example:
we have two documents below:

```<code>1. {
  "_id": "finance100",
  "status": "ACTIVE",
  "customerId": "100",
  "contactId": "contact_100",
  "itemId": "profile_100",
  "audit": {
    "dateCreated": "2022-02-16T16:34:52.718539Z",
    "dateModified": "2022-03-18T09:36:42.774271Z",
    "createdBy": "41d38c187155427fa37c855a4d1868d1",
    "modifiedBy": "41d38c187155427fa37c855a4d1868d1"
  },
  "location": "US"
}

2. {
  "_id": "finance101",
  "status": "ACTIVE",
  "customerId": "100",
  "contactId": "contact_100",
  "itemId": "profile_100",
  "audit": {
    "dateCreated": "2022-02-16T16:34:52.718539Z",
    "dateModified": "2022-03-18T09:36:42.774271Z",
    "createdBy": "41d38c187155427fa37c855a4d1868d1",
    "modifiedBy": "41d38c187155427fa37c855a4d1868d1"
  },
  "location": "US"
}

3. {
  "_id": "finance101",
  "status": "ACTIVE",
  "customerId": "100",
  "contactId": "contact_100",
  "itemId": "profile_100",
  "audit": {
    "dateCreated": "2022-02-16T16:34:52.718539Z",
    "dateModified": "2022-03-18T09:36:42.774271Z",
    "createdBy": "41d38c187155427fa37c855a4d1868d1",
    "modifiedBy": "41d38c187155427fa37c855a4d1868d1"
  },
  "location": "UK"
}
</code>```

The following parameter should have the same values:

customerId
contactId
itemId
location
so, need the fetch those records, matching with these above parameters having the same values in all the documents.

So, it should fetch the first two records (1 and 2) because the values for customerId, contactId, itemId, and location is same in first two document and in 3rd document only the location value is different(so it will not be fetched).

Could you please share the appropriate mongo query to work for this. I tried aggeration but it did not work. Thanks in advance.

Need the fetch those records, matching with these above parameters having the same values in all the documents.

Body:
The requirement is to fetch the document with some field having the same values in the particular collection..

For Example:
we have two documents below:

1. {
  "_id": "finance100",
  "status": "ACTIVE",
  "customerId": "100",
  "contactId": "contact_100",
  "itemId": "profile_100",
  "audit": {
    "dateCreated": "2022-02-16T16:34:52.718539Z",
    "dateModified": "2022-03-18T09:36:42.774271Z",
    "createdBy": "41d38c187155427fa37c855a4d1868d1",
    "modifiedBy": "41d38c187155427fa37c855a4d1868d1"
  },
  "location": "US"
}

2. {
  "_id": "finance101",
  "status": "ACTIVE",
  "customerId": "100",
  "contactId": "contact_100",
  "itemId": "profile_100",
  "audit": {
    "dateCreated": "2022-02-16T16:34:52.718539Z",
    "dateModified": "2022-03-18T09:36:42.774271Z",
    "createdBy": "41d38c187155427fa37c855a4d1868d1",
    "modifiedBy": "41d38c187155427fa37c855a4d1868d1"
  },
  "location": "US"
}

3. {
  "_id": "finance101",
  "status": "ACTIVE",
  "customerId": "100",
  "contactId": "contact_100",
  "itemId": "profile_100",
  "audit": {
    "dateCreated": "2022-02-16T16:34:52.718539Z",
    "dateModified": "2022-03-18T09:36:42.774271Z",
    "createdBy": "41d38c187155427fa37c855a4d1868d1",
    "modifiedBy": "41d38c187155427fa37c855a4d1868d1"
  },
  "location": "UK"
}

The following parameter should have the same values:

customerId
contactId
itemId
location
so, need the fetch those records, matching with these above parameters having the same values in all the documents.

So, it should fetch the first two records (1 and 2) because the values for customerId, contactId, itemId, and location is same in first two document and in 3rd document only the location value is different(so it will not be fetched).

Could you please share the appropriate mongo query to work for this. I tried aggeration but it did not work. Thanks in advance.

Need the fetch those records, matching with these above parameters having the same values in all the documents.


问:
sbt server is already booting. Create a new server? error in sbt 1.4.x
I am upgrading sbt version from 1.3.3 to 1.4.x. Totally 3 projects configured in my build.sbt and I was able to start all 3 projects in 1.3.3 but in 1.4.x I am able to start either one server successfully but when I am trying to start another servers getting error "sbt server is already booting. Create a new server?" The command which I am using to start the server is sbt "project first" run. Can anyone help me to solve this?

My play version is 2.6.19, seems this may not be an issue. I upgraded

```<code>"com.eed3si9n" % "sbt-buildinfo" % "0.9.0"
</code>```

to 0.11.0 but still same error.

Body:
I am upgrading sbt version from 1.3.3 to 1.4.x. Totally 3 projects configured in my build.sbt and I was able to start all 3 projects in 1.3.3 but in 1.4.x I am able to start either one server successfully but when I am trying to start another servers getting error "sbt server is already booting. Create a new server?" The command which I am using to start the server is sbt "project first" run. Can anyone help me to solve this?

My play version is 2.6.19, seems this may not be an issue. I upgraded

"com.eed3si9n" % "sbt-buildinfo" % "0.9.0"

to 0.11.0 but still same error.


问:
Problem with a new revised code for pyflowchart
I am having an error labeled "

```<code>**Exception has occurred: TypeError
Node.__init__() takes 1 positional argument but 2 were given
  File "C:\Users\::::::\::::::\::::::\folder\*****.py", line 36, in <module>
    start_node = Node('Start')**
</code>```

"

This is for a school project about hydroponic farming as you might be able to tell from the code :)

```<code># Import flowchart libraries
from pyflowchart.flowchart import Flowchart, Node

# Define blocks for flowchart
def identify_goals():
    print("Identify goals for project, such as producing a certain amount of vegetables for the school cafeteria within a certain time frame.")

def choose_location():
    print("Choose a suitable indoor location on the school grounds, such as a greenhouse or a room with good lighting.")

def gather_materials():
    print("Gather necessary materials and equipment, such as buckets, fertilizers, watering systems, and light sources.")

def prepare_containers():
    print("Prepare buckets and other containers to hold the plant material.")

def choose_vegetables():
    print("Choose the vegetables to be grown, and obtain seeds or plant starters.")

def plant_seeds():
    print("Plant the seeds or starters in the buckets or containers.")

def set_up_system():
    print("Set up light sources and watering systems.")

def monitor_and_adjust():
    print("Monitor and adjust the system as needed to ensure optimal growth of the plants.")

def harvest_vegetables():
    print("Harvest the vegetables when they are ripe and ready to be eaten.")

def restart_process():
    print("Restart the process so that the school can have a continuous supply of fresh vegetables.")

# Create start node
start_node = Node('Start')

# Create flowchart
pyflowchart = Flowchart(head_node=start_node)

# Add blocks to flowchart
pyflowchart.add_block('Start', {'Next': 'identify_goals'})
pyflowchart.add_block(identify_goals, {'Next': 'choose_location'})
pyflowchart.add_block(choose_location, {'Next': 'gather_materials'})
pyflowchart.add_block(gather_materials, {'Next': 'prepare_containers'})
pyflowchart.add_block(prepare_containers, {'Next': 'choose_vegetables'})
pyflowchart.add_block(choose_vegetables, {'Next': 'plant_seeds'})
pyflowchart.add_block(plant_seeds, {'Next': 'set_up_system'})
pyflowchart.add_block(set_up_system, {'Next': 'monitor_and_adjust'})
pyflowchart.add_block(monitor_and_adjust, {'Next': 'harvest_vegetables'})
pyflowchart.add_block(harvest_vegetables, {'Next': 'restart_process'})
pyflowchart.add_block(restart_process, {'Next': 'End'})
pyflowchart.add_block('End')

pyflowchart.draw('flowchart.png')
</code>```

The code is giving an error which I am unsure how to fix, any help is much appreciated :)
if anyone has more experience with making flowcharts in python, or just in general python it would help a lot

Body:
I am having an error labeled "

**Exception has occurred: TypeError
Node.__init__() takes 1 positional argument but 2 were given
  File "C:\Users\::::::\::::::\::::::\folder\*****.py", line 36, in <module>
    start_node = Node('Start')**

"

This is for a school project about hydroponic farming as you might be able to tell from the code :)

# Import flowchart libraries
from pyflowchart.flowchart import Flowchart, Node

# Define blocks for flowchart
def identify_goals():
    print("Identify goals for project, such as producing a certain amount of vegetables for the school cafeteria within a certain time frame.")

def choose_location():
    print("Choose a suitable indoor location on the school grounds, such as a greenhouse or a room with good lighting.")

def gather_materials():
    print("Gather necessary materials and equipment, such as buckets, fertilizers, watering systems, and light sources.")

def prepare_containers():
    print("Prepare buckets and other containers to hold the plant material.")

def choose_vegetables():
    print("Choose the vegetables to be grown, and obtain seeds or plant starters.")

def plant_seeds():
    print("Plant the seeds or starters in the buckets or containers.")

def set_up_system():
    print("Set up light sources and watering systems.")

def monitor_and_adjust():
    print("Monitor and adjust the system as needed to ensure optimal growth of the plants.")

def harvest_vegetables():
    print("Harvest the vegetables when they are ripe and ready to be eaten.")

def restart_process():
    print("Restart the process so that the school can have a continuous supply of fresh vegetables.")

# Create start node
start_node = Node('Start')

# Create flowchart
pyflowchart = Flowchart(head_node=start_node)

# Add blocks to flowchart
pyflowchart.add_block('Start', {'Next': 'identify_goals'})
pyflowchart.add_block(identify_goals, {'Next': 'choose_location'})
pyflowchart.add_block(choose_location, {'Next': 'gather_materials'})
pyflowchart.add_block(gather_materials, {'Next': 'prepare_containers'})
pyflowchart.add_block(prepare_containers, {'Next': 'choose_vegetables'})
pyflowchart.add_block(choose_vegetables, {'Next': 'plant_seeds'})
pyflowchart.add_block(plant_seeds, {'Next': 'set_up_system'})
pyflowchart.add_block(set_up_system, {'Next': 'monitor_and_adjust'})
pyflowchart.add_block(monitor_and_adjust, {'Next': 'harvest_vegetables'})
pyflowchart.add_block(harvest_vegetables, {'Next': 'restart_process'})
pyflowchart.add_block(restart_process, {'Next': 'End'})
pyflowchart.add_block('End')

pyflowchart.draw('flowchart.png')

The code is giving an error which I am unsure how to fix, any help is much appreciated :)
if anyone has more experience with making flowcharts in python, or just in general python it would help a lot


问:
What is wrong with this values.yaml?
im getting this error with this helm install

```<code>Error: INSTALLATION FAILED: unable to build kubernetes objects from release manifest:
error validating "":
error validating data: ValidationError(Ingress.spec.rules[0].http):
missing required field "paths" in io.k8s.api.networking.v1.HTTPIngressRuleValue
</code>```

and this is my code for the values.yaml

```<code>  ingress:
  enabled: true
  className: ""
  annotations:
    #  kubernetes.io/ingress.class: nginx
    # kubernetes.io/tls-acme: "true"
       alb.ingress.kubernetes.io/target-type: ip
       kubernetes.io/ingress.class: alb
       alb.ingress.kubernetes.io/scheme: internet-facing
  hosts:
    - host: metabasea0000125955
      paths:
      - path: /
        backend:
            service:
              name: test
              port:
               number: 3000
          pathType: Prefix
</code>```

i can't understand what im doing wrong

Title: What is wrong with this values.yaml?

Body:
im getting this error with this helm install

Error: INSTALLATION FAILED: unable to build kubernetes objects from release manifest:
error validating "":
error validating data: ValidationError(Ingress.spec.rules[0].http):
missing required field "paths" in io.k8s.api.networking.v1.HTTPIngressRuleValue

and this is my code for the values.yaml

  ingress:
  enabled: true
  className: ""
  annotations:
    #  kubernetes.io/ingress.class: nginx
    # kubernetes.io/tls-acme: "true"
       alb.ingress.kubernetes.io/target-type: ip
       kubernetes.io/ingress.class: alb
       alb.ingress.kubernetes.io/scheme: internet-facing
  hosts:
    - host: metabasea0000125955
      paths:
      - path: /
        backend:
            service:
              name: test
              port:
               number: 3000
          pathType: Prefix

i can't understand what im doing wrong


问:
Creating 2D std::vector as input vector for Tensor Flow Lite results in crashing ESP although there is enough heap memory
I want to create a 2D input vector for my machine learning model. The model runs on a ESP32 but I am running into issues when it comes to setting up such an vector.
I initialise a vector by std::vector<std::vector<float>> testing_vector;
and reserve memory in my setup routine by  testing_vector.reserve(1000);

This works fine when I reserve for 1000 elements. When I reserve for over 4700 elements though,
my ESP crashes although ESP.getFreeHeap() and ESP.getMaxAllocHeap() shows me that there should be enough heap memory available.

Edit:
Thanks to the answers of "Some programmer dude" and "molbdnilo" below I realised that my calculations for required space first was wrong. When I reserve 4700 elements of 12Byte vector objects this would now result in 56.400 Bytes which is still under Max Alloc Heap of 110580 though.

Input
When I reserve memory for 4.700 elements by testing_vector.reserve(4700);the ESP crashes

Outcome
My serial monitor with enabled "ESP32 Exception Decoder" gives me:

```<code>Rebooting...
ets Jul 29 2019 12:21:46

rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:2
load:0x3fff0030,len:1184
load:0x40078000,len:13132
load:0x40080400,len:3036
entry 0x400805e4
Total heap: 298076
Free heap: 274232
Total PSRAM: 0
Free PSRAM: 0
Max Alloc Heap: 110580
Max Vector Size: 357913941

abort() was called at PC 0x4013457b on core 1

Backtrace:0x400834e1:0x3ffb26900x40088c5d:0x3ffb26b0 0x4008d6b5:0x3ffb26d0 0x4013457b:0x3ffb2750 0x401345c2:0x3ffb2770 0x401346bb:0x3ffb2790 0x4013461a:0x3ffb27b0 0x400d1b16:0x3ffb27d0 0x400d1d95:0x3ffb27f0 0x40129fe7:0x3ffb2820

  #0  0x400834e1:0x3ffb2690 in panic_abort at /home/runner/work/esp32-arduino-lib-builder/esp32-arduino-lib-builder/esp-idf/components/esp_system/panic.c:402
  #1  0x40088c5d:0x3ffb26b0 in esp_system_abort at /home/runner/work/esp32-arduino-lib-builder/esp32-arduino-lib-builder/esp-idf/components/esp_system/esp_system.c:128
  #2  0x4008d6b5:0x3ffb26d0 in abort at /home/runner/work/esp32-arduino-lib-builder/esp32-arduino-lib-builder/esp-idf/components/newlib/abort.c:46
  #3  0x4013457b:0x3ffb2750 in __cxxabiv1::__terminate(void (*)()) at /builds/idf/crosstool-NG/.build/HOST-x86_64-w64-mingw32/xtensa-esp32-elf/src/gcc/libstdc++-v3/libsupc++/eh_terminate.cc:47
  #4  0x401345c2:0x3ffb2770 in std::terminate() at /builds/idf/crosstool-NG/.build/HOST-x86_64-w64-mingw32/xtensa-esp32-elf/src/gcc/libstdc++-v3/libsupc++/eh_terminate.cc:57
  #5  0x401346bb:0x3ffb2790 in __cxa_throw at /builds/idf/crosstool-NG/.build/HOST-x86_64-w64-mingw32/xtensa-esp32-elf/src/gcc/libstdc++-v3/libsupc++/eh_throw.cc:95
  #6  0x4013461a:0x3ffb27b0 in operator new(unsigned int) at /builds/idf/crosstool-NG/.build/HOST-x86_64-w64-mingw32/xtensa-esp32-elf/src/gcc/libstdc++-v3/libsupc++/new_op.cc:54
  #7  0x400d1b16:0x3ffb27d0 in __gnu_cxx::new_allocator<std::vector<float, std::allocator<float> > >::allocate(unsigned int, void const*) at c:\users\d.fluhr\.platformio\packages\toolchain-xtensa-esp32\xtensa-esp32-elf\include\c++\8.4.0\ext/new_allocator.h:111
      (inlined by) std::allocator_traits<std::allocator<std::vector<float, std::allocator<float> > > >::allocate(std::allocator<std::vector<float, std::allocator<float> > >&, unsigned int) at c:\users\d.fluhr\.platformio\packages\toolchain-xtensa-esp32\xtensa-esp32-elf\include\c++\8.4.0\bits/alloc_traits.h:436
      (inlined by) std::_Vector_base<std::vector<float, std::allocator<float> >, std::allocator<std::vector<float, std::allocator<float> > > >::_M_allocate(unsigned int) at c:\users\d.fluhr\.platformio\packages\toolchain-xtensa-esp32\xtensa-esp32-elf\include\c++\8.4.0\bits/stl_vector.h:296
      (inlined by) std::vector<float, std::allocator<float> >* std::vector<std::vector<float, std::allocator<float> >, std::allocator<std::vector<float, std::allocator<float> > > >::_M_allocate_and_copy<std::move_iterator<std::vector<float, std::allocator<float> >*> >(unsigned int, std::move_iterator<std::vector<float, std::allocator<float> >*>, std::move_iterator<std::vector<float, std::allocator<float> >*>) at c:\users\d.fluhr\.platformio\packages\toolchain-xtensa-esp32\xtensa-esp32-elf\include\c++\8.4.0\bits/stl_vector.h:1398
      (inlined by) std::vector<std::vector<float, std::allocator<float> >, std::allocator<std::vector<float, std::allocator<float> > > >::reserve(unsigned int) at c:\users\d.fluhr\.platformio\packages\toolchain-xtensa-esp32\xtensa-esp32-elf\include\c++\8.4.0\bits/vector.tcc:74
  #8  0x400d1d95:0x3ffb27f0 in setup() at src/main.cc:104
  #9  0x40129fe7:0x3ffb2820 in loopTask(void*) at C:/Users/d.fluhr/.platformio/packages/framework-arduinoespressif32/cores/esp32/main.cpp:42
</code>```

Conclusion

I don't understand this output very well but I understand the result is invoked by my "reserve" method.
But what could be the reason for this crash?

Code
unfortunately the tensorflow lib is very big. This is why I just present my main.cc here.
I reduced the main loop part but kept the setup part as it is for a better understanding whats going on in the background.

```<code>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/lite/micro/all_ops_resolver.h"
#include "tensorflow/lite/micro/micro_interpreter.h"
#include "tensorflow/lite/micro/system_setup.h"
#include "tensorflow/lite/schema/schema_generated.h"

// #include "main_functions.h"
#include "model.h"
#include "constants.h"
#include "output_handler.h"

// additional libraries by Daniel
#include "Arduino.h"
#include <chrono>
#include <iostream>
#include <vector>

#include "input_data.h"

//setting timer
using namespace std::chrono;
unsigned long interval = 2000;
auto t_0 = high_resolution_clock::from_time_t(0);
auto now   = high_resolution_clock::now();
auto previousMillis = duration_cast<milliseconds>(now - t_0).count();
bool debug_flag = true;

// Globals, used for compatibility with Arduino-style sketches.
namespace {
const tflite::Model* model = nullptr;
tflite::MicroInterpreter* interpreter = nullptr;
TfLiteTensor* input = nullptr;
TfLiteTensor* output = nullptr;
int inference_count = 0;

// increase if esp spits out "Failed to resize buffer"
constexpr int kTensorArenaSize = 55000;
uint8_t tensor_arena[kTensorArenaSize];

}  // namespace

// initialise test vector
std::vector<std::vector<float>> testing_vector;

// The name of this function is important for Arduino compatibility.
void setup() {

  // Map the model into a usable data structure. This doesn't involve any
  // copying or parsing, it's a very lightweight operation.
  model = tflite::GetModel(g_model);
  if (model->version() != TFLITE_SCHEMA_VERSION) {
    MicroPrintf("Model provided is schema version %d not equal to supported "
                "version %d.", model->version(), TFLITE_SCHEMA_VERSION);
    return;
  }

  // This pulls in all the operation implementations we need.
  // NOLINTNEXTLINE(runtime-global-variables)
  static tflite::AllOpsResolver resolver;

  // Build an interpreter to run the model with.
  static tflite::MicroInterpreter static_interpreter(
      model, resolver, tensor_arena, kTensorArenaSize);
  interpreter = &static_interpreter;

  // Allocate memory from the tensor_arena for the model's tensors.
  TfLiteStatus allocate_status = interpreter->AllocateTensors();
  if (allocate_status != kTfLiteOk) {
    MicroPrintf("AllocateTensors() failed");
    return;
  }

  // Obtain pointers to the model's input and output tensors.
  input = interpreter->input(0);
  output = interpreter->output(0);

  // Keep track of how many inferences we have performed.
  inference_count = 0;

  //debugg information
  std::cout << "Total heap: " << ESP.getHeapSize() << "\n";
  std::cout << "Free heap: " << ESP.getFreeHeap() << "\n";
  std::cout << "Total PSRAM: " << ESP.getPsramSize() << "\n";
  std::cout << "Free PSRAM: " << ESP.getFreePsram() << "\n";
  std::cout << "Max Alloc Heap: " << ESP.getMaxAllocHeap() << "\n";
  std::cout << "Max Vector Size: " << testing_vector.max_size() << "\n";

  // reserve memory for vector
  testing_vector.reserve(4700);
}

// The name of this function is important for Arduino compatibility.
void loop() {

  // setting up timer for test ouput
  now   = high_resolution_clock::now();
  auto mseconds = duration_cast<milliseconds>(now - t_0).count();

  if (mseconds- interval > previousMillis){
    std::cout << "test ouput: I am in main loop";
    previousMillis = duration_cast<milliseconds>(now - t_0).count();
  }
}
</code>```

Further Information:

I have a partition table and already played with configure different sizes

Partition Table

partition table image

Hardware

ESP32-S (NODEMCU-32)
SPI Flash 32Mbit

Body:
I want to create a 2D input vector for my machine learning model. The model runs on a ESP32 but I am running into issues when it comes to setting up such an vector.
I initialise a vector by std::vector<std::vector<float>> testing_vector;
and reserve memory in my setup routine by  testing_vector.reserve(1000);

This works fine when I reserve for 1000 elements. When I reserve for over 4700 elements though,
my ESP crashes although ESP.getFreeHeap() and ESP.getMaxAllocHeap() shows me that there should be enough heap memory available.

Edit:
Thanks to the answers of "Some programmer dude" and "molbdnilo" below I realised that my calculations for required space first was wrong. When I reserve 4700 elements of 12Byte vector objects this would now result in 56.400 Bytes which is still under Max Alloc Heap of 110580 though.

Input
When I reserve memory for 4.700 elements by testing_vector.reserve(4700);the ESP crashes

Outcome
My serial monitor with enabled "ESP32 Exception Decoder" gives me:

Rebooting...
ets Jul 29 2019 12:21:46

rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:2
load:0x3fff0030,len:1184
load:0x40078000,len:13132
load:0x40080400,len:3036
entry 0x400805e4
Total heap: 298076
Free heap: 274232
Total PSRAM: 0
Free PSRAM: 0
Max Alloc Heap: 110580
Max Vector Size: 357913941

abort() was called at PC 0x4013457b on core 1

Backtrace:0x400834e1:0x3ffb26900x40088c5d:0x3ffb26b0 0x4008d6b5:0x3ffb26d0 0x4013457b:0x3ffb2750 0x401345c2:0x3ffb2770 0x401346bb:0x3ffb2790 0x4013461a:0x3ffb27b0 0x400d1b16:0x3ffb27d0 0x400d1d95:0x3ffb27f0 0x40129fe7:0x3ffb2820

  #0  0x400834e1:0x3ffb2690 in panic_abort at /home/runner/work/esp32-arduino-lib-builder/esp32-arduino-lib-builder/esp-idf/components/esp_system/panic.c:402
  #1  0x40088c5d:0x3ffb26b0 in esp_system_abort at /home/runner/work/esp32-arduino-lib-builder/esp32-arduino-lib-builder/esp-idf/components/esp_system/esp_system.c:128
  #2  0x4008d6b5:0x3ffb26d0 in abort at /home/runner/work/esp32-arduino-lib-builder/esp32-arduino-lib-builder/esp-idf/components/newlib/abort.c:46
  #3  0x4013457b:0x3ffb2750 in __cxxabiv1::__terminate(void (*)()) at /builds/idf/crosstool-NG/.build/HOST-x86_64-w64-mingw32/xtensa-esp32-elf/src/gcc/libstdc++-v3/libsupc++/eh_terminate.cc:47
  #4  0x401345c2:0x3ffb2770 in std::terminate() at /builds/idf/crosstool-NG/.build/HOST-x86_64-w64-mingw32/xtensa-esp32-elf/src/gcc/libstdc++-v3/libsupc++/eh_terminate.cc:57
  #5  0x401346bb:0x3ffb2790 in __cxa_throw at /builds/idf/crosstool-NG/.build/HOST-x86_64-w64-mingw32/xtensa-esp32-elf/src/gcc/libstdc++-v3/libsupc++/eh_throw.cc:95
  #6  0x4013461a:0x3ffb27b0 in operator new(unsigned int) at /builds/idf/crosstool-NG/.build/HOST-x86_64-w64-mingw32/xtensa-esp32-elf/src/gcc/libstdc++-v3/libsupc++/new_op.cc:54
  #7  0x400d1b16:0x3ffb27d0 in __gnu_cxx::new_allocator<std::vector<float, std::allocator<float> > >::allocate(unsigned int, void const*) at c:\users\d.fluhr\.platformio\packages\toolchain-xtensa-esp32\xtensa-esp32-elf\include\c++\8.4.0\ext/new_allocator.h:111
      (inlined by) std::allocator_traits<std::allocator<std::vector<float, std::allocator<float> > > >::allocate(std::allocator<std::vector<float, std::allocator<float> > >&, unsigned int) at c:\users\d.fluhr\.platformio\packages\toolchain-xtensa-esp32\xtensa-esp32-elf\include\c++\8.4.0\bits/alloc_traits.h:436
      (inlined by) std::_Vector_base<std::vector<float, std::allocator<float> >, std::allocator<std::vector<float, std::allocator<float> > > >::_M_allocate(unsigned int) at c:\users\d.fluhr\.platformio\packages\toolchain-xtensa-esp32\xtensa-esp32-elf\include\c++\8.4.0\bits/stl_vector.h:296
      (inlined by) std::vector<float, std::allocator<float> >* std::vector<std::vector<float, std::allocator<float> >, std::allocator<std::vector<float, std::allocator<float> > > >::_M_allocate_and_copy<std::move_iterator<std::vector<float, std::allocator<float> >*> >(unsigned int, std::move_iterator<std::vector<float, std::allocator<float> >*>, std::move_iterator<std::vector<float, std::allocator<float> >*>) at c:\users\d.fluhr\.platformio\packages\toolchain-xtensa-esp32\xtensa-esp32-elf\include\c++\8.4.0\bits/stl_vector.h:1398
      (inlined by) std::vector<std::vector<float, std::allocator<float> >, std::allocator<std::vector<float, std::allocator<float> > > >::reserve(unsigned int) at c:\users\d.fluhr\.platformio\packages\toolchain-xtensa-esp32\xtensa-esp32-elf\include\c++\8.4.0\bits/vector.tcc:74
  #8  0x400d1d95:0x3ffb27f0 in setup() at src/main.cc:104
  #9  0x40129fe7:0x3ffb2820 in loopTask(void*) at C:/Users/d.fluhr/.platformio/packages/framework-arduinoespressif32/cores/esp32/main.cpp:42

Conclusion

I don't understand this output very well but I understand the result is invoked by my "reserve" method.
But what could be the reason for this crash?

Code
unfortunately the tensorflow lib is very big. This is why I just present my main.cc here.
I reduced the main loop part but kept the setup part as it is for a better understanding whats going on in the background.

/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/lite/micro/all_ops_resolver.h"
#include "tensorflow/lite/micro/micro_interpreter.h"
#include "tensorflow/lite/micro/system_setup.h"
#include "tensorflow/lite/schema/schema_generated.h"

// #include "main_functions.h"
#include "model.h"
#include "constants.h"
#include "output_handler.h"

// additional libraries by Daniel
#include "Arduino.h"
#include <chrono>
#include <iostream>
#include <vector>

#include "input_data.h"

//setting timer
using namespace std::chrono;
unsigned long interval = 2000;
auto t_0 = high_resolution_clock::from_time_t(0);
auto now   = high_resolution_clock::now();
auto previousMillis = duration_cast<milliseconds>(now - t_0).count();
bool debug_flag = true;

// Globals, used for compatibility with Arduino-style sketches.
namespace {
const tflite::Model* model = nullptr;
tflite::MicroInterpreter* interpreter = nullptr;
TfLiteTensor* input = nullptr;
TfLiteTensor* output = nullptr;
int inference_count = 0;

// increase if esp spits out "Failed to resize buffer"
constexpr int kTensorArenaSize = 55000;
uint8_t tensor_arena[kTensorArenaSize];

}  // namespace

// initialise test vector
std::vector<std::vector<float>> testing_vector;

// The name of this function is important for Arduino compatibility.
void setup() {

  // Map the model into a usable data structure. This doesn't involve any
  // copying or parsing, it's a very lightweight operation.
  model = tflite::GetModel(g_model);
  if (model->version() != TFLITE_SCHEMA_VERSION) {
    MicroPrintf("Model provided is schema version %d not equal to supported "
                "version %d.", model->version(), TFLITE_SCHEMA_VERSION);
    return;
  }

  // This pulls in all the operation implementations we need.
  // NOLINTNEXTLINE(runtime-global-variables)
  static tflite::AllOpsResolver resolver;

  // Build an interpreter to run the model with.
  static tflite::MicroInterpreter static_interpreter(
      model, resolver, tensor_arena, kTensorArenaSize);
  interpreter = &static_interpreter;

  // Allocate memory from the tensor_arena for the model's tensors.
  TfLiteStatus allocate_status = interpreter->AllocateTensors();
  if (allocate_status != kTfLiteOk) {
    MicroPrintf("AllocateTensors() failed");
    return;
  }

  // Obtain pointers to the model's input and output tensors.
  input = interpreter->input(0);
  output = interpreter->output(0);

  // Keep track of how many inferences we have performed.
  inference_count = 0;

  //debugg information
  std::cout << "Total heap: " << ESP.getHeapSize() << "\n";
  std::cout << "Free heap: " << ESP.getFreeHeap() << "\n";
  std::cout << "Total PSRAM: " << ESP.getPsramSize() << "\n";
  std::cout << "Free PSRAM: " << ESP.getFreePsram() << "\n";
  std::cout << "Max Alloc Heap: " << ESP.getMaxAllocHeap() << "\n";
  std::cout << "Max Vector Size: " << testing_vector.max_size() << "\n";

  // reserve memory for vector
  testing_vector.reserve(4700);
}

// The name of this function is important for Arduino compatibility.
void loop() {

  // setting up timer for test ouput
  now   = high_resolution_clock::now();
  auto mseconds = duration_cast<milliseconds>(now - t_0).count();

  if (mseconds- interval > previousMillis){
    std::cout << "test ouput: I am in main loop";
    previousMillis = duration_cast<milliseconds>(now - t_0).count();
  }
}

Further Information:

I have a partition table and already played with configure different sizes

Partition Table

partition table image

Hardware

ESP32-S (NODEMCU-32)
SPI Flash 32Mbit


问:
How can I include C with dependencies in Rust?
I want to use C code which depends on babeltrace2 in Rust.

For now I have in my main.rs, where prepare_graph is a custom C function:

#[link(name = "bt_util", kind = "static")]
extern "C" {
    fn prepare_graph(
        ctf_directory: *const c_char,
        plugins_directory: *const c_char
        ) -> c_int;
}
```
<p>with libbabeltrace/<strong>bt_util.c</strong>:</p>
<pre class="lang-c prettyprint-override"><code>#include <babeltrace2/babeltrace.h>
#include "bt_util.h"
int prepare_graph(const char *ctf_directory, const char *plugins_directory) {
    bt_graph *graph = bt_graph_create(0);
    int error_code = 0;
    bt_plugin_find_all_from_dir_status ret;
    const bt_plugin_set *plugins;
    ...
}

</code>```

it is built with the following build.rs:

extern crate cmake;

use cmake::Config;

fn main(){
    let babeltrace_path = Config::new("libbabeltrace").build();

    println!("cargo:rustc-link-search=native={}", babeltrace_path.display());
    println!("cargo:rustc-link-lib=static=bt_util");
}

```
<p>and the libbabeltrace/<strong>CMakeLists.txt</strong>:</p>
```cmake_minimum_required(VERSION 3.22)
project(LibBabeltrace C)

set(CMAKE_C_STANDARD 17)

include(ExternalProject)
include(FetchContent)

set(EXTERNAL_INSTALL_LOCATION ${CMAKE_BINARY_DIR}/external)
include_directories(${EXTERNAL_INSTALL_LOCATION}/include)
link_directories(${EXTERNAL_INSTALL_LOCATION}/lib)

ExternalProject_Add(babeltrace2
        GIT_REPOSITORY https://github.com/efficios/babeltrace.git
        GIT_TAG v2.0.4
        BUILD_IN_SOURCE 0
        WORKING_DIR ${CMAKE_CURRENT_SOURCE_DIR}/babeltrace2
        SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/babeltrace2
        CONFIGURE_COMMAND bash ${CMAKE_CURRENT_SOURCE_DIR}/babeltrace2/bootstrap && BABELTRACE_DEBUG_MODE=1 BABELTRACE_DEV_MODE=1 BABELTRACE_MINIMAL_LOG_LEVEL=TRACE BABELTRACE_PLUGINS_DIR=${CMAKE_CURRENT_SOURCE_DIR}/babeltrace2/plugins ./configure --disable-man-pages --disable-glibtest --disable-doxygen-doc --disable-doxygen-html --prefix "${EXTERNAL_INSTALL_LOCATION}"
        BUILD_COMMAND ${MAKE_EXE}
        BUILD_ALWAYS FALSE
        )

add_custom_target(build_external
        DEPENDS babeltrace2
        )
add_library(bt_util STATIC src/bt_util.c)
install(TARGETS bt_util DESTINATION .)
```
<p>As can be seen the libbabeltrace/bt_util.c depends on an external library (babeltrace2).
This leads to a compilation error within the build.rs which is due to not being able to link the external library.</p>
```   Compiling ctf_reader v0.1.0 (/home/tk/Documents/bitaggregat/minimal-stide-examples/Rust)
error: linking with `cc` failed: exit status: 1
  |

   ...

  = note: /usr/bin/ld: .../target/debug/build/ctf_reader-13cbb68ba72803ed/out/libbt_util.a(bt_util.c.o): in function `my_consumer_func':
          .../libbabeltrace/src/bt_util.c:18: undefined reference to `bt_message_get_type'
          /usr/bin/ld: .../libbabeltrace/src/bt_util.c:24: undefined reference to `bt_message_event_borrow_event_const'
          /usr/bin/ld: .../libbabeltrace/src/bt_util.c:25: undefined reference to `bt_event_borrow_class_const'
          /usr/bin/ld: .../libbabeltrace/src/bt_util.c:29: undefined reference to `bt_event_borrow_payload_field_const'

   ...

error: could not compile `ctf_reader` due to previous error
```

Couldn't find resources on including C with dependencies.
I know there is also a babeltrace2-sys crate. But I couldn't get this to work with system call traces.

Any help appreciated.

Body:
I want to use C code which depends on babeltrace2 in Rust.

For now I have in my main.rs, where prepare_graph is a custom C function:

#[link(name = "bt_util", kind = "static")]
extern "C" {
    fn prepare_graph(
        ctf_directory: *const c_char,
        plugins_directory: *const c_char
        ) -> c_int;
}

with libbabeltrace/bt_util.c:

#include <babeltrace2/babeltrace.h>
#include "bt_util.h"
int prepare_graph(const char *ctf_directory, const char *plugins_directory) {
    bt_graph *graph = bt_graph_create(0);
    int error_code = 0;
    bt_plugin_find_all_from_dir_status ret;
    const bt_plugin_set *plugins;
    ...
}

it is built with the following build.rs:

extern crate cmake;

use cmake::Config;

fn main(){
    let babeltrace_path = Config::new("libbabeltrace").build();

    println!("cargo:rustc-link-search=native={}", babeltrace_path.display());
    println!("cargo:rustc-link-lib=static=bt_util");
}

and the libbabeltrace/CMakeLists.txt:

cmake_minimum_required(VERSION 3.22)
project(LibBabeltrace C)

set(CMAKE_C_STANDARD 17)

include(ExternalProject)
include(FetchContent)

set(EXTERNAL_INSTALL_LOCATION ${CMAKE_BINARY_DIR}/external)
include_directories(${EXTERNAL_INSTALL_LOCATION}/include)
link_directories(${EXTERNAL_INSTALL_LOCATION}/lib)

ExternalProject_Add(babeltrace2
        GIT_REPOSITORY https://github.com/efficios/babeltrace.git
        GIT_TAG v2.0.4
        BUILD_IN_SOURCE 0
        WORKING_DIR ${CMAKE_CURRENT_SOURCE_DIR}/babeltrace2
        SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/babeltrace2
        CONFIGURE_COMMAND bash ${CMAKE_CURRENT_SOURCE_DIR}/babeltrace2/bootstrap && BABELTRACE_DEBUG_MODE=1 BABELTRACE_DEV_MODE=1 BABELTRACE_MINIMAL_LOG_LEVEL=TRACE BABELTRACE_PLUGINS_DIR=${CMAKE_CURRENT_SOURCE_DIR}/babeltrace2/plugins ./configure --disable-man-pages --disable-glibtest --disable-doxygen-doc --disable-doxygen-html --prefix "${EXTERNAL_INSTALL_LOCATION}"
        BUILD_COMMAND ${MAKE_EXE}
        BUILD_ALWAYS FALSE
        )

add_custom_target(build_external
        DEPENDS babeltrace2
        )
add_library(bt_util STATIC src/bt_util.c)
install(TARGETS bt_util DESTINATION .)

As can be seen the libbabeltrace/bt_util.c depends on an external library (babeltrace2).
This leads to a compilation error within the build.rs which is due to not being able to link the external library.

   Compiling ctf_reader v0.1.0 (/home/tk/Documents/bitaggregat/minimal-stide-examples/Rust)
error: linking with `cc` failed: exit status: 1
  |

   ...

  = note: /usr/bin/ld: .../target/debug/build/ctf_reader-13cbb68ba72803ed/out/libbt_util.a(bt_util.c.o): in function `my_consumer_func':
          .../libbabeltrace/src/bt_util.c:18: undefined reference to `bt_message_get_type'
          /usr/bin/ld: .../libbabeltrace/src/bt_util.c:24: undefined reference to `bt_message_event_borrow_event_const'
          /usr/bin/ld: .../libbabeltrace/src/bt_util.c:25: undefined reference to `bt_event_borrow_class_const'
          /usr/bin/ld: .../libbabeltrace/src/bt_util.c:29: undefined reference to `bt_event_borrow_payload_field_const'

   ...

error: could not compile `ctf_reader` due to previous error

Couldn't find resources on including C with dependencies.
I know there is also a babeltrace2-sys crate. But I couldn't get this to work with system call traces.

Any help appreciated.


问:
How to Use Ai in 2D sprite Like Enemy follow player in 2D?
So I am working on something and in my project square is my player and circle and triangle are enemies So How can I move my enemy towards the my player I tried lot of things but I failed… Please help me

https://i.stack.imgur.com/UbZJd.jpg

Give simple BP Solution


问:
What does .NET application setting type (Web Service URL) do?
In the Visual Studio 2022 designer for Settings.settings, one of the available Types for your setting is '(Web Service URL)'.

In the generated code, the only difference compared to choosing 'string' is the addition of the SpecialSettingAttribute on the third line below.

```<code>[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.SpecialSettingAttribute(global::System.Configuration.SpecialSetting.WebServiceUrl)]
[global::System.Configuration.DefaultSettingValueAttribute("not-a-url")]
public string HelpUrl {
    get {
        return ((string)(this["HelpUrl"]));
    }
}
</code>```

The general docs for application settings mention the URL possibility but don't give any details. While the specific docs for that VS page don't say anything useful.

What are the differences between '(Web Service URL)' and 'string'?

Why is it Web Service URL, and not just URL?

Is there a way to get the designer, or the runtime, to validate the setting actually contains a URL, and better yet, to return a System.Uri rather than a string?

Body:
In the Visual Studio 2022 designer for Settings.settings, one of the available Types for your setting is '(Web Service URL)'.

In the generated code, the only difference compared to choosing 'string' is the addition of the SpecialSettingAttribute on the third line below.

[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.SpecialSettingAttribute(global::System.Configuration.SpecialSetting.WebServiceUrl)]
[global::System.Configuration.DefaultSettingValueAttribute("not-a-url")]
public string HelpUrl {
    get {
        return ((string)(this["HelpUrl"]));
    }
}

The general docs for application settings mention the URL possibility but don't give any details. While the specific docs for that VS page don't say anything useful.

What are the differences between '(Web Service URL)' and 'string'?

Why is it Web Service URL, and not just URL?

Is there a way to get the designer, or the runtime, to validate the setting actually contains a URL, and better yet, to return a System.Uri rather than a string?


问:
How to define roles and responsibilities in MongoDB other than ADMIN
As i am new to mongodb, I am doing a project of pharmacy management system in node and mongoDB.

I want to make a table ROLE in which i only state id and ROLE attribute {can be admin, can be customer}, and a table of user -> having attributes {id, name, contact, gender, role_id(make relation of role table to user)}.

A user can be a admin or customer at a time, there can be multiple customers...

How could i do this relationship query in database.


问:
I can't update the sqlite3 version in python 3.8 command line?
I am following the pip steps in the manual for the installation of readthedocs. However, in the requests of this installation, sqlite3 has specified a minimum of 3.19 and above. I am upgrading sqlite3 version 3.17 to 3.40 on redhat 7.9 linux server. When I look with "Sqlite3 --version ", I see that it has been updated to version 3.40. However, when I check with the command "import sqlite3 sqlite3.sqlite.version " on the python3.8 command line, it appears as 3.17. 3.40 does not seem to be updated. Why pyhton3 still detects 3.17 even though I updated sqlite3 on Redhat and it shows 3.40 with sqlite3 --version. How can I overcome this problem?

I updated Redhat 7.9 sqlite3 from version 3.17 to 3.40 but with no results.


问:
not allowing 10MB .xlsx file in Laravel 6
I am trying to upload the .xlsx file in laravel 6.
In Small size file there is no problem. But Huge MB file is not allowing to upload.

I have return this code ...

```<code>        ini_set('max_execution_time', '0'); // for infinite time of execution
        ini_set('upload_max_filesize', '10M'); // for allow 10MB file size
        ini_set('post_max_size', '10M'); // for allow 10MB file size

        //dd($request->file('file'));
        $this->validate($request, [
            'file' => 'required|file|max:10000|mimes:xls,xlsx'
        ]);
</code>```

This is also not affecting.
Please help me anyone.

I am expecting solution to be implement in controller only.

Body:
I am trying to upload the .xlsx file in laravel 6.
In Small size file there is no problem. But Huge MB file is not allowing to upload.

I have return this code ...

        ini_set('max_execution_time', '0'); // for infinite time of execution
        ini_set('upload_max_filesize', '10M'); // for allow 10MB file size
        ini_set('post_max_size', '10M'); // for allow 10MB file size

        //dd($request->file('file'));
        $this->validate($request, [
            'file' => 'required|file|max:10000|mimes:xls,xlsx'
        ]);

This is also not affecting.
Please help me anyone.

I am expecting solution to be implement in controller only.


问:
How to call different data from one column via intermediary table?
At first I have to say that I am an absolute SQL newbie.

I have two SQL tables. The second one is an intermediary m:n table.

Table: people

id
name

1
Yoda

2
Anakin

3
Luke

4
Obi-Wan

Table: master-padawan_relation

master_id
padawan_id

1
3

4
2

master-padawan_relation.master_id and master-padawan_relation.padawan_id both refer to people.id.

Now I want a query that shows the following data:

Master
Padawan

Yoda
Luke

My query looks currently like this but it lacks the integration of the Masters name:

```<code>SELECT
    people.name AS Padawan
FROM
    people
LEFT JOIN
    master-padawan_relation ON master-padawan_relation.padawan_id = people.id
WHERE
    people.id = 3
</code>```

I don't know how to get that Masters name in there, because both names are in the same column (people.name).

I also managed to get the masters id, but I really need that name.

Appreciate every help! Thank you :)

Body:
At first I have to say that I am an absolute SQL newbie.

I have two SQL tables. The second one is an intermediary m:n table.

Table: people

id
name

1
Yoda

2
Anakin

3
Luke

4
Obi-Wan

Table: master-padawan_relation

master_id
padawan_id

1
3

4
2

master-padawan_relation.master_id and master-padawan_relation.padawan_id both refer to people.id.

Now I want a query that shows the following data:

Master
Padawan

Yoda
Luke

My query looks currently like this but it lacks the integration of the Masters name:

SELECT
    people.name AS Padawan
FROM
    people
LEFT JOIN
    master-padawan_relation ON master-padawan_relation.padawan_id = people.id
WHERE
    people.id = 3

I don't know how to get that Masters name in there, because both names are in the same column (people.name).

I also managed to get the masters id, but I really need that name.

Appreciate every help! Thank you :)