问:
Devise - remember me not working? LocalHost Issue?
I'm using devise with my rails 3 app. For some reason the sign in with Remember Me is not working.

Could this be due to testing on localhost:3000 ?

in devise.rb, I have the following set:

```<code>config.remember_for = 2.weeks
</code>```

In the logs, when I post a signin I see:

```<code>Started POST "/users/sign_in" for 127.0.0.1 at Thu May 12 20:53:04 -0700 2011
  Processing by SessionsController#create as HTML
  Parameters: {"signIn"=>"LOG IN", "authenticity_token"=>"GR09TIq4uSbu6UWxDRhpfQeLWp7qtJTxkCFksLmFzdE=", "utf8"=>"✓", "user"=>{"remember_me"=>"on", "password"=>"[FILTERED]", "email"=>"xxxx@xxxxxxx-inc.com"}}
</code>```

Is there anything wrong there?

I also have the following in my sessions_controller.rb

```<code>class SessionsController < Devise::SessionsController

  prepend_before_filter :require_no_authentication, :only => [ :new, :create ]
  include Devise::Controllers::InternalHelpers

  # GET /resource/sign_in
  def new
    clean_up_passwords(build_resource)
    render_with_scope :new
  end

  # POST /resource/sign_in
  def create
    resource = warden.authenticate!(:scope => resource_name, :recall => "new")
    #set_flash_message :notice, :signed_in
    sign_in_and_redirect(resource_name, resource)
  end

  # GET /resource/sign_out
  def destroy
    #set_flash_message :notice, :signed_out if signed_in?(resource_name)
    sign_out_and_redirect(resource_name)
  end

  protected

  def after_sign_in_path_for(resource)
    if resource.is_a?(User) && resource.banned?
      sign_out resource
      flash[:error] = "This account has been suspended."
      root_path
    else
      super
    end
  end

end
</code>```

Any ideas why signing in and remembering is not working? Thanks

答:
Do you have the sessions set aswell with config.timeout_in = 10.minutes?

If so see this contribution on stackoverflow which solves it solution

Body:
I'm using devise with my rails 3 app. For some reason the sign in with Remember Me is not working.

Could this be due to testing on localhost:3000 ?

in devise.rb, I have the following set:

config.remember_for = 2.weeks

In the logs, when I post a signin I see:

Started POST "/users/sign_in" for 127.0.0.1 at Thu May 12 20:53:04 -0700 2011
  Processing by SessionsController#create as HTML
  Parameters: {"signIn"=>"LOG IN", "authenticity_token"=>"GR09TIq4uSbu6UWxDRhpfQeLWp7qtJTxkCFksLmFzdE=", "utf8"=>"✓", "user"=>{"remember_me"=>"on", "password"=>"[FILTERED]", "email"=>"xxxx@xxxxxxx-inc.com"}}

Is there anything wrong there?

I also have the following in my sessions_controller.rb

class SessionsController < Devise::SessionsController

  prepend_before_filter :require_no_authentication, :only => [ :new, :create ]
  include Devise::Controllers::InternalHelpers

  # GET /resource/sign_in
  def new
    clean_up_passwords(build_resource)
    render_with_scope :new
  end

  # POST /resource/sign_in
  def create
    resource = warden.authenticate!(:scope => resource_name, :recall => "new")
    #set_flash_message :notice, :signed_in
    sign_in_and_redirect(resource_name, resource)
  end

  # GET /resource/sign_out
  def destroy
    #set_flash_message :notice, :signed_out if signed_in?(resource_name)
    sign_out_and_redirect(resource_name)
  end

  protected

  def after_sign_in_path_for(resource)
    if resource.is_a?(User) && resource.banned?
      sign_out resource
      flash[:error] = "This account has been suspended."
      root_path
    else
      super
    end
  end

end

Any ideas why signing in and remembering is not working? Thanks


来源: stackexchange

问:
Kivy AttributeError: 'NoneType' object has no attribute 'ids'
I created a custom button in the kv file, i want to set disabled = True if app.root.ids.my_label == "disabled" else disabled=False. However i keep getting AttributeError: 'NoneType' object has no attribute 'ids. I no this can be done, i'm not just doing it right, i will be grateful for any help. Thanks!

test.py

```<code>from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
from kivy.properties import ObjectProperty

Builder.load_string('''
<CustomBtn@Button>
       disabled: True if app.root.ids.word.my_label == "disable" else False

<main>:
my_label:my_label
BoxLayout:
    orientation:"vertical"

    Label:
        id: my_label
        text: "Disabled"
    CustomBtn:
        text: "Btn1"
    CustomBtn:
        text: "Btn2"
    CustomBtn:
        text: "Btn3"
    Button:
        text: "Disable/Enable"
        on_press: root.disablebtn()
        ''')

class main(BoxLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        my_label = ObjectProperty()

    def disablebtn(self):
        print(self.my_label)
        if self.my_label.text == "Disabled":
            self.my_label.text = "Enabled"
        else:
            self.my_label.text = "Disabled"

class CallApp(App):
    def build(self):
        return main()

CallApp().run()
</code>```

答:
Your original approach won't work because app.root is not set when your <CustomBtn@Button> rule is applied. Here is a modified version of your code, that does what you want without that problem:

```<code>from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
from kivy.properties import ObjectProperty
from kivy.uix.button import Button

class CustomBtn(Button):
    pass

Builder.load_string('''
<main>:
    my_label:my_label
    BoxLayout:
        orientation:"vertical"

        Label:
            id: my_label
            text: "Disabled"
        CustomBtn:
            text: "Btn1"
        CustomBtn:
            text: "Btn2"
        CustomBtn:
            text: "Btn3"
        Button:
            text: "Disable/Enable"
            on_press: root.disablebtn()
        ''')

class main(BoxLayout):
    my_label = ObjectProperty()

    def disablebtn(self):
        if self.my_label.text == "Disabled":
            self.my_label.text = "Enabled"
            self.disable_customBtns(False)
        else:
            self.my_label.text = "Disabled"
            self.disable_customBtns(True)

    def disable_customBtns(self, is_disabled):
        # Look for CustomBtn instances, and set their `disabled` value
        for child in self.walk():
            if isinstance(child, CustomBtn):
                child.disabled = is_disabled

    def on_my_label(self, *args):
        # this just sets the initial value of disabled to True
        self.disable_customBtns(True)

class CallApp(App):
    def build(self):
        return main()

CallApp().run()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I created a custom button in the kv file, i want to set disabled = True if app.root.ids.my_label == "disabled" else disabled=False. However i keep getting AttributeError: 'NoneType' object has no attribute 'ids. I no this can be done, i'm not just doing it right, i will be grateful for any help. Thanks!

test.py

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
from kivy.properties import ObjectProperty

Builder.load_string('''
<CustomBtn@Button>
       disabled: True if app.root.ids.word.my_label == "disable" else False

:
my_label:my_label
BoxLayout:
    orientation:"vertical"

    Label:
        id: my_label
        text: "Disabled"
    CustomBtn:
        text: "Btn1"
    CustomBtn:
        text: "Btn2"
    CustomBtn:
        text: "Btn3"
    Button:
        text: "Disable/Enable"
        on_press: root.disablebtn()
        ''')

class main(BoxLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        my_label = ObjectProperty()

    def disablebtn(self):
        print(self.my_label)
        if self.my_label.text == "Disabled":
            self.my_label.text = "Enabled"
        else:
            self.my_label.text = "Disabled"

class CallApp(App):
    def build(self):
        return main()

CallApp().run()

Body:
Your original approach won't work because app.root is not set when your <CustomBtn@Button> rule is applied. Here is a modified version of your code, that does what you want without that problem:

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
from kivy.properties import ObjectProperty
from kivy.uix.button import Button

class CustomBtn(Button):
    pass

Builder.load_string('''
<main>:
    my_label:my_label
    BoxLayout:
        orientation:"vertical"

        Label:
            id: my_label
            text: "Disabled"
        CustomBtn:
            text: "Btn1"
        CustomBtn:
            text: "Btn2"
        CustomBtn:
            text: "Btn3"
        Button:
            text: "Disable/Enable"
            on_press: root.disablebtn()
        ''')

class main(BoxLayout):
    my_label = ObjectProperty()

    def disablebtn(self):
        if self.my_label.text == "Disabled":
            self.my_label.text = "Enabled"
            self.disable_customBtns(False)
        else:
            self.my_label.text = "Disabled"
            self.disable_customBtns(True)

    def disable_customBtns(self, is_disabled):
        # Look for CustomBtn instances, and set their `disabled` value
        for child in self.walk():
            if isinstance(child, CustomBtn):
                child.disabled = is_disabled

    def on_my_label(self, *args):
        # this just sets the initial value of disabled to True
        self.disable_customBtns(True)

class CallApp(App):
    def build(self):
        return main()

CallApp().run()


问:
Gray weird layer after send and app to playstore
I was developing an app normally, the apk generated by android studio is everything ok. I started to have some problem when I sended my frist version to playstore google. I did to upload correctly but when the google take me to do the download from playstore, it come the problem. The login page is ok but when I acess the main page of the app, there is a grey layter over the drawer widget the contain the main menu of the of (I´ll send a print screen). Beside that, over the google map widget on the main page also there is the same grey shape like a layer. I need some help to solve them because I didt find any information on internet about this issue. This error have happend just after send the apk ou app bundle to playstore, in all test whit apk is everything ok.
enter image description here

enter link description here
I took in this message 4 images. 2 whit de issue and 2 correct.enter image description here

答:
DefaultTabController( // Added
length: 4, // Added
initialIndex: 0, //Added
child: Scaffold(
key: _scaffoldKey,
floatingActionButton:
this.pilotoTemVooAssumido=='1' ?
this.tabIndex==0 ?
FloatingActionButton(
backgroundColor: Colors.redAccent,
onPressed: () async {
},
child: Icon(Icons.delete_forever,color: Colors.white,),
) : null : null,
appBar: AppBar(
backgroundColor: Color.fromRGBO(37, 67, 154, 1),
//LARANJA Color.fromRGBO(249, 138, 18, 1) AZUL "Color.fromRGBO(37, 67, 154, 1)"
title: Text(
"Ata Brasil VA", style: TextStyle(color: Colors.white),),
iconTheme: new IconThemeData(color: Colors.white),
),
drawer: buildDrawer(),
body: buildBody(tabIndex),
bottomNavigationBar: BottomNavigationBar(

selectedItemColor: Color.fromRGBO(249, 138, 18, 1),
unselectedItemColor: Colors.white,
//backgroundColor: Color.fromRGBO(249, 138, 18, 1) ,
backgroundColor: Color.fromRGBO(37, 67, 154, 1),
currentIndex: tabIndex,
onTap: (int index) {
},
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home),
title: Text('Home'),
),
BottomNavigationBarItem(
icon: Icon(Icons.airplanemode_active),
title: Text('Últimos Voos'),
),
BottomNavigationBarItem(
icon: Icon(Icons.map),
title: Text('Ao Vivo'),
),
]),
));```


