问:
How to convert JSON data into table and store into Postgres DB using Node JS?
I need help in converting json data into datatable and store inside postgresql DB.

For example,

```<code>[{"name":"abc", "role":"swe"}, {"name":"xyz", "role":"Tester"}]
</code>```

I'd like to convert the above data or lets say store the data as a table with rows and columns.

I think we do have a datatype called "json" but it's to store the entire json right? But I want to convert as real table what we see in DB, like below,

```<code>   name   |  role
--------------+-------
"abc"     | "swe"
"xyz"     | "Tester
</code>```

Could you please help me how to parse them please? I'm using Node JS.

Any pointers will be helpful. Thanks a lot for your time.

答:
May be something like you need ?

```<code>select jsonb_array_elements(j)->>'name' as name, jsonb_array_elements(j)->>'role' as role
from (
    select '[{"name":"abc", "role":"swe"}, {"name":"xyz", "role":"Tester"}]'::jsonb as j
) t
</code>```

If so, You can simply do INSERT INTO .. SELECT for saving data into table

demo: https://rextester.com/LIV68809

Body:
I need help in converting json data into datatable and store inside postgresql DB.

For example,

[{"name":"abc", "role":"swe"}, {"name":"xyz", "role":"Tester"}]

I'd like to convert the above data or lets say store the data as a table with rows and columns.

I think we do have a datatype called "json" but it's to store the entire json right? But I want to convert as real table what we see in DB, like below,

   name   |  role
--------------+-------
"abc"     | "swe"
"xyz"     | "Tester

Could you please help me how to parse them please? I'm using Node JS.

Any pointers will be helpful. Thanks a lot for your time.

Body:
May be something like you need ?

select jsonb_array_elements(j)->>'name' as name, jsonb_array_elements(j)->>'role' as role
from (
    select '[{"name":"abc", "role":"swe"}, {"name":"xyz", "role":"Tester"}]'::jsonb as j
) t

If so, You can simply do INSERT INTO .. SELECT for saving data into table

demo: https://rextester.com/LIV68809


来源: stackexchange

问:
How to call another class with button and pass variable between classes?
I want to pass variable between GUI classes. Below, when i Show Other_b  class, it Show frame but i couldn't get Main1 class' data to there. However when i try to Show Other_a class, it passes x value (because of it is inside of __init__) but it doesn't pass the y value because of it is related to Btn2(and of course because of not having any frame to pressing button).

How can i overcome this problem? Any help would be appreciated.

```<code>import wx

class Main1 (wx.Frame):
    def __init__(self,parent):
        wx.Frame.__init__ ( self, parent )
        self.bSizer1 = wx.BoxSizer( wx.VERTICAL )
        self.Btn1 = wx.Button( self, wx.ID_ANY, u"Btn1", wx.DefaultPosition, wx.DefaultSize, 0 )
        self.bSizer1.Add( self.Btn1, 1, wx.ALL|wx.EXPAND, 5 )
        self.SetSizer( self.bSizer1 )
        self.Btn1.Bind( wx.EVT_BUTTON, self.btn1_f )

    def btn1_f( self, event ):
        print("here 1")
        self.x = 12
        self.y = 30

        a=Other_a(self).Show()
        b=Other_b(self).Show()

class Other_a (wx.Frame):
    def __init__(self, foo):
        wx.Frame.__init__ ( self )
        self.bSizer2 = wx.BoxSizer( wx.VERTICAL )
        self.Btn2 = wx.Button( self, wx.ID_ANY, u"Btn 2", wx.DefaultPosition, wx.DefaultSize, 0 )
        self.bSizer2.Add( self.Btn2, 0, wx.ALL|wx.EXPAND, 5 )
        self.SetSizer( self.bSizer2 )
        self.Btn2.Bind( wx.EVT_BUTTON, self.btn2_f )

        print("here 2")
        print(foo.x)

    def btn2_f(self,foo):
        print("here 3")
        print(foo.y)

class Other_b (wx.Frame):
    def __init__(self,parent):
        wx.Frame.__init__ ( self, parent )
        self.bSizer3 = wx.BoxSizer( wx.VERTICAL )
        self.Btn3 = wx.Button( self, wx.ID_ANY, u"Btn 2", wx.DefaultPosition, wx.DefaultSize, 0 )
        self.bSizer3.Add( self.Btn3, 0, wx.ALL|wx.EXPAND, 5 )
        self.SetSizer( self.bSizer3 )
        self.Btn3.Bind( wx.EVT_BUTTON, self.btn3_f )
        print("here 4")

    def btn3_f(self,event):
        print("here 5")
        print(self.x)

if __name__ == "__main__":
    app = wx.App(False)
    frame = Main1(None)
    frame.Show(True)
    app.MainLoop()
</code>```

答:
I arrange your code a little bit so now it passes the variable from the Main1 class to the Other classes.

The main problem is that you are not passing the variables at all. The line a=Other_a(self).Show() in your code is actually giving the entire frame to the Other_a class. If you want to pass the x and y values then you can give a list [self.x, self.y] as the foo value for Other_a.

Then, in the instance a of the class Other_a you need a line like self.foo = foo. Why? Because you want to use the value of foo outside of the __init__ method.

The same happens with b and Other_b.

Take a look here and here for more details about how clasess work in Python.

```<code>import wx

class Main1(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent=parent)
        self.bSizer1 = wx.BoxSizer(wx.VERTICAL)
        self.Btn1 = wx.Button(self, wx.ID_ANY, "Btn1", wx.DefaultPosition, wx.DefaultSize, 0)
        self.bSizer1.Add(self.Btn1, 1, wx.ALL|wx.EXPAND, 5)
        self.SetSizer(self.bSizer1)
        self.Btn1.Bind(wx.EVT_BUTTON, self.btn1_f)

    def btn1_f(self, event):
        print("here 1")
        self.x = 12
        self.y = 30

        a = Other_a([self.x, self.y])
        a.Show()
        b = Other_b(self.x)
        b.Show()

class Other_a(wx.Frame):
    def __init__(self, foo):
        self.foo = foo
        wx.Frame.__init__(self, None)
        self.bSizer2 = wx.BoxSizer(wx.VERTICAL)
        self.Btn2 = wx.Button(self, wx.ID_ANY, "Btn 2a", wx.DefaultPosition, wx.DefaultSize, 0)
        self.bSizer2.Add(self.Btn2, 0, wx.ALL|wx.EXPAND, 5)
        self.SetSizer(self.bSizer2)
        self.Btn2.Bind(wx.EVT_BUTTON, self.btn2_f)

        print("here 2")
        print(self.foo[0])

    def btn2_f(self, event):
        print("here 3")
        print(self.foo[1])

class Other_b(wx.Frame):
    def __init__(self, x):
        self.x = x
        wx.Frame.__init__(self, None)
        self.bSizer3 = wx.BoxSizer(wx.VERTICAL)
        self.Btn3 = wx.Button(self, wx.ID_ANY, "Btn 2b", wx.DefaultPosition, wx.DefaultSize, 0)
        self.bSizer3.Add(self.Btn3, 0, wx.ALL|wx.EXPAND, 5)
        self.SetSizer(self.bSizer3)
        self.Btn3.Bind(wx.EVT_BUTTON, self.btn3_f)
        print("here 4")

    def btn3_f(self, event):
        print("here 5")
        print(self.x)

if __name__ == "__main__":
    app = wx.App(False)
    frame = Main1(None)
    frame.Show(True)
    app.MainLoop()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to pass variable between GUI classes. Below, when i Show Other_b  class, it Show frame but i couldn't get Main1 class' data to there. However when i try to Show Other_a class, it passes x value (because of it is inside of __init__) but it doesn't pass the y value because of it is related to Btn2(and of course because of not having any frame to pressing button).

How can i overcome this problem? Any help would be appreciated.

import wx

class Main1 (wx.Frame):
    def __init__(self,parent):
        wx.Frame.__init__ ( self, parent )
        self.bSizer1 = wx.BoxSizer( wx.VERTICAL )
        self.Btn1 = wx.Button( self, wx.ID_ANY, u"Btn1", wx.DefaultPosition, wx.DefaultSize, 0 )
        self.bSizer1.Add( self.Btn1, 1, wx.ALL|wx.EXPAND, 5 )
        self.SetSizer( self.bSizer1 )
        self.Btn1.Bind( wx.EVT_BUTTON, self.btn1_f )

    def btn1_f( self, event ):
        print("here 1")
        self.x = 12
        self.y = 30

        a=Other_a(self).Show()
        b=Other_b(self).Show()

class Other_a (wx.Frame):
    def __init__(self, foo):
        wx.Frame.__init__ ( self )
        self.bSizer2 = wx.BoxSizer( wx.VERTICAL )
        self.Btn2 = wx.Button( self, wx.ID_ANY, u"Btn 2", wx.DefaultPosition, wx.DefaultSize, 0 )
        self.bSizer2.Add( self.Btn2, 0, wx.ALL|wx.EXPAND, 5 )
        self.SetSizer( self.bSizer2 )
        self.Btn2.Bind( wx.EVT_BUTTON, self.btn2_f )

        print("here 2")
        print(foo.x)

    def btn2_f(self,foo):
        print("here 3")
        print(foo.y)

class Other_b (wx.Frame):
    def __init__(self,parent):
        wx.Frame.__init__ ( self, parent )
        self.bSizer3 = wx.BoxSizer( wx.VERTICAL )
        self.Btn3 = wx.Button( self, wx.ID_ANY, u"Btn 2", wx.DefaultPosition, wx.DefaultSize, 0 )
        self.bSizer3.Add( self.Btn3, 0, wx.ALL|wx.EXPAND, 5 )
        self.SetSizer( self.bSizer3 )
        self.Btn3.Bind( wx.EVT_BUTTON, self.btn3_f )
        print("here 4")

    def btn3_f(self,event):
        print("here 5")
        print(self.x)

if __name__ == "__main__":
    app = wx.App(False)
    frame = Main1(None)
    frame.Show(True)
    app.MainLoop()

Body:
I arrange your code a little bit so now it passes the variable from the Main1 class to the Other classes.

The main problem is that you are not passing the variables at all. The line a=Other_a(self).Show() in your code is actually giving the entire frame to the Other_a class. If you want to pass the x and y values then you can give a list [self.x, self.y] as the foo value for Other_a.

Then, in the instance a of the class Other_a you need a line like self.foo = foo. Why? Because you want to use the value of foo outside of the __init__ method.

The same happens with b and Other_b.

Take a look here and here for more details about how clasess work in Python.

import wx

class Main1(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent=parent)
        self.bSizer1 = wx.BoxSizer(wx.VERTICAL)
        self.Btn1 = wx.Button(self, wx.ID_ANY, "Btn1", wx.DefaultPosition, wx.DefaultSize, 0)
        self.bSizer1.Add(self.Btn1, 1, wx.ALL|wx.EXPAND, 5)
        self.SetSizer(self.bSizer1)
        self.Btn1.Bind(wx.EVT_BUTTON, self.btn1_f)

    def btn1_f(self, event):
        print("here 1")
        self.x = 12
        self.y = 30

        a = Other_a([self.x, self.y])
        a.Show()
        b = Other_b(self.x)
        b.Show()

class Other_a(wx.Frame):
    def __init__(self, foo):
        self.foo = foo
        wx.Frame.__init__(self, None)
        self.bSizer2 = wx.BoxSizer(wx.VERTICAL)
        self.Btn2 = wx.Button(self, wx.ID_ANY, "Btn 2a", wx.DefaultPosition, wx.DefaultSize, 0)
        self.bSizer2.Add(self.Btn2, 0, wx.ALL|wx.EXPAND, 5)
        self.SetSizer(self.bSizer2)
        self.Btn2.Bind(wx.EVT_BUTTON, self.btn2_f)

        print("here 2")
        print(self.foo[0])

    def btn2_f(self, event):
        print("here 3")
        print(self.foo[1])

class Other_b(wx.Frame):
    def __init__(self, x):
        self.x = x
        wx.Frame.__init__(self, None)
        self.bSizer3 = wx.BoxSizer(wx.VERTICAL)
        self.Btn3 = wx.Button(self, wx.ID_ANY, "Btn 2b", wx.DefaultPosition, wx.DefaultSize, 0)
        self.bSizer3.Add(self.Btn3, 0, wx.ALL|wx.EXPAND, 5)
        self.SetSizer(self.bSizer3)
        self.Btn3.Bind(wx.EVT_BUTTON, self.btn3_f)
        print("here 4")

    def btn3_f(self, event):
        print("here 5")
        print(self.x)

if __name__ == "__main__":
    app = wx.App(False)
    frame = Main1(None)
    frame.Show(True)
    app.MainLoop()


问:
MySQL create stored procedure syntax with delimiter
I am trying to create a stored procedure in MySQL using a delimiter like this:

```<code>use am;

