问:
Protofuf c++ - Deserialized message has no data
I'm not entirely sure i'm doing this correctly. If tried both Merge and ParseFromCodedStream.  Code and output below:

```<code>bool tcp_connection::readDelimitedFrom(
    google::protobuf::io::ZeroCopyInputStream* rawInput,
    jvm* message, uint32_t* payloadSize) {

    DEBUG && (cerr << "------ readDelimitedFrom.begin " << '\n');
    // We create a new coded stream for each message.  Don't worry, this is fast,
    // and it makes sure the 64MB total size limit is imposed per-message rather
    // than on the whole stream.  (See the CodedInputStream interface for more
    // info on this limit.)
    google::protobuf::io::CodedInputStream input(rawInput);

    // Read the size.
    if (!input.ReadLittleEndian32(payloadSize)) return false;

    DEBUG && (cerr << "------ readDelimitedFrom got size: " << *payloadSize << '\n');
    DEBUG && (cerr << "------   input.CurrentPosition: " << input.CurrentPosition() << '\n');

    DEBUG && (cerr << "------ "  << '\n');
    try {

        google::protobuf::io::CodedInputStream::Limit limit =
            input.PushLimit(*payloadSize);
        DEBUG && (cerr << "------ PushLimit:" << *payloadSize << '\n');

        // Parse the message.
        if (!message->ParseFromCodedStream(&input)) return false;
        DEBUG && (cerr << "------ MergeFromCodedStream" << '\n');
                  cout << "----------- size:" << message->ByteSize() << endl;

        if (!input.ConsumedEntireMessage()) return false;
        DEBUG && (cerr << "------ ConsumedEntireMessage" << '\n');

        // Release the limit.
        input.PopLimit(limit);
        DEBUG && (cerr << "------ PopLimit" << '\n');
    }
    catch (const std::exception &exc)
    {
        // catch anything thrown within try block that derives from std::exception
        cerr << exc.what() << endl;
        return false;
    }
    // Tell the stream not to read beyond that size.
    DEBUG && (cerr << "------ readDelimitedFrom return true " << '\n');

    return true;
}
</code>```

Console out:

```<code>---- connection.start (disabling Nagle)
------ h.r.h 4 bytes
------ readDelimitedFrom.begin
------ readDelimitedFrom got size: 76
------   input.CurrentPosition: 4
------
------ PushLimit:76
------ MergeFromCodedStream
----------- size:0
------ ConsumedEntireMessage
------ PopLimit
------ readDelimitedFrom return true
</code>```

答:
I think the issue was that I wasn't adjusting the stream after parsing the header. Now I only peek the socket header:

```<code>char buf[HEADER_SIZE];
socket().receive(boost::asio::buffer(buf), tcp::socket::message_peek);
</code>```

For anyone wanting to know the correct code:

```<code>ArrayInputStream ais(&m_readbuf[HEADER_SIZE], msg_len - HEADER_SIZE);
CodedInputStream cis(&ais);
jvm jvm;
bool isParsed = jvm.ParseFromCodedStream(&cis);

if (isParsed) {
    DEBUG && (cerr << "jvm:[" << jvm.name() << "] size:" << jvm.ByteSize() << endl);
    DEBUG && (cerr << "Got body:\n");
    DEBUG && (cerr << show_hex(m_readbuf) << endl);
    handle_request(&jvm);
}
else {
    DEBUG && (cerr << "didnt parse <----\n");
}
</code>```

Body:
I'm not entirely sure i'm doing this correctly. If tried both Merge and ParseFromCodedStream.  Code and output below:

bool tcp_connection::readDelimitedFrom(
    google::protobuf::io::ZeroCopyInputStream* rawInput,
    jvm* message, uint32_t* payloadSize) {

    DEBUG && (cerr << "------ readDelimitedFrom.begin " << '\n');
    // We create a new coded stream for each message.  Don't worry, this is fast,
    // and it makes sure the 64MB total size limit is imposed per-message rather
    // than on the whole stream.  (See the CodedInputStream interface for more
    // info on this limit.)
    google::protobuf::io::CodedInputStream input(rawInput);

    // Read the size.
    if (!input.ReadLittleEndian32(payloadSize)) return false;

    DEBUG && (cerr << "------ readDelimitedFrom got size: " << *payloadSize << '\n');
    DEBUG && (cerr << "------   input.CurrentPosition: " << input.CurrentPosition() << '\n');

    DEBUG && (cerr << "------ "  << '\n');
    try {

        google::protobuf::io::CodedInputStream::Limit limit =
            input.PushLimit(*payloadSize);
        DEBUG && (cerr << "------ PushLimit:" << *payloadSize << '\n');

        // Parse the message.
        if (!message->ParseFromCodedStream(&input)) return false;
        DEBUG && (cerr << "------ MergeFromCodedStream" << '\n');
                  cout << "----------- size:" << message->ByteSize() << endl;

        if (!input.ConsumedEntireMessage()) return false;
        DEBUG && (cerr << "------ ConsumedEntireMessage" << '\n');

        // Release the limit.
        input.PopLimit(limit);
        DEBUG && (cerr << "------ PopLimit" << '\n');
    }
    catch (const std::exception &exc)
    {
        // catch anything thrown within try block that derives from std::exception
        cerr << exc.what() << endl;
        return false;
    }
    // Tell the stream not to read beyond that size.
    DEBUG && (cerr << "------ readDelimitedFrom return true " << '\n');

    return true;
}

Console out:

---- connection.start (disabling Nagle)
------ h.r.h 4 bytes
------ readDelimitedFrom.begin
------ readDelimitedFrom got size: 76
------   input.CurrentPosition: 4
------
------ PushLimit:76
------ MergeFromCodedStream
----------- size:0
------ ConsumedEntireMessage
------ PopLimit
------ readDelimitedFrom return true

Body:
I think the issue was that I wasn't adjusting the stream after parsing the header. Now I only peek the socket header:

char buf[HEADER_SIZE];
socket().receive(boost::asio::buffer(buf), tcp::socket::message_peek);

For anyone wanting to know the correct code:

ArrayInputStream ais(&m_readbuf[HEADER_SIZE], msg_len - HEADER_SIZE);
CodedInputStream cis(&ais);
jvm jvm;
bool isParsed = jvm.ParseFromCodedStream(&cis);

if (isParsed) {
    DEBUG && (cerr << "jvm:[" << jvm.name() << "] size:" << jvm.ByteSize() << endl);
    DEBUG && (cerr << "Got body:\n");
    DEBUG && (cerr << show_hex(m_readbuf) << endl);
    handle_request(&jvm);
}
else {
    DEBUG && (cerr << "didnt parse <----\n");
}


来源: stackexchange

问:
Adding hook to model creation in rails
I have a model class Person, and I create instances of them using:

```<code>person = Person.create!
</code>```

Now I want to say that this person was born in California, USA, but in this peculiar way:

```<code>person = Person.create!({:name => "Matt", :born => "USCA"})
</code>```

This means there are two characters to identify the country and another two characters to identify the state.
But I don't want to store the string in the database, I want to store in a structured way, like:

| Name | Country | State      |

| Matt | USA     | California |

Where can I parse the string to assign the country and state based on it? Which method in the model?

Thanks in advance

答:
You could use a before_save callback — something like this:

```<code>attr_accessible :born

before_save :parse_location

def parse_location
    # parsing here…
end
</code>```

ContentLicense: CC BY-SA 2.5

Title: Adding hook to model creation in rails

Body:
I have a model class Person, and I create instances of them using:

person = Person.create!

Now I want to say that this person was born in California, USA, but in this peculiar way:

person = Person.create!({:name => "Matt", :born => "USCA"})

This means there are two characters to identify the country and another two characters to identify the state.
But I don't want to store the string in the database, I want to store in a structured way, like:

| Name | Country | State      |

| Matt | USA     | California |

Where can I parse the string to assign the country and state based on it? Which method in the model?

Thanks in advance

Body:
You could use a before_save callback — something like this:

attr_accessible :born

before_save :parse_location

def parse_location
    # parsing here…
end


问:
Purescript Halogen Component, Input vs State
I want to make a Halogen Component where the component's input differs from its state. According to the guide for Halogen (https://github.com/slamdata/purescript-halogen/blob/master/docs/5%20-%20Parent%20and%20child%20components.md#input-values) this should be possible. I changed the example from the guide as follows

```<code>import Prelude
import Data.Int (decimal, toStringAs)
import Halogen as H
import Halogen.HTML as HH
import Halogen.HTML.Events as HHE

type Input = Int

type State = String

data Query a = HandleInput Input a

component :: forall m. H.Component HH.HTML Query Input Void m
component =
  H.component
    { initialState: id
    , render
    , eval
    , receiver: HHE.input HandleInput
    }
  where

  render :: State -> H.ComponentHTML Query
  render state =
    HH.div_
      [ HH.text "My input value is:"
      , HH.strong_ [ HH.text (show state) ]
      ]

  eval :: Query ~> H.ComponentDSL State Query Void m
  eval = case _ of
    HandleInput n next -> do
      oldN <- H.get
      when (oldN /= (toStringAs decimal n)) $ H.put $ toStringAs decimal n
      pure next
</code>```

But then I get a compile error at the line with , receiver: HHE.input HandleInput

```<code>Could not match type

  String

with type

  Int
</code>```

What am I doing wrong here?

