问:
Initialize LiveData later in ViewModel
Having recently opted to use LiveData, I encounter a problem when initializing for a variable.
I have 2 Activities (I don't use Navigation but that's not the point) :

One is a list with items fetch by API

The other is a Detail Activity for the selected item in the previous list

The problem is that I need to be able to consult the Detail Activity in creation mode, i.e. in my ViewModel the object must not be retrieved via Retrofit but created via a new instantiation.

This is how it is done for now :

Detail Activity :

```<code>override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.details)

        val isNew = intent.extras?.getBoolean("new")
        if (isNew) {
            // Trigger lazy property
            viewModel.value
        } else {
            viewModel.getDetails()
        }

        presenter.value.observe(this, Observer { value ->
            value?.let {
                displayDetails(it)
            }
        })
    }
</code>```

ViewModel

```<code>class DetailsPresenter(private val repository: WorkOrderRepository)
    : ViewModel(), LifecycleObserver {

    val value: MutableLiveData<Details> by lazy { MutableLiveData(Details("")) }

    fun getDetails() {
        RetrofitClient.getDetails()
        .onSuccess {
            this.value.value = it
        }

    }

}
</code>```

The problem with this method is that my displayDetails() method is called twice.
One for lazy initialization and the other in case I'm looking at an existing item.

How can i initialize LiveData later in code ?

答:
Basically lazy won't create the second instance, ViewModel reference won't recreate.
So we can use the Val value: LiveData = MutableLiveData() instead of lazy.

You can add getDetails() method in init block itself to avoid the second call.

Title: Initialize LiveData later in ViewModel

Body:
Having recently opted to use LiveData, I encounter a problem when initializing for a variable.
I have 2 Activities (I don't use Navigation but that's not the point) :

One is a list with items fetch by API

The other is a Detail Activity for the selected item in the previous list

The problem is that I need to be able to consult the Detail Activity in creation mode, i.e. in my ViewModel the object must not be retrieved via Retrofit but created via a new instantiation.

This is how it is done for now :

Detail Activity :

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.details)

        val isNew = intent.extras?.getBoolean("new")
        if (isNew) {
            // Trigger lazy property
            viewModel.value
        } else {
            viewModel.getDetails()
        }

        presenter.value.observe(this, Observer { value ->
            value?.let {
                displayDetails(it)
            }
        })
    }

ViewModel

class DetailsPresenter(private val repository: WorkOrderRepository)
    : ViewModel(), LifecycleObserver {

    val value: MutableLiveData by lazy { MutableLiveData(Details("")) }

    fun getDetails() {
        RetrofitClient.getDetails()
        .onSuccess {
            this.value.value = it
        }

    }

}

The problem with this method is that my displayDetails() method is called twice.
One for lazy initialization and the other in case I'm looking at an existing item.

How can i initialize LiveData later in code ?

Body:
Basically lazy won't create the second instance, ViewModel reference won't recreate.
So we can use the Val value: LiveData<Details> = MutableLiveData() instead of lazy.

You can add getDetails() method in init block itself to avoid the second call.


来源: stackexchange

问:
Tkinter: Can you see all bindings of a widget?
In my application I want to toggle between two states, and in each of the states I want -> don't want various keys bound.

Right now what I've done is that in my class I've created an attribute self.bindings = [] and then I have a method to create bindings:

```<code>def _create_bindings(self):
    self.bind("<Button-1>", self._canvas_on_click)
    self.bindings.append("<Button-1>")
    self.bind("<Double-Button-1>", self._canvas_on_2click)
    self.bindings.append("<Double-Button-1>")
    self.bind("<<arrow>>", self._canvas_on_arrows)
    self.bindings.append("<<arrow>>")
    self.bind("<space>", lambda event: self._toggle_selected())
    self.bindings.append("<space>")
    self.bind("<Key>", self._canvas_on_key_press)
    self.bindings.append("<Key>")
    self.bind("<BackSpace>", lambda event: self._empty_cell())
    self.bindings.append("<BackSpace>")
    self.bind("<Escape>", self._esc)
    self.bindings.append("<Escape>")
</code>```

and then to remove them:

```<code>def _remove_bindings(self):
    for b in self.bindings:
        self.unbind(b)
</code>```

It's not terrible but it does lead to some duplication (see create function: create binding + add to list).

I could create a wrapper to combine these two steps, but regardless I still have an extra attribute to manage.

Is there a function which I can call which would provide me the same information as self.bindings above?

答:
There is no need to remove the bindings. </p>

<p>Altering the 'state' attribute of the e.g. Canvas, Button disables any bindings. </p>

ContentLicense: CC BY-SA 4.0

Body:
In my application I want to toggle between two states, and in each of the states I want -> don't want various keys bound.

Right now what I've done is that in my class I've created an attribute self.bindings = [] and then I have a method to create bindings:

def _create_bindings(self):
    self.bind("<Button-1>", self._canvas_on_click)
    self.bindings.append("<Button-1>")
    self.bind("<Double-Button-1>", self._canvas_on_2click)
    self.bindings.append("<Double-Button-1>")
    self.bind("<<arrow>>", self._canvas_on_arrows)
    self.bindings.append("<<arrow>>")
    self.bind("<space>", lambda event: self._toggle_selected())
    self.bindings.append("<space>")
    self.bind("<Key>", self._canvas_on_key_press)
    self.bindings.append("<Key>")
    self.bind("<BackSpace>", lambda event: self._empty_cell())
    self.bindings.append("<BackSpace>")
    self.bind("<Escape>", self._esc)
    self.bindings.append("<Escape>")

and then to remove them:

def _remove_bindings(self):
    for b in self.bindings:
        self.unbind(b)

It's not terrible but it does lead to some duplication (see create function: create binding + add to list).

I could create a wrapper to combine these two steps, but regardless I still have an extra attribute to manage.

Is there a function which I can call which would provide me the same information as self.bindings above?

Body:
There is no need to remove the bindings.

Altering the 'state' attribute of the e.g. Canvas, Button disables any bindings.


问:
How to pass multiple condition in a firebase query in Flutter
I want to add another conditon to my firebase query. I want to say userID = xx and status = yy.
Is there any way to do that in same query?</p>

```<code>static Future<List<Ticket>> ticketDataStream(userID) async {
    final databaseReference = Firestore.instance;

    List<Ticket> tickets = List<Ticket>();

    await for (var snapshot in databaseReference
        .collection('bets')
        .where('userID', isEqualTo: userID)
        .snapshots()) {
      for (var document in snapshot.documents) {
        Ticket ticket = Ticket();

        ticket.status = document.data['status'];
        ticket.numOfMatches = document.data['numOfMatches'];
        ticket.returnAmount = document.data['return'];
        ticket.totalOdds = document.data['odds'];
        ticket.dateTime = document.data['dateTime'].toDate();
        ticket.betAmount = document.data['betAmount'];
        ticket.ticketID = document.documentID;

        tickets.add(ticket);
      }

      return tickets;
    }
    return null; //TODO: be sure that is not a problem
  }
}
</code>```

答:
try to use multiple .where like</p>

```<code>databaseReference
    .collection('bets')
    .where('userID', isEqualTo: userID)
    .where('status', isEqualTo:status)
</code>```

Body:
I want to add another conditon to my firebase query. I want to say userID = xx and status = yy.
Is there any way to do that in same query?

static Future<List<Ticket>> ticketDataStream(userID) async {
    final databaseReference = Firestore.instance;

    List<Ticket> tickets = List<Ticket>();

    await for (var snapshot in databaseReference
        .collection('bets')
        .where('userID', isEqualTo: userID)
        .snapshots()) {
      for (var document in snapshot.documents) {
        Ticket ticket = Ticket();

        ticket.status = document.data['status'];
        ticket.numOfMatches = document.data['numOfMatches'];
        ticket.returnAmount = document.data['return'];
        ticket.totalOdds = document.data['odds'];
        ticket.dateTime = document.data['dateTime'].toDate();
        ticket.betAmount = document.data['betAmount'];
        ticket.ticketID = document.documentID;

        tickets.add(ticket);
      }

      return tickets;
    }
    return null; //TODO: be sure that is not a problem
  }
}

Body:
try to use multiple .where like

databaseReference
    .collection('bets')
    .where('userID', isEqualTo: userID)
    .where('status', isEqualTo:status)


问:
Android openFileOutput - no permission to create storage
I have a problem with permissions in my application. It looks like my app does not have permissions to create files on storage.

```<code>String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos;

try
{
   fos = getApplicationContext()
           .openFileOutput(FILENAME, Context.MODE_PRIVATE);
   fos.write(string.getBytes());
   fos.close();
}
catch (Exception e)
{
   e.printStackTrace();
}
</code>```

In my main class onCreate handler, and I always get:

```<code>06-02 13:23:52.996: WARN/ApplicationContext(6278): Unable to create files directory
06-02 13:23:54.203: WARN/System.err(6278): java.lang.NullPointerException
06-02 13:23:54.226: WARN/System.err(6278):     at android.app.ContextImpl.openFileOutput(ContextImpl.java:464)
06-02 13:23:54.234: WARN/ActivityManager(2470): Activity idle timeout for HistoryRecord{485ebe10 com.servision.svclient/.Main}
06-02 13:23:54.257: WARN/System.err(6278):     at android.content.ContextWrapper.openFileOutput(ContextWrapper.java:158)
06-02 13:23:54.273: WARN/System.err(6278):     at com.servision.svclient.Main.onCreate(Main.java:59)
06-02 13:23:54.277: WARN/System.err(6278):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
06-02 13:23:54.285: WARN/System.err(6278):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
06-02 13:23:54.293: WARN/System.err(6278):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
06-02 13:23:54.296: WARN/System.err(6278):     at android.app.ActivityThread.access$2300(ActivityThread.java:125)
06-02 13:23:54.304: WARN/System.err(6278):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
06-02 13:23:54.312: WARN/System.err(6278):     at android.os.Handler.dispatchMessage(Handler.java:99)
06-02 13:23:54.320: WARN/System.err(6278):     at android.os.Looper.loop(Looper.java:123)
06-02 13:23:54.324: WARN/System.err(6278):     at android.app.ActivityThread.main(ActivityThread.java:4627)
06-02 13:23:54.332: WARN/System.err(6278):     at java.lang.reflect.Method.invokeNative(Native Method)
06-02 13:23:54.336: WARN/System.err(6278):     at java.lang.reflect.Method.invoke(Method.java:521)
06-02 13:23:54.343: WARN/System.err(6278):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
06-02 13:23:54.355: WARN/System.err(6278):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
06-02 13:23:54.359: WARN/System.err(6278):     at dalvik.system.NativeStart.main(Native Method)
</code>```

in response.

I believe its something very simple in definitions of my project. But I can't figure out what it is.

If I create another project and put same code in to it, it works fine.