DELIMITER $$

CREATE PROCEDURE addfields()
BEGIN
  DECLARE done INT DEFAULT FALSE;
  DECLARE acc INT(16);
  DECLARE validId INT DEFAULT 0;

END $$

DELIMITER ;
</code>```

It gives me an error:

```<code>#1304 - PROCEDURE addfields already exists
</code>```

What is the proper syntax for making a stored procedure with a delimiter and dropping it if it exists first?

答:
MY SQL STORED PROCEDURE CREATION

```<code>DELIMiTER $$
create procedure GetUserRolesEnabled(in UserId int)
Begin

select * from users
where id=UserId ;
END $$
DELIMITER ;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to create a stored procedure in MySQL using a delimiter like this:

use am;

DELIMITER $$

CREATE PROCEDURE addfields()
BEGIN
  DECLARE done INT DEFAULT FALSE;
  DECLARE acc INT(16);
  DECLARE validId INT DEFAULT 0;

END $$

DELIMITER ;

It gives me an error:

#1304 - PROCEDURE addfields already exists

What is the proper syntax for making a stored procedure with a delimiter and dropping it if it exists first?

Body:
MY SQL STORED PROCEDURE CREATION

DELIMiTER $$
create procedure GetUserRolesEnabled(in UserId int)
Begin

select * from users
where id=UserId ;
END $$
DELIMITER ;


问:
How to display progress indicator in flutter?
I am trying to show a progress indicator when i am logging in. I have created a boolean value to toggle when I want to show and hide the indicator, however i am not able to figure out where exactly i should show the indicator.

I can add it as one of my widgets in my Container where I am displaying all other screen widgets, however i dont want it to interfere with other widgets and rather show on top of all of them.  How can I achieve this?  How can I achieve this?

Thanks in advance.

My code

```<code>import ....

class Login extends StatefulWidget{
...
}

class _LoginState extends State<Login> {

bool _loading = false;

  @override
  Widget build(BuildContext context){

    Future<Map<String, dynamic>> getData() async {
      var client = http.Client();

      //to SHOW Indicator
      setState(() {
        _loading = true;
      });

      var response = await client
          .post(
          Uri.encodeFull(
              ' api url '),
          body:
        {"email":"$username","password":"$password"}

      ).whenComplete(
          client.close);

      var res = json.decode(response.body);

      //to HIDE indicator
      setState(() {
        _loading = false;
      });

      if(response.statusCode <200 || response.statusCode > 400){
        print("Error");
         throwError();
      }
      if(response.statusCode == 200 ){
        widget.onSignedIn();
      }

      if (!mounted)
        return {'success': false};

      return json.decode(response.body);
    }

    Container view = Container(
      ....
    );

    return Scaffold(
        resizeToAvoidBottomPadding: false,
      body: view

    );
  }
}
</code>```

答:
You can use  xs_progress_hud: ^1.0.2 this library and Import from here

Show dialog

```<code> XsProgressHud.show(context);
</code>```

Hide dialog

```<code> XsProgressHud.hide();
</code>```

Here you can do something like this in your code.

```<code> Future<Map<String, dynamic>> getData() async {
      var client = http.Client();
      XsProgressHud.show(context);
      //to SHOW Indicator
      setState(() {
        _loading = true;
      });

      var response = await client
          .post(
          Uri.encodeFull(
              ' api url '),
          body:
        {"email":"$username","password":"$password"}

      ).whenComplete(
          client.close);

      var res = json.decode(response.body);

      //to HIDE indicator
      setState(() {
        _loading = false;
      });

      if(response.statusCode <200 || response.statusCode > 400){
        XsProgressHud.hide();
        print("Error");
         throwError();
      }
      if(response.statusCode == 200 ){
        XsProgressHud.hide();
        widget.onSignedIn();
      }

      if (!mounted)
        return {'success': false};

      return json.decode(response.body);
    }
</code>```

Body:
I am trying to show a progress indicator when i am logging in. I have created a boolean value to toggle when I want to show and hide the indicator, however i am not able to figure out where exactly i should show the indicator.

I can add it as one of my widgets in my Container where I am displaying all other screen widgets, however i dont want it to interfere with other widgets and rather show on top of all of them.  How can I achieve this?  How can I achieve this?

Thanks in advance.

My code

import ....

class Login extends StatefulWidget{
...
}

class _LoginState extends State<Login> {

bool _loading = false;

  @override
  Widget build(BuildContext context){

    Future<Map<String, dynamic>> getData() async {
      var client = http.Client();

      //to SHOW Indicator
      setState(() {
        _loading = true;
      });

      var response = await client
          .post(
          Uri.encodeFull(
              ' api url '),
          body:
        {"email":"$username","password":"$password"}

      ).whenComplete(
          client.close);

      var res = json.decode(response.body);

      //to HIDE indicator
      setState(() {
        _loading = false;
      });

      if(response.statusCode <200 || response.statusCode > 400){
        print("Error");
         throwError();
      }
      if(response.statusCode == 200 ){
        widget.onSignedIn();
      }

      if (!mounted)
        return {'success': false};

      return json.decode(response.body);
    }

    Container view = Container(
      ....
    );

    return Scaffold(
        resizeToAvoidBottomPadding: false,
      body: view

    );
  }
}

Body:
You can use  xs_progress_hud: ^1.0.2 this library and Import from here

Show dialog

 XsProgressHud.show(context);

Hide dialog

 XsProgressHud.hide();

Here you can do something like this in your code.

 Future<Map<String, dynamic>> getData() async {
      var client = http.Client();
      XsProgressHud.show(context);
      //to SHOW Indicator
      setState(() {
        _loading = true;
      });

      var response = await client
          .post(
          Uri.encodeFull(
              ' api url '),
          body:
        {"email":"$username","password":"$password"}

      ).whenComplete(
          client.close);

      var res = json.decode(response.body);

      //to HIDE indicator
      setState(() {
        _loading = false;
      });

      if(response.statusCode <200 || response.statusCode > 400){
        XsProgressHud.hide();
        print("Error");
         throwError();
      }
      if(response.statusCode == 200 ){
        XsProgressHud.hide();
        widget.onSignedIn();
      }

      if (!mounted)
        return {'success': false};

      return json.decode(response.body);
    }


问:
CMake's STREQUAL not working
According to the CMake documentation, the STREQUAL comparison is allowed to take either a VARIABLE or a STRING as either parameter. So, in this example below, the message does NOT print, which is broken:

```<code>set( FUBARTEST "OK" )
if( FUBARTEST STREQUAL "OK" )
    message( "It Worked" )
endif()
</code>```

Any reason why this isn't working as documented?

答:
The same thing happens when using ' instead of " for the string comparison

This won't work:

```<code>if( FUBARTEST STREQUAL 'OK' )
    message( "It Worked" )
endif()
</code>```

This works (except if there is a cache issue like mentioned above):

```<code>if( FUBARTEST STREQUAL "OK" )
    message( "It Worked" )
endif()
</code>```

Title: CMake's STREQUAL not working

Body:
According to the CMake documentation, the STREQUAL comparison is allowed to take either a VARIABLE or a STRING as either parameter. So, in this example below, the message does NOT print, which is broken:

set( FUBARTEST "OK" )
if( FUBARTEST STREQUAL "OK" )
    message( "It Worked" )
endif()

Any reason why this isn't working as documented?

Body:
The same thing happens when using ' instead of " for the string comparison

This won't work:

if( FUBARTEST STREQUAL 'OK' )
    message( "It Worked" )
endif()

This works (except if there is a cache issue like mentioned above):

if( FUBARTEST STREQUAL "OK" )
    message( "It Worked" )
endif()


问:
How to handle two different times if they are not in the same day?
I'm handling restaurant opening and closing hours , i am using moment to parse time it and it works perfect but there is one case in which its not working,
If the restaurant open at 9:00 am and closes 1:00 am (next day), it gives restaurant is closed no matter the time .</p>

```<code>   if (current_time.isBetween(opening_hour, close_hour))  {
     console.log('its open');
   } else {
     console.log('its closed');
   }

</code>```

答:
You should change the open/close strings to moment object as well.

```<code>var opening_time = moment("10:40", 'hh:mm')
var closing_time = moment("23:00", 'hh:mm:ss')

if (moment().isBetween(opening_time, closing_time)) {
  console.log("Open");
} else {
  console.log("Close")
}
</code>```

https://jsfiddle.net/w7e028fg/

Body:
I'm handling restaurant opening and closing hours , i am using moment to parse time it and it works perfect but there is one case in which its not working,
If the restaurant open at 9:00 am and closes 1:00 am (next day), it gives restaurant is closed no matter the time .

   if (current_time.isBetween(opening_hour, close_hour))  {
     console.log('its open');
   } else {
     console.log('its closed');
   }

Body:
You should change the open/close strings to moment object as well.

var opening_time = moment("10:40", 'hh:mm')
var closing_time = moment("23:00", 'hh:mm:ss')

if (moment().isBetween(opening_time, closing_time)) {
  console.log("Open");
} else {
  console.log("Close")
}

https://jsfiddle.net/w7e028fg/


问:
How to crop interiour of a contour?
I am new to image processing and also new to python. Can you explain properly about how to get the results? Here is my code :

```<code>import cv2
import numpy as np
img = cv2.imread("C:\\Users\\shashisanha\\Desktop\\shapes.jpg", cv2.IMREAD_GRAYSCALE)
_, threshold = cv2.threshold(img, 240, 255, cv2.THRESH_BINARY)
contours,_=cv2.findContours(threshold, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
    approx = cv2.approxPolyDP(cnt , 0.01*cv2.arcLength(cnt, True), True)
    cv2.drawContours(img,[approx],0,(0) , 5)
    if len(approx)==3:
        print(3)
cv2.imshow("shape",img)
cv2.waitKey(0)
cv2.destroyAllWindows()
</code>```

This is only for finding contour and now I want to crop it up.

答:
First you find the dimensions of the boundingbox of the contour:

x,y,w,h = cv2.boundingRect(cnt)

Then you create a new image that holds the region of the boundingrect:

subimg = img[y:y+h,x:x+w]

Title: How to crop interiour of a contour?

Body:
I am new to image processing and also new to python. Can you explain properly about how to get the results? Here is my code :

