问:
Integer division optimization MSVC C++
I'm trying to reduce the CPU usage of a portion of my code, taking 40% of the CPU power. The portion is this one:

```<code>void CalibrationFunction(cv::Mat* pMatSrc, cv::Mat* pMatDst,
                         cv::Mat* pBlack, cv::Mat* pWhite, INT32 nRadioFactor)
{
  if (pMatSrc && pMatDst && pMatSrc->data && pMatDst->data)
  {
    for (int i = 0; i < pMatSrc->size[0]; i++)
    {
      UINT16* pBlackVal = (UINT16*)(pBlack->data + i*pBlack->step[0]);
      UINT16* pWhiteVal = (UINT16*)(pWhite->data + i*pWhite->step[0]);
      UINT16* pData = (UINT16*)(pMatSrc->data + i*pMatSrc->step[0]);
      INT32 nDif;
      UINT16 un16Value;
      for (int j = 0; j < pMatSrc->size[1]; j++)
      {
        nDif = (*pData) - (*pBlackVal);
        un16Value = (UINT16)min(65535, (max(0, nDif) * nRadioFactor / max(1, (*pWhiteVal))));
        pBlackVal++;
        pWhiteVal++;
        pData++;

        int i0 = 0, i1 = j, i2 = i;
        *(UINT16*)(pMatDst->data + i0 * pMatDst->step[0] + i1 * pMatDst->step[1] + i2 * pMatDst->step[2]) = un16Value;
      }
    }
  }
}
</code>```

Multithreading is already implemented: 8 threads are used.

I looked at SIMD with integer arithmetic operation, but as there is an integer division, it seems this is not the way to proceed. I looked at optimized integer division libraries, but they all seem to only be effective when all the integers are divided by the same denominator, which is not the case here.

Does someone have a lead to follow? I'm very open to exotic solution (compile the code in another language and call it from the current solution, etc), the only restriction is this has to stay a MSVC project, using MSVC compiler.

I've seen that Intel implemented integer division with SMID, maybe I should compile this piece of code with the Intel compiler, and call the generated binary from the current solution (I have an Intel compiler), but this solution would only work on my computer and would be, in my opinion, "too custom".

EDIT

I finally managed to use SIMD however. The trick was, for the division, to cast the vector of 8 integers of 16 bits into 2 vectors of four float of 32 bits, and then I could divide them, because there are some function to divide floats in SIMD. After the division, recast in order to have 16 bits integer results.
The new function, using SIMD, is 6 times faster, which is enough at this moment. I keep in mind all your remarks, as they could be helpful if this portion of my solution become again a bottleneck.

EDIT 2

As requested, here is the new code:

```<code>void CalibrationRadioSIMD(UINT16* pBlackVal, UINT16* pWhiteVal, UINT16* pData, UINT16* pResult, int size, int nRadioFactor = 2)
{

    for (int hop = 0; hop < 100; hop++) {
        UINT16* pResultTmp = pResult;
        UINT16* pDataTmp = pData;
        UINT16* pBlackValTmp = pBlackVal;
        UINT16* pWhiteValTmp = pWhiteVal;
        __m128i radio;

        radio.m128i_i32[0] = nRadioFactor;
        radio.m128i_i32[1] = nRadioFactor;
        radio.m128i_i32[2] = nRadioFactor;
        radio.m128i_i32[3] = nRadioFactor;
        for (int j = 0; j < size / 8; j++)
        {
            //
            // nDif = max(0, (*pData) - (*pBlackVal));
            //
            // 1/ Loads 128-bit value
            //    Address p must be 16-byte aligned.
            //    For the unaligned version, see _mm_loadu_si128.
            __m128i reg_a = _mm_load_si128((__m128i*)pDataTmp);
            __m128i reg_B = _mm_load_si128((__m128i*)pBlackValTmp);
            __m128i reg_white = _mm_load_si128((__m128i*)pWhiteValTmp);
            pDataTmp += 8;
            pBlackValTmp += 8;
            pWhiteValTmp += 8;

            // 2/ Subtracts the 8 unsigned 16-bit integers of b from the 8 unsigned 16-bit integers of a and saturates.
            __m128i reg_diff = _mm_subs_epu16(reg_a, reg_B);

            /////////////////////////////////////////////////////////////////////////////

            // unpack your vector of 8 x 16 bit unsigned shorts into two vectors of 32 bit unsigned ints, :
            __m128i xlo = _mm_unpacklo_epi16(reg_diff, _mm_set1_epi16(0));
            __m128i xhi = _mm_unpackhi_epi16(reg_diff, _mm_set1_epi16(0));

            // This instruction multiplies two sets of 32-bit signed integers.
            __m128i mullo = _mm_mullo_epi32(xlo, radio);
            __m128i mulhi = _mm_mullo_epi32(xhi, radio);

            // convert each of these vectors to float
            __m128 ylo = _mm_cvtepi32_ps(mullo);
            __m128 yhi = _mm_cvtepi32_ps(mulhi);

            // Meme question que pour xlo et xhi
            __m128i i32_whitelo = _mm_unpacklo_epi16(reg_white, _mm_set1_epi16(0));
            __m128i i32_whitehi = _mm_unpackhi_epi16(reg_white, _mm_set1_epi16(0));

            __m128 f32_white_lo = _mm_cvtepi32_ps(i32_whitelo);
            __m128 f32_white_hi = _mm_cvtepi32_ps(i32_whitehi);

            __m128 f32_res_lo = _mm_div_ps(ylo, f32_white_lo);
            __m128 f32_res_hi = _mm_div_ps(yhi, f32_white_hi);

            // Reconvertir en entier 16 bits

            __m128i n32_res_lo = _mm_cvtps_epi32(f32_res_lo);
            __m128i n32_res_hi = _mm_cvtps_epi32(f32_res_hi);

            // Put result into result vector
            UINT16* f32_res_lo_i16 = (UINT16*)&n32_res_lo;
            UINT16* f32_res_hi_i16 = (UINT16*)&n32_res_hi;
            int l = 0;
            for (int k = 0; k < 4; k++) {
                *(pResultTmp + k + 0) = *(f32_res_lo_i16 + l);
                *(pResultTmp + k + 4) = *(f32_res_hi_i16 + l);
                l += 2;
            }
            pResultTmp += 8;

        }
    }
}
</code>```

答:
You can create a inverse (I mean multiplicative inverse) table for that. If you allow some little imprecision, this table will fit in 128k. It won't fit L1 cache. So, maybe you'll need to prefetch it to maximize performance. With SIMD, this solution should be faster than your current one.

If your white image happens to be constant (I mean that you call CalibrationFunction multiple times with the same white image), then you can invert it before, so you won't need the inverse table, and the solution will be even faster.

Title: Integer division optimization MSVC C++

Body:
I'm trying to reduce the CPU usage of a portion of my code, taking 40% of the CPU power. The portion is this one:

void CalibrationFunction(cv::Mat* pMatSrc, cv::Mat* pMatDst,
                         cv::Mat* pBlack, cv::Mat* pWhite, INT32 nRadioFactor)
{
  if (pMatSrc && pMatDst && pMatSrc->data && pMatDst->data)
  {
    for (int i = 0; i < pMatSrc->size[0]; i++)
    {
      UINT16* pBlackVal = (UINT16*)(pBlack->data + i*pBlack->step[0]);
      UINT16* pWhiteVal = (UINT16*)(pWhite->data + i*pWhite->step[0]);
      UINT16* pData = (UINT16*)(pMatSrc->data + i*pMatSrc->step[0]);
      INT32 nDif;
      UINT16 un16Value;
      for (int j = 0; j < pMatSrc->size[1]; j++)
      {
        nDif = (*pData) - (*pBlackVal);
        un16Value = (UINT16)min(65535, (max(0, nDif) * nRadioFactor / max(1, (*pWhiteVal))));
        pBlackVal++;
        pWhiteVal++;
        pData++;

        int i0 = 0, i1 = j, i2 = i;
        *(UINT16*)(pMatDst->data + i0 * pMatDst->step[0] + i1 * pMatDst->step[1] + i2 * pMatDst->step[2]) = un16Value;
      }
    }
  }
}

Multithreading is already implemented: 8 threads are used.

I looked at SIMD with integer arithmetic operation, but as there is an integer division, it seems this is not the way to proceed. I looked at optimized integer division libraries, but they all seem to only be effective when all the integers are divided by the same denominator, which is not the case here.

Does someone have a lead to follow? I'm very open to exotic solution (compile the code in another language and call it from the current solution, etc), the only restriction is this has to stay a MSVC project, using MSVC compiler.

I've seen that Intel implemented integer division with SMID, maybe I should compile this piece of code with the Intel compiler, and call the generated binary from the current solution (I have an Intel compiler), but this solution would only work on my computer and would be, in my opinion, "too custom".

EDIT

I finally managed to use SIMD however. The trick was, for the division, to cast the vector of 8 integers of 16 bits into 2 vectors of four float of 32 bits, and then I could divide them, because there are some function to divide floats in SIMD. After the division, recast in order to have 16 bits integer results.
The new function, using SIMD, is 6 times faster, which is enough at this moment. I keep in mind all your remarks, as they could be helpful if this portion of my solution become again a bottleneck.

EDIT 2

As requested, here is the new code:

void CalibrationRadioSIMD(UINT16* pBlackVal, UINT16* pWhiteVal, UINT16* pData, UINT16* pResult, int size, int nRadioFactor = 2)
{

    for (int hop = 0; hop < 100; hop++) {
        UINT16* pResultTmp = pResult;
        UINT16* pDataTmp = pData;
        UINT16* pBlackValTmp = pBlackVal;
        UINT16* pWhiteValTmp = pWhiteVal;
        __m128i radio;

        radio.m128i_i32[0] = nRadioFactor;
        radio.m128i_i32[1] = nRadioFactor;
        radio.m128i_i32[2] = nRadioFactor;
        radio.m128i_i32[3] = nRadioFactor;
        for (int j = 0; j < size / 8; j++)
        {
            //
            // nDif = max(0, (*pData) - (*pBlackVal));
            //
            // 1/ Loads 128-bit value
            //    Address p must be 16-byte aligned.
            //    For the unaligned version, see _mm_loadu_si128.
            __m128i reg_a = _mm_load_si128((__m128i*)pDataTmp);
            __m128i reg_B = _mm_load_si128((__m128i*)pBlackValTmp);
            __m128i reg_white = _mm_load_si128((__m128i*)pWhiteValTmp);
            pDataTmp += 8;
            pBlackValTmp += 8;
            pWhiteValTmp += 8;

            // 2/ Subtracts the 8 unsigned 16-bit integers of b from the 8 unsigned 16-bit integers of a and saturates.
            __m128i reg_diff = _mm_subs_epu16(reg_a, reg_B);

            /////////////////////////////////////////////////////////////////////////////

            // unpack your vector of 8 x 16 bit unsigned shorts into two vectors of 32 bit unsigned ints, :
            __m128i xlo = _mm_unpacklo_epi16(reg_diff, _mm_set1_epi16(0));
            __m128i xhi = _mm_unpackhi_epi16(reg_diff, _mm_set1_epi16(0));

            // This instruction multiplies two sets of 32-bit signed integers.
            __m128i mullo = _mm_mullo_epi32(xlo, radio);
            __m128i mulhi = _mm_mullo_epi32(xhi, radio);

            // convert each of these vectors to float
            __m128 ylo = _mm_cvtepi32_ps(mullo);
            __m128 yhi = _mm_cvtepi32_ps(mulhi);

            // Meme question que pour xlo et xhi
            __m128i i32_whitelo = _mm_unpacklo_epi16(reg_white, _mm_set1_epi16(0));
            __m128i i32_whitehi = _mm_unpackhi_epi16(reg_white, _mm_set1_epi16(0));

            __m128 f32_white_lo = _mm_cvtepi32_ps(i32_whitelo);
            __m128 f32_white_hi = _mm_cvtepi32_ps(i32_whitehi);

            __m128 f32_res_lo = _mm_div_ps(ylo, f32_white_lo);
            __m128 f32_res_hi = _mm_div_ps(yhi, f32_white_hi);

            // Reconvertir en entier 16 bits

            __m128i n32_res_lo = _mm_cvtps_epi32(f32_res_lo);
            __m128i n32_res_hi = _mm_cvtps_epi32(f32_res_hi);

            // Put result into result vector
            UINT16* f32_res_lo_i16 = (UINT16*)&n32_res_lo;
            UINT16* f32_res_hi_i16 = (UINT16*)&n32_res_hi;
            int l = 0;
            for (int k = 0; k < 4; k++) {
                *(pResultTmp + k + 0) = *(f32_res_lo_i16 + l);
                *(pResultTmp + k + 4) = *(f32_res_hi_i16 + l);
                l += 2;
            }
            pResultTmp += 8;

        }
    }
}