问:
Is arr, *arr, arr[0] and &arr[0][0] the same in C?
i find some similar questions but not this...

if I got this:

```<code> double B[3][3] = {{1.,0.,0.},{0.,1.,0.},{0.,0.,1.}};
</code>```

then:

B, *B, B[0], and &B[0][0]

are the same?

for example, if i create this method:

```<code>void suma(double A[][3], double *B, double *C);

int main(int argc, char **argv) {
     double A[3][3] = {{1.,2.,3.},{4.,5.,6.},{7.,8.,9.}};
     double B[3][3] = {{1.,0.,0.},{0.,1.,0.},{0.,0.,1.}};
     double C[3][3];

     suma(A, &B[0][0], C[0]);

     return 0;
}

void suma(double A[][3], double *B, double *C){
    for(int i = 0; i < 3; i++){
        for(int j = 0; j < 3; j++){
            *(C+i*3+j) = A[i][j] + *(B+i*3+j);
        }
    }
}
</code>```

I can call the function with the 4 diferents ways, and work all

答:
When used in expressions (except for example as operand of the sizeof operator):

B - is a pointer to an array of 3 double, double (*)[3] -  Nonetheless it gains the address of the first element of the first array.

*B - is a pointer to double , double *- Actually a pointer to the first element in the first array.

B[0] - is a pointer to double, double * - Actually a pointer to the first element in the first array.

&B[0][0] - is a pointer to double, double * - Actually a pointer to the first element in the first array.

There are not the same. B has a different type. - However, they all actually have the same result. - The evaluation to the address of the first element in the first array.

Body:
i find some similar questions but not this...

if I got this:

 double B[3][3] = {{1.,0.,0.},{0.,1.,0.},{0.,0.,1.}};

then:

B, *B, B[0], and &B[0][0]

are the same?

for example, if i create this method:

void suma(double A[][3], double *B, double *C);

int main(int argc, char **argv) {
     double A[3][3] = {{1.,2.,3.},{4.,5.,6.},{7.,8.,9.}};
     double B[3][3] = {{1.,0.,0.},{0.,1.,0.},{0.,0.,1.}};
     double C[3][3];

     suma(A, &B[0][0], C[0]);

     return 0;
}

void suma(double A[][3], double *B, double *C){
    for(int i = 0; i < 3; i++){
        for(int j = 0; j < 3; j++){
            *(C+i*3+j) = A[i][j] + *(B+i*3+j);
        }
    }
}

I can call the function with the 4 diferents ways, and work all


问:
SS2.0 Display Message on Record
I'd like to use SS2.0 and the 'new' N/ui/message module to display warnings or errors when a user views a record.  In reality, I'd like to understand how to run any 2.0 client script code on record view.

I managed an example I can run, which works from the console:

```<code>require(['N/currentRecord', 'N/ui/message'],
    function(curr, mess) {
        var rec = curr.get();
        var status = rec.getValue('status');
        if (status === 'Unapproved Payment') {
            var myMsg = mess.create({
                title: "PAYMENT ERROR",
                message: status,
                type: mess.Type.ERROR
            }).show({
                duration: 500000
            });
        }});
</code>```

Runs fine in edit mode(pageInit or wherever) but haven't found a method to load and execute on 'View'.  Is this even possible in 2.0? Do I have to use the 1.0 tricks still?

答:
Since the release 2018.2 they added a new method in N/ui/serverWidget module named Form.addPageInitMessage(options) and does exactly what OP wanted to do.

Given the example above it should look something like this.

```<code>/**
 *@NApiVersion 2.0
 *@NScriptType UserEventScript
*/
define(['N/ui/serverWidget', 'N/record'],
    function(serverWidget, record) {
        function beforeLoad(context) {

          var rec = context.newRecord;
          var status = rec.getValue('status');
          if (status === 'Unapproved Payment') {
           var myMsg = mess.create({
                title: "PAYMENT ERROR",
                message: status,
                type: mess.Type.ERROR,
                duration: 500000
           });
           context.form.addPageInitMessage({message: myMsg});
        }

    return {
        beforeLoad: beforeLoad
    };
});
</code>```

ContentLicense: CC BY-SA 3.0

Title: SS2.0 Display Message on Record

Body:
I'd like to use SS2.0 and the 'new' N/ui/message module to display warnings or errors when a user views a record.  In reality, I'd like to understand how to run any 2.0 client script code on record view.

I managed an example I can run, which works from the console:

require(['N/currentRecord', 'N/ui/message'],
    function(curr, mess) {
        var rec = curr.get();
        var status = rec.getValue('status');
        if (status === 'Unapproved Payment') {
            var myMsg = mess.create({
                title: "PAYMENT ERROR",
                message: status,
                type: mess.Type.ERROR
            }).show({
                duration: 500000
            });
        }});

Runs fine in edit mode(pageInit or wherever) but haven't found a method to load and execute on 'View'.  Is this even possible in 2.0? Do I have to use the 1.0 tricks still?

Body:
Since the release 2018.2 they added a new method in N/ui/serverWidget module named Form.addPageInitMessage(options) and does exactly what OP wanted to do.

Given the example above it should look something like this.

