问:
SQL Server Query using a Dynamic Column Name
I'm trying to do a SQL query on a priority matrix. So I want to pass the column name dynamically and then also filter based on a where clause that also has a dynamic value.

I've found some answers on Stackoverflow that have been useful but they've only got me so far, and now I'm a bit stuck. Can anyone see where I'm going wrong?

Query I have the issue with:

```<code>DECLARE @var1 VARCHAR(50)
DECLARE @var2 VARCHAR(50)
DECLARE @sql VARCHAR(255)

SET @var1 = 'partial impact'
SET @var2 = 'single user'
SET @sql = 'select [' + @var1 + '] from [priority matrix] where impact is ['+ @var2 + ']'

EXECUTE(@sql);
</code>```

Query that isn't dynamic and works fine:

```<code>SELECT [partial impact]
FROM priorityMatrix
WHERE impact = 'single user';
</code>```

Error I'm seeing when I run it:

Msg 102, Level 15, State 1, Line 1
    Incorrect syntax near 'single user'.

Stackoverflow queries that have helped so far:

SQL Server + Dynamic Query 'Invalid Column Name'
How to set variable from a SQL query?

答:
IS <> =, so you need to fix it :

```<code>SET @sql = 'select [' + @var1 + '] from [priority matrix] where impact  = ['+ @var2 + ']';
</code>```

I would use QUOTENAME() instead of manual [] :

```<code>SET @sql = 'SELECT '+ QUOTENAME(@var1) +' FROM [priority matrix] WHERE impact  = '''+@var2+'''';
</code>```

Literal strings are quoted with single quotes, [] are not required.

Body:
I'm trying to do a SQL query on a priority matrix. So I want to pass the column name dynamically and then also filter based on a where clause that also has a dynamic value.

I've found some answers on Stackoverflow that have been useful but they've only got me so far, and now I'm a bit stuck. Can anyone see where I'm going wrong?

Query I have the issue with:

DECLARE @var1 VARCHAR(50)
DECLARE @var2 VARCHAR(50)
DECLARE @sql VARCHAR(255)

SET @var1 = 'partial impact'
SET @var2 = 'single user'
SET @sql = 'select [' + @var1 + '] from [priority matrix] where impact is ['+ @var2 + ']'

EXECUTE(@sql);

Query that isn't dynamic and works fine:

SELECT [partial impact]
FROM priorityMatrix
WHERE impact = 'single user';

Error I'm seeing when I run it:

Msg 102, Level 15, State 1, Line 1
    Incorrect syntax near 'single user'.

Stackoverflow queries that have helped so far:

SQL Server + Dynamic Query 'Invalid Column Name'
How to set variable from a SQL query?

Body:
IS <> =, so you need to fix it :

SET @sql = 'select [' + @var1 + '] from [priority matrix] where impact  = ['+ @var2 + ']';

I would use QUOTENAME() instead of manual [] :