来源: stackexchange

问:
How to share photo to Facebook within iOS app, when Facebook app is not installed on the phone?
Im using FBSDKShareKit (4.22.1), i'm trying to share photo with the following code:

```<code>let photo = FBSDKSharePhoto()
photo1.imageURL = URL(string: "sample url")
photo.isUserGenerated = false
let photoContent = FBSDKSharePhotoContent()
photoContent.photos = [photo]
FBSDKShareDialog.show(from: self, with: photoContent, delegate: nil)
</code>```

but it only works when the native Facebook app is installed on the phone.
I also tried to show the content with Share Button instead of Share Dialog like:

```<code>var shareButton = FBSDKShareButton()
shareButton.shareContent = photoContent
shareButton.center = self.view.center
self.view.addSubview(shareButton)
</code>```

it didn't work, if app was not installed either.

i want the FBSDK i used in my app, opens Safari when Facebook app is not installed, it opens safari by default for FBSDKShareLinkContent, but not working for FBSDKSharePhotoContent.
does anyone know what is the problem?

答:
Well, I found the answer in Facebook developer website, which is:

Photos

People can share photos from your app to Facebook with the Share
  Dialog or with a custom interface:

Photos must be less than 12MB in size

People need the native Facebook for iOS app installed, version 7.0 or higher

you can also ask for "publish_actions", you need to login twice, first with readPermission for email, then when user wants to share a post loginWithPublishPermission for "publish_actions". the point is that you have to add "publish_actions" first of all in your Facebook developer account.

ContentLicense: CC BY-SA 3.0

Body:
Im using FBSDKShareKit (4.22.1), i'm trying to share photo with the following code:

let photo = FBSDKSharePhoto()
photo1.imageURL = URL(string: "sample url")
photo.isUserGenerated = false
let photoContent = FBSDKSharePhotoContent()
photoContent.photos = [photo]
FBSDKShareDialog.show(from: self, with: photoContent, delegate: nil)

but it only works when the native Facebook app is installed on the phone.
I also tried to show the content with Share Button instead of Share Dialog like:

var shareButton = FBSDKShareButton()
shareButton.shareContent = photoContent
shareButton.center = self.view.center
self.view.addSubview(shareButton)

it didn't work, if app was not installed either.

i want the FBSDK i used in my app, opens Safari when Facebook app is not installed, it opens safari by default for FBSDKShareLinkContent, but not working for FBSDKSharePhotoContent.
does anyone know what is the problem?


问:
how to get day from mysql with codeigniter query
I need to take my date to sunday, monday, tuesday .... from my databse, currently i getting the date from the databse, how can i convert it to day (like sunday, monday)

```<code>$start_date = $data['start_date'];
    $end_date = $data ['end_date'];
    $student_id = $data['student_id'];

    $where_condition = ['sa.school_id' => $school_id, 'sa.student_id' => $student_id];
    $this->db
    ->select('sa.id, sa.date, sa.attendance_type, sa.reason')
    ->from('student_attendance sa')
    ->join('student st', 'st.id = sa.student_id AND st.school_id = sa.school_id', 'left')
    ->where($where_condition)
    ->where('sa.date >=', $start_date)
    ->where('sa.date <=', $end_date);
    $query = $this->db->get()->result();
    return $query;
</code>```

and this is my result when i run my query

```<code>[{"id":"2","date":"2017-07-03","attendance_type":"absent","reason":""},{"id":"3","date":"2017-07-04","attendance_type":"present","reason":""}]
</code>```

答:
DayName(Date) As Day
You can refer
http://www.w3resource.com/mysql/date-and-time-functions/mysql-dayname-function.php</p>

Body:
I need to take my date to sunday, monday, tuesday .... from my databse, currently i getting the date from the databse, how can i convert it to day (like sunday, monday)

$start_date = $data['start_date'];
    $end_date = $data ['end_date'];
    $student_id = $data['student_id'];

    $where_condition = ['sa.school_id' => $school_id, 'sa.student_id' => $student_id];
    $this->db
    ->select('sa.id, sa.date, sa.attendance_type, sa.reason')
    ->from('student_attendance sa')
    ->join('student st', 'st.id = sa.student_id AND st.school_id = sa.school_id', 'left')
    ->where($where_condition)
    ->where('sa.date >=', $start_date)
    ->where('sa.date <=', $end_date);
    $query = $this->db->get()->result();
    return $query;

and this is my result when i run my query

[{"id":"2","date":"2017-07-03","attendance_type":"absent","reason":""},{"id":"3","date":"2017-07-04","attendance_type":"present","reason":""}]


问:
Jquery button don't append elements with no errors at the console
I have this html form:

```<code>         <div class="col-sm-4 rounded" style="background-color: #D3D3D3">
          <div class="row clonedInput" id="clonedInput1">
          <div class="col-sm-6">
              <label for="diagnosis_data">Medication</label>
                <fieldset class="form-group">
                  <select class="form-control select" name="diagnosis_data" id="diagnosis_data">
                    <option value="choose">Select</option>
                  </select>
                </fieldset>
            <!-- End class="col-sm-6" -->
            </div>
            <div class="col-sm-6">
              <label for="patient_weight">Quantity</label>
                <fieldset class="form-group">
                  <input type="number" class="form-control" name="patient_weight" id="patient_weight">
                </fieldset>
            <!-- End class="col-sm-6" -->
            </div>
            <!-- End class="col-sm-6" -->
          </div>
          <div class="actions pull-right">
            <button class="btn btn-danger clone">Add More</button>
            <button class="btn btn-danger remove">Remove</button>
          </div>
</code>```

And this jQuery Script from this link here:

```<code><script>
  $(document).ready(function()
  {
    $("button.clone").on("click", clone);

    $("button.remove").on("click", remove);
  })
    var regex = /^(.+?)(\d+)$/i;
    var cloneIndex = $(".clonedInput").length;
    function clone(){
        $(this).parents(".clonedInput").clone()
            .appendTo(".rounded")
            .attr("id", "clonedInput" +  cloneIndex)
            .find("*")
            .each(function() {
                var id = this.id || "";
                var match = id.match(regex) || [];
                if (match.length == 3) {
                    this.id = match[1] + (cloneIndex);
                }
            })
            .on('click', 'button.clone', clone)
            .on('click', 'button.remove', remove);
        cloneIndex++;
    }
    function remove(){
        $(this).parents(".clonedInput").remove();
    }

  </script>
</code>```

But of course with changes to html but nothing happens when I click on each of the buttons, even no errors at the console. Here is my fiddle.

I am using jQuery 3.2.1

EDIT 1

I tried this script:

```<code>$("button.clone").on("click", function()
{
   $('.clonedInput').clone().insertAfter('.clonedInput')
});
</code>```

it works but there is 2 problems:

ID of each element is not incrementing;

If I had 2 elements and clicked on the button they will be 4, then 8, then...

EDIT 2

I tried this and the problem number 2 is gone:

```<code>$("button.clone").on("click", function()
{
  $('#clonedInput1').clone().insertAfter('#clonedInput1')
});
</code>```

Now I still have to increment the id so I can send the data later using Ajax. Here is my updated fiddle.

答:
If you're open to hyphenating the id's:

var regex = /^(.+?)(\d+)$/i;
var cloneIndex = 1;

function clone(){
  cloneIndex++;
    $(this).parents(".clonedInput").clone()
        .appendTo("body")
        .attr("id", 'clonedInput-'+(cloneIndex))
        .find("*")
        .each(function() {
            var id = this.id || "";
            var match = id.match(regex) || [];
            if (match.length == 3) {
                this.id = id.split('-')[0] +'-'+(cloneIndex);
            }
        })
        .on('click', 'button.clone', clone)
        .on('click', 'button.remove', remove);
}
function remove(){
    $(this).parents(".clonedInput").remove();
}
$("button.clone").on("click", clone);

$("button.remove").on("click", remove);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="clonedInput-1" class="clonedInput">
    <div>
        <label for="txtCategory" class="">Learning category <span class="requiredField">*</span></label>
        <select class="" name="txtCategory[]" id="category-1">
            <option value="">Please select</option>
        </select>
    </div>
    <div>
        <label for="txtSubCategory" class="">Sub-category <span class="requiredField">*</span></label>
        <select class="" name="txtSubCategory[]" id="subcategory-1">
            <option value="">Please select category</option>
        </select>
    </div>
    <div>
        <label for="txtSubSubCategory">Sub-sub-category <span class="requiredField">*</span></label>
        <select name="txtSubSubCategory[]" id="subsubcategory-1">
            <option value="">Please select sub-category</option>
        </select>
    </div>
    <div class="actions">
        <button class="clone">Clone</button>
        <button class="remove">Remove</button>
    </div>
