问:
Why are field initializers of a derived class are executed before base classes's initializers
constructors are executed in the order from top to bottom I.E. base's first followed by derived one. This arangement is based on an important OOP assurance that an object (base here) must always be initialized before it can be used (here in derived class's constructor).

I'm wondering why field-initializers do not follow this principle in C#? Am I missing something here?

I've come across a usefulness of this principle with field-initializers as well. I have a base class with a property returning Identity object. Every derived class has its own repository field which I have been initializing using field-initializer (using default constructor). Recently I've decided that the repository class must also be provided with Identity object so I introduced an extra argument in the repository constructor. But I'm stuck to find out:

```<code>public class ForumController : AppControllerBase
{
        ForumRepository repository = new ForumRepository(Identity);
    // Above won't compile since Identity is in the base class.

   // ... Action methods.
}
</code>```

Now I'm left with only one option that is to plump my every controller with a default constructor for only to do the job of initializing of repository object with Identity.

答:
Field Initializers are not meant to be a replacement for constructors.

As per MSDN documentation all field initializers are executed before constructors. However a restriction on  the Field Initializer is that they cannot refer to other instance fields. ( http://msdn.microsoft.com/en-us/library/ms173118(v=vs.80).aspx)

The restriction is due to the fact that there is no way to identify the right order and the dependencies to execute the Field Initializers at a compiler level.

You would have to write a default constructor to achieve what you want. You could possibly try with a static field, however; it is a bad practice and might not even suit your design.

Edit for clarifying question asked in comment:

As far as a derived class is concerned, the base class fields look the same whether they are initialized through the initializer or the constructor. This information cannot be supplied to the child classes as this would mean exposing the implementation of the base class (which is strictly private to the base class).

This implies that the derived class Initializer has no way to figure out if all the base class fields have been initialized before accessing them. Hence the behavior is not allowed.

Body:
constructors are executed in the order from top to bottom I.E. base's first followed by derived one. This arangement is based on an important OOP assurance that an object (base here) must always be initialized before it can be used (here in derived class's constructor).

I'm wondering why field-initializers do not follow this principle in C#? Am I missing something here?

I've come across a usefulness of this principle with field-initializers as well. I have a base class with a property returning Identity object. Every derived class has its own repository field which I have been initializing using field-initializer (using default constructor). Recently I've decided that the repository class must also be provided with Identity object so I introduced an extra argument in the repository constructor. But I'm stuck to find out:

public class ForumController : AppControllerBase
{
        ForumRepository repository = new ForumRepository(Identity);
    // Above won't compile since Identity is in the base class.

   // ... Action methods.
}

Now I'm left with only one option that is to plump my every controller with a default constructor for only to do the job of initializing of repository object with Identity.


来源: stackexchange

问:
vue transition components disappear during animation
I am using Vue Transition when navigating between pages and found a problem. I have a table, components inside it, and when I start to make a transition to a new page, the animation starts and some of the components from the table disappear, the table re-renders and blinks before completing the transition. For a long time I could not understand what the problem was, until I myself reproduced it in the codepan by the link https://codepen.io/gleb-shalajkin/pen/PoGgejp. Go to the table page by clicking on the button, and then return to the main page and pay attention to the v-chip. It will disappear from you during the transition. The problem is that for the table I use the template of a certain field, and inside this template I use another template, only this time the v-tooltip. This problem occurs due to the fact that there is another template inside the template. So far, I have no idea how to solve it. I would be grateful for any help.

Code from codepan:

const Main = {
    template: '#contacts'
}

const ChildComponent = {
  template: "#childComponent"
}

const Table = {
  components: {
    'child-component': ChildComponent
  },
  data () {
    return {
        headers: [
          {
            text: 'Dessert (100g serving)',
            align: 'start',
            value: 'name',
          },
          { text: 'Calories', value: 'calories' },
          { text: 'Fat (g)', value: 'fat' },
          { text: 'Carbs (g)', value: 'carbs' },
          { text: 'Protein (g)', value: 'protein' },
          { text: 'Iron (%)', value: 'iron' },
        ],
        items: [
          {
            name: 'Frozen Yogurt',
            calories: 159,
            fat: 6.0,
            carbs: 24,
            protein: 4.0,
            iron: '1%',
          },
                    {
            name: 'Frozen Yogurt',
            calories: 159,
            fat: 6.0,
            carbs: 24,
            protein: 4.0,
            iron: '1%',
          },
                    {
            name: 'Frozen Yogurt',
            calories: 159,
            fat: 6.0,
            carbs: 24,
            protein: 4.0,
            iron: '1%',
          }
        ],
      }
  },
  computed: {
      vTable () {
        return {
          options: {
            itemsPerPage: 15
          },
          headers: this.headers,
          items: this.items,
          footerProps: {
            itemsPerPageText: 'Кол-во элементов на странице',
            itemsPerPageOptions: [15, 30, 50, 100]
          },
          noDataText: 'Нет данных',
          loadingText: 'Идет загрузка...'
        }
    }
  },
  template: "#table"
}

const routes = [
    {path: '/', name: 'Main', component: Main},
    {path: '/table', name: 'Table', component: Table }
]

const router = new VueRouter({
    routes
})

new Vue({
  vuetify: new Vuetify(),
    router
}).$mount('#app');```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.fade-enter-active,
.fade-leave-active {
  transition-duration: 1.2s;
  transition-property: opacity;
}

.fade-enter,
.fade-leave-active {
  opacity: 0
}</code>```

<link href="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.min.css" rel="stylesheet"/>
<link href="https://cdn.jsdelivr.net/npm/@mdi/font@3.x/css/materialdesignicons.min.css" rel="stylesheet"/>

<v-app id="app">
  <v-main>
     <keep-alive>
      <transition
          name="fade"
          mode="out-in"
      >
        <router-view></router-view>
      </transition>
    </keep-alive>
  </v-main>
</v-app>```

答: The problem is in vuetify version. Apparently it was a bug and they fixed it. After version 2.6.3 everything works great.</p>

ContentLicense: CC BY-SA 4.0

Body:
I am using Vue Transition when navigating between pages and found a problem. I have a table, components inside it, and when I start to make a transition to a new page, the animation starts and some of the components from the table disappear, the table re-renders and blinks before completing the transition. For a long time I could not understand what the problem was, until I myself reproduced it in the codepan by the link https://codepen.io/gleb-shalajkin/pen/PoGgejp. Go to the table page by clicking on the button, and then return to the main page and pay attention to the v-chip. It will disappear from you during the transition. The problem is that for the table I use the template of a certain field, and inside this template I use another template, only this time the v-tooltip. This problem occurs due to the fact that there is another template inside the template. So far, I have no idea how to solve it. I would be grateful for any help.

Code from codepan:

const Main = {
    template: '#contacts'
}

const ChildComponent = {
  template: "#childComponent"
}

const Table = {
  components: {
    'child-component': ChildComponent
  },
  data () {
    return {
        headers: [
          {
            text: 'Dessert (100g serving)',
            align: 'start',
            value: 'name',
          },
          { text: 'Calories', value: 'calories' },
          { text: 'Fat (g)', value: 'fat' },
          { text: 'Carbs (g)', value: 'carbs' },
          { text: 'Protein (g)', value: 'protein' },
          { text: 'Iron (%)', value: 'iron' },
        ],
        items: [
          {
            name: 'Frozen Yogurt',
            calories: 159,
            fat: 6.0,
            carbs: 24,
            protein: 4.0,
            iron: '1%',
          },
                    {
            name: 'Frozen Yogurt',
            calories: 159,
            fat: 6.0,
            carbs: 24,
            protein: 4.0,
            iron: '1%',
          },
                    {
            name: 'Frozen Yogurt',
            calories: 159,
            fat: 6.0,
            carbs: 24,
            protein: 4.0,
            iron: '1%',
          }
        ],
      }
  },
  computed: {
      vTable () {
        return {
          options: {
            itemsPerPage: 15
          },
          headers: this.headers,
          items: this.items,
          footerProps: {
            itemsPerPageText: 'Кол-во элементов на странице',
            itemsPerPageOptions: [15, 30, 50, 100]
          },
          noDataText: 'Нет данных',
          loadingText: 'Идет загрузка...'
        }
    }
  },
  template: "#table"
}

const routes = [
    {path: '/', name: 'Main', component: Main},
    {path: '/table', name: 'Table', component: Table }
]

const router = new VueRouter({
    routes
})

new Vue({
  vuetify: new Vuetify(),
    router
}).$mount('#app');

.fade-enter-active,
.fade-leave-active {
  transition-duration: 1.2s;
  transition-property: opacity;
}

.fade-enter,
.fade-leave-active {
  opacity: 0
}

<link href="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.min.css" rel="stylesheet"/>
<link href="https://cdn.jsdelivr.net/npm/@mdi/font@3.x/css/materialdesignicons.min.css" rel="stylesheet"/>

<v-app id="app">
  <v-main>
     <keep-alive>
      <transition
          name="fade"
          mode="out-in"
      >
        <router-view></router-view>
      </transition>
    </keep-alive>
  </v-main>
</v-app>


问:
How to implement BigQuery for the Google EKM?
I want to implement BigQuery which interacts with an external key management using HYOK function.

I have not found any guides about the configuration of BigQuery with EKM (and then using HYOK) but just the configuration of it with the CMEK (that use BYOK).

Can someone here help me?

答:
To clarify some of the terminology in your question,

HYOK = Hold your own key = The ability to use keys outside GCP from within GCP

Cloud EKM = Cloud external key manager = Cloud EKM is the service that GCP uses to implement HYOK.  Cloud EKM is used through the Cloud KMS API.  EKM keys have the EXTERNAL protection level in Cloud KMS.

CMEK = Customer managed encryption keys = The ability to use keys in Cloud KMS to protect data at rest in other GCP services (such as BigQuery).

Answering your question directly, this guide applies equally to all keys available through Cloud KMS, including Cloud EKM keys.  The difference for using a Cloud EKM key as opposed to one stored inside GCP is in how you set up the key in the Cloud KMS API (see this documentation).  Once it is set up, the Cloud EKM keys work the same as other protection levels.


问:
How to compare vector with array?
I would like to compare vector with an array. Elements in vector and in array are in different order, unsorted and can duplicated. E.g.

Below are the same:

```<code>vector<int> lvector = {5,7,3,1,2,7};
int larray[6] = {3,5,1,7,2,7}
</code>```

Below, not the same:

```<code>vector<int> lvector = {5,7,3,1,2,7,5};
int larray[7] = {3,5,1,7,2,7,3}
</code>```

And something like this is also not the same:

```<code>vector<int> lvector = {1,1,1,1,2,2};
int larray[6] = {1,1,1,1,1,2}
</code>```

Now I need to check if vector and array have got the same elements. I can't modify the vector and the array, but I can create a new container and copy the element from vector and array to this new container and then copare them. I am asking about this, because I would like to do this in en efficient way. Thanks.

答:
Here is template function to compare vector with array:

```<code>#include <array>
#include <algorithm>
#include <vector>