SET @sql = 'SELECT '+ QUOTENAME(@var1) +' FROM [priority matrix] WHERE impact  = '''+@var2+'''';

Literal strings are quoted with single quotes, [] are not required.


来源: stackexchange

问:
How to display my background-image in my html/css?
I've seen another topic about my issue, but it doesn't resolve it, I try to put a background image for my portfolio but it doesn't work. I don't understand why, do you have an idea ?

my code:

html:

          Project
          Skills
          Contact

```

```css:

.main{
background-image: url(../img/dev-dots.png);
background-position: center;
background-repeat: no-repeat;
background-size: cover;

}

.navbar{
    height: 10vh;
    background-color: purple;
    position: fixed;
}
```

PS: Sorry for my english, it's not my first language.

答:
.main{
  background-image: url('http://scontent-vie1-1.xx.fbcdn.net/v/t1.0-0/p640x640/86969955_2219297081712551_4370094468804640768_o.jpg?_nc_cat=108&_nc_ohc=RXVSJ86AsuoAX_l1w_j&_nc_ht=scontent-vie1-1.xx&_nc_tp=6&oh=f79e4654f5cee0a184fa73d9faa0af49&oe=5EFBD055');
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  min-height: 200px;

}

.navbar{
    height: 10vh;
    background-color: purple;
    position: fixed;
    width: 100%;
    padding: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div class="main">
    <div class="navbar container-fluid d-flex justify-content-center">
        <i class="fab fa-react fa-3x firstIcon mr-4"> <span class="txtIcon"> Project</span></i>
        <i class="fas fa-check-square fa-3x mx-4"> <span class="txtIcon2"> Skills</span></i>
        <i class="fas fa-id-card fa-3x ml-4"> <span class="txtIcon3"> Contact</span></i>
    </div>
</div></code>```

This is what you looking for? The fixed attribute made the container not expanding, so no background to show.

ContentLicense: CC BY-SA 4.0

Body:
I've seen another topic about my issue, but it doesn't resolve it, I try to put a background image for my portfolio but it doesn't work. I don't understand why, do you have an idea ?

my code:

html:

          Project
          Skills
          Contact

css:

.main{
background-image: url(../img/dev-dots.png);
background-position: center;
background-repeat: no-repeat;
background-size: cover;

}

.navbar{
    height: 10vh;
    background-color: purple;
    position: fixed;
}

PS: Sorry for my english, it's not my first language.

Body:
.main{
  background-image: url('http://scontent-vie1-1.xx.fbcdn.net/v/t1.0-0/p640x640/86969955_2219297081712551_4370094468804640768_o.jpg?_nc_cat=108&_nc_ohc=RXVSJ86AsuoAX_l1w_j&_nc_ht=scontent-vie1-1.xx&_nc_tp=6&oh=f79e4654f5cee0a184fa73d9faa0af49&oe=5EFBD055');
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  min-height: 200px;

}

.navbar{
    height: 10vh;
    background-color: purple;
    position: fixed;
    width: 100%;
    padding: 20px;
}

 <div class="main">
    <div class="navbar container-fluid d-flex justify-content-center">
        <i class="fab fa-react fa-3x firstIcon mr-4"> <span class="txtIcon"> Project</span></i>
        <i class="fas fa-check-square fa-3x mx-4"> <span class="txtIcon2"> Skills</span></i>
        <i class="fas fa-id-card fa-3x ml-4"> <span class="txtIcon3"> Contact</span></i>
    </div>
</div>

This is what you looking for? The fixed attribute made the container not expanding, so no background to show.


问:
How to extract question mark surrounded texts into an array in Javascript
I have a string like this,

```<code>var str = " This is a ?sample? text to ?extract? question marks separated texts into an array in ?Javascript?. "
</code>```

I want a javascript array as below,

```<code>arr = {
        'sample',
        'extract',
        'Javascript'
      }
</code>```

答:
You can split() and then filter() the results having an odd index :

// After the split('?'), an array will be created. One needs the odd indexes
//                0        1         2      3                         4                                 5      6  7
const str = " This is a ?sample? text to ?extract? question marks separated texts into an array in ?Javascript?. ?";

const arr = str.split('?').filter((word, index) => index % 2 !== 0 && word !== '');

console.log(arr);```
</div>
</div>
</p>

<p>This will be working <strong>only</strong> if you are sure that the input contains only an even number of <code>?</code>. An input like <code>"foo?bar"</code> will output <code>[ 'bar' ]</code>.</p>

<p>To make sure this work with any input, you can use RegEx :</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function getWordsBetweenParenthesis(input)
{
  const pattern = /(?:\?)(.*?)(?:\?)/gm;
  const matches = input.matchAll(pattern);
  return [...matches].map(arr => arr[1]);
}

console.log(getWordsBetweenParenthesis(" This is a ?sample? text to ?extract? question marks separated texts into an array in ?Javascript?. "));
console.log(getWordsBetweenParenthesis("foo?bar"));
console.log(getWordsBetweenParenthesis("foo??bar"));
console.log(getWordsBetweenParenthesis("?hello?World?"));
console.log(getWordsBetweenParenthesis("?hello??World?"));</code>```

Body:
I have a string like this,

var str = " This is a ?sample? text to ?extract? question marks separated texts into an array in ?Javascript?. "

I want a javascript array as below,

arr = {
        'sample',
        'extract',
        'Javascript'
      }

Body:
You can split() and then filter() the results having an odd index :

// After the split('?'), an array will be created. One needs the odd indexes
//                0        1         2      3                         4                                 5      6  7
const str = " This is a ?sample? text to ?extract? question marks separated texts into an array in ?Javascript?. ?";

const arr = str.split('?').filter((word, index) => index % 2 !== 0 && word !== '');

console.log(arr);

This will be working only if you are sure that the input contains only an even number of ?. An input like "foo?bar" will output [ 'bar' ].

To make sure this work with any input, you can use RegEx :

function getWordsBetweenParenthesis(input)
{
  const pattern = /(?:\?)(.*?)(?:\?)/gm;
  const matches = input.matchAll(pattern);
  return [...matches].map(arr => arr[1]);
}

console.log(getWordsBetweenParenthesis(" This is a ?sample? text to ?extract? question marks separated texts into an array in ?Javascript?. "));
console.log(getWordsBetweenParenthesis("foo?bar"));
console.log(getWordsBetweenParenthesis("foo??bar"));
console.log(getWordsBetweenParenthesis("?hello?World?"));
console.log(getWordsBetweenParenthesis("?hello??World?"));


问:
I cannot pass data to view it show http error 500 in laravel
Hi guyz i am kind of new to laravel and im trying to show the reviews posted by users . Now i checked with dd() and indeed i am able to get that data however when i send it to the view laravel responds with Http error 500. Previously i was only sending the doctors data which was working fine but when i tried to pass the reviews this happened.
This is my show Profile function

```<code>     public function profile($id)
    {
    $doctor=Doctor::find($id);
    $reviews=Review::where('doctor_id',$doctor->account_id)->get();

   // dd($doctor,$reviews);
    //  foreach($reviews as $review)
    //  {
    //      dd($doctor,$review);
    //  }
   // dd($reviews);
   // dd(DB::select("select * from reviews where doctor_id='D-1'"));
    //dd(Review::all()->where('doctor_id',$doctor->account_id));
   // $reviews=;
  // $array=['reviews'=>$reviews];
    return View('pages.doctorProfile',['reviews'=>$reviews])->with('doctor',$doctor);
}
</code>```

and this is the section of the view where i was trying to show the review

```<code>@foreach($reviews as $review)
    <!-- Comment List -->
    <li>
    <div class="comment">
        <img class="avatar avatar-sm rounded-circle" alt="User Image" src="/storage/images/patients/{{$review->patient->image}}">
        <div class="comment-body">
            <div class="meta-data">
                <span class="comment-author">{{$review->patient->first_name}} {{$review->patient->last_name}}</span>
                <span class="comment-date">{{$review->created_at}}</span>

            </div>
            <div  class="review-count rating">
                <?php $rating=explode('-',$review->rating)  ?>
                @for($i=1;$i<=5;$i++)
                    @for($i=1;$i<=$rating[1];$i++)
                        <i class="fas fa-star filled"></i>
                    @endfor
                    <i class="fas fa-star"></i>
                @endfor
                {{-- <i class="fas fa-star filled"></i>
                <i class="fas fa-star filled"></i>
                <i class="fas fa-star filled"></i>
                <i class="fas fa-star filled"></i>
                <i class="fas fa-star"></i> --}}
            </div>
            <p class="comment-content">
               {{$review->content}}
            </p>
            <div class="comment-reply">
                <a class="comment-btn" href="#">
                    <i class="fas fa-reply"></i> Reply
                </a>

            </div>
        </div>
    </div>
    </li>
    <!-- /Comment List -->
@endforeach
</code>```

Need this solved quick. Please help

答:
```<code>@for($i=1;$i<=5;$i++)
     @for($j=1;$j<=$rating[1];$j++)
          <i class="fas fa-star filled"></i>
     @endfor
     <i class="fas fa-star"></i>
@endfor
</code>```

change i to j, becouse execute infinite time

I think you are considering

```<code> @for($i=1;$i<=5;$i++)
    <i class="fas fa-star {{ $i<= $rating[1] ? 'failed' : '' }}"></i>
 @endfor
</code>```

Body:
Hi guyz i am kind of new to laravel and im trying to show the reviews posted by users . Now i checked with dd() and indeed i am able to get that data however when i send it to the view laravel responds with Http error 500. Previously i was only sending the doctors data which was working fine but when i tried to pass the reviews this happened.
This is my show Profile function

     public function profile($id)
    {
    $doctor=Doctor::find($id);
    $reviews=Review::where('doctor_id',$doctor->account_id)->get();

   // dd($doctor,$reviews);
    //  foreach($reviews as $review)
    //  {
    //      dd($doctor,$review);
    //  }
   // dd($reviews);
   // dd(DB::select("select * from reviews where doctor_id='D-1'"));
    //dd(Review::all()->where('doctor_id',$doctor->account_id));
   // $reviews=;
  // $array=['reviews'=>$reviews];
    return View('pages.doctorProfile',['reviews'=>$reviews])->with('doctor',$doctor);
}

and this is the section of the view where i was trying to show the review

@foreach($reviews as $review)

        patient->image}}">

                {{$review->patient->first_name}} {{$review->patient->last_name}}
                {{$review->created_at}}

                <?php $rating=explode('-',$review->rating)  ?>
                @for($i=1;$i<=5;$i++)
                    @for($i=1;$i<=$rating[1];$i++)

                    @endfor

                @endfor
                {{--

                 --}}

               {{$review->content}}

                     Reply

@endforeach

Need this solved quick. Please help

Body:
@for($i=1;$i<=5;$i++)
     @for($j=1;$j<=$rating[1];$j++)
          <i class="fas fa-star filled"></i>
     @endfor
     <i class="fas fa-star"></i>
@endfor

change i to j, becouse execute infinite time

I think you are considering

 @for($i=1;$i<=5;$i++)
    <i class="fas fa-star {{ $i<= $rating[1] ? 'failed' : '' }}"></i>
 @endfor


问:
Collections.sort() Comparison method violates its general contract
I am trying to sort arraylist based on comparing two strings using comparator ,but i end up with Comparison method violates its general contract error. How do i handle if null comparison occurs in the string.

Code

Collections.sort(keyList, new DIMsComparator<DIM>(sortField));

public static class DIMsComparator<T> implements Comparator<T> {
    String sortField = "";

    public DIMsComparator(String sortField) {
        this.sortField = sortField;
    }

    public int compare(T obj1, T obj2) {
        if (!(obj1 instanceof DIM) || !(obj2 instanceof DIM))
            return obj1 instanceof DIM ? -1 : obj2 instanceof DIM ? 1 : 0;
        DIM dim1 = (DIM) obj1;
        DIM dim2 = (DIM) obj2;
        // Changes for Grouping enhancement starts
        /*
         * if(dim1.getGroupName() != "" || dim2.getGroupName() != "") return -1;
         */
        // Changes for Grouping enhancement ends
        if (dim1.isTextLine())
            return 1;
        if (dim2.isTextLine())
            return -1;
        String[] mySortFields = Util.split(this.sortField, ",");
        for (int i = 0; i < mySortFields.length; i++) {
            if (mySortFields[i].equals(""))
                break;
            int value = compare(dim1, dim2, mySortFields[i]);
            if (value == 0)
                continue;
            else
                return value;
        }

        return dim1.dimSeqNo > dim2.dimSeqNo ? 1 : dim1.dimSeqNo < dim2.dimSeqNo ? -1 : 0;
    }
```

<p>Error</p>

```[err] java.lang.IllegalArgumentException: Comparison method violates its general contract!
[err]   at java.util.TimSort.mergeLo(TimSort.java:788)
[err]   at java.util.TimSort.mergeAt(TimSort.java:525)
[err]   at java.util.TimSort.mergeCollapse(TimSort.java:452)
[err]   at java.util.TimSort.sort(TimSort.java:256)
[err]   at java.util.Arrays.sort(Arrays.java:1856)
[err]   at java.util.ArrayList.sort(ArrayList.java:1471)
[err]   at java.util.Collections.sort(Collections.java:186)
```

答:
Regarding [err] java.lang.IllegalArgumentException: Comparison method violates its general contract!

Your solution probably is not transitive

If A == B and B == C, then A must be equal to C.

Regarding your question:

How do i handle if null comparison occurs in the string.

Have a look at this answer

if(str != null && !str.isEmpty())

You should also take a look at this line int value = compare(dim1, dim2, mySortFields[i]);
I'm not sure what it's supposed to do.

Hope this helps!

Body:
I am trying to sort arraylist based on comparing two strings using comparator ,but i end up with Comparison method violates its general contract error. How do i handle if null comparison occurs in the string.

Code

Collections.sort(keyList, new DIMsComparator<DIM>(sortField));

public static class DIMsComparator<T> implements Comparator<T> {
    String sortField = "";

    public DIMsComparator(String sortField) {
        this.sortField = sortField;
    }

    public int compare(T obj1, T obj2) {
        if (!(obj1 instanceof DIM) || !(obj2 instanceof DIM))
            return obj1 instanceof DIM ? -1 : obj2 instanceof DIM ? 1 : 0;
        DIM dim1 = (DIM) obj1;
        DIM dim2 = (DIM) obj2;
        // Changes for Grouping enhancement starts
        /*
         * if(dim1.getGroupName() != "" || dim2.getGroupName() != "") return -1;
         */
        // Changes for Grouping enhancement ends
        if (dim1.isTextLine())
            return 1;
        if (dim2.isTextLine())
            return -1;
        String[] mySortFields = Util.split(this.sortField, ",");
        for (int i = 0; i < mySortFields.length; i++) {
            if (mySortFields[i].equals(""))
                break;
            int value = compare(dim1, dim2, mySortFields[i]);
            if (value == 0)
                continue;
            else
                return value;
        }

        return dim1.dimSeqNo > dim2.dimSeqNo ? 1 : dim1.dimSeqNo < dim2.dimSeqNo ? -1 : 0;
    }

Error

[err] java.lang.IllegalArgumentException: Comparison method violates its general contract!
[err]   at java.util.TimSort.mergeLo(TimSort.java:788)
[err]   at java.util.TimSort.mergeAt(TimSort.java:525)
[err]   at java.util.TimSort.mergeCollapse(TimSort.java:452)
[err]   at java.util.TimSort.sort(TimSort.java:256)
[err]   at java.util.Arrays.sort(Arrays.java:1856)
[err]   at java.util.ArrayList.sort(ArrayList.java:1471)
[err]   at java.util.Collections.sort(Collections.java:186)


问:
input field, only numbers jquery/js
I have a input field where i only wish users to type numbers

html: <input id="num" type="text" name="page" size="4" value="" />

jquery/ js:

```<code> $("#num").keypress(function (e){
      if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)){
        return false;
      }
});
</code>```

hope someone can help me.

btw: I'm not interesting in a larger jquery plugin to make the function work. (I have found some jquery-plugins , but there must be som other ways to fix it, with a smaller code)

答:
text input:

```<code><input id="number" type="text" />
</code>```

and script:

```<code>var number = $('#number');
number.on('input', function () {
    $(this).val(getOnlyNumbers($(this).val()));
});

// this function return only numbers as string or ''
function getOnlyNumbers(value) {
                let arr = value.toString().split('');
                let number = [];

                arr.forEach(function (elem) {
                    let charCode = elem.charCodeAt(0);

                    if (charCode > 31 && (charCode < 48 || charCode > 57)) {

                    } else {
                        number.push(elem);
                    }
                });

                return parseInt(number.join('')) || '';
            }
</code>```

ContentLicense: CC BY-SA 2.5

Title: input field, only numbers jquery/js

Body:
I have a input field where i only wish users to type numbers

html: <input id="num" type="text" name="page" size="4" value="" />

jquery/ js:

 $("#num").keypress(function (e){
      if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)){
        return false;
      }
});

hope someone can help me.

btw: I'm not interesting in a larger jquery plugin to make the function work. (I have found some jquery-plugins , but there must be som other ways to fix it, with a smaller code)

Body:
text input:

<input id="number" type="text" />

and script:

var number = $('#number');
number.on('input', function () {
    $(this).val(getOnlyNumbers($(this).val()));
});

// this function return only numbers as string or ''
function getOnlyNumbers(value) {
                let arr = value.toString().split('');
                let number = [];

                arr.forEach(function (elem) {
                    let charCode = elem.charCodeAt(0);

                    if (charCode > 31 && (charCode < 48 || charCode > 57)) {

                    } else {
                        number.push(elem);
                    }
                });

                return parseInt(number.join('')) || '';
            }


问:
JavaScript positional property access in Objects
I have the following JavaScript object:

```<code>{
  "_embedded": {
    "dealerListItemDToes": [
      {
        ...
      },
      {
        ...
      }
    ]
  }
}
</code>```

Property called 'dealerListItemDToes' will always be at the given position in the object but its name can vary depending on the HTTP requests.

How can I access the property 'dealerListItemDToes' and retrieve its content without referencing its name?

答:
Since it's the only property of the _embedded object, you could access the [0]th item in an array of object entries:

const obj = {
  "_embedded": {
    "dealerListItemDToes": [
      {
        // ...
      },
      {
        // ...
      }
    ]
  }
};

console.log(
  Object.entries(obj._embedded)[0]
);```

Body:
I have the following JavaScript object:

{
  "_embedded": {
    "dealerListItemDToes": [
      {
        ...
      },
      {
        ...
      }
    ]
  }
}

Property called 'dealerListItemDToes' will always be at the given position in the object but its name can vary depending on the HTTP requests.

How can I access the property 'dealerListItemDToes' and retrieve its content without referencing its name?


问:
How to pass parameters when importing a module that provides JSON data?
If I have something like,

```<code>// resources.js
import DB from 'some/massive.json';

export const RESOURCES = (() => {
  const {
    dataA,
    dataB
  } = DB;

  return [
    dataA,
    dataB
  ];
})
</code>```

And I import it like

```<code>// someOtherFile.js
import { RESOURCES } from 'path/to/resources.js'
</code>```

How can I import RESOURCES, passing in parameters, so as to limit the data that is received? RESOURCES could be MB in size, and I don't need all of them for each test that runs, I just need specific resources for specific tests.

Something like,

```<code>import DB from 'some/massive.json';

export const RESOURCES = (dataToExclude = null, () => {
  const {
    dataA,
    dataB
  } = DB;

  const dataArray = [
    dataA, dataB
  ].flatMap(data => {
    // Process
    return data;
  })

  // dataArray will look something like,
  // [ { dataName: 'NameA', ...props }, { dataName: 'NameB', ...props } ]
  if (dataToExclude) {
    const indexToSplice = dataArray.findIndex(({ dataName }) => dataName === dataToExclude)
    dataArray.splice(indexToSplice, 1)
  }

  return dataToExclude;
});
</code>```

答:
The body of RESOURCES isn't the question, I'm just asking to see if it's possible to pass in parameters

Your RESOURCES is already a function, there's no need to wrap it in another function. (There's also no reason to wrap it in parens, though they're harmless.) Pass it the filtering criteria you want it to have:

```<code>export const RESOURCES = (filteringCriteria) => {
  const {
    dataA,
    dataB
  } = DB;

  // ...apply filtering here...

  return [
    dataA,
    dataB
  ];
};
</code>```

...then call it after importing it:

```<code>const data = RESOURCES({/*...filtering criteria...*/});
</code>```

But if you want to wrap it in another function, yes, you can do that and have the inner function close over the filtering criteria:

```<code>export const RESOURCES = (filteringCriteria) => {
  return () => {
      const {
        dataA,
        dataB
      } = DB;

      // ...apply filtering here...

      return [
        dataA,
        dataB
      ];
  };
};
</code>```

Then you'd call it once to establish the filtering criteria, and call the result of that to actually get the data:

```<code>const dataSupplier = RESOURCES({/*...filtering criteria...*/});
// ...
const data = dataSupplier();
</code>```

Body:
If I have something like,

// resources.js
import DB from 'some/massive.json';

export const RESOURCES = (() => {
  const {
    dataA,
    dataB
  } = DB;

  return [
    dataA,
    dataB
  ];
})

And I import it like

// someOtherFile.js
import { RESOURCES } from 'path/to/resources.js'

How can I import RESOURCES, passing in parameters, so as to limit the data that is received? RESOURCES could be MB in size, and I don't need all of them for each test that runs, I just need specific resources for specific tests.

Something like,

import DB from 'some/massive.json';

export const RESOURCES = (dataToExclude = null, () => {
  const {
    dataA,
    dataB
  } = DB;

  const dataArray = [
    dataA, dataB
  ].flatMap(data => {
    // Process
    return data;
  })

  // dataArray will look something like,
  // [ { dataName: 'NameA', ...props }, { dataName: 'NameB', ...props } ]
  if (dataToExclude) {
    const indexToSplice = dataArray.findIndex(({ dataName }) => dataName === dataToExclude)
    dataArray.splice(indexToSplice, 1)
  }

  return dataToExclude;
});

Body:
The body of RESOURCES isn't the question, I'm just asking to see if it's possible to pass in parameters

Your RESOURCES is already a function, there's no need to wrap it in another function. (There's also no reason to wrap it in parens, though they're harmless.) Pass it the filtering criteria you want it to have:

export const RESOURCES = (filteringCriteria) => {
  const {
    dataA,
    dataB
  } = DB;

  // ...apply filtering here...

  return [
    dataA,
    dataB
  ];
};

...then call it after importing it:

const data = RESOURCES({/*...filtering criteria...*/});

But if you want to wrap it in another function, yes, you can do that and have the inner function close over the filtering criteria:

export const RESOURCES = (filteringCriteria) => {
  return () => {
      const {
        dataA,
        dataB
      } = DB;

      // ...apply filtering here...

      return [
        dataA,
        dataB
      ];
  };
};

Then you'd call it once to establish the filtering criteria, and call the result of that to actually get the data:

const dataSupplier = RESOURCES({/*...filtering criteria...*/});
// ...
const data = dataSupplier();


问:
using Jasmines spyon upon a private method
is it possible to use Jasmine unit testing framework's spyon method upon a classes private methods?

The documentation gives this example but can this be flexible for a private function?

```<code>describe("Person", function() {
    it("calls the sayHello() function", function() {
        var fakePerson = new Person();
        spyOn(fakePerson, "sayHello");
        fakePerson.helloSomeone("world");
        expect(fakePerson.sayHello).toHaveBeenCalled();
    });
});
</code>```

答:
```<code>spyOn<any>(fakePerson, 'sayHello');
expect(fakePerson['sayHello']).toHaveBeenCalled();
</code>```

by adding <any> to spyOn you remove it from typescript type check.
you also need to use array index notation in order to access a private method (sayHello) in the test expect

Body:
is it possible to use Jasmine unit testing framework's spyon method upon a classes private methods?

The documentation gives this example but can this be flexible for a private function?

describe("Person", function() {
    it("calls the sayHello() function", function() {
        var fakePerson = new Person();
        spyOn(fakePerson, "sayHello");
        fakePerson.helloSomeone("world");
        expect(fakePerson.sayHello).toHaveBeenCalled();
    });
});

Body:
spyOn<any>(fakePerson, 'sayHello');
expect(fakePerson['sayHello']).toHaveBeenCalled();

by adding <any> to spyOn you remove it from typescript type check.
you also need to use array index notation in order to access a private method (sayHello) in the test expect


问:
Pipeline Loading Models and Tokenizers for Q&A
Hi I'm trying to use 'fmikaelian/flaubert-base-uncased-squad' for question answering. I understand that I should load the model and the tokenizers. I'm not sure how should I do this.

My code is basically far

```<code>from transformers import pipeline, BertTokenizer

nlp = pipeline('question-answering', \
model='fmikaelian/flaubert-base-uncased-squad', \
tokenizer='fmikaelian/flaubert-base-uncased-squad')
</code>```

Most probably this can be solve with a two liner.

Many thanks

EDIT

I have also tried to use automodels but it seems those are not there:

```<code>OSError: Model name 'flaubert-base-uncased-squad' was not found in model name list (bert-base-uncased, bert-large-uncased, bert-base-cased, bert-large-cased, bert-base-multilingual-uncased, bert-base-multilingual-cased, bert-base-chinese, bert-base-german-cased, bert-large-uncased-whole-word-masking, bert-large-cased-whole-word-masking, bert-large-uncased-whole-word-masking-finetuned-squad, bert-large-cased-whole-word-masking-finetuned-squad, bert-base-cased-finetuned-mrpc, bert-base-german-dbmdz-cased, bert-base-german-dbmdz-uncased). We assumed 'flaubert-base-uncased-squad' was a path or url to a configuration file named config.json or a directory containing such a file but couldn't find any such file at this path or url.
</code>```

EDIT II
I tried following the approach suggested with the following code that loads models that have been saved from S3:

tokenizer_ = FlaubertTokenizer.from_pretrained(MODELS)
model_ = FlaubertModel.from_pretrained(MODELS)

p = transformers.QuestionAnsweringPipeline(
    model=transformers.AutoModel.from_pretrained(MODELS),
    tokenizer=transformers.AutoTokenizer.from_pretrained(MODELS)
)

question_="Quel est le montant de la garantie?"
language_="French"
context_="le montant de la garantie est € 1000"

output=p({'question':question_, 'context': context_})
print(output)
```

<p>Unfortunately I have been getting the following error:</p>

```Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\multiprocessing\spawn.py", line 105, in spawn_main
    exitcode = _main(fd)
Traceback (most recent call last):
  File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\multiprocessing\spawn.py", line 114, in _main
  File "question_extraction.py", line 61, in <module>
        prepare(preparation_data)
output=p({'question':question_, 'context': context_})  File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\multiprocessing\spawn.py", line 225, in prepare

      File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\site-packages\transformers\pipelines.py", line 802, in __call__
_fixup_main_from_path(data['init_main_from_path'])
  File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\multiprocessing\spawn.py", line 277, in _fixup_main_from_path
    run_name="__mp_main__")
  File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\runpy.py", line 263, in run_path
    pkg_name=pkg_name, script_name=fname)
  File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\runpy.py", line 96, in _run_module_code
    mod_name, mod_spec, pkg_name, script_name)
  File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\Users\... ...\Box Sync\nlp - 2...\NLP\src\question_extraction.py", line 61, in <module>
    output=p({'question':question_, 'context': context_})
  File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\site-packages\transformers\pipelines.py", line 802, in __call__
    for example in examples
      File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\site-packages\transformers\pipelines.py", line 802, in <listcomp>
for example in examples
for example in examples  File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\site-packages\transformers\pipelines.py", line 802, in <listcomp>

      File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\site-packages\transformers\data\processors\squad.py", line 304, in squad_convert_examples_to_features
for example in examples
  File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\site-packages\transformers\data\processors\squad.py", line 304, in squad_convert_examples_to_features
        with Pool(threads, initializer=squad_convert_example_to_features_init, initargs=(tokenizer,)) as p:with Pool(threads, initializer=squad_convert_example_to_features_init, initargs=(tokenizer,)) as p:

  File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\multiprocessing\context.py", line 119, in Pool
  File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\multiprocessing\context.py", line 119, in Pool
        context=self.get_context())context=self.get_context())

  File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\multiprocessing\pool.py", line 174, in __init__
  File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\multiprocessing\pool.py", line 174, in __init__
        self._repopulate_pool()self._repopulate_pool()

  File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\multiprocessing\pool.py", line 239, in _repopulate_pool
  File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\multiprocessing\pool.py", line 239, in _repopulate_pool
    w.start()
    w.start()
  File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\multiprocessing\process.py", line 105, in start
  File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\multiprocessing\process.py", line 105, in start
    self._popen = self._Popen(self)
      File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\multiprocessing\context.py", line 322, in _Popen
self._popen = self._Popen(self)
      File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\multiprocessing\context.py", line 322, in _Popen
return Popen(process_obj)
return Popen(process_obj)  File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\multiprocessing\popen_spawn_win32.py", line 65, in __init__

  File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\multiprocessing\popen_spawn_win32.py", line 33, in __init__
        prep_data = spawn.get_preparation_data(process_obj._name)reduction.dump(process_obj, to_child)

  File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\multiprocessing\spawn.py", line 143, in get_preparation_data
  File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\multiprocessing\reduction.py", line 60, in dump
    _check_not_importing_main()
  File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\multiprocessing\spawn.py", line 136, in _check_not_importing_main
    is not going to be frozen to produce an executable.''')