my manifest file looks like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.servision.svclient"
      android:versionCode="1"
      android:versionName="1.0">
  <uses-permission android:name="android.permission.INTERNET" />
  <uses-permission android:name="android.permission.WAKE_LOCK" />
  <uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />

  <application android:icon="@drawable/main" android:label="@string/app_name" android:debuggable="true">
    <activity android:name=".Main" android:label="@string/app_name" android:theme="@android:style/Theme.NoTitleBar">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
    </activity>
    <activity android:name=".StreamActivity" android:label="@string/app_name"/>
    <activity android:name=".MainActivity"/>
    <activity android:name=".GatewayList"/>
    <activity android:name=".StatisticsActivity"/>
    <activity android:name=".SettingsActivity"/>
    <activity android:name=".MapsActivity"/>
    <activity android:name=".AboutActivity"/>
  </application>
  <uses-sdk android:minSdkVersion="8" />

</manifest>
</code>```

答: Is the file you are accessing definitely on the internal storage? You haven't declared the WRITE_EXTERNAL_STORAGE permission. You would need this to write to the sdcard</p>

ContentLicense: CC BY-SA 3.0

Body:
I have a problem with permissions in my application. It looks like my app does not have permissions to create files on storage.

String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos;

try
{
   fos = getApplicationContext()
           .openFileOutput(FILENAME, Context.MODE_PRIVATE);
   fos.write(string.getBytes());
   fos.close();
}
catch (Exception e)
{
   e.printStackTrace();
}

In my main class onCreate handler, and I always get:

06-02 13:23:52.996: WARN/ApplicationContext(6278): Unable to create files directory
06-02 13:23:54.203: WARN/System.err(6278): java.lang.NullPointerException
06-02 13:23:54.226: WARN/System.err(6278):     at android.app.ContextImpl.openFileOutput(ContextImpl.java:464)
06-02 13:23:54.234: WARN/ActivityManager(2470): Activity idle timeout for HistoryRecord{485ebe10 com.servision.svclient/.Main}
06-02 13:23:54.257: WARN/System.err(6278):     at android.content.ContextWrapper.openFileOutput(ContextWrapper.java:158)
06-02 13:23:54.273: WARN/System.err(6278):     at com.servision.svclient.Main.onCreate(Main.java:59)
06-02 13:23:54.277: WARN/System.err(6278):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
06-02 13:23:54.285: WARN/System.err(6278):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
06-02 13:23:54.293: WARN/System.err(6278):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
06-02 13:23:54.296: WARN/System.err(6278):     at android.app.ActivityThread.access$2300(ActivityThread.java:125)
06-02 13:23:54.304: WARN/System.err(6278):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
06-02 13:23:54.312: WARN/System.err(6278):     at android.os.Handler.dispatchMessage(Handler.java:99)
06-02 13:23:54.320: WARN/System.err(6278):     at android.os.Looper.loop(Looper.java:123)
06-02 13:23:54.324: WARN/System.err(6278):     at android.app.ActivityThread.main(ActivityThread.java:4627)
06-02 13:23:54.332: WARN/System.err(6278):     at java.lang.reflect.Method.invokeNative(Native Method)
06-02 13:23:54.336: WARN/System.err(6278):     at java.lang.reflect.Method.invoke(Method.java:521)
06-02 13:23:54.343: WARN/System.err(6278):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
06-02 13:23:54.355: WARN/System.err(6278):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
06-02 13:23:54.359: WARN/System.err(6278):     at dalvik.system.NativeStart.main(Native Method)

in response.

I believe its something very simple in definitions of my project. But I can't figure out what it is.

If I create another project and put same code in to it, it works fine.

my manifest file looks like this:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.servision.svclient"
      android:versionCode="1"
      android:versionName="1.0">
  <uses-permission android:name="android.permission.INTERNET" />
  <uses-permission android:name="android.permission.WAKE_LOCK" />
  <uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />

  <application android:icon="@drawable/main" android:label="@string/app_name" android:debuggable="true">
    <activity android:name=".Main" android:label="@string/app_name" android:theme="@android:style/Theme.NoTitleBar">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
    </activity>
    <activity android:name=".StreamActivity" android:label="@string/app_name"/>
    <activity android:name=".MainActivity"/>
    <activity android:name=".GatewayList"/>
    <activity android:name=".StatisticsActivity"/>
    <activity android:name=".SettingsActivity"/>
    <activity android:name=".MapsActivity"/>
    <activity android:name=".AboutActivity"/>
  </application>
  <uses-sdk android:minSdkVersion="8" />

</manifest>


问:
Access Button inside DataTemplate in WPF ItemsControl
I want to access the Button inside MouseDown event, I have the following:

XAML:

```<code><ItemsControlx:Name="icName" MouseDown="icItems_MouseDown" >
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Button x:Name="btnName" Tag="{Binding ItemName}"</Button>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
 </ItemsControl>
</code>```

C#:

```<code>private void icName_MouseDown(object sender, MouseButtonEventArgs e)
    {
       ???
    }
</code>```

How can I access to the button from ItemsControl MouseDown event

ex: MessageBox.Show(ItemName);

Thanks

答:
if you don't need access to the button, but only need the item name from the bound item, then personally I would add the handler inside the datatemplate, I'm using a grid below.

```<code><ItemsControl x:Name="icName" >
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Grid MouseDown="icItems_MouseDown" />
                    <Button x:Name="btnName" Tag="{Binding ItemName}"</Button>
                </Grid>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
 </ItemsControl>
</code>```

Then you can access your datacontext from within the handler.

```<code>    private void icName_MouseDown(object sender, MouseButtonEventArgs e)
    {
       var item = (YourItemType)((FrameworkElement)sender).DataContext;
       var itemName = item.ItemName;
    }
</code>```

You also don't need the tag at all

Body:
I want to access the Button inside MouseDown event, I have the following:

XAML:

<ItemsControlx:Name="icName" MouseDown="icItems_MouseDown" >
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Button x:Name="btnName" Tag="{Binding ItemName}"</Button>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
 </ItemsControl>

C#:

private void icName_MouseDown(object sender, MouseButtonEventArgs e)
    {
       ???
    }

How can I access to the button from ItemsControl MouseDown event

ex: MessageBox.Show(ItemName);

Thanks

Body:
if you don't need access to the button, but only need the item name from the bound item, then personally I would add the handler inside the datatemplate, I'm using a grid below.

<ItemsControl x:Name="icName" >
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Grid MouseDown="icItems_MouseDown" />
                    <Button x:Name="btnName" Tag="{Binding ItemName}"</Button>
                </Grid>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
 </ItemsControl>

Then you can access your datacontext from within the handler.

    private void icName_MouseDown(object sender, MouseButtonEventArgs e)
    {
       var item = (YourItemType)((FrameworkElement)sender).DataContext;
       var itemName = item.ItemName;
    }

You also don't need the tag at all


问:
How to properly apply a color gradient to an arc?
I am working on building a visual that looks something like this: .

So far I've managed to create this:

The idea is to map a value to an angle so that I know where to point the arrow and then I will color the arrow the same color as the point on the arc that its pointing to.

I essentially have two questions:

First what can I do in order to make the colors line up better. I've used a linear gradient like so:

```<code> let defs = this.gaugeEl
                .append("defs")
                .classed("definitions",true);
        let gradient = defs
            .append("linearGradient")
            .classed("linearGradient",true);

        gradient
            .attr({
                id: 'gradient',
                x1: '0%',
                y1: '0%',
                x2: '100%',
                y2: '100%',
                spreadMethod: "pad"
            });

        gradient
            .append("stop")
            .classed('start',true)
            .attr({
                offset: '0%',
                'stop-color': 'lawngreen',
                'stop-opacity': 1
            });

        gradient.append("stop")
            .classed('end',true)
            .attr({
                offset: '100%',
                'stop-color': 'red',
                'stop-opacity': 1
            });