/**
 *@NApiVersion 2.0
 *@NScriptType UserEventScript
*/
define(['N/ui/serverWidget', 'N/record'],
    function(serverWidget, record) {
        function beforeLoad(context) {

          var rec = context.newRecord;
          var status = rec.getValue('status');
          if (status === 'Unapproved Payment') {
           var myMsg = mess.create({
                title: "PAYMENT ERROR",
                message: status,
                type: mess.Type.ERROR,
                duration: 500000
           });
           context.form.addPageInitMessage({message: myMsg});
        }

    return {
        beforeLoad: beforeLoad
    };
});


问:
No response from Aerospike
I am writing my own Aerospike client in C ++ and I have a problem: although my request seems to reach the server (if you send nonsense, the connection will be dropped), the server does not return any response.

Here is my code:

```<code>#include <boost/asio.hpp>
#include <boost/array.hpp>
#include <iostream>

void read_message(boost::asio::ip::tcp::socket& socket)
{
    for (;;)
    {
      boost::array<char, 1> buf;
      boost::system::error_code error;
      size_t len = socket.read_some(boost::asio::buffer(buf), error);
      if (error == boost::asio::error::eof)
        break;
      else if (error)
        throw boost::system::system_error(error);
      std::cout.write(buf.data(), len);
      std::cout << std::endl;
    }
}

void send_message(boost::asio::ip::tcp::socket& socket, std::string message)
{
    boost::array<char, 1024> buf;
    std::copy(message.begin(), message.end(), buf.begin());
    boost::system::error_code error;
    socket.write_some(boost::asio::buffer(buf, message.size()), error);
}

int main()
{
    std::cout << "Connecting to socket.." << std::endl;
    boost::asio::io_service ios;
    boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::address::from_string("127.0.0.1"), 3000);
    boost::asio::ip::tcp::socket socket(ios);
    socket.connect(endpoint);
    std::cout << "Connected to socket. Writing message." << std::endl;
    send_message(socket, "\x02\x01\x00\x00\x00\x00\x006build\nedition\nnode\nservice\nservices\nstatistics\nversion");
    std::cout << "Writed message. Reading response." << std::endl;
    read_message(socket);
    std::cout << "Read response. Exiting prigram." << std::endl;
    socket.close();
    return 0;
}
</code>```

This code works correctly with, for example, 1.1.1.1:80 - HTML is returned with the words "Bad request".

答: You are calling socket.write_some() only once in your send_message() function. You are basically assuming that all the bytes will be sent in one call. There is no such guarantee. When I tried your code, it sent only 2 bytes in my run. Unless all bytes reach the server, it won't respond (obviously).

Title: No response from Aerospike

Body:
I am writing my own Aerospike client in C ++ and I have a problem: although my request seems to reach the server (if you send nonsense, the connection will be dropped), the server does not return any response.

Here is my code:

#include <boost/asio.hpp>
#include <boost/array.hpp>
#include <iostream>

void read_message(boost::asio::ip::tcp::socket& socket)
{
    for (;;)
    {
      boost::array<char, 1> buf;
      boost::system::error_code error;
      size_t len = socket.read_some(boost::asio::buffer(buf), error);
      if (error == boost::asio::error::eof)
        break;
      else if (error)
        throw boost::system::system_error(error);
      std::cout.write(buf.data(), len);
      std::cout << std::endl;
    }
}

void send_message(boost::asio::ip::tcp::socket& socket, std::string message)
{
    boost::array<char, 1024> buf;
    std::copy(message.begin(), message.end(), buf.begin());
    boost::system::error_code error;
    socket.write_some(boost::asio::buffer(buf, message.size()), error);
}

int main()
{
    std::cout << "Connecting to socket.." << std::endl;
    boost::asio::io_service ios;
    boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::address::from_string("127.0.0.1"), 3000);
    boost::asio::ip::tcp::socket socket(ios);
    socket.connect(endpoint);
    std::cout << "Connected to socket. Writing message." << std::endl;
    send_message(socket, "\x02\x01\x00\x00\x00\x00\x006build\nedition\nnode\nservice\nservices\nstatistics\nversion");
    std::cout << "Writed message. Reading response." << std::endl;
    read_message(socket);
    std::cout << "Read response. Exiting prigram." << std::endl;
    socket.close();
    return 0;
}

This code works correctly with, for example, 1.1.1.1:80 - HTML is returned with the words "Bad request".


问:
AWS Firehose transform Lambda function throws Lambda.MissingRecordId error for every record
I'm using AWS firehose with an S3 backup and an S3 destination bucket, and it works great. The problem arises when I try to transform the data with a Lambda function.

I'm using the .NET AWS SDK, my Lambda function is written in C# and is using the included firehose transform example:

```<code>[assembly:LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.JsonSerializer))]

namespace LambdaFunctions
{
    public class Function
    {
        public KinesisFirehoseResponse FunctionHandler(KinesisFirehoseEvent evnt, ILambdaContext context)
        {
            context.Logger.LogLine($"InvocationId: {evnt.InvocationId}");
            context.Logger.LogLine($"DeliveryStreamArn: {evnt.DeliveryStreamArn}");
            context.Logger.LogLine($"Region: {evnt.Region}");

            KinesisFirehoseResponse response = new KinesisFirehoseResponse
            {
                Records = new List<KinesisFirehoseResponse.FirehoseRecord>()
            };

            foreach (KinesisFirehoseEvent.FirehoseRecord record in evnt.Records)
            {
                context.Logger.LogLine($"\tRecordId: {record.RecordId}");
                context.Logger.LogLine($"\t\tApproximateArrivalEpoch: {record.ApproximateArrivalEpoch}");
                context.Logger.LogLine($"\t\tApproximateArrivalTimestamp: {record.ApproximateArrivalTimestamp}");
                context.Logger.LogLine($"\t\tData: {record.DecodeData()}");

                // Transform data: For example ToUpper the data
                KinesisFirehoseResponse.FirehoseRecord transformedRecord = new KinesisFirehoseResponse.FirehoseRecord
                {
                    RecordId = record.RecordId,
                    Result = KinesisFirehoseResponse.TRANSFORMED_STATE_OK
                };

                transformedRecord.EncodeData(record.DecodeData().ToUpperInvariant());

                response.Records.Add(transformedRecord);
            }

            return response;
        }
    }
}
</code>```

The data is successfully & correctly processed by the transform Lambda function (as indicated by tests & logs).

However, the data is not successfully returned by the Lambda function to the S3 destination bucket, all of the records are unsuccessfully processed.

This error is returned for each record:

```<code>{
    "attemptsMade": 1,
    "arrivalTimestamp": 1590656820209,
    "errorCode": "Lambda.MissingRecordId",
    "errorMessage": "One or more record Ids were not returned. Ensure that the Lambda function returns all received record Ids.",
    "attemptEndingTimestamp": 1590656883464,
    "rawData": "dGVzdDE=",
    "lambdaArn": "arn:aws:lambda:Region:AccountNumber:function:transform-function:$LATEST"
}
</code>```

I'm at a loss as to why or where this error is occurring. I know the Lambda function is returning the correct response, recordId included.

I've recreated all the resources, applied and re-applied permissions, done just about everything I can think of.

This issue doesn't happen when using the Node.js or Python versions, it seems to be unique to the .NET implementation.

EDIT:

I forgot to add the serializer assembly attribute to the original code block which ended up being the source of the issue.

答:
The C# example provided by AWS is out of date, specifically this serialization package:

```<code>Amazon.Lambda.Serialization.SystemTextJson
</code>```

To solve this issue, simply replace the package with this one:

```<code>Amazon.Lambda.Serialization.Json
</code>```

and update the assembly attribute like so:

```<code>[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]

namespace LambdaFunctions
{
    ...
</code>```

This serialization package is mentioned in the AWS Documentation here, under "Serializing Lambda functions".

However, Amazon have not yet updated the SDK examples to reflect this change (or at least, this example specifically), causing the function to fail when deployed.

Body:
I'm using AWS firehose with an S3 backup and an S3 destination bucket, and it works great. The problem arises when I try to transform the data with a Lambda function.

I'm using the .NET AWS SDK, my Lambda function is written in C# and is using the included firehose transform example:

[assembly:LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.JsonSerializer))]

namespace LambdaFunctions
{
    public class Function
    {
        public KinesisFirehoseResponse FunctionHandler(KinesisFirehoseEvent evnt, ILambdaContext context)
        {
            context.Logger.LogLine($"InvocationId: {evnt.InvocationId}");
            context.Logger.LogLine($"DeliveryStreamArn: {evnt.DeliveryStreamArn}");
            context.Logger.LogLine($"Region: {evnt.Region}");

            KinesisFirehoseResponse response = new KinesisFirehoseResponse
            {
                Records = new List<KinesisFirehoseResponse.FirehoseRecord>()
            };

            foreach (KinesisFirehoseEvent.FirehoseRecord record in evnt.Records)
            {
                context.Logger.LogLine($"\tRecordId: {record.RecordId}");
                context.Logger.LogLine($"\t\tApproximateArrivalEpoch: {record.ApproximateArrivalEpoch}");
                context.Logger.LogLine($"\t\tApproximateArrivalTimestamp: {record.ApproximateArrivalTimestamp}");
                context.Logger.LogLine($"\t\tData: {record.DecodeData()}");

                // Transform data: For example ToUpper the data
                KinesisFirehoseResponse.FirehoseRecord transformedRecord = new KinesisFirehoseResponse.FirehoseRecord
                {
                    RecordId = record.RecordId,
                    Result = KinesisFirehoseResponse.TRANSFORMED_STATE_OK
                };

                transformedRecord.EncodeData(record.DecodeData().ToUpperInvariant());

                response.Records.Add(transformedRecord);
            }

            return response;
        }
    }
}

The data is successfully & correctly processed by the transform Lambda function (as indicated by tests & logs).

However, the data is not successfully returned by the Lambda function to the S3 destination bucket, all of the records are unsuccessfully processed.

This error is returned for each record:

{
    "attemptsMade": 1,
    "arrivalTimestamp": 1590656820209,
    "errorCode": "Lambda.MissingRecordId",
    "errorMessage": "One or more record Ids were not returned. Ensure that the Lambda function returns all received record Ids.",
    "attemptEndingTimestamp": 1590656883464,
    "rawData": "dGVzdDE=",
    "lambdaArn": "arn:aws:lambda:Region:AccountNumber:function:transform-function:$LATEST"
}

I'm at a loss as to why or where this error is occurring. I know the Lambda function is returning the correct response, recordId included.

I've recreated all the resources, applied and re-applied permissions, done just about everything I can think of.

This issue doesn't happen when using the Node.js or Python versions, it seems to be unique to the .NET implementation.

EDIT:

I forgot to add the serializer assembly attribute to the original code block which ended up being the source of the issue.

Body:
The C# example provided by AWS is out of date, specifically this serialization package:

Amazon.Lambda.Serialization.SystemTextJson

To solve this issue, simply replace the package with this one:

Amazon.Lambda.Serialization.Json

and update the assembly attribute like so:

[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]

namespace LambdaFunctions
{
    ...

This serialization package is mentioned in the AWS Documentation here, under "Serializing Lambda functions".

However, Amazon have not yet updated the SDK examples to reflect this change (or at least, this example specifically), causing the function to fail when deployed.


问:
close a section of a accordion in jquery
It's a simple question, but i don't know how do it. I think there's a way to close all of the sections in the accordion attached to a event click, but i haven't found a method that will allow it to be done. I tried this:</p>

```<code>$(document).ready(initialize);

$("#accordion").accordion("destroy");

$("#accordion").accordion({
    collapsible: true,
    active: false
});

function initialize() {

    $(".btnOk").click(function (e) {
    e.preventDefault();
    $("#accordion").accordion("active", false);
    }
}
</code>```

答:
You can do it by using .accordian("activate", -1).

Check out my working jsFiddle demo:

```<code>$(function() {

    var $accordion = $("#accordion");

    $accordion
        .accordion("destroy")
        .accordion({

            collapsible: true,
            active: false

        });

    $(".btnOk").click(function(e) {

        e.preventDefault();
        $accordion.accordion("activate", -1);

    });

});
</code>```

Body:
It's a simple question, but i don't know how do it. I think there's a way to close all of the sections in the accordion attached to a event click, but i haven't found a method that will allow it to be done. I tried this:

$(document).ready(initialize);

$("#accordion").accordion("destroy");

$("#accordion").accordion({
    collapsible: true,
    active: false
});

function initialize() {

    $(".btnOk").click(function (e) {
    e.preventDefault();
    $("#accordion").accordion("active", false);
    }
}

Body:
You can do it by using .accordian("activate", -1).

Check out my working jsFiddle demo:

$(function() {

    var $accordion = $("#accordion");

    $accordion
        .accordion("destroy")
        .accordion({

            collapsible: true,
            active: false

        });

    $(".btnOk").click(function(e) {

        e.preventDefault();
        $accordion.accordion("activate", -1);

    });

});


问:
Insert Task in Google Task API , Error: 403, message: Request had insufficient authentication scopes
I am trying to insert a new task into TaskList.
here is my code:

```<code>$client = getClient();
$service = new Google_Service_Tasks($client);

$optParams = array('maxResults' => 10);

$serviceTasklist = $service->tasklists->listTasklists($optParams);

$serviceTask = $service->tasks->listTasks("@default", $optParams);

try {
    $task = new Google_Service_Tasks_Task();
    $task->setTitle("here is new task");
    $task->setNotes("this is note of new task");

    $result = $service->tasks->insert("@default", $task);
    return $result->getId();

} catch (Google_Exception $ggex) {
    echo "\n Error: " . $ggex->getMessage();
}
</code>```

I had tried to change scope from Google_Service_Task::TASK_READONLY  to Google_Service_Task::TASK, included google task document also do a samething, but I tried then it not work . Can someone give my suggest or tell me know where am I wrong? Thank You !.

答:
For documentation purpose:

The problem was in the token file itself. When you change the scopes you need to make sure to get a new updated token. If you still use the previous token is like haven't changed your code at all.

Body:
I am trying to insert a new task into TaskList.
here is my code:

$client = getClient();
$service = new Google_Service_Tasks($client);

$optParams = array('maxResults' => 10);

$serviceTasklist = $service->tasklists->listTasklists($optParams);

$serviceTask = $service->tasks->listTasks("@default", $optParams);

try {
    $task = new Google_Service_Tasks_Task();
    $task->setTitle("here is new task");
    $task->setNotes("this is note of new task");

    $result = $service->tasks->insert("@default", $task);
    return $result->getId();

} catch (Google_Exception $ggex) {
    echo "\n Error: " . $ggex->getMessage();
}

I had tried to change scope from Google_Service_Task::TASK_READONLY  to Google_Service_Task::TASK, included google task document also do a samething, but I tried then it not work . Can someone give my suggest or tell me know where am I wrong? Thank You !.


答:
Remove where clause from subquery & use boolean logic : </p>

```<code>select t.*
from (select t.*, row_number() over(partition by id order by date desc) as seq
      from table t
      ) t
where (status = 'A' and seq = 1) or (status = 'B' and seq = 2) ;
</code>```

Title: How to find latest 2 result with specific alpabet but with same ID

Body:
Raw Data

+---------+--------+------------+
|   ID    | STATUS |    DATE    |
+---------+--------+------------+
| ABC1234 | P      | 2020-01-01 |
| ABC1234 | P      | 2020-01-02 |
| ABC1234 | B      | 2020-01-03 |
| ABC1234 | A      | 2020-01-04 |
| ABC1234 | A      | 2020-01-05 |
| BCD     | P      | 2020-01-01 |
| BCD     | P      | 2020-01-02 |
| BCD     | P      | 2020-01-03 |
| BCD     | B      | 2020-01-04 |
| BCD     | A      | 2020-01-05 |
| 12XY    | P      | 2020-01-01 |
| 12XY    | P      | 2020-01-02 |
| 12XY    | P      | 2020-01-03 |
| 12XY    | B      | 2020-01-04 |
| 12XY    | B      | 2020-01-05 |
+---------+--------+------------+

Result I want

+-----+--------+------------+
| ID  | STATUS |    DATE    |
+-----+--------+------------+
| BCD | B      | 2020-01-04 |
| BCD | A      | 2020-01-05 |
+-----+--------+------------+

How to find result whereby latest record Status=A, and second latest record Status=B?

Tried on below but still missing idea how get for ID=BCD

select ROW_NUMBER()
        OVER (PARTITION BY ID ORDER BY date2 DESC) AS rownum
         ,*
         into testingtable
         from mytable
         WHERE status in ('b', 'a')

Body:
Remove where clause from subquery & use boolean logic :

select t.*
from (select t.*, row_number() over(partition by id order by date desc) as seq
      from table t
      ) t
where (status = 'A' and seq = 1) or (status = 'B' and seq = 2) ;


问:
JS - Show a div only when a number is typed
I have a form with an input type="number", and I need to display a div if the user types a number within a range.

My current code only works when I reload the page, but I want to display the "#alert-one" div when the numeric range is typed (not when the page reloads).

What am I doing wrong...?

Thanks in advance!

CSS:

```<code>#alert-one {
    display:none
}
</code>```

HTML:

```<code><div id="alert-one">Hello</div>

<input type="number" id="enviara" name="enviara" maxlength="5" required>
</code>```

Script:

```<code>$(document).ready(function(){
  function alertaislas() {
    const total = Number($("#enviara").val().replace(".",""));

    if(total > 28999 && total < 29999) {
      $('#alert-one').show();
    }

    else{
      $('#alert-one').hide();
}}

    alertaislas();
});
</code>```

答:
Actually this won't display anything without reloading.
You must use jquery inline html onkeyup=myfn() as well as onchange=myfn()

as follows:

HTML :

```<code><div id="alert-one">Hello</div>

<input type="number" id="enviara" name="enviara" maxlength="5" onkeyup="alertaislas()" onchange="alertaislas()" required>
</code>```

Javascript/Jquery :

```<code>$(document).ready(function(){
  function alertaislas() {
    const total = Number($("#enviara").val().replace(".",""));

    if(total > 28999 && total < 29999) {
      $('#alert-one').show();
    }

    else{
      $('#alert-one').hide();
}}

});
</code>```

Body:
I have a form with an input type="number", and I need to display a div if the user types a number within a range.

My current code only works when I reload the page, but I want to display the "#alert-one" div when the numeric range is typed (not when the page reloads).

What am I doing wrong...?

Thanks in advance!

CSS:

#alert-one {
    display:none
}

HTML:

Hello

<input type="number" id="enviara" name="enviara" maxlength="5" required>

Script:

$(document).ready(function(){
  function alertaislas() {
    const total = Number($("#enviara").val().replace(".",""));

    if(total > 28999 && total < 29999) {
      $('#alert-one').show();
    }

    else{
      $('#alert-one').hide();
}}

    alertaislas();
});

Body:
Actually this won't display anything without reloading.
You must use jquery inline html onkeyup=myfn() as well as onchange=myfn()

as follows:

HTML :

<div id="alert-one">Hello</div>

<input type="number" id="enviara" name="enviara" maxlength="5" onkeyup="alertaislas()" onchange="alertaislas()" required>

Javascript/Jquery :

$(document).ready(function(){
  function alertaislas() {
    const total = Number($("#enviara").val().replace(".",""));

    if(total > 28999 && total < 29999) {
      $('#alert-one').show();
    }

    else{
      $('#alert-one').hide();
}}

});


问:
How do i check if a wordpress query has more posts?
So i am using ajax to filter and load posts into a container. I want to limit the amount of posts to 6 at a time and add a load more button underneath if there are more than 6 posts, but i don't want to add pages because i have a few containers on the same page that i'm using this same treatment for and my understanding is pages would add a /page-1 or something like that to the url (am i wrong?).

Either way, i just want to know how to check if there are more posts that fit this criteria so i can show the load more button, and then when the load more button fires how do i just load 6 more. Do i have to keep a page variable somewhere? or is there another smarter way.

Here is my query

```<code>function ajax_filter_get_posts( $category, $tag )
{
  $category = $_POST['category'];
  $tag = $_POST['tag'];

  if($category)
  {
    $category_args = array(
      'taxonomy' => 'category',
      'field'    => 'slug',
      'terms'    => $category
    );
  }

  $args = array(
    'posts_per_page' => 6,
    'post_status'    => 'publish',
    'tag'            => implode(",",$tag),
    'tax_query'      => array(
      $category_args,
    ),
    'category__in'      => array(187,186,183,182,184),
  );

  $query = new WP_Query( $args );

  if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post();

    $output = post_factory($post);

    $result['response'][] = $output;
    $result['status']     = 'success';

  endwhile; else:
    $result['response'] = '<h2>No posts found</h2>';
    $result['status']   = '404';
  endif;

  $result = json_encode($result);
  echo $result;

  die();
}
</code>```

答:
WP_Query has a parameter max_num_posts which will tell you how many pages in total the query have.
Inside the callback function you can check if there any more pages left in a query and send the value in response. Than you will be able to hide/show "load more" button with JS function based on that value. You can something similar to this:

```<code>function ajax_filter_get_posts( $category, $tag, $paged = 1 )
{
  $paged = $_POST['paged']; // Pass a number of a page that you want to retrieve. Default is page #1
  $category = $_POST['category'];
  $tag = $_POST['tag'];

  if($category)
  {
    $category_args = array(
      'taxonomy' => 'category',
      'field'    => 'slug',
      'terms'    => $category
    );
  }

  $args = array(
    'posts_per_page' => 6,
    'paged'          => $paged, // pass required page number to WP_Query
    'post_status'    => 'publish',
    'tag'            => implode(",",$tag),
    'tax_query'      => array(
      $category_args,
    ),
    'category__in'      => array(187,186,183,182,184),
  );

  $query = new WP_Query( $args );

  if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post();

    $output = post_factory($post);

    $result['response'][] = $output;
    $result['status']     = 'success';

  endwhile; else:
    $result['response'] = '<h2>No posts found</h2>';
    $result['status']   = '404';
  endif;

  // Check if there are any more pages to query and pass the boolean value in response
  $result['more_pages'] = ( ( $query->max_num_pages - $paged ) > 0 ) ? true : false;

  $result = json_encode($result);
  echo $result;

  die();
}

</code>```

Body:
So i am using ajax to filter and load posts into a container. I want to limit the amount of posts to 6 at a time and add a load more button underneath if there are more than 6 posts, but i don't want to add pages because i have a few containers on the same page that i'm using this same treatment for and my understanding is pages would add a /page-1 or something like that to the url (am i wrong?).

Either way, i just want to know how to check if there are more posts that fit this criteria so i can show the load more button, and then when the load more button fires how do i just load 6 more. Do i have to keep a page variable somewhere? or is there another smarter way.

Here is my query

function ajax_filter_get_posts( $category, $tag )
{
  $category = $_POST['category'];
  $tag = $_POST['tag'];

  if($category)
  {
    $category_args = array(
      'taxonomy' => 'category',
      'field'    => 'slug',
      'terms'    => $category
    );
  }

  $args = array(
    'posts_per_page' => 6,
    'post_status'    => 'publish',
    'tag'            => implode(",",$tag),
    'tax_query'      => array(
      $category_args,
    ),
    'category__in'      => array(187,186,183,182,184),
  );

  $query = new WP_Query( $args );

  if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post();

    $output = post_factory($post);

    $result['response'][] = $output;
    $result['status']     = 'success';

  endwhile; else:
    $result['response'] = '
No posts found
';
    $result['status']   = '404';
  endif;

  $result = json_encode($result);
  echo $result;

  die();
}

Body:
WP_Query has a parameter max_num_posts which will tell you how many pages in total the query have.
Inside the callback function you can check if there any more pages left in a query and send the value in response. Than you will be able to hide/show "load more" button with JS function based on that value. You can something similar to this:

function ajax_filter_get_posts( $category, $tag, $paged = 1 )
{
  $paged = $_POST['paged']; // Pass a number of a page that you want to retrieve. Default is page #1
  $category = $_POST['category'];
  $tag = $_POST['tag'];

  if($category)
  {
    $category_args = array(
      'taxonomy' => 'category',
      'field'    => 'slug',
      'terms'    => $category
    );
  }

  $args = array(
    'posts_per_page' => 6,
    'paged'          => $paged, // pass required page number to WP_Query
    'post_status'    => 'publish',
    'tag'            => implode(",",$tag),
    'tax_query'      => array(
      $category_args,
    ),
    'category__in'      => array(187,186,183,182,184),
  );

  $query = new WP_Query( $args );

  if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post();

    $output = post_factory($post);

    $result['response'][] = $output;
    $result['status']     = 'success';

  endwhile; else:
    $result['response'] = '<h2>No posts found</h2>';
    $result['status']   = '404';
  endif;

  // Check if there are any more pages to query and pass the boolean value in response
  $result['more_pages'] = ( ( $query->max_num_pages - $paged ) > 0 ) ? true : false;

  $result = json_encode($result);
  echo $result;

  die();
}


问:
Is there anything similar to "Add Service Reference" in Xcode?
My current place of employment is primarily a Microsoft shop and we use Visual Studio pretty extensively. I've grown fond of the laziness of using "Add Service Reference" (formerly "Add Web Reference" in VS2005) to download WSDLs and form classes and methods in nice, convenient namespaces for me.

Since we have started to branch out into iPhone development, we have been using Xcode as our IDE for iPhone projects. I would like to be able to do something similar, but haven't been able to find if this ability exists.

If there is similar functionality in Xcode, where is it?

If not, is there a template or something I can download that will do what I want?

答: There is not anything built in for consuming soap services.  If your team is using WCF for the web-service your easiest route is going to be adding a REST endpoint to your existing service.  Then you can use a combination of NSUrlConnection, NSXmlParser and key-value coding to make it almost as easy.</p>

OwnerDisplayName: toast

LastEditorDisplayName: toast

OwnerDisplayName: Lounges

ContentLicense: CC BY-SA 2.5


问:
Don't output same items from array
I'm using react js. I try to map an array with objects and to output the name of each object from array:

const arr = [
  {
    name:"Bill",
    age:88
  },
   {
    name:"Bill",
    age:18
  },
   {
    name:"Jack",
    age:55
  },
]
  {arr.map(i => (

          {i.name}

   ))}```
</div>
</div>
</p>

<p>I want to avoid the same name when i do <code>{i.name}</code>. For this i made this:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>{new Set(i.name)}</code>```

.. but it does not help. How to avoid displaying the same name in map function?

答:
you can use lodash to overcome this issue. Following code snippet will easily do what you need.

```<code>_.uniqBy(arr,"name").map(i => (
    <li key={i.id}>
      {i.name}
    </li>
</code>```

))}