RuntimeError:
        An attempt has been made to start a new process before the
        current process has finished its bootstrapping phase.

        This probably means that you are not using fork to start your
        child processes and you have forgotten to use the proper idiom
        in the main module:

            if __name__ == '__main__':
                freeze_support()
                ...

        The "freeze_support()" line can be omitted if the program
        is not going to be frozen to produce an executable.
    ForkingPickler(file, protocol).dump(obj)
BrokenPipeError: [Errno 32] Broken pipe
```

<p><strong>*EDIT IV *</strong></p>

<p>I solved the previous EDIT error by placing the functions inside the "<strong>main</strong>".
Unfortunately when I run the following code:</p>

<pre class="lang-py prettyprint-override"><code>tokenizer_ = FlaubertTokenizer.from_pretrained(MODELS)
model_ = FlaubertModel.from_pretrained(MODELS)

def question_extraction(text, question, model, tokenizer, language="French", verbose=False):

    if language=="French":
        nlp = pipeline('question-answering', \
        model=model, \
        tokenizer=tokenizer)
    else:
        nlp=pipeline('question-answering')

    output=nlp({'question':question, 'context': text})

    answer, score = output.answer, output.score

    if verbose==True:
        print("Q: ", question ,"\n",\
              "A:", answer,"\n", \
              "Confidence (%):", "{0:.2f}".format(str(score*100) )
              )

    return answer, score

if __name__=="__main__":
    question_="Quel est le montant de la garantie?"
    language_="French"
    text="le montant de la garantie est € 1000"

    answer, score=question_extraction(text, question_, model_, tokenizer_, language_, verbose= True)
</code>```