</code>```

The effect is not what I was hoping for, what can be done?

The next question about how the gradient works, I need to be able to associate an angle with a color so that I can color the arrow and the tick marks properly and in my current setup I don't know how to do that. Is it even possible?

答:
There is an easier way to do this now with a css property called conic-gradient

https://css-tricks.com/snippets/css/css-conic-gradient/

It sets the color according to the angle, given a center point. Maybe you could get the angle to the point with a click event, calculate the angel from the center, and set the colour that way.

There's some more info on conic gradients here, including how to calculate it: https://wiki.inkscape.org/wiki/index.php/Advanced_Gradients#Conical_gradient

Body:
I am working on building a visual that looks something like this: .

So far I've managed to create this:

The idea is to map a value to an angle so that I know where to point the arrow and then I will color the arrow the same color as the point on the arc that its pointing to.

I essentially have two questions:

First what can I do in order to make the colors line up better. I've used a linear gradient like so:

 let defs = this.gaugeEl
                .append("defs")
                .classed("definitions",true);
        let gradient = defs
            .append("linearGradient")
            .classed("linearGradient",true);

        gradient
            .attr({
                id: 'gradient',
                x1: '0%',
                y1: '0%',
                x2: '100%',
                y2: '100%',
                spreadMethod: "pad"
            });

        gradient
            .append("stop")
            .classed('start',true)
            .attr({
                offset: '0%',
                'stop-color': 'lawngreen',
                'stop-opacity': 1
            });

        gradient.append("stop")
            .classed('end',true)
            .attr({
                offset: '100%',
                'stop-color': 'red',
                'stop-opacity': 1
            });

The effect is not what I was hoping for, what can be done?

The next question about how the gradient works, I need to be able to associate an angle with a color so that I can color the arrow and the tick marks properly and in my current setup I don't know how to do that. Is it even possible?


问:
How to fix Deploying cordapp to corda node in testnet error
I deployed a corda node to corda testnet and I built my sample coded cordapp and copied the jars to the corda node cordapp folder and ran the node and It loaded the workflow (Workflow Cordapp : Template Flows) jar but not the contract (CorDapp Template Contract) jar. The node also is running in production mode. When I do POST requests to the node. It shows error

I configured the contract build.gradle file and turn the signing to false.

This is the node error and the logs:

答:
I believe Devman is correct, in this case, you can't just build cordapps on your local machine and then try to use them for the Corda testnet without some additional changes. You'll need to build and sign your apps with the production keys.

There are a few things you'll have to do with local machine configuration and networking.

Here's the corda docs page on the topic: https://docs.corda.net/docs/corda-os/4.4/deploy-locally.html


问:
"a specified logon session does not exist. it may already have been terminated" after i joined the device to azure active directory
"a specified logon session does not exist. it may already have been terminated" after i joined the device to azure active directory

-i can't access our shared folder in our server after i joined the device to azure AD and use office 365 account (Please see click the link below to see the error image for your reference), but if i use local administrator of the device i can access the file server using the credentials with no problem, please note that we don't have an premises active directory or GPO, kindly help me.

a specified logon session does not exist. it may already have been terminated

答:
To access the share, the server would also need to be azure ad joined. which you cannot do with windows server, you would need azure ad Domain Services (AD DS) on azure, then join your file server to that.
Only Windows 10 devices can be "azure ad-joined devices"

If you don't want to do that, you could create a azure file store, and secure it using your azure ad / rbac, then map that on your devices.. that would probably work too.


问:
How to escape space in connection string
How to escape space in connection string using this example for (trusted mobile users).

I have a OU that is called Trusted mobile users:

```<code>connectionString="LDAP://floor.net/OU=USERS,OU=Trusted mobile users, DC=floor, DC=net"
</code>```

答:
You don't need to escape spaces in LDAP paths. You also should not have spaces after the commas:

```<code>connectionString="LDAP://floor.net/OU=USERS,OU=Trusted mobile users,DC=floor,DC=net"
</code>```

If you're binding to a specific object (an OU in this case) the distinguished name (DN) you use should match exactly what is in the distinguishedName attribute of the object.

The only exception to this is is the forward slash (/). If the DN has a forward slash, you must escape it (by using \/) when you use it in an LDAP path, since that is used as a separator. For example, if your OU was called "Users / Groups", then your LDAP path would look like this:

```<code>LDAP://floor.net/OU=Users \/ Groups,OU=Trusted mobile users,DC=floor,DC=net
</code>```

Body:
How to escape space in connection string using this example for (trusted mobile users).

I have a OU that is called Trusted mobile users:

connectionString="LDAP://floor.net/OU=USERS,OU=Trusted mobile users, DC=floor, DC=net"

Body:
You don't need to escape spaces in LDAP paths. You also should not have spaces after the commas:

connectionString="LDAP://floor.net/OU=USERS,OU=Trusted mobile users,DC=floor,DC=net"

If you're binding to a specific object (an OU in this case) the distinguished name (DN) you use should match exactly what is in the distinguishedName attribute of the object.

The only exception to this is is the forward slash (/). If the DN has a forward slash, you must escape it (by using \/) when you use it in an LDAP path, since that is used as a separator. For example, if your OU was called "Users / Groups", then your LDAP path would look like this:

LDAP://floor.net/OU=Users \/ Groups,OU=Trusted mobile users,DC=floor,DC=net


问:
Laravel 6.x Page Expired after inserting StartSession in Kernel's middleware
I need to send some values to my Controller's constructor via Session, by default Session is not available on the constructor unless you insert this 2 lines in the Kernel's middleware block:

```<code>\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
</code>```

The problem is that after I place those lines I get a 419 | Page Expired message on my view.

Here is how my Kernel looks:

```<code>protected $middleware = [
    \App\Http\Middleware\TrustProxies::class,
    \App\Http\Middleware\CheckForMaintenanceMode::class,
    \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
    \App\Http\Middleware\TrimStrings::class,
    \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,

    \Illuminate\Session\Middleware\StartSession::class,
    \Illuminate\View\Middleware\ShareErrorsFromSession::class,
];

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        // \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],

    'api' => [
        'throttle:60,1',
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],
];
</code>```

答: I dont know what was the problem so I had to install a new Laravel project and now its working.</p>

Body:
I need to send some values to my Controller's constructor via Session, by default Session is not available on the constructor unless you insert this 2 lines in the Kernel's middleware block:

\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,

The problem is that after I place those lines I get a 419 | Page Expired message on my view.

Here is how my Kernel looks:

protected $middleware = [
    \App\Http\Middleware\TrustProxies::class,
    \App\Http\Middleware\CheckForMaintenanceMode::class,
    \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
    \App\Http\Middleware\TrimStrings::class,
    \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,

    \Illuminate\Session\Middleware\StartSession::class,
    \Illuminate\View\Middleware\ShareErrorsFromSession::class,
];

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        // \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],

    'api' => [
        'throttle:60,1',
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],
];


问:
Capturing consecutive year ranges with break in hive
I am trying to write a query in hive to return a data with the year range if they are consecutive years along with the gap year, if there are gaps between the years.

I am trying to get my head around it, but can't seem to find the logic to achieve the results. How does hive logic work for this. Please help.

Input

```<code>group_no            year
1111                2003
1111                2004
1111                2005
1111                2008
1111                2010
1111                2011
1111                2012
2222                2015
3333                2014
3333                2015
3333                2017
3333                2019
4444                2010
4444                2012
</code>```

Output:

```<code>group_no year
1111    [2003-2005,2008,2010-2012]
2222    [2015]
3333    [2014-2015,2017,2019]
4444    [2010,2012]
</code>```

答:
New range starts when (year - prev_year) > 1 or (prev_year is NULL), you can take current year as first year for new range.
Assign first_year to all rows then calculate last_year for each group (group_no, first_year).

```<code>    with my_data as(
    select stack(14,
    1111, 2003,
    1111, 2004,
    1111, 2005,
    1111, 2008,
    1111, 2010,
    1111, 2011,
    1111, 2012,
    2222, 2015,
    3333, 2014,
    3333, 2015,
    3333, 2017,
    3333, 2019,
    4444, 2010,
    4444, 2012
    ) as (group_no, year)
    )

select group_no, array_sort(collect_list(case when first_year=last_year then first_year else concat(first_year,'-',last_year) end)) as year
from
(--calculate last_year
select s.group_no, s.first_year, max(year) last_year
from
(
select group_no, year,
       --New range starts when (year - prev_year) > 1 or (prev_year is NULL)
       --Calculate first_year for every row
       max(case when (year - prev_year) = 1 then NULL else year end) over(partition by group_no order by year rows between unbounded preceding and current row ) first_year
  from
(
select d.*,
       lag(year) over(partition by group_no order by year) prev_year
  from my_data d
)s
)s
group by s.group_no, s.first_year
)s
group by group_no
order by group_no
</code>```

Result:

```<code>group_no  year
1111  ["2003-2005","2008","2010-2012"]
2222  ["2015"]
3333  ["2014-2015","2017","2019"]
4444  ["2010","2012"]
</code>```

Body:
I am trying to write a query in hive to return a data with the year range if they are consecutive years along with the gap year, if there are gaps between the years.

I am trying to get my head around it, but can't seem to find the logic to achieve the results. How does hive logic work for this. Please help.

Input

group_no            year
1111                2003
1111                2004
1111                2005
1111                2008
1111                2010
1111                2011
1111                2012
2222                2015
3333                2014
3333                2015
3333                2017
3333                2019
4444                2010
4444                2012

Output:

group_no year
1111    [2003-2005,2008,2010-2012]
2222    [2015]
3333    [2014-2015,2017,2019]
4444    [2010,2012]

Body:
New range starts when (year - prev_year) > 1 or (prev_year is NULL), you can take current year as first year for new range.
Assign first_year to all rows then calculate last_year for each group (group_no, first_year).

    with my_data as(
    select stack(14,
    1111, 2003,
    1111, 2004,
    1111, 2005,
    1111, 2008,
    1111, 2010,
    1111, 2011,
    1111, 2012,
    2222, 2015,
    3333, 2014,
    3333, 2015,
    3333, 2017,
    3333, 2019,
    4444, 2010,
    4444, 2012
    ) as (group_no, year)
    )

select group_no, array_sort(collect_list(case when first_year=last_year then first_year else concat(first_year,'-',last_year) end)) as year
from
(--calculate last_year
select s.group_no, s.first_year, max(year) last_year
from
(
select group_no, year,
       --New range starts when (year - prev_year) > 1 or (prev_year is NULL)
       --Calculate first_year for every row
       max(case when (year - prev_year) = 1 then NULL else year end) over(partition by group_no order by year rows between unbounded preceding and current row ) first_year
  from
(
select d.*,
       lag(year) over(partition by group_no order by year) prev_year
  from my_data d
)s
)s
group by s.group_no, s.first_year
)s
group by group_no
order by group_no

Result:

group_no  year
1111  ["2003-2005","2008","2010-2012"]
2222  ["2015"]
3333  ["2014-2015","2017","2019"]
4444  ["2010","2012"]


问:
Cannot debug C++ dll loaded in C#
I wanna debug a dll made in C++ while it is inside an executable built from C# with Release mode. The C# app is supposed to not be aware. After I run the C# app I'm able to inject the dll manually which currently opens another window (so I know it was a success)

I built the dll in Debug mode in VS2019. I go Debug > Attach to Process. When I put a breakpoint it says me that it won't be hit as the symbols are not loaded. After injecting they indeed are not hit. The dll does not appear in Debug > Windows > Modules

I tried the same tasks but this time with notepad.exe as target rather than my C# app. It worked flawlessly. I guess Notepad is built with C++ or C rather than C#

Is it impossible to debug my injected C++ dll without touching the C# project?

答:
The dll does not appear in Debug > Windows > Modules

Look in the output window, it will tell you every library it's loading at run-time and whether or not it found symbols for it.

If it says symbols aren't there, make sure the .pdb file is in the same folder with the same name a the .dll, and try again.

Also since you're debugging a .Net application, make sure you set your debugger to also debug native code (the C++ library), because by default the VS debugger will only attach the managed debugger to the application:

As a last thing to check, make sure "Just My Code" debugging isn't selected in VS's options, since the library you want to debug isn't considered "my code" from the point of view of the .Net host application.

Title: Cannot debug C++ dll loaded in C#


问:
How to display the serial number of the table rows in descending order in php?
I am looking way to sort the serial number of the table in descending order. I am using a here simple while loop, with a counter variable inside it.

Code sample:

```<code>       $i= 0;
       while(condition)
       {
           $i++;
         echo "<td>".$i."</td>";
       }
</code>```

Output:

I am not using an autoincrement column here. I just want it with a simple counter, but in descending order.

example:

```<code>#
10
9
8
7
6
5
4
3
2
1
</code>```

Any help is highly appreciated.

答:
If you are fetching from MYSQL Database and you're using PDO to connect to Database

```<code>//COUNT THE TOTAL NUMBER OF ROWS RETURNED
$sql = "SELECT COUNT(*) FROM all_tnxs ORDER BY id DESC";
$stmt = $con->query($sql);
$stmt_num_rows = $stmt->fetch();
$tot_rows = array_shift($stmt_num_rows);
$sn = $tot_rows

while(){
 $sn--;
 echo '<td>' . $sn . '</td>';
}
</code>```

So whatever the total number of rows you have - fetching from the database it'll countdown to '0'using the while loop.
I have been looking for this for long but later figured it out myself so I decided to drop it here for anyone it might be helpful to...

Body:
I am looking way to sort the serial number of the table in descending order. I am using a here simple while loop, with a counter variable inside it.

Code sample:

       $i= 0;
       while(condition)
       {
           $i++;
         echo "".$i."	";
       }

Output:

I am not using an autoincrement column here. I just want it with a simple counter, but in descending order.

example:

#
10
9
8
7
6
5
4
3
2
1

Any help is highly appreciated.

Body:
If you are fetching from MYSQL Database and you're using PDO to connect to Database

//COUNT THE TOTAL NUMBER OF ROWS RETURNED
$sql = "SELECT COUNT(*) FROM all_tnxs ORDER BY id DESC";
$stmt = $con->query($sql);
$stmt_num_rows = $stmt->fetch();
$tot_rows = array_shift($stmt_num_rows);
$sn = $tot_rows

while(){
 $sn--;
 echo '<td>' . $sn . '</td>';
}

So whatever the total number of rows you have - fetching from the database it'll countdown to '0'using the while loop.
I have been looking for this for long but later figured it out myself so I decided to drop it here for anyone it might be helpful to...


问:
How to get the Enum Index value in C#
In C, enums, internally equates to an integer. Therefore we can treat data types of enum as integer also.

How to achieve the same with C#?

答:
Firstly, there could be two values that you're referring to:

Underlying Value

If you are asking about the underlying value, which could be any of these types: byte, sbyte, short, ushort, int, uint, long or ulong

Then you can simply cast it to it's underlying type. Assuming it's an int, you can do it like this:

```<code>int eValue = (int)enumValue;
</code>```

However, also be aware of each items default value (first item is 0, second is 1 and so on) and the fact that each item could have been assigned a new value, which may not necessarily be in any order particular order! (Credit to @JohnStock for the poke to clarify).

This example assigns each a new value, and show the value returned:

```<code>public enum MyEnum
{
    MyValue1 = 34,
    MyValue2 = 27
}

