问:
How to edit Text Style in List Flutter
I have a List that is populated with the return data of various var's called by a Json API

This List also has a fixed Text element preceding the data

I want to have separate weight, size etc for the initial text and then the String being passed in

I have tried RichText  and TextStyle but needed a text function, not a list for it to work correctly

Here is the List, which is then passed into a function which pushes it to ShowDialog via the dynamic message

For example, Line: to be FontWeight.w600 & $pln String to be FontWeight.w400

```<code>List data = [
    "Line: $pln",
    "Departed from: $originname",
    "Destination: $destname",
    "Last seen: $recordedattime",
    ];
</code>```

ShowDialog, where message is the list from previous function

```<code>title: Text(title),
          content: SingleChildScrollView(
            child: ListBody(
              children: <Widget>[
                Text(message,
                style: TextStyle(
              fontSize: 18,
              color: Color(0xff2F2F2F),
              fontWeight: FontWeight.w500,
              ...
</code>```

Update 2 -

```<code>Future<void> _showDialog(String title, String message) async {
    return showDialog<void>(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return AlertDialog(
          backgroundColor: Color(0xff2AC6FF),
          shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(10)),
          title: Text(title),
          content: Container(
        // Just set a height & a width so you don't receive the previous error
        width: 200,
        height: 200,
            child: ListView.builder(
      itemCount: data.length,
      itemBuilder: (context, index){
        final titleText = data[index].split(': ')[0];
        final subText = data[index].split(': ')[1];

        return RichText(
          text: TextSpan(
           children: <TextSpan>[
              TextSpan(text: titleText, style: TextStyle(fontWeight: FontWeight.w600) ),
              TextSpan(text: subText, style: TextStyle(fontWeight: FontWeight.w400) ),
             ]
           ),
        );
      }
    )
          ),
          actions: <Widget>[
            TextButton(
              child: Text('OK',
...
</code>```

答:
Place this where your ListBody is

```<code>    ListView.builder(
      itemCount: data.length,
      itemBuilder: (context, index){
        final textData = data[index].split(': ');
        final titleText = textData[0] + ": ";
        final subText = textData[1];

        return RichText(
          text: TextSpan(
           children: <TextSpan>[
              TextSpan(text: titleText, style: TextStyle(fontWeight: FontWeight.w600) ),
              TextSpan(text: subText, style: TextStyle(fontWeight: FontWeight.w400) ),
             ]
           ),
        );
      }
    );

</code>```

As for your scroll view error

```<code>AlertDialog(
    title: Text(title),
    content: Container(
        // Just set a height & a width so you don't receive the previous error
        width: 200,
        height: 200,
        child: ListView.builder(
            ...
        )
    )
)
</code>```

Title: How to edit Text Style in List Flutter

Body:
I have a List that is populated with the return data of various var's called by a Json API

This List also has a fixed Text element preceding the data

I want to have separate weight, size etc for the initial text and then the String being passed in

I have tried RichText  and TextStyle but needed a text function, not a list for it to work correctly

Here is the List, which is then passed into a function which pushes it to ShowDialog via the dynamic message

For example, Line: to be FontWeight.w600 & $pln String to be FontWeight.w400

List data = [
    "Line: $pln",
    "Departed from: $originname",
    "Destination: $destname",
    "Last seen: $recordedattime",
    ];

ShowDialog, where message is the list from previous function