I'm getting the following error:

```<code>C:\...\NLP\src>python question_extraction.py
OK
OK
convert squad examples to features: 100%|████████████████████████████████████████████████| 1/1 [00:00<00:00,  4.66it/s]
add example index and unique id: 100%|███████████████████████████████████████████████████████████| 1/1 [00:00<?, ?it/s]
Traceback (most recent call last):
  File "question_extraction.py", line 77, in <module>
    answer, score=question_extraction(text, question_, model_, tokenizer_, language_, verbose= True)
  File "question_extraction.py", line 60, in question_extraction
    output=nlp({'question':question, 'context': text})
  File "C:\...\transformers\pipelines.py", line 818, in __call__
    start, end = self.model(**fw_args)
ValueError: not enough values to unpack (expected 2, got 1)

</code>```

答:
As stated in the source, there is a specific QuestionAnsweringPipeline. Below example is what I used to successfully load the Flaubert model.

import transformers as trf
p = trf.QuestionAnsweringPipeline(model=trf.AutoModel.from_pretrained("fmikaelian/flaubert-base-uncased-squad"), tokenizer=trf.AutoTokenizer.from_pretrained("fmikaelian/flaubert-base-uncased-squad"))
```

Of course, there is also the alternative to use the pre-trained model FlaubertForQuestionAnswering, since pipelines just got released with the latest release and might be subject to change.

Body:
Hi I'm trying to use 'fmikaelian/flaubert-base-uncased-squad' for question answering. I understand that I should load the model and the tokenizers. I'm not sure how should I do this.

My code is basically far

from transformers import pipeline, BertTokenizer

nlp = pipeline('question-answering', \
model='fmikaelian/flaubert-base-uncased-squad', \
tokenizer='fmikaelian/flaubert-base-uncased-squad')

Most probably this can be solve with a two liner.

Many thanks

EDIT

I have also tried to use automodels but it seems those are not there:

OSError: Model name 'flaubert-base-uncased-squad' was not found in model name list (bert-base-uncased, bert-large-uncased, bert-base-cased, bert-large-cased, bert-base-multilingual-uncased, bert-base-multilingual-cased, bert-base-chinese, bert-base-german-cased, bert-large-uncased-whole-word-masking, bert-large-cased-whole-word-masking, bert-large-uncased-whole-word-masking-finetuned-squad, bert-large-cased-whole-word-masking-finetuned-squad, bert-base-cased-finetuned-mrpc, bert-base-german-dbmdz-cased, bert-base-german-dbmdz-uncased). We assumed 'flaubert-base-uncased-squad' was a path or url to a configuration file named config.json or a directory containing such a file but couldn't find any such file at this path or url.

EDIT II
I tried following the approach suggested with the following code that loads models that have been saved from S3:

tokenizer_ = FlaubertTokenizer.from_pretrained(MODELS)
model_ = FlaubertModel.from_pretrained(MODELS)

p = transformers.QuestionAnsweringPipeline(
    model=transformers.AutoModel.from_pretrained(MODELS),
    tokenizer=transformers.AutoTokenizer.from_pretrained(MODELS)
)

question_="Quel est le montant de la garantie?"
language_="French"
context_="le montant de la garantie est € 1000"

output=p({'question':question_, 'context': context_})
print(output)

Unfortunately I have been getting the following error:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\multiprocessing\spawn.py", line 105, in spawn_main
    exitcode = _main(fd)
Traceback (most recent call last):
  File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\multiprocessing\spawn.py", line 114, in _main
  File "question_extraction.py", line 61, in <module>
        prepare(preparation_data)
output=p({'question':question_, 'context': context_})  File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\multiprocessing\spawn.py", line 225, in prepare

      File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\site-packages\transformers\pipelines.py", line 802, in __call__
_fixup_main_from_path(data['init_main_from_path'])
  File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\multiprocessing\spawn.py", line 277, in _fixup_main_from_path
    run_name="__mp_main__")
  File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\runpy.py", line 263, in run_path
    pkg_name=pkg_name, script_name=fname)
  File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\runpy.py", line 96, in _run_module_code
    mod_name, mod_spec, pkg_name, script_name)
  File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\Users\... ...\Box Sync\nlp - 2...\NLP\src\question_extraction.py", line 61, in <module>
    output=p({'question':question_, 'context': context_})
  File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\site-packages\transformers\pipelines.py", line 802, in __call__
    for example in examples
      File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\site-packages\transformers\pipelines.py", line 802, in <listcomp>
for example in examples
for example in examples  File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\site-packages\transformers\pipelines.py", line 802, in <listcomp>

      File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\site-packages\transformers\data\processors\squad.py", line 304, in squad_convert_examples_to_features
for example in examples
  File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\site-packages\transformers\data\processors\squad.py", line 304, in squad_convert_examples_to_features
        with Pool(threads, initializer=squad_convert_example_to_features_init, initargs=(tokenizer,)) as p:with Pool(threads, initializer=squad_convert_example_to_features_init, initargs=(tokenizer,)) as p:

  File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\multiprocessing\context.py", line 119, in Pool
  File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\multiprocessing\context.py", line 119, in Pool
        context=self.get_context())context=self.get_context())

  File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\multiprocessing\pool.py", line 174, in __init__
  File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\multiprocessing\pool.py", line 174, in __init__
        self._repopulate_pool()self._repopulate_pool()

  File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\multiprocessing\pool.py", line 239, in _repopulate_pool
  File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\multiprocessing\pool.py", line 239, in _repopulate_pool
    w.start()
    w.start()
  File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\multiprocessing\process.py", line 105, in start
  File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\multiprocessing\process.py", line 105, in start
    self._popen = self._Popen(self)
      File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\multiprocessing\context.py", line 322, in _Popen
self._popen = self._Popen(self)
      File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\multiprocessing\context.py", line 322, in _Popen
return Popen(process_obj)
return Popen(process_obj)  File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\multiprocessing\popen_spawn_win32.py", line 65, in __init__

  File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\multiprocessing\popen_spawn_win32.py", line 33, in __init__
        prep_data = spawn.get_preparation_data(process_obj._name)reduction.dump(process_obj, to_child)

  File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\multiprocessing\spawn.py", line 143, in get_preparation_data
  File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\multiprocessing\reduction.py", line 60, in dump
    _check_not_importing_main()
  File "C:\Users\... ...\AppData\Local\Continuum\Anaconda3\envs\nlp_nlp\lib\multiprocessing\spawn.py", line 136, in _check_not_importing_main
    is not going to be frozen to produce an executable.''')
RuntimeError:
        An attempt has been made to start a new process before the
        current process has finished its bootstrapping phase.

        This probably means that you are not using fork to start your
        child processes and you have forgotten to use the proper idiom
        in the main module:

            if __name__ == '__main__':
                freeze_support()
                ...

        The "freeze_support()" line can be omitted if the program
        is not going to be frozen to produce an executable.
    ForkingPickler(file, protocol).dump(obj)
BrokenPipeError: [Errno 32] Broken pipe

*EDIT IV *

I solved the previous EDIT error by placing the functions inside the "main".
Unfortunately when I run the following code:

tokenizer_ = FlaubertTokenizer.from_pretrained(MODELS)
model_ = FlaubertModel.from_pretrained(MODELS)

def question_extraction(text, question, model, tokenizer, language="French", verbose=False):

    if language=="French":
        nlp = pipeline('question-answering', \
        model=model, \
        tokenizer=tokenizer)
    else:
        nlp=pipeline('question-answering')

    output=nlp({'question':question, 'context': text})

    answer, score = output.answer, output.score

    if verbose==True:
        print("Q: ", question ,"\n",\
              "A:", answer,"\n", \
              "Confidence (%):", "{0:.2f}".format(str(score*100) )
              )

    return answer, score

if __name__=="__main__":
    question_="Quel est le montant de la garantie?"
    language_="French"
    text="le montant de la garantie est € 1000"

    answer, score=question_extraction(text, question_, model_, tokenizer_, language_, verbose= True)

I'm getting the following error:

C:\...\NLP\src>python question_extraction.py
OK
OK
convert squad examples to features: 100%|████████████████████████████████████████████████| 1/1 [00:00<00:00,  4.66it/s]
add example index and unique id: 100%|███████████████████████████████████████████████████████████| 1/1 [00:00<?, ?it/s]
Traceback (most recent call last):
  File "question_extraction.py", line 77, in <module>
    answer, score=question_extraction(text, question_, model_, tokenizer_, language_, verbose= True)
  File "question_extraction.py", line 60, in question_extraction
    output=nlp({'question':question, 'context': text})
  File "C:\...\transformers\pipelines.py", line 818, in __call__
    start, end = self.model(**fw_args)
ValueError: not enough values to unpack (expected 2, got 1)

Body:
As stated in the source, there is a specific QuestionAnsweringPipeline. Below example is what I used to successfully load the Flaubert model.

import transformers as trf
p = trf.QuestionAnsweringPipeline(model=trf.AutoModel.from_pretrained("fmikaelian/flaubert-base-uncased-squad"), tokenizer=trf.AutoTokenizer.from_pretrained("fmikaelian/flaubert-base-uncased-squad"))

Of course, there is also the alternative to use the pre-trained model FlaubertForQuestionAnswering, since pipelines just got released with the latest release and might be subject to change.


问:
Find and replace tagged words from string using python?
I need to find and replace some tagged words from a paragraph.

```<code>str = "my name is [tag1]alan[/tag1] . i am a [tag2]python[/tag2] developer."
</code>```

tag1 and tag2 are words I need to find and replace their middle content with another word.
tags are not limited. it may have more than 10. but every tag is enclosed in the same way, like in square brackets, [tag][/tag].

I want a result like this,

```<code>str = "my name is alan . i am a python developer."
</code>```

Is there any way to do it using regex? without using beautifulsoup.

答:
you can use the following regular expression:

```<code>import re