(int)MyEnum.MyValue2 == 27; // True
</code>```

Index Value

The above is generally the most commonly required value, and is what your question detail suggests you need, however each value also has an index value (which you refer to in the title). If you require this then please see other answers below for details.

Title: How to get the Enum Index value in C#

Body:
Firstly, there could be two values that you're referring to:

Underlying Value

If you are asking about the underlying value, which could be any of these types: byte, sbyte, short, ushort, int, uint, long or ulong

Then you can simply cast it to it's underlying type. Assuming it's an int, you can do it like this:

int eValue = (int)enumValue;

However, also be aware of each items default value (first item is 0, second is 1 and so on) and the fact that each item could have been assigned a new value, which may not necessarily be in any order particular order! (Credit to @JohnStock for the poke to clarify).

This example assigns each a new value, and show the value returned:

public enum MyEnum
{
    MyValue1 = 34,
    MyValue2 = 27
}

(int)MyEnum.MyValue2 == 27; // True

Index Value

The above is generally the most commonly required value, and is what your question detail suggests you need, however each value also has an index value (which you refer to in the title). If you require this then please see other answers below for details.


问:
How to load test 10k requests per second using jmeter?
I need to load test my website with 10k req/sec for 1 hour using JMeter. I am confused with the values of loop count, number of thread, ramp-up period and duration.

Also will my laptop (i5 8GB) be able to do that? If not what is the alternative.

PS: I checked every question/answer on stackoverflow for this but I couldn't find any help. Please dont mark it repeated question.

答:
The easiest way of configuring JMeter to send X requests per second is using either Precise Troughput Timer or Throughput Shaping Timer in combination with the Concurrency Thread Group. The number of threads needs to be sufficient, the exact number mainly depends on your application response time, if response time is 1 second - you will need 10k threads, if it's 500ms - you will need 5k threads, if it is 2 seconds - you will need 20k threads, etc.

Only you can answer whether your laptop can kick off the required number of virtual users as there are too many factors to consider: nature of the test, the size of the requests/responses, number of pre/post processors and assertions, etc. Make sure to follow JMeter Best Practices and monitor CPU, RAM, Network, etc. usage using i.e. JMeter PerfMon Plugin as if your laptop will be overloaded - JMeter won't be able to send requests fast enough and you will not be able to conduct 10k requests per second even if the server supports it. If your laptop hardware specifications are too low for the test scenario - you will have to go for Distributed Testing


问:
Getting length of
 when using Bootstrap 4 tab-content
I am a bit stuck on this. I am trying to get the length of a list using Bootstrap 4's tab-content. Since the tab is not active on page load, the length is 0. When I open the tab, it is still 0.

I added the html that gets printed as well as the ajax call to get the data.

// print applicant status
if (applicantStatus == 'true') {
  $('#aStatus').html('Applicant');

  // video module count
  var totalModCount = $("#vidList").find("li").length;
  console.log(totalModCount); // 0 Supposed to be 9
  $('#totalCount').html(totalModCount)

  // form total count
  var totalFormCount = $("#vidList").find("li").length;
  console.log(totalFormCount); // 0 Supposed to be 4
  $('#formTotalCount').html(totalFormCount);
}
else {
  $('#aStatus').html('Employee');
};

var listOfTypes = "";
$.each(parsedData, function (index, item) {

  var dateOfCompletion = moment(item.DateCompleted).format('MM/DD/YYYY');
  lastAttempt = moment(item.DateOfExam).format('MM/DD/YYYY');
  isValid = item.Valid;
  isOrientation = item.IsOrientation;
  isInservice = item.IsInservice;

  if (applicantStatus == "true") {
    if (isOrientation) {
      if (isValid) {
        if (item.IsComplete == true) {
          listOfTypes += "
";
          listOfTypes += item.TypeName + "";
          listOfTypes += "

Completed on: " + dateOfCompletion + "

";

        }
        else {
          listOfTypes += "
";
          listOfTypes += item.TypeName + "";
          listOfTypes += "

Time Duration: " + item.Duration + "

";
        }
      }
      else {
        listOfTypes += "
";
        listOfTypes += item.TypeName + "";
      }
    }
  }
});
```

<pre class="lang-html prettyprint-override"><code><div class='tab-content'>
  <div id="videoList" class="tab-pane fade">
    <ul class='list-group' id='vidList'>
      <li class="list-group-item videoItem"></li>
      <li class="list-group-item videoItem"></li>
      <li class="list-group-item videoItem"></li>
      <li class="list-group-item videoItem"></li>
      <li class="list-group-item videoItem"></li>
      <li class="list-group-item videoItem"></li>
    </ul>
  </div>
  <div id="formsList" class="tab-pane fade">
    <ul class='list-group' id='fList'>
      <li class="list-group-item formItem"></li>
      <li class="list-group-item formItem"></li>
      <li class="list-group-item formItem"></li>
      <li class="list-group-item formItem"></li>
    </ul>
  </div>
</div>
</code>```

答:
This is what I had to do to make it work.

Thank you everyone for your help. I believe my explanations were very confusing, but your input helped me land the answer.

```<code>var completedCount = parsedData.filter(function (item) {
  if (item.Valid == true) {
    return item.IsComplete
  }
}).length;
$('#completionCount').html(completedCount);

// totalCount
var totalCount = parsedData.filter(function (item) {
  if (item.IsOrientation == true && item.Valid == true) {
    return item.IsOrientation
  }
}).length;
$('#totalCount').html(totalCount);
</code>```

Title: Getting length of <li> when using Bootstrap 4 tab-content

Body:
This is what I had to do to make it work.

Thank you everyone for your help. I believe my explanations were very confusing, but your input helped me land the answer.

var completedCount = parsedData.filter(function (item) {
  if (item.Valid == true) {
    return item.IsComplete
  }
}).length;
$('#completionCount').html(completedCount);

// totalCount
var totalCount = parsedData.filter(function (item) {
  if (item.IsOrientation == true && item.Valid == true) {
    return item.IsOrientation
  }
}).length;
$('#totalCount').html(totalCount);


问:
How to get variable, array, nodelist from different function?
I am trying to write a ToDoList with JavaScript.

I have an input-element. Whenever I type something and press enter, it creates a new fieldset(in my example its a fieldset but it can also be a Div) with the class name ".fieldListClass" and a P-Tag as a child of fieldset. the P-tag innerHTML is the the value of input. I used Click-EventListener for that.

After each click, I assigned the query selector of all .fieldListClass to a nodeList "fieldListQuery". I even converted this nodeList into an Array but no result.

Now I want to create an addEventListner but outside the previous one. it should be a new one. And It should be a click-EventListener for all fieldListQuery which where created inside the previous function.(this part is at the bottom of my code)

When I click on it something should happen like removing the current target etc. But it wont work because outside the function it always says that this variable is undefined. I don't get it because I declared it global outside of the function.

I don't want to use DOMNodeInserted or MutationObserver yet for detecting changes inside the DOM. Simple because the first one is not recommended anymore it and the last one I have no idea how to use it. Many people saying that this is not a safe way.

Any Help please?

```<code>let addDiv = document.createElement("div"); addDiv.id = "addDivId";
let listDiv = document.createElement("div"); listDiv.id = "listDivId";
let inputText = document.createElement("input"); inputText.id = "inputTextId";
let fieldList; // = document.createElement("fieldset");
let fieldDiv; // = document.createElement("div");
let fieldDivP; // = document.createElement("P");
let fieldListArr;
let fieldListQuery;

document.body.appendChild(addDiv);
addDiv.appendChild(inputText);
document.body.appendChild(listDiv);

inputText.addEventListener("keypress", event => {
  if (event.key === "Enter") {
 fieldList = document.createElement("fieldset");
 fieldDiv = document.createElement("div");
 fieldDivP = document.createElement("P");

 listDiv.appendChild(fieldList);
 fieldList.className = "fieldListClass";
 fieldList.appendChild(fieldDiv);
 fieldDiv.appendChild(fieldDivP);
 fieldDivP.innerHTML = inputText.value;

 fieldListQuery = document.querySelectorAll(".fieldListClass") ;

  }
})

fieldListQuery.forEach(element => {  // <- it say fieldListQuery is undefined.
 fieldListQuery.addEventListener("click", e =>  {
e.currentTarget.innerHTML="test";
})
});

´´´

</code>```

答:
Since I offered critique of your approach, I thought it is only fair I at least try to offer you some code that accomplishes (on the overall level, in light of absence of much detail about your solution) something along of what you have.

First off, I think creating trees of elements through a script when other solutions are more viable, tends to show an anti-pattern. Your script is invariably loaded in the context of an HTML document, which may already contain a lot of useful markup -- including an input field (that you were creating with createElement). If the input field is a "constant" there is no need to waste code on creating it -- just put it in your markup.

Second, even for elements or hierarchies of elements that are created "on demand" -- as a reaction to an event or however else -- it typically is much more readable and manageable to use templates. As a fallback -- if template cannot be used for some reason -- using innerHTML to create entire element trees is actually an appealing and more readable option than a lot of "boilerplate" containing createElement, appendChild, etc.

Third, you should always try to see if you can have your interactive controls be part of a form. I won't go into all reasons to do so, but suffice to say it helps user agents that screen-read content and for other accessibility systems, to name one. There are exceptions to this rule, but I don't recall looking at code where a control should not be part of a form -- so the rule is a good one.

Here is a proof-of-concept bare-bones to-do application:

        <template id="todo-item-template">

        </template>

        <form action="javascript: submit_create_todo_item_form()">
            <input>
        </form>

```

Take note that I use textContent instead of innerHTML to create content for a to-do item's body. innerHTML invokes the HTML parser and unless you plan to be typing hypertext into that single line of input field, innerHTML only costs you extra for no clear benefit. If you need to interpret the value verbatim, textContent is instead exactly what's needed. So, approach your solution with that in mind.

I hope this is useful, I worked with what I thought I had.

Body:
I am trying to write a ToDoList with JavaScript.