title: Text(title),
          content: SingleChildScrollView(
            child: ListBody(
              children: <Widget>[
                Text(message,
                style: TextStyle(
              fontSize: 18,
              color: Color(0xff2F2F2F),
              fontWeight: FontWeight.w500,
              ...

Update 2 -

Future<void> _showDialog(String title, String message) async {
    return showDialog<void>(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return AlertDialog(
          backgroundColor: Color(0xff2AC6FF),
          shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(10)),
          title: Text(title),
          content: Container(
        // Just set a height & a width so you don't receive the previous error
        width: 200,
        height: 200,
            child: ListView.builder(
      itemCount: data.length,
      itemBuilder: (context, index){
        final titleText = data[index].split(': ')[0];
        final subText = data[index].split(': ')[1];

        return RichText(
          text: TextSpan(
           children: <TextSpan>[
              TextSpan(text: titleText, style: TextStyle(fontWeight: FontWeight.w600) ),
              TextSpan(text: subText, style: TextStyle(fontWeight: FontWeight.w400) ),
             ]
           ),
        );
      }
    )
          ),
          actions: <Widget>[
            TextButton(
              child: Text('OK',
...

Body:
Place this where your ListBody is

    ListView.builder(
      itemCount: data.length,
      itemBuilder: (context, index){
        final textData = data[index].split(': ');
        final titleText = textData[0] + ": ";
        final subText = textData[1];

        return RichText(
          text: TextSpan(
           children: <TextSpan>[
              TextSpan(text: titleText, style: TextStyle(fontWeight: FontWeight.w600) ),
              TextSpan(text: subText, style: TextStyle(fontWeight: FontWeight.w400) ),
             ]
           ),
        );
      }
    );

As for your scroll view error

AlertDialog(
    title: Text(title),
    content: Container(
        // Just set a height & a width so you don't receive the previous error
        width: 200,
        height: 200,
        child: ListView.builder(
            ...
        )
    )
)


来源: stackexchange

问:
HashTable to Lwuit Table
```<code>Hashtable iHashtable=new Hashtable();
        iHashtable.put("Name", "Jhon");
        iHashtable.put("Address","India");
        Enumeration iEnumeration=iHashtable.keys();
        while(iEnumeration.hasMoreElements())
        {
         Object iresult1=iEnumeration.nextElement();
         String iresult2=(String) iHashtable.get(iresult1);

         System.out.println(iresult1);
         System.out.println(iresult2);
</code>```

My problem is I want to put the value at LWUIT table dynamically using the HashTable key and value,here is  iresult1  and  iresult2,using the key and value I want to create the LWUIT table where the value will be shown in the following form.
Name    Jhon
Address India
please help me with the source code because i am new in J2me Application.please remember don't hardcore the key and value ,we get the value after parsing.

答:
You can't do that since the JSON data isn't tabular but rather a hierarchy of nested hashtables and vectors based on the response from the server.

You can show the JSON data as a tree though by implementing the tree model interface, its not trivial but not too hard. You just need to return key objects for the keys (instead of strings) so they will allow including a reference to the value element.

ContentLicense: CC BY-SA 3.0

Title: HashTable to Lwuit Table

Body:
Hashtable iHashtable=new Hashtable();
        iHashtable.put("Name", "Jhon");
        iHashtable.put("Address","India");
        Enumeration iEnumeration=iHashtable.keys();
        while(iEnumeration.hasMoreElements())
        {
         Object iresult1=iEnumeration.nextElement();
         String iresult2=(String) iHashtable.get(iresult1);

         System.out.println(iresult1);
         System.out.println(iresult2);

My problem is I want to put the value at LWUIT table dynamically using the HashTable key and value,here is  iresult1  and  iresult2,using the key and value I want to create the LWUIT table where the value will be shown in the following form.
Name    Jhon
Address India
please help me with the source code because i am new in J2me Application.please remember don't hardcore the key and value ,we get the value after parsing.


问:
Limit the length of a post being displayed in handlebars
I have a blog app that I'm building for a class.  It's an express app using sequelize and handlebars. I am able to display the most recent 4 plost on the home page and display all posts on the /post route, but I am trying to show only a limited number of characters with a read more.. buton that links to the full post.  I cannot figure out how to limit the number of characters.  I found some handlebars helpers on here but cannot get them to work.

Here is my partial:

```<code><div class="container">
    {{#each posts as |post|}}

        <div class="card mt-4">
            <div class="card-header bg-dark">
                {{ post.title }}
                <div class="text-end">Submitted {{ format_date post.createdAt}}</div>
            </div>
            <div class="card-body text-dark">
                <h5 class="card-title">{{ User.username }}</h5>
                <p class="card-text">{{ post.body }}</p>
                <a href="/posts/{{ post.id}}" class="btn btn-dark">Read more...</a>
            </div>
        </div>
    {{/each}}
</div>
</code>```

I have a helpers.js file to format the date but I cannot figure out how to incorporate a helper to trim the post length.

Here is my current helper.js file:

```<code>function getMonthName(val){
    switch(val){
        case 0 :
            return 'January';
        case 1 :
            return 'February';
        case 2 :
            return 'March';
        case 3 :
            return 'April';
        case 4 :
            return 'May';
        case 5 :
            return 'June';
        case 6 :
            return 'July';
        case 7 :
            return 'August';
        case 8 :
            return 'September';
        case 9 :
            return 'October';
        case 10 :
            return 'November';
        case 11 :
            return 'December';
        default:
            return '';
    }
}

module.exports = {
    format_date: date => {
        var hours = date.getHours();
        var minutes = date.getMinutes();
        var ampm = hours >= 12 ? 'pm' : 'am';
        hours = hours % 12;
        hours = hours ? hours : 12; // the hour '0' should be '12'
        minutes = minutes < 10 ? '0'+minutes : minutes;
        var strTime = hours + ':' + minutes + ' ' + ampm;
        let monthValue = date.getMonth();
        return (getMonthName(monthValue)) + " " + date.getDate() + ", " + date.getFullYear() + " at " + strTime;
        //return `${new Date(date).getMonth() + 1}/${new Date(date).getDate()}/${new Date(date).getFullYear()}`;
    }
}
</code>```

答:
I found a bunch of complicated handlebars helpers but I figured out a simple solution.

In the helps file I just added:

```<code>post_tease: str => {
    const first25 =  str.slice(0, 50);
    return first25;
}
</code>```

Then in the post I just added {{ post_tease post.body }}

ContentLicense: CC BY-SA 4.0

Body:
I have a blog app that I'm building for a class.  It's an express app using sequelize and handlebars. I am able to display the most recent 4 plost on the home page and display all posts on the /post route, but I am trying to show only a limited number of characters with a read more.. buton that links to the full post.  I cannot figure out how to limit the number of characters.  I found some handlebars helpers on here but cannot get them to work.

Here is my partial:

    {{#each posts as |post|}}

                {{ post.title }}

Submitted {{ format_date post.createdAt}}

{{ User.username }}

{{ post.body }}

                Read more...

    {{/each}}

I have a helpers.js file to format the date but I cannot figure out how to incorporate a helper to trim the post length.

Here is my current helper.js file:

function getMonthName(val){
    switch(val){
        case 0 :
            return 'January';
        case 1 :
            return 'February';
        case 2 :
            return 'March';
        case 3 :
            return 'April';
        case 4 :
            return 'May';
        case 5 :
            return 'June';
        case 6 :
            return 'July';
        case 7 :
            return 'August';
        case 8 :
            return 'September';
        case 9 :
            return 'October';
        case 10 :
            return 'November';
        case 11 :
            return 'December';
        default:
            return '';
    }
}

module.exports = {
    format_date: date => {
        var hours = date.getHours();
        var minutes = date.getMinutes();
        var ampm = hours >= 12 ? 'pm' : 'am';
        hours = hours % 12;
        hours = hours ? hours : 12; // the hour '0' should be '12'
        minutes = minutes < 10 ? '0'+minutes : minutes;
        var strTime = hours + ':' + minutes + ' ' + ampm;
        let monthValue = date.getMonth();
        return (getMonthName(monthValue)) + " " + date.getDate() + ", " + date.getFullYear() + " at " + strTime;
        //return `${new Date(date).getMonth() + 1}/${new Date(date).getDate()}/${new Date(date).getFullYear()}`;
    }
}

Body:
I found a bunch of complicated handlebars helpers but I figured out a simple solution.

In the helps file I just added:

post_tease: str => {
    const first25 =  str.slice(0, 50);
    return first25;
}

Then in the post I just added {{ post_tease post.body }}


问:
Python Function that Match a Given Template
Say I have a template and I have a dictionary containing words. I want to create a function that returns a list of words that match the given template. To illustrate this:

```<code>template = 'W**ER'
dictionary = {'apple': '', 'water': '', 'weber': '', 'tiger': '', 'elder': '', 'rover': '', 'waver': ''}

Desired output:
output_list = ['water', 'weber', 'waver']
</code>```

I'm not entirely sure how to create the function and I would totally appreciate any help. Thanks!

答:
Here is a working solution

```<code>import re

dictionary = {'apple': '', 'water': '', 'weber': '', 'tiger': '', 'elder': '', 'rover': '', 'waver': ''}
keys = list(dictionary.keys()) # not necessary but I think it's cleaner

output_list = [key for key in keys if re.search(r'^w..er$', key)]
</code>```

First ^ assert this is the beginning of your word (prevent word that would not start with w but still have this pattern inside), re.match does it by default, . correspond to any character and $ as for ^ assert you touch the end of the string (here, the word).

Body:
Say I have a template and I have a dictionary containing words. I want to create a function that returns a list of words that match the given template. To illustrate this:

template = 'W**ER'
dictionary = {'apple': '', 'water': '', 'weber': '', 'tiger': '', 'elder': '', 'rover': '', 'waver': ''}

Desired output:
output_list = ['water', 'weber', 'waver']

I'm not entirely sure how to create the function and I would totally appreciate any help. Thanks!

Body:
Here is a working solution

import re

dictionary = {'apple': '', 'water': '', 'weber': '', 'tiger': '', 'elder': '', 'rover': '', 'waver': ''}
keys = list(dictionary.keys()) # not necessary but I think it's cleaner

output_list = [key for key in keys if re.search(r'^w..er$', key)]

First ^ assert this is the beginning of your word (prevent word that would not start with w but still have this pattern inside), re.match does it by default, . correspond to any character and $ as for ^ assert you touch the end of the string (here, the word).


问:
Why self.size give me back 100,100 in kivy
I need the size of the window but self.size give me back 100,100

This is the code:

from kivy.config import Config

Config.set('graphics', 'width', '700')
Config.set('graphics', 'height', '400')

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.graphics.context_instructions import Color
from kivy.graphics.vertex_instructions import Quad
from random import randint
from kivy.uix.relativelayout import RelativeLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.boxlayout import BoxLayout

class MyWidget(FloatLayout):

    enemis_list = []
    enemi_width = .1
    enemi_height = .1

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.init_enemis()
        self.new_enemi_cordinates()

    def on_size(self, instance, value):

        print(self.size)

#creo nemico
    def init_enemis(self):
        with self.canvas:
            Color(1, 1, 1)
            self.enemis_list.append(Quad())

#posiziono nemico
    def new_enemi_cordinates(self):

        r = randint(0, self.width)

        x1, y1 = r, self.height*0.1
        x2, y2 = r-(self.width*self.enemi_width)/2, y1+(self.height*self.enemi_height)/2
        x3, y3 = x1, y1+(self.height*self.enemi_height)
        x4, y4 = x2+(self.width*self.enemi_width), y2

        self.enemis_list[-1].points = [x1, y1, x2, y2, x3, y3, x4, y4]

        print(self.size)

class MyGameApp(App):
    pass

MyGameApp().run()
```

I try "Widget, BoxLayout, RelativeLayout" instead FloatLayout  but the result is the same

Instead the method on_size() works properly give me back 700,400

答: Your on_size() method will get called twice. Once when the MyWidget gets the default size for all widgets assigned (which is (100,100)), and again later when it gets its actual size set.

Body:
I need the size of the window but self.size give me back 100,100

This is the code:

from kivy.config import Config

Config.set('graphics', 'width', '700')
Config.set('graphics', 'height', '400')

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.graphics.context_instructions import Color
from kivy.graphics.vertex_instructions import Quad
from random import randint
from kivy.uix.relativelayout import RelativeLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.boxlayout import BoxLayout

class MyWidget(FloatLayout):

    enemis_list = []
    enemi_width = .1
    enemi_height = .1

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.init_enemis()
        self.new_enemi_cordinates()

    def on_size(self, instance, value):

        print(self.size)

#creo nemico
    def init_enemis(self):
        with self.canvas:
            Color(1, 1, 1)
            self.enemis_list.append(Quad())

#posiziono nemico
    def new_enemi_cordinates(self):

        r = randint(0, self.width)

        x1, y1 = r, self.height*0.1
        x2, y2 = r-(self.width*self.enemi_width)/2, y1+(self.height*self.enemi_height)/2
        x3, y3 = x1, y1+(self.height*self.enemi_height)
        x4, y4 = x2+(self.width*self.enemi_width), y2

        self.enemis_list[-1].points = [x1, y1, x2, y2, x3, y3, x4, y4]

        print(self.size)

class MyGameApp(App):
    pass

MyGameApp().run()

I try "Widget, BoxLayout, RelativeLayout" instead FloatLayout  but the result is the same

Instead the method on_size() works properly give me back 700,400


问:
Ionic Vibration not working in IOS mobile browser
Hi every one I am working on chat app and it is deploy as web and I added vibration on sending any message.

the vibration is working fine on android chrome mobile browser but not working on iOS.

import { Vibration } from '@awesome-cordova-plugins/vibration/ngx'; this.vibration.vibrate(1000);

any advise why is that

答:
Vibration API is not available on safari

https://caniuse.com/vibration


问:
How do you change the font of axis tick labels in a custom stylesheet?
I have made a custom style sheet which is working fine. I specify the font which I would like to use (Helvetica for example) by writing:

```<code>font.family: sans-serif

font.serif: Helvetica
</code>```

This results in plot components like the title and axis labels obeying the prescribed font correctly. However, the axis tick labels (the numbers on the axis) are not changing their font. For instance, in my Helvetica case, the labels of the axis ticks remain serif, while the axis labels and figure title are correctly in sans-serif (Helvetica).

I have not found a parameter to specify the font of the axis ticks (like "xtick.font" for example?). How do I change the font of the axis tick label, or atleast make it the same as the general font, within my style sheet?

答:
Okay I solved my own problem!

If you have [text.usetex: True] in the StyleSheet, it won't keep the font of the minor tick labels up to date with the font you specify in (for example) [font.serif] and [font.serif: Times New Roman].

I learned this by trying to set the math font to be non-italic ('normal'), which also was not able to be changed in any of the common ways reported online. Once I changed to my StyleSheet to have [text.usetex: False], it allowed me to set the math font by [mathtext.default: regular].

Body:
I have made a custom style sheet which is working fine. I specify the font which I would like to use (Helvetica for example) by writing:

font.family: sans-serif

font.serif: Helvetica

This results in plot components like the title and axis labels obeying the prescribed font correctly. However, the axis tick labels (the numbers on the axis) are not changing their font. For instance, in my Helvetica case, the labels of the axis ticks remain serif, while the axis labels and figure title are correctly in sans-serif (Helvetica).

I have not found a parameter to specify the font of the axis ticks (like "xtick.font" for example?). How do I change the font of the axis tick label, or atleast make it the same as the general font, within my style sheet?


问:
use of deleted function ofstream
I have a C++ code with multiple files. I use g++-4.8 as my compiler with Ubuntu 18.04. Upon compiling the program I face the error below. Could you please help me to fix this?

use of deleted function 'std::basic_ofstream<char>::basic_ofstream(const std::_basic_ofstream<char>)'

I did not have this error, however by adding emplace_back() to code this error showed up:

```<code>#include "FileOutputHub.h"

#include <boost/filesystem.hpp>

#include "InitialCondition.h"

using namespace std;

const char* LogFileName = "simulation_log.txt";
const char* StatsFilePrefix = "stats_";
const char* QSP_prefix = "QSP_";
const char* OdeStatsFilePrefix = "odeStats_";
const char* SnapShotDir = "/snapShots";
const char* SaveStateDir = "/savedStates";

extern InitialCondition ic;

FileOutputHub::FileOutputHub(void)
: _seed()
, _outDirBase()
, _log()
, _generalStats_core()
, _generalStats_margin()
, _lymph_blood_QSP()
, _gridSnapshotFstream()
, _makeshiftSteam()
{
}

FileOutputHub::~FileOutputHub()
{
    _log.close();
    for (auto& fs : _generalStats_core) {
        fs.close();
    }
    for (auto& fs : _generalStats_margin) {
        fs.close();
    }
}

/*!
    Process paths and setup output file streams
    \param [in] seed: seed is used as part of the ABM/ODE stats file names
    \param [in] baseDirectory: base directory for all output files

    Simulation log file is saved in the base directory. If a new simulation's output
    directory is set to be the same as an older one, new log will append to the end of
    existing log.

    ABM/ODE stats are placed inside the base directory, which has a file name including
    the seed of the simulation. If output directory exists, stats will be attached to
    existing files. This is because when loading from a saved state, if the seed is the same,
    we assume the simulation is continuation of the saved progress, and append statas to
    the end of existing stats file without writing new headers; otherwise, new header is writen,
    so output directory should be set to a new location.

    all grid snapshot output file are placed in a sub-folder "snapShots".

    all serialization (saved states) are placed in a sub-folder "savedStates".
    */
void FileOutputHub::setup(long seed, string baseDirectory){

    _seed = seed;
    _outDirBase = baseDirectory;

    // create directories
    boost::filesystem::path pSnap(_outDirBase + SnapShotDir);
    boost::filesystem::create_directories(pSnap);// create snapshot directory tree

    boost::filesystem::path pState(_outDirBase + SaveStateDir);
    boost::filesystem::create_directories(pState);// create save states directory tree

    // initialize filestreams
    string logFileName = _outDirBase + "/" + LogFileName;
    _log.open(logFileName, ios::out | ios::app);

    string statsFileName;
    for (int i = 0; i < ic.getVal(IC_NUM_ROI_core); i++) {

        _generalStats_core.emplace_back(ofstream());
        statsFileName = _outDirBase + "/" + StatsFilePrefix + "core_"
            + to_string(i) + "_s_" + to_string(_seed) + ".csv";
        //std::cout << "file: " << i << ", " <<statsFileName << std::endl;
        _generalStats_core[i].open(statsFileName, ios::out | ios::app);
    }
    for (int i = 0; i < ic.getVal(IC_NUM_ROI_margin); i++) {
        _generalStats_margin.emplace_back(ofstream());
        statsFileName = _outDirBase + "/" + StatsFilePrefix + "margin_"
            + to_string(i) + "_s_" + to_string(_seed) + ".csv";
        //std::cout << "file: " << i << ", " <<statsFileName << std::endl;
        _generalStats_margin[i].open(statsFileName, ios::out | ios::app);
    }

    string QSP_FileName = _outDirBase + "/" + QSP_prefix + to_string(_seed) + ".csv";
    _lymph_blood_QSP.open(QSP_FileName, ios::out | ios::app);

}

ofstream& FileOutputHub::getStatsFstream(bool core, int i){
    if (core)
    {
        return _generalStats_core[i];
    }
    else{
        return _generalStats_margin[i];
    }
}
/*! Create a new output file stream for grid snapshot and return the pointer
    \param [in] time: used to time stamp the file name
    \param [in] tag: goes to first part of file name
    use case:
    std::ofstream * snap;
    snap = <FileOutputHub instance>.getNewGridToSnapshot(time, tag);
    *snap << [contents] << std::endl;
    snap->close();
*/
ofstream& FileOutputHub::getNewGridToSnapshotStream(unsigned long time, std::string tag){

    string gridSnapFileName = _outDirBase + SnapShotDir+ "/" + tag + to_string(time) + ".csv";
    _gridSnapshotFstream.open(gridSnapFileName, ios::out | ios::trunc);
    return _gridSnapshotFstream;
}

/*! Create a new output file stream for serialzation and return the pointer
    \param [in] time: used to time stamp the file name
    \param [in] tag: goes to first part of file name
    use case:
    std::ofstream * pState;
    pState = <FileOutputHub instance>.getNewSaveStateStream(time, tag);
    *pState << BOOST_SERIALIZATION_NVP(item1) << [item2] ...;
    pState->close();
    note that the NVP macro uses the variable name as xml tag; if want to use a different
    name, use boost::serialization::make_nvp("tag", variable)
*/
ofstream& FileOutputHub::getNewSaveStateStream(unsigned long time, std::string tag){
    string saveStateFileName = _outDirBase + SaveStateDir+ "/" + tag + to_string(time) + ".dat";
    _saveStateStream.open(saveStateFileName, ios::out | ios::trunc);
    return _saveStateStream;
}

/*!
    Create a new output file stream for temporary and general purposes
    \Param [in] tag: file name
    use case:
    std::ofstream * pOFS;
    pOFS = <output overseer instance>.getNewMakeshiftStream(tag);
    *pOFS << ...
    pOFS->CLOSE()
*/
ofstream& FileOutputHub::getNewMakeshiftStream(std::string tag){

    string makeShiftFileName = _outDirBase + "/" + tag;
    _makeshiftSteam.open(makeShiftFileName, ios::out | ios::trunc);
    return _makeshiftSteam;
}
</code>```

答:
emplace_back() creates a new object in-place in the container, passing its constructor the input parameters passed to emplace_back().

In FileOutputHub::setup(), your 2 loops are creating a temporary ofstream object and passing it to emplace_back(), so it will try to create a new element passing that temporary ofstream to the new element's constructor.

It is clear from the error message that _generalStats_core and _generalStats_margin are holding ofstream elements, and your compiler is trying to call ofstream's copy constructor instead of its move constructor, so this will not work, as C++ streams are not copyable, only movable.

However, ofstream has a constructor that accepts the same input parameters as its open() method, so the loops can be re-written to not create the temporary ofstream objects at all:

```<code>for (int i = 0; i < ic.getVal(IC_NUM_ROI_core); i++) {
    statsFileName = _outDirBase + "/" + StatsFilePrefix + "core_"
        + to_string(i) + "_s_" + to_string(_seed) + ".csv";
    //std::cout << "file: " << i << ", " << statsFileName << std::endl;
    _generalStats_core.emplace_back(statsFileName, ios::app);
}

for (int i = 0; i < ic.getVal(IC_NUM_ROI_margin); i++) {
    statsFileName = _outDirBase + "/" + StatsFilePrefix + "margin_"
        + to_string(i) + "_s_" + to_string(_seed) + ".csv";
    //std::cout << "file: " << i << ", " << statsFileName << std::endl;
    _generalStats_margin.emplace_back(statsFileName, ios::app);
}
</code>```

Title: use of deleted function ofstream

Body:
I have a C++ code with multiple files. I use g++-4.8 as my compiler with Ubuntu 18.04. Upon compiling the program I face the error below. Could you please help me to fix this?

use of deleted function 'std::basic_ofstream<char>::basic_ofstream(const std::_basic_ofstream<char>)'

I did not have this error, however by adding emplace_back() to code this error showed up:

#include "FileOutputHub.h"

#include <boost/filesystem.hpp>

#include "InitialCondition.h"

using namespace std;

const char* LogFileName = "simulation_log.txt";
const char* StatsFilePrefix = "stats_";
const char* QSP_prefix = "QSP_";
const char* OdeStatsFilePrefix = "odeStats_";
const char* SnapShotDir = "/snapShots";
const char* SaveStateDir = "/savedStates";

extern InitialCondition ic;

FileOutputHub::FileOutputHub(void)
: _seed()
, _outDirBase()
, _log()
, _generalStats_core()
, _generalStats_margin()
, _lymph_blood_QSP()
, _gridSnapshotFstream()
, _makeshiftSteam()
{
}

FileOutputHub::~FileOutputHub()
{
    _log.close();
    for (auto& fs : _generalStats_core) {
        fs.close();
    }
    for (auto& fs : _generalStats_margin) {
        fs.close();
    }
}

/*!
    Process paths and setup output file streams
    \param [in] seed: seed is used as part of the ABM/ODE stats file names
    \param [in] baseDirectory: base directory for all output files

    Simulation log file is saved in the base directory. If a new simulation's output
    directory is set to be the same as an older one, new log will append to the end of
    existing log.

    ABM/ODE stats are placed inside the base directory, which has a file name including
    the seed of the simulation. If output directory exists, stats will be attached to
    existing files. This is because when loading from a saved state, if the seed is the same,
    we assume the simulation is continuation of the saved progress, and append statas to
    the end of existing stats file without writing new headers; otherwise, new header is writen,
    so output directory should be set to a new location.

    all grid snapshot output file are placed in a sub-folder "snapShots".

    all serialization (saved states) are placed in a sub-folder "savedStates".
    */
void FileOutputHub::setup(long seed, string baseDirectory){

    _seed = seed;
    _outDirBase = baseDirectory;

    // create directories
    boost::filesystem::path pSnap(_outDirBase + SnapShotDir);
    boost::filesystem::create_directories(pSnap);// create snapshot directory tree

    boost::filesystem::path pState(_outDirBase + SaveStateDir);
    boost::filesystem::create_directories(pState);// create save states directory tree

    // initialize filestreams
    string logFileName = _outDirBase + "/" + LogFileName;
    _log.open(logFileName, ios::out | ios::app);

    string statsFileName;
    for (int i = 0; i < ic.getVal(IC_NUM_ROI_core); i++) {

        _generalStats_core.emplace_back(ofstream());
        statsFileName = _outDirBase + "/" + StatsFilePrefix + "core_"
            + to_string(i) + "_s_" + to_string(_seed) + ".csv";
        //std::cout << "file: " << i << ", " <<statsFileName << std::endl;
        _generalStats_core[i].open(statsFileName, ios::out | ios::app);
    }
    for (int i = 0; i < ic.getVal(IC_NUM_ROI_margin); i++) {
        _generalStats_margin.emplace_back(ofstream());
        statsFileName = _outDirBase + "/" + StatsFilePrefix + "margin_"
            + to_string(i) + "_s_" + to_string(_seed) + ".csv";
        //std::cout << "file: " << i << ", " <<statsFileName << std::endl;
        _generalStats_margin[i].open(statsFileName, ios::out | ios::app);
    }

    string QSP_FileName = _outDirBase + "/" + QSP_prefix + to_string(_seed) + ".csv";
    _lymph_blood_QSP.open(QSP_FileName, ios::out | ios::app);

}

ofstream& FileOutputHub::getStatsFstream(bool core, int i){
    if (core)
    {
        return _generalStats_core[i];
    }
    else{
        return _generalStats_margin[i];
    }
}
/*! Create a new output file stream for grid snapshot and return the pointer
    \param [in] time: used to time stamp the file name
    \param [in] tag: goes to first part of file name
    use case:
    std::ofstream * snap;
    snap = <FileOutputHub instance>.getNewGridToSnapshot(time, tag);
    *snap << [contents] << std::endl;
    snap->close();
*/
ofstream& FileOutputHub::getNewGridToSnapshotStream(unsigned long time, std::string tag){

    string gridSnapFileName = _outDirBase + SnapShotDir+ "/" + tag + to_string(time) + ".csv";
    _gridSnapshotFstream.open(gridSnapFileName, ios::out | ios::trunc);
    return _gridSnapshotFstream;
}

/*! Create a new output file stream for serialzation and return the pointer
    \param [in] time: used to time stamp the file name
    \param [in] tag: goes to first part of file name
    use case:
    std::ofstream * pState;
    pState = <FileOutputHub instance>.getNewSaveStateStream(time, tag);
    *pState << BOOST_SERIALIZATION_NVP(item1) << [item2] ...;
    pState->close();
    note that the NVP macro uses the variable name as xml tag; if want to use a different
    name, use boost::serialization::make_nvp("tag", variable)
*/
ofstream& FileOutputHub::getNewSaveStateStream(unsigned long time, std::string tag){
    string saveStateFileName = _outDirBase + SaveStateDir+ "/" + tag + to_string(time) + ".dat";
    _saveStateStream.open(saveStateFileName, ios::out | ios::trunc);
    return _saveStateStream;
}

/*!
    Create a new output file stream for temporary and general purposes
    \Param [in] tag: file name
    use case:
    std::ofstream * pOFS;
    pOFS = <output overseer instance>.getNewMakeshiftStream(tag);
    *pOFS << ...
    pOFS->CLOSE()
*/
ofstream& FileOutputHub::getNewMakeshiftStream(std::string tag){

    string makeShiftFileName = _outDirBase + "/" + tag;
    _makeshiftSteam.open(makeShiftFileName, ios::out | ios::trunc);
    return _makeshiftSteam;
}

Body:
emplace_back() creates a new object in-place in the container, passing its constructor the input parameters passed to emplace_back().

In FileOutputHub::setup(), your 2 loops are creating a temporary ofstream object and passing it to emplace_back(), so it will try to create a new element passing that temporary ofstream to the new element's constructor.

It is clear from the error message that _generalStats_core and _generalStats_margin are holding ofstream elements, and your compiler is trying to call ofstream's copy constructor instead of its move constructor, so this will not work, as C++ streams are not copyable, only movable.

However, ofstream has a constructor that accepts the same input parameters as its open() method, so the loops can be re-written to not create the temporary ofstream objects at all:

for (int i = 0; i < ic.getVal(IC_NUM_ROI_core); i++) {
    statsFileName = _outDirBase + "/" + StatsFilePrefix + "core_"
        + to_string(i) + "_s_" + to_string(_seed) + ".csv";
    //std::cout << "file: " << i << ", " << statsFileName << std::endl;
    _generalStats_core.emplace_back(statsFileName, ios::app);
}

for (int i = 0; i < ic.getVal(IC_NUM_ROI_margin); i++) {
    statsFileName = _outDirBase + "/" + StatsFilePrefix + "margin_"
        + to_string(i) + "_s_" + to_string(_seed) + ".csv";
    //std::cout << "file: " << i << ", " << statsFileName << std::endl;
    _generalStats_margin.emplace_back(statsFileName, ios::app);
}


问:
Iterate through Python for loop more quickly
I have a Pandas data frame (called "ud_flex" below) that looks like the one below:

The data frame has over 27 million observations in it that I'm trying to iterate through to do a calculation for each row. Below is the calculation that I'm using:

```<code>def set_fpts(pos, rank, curr_fpts):
    if pos == "RB" and rank >= 3.0:
        return 0
    elif pos == "WR" and rank >= 4.0:
        return 0
    elif (pos == "TE" or pos == "QB") and rank >= 2.0:
        return 0
    else:
        return curr_fpts
</code>```

Here is the for loop that I've created:

```<code>players = ud_flex.shape[0]

for i in range(0,players):
    new_fpts = set_fpts(ud_flex.iloc[i]['position_name'], ud_flex.iloc[i]['wk_rank_orig'], ud_flex.iloc[i]['fpts'])
    ud_flex.at[i, 'fpts_orig'] = new_fpts
</code>```

Does anyone have any suggestions for how to speed up this loop? It's currently taking nearly an hour! Thanks!

答:
You could start making an algorithm that exits faster:

def set_fpts(pos, rank, curr_fpts):
    if rank > 4:
        return 0
    if rank < 2:
        return curr_fpts
    if pos in ["TE", "QB"]:
        return 0
    if rank >= 3:
        if pos == "RB":
            return 0
    return curr_fpts
```

Body:
I have a Pandas data frame (called "ud_flex" below) that looks like the one below:

The data frame has over 27 million observations in it that I'm trying to iterate through to do a calculation for each row. Below is the calculation that I'm using:

def set_fpts(pos, rank, curr_fpts):
    if pos == "RB" and rank >= 3.0:
        return 0
    elif pos == "WR" and rank >= 4.0:
        return 0
    elif (pos == "TE" or pos == "QB") and rank >= 2.0:
        return 0
    else:
        return curr_fpts

Here is the for loop that I've created:

players = ud_flex.shape[0]

for i in range(0,players):
    new_fpts = set_fpts(ud_flex.iloc[i]['position_name'], ud_flex.iloc[i]['wk_rank_orig'], ud_flex.iloc[i]['fpts'])
    ud_flex.at[i, 'fpts_orig'] = new_fpts

Does anyone have any suggestions for how to speed up this loop? It's currently taking nearly an hour! Thanks!


问:
Graph api get members of channel not able get the userId

the response of the get members of the channels has userid, when we debugg it we can find it in the response

but when we try to

```<code> var response = await graphClient.Teams[teamid].Channels[channeId].Members
                        .Request()
                        .GetAsync();
        foreach (var res in response)
        {
            var member = new Members();
            member.UserId = res.Id;      //this id is not user id
            member.FullName = res.DisplayName;
            members.Add(member);
        }
</code>```

The response has userId, not able to get the userID, how do we retrive userId

答:
I assume your debug code is accessing the beta api, while the your code snippet is using the v1.0 api.

```<code>GET https://graph.microsoft.com/beta/Teams/02bd9fd6-8f93-4758-83-1fb73740a315/channels/19:09fc54a3141a45d0bc769cf506d279@thread.skype/members

{
    "@odata.context": "https://graph.microsoft.com/beta/$metadata#teams('09fd6-8f93-4758-87c3-1fb73740a315')/channels('19%3A09fc54a3141a45d0b69cf506d2e079%40thread.skype')/members",
    "@odata.count": 19,
    "value": [
        {
            "@odata.type": "#microsoft.graph.aadUserConversationMember",
            "id": "MCMjMiMjZGNkMjE5ZGQtYmM2OC00YjliLWJmMGItNGEzM2E3OTZiZTM1IyMxOTowOWZjNTRhMzE0MWE0NWQwYmM3NjljZjUwNmQyZTA3OUB0aHJlYWQuc2t5cGUjIzA3NGU1NmVhLTBiNTAtNDQ2MS04OWU1LWM2N2FlMTRhMmMwYg==",
            "roles": [],
            "displayName": "Lee Gu",
            "visibleHistoryStartDateTime": "0001-01-01T00:00:00Z",
            "userId": "074e56ea-0b50-4461-89e5-ae14a2c0b",
            "email": "LeeG@M365x2143.onmicrosoft.com",
            "te
...
</code>```

versus the 1.0 api :

```<code>GET https://graph.microsoft.com/v1.0/Teams/02bd9fd6-8f93-4758-87c3-1fb73740a315/channels/19:09fc54a3141a45d0bc769cf506d2e079@thread.skype/members

{
    "error": {
        "code": "Forbidden",
        "message": "Caller does not have the required permissions for accessing this API. AllowedPermissions:'ChannelMember.Read.All,ChannelMember.ReadWrite.All'",
        "innerError": {
            "date": "2022-02-07T23:54:32",
            "request-id": "d82250a3-9637-4626-8afd-499ea3fd519e",
            "client-request-id": "d82250a3-9637-4626-8afd-499ea3fd519e"
        }
    }
}

</code>```

the v1.0 api appears to have more stringent permission requirements.

Body:
the response of the get members of the channels has userid, when we debugg it we can find it in the response

but when we try to

 var response = await graphClient.Teams[teamid].Channels[channeId].Members
                        .Request()
                        .GetAsync();
        foreach (var res in response)
        {
            var member = new Members();
            member.UserId = res.Id;      //this id is not user id
            member.FullName = res.DisplayName;
            members.Add(member);
        }

The response has userId, not able to get the userID, how do we retrive userId

Body:
I assume your debug code is accessing the beta api, while the your code snippet is using the v1.0 api.

GET https://graph.microsoft.com/beta/Teams/02bd9fd6-8f93-4758-83-1fb73740a315/channels/19:09fc54a3141a45d0bc769cf506d279@thread.skype/members

{
    "@odata.context": "https://graph.microsoft.com/beta/$metadata#teams('09fd6-8f93-4758-87c3-1fb73740a315')/channels('19%3A09fc54a3141a45d0b69cf506d2e079%40thread.skype')/members",
    "@odata.count": 19,
    "value": [
        {
            "@odata.type": "#microsoft.graph.aadUserConversationMember",
            "id": "MCMjMiMjZGNkMjE5ZGQtYmM2OC00YjliLWJmMGItNGEzM2E3OTZiZTM1IyMxOTowOWZjNTRhMzE0MWE0NWQwYmM3NjljZjUwNmQyZTA3OUB0aHJlYWQuc2t5cGUjIzA3NGU1NmVhLTBiNTAtNDQ2MS04OWU1LWM2N2FlMTRhMmMwYg==",
            "roles": [],
            "displayName": "Lee Gu",
            "visibleHistoryStartDateTime": "0001-01-01T00:00:00Z",
            "userId": "074e56ea-0b50-4461-89e5-ae14a2c0b",
            "email": "LeeG@M365x2143.onmicrosoft.com",
            "te
...

versus the 1.0 api :

GET https://graph.microsoft.com/v1.0/Teams/02bd9fd6-8f93-4758-87c3-1fb73740a315/channels/19:09fc54a3141a45d0bc769cf506d2e079@thread.skype/members

{
    "error": {
        "code": "Forbidden",
        "message": "Caller does not have the required permissions for accessing this API. AllowedPermissions:'ChannelMember.Read.All,ChannelMember.ReadWrite.All'",
        "innerError": {
            "date": "2022-02-07T23:54:32",
            "request-id": "d82250a3-9637-4626-8afd-499ea3fd519e",
            "client-request-id": "d82250a3-9637-4626-8afd-499ea3fd519e"
        }
    }
}

the v1.0 api appears to have more stringent permission requirements.


问:
discord.js TypeError Cannot Read properties of undefined (reading 'options')
I created a ban command for my discord bot, but I encountered such an error

code :

module.exports = {
    name: "ban",
    permission: "BAN_MEMBERS",
    options: [
        {
            name: "target",
            description: "banlamak için bir hedef seçin.",
            type: "USER",
            required: true,

        },
        {
            name: "reason",
            description: "banlamak için bir sebep seçin.",
            type: "STRING",
            required: true,

        },
        {
            name: "messages",
            description: "Seçeneklerden birini seç.",
            type: "STRING",
            required: true,
            choices: [
                {
                    name: "hiç birini silme",
                    value: 0
                },
                {
                    name: "önceki 7 gün",
                    value: 7
                }

            ]
        },

    ],

    execute(client, interaction) {
        const Target = interaction.options.getMember('target');

        if (Target.id === interaction.member.id)
        return interaction.followUp({embeds: [new MessageEmbed().setColor('BLACK').setDescription(`⛔ kendini yasaklayamazsın. `)]})

        if (Target.permissions.has('ADMINISTRATOR'))
        return interaction.followUp({embeds: [new MessageEmbed().setColor('BLACK').setDescription(`⛔ Bir Yöneticiyi Yasaklayamazsınız. `)]})

        const Reason = interaction.options.getString('reason');

        if (Reason.length > 512)
        return interaction.followUp({embeds: [new MessageEmbed().setColor('BLACK').setDescription(`⛔ sebep 512 karakteri geçemez. `)]})

        const Amount = interaction.options.getString('messages');

        Target.ban({ days : Amount, reason : Reason})

        interaction.followUp({embeds : [new MessageEmbed().setColor("WHITE").setDescription(`✅ **${Target.user.username}** banlanmıştır. `)]})

    }
}
```

答:
if the error occurs on the first line where this is executed

```<code>const Target = interaction.options.getMember('target');
</code>```

then the issue could be caused by options not being a member of the interaction. Are you sure that the interaction you are running is a command interaction. You could check this easily by adding this call before anything else. If nothing is ran after this is executed then it means the interaction you are interacting with is not a command so options won't exist on that interaction.

```<code>if (!interaction.isCommand()) return;
</code>```

Body:
if the error occurs on the first line where this is executed

const Target = interaction.options.getMember('target');

then the issue could be caused by options not being a member of the interaction. Are you sure that the interaction you are running is a command interaction. You could check this easily by adding this call before anything else. If nothing is ran after this is executed then it means the interaction you are interacting with is not a command so options won't exist on that interaction.

if (!interaction.isCommand()) return;


问:
How to get VS build agent capabilities without installing the full Visual Studio application?
I've installed the latest VS Build Tools (2022), but my on-prem build agent isn't picking up the VisualStudio-related capabilities. I've been under the impression that we no longer need to install the full application in order to get these capabilities.

An example from this blog post:

I've added all workloads to my offline layout, and I've included them in my installation.

I know this is possible, because earlier I accidentally included Python and VS 2019 Build Tools in my Node.js installation configuration. The VS-related capabilities were found by the agent then.

But I'm trying to get 2022, so I uninstalled 2019.

How can I get the 2022 VS-related capabilities to be installed and detected by my build agent, without installing the full Visual Studio product?

答:
You need to upgrade the agent to a recent enough version. You can download the agent from the azure-pipelines-agent repository's releases page. Or manually specify the capabilities.

You may need to set a special environment flag on the agent to prevent it from automatically being downgraded to whatever version shipped with your version if Azure DevOps Server or Team Foundation Server.

And then you'll also need to install the latest version of the vsbuild/msbuild and vstest tasks

Required agent version

You will need to install the most recent agent from the azure-pipelines-agent repository for it to auto-detect Visual Studio 2022, or alternatively add the capabilities to the agent manually.

You may need to force Azure DevOps Server to not downgrade back to its preferred agent version. You can do so by setting the following environment variable at the system level on your server before launching the agent:

```<code> AZP_AGENT_DOWNGRADE_DISABLED=true
</code>```

These tricks will work for most tasks in the azure-pipelines-tasks repository, as long as it doesn't depend on a UI extension or service connection type that isn't available in your version of Azure DevOps Server.

https://jessehouwing.net/adding-visual-studio-2022-to-azure-devops-server-2020/

Body:
You need to upgrade the agent to a recent enough version. You can download the agent from the azure-pipelines-agent repository's releases page. Or manually specify the capabilities.

You may need to set a special environment flag on the agent to prevent it from automatically being downgraded to whatever version shipped with your version if Azure DevOps Server or Team Foundation Server.

And then you'll also need to install the latest version of the vsbuild/msbuild and vstest tasks

Required agent version

You will need to install the most recent agent from the azure-pipelines-agent repository for it to auto-detect Visual Studio 2022, or alternatively add the capabilities to the agent manually.

You may need to force Azure DevOps Server to not downgrade back to its preferred agent version. You can do so by setting the following environment variable at the system level on your server before launching the agent:

 AZP_AGENT_DOWNGRADE_DISABLED=true

These tricks will work for most tasks in the azure-pipelines-tasks repository, as long as it doesn't depend on a UI extension or service connection type that isn't available in your version of Azure DevOps Server.

https://jessehouwing.net/adding-visual-studio-2022-to-azure-devops-server-2020/


答:
As all the answers contain '.' as any symbol, although it may be better to use any letter instead. Also note having start of string and end of string. That means that waterdasdadad won't proceed

Here is my code

```<code>import re

template = r'^w\w\wer$'  # means start of string, w, any alphabet char twice, e, r, end of string
regex = re.compile(template)
dictionary = {'apple': '', 'water': '', 'weber': '', 'tiger': '', 'elder': '', 'rover': '', 'waver': ''}

output_list = list()

for key in dictionary:
    if regex.fullmatch(key):  # use key.lower() for case insensitivity
        output_list.append(key)

print(output_list)
</code>```

Title: Python Function that Match a Given Template

Body:
As all the answers contain '.' as any symbol, although it may be better to use any letter instead. Also note having start of string and end of string. That means that waterdasdadad won't proceed

Here is my code

import re

template = r'^w\w\wer$'  # means start of string, w, any alphabet char twice, e, r, end of string
regex = re.compile(template)
dictionary = {'apple': '', 'water': '', 'weber': '', 'tiger': '', 'elder': '', 'rover': '', 'waver': ''}

output_list = list()

for key in dictionary:
    if regex.fullmatch(key):  # use key.lower() for case insensitivity
        output_list.append(key)

print(output_list)


问:
JSON.stringify is distorting code adding \ inside strings?
I am trying to save local storage info but what happens is I am getting \ added to all the items that are strings I mean as some answers stated it is caused by double stringfy ? issue is my blob action that saves the local storage refuse to handle the it unless is it is stringifed, long story short could this double stringfy needed for the function cause issues later, I have no problem when parsing back but the look of the saved elements looks really weird  ?

//const ls = JSON.stringify(localStorage);
// "id":"\"159e17e9-19b7-453d-8e10-a411c7424586\"
// "groups":"{\"bee7bdc4-d888-46e6-93d7-ed0c\" : :[{\"id\":\"0e6e6426-4d79-4eea-9180-06111dd2a0e3\"}]

const config = {a: 'fdfgdg', b: 2}
console.log(JSON.stringify(config))```

答:
When you are getting a stringfied object and you want him to become an object again, there is another command to do so

```<code>JSON.parse(obj)
</code>```

var obj = {
    id: '159e17e9-19b7-453d-8e10-a411c7424586',
    groups: '000e17e9-19b7-453d-8e10-a411c7424500'
}

var stringfiedObject = JSON.stringify(obj)
console.log(stringfiedObject)

var objectFromStringfiedObject = JSON.parse(stringfiedObject)
console.log(objectFromStringfiedObject)```

Body:
When you are getting a stringfied object and you want him to become an object again, there is another command to do so

JSON.parse(obj)

var obj = {
    id: '159e17e9-19b7-453d-8e10-a411c7424586',
    groups: '000e17e9-19b7-453d-8e10-a411c7424500'
}

var stringfiedObject = JSON.stringify(obj)
console.log(stringfiedObject)

var objectFromStringfiedObject = JSON.parse(stringfiedObject)
console.log(objectFromStringfiedObject)


问:
Looping through array with forEach
I am trying to make a basic program that loops through an array and logs the 'place' & 'distance' to the console. My program isn't working as intended and won't log the values to the console. What am I doing wrong and how can I fix it?</p>
```<code>let destinations = [
  {place: ['Dubai'],
  distance: 7276},
  {place: ['Sydney'],
  distance: 8759},
  {place: ['London'],
  distance: 4166},
  {place: ['tokyo'],
  distance: 5754},
  {place: ['Seoul'],
  distance: 6037},
];

destinations.forEach(spot => {
    if (spot.length < 6) {
      console.log(`${spot} is an interesting vacation spot.
      Let's see how far it is before we pull the trigger`);
      destinations.forEach(howFar => {
        if (howFar < 6000) {
          console.log(`${spot} is close enough. Let's go there!`);
        } if (howFar > 6000) {
          console.log(`Nevermind. ${spot} is too far.`);
        }});
    }
});
</code>```

答:
You are basically doing an Object.length, wich doesn't exist. Try something like spot.place or spot.distance.

Also, you cannot do a destinations.forEach inside destinations. Is this really necessary?
Try something like this:

```<code>destinations.forEach(spot => {
if (spot.place.length < 6) {
  console.log(`${spot.place} is an interesting vacation spot.
  Let's see how far it is before we pull the trigger`);
  if (spot.distance < 6000) {
     console.log(`${spot.place} is close enough. Let's go there!`);
  } else {
      console.log(`Nevermind. ${spot.place} is too far.`);
  }
}})
</code>```

Title: Looping through array with forEach

Body:
I am trying to make a basic program that loops through an array and logs the 'place' & 'distance' to the console. My program isn't working as intended and won't log the values to the console. What am I doing wrong and how can I fix it?

let destinations = [
  {place: ['Dubai'],
  distance: 7276},
  {place: ['Sydney'],
  distance: 8759},
  {place: ['London'],
  distance: 4166},
  {place: ['tokyo'],
  distance: 5754},
  {place: ['Seoul'],
  distance: 6037},
];

destinations.forEach(spot => {
    if (spot.length < 6) {
      console.log(`${spot} is an interesting vacation spot.
      Let's see how far it is before we pull the trigger`);
      destinations.forEach(howFar => {
        if (howFar < 6000) {
          console.log(`${spot} is close enough. Let's go there!`);
        } if (howFar > 6000) {
          console.log(`Nevermind. ${spot} is too far.`);
        }});
    }
});

Body:
You are basically doing an Object.length, wich doesn't exist. Try something like spot.place or spot.distance.

Also, you cannot do a destinations.forEach inside destinations. Is this really necessary?
Try something like this:

destinations.forEach(spot => {
if (spot.place.length < 6) {
  console.log(`${spot.place} is an interesting vacation spot.
  Let's see how far it is before we pull the trigger`);
  if (spot.distance < 6000) {
     console.log(`${spot.place} is close enough. Let's go there!`);
  } else {
      console.log(`Nevermind. ${spot.place} is too far.`);
  }
}})


问:
Finding whether the element exists in whole html page
I want to check whether an element exists in the whole page or not. Is there any way to know if the element exists in the page through jQuery?

For example:

```<code><html>
     <body>
        <p id="para1" class="para_class"></p>
     </body>
</html>
</code>```

In the above code, I have to check whether
 of id para1 exists in the DOM or not. In any case if with the help of the 'class' attribute we can know if the element exists, it also would be helpful.

答:
I know I'm a little late, but, to check if an input doesn't exist with an id using JQuery, you can do this:</p>
```<code>if (!$('#inputid').length > 0)) {
}
</code>```

Body:
I want to check whether an element exists in the whole page or not. Is there any way to know if the element exists in the page through jQuery?

For example:

In the above code, I have to check whether
 of id para1 exists in the DOM or not. In any case if with the help of the 'class' attribute we can know if the element exists, it also would be helpful.

Body:
I know I'm a little late, but, to check if an input doesn't exist with an id using JQuery, you can do this:

if (!$('#inputid').length > 0)) {
}


问:
How do I create a Postgres table with a column that holds an array of objects?
The documentation shows that arrays can be created as either text or integer. I did not find an example for creating an object array. An example is the items column:

```<code>CREATE TABLE cart (
_id serial PRIMARY KEY,
user_id Integer UNIQUE NOT NULL,
items varchar [],
FOREIGN KEY (user_id)
REFERENCES users (_id)
</code>```

Object stored in the items array have quotes around them making them strings instead of objects. A code segment creating objects in items is shown below:

```<code>update cart
set items =
array_append(items,
'{product_id: ${cartItem.productId}, size: ${cartItem.size}, quantity: ${cartItem.quantity}}')
where _id = ${cart._id}
and user_id = ${userId}
RETURNING *
</code>```

I am compelled to put quotes around the object value. As a result it is stored as a string in the column with quotes around it.

```<code>cart {
  _id: 1,
  user_id: 1,
  items: [
    '{product_id: 1, size: Small, quantity: 1}',
    '{product_id: 1, size: Small, quantity: 1}',
    '{product_id: 1, size: Small, quantity: 1}'
  ]
}
</code>```

Because the items in the items column are stored as string instead of objects, I cannot correctly iterate over them in my program.  For example,
items.product_id does not exist.

How do I fix this?

答:
I wrote some examples for you

Example 1. (Insert into JSONB type using converting String to JSONB)

```<code>INSERT INTO cart
(
    product_id,
    quantity,
    "size",
    user_id,
    items
)
values
(
    1,
    1,
    'Small',
    1,
    '[
        {"size": "Small", "quantity": 1, "product_id": 1},
        {"size": "Small", "quantity": 1, "product_id": 1},
        {"size": "Small", "quantity": 1, "product_id": 1}
     ]'::jsonb
);
</code>```

Example 2. (Convert fields of selected table to JSONB using row_to_json)

```<code>select row_to_json(t1) as your_json from (
    select product_id, "size", quantity from cart
) t1

Result:

your_json
--------------------------------------------
{"product_id":1,"size":"Small","quantity":1}
{"product_id":1,"size":"Small","quantity":1}
{"product_id":1,"size":"Small","quantity":1}
</code>```

Example 3. (Concat all rows of type JSONB)

```<code>select jsonb_agg(row_to_json(t1)) as your_json from (
    select product_id, "size", quantity from cart
) t1

Result:

your_json
---------------------------------------------------------------------------------------------------------------------------------------------------------
[{"size": "Small", "quantity": 1, "product_id": 1}, {"size": "Small", "quantity": 1, "product_id": 1}, {"size": "Small", "quantity": 1, "product_id": 1}]
</code>```

Example 4. (Similar of row_to_json)

```<code>select
  json_build_object('product_id', product_id, 'size', size, 'quantity', quantity) as your_json
from cart;

Result:

your_json
--------------------------------------------
{"product_id":1,"size":"Small","quantity":1}
{"product_id":1,"size":"Small","quantity":1}
{"product_id":1,"size":"Small","quantity":1}
</code>```

Example 5. (Concatenate many JSONB objects using ||)

```<code>select jsonb_build_array('{"product_id":1,"size":"Small","quantity":1}'::jsonb) || jsonb_build_array('{"product_id":1,"size":"Small","quantity":1}'::jsonb) as your_json
-- or
select jsonb_build_array('{"product_id":1,"size":"Small","quantity":1}'::jsonb, '{"product_id":1,"size":"Small","quantity":1}'::jsonb) as your_json

Result:

your_json
------------------------------------------------------------------------------------------------------
[{"product_id": 1, "size": "Small", "quantity": 1}, {"product_id": 1, "size": "Small", "quantity": 1}]
</code>```

Example 6. (Similar example to your update query (using concatenating JSONB types)

```<code>update cart
set
    items = jsonb_build_array(items) || jsonb_build_array('{"product_id":1,"size":"Small","quantity":1}'::jsonb)
where id = 1

Result:

items
------------------------------------------------------------------------------------------------------
[{"product_id": 1, "size": "Small", "quantity": 1}, {"product_id": 1, "size": "Small", "quantity": 1}]
</code>```

Body:
The documentation shows that arrays can be created as either text or integer. I did not find an example for creating an object array. An example is the items column:

CREATE TABLE cart (
_id serial PRIMARY KEY,
user_id Integer UNIQUE NOT NULL,
items varchar [],
FOREIGN KEY (user_id)
REFERENCES users (_id)

Object stored in the items array have quotes around them making them strings instead of objects. A code segment creating objects in items is shown below:

update cart
set items =
array_append(items,
'{product_id: ${cartItem.productId}, size: ${cartItem.size}, quantity: ${cartItem.quantity}}')
where _id = ${cart._id}
and user_id = ${userId}
RETURNING *

I am compelled to put quotes around the object value. As a result it is stored as a string in the column with quotes around it.

cart {
  _id: 1,
  user_id: 1,
  items: [
    '{product_id: 1, size: Small, quantity: 1}',
    '{product_id: 1, size: Small, quantity: 1}',
    '{product_id: 1, size: Small, quantity: 1}'
  ]
}

Because the items in the items column are stored as string instead of objects, I cannot correctly iterate over them in my program.  For example,
items.product_id does not exist.

How do I fix this?

Body:
I wrote some examples for you

Example 1. (Insert into JSONB type using converting String to JSONB)

INSERT INTO cart
(
    product_id,
    quantity,
    "size",
    user_id,
    items
)
values
(
    1,
    1,
    'Small',
    1,
    '[
        {"size": "Small", "quantity": 1, "product_id": 1},
        {"size": "Small", "quantity": 1, "product_id": 1},
        {"size": "Small", "quantity": 1, "product_id": 1}
     ]'::jsonb
);

Example 2. (Convert fields of selected table to JSONB using row_to_json)

select row_to_json(t1) as your_json from (
    select product_id, "size", quantity from cart
) t1

Result:

your_json
--------------------------------------------
{"product_id":1,"size":"Small","quantity":1}
{"product_id":1,"size":"Small","quantity":1}
{"product_id":1,"size":"Small","quantity":1}

Example 3. (Concat all rows of type JSONB)

select jsonb_agg(row_to_json(t1)) as your_json from (
    select product_id, "size", quantity from cart
) t1

Result:

your_json
---------------------------------------------------------------------------------------------------------------------------------------------------------
[{"size": "Small", "quantity": 1, "product_id": 1}, {"size": "Small", "quantity": 1, "product_id": 1}, {"size": "Small", "quantity": 1, "product_id": 1}]

Example 4. (Similar of row_to_json)

select
  json_build_object('product_id', product_id, 'size', size, 'quantity', quantity) as your_json
from cart;

Result:

your_json
--------------------------------------------
{"product_id":1,"size":"Small","quantity":1}
{"product_id":1,"size":"Small","quantity":1}
{"product_id":1,"size":"Small","quantity":1}

Example 5. (Concatenate many JSONB objects using ||)

select jsonb_build_array('{"product_id":1,"size":"Small","quantity":1}'::jsonb) || jsonb_build_array('{"product_id":1,"size":"Small","quantity":1}'::jsonb) as your_json
-- or
select jsonb_build_array('{"product_id":1,"size":"Small","quantity":1}'::jsonb, '{"product_id":1,"size":"Small","quantity":1}'::jsonb) as your_json

Result:

your_json
------------------------------------------------------------------------------------------------------
[{"product_id": 1, "size": "Small", "quantity": 1}, {"product_id": 1, "size": "Small", "quantity": 1}]

Example 6. (Similar example to your update query (using concatenating JSONB types)

update cart
set
    items = jsonb_build_array(items) || jsonb_build_array('{"product_id":1,"size":"Small","quantity":1}'::jsonb)
where id = 1

Result:

items
------------------------------------------------------------------------------------------------------
[{"product_id": 1, "size": "Small", "quantity": 1}, {"product_id": 1, "size": "Small", "quantity": 1}]


问:
Finding Subclass ID From Superclass ID
I have a hierarchical database structure with a base table and then several child tables:

```<code>Base: {ID, Date, ...}
ChildA: {ID, Color, ...}
ChildB: {ID, Age, ...}
</code>```

Each child table has an ID that is a foreign key to Base.ID; so each child is linked to an ID that is also in Base.

I now have a situation in which I have a list of IDs and I want to figure out which child tables they actually belong to.  What is the best way to determine the child table of a given ID?

I'd like to have a function that returns a Type from an ID: Type TypeFromBaseID(int baseID)

I can think of two ways to do this, but I'm hoping there is a better way:

A) Simply add a column to Base that stores the table name of its child table

B) Have a series of if statements that does something like db.ChildA.Any(x=>x.ID == baseID)

答:
What you proposed in A) is effectively what is known in ER modeling as "discriminator" and this seems like a cleaner solution to me.

I would just urge you to reconsider using full table names here. Try saving some space (and performance) by using integers (and clearly documenting which integer value "maps" to which sub-table).

Title: Finding Subclass ID From Superclass ID

Body:
I have a hierarchical database structure with a base table and then several child tables:

Base: {ID, Date, ...}
ChildA: {ID, Color, ...}
ChildB: {ID, Age, ...}

Each child table has an ID that is a foreign key to Base.ID; so each child is linked to an ID that is also in Base.

I now have a situation in which I have a list of IDs and I want to figure out which child tables they actually belong to.  What is the best way to determine the child table of a given ID?

I'd like to have a function that returns a Type from an ID: Type TypeFromBaseID(int baseID)

I can think of two ways to do this, but I'm hoping there is a better way:

A) Simply add a column to Base that stores the table name of its child table

B) Have a series of if statements that does something like db.ChildA.Any(x=>x.ID == baseID)


问:
Custom domain for "cognito-idp.us-east-1.amazonaws.com"
I have a Cognito app client configured to use USER_PASSWORD_AUTH flow. By POSTing this request:

```<code>{
    "AuthParameters": {
        "USERNAME": "{{Username}}",
        "PASSWORD": "{{Password}}"
    },
    "AuthFlow": "USER_PASSWORD_AUTH",
    "ClientId": "{{AppClientId}}"
}
</code>```

to "cognito-idp.us-east-1.amazonaws.com", I am able to successfully authenticate and retrieve JWTs.

I would like to CNAME the URL to be something like "auth.mydomain.com", but when I do that, I get a client certificate validation error. Is there anyway to associate a valid certificate so I can CNAME the URL successfully?

答: You can configure a custom domain within your Cognito user pool.  That's what we had to do to make this work. Check out this Cognito documentation.  It discuses using the hosted UI stuff, but it should also apply to your scenario where you provide the login UI.</p>

Body:
I have a Cognito app client configured to use USER_PASSWORD_AUTH flow. By POSTing this request:

{
    "AuthParameters": {
        "USERNAME": "{{Username}}",
        "PASSWORD": "{{Password}}"
    },
    "AuthFlow": "USER_PASSWORD_AUTH",
    "ClientId": "{{AppClientId}}"
}

to "cognito-idp.us-east-1.amazonaws.com", I am able to successfully authenticate and retrieve JWTs.

I would like to CNAME the URL to be something like "auth.mydomain.com", but when I do that, I get a client certificate validation error. Is there anyway to associate a valid certificate so I can CNAME the URL successfully?


问:
Error- 'c' argument must be a color, a sequence of colors, or a sequence of numbers,
This is the code I am getting an error with. Can anyone help me with this?

plt.scatter(
    x = y_test.index,
    y = [1] * len(y_test),
    c = (accuracy_data != True).astype(float),
    marker = '.',
    cmap = cmap,
)
```

Error- 'c' argument must be a color, a sequence of colors, or a sequence of numbers

accuracy_data is a DataFrame of true/false values. (But I guess I have done something wrong in the code as the entire column is filled with False.)

I am trying to run a classification ML algorithm on the Nifty data set (Index for Indian Stock Market) for 25 years and trying to predict next day closing prices. The train and test data is in the ratio of 4:1.

答:
From the docs:

c: array-like or list of colors or color, optional

The marker colors. Possible values:

A scalar or sequence of n numbers to be mapped to colors using cmap and norm.

A 2D array in which the rows are RGB or RGBA.

A sequence of colors of length n.

A single color format string.

Note that c should not be a single numeric RGB or RGBA sequence because that is indistinguishable from an array of values to be colormapped. If you want to specify the same RGB or RGBA value for all points, use a 2D array with a single row. Otherwise, value- matching will have precedence in case of a size matching with x and y.

If you wish to specify a single color for all points prefer the color keyword argument.

Now, this is a guess. I've not used MatPlotLib or Pandas. But it looks like you're turning the entire accuracy_data into a single value and turning it into a float?

Could you try turning the dataframe into a list of 0.0 and 1.0 floats?
(float(False) == 0.0; float(True) == 1.0)

plt.scatter(
    x = y_test.index,
    y = [1] * len(y_test),
    c = [float(x) for x in accuracy_data]
    marker = '.',
    cmap = cmap,
)
```

Body:
This is the code I am getting an error with. Can anyone help me with this?

plt.scatter(
    x = y_test.index,
    y = [1] * len(y_test),
    c = (accuracy_data != True).astype(float),
    marker = '.',
    cmap = cmap,
)

Error- 'c' argument must be a color, a sequence of colors, or a sequence of numbers

accuracy_data is a DataFrame of true/false values. (But I guess I have done something wrong in the code as the entire column is filled with False.)

I am trying to run a classification ML algorithm on the Nifty data set (Index for Indian Stock Market) for 25 years and trying to predict next day closing prices. The train and test data is in the ratio of 4:1.


问:
Use Image in SwiftUI with either URL or Data without UIKit
I have downloaded an image in bytes (Data). I stored it with FileManager in the cache of the user's device. I was wondering if I could create an Image with either Data or a local URL, I am currently using UIImage but I want to support macOS.

Is there a full SwiftUI way of creating an Image with URL or Data without UIKit/UIImage?

答:
if your question is about showing and image in macos, that you already have downloaded (and is in the cachesDirectory), then try something like this, to create an image from your image in bytes: (using NSImage for macos)

```<code>struct ContentView: View {
    @State var img = NSImage()

    var body: some View {
        Image(nsImage: img)
            .onAppear {
                do {
                    // local file
                    let url = try FileManager.default
                        .url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
                        .appendingPathComponent("kat")  // <--- your file name here
                        .appendingPathExtension("png")

                    print("----> url: \(url)")

                    // even from the net
//                    let url = URL(string: "https://upload.wikimedia.org/wikipedia/commons/e/ef/Red-billed_gull%2C_Red_Zone%2C_Christchurch%2C_New_Zealand.jpg")!

                    if let nsimg = NSImage(contentsOf: url) { img = nsimg }
                } catch {
                    print("\(error)")
                }
            }
    }

}
</code>```

Body:
if your question is about showing and image in macos, that you already have downloaded (and is in the cachesDirectory), then try something like this, to create an image from your image in bytes: (using NSImage for macos)

struct ContentView: View {
    @State var img = NSImage()

    var body: some View {
        Image(nsImage: img)
            .onAppear {
                do {
                    // local file
                    let url = try FileManager.default
                        .url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
                        .appendingPathComponent("kat")  // <--- your file name here
                        .appendingPathExtension("png")

                    print("----> url: \(url)")

                    // even from the net
//                    let url = URL(string: "https://upload.wikimedia.org/wikipedia/commons/e/ef/Red-billed_gull%2C_Red_Zone%2C_Christchurch%2C_New_Zealand.jpg")!

                    if let nsimg = NSImage(contentsOf: url) { img = nsimg }
                } catch {
                    print("\(error)")
                }
            }
    }

}


问:
Python - Generate 2nd Mouse Independent of Main Mouse
I have a code that uses pyautogui to move the mouse around on my 2nd monitor. However, this disables me from using the PC myself since the mouse is occupied.

Is it possible to create a replica mouse pointer just for the program, so that I can simultaneously use the computer with my own mouse?

答:
From what I read in the documentation, it's not possible to have a second mouse working from your code while you are using your computer, because it's programmatically to control the mouse itself.

An that's why they use Fail-Safes as a safety feature.

As they say:

When a PyAutoGUI function is called, if the mouse is in any of the
four corners of the primary monitor, they will raise a
pyautogui.FailSafeException.

You can read more about from PyautoGUI documentation.


问:
Can'r run curl in nodejs with execFile
As node exec is deprecated, I am trying to migrate my nodejs application to execFile, but I am getting problems with a curl call.

this was working with exec:

```<code>const pab_state = `/usr/bin/curl -d '{"jsonrpc": "2.0", "id": 1, "method": "core.playback.get_state"}' -H 'Content-Type: application/json' http://192.168.1.59:6680/mopidy/rpc`
child = exec(pab_state, (error, stdout, stderr) => {
</code>```

Trying to migrate to execFile I am getting issues with escaping quotes:

```<code>const pab_args = ['-d \'{"jsonrpc": "2.0", "id": 1, "method": "core.playback.get_current_tl_track"}\'',' -H \'Content-Type: application/json\'',' http://192.168.1.59:6680/mopidy/rpc'];

child = execFile("/usr/bin/curl",pab_args, (error, stdout, stderr) => {
</code>```

This is the error I am getting:

```<code>{"killed":false,"code":3,"signal":null,"cmd":"/usr/bin/curl -d '{\"jsonrpc\": \"2.0\", \"id\": 1, \"method\": \"core.playback.get_current_tl_track\"}'  -H 'Content-Type: application/json'  http://192.168.1.59:6680/mopidy/rpc"}
</code>```

答:
I have a similar issue with OP. The cUrl works on terminal but on NodeJS I am getting HTTP 405. I can see what string Exec generates out of this input. Here is the spawnargs field in ExecFile log.

```<code>spawnargs:
       [ '/bin/bash',
         '-c',
         '/usr/bin/curl -v -k -H "Content-Type: application/zip" --data-binary "@/tmp/<filename>.zip" http://<username>:<password>@<host>:8080/path/to/upload?name=<filename>.zip' ],
</code>```

When I run the command above, it just works. I've tried your method but, couldn't see anything different. I've tried lot of things, even checked file permissions but no clue what's happening. I'm suspecting the string formatting in my url and args but not sure. Any idea?

```<code>let url = `http://<username>:<password>@<host>:8080/path/to/upload?name=${filename}.zip`
let resp = await execFile(`/usr/bin/curl`,
           [
           `-v -k -H \"Content-Type: application/zip\"`,
           `--data-binary \"@/tmp/${filename}.zip\"`,
           `${url}`
           ],
           {shell:'/bin/bash'},
           async function (error, stdout, stderr) {
           if (error) {
                console.log(`error: ${error.message}`);
                resolve(error);
           }
           if (stderr) {
                console.log(`stderr: ${stderr}`);
                resolve(stderr);
           }
   });
</code>```

Title: Can'r run curl in nodejs with execFile

Body:
As node exec is deprecated, I am trying to migrate my nodejs application to execFile, but I am getting problems with a curl call.

this was working with exec:

const pab_state = `/usr/bin/curl -d '{"jsonrpc": "2.0", "id": 1, "method": "core.playback.get_state"}' -H 'Content-Type: application/json' http://192.168.1.59:6680/mopidy/rpc`
child = exec(pab_state, (error, stdout, stderr) => {

Trying to migrate to execFile I am getting issues with escaping quotes:

const pab_args = ['-d \'{"jsonrpc": "2.0", "id": 1, "method": "core.playback.get_current_tl_track"}\'',' -H \'Content-Type: application/json\'',' http://192.168.1.59:6680/mopidy/rpc'];

child = execFile("/usr/bin/curl",pab_args, (error, stdout, stderr) => {

This is the error I am getting:

{"killed":false,"code":3,"signal":null,"cmd":"/usr/bin/curl -d '{\"jsonrpc\": \"2.0\", \"id\": 1, \"method\": \"core.playback.get_current_tl_track\"}'  -H 'Content-Type: application/json'  http://192.168.1.59:6680/mopidy/rpc"}

Body:
I have a similar issue with OP. The cUrl works on terminal but on NodeJS I am getting HTTP 405. I can see what string Exec generates out of this input. Here is the spawnargs field in ExecFile log.

spawnargs:
       [ '/bin/bash',
         '-c',
         '/usr/bin/curl -v -k -H "Content-Type: application/zip" --data-binary "@/tmp/<filename>.zip" http://<username>:<password>@<host>:8080/path/to/upload?name=<filename>.zip' ],

When I run the command above, it just works. I've tried your method but, couldn't see anything different. I've tried lot of things, even checked file permissions but no clue what's happening. I'm suspecting the string formatting in my url and args but not sure. Any idea?

let url = `http://<username>:<password>@<host>:8080/path/to/upload?name=${filename}.zip`
let resp = await execFile(`/usr/bin/curl`,
           [
           `-v -k -H \"Content-Type: application/zip\"`,
           `--data-binary \"@/tmp/${filename}.zip\"`,
           `${url}`
           ],
           {shell:'/bin/bash'},
           async function (error, stdout, stderr) {
           if (error) {
                console.log(`error: ${error.message}`);
                resolve(error);
           }
           if (stderr) {
                console.log(`stderr: ${stderr}`);
                resolve(stderr);
           }
   });


问:
Initializing array on stack with copy constructor
I want to have a stack-allocated array initialized by a copy constructor.

I only see methods allocating memory on the heap, or using std::array.

With std::array, it would look like the following:

```<code>class A
{
    std::array<int, 5> my_array;    // I would like to have int my_array[5]; instead of the std::array
    int size;
public:
    A(const A& p)
        : my_array{ p.my_array }, size(p.size) {}
}
</code>```

How can I implement this without std::array<int,5> but with a plain array (int my_array[5];)? I have added this in the comment in the code.

At the moment, the array contains integers. If this would contain, let's say a class B, which contains also a pointer:

```<code>class B
{
   int* my_ptr;
}
</code>```

Does std::array handle this correctly and perform a deep copy?

答:
Arrays cannot be copy-initialised in C++. You can either:

Assign each member in a loop i.e. std::copy in the constructor body.

Or wrap the array inside a class, and use the generated copy constructor. There is a template for such wrapper class in the standard library. It's the std::array that you already know of.

Of course, your class itself is a class that is a wrapper for the array, so you could simply not have user defined copy constructor, and instead use the implicitly generated one:

```<code>struct A
{
    int my_array[5];
    int size;
};
</code>```

If this would contain, let's say a class B which contains also a pointer ... does the std::array handle this correctly

Yes.

... and performs a deep copy?

No. Copying a std::array copies each element and nothing more. Copying a pointer is a shallow copy.

Body:
I want to have a stack-allocated array initialized by a copy constructor.

I only see methods allocating memory on the heap, or using std::array.

With std::array, it would look like the following:

class A
{
    std::array<int, 5> my_array;    // I would like to have int my_array[5]; instead of the std::array
    int size;
public:
    A(const A& p)
        : my_array{ p.my_array }, size(p.size) {}
}

How can I implement this without std::array<int,5> but with a plain array (int my_array[5];)? I have added this in the comment in the code.

At the moment, the array contains integers. If this would contain, let's say a class B, which contains also a pointer:

class B
{
   int* my_ptr;
}

Does std::array handle this correctly and perform a deep copy?

Body:
Arrays cannot be copy-initialised in C++. You can either:

Assign each member in a loop i.e. std::copy in the constructor body.

Or wrap the array inside a class, and use the generated copy constructor. There is a template for such wrapper class in the standard library. It's the std::array that you already know of.

Of course, your class itself is a class that is a wrapper for the array, so you could simply not have user defined copy constructor, and instead use the implicitly generated one:

struct A
{
    int my_array[5];
    int size;
};

If this would contain, let's say a class B which contains also a pointer ... does the std::array handle this correctly

Yes.

... and performs a deep copy?

No. Copying a std::array copies each element and nothing more. Copying a pointer is a shallow copy.


问:
How to open keyboard automatically in React Native?
I have a screen in my React Native application in which I have few text fields.

I was wondering if there is any way in which on screen load my keyword opens automatically  and focuses on my first text input field?

I was searching for something like stateAlwaysVisible in android.

答:
This is how it looks in code, using the setTimeout() Hook</p>
```<code>import { StyleSheet, Text, View, TextInput } from "react-native";
import React from "react";

const HomeScreen = () => {
  const inputRef = React.useRef();

  setTimeout(() => inputRef.current.focus(), 100);
  return (
    <View style={{ paddingVertical: 20 }}>
      <Text>circle</Text>
      <TextInput ref={inputRef} />
    </View>
  );
};

export default HomeScreen;

const styles = StyleSheet.create({});
</code>```

Body:
This is how it looks in code, using the setTimeout() Hook

import { StyleSheet, Text, View, TextInput } from "react-native";
import React from "react";

const HomeScreen = () => {
  const inputRef = React.useRef();

  setTimeout(() => inputRef.current.focus(), 100);
  return (
    <View style={{ paddingVertical: 20 }}>
      <Text>circle</Text>
      <TextInput ref={inputRef} />
    </View>
  );
};

export default HomeScreen;

const styles = StyleSheet.create({});


问:
Get the last Wednesday from a given date
If a datetime field is passed, how do I determine when the last Wednesday was and set it to 10AM on that day?

Declare DateTime @datetime

For example:

if I pass in @datetime = '2022-Feb-7 5:00:00' then I should get 2022-Feb-2 10:00:00

if I pass in @datetime = '2022-Feb-10 16:00:00' then I should get 2022-Feb-9 10:00:00

I have an edge case here:

if the @datetime is Wednesday and the time is less than 10AM then it should set it to last Wednesday and if the time is greater than 10AM then it should set it current Wednesday 10AM.

For example:

if I pass in @datetime='2022-Feb-9 5:00:000' then I should get 2022-Feb-2 10:00:00

if I pass in @datetime = '2022-Feb-9 16:00:00' then I should get 2022-Feb-9 10:00:00

答:
You can calculate the previous Wednesday 10 AM like this:

```<code>DECLARE @DateTime DATETIME = GETDATE();
DECLARE @LastWednesday DATETIME;

SET @LastWednesday = CAST(DATEADD(day, -(3+@@DATEFIRST+DATEPART(weekday,@DateTime-'10:00'))%7,
CAST(@DateTime-'10:00' AS DATE)) AS DATETIME)+'10:00';

SELECT @DateTime, @LastWednesday;
</code>```

Demo on db<>fiddle here

How it works

The 10 hours is first subtracted from the @DateTime to get the cutoff time effect on a Wednesday.

@DateTime-'10:00'
So after 10 AM on a Wednesday it calculates current Wednesday.

Now, to calculate the first day of the week, you could subtract the weekday+1 from the date.

But the first day of the week depends on the DATEFIRST setting.  If it's 1 then Monday, if 7 then it's Sunday.
So the variable @@datefirst is used to normalize the calculation.  So that the calculation doesn't depend on the DATEFIRST setting.

This will get the previous Saturday:

@datetime-(0+@@datefirst+DATEPART(weekday,@datetime))%7

So this gets the previous Wednesday:

@datetime-(3+@@datefirst+DATEPART(weekday,@datetime))%7

The modulus 7 (%7) makes sure that it can't subtract more than 6.

```<code>--
-- Test over date range
--
DECLARE @StartDatetime SMALLDATETIME;
DECLARE @EndDatetime SMALLDATETIME;
SET @StartDateTime = DATEADD(month, -1, DATEADD(day, 1, EOMONTH(GETDATE())));
SET @EndDatetime = EOMONTH(@StartDatetime);

with cte as (
  select @StartDatetime+'11:00' as [Dt]
  union all
  select dateadd(day, 1, [Dt]) from cte
  where [Dt] < @EndDatetime
)
select top 16
  [Dt]
, datepart(weekday, [Dt]) AS weekday
, datename(weekday, [Dt]) AS weekdayname
, -(3+@@DATEFIRST+DATEPART(weekday,[Dt]-'10:00'))%7 AS daydiff
, prevWed = CAST(DATEADD(day,-(3+@@DATEFIRST+DATEPART(weekday,[Dt]-'10:00'))%7,CAST([Dt]-'10:00' AS DATE)) AS DATETIME)+'10:00'
, @@DATEFIRST AS df
from cte;
</code>```

Dt
weekday
weekdayname
daydiff
prevWed
df

2022-02-01 11:00
3
Tuesday
-6
2022-01-26 10:00:00.000
7

2022-02-02 11:00
4
Wednesday
0
2022-02-02 10:00:00.000
7

2022-02-03 11:00
5
Thursday
-1
2022-02-02 10:00:00.000
7

2022-02-04 11:00
6
Friday
-2
2022-02-02 10:00:00.000
7

2022-02-05 11:00
7
Saturday
-3
2022-02-02 10:00:00.000
7

2022-02-06 11:00
1
Sunday
-4
2022-02-02 10:00:00.000
7

2022-02-07 11:00
2
Monday
-5
2022-02-02 10:00:00.000
7

2022-02-08 11:00
3
Tuesday
-6
2022-02-02 10:00:00.000
7

2022-02-09 11:00
4
Wednesday
0
2022-02-09 10:00:00.000
7

2022-02-10 11:00
5
Thursday
-1
2022-02-09 10:00:00.000
7

2022-02-11 11:00
6
Friday
-2
2022-02-09 10:00:00.000
7

2022-02-12 11:00
7
Saturday
-3
2022-02-09 10:00:00.000
7

2022-02-13 11:00
1
Sunday
-4
2022-02-09 10:00:00.000
7

2022-02-14 11:00
2
Monday
-5
2022-02-09 10:00:00.000
7

2022-02-15 11:00
3
Tuesday
-6
2022-02-09 10:00:00.000
7

2022-02-16 11:00
4
Wednesday
0
2022-02-16 10:00:00.000
7

Body:
You can calculate the previous Wednesday 10 AM like this:

DECLARE @DateTime DATETIME = GETDATE();
DECLARE @LastWednesday DATETIME;

SET @LastWednesday = CAST(DATEADD(day, -(3+@@DATEFIRST+DATEPART(weekday,@DateTime-'10:00'))%7,
CAST(@DateTime-'10:00' AS DATE)) AS DATETIME)+'10:00';

SELECT @DateTime, @LastWednesday;

Demo on db<>fiddle here

How it works

The 10 hours is first subtracted from the @DateTime to get the cutoff time effect on a Wednesday.

@DateTime-'10:00'
So after 10 AM on a Wednesday it calculates current Wednesday.

Now, to calculate the first day of the week, you could subtract the weekday+1 from the date.

But the first day of the week depends on the DATEFIRST setting.  If it's 1 then Monday, if 7 then it's Sunday.
So the variable @@datefirst is used to normalize the calculation.  So that the calculation doesn't depend on the DATEFIRST setting.

This will get the previous Saturday:

@datetime-(0+@@datefirst+DATEPART(weekday,@datetime))%7

So this gets the previous Wednesday:

@datetime-(3+@@datefirst+DATEPART(weekday,@datetime))%7

The modulus 7 (%7) makes sure that it can't subtract more than 6.

--
-- Test over date range
--
DECLARE @StartDatetime SMALLDATETIME;
DECLARE @EndDatetime SMALLDATETIME;
SET @StartDateTime = DATEADD(month, -1, DATEADD(day, 1, EOMONTH(GETDATE())));
SET @EndDatetime = EOMONTH(@StartDatetime);

with cte as (
  select @StartDatetime+'11:00' as [Dt]
  union all
  select dateadd(day, 1, [Dt]) from cte
  where [Dt] < @EndDatetime
)
select top 16
  [Dt]
, datepart(weekday, [Dt]) AS weekday
, datename(weekday, [Dt]) AS weekdayname
, -(3+@@DATEFIRST+DATEPART(weekday,[Dt]-'10:00'))%7 AS daydiff
, prevWed = CAST(DATEADD(day,-(3+@@DATEFIRST+DATEPART(weekday,[Dt]-'10:00'))%7,CAST([Dt]-'10:00' AS DATE)) AS DATETIME)+'10:00'
, @@DATEFIRST AS df
from cte;

Dt
weekday
weekdayname
daydiff
prevWed
df

2022-02-01 11:00
3
Tuesday
-6
2022-01-26 10:00:00.000
7

2022-02-02 11:00
4
Wednesday
0
2022-02-02 10:00:00.000
7

2022-02-03 11:00
5
Thursday
-1
2022-02-02 10:00:00.000
7

2022-02-04 11:00
6
Friday
-2
2022-02-02 10:00:00.000
7

2022-02-05 11:00
7
Saturday
-3
2022-02-02 10:00:00.000
7

2022-02-06 11:00
1
Sunday
-4
2022-02-02 10:00:00.000
7

2022-02-07 11:00
2
Monday
-5
2022-02-02 10:00:00.000
7

2022-02-08 11:00
3
Tuesday
-6
2022-02-02 10:00:00.000
7

2022-02-09 11:00
4
Wednesday
0
2022-02-09 10:00:00.000
7

2022-02-10 11:00
5
Thursday
-1
2022-02-09 10:00:00.000
7

2022-02-11 11:00
6
Friday
-2
2022-02-09 10:00:00.000
7

2022-02-12 11:00
7
Saturday
-3
2022-02-09 10:00:00.000
7

2022-02-13 11:00
1
Sunday
-4
2022-02-09 10:00:00.000
7

2022-02-14 11:00
2
Monday
-5
2022-02-09 10:00:00.000
7

2022-02-15 11:00
3
Tuesday
-6
2022-02-09 10:00:00.000
7

2022-02-16 11:00
4
Wednesday
0
2022-02-16 10:00:00.000
7