my_str = 'my name is [tag1]alan[/tag1]. i am a [tag2]python[/tag2] developer.'

re.sub(r'\[[/]*tag\d+?\]', '', my_str )
</code>```

output:

```<code>'my name is alan . i am a python developer.'
</code>```

regex explanation:

\[ =  start with [

[/]* = next charcter can be / or not

tag = must contain the string tag

\d+?= must contain a number

\] = ends with ]

Body:
I need to find and replace some tagged words from a paragraph.

str = "my name is [tag1]alan[/tag1] . i am a [tag2]python[/tag2] developer."

tag1 and tag2 are words I need to find and replace their middle content with another word.
tags are not limited. it may have more than 10. but every tag is enclosed in the same way, like in square brackets, [tag][/tag].

I want a result like this,

str = "my name is alan . i am a python developer."

Is there any way to do it using regex? without using beautifulsoup.

Body:
you can use the following regular expression:

import re

my_str = 'my name is [tag1]alan[/tag1]. i am a [tag2]python[/tag2] developer.'

re.sub(r'\[[/]*tag\d+?\]', '', my_str )

output:

'my name is alan . i am a python developer.'

regex explanation:

\[ =  start with [

[/]* = next charcter can be / or not

tag = must contain the string tag

\d+?= must contain a number

\] = ends with ]


问:
Keras minibatch gradient descent with Dropout layer
I have a question about Dropout implementation in Keras/Tensorflow with mini-batch gradient descent optimization when batch_size parameter is bigger than one. The original paper says:

The only difference is that for each training case in a mini-batch, we
  sample a thinned network by dropping out units. Forward and
  backpropagation for that training case are done only on this thinned
  network. The gradients for each parameter are averaged over the
  training cases in each mini-batch. Any training case which does not
  use a parameter contributes a gradient of zero for that parameter.

But how is it implemented in Keras? As I understand, for each sample in a batch, individual gradient is calculated depending on the current model (as different units as dropped for different samples). Next after all samples from the batch are processed, for each weight respective gradients are summed, these sums are divided by batch_size and then applied to respective weights.

Going through source code I cannot see if and where it is handled. In the function _process_single_batch, the overall\avereged batch loss is computed and based on that batch gradient is calculated. This works fine for models without Dropout layer, but what about Dropout layer, how individual model settings for each sample (with different neurons dropped) are remembered and then taken into account during gradient descent calculation?

I think that I am missing something and I want to be sure that I understand correctly Keras implementation of mini-batch gradient descent when Dropout layer is involved.

答:
What you describe from the paper is a theoretical interpretation of how Dropout can be implemented. It is not really implemented like that in any framework.

Dropout is implemented as a layer that during training, samples a drop mask from a Bernoulli distribution with a given probability. This mask contains 0's and 1's, where a 0 means that this particular neuron was dropped.

Then automatic differentiation is used to compute the gradient through the Dropout layer, which just means multiplying component-wise the incoming gradient from the previous layer by the drop mask, which cancels the gradients from the dropped neurons.

As you mention, the drop mask is key to obtain the appropriate behavior. The gradients and forward pass are computed together, and a different drop mask is sampled for each sample in a batch, meaning that this works without additional support from the framework.

Implementing the full idea of dropping neurons would be much more complicated.


问:
Recyclerview reverse layout starting scroll position issue
I'm creating a chat app and for displaying messages I'm using recycler view. Newest messages are displayed on the bottom. The user scrolls up to see more messages.

When the chat screen is loaded the view doesn't start from the very bottom, and the newest message isn't visible. The user has to scroll down a few rows to see the newest message.  This is bad UI and the newest message should be visible at the end/bottom of the screen.

I'm using setReverseLayout(true) and setStackFromEnd(false), and I've searched online for similar issues with no luck. For now, I'm setting the scroll position to 0 right after setting up the recycler view with a delay, but this doesn't always work and it's jumpy.

If I set up recyclerview normally(without using setReverseLayout and setStackFromEnd), the newest message loads at the top each time perfectly as it should.

Here's the code to start recycler view:

```<code>RecyclerView recyclerView = findViewById(R.id.recyclerViewMessageRoom);
    adapter = new RA_MessageRoom(this, userFirebaseUid, messagesGroupedByDate, messageUsers);
    recyclerView.setAdapter(adapter);

    LinearLayoutManager layoutManager = new LinearLayoutManager(this);
    layoutManager.setReverseLayout(true);
    layoutManager.setStackFromEnd(false);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(layoutManager);

    // -- Workaround with delay - still doesn't completely work
    new Handler().postDelayed(() -> {
        recyclerView.scrollToPosition(0);
    }, 200);
</code>```

Anyone who's experienced this issue and knows how to resolve it please share! Thanks.

EDIT (6 JUL 2019):

Here is the recycler adapter's code. As a reminder if I remove the reverse layout settings it works perfectly fine.

RA_MessageRoom:

```<code>public class RA_MessageRoom extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final String TAG = "RA_MessageRoom";
private static final int TYPE_USER = 1;
private static final int TYPE_PARTICIPANT = 2;

private Context context;
private String userFirebaseUid;
private List<MessagesDateGrouper> messagesGroupedByDate;
private HashSet<MessagesUserModel> messageUsers;

public RA_MessageRoom(Context context, String userFirebaseUid, List<MessagesDateGrouper> messagesGroupedByDate, HashSet<MessagesUserModel> messageUsers) {
    this.context = context;
    this.userFirebaseUid = userFirebaseUid;
    this.messagesGroupedByDate = messagesGroupedByDate;
    this.messageUsers = messageUsers;
}

@Override
public int getItemViewType(int position) {

    if (messagesGroupedByDate.get(position).getViewType() == MessagesDateGrouper.TYPE_CHAT) {
        MessageChatItem message = (MessageChatItem) messagesGroupedByDate.get(position);
        if (message.getMessages().getSenderFirebaseUid().equals(userFirebaseUid)) {
            return TYPE_USER;
        } else {
            return TYPE_PARTICIPANT;
        }
    } else {
        return messagesGroupedByDate.get(position).getViewType();
    }
}

@Override
public int getItemCount() {
    return messagesGroupedByDate != null ? messagesGroupedByDate.size() : 0;
}

@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    final RecyclerView.ViewHolder holder;
    View view;

    switch (viewType) {
        case MessagesDateGrouper.TYPE_DATE:
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_message_room_separator, parent, false);
            holder = new MessageRoomDateVH(view);
            break;

        case TYPE_USER:
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_message_room_user, parent, false);
            holder = new MessageRoomUserVH(view);
            break;

        case TYPE_PARTICIPANT:
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_message_room_participant, parent, false);;
            holder = new MessageRoomParticipantVH(view);
            break;

        default:
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_message_room_user, parent, false);;
            holder = new MessageRoomUserVH(view);
            break;
    }

    return holder;
}

@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
    if (holder instanceof MessageRoomDateVH) {
        MessageDateItem date = (MessageDateItem) messagesGroupedByDate.get(position);
        ((MessageRoomDateVH)holder).date.setText(date.getDate());

    } else if (holder instanceof MessageRoomParticipantVH) {
        MessageRoomParticipantVH view = (MessageRoomParticipantVH) holder;
        MessageChatItem messageItem = (MessageChatItem) messagesGroupedByDate.get(position);
        MessagesModel message = messageItem.getMessages();

        view.name.setText(context.getString(R.string.unknown));
        view.profileImage.setImageResource(R.drawable.default_profile_image_grey);

        for (MessagesUserModel user: messageUsers) {
            if (user.getFirebaseId().equals(message.getSenderFirebaseUid())) {
                int fallbackImage;
                if (user.getMerchant() == null || !user.getMerchant()) {
                    fallbackImage = R.drawable.default_profile_image_grey;
                } else {
                    fallbackImage = R.drawable.store_profile;
                }

                GlideApp.with(context)
                        .load(user.getPhotoThumbUrl())
                        .placeholder(R.drawable.placeholder)
                        .fallback(fallbackImage)
                        .into(view.profileImage);

                view.name.setText(user.getName());
                break;
            }
        }

        if (message.getImageUrl() != null && !message.getImageUrl().equals("") ) {
            view.image.setVisibility(View.VISIBLE);
            view.imageSpinner.setVisibility(View.VISIBLE);
            view.chat.setVisibility(View.GONE);

            view.image.setClipToOutline(true);

            GlideApp.with(context)
                    .load(message.getImageUrl())
                    .placeholder(R.drawable.placeholder_message)
                    .fallback(R.drawable.placeholder_message)
                    .listener(new RequestListener<Drawable>() {
                        @Override
                        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                            return false;
                        }

                        @Override
                        public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                            view.imageSpinner.setVisibility(View.GONE);
                            return false;
                        }
                    })
                    .into(view.image);

        } else {
            view.chat.setVisibility(View.VISIBLE);
            view.image.setVisibility(View.GONE);
            view.imageSpinner.setVisibility(View.GONE);

            view.chat.setText(message.getMessageText());
        }

        String time = DateFormatService.messageRoomParseDateToTimeString(message.getDate());
        view.date.setText(time);

    } else if (holder instanceof MessageRoomUserVH){
        MessageRoomUserVH view = (MessageRoomUserVH) holder;
        MessageChatItem messageItem = (MessageChatItem) messagesGroupedByDate.get(position);
        MessagesModel message = messageItem.getMessages();

        if (message.getImageUrl() != null && !message.getImageUrl().equals("") ) {
            view.image.setVisibility(View.VISIBLE);
            view.imageSpinner.setVisibility(View.VISIBLE);
            view.chat.setVisibility(View.GONE);

            view.image.setClipToOutline(true);

            GlideApp.with(context)
                    .load(message.getImageUrl())
                    .placeholder(R.drawable.placeholder_message)
                    .fallback(R.drawable.placeholder_message)
                    .listener(new RequestListener<Drawable>() {
                        @Override
                        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                            return false;
                        }

                        @Override
                        public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                            view.imageSpinner.setVisibility(View.GONE);
                            return false;
                        }
                    })
                    .into(view.image);

        } else {
            view.chat.setVisibility(View.VISIBLE);
            view.image.setVisibility(View.GONE);
            view.imageSpinner.setVisibility(View.GONE);

            view.chat.setText(message.getMessageText());
        }

        String time = DateFormatService.messageRoomParseDateToTimeString(message.getDate());
        view.date.setText(time);
    }

}

public class MessageRoomDateVH extends RecyclerView.ViewHolder {
    TextView date;