</div></code>```

Body:
I have this html form:

              Medication
                <fieldset class="form-group">
                  <select class="form-control select" name="diagnosis_data" id="diagnosis_data">
                    <option value="choose">Select</option>
                  </select>
                </fieldset>

              Quantity
                <fieldset class="form-group">
                  <input type="number" class="form-control" name="patient_weight" id="patient_weight">
                </fieldset>

            <button class="btn btn-danger clone">Add More</button>
            <button class="btn btn-danger remove">Remove</button>

And this jQuery Script from this link here:

But of course with changes to html but nothing happens when I click on each of the buttons, even no errors at the console. Here is my fiddle.

I am using jQuery 3.2.1

EDIT 1

I tried this script:

$("button.clone").on("click", function()
{
   $('.clonedInput').clone().insertAfter('.clonedInput')
});

it works but there is 2 problems:

ID of each element is not incrementing;

If I had 2 elements and clicked on the button they will be 4, then 8, then...

EDIT 2

I tried this and the problem number 2 is gone:

$("button.clone").on("click", function()
{
  $('#clonedInput1').clone().insertAfter('#clonedInput1')
});

Now I still have to increment the id so I can send the data later using Ajax. Here is my updated fiddle.

Body:
If you're open to hyphenating the id's:

var regex = /^(.+?)(\d+)$/i;
var cloneIndex = 1;

function clone(){
  cloneIndex++;
    $(this).parents(".clonedInput").clone()
        .appendTo("body")
        .attr("id", 'clonedInput-'+(cloneIndex))
        .find("*")
        .each(function() {
            var id = this.id || "";
            var match = id.match(regex) || [];
            if (match.length == 3) {
                this.id = id.split('-')[0] +'-'+(cloneIndex);
            }
        })
        .on('click', 'button.clone', clone)
        .on('click', 'button.remove', remove);
}
function remove(){
    $(this).parents(".clonedInput").remove();
}
$("button.clone").on("click", clone);

$("button.remove").on("click", remove);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="clonedInput-1" class="clonedInput">
    <div>
        <label for="txtCategory" class="">Learning category <span class="requiredField">*</span></label>
        <select class="" name="txtCategory[]" id="category-1">
            <option value="">Please select</option>
        </select>
    </div>
    <div>
        <label for="txtSubCategory" class="">Sub-category <span class="requiredField">*</span></label>
        <select class="" name="txtSubCategory[]" id="subcategory-1">
            <option value="">Please select category</option>
        </select>
    </div>
    <div>
        <label for="txtSubSubCategory">Sub-sub-category <span class="requiredField">*</span></label>
        <select name="txtSubSubCategory[]" id="subsubcategory-1">
            <option value="">Please select sub-category</option>
        </select>
    </div>
    <div class="actions">
        <button class="clone">Clone</button>
        <button class="remove">Remove</button>
    </div>
</div>


问:
How to align html elements on the same row
If you see the attachment below, three share buttons are not equally margined from the top. Tweet button didn't maintain the consistency, it is little bit up than the other two. How do I make all of them equally distanced from the top?

The code I am working on:

```<code>                            <h2 class="title">Share this blog</h2>

                            <div class="fb-share-button" data-href="http://alfa-blog.com/"
                                 data-layout="button_count" data-size="large" data-mobile-iframe="true">
                                <a class="fb-xfbml-parse-ignore" target="_blank"
                                   href="https://www.facebook.com/sharer/sharer.php?u=http%3A%2F%2Falfa-blog.com%2Findex.html&src=sdkpreparse">Share</a>
                            </div>

                            <a href="https://twitter.com/share"
                               data-size="large"
                               class="twitter-share-button" data-show-count="false">Tweet</a>

                            <div class="g-plus" data-action="share" data-height="24" data-href="http://alfa-blog.com/"></div>
</code>```

答:
using flex-box it can be done like this

```<code><div class="container">
   <div class="fb-share-button" data-href="http://alfa-blog.com/"
      data-layout="button_count" data-size="large" data-mobile-iframe="true">
      <a class="fb-xfbml-parse-ignore" target="_blank"
         href="https://www.facebook.com/sharer/sharer.php?u=http%3A%2F%2Falfa-blog.com%2Findex.html&src=sdkpreparse">Share</a>
   </div>
   <a href="https://twitter.com/share"
      data-size="large"
      class="twitter-share-button" data-show-count="false">Tweet</a>
   <div class="g-plus" data-action="share" data-height="24" data-href="http://alfa-blog.com/"></div>
</div>
</code>```

CSS

```<code>.container{
    display: flex;
    flex-direction: row;
    align-items: flex-start
    }
</code>```

this is a really good guide
https://css-tricks.com/snippets/css/a-guide-to-flexbox/

Body:
If you see the attachment below, three share buttons are not equally margined from the top. Tweet button didn't maintain the consistency, it is little bit up than the other two. How do I make all of them equally distanced from the top?

The code I am working on:

Share this blog

                                Share

                            Tweet

Body:
using flex-box it can be done like this

<div class="container">
   <div class="fb-share-button" data-href="http://alfa-blog.com/"
      data-layout="button_count" data-size="large" data-mobile-iframe="true">
      <a class="fb-xfbml-parse-ignore" target="_blank"
         href="https://www.facebook.com/sharer/sharer.php?u=http%3A%2F%2Falfa-blog.com%2Findex.html&amp;src=sdkpreparse">Share</a>
   </div>
   <a href="https://twitter.com/share"
      data-size="large"
      class="twitter-share-button" data-show-count="false">Tweet</a>
   <div class="g-plus" data-action="share" data-height="24" data-href="http://alfa-blog.com/"></div>
</div>

CSS

.container{
    display: flex;
    flex-direction: row;
    align-items: flex-start
    }

this is a really good guide
https://css-tricks.com/snippets/css/a-guide-to-flexbox/


问:
getting null value when getting the datatable value to the textbox in static web method
when textbox getting the data through datatable object in static method at that time it shows the null value (i.e. showing error : object reference not set to an instance of the object). But when I am doing the debug mode at that time it shows the data in the datatable, so from that I am confusing that how in textbox it getting the null value.

Here is my code

```<code>[WebMethod]
    public static void GetCnorGSTNo(string Param1)
    {
        Page page = (Page)HttpContext.Current.Handler;
        TextBox cnorGST = (TextBox)page.FindControl("txtbx_cnortin");

        DataAccess clsObjDataAccess = new DataAccess();
        string qrySelCnorGtinNo = "select TinNo1 from CnorMaster where CnorName = '" + Param1 + "'";
        DataTable dtqrySelCnorGtinNo = new DataTable();
        dtqrySelCnorGtinNo = clsObjDataAccess.GetDataTable(qrySelCnorGtinNo);
        if (dtqrySelCnorGtinNo.Rows.Count > 0)
        {
            cnorGST.Text = dtqrySelCnorGtinNo.Rows[0]["TinNo1"].ToString();
        }
    }
</code>```

When I am doing in debug mode

```<code>"dtqrySelCnorGtinNo.Rows[0]["TinNo1"].ToString();"
</code>```

this line shows the data

but when this data is giving to the textbox i.e. cnorGST.Text at that time it showing an error i.e. object reference not set to an instance of the object.

Please help me to solve this issues.

Thank You.

答:
A webmethod runs outside of the context of a page's lifecycle, so the controls don't exist on the server. You cannot access them.

But you are calling this webemethod from a clientside method. There you can assign the text. So get the value from the database in the webmethod and return it:

```<code>[WebMethod]
public static string GetCnorGSTNo(string Param1)
{
    DataAccess clsObjDataAccess = new DataAccess();
    string qrySelCnorGtinNo = "select TinNo1 from CnorMaster where CnorName = '" + Param1 + "'";
    return clsObjDataAccess.GetDataTable(qrySelCnorGtinNo).AsEnumerable()
       .ElementAtOrDefault(0)?.Field<string>("TinNo1");
}
</code>```

The javascript method that calls this webmethod assigns the returned text to txtbx_cnortin.Value.

Sir, can you give me this parameterized queries demo. I'm using sqlserver2005

Sure

```<code>[WebMethod]
public static string GetCnorGSTNo(string cnorName)
{
    using (var con = new SqlConnection("connection-string here"))
    using (var cmd = new SqlCommand("select TinNo1 from CnorMaster where CnorName = @CnorName", con))
    {
        cmd.Parameters.Add("@CnorName", SqlDbType.NVarChar).Value = cnorName;
        con.Open();
        object val = cmd.ExecuteScalar();
        return val == DBNull.Value ? "" : (string)val;
    }
}
</code>```

Since i don't know the db-type of the TinNo1-column you might have to change the (string)val.

Body:
when textbox getting the data through datatable object in static method at that time it shows the null value (i.e. showing error : object reference not set to an instance of the object). But when I am doing the debug mode at that time it shows the data in the datatable, so from that I am confusing that how in textbox it getting the null value.

Here is my code

[WebMethod]
    public static void GetCnorGSTNo(string Param1)
    {
        Page page = (Page)HttpContext.Current.Handler;
        TextBox cnorGST = (TextBox)page.FindControl("txtbx_cnortin");

        DataAccess clsObjDataAccess = new DataAccess();
        string qrySelCnorGtinNo = "select TinNo1 from CnorMaster where CnorName = '" + Param1 + "'";
        DataTable dtqrySelCnorGtinNo = new DataTable();
        dtqrySelCnorGtinNo = clsObjDataAccess.GetDataTable(qrySelCnorGtinNo);
        if (dtqrySelCnorGtinNo.Rows.Count > 0)
        {
            cnorGST.Text = dtqrySelCnorGtinNo.Rows[0]["TinNo1"].ToString();
        }
    }

When I am doing in debug mode

"dtqrySelCnorGtinNo.Rows[0]["TinNo1"].ToString();"

this line shows the data

but when this data is giving to the textbox i.e. cnorGST.Text at that time it showing an error i.e. object reference not set to an instance of the object.

Please help me to solve this issues.

Thank You.

Body:
A webmethod runs outside of the context of a page's lifecycle, so the controls don't exist on the server. You cannot access them.

But you are calling this webemethod from a clientside method. There you can assign the text. So get the value from the database in the webmethod and return it:

[WebMethod]
public static string GetCnorGSTNo(string Param1)
{
    DataAccess clsObjDataAccess = new DataAccess();
    string qrySelCnorGtinNo = "select TinNo1 from CnorMaster where CnorName = '" + Param1 + "'";
    return clsObjDataAccess.GetDataTable(qrySelCnorGtinNo).AsEnumerable()
       .ElementAtOrDefault(0)?.Field<string>("TinNo1");
}

The javascript method that calls this webmethod assigns the returned text to txtbx_cnortin.Value.

Sir, can you give me this parameterized queries demo. I'm using sqlserver2005

Sure

[WebMethod]
public static string GetCnorGSTNo(string cnorName)
{
    using (var con = new SqlConnection("connection-string here"))
    using (var cmd = new SqlCommand("select TinNo1 from CnorMaster where CnorName = @CnorName", con))
    {
        cmd.Parameters.Add("@CnorName", SqlDbType.NVarChar).Value = cnorName;
        con.Open();
        object val = cmd.ExecuteScalar();
        return val == DBNull.Value ? "" : (string)val;
    }
}

Since i don't know the db-type of the TinNo1-column you might have to change the (string)val.


答:
Day Name from Date in query

Try example :

s_date formate must be year-month-day)

```<code>SELECT DAYNAME( s_date ) AS DAY FROM `Table_name`
</code>```

put that DAYNAME() function in the query

Title: how to get day from mysql with codeigniter query

Body:
Day Name from Date in query

Try example :

s_date formate must be year-month-day)

SELECT DAYNAME( s_date ) AS DAY FROM `Table_name`

put that DAYNAME() function in the query


问:
AngularJS input with number get undefined when out of range
I am trying to validate custom input box as following

```<code><div class="form-group">
<label for="inputNetwork" class="control-label">{{'DNS_PRIMARY' | translate}}</label>
<div class="control-content">
    <p>
        <input type="number" integer min="1" max="223"
            class="ip-single-column" ng-model="network.dnsPrimary[0]" name="dnsP0" required ng-blur="dnsBlur('P', 0)"
            ng-class="{'has-error': networkForm.dnsP0.$invalid}" validate-dns>.
        <input type="number" integer min="0" max="255"
            class="ip-single-column" ng-model="network.dnsPrimary[1]" name="dnsP1" required ng-blur="dnsBlur('P', 1)"
            ng-class="{'has-error': networkForm.dnsP1.$invalid}" validate-dns>.
        <input type="number" integer min="0" max="255"
            class="ip-single-column" ng-model="network.dnsPrimary[2]" name="dnsP2" required ng-blur="dnsBlur('P', 2)"
            ng-class="{'has-error': networkForm.dnsP2.$invalid}" validate-dns>.
        <input type="number" integer min="0" max="254"
            class="ip-single-column" ng-model="network.dnsPrimary[3]" name="dnsP3" required ng-blur="dnsBlur('P', 3)"
            ng-class="{'has-error': networkForm.dnsP3.$invalid}" validate-dns>
    </p>