import cv2
import numpy as np
img = cv2.imread("C:\\Users\\shashisanha\\Desktop\\shapes.jpg", cv2.IMREAD_GRAYSCALE)
_, threshold = cv2.threshold(img, 240, 255, cv2.THRESH_BINARY)
contours,_=cv2.findContours(threshold, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
    approx = cv2.approxPolyDP(cnt , 0.01*cv2.arcLength(cnt, True), True)
    cv2.drawContours(img,[approx],0,(0) , 5)
    if len(approx)==3:
        print(3)
cv2.imshow("shape",img)
cv2.waitKey(0)
cv2.destroyAllWindows()

This is only for finding contour and now I want to crop it up.


问:
return last word in a file that starts with capital letter
I'm trying to make a simple script that seraches for a designated .txt file for the last word that starts with a capital letter and returns it. If there are no words that start with a capital letter, it returns an empty string.

This is what I have tried so far:

```<code>def find_last_capitalised(file_name):
    with open(file_name) as wordfile:
        text_str = wordfile.read()
        word_list = text_str.split()
        upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        for word in word_list:
            if word.rfind(upper):
                return word
            else:
                return " "
</code>```

but this isn't working.

I also tried this:

```<code>    with open(file_name) as wordfile:
        text_str = wordfile.read()
        word_list = text_str.split()
        for word in word_list:
            if word_list[-1].isupper():
                return word_list[-1]
            else:
                return " "
</code>```

Any help?

答:
```<code>def find_last_capitalised(word_list):
    lastCapWord = " "
    for word in word_list:
        print(word)
        if word[0].isupper():
            lastCapWord = word
    print('lastCapWord:', lastCapWord)
    return lastCapWord

word_list = ['this', 'is', 'A', 'test']
find_last_capitalised(word_list)
</code>```

Your algorithm is a little off. It doesn't go through each word in the list, instead it just returns based off the first word it sees. Assuming you make you make your word list into an array, the following code should work just fine.

Body:
I'm trying to make a simple script that seraches for a designated .txt file for the last word that starts with a capital letter and returns it. If there are no words that start with a capital letter, it returns an empty string.

This is what I have tried so far:

def find_last_capitalised(file_name):
    with open(file_name) as wordfile:
        text_str = wordfile.read()
        word_list = text_str.split()
        upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        for word in word_list:
            if word.rfind(upper):
                return word
            else:
                return " "

but this isn't working.

I also tried this:

    with open(file_name) as wordfile:
        text_str = wordfile.read()
        word_list = text_str.split()
        for word in word_list:
            if word_list[-1].isupper():
                return word_list[-1]
            else:
                return " "

Any help?

Body:
def find_last_capitalised(word_list):
    lastCapWord = " "
    for word in word_list:
        print(word)
        if word[0].isupper():
            lastCapWord = word
    print('lastCapWord:', lastCapWord)
    return lastCapWord

word_list = ['this', 'is', 'A', 'test']
find_last_capitalised(word_list)

Your algorithm is a little off. It doesn't go through each word in the list, instead it just returns based off the first word it sees. Assuming you make you make your word list into an array, the following code should work just fine.


问:
Abstract base class to force each derived classes to be Singleton
How do I make an abstract class that shall force each derived classes to be Singleton ? I use C#.</p>

答:
Here my implementation of Singleton inheritance:</p>

```<code>using System;
using System.Reflection;

namespace Mik.Singleton
{
    class Program
    {
        static void Main()
        {
            //You can not create an instance of class directly
            //Singleton1 singleton1 = new Singleton1();

            Singleton1 singleton1 = Singleton1.Instance;
            Singleton2 singleton2 = Singleton2.Instance;

            Console.WriteLine(singleton1.Singleton1Text);
            Console.WriteLine(singleton2.Singleton2Text);

            Console.ReadLine();
        }
    }

    public class SingletonBase<T> where T : class
    {
        #region Singleton implementation

        private static readonly object lockObj = new object();
        private static T _instance;

        protected SingletonBase() { }

        public static T Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (lockObj)
                    {
                        if (_instance == null)
                            _instance = CreateInstance();
                    }
                }
                return _instance;
            }
        }

        private static T CreateInstance()
        {
            ConstructorInfo constructor = typeof(T).GetConstructor(
                            BindingFlags.Instance | BindingFlags.NonPublic,
                            null, new Type[0],
                            new ParameterModifier[0]);

            if (constructor == null)
                throw new Exception(
                    $"Target type is missing private or protected no-args constructor: {typeof(T).FullName}");
            try
            {
                T instance = constructor.Invoke(new object[0]) as T;

                return instance;
            }
            catch (Exception e)
            {
                throw new Exception(
                    "Failed to create target: type=" + typeof(T).FullName, e);
            }
        }

        #endregion Singleton implementation
    }

    public class Singleton1 : SingletonBase<Singleton1>
    {
        private Singleton1() { }

        public string Singleton1Text { get; } = "Singleton1Text value";
    }

    public class Singleton2 : SingletonBase<Singleton2>
    {
        private Singleton2() { }

        public string Singleton2Text { get; } = "Singleton2Text value";
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Here my implementation of Singleton inheritance:

using System;
using System.Reflection;

namespace Mik.Singleton
{
    class Program
    {
        static void Main()
        {
            //You can not create an instance of class directly
            //Singleton1 singleton1 = new Singleton1();

            Singleton1 singleton1 = Singleton1.Instance;
            Singleton2 singleton2 = Singleton2.Instance;

            Console.WriteLine(singleton1.Singleton1Text);
            Console.WriteLine(singleton2.Singleton2Text);

            Console.ReadLine();
        }
    }

    public class SingletonBase<T> where T : class
    {
        #region Singleton implementation

        private static readonly object lockObj = new object();
        private static T _instance;

        protected SingletonBase() { }

        public static T Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (lockObj)
                    {
                        if (_instance == null)
                            _instance = CreateInstance();
                    }
                }
                return _instance;
            }
        }

        private static T CreateInstance()
        {
            ConstructorInfo constructor = typeof(T).GetConstructor(
                            BindingFlags.Instance | BindingFlags.NonPublic,
                            null, new Type[0],
                            new ParameterModifier[0]);

            if (constructor == null)
                throw new Exception(
                    $"Target type is missing private or protected no-args constructor: {typeof(T).FullName}");
            try
            {
                T instance = constructor.Invoke(new object[0]) as T;

                return instance;
            }
            catch (Exception e)
            {
                throw new Exception(
                    "Failed to create target: type=" + typeof(T).FullName, e);
            }
        }

        #endregion Singleton implementation
    }

    public class Singleton1 : SingletonBase<Singleton1>
    {
        private Singleton1() { }

        public string Singleton1Text { get; } = "Singleton1Text value";
    }

    public class Singleton2 : SingletonBase<Singleton2>
    {
        private Singleton2() { }

        public string Singleton2Text { get; } = "Singleton2Text value";
    }
}


问:
ValueError: Invalid tensors 'input' were found
I'm not able to convert .pb to tflite

Here is the command that I'm executing to generate .pb I am successful in generating it.

```<code>IMAGE_SIZE=224
ARCHITECTURE="mobilenet_1_1.0_${IMAGE_SIZE}"

python retrain.py
 --bottleneck_dir=tf_files/bottlenecks
 --how_many_training_steps=500
 --model_dir=tf_files/models/
 --summaries_dir=tf_files/training_summaries/"${ARCHITECTURE}"
  --output_graph=tf_files/retrained_graph.pb
  --output_labels=tf_files/retrained_labels.txt
  --architecture="${ARCHITECTURE}"
  --image_dir=tf_files/flower_photos
</code>```

Once I am trying to create that .pb to .tflite get fail with same error "ValueError: Invalid tensors 'input' were found."

```<code>tflite_convert \
  --output_file=foo.tflite \
  --graph_def_file=retrained_graph.pb \
  --input_arrays=input \
  --output_arrays=MobilenetV1/Predictions/Reshape_1
</code>```

答:
I just follow this google code demo.

https://codelabs.developers.google.com/codelabs/tensorflow-for-poets/#0

Working fine

```<code>IMAGE_SIZE=224
ARCHITECTURE="mobilenet_1.0_${IMAGE_SIZE}"

python -m scripts.retrain \
--bottleneck_dir=tf_files/bottlenecks \
--how_many_training_steps=500 \
--model_dir=tf_files/models/ \
--summaries_dir=tf_files/training_summaries/"${ARCHITECTURE}" \
--output_graph=tf_files/retrained_graph.pb \
--output_labels=tf_files/retrained_labels.txt \
--architecture="${ARCHITECTURE}" \
--image_dir=tf_files/flower_photos

tflite_convert   --graph_def_file=tf_files/retrained_graph.pb   --output_file=tf_files/optimized_graph.tflite   --input_format=TENSORFLOW_GRAPHDEF   --output_format=TFLITE   --input_shape=1,224,224,3   --input_array=input   --output_array=final_result   --inference_type=FLOAT   --input_data_type=FLOAT
</code>```

I made one change for it simpley change mobilenet version.

Body:
I'm not able to convert .pb to tflite

Here is the command that I'm executing to generate .pb I am successful in generating it.

IMAGE_SIZE=224
ARCHITECTURE="mobilenet_1_1.0_${IMAGE_SIZE}"

python retrain.py
 --bottleneck_dir=tf_files/bottlenecks
 --how_many_training_steps=500
 --model_dir=tf_files/models/
 --summaries_dir=tf_files/training_summaries/"${ARCHITECTURE}"
  --output_graph=tf_files/retrained_graph.pb
  --output_labels=tf_files/retrained_labels.txt
  --architecture="${ARCHITECTURE}"
  --image_dir=tf_files/flower_photos

Once I am trying to create that .pb to .tflite get fail with same error "ValueError: Invalid tensors 'input' were found."

tflite_convert \
  --output_file=foo.tflite \
  --graph_def_file=retrained_graph.pb \
  --input_arrays=input \
  --output_arrays=MobilenetV1/Predictions/Reshape_1

Body:
I just follow this google code demo.

https://codelabs.developers.google.com/codelabs/tensorflow-for-poets/#0

Working fine

IMAGE_SIZE=224
ARCHITECTURE="mobilenet_1.0_${IMAGE_SIZE}"

python -m scripts.retrain \
--bottleneck_dir=tf_files/bottlenecks \
--how_many_training_steps=500 \
--model_dir=tf_files/models/ \
--summaries_dir=tf_files/training_summaries/"${ARCHITECTURE}" \
--output_graph=tf_files/retrained_graph.pb \
--output_labels=tf_files/retrained_labels.txt \
--architecture="${ARCHITECTURE}" \
--image_dir=tf_files/flower_photos

tflite_convert   --graph_def_file=tf_files/retrained_graph.pb   --output_file=tf_files/optimized_graph.tflite   --input_format=TENSORFLOW_GRAPHDEF   --output_format=TFLITE   --input_shape=1,224,224,3   --input_array=input   --output_array=final_result   --inference_type=FLOAT   --input_data_type=FLOAT

I made one change for it simpley change mobilenet version.


问:
JAVA_HOME is incorrectly set when launching Zookeeper on Windows
I'm having a "JAVA_HOME is incorrectly set" error when launching Zookeeper on windows with zkServer.cmd while it is correctly set!
When I issue %JAVA_HOME% I got C:\Program Files\Java\jdk1.7.0_45 which is the correct directory of the java instalation.

I suspect the problem is due to the space in program files, as when I issue %JAVA_HOME%\bin\java.exe (the command used in zkEnv.cmd) I got:

```<code>'C:\Program' is not recognized as an internal or external command, operable program or batch file.
</code>```

How I can fix this?

答:
in my environment i setted to:

JAVA_HOME=C:\Progra~1\Java\jdk1.8.0_65

Note for Windows users on 64-bit systems

Progra~1 = 'Program Files'

Progra~2 = 'Program Files(x86)'

Body:
I'm having a "JAVA_HOME is incorrectly set" error when launching Zookeeper on windows with zkServer.cmd while it is correctly set!
When I issue %JAVA_HOME% I got C:\Program Files\Java\jdk1.7.0_45 which is the correct directory of the java instalation.

I suspect the problem is due to the space in program files, as when I issue %JAVA_HOME%\bin\java.exe (the command used in zkEnv.cmd) I got:

'C:\Program' is not recognized as an internal or external command, operable program or batch file.

How I can fix this?


问:
Get value based on input in two dimensional array
I have a 2 dimensional array

```<code>var years = [[-1,"0 years"], [1,"< 1 year"], [2,"1-3 years"], [3,"> 3 years"]];
</code>```

And I want to get the number of years based on user Input, which is -1,1,2,3 how can I do it in Javascript?

I'm trying using years[years_input] but I don't get the correct value.

答:
Try this,hope it works

let years = [
  [-1, "0 years"],
  [1, "< 1 year"],
  [2, "1-3 years"],
  [3, "> 3 years"]
];

function getYear(year) {

  return years.find(el => el.indexOf(year) > -1)[1]

}

console.log(getYear(-1))
console.log(getYear(1))
console.log(getYear(2))
console.log(getYear(3))```

Body:
I have a 2 dimensional array

var years = [[-1,"0 years"], [1,"< 1 year"], [2,"1-3 years"], [3,"> 3 years"]];

And I want to get the number of years based on user Input, which is -1,1,2,3 how can I do it in Javascript?

I'm trying using years[years_input] but I don't get the correct value.


问:
Pre-processing training data for Microsoft Custom Translator Text JA->EN? (tokenization, lowercase)
I'm creating a custom model out of a training set in Microsoft Translator Text for Japanese (JA) to English (EN) translation. Should the training data be tokenized, and is all lowercase preferable?

In Japanese the quotation characters (「」 and 『』)are different than in English. In JA training data should these be tokenized (separated by a space)? In parallel EN training data should the EN quotation marks ("") be used, or the JA quotation marks?

Beyond that, is any other pre-processing desirable such as transforming the text to all lowercase? The text casing returned by the model when deployed does not matter.

答:
Leave the training material as you would present it to a human reader, with casing and punctuation intact. Casing and punctuation matter in translation, it is a relevant signal for the engine to receive. No reason to apply your own tokenization, it would interfere with the system's tokenization.
The best training material is sentence- or segment aligned, like you would get it in a TMX or XLIFF in an export from a TM. </p>


问:
Can't access services on master node via public IP (but I can SSH?)
I've been toying around with kubernetes and have run into an issue. The core of my problem is that while I can access the services on the master node by curling localhost, attempting to access the same via the public ip and port doing the same on another machine (or web browser) hangs forever.

I've configured the cluster using a terraform script (runs as root):

```<code>#!/bin/bash -v

exec 3>&1 4>&2
trap 'exec 2>&4 1>&3' 0 1 2 3
exec 1>startup_log.out 2>&1

curl -fsSL https://download.docker.com/linux/ubuntu/gpg | apt-key add -
curl -s https://packages.cloud.google.com/apt/doc/apt-key.gpg | apt-key add -

add-apt-repository \
   "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
   $(lsb_release -cs) \
   stable"

cat << EOF | tee /etc/apt/sources.list.d/kubernetes.list
deb https://apt.kubernetes.io/ kubernetes-xenial main
EOF

apt-get update
apt-get install -y docker-ce
apt-mark hold docker-ce
apt-get install -y kubelet kubeadm kubectl kubernetes-cni
apt-mark hold kubelet kubeadm kubectl

kubeadm init --token=${k8stoken} --pod-network-cidr=10.244.0.0/16

mkdir -p /home/ubuntu/.kube
cp -i /etc/kubernetes/admin.conf /home/ubuntu/.kube/config
chown -R $(id -u ubuntu):$(id -g ubuntu) /home/ubuntu/.kube/

usermod -aG docker ubuntu

echo "net.bridge.bridge-nf-call-iptables=1" | tee -a /etc/sysctl.conf
sysctl -p

runuser -l ubuntu -c '\
   kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/bc79dd1505b0c8681ece4de4c0d86c5cd2643275/Documentation/kube-flannel.yml
'
</code>```

After which I SSH to the master node (works fine) and run:

```<code>$ git clone https://github.com/linuxacademy/robot-shop.git
$ kubectl create namespace robot-shop
$ kubectl -n robot-shop create -f ~/robot-shop/K8s/descriptors/
$ ubuntu@ip-10-0-100-167:~$ kubectl -n robot-shop get svc
NAME        TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)              AGE
cart        ClusterIP   10.105.152.135   <none>        8080/TCP             15s
catalogue   ClusterIP   10.97.111.197    <none>        8080/TCP             15s
dispatch    ClusterIP   None             <none>        55555/TCP            15s
mongodb     ClusterIP   10.107.178.183   <none>        27017/TCP            15s
mysql       ClusterIP   10.110.254.52    <none>        3306/TCP             15s
payment     ClusterIP   10.99.195.138    <none>        8080/TCP             15s
rabbitmq    ClusterIP   10.99.70.232     <none>        5672/TCP,15672/TCP   15s
ratings     ClusterIP   10.98.80.21      <none>        80/TCP               15s
redis       ClusterIP   10.101.232.84    <none>        6379/TCP             15s
shipping    ClusterIP   10.106.246.97    <none>        8080/TCP             15s
user        ClusterIP   10.109.120.146   <none>        8080/TCP             15s
web         NodePort    10.97.162.113    <none>        8080:30080/TCP       15s
</code>```

Services appear to startup fine but I can't access anything on this host externally. I've tried following this debugging guide, and identified a discrepancy that when I type:

```<code>$ iptables-save | grep
</code>```

I get nothing. But the doc doesn't make a recommendation as to a fix. Has anyone seen this issue before? I'm concerned my config file has a problem with it but I can't figure out what!

答: As @Ashworth mentioned in the comment issue has been solved after appropriate service port enabled in the particular security group for the relevant master node instance.</p>

Body:
I've been toying around with kubernetes and have run into an issue. The core of my problem is that while I can access the services on the master node by curling localhost, attempting to access the same via the public ip and port doing the same on another machine (or web browser) hangs forever.

I've configured the cluster using a terraform script (runs as root):

#!/bin/bash -v

exec 3>&1 4>&2
trap 'exec 2>&4 1>&3' 0 1 2 3
exec 1>startup_log.out 2>&1

curl -fsSL https://download.docker.com/linux/ubuntu/gpg | apt-key add -
curl -s https://packages.cloud.google.com/apt/doc/apt-key.gpg | apt-key add -

add-apt-repository \
   "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
   $(lsb_release -cs) \
   stable"

cat << EOF | tee /etc/apt/sources.list.d/kubernetes.list
deb https://apt.kubernetes.io/ kubernetes-xenial main
EOF

apt-get update
apt-get install -y docker-ce
apt-mark hold docker-ce
apt-get install -y kubelet kubeadm kubectl kubernetes-cni
apt-mark hold kubelet kubeadm kubectl

kubeadm init --token=${k8stoken} --pod-network-cidr=10.244.0.0/16

mkdir -p /home/ubuntu/.kube
cp -i /etc/kubernetes/admin.conf /home/ubuntu/.kube/config
chown -R $(id -u ubuntu):$(id -g ubuntu) /home/ubuntu/.kube/

usermod -aG docker ubuntu

echo "net.bridge.bridge-nf-call-iptables=1" | tee -a /etc/sysctl.conf
sysctl -p

runuser -l ubuntu -c '\
   kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/bc79dd1505b0c8681ece4de4c0d86c5cd2643275/Documentation/kube-flannel.yml
'

After which I SSH to the master node (works fine) and run:

$ git clone https://github.com/linuxacademy/robot-shop.git
$ kubectl create namespace robot-shop
$ kubectl -n robot-shop create -f ~/robot-shop/K8s/descriptors/
$ ubuntu@ip-10-0-100-167:~$ kubectl -n robot-shop get svc
NAME        TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)              AGE
cart        ClusterIP   10.105.152.135   <none>        8080/TCP             15s
catalogue   ClusterIP   10.97.111.197    <none>        8080/TCP             15s
dispatch    ClusterIP   None             <none>        55555/TCP            15s
mongodb     ClusterIP   10.107.178.183   <none>        27017/TCP            15s
mysql       ClusterIP   10.110.254.52    <none>        3306/TCP             15s
payment     ClusterIP   10.99.195.138    <none>        8080/TCP             15s
rabbitmq    ClusterIP   10.99.70.232     <none>        5672/TCP,15672/TCP   15s
ratings     ClusterIP   10.98.80.21      <none>        80/TCP               15s
redis       ClusterIP   10.101.232.84    <none>        6379/TCP             15s
shipping    ClusterIP   10.106.246.97    <none>        8080/TCP             15s
user        ClusterIP   10.109.120.146   <none>        8080/TCP             15s
web         NodePort    10.97.162.113    <none>        8080:30080/TCP       15s