    public MessageRoomDateVH(@NonNull View itemView) {
        super(itemView);
        date = itemView.findViewById(R.id.textMessageRoomDateSection);
    }
}

public class MessageRoomParticipantVH extends RecyclerView.ViewHolder {
    ImageView profileImage;
    TextView name;
    TextView chat;
    ImageView image;
    TextView date;
    ProgressBar imageSpinner;

    public MessageRoomParticipantVH(@NonNull View itemView) {
        super(itemView);

        profileImage = itemView.findViewById(R.id.imageMessageRoomParticipantProfile);
        name = itemView.findViewById(R.id.textMessageRoomParticipantName);
        chat = itemView.findViewById(R.id.textMessageRoomParticipantChat);
        image = itemView.findViewById(R.id.imageMessageRoomParticipantImage);
        date = itemView.findViewById(R.id.textMessageRoomParticipantDate);
        imageSpinner = itemView.findViewById(R.id.progressBarMessageRoomParticipantImage);

    }
}

public class MessageRoomUserVH extends RecyclerView.ViewHolder {
    TextView chat;
    ImageView image;
    TextView date;
    ProgressBar imageSpinner;

    public MessageRoomUserVH(@NonNull View itemView) {
        super(itemView);

        chat = itemView.findViewById(R.id.textMessageRoomUserChat);
        image = itemView.findViewById(R.id.imageMessageRoomUserImage);
        date = itemView.findViewById(R.id.textMessageRoomUserDate);
        imageSpinner = itemView.findViewById(R.id.progressBarMessageRoomUserImage);
    }
}
</code>```

}

EDIT:

Although the preference was to have stackFromEnd set to false, I ended up changing stackFromEnd from false to true, removed the delay, and kept setting the scroll position as suggested by the accepted answer to resolve this issue.

Updated Working Code:

```<code>RecyclerView recyclerView = findViewById(R.id.recyclerViewMessageRoom);
    adapter = new RA_MessageRoom(this, userFirebaseUid, messagesGroupedByDate, messageUsers);
    recyclerView.setAdapter(adapter);

    LinearLayoutManager layoutManager = new LinearLayoutManager(this);
    layoutManager.setReverseLayout(true);
    layoutManager.setStackFromEnd(true);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.scrollToPosition(0);
</code>```

Thanks for the help!

You  will also need to handle message loads on first page load and new messages received to be at bottom of recyclerview:

```<code>if (pageLoad) {

 list.add(Model)

} else {

 // Add to the top of the list (since list is reverse message will come at the bottom)
  list.add(0, Model)

}
</code>```

答:
You can set layout manager in xml and reverse layout. When we set reverse layout we find this issue. We can resolve it by adding setStackFromEnd =true</p>

```<code>    app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
    android:orientation="vertical"
    app:reverseLayout="true"
    app:stackFromEnd="true"
</code>```

Body:
I'm creating a chat app and for displaying messages I'm using recycler view. Newest messages are displayed on the bottom. The user scrolls up to see more messages.

When the chat screen is loaded the view doesn't start from the very bottom, and the newest message isn't visible. The user has to scroll down a few rows to see the newest message.  This is bad UI and the newest message should be visible at the end/bottom of the screen.

I'm using setReverseLayout(true) and setStackFromEnd(false), and I've searched online for similar issues with no luck. For now, I'm setting the scroll position to 0 right after setting up the recycler view with a delay, but this doesn't always work and it's jumpy.

If I set up recyclerview normally(without using setReverseLayout and setStackFromEnd), the newest message loads at the top each time perfectly as it should.

Here's the code to start recycler view:

RecyclerView recyclerView = findViewById(R.id.recyclerViewMessageRoom);
    adapter = new RA_MessageRoom(this, userFirebaseUid, messagesGroupedByDate, messageUsers);
    recyclerView.setAdapter(adapter);

    LinearLayoutManager layoutManager = new LinearLayoutManager(this);
    layoutManager.setReverseLayout(true);
    layoutManager.setStackFromEnd(false);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(layoutManager);

    // -- Workaround with delay - still doesn't completely work
    new Handler().postDelayed(() -> {
        recyclerView.scrollToPosition(0);
    }, 200);

Anyone who's experienced this issue and knows how to resolve it please share! Thanks.

EDIT (6 JUL 2019):

Here is the recycler adapter's code. As a reminder if I remove the reverse layout settings it works perfectly fine.

RA_MessageRoom:

public class RA_MessageRoom extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final String TAG = "RA_MessageRoom";
private static final int TYPE_USER = 1;
private static final int TYPE_PARTICIPANT = 2;

private Context context;
private String userFirebaseUid;
private List<MessagesDateGrouper> messagesGroupedByDate;
private HashSet<MessagesUserModel> messageUsers;

public RA_MessageRoom(Context context, String userFirebaseUid, List<MessagesDateGrouper> messagesGroupedByDate, HashSet<MessagesUserModel> messageUsers) {
    this.context = context;
    this.userFirebaseUid = userFirebaseUid;
    this.messagesGroupedByDate = messagesGroupedByDate;
    this.messageUsers = messageUsers;
}

@Override
public int getItemViewType(int position) {

    if (messagesGroupedByDate.get(position).getViewType() == MessagesDateGrouper.TYPE_CHAT) {
        MessageChatItem message = (MessageChatItem) messagesGroupedByDate.get(position);
        if (message.getMessages().getSenderFirebaseUid().equals(userFirebaseUid)) {
            return TYPE_USER;
        } else {
            return TYPE_PARTICIPANT;
        }
    } else {
        return messagesGroupedByDate.get(position).getViewType();
    }
}

@Override
public int getItemCount() {
    return messagesGroupedByDate != null ? messagesGroupedByDate.size() : 0;
}

@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    final RecyclerView.ViewHolder holder;
    View view;

    switch (viewType) {
        case MessagesDateGrouper.TYPE_DATE:
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_message_room_separator, parent, false);
            holder = new MessageRoomDateVH(view);
            break;

        case TYPE_USER:
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_message_room_user, parent, false);
            holder = new MessageRoomUserVH(view);
            break;

        case TYPE_PARTICIPANT:
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_message_room_participant, parent, false);;
            holder = new MessageRoomParticipantVH(view);
            break;

        default:
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_message_room_user, parent, false);;
            holder = new MessageRoomUserVH(view);
            break;
    }

    return holder;
}

@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
    if (holder instanceof MessageRoomDateVH) {
        MessageDateItem date = (MessageDateItem) messagesGroupedByDate.get(position);
        ((MessageRoomDateVH)holder).date.setText(date.getDate());

    } else if (holder instanceof MessageRoomParticipantVH) {
        MessageRoomParticipantVH view = (MessageRoomParticipantVH) holder;
        MessageChatItem messageItem = (MessageChatItem) messagesGroupedByDate.get(position);
        MessagesModel message = messageItem.getMessages();

        view.name.setText(context.getString(R.string.unknown));
        view.profileImage.setImageResource(R.drawable.default_profile_image_grey);

        for (MessagesUserModel user: messageUsers) {
            if (user.getFirebaseId().equals(message.getSenderFirebaseUid())) {
                int fallbackImage;
                if (user.getMerchant() == null || !user.getMerchant()) {
                    fallbackImage = R.drawable.default_profile_image_grey;
                } else {
                    fallbackImage = R.drawable.store_profile;
                }

                GlideApp.with(context)
                        .load(user.getPhotoThumbUrl())
                        .placeholder(R.drawable.placeholder)
                        .fallback(fallbackImage)
                        .into(view.profileImage);

                view.name.setText(user.getName());
                break;
            }
        }

        if (message.getImageUrl() != null && !message.getImageUrl().equals("") ) {
            view.image.setVisibility(View.VISIBLE);
            view.imageSpinner.setVisibility(View.VISIBLE);
            view.chat.setVisibility(View.GONE);

            view.image.setClipToOutline(true);

            GlideApp.with(context)
                    .load(message.getImageUrl())
                    .placeholder(R.drawable.placeholder_message)
                    .fallback(R.drawable.placeholder_message)
                    .listener(new RequestListener<Drawable>() {
                        @Override
                        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                            return false;
                        }

                        @Override
                        public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                            view.imageSpinner.setVisibility(View.GONE);
                            return false;
                        }
                    })
                    .into(view.image);

        } else {
            view.chat.setVisibility(View.VISIBLE);
            view.image.setVisibility(View.GONE);
            view.imageSpinner.setVisibility(View.GONE);

            view.chat.setText(message.getMessageText());
        }

        String time = DateFormatService.messageRoomParseDateToTimeString(message.getDate());
        view.date.setText(time);

    } else if (holder instanceof MessageRoomUserVH){
        MessageRoomUserVH view = (MessageRoomUserVH) holder;
        MessageChatItem messageItem = (MessageChatItem) messagesGroupedByDate.get(position);
        MessagesModel message = messageItem.getMessages();

        if (message.getImageUrl() != null && !message.getImageUrl().equals("") ) {
            view.image.setVisibility(View.VISIBLE);
            view.imageSpinner.setVisibility(View.VISIBLE);
            view.chat.setVisibility(View.GONE);

            view.image.setClipToOutline(true);

            GlideApp.with(context)
                    .load(message.getImageUrl())
                    .placeholder(R.drawable.placeholder_message)
                    .fallback(R.drawable.placeholder_message)
                    .listener(new RequestListener<Drawable>() {
                        @Override
                        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                            return false;
                        }

                        @Override
                        public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                            view.imageSpinner.setVisibility(View.GONE);
                            return false;
                        }
                    })
                    .into(view.image);

        } else {
            view.chat.setVisibility(View.VISIBLE);
            view.image.setVisibility(View.GONE);
            view.imageSpinner.setVisibility(View.GONE);

            view.chat.setText(message.getMessageText());
        }

        String time = DateFormatService.messageRoomParseDateToTimeString(message.getDate());
        view.date.setText(time);
    }

}

public class MessageRoomDateVH extends RecyclerView.ViewHolder {
    TextView date;

    public MessageRoomDateVH(@NonNull View itemView) {
        super(itemView);
        date = itemView.findViewById(R.id.textMessageRoomDateSection);
    }
}

public class MessageRoomParticipantVH extends RecyclerView.ViewHolder {
    ImageView profileImage;
    TextView name;
    TextView chat;
    ImageView image;
    TextView date;
    ProgressBar imageSpinner;

    public MessageRoomParticipantVH(@NonNull View itemView) {
        super(itemView);

        profileImage = itemView.findViewById(R.id.imageMessageRoomParticipantProfile);
        name = itemView.findViewById(R.id.textMessageRoomParticipantName);
        chat = itemView.findViewById(R.id.textMessageRoomParticipantChat);
        image = itemView.findViewById(R.id.imageMessageRoomParticipantImage);
        date = itemView.findViewById(R.id.textMessageRoomParticipantDate);
        imageSpinner = itemView.findViewById(R.id.progressBarMessageRoomParticipantImage);

    }
}

public class MessageRoomUserVH extends RecyclerView.ViewHolder {
    TextView chat;
    ImageView image;
    TextView date;
    ProgressBar imageSpinner;

    public MessageRoomUserVH(@NonNull View itemView) {
        super(itemView);

        chat = itemView.findViewById(R.id.textMessageRoomUserChat);
        image = itemView.findViewById(R.id.imageMessageRoomUserImage);
        date = itemView.findViewById(R.id.textMessageRoomUserDate);
        imageSpinner = itemView.findViewById(R.id.progressBarMessageRoomUserImage);
    }
}

}

EDIT:

Although the preference was to have stackFromEnd set to false, I ended up changing stackFromEnd from false to true, removed the delay, and kept setting the scroll position as suggested by the accepted answer to resolve this issue.

Updated Working Code:

RecyclerView recyclerView = findViewById(R.id.recyclerViewMessageRoom);
    adapter = new RA_MessageRoom(this, userFirebaseUid, messagesGroupedByDate, messageUsers);
    recyclerView.setAdapter(adapter);

    LinearLayoutManager layoutManager = new LinearLayoutManager(this);
    layoutManager.setReverseLayout(true);
    layoutManager.setStackFromEnd(true);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.scrollToPosition(0);

Thanks for the help!

You  will also need to handle message loads on first page load and new messages received to be at bottom of recyclerview:

if (pageLoad) {

 list.add(Model)

} else {

 // Add to the top of the list (since list is reverse message will come at the bottom)
  list.add(0, Model)

}

Body:
You can set layout manager in xml and reverse layout. When we set reverse layout we find this issue. We can resolve it by adding setStackFromEnd =true

    app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
    android:orientation="vertical"
    app:reverseLayout="true"
    app:stackFromEnd="true"


问:
Retrieving Reduced Cost of Dvar composed of "tuples" in CPLEX OPL
I want to retrieve the reduced cost of a decision variable in CPLEX OPL.
However, the dvar indices are tuples, and cplex cannot iterate over a tuple to print the reduced costs. Is it impossible with tuples, or is there a way for it?
For example there is a decision variable as below:

```<code>dvar float+ Production[ProductionLocations][TimePeriods];