</div>
</code>```

```<code>       $scope.dnsBlur= function(section, pos) {

        var elem = $scope.network.dnsPrimary;
        var i = pos;
        if(section.endsWith('P')) {
            // primary
            switch(i) {
                case 0:
                    if (angular.isUndefined(elem[i]) || (elem[i] < 1 && elem[i] > 223))
                        elem[i] = $scope.defaultDns[i];
                    break;
                case 1:
                    // if (!elem[i] || (elem[i] < 0 && elem[i] > 254))
                    if (angular.isUndefined(elem[i]) || (elem[i] < 0 && elem[i] > 254))
                        elem[i] = $scope.defaultDns[i];
                    break;
                case 2:
                    if (angular.isUndefined(elem[i]) || (elem[i] < 0 && elem[i] > 255))
                        elem[i] = $scope.defaultDns[i];
                    break;
                case 3:
                    if (angular.isUndefined(elem[i]) || (elem[i] < 0 && elem[i] > 254))
                        elem[i] = $scope.defaultDns[i];
                    break;
            }
        }
    }

}]).directive('validateDns', ['$rootScope',
function($rootScope) {
    function link($scope, elem, attrs, c) {
        $scope.$watch(attrs.ngModel, function(newValue, oldValue) {
            c.$setValidity('outOfRange', true);

            switch(c.$name.charAt(c.$name.length - 1)) {
                case 0:
                    if (!$scope.network.dnsPrimary[i] || ($scope.network.dnsPrimary[i] < 1 && $scope.network.dnsPrimary[i] > 223))
                        c.$setValidity('outOfRange', false);
                    break;
                case 1:
                    if (!$scope.network.dnsPrimary[i] || ($scope.network.dnsPrimary[i] < 0 && $scope.network.dnsPrimary[i] > 255))
                        c.$setValidity('outOfRange', false);
                    break;
                case 2:
                    if (!$scope.network.dnsPrimary[i] || ($scope.network.dnsPrimary[i] < 0 && $scope.network.dnsPrimary[i] > 255))
                        c.$setValidity('outOfRange', false);
                    break;
                case 3:
                    if (!$scope.network.dnsPrimary[i] || ($scope.network.dnsPrimary[i] < 0 && $scope.network.dnsPrimary[i] > 254))
                        c.$setValidity('outOfRange', false);
                    break;
            }

        });
    }
    return {
        require: 'ngModel',
        link: link
    };
}
</code>```

But when I trying to get input number in Blur() function.

It will get undefined when the input out or range. For example, input 999 but get undefined.
Is it anyway to get 999 in Blur()?

答:
You have a problem in Blur or in the others decorators in there. The value of the field should be the actual value otherwise even if it is out of the specified range.

<form action="#" onsubmit="console.log(this.quantity.value);return false;">
  Quantity:
  <input type="number" name="quantity"
   min="0" max="100" step="10" value="30" onblur="console.log(this.value);">
  <input type="submit">
</form>```

Body:
I am trying to validate custom input box as following

{{'DNS_PRIMARY' | translate}}

        <input type="number" integer min="1" max="223"
            class="ip-single-column" ng-model="network.dnsPrimary[0]" name="dnsP0" required ng-blur="dnsBlur('P', 0)"
            ng-class="{'has-error': networkForm.dnsP0.$invalid}" validate-dns>.
        <input type="number" integer min="0" max="255"
            class="ip-single-column" ng-model="network.dnsPrimary[1]" name="dnsP1" required ng-blur="dnsBlur('P', 1)"
            ng-class="{'has-error': networkForm.dnsP1.$invalid}" validate-dns>.
        <input type="number" integer min="0" max="255"
            class="ip-single-column" ng-model="network.dnsPrimary[2]" name="dnsP2" required ng-blur="dnsBlur('P', 2)"
            ng-class="{'has-error': networkForm.dnsP2.$invalid}" validate-dns>.
        <input type="number" integer min="0" max="254"
            class="ip-single-column" ng-model="network.dnsPrimary[3]" name="dnsP3" required ng-blur="dnsBlur('P', 3)"
            ng-class="{'has-error': networkForm.dnsP3.$invalid}" validate-dns>

       $scope.dnsBlur= function(section, pos) {

        var elem = $scope.network.dnsPrimary;
        var i = pos;
        if(section.endsWith('P')) {
            // primary
            switch(i) {
                case 0:
                    if (angular.isUndefined(elem[i]) || (elem[i] < 1 && elem[i] > 223))
                        elem[i] = $scope.defaultDns[i];
                    break;
                case 1:
                    // if (!elem[i] || (elem[i] < 0 && elem[i] > 254))
                    if (angular.isUndefined(elem[i]) || (elem[i] < 0 && elem[i] > 254))
                        elem[i] = $scope.defaultDns[i];
                    break;
                case 2:
                    if (angular.isUndefined(elem[i]) || (elem[i] < 0 && elem[i] > 255))
                        elem[i] = $scope.defaultDns[i];
                    break;
                case 3:
                    if (angular.isUndefined(elem[i]) || (elem[i] < 0 && elem[i] > 254))
                        elem[i] = $scope.defaultDns[i];
                    break;
            }
        }
    }

}]).directive('validateDns', ['$rootScope',
function($rootScope) {
    function link($scope, elem, attrs, c) {
        $scope.$watch(attrs.ngModel, function(newValue, oldValue) {
            c.$setValidity('outOfRange', true);

            switch(c.$name.charAt(c.$name.length - 1)) {
                case 0:
                    if (!$scope.network.dnsPrimary[i] || ($scope.network.dnsPrimary[i] < 1 && $scope.network.dnsPrimary[i] > 223))
                        c.$setValidity('outOfRange', false);
                    break;
                case 1:
                    if (!$scope.network.dnsPrimary[i] || ($scope.network.dnsPrimary[i] < 0 && $scope.network.dnsPrimary[i] > 255))
                        c.$setValidity('outOfRange', false);
                    break;
                case 2:
                    if (!$scope.network.dnsPrimary[i] || ($scope.network.dnsPrimary[i] < 0 && $scope.network.dnsPrimary[i] > 255))
                        c.$setValidity('outOfRange', false);
                    break;
                case 3:
                    if (!$scope.network.dnsPrimary[i] || ($scope.network.dnsPrimary[i] < 0 && $scope.network.dnsPrimary[i] > 254))
                        c.$setValidity('outOfRange', false);
                    break;
            }

        });
    }
    return {
        require: 'ngModel',
        link: link
    };
}

But when I trying to get input number in Blur() function.

It will get undefined when the input out or range. For example, input 999 but get undefined.
Is it anyway to get 999 in Blur()?


问:
Why does: string st = "" + 12; work in c# without conversion?
This is super dumb, but I've googled and checked references and I just cannot find an answer... Why can an int or float etc be added as part of a string without converstion but not on it's own? that is:

while this work fine:

```<code> string st = "" + 12;
</code>```

this doesn't (of course):

```<code> string st = 12;
</code>```

Where is the magic here? I know it works I just want to know WHY it works and how I control HOW the conversion is done?

答:
Because the first is an expression and there C# makes an implicit conversion.

The second is an assignement with a static value, and the static value has no methods to be called.

As long as the value to be asigned is a variable or expression return there will be a toSting method to call.

ContentLicense: CC BY-SA 2.5

Body:
This is super dumb, but I've googled and checked references and I just cannot find an answer... Why can an int or float etc be added as part of a string without converstion but not on it's own? that is:

while this work fine:

 string st = "" + 12;

this doesn't (of course):

 string st = 12;

Where is the magic here? I know it works I just want to know WHY it works and how I control HOW the conversion is done?


问:
How do I return a reference to something owned and alive?
How do I correctly return a reference in the set function in the following code? I do understand that the variable set goes out of scope when the block ends, but the array it is referencing is owned and alive. The attempt with the lifetime 'b was futile.

```<code>#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
struct Appearance<'a> {
    identity:   &'a u64,
    role:       &'a str
}

#[derive(Clone, Copy, Debug)]
enum Dereference<'a> {
    Dereference1ary {set: [&'a Appearance<'a>;1]},
    Dereference2ary {set: [&'a Appearance<'a>;2]},
}
impl<'a, 'b> Dereference<'a> {
    fn set(&self) -> &'b [&'a Appearance<'a>] {
        match *self {
            Dereference::Dereference1ary{set} => &set,
            Dereference::Dereference2ary{set} => &set
        }
    }
}

fn main() {
    let r = "hair_color";
    let i1 = 42;
    let i2 = 43;
    let a1 = Appearance{identity: &i1, role: r};
    let a2 = Appearance{identity: &i2, role: r};
    let d1 = Dereference::Dereference1ary{set: [&a1]};
    let d2 = Dereference::Dereference2ary{set: [&a1, &a2]};
    let list: Vec<Dereference> = vec!(d1, d2);
    println!("{:?}", list);
    println!("{:?}", d1.set());
}
</code>```

There is a playground set up here: https://play.rust-lang.org/?gist=fd528ebd054a9ce96004c8608166f9ac&version=stable&backtrace=0

答:
The issue is that Derefencece1ary{set} copies set and takes a reference to the copy. What you want is to reference the set field directly, by using Dereference1ary{ ref set }

```<code>impl<'a> Dereference<'a> {
    fn set(&self) -> &[&'a Appearance<'a>] {
        match *self {
            Dereference::Dereference1ary{ref set} => set,
            Dereference::Dereference2ary{ref set} => set,
        }
    }
}
</code>```

Note that your lifetime 'b is superfluous, but if you want it explicitly, you can write

```<code>fn set<'b>(&'b self) -> &'b [&'a Appearance<'a>]
</code>```

because you want to borrow a part of the self object, so the lifetimes need to match.

Body:
How do I correctly return a reference in the set function in the following code? I do understand that the variable set goes out of scope when the block ends, but the array it is referencing is owned and alive. The attempt with the lifetime 'b was futile.

#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
struct Appearance<'a> {
    identity:   &'a u64,
    role:       &'a str
}

#[derive(Clone, Copy, Debug)]
enum Dereference<'a> {
    Dereference1ary {set: [&'a Appearance<'a>;1]},
    Dereference2ary {set: [&'a Appearance<'a>;2]},
}
impl<'a, 'b> Dereference<'a> {
    fn set(&self) -> &'b [&'a Appearance<'a>] {
        match *self {
            Dereference::Dereference1ary{set} => &set,
            Dereference::Dereference2ary{set} => &set
        }
    }
}