template <class T, std::size_t N>
bool equal(const std::vector<T>& v, const std::array<T, N>& a)
{
    if (v.size() != N)
        return false;

    return std::equal(v.begin(), v.end(), a.begin());
}
</code>```

Usage example:

```<code>std::vector<int> v = {1, 2, 3};
std::array<int, 4> a = {1, 2, 3, 4};

bool eq = equal(v, a);
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to compare vector with array?

Body:
I would like to compare vector with an array. Elements in vector and in array are in different order, unsorted and can duplicated. E.g.

Below are the same:

vector<int> lvector = {5,7,3,1,2,7};
int larray[6] = {3,5,1,7,2,7}

Below, not the same:

vector<int> lvector = {5,7,3,1,2,7,5};
int larray[7] = {3,5,1,7,2,7,3}

And something like this is also not the same:

vector<int> lvector = {1,1,1,1,2,2};
int larray[6] = {1,1,1,1,1,2}

Now I need to check if vector and array have got the same elements. I can't modify the vector and the array, but I can create a new container and copy the element from vector and array to this new container and then copare them. I am asking about this, because I would like to do this in en efficient way. Thanks.

Body:
Here is template function to compare vector with array:

#include <array>
#include <algorithm>
#include <vector>

template <class T, std::size_t N>
bool equal(const std::vector<T>& v, const std::array<T, N>& a)
{
    if (v.size() != N)
        return false;

    return std::equal(v.begin(), v.end(), a.begin());
}

Usage example:

std::vector<int> v = {1, 2, 3};
std::array<int, 4> a = {1, 2, 3, 4};

bool eq = equal(v, a);


问:
Remote Installation of "Remotely" app via PowerShell
My organization uses a software called Remotely for remote access to some of our users devices. I'm trying to find a way to install the software remotely via PowerShell. I have the installer file copied locally on the root of the C drive on each machine. Here is what I've tried.

```<code>enterPS C:\Users\USER> Invoke-Command -ComputerName REMOTEPC -ScriptBlock {
Start-Process C:\Remotely_Installer.exe -install -quiet -organizationid "IDSTRING" -serverurl "https://remotely.CORP.com"
}
</code>```

Running this command returns a "Paramater cannot be found that matches the names "install." This is what is on Remotely's website but it doesn't specify anything for remote installation via PowerShell.

```<code>Remotely_Installer.exe -install -quiet -organizationid "0b3d706b-9c5d-41e6-8ae9-5720d16324e6" -serverurl "https://remotely.mytechshop.com"
</code>```

Ideally I'd be able to have a simple script where I can have the user copy the file to their C drive and then I can run the script, target their device, and have it show up in the remote management portal.

答:
Does this work?  Start-process isn't needed that often, except to wait for something started in the background.  This assumes the installer is already on the remote computer.</p>
```<code># $s = new-pssession remotepc
# copy-item C:\Remotely_Installer.exe c:\ -tosession $s  # slow
Invoke-Command REMOTEPC {
  C:\Remotely_Installer.exe -install -quiet -organizationid IDSTRING -serverurl https://remotely.CORP.com
}
</code>```

Body:
My organization uses a software called Remotely for remote access to some of our users devices. I'm trying to find a way to install the software remotely via PowerShell. I have the installer file copied locally on the root of the C drive on each machine. Here is what I've tried.

enterPS C:\Users\USER> Invoke-Command -ComputerName REMOTEPC -ScriptBlock {
Start-Process C:\Remotely_Installer.exe -install -quiet -organizationid "IDSTRING" -serverurl "https://remotely.CORP.com"
}

Running this command returns a "Paramater cannot be found that matches the names "install." This is what is on Remotely's website but it doesn't specify anything for remote installation via PowerShell.

Remotely_Installer.exe -install -quiet -organizationid "0b3d706b-9c5d-41e6-8ae9-5720d16324e6" -serverurl "https://remotely.mytechshop.com"

Ideally I'd be able to have a simple script where I can have the user copy the file to their C drive and then I can run the script, target their device, and have it show up in the remote management portal.

Body:
Does this work?  Start-process isn't needed that often, except to wait for something started in the background.  This assumes the installer is already on the remote computer.

# $s = new-pssession remotepc
# copy-item C:\Remotely_Installer.exe c:\ -tosession $s  # slow
Invoke-Command REMOTEPC {
  C:\Remotely_Installer.exe -install -quiet -organizationid IDSTRING -serverurl https://remotely.CORP.com
}


问:
How to handle multiple instances of input to one field
I want to add a line in a multiline textbox after every information that the user enters in the TextBox in Windows form. I wont be able to determine the point to draw line as I wont know how long the user will enter information. So I am thinking of adding a  string "_______" after a button click in the code. Is there a better way? </p>

答: If the user is going to be required to click a button to confirm a single entry then I don't think you should continue to store the information in the same text box & provide a visual separation with a bunch of dashes, rather move the text entered from the input to a more formatted display (set of controls).  Then the display will be separated from input. You could them allow the user to select individual input in the display to modify entry providing a nice user experience.</p>

OwnerDisplayName: LearnOneTime

LastEditorDisplayName: Keltex

OwnerDisplayName: Quintin Robinson

ContentLicense: CC BY-SA 2.5


问:
Can't find a link button in a repeater
I have a link button in a repeater with a couple of databound fields. I'm trying to get to where I can set the buttons onClientClick after the databinding however everytime I try to access the link button I keep getting Null returned.

I've looked through every single question involving repeaters and controls here and haven't been able to figure it out.

The .aspx

```<code>    <asp:Repeater ID="DailyRepeater" OnItemCommand="DailyRepeater_ItemCommand" runat="server">
                    <HeaderTemplate>
                        <tr>
                            <td class="coltitle">
                                Time
                            </td>
                            <td class="coltitle">
                                Activity
                            </td>
                            <td class="coltitle">
                                Hours
                            </td>
                        </tr>
                    </HeaderTemplate>
                    <ItemTemplate>
                        <tr class="evenrow">
                            <td>
                                <%# Eval("StartTime","{0:HH:mm}") %>-<%# Eval("EndTime","{0:HH:mm}") %>
                            </td>
                            <td>
                                <%# Eval("Description") %>
                            </td>
                            <td>
                                <%# Eval("Hours","{0:0.0}") %>
                            </td>
                            <td>
                                   <asp:LinkButton runat="server" CausesValidation="false" ID="editbutton" Text="Edit">Edit</asp:LinkButton>
                            </td>
                        </tr>
                    </ItemTemplate>
</code>```

The .aspx.cs

```<code>    protected void DailyRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        LinkButton myButton = (LinkButton)e.Item.FindControl("editbutton");
        myButton.OnClientClick = (popupWindow.GetTargetPopupCode("URL");
    }
</code>```

From what I've read, I should have been able to get to the button using the RepeaterItemEventargs. However I can't seem to find it here. The other thing I thought of was that the binding wasn't happening by the time this happened (which made no sense to be as this is a databound event) but for some reason e is coming back e.Item has a dataItem of null and an itemIndex of -1...

I'm just really confused and lost any help would be greatly appreciated.

Thanks!

答:
Why not setting the property on the sender object, like this:

```<code>sender.OnClientClick = //whatever//
</code>```

Title: Can't find a link button in a repeater

Body:
I have a link button in a repeater with a couple of databound fields. I'm trying to get to where I can set the buttons onClientClick after the databinding however everytime I try to access the link button I keep getting Null returned.

I've looked through every single question involving repeaters and controls here and haven't been able to figure it out.

The .aspx

    <asp:Repeater ID="DailyRepeater" OnItemCommand="DailyRepeater_ItemCommand" runat="server">
                    <HeaderTemplate>

                                Time

                                Activity

                                Hours

                    </HeaderTemplate>
                    <ItemTemplate>

                                <%# Eval("StartTime","{0:HH:mm}") %>-<%# Eval("EndTime","{0:HH:mm}") %>

                                <%# Eval("Description") %>

                                <%# Eval("Hours","{0:0.0}") %>

                                   <asp:LinkButton runat="server" CausesValidation="false" ID="editbutton" Text="Edit">Edit</asp:LinkButton>

                    </ItemTemplate>

The .aspx.cs

    protected void DailyRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        LinkButton myButton = (LinkButton)e.Item.FindControl("editbutton");
        myButton.OnClientClick = (popupWindow.GetTargetPopupCode("URL");
    }

From what I've read, I should have been able to get to the button using the RepeaterItemEventargs. However I can't seem to find it here. The other thing I thought of was that the binding wasn't happening by the time this happened (which made no sense to be as this is a databound event) but for some reason e is coming back e.Item has a dataItem of null and an itemIndex of -1...

I'm just really confused and lost any help would be greatly appreciated.

Thanks!

Body:
Why not setting the property on the sender object, like this:

sender.OnClientClick = //whatever//


问:
vibrator.cancel not called in OnDestroy of service class
AlarmService.kt

```<code>class AlarmService : Service() {
private var vibrator: Vibrator? = null

override fun onCreate() {
    super.onCreate()
    vibrator = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
        val vibratorManager = this.getSystemService(Context.VIBRATOR_MANAGER_SERVICE) as VibratorManager
        vibratorManager.defaultVibrator
    } else {
        @Suppress("DEPRECATION")
        getSystemService(VIBRATOR_SERVICE) as Vibrator
    }
}

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int):
Int {
  val pattern = longArrayOf(1500, 800, 800, 800)
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            vibrator?.vibrate(VibrationEffect.createWaveform(pattern, 0))
  } else {
    @Suppress("DEPRECATION")
    vibrator?.vibrate(pattern, 0)
 }
}

 override fun onDestroy() {
    super.onDestroy()
    vibrator?.cancel() // ---< This is not called
    Log.e("served", "Service Stopped") // ---< This is called and shows in logcat
  }

}
</code>```

In My BroadcastRecciever,

```<code> private fun snoozeAlarm(context: Context?, intent: Intent?){
 val intentService = Intent(context.applicationContext,
 AlarmService::class.java)
    context.applicationContext.stopService(intentService)

 }
</code>```

As you can see, vibrator?.cancel() is not called when I tried to stop the service class from broadcastReciever.

The notification in my service is cleared but phone keeps vibrating.

Tested with emulator (pixel 2) api 31

UPDATE

It appears, this is only an issue with android studio emulator using bumblebee

When I ran with a real device, it worked.

答:
Try swapping the order of the operations in Your onDestroy method. Most importantly put the super call at the end of the method:

override fun onDestroy() {
    vibrator?.cancel()
    Log.e("served", "Service Stopped")

    super.onDestroy()
}
```

Freeing up resources and uninitializing any child classes probably should be done on a fully functional object and since Your service was previously in the destruction process already (because of calling super.onDestroy() before your own operations) it might have had some impact on the vibrator?.cancel() code completion.

Body:
AlarmService.kt

class AlarmService : Service() {
private var vibrator: Vibrator? = null

override fun onCreate() {
    super.onCreate()
    vibrator = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
        val vibratorManager = this.getSystemService(Context.VIBRATOR_MANAGER_SERVICE) as VibratorManager
        vibratorManager.defaultVibrator
    } else {
        @Suppress("DEPRECATION")
        getSystemService(VIBRATOR_SERVICE) as Vibrator
    }
}

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int):
Int {
  val pattern = longArrayOf(1500, 800, 800, 800)
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            vibrator?.vibrate(VibrationEffect.createWaveform(pattern, 0))
  } else {
    @Suppress("DEPRECATION")
    vibrator?.vibrate(pattern, 0)
 }
}

 override fun onDestroy() {
    super.onDestroy()
    vibrator?.cancel() // ---< This is not called
    Log.e("served", "Service Stopped") // ---< This is called and shows in logcat
  }

}

In My BroadcastRecciever,

 private fun snoozeAlarm(context: Context?, intent: Intent?){
 val intentService = Intent(context.applicationContext,
 AlarmService::class.java)
    context.applicationContext.stopService(intentService)

 }

As you can see, vibrator?.cancel() is not called when I tried to stop the service class from broadcastReciever.

The notification in my service is cleared but phone keeps vibrating.

Tested with emulator (pixel 2) api 31

UPDATE

It appears, this is only an issue with android studio emulator using bumblebee

When I ran with a real device, it worked.

Body:
Try swapping the order of the operations in Your onDestroy method. Most importantly put the super call at the end of the method:

override fun onDestroy() {
    vibrator?.cancel()
    Log.e("served", "Service Stopped")

    super.onDestroy()
}

Freeing up resources and uninitializing any child classes probably should be done on a fully functional object and since Your service was previously in the destruction process already (because of calling super.onDestroy() before your own operations) it might have had some impact on the vibrator?.cancel() code completion.


问:
terraform cant access module output
In Terraform using this cognito module

https://github.com/lgallard/terraform-aws-cognito-user-pool/blob/master/outputs.tf#L34

I'm not able to access the Output Variable

```<code>output "domain_cloudfront_distribution_arn" {
  description = "The ARN of the CloudFront distribution"
  value       = var.enabled ? join("", module.aws_cognito_user_pool_stardust.domain.*.cloudfront_distribution_arn) : null
}
</code>```

Throws me this error

```<code>❯ terraform apply  -var-file fixtures.us-east-1.tfvars   -auto-approve
Acquiring state lock. This may take a few moments...
module.aws_cognito_user_pool_stardust.aws_cognito_user_pool.pool[0]: Refreshing state... [id=us-east-1_wEWpH9pmy]
module.aws_cognito_user_pool_stardust.aws_cognito_user_pool_domain.domain[0]: Refreshing state... [id=stardust-admin-dashboard-dev]
module.aws_cognito_user_pool_stardust.aws_cognito_identity_provider.identity_provider[0]: Refreshing state... [id=us-east-1_wEWpH9pmy:Google]
module.aws_cognito_user_pool_stardust.aws_cognito_user_group.main[1]: Refreshing state... [id=us-east-1_wEWpH9pmy/players]
module.aws_cognito_user_pool_stardust.aws_cognito_user_group.main[0]: Refreshing state... [id=us-east-1_wEWpH9pmy/owners]
module.aws_cognito_user_pool_stardust.aws_cognito_user_pool_client.client[1]: Refreshing state... [id=kifo1avcbbd2hn7phraa1fbca]
module.aws_cognito_user_pool_stardust.aws_cognito_user_pool_client.client[0]: Refreshing state... [id=4dpv821e9biuve5ri9ka319ecr]
╷
│ Error: Unsupported attribute
│
│   on outputs.tf line 18, in output "domain_cloudfront_distribution_arn":
│   18:   value       = var.enabled ? join("", module.aws_cognito_user_pool_stardust.domain.*.cloudfront_distribution_arn) : null
│     ├────────────────
│     │ module.aws_cognito_user_pool_stardust is object with 14 attributes
│
│ This object does not have an attribute named "domain".
╵
Releasing state lock. This may take a few moments...
</code>```

This is my main.tf file

```<code>module "aws_cognito_user_pool_stardust" {

  source  = "lgallard/cognito-user-pool/aws"
  version = "0.14.2"
  .....

}
</code>```

答:
This is definition inside the module:

```<code>output "domain_cloudfront_distribution_arn" {
  description = "The ARN of the CloudFront distribution"
  value       = var.enabled ? join("", aws_cognito_user_pool_domain.domain.*.cloudfront_distribution_arn) : null
}
</code>```

What you want to do is just to pass it through as an output from the main module, therefore on your side you need to define:

```<code>output "domain_cloudfront_distribution_arn" {
  description = "The ARN of the CloudFront distribution"
  value       = module.aws_cognito_user_pool_stardust.domain_cloudfront_distribution_arn
}
</code>```

Title: terraform cant access module output

Body:
In Terraform using this cognito module

https://github.com/lgallard/terraform-aws-cognito-user-pool/blob/master/outputs.tf#L34

I'm not able to access the Output Variable

output "domain_cloudfront_distribution_arn" {
  description = "The ARN of the CloudFront distribution"
  value       = var.enabled ? join("", module.aws_cognito_user_pool_stardust.domain.*.cloudfront_distribution_arn) : null
}

Throws me this error

❯ terraform apply  -var-file fixtures.us-east-1.tfvars   -auto-approve
Acquiring state lock. This may take a few moments...
module.aws_cognito_user_pool_stardust.aws_cognito_user_pool.pool[0]: Refreshing state... [id=us-east-1_wEWpH9pmy]
module.aws_cognito_user_pool_stardust.aws_cognito_user_pool_domain.domain[0]: Refreshing state... [id=stardust-admin-dashboard-dev]
module.aws_cognito_user_pool_stardust.aws_cognito_identity_provider.identity_provider[0]: Refreshing state... [id=us-east-1_wEWpH9pmy:Google]
module.aws_cognito_user_pool_stardust.aws_cognito_user_group.main[1]: Refreshing state... [id=us-east-1_wEWpH9pmy/players]
module.aws_cognito_user_pool_stardust.aws_cognito_user_group.main[0]: Refreshing state... [id=us-east-1_wEWpH9pmy/owners]
module.aws_cognito_user_pool_stardust.aws_cognito_user_pool_client.client[1]: Refreshing state... [id=kifo1avcbbd2hn7phraa1fbca]
module.aws_cognito_user_pool_stardust.aws_cognito_user_pool_client.client[0]: Refreshing state... [id=4dpv821e9biuve5ri9ka319ecr]
╷
│ Error: Unsupported attribute
│
│   on outputs.tf line 18, in output "domain_cloudfront_distribution_arn":
│   18:   value       = var.enabled ? join("", module.aws_cognito_user_pool_stardust.domain.*.cloudfront_distribution_arn) : null
│     ├────────────────
│     │ module.aws_cognito_user_pool_stardust is object with 14 attributes
│
│ This object does not have an attribute named "domain".
╵
Releasing state lock. This may take a few moments...

This is my main.tf file

module "aws_cognito_user_pool_stardust" {

  source  = "lgallard/cognito-user-pool/aws"
  version = "0.14.2"
  .....

}

Body:
This is definition inside the module:

output "domain_cloudfront_distribution_arn" {
  description = "The ARN of the CloudFront distribution"
  value       = var.enabled ? join("", aws_cognito_user_pool_domain.domain.*.cloudfront_distribution_arn) : null
}

What you want to do is just to pass it through as an output from the main module, therefore on your side you need to define:

output "domain_cloudfront_distribution_arn" {
  description = "The ARN of the CloudFront distribution"
  value       = module.aws_cognito_user_pool_stardust.domain_cloudfront_distribution_arn
}


问:
Why user data is null in props in React Js?
I create multi step register that user create in first step and then send OTP code in last step user set username and password. In last step when I use props show me user is null but in react dev tools user already exist. This Two picture:

This is my reduser code :

```<code>    import {
    USER_LOADED,
    USER_LOADING,
    AUTH_ERROR,
    LOGIN_SUCCESS,
    LOGIN_FAIL,
    LOGOUT_SUCCESS,
    REGISTER_SUCCESS,
    REGISTER_FAIL,
    VERIFY_CODE,
    SET_PASS,
    SET_PASS_FAIL,
    VERIFY_FAIL
} from "../actions/types";

const initialState = {
    token: localStorage.getItem("token"),
    isAuthenticated: null,
    isLoading: false,
    verifyCode : null,
    setPass : null,
    user: null,
};

export default function (state = initialState, action) {
    switch (action.type) {
        case USER_LOADING:
            return {
                ...state,
                isLoading: true,

            };
        case USER_LOADED:
            return {
                ...state,
                isAuthenticated: true,
                isLoading: false,
                verifyCode: true,
                user: action.payload,
            };
        case LOGIN_SUCCESS:
        case REGISTER_SUCCESS:
            localStorage.setItem("token", action.payload.token);
            return {
                ...state,
                ...action.payload,
                isAuthenticated: true,
                isLoading: false,
                verifyCode: false
            };
        case SET_PASS_FAIL:
        case AUTH_ERROR:
        case LOGIN_FAIL:
        case VERIFY_FAIL:
            return {
                ...state,
                verifyCode: false,
                isLoading: true
            }
        case VERIFY_CODE :
            return {
                ...state,
                user: action.payload,
                verifyCode: true,
                isAuthenticated: true,
                isLoading: false
            };
        case SET_PASS :
            return {
                ...state,
                user: action.payload,
                isAuthenticated: true,
                isLoading: false,
                setPass: true,
            }
        case LOGOUT_SUCCESS:
            localStorage.removeItem("token");
            return {
                token: null,
                user : null,
                isAuthenticated: false,
                isLoading: true
            }
        case REGISTER_FAIL:
            localStorage.removeItem("token");
            return {
                ...state,
                token: null,
                user: null,
                isAuthenticated: false,
                isLoading: false,
            };
        default:
            return state;
    }
}
</code>```

In last step user fill username and password and we need pass email too. And this my component code :

```<code>import React, {Component} from "react";
import PropTypes from "prop-types";
import {loadUser, setPass, verifyCode , browserHistory} from "../../actions/authAction";
import {connect} from "react-redux";
import {clearError} from "../../actions/errorAction";
import {toast} from "react-toastify";
import store from "../../store";

class RegisterFinal extends Component {
    constructor(props) {
        super(props);
        this.state = {
            email: this.props.auth,
        }
    }

    componentDidMount() {
        store.dispatch(loadUser());

    }

    state = {
        user : [],
        userName : "",
        password : "",
        verifyCode : "",
        passwordConfirm : "",
        isLoading: true,
        msg: null
    }

    static propTypes = {
        isAuthenticated : PropTypes.bool,
        setPass : PropTypes.func.isRequired,
        auth: PropTypes.object.isRequired,
    };
    componentDidUpdate(prevProps) {

        const {error} = this.props;
        if (error !== prevProps.error) {
            if (error.id === 'SET_PASS_FAIL') {
                let status =error.status;
                if (status === 400) {
                    toast.error("کاربر موجود است")
                }
            } else {
                this.setState({msg: null});
            }
        }
    }
    onSubmit = (e) => {
        e.preventDefault();
        const {password , userName , verifyCode} = this.state
        const setPass = {
            password , userName , verifyCode
        }
        this.props.setPass(setPass);
        const { passwordConfirm } = e.target;
        const errors = {};
        if (password.value !== passwordConfirm.value) {
            errors.passwordMismatch = "Entered passwords do not match.";
            console.log(errors)
        }}
    onChange = (e) => {
        this.setState({
            [e.target.name]: e.target.value,
        });
    };