答:
Changed line { initialState: id in { initialState: const initialState and added after where the following lines

```<code>initialState :: State
initialState = ""
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to make a Halogen Component where the component's input differs from its state. According to the guide for Halogen (https://github.com/slamdata/purescript-halogen/blob/master/docs/5%20-%20Parent%20and%20child%20components.md#input-values) this should be possible. I changed the example from the guide as follows

import Prelude
import Data.Int (decimal, toStringAs)
import Halogen as H
import Halogen.HTML as HH
import Halogen.HTML.Events as HHE

type Input = Int

type State = String

data Query a = HandleInput Input a

component :: forall m. H.Component HH.HTML Query Input Void m
component =
  H.component
    { initialState: id
    , render
    , eval
    , receiver: HHE.input HandleInput
    }
  where

  render :: State -> H.ComponentHTML Query
  render state =
    HH.div_
      [ HH.text "My input value is:"
      , HH.strong_ [ HH.text (show state) ]
      ]

  eval :: Query ~> H.ComponentDSL State Query Void m
  eval = case _ of
    HandleInput n next -> do
      oldN <- H.get
      when (oldN /= (toStringAs decimal n)) $ H.put $ toStringAs decimal n
      pure next

But then I get a compile error at the line with , receiver: HHE.input HandleInput

Could not match type

  String

with type

  Int

What am I doing wrong here?

Body:
Changed line { initialState: id in { initialState: const initialState and added after where the following lines

initialState :: State
initialState = ""


问:
How to bind <select> ng-model using ng-options inside a ng-repeat
I have a list of tasks:

```<code>[{
    Titel: "Title1",
    Position: "9"
},{
    Titel: "Title2",
    Position: "1"
},{
    Titel: "Title3",
    Position: "5"
},{
    Titel: "Title4",
    Position: "7"
}]
</code>```

I'm trying to create a list of <select>, where each is list.lenght long and has a selected value. The html snippet:

```<code><table cellpadding="0" cellspacing="0" border="0">
    <tr>
        <td class="ms-authoringcontrols"><b>Title</b></td>
        <td class="ms-authoringcontrols"><b>Position</b></td>
    </tr>
    <tr ng-repeat="t in tasks">
        <td>
            <a href="TODO">{{t.Titel}}</a>
        </td>
        <td>
            <select ng-model="t.Position" ng-options="t.Position as tasks.indexOf(i)+1 for i in tasks"></select>
        </td>
    </tr>
</table
</code>```

Output:

What it is missing, is the selected value (position) of each <select>. I Know the value is set by defining the ng-model and ng-model="t.Position" is wrong, but how can I set the Position value of each item to its related select element? The <option>'s of each select should be the length of the tasks and ordered from 1 to n.

答:
You are very close, the ngOptions format you are looking for is select as label for value in array, where select is the value that will be assigned to the model.

In your case Position is string, so we need to convert select to string too so it matches the model:

```<code>ng-options="(tasks.indexOf(i)+1).toString() as tasks.indexOf(i)+1 for i in tasks"
            ^ model value                      ^ display
</code>```

( tasks.indexOf(i)+1+'' would work too)

angular
  .module('Test', [])
  .controller('TestCtrl', function($scope) {
    $scope.tasks = [{
          Titel: "Title1",
          Position: "9"
      },{
          Titel: "Title2",
          Position: "1"
      },{
          Titel: "Title3",
          Position: "3"
      },{
          Titel: "Title4",
          Position: "2"
      }];
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="Test" ng-controller="TestCtrl">
  <table cellpadding="0" cellspacing="0" border="0">
      <tr>
          <td class="ms-authoringcontrols"><b>Title</b></td>
          <td class="ms-authoringcontrols"><b>Position</b></td>
      </tr>

      <tr ng-repeat="t in tasks">
          <td>
              {{t.Titel}}
          </td>
          <td>
              <select ng-model="t.Position" ng-options="(tasks.indexOf(i)+1).toString() as tasks.indexOf(i)+1 for i in tasks"></select>
          </td>
      </tr>
  </table>
  ```{{tasks|json}}```
</div></code>```

(If you run the snippet you will notice the first  is not
  selected, that's because [1,2,3,4] doesn't contain 9.)

Body:
I have a list of tasks:

[{
    Titel: "Title1",
    Position: "9"
},{
    Titel: "Title2",
    Position: "1"
},{
    Titel: "Title3",
    Position: "5"
},{
    Titel: "Title4",
    Position: "7"
}]

I'm trying to create a list of <select>, where each is list.lenght long and has a selected value. The html snippet:

        Title
        Position

            {{t.Titel}}

            <select ng-model="t.Position" ng-options="t.Position as tasks.indexOf(i)+1 for i in tasks"></select>

</table

Output:

What it is missing, is the selected value (position) of each <select>. I Know the value is set by defining the ng-model and ng-model="t.Position" is wrong, but how can I set the Position value of each item to its related select element? The <option>'s of each select should be the length of the tasks and ordered from 1 to n.

Body:
You are very close, the ngOptions format you are looking for is select as label for value in array, where select is the value that will be assigned to the model.

In your case Position is string, so we need to convert select to string too so it matches the model:

ng-options="(tasks.indexOf(i)+1).toString() as tasks.indexOf(i)+1 for i in tasks"
            ^ model value                      ^ display

( tasks.indexOf(i)+1+'' would work too)

angular
  .module('Test', [])
  .controller('TestCtrl', function($scope) {
    $scope.tasks = [{
          Titel: "Title1",
          Position: "9"
      },{
          Titel: "Title2",
          Position: "1"
      },{
          Titel: "Title3",
          Position: "3"
      },{
          Titel: "Title4",
          Position: "2"
      }];
  });

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="Test" ng-controller="TestCtrl">
  <table cellpadding="0" cellspacing="0" border="0">
      <tr>
          <td class="ms-authoringcontrols"><b>Title</b></td>
          <td class="ms-authoringcontrols"><b>Position</b></td>
      </tr>

      <tr ng-repeat="t in tasks">
          <td>
              <a href="TODO">{{t.Titel}}</a>
          </td>
          <td>
              <select ng-model="t.Position" ng-options="(tasks.indexOf(i)+1).toString() as tasks.indexOf(i)+1 for i in tasks"></select>
          </td>
      </tr>
  </table>
  <pre>{{tasks|json}}</pre>
</div>

(If you run the snippet you will notice the first  is not
  selected, that's because [1,2,3,4] doesn't contain 9.)


问:
Bash output using awk or sed possibly
I have a file that looks like the below.

INPUT FILE SAMPLE

```<code>$ more showportlist
1/1
1/2
1/3
1/4
2/1
2/2
2/4
3/1
3/2
3/3
3/4
4/1
4/2
4/3
</code>```

And I have the script below

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

cat ports.csv | awk -F: '{print $1}' | sort -u > showportlist
#echo "$var2" > BNGIP
echo "proc_sendcommands()" > showportlist2
echo "{" >> showportlist2
echo 'rt_host=$1' >> showportlist2
echo 'rt_username=$USERNAME' >> showportlist2
echo 'rt_password=$PASSWORD' >> showportlist2
cat showportlist | while read LINE; do
    echo "rt_command_$((i++))='show circuit $LINE summary | grep bound'" >> showportlist2
done
</code>```

The script outputs a file that looks like this

```<code>proc_sendcommands()
{
    rt_host=$1
    rt_username=$USERNAME
    rt_password=$PASSWORD
    rt_command_0='show circuit 1/1 summary | grep bound'
    rt_command_1='show circuit 1/2 summary | grep bound'
    rt_command_2='show circuit 1/3 summary | grep bound'
    rt_command_3='show circuit 1/4 summary | grep bound'
    rt_command_4='show circuit 2/1 summary | grep bound'
    rt_command_5='show circuit 2/2 summary | grep bound'
    rt_command_6='show circuit 2/4 summary | grep bound'
    rt_command_7='show circuit 3/1 summary | grep bound'
    rt_command_8='show circuit 3/2 summary | grep bound'
    rt_command_9='show circuit 3/3 summary | grep bound'
    rt_command_10='show circuit 3/4 summary | grep bound'
    rt_command_11='show circuit 4/1 summary | grep bound'
    rt_command_12='show circuit 4/2 summary | grep bound'
    rt_command_13='show circuit 4/3 summary | grep bound'
    rt_command_14='show circuit 4/4 summary | grep bound'
    rt_command_15='show circuit 5/1 summary | grep bound'
    rt_command_16='show circuit 5/2 summary | grep bound'
    rt_command_17='show circuit 5/3 summary | grep bound'
    rt_command_18='show circuit 5/4 summary | grep bound'
    rt_command_19='show circuit 6/1 summary | grep bound'
    rt_command_20='show circuit 6/2 summary | grep bound'
    rt_command_21='show circuit 6/3 summary | grep bound'
    rt_command_22='show circuit 6/4 summary | grep bound'
    rt_command_23='show circuit 9/1 summary | grep bound'
    rt_command_24='show circuit 9/2 summary | grep bound'
</code>```

But I also need it to output the below I am just not sure how to get there.

(sleep 1; echo $rt_username; sleep 1; echo $rt_password; sleep 1;echo $rt_command_0;sleep 1;echo $rt_command_1;sle

ep 10;echo $rt_command_2;sleep 1;echo $rt_command_3;sleep 1; echo $rt_command_4;sleep 1; echo $rt_command_5;sleep

10; echo $rt_command_6;sleep 1; echo $rt_command_7;sleep 1;echo $rt_command_8;sleep 1;echo $rt_command_9;sleep

5;echo $rt_command_10;sleep 1;echo $rt_command_11;sleep 1;echo $rt_command_12;sleep 1;echo $rt_command_13;sleep 1;

echo $rt_command_14;sleep 1;echo $rt_command_15;sleep 1;echo $rt_command_16;sleep 1; echo $rt_command_17;sleep 1; echo $rt_command_18;sleep 1; echo $rt_command_19;sleep 1; echo $rt_command_20;sleep 1; echo $rt_command_21;sleep 1; echo $rt_command_22;sleep 1; echo $rt_command_23;sleep 1; echo $rt_command_24;sleep 1; echo "exit" ) | ssh $rt_host

答:
The answer to the question is quite trivial:

```<code>typeset -j i
echo -n '(sleep 1; echo $rt_username; sleep 1; echo $rt_password; sleep 1;'
j=0
while [ $j -lt $i ] ; do
    j=j+1
    echo -n "$rt_command_$j;sleep1;"
done
echo 'echo "exit" ) | ssh $rt_host'
</code>```

but this is almost certainly not what you want to do.

If it is possible, you should set-up public/private key authentication for ssh with your $rt_host which will remove the requirement to login every time.

If setting up key-authentication is absolutely impossible, you will need to fall-back to expect.  As an example:

```<code>spawn ssh -l username target_host
expect "ord\\: "
send "secret_password\r"
set handle [ open file_with_commands r ]
while { ! [eof $handle] } {
    gets $handle buf
    expect "\\$"
    send "$buf\r"
}
send "exit\r"
</code>```

Title: Bash output using awk or sed possibly

Body:
I have a file that looks like the below.

INPUT FILE SAMPLE

$ more showportlist
1/1
1/2
1/3
1/4
2/1
2/2
2/4
3/1
3/2
3/3
3/4
4/1
4/2
4/3

And I have the script below

#!/bin/bash

cat ports.csv | awk -F: '{print $1}' | sort -u > showportlist
#echo "$var2" > BNGIP
echo "proc_sendcommands()" > showportlist2
echo "{" >> showportlist2
echo 'rt_host=$1' >> showportlist2
echo 'rt_username=$USERNAME' >> showportlist2
echo 'rt_password=$PASSWORD' >> showportlist2
cat showportlist | while read LINE; do
    echo "rt_command_$((i++))='show circuit $LINE summary | grep bound'" >> showportlist2
done

The script outputs a file that looks like this

proc_sendcommands()
{
    rt_host=$1
    rt_username=$USERNAME
    rt_password=$PASSWORD
    rt_command_0='show circuit 1/1 summary | grep bound'
    rt_command_1='show circuit 1/2 summary | grep bound'
    rt_command_2='show circuit 1/3 summary | grep bound'
    rt_command_3='show circuit 1/4 summary | grep bound'
    rt_command_4='show circuit 2/1 summary | grep bound'
    rt_command_5='show circuit 2/2 summary | grep bound'
    rt_command_6='show circuit 2/4 summary | grep bound'
    rt_command_7='show circuit 3/1 summary | grep bound'
    rt_command_8='show circuit 3/2 summary | grep bound'
    rt_command_9='show circuit 3/3 summary | grep bound'
    rt_command_10='show circuit 3/4 summary | grep bound'
    rt_command_11='show circuit 4/1 summary | grep bound'
    rt_command_12='show circuit 4/2 summary | grep bound'
    rt_command_13='show circuit 4/3 summary | grep bound'
    rt_command_14='show circuit 4/4 summary | grep bound'
    rt_command_15='show circuit 5/1 summary | grep bound'
    rt_command_16='show circuit 5/2 summary | grep bound'
    rt_command_17='show circuit 5/3 summary | grep bound'
    rt_command_18='show circuit 5/4 summary | grep bound'
    rt_command_19='show circuit 6/1 summary | grep bound'
    rt_command_20='show circuit 6/2 summary | grep bound'
    rt_command_21='show circuit 6/3 summary | grep bound'
    rt_command_22='show circuit 6/4 summary | grep bound'
    rt_command_23='show circuit 9/1 summary | grep bound'
    rt_command_24='show circuit 9/2 summary | grep bound'

But I also need it to output the below I am just not sure how to get there.

(sleep 1; echo $rt_username; sleep 1; echo $rt_password; sleep 1;echo $rt_command_0;sleep 1;echo $rt_command_1;sle

ep 10;echo $rt_command_2;sleep 1;echo $rt_command_3;sleep 1; echo $rt_command_4;sleep 1; echo $rt_command_5;sleep

10; echo $rt_command_6;sleep 1; echo $rt_command_7;sleep 1;echo $rt_command_8;sleep 1;echo $rt_command_9;sleep

5;echo $rt_command_10;sleep 1;echo $rt_command_11;sleep 1;echo $rt_command_12;sleep 1;echo $rt_command_13;sleep 1;

echo $rt_command_14;sleep 1;echo $rt_command_15;sleep 1;echo $rt_command_16;sleep 1; echo $rt_command_17;sleep 1; echo $rt_command_18;sleep 1; echo $rt_command_19;sleep 1; echo $rt_command_20;sleep 1; echo $rt_command_21;sleep 1; echo $rt_command_22;sleep 1; echo $rt_command_23;sleep 1; echo $rt_command_24;sleep 1; echo "exit" ) | ssh $rt_host

Body:
The answer to the question is quite trivial:

typeset -j i
echo -n '(sleep 1; echo $rt_username; sleep 1; echo $rt_password; sleep 1;'
j=0
while [ $j -lt $i ] ; do
    j=j+1
    echo -n "$rt_command_$j;sleep1;"
done
echo 'echo "exit" ) | ssh $rt_host'

but this is almost certainly not what you want to do.

If it is possible, you should set-up public/private key authentication for ssh with your $rt_host which will remove the requirement to login every time.

If setting up key-authentication is absolutely impossible, you will need to fall-back to expect.  As an example:

spawn ssh -l username target_host
expect "ord\\: "
send "secret_password\r"
set handle [ open file_with_commands r ]
while { ! [eof $handle] } {
    gets $handle buf
    expect "\\$"
    send "$buf\r"
}
send "exit\r"


问:
Git: "Not currently on any branch." Is there an easy way to get back on a branch, while keeping the changes?
So I've done some work in the repository and when I'm about to commit I realize that I'm not currently on any branch.

This happens a lot when working with submodules and I am able to solve it, but the process is tedious and I've been thinking that there must be an easier way to do this.

Is there an easy way to get back on a branch, while keeping the changes?

答:
If you have not committed:

```<code>git stash
git checkout some-branch
git stash pop
</code>```

If you have committed and have not changed anything since:

```<code>git log --oneline -n1 # this will give you the SHA
git checkout some-branch
git merge ${commit-sha}
</code>```

If you have committed and then done extra work:

```<code>git stash
git log --oneline -n1 # this will give you the SHA
git checkout some-branch
git merge ${commit-sha}
git stash pop
</code>```

Body:
If you have not committed:

git stash
git checkout some-branch
git stash pop

If you have committed and have not changed anything since:

git log --oneline -n1 # this will give you the SHA
git checkout some-branch
git merge ${commit-sha}

If you have committed and then done extra work:

git stash
git log --oneline -n1 # this will give you the SHA
git checkout some-branch
git merge ${commit-sha}
git stash pop


问:
Split String if length is more than a value
I have a label that contains comments and I am using iTextsharp to insert those lines into a pdf now the point where comments come in here is the box for comments int he pdf:

This is the PDF comment box

I will use this code to put in a line:

```<code>     string comment = lblComment.text;
// lets say the lblComment.text = "This is a Document where User Added new Address"
         cb.BeginText();
            cb.SetColorFill(BaseColor.DARK_GRAY);
            cb.SetFontAndSize(bf, 11);
            cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, Comment, 215, 96, 0); // Insert the Cooments
            cb.EndText();
</code>```

Now the problem is Comment can be long and I want some way of doing this so if the Line for the Comment is more than these many charechters insert next line and take half of the comment strign to the next line. I tried looking at splitting string on google all i could find:

```<code>    string data = "THExxQUICKxxBROWNxxFOX";

return data.Split(new string[] { "xx" }, StringSplitOptions.None);
</code>```

This is where the string has xx you split it but didnt work.

答:
I'll try to answer this part: "... if the Line for the Comment is more than these many characters insert next line and take half of the comment string to the next line."

```<code>public string Summarize(string input, int length)
{
    if (input.Length <= length) return input;
    string result = input.Substring(0, length) + System.Environment.NewLine + input.Substring(length, length/2);
    //You may want to add more logic like spliting the string at the previous whitespace
    return result;
}
</code>```

edit- There are more efficient ways of performing this task, such as using a
StringBuilder, but I am going for readability here.

Body:
I have a label that contains comments and I am using iTextsharp to insert those lines into a pdf now the point where comments come in here is the box for comments int he pdf:

This is the PDF comment box

I will use this code to put in a line:

     string comment = lblComment.text;
// lets say the lblComment.text = "This is a Document where User Added new Address"
         cb.BeginText();
            cb.SetColorFill(BaseColor.DARK_GRAY);
            cb.SetFontAndSize(bf, 11);
            cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, Comment, 215, 96, 0); // Insert the Cooments
            cb.EndText();

Now the problem is Comment can be long and I want some way of doing this so if the Line for the Comment is more than these many charechters insert next line and take half of the comment strign to the next line. I tried looking at splitting string on google all i could find:

    string data = "THExxQUICKxxBROWNxxFOX";

return data.Split(new string[] { "xx" }, StringSplitOptions.None);

This is where the string has xx you split it but didnt work.

Body:
I'll try to answer this part: "... if the Line for the Comment is more than these many characters insert next line and take half of the comment string to the next line."

public string Summarize(string input, int length)
{
    if (input.Length <= length) return input;
    string result = input.Substring(0, length) + System.Environment.NewLine + input.Substring(length, length/2);
    //You may want to add more logic like spliting the string at the previous whitespace
    return result;
}

edit- There are more efficient ways of performing this task, such as using a
StringBuilder, but I am going for readability here.


问:
Dynamically Filter an Array of Objects in Vue.js
I have a Vue.js app. In this app, I'm trying to dynamically apply filter value to an Array of objects. Each object in the Array has fields. I'm trying to filter these objects by field values. Each field can be filtered by multiple values.

At this time, I have been unsuccessful in figuring out how to do this filtering. I've tried using JavaScript's baked-in filter function. However, that always returned an empty result set for me. I've put together this Fiddle, which includes this code:

```<code>new Vue({
  el: '#app',
  data: {
    currentFilterProperty: '',
    currentFilterValue: '',

    cols: [
      { title: 'Name', prop:'name' },
      { title: 'Age', prop:'age' },
      { title: 'Birthday', prop:'birthday' },
    ],

    dataFilters: [],
    data: [
      { name:'Patricia Miller', age:69, birthday:'04-15-1948' },
      { name:'Bill Baggett', age:62, birthday:'05-07-1955' },
      { name:'Maxine Thies', age:21, birthday:'11-28-1995' },
      { name:'Alison Battle', age:65, birthday:'08-07-1952' },
      { name:'Dick Triplett', age:25, birthday:'08-27-1982' }
    ]
  },

  methods: {
    addFilter: function() {
      var f = this.dataFilters[this.currentFilterProperty];
      if (!f) {
        this.dataFilters = {};
        this.dataFilters[this.currentFilterProperty] = [ this.currentFilterValue ];
      } else {
        this.dataFilters[this.currentFilterProperty].push(this.currentFilterValue);
      }

      // How to apply filter?
    }
  }
})
</code>```

I'm not sure how to apply the filters to the data object.

答:
Complete solution. Best test: add filter Age 62, then Birthday 04-15-1948, then 'tri' in Name Patricia.

new Vue({
  el: '#app',
  data: {
    filteredProperty: 'name',
    query: '',
    activeFilters: [],
    data: [
      {name: 'Patricia Miller', age: 62, birthday: '04-15-1948'},
      {name: 'Bill Baggett', age:62, birthday: '04-15-1948' },
      {name:'Maxine Thies', age:62, birthday:'11-28-1948'},
      {name:'Alison Battle', age:65, birthday:'08-07-1952'},
      {name:'Dick Triplett', age:25, birthday:'08-27-1982'}
    ]
  },
  computed: {
    filtered () {
      var filtered = this.data
      this.activeFilters.forEach(filter => {
        filtered = filtered.filter(record => {
          return filter.name === 'name'
            ? new RegExp(filter.value, 'i').test(record[filter.name])
            : record[filter.name] == filter.value
        })
      })
      return filtered
    }
  },
  methods: {
    addFilter () {
      this.activeFilters.push({
        name: this.filteredProperty,
        value: this.query
      })
      this.query = ''
    },
    removeFilter (idx) {
      this.activeFilters.splice(idx, 1)
    }
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="app">
  <div>
    <select v-model="filteredProperty">
      <option value="name">Name</option>
      <option value="age">Age</option>
      <option value="birthday">Birthdate</option>
    </select>
    <input placeholder="filter value" v-model="query">
    <button @click="addFilter">add filter</button>
  </div>
  <hr>
  <table v-if="activeFilters.length">
    <tr style="width: 100px">
      <th colspan="3">Filters in use:</th>
    </tr>
    <tr v-for="(filter, index) in activeFilters" :key="index">
      <td>{{ _.capitalize(filter.name) }}:</td>
      <td>{{ filter.value }}</td>
      <td style="padding-left: 10px;">

          remove

      </td>
    </tr>
  </table>
  <hr v-if="activeFilters.length">
  <table>
    <tbody>
      <tr v-for="(record, index) in filtered" :key="index">
        <td style="padding-right:18px;">{{ record.name }}</td>
        <td style="padding-right:18px;">{{ record.age }}</td>
        <td>{{ record.birthday }}</td>
      </tr>
    </tbody>
  </table>
</div>

<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/lodash"></script></code>```

Body:
I have a Vue.js app. In this app, I'm trying to dynamically apply filter value to an Array of objects. Each object in the Array has fields. I'm trying to filter these objects by field values. Each field can be filtered by multiple values.

At this time, I have been unsuccessful in figuring out how to do this filtering. I've tried using JavaScript's baked-in filter function. However, that always returned an empty result set for me. I've put together this Fiddle, which includes this code:

new Vue({
  el: '#app',
  data: {
    currentFilterProperty: '',
    currentFilterValue: '',

    cols: [
      { title: 'Name', prop:'name' },
      { title: 'Age', prop:'age' },
      { title: 'Birthday', prop:'birthday' },
    ],

    dataFilters: [],
    data: [
      { name:'Patricia Miller', age:69, birthday:'04-15-1948' },
      { name:'Bill Baggett', age:62, birthday:'05-07-1955' },
      { name:'Maxine Thies', age:21, birthday:'11-28-1995' },
      { name:'Alison Battle', age:65, birthday:'08-07-1952' },
      { name:'Dick Triplett', age:25, birthday:'08-27-1982' }
    ]
  },

  methods: {
    addFilter: function() {
      var f = this.dataFilters[this.currentFilterProperty];
      if (!f) {
        this.dataFilters = {};
        this.dataFilters[this.currentFilterProperty] = [ this.currentFilterValue ];
      } else {
        this.dataFilters[this.currentFilterProperty].push(this.currentFilterValue);
      }

      // How to apply filter?
    }
  }
})

I'm not sure how to apply the filters to the data object.

Body:
Complete solution. Best test: add filter Age 62, then Birthday 04-15-1948, then 'tri' in Name Patricia.

new Vue({
  el: '#app',
  data: {
    filteredProperty: 'name',
    query: '',
    activeFilters: [],
    data: [
      {name: 'Patricia Miller', age: 62, birthday: '04-15-1948'},
      {name: 'Bill Baggett', age:62, birthday: '04-15-1948' },
      {name:'Maxine Thies', age:62, birthday:'11-28-1948'},
      {name:'Alison Battle', age:65, birthday:'08-07-1952'},
      {name:'Dick Triplett', age:25, birthday:'08-27-1982'}
    ]
  },
  computed: {
    filtered () {
      var filtered = this.data
      this.activeFilters.forEach(filter => {
        filtered = filtered.filter(record => {
          return filter.name === 'name'
            ? new RegExp(filter.value, 'i').test(record[filter.name])
            : record[filter.name] == filter.value
        })
      })
      return filtered
    }
  },
  methods: {
    addFilter () {
      this.activeFilters.push({
        name: this.filteredProperty,
        value: this.query
      })
      this.query = ''
    },
    removeFilter (idx) {
      this.activeFilters.splice(idx, 1)
    }
  }
})

<div id="app">
  <div>
    <select v-model="filteredProperty">
      <option value="name">Name</option>
      <option value="age">Age</option>
      <option value="birthday">Birthdate</option>
    </select>
    <input placeholder="filter value" v-model="query">
    <button @click="addFilter">add filter</button>
  </div>
  <hr>
  <table v-if="activeFilters.length">
    <tr style="width: 100px">
      <th colspan="3">Filters in use:</th>
    </tr>
    <tr v-for="(filter, index) in activeFilters" :key="index">
      <td>{{ _.capitalize(filter.name) }}:</td>
      <td>{{ filter.value }}</td>
      <td style="padding-left: 10px;">
        <a href="#" @click.prevented=removeFilter(index)>
          remove
        </a>
      </td>
    </tr>
  </table>
  <hr v-if="activeFilters.length">
  <table>
    <tbody>
      <tr v-for="(record, index) in filtered" :key="index">
        <td style="padding-right:18px;">{{ record.name }}</td>
        <td style="padding-right:18px;">{{ record.age }}</td>
        <td>{{ record.birthday }}</td>
      </tr>
    </tbody>
  </table>
</div>

<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/lodash"></script>


问:
What is the performace of PHPs strtotime()?
I am doing some large timestamp-list iterations: Putting them in tables with date-ranges, and grouping them by ranges.
In order to do that, I found strtotime() a very helpfull function, but I am worried about its performance.

For example, a function that loops over a list of weeks (say, week 49 to 05) and has to decide the beginning of the week and the timestamp at the end of that week. A usefull way to do that, would be:

```<code>foreach ($this->weeks($first, $amount) as $starts_at) {
  $ends_at = strtotime('+1 week', $starts_at);
  $groups[$week_key] = $this->slice($timestamps, $starts_at, $ends_at);
}

//$this->weeks returns a list of timestamps at which each week starts.
//$this->slice is a simple helper that returns only the timestamps within a range, from a list of timestamps.
</code>```

Instead of strtotime(), I could, potentially, find out the amount of seconds between begin and end of the week, 99% of the times that would be 24 * 60 * 60 * 7. But in these rare cases where there is a DST-switch, that 24 should either be 23 or 25. Code to sort that out, will probably be a lot slower then strtotime(), not?

I use the same patterns for ranges of years, months (months, being very inconsistent!), days and hours. Only with hours would I suspect simply adding 3600 to the timestamp is faster.

Any other gotcha's? Are there ways (that do not depend on PHP5.3!) that offer better routes for consistent, DST and leap-year safe dateranges?

答:
To respond to the question, finaly :

Based on many benchmarks like this one: https://en.code-bude.net/2013/12/19/benchmark-strtotime-vs-datetime-vs-gettimestamp-in-php/

We can see that strtotime() is more effective that we can think.
So yes, to convert a string to a timestamp, the strtotime function has pretty good performance.

Body:
I am doing some large timestamp-list iterations: Putting them in tables with date-ranges, and grouping them by ranges.
In order to do that, I found strtotime() a very helpfull function, but I am worried about its performance.

For example, a function that loops over a list of weeks (say, week 49 to 05) and has to decide the beginning of the week and the timestamp at the end of that week. A usefull way to do that, would be:

foreach ($this->weeks($first, $amount) as $starts_at) {
  $ends_at = strtotime('+1 week', $starts_at);
  $groups[$week_key] = $this->slice($timestamps, $starts_at, $ends_at);
}

//$this->weeks returns a list of timestamps at which each week starts.
//$this->slice is a simple helper that returns only the timestamps within a range, from a list of timestamps.

Instead of strtotime(), I could, potentially, find out the amount of seconds between begin and end of the week, 99% of the times that would be 24 * 60 * 60 * 7. But in these rare cases where there is a DST-switch, that 24 should either be 23 or 25. Code to sort that out, will probably be a lot slower then strtotime(), not?

I use the same patterns for ranges of years, months (months, being very inconsistent!), days and hours. Only with hours would I suspect simply adding 3600 to the timestamp is faster.

Any other gotcha's? Are there ways (that do not depend on PHP5.3!) that offer better routes for consistent, DST and leap-year safe dateranges?


问:
What is the most pythonic way to split a 3d array to 2d arrays with different second indexes?
I have a function foo that returns an array with the shape (1000, 3, 1000)
how can I split it to three arrays a(1000, 1000) and b(1000, 1000) and c(1000, 1000)
I'm looking for something like this:

```<code>a,b,c = foo()[:,*,:]
</code>```

that will result in a,b,c equal to:

```<code>res = foo()
a = res[:,0,:]
b = res[:,1,:]
c = res[:,2,:]
</code>```

答:
Similar to your previous question:

```<code>def foo():
    return np.ones((1000, 3, 1000))

a, b, c = [np.squeeze(arr) for arr in np.hsplit(foo(), foo().shape[1])]

for arr in [a, b, c]:
    print(arr.shape)
# (1000, 1000)
# (1000, 1000)
# (1000, 1000)
</code>```

Without np.squeeze you'll get shapes of (1000, 1, 1000).

Body:
I have a function foo that returns an array with the shape (1000, 3, 1000)
how can I split it to three arrays a(1000, 1000) and b(1000, 1000) and c(1000, 1000)
I'm looking for something like this:

a,b,c = foo()[:,*,:]

that will result in a,b,c equal to:

res = foo()
a = res[:,0,:]
b = res[:,1,:]
c = res[:,2,:]

Body:
Similar to your previous question:

def foo():
    return np.ones((1000, 3, 1000))

a, b, c = [np.squeeze(arr) for arr in np.hsplit(foo(), foo().shape[1])]

for arr in [a, b, c]:
    print(arr.shape)
# (1000, 1000)
# (1000, 1000)
# (1000, 1000)

Without np.squeeze you'll get shapes of (1000, 1, 1000).


问:
set default url param if not exist .net
I'm a bit stuck on how to solve this.

The edge case I'm testing for is if someone goes to the URL but removes the query params.

EXAMPLE

```<code>www.example.com
</code>```

I want to be able to check if there are no URL params given then set it to a default and redirect with the default URL params.

EXPECTED RESULT

```<code>www.example.com?year=2016
</code>```

This is my code I'm using or misusing. Some help would be very much appreciated.

```<code>Dim noURLParam As String = ""
If Not(Request.QueryString("Year") Is Nothing) Then
  If Request.QueryString("Year").ToString() <> "" Then
    noURLParam = Request.QueryString("Year").ToString()
  End If
End If
</code>```

答:
The way your code is currently structured you can simply do this

```<code>' Set a default
Dim noURLParam As String = "2017"
</code>```

And 2017 will be the default if no value is provided for year in the querystring.

Title: set default url param if not exist .net

Body:
I'm a bit stuck on how to solve this.

The edge case I'm testing for is if someone goes to the URL but removes the query params.

EXAMPLE

www.example.com

I want to be able to check if there are no URL params given then set it to a default and redirect with the default URL params.

EXPECTED RESULT

www.example.com?year=2016

This is my code I'm using or misusing. Some help would be very much appreciated.

Dim noURLParam As String = ""
If Not(Request.QueryString("Year") Is Nothing) Then
  If Request.QueryString("Year").ToString() <> "" Then
    noURLParam = Request.QueryString("Year").ToString()
  End If
End If

Body:
The way your code is currently structured you can simply do this

' Set a default
Dim noURLParam As String = "2017"

And 2017 will be the default if no value is provided for year in the querystring.


问:
How to Speed up Android Studio 3.0
I just want to ask "How can I speed up my Android Studio?". Though I do own:

```<code>Dell Inspiron 15R
12GB of RAM Core i7 (N5537),
</code>```

these specs may look cool but still I am unable to working on Android Studio in Peace. As my Android Studio takes a lot of time when I reboot my machine and start the Android studio, its indexing process is way too long, the gradle build process is also way too laggy!

Even whenever I try to run my app on any device say on Virtual Device or any other real device it takes a lot of time, to switch between .java to .xml files is also way too long! For the most of times the Android Studio also stuck and hangs on different events especially on Gradle Build or refreshing the project and indexing the project files!

答:
For the above issue, I have done some work around to speed up my Android Studio. In other words the results are just boosted my Android Studio!

Step 1 Increase Windows Virtual Memory

Goto Computer, Right Click and Choose Properties

Select Advanced System Settings

Select Performance Settings

Select the Advanced tab, and click the Change button on Virtual Memory Section

Uncheck the Automatically manage paging file size for all drives

Choose your desired drive to use as a Virtual Memory Part

Check the Custom Size Radio Box

Insert the Inital Size (MBs), this step is important! For me I have about 150GBs free in my C Drive so I set the initial size to 40GB!

Set the Maximum Size (MBs), I have set it to 50GB because have a lot of free space!

Click Set, then Ok

Step 2 Edit Custom VM Options in Android Studio

Start Android Studio

Click Help

Select Edit Custom VM Options

Click Yes to the Next dialog (If file didn't exists already it will prompt you to create one)

Add these Lines to that Opened File:

```<code> # custom Android Studio VM options, see http://tools.android.com/tech-docs/configuration
-Xms1024m
-Xmx4096m *****INCREASE THIS TO MAXIMUM OF YOUR RAM
-XX:MaxPermSize=1024m
-XX:ReservedCodeCacheSize=1024m
-XX:+UseCompressedOops
-XX:+HeapDumpOnOutOfMemoryError
-Dfile.encoding=UTF-8
</code>```

(You Should increase these values to the maximum of your machine resource, the above is for my own machine settings)

Step 3

Simply Invalidate Caches and Restart Your Android Studio

Don't forget to edit your startup programs and service, you have to disable all junk/useless or non important services at the startup and reboot! (This step is also very important)

Give your machine a Reboot

For me these all steps are a great workaround, so you should give them a try

Please Note that you should set all the said values according to your machine hardware and software resources

Thanks

Title: How to Speed up Android Studio 3.0

Body:
I just want to ask "How can I speed up my Android Studio?". Though I do own:

Dell Inspiron 15R
12GB of RAM Core i7 (N5537),

these specs may look cool but still I am unable to working on Android Studio in Peace. As my Android Studio takes a lot of time when I reboot my machine and start the Android studio, its indexing process is way too long, the gradle build process is also way too laggy!

Even whenever I try to run my app on any device say on Virtual Device or any other real device it takes a lot of time, to switch between .java to .xml files is also way too long! For the most of times the Android Studio also stuck and hangs on different events especially on Gradle Build or refreshing the project and indexing the project files!

Body:
For the above issue, I have done some work around to speed up my Android Studio. In other words the results are just boosted my Android Studio!

Step 1 Increase Windows Virtual Memory

Goto Computer, Right Click and Choose Properties

Select Advanced System Settings

Select Performance Settings

Select the Advanced tab, and click the Change button on Virtual Memory Section

Uncheck the Automatically manage paging file size for all drives

Choose your desired drive to use as a Virtual Memory Part

Check the Custom Size Radio Box

Insert the Inital Size (MBs), this step is important! For me I have about 150GBs free in my C Drive so I set the initial size to 40GB!

Set the Maximum Size (MBs), I have set it to 50GB because have a lot of free space!

Click Set, then Ok

Step 2 Edit Custom VM Options in Android Studio

Start Android Studio

Click Help

Select Edit Custom VM Options

Click Yes to the Next dialog (If file didn't exists already it will prompt you to create one)

Add these Lines to that Opened File:

 # custom Android Studio VM options, see http://tools.android.com/tech-docs/configuration
-Xms1024m
-Xmx4096m *****INCREASE THIS TO MAXIMUM OF YOUR RAM
-XX:MaxPermSize=1024m
-XX:ReservedCodeCacheSize=1024m
-XX:+UseCompressedOops
-XX:+HeapDumpOnOutOfMemoryError
-Dfile.encoding=UTF-8

(You Should increase these values to the maximum of your machine resource, the above is for my own machine settings)

Step 3

Simply Invalidate Caches and Restart Your Android Studio

Don't forget to edit your startup programs and service, you have to disable all junk/useless or non important services at the startup and reboot! (This step is also very important)

Give your machine a Reboot

For me these all steps are a great workaround, so you should give them a try

Please Note that you should set all the said values according to your machine hardware and software resources

Thanks


问:
Word - Conditional Text
I'm having to convert some documents which had been built in OpenOffice over to word, and one thing which seems overly complicated in Word is conditional text.  OO had some features which made this a breeze, but I'm thinking I'm missing something in Word.

For more simple pieces of text I've used the {IF {DOCVARIABLE xxxx} = ...} method which seems to work well with single lines of text.

For longer blocks of text I've tried using a similar method but inserting an Autotext block.  This works well if the content is static, but if the content I'm inserting needs to be edited, updating the document ends up replacing any changes with the Autotext block.  So this method won't work for parts of my document.

Most of the search results I'm seeing use some variation of the two methods above.  Is there something else I can use which allows blocks of text, possibly including tables, to be conditionally inserted or hidden and also editable?

Macros are okay since this is how I'm setting various DOCVARIABLE parameters in the document.

I'm using Word 2016 on Windows 7.

答:
After doing more experimenting, it looks like I can use bookmarks to do what I need.
I can select the block of text I want to conditionally show/hide, then create a bookmark for the selection.
Then in my macro I can hide the section when necessary with:

```<code>ActiveDocument.Bookmarks("MyBookmarkName").Range.Font.Hidden = True
</code>```

or show it again using False instead of True.  This seems to hide tables and other things within that block of text.  I'd love it if the Word developers would add some of the features for this type of thing which are in OpenOffice.

Title: Word - Conditional Text

Body:
After doing more experimenting, it looks like I can use bookmarks to do what I need.
I can select the block of text I want to conditionally show/hide, then create a bookmark for the selection.
Then in my macro I can hide the section when necessary with:

ActiveDocument.Bookmarks("MyBookmarkName").Range.Font.Hidden = True

or show it again using False instead of True.  This seems to hide tables and other things within that block of text.  I'd love it if the Word developers would add some of the features for this type of thing which are in OpenOffice.


问:
Access command line arguments in C++
Is it possible to get the command line arguments without receiving them via int main(int, char**)? I don't want to pass the arguments to multiple methods, so a global function would be perfect. Also, I do not want to store the arguments by myself via global variables. I'm running Windows and Linux.

edit:
Example:

```<code>int main()
{
   int argc = GetArgumentCount();
   char ** argv = GetArguments();
   return 0;
}
</code>```

edit:
It's possible to use LPTSTR WINAPI GetCommandLine(void); in win32.

https://msdn.microsoft.com/en-us/library/ms683156(v=vs.85).aspx

I'm looking for equivalent functions in Linux.

答:
If you really think that is a good idea, you can easily make cor command line arguments global:</p>

```<code>int argc_ = 0;
char** argv_ = NULL;

int main(int argc, char* argv[]) {
    argc_ = argc;
    argv_ = argv;

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

Title: Access command line arguments in C++

Body:
Is it possible to get the command line arguments without receiving them via int main(int, char**)? I don't want to pass the arguments to multiple methods, so a global function would be perfect. Also, I do not want to store the arguments by myself via global variables. I'm running Windows and Linux.

edit:
Example:

int main()
{
   int argc = GetArgumentCount();
   char ** argv = GetArguments();
   return 0;
}

edit:
It's possible to use LPTSTR WINAPI GetCommandLine(void); in win32.

https://msdn.microsoft.com/en-us/library/ms683156(v=vs.85).aspx

I'm looking for equivalent functions in Linux.

Body:
If you really think that is a good idea, you can easily make cor command line arguments global:

int argc_ = 0;
char** argv_ = NULL;

int main(int argc, char* argv[]) {
    argc_ = argc;
    argv_ = argv;

    // ...
}


答:
Something like:

```<code>before_save :parse_country_code

def parse_country_code
  if born_changed?
    self.state = ...
    self.country = ...
  end
  true # avoid cancelling the callback chain
end
</code>```

You may also find ActiveRecord::Aggregations::ClassMethods useful. With that you could consolidate your parsing and other logic to another class.

Title: Adding hook to model creation in rails

Body:
I have a model class Person, and I create instances of them using:

person = Person.create!

Now I want to say that this person was born in California, USA, but in this peculiar way:

person = Person.create!({:name => "Matt", :born => "USCA"})

This means there are two characters to identify the country and another two characters to identify the state.
But I don't want to store the string in the database, I want to store in a structured way, like:

| Name | Country | State      |

| Matt | USA     | California |

Where can I parse the string to assign the country and state based on it? Which method in the model?

Thanks in advance

Body:
Something like:

before_save :parse_country_code

def parse_country_code
  if born_changed?
    self.state = ...
    self.country = ...
  end
  true # avoid cancelling the callback chain
end

You may also find ActiveRecord::Aggregations::ClassMethods useful. With that you could consolidate your parsing and other logic to another class.


问:
Defining fields in Laravel 5.5 Migrations with Postgres
Working with Laravel 5.5 Migrations with Postgres :

1) Defining field as :

```<code>$table->enum('is_applied', ['Y', 'N']) ->comment('Y => is_applied, N=> Is not applied');
</code>```

I see in generated table next:

```<code>is_applied varchar(255) NOT NULL,
    CONSTRAINT cs_tmp_csvps_is_applied_check CHECK (((is_applied)::text = ANY ((ARRAY['Y'::character varying, 'N'::character varying])::text[]))),
</code>```

actually I would like to get sql I used in Postgres with type:

```<code>CREATE TYPE type_cms_item_content_type AS ENUM (
    'P',
    'M',
    'H'
);

    content_type type_cms_item_content_type NOT NULL DEFAULT 'P'::type_cms_item_content_type,
</code>```

Is it possible?

2) Defining field as :

```<code>$table->timestamps();
</code>```

I have 2 fields created created_at and  updated_at .
As I need to create only created_at I could write :

```<code>$table->dateTime('created_at');
</code>```

But is there is a way to set default time on server, like :

```<code>created_at timestamp NOT NULL DEFAULT now(),
</code>```

?

Thanks!

答:
You can do:

```<code>$table->timestamp('created_at')->useCurrent();
</code>```

for the timestamps issue. If you really want exact sql changes you can always do a raw sql statement in a migration:

```<code>Schema::table('content_type', function(Blueprint $table){
    $sql = 'CREATE TYPE type_cms_item_content_type AS ENUM (
    `P`,
    `M`,
    `H`
);

    content_type type_cms_item_content_type NOT NULL DEFAULT `P`::type_cms_item_content_type';
    DB::connection()->getPdo()->exec($sql);
});
</code>```

Body:
Working with Laravel 5.5 Migrations with Postgres :

1) Defining field as :

$table->enum('is_applied', ['Y', 'N']) ->comment('Y => is_applied, N=> Is not applied');

I see in generated table next:

is_applied varchar(255) NOT NULL,
    CONSTRAINT cs_tmp_csvps_is_applied_check CHECK (((is_applied)::text = ANY ((ARRAY['Y'::character varying, 'N'::character varying])::text[]))),

actually I would like to get sql I used in Postgres with type:

CREATE TYPE type_cms_item_content_type AS ENUM (
    'P',
    'M',
    'H'
);

    content_type type_cms_item_content_type NOT NULL DEFAULT 'P'::type_cms_item_content_type,

Is it possible?

2) Defining field as :

$table->timestamps();

I have 2 fields created created_at and  updated_at .
As I need to create only created_at I could write :

$table->dateTime('created_at');

But is there is a way to set default time on server, like :

created_at timestamp NOT NULL DEFAULT now(),

?

Thanks!

Body:
You can do:

$table->timestamp('created_at')->useCurrent();

for the timestamps issue. If you really want exact sql changes you can always do a raw sql statement in a migration:

Schema::table('content_type', function(Blueprint $table){
    $sql = 'CREATE TYPE type_cms_item_content_type AS ENUM (
    `P`,
    `M`,
    `H`
);

    content_type type_cms_item_content_type NOT NULL DEFAULT `P`::type_cms_item_content_type';
    DB::connection()->getPdo()->exec($sql);
});


问:
Stop Thread Runnable impossible
I have this thread:

```<code>myThread = new Thread(new Runnable() {
                    public void run() {

                        ServerSocket ss = null;

                        while (!end) {

                            final String incomingMsg;
                            try {
                                ss = new ServerSocket(2201);
                                ss.setSoTimeout(15000);
.. some code ...
    }
                });
                myThread.start();
</code>```

Now i need to stop this with button but nothing work, and i have tried with some code like:

```<code>Handler handler= new Handler();
handler.removeCallbacks(myThread);
myThread.interrupt();
</code>```

But Thread not stopping =(

答: You can use .stop(), but it is very bad practice and it can cause you some troubles. Try to add some boolean inside your .run() (like Wizard said)</p>

Title: Stop Thread Runnable impossible

Body:
I have this thread:

myThread = new Thread(new Runnable() {
                    public void run() {

                        ServerSocket ss = null;

                        while (!end) {

                            final String incomingMsg;
                            try {
                                ss = new ServerSocket(2201);
                                ss.setSoTimeout(15000);
.. some code ...
    }
                });
                myThread.start();

Now i need to stop this with button but nothing work, and i have tried with some code like:

Handler handler= new Handler();
handler.removeCallbacks(myThread);
myThread.interrupt();

But Thread not stopping =(


问:
mule/java - reading a property file which is inside of jar dependency from java class
Here my requirement is, I have created one mule application which has java class. Some of the values which I don't want to keep it as a hard-coded so I am trying to externalize it. I kept this values in mule-app.properties file and used FileInputStream as below.

```<code>String propFileName = "src/main/app/mule-app.properties"
Properties property = new Properties();
property.load(new FileInputStream(propFileName));
</code>```

But this code needs to be deployed on CloudHub; there its failing saying that file not found. I Tried with give path of the file name as

```<code>String propFileName = "target/classes/mule-app.properties"
</code>```

for both the cases its running fine locally but gives same results on CloudHub as "File Not Found".

What could be the solution?

Another thing is I have a common code in which we are keeping all the properties related to different environment. Packaging of this common code is in the form of jar. So, can I keep properties which I am using in above code and read it from jar itself.

If Yes, then How?

答:
Use the below sample code it should work. </p>

```<code>FileInputStream fi = new FileInputStream(System.getProperty("C:\Users\userName\
      AnypointStudio\workspace\test\src\main\resources\my-app1.propertie");

Properties prop = new Properties();
prop.load(fi)
</code>```

Body:
Here my requirement is, I have created one mule application which has java class. Some of the values which I don't want to keep it as a hard-coded so I am trying to externalize it. I kept this values in mule-app.properties file and used FileInputStream as below.

String propFileName = "src/main/app/mule-app.properties"
Properties property = new Properties();
property.load(new FileInputStream(propFileName));

But this code needs to be deployed on CloudHub; there its failing saying that file not found. I Tried with give path of the file name as

String propFileName = "target/classes/mule-app.properties"

for both the cases its running fine locally but gives same results on CloudHub as "File Not Found".

What could be the solution?

Another thing is I have a common code in which we are keeping all the properties related to different environment. Packaging of this common code is in the form of jar. So, can I keep properties which I am using in above code and read it from jar itself.

If Yes, then How?

Body:
Use the below sample code it should work.

FileInputStream fi = new FileInputStream(System.getProperty("C:\Users\userName\
      AnypointStudio\workspace\test\src\main\resources\my-app1.propertie");

Properties prop = new Properties();
prop.load(fi)


问:
SQL : Multiple left joins with similar tables
I have the following tables:

```<code>TABLE A
id
info

TABLE B
f_id
question
choices

TABLE C
f_id
question
lines
</code>```

The id from the Table A always match a f_id from either Table B or C, but never both. I want to join Table B and Table C on table A only when it matches so I would get a table with the following columns :

```<code>id |   info   |   question   | choices | lines
</code>```

where all rows are filled in the question column, some are NULL in the column choices and some are NULL in the column lines.

What I tried is to do two consecutive left joins, but the second one overrides the first so all the rows that doesn't match in Table C (second left join) get a NULL value in the question column.

Is there a way to do a query that will not override previously joined data with NULL values? I'm working with Laravel Eloquent, so any of raw SQL or Eloquent Query would help me.

答:
UNION B and C and then INNER JOIN A to those results.

```<code>SELECT s1.f_id, s1.question, s1.choices, s1.lines
FROM
(
  SELECT f_id, question, choices, lines = null
  FROM B
  UNION
  SELECT f_id, question, choices = null, lines
  FROM C
) s1
INNER JOIN A ON s1.f_id = A.id
</code>```

Body:
I have the following tables:

TABLE A
id
info

TABLE B
f_id
question
choices

TABLE C
f_id
question
lines

The id from the Table A always match a f_id from either Table B or C, but never both. I want to join Table B and Table C on table A only when it matches so I would get a table with the following columns :

id |   info   |   question   | choices | lines

where all rows are filled in the question column, some are NULL in the column choices and some are NULL in the column lines.

What I tried is to do two consecutive left joins, but the second one overrides the first so all the rows that doesn't match in Table C (second left join) get a NULL value in the question column.

Is there a way to do a query that will not override previously joined data with NULL values? I'm working with Laravel Eloquent, so any of raw SQL or Eloquent Query would help me.

Body:
UNION B and C and then INNER JOIN A to those results.

SELECT s1.f_id, s1.question, s1.choices, s1.lines
FROM
(
  SELECT f_id, question, choices, lines = null
  FROM B
  UNION
  SELECT f_id, question, choices = null, lines
  FROM C
) s1
INNER JOIN A ON s1.f_id = A.id


问:
How to provider user with autocomplete suggestions for given boost::spirit grammar?
I am using Boost::Spirit to build simple "data-filter" language in my C++ GUI application for non-technical users. Language is very similiar to plain English and parse-able into AST. I am requested to make the process as user-friendly as possible, so I wish to provide CLang-like error messages ("Unrecognized 'tokken', did you meant 'token'?") and autocompletion.

The question in place is how to use Boost::Spirit grammar to generate possible token list for both goals (I will use simple string distance algorithm to satisfy first requirement)?

My ideas so far:

Add position and length in source stream to token definition obtained from parser.

Add special invalid token to grammar, which will match anything... well... not valid :-)

If user presses ctrl + space, build AST (with invalid token the tree will be always buildable), then look for token inside current cursor position

Use simple matcher on all possible tokens (I have token list after all) and prepare a list of suggestions

The problem with this solution is the suggestion will also suggest tokens that are invalid for given place. And if I add (and I will) definable identifiers, I have much bigger problem in hand...

One more constraint: I want to have grammar for this language defined in only one place; If the grammar changes, I want to autocompleter be aware of this changes after recompilation

答:
Spirit doesn't have that feature. You could generate it yourself but it would be considerable effort to do it generically (if not straight up impossible, due  NP-completeness). Perhaps just detect parse error (on_error) and have a limited number of stock "options" - the 80% rule should go a long way.

Also, I think the "sketch" with parsing 'invalid placeholder tokens'  will not work because you'll have to build in assumptions about the type of the placeholder token and it may therefore not result in a valid expression.

I sense that you treat expression parsing as little more than tokenizing -
 which isn't accurate in most cases.


问:
SLIME on Emacs with paredit in repl - how to prevent execution of incomplete but balanced expressions?
I use paredit on emacs with SLIME's repl. This means that at any point during my typing on the repl, my s-expressions are balanced.

However, they may not be complete, and I might want to continue typing inside them in another line, as follows:

```<code>CL-USER> (defun print-hello ()
            )
</code>```

When I start a new line by pressing the enter key, however, the SLIME repl executes my incomplete expression. I want it to wait for me to complete the expression, as follows:

```<code>CL-USER> (defun print-hello ()
            (format t "Hello, world"))
</code>```

How do I make this happen please?

答:
Related to your question, lispy provides integration with SLIME.

I typically never type anything into the REPL buffer. Instead, I edit all code in place in the source file, and use e to eval the current sexp.

lispy is also a super-set of paredit, if compatibility is your concern.

Body:
I use paredit on emacs with SLIME's repl. This means that at any point during my typing on the repl, my s-expressions are balanced.

However, they may not be complete, and I might want to continue typing inside them in another line, as follows:

CL-USER> (defun print-hello ()
            )

When I start a new line by pressing the enter key, however, the SLIME repl executes my incomplete expression. I want it to wait for me to complete the expression, as follows:

CL-USER> (defun print-hello ()
            (format t "Hello, world"))

How do I make this happen please?


问:
How to configure SharePoint to access the Certificate?
I'm using SharePoint 2010 and I'm configuring a web part using ChannelFactory and Certificate to access a WCF service.

But I'm getting this error message:

Error occured: Could not establish secure channel for SSL/TLS with authority 'my FQDN'.

How could I configure my SharePoint web application to have access to read this installed certificate?

(I'm sure the certificate is installed correctly on the server where sharepoint is installed and all the WCF configurations are correct)

Many thanks in advance,

答:
Have you tried uploading it to the Manage trusts area?

http://centraladmin/_admin/ManageTrust.aspx

Rebooted the server?

Installed on all servers in the farm? Into the machine store (not service or personal)?


问:
Problems building Google Drive API File Upload
I am trying to build an android app that'll allow me to upload files to Google Drive upon requirement of the user. But, I can't find a single working example anywhere. There are half baked snippets scattered here and there. Some of them are able to connect through OAuth, others are able to create an empty file or folder, but nowhere I can find an app that saves the tokens, and uploads the files seamlessly. I am just clueless as to how to implement the functionality as no books or videos are available, google's own samples don't work for me. I'm struggling to make the code work. Please help someone. Thanks.</p>

答:
I always use the class below to create a Google drive service.

First you need to have these dependencies on your pom file :

```<code><dependency>
    <groupId>com.google.api-client</groupId>
    <artifactId>google-api-client</artifactId>
    <version>1.23.0</version>
</dependency>
<dependency>
    <groupId>com.google.oauth-client</groupId>
    <artifactId>google-oauth-client-jetty</artifactId>
    <version>1.23.0</version>
</dependency>
<dependency>
    <groupId>com.google.apis</groupId>
    <artifactId>google-api-services-drive</artifactId>
    <version>v2-rev282-1.23.0</version>
</dependency>
</code>```

Then use this class to create instance of the drive api client :

```<code>import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.List;

/**
 *
 * @author jalal-sordo
 */
public class GoogleDriveServiceFactory {

    private String applicationName;

    private JsonFactory jsonFactory;
    private HttpTransport googleDriveHttpTransport;
    private List<String> googleDriveApiScopes;
    private String googleDriveClientSecretFilePath;
    private FileDataStoreFactory credentialsStoreFolder;

    public GoogleDriveServiceFactory(ApplicationParameters params) {
        try {
            this.googleDriveClientSecretFilePath = params.getGoogleDriveClientSecretFilePath();
            //  = new FileInputStream(googleDriveClientSecretFilePath);
            applicationName = "someApplicationName";
            jsonFactory = JacksonFactory.getDefaultInstance();
            googleDriveApiScopes = Arrays.asList(DriveScopes.DRIVE);
            googleDriveHttpTransport = GoogleNetHttpTransport.newTrustedTransport();
            java.io.File googleDriveCredentialsStore = new java.io.File(params.getGoogleDriveCredentialsFolderPath());
            credentialsStoreFolder = new FileDataStoreFactory(googleDriveCredentialsStore);
        } catch (IOException | GeneralSecurityException t) {
            System.err.println(t.getMessage());
            System.exit(1);
        }
    }

    public Credential authorize() throws IOException {
        InputStreamReader streamReader = new FileReader(new java.io.File(googleDriveClientSecretFilePath));
        GoogleClientSecrets clientSecrets
                = GoogleClientSecrets.load(jsonFactory, streamReader);
        // Build flow and trigger user authorization request.
        GoogleAuthorizationCodeFlow flow
                = new GoogleAuthorizationCodeFlow.Builder(
                        googleDriveHttpTransport, jsonFactory, clientSecrets, googleDriveApiScopes)
                        .setDataStoreFactory(credentialsStoreFolder)
                        .setAccessType("offline")
                        .build();
        Credential credential = new AuthorizationCodeInstalledApp(
                flow, new LocalServerReceiver()).authorize("user");

        return credential;
    }

    public Drive getDriveService() throws IOException {
        Credential credential = authorize();
        return new Drive.Builder(
                googleDriveHttpTransport, jsonFactory, credential)
                .setApplicationName(applicationName)
                .build();
    }
}
</code>```

You will also need this class to provide parameters to the class above :

```<code>/**
 *
 * @author jalal-sordo
 */
public class ApplicationParameters {

    private String googleDriveCredentialsFolderPath;
    private String googleDriveClientSecretFilePath;

    public String getGoogleDriveCredentialsFolderPath() {
        return googleDriveCredentialsFolderPath;
    }

    public void setGoogleDriveCredentialsFolderPath(String googleDriveCredentialsFolderPath) {
        this.googleDriveCredentialsFolderPath = googleDriveCredentialsFolderPath;
    }

    public String getGoogleDriveClientSecretFilePath() {
        return googleDriveClientSecretFilePath;
    }

    public void setGoogleDriveClientSecretFilePath(String googleDriveClientSecretFilePath) {
        this.googleDriveClientSecretFilePath = googleDriveClientSecretFilePath;
    }

    @Override
    public String toString() {
        return "ApplicationParameters{"
                + "\ngoogleDriveCredentialsFolderPath = " + googleDriveCredentialsFolderPath
                + "\ngoogleDriveClientSecretFilePath = " + googleDriveClientSecretFilePath
               + "\n}";
    }

}
</code>```

And this is how you can create an instance of the GoogleDriveServiceFactory and perform a file upload :

```<code>ApplicationParameters params = new ApplicationParameters();
//this is where you specify where you want the credentials to be stored
//after a successful autherization is made from the browser (this code will
//open the authorization consent page on your default browser).
params.setGoogleDriveCredentialsFolderPath("/path/to/credentials/folder");
//this is the path to your client_id that you downloaded from google cloud
//console credentials page.
params.setGoogleDriveClientSecretFilePath("/path/to/client_id.json");
GoogleDriveServiceFactory  driveFactory = new GoogleDriveServiceFactory (params);

File fileMetadata = new File();
fileMetadata.setName("photo.jpg");
java.io.File filePath = new java.io.File("files/photo.jpg");
FileContent mediaContent = new FileContent("image/jpeg", filePath);
File file = driveFactory.getDriveService.files().create(fileMetadata, mediaContent)
    .setFields("id")
    .execute();
System.out.println("File ID: " + file.getId());
</code>```

Body:
I always use the class below to create a Google drive service.

First you need to have these dependencies on your pom file :

<dependency>
    <groupId>com.google.api-client</groupId>
    <artifactId>google-api-client</artifactId>
    <version>1.23.0</version>
</dependency>
<dependency>
    <groupId>com.google.oauth-client</groupId>
    <artifactId>google-oauth-client-jetty</artifactId>
    <version>1.23.0</version>
</dependency>
<dependency>
    <groupId>com.google.apis</groupId>
    <artifactId>google-api-services-drive</artifactId>
    <version>v2-rev282-1.23.0</version>
</dependency>

Then use this class to create instance of the drive api client :

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.List;

/**
 *
 * @author jalal-sordo
 */
public class GoogleDriveServiceFactory {

    private String applicationName;

    private JsonFactory jsonFactory;
    private HttpTransport googleDriveHttpTransport;
    private List<String> googleDriveApiScopes;
    private String googleDriveClientSecretFilePath;
    private FileDataStoreFactory credentialsStoreFolder;

    public GoogleDriveServiceFactory(ApplicationParameters params) {
        try {
            this.googleDriveClientSecretFilePath = params.getGoogleDriveClientSecretFilePath();
            //  = new FileInputStream(googleDriveClientSecretFilePath);
            applicationName = "someApplicationName";
            jsonFactory = JacksonFactory.getDefaultInstance();
            googleDriveApiScopes = Arrays.asList(DriveScopes.DRIVE);
            googleDriveHttpTransport = GoogleNetHttpTransport.newTrustedTransport();
            java.io.File googleDriveCredentialsStore = new java.io.File(params.getGoogleDriveCredentialsFolderPath());
            credentialsStoreFolder = new FileDataStoreFactory(googleDriveCredentialsStore);
        } catch (IOException | GeneralSecurityException t) {
            System.err.println(t.getMessage());
            System.exit(1);
        }
    }

    public Credential authorize() throws IOException {
        InputStreamReader streamReader = new FileReader(new java.io.File(googleDriveClientSecretFilePath));
        GoogleClientSecrets clientSecrets
                = GoogleClientSecrets.load(jsonFactory, streamReader);
        // Build flow and trigger user authorization request.
        GoogleAuthorizationCodeFlow flow
                = new GoogleAuthorizationCodeFlow.Builder(
                        googleDriveHttpTransport, jsonFactory, clientSecrets, googleDriveApiScopes)
                        .setDataStoreFactory(credentialsStoreFolder)
                        .setAccessType("offline")
                        .build();
        Credential credential = new AuthorizationCodeInstalledApp(
                flow, new LocalServerReceiver()).authorize("user");

        return credential;
    }

    public Drive getDriveService() throws IOException {
        Credential credential = authorize();
        return new Drive.Builder(
                googleDriveHttpTransport, jsonFactory, credential)
                .setApplicationName(applicationName)
                .build();
    }
}

You will also need this class to provide parameters to the class above :

/**
 *
 * @author jalal-sordo
 */
public class ApplicationParameters {

    private String googleDriveCredentialsFolderPath;
    private String googleDriveClientSecretFilePath;

    public String getGoogleDriveCredentialsFolderPath() {
        return googleDriveCredentialsFolderPath;
    }

    public void setGoogleDriveCredentialsFolderPath(String googleDriveCredentialsFolderPath) {
        this.googleDriveCredentialsFolderPath = googleDriveCredentialsFolderPath;
    }

    public String getGoogleDriveClientSecretFilePath() {
        return googleDriveClientSecretFilePath;
    }

    public void setGoogleDriveClientSecretFilePath(String googleDriveClientSecretFilePath) {
        this.googleDriveClientSecretFilePath = googleDriveClientSecretFilePath;
    }

    @Override
    public String toString() {
        return "ApplicationParameters{"
                + "\ngoogleDriveCredentialsFolderPath = " + googleDriveCredentialsFolderPath
                + "\ngoogleDriveClientSecretFilePath = " + googleDriveClientSecretFilePath
               + "\n}";
    }

}

And this is how you can create an instance of the GoogleDriveServiceFactory and perform a file upload :

ApplicationParameters params = new ApplicationParameters();
//this is where you specify where you want the credentials to be stored
//after a successful autherization is made from the browser (this code will
//open the authorization consent page on your default browser).
params.setGoogleDriveCredentialsFolderPath("/path/to/credentials/folder");
//this is the path to your client_id that you downloaded from google cloud
//console credentials page.
params.setGoogleDriveClientSecretFilePath("/path/to/client_id.json");
GoogleDriveServiceFactory  driveFactory = new GoogleDriveServiceFactory (params);

File fileMetadata = new File();
fileMetadata.setName("photo.jpg");
java.io.File filePath = new java.io.File("files/photo.jpg");
FileContent mediaContent = new FileContent("image/jpeg", filePath);
File file = driveFactory.getDriveService.files().create(fileMetadata, mediaContent)
    .setFields("id")
    .execute();
System.out.println("File ID: " + file.getId());


问:
Jackson wrongly ignoring unknown fields by default
I have a pretty simple REST API project using Spring Boot 1.5.7 and Jackson 2.8.

Problem

I want Jackson to complain and raise an exception if there is an unknown field in the request. Although I have not set up anything telling it to ignore them, it simply ignores it and I do not know why.

Request:

```<code>{
  "appId":1,
  "version":"1.0",
  "status":true,
  "locked":false,
  "field": "it is ignored, but it must not be"
}
</code>```

Requet method

```<code>@PutMapping
public ResponseEntity<?> updateAppToggle(@RequestBody AppToggleUpdateRequest request) {
   AppToggle updatedAppToggle = service.update(request);
   return new ResponseEntity<AppToggleResponse>
       (AppToggleResponse.fillResponse(updatedAppToggle), HttpStatus.OK);
   }
</code>```

Request class

```<code>@Data
public class AppToggleUpdateRequest {

   @NotNull
   @Getter
   private Long appId;

   @NotNull
   @Getter
   private String version;

   private Boolean status;

   private Boolean locked;
}
</code>```

My application.properties does not contain anything special, just datasource and a few stuff for H2 in-memory database.

I really do not know what is going on. Any help would be truly appreciated.

答:
Have you tried this:</p>

```<code>@JsonIgnoreProperties(ignoreUnknown = true)
@Data
public class AppToggleUpdateRequest { .. }
</code>```

Body:
I have a pretty simple REST API project using Spring Boot 1.5.7 and Jackson 2.8.

Problem

I want Jackson to complain and raise an exception if there is an unknown field in the request. Although I have not set up anything telling it to ignore them, it simply ignores it and I do not know why.

Request:

{
  "appId":1,
  "version":"1.0",
  "status":true,
  "locked":false,
  "field": "it is ignored, but it must not be"
}

Requet method

@PutMapping
public ResponseEntity<?> updateAppToggle(@RequestBody AppToggleUpdateRequest request) {
   AppToggle updatedAppToggle = service.update(request);
   return new ResponseEntity<AppToggleResponse>
       (AppToggleResponse.fillResponse(updatedAppToggle), HttpStatus.OK);
   }

Request class

@Data
public class AppToggleUpdateRequest {

   @NotNull
   @Getter
   private Long appId;

   @NotNull
   @Getter
   private String version;

   private Boolean status;

   private Boolean locked;
}

My application.properties does not contain anything special, just datasource and a few stuff for H2 in-memory database.

I really do not know what is going on. Any help would be truly appreciated.

Body:
Have you tried this:

@JsonIgnoreProperties(ignoreUnknown = true)
@Data
public class AppToggleUpdateRequest { .. }


问:
Add line near TextView
I would like to add a line near a textView like the img below in android:

line near text view

here is my xml code:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/grey">
    <Switch
        android:id="@+id/bluetoothSwitch"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:paddingBottom="8dp"
        android:paddingLeft="16dp"
        android:paddingRight="16dp"
        android:paddingTop="8dp"
        android:text="Bluetooth"
        android:textSize="30sp"
        android:background="@android:color/white"/>
    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/bluetoothSwitch"
        android:layout_marginTop="20dp"
        android:background="@android:color/white"
        android:divider="?android:dividerVertical"
        android:dividerPadding="8dp"
        android:orientation="vertical"
        android:showDividers="middle">
        <Button
            android:id="@+id/btn1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_below="@+id/bluetoothSwitch"
            android:layout_gravity="start"
            android:background="?android:attr/selectableItemBackground"
            android:paddingBottom="8dp"
            android:paddingLeft="18dp"
            android:paddingTop="8dp"
            android:text="Scan"
            android:textAlignment="viewStart"
            android:textAllCaps="false"
            android:textSize="20sp" />

        <Button
            android:id="@+id/btn2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/btn1"
            android:layout_gravity="start"
            android:background="?android:attr/selectableItemBackground"
            android:paddingBottom="8dp"
            android:paddingLeft="18dp"
            android:paddingTop="8dp"
            android:text="Show Paired Device"
            android:textAlignment="viewStart"
            android:textAllCaps="false"
            android:textSize="20sp" />
    </LinearLayout>
    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/linearLayout1"
        android:layout_marginTop="20dp"
        android:paddingLeft="16dp"
        android:text="PAIRED DEVICE: "
        android:background="@android:color/white"
        android:paddingBottom="8dp"
        android:paddingTop="8dp"/>
</RelativeLayout>
</code>```

and my app screen:

where a would like to add line

i took this screenshot from my samsung settings. i would add the line near the textview "paired device".
i read to use view but i can't do it.
Can someone help me?
thank you all

答:
Try this :

```<code>       <LinearLayout
        android:layout_width="match_parent"
        android:orientation="horizontal"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Your Text"
            />

        <View
            android:layout_width="match_parent"
            android:layout_height="0.7dp"
            android:background="#dddddd"
            android:layout_gravity="center_vertical"
            />

    </LinearLayout>
</code>```

Change the background colour of view to any colour and change it's height accordingly and place marginLeft also if needed.
Hope this helps.

Title: Add line near TextView

Body:
I would like to add a line near a textView like the img below in android:

line near text view

here is my xml code:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/grey">
    <Switch
        android:id="@+id/bluetoothSwitch"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:paddingBottom="8dp"
        android:paddingLeft="16dp"
        android:paddingRight="16dp"
        android:paddingTop="8dp"
        android:text="Bluetooth"
        android:textSize="30sp"
        android:background="@android:color/white"/>
    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/bluetoothSwitch"
        android:layout_marginTop="20dp"
        android:background="@android:color/white"
        android:divider="?android:dividerVertical"
        android:dividerPadding="8dp"
        android:orientation="vertical"
        android:showDividers="middle">
        <Button
            android:id="@+id/btn1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_below="@+id/bluetoothSwitch"
            android:layout_gravity="start"
            android:background="?android:attr/selectableItemBackground"
            android:paddingBottom="8dp"
            android:paddingLeft="18dp"
            android:paddingTop="8dp"
            android:text="Scan"
            android:textAlignment="viewStart"
            android:textAllCaps="false"
            android:textSize="20sp" />

        <Button
            android:id="@+id/btn2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/btn1"
            android:layout_gravity="start"
            android:background="?android:attr/selectableItemBackground"
            android:paddingBottom="8dp"
            android:paddingLeft="18dp"
            android:paddingTop="8dp"
            android:text="Show Paired Device"
            android:textAlignment="viewStart"
            android:textAllCaps="false"
            android:textSize="20sp" />
    </LinearLayout>
    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/linearLayout1"
        android:layout_marginTop="20dp"
        android:paddingLeft="16dp"
        android:text="PAIRED DEVICE: "
        android:background="@android:color/white"
        android:paddingBottom="8dp"
        android:paddingTop="8dp"/>
</RelativeLayout>

and my app screen:

where a would like to add line

i took this screenshot from my samsung settings. i would add the line near the textview "paired device".
i read to use view but i can't do it.
Can someone help me?
thank you all

Body:
Try this :

       <LinearLayout
        android:layout_width="match_parent"
        android:orientation="horizontal"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Your Text"
            />

        <View
            android:layout_width="match_parent"
            android:layout_height="0.7dp"
            android:background="#dddddd"
            android:layout_gravity="center_vertical"
            />

    </LinearLayout>

Change the background colour of view to any colour and change it's height accordingly and place marginLeft also if needed.
Hope this helps.


答:
Try something like this - </p>

```<code><LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="center_vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TEXT"/>

        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="@android:color/black" />

    </LinearLayout>
</code>```

Title: Add line near TextView

Body:
Try something like this -

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="center_vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TEXT"/>

        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="@android:color/black" />

    </LinearLayout>


问:
Inverse of matrix inaccurate
I'm trying to write tests to validate inverse of matrix, but test fails when I use FLT_EPSILON to compare results.

Comparing function looks like this: test_assert_mat4_eq

What I'm trying to do is:

```<code>A = random matrix (4x4 float matrix)
B = inv(A)
C = inv(B)

assert(A == C) <---- fails
</code>```

First let me explain how I calculate matrix inverse; mat4 is 4x4 float matrix, if SIMD is enabled then inverse of matrix will be computed via SIMD instructions (SSE2 and AVX).

You can see matrix inverse code at glm_mat4_inv if SSE2 is enabled then the inverse is calculated via glm_mat4_inv_sse2 also there is glm_mat4_inv_precise_sse2 version to get more precision by avoid _mm_rcp_ps instruction. I used the second (glm_mat4_inv_precise_sse2) version to test.

assert_true(fabsf(m1[i][j] - m2[i][j]) <= 0.0001);

passes on my macbook but it still fails on linux.

assert_true(fabsf(m1[i][j] - m2[i][j]) <= FLT_EPSILON); this even not passes on macos. Maybe comparing with 0.001 will also work on linux but precision is too low.

I also created an issue on glm repo (https://github.com/g-truc/glm/issues/700) because this issue also valid for glm.

What is wrong with this? Why the precision is too low? Is this ok? Should I leave it like this (by removing the test or by changing precision)?

NOTE: Random matrix is generating with test_rand_mat4 function. But I'm using it just for generating a matrix. I'm not using any random matrix in anywhere, all matrices are affine transformation matrices, maybe I should use affine transforms (which is the main purpose) for comparing

答:
A 4⨉4 matrix is small enough that you could instrument the code to print each floating-point number involved after each step of calculation and then compare the macOS and Linux results to see where they differ. (Use the %a format in C’s printf to print hexadecimal floating-point or use something like %.30g to print the entire value in decimal.)

Telling us the difference exceeds .0001 is meaningless since we do not know what magnitude your data is. Commonly, numerical errors will be roughly proportional to the magnitudes of some of the numbers involved.

If the “same” operations are performed on macOS and on Linux running on hardware that uses IEEE-754 floating-point, then identical results should be achieved. So any differences are likely because you are not using the same operations. Causes of such differences may include that the two systems are using different source code (e.g., because one uses SIMD because SSE is enabled, and the other uses scalar code) or the compilers are compiling code differently. Override the SSE decision temporarily so that you are testing the same source code on both systems. Once that is debugged, test the SSE code on both systems, if possible. After that, compare the SSE code to the non-SSE code.

Instead of testing with random data, you should start with simple test cases and work up to more involved test cases. Start with the identity matrix. Simple cases would help debug the fundamental logic without involving significant floating-point errors. Then modify elements to generate more complicated cases. When generating matrices for testing, avoid ill-conditioned matrices. I am not experienced in generating matrices for testing matrix inverse, so you will have to investigate how to modify a matrix to improve its condition number, or someone else might suggest something.

Do not test matrix inverse by calling inv twice. This misses simple errors such as a copy-and-paste error that results in a routine named inv actually being a matrix copy or a negate. Instead, use a known-good reference implementation of matrix inverse or use known test cases (the inverse of the identity matrix is the identity matrix, and others can be constructed) or use other properties of the inverse (multiplying the inverse by the original matrix should produce the identity matrix). Use double for the test code. The number of test cases needed to find errors in a 4⨉4 matrix inversion is not large enough that performance matters.

Title: Inverse of matrix inaccurate

Body:
I'm trying to write tests to validate inverse of matrix, but test fails when I use FLT_EPSILON to compare results.

Comparing function looks like this: test_assert_mat4_eq

What I'm trying to do is:

A = random matrix (4x4 float matrix)
B = inv(A)
C = inv(B)

assert(A == C) <---- fails

First let me explain how I calculate matrix inverse; mat4 is 4x4 float matrix, if SIMD is enabled then inverse of matrix will be computed via SIMD instructions (SSE2 and AVX).

You can see matrix inverse code at glm_mat4_inv if SSE2 is enabled then the inverse is calculated via glm_mat4_inv_sse2 also there is glm_mat4_inv_precise_sse2 version to get more precision by avoid _mm_rcp_ps instruction. I used the second (glm_mat4_inv_precise_sse2) version to test.

assert_true(fabsf(m1[i][j] - m2[i][j]) <= 0.0001);

passes on my macbook but it still fails on linux.

assert_true(fabsf(m1[i][j] - m2[i][j]) <= FLT_EPSILON); this even not passes on macos. Maybe comparing with 0.001 will also work on linux but precision is too low.

I also created an issue on glm repo (https://github.com/g-truc/glm/issues/700) because this issue also valid for glm.

What is wrong with this? Why the precision is too low? Is this ok? Should I leave it like this (by removing the test or by changing precision)?

NOTE: Random matrix is generating with test_rand_mat4 function. But I'm using it just for generating a matrix. I'm not using any random matrix in anywhere, all matrices are affine transformation matrices, maybe I should use affine transforms (which is the main purpose) for comparing