fn main() {
    let r = "hair_color";
    let i1 = 42;
    let i2 = 43;
    let a1 = Appearance{identity: &i1, role: r};
    let a2 = Appearance{identity: &i2, role: r};
    let d1 = Dereference::Dereference1ary{set: [&a1]};
    let d2 = Dereference::Dereference2ary{set: [&a1, &a2]};
    let list: Vec<Dereference> = vec!(d1, d2);
    println!("{:?}", list);
    println!("{:?}", d1.set());
}

There is a playground set up here: https://play.rust-lang.org/?gist=fd528ebd054a9ce96004c8608166f9ac&version=stable&backtrace=0

Body:
The issue is that Derefencece1ary{set} copies set and takes a reference to the copy. What you want is to reference the set field directly, by using Dereference1ary{ ref set }

impl<'a> Dereference<'a> {
    fn set(&self) -> &[&'a Appearance<'a>] {
        match *self {
            Dereference::Dereference1ary{ref set} => set,
            Dereference::Dereference2ary{ref set} => set,
        }
    }
}

Note that your lifetime 'b is superfluous, but if you want it explicitly, you can write

fn set<'b>(&'b self) -> &'b [&'a Appearance<'a>]

because you want to borrow a part of the self object, so the lifetimes need to match.


问:
What does graph argument in tf.Session() do?
I am having trouble understanding the graph argument in the tf.Session(). I tried looking up at the TensorFlow website :link but couldn't understand much.

I am trying to find out the different between tf.Session() and tf.Session(graph=some_graph_inserted_here).

Question Context

Code A (Not Working):

```<code>def predict():
    with tf.name_scope("predict"):
        with tf.Session() as sess:
            saver = tf.train.import_meta_graph("saved_models/testing.meta")
            saver.restore(sess, "saved_models/testing")
            loaded_graph = tf.get_default_graph()
            output_ = loaded_graph.get_tensor_by_name('loss/network/output_layer/BiasAdd:0')
            _x = loaded_graph.get_tensor_by_name('x:0')
            print sess.run(output_, feed_dict={_x: np.array([12003]).reshape([-1, 1])})
</code>```

This code gives the following error: ValueError: cannot add op with name hidden_layer1/kernel/Adam as that name is already used when trying to load the graph at saver = tf.train.import_meta_graph("saved_models/testing.meta")

Code B (Working):

```<code>def predict():
    with tf.name_scope("predict"):
        loaded_graph = tf.Graph()
        with tf.Session(graph=loaded_graph) as sess:
            saver = tf.train.import_meta_graph("saved_models/testing.meta")
            saver.restore(sess, "saved_models/testing")
            output_ = loaded_graph.get_tensor_by_name('loss/network/output_layer/BiasAdd:0')
            _x = loaded_graph.get_tensor_by_name('x:0')
            print sess.run(output_, feed_dict={_x: np.array([12003]).reshape([-1, 1])})
</code>```

The codes does not work if I replace loaded_graph = tf.Graph() with loaded_graph = tf.get_default_graph(). Why?

Full Code if it helps:
 (https://gist.github.com/duemaster/f8cf05c0923ebabae476b83e895619ab)

答:
When you create a Session you're placing a graph into a specified device.

If no graph is specified, the Session constructor tries to build a graph using the default one (that you can get using tf.get_default_graph).

Your code A doesn't work because in the current session already exists a graph and that graph already contains the same exact node you're trying to import.

Your code B works because you're placing into the Session a new empyt graph (created with tf.Graph()): when you import the graph definition there's no collision among the existing nodes in the current session (that are 0, because the graph is empty) and the ones you're importing

Body:
I am having trouble understanding the graph argument in the tf.Session(). I tried looking up at the TensorFlow website :link but couldn't understand much.

I am trying to find out the different between tf.Session() and tf.Session(graph=some_graph_inserted_here).

Question Context

Code A (Not Working):

def predict():
    with tf.name_scope("predict"):
        with tf.Session() as sess:
            saver = tf.train.import_meta_graph("saved_models/testing.meta")
            saver.restore(sess, "saved_models/testing")
            loaded_graph = tf.get_default_graph()
            output_ = loaded_graph.get_tensor_by_name('loss/network/output_layer/BiasAdd:0')
            _x = loaded_graph.get_tensor_by_name('x:0')
            print sess.run(output_, feed_dict={_x: np.array([12003]).reshape([-1, 1])})

This code gives the following error: ValueError: cannot add op with name hidden_layer1/kernel/Adam as that name is already used when trying to load the graph at saver = tf.train.import_meta_graph("saved_models/testing.meta")

Code B (Working):

def predict():
    with tf.name_scope("predict"):
        loaded_graph = tf.Graph()
        with tf.Session(graph=loaded_graph) as sess:
            saver = tf.train.import_meta_graph("saved_models/testing.meta")
            saver.restore(sess, "saved_models/testing")
            output_ = loaded_graph.get_tensor_by_name('loss/network/output_layer/BiasAdd:0')
            _x = loaded_graph.get_tensor_by_name('x:0')
            print sess.run(output_, feed_dict={_x: np.array([12003]).reshape([-1, 1])})

The codes does not work if I replace loaded_graph = tf.Graph() with loaded_graph = tf.get_default_graph(). Why?

Full Code if it helps:
 (https://gist.github.com/duemaster/f8cf05c0923ebabae476b83e895619ab)


问:
android recyclerview load more item upon scrolling using volley
Please help me out to load more data from the server upon scrolling my RecyclerView . Here I have successfully created RecyclerView by loading data from my Mysql server by using volley string request.

Here is my code.

```<code>    private void populateRecycleView() {
    if (Utility.checkNetworkConnection(this)) {
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("Searching...");
        progressDialog.setMessage("Searching for the blood donor. Please wait a moment.");
        progressDialog.setCancelable(false);
        progressDialog.show();
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constants.GET_DONORS_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        progressDialog.dismiss();
                        try {
                            JSONArray jsonArray = new JSONArray(response);
                            int count = 0;
                            while (count < jsonArray.length()) {
                                JSONObject jsonObject = jsonArray.getJSONObject(count);

                                String firstName = jsonObject.getString("fName");
                                String secondName = jsonObject.getString("sName");
                                String email = jsonObject.getString("emailid");
                                String password = jsonObject.getString("pass");
                                String mobile = jsonObject.getString("mobile");
                                String bloodRt = jsonObject.getString("blood");
                                String age = jsonObject.getString("age");
                                String gender = jsonObject.getString("gender");
                                String country = jsonObject.getString("country");
                                String location = jsonObject.getString("location");
                                String latitude = jsonObject.getString("latitude");
                                String longitude = jsonObject.getString("longitude");
                                String profilePicFIleName = jsonObject.getString("picname");
                                String profilePicURL = jsonObject.getString("pic");

                                Donor donor = new Donor(firstName, secondName, email, password, mobile, bloodRt, age, gender,
                                        country, location, latitude, longitude, profilePicFIleName, profilePicURL);
                                donorsList.add(donor);
                                count++;
                            }
                            donorsAdapter = new DonorsAdapter(FindDonorResult.this, donorsList);
                            recyclerView = (RecyclerView) findViewById(R.id.rv_search_result_donor);
                            recyclerView.setHasFixedSize(true);
                            recyclerView.setLayoutManager(new LinearLayoutManager(FindDonorResult.this));
                            recyclerView.setItemAnimator(new DefaultItemAnimator());
                            recyclerView.setAdapter(donorsAdapter);

                            donorsAdapter.notifyDataSetChanged();

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        progressDialog.dismiss();
                        Toast.makeText(FindDonorResult.this, "Active data network is not available.", Toast.LENGTH_LONG).show();

                    }
                }
        ) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("bloodGroup", bloodGroup);
                return params;
            }
        };
        NetworkRequestSingleTon.getOurInstance(this).addToRequestQue(stringRequest);
    } else {
        Utility.checkNetworkConnectionFound(this);
    }
}
</code>```

And this is my RecyclerView  adapter...

```<code>public class DonorsAdapter extends RecyclerView.Adapter<DonorsAdapter.CustomViewHolder> {

private Context context;
private ArrayList<Donor> donorList;
private String bloodGroup;

public DonorsAdapter(Context context, ArrayList<Donor> donorList) {
    this.context = context;
    this.donorList = donorList;
}

@Override
public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rv_blood_donors_result,
            parent, false);
    return new CustomViewHolder(view);
}

@Override
public void onBindViewHolder(CustomViewHolder holder, int position) {

    final Donor donor = donorList.get(position);
    String displayName = donor.getFirstName() + " " + donor.getSecondName();
    holder.tvDisplayName.setText(displayName);
    holder.tvEmailID.setText(donor.getEmail());

    String userProfileURL = donor.getProfilePicURL();
    if (!userProfileURL.equals("")) {
        Picasso.with(context).load(userProfileURL).resize(80, 80).centerCrop().
                into(holder.ivProfilePic);
    } else {
        holder.ivProfilePic.setImageResource(R.drawable.ic_person_white_24dp);
    }

    bloodGroup = donor.getBloodGroup();
    if (bloodGroup.equals("A+"))
        holder.ivBloodTypeDisplay.setImageResource(R.drawable.a_);
    else if (bloodGroup.equals("A-"))
        holder.ivBloodTypeDisplay.setImageResource(R.drawable.a_negative);
    else if (bloodGroup.equals("B+"))
        holder.ivBloodTypeDisplay.setImageResource(R.drawable.b_positive);
    else if (bloodGroup.equals("B-"))
        holder.ivBloodTypeDisplay.setImageResource(R.drawable.b_negative);
    else if (bloodGroup.equals("O+"))
        holder.ivBloodTypeDisplay.setImageResource(R.drawable.o_positive);
    else if (bloodGroup.equals("O-"))
        holder.ivBloodTypeDisplay.setImageResource(R.drawable.o_negative);
    else if (bloodGroup.equals("AB+"))
        holder.ivBloodTypeDisplay.setImageResource(R.drawable.ab_positive);
    else if (bloodGroup.equals("AB-"))
        holder.ivBloodTypeDisplay.setImageResource(R.drawable.ab_negative);

    if(Utility.isNetworkEnabled){
        holder.constraintLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, DisplayDonorDetails.class);
                intent.putExtra("donor", donor);
                context.startActivity(intent);
            }
        });
    }else {
        Toast.makeText(context, "Network not available.", Toast.LENGTH_SHORT).show();
    }

}

@Override
public int getItemCount() {
    if(donorList != null){
        return donorList.size();
    }else {
        return 0;
    }
}

public class CustomViewHolder extends RecyclerView.ViewHolder {
    ImageView ivProfilePic, ivBloodTypeDisplay, ivArrow;
    TextView tvDisplayName;
    TextView tvEmailID;
    ConstraintLayout constraintLayout;

    public CustomViewHolder(View itemView) {
        super(itemView);
        ivProfilePic = (ImageView) itemView.findViewById(R.id.civ_user_profile_picture);
        ivBloodTypeDisplay = (ImageView) itemView.findViewById(R.id.civ_user_blood_type_display);
        ivArrow = (ImageView) itemView.findViewById(R.id.civ_arrow);
        tvDisplayName = (TextView) itemView.findViewById(R.id.tvUserNameOnRV);
        tvEmailID = (TextView) itemView.findViewById(R.id.tvEmailDisplayOnRV);
        constraintLayout = (ConstraintLayout) itemView.findViewById(R.id.recycle_view_item_container);
    }
}

}
</code>```

答:
Populate your donorsAdapter only with the 50 first elements of your donorsList, create a function that save the position of the latest element displayed and add other 50 donors to your adapter starting from the latest position saved when you need it.

Hope it helps.

EDIT

First create an emptyList:

```<code>List<Donor> subElements = new ArrayList<>();
</code>```

and pass it to your adapter:

```<code>donorsAdapter = new DonorsAdapter(FindDonorResult.this, subElements);
</code>```

Now you can create a method like this (you can call in onClick event for example):

```<code>private int LAST_POSITION = 0;
private int DONORS_NUM_TOSHOW = 50;

public void showMoreDonors(){
    if(donarsList.size() > Last_postion+50){
        List<Donor> tempList = new ArrayList<Donor>(donorsList.subList(Last_postion,Last_postion+DONORS_NUM_TOSHOW));

        for(Donor a : tempList){
            subElements.add(a);
        }
        Last_postion += DONORS_NUM_TOSHOW;
        donorsAdapter.notifyDataSetChanged();
    }else{
        List<Donor> tempList = new ArrayList<Donor>(donorsList.subList(Last_postion,donorsList.size()));
        for(Donor a : tempList){
            subElements.add(a);
        }
        donorsAdapter.notifyDataSetChanged();
    }
}
</code>```

Remember to check when donorsList is over.
I didn't test it, but i hope it is usefull to understand the idea.

Body:
Please help me out to load more data from the server upon scrolling my RecyclerView . Here I have successfully created RecyclerView by loading data from my Mysql server by using volley string request.

Here is my code.

    private void populateRecycleView() {
    if (Utility.checkNetworkConnection(this)) {
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("Searching...");
        progressDialog.setMessage("Searching for the blood donor. Please wait a moment.");
        progressDialog.setCancelable(false);
        progressDialog.show();
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constants.GET_DONORS_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        progressDialog.dismiss();
                        try {
                            JSONArray jsonArray = new JSONArray(response);
                            int count = 0;
                            while (count < jsonArray.length()) {
                                JSONObject jsonObject = jsonArray.getJSONObject(count);

                                String firstName = jsonObject.getString("fName");
                                String secondName = jsonObject.getString("sName");
                                String email = jsonObject.getString("emailid");
                                String password = jsonObject.getString("pass");
                                String mobile = jsonObject.getString("mobile");
                                String bloodRt = jsonObject.getString("blood");
                                String age = jsonObject.getString("age");
                                String gender = jsonObject.getString("gender");
                                String country = jsonObject.getString("country");
                                String location = jsonObject.getString("location");
                                String latitude = jsonObject.getString("latitude");
                                String longitude = jsonObject.getString("longitude");
                                String profilePicFIleName = jsonObject.getString("picname");
                                String profilePicURL = jsonObject.getString("pic");

                                Donor donor = new Donor(firstName, secondName, email, password, mobile, bloodRt, age, gender,
                                        country, location, latitude, longitude, profilePicFIleName, profilePicURL);
                                donorsList.add(donor);
                                count++;
                            }
                            donorsAdapter = new DonorsAdapter(FindDonorResult.this, donorsList);
                            recyclerView = (RecyclerView) findViewById(R.id.rv_search_result_donor);
                            recyclerView.setHasFixedSize(true);
                            recyclerView.setLayoutManager(new LinearLayoutManager(FindDonorResult.this));
                            recyclerView.setItemAnimator(new DefaultItemAnimator());
                            recyclerView.setAdapter(donorsAdapter);

                            donorsAdapter.notifyDataSetChanged();

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        progressDialog.dismiss();
                        Toast.makeText(FindDonorResult.this, "Active data network is not available.", Toast.LENGTH_LONG).show();

                    }
                }
        ) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("bloodGroup", bloodGroup);
                return params;
            }
        };
        NetworkRequestSingleTon.getOurInstance(this).addToRequestQue(stringRequest);
    } else {
        Utility.checkNetworkConnectionFound(this);
    }
}