Services appear to startup fine but I can't access anything on this host externally. I've tried following this debugging guide, and identified a discrepancy that when I type:

$ iptables-save | grep

I get nothing. But the doc doesn't make a recommendation as to a fix. Has anyone seen this issue before? I'm concerned my config file has a problem with it but I can't figure out what!


问:
Can any one point me which widget is this?
PFA screenshot

The widget below symbol 'G' with three options "All", "Web", "Apps"..Whats the name of the widget?.

答: You might want to check this question which says it is the Quick Action Dialog.</p>


答:
You can use includes:

var years = [[-1,"0 years"], [1,"< 1 year"], [2,"1-3 years"], [3,"> 3 years"]];

var input = +prompt()

for(var i = 0; i < years.length; i++) {
  if (years[i].includes(input)) {
  console.log(years[i][1])
  break
  }
}```

Title: Get value based on input in two dimensional array


问:
creating the sql query for company supervisors
I have four tables

```<code>create table emp (emp_ss int, emp_name nvarchar(20));

create table comp(comp_name nvarchar(20), comp_address nvarchar(20));

create table works (emp_ss int, comp_name nvarchar(20));

create table supervises (spv_ss int, emp_ss int );
</code>```

Here SUPRVISER_SS and EMP_SS are subset of SS. Now I have to find:

the name of all the companies who have more than 4 supervisors

I have made a query for the above problem but not sure whether it is correct or not

```<code>SELECT COMP_NAME , COUNT(EMP_SS) FROM WORKS
WHERE EMP_SS IN (SELECT DISTINCT SPV_SS FROM supervises)
GROUP BY COMP_NAME
HAVING COUNT(EMP_SS) > 4;
</code>```

the name of supervisors who have the largest number of employees
but unable to get the required result of the above condition

SELECT SPV_SS, COUNT(*) max_ FROM supervises GROUP BY SPV_SS

答:
You don't need to have a seperate table for supervisors unless they come with extra information that doesn't belong in the employee table, just add an extra field (foreign key) in Employee table that links to the primary key in the same table.

First question: select company just use a group by companyid clause and then check if the count of supervisors is larger than 4 for.

Second question: select count(empid) and supervisor, use group by supervisor clause and add order by clause on the count column

I explained the logic, as for the actual sql code, you're gonna have to figure that out yourself.

Body:
I have four tables

create table emp (emp_ss int, emp_name nvarchar(20));

create table comp(comp_name nvarchar(20), comp_address nvarchar(20));

create table works (emp_ss int, comp_name nvarchar(20));

create table supervises (spv_ss int, emp_ss int );

Here SUPRVISER_SS and EMP_SS are subset of SS. Now I have to find:

the name of all the companies who have more than 4 supervisors

I have made a query for the above problem but not sure whether it is correct or not

SELECT COMP_NAME , COUNT(EMP_SS) FROM WORKS
WHERE EMP_SS IN (SELECT DISTINCT SPV_SS FROM supervises)
GROUP BY COMP_NAME
HAVING COUNT(EMP_SS) > 4;

the name of supervisors who have the largest number of employees
but unable to get the required result of the above condition

SELECT SPV_SS, COUNT(*) max_ FROM supervises GROUP BY SPV_SS


问:
EF Core Multiple Entities have a property of a common type
I have the following schema (abbreviated to relevant code)

class Person
{
  public int Id {get;set;}
  public string Name {get;set;}
  public ICollection<MetaData> MetaData {get;set;}
}
class Car
{
  public int Id {get;set;}
  public string Make {get;set;}
  public ICollection<MetaData> MetaData {get;set;}
}
class Building
{
  public int Id {get;set;}
  public string Address {get;set;}
  public ICollection<MetaData> MetaData {get;set;}
}
class MetaData
{
  public int Id {get;set;}
  public string CLRType {get;set;}
  public string Value {get;set;}

  // These two fields together form a connection to the other entities
  public int Key {get;set;} // the PK of the connected entity
  public string Type {get;set;} // nameof(Entity)
}
```