I have an input-element. Whenever I type something and press enter, it creates a new fieldset(in my example its a fieldset but it can also be a Div) with the class name ".fieldListClass" and a P-Tag as a child of fieldset. the P-tag innerHTML is the the value of input. I used Click-EventListener for that.

After each click, I assigned the query selector of all .fieldListClass to a nodeList "fieldListQuery". I even converted this nodeList into an Array but no result.

Now I want to create an addEventListner but outside the previous one. it should be a new one. And It should be a click-EventListener for all fieldListQuery which where created inside the previous function.(this part is at the bottom of my code)

When I click on it something should happen like removing the current target etc. But it wont work because outside the function it always says that this variable is undefined. I don't get it because I declared it global outside of the function.

I don't want to use DOMNodeInserted or MutationObserver yet for detecting changes inside the DOM. Simple because the first one is not recommended anymore it and the last one I have no idea how to use it. Many people saying that this is not a safe way.

Any Help please?

let addDiv = document.createElement("div"); addDiv.id = "addDivId";
let listDiv = document.createElement("div"); listDiv.id = "listDivId";
let inputText = document.createElement("input"); inputText.id = "inputTextId";
let fieldList; // = document.createElement("fieldset");
let fieldDiv; // = document.createElement("div");
let fieldDivP; // = document.createElement("P");
let fieldListArr;
let fieldListQuery;

document.body.appendChild(addDiv);
addDiv.appendChild(inputText);
document.body.appendChild(listDiv);

inputText.addEventListener("keypress", event => {
  if (event.key === "Enter") {
 fieldList = document.createElement("fieldset");
 fieldDiv = document.createElement("div");
 fieldDivP = document.createElement("P");

 listDiv.appendChild(fieldList);
 fieldList.className = "fieldListClass";
 fieldList.appendChild(fieldDiv);
 fieldDiv.appendChild(fieldDivP);
 fieldDivP.innerHTML = inputText.value;

 fieldListQuery = document.querySelectorAll(".fieldListClass") ;

  }
})

fieldListQuery.forEach(element => {  // <- it say fieldListQuery is undefined.
 fieldListQuery.addEventListener("click", e =>  {
e.currentTarget.innerHTML="test";
})
});

´´´

Body:
Since I offered critique of your approach, I thought it is only fair I at least try to offer you some code that accomplishes (on the overall level, in light of absence of much detail about your solution) something along of what you have.

First off, I think creating trees of elements through a script when other solutions are more viable, tends to show an anti-pattern. Your script is invariably loaded in the context of an HTML document, which may already contain a lot of useful markup -- including an input field (that you were creating with createElement). If the input field is a "constant" there is no need to waste code on creating it -- just put it in your markup.

Second, even for elements or hierarchies of elements that are created "on demand" -- as a reaction to an event or however else -- it typically is much more readable and manageable to use templates. As a fallback -- if template cannot be used for some reason -- using innerHTML to create entire element trees is actually an appealing and more readable option than a lot of "boilerplate" containing createElement, appendChild, etc.

Third, you should always try to see if you can have your interactive controls be part of a form. I won't go into all reasons to do so, but suffice to say it helps user agents that screen-read content and for other accessibility systems, to name one. There are exceptions to this rule, but I don't recall looking at code where a control should not be part of a form -- so the rule is a good one.

Here is a proof-of-concept bare-bones to-do application:

<html>
    <head>
        <script>
            function submit_create_todo_item_form() {
                const new_todo_fragment = document.getElementById("todo-item-template").content.cloneNode(true);
                new_todo_fragment.querySelector(".body").textContent = document.forms[0].elements[0].value;
                document.body.appendChild(new_todo_fragment);
            }
        </script>
        <template id="todo-item-template">
            <div class="todo-item">
                <p class="body"></p>
            </div>
        </template>
    </head>
    <body>
        <form action="javascript: submit_create_todo_item_form()">
            <input>
        </form>
    </body>
<html>

Take note that I use textContent instead of innerHTML to create content for a to-do item's body. innerHTML invokes the HTML parser and unless you plan to be typing hypertext into that single line of input field, innerHTML only costs you extra for no clear benefit. If you need to interpret the value verbatim, textContent is instead exactly what's needed. So, approach your solution with that in mind.

I hope this is useful, I worked with what I thought I had.


问:
Find min/max of two dates (typed)
I want a strongly typed code. When I apply solutions from a similar question - Min/Max of dates in an array? - I get error

```<code>TS2345: Argument of type 'Date' is not assignable to parameter of type 'number'.
</code>```

my code

```<code>  const min: Date = Math.min(begin as Date, (end || defaultDate) as Date);
  const max: Date = Math.max(begin as Date, (end || defaultDate) as Date);
</code>```

begin as Date part is underlined.

What's the correct way of finding min/max dates in Typescript?

答:
Thank you @OliverRadini for sample code!

My own solution, taking into account possibly nullable dates:

```<code>const begin: Date | null | undefined = // ...
const end: Date | null | undefined = // ...
const defaultDate: Date = new Date();

let min: Date;
let max: Date;
if (!begin || !end) {
  min = (begin || end || defaultDate);
  max = (begin || end || defaultDate);
} else if (begin > end) {
  min = end;
  max = begin;
} else {
  min = begin;
  max = end;
}
</code>```

Title: Find min/max of two dates (typed)

Body:
I want a strongly typed code. When I apply solutions from a similar question - Min/Max of dates in an array? - I get error

TS2345: Argument of type 'Date' is not assignable to parameter of type 'number'.

my code

  const min: Date = Math.min(begin as Date, (end || defaultDate) as Date);
  const max: Date = Math.max(begin as Date, (end || defaultDate) as Date);

begin as Date part is underlined.

What's the correct way of finding min/max dates in Typescript?

Body:
Thank you @OliverRadini for sample code!

My own solution, taking into account possibly nullable dates:

const begin: Date | null | undefined = // ...
const end: Date | null | undefined = // ...
const defaultDate: Date = new Date();

let min: Date;
let max: Date;
if (!begin || !end) {
  min = (begin || end || defaultDate);
  max = (begin || end || defaultDate);
} else if (begin > end) {
  min = end;
  max = begin;
} else {
  min = begin;
  max = end;
}


问:
How do I perform a regular expression on multiple .txt files in a folder (Python)?
I'm trying to open up 32 .txt files, extract some text from them (using RegEx) and then save them as individual files again(later on in the project I'm hoping to collate them together). I've tested the RegEx on a single file and it seems to work:

```<code>import os
import re
os.chdir(r'C:\Users\garet\OneDrive - University of Exeter\Masters\Year Two\Dissertation planning\Manual scrape\Finished years proper')
with open('1988.txt') as txtfile:
    text= txtfile.read()
#print(len(text)) #sentences in text

start = r'Body\n\n\n'

docs = re.findall(start, text)
print('Found the start of %s documents.' % len(docs))
end = r'Load-Date:'
print('Found the end of %s documents.' % len(docs))
docs = re.findall(end, text)
regex = start+r'(.+?)'+end
articles = re.findall(regex, text, re.S)
print('You have now parsed the 154 articles so only the body of content remains. All metadata has been removed.')
print('Here is an example of a parsed article:', articles[0])
</code>```

Now I want to perform the exact same thing on all my .txt files in that folder, but I can't figure out how to. I've been playing around with For loops but with little success. Currently I have this:

```<code>import os
import re
finished_years_proper= os.listdir(r'C:\Users\garet\OneDrive - University of Exeter\Masters\Year Two\Dissertation\Manual scrape\Finished years proper')
os.chdir(r'C:\Users\garet\OneDrive - University of Exeter\Masters\Year Two\Dissertation\Manual scrape\Finished years proper')
print('There are %s .txt files in this folder.' % len(finished_years_proper))

if i.endswith(".txt"):
    with open(finished_years_proper + i, 'r') as all_years:
        for line in all_years:
            start = r'Body\n\n\n'
            docs = re.findall(start, all_years)
            end = r'Load-Date:'
            docs = re.findall(end, all_years)
            regex = start+r'(.+?)'+end
            articles = re.findall(regex, all_years, re.S)
</code>```

However, I'm returning a type error:

```<code> File "C:\Users\garet\OneDrive - University of Exeter\Masters\Year Two\Dissertation\Method\Python\untitled1.py", line 15, in <module>
        with open(finished_years_proper + i, 'r') as all_years:

    TypeError: can only concatenate list (not "str") to list
</code>```

I'm unsure how to proceed... I've seen on other forums that I should convert something into a string, but I'm not sure what to convert or even if this is the right way to proceed. Any help with this would be really appreciated!

After taking Benedictanjw's into my codes I've ended up with this:
Hi, this is what I ended up with:

all_years= []
for fyp in finished_years_proper: #fyp is each text file in folder
    with open(fyp, 'r') as year:
        for line in year: #line is each element in each text file in folder
            start = r'Body\n\n\n'
            docs = re.findall(start, line)
            end = r'Load-Date:'
            docs = re.findall(end, line)
            regex = start+r'(.+?)'+end
            articles = re.findall(regex, line, re.S)
            all_years.append(articles) #append strings to reflect RegEx
            parsed_documents= all_years.append(articles)
            print(parsed_documents) #returns None. Apparently this is okay.

Does the 'None' mean that the parsing of each file is successful (as in it emulates the result I had when I tested the RegEx on a single file)? And if so, how can I visualise my output without returning None.  Many thanks in advance!!

答:
The problem shows because finished_years_proper is a list and in your line:

with open(finished_years_proper + i, 'r') as all_years:
```

<p>you are trying to concatenate <code>i</code> with that list. I presume you had accidentally defined <code>i</code> elsewhere as a string. I guess you probably want to do something like:</p>

<pre class="lang-py prettyprint-override"><code>all_years = []
for fyp in finished_years_proper:
  with open(fyp, 'r') as year:
    for line in year:
      ... # your regex search on year
      all_years.append(xxx)

</code>```

Body:
I'm trying to open up 32 .txt files, extract some text from them (using RegEx) and then save them as individual files again(later on in the project I'm hoping to collate them together). I've tested the RegEx on a single file and it seems to work:

import os
import re
os.chdir(r'C:\Users\garet\OneDrive - University of Exeter\Masters\Year Two\Dissertation planning\Manual scrape\Finished years proper')
with open('1988.txt') as txtfile:
    text= txtfile.read()
#print(len(text)) #sentences in text

start = r'Body\n\n\n'

docs = re.findall(start, text)
print('Found the start of %s documents.' % len(docs))
end = r'Load-Date:'
print('Found the end of %s documents.' % len(docs))
docs = re.findall(end, text)
regex = start+r'(.+?)'+end
articles = re.findall(regex, text, re.S)
print('You have now parsed the 154 articles so only the body of content remains. All metadata has been removed.')
print('Here is an example of a parsed article:', articles[0])

Now I want to perform the exact same thing on all my .txt files in that folder, but I can't figure out how to. I've been playing around with For loops but with little success. Currently I have this:

import os
import re
finished_years_proper= os.listdir(r'C:\Users\garet\OneDrive - University of Exeter\Masters\Year Two\Dissertation\Manual scrape\Finished years proper')
os.chdir(r'C:\Users\garet\OneDrive - University of Exeter\Masters\Year Two\Dissertation\Manual scrape\Finished years proper')
print('There are %s .txt files in this folder.' % len(finished_years_proper))

if i.endswith(".txt"):
    with open(finished_years_proper + i, 'r') as all_years:
        for line in all_years:
            start = r'Body\n\n\n'
            docs = re.findall(start, all_years)
            end = r'Load-Date:'
            docs = re.findall(end, all_years)
            regex = start+r'(.+?)'+end
            articles = re.findall(regex, all_years, re.S)

However, I'm returning a type error:

 File "C:\Users\garet\OneDrive - University of Exeter\Masters\Year Two\Dissertation\Method\Python\untitled1.py", line 15, in <module>
        with open(finished_years_proper + i, 'r') as all_years:

    TypeError: can only concatenate list (not "str") to list

I'm unsure how to proceed... I've seen on other forums that I should convert something into a string, but I'm not sure what to convert or even if this is the right way to proceed. Any help with this would be really appreciated!

After taking Benedictanjw's into my codes I've ended up with this:
Hi, this is what I ended up with:

all_years= []
for fyp in finished_years_proper: #fyp is each text file in folder
    with open(fyp, 'r') as year:
        for line in year: #line is each element in each text file in folder
            start = r'Body\n\n\n'
            docs = re.findall(start, line)
            end = r'Load-Date:'
            docs = re.findall(end, line)
            regex = start+r'(.+?)'+end
            articles = re.findall(regex, line, re.S)
            all_years.append(articles) #append strings to reflect RegEx
            parsed_documents= all_years.append(articles)
            print(parsed_documents) #returns None. Apparently this is okay.

Does the 'None' mean that the parsing of each file is successful (as in it emulates the result I had when I tested the RegEx on a single file)? And if so, how can I visualise my output without returning None.  Many thanks in advance!!

Body:
The problem shows because finished_years_proper is a list and in your line:

with open(finished_years_proper + i, 'r') as all_years:

you are trying to concatenate i with that list. I presume you had accidentally defined i elsewhere as a string. I guess you probably want to do something like:

all_years = []
for fyp in finished_years_proper:
  with open(fyp, 'r') as year:
    for line in year:
      ... # your regex search on year
      all_years.append(xxx)


问:
Converting dataframe to dictionary with key and multiple value
I have an usecase where I have to read xl file with multiple header columns and values.

```<code>I have to convert that into a dictionary, key with multiple values.
The xl header will vary each time, some times 2 columns some to three, and so on.

The sample data frame for an xl file is
      key1    key2
      abc     xyz
      bca     yxz
      cab     zxy

the output should be as...
   {'key1': ['abc','bca','cab'], 'key2': ['xyz','yxz', 'zxy']}

if there is one more column key3, I should able to include that as well in the dictionary
</code>```

.

```<code>import pandas as pd
workbook_loc = "c:\\2020\Book1.xlsx"
df = pd.read_excel(workbook_loc, sheet_name=None)
data_dict = df.to_dict()

but the above script is throwing out  AttributeErro 'dict' object has no attribute.

what is the wrong I am doing?
</code>```

答:
When you specify sheet_name=None it returns a dictionary instead of pandas dataframe. its always good practice to specify a sheet name.

You can try this..

```<code>import pandas as pd
workbook_loc = "c:\\2020\Book1.xlsx"
df = pd.read_excel(workbook_loc, index_col=0, sheet_name='Sheet1')
data_dict = {}
for col in df.columns:
    data_dict[col]=[row for row in df[col]]
</code>```

Body:
I have an usecase where I have to read xl file with multiple header columns and values.

I have to convert that into a dictionary, key with multiple values.
The xl header will vary each time, some times 2 columns some to three, and so on.

The sample data frame for an xl file is
      key1    key2
      abc     xyz
      bca     yxz
      cab     zxy

the output should be as...
   {'key1': ['abc','bca','cab'], 'key2': ['xyz','yxz', 'zxy']}

if there is one more column key3, I should able to include that as well in the dictionary

.

import pandas as pd
workbook_loc = "c:\\2020\Book1.xlsx"
df = pd.read_excel(workbook_loc, sheet_name=None)
data_dict = df.to_dict()

but the above script is throwing out  AttributeErro 'dict' object has no attribute.

what is the wrong I am doing?

Body:
When you specify sheet_name=None it returns a dictionary instead of pandas dataframe. its always good practice to specify a sheet name.

You can try this..

import pandas as pd
workbook_loc = "c:\\2020\Book1.xlsx"
df = pd.read_excel(workbook_loc, index_col=0, sheet_name='Sheet1')
data_dict = {}
for col in df.columns:
    data_dict[col]=[row for row in df[col]]


问:
ZAP Scanning Report - Wildcard Directive,style-src unsafe-inline,script-src unsafe-inline
 When scanning using OWASP ZAP, the report shows the following as medium risk:

Wildcard Directive

style-src unsafe-inline

script-src unsafe-inline

How can I fixed this issue on my server?

答:
Have you looked at everything that ZAP is reporting? There should be a lot more information than this.

For the unsafe-inline findings you'll need to remove those elements from your CSP and move all of the inline styles and scripts into external files from the HTML. I'd focus on  the inline scripts as they are more concerning.


问:
Is there an easier way to pause execution then a callback on an async function?
I have a nodejs application where I download a file which is then immediately used and the rest of the program depends on that file being used, the only problem is that the only function I have to download the file through Google Cloud is asynchronous which means in order to stop the program from immediately crashing when it realizes the file hasn't been fully downloaded is to stick a callback on my asyncronous function for downloading.

This would normally be fine, but unfortunately the rest of the program is around 400 LINES LONG which means a 400 LINE LONG CALLBACK FUNCTION. Which is understandably ugly.

If anyone can tell me of a simpler method for pausing execution than this callback function, I would appreciate it.

Feel free to let me know if this is a duplicate question and this exact one has been answered elsewhere. I scoured for this question myself, but couldn't find it.