And this is my RecyclerView  adapter...

public class DonorsAdapter extends RecyclerView.Adapter<DonorsAdapter.CustomViewHolder> {

private Context context;
private ArrayList<Donor> donorList;
private String bloodGroup;

public DonorsAdapter(Context context, ArrayList<Donor> donorList) {
    this.context = context;
    this.donorList = donorList;
}

@Override
public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rv_blood_donors_result,
            parent, false);
    return new CustomViewHolder(view);
}

@Override
public void onBindViewHolder(CustomViewHolder holder, int position) {

    final Donor donor = donorList.get(position);
    String displayName = donor.getFirstName() + " " + donor.getSecondName();
    holder.tvDisplayName.setText(displayName);
    holder.tvEmailID.setText(donor.getEmail());

    String userProfileURL = donor.getProfilePicURL();
    if (!userProfileURL.equals("")) {
        Picasso.with(context).load(userProfileURL).resize(80, 80).centerCrop().
                into(holder.ivProfilePic);
    } else {
        holder.ivProfilePic.setImageResource(R.drawable.ic_person_white_24dp);
    }

    bloodGroup = donor.getBloodGroup();
    if (bloodGroup.equals("A+"))
        holder.ivBloodTypeDisplay.setImageResource(R.drawable.a_);
    else if (bloodGroup.equals("A-"))
        holder.ivBloodTypeDisplay.setImageResource(R.drawable.a_negative);
    else if (bloodGroup.equals("B+"))
        holder.ivBloodTypeDisplay.setImageResource(R.drawable.b_positive);
    else if (bloodGroup.equals("B-"))
        holder.ivBloodTypeDisplay.setImageResource(R.drawable.b_negative);
    else if (bloodGroup.equals("O+"))
        holder.ivBloodTypeDisplay.setImageResource(R.drawable.o_positive);
    else if (bloodGroup.equals("O-"))
        holder.ivBloodTypeDisplay.setImageResource(R.drawable.o_negative);
    else if (bloodGroup.equals("AB+"))
        holder.ivBloodTypeDisplay.setImageResource(R.drawable.ab_positive);
    else if (bloodGroup.equals("AB-"))
        holder.ivBloodTypeDisplay.setImageResource(R.drawable.ab_negative);

    if(Utility.isNetworkEnabled){
        holder.constraintLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, DisplayDonorDetails.class);
                intent.putExtra("donor", donor);
                context.startActivity(intent);
            }
        });
    }else {
        Toast.makeText(context, "Network not available.", Toast.LENGTH_SHORT).show();
    }

}

@Override
public int getItemCount() {
    if(donorList != null){
        return donorList.size();
    }else {
        return 0;
    }
}

public class CustomViewHolder extends RecyclerView.ViewHolder {
    ImageView ivProfilePic, ivBloodTypeDisplay, ivArrow;
    TextView tvDisplayName;
    TextView tvEmailID;
    ConstraintLayout constraintLayout;

    public CustomViewHolder(View itemView) {
        super(itemView);
        ivProfilePic = (ImageView) itemView.findViewById(R.id.civ_user_profile_picture);
        ivBloodTypeDisplay = (ImageView) itemView.findViewById(R.id.civ_user_blood_type_display);
        ivArrow = (ImageView) itemView.findViewById(R.id.civ_arrow);
        tvDisplayName = (TextView) itemView.findViewById(R.id.tvUserNameOnRV);
        tvEmailID = (TextView) itemView.findViewById(R.id.tvEmailDisplayOnRV);
        constraintLayout = (ConstraintLayout) itemView.findViewById(R.id.recycle_view_item_container);
    }
}

}

Body:
Populate your donorsAdapter only with the 50 first elements of your donorsList, create a function that save the position of the latest element displayed and add other 50 donors to your adapter starting from the latest position saved when you need it.

Hope it helps.

EDIT

First create an emptyList:

List<Donor> subElements = new ArrayList<>();

and pass it to your adapter:

donorsAdapter = new DonorsAdapter(FindDonorResult.this, subElements);

Now you can create a method like this (you can call in onClick event for example):

private int LAST_POSITION = 0;
private int DONORS_NUM_TOSHOW = 50;

public void showMoreDonors(){
    if(donarsList.size() > Last_postion+50){
        List<Donor> tempList = new ArrayList<Donor>(donorsList.subList(Last_postion,Last_postion+DONORS_NUM_TOSHOW));

        for(Donor a : tempList){
            subElements.add(a);
        }
        Last_postion += DONORS_NUM_TOSHOW;
        donorsAdapter.notifyDataSetChanged();
    }else{
        List<Donor> tempList = new ArrayList<Donor>(donorsList.subList(Last_postion,donorsList.size()));
        for(Donor a : tempList){
            subElements.add(a);
        }
        donorsAdapter.notifyDataSetChanged();
    }
}

Remember to check when donorsList is over.
I didn't test it, but i hope it is usefull to understand the idea.


问:
Send Intent from Activity to another Activity with RecyclerView
I have an Activity where I enter a phone number and a message and when I click on the send Button, I want to display the message and number I entered in the layout of another Activity which has a RecyclerView. I have tried to use an Intent but it displays "NUMBER" and "NUMBER" in both TextViews.
This is some of the code below.

```<code>public class NewMessageActivity extends AppCompatActivity {

private String message, number;
private EditText mComposeMessage, mPhoneNumber;
private Button mSendButton, mCancelButton;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.new_message_layout);

    mPhoneNumber = (EditText) findViewById(R.id.phone_number_et);
    mComposeMessage = (EditText) findViewById(R.id.compose_et);
    mSendButton = (Button) findViewById(R.id.send_button);
    mCancelButton = (Button) findViewById(R.id.cancel_button);

    number = mPhoneNumber.getText().toString();
    message = mComposeMessage.getText().toString();

    mSendButton.setOnClickListener(mButtonClickListener);
    mCancelButton.setOnClickListener(mButtonClickListener);
}

private View.OnClickListener mButtonClickListener = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        int id = v.getId();

        switch (id) {
            case R.id.send_button:
                Intent intent = new Intent(v.getContext(), SentActivity.class);
                intent.putExtra(getString(R.string.key_message), message);
                intent.putExtra("NUMBER", number);
                startActivity(intent);
                break;

            case R.id.cancel_button:
                break;
        }
    }
};

}
</code>```

This is my Adapter