Title: Don't output same items from array

Body:
I'm using react js. I try to map an array with objects and to output the name of each object from array:

const arr = [
  {
    name:"Bill",
    age:88
  },
   {
    name:"Bill",
    age:18
  },
   {
    name:"Jack",
    age:55
  },
]
  {arr.map(i => (

          {i.name}

   ))}

I want to avoid the same name when i do {i.name}. For this i made this:

{new Set(i.name)}

.. but it does not help. How to avoid displaying the same name in map function?

Body:
you can use lodash to overcome this issue. Following code snippet will easily do what you need.

_.uniqBy(arr,"name").map(i => (
    <li key={i.id}>
      {i.name}
    </li>

))}


问:
Docker TCP vs host port
can some one please help me on understanding this, I have a Dockerfile and dockercompose.yaml

When i do docker-compose up, I see the tcp being diffrent compared to the exposed ports, here is the file

```<code>> Dockerfile
FROM msridhara/tomcat
VOLUME /tmp
CMD ["catalina.sh","run"]
EXPOSE 81
</code>```

```<code>>docker-compose.yaml
version: '2'
services:
  web:
    image: msridtomcat
    build: .
    container_name: mcontainer
    restart: always
    volumes:
      - /home/murali/website/containerjob/war/:/usr/local/tomcat/webapps/
#      - /home/ubuntu/webimage/index.html:/var/www/html/index.html
    ports:
      - "81:8080"
</code>```