tuple timeperiod {
  string TimePeriodID;
  string TimePeriodName;
  float CurrencyRate;
  float Rank;
  string ActivePeriod;
}
{timeperiod} TimePeriods = ...;
tuple productionlocation {
  string ProductID;
  string ProductName;
  string LocationID;
  string LocationName;
}
{productionlocation} ProductionLocations = ...;
</code>```

Thanks in advance.

答:
Let me expand on Alex's answer: it seems you attempt to query dual values for a MIP. Dual values are however not defined for MIPs. You have two options here:

You can relax all the variables and solve the relaxed problem. That is an LP and will thus provide duals. However, this may not be too helpful.

You can compute the optimal solution to the MIP, fix all integer variables and then solve the remaining problem. This is again an LP and will thus provide dual values. These dual values may be more meaningful than the values you get from relaxing everything.

In order to do the second thing, you can still use scripting:

```<code>main {
  thisOplModel.generate();
  cplex.solve(); // Compute integer optimal solution
  cplex.solveFixed(); // Fix integer variables to optimal values, solve LP
  // query your dual values:
  for (var g in Gasolines) {
    writeln("a[",g,"].reducedCost = ",a[g].reducedCost);
  }
}
</code>```

Body:
I want to retrieve the reduced cost of a decision variable in CPLEX OPL.
However, the dvar indices are tuples, and cplex cannot iterate over a tuple to print the reduced costs. Is it impossible with tuples, or is there a way for it?
For example there is a decision variable as below:

dvar float+ Production[ProductionLocations][TimePeriods];

tuple timeperiod {
  string TimePeriodID;
  string TimePeriodName;
  float CurrencyRate;
  float Rank;
  string ActivePeriod;
}
{timeperiod} TimePeriods = ...;
tuple productionlocation {
  string ProductID;
  string ProductName;
  string LocationID;
  string LocationName;
}
{productionlocation} ProductionLocations = ...;

Thanks in advance.

Body:
Let me expand on Alex's answer: it seems you attempt to query dual values for a MIP. Dual values are however not defined for MIPs. You have two options here:

You can relax all the variables and solve the relaxed problem. That is an LP and will thus provide duals. However, this may not be too helpful.

You can compute the optimal solution to the MIP, fix all integer variables and then solve the remaining problem. This is again an LP and will thus provide dual values. These dual values may be more meaningful than the values you get from relaxing everything.

In order to do the second thing, you can still use scripting:

main {
  thisOplModel.generate();
  cplex.solve(); // Compute integer optimal solution
  cplex.solveFixed(); // Fix integer variables to optimal values, solve LP
  // query your dual values:
  for (var g in Gasolines) {
    writeln("a[",g,"].reducedCost = ",a[g].reducedCost);
  }
}


问:
"Reading initial communication packet" error while trying to connect to a mysql docker container from the host
I'd like to be able to connect to my docker container as if MySQL server were installed on my local machine. I test my connection with:

```<code>mysql -u root -proot -h 127.0.0.1 -P 3306 --protocol=tcp
</code>```

If I create a container using docker, I can successfully do it. Like this:

```<code>docker run --name some-mysql-standalone -p 127.0.0.1:3306:3306 -e MYSQL_ROOT_PASSWORD=root -d mysql:5.7.29
</code>```

If I use a container as a service in docker-compose, I get an error:

```<code>ERROR 2013 (HY000): Lost connection to MySQL server at 'reading initial communication packet', system error: 2
</code>```

MySQL server is running inside the container and I can access it.

My docker compose snippet:

```<code>version: '2'

services:

    mysql:

        image: mysql:5.7.29
        container_name: some_mysql
        restart: unless-stopped

        volumes:
            - ./mysql/data:/var/lib/mysql
            - ./mysql/init:/docker-entrypoint-initdb.d

        ports:
            - 3306:3306

        environment:
            MYSQL_DATABASE: some_mysql
            MYSQL_USER: root
            MYSQL_PASSWORD: root
            MYSQL_ROOT_PASSWORD: root
</code>```

The interesting part is that I've been using this docker-compose.yml for some time now without any issues. I'm not really sure what's changed about my environment that caused it to stop working.

How can I make my mysql container in docker-compose accessible from the host machine?

答: Found a similar error on this thread. See if any of your firewall configuration has been changed and try to bind your SQL server to 0.0.0.0 instead of localhost or 127.0.0.1.

Body:
I'd like to be able to connect to my docker container as if MySQL server were installed on my local machine. I test my connection with:

mysql -u root -proot -h 127.0.0.1 -P 3306 --protocol=tcp

If I create a container using docker, I can successfully do it. Like this:

docker run --name some-mysql-standalone -p 127.0.0.1:3306:3306 -e MYSQL_ROOT_PASSWORD=root -d mysql:5.7.29

If I use a container as a service in docker-compose, I get an error:

ERROR 2013 (HY000): Lost connection to MySQL server at 'reading initial communication packet', system error: 2

MySQL server is running inside the container and I can access it.

My docker compose snippet:

version: '2'

services:

    mysql:

        image: mysql:5.7.29
        container_name: some_mysql
        restart: unless-stopped

        volumes:
            - ./mysql/data:/var/lib/mysql
            - ./mysql/init:/docker-entrypoint-initdb.d

        ports:
            - 3306:3306

        environment:
            MYSQL_DATABASE: some_mysql
            MYSQL_USER: root
            MYSQL_PASSWORD: root
            MYSQL_ROOT_PASSWORD: root

The interesting part is that I've been using this docker-compose.yml for some time now without any issues. I'm not really sure what's changed about my environment that caused it to stop working.

How can I make my mysql container in docker-compose accessible from the host machine?


Title: How can I get my time strings in a right format?

Body:
I am stuck with converting strings to times. I am aware that there are many topics on Stack regarding converting strings-to-times, however I couldn't fix this problem with the solutions.

Situation
I have a file with times like this:

> dput(df$Time[1:50])
c("1744.3", "2327.54", "1718.51", "2312.3200000000002", "1414.16",
"2046.15", "1442.5", "1912.22", "2303.2199999999998", "2146.3200000000002",
"1459.02", "1930.15", "1856.23", "2319.15", "1451.05", "25.460000000000036",
"1453.25", "2309.02", "2342.48", "2322.5300000000002", "2101.5",
"2026.07", "1245.04", "1945.15", "5.4099999999998545", "1039.5",
"1731.37", "2058.41", "2030.36", "1814.31", "1338.18", "1858.33",
"1731.36", "2343.38", "1733.27", "2304.59", "1309.47", "1916.11",
"1958.3", "1929.54", "1756.4", "1744.23", "1731.26", "1844.47",
"1353.25", "1958.3", "1746.44", "1857.53", "2047.15", "2327.2199999999998", "1915"
)

In this example, the times should be like this:

"1744.3"   = 17:44:30
"2327.54"  = 23:27:54
"1718.51"  = 17:18:51
"2312.3200000000002" = 23:12:32
...
"25.460000000000036" = 00:25:46 # as you can see, the first two 00 are missing.

"1915" = 19:15:00

However, I tried multiple things (and now I am even stuck with str_replace()). Hopefully some one knows how I can transform this.

What have I tried?

format(df$Time, "%H%M.%S") # Yes I know...

# So therefore I thought, lets replace the strings to get them in a proper format
# like HH:MM:SS. First step was to replace the "." for a ":"

str_replace("." , ":", df$Time) # this was leading to "." (don't know why)

And that was the point that I was so frustrated that I posted it on Stack. Hope that you guys can help me.

Many thanks in advance!

Body:
The main problem is the time "25.460000000000036". But I think I found a clear though somewhat verbose solution:

library(tidyverse)

df %>%
  mutate(hours = formatC(as.numeric(Time), width = 4, format = "d", flag = "0"),
         seconds = as.numeric(str_extract(Time, "[.].+")) * 100) %>%
  mutate(Time_new = stringi::stri_datetime_parse(paste0(hours, seconds), format = "HHmm.ss"))
#> # A tibble: 51 x 4
#>    Time               hours seconds Time_new
#>    <chr>              <chr>   <dbl> <dttm>
#>  1 25.460000000000036 0025     46.  2020-02-19 00:25:46  # I changed the order of the times so the weird format is on top
#>  2 1744.3             1744     30   2020-02-19 17:44:30
#>  3 2327.54            2327     54   2020-02-19 23:27:54
#>  4 1718.51            1718     51   2020-02-19 17:18:51
#>  5 2312.3200000000002 2312     32.  2020-02-19 23:12:32
#>  6 1414.16            1414     16   2020-02-19 14:14:16
#>  7 2046.15            2046     15   2020-02-19 20:46:15
#>  8 1442.5             1442     50   2020-02-19 14:42:50
#>  9 1912.22            1912     22   2020-02-19 19:12:22
#> 10 2303.2199999999998 2303     22.0 2020-02-19 23:03:21
#> # ... with 41 more rows

If you also have times without fractions (i.e., without the dot) you could use this approach:

normalize_time <- function(t) {
  formatC(as.numeric(t) * 100, width = 6, format = "d", flag = "0")
}

df %>%
  mutate(Time_new = as.POSIXct(normalize_time(Time), format = "%H%M%S"))


问:
Does Spring-Data-JDBC support Oracle identity columns?
I'm trying to save into a table with an Oracle identity field (it's some sort of auto increment). But as soon as I do that I get an "identity must not be null after save" exception ?

Is this scenario currently not supported or do I need a special config ?

BTW: it's works with JPA.

答:
Yes, your assumption is correct.
Spring Data JDBC currently does not identity fields with Oracle Databases.</p>


问:
binding to observable collection silverlight 4, grid
Can I bind a simple 'grid' to an observable collection? So i have a grid with just one column and several rows. The rows get populated at runtime with some hyperlinks which can get deleted/added etc. I don't want to write functions to add/remove them from the grid everytime and would prefer to use an observable collection and let the grid update itself. Can a simple grid do that ? i tried but it didn't even compile.

Thanks

[EDIT] Solved. The marked answer is correct [/EDIT]

答:
Silverlight does not support this. You have two options, either use a DataGrid or use the following code that allows you to use a Grid within an ItemsControl which will achieve what you are after.

http://www.scottlogic.co.uk/blog/colin/2010/11/using-a-grid-as-the-panel-for-an-itemscontrol/

ContentLicense: CC BY-SA 3.0


问:
How to set POSIX message queues limit to unlimited in docker container using --ulimit option
How to set the POSIX message queues limit as unlimited for docker container.

I know that --ulimit is an option that can be used along with docker run, but i'm not quite sure on how to use the --ulimit option along with docker run for POSIX message queues.

tried following but did not work:

docker run -it --ulimit msgqueue=unlimited

Also tried following within container

ulimit -q unlimited

error: Operation not permitted

答:
Got to know that --ulimit in docker does not support the value unlimited

The way to do it is

```<code>docker run -it --ulimit msgqueue=100000000:100000000
</code>```

100000000 is for 100GB

Body:
Got to know that --ulimit in docker does not support the value unlimited

The way to do it is

docker run -it --ulimit msgqueue=100000000:100000000

100000000 is for 100GB


问:
Slope/Intercept ratio with Purrr in R
I'm looking to print a one way view for the ratio between the slope and the intercept.

so far I've got:

```<code>mtcars %>% split(.$cyl) %>%
  map(~lm(mpg~wt, data =.)) %>%
  map(coefficients) %>% map_dbl("(Intercept)")