```<code>public class SentMessageAdapter extends RecyclerView.Adapter<SentMessageAdapter.MessageHolder> {
private List<String> mMessages;

public static class MessageHolder extends RecyclerView.ViewHolder {
    private TextView mSentMessageTv;
    private TextView mRecipientNumberTv;
    private TextView mRecipientTv;

    public MessageHolder(View v){
        super(v);
        mSentMessageTv = (TextView) v.findViewById(R.id.sent_message_tv);
        mRecipientNumberTv = (TextView) v.findViewById(R.id.recipient_number_tv);
        mRecipientTv = (TextView) v.findViewById(R.id.recipient_tv);
    }
}

public SentMessageAdapter(List<String> messages){
    mMessages = messages;
}

@Override
public MessageHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.sent_list_item, parent, false);
    MessageHolder vH = new MessageHolder(v);
    return vH;
}

@Override
public void onBindViewHolder(MessageHolder holder, int position) {
    holder.mSentMessageTv.setText(mMessages.get(position));
    holder.mRecipientNumberTv.setText(mMessages.get(position));
    holder.mRecipientTv.setText(R.string.to);
}

@Override
public int getItemCount() {
    return mMessages.size();
}

}
</code>```

Activity where the text should be displayed

```<code>public class SentActivity extends AppCompatActivity {

private static final String LOG_TAG = SentActivity.class.getSimpleName();

private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;

final ArrayList<String> messages = new ArrayList<>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.message_recycler_list);

    Bundle extras = getIntent().getExtras();
    String message = null;

    if (extras != null){
        message = extras.getString(String.valueOf(R.string.key_message), String.valueOf("NUMBER"));
    }

    if (message == null){
        message = "text";
    }
    Log.d(LOG_TAG, message);
    messages.add(0, message);

    Toast.makeText(this, message, Toast.LENGTH_SHORT).show();

    mRecyclerView = (RecyclerView) findViewById(R.id.message_recycler_view);
    mLayoutManager = new LinearLayoutManager(this);
    mRecyclerView.setLayoutManager(mLayoutManager);

    mAdapter = new SentMessageAdapter(messages);
    mRecyclerView.setAdapter(mAdapter);
    mAdapter.notifyDataSetChanged();
}

}
</code>```

Layout for the Activity

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp">

<TextView
    android:id="@+id/sent_message_tv"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="4dp"
    tools:text="Hello world"/>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="4dp"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/recipient_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        tools:text="@string/to"/>

    <TextView
        android:id="@+id/recipient_number_tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="4dp"
        android:paddingStart="4dp"
        android:paddingRight="4dp"
        android:paddingEnd="4dp" />
</LinearLayout>

</LinearLayout>
</code>```

答:
Get message and number value in onClick method not onCreate

```<code>switch (id) {
        case R.id.send_button:
number = mPhoneNumber.getText().toString();
message = mComposeMessage.getText().toString();

Intent intent = new Intent(v.getContext(), SentActivity.class);
            intent.putExtra(getString(R.string.key_message), message);
            intent.putExtra("NUMBER", number);
            startActivity(intent);
            break;
}
</code>```

Hope this will help you.

Body:
I have an Activity where I enter a phone number and a message and when I click on the send Button, I want to display the message and number I entered in the layout of another Activity which has a RecyclerView. I have tried to use an Intent but it displays "NUMBER" and "NUMBER" in both TextViews.
This is some of the code below.

public class NewMessageActivity extends AppCompatActivity {

private String message, number;
private EditText mComposeMessage, mPhoneNumber;
private Button mSendButton, mCancelButton;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.new_message_layout);

    mPhoneNumber = (EditText) findViewById(R.id.phone_number_et);
    mComposeMessage = (EditText) findViewById(R.id.compose_et);
    mSendButton = (Button) findViewById(R.id.send_button);
    mCancelButton = (Button) findViewById(R.id.cancel_button);

    number = mPhoneNumber.getText().toString();
    message = mComposeMessage.getText().toString();

    mSendButton.setOnClickListener(mButtonClickListener);
    mCancelButton.setOnClickListener(mButtonClickListener);
}

private View.OnClickListener mButtonClickListener = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        int id = v.getId();

        switch (id) {
            case R.id.send_button:
                Intent intent = new Intent(v.getContext(), SentActivity.class);
                intent.putExtra(getString(R.string.key_message), message);
                intent.putExtra("NUMBER", number);
                startActivity(intent);
                break;

            case R.id.cancel_button:
                break;
        }
    }
};

}

This is my Adapter

public class SentMessageAdapter extends RecyclerView.Adapter<SentMessageAdapter.MessageHolder> {
private List<String> mMessages;

public static class MessageHolder extends RecyclerView.ViewHolder {
    private TextView mSentMessageTv;
    private TextView mRecipientNumberTv;
    private TextView mRecipientTv;

    public MessageHolder(View v){
        super(v);
        mSentMessageTv = (TextView) v.findViewById(R.id.sent_message_tv);
        mRecipientNumberTv = (TextView) v.findViewById(R.id.recipient_number_tv);
        mRecipientTv = (TextView) v.findViewById(R.id.recipient_tv);
    }
}

public SentMessageAdapter(List<String> messages){
    mMessages = messages;
}

@Override
public MessageHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.sent_list_item, parent, false);
    MessageHolder vH = new MessageHolder(v);
    return vH;
}

@Override
public void onBindViewHolder(MessageHolder holder, int position) {
    holder.mSentMessageTv.setText(mMessages.get(position));
    holder.mRecipientNumberTv.setText(mMessages.get(position));
    holder.mRecipientTv.setText(R.string.to);
}

@Override
public int getItemCount() {
    return mMessages.size();
}

}

Activity where the text should be displayed

public class SentActivity extends AppCompatActivity {

private static final String LOG_TAG = SentActivity.class.getSimpleName();

private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;

final ArrayList<String> messages = new ArrayList<>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.message_recycler_list);

    Bundle extras = getIntent().getExtras();
    String message = null;

    if (extras != null){
        message = extras.getString(String.valueOf(R.string.key_message), String.valueOf("NUMBER"));
    }

    if (message == null){
        message = "text";
    }
    Log.d(LOG_TAG, message);
    messages.add(0, message);

    Toast.makeText(this, message, Toast.LENGTH_SHORT).show();

    mRecyclerView = (RecyclerView) findViewById(R.id.message_recycler_view);
    mLayoutManager = new LinearLayoutManager(this);
    mRecyclerView.setLayoutManager(mLayoutManager);

    mAdapter = new SentMessageAdapter(messages);
    mRecyclerView.setAdapter(mAdapter);
    mAdapter.notifyDataSetChanged();
}

}

Layout for the Activity

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp">

<TextView
    android:id="@+id/sent_message_tv"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="4dp"
    tools:text="Hello world"/>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="4dp"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/recipient_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        tools:text="@string/to"/>

    <TextView
        android:id="@+id/recipient_number_tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="4dp"
        android:paddingStart="4dp"
        android:paddingRight="4dp"
        android:paddingEnd="4dp" />
</LinearLayout>

</LinearLayout>

Body:
Get message and number value in onClick method not onCreate

switch (id) {
        case R.id.send_button:
number = mPhoneNumber.getText().toString();
message = mComposeMessage.getText().toString();

Intent intent = new Intent(v.getContext(), SentActivity.class);
            intent.putExtra(getString(R.string.key_message), message);
            intent.putExtra("NUMBER", number);
            startActivity(intent);
            break;
}

Hope this will help you.


问:
SQL server 2016 installation freeze
Hope someone can help me here .
I have no further information other than that at a later stage in setup the whole process hangs showing  install_confignonrc_cpu64<br>
I am unable to cancel out of it even , the only way was to kill it .
Is there any solution for that  ? </p>

答:
just had the same problem which is why I found this question.
Fixed the problem by closing the original media install menu window (where I'd selected "New SQL Server standalone" which is the first option).
The install window then carried on.</p>

Title: SQL server 2016 installation freeze

Body:
Hope someone can help me here .
I have no further information other than that at a later stage in setup the whole process hangs showing  install_confignonrc_cpu64

I am unable to cancel out of it even , the only way was to kill it .
Is there any solution for that  ?


问:
How to reduce noise while recording sound in java?
Hi guys i am developing an online audio recorder, i need to reduce the noise while recording the sound.How to achieve this?
My current audio format is

AudioFormat(8000.0F,16,1,true,false);

答: You'll need to implement some digital signal filters on your data. Depending on the kind of noise you're targeting, simple band pass filters might work, or you could go the whole hog and implement something like Dolby A/B</p>


问:
Call to Url from node is not working
I use postman to call to URL with headers etc which is working fine ( I was able to get the token in postman call ) and when I try to use it from node its not working , i Got the following error :

```<code>Error: Error: connect ECONNREFUSED 35.122.111.52:445
</code>```

I even copy the code from postman and use it in some simple node.js app and its not working , any idea what could be wrong here ?

```<code>const server = app.listen(port, () => {
    "use strict";
    console.log("Server listen to port :" + port);

    var options = {
        method: 'POST',
        url: 'https://app.authentication.orc.com/oauth/token',
        headers: {
            grant_type: 'client_credentials',
            authorization: 'Basic c2ItY2xvbmUzZjkwNWRmNmRkYzg0YmXCRjlkZmQ0MDdmMCFiMTc0fGNvbm5lY3Rpdml0eSFiMTM3OkpYQUlyd1BrS2tlQVRDWThDNDFsdkhibGNTbz0=',
            accept: 'application/json;charset=utf-8',
            'content-type': 'application/x-www-form-urlencoded'
        },
        form: {
            grant_type: 'client_credentials',
            token_format: 'opaque&response_type=token'
        }
    };

    request(options, function (error, response, body) {
        if (error) throw new Error(error);

        console.log(body);
    });
})
</code>```

答:
If you are behind a corporate proxy then set NPM proxy settings as below. </p>

```<code>npm config set proxy http://"user:P@ssword"@proxy.server:8080
</code>```

Title: Call to Url from node is not working

Body:
I use postman to call to URL with headers etc which is working fine ( I was able to get the token in postman call ) and when I try to use it from node its not working , i Got the following error :

Error: Error: connect ECONNREFUSED 35.122.111.52:445

I even copy the code from postman and use it in some simple node.js app and its not working , any idea what could be wrong here ?

const server = app.listen(port, () => {
    "use strict";
    console.log("Server listen to port :" + port);

    var options = {
        method: 'POST',
        url: 'https://app.authentication.orc.com/oauth/token',
        headers: {
            grant_type: 'client_credentials',
            authorization: 'Basic c2ItY2xvbmUzZjkwNWRmNmRkYzg0YmXCRjlkZmQ0MDdmMCFiMTc0fGNvbm5lY3Rpdml0eSFiMTM3OkpYQUlyd1BrS2tlQVRDWThDNDFsdkhibGNTbz0=',
            accept: 'application/json;charset=utf-8',
            'content-type': 'application/x-www-form-urlencoded'
        },
        form: {
            grant_type: 'client_credentials',
            token_format: 'opaque&response_type=token'
        }
    };

    request(options, function (error, response, body) {
        if (error) throw new Error(error);

        console.log(body);
    });
})

Body:
If you are behind a corporate proxy then set NPM proxy settings as below.

npm config set proxy http://"user:P@ssword"@proxy.server:8080


问:
Why do java programs start with a class definition?
It is said that a java program itself is a class, but I just don't get the logic behind this.

The java program itself starts of by the definition of a class (after importing the packages...etc) and the main method itself is defined inside a class.

Why is it this way?

Why does a main method have to be included within a class rather than outside as a separate method/function like in the languages such as c, c++...etc.

For example a simple hello world program in java:-

```<code>public class HelloWorld
{
    public static void main(String[] args)
    {
        System.out.println("Hello world!"+"Hello again");
    }
}
</code>```

Why is it necessary that a program should start with a class and the main method included within it?

答:
Because the Java language specification says so! See here for example. Or more precisely:

The Java Virtual Machine starts up by loading a specified class and then invoking the method main in this specified class.

(to be found right in the beginning of chapter 12, Execution).

Sometimes there isn't a "big" reason behind things.The fathers of the java language probably had a look around what other languages did at that time when they started Java. They decided to go for this approach - and there was never a hard, pressing reason to come back and change that.

Beyond that: you have to understand that the JVM doesn't care about Java source code. It only cares about the Java bytecode specification - and complete classes coming in as compiled .class files.

In other words: there is simply no other "unit" that could wrap around single methods/functions but classes.

Body:
It is said that a java program itself is a class, but I just don't get the logic behind this.

The java program itself starts of by the definition of a class (after importing the packages...etc) and the main method itself is defined inside a class.

Why is it this way?

Why does a main method have to be included within a class rather than outside as a separate method/function like in the languages such as c, c++...etc.

For example a simple hello world program in java:-

public class HelloWorld
{
    public static void main(String[] args)
    {
        System.out.println("Hello world!"+"Hello again");
    }
}

Why is it necessary that a program should start with a class and the main method included within it?


问:
python insert into mysql table errors
to write python program to insert data in mysql table fb_web_active_group_members_user_hClustering_six

```<code>if cur.execute(is_exist_table_sql) == 0:
    create_sql  = '''CREATE TABLE fb_web_active_group_members_user_hClustering_six (id bigint not null primary key auto_increment,userID bigint,GroupName varchar(128),
                Friends int,NoProfilePhotos int,UploadPhotoSum int,NoPosts int,UploadVideoSum int,postCluster0 int,postCluster1 int,postCluster2 int,postCluster3 int,postCluster4 int,
                normal_Friends float,normal_NoProfilePhotos float,normal_UploadPhotoSum float,normal_NoPosts float,normal_UploadVideoSum float,normal_postCluster0 float,
                normal_postCluster1 float,normal_postCluster2 float,normal_postCluster3 float,normal_postCluster4 float,postCluster0_ratio float,postCluster1_ratio float,
                postCluster2_ratio float,postCluster3_ratio float,postCluster4_ratio float, cluster_label int)'''
    cur.execute(create_sql)