    render() {
const {user} = this.state;
        return (
            <div className={"container"}>
                <div className={"row row-of-final-register justify-content-center"}>
                    <div className={"mt-5 register-teacher-inputs-box final-register-teacher-inputs-box"}>
                        <div className={"final-register-wrapper"}>
                            <div className={"register-teacher-icon final-register-teacher-icon"}>

                            </div>
                            <div className={"register-teacher-text final-register-teacher-text"}>
                                <h4>
                                   Last Step
                                </h4>
                                <p>
                                   Account
                                </p>
                            </div>
                        </div>
                        <form className={"mt-5"} onSubmit={this.onSubmit}>
                            <div className={"row"}>
                                <div className={"col-12"}>
                                    <label
                                        htmlFor={"userName"} className={"text-right username-label"}>
                                        <span>*</span>
                                    </label>
                                    <input type="text" className="form-control w-100" placeholder={"username"}
                                           name={"userName"}
                                           autoComplete="true"
                                           value={this.userName}
                                           onChange={this.onChange}
                                           onFocus={(e) => e.target.placeholder = ""}
                                    />
                                </div>
                            </div>
                            <div className={"row"}>
                                <div className={"col-12 col-lg-6 mt-3"}>
                                    <label
                                        htmlFor={"password"} className={" text-right"}>
                                        <span>*</span>
                                    </label>
                                    <input type="password" className="form-control " placeholder={"Password"}
                                           name={"password"}
                                           value={this.password}
                                           onChange={this.onChange}
                                           onFocus={(e) => e.target.placeholder = ""}
                                    />
                                </div>

                            </div>
                            <div className={"row mt-3 pt-2"}>
                                <div className={"col-12 final-register-wrapper final-register-btn"}>
                                    <button type={"submit"} className={"final-register-btn"}>Submit</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        )
    }
}

const mapStateToProps = (state) => ({
    setPass : state.setPass,
    isAuthenticated : state.isAuthenticated,
    error : state.error,
    auth: state.auth,
});
export default connect(mapStateToProps , {
    setPass , clearError ,loadUser
})(RegisterFinal);
</code>```

答:
// First of all, I would change this,
// is not a good idea import your store to each component.
import store from '../store';
...
componentDidMount() {
  store.dispatch(loadUser());
}

// and I would do this
import { loadUser as loadUserAction } from '../actions';
...
componentDidMount() {
  this.props.loadUser();
}
...
...
const mapDispatchToProps = (dispatch) => ({
    loadUser: () => dispatch(loadUserAction()),
    setPass: () => dispatch(setPassAction()),
    clearError: () => dispatch(clearErrorAction()),
});

export default connect(mapStateToProps, mapDispatchToProps)(RegisterFinal);```

Body:
I create multi step register that user create in first step and then send OTP code in last step user set username and password. In last step when I use props show me user is null but in react dev tools user already exist. This Two picture:

This is my reduser code :

    import {
    USER_LOADED,
    USER_LOADING,
    AUTH_ERROR,
    LOGIN_SUCCESS,
    LOGIN_FAIL,
    LOGOUT_SUCCESS,
    REGISTER_SUCCESS,
    REGISTER_FAIL,
    VERIFY_CODE,
    SET_PASS,
    SET_PASS_FAIL,
    VERIFY_FAIL
} from "../actions/types";

const initialState = {
    token: localStorage.getItem("token"),
    isAuthenticated: null,
    isLoading: false,
    verifyCode : null,
    setPass : null,
    user: null,
};

export default function (state = initialState, action) {
    switch (action.type) {
        case USER_LOADING:
            return {
                ...state,
                isLoading: true,

            };
        case USER_LOADED:
            return {
                ...state,
                isAuthenticated: true,
                isLoading: false,
                verifyCode: true,
                user: action.payload,
            };
        case LOGIN_SUCCESS:
        case REGISTER_SUCCESS:
            localStorage.setItem("token", action.payload.token);
            return {
                ...state,
                ...action.payload,
                isAuthenticated: true,
                isLoading: false,
                verifyCode: false
            };
        case SET_PASS_FAIL:
        case AUTH_ERROR:
        case LOGIN_FAIL:
        case VERIFY_FAIL:
            return {
                ...state,
                verifyCode: false,
                isLoading: true
            }
        case VERIFY_CODE :
            return {
                ...state,
                user: action.payload,
                verifyCode: true,
                isAuthenticated: true,
                isLoading: false
            };
        case SET_PASS :
            return {
                ...state,
                user: action.payload,
                isAuthenticated: true,
                isLoading: false,
                setPass: true,
            }
        case LOGOUT_SUCCESS:
            localStorage.removeItem("token");
            return {
                token: null,
                user : null,
                isAuthenticated: false,
                isLoading: true
            }
        case REGISTER_FAIL:
            localStorage.removeItem("token");
            return {
                ...state,
                token: null,
                user: null,
                isAuthenticated: false,
                isLoading: false,
            };
        default:
            return state;
    }
}

In last step user fill username and password and we need pass email too. And this my component code :

import React, {Component} from "react";
import PropTypes from "prop-types";
import {loadUser, setPass, verifyCode , browserHistory} from "../../actions/authAction";
import {connect} from "react-redux";
import {clearError} from "../../actions/errorAction";
import {toast} from "react-toastify";
import store from "../../store";

class RegisterFinal extends Component {
    constructor(props) {
        super(props);
        this.state = {
            email: this.props.auth,
        }
    }

    componentDidMount() {
        store.dispatch(loadUser());

    }

    state = {
        user : [],
        userName : "",
        password : "",
        verifyCode : "",
        passwordConfirm : "",
        isLoading: true,
        msg: null
    }

    static propTypes = {
        isAuthenticated : PropTypes.bool,
        setPass : PropTypes.func.isRequired,
        auth: PropTypes.object.isRequired,
    };
    componentDidUpdate(prevProps) {

        const {error} = this.props;
        if (error !== prevProps.error) {
            if (error.id === 'SET_PASS_FAIL') {
                let status =error.status;
                if (status === 400) {
                    toast.error("کاربر موجود است")
                }
            } else {
                this.setState({msg: null});
            }
        }
    }
    onSubmit = (e) => {
        e.preventDefault();
        const {password , userName , verifyCode} = this.state
        const setPass = {
            password , userName , verifyCode
        }
        this.props.setPass(setPass);
        const { passwordConfirm } = e.target;
        const errors = {};
        if (password.value !== passwordConfirm.value) {
            errors.passwordMismatch = "Entered passwords do not match.";
            console.log(errors)
        }}
    onChange = (e) => {
        this.setState({
            [e.target.name]: e.target.value,
        });
    };

    render() {
const {user} = this.state;
        return (

                                   Last Step

                                   Account

                        <form className={"mt-5"} onSubmit={this.onSubmit}>

                                        *

                                    <input type="text" className="form-control w-100" placeholder={"username"}
                                           name={"userName"}
                                           autoComplete="true"
                                           value={this.userName}
                                           onChange={this.onChange}
                                           onFocus={(e) => e.target.placeholder = ""}
                                    />

                                        *

                                    <input type="password" className="form-control " placeholder={"Password"}
                                           name={"password"}
                                           value={this.password}
                                           onChange={this.onChange}
                                           onFocus={(e) => e.target.placeholder = ""}
                                    />

                                    <button type={"submit"} className={"final-register-btn"}>Submit</button>

                        </form>

        )
    }
}

const mapStateToProps = (state) => ({
    setPass : state.setPass,
    isAuthenticated : state.isAuthenticated,
    error : state.error,
    auth: state.auth,
});
export default connect(mapStateToProps , {
    setPass , clearError ,loadUser
})(RegisterFinal);


问:
Oracle - How to join multiple Tables with same FK and no other correlation between them. Avoiding row duplication
I'm Making a Query to get the Payments of a Invoice.
But since i can have, multiple cards, Accounts Receivable and Money (cash and change).
is it possible to make this work without using function, Unions and subqueries?
all tables have 300k+ records, and i want to make a view for ease of use/maintain.
however when i use union on views perfromance drops drastically

THE FOLLOWING EXEMPLE

Invoice

INVOICE

113806

Invoice -> entry

INVOICE
ID_ENTRY

113806
387473

Accounts Receivable

ID_ENTRY
ID_AR
DUE TO

387473
31014
15/05/2022

387473
31015
15/06/2022

Card

ID_ENTRY
ID_CARD
DUE TO

387473
407214
01/01/2022

Cash

ID_ENTRY
ID_CASH
VALUE

387473
407214
10

387473
407215
-5

Query

```<code>SELECT NAF.INVOICE_ENTRY, ADRE.ID_AR, ACAR.ID_CARD, ADIN.ID_CASH
FROM INVOICE N
INNER JOIN INVOICE_ENTRY NAF
    ON NAF.ID_INVOICE = N.ID_INVOICE
LEFT JOIN AR_ENTRY ADRE
    ON ADRE.ID_ENTRY = NAF.ID_ENTRY
LEFT JOIN CARD_ENTRY ACAR
    ON ACAR.ID_ENTRY = NAF.ID_ENTRY
LEFT JOIN CASH_ENTRY ADIN
    ON ADIN.ID_ENTRY = NAF.ID_ENTRY
WHERE N.ID_INVOICE = :ID_INVOICE
</code>```

Result

ID_ENTRY
ID_AR
ID_CARD
ID_CASH

387473
31014
221396
407214

387473
31014
221396
407215

387473
31015
221396
407214

387473
31015
221396
407215

Expected Result

ACERFIN
IDAD
IDCAR
IDDIN

387473
31014
NULL
NULL

387473
31015
NULL
NULL

387473
NULL
221396
NULL

387473
NULL
NULL
407214

387473
NULL
NULL
407215

答:
You can use UNION ALL on the accounts_receivable, cash and card tables and then join the result to the other tables:

SELECT u.*
FROM   invoice i
       INNER JOIN entry e
       ON (i.invoice = e.invoice)
       INNER JOIN (
         SELECT id_entry AS acerfin, id_ar AS idad, NULL AS idcar, NULL AS iddin
         FROM   accounts_receivable
         UNION ALL
         SELECT id_entry, NULL, id_card, NULL
         FROM   card
         UNION ALL
         SELECT id_entry, NULL, NULL, id_cash
         FROM   cash
       ) u
       ON (e.id_entry = u.acerfin)
WHERE  i.invoice = 113806
```
<p>Which, for the sample data:</p>
<pre class="lang-sql prettyprint-override"><code>CREATE TABLE invoice (INVOICE) AS
SELECT 113806 FROM DUAL;

CREATE TABLE entry (INVOICE, ID_ENTRY) AS
SELECT 113806, 387473 FROM DUAL;

CREATE TABLE Accounts_Receivable (ID_ENTRY, ID_AR, DUE_TO) AS
SELECT 387473, 31014, DATE '2022-05-15' FROM DUAL UNION ALL
SELECT 387473, 31015, DATE '2022-06-15' FROM DUAL;

CREATE TABLE Card (ID_ENTRY, ID_CARD, DUE_TO) AS
SELECT 387473, 407214, DATE '2022-05-01' FROM DUAL;

CREATE TABLE Cash (ID_ENTRY, ID_CASH, VALUE) AS
SELECT 387473, 407214, 10 FROM DUAL UNION ALL
SELECT 387473, 407215, -5 FROM DUAL;
</code>```