async function downloader(callback){
  await download(file); //insert download function here

 callback();
}
downloader(function(){
  var usefulthing = JSON.parse(file);
  //Insert 400 lines of code here
});```

答:
```<code>const Downloader=async()=>{

   const file = await download(file)
    // this now returns the file as a promise
   return file
}
function MainStuff async(){
   const file =await Downloader()
  // the 400 lines of code now will wait this file to finish downloading
}
</code>```


问:
Access dom element with vuejs and vuetify in v-tabs
I have a div tag with an 'id="meet"' into v-tabs.

I need to access the node of this tag after I click a tab. I am using

```<code>let node=document.querySelector("#meet").
</code>```

My problem is that it always returns "null". Here is the codepen: https://codepen.io/luizalves/pen/WNrepxz

What is wrong here?

答:
There is no guarantee that after $nextTick you will see DOM element immediately.

```<code> <div id="meet"></div>
<button @click="onTest">test</button>
...
methods: {
onTest () {
      let node=document.querySelector("#meet");
      console.log('meet here',node)
    },
</code>```

After you clicked test you'll see in a console:

```<code>"meet here" "<div id='meet'></div>"
</code>```

You can try to extract this div with an unique id into a separate component and inside it you can use mounted hook to know that it exists in DOM

Body:
I have a div tag with an 'id="meet"' into v-tabs.

I need to access the node of this tag after I click a tab. I am using

let node=document.querySelector("#meet").

My problem is that it always returns "null". Here is the codepen: https://codepen.io/luizalves/pen/WNrepxz

What is wrong here?

Body:
There is no guarantee that after $nextTick you will see DOM element immediately.

 <div id="meet"></div>
<button @click="onTest">test</button>
...
methods: {
onTest () {
      let node=document.querySelector("#meet");
      console.log('meet here',node)
    },

After you clicked test you'll see in a console:

"meet here" "<div id='meet'></div>"

You can try to extract this div with an unique id into a separate component and inside it you can use mounted hook to know that it exists in DOM


问:
Warp a 2D image onto another image
I have obtained a 3D wavefront model of face inside a portrait and then that face is transformed using mesh_numpy and a 2D transformed image is saved. As the images are attached. Now I want to warp this transformed image back onto the original image. It's like face swap where I have both source and target image. What is the better way to achieve it.

Original:

Transformed:

答: Update: If anyone faces this issue in near future, I managed to achieve this by using Homography.</p>

Title: Warp a 2D image onto another image


问:
Find all files that end with txt and out in all directories within a size margin
Here is the code:

```<code>find /home/185053/ -iname "*.{txt,out}" -type f -size +8 -size -15
</code>```

So, the command works if I exclude the -iname "*.{txt,out}" part out.

I've tried using | grep "*.{txt,out}" at the end but that doesn't work either.

Any ideas?

答:
Try using grep with -E option and like this:

```<code>find /home/185053/ -type f -size +8 -size -15 | grep -E "*\.txt|*\.out"
</code>```

Body:
Here is the code:

find /home/185053/ -iname "*.{txt,out}" -type f -size +8 -size -15

So, the command works if I exclude the -iname "*.{txt,out}" part out.

I've tried using | grep "*.{txt,out}" at the end but that doesn't work either.

Any ideas?

Body:
Try using grep with -E option and like this:

find /home/185053/ -type f -size +8 -size -15 | grep -E "*\.txt|*\.out"


问:
Java -- Best way to grab ALL Strings between two regex?
I have a requirement where I want to extract the content from a file which can have multiple occurrences of the pattern. Basically files containing multiple sections and I want to extra each section. The extracted content should include the string matching the pattern

Eg: File content

```<code>01
Community based Index1-
...some text....
...some text..
Conclusion: The significant increase of testing
...
some text.

02
Community based Index2-
.some text.
.some text.
Conclusion: The significant increase of testing
...
...<End of para>
:
:
</code>```

I am trying with the following pattern but it is not working

```<code>String patternStart = "\\d{2}[^\\d.,)][\\s:-]?[\\r\\n][A-Z]";
String patternEnd = "Conclusion.*(\\n.*)*"; \\ including the entire para

I am trying with pattern matcher but it is not working, I am getting no match found.

 String regexString = Pattern.quote(patternStart)  + "(.*?)" + Pattern.quote(patternEnd);
 Pattern pattern = Pattern.compile(regexString);
 while (matcher.find()) {
            String textInBetween = matcher.group(1);
  }
</code>```

答:
You could use a single pattern to extract the whole section:

```<code>^\d+(?:\R(?!\d+\R|Conclusion:).*)*\RConclusion:\h+(.*(?:\R(?!\d+\R|Conclusion:).*)*)
</code>```

Explanation

^ Start of string

\d+ Match 1+ digits

(?: Non capture group

\R(?!\d+\R|Conclusion:).* Match a unicode newline sequence and the rest of the line if it does not start with either 1+ digits and a newline or Conclusion:

)* Close group and repeat 0+ times to match all the lines

\RConclusion:\h+ Match a newline and Conclusion: followed by 1+ horizontal whitespace chars

( Capture group 1

.* Match the whole line

(?:\R(?!\d+\R|Conclusion:).*)* Repeat 0+ times matching all lines that do not start with either 1+ digits followed by a newline or Conclusion:

) Close group 1

Regex demo

In Java

```<code>String regex = "^\\d+(?:\\R(?!\\d+\\R|Conclusion:).*)*\\RConclusion: (.*(?:\\R(?!\\d+\\R|Conclusion:).*)*)";
</code>```

See a Java demo

Body:
I have a requirement where I want to extract the content from a file which can have multiple occurrences of the pattern. Basically files containing multiple sections and I want to extra each section. The extracted content should include the string matching the pattern

Eg: File content

01
Community based Index1-
...some text....
...some text..
Conclusion: The significant increase of testing
...
some text.

02
Community based Index2-
.some text.
.some text.
Conclusion: The significant increase of testing
...
...<End of para>
:
:

I am trying with the following pattern but it is not working

String patternStart = "\\d{2}[^\\d.,)][\\s:-]?[\\r\\n][A-Z]";
String patternEnd = "Conclusion.*(\\n.*)*"; \\ including the entire para

I am trying with pattern matcher but it is not working, I am getting no match found.

 String regexString = Pattern.quote(patternStart)  + "(.*?)" + Pattern.quote(patternEnd);
 Pattern pattern = Pattern.compile(regexString);
 while (matcher.find()) {
            String textInBetween = matcher.group(1);
  }

Body:
You could use a single pattern to extract the whole section:

^\d+(?:\R(?!\d+\R|Conclusion:).*)*\RConclusion:\h+(.*(?:\R(?!\d+\R|Conclusion:).*)*)

Explanation

^ Start of string

\d+ Match 1+ digits

(?: Non capture group

\R(?!\d+\R|Conclusion:).* Match a unicode newline sequence and the rest of the line if it does not start with either 1+ digits and a newline or Conclusion:

)* Close group and repeat 0+ times to match all the lines

\RConclusion:\h+ Match a newline and Conclusion: followed by 1+ horizontal whitespace chars

( Capture group 1

.* Match the whole line

(?:\R(?!\d+\R|Conclusion:).*)* Repeat 0+ times matching all lines that do not start with either 1+ digits followed by a newline or Conclusion:

) Close group 1

Regex demo

In Java

String regex = "^\\d+(?:\\R(?!\\d+\\R|Conclusion:).*)*\\RConclusion: (.*(?:\\R(?!\\d+\\R|Conclusion:).*)*)";

See a Java demo


问:
How to read complex numbers from a file using class and problem with access to private variable in C++?
I get a task. I must read complex numbers from a file and write them into another file. In class, I must create two private variables for the real number and imaginary number. A little bigger function I must create outside class as inline functions.

This is my code:

```<code>#include <iostream>
#include <fstream>
#include <cstdlib>
#include <assert.h>

using namespace std;

class Complex_num {
    double real, imag;
public:
    Complex_num(){
    real=0;
    imag=0;
    }

    friend std::ostream& operator<<(std::ostream&, const Complex_num&);
    friend std::istream& operator>>(std::istream&, Complex_num&);
};

inline void readC(FILE *wp, double *real, double *imag) {
    char c;
    assert(fscanf(wp,"%c%lg%c%lg%c%c",&c,real,&c,real,&c,&c));
}
inline int writeC(FILE *wp, double real, double imag)
{
    fprintf(wp, "%.2f, %.2f\n", real, imag);

    return 1;
}

int main(int argc, char* argv[])
{
    FILE *wz, *wc;

    char c;
    ifstream read(argv[1]);
    if (!read)
        { cerr << "Open error: " << argv[1] << endl; exit(1);}
    ofstream write(argv[2]);
    if(!write) { cerr << "Open error: " << argv[2] << endl; exit(2);}
    while(read.get(c))
        write.put(c);

    Complex_num x1;
    readC(wz, x1.real, x1.imag);
    write(wc, x1.real, x1.imag);

    return 0;
}
</code>```

I have some errors

```<code>czyt_pisanie.cpp: In function ‘int main(int, char**)’:
czyt_pisanie.cpp:48:18: error: ‘double Complex_num::real’ is private within this context
     readC(wz, x1.real, x1.imag);
                  ^~~~
czyt_pisanie.cpp:9:12: note: declared private here
     double real, imag;
            ^~~~
czyt_pisanie.cpp:48:27: error: ‘double Complex_num::imag’ is private within this context
     readC(wz, x1.real, x1.imag);
                           ^~~~
czyt_pisanie.cpp:9:18: note: declared private here
     double real, imag;
                  ^~~~
czyt_pisanie.cpp:48:31: error: cannot convert ‘double’ to ‘double*’ for argument ‘2’ to ‘void readC(FILE*, double*, double*)’
     readC(wz, x1.real, x1.imag);
                               ^
czyt_pisanie.cpp:49:18: error: ‘double Complex_num::real’ is private within this context
     write(wc, x1.real, x1.imag);
                  ^~~~
czyt_pisanie.cpp:9:12: note: declared private here
     double real, imag;
            ^~~~
czyt_pisanie.cpp:49:27: error: ‘double Complex_num::imag’ is private within this context
     write(wc, x1.real, x1.imag);
                           ^~~~
czyt_pisanie.cpp:9:18: note: declared private here
     double real, imag;
                  ^~~~
czyt_pisanie.cpp:49:31: error: no match for call to ‘(std::ofstream {aka std::basic_ofstream<char>}) (FILE*&, double&, double&)’
     write(wc, x1.real, x1.imag);

</code>```

I also have operators, but I don't know what I should do with them

```<code>    friend std::ostream& operator<<(std::ostream&, const Complex_num&);
    friend std::istream& operator>>(std::istream&, Complex_num&);
</code>```

答:
You have declared two friend operators that can access the private variables. So your code should look something like this</p>

```<code>std::ostream& operator<<(std::ostream& out, const Complex_num& c)
{
    return out << c.real << ' ' << c.imag;
}

std::istream& operator>>(std::istream& in, Complex_num& c)
{
    // code to read c.real and c.imag
    return in;
}

int main()
{
    ...
    Complex_num x1;
    read >> x1;
    write << x1;
}
</code>```

Body:
I get a task. I must read complex numbers from a file and write them into another file. In class, I must create two private variables for the real number and imaginary number. A little bigger function I must create outside class as inline functions.

This is my code:

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <assert.h>

using namespace std;

class Complex_num {
    double real, imag;
public:
    Complex_num(){
    real=0;
    imag=0;
    }

    friend std::ostream& operator<<(std::ostream&, const Complex_num&);
    friend std::istream& operator>>(std::istream&, Complex_num&);
};

inline void readC(FILE *wp, double *real, double *imag) {
    char c;
    assert(fscanf(wp,"%c%lg%c%lg%c%c",&c,real,&c,real,&c,&c));
}
inline int writeC(FILE *wp, double real, double imag)
{
    fprintf(wp, "%.2f, %.2f\n", real, imag);

    return 1;
}

int main(int argc, char* argv[])
{
    FILE *wz, *wc;

    char c;
    ifstream read(argv[1]);
    if (!read)
        { cerr << "Open error: " << argv[1] << endl; exit(1);}
    ofstream write(argv[2]);
    if(!write) { cerr << "Open error: " << argv[2] << endl; exit(2);}
    while(read.get(c))
        write.put(c);

    Complex_num x1;
    readC(wz, x1.real, x1.imag);
    write(wc, x1.real, x1.imag);

    return 0;
}

I have some errors

czyt_pisanie.cpp: In function ‘int main(int, char**)’:
czyt_pisanie.cpp:48:18: error: ‘double Complex_num::real’ is private within this context
     readC(wz, x1.real, x1.imag);
                  ^~~~
czyt_pisanie.cpp:9:12: note: declared private here
     double real, imag;
            ^~~~
czyt_pisanie.cpp:48:27: error: ‘double Complex_num::imag’ is private within this context
     readC(wz, x1.real, x1.imag);
                           ^~~~
czyt_pisanie.cpp:9:18: note: declared private here
     double real, imag;
                  ^~~~
czyt_pisanie.cpp:48:31: error: cannot convert ‘double’ to ‘double*’ for argument ‘2’ to ‘void readC(FILE*, double*, double*)’
     readC(wz, x1.real, x1.imag);
                               ^
czyt_pisanie.cpp:49:18: error: ‘double Complex_num::real’ is private within this context
     write(wc, x1.real, x1.imag);
                  ^~~~
czyt_pisanie.cpp:9:12: note: declared private here
     double real, imag;
            ^~~~
czyt_pisanie.cpp:49:27: error: ‘double Complex_num::imag’ is private within this context
     write(wc, x1.real, x1.imag);
                           ^~~~
czyt_pisanie.cpp:9:18: note: declared private here
     double real, imag;
                  ^~~~
czyt_pisanie.cpp:49:31: error: no match for call to ‘(std::ofstream {aka std::basic_ofstream<char>}) (FILE*&, double&, double&)’
     write(wc, x1.real, x1.imag);

I also have operators, but I don't know what I should do with them

    friend std::ostream& operator<<(std::ostream&, const Complex_num&);
    friend std::istream& operator>>(std::istream&, Complex_num&);

Body:
You have declared two friend operators that can access the private variables. So your code should look something like this

std::ostream& operator<<(std::ostream& out, const Complex_num& c)
{
    return out << c.real << ' ' << c.imag;
}

std::istream& operator>>(std::istream& in, Complex_num& c)
{
    // code to read c.real and c.imag
    return in;
}

int main()
{
    ...
    Complex_num x1;
    read >> x1;
    write << x1;
}


问:
Unsupported Media Type 415, but in Postman works fine
After registration user get a link, which consist of userId and token. When user click on it - angular project opens, then angular takes userId and token from link, and send a post method to backend for verifying email.

Link example

http://localhost:4200/user/confirmemail/?userId=9bc9a474-d10c-438b-8953-1c32fc57551b&token=Q2ZESjhPRkF6d3BPQ1E5TmtLbWplTnlIZ3g3bzJEVEZQZDQ3MFNSblExaWxBTWh3MmdSMWl2ZkU3djZxcWR3bmY4OFMwd2l6STZOY3VMR2FoZ1ZCM28rWFo1YlJhejhOTE5pamFFdGRETTNiNGttT0lOQ2dZVmdLRVlRdWlKRmtQMVpEWHE0b2t2NVBQZTZ0bkR3cUdrb3JiMWRIQUpRUE5pMTZjTW96YUdJcVZBUUxPSG5pd3NDU3BDeTBNREMvMTVyTlhUNUpCL2tRZTJWMjJlTzVHZ1dDbEh5VWNESGNsNlVTQkpXZ1FJaThDTk1kcUovcmdtV0ZEdEQza2hXR1p6V0pEdz09

Post method, which verify email:

```<code>        [HttpPost("confirmEmail/{userId}")]
        public async Task<IActionResult> ConfirmEmail(string userId, [FromBody]string token)
        {
            var codeDecodedBytes = WebEncoders.Base64UrlDecode(token);
            var codeDecoded = Encoding.UTF8.GetString(codeDecodedBytes);
            var user = await _userManager.FindByIdAsync(userId);
            var result = await _userManager.ConfirmEmailAsync(user, codeDecoded);
            return Ok(result);
        }
</code>```

It works fine in postman:

Error in Angular project:

Getting userId and token in Angular

```<code>  userId: string;
  token: string;
  constructor(private activatedRoute: ActivatedRoute, private authService: AuthService) {
    this.activatedRoute.queryParams.subscribe(params => {
          this.userId = params['userId'];
          this.token = params['token'];
      });
  }

  ngOnInit(): void {
    this.confirmEmail();
  }

  confirmEmail(){
    this.authService.confirmEmail(this.userId, this.token).subscribe(data => { console.log("success")});
  }
</code>```

(AuthService) Sending data to backend

```<code>  confirmEmail(userId: string, token: string){
    console.log(userId);
    console.log(token);
    return this.http.post(this.authUrl + `confirmemail/${userId}`, token);
  }
</code>```

答:
Try to set Content-Type to json type:

```<code>confirmEmail(userId: string, token: string) {
    const body = JSON.stringify(token);
    const options = {
      headers: new HttpHeaders().append('Content-Type', 'application/json')
    };

    return this.http.post(this.authUrl + `confirmemail/${userId}`, body, options)
          .pipe(
              map(res => res)
            , catchError(this.handleError())
          );
}
</code>```

Body:
After registration user get a link, which consist of userId and token. When user click on it - angular project opens, then angular takes userId and token from link, and send a post method to backend for verifying email.

Link example

http://localhost:4200/user/confirmemail/?userId=9bc9a474-d10c-438b-8953-1c32fc57551b&token=Q2ZESjhPRkF6d3BPQ1E5TmtLbWplTnlIZ3g3bzJEVEZQZDQ3MFNSblExaWxBTWh3MmdSMWl2ZkU3djZxcWR3bmY4OFMwd2l6STZOY3VMR2FoZ1ZCM28rWFo1YlJhejhOTE5pamFFdGRETTNiNGttT0lOQ2dZVmdLRVlRdWlKRmtQMVpEWHE0b2t2NVBQZTZ0bkR3cUdrb3JiMWRIQUpRUE5pMTZjTW96YUdJcVZBUUxPSG5pd3NDU3BDeTBNREMvMTVyTlhUNUpCL2tRZTJWMjJlTzVHZ1dDbEh5VWNESGNsNlVTQkpXZ1FJaThDTk1kcUovcmdtV0ZEdEQza2hXR1p6V0pEdz09

Post method, which verify email:

        [HttpPost("confirmEmail/{userId}")]
        public async Task<IActionResult> ConfirmEmail(string userId, [FromBody]string token)
        {
            var codeDecodedBytes = WebEncoders.Base64UrlDecode(token);
            var codeDecoded = Encoding.UTF8.GetString(codeDecodedBytes);
            var user = await _userManager.FindByIdAsync(userId);
            var result = await _userManager.ConfirmEmailAsync(user, codeDecoded);
            return Ok(result);
        }

It works fine in postman:

Error in Angular project:

Getting userId and token in Angular

  userId: string;
  token: string;
  constructor(private activatedRoute: ActivatedRoute, private authService: AuthService) {
    this.activatedRoute.queryParams.subscribe(params => {
          this.userId = params['userId'];
          this.token = params['token'];
      });
  }

  ngOnInit(): void {
    this.confirmEmail();
  }

  confirmEmail(){
    this.authService.confirmEmail(this.userId, this.token).subscribe(data => { console.log("success")});
  }

(AuthService) Sending data to backend

  confirmEmail(userId: string, token: string){
    console.log(userId);
    console.log(token);
    return this.http.post(this.authUrl + `confirmemail/${userId}`, token);
  }

Body:
Try to set Content-Type to json type:

confirmEmail(userId: string, token: string) {
    const body = JSON.stringify(token);
    const options = {
      headers: new HttpHeaders().append('Content-Type', 'application/json')
    };

    return this.http.post(this.authUrl + `confirmemail/${userId}`, body, options)
          .pipe(
              map(res => res)
            , catchError(this.handleError())
          );
}


问:
Are dimension tables and domain tables the same thing?
I think I know what a domain table is (it basically contains all the possible values that some other column can contain), and I've looked up dimension table in Wikipedia. Unfortunately, I'm having a hard time understanding the description they have there, because they explain it in terms of another piece of jargon: "fact table", which is explained to "consists of the measurements, metrics or facts of a business process." To me, that's very tautological, which is not helpful. Can someone explain this in plain English?

答:
Fact Tables and Dimension Tables, taken together, make up a Star Schema.  A Star Schema is a representation, in SQL tables, of a Multidimensional data model.  A multidimensional data model stores statistics,  "facts", as values in a multidimensional space, where the "location" in each dimension establishes part of the context for the fact.   The multidimensional data model was developed in the context of advancing the concept of data warehousing.

Dimension tables provide a key to each dimension, and attributes relevant to that dimension.

An MDDB can be stored in a data cube specially built for that purpose instead of using an SQL (relational) database.  Cognos is one vendor that has its own data cube product out there.  There are some advantages to using an SQL database and a star schema, over using a special purpose data cube product.  There are other advantages to using a data cube product.  Sometimes the advantages to the SQL plus Star schema approach outweigh the advantages of a data cube product.

Some of the advantages obtained by normalization can be obtained by designing a Snowflake Schema instead of a Star schema.  However, neither star schema nor snowflake schema are going to be free from update anomalies.  They are generally used in data warehousing or reporting databases,  and copying data from an operational DB into one of these databases is something of a programming challenge.  There are tools sold for this purpose.


问:
NameError when starting NeoVim while Python virtual environment is active
When I launch NeoVim while a virtualenv is activated, I get the following error:

```<code>Error detected while processing function provider#python3#Call:
line   18:
Error invoking 'python_execute' on channel 3 (python3-script-host):
Traceback (most recent call last):
  File "<string>", line 6, in <module>
NameError: name 'execfile' is not defined
Press ENTER or type command to continue
</code>```

This is what I see when I run :checkhealth provider:

```<code>
health#provider#check
========================================================================
## Clipboard (optional)
  - OK: Clipboard tool found: pbcopy

## Python 2 provider (optional)
  - INFO: pyenv: Path: /usr/local/Cellar/pyenv/1.2.16/libexec/pyenv
  - INFO: pyenv: $PYENV_ROOT is not set. Infer from `pyenv root`.
  - INFO: pyenv: Root: /Users/myname/.pyenv
  - INFO: Using: g:python_host_prog = "~/.pyenv/versions/2.7.16/envs/neovim-python2-venv/bin/python"
  - INFO: $VIRTUAL_ENV matches executable
  - INFO: Executable: /Users/myname/.pyenv/versions/2.7.16/envs/neovim-python2-venv/bin/python
  - INFO: Python version: 2.7.16
  - INFO: pynvim version: 0.4.1
  - OK: Latest pynvim is installed.

## Python 3 provider (optional)
  - INFO: pyenv: Path: /usr/local/Cellar/pyenv/1.2.16/libexec/pyenv
  - INFO: pyenv: $PYENV_ROOT is not set. Infer from `pyenv root`.
  - INFO: pyenv: Root: /Users/myname/.pyenv
  - INFO: Using: g:python3_host_prog = "~/.virtualenvs/neovim-python3-venv/bin/python3"
  - WARNING: $VIRTUAL_ENV exists but appears to be inactive. This could lead to unexpected results.
    - ADVICE:
      - If you are using Zsh, see: http://vi.stackexchange.com/a/7654
  - INFO: Executable: /Users/myname/.virtualenvs/neovim-python3-venv/bin/python3
  - INFO: Python version: 3.8.0
  - INFO: pynvim version: 0.4.1
  - OK: Latest pynvim is installed.
</code>```

I don't use Zsh, I use Bash. An attempt to use the snippet from the linked answer in .bashrc did not change the situation.

I do not get the error when not launching NeoVim while a virtualenv is activated.

Removing all Vim plugins did not get rid of the error.

I have tried this with virtualenvs that use both Python 2 and Python 3. The error is the same.

答:
I believe you have some python code in your init.vim before the line g:python3_host_prog = "~/.virtualenvs/neovim-python3-venv/bin/python3" and while you are launching nvim this code is trying to get executed before knowing which interpreter to use.
(At least I had the same problem fighting that half a day)

So just place the mentioned line before the python code.

Body:
When I launch NeoVim while a virtualenv is activated, I get the following error:

Error detected while processing function provider#python3#Call:
line   18:
Error invoking 'python_execute' on channel 3 (python3-script-host):
Traceback (most recent call last):
  File "<string>", line 6, in <module>
NameError: name 'execfile' is not defined
Press ENTER or type command to continue

This is what I see when I run :checkhealth provider:

health#provider#check
========================================================================
## Clipboard (optional)
  - OK: Clipboard tool found: pbcopy

## Python 2 provider (optional)
  - INFO: pyenv: Path: /usr/local/Cellar/pyenv/1.2.16/libexec/pyenv
  - INFO: pyenv: $PYENV_ROOT is not set. Infer from `pyenv root`.
  - INFO: pyenv: Root: /Users/myname/.pyenv
  - INFO: Using: g:python_host_prog = "~/.pyenv/versions/2.7.16/envs/neovim-python2-venv/bin/python"
  - INFO: $VIRTUAL_ENV matches executable
  - INFO: Executable: /Users/myname/.pyenv/versions/2.7.16/envs/neovim-python2-venv/bin/python
  - INFO: Python version: 2.7.16
  - INFO: pynvim version: 0.4.1
  - OK: Latest pynvim is installed.

## Python 3 provider (optional)
  - INFO: pyenv: Path: /usr/local/Cellar/pyenv/1.2.16/libexec/pyenv
  - INFO: pyenv: $PYENV_ROOT is not set. Infer from `pyenv root`.
  - INFO: pyenv: Root: /Users/myname/.pyenv
  - INFO: Using: g:python3_host_prog = "~/.virtualenvs/neovim-python3-venv/bin/python3"
  - WARNING: $VIRTUAL_ENV exists but appears to be inactive. This could lead to unexpected results.
    - ADVICE:
      - If you are using Zsh, see: http://vi.stackexchange.com/a/7654
  - INFO: Executable: /Users/myname/.virtualenvs/neovim-python3-venv/bin/python3
  - INFO: Python version: 3.8.0
  - INFO: pynvim version: 0.4.1
  - OK: Latest pynvim is installed.

I don't use Zsh, I use Bash. An attempt to use the snippet from the linked answer in .bashrc did not change the situation.

I do not get the error when not launching NeoVim while a virtualenv is activated.

Removing all Vim plugins did not get rid of the error.

I have tried this with virtualenvs that use both Python 2 and Python 3. The error is the same.