```<code>docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                          NAMES
2cb36ee8c5ee        msridtomcat         "catalina.sh run"   58 seconds ago      Up 57 seconds       83/tcp, 0.0.0.0:81->8080/tcp   mcontainer
</code>```

Please see the 83/tcp? from where it is coming?

```<code>docker inspect -- results in
"NetworkSettings": {
            "Bridge": "",
            "SandboxID": "397ab289e556f8ee4b92c47e806a11a1f76d53cb398bdd5701e10e20a3362882",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {
                "8080/tcp": [
                    {
                        "HostIp": "0.0.0.0",
                        "HostPort": "81"
                    }
                ],
                "83/tcp": null
            },
</code>```

Thanks
Murali

答: This tcp 83 is due to Expose 83 in Dockerfile. Just removed the Expose from Dockerfile and exposed the port via docker-compose yaml. All worked well</p>

Title: Docker TCP vs host port

Body:
can some one please help me on understanding this, I have a Dockerfile and dockercompose.yaml

When i do docker-compose up, I see the tcp being diffrent compared to the exposed ports, here is the file

> Dockerfile
FROM msridhara/tomcat
VOLUME /tmp
CMD ["catalina.sh","run"]
EXPOSE 81

>docker-compose.yaml
version: '2'
services:
  web:
    image: msridtomcat
    build: .
    container_name: mcontainer
    restart: always
    volumes:
      - /home/murali/website/containerjob/war/:/usr/local/tomcat/webapps/
#      - /home/ubuntu/webimage/index.html:/var/www/html/index.html
    ports:
      - "81:8080"

docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                          NAMES
2cb36ee8c5ee        msridtomcat         "catalina.sh run"   58 seconds ago      Up 57 seconds       83/tcp, 0.0.0.0:81->8080/tcp   mcontainer

Please see the 83/tcp? from where it is coming?