for item in user_level_cluster_list:
    insert_sql = '''INSERT INTO fb_web_active_group_members_user_hClustering_six (userID,GroupName,
                Friends,NoProfilePhotos,UploadPhotoSum,NoPosts,UploadVideoSum,postCluster0,postCluster1,postCluster2,postCluster3,postCluster4,
                normal_Friends,normal_NoProfilePhotos,normal_UploadPhotoSum,normal_NoPosts,normal_UploadVideoSum,normal_postCluster0,
                normal_postCluster1,normal_postCluster2,normal_postCluster3,normal_postCluster4,postCluster0_ratio,postCluster1_ratio,
                postCluster2_ratio,postCluster3_ratio,postCluster4_ratio, cluster_label) VALUES
                ({0},"{1}",{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15},{16}，{17}，{18}，{19}，{20}，{21}，{22}，{23}，{24},{25},{26},{27})'''.format(item["UserID"],
                                                                               item["GroupName"],item["Friends"],item["NoProfilePhotos"],item["UploadPhotoSum"],
                                                                               item["NoPosts"], item["UploadVideoSum"],item["postCluster0"],item["postCluster1"],item["postCluster2"],item["postCluster3"],
                                                                               item["postCluster4"],"%.5f"% item["normal_Friends"],"%.5f"%item["normal_NoProfilePhotos"],"%.5f"%item["normal_UploadPhotoSum"],"%.5f"%item["normal_NoPosts"],
                                                                                "%.5f" %item["normal_UploadVideoSum"],"%.5f"%item["normal_postCluster0"],"%.5f"%item["normal_postCluster1"],"%.5f"%item["normal_postCluster2"],
                                                                                "%.5f" %item["normal_postCluster3"],"%.5f"%item["normal_postCluster4"],"%.5f"%item["postCluster0_ratio"],"%.5f"%item["postCluster1_ratio"],
                                                                                "%.5f" %item["postCluster2_ratio"],"%.5f"%item["postCluster3_ratio"],"%.5f"%item["postCluster4_ratio"],item["cluster_label"])

    print(insert_sql)
    cur.execute(insert_sql)
</code>```

but it errors:

```<code>Traceback (most recent call last):
    INSERT INTO fb_web_active_group_members_user_hClustering_six (userID,GroupName,Friends,NoProfilePhotos,UploadPhotoSum,NoPosts,UploadVideoSum,postCluster0,postCluster1,postCluster2,postCluster3,postCluster4,normal_Friends,normal_NoProfilePhotos,normal_UploadPhotoSum,normal_NoPosts,normal_UploadVideoSum,normal_postCluster0,normal_postCluster1,normal_postCluster2,normal_postCluster3,normal_postCluster4,postCluster0_ratio,postCluster1_ratio,postCluster2_ratio,postCluster3_ratio,postCluster4_ratio, cluster_label) VALUES (1,"Jazzmasters&Jaguars",964,195,5,339,0,119,14,73,20,36,0.19280,0.17016,0.00028,0.37184,0.00000，0.27483，0.09589，0.20055，0.18868，0.15000，0.45420，0.05344，0.27863,0.07634,0.13740,4.00000)

pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '，0.27483，0.09589，0.20055，0.18868，0.15000，0.45420，0.05344，0.27863' at line 6")
</code>```

could you please tell me the reason and how to resolve it

答:
Please, please use the standard syntax presented in MySQL python docs.

I.e. the format of your query should be:

```<code> query = ("INSERT INTO table"
           "(col1, col2, col3, col4)"
           "VALUES (%s, %s, %s, %s)")
 data = (value1, value2, value3, value4)
 cursor.execute(query, data)
</code>```

Don't use the python {}-formats. Your current implementation (if it happened to work, which it luckily does not, probably due to those weird commas) would be vulnerable to SQL-injections.

Title: python insert into mysql table errors

Body:
to write python program to insert data in mysql table fb_web_active_group_members_user_hClustering_six

if cur.execute(is_exist_table_sql) == 0:
    create_sql  = '''CREATE TABLE fb_web_active_group_members_user_hClustering_six (id bigint not null primary key auto_increment,userID bigint,GroupName varchar(128),
                Friends int,NoProfilePhotos int,UploadPhotoSum int,NoPosts int,UploadVideoSum int,postCluster0 int,postCluster1 int,postCluster2 int,postCluster3 int,postCluster4 int,
                normal_Friends float,normal_NoProfilePhotos float,normal_UploadPhotoSum float,normal_NoPosts float,normal_UploadVideoSum float,normal_postCluster0 float,
                normal_postCluster1 float,normal_postCluster2 float,normal_postCluster3 float,normal_postCluster4 float,postCluster0_ratio float,postCluster1_ratio float,
                postCluster2_ratio float,postCluster3_ratio float,postCluster4_ratio float, cluster_label int)'''
    cur.execute(create_sql)

for item in user_level_cluster_list:
    insert_sql = '''INSERT INTO fb_web_active_group_members_user_hClustering_six (userID,GroupName,
                Friends,NoProfilePhotos,UploadPhotoSum,NoPosts,UploadVideoSum,postCluster0,postCluster1,postCluster2,postCluster3,postCluster4,
                normal_Friends,normal_NoProfilePhotos,normal_UploadPhotoSum,normal_NoPosts,normal_UploadVideoSum,normal_postCluster0,
                normal_postCluster1,normal_postCluster2,normal_postCluster3,normal_postCluster4,postCluster0_ratio,postCluster1_ratio,
                postCluster2_ratio,postCluster3_ratio,postCluster4_ratio, cluster_label) VALUES
                ({0},"{1}",{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15},{16}，{17}，{18}，{19}，{20}，{21}，{22}，{23}，{24},{25},{26},{27})'''.format(item["UserID"],
                                                                               item["GroupName"],item["Friends"],item["NoProfilePhotos"],item["UploadPhotoSum"],
                                                                               item["NoPosts"], item["UploadVideoSum"],item["postCluster0"],item["postCluster1"],item["postCluster2"],item["postCluster3"],
                                                                               item["postCluster4"],"%.5f"% item["normal_Friends"],"%.5f"%item["normal_NoProfilePhotos"],"%.5f"%item["normal_UploadPhotoSum"],"%.5f"%item["normal_NoPosts"],
                                                                                "%.5f" %item["normal_UploadVideoSum"],"%.5f"%item["normal_postCluster0"],"%.5f"%item["normal_postCluster1"],"%.5f"%item["normal_postCluster2"],
                                                                                "%.5f" %item["normal_postCluster3"],"%.5f"%item["normal_postCluster4"],"%.5f"%item["postCluster0_ratio"],"%.5f"%item["postCluster1_ratio"],
                                                                                "%.5f" %item["postCluster2_ratio"],"%.5f"%item["postCluster3_ratio"],"%.5f"%item["postCluster4_ratio"],item["cluster_label"])

    print(insert_sql)
    cur.execute(insert_sql)

but it errors:

Traceback (most recent call last):
    INSERT INTO fb_web_active_group_members_user_hClustering_six (userID,GroupName,Friends,NoProfilePhotos,UploadPhotoSum,NoPosts,UploadVideoSum,postCluster0,postCluster1,postCluster2,postCluster3,postCluster4,normal_Friends,normal_NoProfilePhotos,normal_UploadPhotoSum,normal_NoPosts,normal_UploadVideoSum,normal_postCluster0,normal_postCluster1,normal_postCluster2,normal_postCluster3,normal_postCluster4,postCluster0_ratio,postCluster1_ratio,postCluster2_ratio,postCluster3_ratio,postCluster4_ratio, cluster_label) VALUES (1,"Jazzmasters&Jaguars",964,195,5,339,0,119,14,73,20,36,0.19280,0.17016,0.00028,0.37184,0.00000，0.27483，0.09589，0.20055，0.18868，0.15000，0.45420，0.05344，0.27863,0.07634,0.13740,4.00000)

pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '，0.27483，0.09589，0.20055，0.18868，0.15000，0.45420，0.05344，0.27863' at line 6")

could you please tell me the reason and how to resolve it

Body:
Please, please use the standard syntax presented in MySQL python docs.

I.e. the format of your query should be:

 query = ("INSERT INTO table"
           "(col1, col2, col3, col4)"
           "VALUES (%s, %s, %s, %s)")
 data = (value1, value2, value3, value4)
 cursor.execute(query, data)

Don't use the python {}-formats. Your current implementation (if it happened to work, which it luckily does not, probably due to those weird commas) would be vulnerable to SQL-injections.