mtcars %>% split(.$cyl) %>%
  map(~lm(mpg~wt, data =.)) %>%
  map(coefficients) %>% map_dbl("wt")
</code>```

This works and prints the intercept and slope as required but i cant seem to do any calculations on either.

I've tried the following to get the ratio between the two.

```<code>mtcars %>% split(.$cyl) %>%
  map(~lm(mpg~wt, data =.)) %>%
  map(coefficients) %>% map_dbl("wt")/map_dbl("(Intercept)")

mtcars %>% split(.$cyl) %>%
  map(~lm(mpg~wt, data =.)) %>%
  map(coefficients) %>% map_dbl("wt"/"(Intercept)")

mtcars %>% split(.$cyl) %>%
  map(~lm(mpg~wt, data =.)) %>%
  map(coefficients) %>% map_dbl(map_dbl("wt")/map_dbl("(Intercept)"))
</code>```

Any help appreciated, thanks.

答:
Another way without purrr, but with broom:</p>

```<code>library(broom)
library(dplyr)

mtcars %>% group_by(cyl) %>%
do(tidy(lm(mpg~wt, data =.))) %>%
summarize(ratio=estimate[2]/estimate[1])
# A tibble: 3 x 2
    cyl   ratio
  <dbl>   <dbl>
1     4 -0.143
2     6 -0.0979
3     8 -0.0919
</code>```

Title: Slope/Intercept ratio with Purrr in R

Body:
I'm looking to print a one way view for the ratio between the slope and the intercept.

so far I've got:

mtcars %>% split(.$cyl) %>%
  map(~lm(mpg~wt, data =.)) %>%
  map(coefficients) %>% map_dbl("(Intercept)")

mtcars %>% split(.$cyl) %>%
  map(~lm(mpg~wt, data =.)) %>%
  map(coefficients) %>% map_dbl("wt")

This works and prints the intercept and slope as required but i cant seem to do any calculations on either.

I've tried the following to get the ratio between the two.

mtcars %>% split(.$cyl) %>%
  map(~lm(mpg~wt, data =.)) %>%
  map(coefficients) %>% map_dbl("wt")/map_dbl("(Intercept)")

mtcars %>% split(.$cyl) %>%
  map(~lm(mpg~wt, data =.)) %>%
  map(coefficients) %>% map_dbl("wt"/"(Intercept)")

mtcars %>% split(.$cyl) %>%
  map(~lm(mpg~wt, data =.)) %>%
  map(coefficients) %>% map_dbl(map_dbl("wt")/map_dbl("(Intercept)"))

Any help appreciated, thanks.

Body:
Another way without purrr, but with broom:

library(broom)
library(dplyr)

mtcars %>% group_by(cyl) %>%
do(tidy(lm(mpg~wt, data =.))) %>%
summarize(ratio=estimate[2]/estimate[1])
# A tibble: 3 x 2
    cyl   ratio
  <dbl>   <dbl>
1     4 -0.143
2     6 -0.0979
3     8 -0.0919


问:
Regex find match word with some range front word
I Have a list of Word

"Dany buy some pear and apple"

"Dany eat the apple"

"Dany love apple"

"Dany make apple pie"

I really dont understand the keyword what is this.
But i want make some like this
Dany{2}(apple) =  find dany with the apple but max between dany and apple is 2 word

so it will give the result

```<code>Dany love apple
Dany make apple pie
Dany eat the apple
</code>```

答: This might do the trick .*Dany (?=(?:\w*(?: \w*)?)? apple).*.https://regex101.com/r/8ouNpf/5.

Body:
I Have a list of Word

"Dany buy some pear and apple"

"Dany eat the apple"

"Dany love apple"

"Dany make apple pie"

I really dont understand the keyword what is this.
But i want make some like this
Dany{2}(apple) =  find dany with the apple but max between dany and apple is 2 word

so it will give the result

Dany love apple
Dany make apple pie
Dany eat the apple


问:
I have writtten code to check if there is even one entry in database to give message duplicate entry
```<code>jQuery(document).ready(function(){
jQuery("#save_btn").click(function(){
            kabina=jQuery("#d_id").val();
            var city = $('.city option:selected').map(function(idx, elem) {
            return $(elem).html();
            }).get();//alert(city);
            //city=jQuery("#ct_title").val();
            $.ajax({
                type:'POST',
                url:'<?php  echo $menulink;?>/checkunique',
                data:{city:city,kabina:kabina},
                success:function(data){
                    //alert(data);
                    if(data == 'True')
                    {
                        toastr.success("Building Created",'Attention',{"positionClass": "toast-bottom-full-width" });
                        $("#city_frm").submit();
                    }
                    else
                    {
                        toastr.error("Building Created",'Attention',{"positionClass": "toast-bottom-full-width" });
                        $("#city_frm").submit();
                    }
                    //alert(data);
                }
            })
        })
    })
</code>```

Here is the ajax from which the controller check unique method is called
This is the controller

```<code>public function checkunique(){
        $count=array();
        if(isset($_POST['kabina'])){
            //$ct_id = $_POST['ct_id'];
            $kabina = $_POST['kabina'];
            $city = $_POST['city'];//print_r($city);

            foreach($city as $ct_title)
            {//print_r($ct_title);
            $ct_count=$this->mod_atyatbox_cities->city_count($ct_title,$kabina);//print_r($ct_count);die;;
                $count[]=$ct_count;
            }//print_r($count);die;
            if(in_array(1,$count))
            {
                echo "False";
            }
            else if(in_array(0,$count))
            {
                echo "True";
            }
}
</code>```

Here is teh model where query is wrote to check for duplicate entry

```<code>function city_count($ct_title,$kabina_id)
{
    $query="select ct_title from city where ct_title='$ct_title' and kabina_id=$kabina_id";
    $result=$this->db->query($query)->num_rows();//echo $result;die;
    return $result;
}
</code>```

Here if I print the query it prints. But when I return the data it returns 0 even if there is 1.

答:
Check all the query from the array </p>

```<code>foreach($city as $ct_title){
    $ct_count=$this->mod_atyatbox_cities->city_count($ct_title,$kabina);
    $count[]=$ct_count;
    $queries[]=$this->db->last_query();
}
print_r($queries);die;
</code>```

Body:
jQuery(document).ready(function(){
jQuery("#save_btn").click(function(){
            kabina=jQuery("#d_id").val();
            var city = $('.city option:selected').map(function(idx, elem) {
            return $(elem).html();
            }).get();//alert(city);
            //city=jQuery("#ct_title").val();
            $.ajax({
                type:'POST',
                url:'<?php  echo $menulink;?>/checkunique',
                data:{city:city,kabina:kabina},
                success:function(data){
                    //alert(data);
                    if(data == 'True')
                    {
                        toastr.success("Building Created",'Attention',{"positionClass": "toast-bottom-full-width" });
                        $("#city_frm").submit();
                    }
                    else
                    {
                        toastr.error("Building Created",'Attention',{"positionClass": "toast-bottom-full-width" });
                        $("#city_frm").submit();
                    }
                    //alert(data);
                }
            })
        })
    })

Here is the ajax from which the controller check unique method is called
This is the controller

public function checkunique(){
        $count=array();
        if(isset($_POST['kabina'])){
            //$ct_id = $_POST['ct_id'];
            $kabina = $_POST['kabina'];
            $city = $_POST['city'];//print_r($city);

            foreach($city as $ct_title)
            {//print_r($ct_title);
            $ct_count=$this->mod_atyatbox_cities->city_count($ct_title,$kabina);//print_r($ct_count);die;;
                $count[]=$ct_count;
            }//print_r($count);die;
            if(in_array(1,$count))
            {
                echo "False";
            }
            else if(in_array(0,$count))
            {
                echo "True";
            }
}

Here is teh model where query is wrote to check for duplicate entry

function city_count($ct_title,$kabina_id)
{
    $query="select ct_title from city where ct_title='$ct_title' and kabina_id=$kabina_id";
    $result=$this->db->query($query)->num_rows();//echo $result;die;
    return $result;
}

Here if I print the query it prints. But when I return the data it returns 0 even if there is 1.

Body:
Check all the query from the array

foreach($city as $ct_title){
    $ct_count=$this->mod_atyatbox_cities->city_count($ct_title,$kabina);
    $count[]=$ct_count;
    $queries[]=$this->db->last_query();
}
print_r($queries);die;