docker inspect -- results in
"NetworkSettings": {
            "Bridge": "",
            "SandboxID": "397ab289e556f8ee4b92c47e806a11a1f76d53cb398bdd5701e10e20a3362882",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {
                "8080/tcp": [
                    {
                        "HostIp": "0.0.0.0",
                        "HostPort": "81"
                    }
                ],
                "83/tcp": null
            },

Thanks
Murali


答:
You can remove the duplicates from the arr based on the name property in each object and then use array map() method on it like:

```<code>{[...new Map(arr.map(i=> [i.name, i])).values()].map(i => (
   <li key={i.id}>
      {i.name}
   </li>
))}
</code>```

Demo:

const arr = [{name:"Bill",age:88},{name:"Bill",age:18},{name:"Jack",age:55}];

class App extends React.Component {
  render() {
    return (

      {[...new Map(arr.map(i=> [i.name, i])).values()].map(i => (

          {i.name}

      ))}

);
  }
}

ReactDOM.render(<App />, document.getElementById("app"));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div></code>```

Title: Don't output same items from array

Body:
You can remove the duplicates from the arr based on the name property in each object and then use array map() method on it like:

{[...new Map(arr.map(i=> [i.name, i])).values()].map(i => (
   <li key={i.id}>
      {i.name}
   </li>
))}

Demo:

const arr = [{name:"Bill",age:88},{name:"Bill",age:18},{name:"Jack",age:55}];

class App extends React.Component {
  render() {
    return (<div>
      {[...new Map(arr.map(i=> [i.name, i])).values()].map(i => (
        <li key={i.id}>
          {i.name}
        </li>
      ))}
    </div>);
  }
}

ReactDOM.render(<App />, document.getElementById("app"));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>


问:
How to save a picture in WPF application
Goal:

Save a picture from the harddrive into my WPF application. The picture should be available if copying the WPF application. The address to the picture located in the WPF application should be saved in the database.

Problem:

How should I do it in a course of action?

```<code>private void btnBrowse_Click(object sender, RoutedEventArgs e)
{
    Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();

    dlg.Filter = "jpg files (*.jpg)|*.jpg|gif files (*.gif)|*.gif|jpeg files (*.jpeg)|*.jpeg";

    Nullable<bool> result = dlg.ShowDialog();

    if (result == true)
    {
        // Open document
        string filename = dlg.FileName;

        txtPicture.Text = filename;

        BitmapImage myBitmapImage = new BitmapImage(new Uri(dlg.FileName, UriKind.Absolute));
        string sss = myBitmapImage.Format.ToString();
        string asd = dlg.SafeFileName.ToString();
    }
}
</code>```

答: There are several image encoders available. A simple example for PNG files can be found here, or a more complete sample here. The same concept applies for the other supported image file types.</p>

Body:
Goal:

Save a picture from the harddrive into my WPF application. The picture should be available if copying the WPF application. The address to the picture located in the WPF application should be saved in the database.

Problem:

How should I do it in a course of action?

private void btnBrowse_Click(object sender, RoutedEventArgs e)
{
    Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();

    dlg.Filter = "jpg files (*.jpg)|*.jpg|gif files (*.gif)|*.gif|jpeg files (*.jpeg)|*.jpeg";

    Nullable<bool> result = dlg.ShowDialog();

    if (result == true)
    {
        // Open document
        string filename = dlg.FileName;

        txtPicture.Text = filename;

        BitmapImage myBitmapImage = new BitmapImage(new Uri(dlg.FileName, UriKind.Absolute));
        string sss = myBitmapImage.Format.ToString();
        string asd = dlg.SafeFileName.ToString();
    }
}


Title: Extract rows from dataframe which were absent on certain days

Body:
I have a dataframe:

Date          Agent
2020-02-10    A
2020-02-11    A
2020-02-12    A
2020-02-13    A
2020-02-14    A
2020-02-10    B
2020-02-12    B
2020-02-10    C
2020-02-11    C
2020-02-14    C

I want to get a data frame with those row which were absent at certain days from 2020-02-10 to 2020-02-14. So desired output is:

Agent  Days_absent
B      2020-02-11; 2020-02-13; 2020-02-14
C      2020-02-12; 2020-02-13

or

Date          Agent
2020-02-11    B
2020-02-13    B
2020-02-14    B
2020-02-12    C
2020-02-13    C

How could i do that?

Body:
A solution using an anti-join:

library(tidyverse)
#Data
df <- structure(list(Date = structure(c(18302, 18303, 18304, 18305,
18306, 18302, 18304, 18302, 18303, 18306), class = "Date"), Agent = c("A",
"A", "A", "A", "A", "B", "B", "C", "C", "C")), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -10L)) %>%
  mutate(Date = as.Date(Date))

dates <- tibble(Date = seq(as.Date("2020-02-10"), as.Date("2020-02-14"), "days")) %>%
  expand_grid(Agent = c("A","B","C"))

dates %>%
  anti_join(df) %>%
  arrange(Agent)

# A tibble: 5 x 2
#  Date       Agent
#  <date>     <chr>
#1 2020-02-11 B
#2 2020-02-13 B
#3 2020-02-14 B
#4 2020-02-12 C
#5 2020-02-13 C


问:
Where to transform store property in Redux/ngrx
I have the following setup

someReducer.ts

```<code>export interface State {
   someProp: MyModel;
}
// some action listeners ..
//
//

export const getProp = (state: State) => state.someProp;
</code>```

selector.ts

```<code>export const getProperty = createSelector(getState, fromSomeReducer.getProperty);
</code>```

Now say in my components I want to use a transformed version of this someProp like

myProp = this.store.pipe(select(fromSelector.getProperty)).pipe(map(val => //some logic here));

Now this mapping logic can be long, and I dont want to be duplicating this code in several components.

Where does it make sense the most to put this mapping?

I add it to the reducer like this

export const getMapped = (state: State) => state.map(val => // some logic); and then I get this in the selector.

Is this the recommended approach?

答:
If I understand, you are looking for Selector

export const mySelector = createSelector(
  getProperty,
  val => // Your logic go here
)
```

<p>You can now use it</p>

<pre class="lang-js prettyprint-override"><code>this.store.pipe(select(fromSelector.mySelector)).subscribe(...);
</code>```

Body:
I have the following setup

someReducer.ts

export interface State {
   someProp: MyModel;
}
// some action listeners ..
//
//

export const getProp = (state: State) => state.someProp;

selector.ts

export const getProperty = createSelector(getState, fromSomeReducer.getProperty);

Now say in my components I want to use a transformed version of this someProp like

myProp = this.store.pipe(select(fromSelector.getProperty)).pipe(map(val => //some logic here));

Now this mapping logic can be long, and I dont want to be duplicating this code in several components.

Where does it make sense the most to put this mapping?

I add it to the reducer like this

export const getMapped = (state: State) => state.map(val => // some logic); and then I get this in the selector.

Is this the recommended approach?

Body:
If I understand, you are looking for Selector

export const mySelector = createSelector(
  getProperty,
  val => // Your logic go here
)

You can now use it

this.store.pipe(select(fromSelector.mySelector)).subscribe(...);


问:
Using XSETBV to write to XCR0 creates a general protection fault in a VM on hardware that supports MPX
I am trying to write to Extended Control Register 0 (xcr0) on an x86_64 Debian v7 virtual machine. My approach to doing so is through a kernel module (so CPL=0) with some inline assembly. However, I keep getting a general protection fault (#GP) when I try to execute the xsetbv instruction.

The init function of my module first checks that the osxsave bit is set in control register 4 (cr4). If it isn't, it sets it. Then, I read the xcr0 register using xgetbv. This works fine and (in the limited testing I have done) has the value 0b111. I would like to set the bndreg and bndcsr bits which are the 3rd and 4th bits (0-indexed), so I do some ORing and write 0b11111 back to xcr0 using xsetbv. The code to achieve this last part is as follows.

```<code>unsigned long xcr0;             /* extended register    */
unsigned long bndreg = 0x8;     /* 3rd bit in xcr0      */
unsigned long bndcsr = 0x10;    /* 4th bit in xcr0      */

/* ... checking cr4 for osxsave and reading xcr0 ... */

if (!(xcr0 & bndreg))
    xcr0 |= bndreg;

if (!(xcr0 & bndcsr))
    xcr0 |= bndcsr;

/* ... xcr0 is now 0b11111 ... */

/*
 * write changes to xcr0; ignore high bits (set them =0) b/c they are reserved
 */
unsigned long new_xcr0 = ((xcr0) & 0xffffffff);
__asm__ volatile (
    "mov $0, %%ecx      \t\n" // %ecx selects the xcr to write
    "xor %%rdx, %%rdx   \t\n" // set %rdx to zero
    "xsetbv             \t\n" // write from edx:eax into xcr0
    :
    : "a" (new_xcr0)        /* input    */
    : "ecx", "rdx"          /* clobbered    */
);
</code>```

By looking at the trace from the general protection fault, I determined that the xsetbv instruction is the problem. However, if I don't manipulate xcr0 and just read its value and write it back, things seem to work fine. Looking at the Intel manual and this site, I found various reasons for a #GP, but none of them seem to match my situation. The reasons are as follows along with my explanation for why they most likely don't apply.

If the current privilege level is not 0 --> I use a kernel module to achieve CPL=0

If an invalid xcr is specified in %ecx --> 0 is in %ecx which is valid and worked for xgetbv

If the value in edx:eax sets bits that are reserved in the xcr specified by ecx --> according to the Intel manual and Wikipedia the bits I am setting are not reserved

If an attempt is made to clear bit 0 of xcr0 --> I printed out xcr0 before setting it, and it was 0b11111

If an attempt is made to set xcr0[2:1] to 0b10 --> I printed out xcr0 before setting it, and it was 0b11111

Thank you in advance for any help discovering why this #GP is happening.

答:
Peter Cordes was right, it was a problem with my hypervisor. I am using VMWare Fusion for virtualization, and after a lot of digging on the internet I found the following quote from VMWare:

Memory protection extensions (MPX) were introduced in Intel Skylake generation CPUs and provided hardware support for bound checking. This feature will not be supported in Intel CPUs beginning with the Ice Lake generation.

Starting with ESXi 6.7 P02 and ESXi 7.0 GA, in order to minimize disruptions during future upgrades, VMware will no longer expose MPX by default to VMs at power-on. A VM configuration option can be used to continue exposing MPX.

The solution VMWare proposed was to edit the virtual machine's .vmx file with the following directive.

```<code>cpuid.enableMPX = "TRUE"
</code>```

After I did this, things worked and I was able to use xsetbv to enable the bndreg and bndcsr bits of xcr0.

When using VMWare to expose CPU features from the host to the guest under more normal conditions (i.e. the feature isn't plagued with deprecation) you can mask the bits of cpuid leaves by adding the following to the VM's .vmx file.

```<code>cpuid.<leaf>.<register> = "<value>"
</code>```

So, for example, if we assume that SMAP can be exposed this way, we would want to set bit 20 of cpuid leaf 7.

```<code>cpuid.7.ebx = "----:----:---1:----:----:----:----:----"
</code>```

Colons are optional to ease reading of the string, ones and zeros override any default settings, and dashes are used to leave default setting alone.

Body:
I am trying to write to Extended Control Register 0 (xcr0) on an x86_64 Debian v7 virtual machine. My approach to doing so is through a kernel module (so CPL=0) with some inline assembly. However, I keep getting a general protection fault (#GP) when I try to execute the xsetbv instruction.

The init function of my module first checks that the osxsave bit is set in control register 4 (cr4). If it isn't, it sets it. Then, I read the xcr0 register using xgetbv. This works fine and (in the limited testing I have done) has the value 0b111. I would like to set the bndreg and bndcsr bits which are the 3rd and 4th bits (0-indexed), so I do some ORing and write 0b11111 back to xcr0 using xsetbv. The code to achieve this last part is as follows.

unsigned long xcr0;             /* extended register    */
unsigned long bndreg = 0x8;     /* 3rd bit in xcr0      */
unsigned long bndcsr = 0x10;    /* 4th bit in xcr0      */

/* ... checking cr4 for osxsave and reading xcr0 ... */

if (!(xcr0 & bndreg))
    xcr0 |= bndreg;

if (!(xcr0 & bndcsr))
    xcr0 |= bndcsr;

/* ... xcr0 is now 0b11111 ... */

/*
 * write changes to xcr0; ignore high bits (set them =0) b/c they are reserved
 */
unsigned long new_xcr0 = ((xcr0) & 0xffffffff);
__asm__ volatile (
    "mov $0, %%ecx      \t\n" // %ecx selects the xcr to write
    "xor %%rdx, %%rdx   \t\n" // set %rdx to zero
    "xsetbv             \t\n" // write from edx:eax into xcr0
    :
    : "a" (new_xcr0)        /* input    */
    : "ecx", "rdx"          /* clobbered    */
);

By looking at the trace from the general protection fault, I determined that the xsetbv instruction is the problem. However, if I don't manipulate xcr0 and just read its value and write it back, things seem to work fine. Looking at the Intel manual and this site, I found various reasons for a #GP, but none of them seem to match my situation. The reasons are as follows along with my explanation for why they most likely don't apply.

If the current privilege level is not 0 --> I use a kernel module to achieve CPL=0

If an invalid xcr is specified in %ecx --> 0 is in %ecx which is valid and worked for xgetbv

If the value in edx:eax sets bits that are reserved in the xcr specified by ecx --> according to the Intel manual and Wikipedia the bits I am setting are not reserved

If an attempt is made to clear bit 0 of xcr0 --> I printed out xcr0 before setting it, and it was 0b11111

If an attempt is made to set xcr0[2:1] to 0b10 --> I printed out xcr0 before setting it, and it was 0b11111

Thank you in advance for any help discovering why this #GP is happening.

Body:
Peter Cordes was right, it was a problem with my hypervisor. I am using VMWare Fusion for virtualization, and after a lot of digging on the internet I found the following quote from VMWare:

Memory protection extensions (MPX) were introduced in Intel Skylake generation CPUs and provided hardware support for bound checking. This feature will not be supported in Intel CPUs beginning with the Ice Lake generation.

Starting with ESXi 6.7 P02 and ESXi 7.0 GA, in order to minimize disruptions during future upgrades, VMware will no longer expose MPX by default to VMs at power-on. A VM configuration option can be used to continue exposing MPX.

The solution VMWare proposed was to edit the virtual machine's .vmx file with the following directive.

cpuid.enableMPX = "TRUE"

After I did this, things worked and I was able to use xsetbv to enable the bndreg and bndcsr bits of xcr0.

When using VMWare to expose CPU features from the host to the guest under more normal conditions (i.e. the feature isn't plagued with deprecation) you can mask the bits of cpuid leaves by adding the following to the VM's .vmx file.

cpuid.<leaf>.<register> = "<value>"

So, for example, if we assume that SMAP can be exposed this way, we would want to set bit 20 of cpuid leaf 7.

cpuid.7.ebx = "----:----:---1:----:----:----:----:----"

Colons are optional to ease reading of the string, ones and zeros override any default settings, and dashes are used to leave default setting alone.


问:
how to deal with sqlalchemy.util._collections.result？
I just want to execute the sql：

```<code>select distinct price from items
</code>```

so I write sqlalchemy code like below:

```<code>result_list = session.query(func.distinct(items.price)).all()
</code>```

In my db, there are only 2 distinct prices, so the result should be 100 and 200 for example.

However, it returns a list of sqlalchemy.util._collections.result.
But what I want is a list of int, such as [100, 200]

Of course I can do like this:

```<code>int_list = [ x.price for x in result_list ]
</code>```

But this "workaround " is so ugly.

So is there a function like to_base_type so that I can write code like this:

```<code>int_list = session.query(func.distinct(items.price)).to_base_type()
</code>```

Thanks very much if anyone can help me

答:
looking at this answer: https://stackoverflow.com/a/13118371/8953378

you can use:

```<code>result_list = [p for (p,) in session.query(func.distinct(items.price))]
</code>```

Body:
I just want to execute the sql：

select distinct price from items

so I write sqlalchemy code like below:

result_list = session.query(func.distinct(items.price)).all()

In my db, there are only 2 distinct prices, so the result should be 100 and 200 for example.

However, it returns a list of sqlalchemy.util._collections.result.
But what I want is a list of int, such as [100, 200]

Of course I can do like this:

int_list = [ x.price for x in result_list ]

But this "workaround " is so ugly.

So is there a function like to_base_type so that I can write code like this:

int_list = session.query(func.distinct(items.price)).to_base_type()

Thanks very much if anyone can help me

Body:
looking at this answer: https://stackoverflow.com/a/13118371/8953378

you can use:

result_list = [p for (p,) in session.query(func.distinct(items.price))]


问:
React-Materialize Modal : any key will close the modal unexpectedly
Description
I have a react-materialize modal with text inputs
In the options, I have set dismissible to false

Actual behavior:
When I type text inside or anything, any key will close the modal.

Expected behavior:
I want to close the modal only when the button close is clicked or the button submit is clicked
Do you know why any key will close the modal ? I think it is because of the OnChange on my inputs.

Thank you

Versions
react-materialize: 3.5.10
materialize-css: 1.0.0
react: 16.12.0

```<code><Form>
  <Modal actions={[ <div>
    <Button className="blue darken-4" size="sm" onClick={()=> this.closeModal()}>Annuler</Button>{' '}
    <Button className="blue darken-4" size="sm" onClick={()=> this.addProd(producerName, producerShare)} >Enregistrer dans la blockchain</Button>
    </div>

    ]} bottomSheet={false} fixedFooter={false} header="Ajouter un coproducteur" id="Modal-0" open={false} options={{ dismissible: false, endingTop: '10%', inDuration: 250, onCloseEnd: null, onCloseStart: null, onOpenEnd: null, onOpenStart: null, opacity:
    0.5, outDuration: 250, preventScrolling: true, startingTop: '4%' }} trigger={
    <Button className="blue darken-4">Ajouter un coproducteur</Button>} >
    <p>

      Veuillez saisir le nom du coproducteur et le pourcentage de ses parts dans le projet
    </p>
    <br></br>

    <TextInput id="producerName" placeholder="Nom" onChange={adresse=> this.setState({producerName: adresse.target.value})} />{' '}
      <br></br>
      <TextInput id="producerShare" placeholder="Part Producteur" onChange={adresse=> this.setState({producerShare: adresse.target.value})} />
        <br></br>
  </Modal>
</Form>
</code>```

答: Solution is to remove open={false} </p>

Body:
Description
I have a react-materialize modal with text inputs
In the options, I have set dismissible to false

Actual behavior:
When I type text inside or anything, any key will close the modal.

Expected behavior:
I want to close the modal only when the button close is clicked or the button submit is clicked
Do you know why any key will close the modal ? I think it is because of the OnChange on my inputs.

Thank you

Versions
react-materialize: 3.5.10
materialize-css: 1.0.0
react: 16.12.0

<Form>
  <Modal actions={[

    <Button className="blue darken-4" size="sm" onClick={()=> this.closeModal()}>Annuler</Button>{' '}
    <Button className="blue darken-4" size="sm" onClick={()=> this.addProd(producerName, producerShare)} >Enregistrer dans la blockchain</Button>

    ]} bottomSheet={false} fixedFooter={false} header="Ajouter un coproducteur" id="Modal-0" open={false} options={{ dismissible: false, endingTop: '10%', inDuration: 250, onCloseEnd: null, onCloseStart: null, onOpenEnd: null, onOpenStart: null, opacity:
    0.5, outDuration: 250, preventScrolling: true, startingTop: '4%' }} trigger={
    <Button className="blue darken-4">Ajouter un coproducteur</Button>} >

      Veuillez saisir le nom du coproducteur et le pourcentage de ses parts dans le projet

    <TextInput id="producerName" placeholder="Nom" onChange={adresse=> this.setState({producerName: adresse.target.value})} />{' '}

      <TextInput id="producerShare" placeholder="Part Producteur" onChange={adresse=> this.setState({producerShare: adresse.target.value})} />

  </Modal>
</Form>

Body: Solution is to remove open={false}


问:
Postgres-XL Load Balancing
Postgres-XL Documentations and also overview describes load balancing as a distinct part of the system.

Am I correct and it is up to Postgres-XL users to load balance or is there specific a way of doing load balance (using load information of coordinators etc.) operation and making it high available?

答:
I think that the question has not been well answered since postgres-xl supports the configuration of several coordinators as explained on their page https://www.postgres-xl.org/documentation/tutorial-arch.html
where says:
Postgres-XL allows multiple Coordinators to accept statements from applications independently but in an integrated way. Any writes from any Coordinator is available from any other Coordinators. They acts as if they are single database. The Coordinator's role is to accept statements, find what Datanodes are involved, send query plans on to the appropriate Datanodes if needed, collect the results and write them back to applications.

The Coordinator does not store any user data. It stores only catalog data to determine how to process statements, where the target Datanodes are, among others. Therefore, you don't have to worry about Coordinator failure much. When the Coordinator fails, you can just switch to the other one.
So the question is aimed at how to have a load balancer that connects the application with the coordinators of postgres-xl, in which a solution such as nginx or HAPproxy can enter, a solution is nginx with its stream modulethat can connect nginx as load balancer to postgres-xl

If you want to use nginx as a load balancer between your application and the postgres-xd database, use the ngx_stream module
the configuration is in the link
http://nginx.org/en/docs/stream/ngx_stream_core_module.html

Title: Postgres-XL Load Balancing


问:
Get current account selected in Metamask using Drizzle
How to (in Drizzle) get the account currently selected in Metamask?

I have a function to call a method set of the smart contract, but currently account is "hardcoded":

```<code>  setValue = value => {
    const { drizzle, drizzleState } = this.props;
    const contract = drizzle.contracts.PartProduction;

    // let drizzle know we want to call the `set` method with `value`
    const stackId = contract.methods["set"].cacheSend(value, {
      from: drizzleState.accounts[0]
    });

    // save the `stackId` for later reference
    this.setState({ stackId });
  };
</code>```

i.e. in: from: drizzleState.accounts[0].

How to change the from: field to use the account selected in Metamask?

答:
The best way is to add an option for the drizzle option so that it can detect web3 objects in the browser.

Edit the drizzle option code to below

```<code>  web3: {
    block: false,
    customProvider: new Web3(Web3.givenProvider || "ws://localhost:8545"),
    // customProvider: new Web3("wss://kovan.infura.io/ws/v3/5b2a79e624554c8ab922b9a84b076645"),

  },
</code>```

Body:
How to (in Drizzle) get the account currently selected in Metamask?

I have a function to call a method set of the smart contract, but currently account is "hardcoded":

  setValue = value => {
    const { drizzle, drizzleState } = this.props;
    const contract = drizzle.contracts.PartProduction;

    // let drizzle know we want to call the `set` method with `value`
    const stackId = contract.methods["set"].cacheSend(value, {
      from: drizzleState.accounts[0]
    });

    // save the `stackId` for later reference
    this.setState({ stackId });
  };

i.e. in: from: drizzleState.accounts[0].

How to change the from: field to use the account selected in Metamask?

Body:
The best way is to add an option for the drizzle option so that it can detect web3 objects in the browser.

Edit the drizzle option code to below

  web3: {
    block: false,
    customProvider: new Web3(Web3.givenProvider || "ws://localhost:8545"),
    // customProvider: new Web3("wss://kovan.infura.io/ws/v3/5b2a79e624554c8ab922b9a84b076645"),

  },