Outputs:

ACERFIN
IDAD
IDCAR
IDDIN

387473
31014
null
null

387473
31015
null
null

387473
null
407214
null

387473
null
null
407214

387473
null
null
407215

db<>fiddle here

Body:
I'm Making a Query to get the Payments of a Invoice.
But since i can have, multiple cards, Accounts Receivable and Money (cash and change).
is it possible to make this work without using function, Unions and subqueries?
all tables have 300k+ records, and i want to make a view for ease of use/maintain.
however when i use union on views perfromance drops drastically

THE FOLLOWING EXEMPLE

Invoice

INVOICE

113806

Invoice -> entry

INVOICE
ID_ENTRY

113806
387473

Accounts Receivable

ID_ENTRY
ID_AR
DUE TO

387473
31014
15/05/2022

387473
31015
15/06/2022

Card

ID_ENTRY
ID_CARD
DUE TO

387473
407214
01/01/2022

Cash

ID_ENTRY
ID_CASH
VALUE

387473
407214
10

387473
407215
-5

Query

SELECT NAF.INVOICE_ENTRY, ADRE.ID_AR, ACAR.ID_CARD, ADIN.ID_CASH
FROM INVOICE N
INNER JOIN INVOICE_ENTRY NAF
    ON NAF.ID_INVOICE = N.ID_INVOICE
LEFT JOIN AR_ENTRY ADRE
    ON ADRE.ID_ENTRY = NAF.ID_ENTRY
LEFT JOIN CARD_ENTRY ACAR
    ON ACAR.ID_ENTRY = NAF.ID_ENTRY
LEFT JOIN CASH_ENTRY ADIN
    ON ADIN.ID_ENTRY = NAF.ID_ENTRY
WHERE N.ID_INVOICE = :ID_INVOICE

Result

ID_ENTRY
ID_AR
ID_CARD
ID_CASH

387473
31014
221396
407214

387473
31014
221396
407215

387473
31015
221396
407214

387473
31015
221396
407215

Expected Result

ACERFIN
IDAD
IDCAR
IDDIN

387473
31014
NULL
NULL

387473
31015
NULL
NULL

387473
NULL
221396
NULL

387473
NULL
NULL
407214

387473
NULL
NULL
407215

Body:
You can use UNION ALL on the accounts_receivable, cash and card tables and then join the result to the other tables:

SELECT u.*
FROM   invoice i
       INNER JOIN entry e
       ON (i.invoice = e.invoice)
       INNER JOIN (
         SELECT id_entry AS acerfin, id_ar AS idad, NULL AS idcar, NULL AS iddin
         FROM   accounts_receivable
         UNION ALL
         SELECT id_entry, NULL, id_card, NULL
         FROM   card
         UNION ALL
         SELECT id_entry, NULL, NULL, id_cash
         FROM   cash
       ) u
       ON (e.id_entry = u.acerfin)
WHERE  i.invoice = 113806

Which, for the sample data:

CREATE TABLE invoice (INVOICE) AS
SELECT 113806 FROM DUAL;

CREATE TABLE entry (INVOICE, ID_ENTRY) AS
SELECT 113806, 387473 FROM DUAL;

CREATE TABLE Accounts_Receivable (ID_ENTRY, ID_AR, DUE_TO) AS
SELECT 387473, 31014, DATE '2022-05-15' FROM DUAL UNION ALL
SELECT 387473, 31015, DATE '2022-06-15' FROM DUAL;

CREATE TABLE Card (ID_ENTRY, ID_CARD, DUE_TO) AS
SELECT 387473, 407214, DATE '2022-05-01' FROM DUAL;

CREATE TABLE Cash (ID_ENTRY, ID_CASH, VALUE) AS
SELECT 387473, 407214, 10 FROM DUAL UNION ALL
SELECT 387473, 407215, -5 FROM DUAL;

Outputs:

ACERFIN
IDAD
IDCAR
IDDIN

387473
31014
null
null

387473
31015
null
null

387473
null
407214
null

387473
null
null
407214

387473
null
null
407215

db<>fiddle here


问:
PostgreSQL said: permission denied for schema
I have a multi-tenant PostgreSQL db on a Ruby on Rails app, and when I try to access to tables on some schemas on Postico, I get the following error:

```<code>Failed to load table schema.
Query failed
PostgreSQL said: permission denied for schema coaching
</code>```

I tried to run: GRANT USAGE ON SCHEMA "lacerba-api" TO "postico7" but I get ERROR:  permission denied for schema lacerba-api

Of course my user have writing permission on the db.

Any idea how to solve it?

答:
My guess is that your user doesn't have permission to read tables in the coaching schema. You can try granting your user permission to read tables in that schema:

GRANT SELECT ON SCHEMA coaching TO postico7

Body:
I have a multi-tenant PostgreSQL db on a Ruby on Rails app, and when I try to access to tables on some schemas on Postico, I get the following error:

Failed to load table schema.
Query failed
PostgreSQL said: permission denied for schema coaching

I tried to run: GRANT USAGE ON SCHEMA "lacerba-api" TO "postico7" but I get ERROR:  permission denied for schema lacerba-api

Of course my user have writing permission on the db.

Any idea how to solve it?


问:
MySql gives an error for no reason at all?
I am writing an mysql program (using the command line editor):

```<code>CREATE TABLE FLIGHTS (
FL_NO  VARCHAR(10) NOT NULL PRIMARY KEY,
STARTING VARCHAR(20) NOT NULL,
ENDING VARCHAR(20) NOT NULL,
NO_FLIGTHS INT NOT NULL,
NO_STOPS INT NOT NULL
);
</code>```

this is somehow gives an error which is surprising. any idea?

Error message:
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'STARTING VARCHAR(20) NOT NULL,
ENDING VARCHAR(20) NOT NULL,
NO_FLIGHTS INTEGER N' at line 3

答: STARTING and ENDING are keywords, and MySql does not accept keywords as column names, changing them should help...

Body:
I am writing an mysql program (using the command line editor):

CREATE TABLE FLIGHTS (
FL_NO  VARCHAR(10) NOT NULL PRIMARY KEY,
STARTING VARCHAR(20) NOT NULL,
ENDING VARCHAR(20) NOT NULL,
NO_FLIGTHS INT NOT NULL,
NO_STOPS INT NOT NULL
);

this is somehow gives an error which is surprising. any idea?

Error message:
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'STARTING VARCHAR(20) NOT NULL,
ENDING VARCHAR(20) NOT NULL,
NO_FLIGHTS INTEGER N' at line 3


问:
Splitting List That Contains Strings and Integers
```<code>myList = [ 4,'a', 'b', 'c', 1 'd', 3]
</code>```

how to split this list into two list that one contains strings and other contains integers in elegant/pythonic way?

output:

```<code>myStrList = [ 'a', 'b', 'c', 'd' ]

myIntList = [ 4, 1, 3 ]
</code>```

NOTE: didn't implemented such a  list, just thought about how to find an elegant answer (is there any?) to such a problem.

答:
```<code>myList = [ 4,'a', 'b', 'c', 1 'd', 3]

myList_string = []
myList_number = []

for a in myList:
  if type(a) == int or type(a) == float:
    myList_number.append(a)
  elif type(a) == str:
    myList_string.append(a)
</code>```

Body:
myList = [ 4,'a', 'b', 'c', 1 'd', 3]

how to split this list into two list that one contains strings and other contains integers in elegant/pythonic way?

output:

myStrList = [ 'a', 'b', 'c', 'd' ]

myIntList = [ 4, 1, 3 ]

NOTE: didn't implemented such a  list, just thought about how to find an elegant answer (is there any?) to such a problem.


问:
elixir phoenix pubsub wildcard topic
when using phoenix pubs directly is there a way for subscribing to a topic with partial match, e.g. something like "user:*"?

just for illustration sake, the following code:

```<code>Phoenix.PubSub.subscribe("my_pubsub", "user:*")
</code>```

should match all the following events:

```<code>Phoenix.PubSub.broadcast("my_pubsub", "user:123", "banana")
Phoenix.PubSub.broadcast("my_pubsub", "user:911", "apple")
Phoenix.PubSub.broadcast("my_pubsub", "user:", "orange")
</code>```

答: Phoenix.PubSub.subscribe does not support wildcard topics. As noted in the Phoenix Docs, and by this answer by Chris McCord, channels and topics can have wildcards in the strings, but subscriptions cannot.

Title: elixir phoenix pubsub wildcard topic

Body:
when using phoenix pubs directly is there a way for subscribing to a topic with partial match, e.g. something like "user:*"?

just for illustration sake, the following code:

Phoenix.PubSub.subscribe("my_pubsub", "user:*")

should match all the following events:

Phoenix.PubSub.broadcast("my_pubsub", "user:123", "banana")
Phoenix.PubSub.broadcast("my_pubsub", "user:911", "apple")
Phoenix.PubSub.broadcast("my_pubsub", "user:", "orange")


问:
Azure PowerShell add User or Group to Service Principal
how can i add users or a group to a service principal in azure with powershell?

My Service Principal:

```<code>$servicePrincipal = Get-AzADServicePrincipal -DisplayName "My Application"
</code>```

i want to add the user test@domain.de or the group "IT" to this service principal.

EDIT: Or the AppRoleAssignmentRequired set to "false" would be fine too.

答:
I found the solution how to disable that role assignment is required.
I post the solution before i delete the thread. Maybe this helps someone.</p>
```<code>Get-AzureADServicePrincipal -Filter "displayname eq 'My Application'" | set-AzureADServicePrincipal -AppRoleAssignmentRequired $true
</code>```

Body:
how can i add users or a group to a service principal in azure with powershell?

My Service Principal:

$servicePrincipal = Get-AzADServicePrincipal -DisplayName "My Application"

i want to add the user test@domain.de or the group "IT" to this service principal.

EDIT: Or the AppRoleAssignmentRequired set to "false" would be fine too.

Body:
I found the solution how to disable that role assignment is required.
I post the solution before i delete the thread. Maybe this helps someone.

Get-AzureADServicePrincipal -Filter "displayname eq 'My Application'" | set-AzureADServicePrincipal -AppRoleAssignmentRequired $true


问:
Matching a number against a comma-separated sequence of ranges
I'm writing a bash script which takes a number, and also a comma-separated sequence of values and strings, e.g.: 3,15,4-7,19-20. I want to check whether the number is contained in the set corresponding to the sequence. For simplicity, assume no comma-separated elements intersect, and that the elements are sorted in ascending order.

Is there a simple way to do this in bash other than the brute-force naive way? Some shell utility which does something like that for me, maybe something related to lpr which already knows how to process page range sequences etc.

答:
A function based on @JamesBrown's method:

```<code>function match_in_range_seq {
    (( $# == 2 )) && [[ -n "$(echo -n "$2" | awk -v val="$1" -v RS=, -F- '(NF==1&&$1==val) || (NF==2&&$1<=val&&$2>=val)' - )" ]]
}
</code>```

Will return 0 (in $?) if the second argument (the range sequence) contains the first argument, 1 otherwise.

Body:
A function based on @JamesBrown's method:

function match_in_range_seq {
    (( $# == 2 )) && [[ -n "$(echo -n "$2" | awk -v val="$1" -v RS=, -F- '(NF==1&&$1==val) || (NF==2&&$1<=val&&$2>=val)' - )" ]]
}

Will return 0 (in $?) if the second argument (the range sequence) contains the first argument, 1 otherwise.


问:
'train' and 'class' have different lengths error in R
I just wanted to conduct a kNN classification with the situation when k is 3. I would like to predict the dependent variable “diabetes” in valid set using train set and calculate the accuracy.

But I faced to the error message with

Error in knn(train = TrainXNormDF, test = ValidXNormDF, cl = MLdata2[,  :  'train' and 'class' have different lengths

I can't solve this problem with get approach with

```<code>for(i in ((length(MLValidY) + 1):length(TrainXNormDF)))+(MLValidY = c(MLValidY, 0))
</code>```

What can I do for it? Please help.

My code is as like below

```<code>install.packages("mlbench")
install.packages("gbm")

library(mlbench)
library(gbm)

data("PimaIndiansDiabetes2")
head(PimaIndiansDiabetes2)

MLdata <- as.data.frame(PimaIndiansDiabetes2)
head(MLdata)
str(MLdata)
View(MLdata)

any(is.na(MLdata))
sum(is.na(MLdata))

MLdata2 <- na.omit(MLdata)
any(is.na(MLdata2))
sum(is.na(MLdata2))
View(MLdata2)

MLIdx <- sample(1:3, size = nrow(MLdata2), prob = c(0.6, 0.2, 0.2), replace = TRUE)

MLTrain <- MLdata2[MLIdx == 1,]
MLValid <- MLdata2[MLIdx == 2,]
MLTest <- MLdata2[MLIdx == 3,]

head(MLTrain)
head(MLValid)
head(MLTest)

str(MLTrain)
str(MLValid)
str(MLTest)

View(MLTestY)

MLTrainX <- MLTrain[ , -9]
MLValidX <- MLValid[ , -9]
MLTestX <- MLTest[ , -9]

MLTrainY <- as.data.frame(MLTrain[ , 9])
MLValidY <- as.data.frame(MLValid[ , 9])
MLTestY <- as.data.frame(MLTest[ , 9])

View(MLTrainX)
View(MLTrainY)

library(caret)

NormValues <- preProcess(MLTrainX, method = c("center", "scale"))

TrainXNormDF <- predict(NormValues, MLTrainX)
ValidXNormDF <- predict(NormValues, MLValidX)
TestXNormDF <- predict(NormValues, MLTestX)

head(TrainXNormDF)
head(ValidXNormDF)
head(TestXNormDF)

install.packages('FNN')
library(FNN)
library(class)

NN <- knn(train = TrainXNormDF,
      test = ValidXNormDF,
      cl = MLValidY,
      k = 3)
</code>```

Thank you

答:
As @rw2 stated, it's the length of cl. I think you meant to use MLtrainY, not MLvalidY. When you have a single column data frame, you can still run into shape problems (converts it to a vector). You could walk back to make sure that you use the right content here, like so:

```<code>NN <- knn(train = TrainXNormDF,
          test = ValidXNormDF,
          cl = MLdata2[MLIdx == 1,]$diabetes, # shape no longer an issue
          k = 3)
</code>```

Body:
I just wanted to conduct a kNN classification with the situation when k is 3. I would like to predict the dependent variable “diabetes” in valid set using train set and calculate the accuracy.

But I faced to the error message with

Error in knn(train = TrainXNormDF, test = ValidXNormDF, cl = MLdata2[,  :  'train' and 'class' have different lengths

I can't solve this problem with get approach with

for(i in ((length(MLValidY) + 1):length(TrainXNormDF)))+(MLValidY = c(MLValidY, 0))

What can I do for it? Please help.

My code is as like below

install.packages("mlbench")
install.packages("gbm")

library(mlbench)
library(gbm)

data("PimaIndiansDiabetes2")
head(PimaIndiansDiabetes2)

MLdata <- as.data.frame(PimaIndiansDiabetes2)
head(MLdata)
str(MLdata)
View(MLdata)

any(is.na(MLdata))
sum(is.na(MLdata))

MLdata2 <- na.omit(MLdata)
any(is.na(MLdata2))
sum(is.na(MLdata2))
View(MLdata2)

MLIdx <- sample(1:3, size = nrow(MLdata2), prob = c(0.6, 0.2, 0.2), replace = TRUE)

MLTrain <- MLdata2[MLIdx == 1,]
MLValid <- MLdata2[MLIdx == 2,]
MLTest <- MLdata2[MLIdx == 3,]

head(MLTrain)
head(MLValid)
head(MLTest)

str(MLTrain)
str(MLValid)
str(MLTest)

View(MLTestY)

MLTrainX <- MLTrain[ , -9]
MLValidX <- MLValid[ , -9]
MLTestX <- MLTest[ , -9]

MLTrainY <- as.data.frame(MLTrain[ , 9])
MLValidY <- as.data.frame(MLValid[ , 9])
MLTestY <- as.data.frame(MLTest[ , 9])

View(MLTrainX)
View(MLTrainY)

library(caret)

NormValues <- preProcess(MLTrainX, method = c("center", "scale"))

TrainXNormDF <- predict(NormValues, MLTrainX)
ValidXNormDF <- predict(NormValues, MLValidX)
TestXNormDF <- predict(NormValues, MLTestX)

head(TrainXNormDF)
head(ValidXNormDF)
head(TestXNormDF)

install.packages('FNN')
library(FNN)
library(class)

NN <- knn(train = TrainXNormDF,
      test = ValidXNormDF,
      cl = MLValidY,
      k = 3)

Thank you

Body:
As @rw2 stated, it's the length of cl. I think you meant to use MLtrainY, not MLvalidY. When you have a single column data frame, you can still run into shape problems (converts it to a vector). You could walk back to make sure that you use the right content here, like so:

NN <- knn(train = TrainXNormDF,
          test = ValidXNormDF,
          cl = MLdata2[MLIdx == 1,]$diabetes, # shape no longer an issue
          k = 3)


问:
IE6 and IE7 float issue on navigation list items
Like many people, I am having trouble with floating elements in IE7 (and 6, but I don't care about that!)

http://www.storybox.co.nz/wordpress/

Looks fine in every other browser, but in IE7 the navigation links sit under each other:

HTML (inline styles are from js dropdown script):

```<code><div id="primary-menu">
  <div class="menu">
    <ul>
      <li><a href="#" class="sf-with-ul">Work.</a>
        <ul class="sub-menu" style="float: none; width: 1em; visibility: hidden; display: none;">
          <li style="white-space: normal; float: left; width: 100%;"><a href="#" style="float: none; width: auto;">Spatial /</a></li>
          <li style="white-space: normal; float: left; width: 100%;"><a href="#" style="float: none; width: auto;">Web /</a></li>
          <li style="white-space: normal; float: left; width: 100%;"><a href="#" style="float: none; width: auto;">Graphic</a></li>
        </ul>
      </li>
      <li><a href="#">Lab.</a></li>
      <li><a href="#">About.</a></li>
    </ul>
  </div>
</div>
</code>```

CSS:

```<code>#primary-menu {
    margin:-30px auto 30px;
}
#primary-menu ul {
    float:right;
}
#primary-menu li {
        float: left;
        list-style: none;
        margin-left: 10px;
            display:inline;
}
#primary-menu ul li a {
        float: right;
}
</code>```

I have tried display:inline on the li items as well as on the a items, but that doesn't work.

Any other tips? Thanks!

答:
the problem is probably width: 100% for li. If ul is 100px, then each of li will also have 100px = they will be displayed as shown. Try to set fixed width for them, but 3x width ( + padding, margins ) should be less than width for ul. You can also try 33%. BT

float: right puts display: block on item and it makes no sense to add display: inline together with float: right. My guess is that IE ignores display: inline. It makes also no sense to put width for inline element. Your CSS simple does not make sense :)

Body:
Like many people, I am having trouble with floating elements in IE7 (and 6, but I don't care about that!)

http://www.storybox.co.nz/wordpress/

Looks fine in every other browser, but in IE7 the navigation links sit under each other:

HTML (inline styles are from js dropdown script):

Work.

Spatial /

Web /

Graphic

Lab.

About.

CSS:

#primary-menu {
    margin:-30px auto 30px;
}
#primary-menu ul {
    float:right;
}
#primary-menu li {
        float: left;
        list-style: none;
        margin-left: 10px;
            display:inline;
}
#primary-menu ul li a {
        float: right;
}

I have tried display:inline on the li items as well as on the a items, but that doesn't work.

Any other tips? Thanks!


问:
Class "Google_Service_MyBusiness" not found in Laravel
I use Google My Business API to fetch the account list, but it shows the following error.

"Class "Google_Service_MyBusiness" not found."

In my Laravel project, I am using Google Analytics, and its classes are working correctly. I installed the google/apiclient": "2.12" package. Do I need to install any other libraries to access my Google My Business account?

```<code>$mybusinessService = new \Google_Service_MyBusiness($client);
$accounts = $mybusinessService->accounts;
$accountsList = $accounts->listAccounts()->getAccounts();
</code>```

答:
First off, FYI: The GMB API will be deprecated as it is to be replaced by the new Business Profile APIs (https://developers.google.com/my-business/ref_overview).

The new APIs are part of the Google PHP API Client Services.

In order to list accounts via the Account Management API (google-api-php-client-services/src/MyBusinessAccountManagement/), I suggest you take a look at Accounts.php.

Body:
I use Google My Business API to fetch the account list, but it shows the following error.

"Class "Google_Service_MyBusiness" not found."

In my Laravel project, I am using Google Analytics, and its classes are working correctly. I installed the google/apiclient": "2.12" package. Do I need to install any other libraries to access my Google My Business account?

$mybusinessService = new \Google_Service_MyBusiness($client);
$accounts = $mybusinessService->accounts;
$accountsList = $accounts->listAccounts()->getAccounts();


问:
Java null String equals result
Please help me how does the string.equals in java work with null value? Is there some problem with exceptions?
Three cases:

```<code>boolean result1,result2, result3;

    //1st case
    String string1 = null;
    String string2 = null;
    result = string1.equals(string2);
    //2nd case
    String string1 = "something";
    String string2 = null;
    result2 = string1.equals(string2);
    //3rd case
    String string1 = null;
    String string2 = "something";
    result3 = string1.equals(string2);
</code>```

What the values of results are? I expect this values:

result1 is true;

  result2 is false;

  result3 is false;

答:
I am late to answer this, but you can use

```<code>StringUtils.equals(str1, str2)
</code>```

if you are using spring

Title: Java null String equals result

Body:
Please help me how does the string.equals in java work with null value? Is there some problem with exceptions?
Three cases:

boolean result1,result2, result3;

    //1st case
    String string1 = null;
    String string2 = null;
    result = string1.equals(string2);
    //2nd case
    String string1 = "something";
    String string2 = null;
    result2 = string1.equals(string2);
    //3rd case
    String string1 = null;
    String string2 = "something";
    result3 = string1.equals(string2);

What the values of results are? I expect this values:

result1 is true;

  result2 is false;

  result3 is false;

Body:
I am late to answer this, but you can use

StringUtils.equals(str1, str2)

if you are using spring


问:
Call javascript function after script is loaded
I have a html page where I am appending html at dynamically through a javascript like below

```<code><script type="text/javascript" src="/myapp/htmlCode"></script>
</code>```

I want to call a js function e.g. loadedContent(); once the above script adds dynamic html.

Can someone help me how I can do that?

答:
This is all you need</p>
```<code>await new Promise((resolve) => {
    let script = document.createElement("script");

    script.onload = () => {
        resolve();
    };

    script.src = "https://example.net/app.js";

    document.head.appendChild(script);
});
</code>```

Body:
I have a html page where I am appending html at dynamically through a javascript like below

I want to call a js function e.g. loadedContent(); once the above script adds dynamic html.

Can someone help me how I can do that?

Body:
This is all you need

await new Promise((resolve) => {
    let script = document.createElement("script");

    script.onload = () => {
        resolve();
    };

    script.src = "https://example.net/app.js";

    document.head.appendChild(script);
});


问:
Calling async event in flutter_bloc
I am trying to fetch data from API as soon as the flutter app loads but I am unable to achieve so

```<code>class MarketBloc extends Bloc<MarketListEvent, MarketListState> {
  MarketBloc() : super(MarketLoading()) {
    on<MarketSelectEvent>((event, emit) async {
      emit(MarketLoading());
      final data = await ApiCall().getData(event.value!);
      globalData = data;
      emit(MarketDataFetched(marDat: globalData.data, dealType: event.value));
    });

  }
}
</code>```

I have called MarketLoading state as the initial state and I want to call MarketSelectEvent just after that but in the current code, action is required to do so and i want to achieve it without any action.

答:
You could do this with in the initState of whatever the first page is that your app loads.

```<code>class TestPage extends StatefulWidget {
  @override
  State<TestPage> createState() => _TestPageState();
}

class _TestPageState extends State<TestPage> {
  late MarketBloc marketBloc;

  @override
  void initState() {
    super.initState();
    marketBloc = BlocProvider.of<MarketBloc>(context);
    marketBloc.add(MarketSelectEvent());
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: BlocBuilder<MarketBloc, MarketListState>(
          builder: (context, state) {
            if (state is MarketLoading) {
              return Text('loading...');
            }
            if (state is MarketDataFetched) {
              return ...your UI that contains data from API call
            }
          },
        ),
      ),
    );
  }
}

</code>```

Title: Calling async event in flutter_bloc

Body:
I am trying to fetch data from API as soon as the flutter app loads but I am unable to achieve so

class MarketBloc extends Bloc<MarketListEvent, MarketListState> {
  MarketBloc() : super(MarketLoading()) {
    on<MarketSelectEvent>((event, emit) async {
      emit(MarketLoading());
      final data = await ApiCall().getData(event.value!);
      globalData = data;
      emit(MarketDataFetched(marDat: globalData.data, dealType: event.value));
    });

  }
}

I have called MarketLoading state as the initial state and I want to call MarketSelectEvent just after that but in the current code, action is required to do so and i want to achieve it without any action.

Body:
You could do this with in the initState of whatever the first page is that your app loads.

class TestPage extends StatefulWidget {
  @override
  State<TestPage> createState() => _TestPageState();
}

class _TestPageState extends State<TestPage> {
  late MarketBloc marketBloc;

  @override
  void initState() {
    super.initState();
    marketBloc = BlocProvider.of<MarketBloc>(context);
    marketBloc.add(MarketSelectEvent());
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: BlocBuilder<MarketBloc, MarketListState>(
          builder: (context, state) {
            if (state is MarketLoading) {
              return Text('loading...');
            }
            if (state is MarketDataFetched) {
              return ...your UI that contains data from API call
            }
          },
        ),
      ),
    );
  }
}


问:
Display aerial photographs interactively in R
I have taken aerial photographs with a drone and stitched those together into a .geotiff file, using third party software. I would like to add this file as a layer to an interactive leaflet map, e.g. as produced by mapview. I can produce an interactive map, but this only shows data, e.g. digital elevation not the actual photograph.

.geotiff files aren't very freely available, so see this link for an example file from naturalearth: https://www.naturalearthdata.com/downloads/50m-raster-data/50m-cross-blend-hypso/

```<code>library(magrittr)

exmpl <- terra::rast(".\\HYP_50M_SR.tif") %>%
  raster::brick()

mapview::mapview(exmpl)
</code>```

I am only interested in showing change over time as documented by repeated aerial photography and not interested in extracting data from the raster image. I have previously only worked with vector data, so please go easy on me if this is not a smart question. I like using mapview for it's simplicity, but base leaflet, tmap or any other interactive, R based solution would be fine by me. Thanks a lot!

答:
I guess you ar looking for the mapview::viewRGB() function.

Please find below a little reprex.

Reprex

library(mapview)
library(magrittr)

exmpl <- terra::rast(".\\HYP_50M_SR.tif") %>%
  raster::brick()

plotRGB(exmpl)
```
<p><img src="https://i.imgur.com/hxqMcN8.png" alt="" /></p>
<pre class="lang-r prettyprint-override"><code>mapview::viewRGB(exmpl, r = 1, g = 2, b = 3, quantiles = NULL)
</code>```

Created on 2022-02-10 by the reprex package (v2.0.1)

Body:
I have taken aerial photographs with a drone and stitched those together into a .geotiff file, using third party software. I would like to add this file as a layer to an interactive leaflet map, e.g. as produced by mapview. I can produce an interactive map, but this only shows data, e.g. digital elevation not the actual photograph.

.geotiff files aren't very freely available, so see this link for an example file from naturalearth: https://www.naturalearthdata.com/downloads/50m-raster-data/50m-cross-blend-hypso/

library(magrittr)

exmpl <- terra::rast(".\\HYP_50M_SR.tif") %>%
  raster::brick()

mapview::mapview(exmpl)

I am only interested in showing change over time as documented by repeated aerial photography and not interested in extracting data from the raster image. I have previously only worked with vector data, so please go easy on me if this is not a smart question. I like using mapview for it's simplicity, but base leaflet, tmap or any other interactive, R based solution would be fine by me. Thanks a lot!

Body:
I guess you ar looking for the mapview::viewRGB() function.

Please find below a little reprex.

Reprex

library(mapview)
library(magrittr)

exmpl <- terra::rast(".\\HYP_50M_SR.tif") %>%
  raster::brick()

plotRGB(exmpl)

mapview::viewRGB(exmpl, r = 1, g = 2, b = 3, quantiles = NULL)

Created on 2022-02-10 by the reprex package (v2.0.1)


问:
Mapping route from root url to dynamic product title / id
I'm developing an MVC 3 app

I want to have a url something like:

/some-product-name-goes-here-4726482648

(with 4726482648 being the product id)

I do have other pages such as:

/category-name

(allows browsing by category)

/about

etc...

How could I go about setting up routing to allow this?

答:
You would certainly be using a RouteConstraint here

in your routes you could have something like this:

```<code>routes.MapRoute("CustomProductUrl",
                 "{Product}",
                 new { controller = "Product", action = "Index" },
                 new { Product= new ProductConstraint() }
                );
</code>```

then in your ProductConstraint class you would have something as follows:

```<code>    public class ProductConstraint : IRouteConstraint
    {

        public ProductConstraint ()
        {
        }

        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
            //do your logic in here to split the name and the id and amke sure it is valid data

            //if valid return true;
            //else false;
        }

    }
</code>```

lastly in the Method signature of the Index action (or action in the route) take the string of the - and then split it down and process as appropriate

let me know if there are any issues

paul

Body:
You would certainly be using a RouteConstraint here

in your routes you could have something like this:

routes.MapRoute("CustomProductUrl",
                 "{Product}",
                 new { controller = "Product", action = "Index" },
                 new { Product= new ProductConstraint() }
                );

then in your ProductConstraint class you would have something as follows:

    public class ProductConstraint : IRouteConstraint
    {

        public ProductConstraint ()
        {
        }

        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
            //do your logic in here to split the name and the id and amke sure it is valid data

            //if valid return true;
            //else false;
        }

    }

lastly in the Method signature of the Index action (or action in the route) take the string of the - and then split it down and process as appropriate

let me know if there are any issues

paul


问:
How to make sure background fills the whole flex row which overflows?
How to make sure that background-color fills the whole flex row which overflows to the right? Currently, it only fills a portion of it that fits on the screen.

Here's an example:

main {
  position: relative;
  display: flex;
  flex-direction: column;
  background-color: white;
  overflow-x: scroll;
}

.wrapper {
  display: flex;
  flex-direction: row;
}
.wrapper:hover {
  background-color: rgba(0, 0, 0, 0.5);
}
.content {
  min-width: 150px;
  min-height: 20px;
  padding: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><main>
  <div class='wrapper'>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
  </div>
  <div class='wrapper'>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
  </div>
</main></code>```

答:
Move background-color from .wrapper to main.

Your main element is what is being scrolled.

Body:
How to make sure that background-color fills the whole flex row which overflows to the right? Currently, it only fills a portion of it that fits on the screen.

Here's an example:

main {
  position: relative;
  display: flex;
  flex-direction: column;
  background-color: white;
  overflow-x: scroll;
}

.wrapper {
  display: flex;
  flex-direction: row;
}
.wrapper:hover {
  background-color: rgba(0, 0, 0, 0.5);
}
.content {
  min-width: 150px;
  min-height: 20px;
  padding: 20px;
}

Content

Content

Content

Content

Content

Content

Content

Content

Content

Content

Content

Content


问:
Relative imports - ModuleNotFoundError: No module named x
This is the first time I've really sat down and tried python 3, and seem to be failing miserably. I have the following two files:

test.py

config.py

config.py has a few functions defined in it as well as a few variables. I've stripped it down to the following:

config.py

```<code>debug = True
</code>```

test.py

```<code>import config
print (config.debug)
</code>```

I also have an __init__.py

However, I'm getting the following error:

```<code>ModuleNotFoundError: No module named 'config'
</code>```

I'm aware that the py3 convention is to use absolute imports:

```<code>from . import config
</code>```

However, this leads to the following error:

```<code>ImportError: cannot import name 'config'
</code>```

So I'm at a loss as to what to do here... Any help is greatly appreciated. :)

答:
In my experience, PYTHONPATH environment variable does not work everytime.

In my case, my pytest only worked when I added the absolute path:
sys.path.insert(
0, "/Users/bob/project/repo/lambda"
)

Body:
This is the first time I've really sat down and tried python 3, and seem to be failing miserably. I have the following two files:

test.py

config.py

config.py has a few functions defined in it as well as a few variables. I've stripped it down to the following:

config.py

debug = True

test.py

import config
print (config.debug)

I also have an __init__.py

However, I'm getting the following error:

ModuleNotFoundError: No module named 'config'

I'm aware that the py3 convention is to use absolute imports:

from . import config

However, this leads to the following error:

ImportError: cannot import name 'config'

So I'm at a loss as to what to do here... Any help is greatly appreciated. :)


问:
prompt loads before anything else
hay if anybody understand why is prompt showing up even  before the console printing

i appreciate the help

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>promptheadache</title>

```

答:
console.logs are actually asynchronous in that they are synchronized (as in always in order) but perform an asynchronous call.

prompt is a very old API and one of the few that actually blocks the page - so even-though it appears after the console.log you see it as soon as it is called.

That said - this is not true for every console nor is it guaranteed - the console.log may appear before the prompt depending on the browser/console implementation.

Title: prompt loads before anything else


问:
How to get older data uploaded by devices to Azure IoT hub
I have a few Raspberry Pi devices uploading data to Azure IoT Hub. I can see all the data on Device Explorer. But is there any way I can see the data of specific time frame? Let's say complete data of last 1 hour?</p>

答:
You can achieve this with Service Bus Explorer. The name might suggest it's only for Service Bus, but it has Event Hub and IoT Hub support as well. To see the data for the last hour, do the following:

Copy the Event Hub compatible endpoint from the Azure Portal and strip off the EntityPath. Example:
Endpoint=sb://REDACTED.servicebus.windows.net/;SharedAccessKeyName=iothubowner;SharedAccessKey=REDACTED=;EntityPath=hub-name

becomes:
Endpoint=sb://REDACTED.servicebus.windows.net/;SharedAccessKeyName=iothubowner;SharedAccessKey=REDACTED=

Open Service Bus Explorer and create a new IoT  Hub Listener.

Add the connection string without the entity path and add the entity path as the Endpoint.

This will open a new listener window. In the window, you can select a start time. Select a time one hour back. The minimum retention period is a day, but if you decide to choose a time further in the past, that time should be within the retention period of the endpoint. If you select a time before the retention period, you will see events from the beginning of the retention period.

If you want to inspect the events, you can go to the Events tab and have a look at the data.


问:
Custom context provider not able to return anything including basic html elements
I'm following this tutorial and am up to the part about implementing a custom AuthContext provider. Here is the suggested code:

const AuthProvider = ({ children }) => {
  const [token, setToken] = React.useState(null);

  const handleLogin = async () => {
    const token = await fakeAuth();

    setToken(token);
  };

  const handleLogout = () => {
    setToken(null);
  };

  const value = {
    token,
    onLogin: handleLogin,
    onLogout: handleLogout,
  };

  return (
    <AuthContext.Provider value={value}> // AuthContext defined right above component; initialised as an empty object.
      {children}
    </AuthContext.Provider>
  );
};
```
<p>As far as I can tell, that's absolutely fine. But when I try adding it to my code (literally copy and paste it in) the return statement throws 9 errors. <code>Cannot find namespace 'AuthContext'.ts(2503)</code>, <code>'>' expected.ts(1005)</code>, <code>Operator '<' cannot be applied to types 'boolean' and 'RegExp'.ts(2365)</code> etc.</p>
<p>Even if I just try to return a <code>div</code>, I get <code>Cannot find name 'div'.ts(2304)</code>.</p>
<p>What's preventing me from being able to return any elements in my return statement?</p>
<p>EDIT: Update to include my full code.</p>
<pre class="lang-js prettyprint-override"><code>import React, { createContext, ReactNode, useState } from "react";

type AuthContextType = {
  token: string | undefined;
};

export const AuthContext = createContext<AuthContextType>(
  {} as AuthContextType
);

const fakeAuth = () =>
    new Promise((resolve: (arg0: string) => void) => {
      setTimeout(() => resolve("2342f2f1d131rf12"), 250);
    });

export const AuthProvider = ({ children }: {children: ReactNode}) => {
  const [token, setToken] = useState<string | undefined>();

  const handleLogin = async () => {
    const token = await fakeAuth();
    setToken(token);
  };

  const handleLogout = () => {
    setToken(undefined);
  };

  const value = {
    token,
    onLogin: handleLogin,
    onLogout: handleLogout,
  };

  return (
    <AuthContext.Provider value={value}>
      {children}
    </AuthContext.Provider>
  );
};
</code>```

答:
In the example you shared the context is created like this before creating the provider

```<code>const AuthContext = React.createContext(null);
</code>```

If you try something like below?

```<code>import React from "react";

const AuthContext = React.createContext(null);

const AuthProvider = ({ children }) => {
  const [token, setToken] = React.useState(null);

  const handleLogin = async () => {
    const token = await fakeAuth();

    setToken(token);
  };

  const handleLogout = () => {
    setToken(null);
  };

  const value = {
    token,
    onLogin: handleLogin,
    onLogout: handleLogout,
  };

  return (
    <AuthContext.Provider value={value}>
      {children}
    </AuthContext.Provider>
  );
};
</code>```

Body:
I'm following this tutorial and am up to the part about implementing a custom AuthContext provider. Here is the suggested code:

const AuthProvider = ({ children }) => {
  const [token, setToken] = React.useState(null);

  const handleLogin = async () => {
    const token = await fakeAuth();

    setToken(token);
  };

  const handleLogout = () => {
    setToken(null);
  };

  const value = {
    token,
    onLogin: handleLogin,
    onLogout: handleLogout,
  };

  return (
    <AuthContext.Provider value={value}> // AuthContext defined right above component; initialised as an empty object.
      {children}
    </AuthContext.Provider>
  );
};

As far as I can tell, that's absolutely fine. But when I try adding it to my code (literally copy and paste it in) the return statement throws 9 errors. Cannot find namespace 'AuthContext'.ts(2503), '>' expected.ts(1005), Operator '<' cannot be applied to types 'boolean' and 'RegExp'.ts(2365) etc.

Even if I just try to return a div, I get Cannot find name 'div'.ts(2304).

What's preventing me from being able to return any elements in my return statement?

EDIT: Update to include my full code.

import React, { createContext, ReactNode, useState } from "react";

type AuthContextType = {
  token: string | undefined;
};

export const AuthContext = createContext<AuthContextType>(
  {} as AuthContextType
);

const fakeAuth = () =>
    new Promise((resolve: (arg0: string) => void) => {
      setTimeout(() => resolve("2342f2f1d131rf12"), 250);
    });

export const AuthProvider = ({ children }: {children: ReactNode}) => {
  const [token, setToken] = useState<string | undefined>();

  const handleLogin = async () => {
    const token = await fakeAuth();
    setToken(token);
  };

  const handleLogout = () => {
    setToken(undefined);
  };

  const value = {
    token,
    onLogin: handleLogin,
    onLogout: handleLogout,
  };

  return (
    <AuthContext.Provider value={value}>
      {children}
    </AuthContext.Provider>
  );
};

Body:
In the example you shared the context is created like this before creating the provider

const AuthContext = React.createContext(null);

If you try something like below?

import React from "react";

const AuthContext = React.createContext(null);

const AuthProvider = ({ children }) => {
  const [token, setToken] = React.useState(null);

  const handleLogin = async () => {
    const token = await fakeAuth();

    setToken(token);
  };

  const handleLogout = () => {
    setToken(null);
  };

  const value = {
    token,
    onLogin: handleLogin,
    onLogout: handleLogout,
  };

  return (
    <AuthContext.Provider value={value}>
      {children}
    </AuthContext.Provider>
  );
};


问:
Why if i created a mock i am still getting error?
i am doing testing, i made a test in that test i create a mock for a fake function

```<code>jest.mock('@/services/myService', ()=>({getAvailables: jest.fn().mockReturnValue()}))
</code>```

that function is running in my component

```<code> onMounted(async () => {
        const answer = await getAvailables1()
        const answer = await getAvailables2()
        const answer = await getAvailables3()
</code>```

but still i am getting this error

(node:81921) UnhandledPromiseRejectionWarning: TypeError: (0 , _ContractService.getAvailables1) is not a function
(node:81921) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag

if i put like this first getAvailables2

```<code> onMounted(async () => {
            const answer = await getAvailables2()
            const answer = await getAvailables1()
</code>```

i am getting this error
(node:81921) UnhandledPromiseRejectionWarning: TypeError: (0 , _ContractService.getAvailables2) is not a function

if i put like this first getAvailables3

```<code> onMounted(async () => {
            const answer = await getAvailables3()
            const answer = await getAvailables2()
</code>```

i am getting this error
(node:81921) UnhandledPromiseRejectionWarning: TypeError: (0 , _ContractService.getAvailables3) is not a function

also i try with mockResolvedValue, does not worked

```<code>export const getAvailables = async () => {
  let response
  let error
  try {
    response = await getData()
  } catch (err) {
    error = err
    throw err
  }
  return { response, error }
}
</code>```

答:
It looks like you want a mock partial:

jest.mock('@/services/myService', () => {
  const originalModule = jest.requireActual('@/services/myService');

  return {
    __esModule: true,
    ...originalModule,
    getAvailables1: () => Promise.resolve({ foo: 'bar' }),
    getAvailables2: () => Promise.resolve({ foo: 'baz' }),
    getAvailables3: () => Promise.resolve({ foo: 'bad' }),
    /* any other method of your service that gets called */
  };
});
```

This will mock the provided functions in the mock while the rest of the service will function as in the original.

Body:
i am doing testing, i made a test in that test i create a mock for a fake function

jest.mock('@/services/myService', ()=>({getAvailables: jest.fn().mockReturnValue()}))

that function is running in my component

 onMounted(async () => {
        const answer = await getAvailables1()
        const answer = await getAvailables2()
        const answer = await getAvailables3()

but still i am getting this error

(node:81921) UnhandledPromiseRejectionWarning: TypeError: (0 , _ContractService.getAvailables1) is not a function
(node:81921) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag

if i put like this first getAvailables2

 onMounted(async () => {
            const answer = await getAvailables2()
            const answer = await getAvailables1()

i am getting this error
(node:81921) UnhandledPromiseRejectionWarning: TypeError: (0 , _ContractService.getAvailables2) is not a function

if i put like this first getAvailables3

 onMounted(async () => {
            const answer = await getAvailables3()
            const answer = await getAvailables2()

i am getting this error
(node:81921) UnhandledPromiseRejectionWarning: TypeError: (0 , _ContractService.getAvailables3) is not a function

also i try with mockResolvedValue, does not worked

export const getAvailables = async () => {
  let response
  let error
  try {
    response = await getData()
  } catch (err) {
    error = err
    throw err
  }
  return { response, error }
}

Body:
It looks like you want a mock partial:

jest.mock('@/services/myService', () => {
  const originalModule = jest.requireActual('@/services/myService');

  return {
    __esModule: true,
    ...originalModule,
    getAvailables1: () => Promise.resolve({ foo: 'bar' }),
    getAvailables2: () => Promise.resolve({ foo: 'baz' }),
    getAvailables3: () => Promise.resolve({ foo: 'bad' }),
    /* any other method of your service that gets called */
  };
});

This will mock the provided functions in the mock while the rest of the service will function as in the original.