How can I represent this in EF Core?

Using OwnsMany create a table per type+metadata type connection
If I try using TPH, then the metadata table ends up with additional fields per connected entity

Neither of those solutions are ideal for me.
I do not need restraints in the database, I just want a way to express this relation in such a way that EF Core will be able to hydrate my models
Even if I have to provide the sql manually (even for both reads and writes) that would be workable

If this is not possible with the existing APIs provided, is there a way I can write extensions on my own that will do what I need?

答:
You are mixing two forms of relations.
You can either have type safe relations and replicate the foreign keys on your Metadata class (don't forget to add unique constraints)

```<code>class MetaData
{
  public int Id {get;set;}
  public string CLRType {get;set;}
  public string Value {get;set;}
  public int PersonId {get;set;}
  public Person Person {get;set;}
  public int CarId {get;set;}
  public Car Car {get;set;}
  public int BuildingId {get;set;}
  public Person Building {get;set;}
}
</code>```

Or keep it loosely coupled and do the joins by hand

```<code>class Car
{
  public int Id {get;set;}
  public string Make {get;set;}
}

// not mapped in the database, just used for display purposes
class CarViewModel
{
  public int Id {get;set;}
  public string Make {get;set;}
}

var carIds = new [] { 1, 2, 3 };

// we use 2 contexts here so we can query both tables at the same time.
// otherwise Task.WhenAll(...) would throw an exception.
// you should also disable change tracking to improve speed.
var carsTask = context1.Cars
    .Where(c => carIds.Contains(c.Id))
    .ToListAsync();
var metadataTask = context2.Metadata
    .Where(m => carIds.Contains(m.Key) && m.Type == "Car")
    .GroupBy(m => m.Key)
    .ToDictionaryAsync(g => g.Key, g => g.ToList());

await Task.WhenAll(carsTask, metadataTask).ConfigureAwait(false);

var cars = carsTask.Result
    .Select(c => new CarViewModel
    {
        Id = c.Id,
        Make = c.Make,
        Metadata = metadataTask.Result.TryGetValue(c.Id, out var m) ? m : Array.Empty<Metadata>(),
    })
    .ToList();
</code>```

Or have separate tables for the metadata

```<code>abstract class MetaData
{
  public int Id {get;set;}
  public string CLRType {get;set;}
  public string Value {get;set;}
}

class CarMetaData : MetaData
{
  public int CarId {get;set;}
  public Car Car {get;set;}
}

class Car
{
  public int Id {get;set;}
  public string Make {get;set;}
  public ICollection<CarMetaData> MetaData {get;set;}
}
</code>```

Which version suits you best is up to your and your specific business needs.

Body:
I have the following schema (abbreviated to relevant code)

class Person
{
  public int Id {get;set;}
  public string Name {get;set;}
  public ICollection<MetaData> MetaData {get;set;}
}
class Car
{
  public int Id {get;set;}
  public string Make {get;set;}
  public ICollection<MetaData> MetaData {get;set;}
}
class Building
{
  public int Id {get;set;}
  public string Address {get;set;}
  public ICollection<MetaData> MetaData {get;set;}
}
class MetaData
{
  public int Id {get;set;}
  public string CLRType {get;set;}
  public string Value {get;set;}

  // These two fields together form a connection to the other entities
  public int Key {get;set;} // the PK of the connected entity
  public string Type {get;set;} // nameof(Entity)
}

How can I represent this in EF Core?

Using OwnsMany create a table per type+metadata type connection
If I try using TPH, then the metadata table ends up with additional fields per connected entity

Neither of those solutions are ideal for me.
I do not need restraints in the database, I just want a way to express this relation in such a way that EF Core will be able to hydrate my models
Even if I have to provide the sql manually (even for both reads and writes) that would be workable

If this is not possible with the existing APIs provided, is there a way I can write extensions on my own that will do what I need?

Body:
You are mixing two forms of relations.
You can either have type safe relations and replicate the foreign keys on your Metadata class (don't forget to add unique constraints)

class MetaData
{
  public int Id {get;set;}
  public string CLRType {get;set;}
  public string Value {get;set;}
  public int PersonId {get;set;}
  public Person Person {get;set;}
  public int CarId {get;set;}
  public Car Car {get;set;}
  public int BuildingId {get;set;}
  public Person Building {get;set;}
}

Or keep it loosely coupled and do the joins by hand

class Car
{
  public int Id {get;set;}
  public string Make {get;set;}
}

// not mapped in the database, just used for display purposes
class CarViewModel
{
  public int Id {get;set;}
  public string Make {get;set;}
}

var carIds = new [] { 1, 2, 3 };

// we use 2 contexts here so we can query both tables at the same time.
// otherwise Task.WhenAll(...) would throw an exception.
// you should also disable change tracking to improve speed.
var carsTask = context1.Cars
    .Where(c => carIds.Contains(c.Id))
    .ToListAsync();
var metadataTask = context2.Metadata
    .Where(m => carIds.Contains(m.Key) && m.Type == "Car")
    .GroupBy(m => m.Key)
    .ToDictionaryAsync(g => g.Key, g => g.ToList());

await Task.WhenAll(carsTask, metadataTask).ConfigureAwait(false);

var cars = carsTask.Result
    .Select(c => new CarViewModel
    {
        Id = c.Id,
        Make = c.Make,
        Metadata = metadataTask.Result.TryGetValue(c.Id, out var m) ? m : Array.Empty<Metadata>(),
    })
    .ToList();

Or have separate tables for the metadata

abstract class MetaData
{
  public int Id {get;set;}
  public string CLRType {get;set;}
  public string Value {get;set;}
}

class CarMetaData : MetaData
{
  public int CarId {get;set;}
  public Car Car {get;set;}
}

class Car
{
  public int Id {get;set;}
  public string Make {get;set;}
  public ICollection<CarMetaData> MetaData {get;set;}
}

Which version suits you best is up to your and your specific business needs.


问:
Remove 2 characters in oracle sql
I have a column that contains 12 digits but user wants only to generate a 10 digits.

I tried the trim, ltrim function but nothing work. Below are the queries I tried.

```<code>ltrim('10', 'column_name')
ltrim('10', column_name)
ltrim(10, column_name)
</code>```

For example I have a column that contains a 12 digit number

```<code>100000000123
100000000456
100000000789
</code>```

and the expected result I want is

```<code>0000000123
0000000456
0000000789
</code>```

答: try to use    SUBSTR(column_name, 2)

Title: Remove 2 characters in oracle sql

Body:
I have a column that contains 12 digits but user wants only to generate a 10 digits.

I tried the trim, ltrim function but nothing work. Below are the queries I tried.

ltrim('10', 'column_name')
ltrim('10', column_name)
ltrim(10, column_name)

For example I have a column that contains a 12 digit number

100000000123
100000000456
100000000789

and the expected result I want is

0000000123
0000000456
0000000789

Body: try to use    SUBSTR(column_name, 2)


问:
How to avoid branching for a call where the number of arguments is dependent on conditionals?
I'm converting some code from using CreateProcess to use boost-process instead. I need to replace my CreateProcess usages with boost::process::child. The problem is they have incompatible ways for me to say "I want to use the default value". What used to be a one line command has become sixteen if statements.

The function I currently use works like this (simplified):

```<code>void CreateProcess(int, float);
</code>```

Each parameter had a value you could use to indicate you wanted the default. I'll use 0 in this example:

```<code>int int_param = ...;
float float_param = ...;

CreateProcess(0, 0); //Use both defaults
CreateProcess(int_param, 0); //Use default float
CreateProcess(0, float_param); //Use default int
CreateProcess(int_param, float_param); //No defaults
</code>```

This is a common design. You know what I am talking about. Whether I wanted to use the default value or not could be decided with a simple conditional, such as (... ? 0 : int_param). This allowed every CreateProcess call to be a single line of code.

```<code>CreateProcess( (... ? 0 : int_param), (... ? 0 : float_param) );
</code>```

Where I used to call CreateProcess, I now want to create a child class. The constructor for child works like this:

```<code>template<typename ...Args>
explicit child(Args&&...args);
</code>```

Instead of passing a specific value to use a default, I have to pass nothing.

```<code>int int_param = ...;
float float_param = ...;

child c; //Use both defaults
child c(int_param); //Use default float
child c(float_param); //Use default int
child c(int_param, float_param); //No defaults
child c(float_param, int_param); //Argument order is irrelevant
</code>```

So far my only "solution" is to use if branches.

```<code>if (...) {
    if (...)
        child c;
    else
        child c(float_param);
} else {
    if (...)
        child c(int_param);
    else
        child c(int_param, float_param);
}
</code>```

This example has only two possible arguments and it becomes four branches. The real child has four possible arguments, so every instance has sixteen branches.

What I would like is some way of building the call to avoid this branching. A solution specific to boost::process is also fine.

FYI, the last two arguments to child may or may not be the same type.

答:
Use a function to create child objects which contains the branches. Pass std::optional as parameters:

```<code>child make_child(const std::optional<int>& int_param,
                 const std::optional<float>& float_param)
{
    if (int_param && float_param) {
        return child(std::to_string(int_param.value()),
                     std::to_string(float_param.value()));
    }

    // Rest of the branches ...
}
</code>```

This allows you to create a child object like this:

```<code>child c = make_child(... ? std::optional<int>() : int_param,
                     ... ? std::optional<float>() : float_param);
</code>```

Body:
I'm converting some code from using CreateProcess to use boost-process instead. I need to replace my CreateProcess usages with boost::process::child. The problem is they have incompatible ways for me to say "I want to use the default value". What used to be a one line command has become sixteen if statements.

The function I currently use works like this (simplified):

void CreateProcess(int, float);

Each parameter had a value you could use to indicate you wanted the default. I'll use 0 in this example:

int int_param = ...;
float float_param = ...;

CreateProcess(0, 0); //Use both defaults
CreateProcess(int_param, 0); //Use default float
CreateProcess(0, float_param); //Use default int
CreateProcess(int_param, float_param); //No defaults

This is a common design. You know what I am talking about. Whether I wanted to use the default value or not could be decided with a simple conditional, such as (... ? 0 : int_param). This allowed every CreateProcess call to be a single line of code.

CreateProcess( (... ? 0 : int_param), (... ? 0 : float_param) );

Where I used to call CreateProcess, I now want to create a child class. The constructor for child works like this:

template<typename ...Args>
explicit child(Args&&...args);

Instead of passing a specific value to use a default, I have to pass nothing.

int int_param = ...;
float float_param = ...;

child c; //Use both defaults
child c(int_param); //Use default float
child c(float_param); //Use default int
child c(int_param, float_param); //No defaults
child c(float_param, int_param); //Argument order is irrelevant

So far my only "solution" is to use if branches.

if (...) {
    if (...)
        child c;
    else
        child c(float_param);
} else {
    if (...)
        child c(int_param);
    else
        child c(int_param, float_param);
}

This example has only two possible arguments and it becomes four branches. The real child has four possible arguments, so every instance has sixteen branches.

What I would like is some way of building the call to avoid this branching. A solution specific to boost::process is also fine.

FYI, the last two arguments to child may or may not be the same type.

Body:
Use a function to create child objects which contains the branches. Pass std::optional as parameters:

child make_child(const std::optional<int>& int_param,
                 const std::optional<float>& float_param)
{
    if (int_param && float_param) {
        return child(std::to_string(int_param.value()),
                     std::to_string(float_param.value()));
    }

    // Rest of the branches ...
}

This allows you to create a child object like this:

child c = make_child(... ? std::optional<int>() : int_param,
                     ... ? std::optional<float>() : float_param);


问:
Does ruby have real multithreading?
I know about the "cooperative" threading of ruby using green threads. How can I create real "OS-level" threads in my application in order to make use of multiple cpu cores for processing?</p>

答: How about using drb? It's not real multi-threading but communication between several processes, but you can use it now in 1.8 and it's fairly low friction.</p>

OwnerDisplayName: Rooby Noob

Title: Does ruby have real multithreading?

OwnerDisplayName: ujh


问:
How can I use datetime.strptime on a string in the format '0000-00-00T00:00:00+00:00'?
Due to my application's circumstances, I would prefer to use datetime.strptime instead of dateutil.parser.

After looking at the docs, I thought that %Y-%m-%dT%H:%M:%S%z may be the proper format for parsing a date string like this. Yet it still gives me an error.

Example

from datetime import datetime

d = '0000-00-00T00:00:00+00:00'
datetime.strptime(d, '%Y-%m-%dT%H:%M:%S%z')
```

```ValueError: time data '0000-00-00T00:00:00+00:00' does not
            match format '%Y-%m-%dT%H:%M:%S%z'
```

答: I'm not sure what you are trying to do with your code but the error is not given because of the wrong format but because '0000-00-00T00:00:00+00:00' is not a valid time, because zero is no date. If you try it with another time like: '1900-01-01T00:00:00+00:00' it should work just fine.

Body:
Due to my application's circumstances, I would prefer to use datetime.strptime instead of dateutil.parser.

After looking at the docs, I thought that %Y-%m-%dT%H:%M:%S%z may be the proper format for parsing a date string like this. Yet it still gives me an error.

Example

from datetime import datetime

d = '0000-00-00T00:00:00+00:00'
datetime.strptime(d, '%Y-%m-%dT%H:%M:%S%z')

ValueError: time data '0000-00-00T00:00:00+00:00' does not
            match format '%Y-%m-%dT%H:%M:%S%z'


问:
Http POST request returns body as json encoded in base64
eXist-db POST request with authorization gives response that contains 2 items. First are headers and the second one is invisible. When I put it in string() function then it reveals as base64 binary string that contains json.
Json is format default type (and propably the only one) that API im connected to sends authorization data.

I tried to check if some headers are added by eXist but seems like nothing is wrong. Used request catcher and got that data:

```<code>OST / HTTP/1.1
Host: endpoint.requestcatcher.com
Accept-Encoding: gzip,deflate
Authorization: Basic OWJhMT...
Connection: Keep-Alive
Content-Length: 0
Content-Type: code
Status-Only: false
User-Agent: Apache-HttpClient/4.5.5 (Java/12.0.1)
</code>```

This is my function code:

```<code>declare function auth:get-access-token() {
    let $accessTokenResponse :=
    hc:send-request(<hc:request method = 'post' href='https://endpoint.requestcatcher.com'>
    <hc:header name = 'Authorization' value = 'Basic { $auth:base64credentials }'/>
    <hc:header name = 'status-only' value = 'false'/>
     </hc:request>)
    return $accessTokenResponse
</code>```

};

The actual result is that response body contains base64 encoded string that contains json data.

I would like to receive json data that is originally sent by API authorization endpoint.

答:
If you know that your API returns JSON, you can handle the Base64-encoded response body simply by passing it to util:binary-to-string() and then, assuming you want parsed JSON rather than raw text, to fn:parse-json().

Here is sample code showing some additional logic for handling the response. Some remarks:

I'm using a sample endpoint that returns JSON.

It checks the response to ensure a 200 response; if not, it returns just the status and message as a map.

It handles various cases of response body types as outlined in the EXPath HTTP Client spec.

It takes the additional step with JSON bodies of parsing the JSON.

The code:

```<code>xquery version "3.1";

import module namespace http = "http://expath.org/ns/http-client";

let $url := "https://jsonplaceholder.typicode.com/todos/1"
let $response := http:send-request(<http:request method = "get" href="{$url}"/>)
let $head := $response[1]
let $body := $response[2]
let $media-type := $head/http:body/@media-type => tokenize("; ") => head()
return
    if ($head/@status eq "200") then
        (: When the response body contains XML or HTML, it is parsed into a document node. :)
        if ($body instance of document-node()) then
            $body
        (: When the media type is text/*, convert the Base64Binary body to string :)
        else if (starts-with($media-type, "text/")) then
            $body => util:binary-to-string()
        (: Parse JSON into XDM :)
        else if ($media-type eq "application/json") then
            $body => util:binary-to-string() => parse-json()
        (: Assume the body is just binary :)
        else
            $body
    else
        map {
            "status": $head/@status => string(),
            "message": $head/@message => string()
        }
</code>```

The response on my system:

```<code>map {
    "userId": 1.0e0,
    "completed": false(),
    "title": "delectus aut autem",
    "id": 1.0e0
}
</code>```

The benefit of parsing the JSON is that you can query the result, e.g., $result?title would return "delectus aut autem".

Body:
eXist-db POST request with authorization gives response that contains 2 items. First are headers and the second one is invisible. When I put it in string() function then it reveals as base64 binary string that contains json.
Json is format default type (and propably the only one) that API im connected to sends authorization data.

I tried to check if some headers are added by eXist but seems like nothing is wrong. Used request catcher and got that data:

OST / HTTP/1.1
Host: endpoint.requestcatcher.com
Accept-Encoding: gzip,deflate
Authorization: Basic OWJhMT...
Connection: Keep-Alive
Content-Length: 0
Content-Type: code
Status-Only: false
User-Agent: Apache-HttpClient/4.5.5 (Java/12.0.1)

This is my function code:

declare function auth:get-access-token() {
    let $accessTokenResponse :=
    hc:send-request(<hc:request method = 'post' href='https://endpoint.requestcatcher.com'>
    <hc:header name = 'Authorization' value = 'Basic { $auth:base64credentials }'/>
    <hc:header name = 'status-only' value = 'false'/>
     </hc:request>)
    return $accessTokenResponse

};

The actual result is that response body contains base64 encoded string that contains json data.

I would like to receive json data that is originally sent by API authorization endpoint.

Body:
If you know that your API returns JSON, you can handle the Base64-encoded response body simply by passing it to util:binary-to-string() and then, assuming you want parsed JSON rather than raw text, to fn:parse-json().

Here is sample code showing some additional logic for handling the response. Some remarks:

I'm using a sample endpoint that returns JSON.

It checks the response to ensure a 200 response; if not, it returns just the status and message as a map.

It handles various cases of response body types as outlined in the EXPath HTTP Client spec.

It takes the additional step with JSON bodies of parsing the JSON.

The code:

xquery version "3.1";

import module namespace http = "http://expath.org/ns/http-client";

let $url := "https://jsonplaceholder.typicode.com/todos/1"
let $response := http:send-request(<http:request method = "get" href="{$url}"/>)
let $head := $response[1]
let $body := $response[2]
let $media-type := $head/http:body/@media-type => tokenize("; ") => head()
return
    if ($head/@status eq "200") then
        (: When the response body contains XML or HTML, it is parsed into a document node. :)
        if ($body instance of document-node()) then
            $body
        (: When the media type is text/*, convert the Base64Binary body to string :)
        else if (starts-with($media-type, "text/")) then
            $body => util:binary-to-string()
        (: Parse JSON into XDM :)
        else if ($media-type eq "application/json") then
            $body => util:binary-to-string() => parse-json()
        (: Assume the body is just binary :)
        else
            $body
    else
        map {
            "status": $head/@status => string(),
            "message": $head/@message => string()
        }

The response on my system:

map {
    "userId": 1.0e0,
    "completed": false(),
    "title": "delectus aut autem",
    "id": 1.0e0
}

The benefit of parsing the JSON is that you can query the result, e.g., $result?title would return "delectus aut autem".


问:
How do I open a new tab in PowerShell 6?
I'm using PowerShell 6 on a Windows 10 machine, 64-bit. I can't figure out how to create new tabs for separate execution environments.

This page from the Microsoft help docs says, "On the File menu, click New PowerShell Tab." But in my PowerShell, there is no menu bar at all.

And this page says to click on the plus sign on the title bar, but again for me, there is no plus sign. The page also says you can hit Ctrl + Win + T to open a new tab, but when I try that, it simply puts ^T on the console.

Can anyone help me figure out how I can enable the tabs feature?

答:
At the top of the second link, you provided it says in big red text: "Sets and Tabs will NOT ship in the next mainstream release of Windows (codenamed RS5)"

And here it says that the feature was pulled but remains a high priority


问:
How to flag items with repeated names and with condition its value less than 20?
Problem

How to return "True" for the repeated items and with both values less than 20?

```<code>=COUNTIF(A:A, A1)>1
</code>```

I am able to detect repeated items, but not sure how to combine another condition.

Expected Results

答:
I didn't try this but it should work:

```<code>=SUMPRODUCT((A:A=A1)*(B:B<20))>1
</code>```

The function evaluates column one with condition one and column two with condition two. Then it multiplies both result vectors and sums the elements of the resulting vector.
If both conditions are met more than one time the function evaluates to TRUE, else to FALSE.

Body:
Problem

How to return "True" for the repeated items and with both values less than 20?

=COUNTIF(A:A, A1)>1

I am able to detect repeated items, but not sure how to combine another condition.

Expected Results

Body:
I didn't try this but it should work:

=SUMPRODUCT((A:A=A1)*(B:B<20))>1

The function evaluates column one with condition one and column two with condition two. Then it multiplies both result vectors and sums the elements of the resulting vector.
If both conditions are met more than one time the function evaluates to TRUE, else to FALSE.


问:
How can i use a variable in a for loop in a command ? (c#)
So i have a matrix of buttons, from a1f to a10f and from a to j, so a1f is on the top left and j10 is on the buttom right.

I want to to something like this:

for (i = 1; i < 11; i++)
  {
      a{i}f.BackgroundImage = Properties.Resources._1mal2_1_Rebellion;
      b{i}f.BackgroundImage = Properties.Resources._1mal2_2_Rebellion;
      a{i}f.Enabled = false;
      a{i}f.Tag = "playerShip";
      b{i}f.Enabled = false;
      b{i}f.Tag = "playerShip";
  }
```

<p>so the first loop would be:</p>

<pre class="lang-cs prettyprint-override"><code>a1f.BackgroundImage = Properties.Resources._1mal2_1_Rebellion;
b1f.BackgroundImage = Properties.Resources._1mal2_2_Rebellion;
a1f.Enabled = false;
a1f.Tag = "playerShip";
b1f.Enabled = false;
b1f.Tag = "playerShip";
</code>```

the second would be:

a2f.BackgroundImage = Properties.Resources._1mal2_1_Rebellion;
b2f.BackgroundImage = Properties.Resources._1mal2_2_Rebellion;
a2f.Enabled = false;
a2f.Tag = "playerShip";
b2f.Enabled = false;
b2f.Tag = "playerShip";
```

and so on..

a{i}f or a[i]f isnt working.

答:
If you can't iterate the controls, you could store them in a temp array.

But you would probably better doing by generating the controls. It might be the next level for improvement. For now, you could try this:

For example:

```<code>// create arrays which contains the controls.
var aShips = new [] { a1f, a2f, a3f, a4f, a5f, a6f, a7f, a8f, a9f, a10f };
var bShips = new [] { b1f, b2f, b3f, b4f, b5f, b6f, b7f, b8f, b9f, b10f };

// notice the 0  and the < 10, because arrays are zero-indexed
for (i = 0; i < 10; i++)
{
    // now you can access them via the array.
    aShips[i].BackgroundImage = Properties.Resources._1mal2_1_Rebellion;
    aShips[i].Enabled = false;
    aShips[i].Tag = "playerShip";

    bShips[i].BackgroundImage = Properties.Resources._1mal2_2_Rebellion;
    bShips[i].Enabled = false;
    bShips[i].Tag = "playerShip";
}
</code>```

Body:
So i have a matrix of buttons, from a1f to a10f and from a to j, so a1f is on the top left and j10 is on the buttom right.

I want to to something like this:

for (i = 1; i < 11; i++)
  {
      a{i}f.BackgroundImage = Properties.Resources._1mal2_1_Rebellion;
      b{i}f.BackgroundImage = Properties.Resources._1mal2_2_Rebellion;
      a{i}f.Enabled = false;
      a{i}f.Tag = "playerShip";
      b{i}f.Enabled = false;
      b{i}f.Tag = "playerShip";
  }

so the first loop would be:

a1f.BackgroundImage = Properties.Resources._1mal2_1_Rebellion;
b1f.BackgroundImage = Properties.Resources._1mal2_2_Rebellion;
a1f.Enabled = false;
a1f.Tag = "playerShip";
b1f.Enabled = false;
b1f.Tag = "playerShip";

the second would be:

a2f.BackgroundImage = Properties.Resources._1mal2_1_Rebellion;
b2f.BackgroundImage = Properties.Resources._1mal2_2_Rebellion;
a2f.Enabled = false;
a2f.Tag = "playerShip";
b2f.Enabled = false;
b2f.Tag = "playerShip";

and so on..

a{i}f or a[i]f isnt working.

Body:
If you can't iterate the controls, you could store them in a temp array.

But you would probably better doing by generating the controls. It might be the next level for improvement. For now, you could try this:

For example:

// create arrays which contains the controls.
var aShips = new [] { a1f, a2f, a3f, a4f, a5f, a6f, a7f, a8f, a9f, a10f };
var bShips = new [] { b1f, b2f, b3f, b4f, b5f, b6f, b7f, b8f, b9f, b10f };

// notice the 0  and the < 10, because arrays are zero-indexed
for (i = 0; i < 10; i++)
{
    // now you can access them via the array.
    aShips[i].BackgroundImage = Properties.Resources._1mal2_1_Rebellion;
    aShips[i].Enabled = false;
    aShips[i].Tag = "playerShip";

    bShips[i].BackgroundImage = Properties.Resources._1mal2_2_Rebellion;
    bShips[i].Enabled = false;
    bShips[i].Tag = "playerShip";
}


问:
Coinbase Pro API - invalid signature
This is edited from original post:

From the docs:

Signing a Message The CB-ACCESS-SIGN header is generated by creating a
  sha256 HMAC using the base64-decoded secret key on the prehash string
  timestamp + method + requestPath + body (where + represents string
  concatenation) and base64-encode the output. The timestamp value is
  the same as the CB-ACCESS-TIMESTAMP header.

Here is information from a key I deleted. This is from Coinbase Pro Sandbox:

publicKey:

```<code>06057d5b5e03d0f8587a248330402b21
</code>```

passPhrase:

```<code>gcgs6k6rp0f
</code>```

secretKey: EFAToD5heo66GIgZlT2TIZzJf8TYlmxyeRxRYDHTBv3lTt9XN6uaNS0RNAy0os/caR47x6EiPDOV3Ik+YzrfEA==

I'm using angular, specifically the node.js crypto-js library:

```<code>private generateSignaturePro(timestamp: string, method: string, resourceUrl: string, requestBody: string): string {
    var prehash: string = timestamp + method + resourceUrl + requestBody;
    var key = (Buffer.from(this.secretKey, 'base64')).toString();
    return crypto.enc.Base64.stringify(crypto.HmacSHA256(prehash, key));
}
</code>```

Server time is Time: 2019-05-20T19:01:38.711Z Epoch: 1558378898.711 (from /time endpoint)

here is my request and the server response:

Request:

```<code>Request URL: https://api-public.sandbox.pro.coinbase.com/accounts
Request Method: GET
Status Code: 400
Remote Address: 104.16.161.226:443
Referrer Policy: no-referrer-when-downgrade
</code>```

Request Headers:

```<code>Provisional headers are shown
Accept: application/json, text/plain, */*
CB-ACCESS-KEY: 06057d5b5e03d0f8587a248330402b21
CB-ACCESS-PASSPHRASE: gcgs6k6rp0f
CB-ACCESS-SIGN: 0cc2BnQYdUhLucXSPwMTjpHjJ32G3RXSH44rSsEopvjAtY90uRCMVy6xUrzg/A/aRJBLqx390fcZc7lmJeP++g==
CB-ACCESS-TIMESTAMP: 1558378899
Referer: https://localhost:44342/dashboard
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Safari/537.36
</code>```

Response Headers:

```<code>access-control-allow-headers: Content-Type, Accept, cb-session, cb-fp
access-control-allow-methods: GET,POST,DELETE,PUT
access-control-allow-origin: *
access-control-expose-headers: cb-before, cb-after, cb-gdpr
access-control-max-age: 7200
cache-control: no-store
cf-cache-status: MISS
cf-ray: 4da08f74ba97cf68-IAD
content-length: 31
content-type: application/json; charset=utf-8
date: Mon, 20 May 2019 19:01:38 GMT
etag: W/"1f-4RjKVp8I05+xcnQ5/G16yRoMSKU"
expect-ct: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
server: cloudflare
status: 400
strict-transport-security: max-age=15552000; includeSubDomains
vary: Accept-Encoding
x-content-type-options: nosniff
x-dns-prefetch-control: off
x-download-options: noopen
x-frame-options: SAMEORIGIN
x-xss-protection: 1; mode=block
</code>```

Response:

```<code>{"message":"invalid signature"}
</code>```

What am I doing wrong?

EDIT: Changed method to the SHA 256 version.  Still doesn't work.

答:
From the gdax-java (as it was named prior to "coinbase pro") library the generate signature method is:

```<code> String prehash = timestamp + method.toUpperCase() + requestPath + body;

 byte[] secretDecoded = Base64.getDecoder().decode(secretKey);
 keyspec = new SecretKeySpec(secretDecoded, "HmacSHA256");
 sha256 = (Mac) GdaxConstants.SHARED_MAC.clone();
 sha256.init(keyspec);
 return Base64.getEncoder().encodeToString(sha256.doFinal(prehash.getBytes()));
</code>```

At least on initial inspection the code you're using specifies using SHA512 rather than HmacSHA256, so I'd suspect that to be a probabale cause.

There is also more help with NodeJS in the right hand column here for generating the signatures. https://docs.pro.coinbase.com/#creating-a-request

Title: Coinbase Pro API - invalid signature

Body:
This is edited from original post:

From the docs:

Signing a Message The CB-ACCESS-SIGN header is generated by creating a
  sha256 HMAC using the base64-decoded secret key on the prehash string
  timestamp + method + requestPath + body (where + represents string
  concatenation) and base64-encode the output. The timestamp value is
  the same as the CB-ACCESS-TIMESTAMP header.

Here is information from a key I deleted. This is from Coinbase Pro Sandbox:

publicKey:

06057d5b5e03d0f8587a248330402b21

passPhrase:

gcgs6k6rp0f

secretKey: EFAToD5heo66GIgZlT2TIZzJf8TYlmxyeRxRYDHTBv3lTt9XN6uaNS0RNAy0os/caR47x6EiPDOV3Ik+YzrfEA==

I'm using angular, specifically the node.js crypto-js library:

private generateSignaturePro(timestamp: string, method: string, resourceUrl: string, requestBody: string): string {
    var prehash: string = timestamp + method + resourceUrl + requestBody;
    var key = (Buffer.from(this.secretKey, 'base64')).toString();
    return crypto.enc.Base64.stringify(crypto.HmacSHA256(prehash, key));
}

Server time is Time: 2019-05-20T19:01:38.711Z Epoch: 1558378898.711 (from /time endpoint)

here is my request and the server response:

Request:

Request URL: https://api-public.sandbox.pro.coinbase.com/accounts
Request Method: GET
Status Code: 400
Remote Address: 104.16.161.226:443
Referrer Policy: no-referrer-when-downgrade

Request Headers:

Provisional headers are shown
Accept: application/json, text/plain, */*
CB-ACCESS-KEY: 06057d5b5e03d0f8587a248330402b21
CB-ACCESS-PASSPHRASE: gcgs6k6rp0f
CB-ACCESS-SIGN: 0cc2BnQYdUhLucXSPwMTjpHjJ32G3RXSH44rSsEopvjAtY90uRCMVy6xUrzg/A/aRJBLqx390fcZc7lmJeP++g==
CB-ACCESS-TIMESTAMP: 1558378899
Referer: https://localhost:44342/dashboard
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Safari/537.36

Response Headers:

access-control-allow-headers: Content-Type, Accept, cb-session, cb-fp
access-control-allow-methods: GET,POST,DELETE,PUT
access-control-allow-origin: *
access-control-expose-headers: cb-before, cb-after, cb-gdpr
access-control-max-age: 7200
cache-control: no-store
cf-cache-status: MISS
cf-ray: 4da08f74ba97cf68-IAD
content-length: 31
content-type: application/json; charset=utf-8
date: Mon, 20 May 2019 19:01:38 GMT
etag: W/"1f-4RjKVp8I05+xcnQ5/G16yRoMSKU"
expect-ct: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
server: cloudflare
status: 400
strict-transport-security: max-age=15552000; includeSubDomains
vary: Accept-Encoding
x-content-type-options: nosniff
x-dns-prefetch-control: off
x-download-options: noopen
x-frame-options: SAMEORIGIN
x-xss-protection: 1; mode=block

Response:

{"message":"invalid signature"}

What am I doing wrong?

EDIT: Changed method to the SHA 256 version.  Still doesn't work.

Body:
From the gdax-java (as it was named prior to "coinbase pro") library the generate signature method is:

 String prehash = timestamp + method.toUpperCase() + requestPath + body;

 byte[] secretDecoded = Base64.getDecoder().decode(secretKey);
 keyspec = new SecretKeySpec(secretDecoded, "HmacSHA256");
 sha256 = (Mac) GdaxConstants.SHARED_MAC.clone();
 sha256.init(keyspec);
 return Base64.getEncoder().encodeToString(sha256.doFinal(prehash.getBytes()));

At least on initial inspection the code you're using specifies using SHA512 rather than HmacSHA256, so I'd suspect that to be a probabale cause.

There is also more help with NodeJS in the right hand column here for generating the signatures. https://docs.pro.coinbase.com/#creating-a-request


问:
Getting items from objectstore returns [object Object] in HTML
Right now I'm looping through all objects in the object store "tasksStore". When I try to embed the objects into my HTML it only returns [object Object]. If I try to specify a part of the object to retrieve (for example getTasks.result.title) it returns undefined.

I'm not quite sure what I'm doing wrong. When I console log the result I get the "normal" return of the object information:
.

I suspected that the datatypes of put and get is crashing, but after some digging it did not seem to be the issue.

Javascript:

```<code>function listTask() {
    //open connection to database
    let request = window.indexedDB.open("KanbanDatabase", 2),
    db,
    tx,
    store,
    index;

    //error handler on connection
    request.onerror = function(e) {
        console.log("There was en error listing tasks: " + e.target.errorCode);
    }

    //success handler on connection
    request.onsuccess = function(e) {
        console.log("Successfully listed tasks");
        db = request.result;

        //define transaction, store and index
        tasksTx = db.transaction("tasksStore", "readwrite");
        tasksStore = tasksTx.objectStore("tasksStore");
        tasksIndex = tasksStore.index("title", "status");

        //error handler on result of the request
        db.onerror = function(e) {
            console.log("ERROR " + e.target.errorCode);
        }

        //variable for counting objects in the index
        let amountOfTasks = tasksIndex.count();

        //error handler
        amountOfTasks.onerror = function() {
            console.log("There was an error finding the amount of tasks")
        }

        //success handler
        amountOfTasks.onsuccess = function() {
            //console.log("Tasks: " + amountOfTasks.result);
            //TODO: add destination to the function to be able to list tasks with the specific statuses
            for (var i = 0; i < amountOfTasks.result+1; i++) {
                let getTasks = tasksStore.get(i);

                let getTasksElementContainer = document.getElementById("list-tasks");
                let createTasksList = document.createElement("li");
                createTasksList.id = "task-" + i;

                getTasks.onerror = function() {
                    console.log("There was an error looping through the tasks")
                }

                getTasks.onsuccess = function() {

                    console.log(getTasks.result);
                    getTasksElementContainer.appendChild(createTasksList);
                    createTasksList.innerHTML = getTasks.result;
                    //createTasksList.innerHTML = getTasks.result.title - does not work, returns undefined

                }
            }
        }
    }
}
</code>```

答:
Use JSON.stringify:

```<code>getTasksElementContainer.appendChild(JSON.stringify(createTasksList));
</code>```

Body:
Right now I'm looping through all objects in the object store "tasksStore". When I try to embed the objects into my HTML it only returns [object Object]. If I try to specify a part of the object to retrieve (for example getTasks.result.title) it returns undefined.

I'm not quite sure what I'm doing wrong. When I console log the result I get the "normal" return of the object information:
.

I suspected that the datatypes of put and get is crashing, but after some digging it did not seem to be the issue.

Javascript:

function listTask() {
    //open connection to database
    let request = window.indexedDB.open("KanbanDatabase", 2),
    db,
    tx,
    store,
    index;

    //error handler on connection
    request.onerror = function(e) {
        console.log("There was en error listing tasks: " + e.target.errorCode);
    }

    //success handler on connection
    request.onsuccess = function(e) {
        console.log("Successfully listed tasks");
        db = request.result;

        //define transaction, store and index
        tasksTx = db.transaction("tasksStore", "readwrite");
        tasksStore = tasksTx.objectStore("tasksStore");
        tasksIndex = tasksStore.index("title", "status");

        //error handler on result of the request
        db.onerror = function(e) {
            console.log("ERROR " + e.target.errorCode);
        }

        //variable for counting objects in the index
        let amountOfTasks = tasksIndex.count();

        //error handler
        amountOfTasks.onerror = function() {
            console.log("There was an error finding the amount of tasks")
        }

        //success handler
        amountOfTasks.onsuccess = function() {
            //console.log("Tasks: " + amountOfTasks.result);
            //TODO: add destination to the function to be able to list tasks with the specific statuses
            for (var i = 0; i < amountOfTasks.result+1; i++) {
                let getTasks = tasksStore.get(i);

                let getTasksElementContainer = document.getElementById("list-tasks");
                let createTasksList = document.createElement("li");
                createTasksList.id = "task-" + i;

                getTasks.onerror = function() {
                    console.log("There was an error looping through the tasks")
                }

                getTasks.onsuccess = function() {

                    console.log(getTasks.result);
                    getTasksElementContainer.appendChild(createTasksList);
                    createTasksList.innerHTML = getTasks.result;
                    //createTasksList.innerHTML = getTasks.result.title - does not work, returns undefined

                }
            }
        }
    }
}

Body:
Use JSON.stringify:

getTasksElementContainer.appendChild(JSON.stringify(createTasksList));


问:
[UITableViewCell otherFeeLblName]: unrecognized selector sent to instance 0x7fc45009a000
I have used UITableViewController with static cells and in that in two section i have dynamic xib cell.It is working fine in all iOS phone devices but in iPad its crashing.

[UITableViewCell otherFeeLblName]: unrecognized selector sent to
  instance 0x7fc45009a000

```<code>    if (indexPath.section == 2 && defaultsOtherFees.count>0 && (flatRateStatus !=YES)) {  OtherFeeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"OtherFeeCell"];
    NSDictionary *otherFeeDict = defaultsOtherFees[indexPath.row];

    if (otherFeeDict.count>indexPath.row) {

        NSString *otherPriceDescription = [otherFeeDict objectForKey:@"otherPriceDescription"];
        cell.otherFeeLblName.text = otherPriceDescription; //crashes on ipad

        cell.delegate = self;

    }

    return cell;
}

if (indexPath.section == 4) {

    RemarkCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RemarkCell"];
    NSDictionary *dict = remarksArray[indexPath.row];

    return cell;
}else
{
    return [super tableView:tableView cellForRowAtIndexPath:indexPath];
}
</code>```

答:
Declaring the custom class is not sufficient, you have to cast it</p>

```<code>OtherFeeCell *cell = (OtherFeeCell *)[tableView dequeueReusableCellWithIdentifier:@"OtherFeeCell"];
</code>```

Body:
I have used UITableViewController with static cells and in that in two section i have dynamic xib cell.It is working fine in all iOS phone devices but in iPad its crashing.

[UITableViewCell otherFeeLblName]: unrecognized selector sent to
  instance 0x7fc45009a000

    if (indexPath.section == 2 && defaultsOtherFees.count>0 && (flatRateStatus !=YES)) {  OtherFeeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"OtherFeeCell"];
    NSDictionary *otherFeeDict = defaultsOtherFees[indexPath.row];

    if (otherFeeDict.count>indexPath.row) {

        NSString *otherPriceDescription = [otherFeeDict objectForKey:@"otherPriceDescription"];
        cell.otherFeeLblName.text = otherPriceDescription; //crashes on ipad

        cell.delegate = self;

    }

    return cell;
}

if (indexPath.section == 4) {

    RemarkCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RemarkCell"];
    NSDictionary *dict = remarksArray[indexPath.row];

    return cell;
}else
{
    return [super tableView:tableView cellForRowAtIndexPath:indexPath];
}

Body:
Declaring the custom class is not sufficient, you have to cast it

OtherFeeCell *cell = (OtherFeeCell *)[tableView dequeueReusableCellWithIdentifier:@"OtherFeeCell"];


问:
Nodejs nodemailer Username and Password not accepted
I'm trying to send mails with nodejs and nodemailer, but it doesn't work for me. I have this code:

```<code>const config = require('../../config');
const http = require('http');
const nodemailer = require('nodemailer');

module.exports = {

    sendMail: function (params) {
        return new Promise((resolve, reject) => {

            var transporter = nodemailer.createTransport({
                //service: 'gmail', //I tried with this too
                host: 'smtp.gmail.com',
                port: 465,
                secure: true,
                auth: {
                    user: params.fromMail,
                    pass: params.fromPass
                }
            });

            var mailOptions = {
                from: params.fromMail,
                to: params.toMailList,
                subject: params.subject,
                html: params.mailHtmlContent,
            };

            transporter.sendMail(mailOptions, function(err, info){
                if (err) {
                    reject(err);
                } else {
                    resolve(info.response);
                }
            });

        });
    }

};
</code>```

I'm getting this error:

{ Error: Invalid login: 535-5.7.8 Username and Password not accepted.
  Learn more at 535 5.7.8
  https://support.google.com/mail/?p=BadCredentials p6sm97493129wrx.50 -
  gsmtp
      at SMTPConnection._formatError (C:\Users\Carlos\Desktop\Proyectos\nodeServer\node_modules\nodemailer\lib\smtp-connection\index.js:774:19)
      at SMTPConnection._actionAUTHComplete (C:\Users\Carlos\Desktop\Proyectos\nodeServer\node_modules\nodemailer\lib\smtp-connection\index.js:1509:34)
      at SMTPConnection._responseActions.push.str (C:\Users\Carlos\Desktop\Proyectos\nodeServer\node_modules\nodemailer\lib\smtp-connection\index.js:547:26)
      at SMTPConnection._processResponse (C:\Users\Carlos\Desktop\Proyectos\nodeServer\node_modules\nodemailer\lib\smtp-connection\index.js:933:20)
      at SMTPConnection._onData (C:\Users\Carlos\Desktop\Proyectos\nodeServer\node_modules\nodemailer\lib\smtp-connection\index.js:739:14)
      at TLSSocket._socket.on.chunk (C:\Users\Carlos\Desktop\Proyectos\nodeServer\node_modules\nodemailer\lib\smtp-connection\index.js:691:47)
      at TLSSocket.emit (events.js:182:13)
      at addChunk (_stream_readable.js:283:12)
      at readableAddChunk (_stream_readable.js:264:11)
      at TLSSocket.Readable.push (_stream_readable.js:219:10)   code: 'EAUTH',   response:    '535-5.7.8 Username and Password not accepted.
  Learn more at\n535 5.7.8
  https://support.google.com/mail/?p=BadCredentials p6sm97493129wrx.50 -
  gsmtp',   responseCode: 535,   command: 'AUTH PLAIN' }

I have changed the correspondant param on my gmail account about "less secure apps".
I tried with another non gmail account too.
I tried with this:

```<code>service: 'gmail',
</code>```

and this for the connection:

```<code>host: 'smtp.gmail.com',
port: 465,
secure: true,
</code>```

I read all "Similar Questions" here in stackoverflow and I don't know if I need anything else or if I'm doing anything bad. (of course I have revieved the username and password in both accounts and they're ok).

What am Im doing bad?

答:
The accepted answer did not work for me. These four steps did:

Sign in to your Google Admin console using an administrator account.

From the Admin console dashboard, go to Security and then Basic settings (you might have to click More controls at the bottom).

Under Less secure apps, select Go to settings for less secure apps.

In the subwindow, select the Enable access to less secure apps for all users radio button.

Body:
I'm trying to send mails with nodejs and nodemailer, but it doesn't work for me. I have this code:

const config = require('../../config');
const http = require('http');
const nodemailer = require('nodemailer');

module.exports = {

    sendMail: function (params) {
        return new Promise((resolve, reject) => {

            var transporter = nodemailer.createTransport({
                //service: 'gmail', //I tried with this too
                host: 'smtp.gmail.com',
                port: 465,
                secure: true,
                auth: {
                    user: params.fromMail,
                    pass: params.fromPass
                }
            });

            var mailOptions = {
                from: params.fromMail,
                to: params.toMailList,
                subject: params.subject,
                html: params.mailHtmlContent,
            };

            transporter.sendMail(mailOptions, function(err, info){
                if (err) {
                    reject(err);
                } else {
                    resolve(info.response);
                }
            });

        });
    }

};

I'm getting this error:

{ Error: Invalid login: 535-5.7.8 Username and Password not accepted.
  Learn more at 535 5.7.8
  https://support.google.com/mail/?p=BadCredentials p6sm97493129wrx.50 -
  gsmtp
      at SMTPConnection._formatError (C:\Users\Carlos\Desktop\Proyectos\nodeServer\node_modules\nodemailer\lib\smtp-connection\index.js:774:19)
      at SMTPConnection._actionAUTHComplete (C:\Users\Carlos\Desktop\Proyectos\nodeServer\node_modules\nodemailer\lib\smtp-connection\index.js:1509:34)
      at SMTPConnection._responseActions.push.str (C:\Users\Carlos\Desktop\Proyectos\nodeServer\node_modules\nodemailer\lib\smtp-connection\index.js:547:26)
      at SMTPConnection._processResponse (C:\Users\Carlos\Desktop\Proyectos\nodeServer\node_modules\nodemailer\lib\smtp-connection\index.js:933:20)
      at SMTPConnection._onData (C:\Users\Carlos\Desktop\Proyectos\nodeServer\node_modules\nodemailer\lib\smtp-connection\index.js:739:14)
      at TLSSocket._socket.on.chunk (C:\Users\Carlos\Desktop\Proyectos\nodeServer\node_modules\nodemailer\lib\smtp-connection\index.js:691:47)
      at TLSSocket.emit (events.js:182:13)
      at addChunk (_stream_readable.js:283:12)
      at readableAddChunk (_stream_readable.js:264:11)
      at TLSSocket.Readable.push (_stream_readable.js:219:10)   code: 'EAUTH',   response:    '535-5.7.8 Username and Password not accepted.
  Learn more at\n535 5.7.8
  https://support.google.com/mail/?p=BadCredentials p6sm97493129wrx.50 -
  gsmtp',   responseCode: 535,   command: 'AUTH PLAIN' }

I have changed the correspondant param on my gmail account about "less secure apps".
I tried with another non gmail account too.
I tried with this:

service: 'gmail',

and this for the connection:

host: 'smtp.gmail.com',
port: 465,
secure: true,

I read all "Similar Questions" here in stackoverflow and I don't know if I need anything else or if I'm doing anything bad. (of course I have revieved the username and password in both accounts and they're ok).

What am Im doing bad?