问:
Excel VBA - delete range of cells based on criteria
I want to delete a "row-range" of cells and shift them up, if one cell (column K8:Kxxxx) isn't "6-Other miscellaneous Cluster".

```<code>With wb2.Sheets("CALC")
    .Range("L8:L" & LastRow3).Formula = "=IF(G8="""","""",CONCATENATE(G8,""/"",VALUE(TEXT(I8,""00#""))))" 'REF'
End With

deleteIds = Array("OTIF", "2-Stock Availability on Non Stock item", "1-Not in full or rejected", "3-Stock Availability on Stock item", "4-Credit Release after MAD", "5-Actual PGI after planned PGI") ' Put your employee ids in here
For Each employeeId In Range(ActiveSheet.Range("K8"), ActiveSheet.Range("K8").End(xlDown))
   If Not (IsError(Application.Match(employeeId.Value, deleteIds, 0))) Then
       ActiveSheet.Range("G" & employeeId.Row).Value = ""
       ActiveSheet.Range("H" & employeeId.Row).Value = ""
       ActiveSheet.Range("I" & employeeId.Row).Value = ""
       ActiveSheet.Range("J" & employeeId.Row).Value = ""
       ActiveSheet.Range("K" & employeeId.Row).Value = ""
       ActiveSheet.Range("L" & employeeId.Row).Value = ""
   End If
Next

lastrow4 = Range("D:D").End(xlDown).Row
For i = lastrow4 To 1 Step -1
    If IsEmpty(Cells(i, "D").Value2) Then
        Cells(i, "G8:L50000").Delete Shift:=xlShiftUp
    End If
Next i

Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic

MsgBox "DONE!"
</code>```

This is just the part of the macro, where i tried to delete the cells that don't match the criteria. At the moment the macro looks for every possible value except "06-Other..." and clears the content of the cells in range G8:Lxxx. But I can't get it to delete and shift up the blank cells. Hopefully someone can solve my Problem.

答:
You can use a DelRng object of type Range, and every time it matches (or doesn't match) your criteria, you add this range toDelRngusing theUnion` function.

Note: try to avoid using ActiveSheet, instead use fully qualifed Worksheets object (see code below):

```<code>Dim DelRng As Range

With ThisWorkbook.Sheets("Sheet1") ' <-- modify "Sheet1" to your sheet's name
    deleteIds = Array("OTIF", "2-Stock Availability on Non Stock item", "1-Not in full or rejected", "3-Stock Availability on Stock item", "4-Credit Release after MAD", "5-Actual PGI after planned PGI") ' Put your employee ids in here
    For Each employeeId In .Range(.Range("K8"), .Range("K8").End(xlDown))
        If Not (IsError(Application.Match(employeeId.Value, deleteIds, 0))) Then
            If Not DelRng Is Nothing Then
                Set DelRng = Application.Union(DelRng, .Range(.Cells(employeeId.Row, "G"), .Cells(employeeId.Row, "L")))
            Else
                Set DelRng = .Range(.Cells(employeeId.Row, "G"), .Cells(employeeId.Row, "L"))
            End If
        End If
    Next
End With

' delete entire range at one-shot
If Not DelRng Is Nothing Then DelRng.Delete
</code>```

Body:
I want to delete a "row-range" of cells and shift them up, if one cell (column K8:Kxxxx) isn't "6-Other miscellaneous Cluster".

With wb2.Sheets("CALC")
    .Range("L8:L" & LastRow3).Formula = "=IF(G8="""","""",CONCATENATE(G8,""/"",VALUE(TEXT(I8,""00#""))))" 'REF'
End With

deleteIds = Array("OTIF", "2-Stock Availability on Non Stock item", "1-Not in full or rejected", "3-Stock Availability on Stock item", "4-Credit Release after MAD", "5-Actual PGI after planned PGI") ' Put your employee ids in here
For Each employeeId In Range(ActiveSheet.Range("K8"), ActiveSheet.Range("K8").End(xlDown))
   If Not (IsError(Application.Match(employeeId.Value, deleteIds, 0))) Then
       ActiveSheet.Range("G" & employeeId.Row).Value = ""
       ActiveSheet.Range("H" & employeeId.Row).Value = ""
       ActiveSheet.Range("I" & employeeId.Row).Value = ""
       ActiveSheet.Range("J" & employeeId.Row).Value = ""
       ActiveSheet.Range("K" & employeeId.Row).Value = ""
       ActiveSheet.Range("L" & employeeId.Row).Value = ""
   End If
Next

lastrow4 = Range("D:D").End(xlDown).Row
For i = lastrow4 To 1 Step -1
    If IsEmpty(Cells(i, "D").Value2) Then
        Cells(i, "G8:L50000").Delete Shift:=xlShiftUp
    End If
Next i

Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic

MsgBox "DONE!"

This is just the part of the macro, where i tried to delete the cells that don't match the criteria. At the moment the macro looks for every possible value except "06-Other..." and clears the content of the cells in range G8:Lxxx. But I can't get it to delete and shift up the blank cells. Hopefully someone can solve my Problem.

Body:
You can use a DelRng object of type Range, and every time it matches (or doesn't match) your criteria, you add this range toDelRngusing theUnion` function.

Note: try to avoid using ActiveSheet, instead use fully qualifed Worksheets object (see code below):

Dim DelRng As Range

With ThisWorkbook.Sheets("Sheet1") ' <-- modify "Sheet1" to your sheet's name
    deleteIds = Array("OTIF", "2-Stock Availability on Non Stock item", "1-Not in full or rejected", "3-Stock Availability on Stock item", "4-Credit Release after MAD", "5-Actual PGI after planned PGI") ' Put your employee ids in here
    For Each employeeId In .Range(.Range("K8"), .Range("K8").End(xlDown))
        If Not (IsError(Application.Match(employeeId.Value, deleteIds, 0))) Then
            If Not DelRng Is Nothing Then
                Set DelRng = Application.Union(DelRng, .Range(.Cells(employeeId.Row, "G"), .Cells(employeeId.Row, "L")))
            Else
                Set DelRng = .Range(.Cells(employeeId.Row, "G"), .Cells(employeeId.Row, "L"))
            End If
        End If
    Next
End With

' delete entire range at one-shot
If Not DelRng Is Nothing Then DelRng.Delete


来源: stackexchange

问:
Timer can not be repeated on android How to fix?
I want Timer execute repeat.
so I try this source

```<code>public static void init() {
    TimerTask timerTask = new TimerTask() {
       @Override
       public void run() {
           Looper.prepare();
           recordWork();
           Looper.loop();
       }
    };
    Timer timer = new Timer();
    timer.schedule(timerTask, 1000, 30000);
}
</code>```

init() called when record button click.

why recordWork() only one execute?
this timer not execute repeat.

How to fix this problem?

thanks.

答:
If you still can't fix your Timertask. Might as well give CountDownTimer a try
https://developer.android.com/reference/android/os/CountDownTimer.html</p>

```<code>public void startCountDown() {
    countDownTimer = new CountDownTimer(totalTimeinMillis,intervalBetweenCountdown) {

                @Override
                public void onTick(long millisUntilFinished) {
                    //execute repeating task here
                }

                @Override
                public void onFinish() {

                }
            };
        }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want Timer execute repeat.
so I try this source

public static void init() {
    TimerTask timerTask = new TimerTask() {
       @Override
       public void run() {
           Looper.prepare();
           recordWork();
           Looper.loop();
       }
    };
    Timer timer = new Timer();
    timer.schedule(timerTask, 1000, 30000);
}

init() called when record button click.

why recordWork() only one execute?
this timer not execute repeat.

How to fix this problem?

thanks.

Body:
If you still can't fix your Timertask. Might as well give CountDownTimer a try
https://developer.android.com/reference/android/os/CountDownTimer.html

public void startCountDown() {
    countDownTimer = new CountDownTimer(totalTimeinMillis,intervalBetweenCountdown) {

                @Override
                public void onTick(long millisUntilFinished) {
                    //execute repeating task here
                }

                @Override
                public void onFinish() {

                }
            };
        }


问:
Function that transforms a list in a list of dictionary
I have to make a function whose purpose is taking in parameter a list.

Such as this one :

```<code>['music', ' extension=mp3', 'reports/INFOB131', ' extension=doc,docx,pdf', ' name_contains=INFOB131', ' max_size=100000', 'reports/INFOB132', ' extension=doc,docx,pdf', ' name_contains=INFOB132', ' max_size=100000', 'games', ' name_contains=SC2,Wesnoth', 'pictures/Namur', ' extension=jpeg', ' min_size=5000000', ' name_contains=cercle', 'pictures/autres', ' extension=jpeg', ' min_size=5000000']
</code>```

And return a list similar to this :

```<code>data_config = [{'music' : {'extension':'mp3'}}, {'reports/INFOB131': {'extension': ['doc', 'docx','pdf'], 'name_contains':'INFOB131', 'max_size':100000}}, {'reports/INFOB132': {'extension': ['doc', 'docx','pdf'], 'name_contains':'INFOB132', 'max_size':100000}}]
</code>```

So I made that function :

```<code>def my_function(list_in_question, my_config_list =[], prev_list = []):
    """ """
    enumerated_list = list(enumerate(list_in_question))

    if not '=' in enumerated_list[0][1]:
        main_key = enumerated_list[0][1]# référencé avant assignement
        pre_dict = {main_key : {}}

        for i in enumerated_list[1:]:

            if '=' in i[1] :
                splitted = i[1].split('=')
                prev_list.append({splitted[0] : splitted[1]})

            elif not '=' in i[1] and i[1] != main_key:
                for j in prev_list:
                    pre_dict[main_key].update(j)

                my_config_list.append(pre_dict)

                return my_function(list_in_question[i[0]:])

            elif not '=' in i[1] and i[1] == main_key and main_key!= enumerated_list[0][1]:
                return my_config_list
    else:
        print("The format of the file containig the data in not adequate !")
</code>```

But I don't understand why when I execute it this way :

```<code>new_lines = ['music', ' extension=mp3', '', 'reports/INFOB131', ' extension=doc,docx,pdf', ' name_contains=INFOB131', ' max_size=100000', '', 'reports/INFOB132', ' extension=doc,docx,pdf', ' name_contains=INFOB132', ' max_size=100000', '', 'games', ' name_contains=SC2,Wesnoth', '', 'pictures/Namur', ' extension=jpeg', ' min_size=5000000', ' name_contains=cercle', '', 'pictures/autres', ' extension=jpeg', ' min_size=5000000']

my_function(new_lines)
</code>```

I end up with this output...

```<code>None
</code>```

I would be very grateful if someone could help me,

Thank you !

PS : If anyone have an idea of how I could do without loop and do it in a recursive way, it would be awesome !

Everyone... Thank you !!! You really hepled me, all your answers are awesome, I have some issues to understand some parts so I'll be annoying just a little longer with some questions of you code. Anyway, thank you for the time you took to help me, you were all more than great help !!!

答:
Yet another try with only lists and dicts:

```<code>def make(lst):
    data_config=[]
    for st in lst:
        if '=' not in st:            # new entry
            dd = dict()
            dds = dd[st] = dict()
            data_config.append(dd)
        else:                        # fill entry
            k,v = st.split('=')
            if ',' in v:
                v = v.split(',')
            dds[k] = v
    return data_config
</code>```

For :

```<code>In [564]: make(l)
Out[564]:
[{'music': {' extension': 'mp3'}},
 {'reports/INFOB131': {' extension': ['doc', 'docx', 'pdf'],
   ' max_size': '100000',
   ' name_contains': 'INFOB131'}},
 {'reports/INFOB132': {' extension': ['doc', 'docx', 'pdf'],
   ' max_size': '100000',
   ' name_contains': 'INFOB132'}},
 {'games': {' name_contains': ['SC2', 'Wesnoth']}},
 {'pictures/Namur': {' extension': 'jpeg',
   ' min_size': '5000000',
   ' name_contains': 'cercle'}},
 {'pictures/autres': {' extension': 'jpeg', ' min_size': '5000000'}}]
</code>```

Body:
I have to make a function whose purpose is taking in parameter a list.

Such as this one :

['music', ' extension=mp3', 'reports/INFOB131', ' extension=doc,docx,pdf', ' name_contains=INFOB131', ' max_size=100000', 'reports/INFOB132', ' extension=doc,docx,pdf', ' name_contains=INFOB132', ' max_size=100000', 'games', ' name_contains=SC2,Wesnoth', 'pictures/Namur', ' extension=jpeg', ' min_size=5000000', ' name_contains=cercle', 'pictures/autres', ' extension=jpeg', ' min_size=5000000']

And return a list similar to this :

data_config = [{'music' : {'extension':'mp3'}}, {'reports/INFOB131': {'extension': ['doc', 'docx','pdf'], 'name_contains':'INFOB131', 'max_size':100000}}, {'reports/INFOB132': {'extension': ['doc', 'docx','pdf'], 'name_contains':'INFOB132', 'max_size':100000}}]

So I made that function :

def my_function(list_in_question, my_config_list =[], prev_list = []):
    """ """
    enumerated_list = list(enumerate(list_in_question))

    if not '=' in enumerated_list[0][1]:
        main_key = enumerated_list[0][1]# référencé avant assignement
        pre_dict = {main_key : {}}

        for i in enumerated_list[1:]:

            if '=' in i[1] :
                splitted = i[1].split('=')
                prev_list.append({splitted[0] : splitted[1]})

            elif not '=' in i[1] and i[1] != main_key:
                for j in prev_list:
                    pre_dict[main_key].update(j)

                my_config_list.append(pre_dict)

                return my_function(list_in_question[i[0]:])

            elif not '=' in i[1] and i[1] == main_key and main_key!= enumerated_list[0][1]:
                return my_config_list
    else:
        print("The format of the file containig the data in not adequate !")

But I don't understand why when I execute it this way :

new_lines = ['music', ' extension=mp3', '', 'reports/INFOB131', ' extension=doc,docx,pdf', ' name_contains=INFOB131', ' max_size=100000', '', 'reports/INFOB132', ' extension=doc,docx,pdf', ' name_contains=INFOB132', ' max_size=100000', '', 'games', ' name_contains=SC2,Wesnoth', '', 'pictures/Namur', ' extension=jpeg', ' min_size=5000000', ' name_contains=cercle', '', 'pictures/autres', ' extension=jpeg', ' min_size=5000000']

my_function(new_lines)

I end up with this output...

None

I would be very grateful if someone could help me,

Thank you !

PS : If anyone have an idea of how I could do without loop and do it in a recursive way, it would be awesome !

Everyone... Thank you !!! You really hepled me, all your answers are awesome, I have some issues to understand some parts so I'll be annoying just a little longer with some questions of you code. Anyway, thank you for the time you took to help me, you were all more than great help !!!

Body:
Yet another try with only lists and dicts:

def make(lst):
    data_config=[]
    for st in lst:
        if '=' not in st:            # new entry
            dd = dict()
            dds = dd[st] = dict()
            data_config.append(dd)
        else:                        # fill entry
            k,v = st.split('=')
            if ',' in v:
                v = v.split(',')
            dds[k] = v
    return data_config

For :

In [564]: make(l)
Out[564]:
[{'music': {' extension': 'mp3'}},
 {'reports/INFOB131': {' extension': ['doc', 'docx', 'pdf'],
   ' max_size': '100000',
   ' name_contains': 'INFOB131'}},
 {'reports/INFOB132': {' extension': ['doc', 'docx', 'pdf'],
   ' max_size': '100000',
   ' name_contains': 'INFOB132'}},
 {'games': {' name_contains': ['SC2', 'Wesnoth']}},
 {'pictures/Namur': {' extension': 'jpeg',
   ' min_size': '5000000',
   ' name_contains': 'cercle'}},
 {'pictures/autres': {' extension': 'jpeg', ' min_size': '5000000'}}]


问:
Matching input tag with Cucumber/Webrat
I'm learning Cucumber, but I can't make a step for just matching input tags.

What I have in the view is

```<code><input type="submit" value="Press!" />
</code>```

And what I tried in Cucumber are

```<code>Then the "input" field should contain "Press!"
Then the "type" field should contain "submit"
</code>```

I just wanna confirm the existence for the input tags with certain values. No interaction.

答:
They're also explicitly supported in webrat.  Even if you can't find the built-in support in cucumber, you can always just drop into your own step definitions.

source:  http://cheat.errtheblog.com/s/webrat/

```<code>== Assertions

   # check for text in the body of html tags
   # can be a string or regexp
  assert_contain("BURNINATOR")
  assert_contain(/trogdor/i)
  assert_not_contain("peasants")

  # check for a css3 selector
  assert_have_selector 'div.pagination'
  assert_have_no_selector 'form input#name'

== Matchers

  # check for text in the body of html tags
  # can be a string or regexp
  # Matchers are verbs used with auxillary verbs should, should_not, etc.
  response.should contain("BURNINATOR")
  response.should contain(/trogdor/i)
  response.should_not contain("peasants")

  # check for a css3 selector
  response.should have_selector('div.pagination')
  response.should_not have_selector('form input#name')
</code>```

ContentLicense: CC BY-SA 2.5

Title: Matching input tag with Cucumber/Webrat

Body:
I'm learning Cucumber, but I can't make a step for just matching input tags.

What I have in the view is

<input type="submit" value="Press!" />

And what I tried in Cucumber are

Then the "input" field should contain "Press!"
Then the "type" field should contain "submit"

I just wanna confirm the existence for the input tags with certain values. No interaction.

Body:
They're also explicitly supported in webrat.  Even if you can't find the built-in support in cucumber, you can always just drop into your own step definitions.

source:  http://cheat.errtheblog.com/s/webrat/

== Assertions

   # check for text in the body of html tags
   # can be a string or regexp
  assert_contain("BURNINATOR")
  assert_contain(/trogdor/i)
  assert_not_contain("peasants")

  # check for a css3 selector
  assert_have_selector 'div.pagination'
  assert_have_no_selector 'form input#name'

== Matchers

  # check for text in the body of html tags
  # can be a string or regexp
  # Matchers are verbs used with auxillary verbs should, should_not, etc.
  response.should contain("BURNINATOR")
  response.should contain(/trogdor/i)
  response.should_not contain("peasants")

  # check for a css3 selector
  response.should have_selector('div.pagination')
  response.should_not have_selector('form input#name')


问:
Why WebRTC chose RTP max packet size to 1200 bytes?
By studying WebRTC sources I was wondering why developers chose max RTP packet size as 1200 bytes.
It's defined in media/engine/constants.cc, as kVideoMtu variable.

Thanks.

答: This is an arbitrarily selected value to avoid packet fragmentation. There is no any exact science behind this as you can be never sure on the actual limits, however 1200 byte is a safe value for all kind of networks on the public internet (including something like a double VPN connection over PPPoE) and for RTP there is no much reason to choose a bigger value.</p>


问:
converting numbers to currency format when text changes
I am using RxTextView.textChanges for EditText that when the user is typing change value of EditText to convert numbers to currency format like below:

```<code>1,000
</code>```

But I can't see any convert numbers to currency format.

I am using from:  NumberFormat.getNumberInstance(Locale.US).format(productPrice);

My code is like bellow:

```<code>Observable<CharSequence> observableDiscountPrice = RxTextView.textChanges(discountPriceEdittext);
        observableDiscountPrice.map(new Function<CharSequence, Boolean>() {
            @Override
            public Boolean apply(@io.reactivex.annotations.NonNull CharSequence charSequence) throws Exception {
                try {
                    if (charSequence.length() > 0) {
                        String pPrice = NumberFormat.getNumberInstance(Locale.US).format(charSequence.toString());
                        originalPriceEdittext.setText(String.valueOf(pPrice));
                        return true;
                    } else {
                        return false;
                    }
                } catch (Exception e) {
                    return true;
                }
            }
        }).subscribe(new Subject<Boolean>() {
            @Override
            public boolean hasObservers() {
                return false;
            }

            @Override
            public boolean hasThrowable() {
                return false;
            }

            @Override
            public boolean hasComplete() {
                return false;
            }

            @Override
            public Throwable getThrowable() {
                return null;
            }

            @Override
            protected void subscribeActual(Observer<? super Boolean> observer) {

            }

            @Override
            public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {

            }

            @Override
            public void onNext(@io.reactivex.annotations.NonNull Boolean aBoolean) {
            }

            @Override
            public void onError(@io.reactivex.annotations.NonNull Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
</code>```

答:
I'm using this watcher to do the same thing:</p>

```<code>    import android.text.Editable;
    import android.text.TextWatcher;
    import android.widget.EditText;

    import java.text.DecimalFormat;
    import java.text.NumberFormat;
    import java.util.Locale;

    public class CurrencyTextWatcher implements TextWatcher {

    private EditText ed;
    private String lastText;
    private boolean bDel = false;
    private boolean bInsert = false;
    private int pos;

    public CurrencyTextWatcher(EditText ed) {
        this.ed = ed;
    }

    public static String getStringWithSeparator(long value) {
        DecimalFormat formatter = (DecimalFormat) NumberFormat.getNumberInstance(Locale.US);
        String f = formatter.format(value);
        return f;
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        bDel = false;
        bInsert = false;
        if (before == 1 && count == 0) {
            bDel = true;
            pos = start;
        } else if (before == 0 && count == 1) {
            bInsert = true;
            pos = start;
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        lastText = s.toString();
    }

    @Override
    public void afterTextChanged(Editable s) {
        ed.removeTextChangedListener(this);
        StringBuilder sb = new StringBuilder();
        String text = s.toString();
        for (int i = 0; i < text.length(); i++) {
            if ((text.charAt(i) >= 0x30 && text.charAt(i) <= 0x39) || text.charAt(i) == '.' || text.charAt(i) == ',')
                sb.append(text.charAt(i));
        }
        if (!sb.toString().equals(s.toString())) {
            bDel = bInsert = false;
        }
        String newText = getFormattedString(sb.toString());
        s.clear();
        s.append(newText);
        ed.addTextChangedListener(this);

        if (bDel) {
            int idx = pos;
            if (lastText.length() - 1 > newText.length())
                idx--;
            if (idx < 0)
                idx = 0;
            ed.setSelection(idx);
        } else if (bInsert) {
            int idx = pos + 1;
            if (lastText.length() + 1 < newText.length())
                idx++;
            if (idx > newText.length())
                idx = newText.length();
            ed.setSelection(idx);
        }
    }

    private String getFormattedString(String text) {
        String res = "";
        try {
            String temp = text.replace(",", "");
            long part1;
            String part2 = "";
            int dotIndex = temp.indexOf(".");
            if (dotIndex >= 0) {
                part1 = Long.parseLong(temp.substring(0, dotIndex));
                if (dotIndex + 1 <= temp.length()) {
                    part2 = temp.substring(dotIndex + 1).trim().replace(".", "").replace(",", "");
                }
            } else
                part1 = Long.parseLong(temp);

            res = getStringWithSeparator(part1);
            if (part2.length() > 0)
                res += "." + part2;
            else if (dotIndex >= 0)
                res += ".";
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return res;
    }
}
</code>```

Body:
I am using RxTextView.textChanges for EditText that when the user is typing change value of EditText to convert numbers to currency format like below:

1,000

But I can't see any convert numbers to currency format.

I am using from:  NumberFormat.getNumberInstance(Locale.US).format(productPrice);

My code is like bellow:

Observable<CharSequence> observableDiscountPrice = RxTextView.textChanges(discountPriceEdittext);
        observableDiscountPrice.map(new Function<CharSequence, Boolean>() {
            @Override
            public Boolean apply(@io.reactivex.annotations.NonNull CharSequence charSequence) throws Exception {
                try {
                    if (charSequence.length() > 0) {
                        String pPrice = NumberFormat.getNumberInstance(Locale.US).format(charSequence.toString());
                        originalPriceEdittext.setText(String.valueOf(pPrice));
                        return true;
                    } else {
                        return false;
                    }
                } catch (Exception e) {
                    return true;
                }
            }
        }).subscribe(new Subject<Boolean>() {
            @Override
            public boolean hasObservers() {
                return false;
            }

            @Override
            public boolean hasThrowable() {
                return false;
            }

            @Override
            public boolean hasComplete() {
                return false;
            }

            @Override
            public Throwable getThrowable() {
                return null;
            }

            @Override
            protected void subscribeActual(Observer<? super Boolean> observer) {

            }

            @Override
            public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {

            }

            @Override
            public void onNext(@io.reactivex.annotations.NonNull Boolean aBoolean) {
            }

            @Override
            public void onError(@io.reactivex.annotations.NonNull Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });

Body:
I'm using this watcher to do the same thing:

    import android.text.Editable;
    import android.text.TextWatcher;
    import android.widget.EditText;

    import java.text.DecimalFormat;
    import java.text.NumberFormat;
    import java.util.Locale;

    public class CurrencyTextWatcher implements TextWatcher {

    private EditText ed;
    private String lastText;
    private boolean bDel = false;
    private boolean bInsert = false;
    private int pos;

    public CurrencyTextWatcher(EditText ed) {
        this.ed = ed;
    }

    public static String getStringWithSeparator(long value) {
        DecimalFormat formatter = (DecimalFormat) NumberFormat.getNumberInstance(Locale.US);
        String f = formatter.format(value);
        return f;
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        bDel = false;
        bInsert = false;
        if (before == 1 && count == 0) {
            bDel = true;
            pos = start;
        } else if (before == 0 && count == 1) {
            bInsert = true;
            pos = start;
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        lastText = s.toString();
    }

    @Override
    public void afterTextChanged(Editable s) {
        ed.removeTextChangedListener(this);
        StringBuilder sb = new StringBuilder();
        String text = s.toString();
        for (int i = 0; i < text.length(); i++) {
            if ((text.charAt(i) >= 0x30 && text.charAt(i) <= 0x39) || text.charAt(i) == '.' || text.charAt(i) == ',')
                sb.append(text.charAt(i));
        }
        if (!sb.toString().equals(s.toString())) {
            bDel = bInsert = false;
        }
        String newText = getFormattedString(sb.toString());
        s.clear();
        s.append(newText);
        ed.addTextChangedListener(this);

        if (bDel) {
            int idx = pos;
            if (lastText.length() - 1 > newText.length())
                idx--;
            if (idx < 0)
                idx = 0;
            ed.setSelection(idx);
        } else if (bInsert) {
            int idx = pos + 1;
            if (lastText.length() + 1 < newText.length())
                idx++;
            if (idx > newText.length())
                idx = newText.length();
            ed.setSelection(idx);
        }
    }

    private String getFormattedString(String text) {
        String res = "";
        try {
            String temp = text.replace(",", "");
            long part1;
            String part2 = "";
            int dotIndex = temp.indexOf(".");
            if (dotIndex >= 0) {
                part1 = Long.parseLong(temp.substring(0, dotIndex));
                if (dotIndex + 1 <= temp.length()) {
                    part2 = temp.substring(dotIndex + 1).trim().replace(".", "").replace(",", "");
                }
            } else
                part1 = Long.parseLong(temp);

            res = getStringWithSeparator(part1);
            if (part2.length() > 0)
                res += "." + part2;
            else if (dotIndex >= 0)
                res += ".";
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return res;
    }
}


问:
Cosmos DB with multiple partition keys
We're looking at potentially using a single Cosmos DB collection to hold multiple document types in a multi-tenanted environment using a tenant ID as the partition key. The path to tenant id may change in each document type and I am therefore looking at various was of exposing the partition key to Cosmos DB to enable correct partitioning / querying.

I have noticed that the Paths property of DocumentCollection.PartitionKey is a collection and was therefore wondering whether it is possible to pass multiple paths during the creation of a document collection and what the behaviour of this might be. Ideally, I would like Cosmos to scan each of these paths and use the first value or aggregate of values as the partition key but cannot find any documentation suggesting that this is indeed the behaviour.

The MSDN documentation for this property is pretty useless and none of the associated documentation seems to answer the question. Does anyone know about or previously used multiple partition key paths in a collection?

To be clear, I'm looking for links to additional documentation about and/or direct experience of the Cosmos DB's behaviour when specifying multiple partition keys in the PartitionKey.Paths collection when creating a DocumentCollection.

This question has also been posted in the Azure Community Support forums.

Thanks, Ian

答:
Further to the above, I ended up adding a partition key property to the document container as suggested by Aravind and then used David Fowler's excellent QueryInteceptor nuget package to apply an ExpressionVisitor which translated any equivalence expression relating to the specific document type's tenant id property into a equivalence expression on the partition key property. This ensured that queries would be performed against only the single, correct partition. Furthermore, I was able to use the ExpressionVisitor as a safety feature in that it is able to enforce that all queries provide a filter on tenant id (as, obviously, tenants should never be able to see each others documents) and if none has been specified then no records are returned (an invalid equivalence expression is added to the partition key property).

This has been tested and seems to be working well.

Title: Cosmos DB with multiple partition keys


问:
How to prevent users from going back to the previous page?
I am using ASP.NET MVC (latest version).

Imagine having 2 pages:

Page-1: "Enter data" >> Page-2: "Thank you"

After submitting Page-1 you are being redirected to Page-2.

My goal: I want to make sure that you can't go back to Page-1 when you hit the browser's back button once you made it to Page-2. Instead I want you rather to stay on Page-2 (or being pushed forward to Page-2 every time you hit the back button).

I have tried all different kind of things. The following is just some simplified pseudo code ...

```<code>[NoBrowserCache]
public ActionResult Page1(int userId)
{
   var user = GetUserFromDb(userId);
   if (user.HasAlreadySubmittedPage1InThePast)
   {
      // forward to page 2
      return RedirectToAction("Page2", routeValues: new { userId = userId });
   }

   var model = new Page1Model();

   return View("Page1", model);
}

[NoBrowserCache]
[HttpPost]
public ActionResult Page1(Page1Model model)
{
   var user = GetUserFromDb(model.UserId);
   if (user.HasAlreadySubmittedPage1InThePast)
   {
       // forward to page 2
       return RedirectToAction("Page2", routeValues: new { userId = model.UserId });
   }

   // Save posted data to the db
   // ...

   return RedirectToAction("Page2", routeValues: new { userId = model.UserId });
}

public class NoBrowserCache : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // Haha ... tried everything I found on the web here:
        // Make sure the requested page is not put in the browser cache.
        filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        filterContext.HttpContext.Response.Cache.SetNoStore();
        filterContext.HttpContext.Response.Cache.AppendCacheExtension("no-cache");
        filterContext.HttpContext.Response.Cache.SetExpires(DateTime.Now);
        filterContext.HttpContext.Response.Expires = 0;
    }
}
</code>```

If only I could make sure that a request is being sent to the server every time I hit the back button. But right now, clicking the back button just pulls Page-1 from my browser's cache without sending a request to the server. So currently, I have no chance to redirect you forward to Page-2 by server means.

Any ideas or suggestions?

Thanks, guys!

Btw: There is no login/authentication involved. So, I can't use Session.Abandon() or stuff like this. And I would rather use some server based code than javascript if possible.

EDIT 2017-5-12
Following @grek40, I made sure that the anti-chaching statements end up in the browser. I therefor completely removed the [NoBrowserCache]-ActionFilterAttribute from my C# code above. Instead I added the following statements in the  section of my _Layout.cshtml:

```<code><meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">
</code>```

I confirm that these three lines are being rendered to my browser (used my browser's developer tools to inspect). However, caching still works. I can still move backward without any server requests. Tested this with Google Chrome v62, Firefox Quantum v57 and Microsoft Edge v41 (all on Win10). #

EDIT 2017-6-12
Again following @grek40's suggestions: tried Expires: 0 as well as Expires: -1. No difference. I still didn't manage, to turn off my browser's cache.

答:
```<code>Response.Cache.SetCacheability(HttpCacheability.NoCache);  // HTTP 1.1.
Response.Cache.AppendCacheExtension("no-store, must-revalidate");
Response.AppendHeader("Pragma", "no-cache"); // HTTP 1.0.
Response.AppendHeader("Expires", "0"); // Proxies.
</code>```

Body:
I am using ASP.NET MVC (latest version).

Imagine having 2 pages:

Page-1: "Enter data" >> Page-2: "Thank you"

After submitting Page-1 you are being redirected to Page-2.

My goal: I want to make sure that you can't go back to Page-1 when you hit the browser's back button once you made it to Page-2. Instead I want you rather to stay on Page-2 (or being pushed forward to Page-2 every time you hit the back button).

I have tried all different kind of things. The following is just some simplified pseudo code ...

[NoBrowserCache]
public ActionResult Page1(int userId)
{
   var user = GetUserFromDb(userId);
   if (user.HasAlreadySubmittedPage1InThePast)
   {
      // forward to page 2
      return RedirectToAction("Page2", routeValues: new { userId = userId });
   }

   var model = new Page1Model();

   return View("Page1", model);
}

[NoBrowserCache]
[HttpPost]
public ActionResult Page1(Page1Model model)
{
   var user = GetUserFromDb(model.UserId);
   if (user.HasAlreadySubmittedPage1InThePast)
   {
       // forward to page 2
       return RedirectToAction("Page2", routeValues: new { userId = model.UserId });
   }

   // Save posted data to the db
   // ...

   return RedirectToAction("Page2", routeValues: new { userId = model.UserId });
}

public class NoBrowserCache : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // Haha ... tried everything I found on the web here:
        // Make sure the requested page is not put in the browser cache.
        filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        filterContext.HttpContext.Response.Cache.SetNoStore();
        filterContext.HttpContext.Response.Cache.AppendCacheExtension("no-cache");
        filterContext.HttpContext.Response.Cache.SetExpires(DateTime.Now);
        filterContext.HttpContext.Response.Expires = 0;
    }
}

If only I could make sure that a request is being sent to the server every time I hit the back button. But right now, clicking the back button just pulls Page-1 from my browser's cache without sending a request to the server. So currently, I have no chance to redirect you forward to Page-2 by server means.

Any ideas or suggestions?

Thanks, guys!

Btw: There is no login/authentication involved. So, I can't use Session.Abandon() or stuff like this. And I would rather use some server based code than javascript if possible.

EDIT 2017-5-12
Following @grek40, I made sure that the anti-chaching statements end up in the browser. I therefor completely removed the [NoBrowserCache]-ActionFilterAttribute from my C# code above. Instead I added the following statements in the  section of my _Layout.cshtml:

<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">

I confirm that these three lines are being rendered to my browser (used my browser's developer tools to inspect). However, caching still works. I can still move backward without any server requests. Tested this with Google Chrome v62, Firefox Quantum v57 and Microsoft Edge v41 (all on Win10). #

EDIT 2017-6-12
Again following @grek40's suggestions: tried Expires: 0 as well as Expires: -1. No difference. I still didn't manage, to turn off my browser's cache.


问:
Switching classes onClick toggle
I am learning by doing and have hit a road block while developing a website. I have a menu with 4 options, there is an active state and off state in css as well as the first option is active by default. When clicking any option it toggles it to the active state but does not change the previous one to the off state.

Code:

function myFunc(e) {
  if (e.className == 'channel') {
    e.className = 'channel active';
  } else {
    e.className = 'channel';
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><li id="test" class="channel active" data-v-a3c933a2="" onclick="openPlayer('option1'); myFunc(this)">
  <div class="status offline" data-v-a3c933a2="">Offline <span class="viewers" data-v-a3c933a2="">0</span>
  </div>Option1
</li>
<li id="test" class="channel" data-v-a3c933a2="" onclick="openPlayer('option2'); myFunc(this)">
  <div class="status offline" data-v-a3c933a2="">Offline <span class="viewers" data-v-a3c933a2="">0</span>
  </div>Option2
</li>
<li id="test" class="channel" data-v-a3c933a2="" onclick="openPlayer('option3'); myFunc(this)">
  <div class="status offline" data-v-a3c933a2="">Offline <span class="viewers" data-v-a3c933a2="">0</span>
  </div>Option3
</li>
<li id="test" class="channel" data-v-a3c933a2="" onclick="openPlayer('option4'); myFunc(this)">
  <div class="status offline" data-v-a3c933a2="">Offline <span class="viewers" data-v-a3c933a2="">0</span>
  </div>Option4
</li></code>```

How do I go about having all nonactive options actually display in the off state instead of just toggling per-click?

Thank you for your time!

答:
Your code doesn't remove the active class from the other LIs. Loop through the LIs and remove the active class. As for the LI that is clicked, check if it's active. If it is, remove the class. If it's not, add the class.

```<code>function myFunc(e) {
  document.querySelectorAll('li').forEach((li) => {
    // Check if the clicked li has the class 'active'. If it doesn't,
    // add the 'active' class.
    if (e === li && !e.classList.contains('active')) {
      li.classList.add('active');
    } else { // Just remove the 'active' class from each li.
      li.classList.remove('active');
    }
  });
}
</code>```

function myFunc(e) {
  document.querySelectorAll('li').forEach((li) => {
    // Check if the clicked li has the class 'active'. If it doesn't,
    // add the 'active' class.
    if (e === li && !e.classList.contains('active')) {
      li.classList.add('active');
    } else { // Just remove the 'active' class from each li.
      li.classList.remove('active');
    }
  });
}

const lis = Array.from(document.getElementsByTagName('li'));

lis.forEach((li) => {
 li.addEventListener('click', myFunc.bind(null, li));
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  margin: 0;
  padding: 0;
}

body {
  font: normal 14px/1.8 sans-serif;
}

ul {
  list-style: none;
}

li {
  cursor: pointer;
  display: inline-block;
  padding: 10px;
}

a {
  color: #666;
  text-decoration: none;
}

.active {
  background: #999;
}

.active a {
  color: #fff;
}</code>```

    Option 1

    Option 2

    Option 3

    Option 4

```

Title: Switching classes onClick toggle

Body:
I am learning by doing and have hit a road block while developing a website. I have a menu with 4 options, there is an active state and off state in css as well as the first option is active by default. When clicking any option it toggles it to the active state but does not change the previous one to the off state.

Code:

function myFunc(e) {
  if (e.className == 'channel') {
    e.className = 'channel active';
  } else {
    e.className = 'channel';
  }
}

Offline 0

Option1

Offline 0

Option2

Offline 0

Option3

Offline 0

Option4

How do I go about having all nonactive options actually display in the off state instead of just toggling per-click?

Thank you for your time!

Body:
Your code doesn't remove the active class from the other LIs. Loop through the LIs and remove the active class. As for the LI that is clicked, check if it's active. If it is, remove the class. If it's not, add the class.

function myFunc(e) {
  document.querySelectorAll('li').forEach((li) => {
    // Check if the clicked li has the class 'active'. If it doesn't,
    // add the 'active' class.
    if (e === li && !e.classList.contains('active')) {
      li.classList.add('active');
    } else { // Just remove the 'active' class from each li.
      li.classList.remove('active');
    }
  });
}

function myFunc(e) {
  document.querySelectorAll('li').forEach((li) => {
    // Check if the clicked li has the class 'active'. If it doesn't,
    // add the 'active' class.
    if (e === li && !e.classList.contains('active')) {
      li.classList.add('active');
    } else { // Just remove the 'active' class from each li.
      li.classList.remove('active');
    }
  });
}

const lis = Array.from(document.getElementsByTagName('li'));

lis.forEach((li) => {
 li.addEventListener('click', myFunc.bind(null, li));
});

* {
  margin: 0;
  padding: 0;
}

body {
  font: normal 14px/1.8 sans-serif;
}

ul {
  list-style: none;
}

li {
  cursor: pointer;
  display: inline-block;
  padding: 10px;
}

a {
  color: #666;
  text-decoration: none;
}

.active {
  background: #999;
}

.active a {
  color: #fff;
}

<ul>
  <li>
    <a href="#">Option 1</a>
  </li>
  <li>
    <a href="#">Option 2</a>
  </li>
  <li>
    <a href="#">Option 3</a>
  </li>
  <li>
    <a href="#">Option 4</a>
  </li>
</ul>


问:
how to download a css file from a style string in asp.net web api
I want to download a file (css type) from a concatenated style string from the database.I want to  return a new file created with the given stylestrings and return on http get request</p>

答:
Your return object is likely using one or both of the IDisposable objects, but disposing of them shortly you return (by way of the using statements).

Manage your memory differently - make calls to stream.Dispose() and httpResponseMessage.Dispose() manually where appropriate - maybe in your class destructor, though in my experience HttpResponseMessage doesn't need disposing as it's dealt with by the garbage collector once you've finished working with it. Example code:

```
            byte[] textAsBytes = Encoding.Unicode.GetBytes(concatenatedStyles);</p>

```        using(MemoryStream stream = new MemoryStream(textAsBytes)) {
            var httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK);
            httpResponseMessage.Content = new StreamContent(stream);
            httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") {
                FileName = "main-theme.scss"
            };
            httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("text/css");

            return ResponseMessage(httpResponseMessage);
        }
```

<p>```

You might need to remove the using around the MemoryStream too, I'm not 100% sure as I can't compile your code on my system.

Body:
Your return object is likely using one or both of the IDisposable objects, but disposing of them shortly you return (by way of the using statements).

Manage your memory differently - make calls to stream.Dispose() and httpResponseMessage.Dispose() manually where appropriate - maybe in your class destructor, though in my experience HttpResponseMessage doesn't need disposing as it's dealt with by the garbage collector once you've finished working with it. Example code:

```
            byte[] textAsBytes = Encoding.Unicode.GetBytes(concatenatedStyles);</p>

<pre><code>        using(MemoryStream stream = new MemoryStream(textAsBytes)) {
            var httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK);
            httpResponseMessage.Content = new StreamContent(stream);
            httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") {
                FileName = "main-theme.scss"
            };
            httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("text/css");

            return ResponseMessage(httpResponseMessage);
        }
</code></pre>

<p>```

You might need to remove the using around the MemoryStream too, I'm not 100% sure as I can't compile your code on my system.


问:
How to load Media Metadata Smoothly in a RecyclerView
I have a Music class that needs to return its cover art as a bitmap in order to use it on a RecylerView. I am using an AsyncTask inner class in the class to perform the retrieval, however, my app freezes once the list is being created from cover arts. Please see the code below for Music.java:

```<code>public class Music {
    private static final String LOG_TAG = Music.class.getSimpleName();
    private String mId;
    private String mTitle;
    private String mUrl;
    private Bitmap mCoverArt;

    public Music(String id, String title, String url) {
        mId = id;
        mTitle = title;
        mUrl = url;
        mCoverArt = null; //Initialize with null
    }

    String getId() {
        return mId;
    }

    String getTitle() {
        return mTitle;
    }

    String getUrl() {
        return mUrl;
    }

    Bitmap getCoverArt() {
        if(mCoverArt != null) {
            return mCoverArt;
        }
        else {
            Bitmap bmp = null;
            try {
                bmp = new GetCoverArt().execute(mUrl).get();
            } catch (InterruptedException e) {
                Log.e(LOG_TAG, "InterruptedException: " + e.getMessage());
            } catch (ExecutionException e) {
                Log.e(LOG_TAG, "ExecutionException: " + e.getMessage());
            }
            return bmp;

        }
    }
    public void setCoverArt(Bitmap bmp) { mCoverArt = bmp; }

    private static class GetCoverArt extends AsyncTask<String, Void, Bitmap> {
        @Override
        protected Bitmap doInBackground(String... paths) {
            MediaMetadataRetriever mmr = new MediaMetadataRetriever();
            mmr.setDataSource(paths[0], new HashMap<String,String>());
            byte[] picData = mmr.getEmbeddedPicture();
            return BitmapFactory.decodeByteArray(picData, 0, picData.length);
        }
    }
}
</code>```

I am calling getCoverArt() in onBindViewHolder for my RecyclerView this way:

```<code>@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    Music song = mDataset.get(position);
    Bitmap songCoverArt = song.getCoverArt();
    String songTitle = song.getTitle();
    String songId = song.getId();
    String songUrl = song.getUrl();

    if(songCoverArt != null) {
        Glide.with(mContext).load(songCoverArt).into(holder.coverArt);
    }
    else {
        holder.coverArt.setImageResource(R.drawable.coverart_fallback);
    }
    Bitmap bmp = song.getCoverArt();
    if(bmp != null) {
        Glide.with(mContext).load(bmp).into(holder.coverArt);
    }
    else {
        Glide.with(mContext).load(R.drawable.coverart_fallback).into(holder.coverArt);
    }
</code>```

I do not understand why doInBackground in AsyncTask might cause the UI thread to freeze. I thought it all runs in the background, but it seems my RecyclerView is waiting for it to finish the job before it can use the value returned. Currently, as an a bad workaround, I am doing such processing in another AsyncTask in the main activity along with other network operations when I construct Music objects and add them to an ArrayList:

```<code> for( int j = 0 ; j < songs.length() ; j++) {
                            JSONObject song = songs.getJSONObject(j); //get song at index j
                            String songId = song.getString( getString(R.string.json_song_id) );
                            String title = song.getString( getString(R.string.json_song_title));
                            String path = song.getString( getString(R.string.json_filepath) );
                            //Create a temp Music object to extract Music info
                            Music songObj = new Music(songId, title, path);
                            Bitmap bmp = createCoverArtBmp(path);
                            songObj.setCoverArt(bmp);
                            mMusicTrackArray.add(songObj); //Add the music object into array
                        }
</code>```

答:
You don't need to convert it to bitmap from the url to show the images. Simply pass the image url to Glide and it will load it for you.

By calling bitmap making in the getCoverArt() you are not doing it async but waiting for the task to finish as a result freezing your view.
See here how to use Glide with url : https://github.com/bumptech/glide#how-do-i-use-glide

Body:
I have a Music class that needs to return its cover art as a bitmap in order to use it on a RecylerView. I am using an AsyncTask inner class in the class to perform the retrieval, however, my app freezes once the list is being created from cover arts. Please see the code below for Music.java:

public class Music {
    private static final String LOG_TAG = Music.class.getSimpleName();
    private String mId;
    private String mTitle;
    private String mUrl;
    private Bitmap mCoverArt;

    public Music(String id, String title, String url) {
        mId = id;
        mTitle = title;
        mUrl = url;
        mCoverArt = null; //Initialize with null
    }

    String getId() {
        return mId;
    }

    String getTitle() {
        return mTitle;
    }

    String getUrl() {
        return mUrl;
    }

    Bitmap getCoverArt() {
        if(mCoverArt != null) {
            return mCoverArt;
        }
        else {
            Bitmap bmp = null;
            try {
                bmp = new GetCoverArt().execute(mUrl).get();
            } catch (InterruptedException e) {
                Log.e(LOG_TAG, "InterruptedException: " + e.getMessage());
            } catch (ExecutionException e) {
                Log.e(LOG_TAG, "ExecutionException: " + e.getMessage());
            }
            return bmp;

        }
    }
    public void setCoverArt(Bitmap bmp) { mCoverArt = bmp; }

    private static class GetCoverArt extends AsyncTask<String, Void, Bitmap> {
        @Override
        protected Bitmap doInBackground(String... paths) {
            MediaMetadataRetriever mmr = new MediaMetadataRetriever();
            mmr.setDataSource(paths[0], new HashMap<String,String>());
            byte[] picData = mmr.getEmbeddedPicture();
            return BitmapFactory.decodeByteArray(picData, 0, picData.length);
        }
    }
}

I am calling getCoverArt() in onBindViewHolder for my RecyclerView this way:

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    Music song = mDataset.get(position);
    Bitmap songCoverArt = song.getCoverArt();
    String songTitle = song.getTitle();
    String songId = song.getId();
    String songUrl = song.getUrl();

    if(songCoverArt != null) {
        Glide.with(mContext).load(songCoverArt).into(holder.coverArt);
    }
    else {
        holder.coverArt.setImageResource(R.drawable.coverart_fallback);
    }
    Bitmap bmp = song.getCoverArt();
    if(bmp != null) {
        Glide.with(mContext).load(bmp).into(holder.coverArt);
    }
    else {
        Glide.with(mContext).load(R.drawable.coverart_fallback).into(holder.coverArt);
    }

I do not understand why doInBackground in AsyncTask might cause the UI thread to freeze. I thought it all runs in the background, but it seems my RecyclerView is waiting for it to finish the job before it can use the value returned. Currently, as an a bad workaround, I am doing such processing in another AsyncTask in the main activity along with other network operations when I construct Music objects and add them to an ArrayList:

 for( int j = 0 ; j < songs.length() ; j++) {
                            JSONObject song = songs.getJSONObject(j); //get song at index j
                            String songId = song.getString( getString(R.string.json_song_id) );
                            String title = song.getString( getString(R.string.json_song_title));
                            String path = song.getString( getString(R.string.json_filepath) );
                            //Create a temp Music object to extract Music info
                            Music songObj = new Music(songId, title, path);
                            Bitmap bmp = createCoverArtBmp(path);
                            songObj.setCoverArt(bmp);
                            mMusicTrackArray.add(songObj); //Add the music object into array
                        }


问:
Mule Session variables are persisted across some but not all transport barriers
I know Session  variables  are  persisted  across  some  but  not  all  transport  barriers for example they  are  not  propagated  across  the  HTTP  transport  barrier.
Can anyone help me to know what are other transport barriers in mule which does not allow propagation of session variable.</p>

答:
Session variables set with a session variable transformer persist for the entire message lifecycle, regardless of transport barriers, except for the HTTP Connector which doesn’t propagate them.

Ref below link

session-variable-transformer-reference


问:
Can I simplify this Rust code dealing with Option<T> and Result<T>?
I'm working on my first actual Rust program, a custom i3status. It's coming along nicely, but there's two places where I have to deal with Result<T> and Option<T> and the code looks really ugly, leading me to believe that I've missed some language feature or library function for writing these parts more cleanly.

This is the file in question, but I'll quote the relevant parts here. The first one is this:

```<code>fn read_number_from_file(path: &str) -> Option<i64> {
    let mut file = match File::open(path) {
        Ok(f) => f,
        Err(_) => return None,
    };
    let mut contents = String::new();
    match file.read_to_string(&mut contents) {
        Ok(_) => {},
        Err(_) => return None,
    };
    match contents.trim().parse::<i64>() {
        Ok(val) => Some(val),
        Err(_) => None,
    }
}
</code>```

Swallowing error messages here is intentional. An i3status does not have an stderr, so all I can do is skip rendering of the broken parts.

Regardless of that, this code looks ugly, with its repeated use of match to discard Err values. I tried to use the new ? operator by making the return type a std::io::Result<i64>, but str::parse returns a different type of error, so that doesn't work AFAICS. I therefore went with Option<i64> as the lowest common denominator.

The second ugly part is where this function gets used:

```<code>let energy_full = match read_number_from_file(ENERGY_FULL_PATH) {
    Some(val) => val,
    None      => return Vec::new(),
};
let energy_now = match read_number_from_file(ENERGY_NOW_PATH) {
    Some(val) => val,
    None      => return Vec::new(),
};
let is_charging = match read_number_from_file(POWER_ONLINE_PATH) {
    Some(val) => val > 0,
    None      => return Vec::new(),
};
</code>```

I feel like one should be able to contract each of the match expressions into a function call like .or_else(), but .or_else(|| return Vec::new()) obviously won't work since the return is scoped to the lambda instead of the original function.

So, in both cases, my question is whether I can replace match by something more compact and idiomatic.

答:
To combine Option<T>s with Result<T, E>s, use ok() and the question mark operator:

```<code>fn read_number_from_file(path: &str) -> Option<i64> {
    let mut file = File::open(path).ok()?;
    let mut contents = String::new();
    file.read_to_string(&mut contents).ok()?;
    contents.trim().parse::<i64>().ok()
}
</code>```

As for the second part of the question, if you can contain all those variable bindings in a single function:

```<code>fn foo() -> Option<Vec<i64>> { // or some other Option<Vec>
    let energy_full = read_number_from_file(ENERGY_FULL_PATH)?;
    let energy_now = read_number_from_file(ENERGY_NOW_PATH)?;
    let is_charging = read_number_from_file(POWER_ONLINE_PATH)? > 0;

    Some(Vec::new()) // placeholder for the valid return value
}
</code>```

You can then use unwrap_or_else() on its result to return an empty Vec upon any error:

```<code>let foo = foo().unwrap_or_else(|| vec![]);
</code>```

Or just unwrap_or(), because empty vectors don't allocate memory:

```<code>let foo = foo().unwrap_or(vec![]);
</code>```

Body:
I'm working on my first actual Rust program, a custom i3status. It's coming along nicely, but there's two places where I have to deal with Result<T> and Option<T> and the code looks really ugly, leading me to believe that I've missed some language feature or library function for writing these parts more cleanly.

This is the file in question, but I'll quote the relevant parts here. The first one is this:

fn read_number_from_file(path: &str) -> Option<i64> {
    let mut file = match File::open(path) {
        Ok(f) => f,
        Err(_) => return None,
    };
    let mut contents = String::new();
    match file.read_to_string(&mut contents) {
        Ok(_) => {},
        Err(_) => return None,
    };
    match contents.trim().parse::<i64>() {
        Ok(val) => Some(val),
        Err(_) => None,
    }
}

Swallowing error messages here is intentional. An i3status does not have an stderr, so all I can do is skip rendering of the broken parts.

Regardless of that, this code looks ugly, with its repeated use of match to discard Err values. I tried to use the new ? operator by making the return type a std::io::Result<i64>, but str::parse returns a different type of error, so that doesn't work AFAICS. I therefore went with Option<i64> as the lowest common denominator.

The second ugly part is where this function gets used:

let energy_full = match read_number_from_file(ENERGY_FULL_PATH) {
    Some(val) => val,
    None      => return Vec::new(),
};
let energy_now = match read_number_from_file(ENERGY_NOW_PATH) {
    Some(val) => val,
    None      => return Vec::new(),
};
let is_charging = match read_number_from_file(POWER_ONLINE_PATH) {
    Some(val) => val > 0,
    None      => return Vec::new(),
};

I feel like one should be able to contract each of the match expressions into a function call like .or_else(), but .or_else(|| return Vec::new()) obviously won't work since the return is scoped to the lambda instead of the original function.

So, in both cases, my question is whether I can replace match by something more compact and idiomatic.

Body:
To combine Option<T>s with Result<T, E>s, use ok() and the question mark operator:

fn read_number_from_file(path: &str) -> Option<i64> {
    let mut file = File::open(path).ok()?;
    let mut contents = String::new();
    file.read_to_string(&mut contents).ok()?;
    contents.trim().parse::<i64>().ok()
}

As for the second part of the question, if you can contain all those variable bindings in a single function:

fn foo() -> Option<Vec<i64>> { // or some other Option<Vec>
    let energy_full = read_number_from_file(ENERGY_FULL_PATH)?;
    let energy_now = read_number_from_file(ENERGY_NOW_PATH)?;
    let is_charging = read_number_from_file(POWER_ONLINE_PATH)? > 0;

    Some(Vec::new()) // placeholder for the valid return value
}

You can then use unwrap_or_else() on its result to return an empty Vec upon any error:

let foo = foo().unwrap_or_else(|| vec![]);

Or just unwrap_or(), because empty vectors don't allocate memory:

let foo = foo().unwrap_or(vec![]);


问:
How does std::map operator[] cause memory leak with fundamental data types?
I'm using Visual Leak Detector to detect memory leaks, and have encountered many instances of memory leaks in lines such as:

```<code>class SomeClass
{
    // ...
    std::map<long,long> some_map;

    void func(long a_long, long b_long)
    {
        some_map[a_long] = b_long;  // here be a memory leak
    }
}
</code>```

How is this even possible? there are no pointers here, no object instantiation.

Could it be a memory leak that is a side-effect of having the program crash due to something else? Would a program crash or exit(1) cause the map to not be destructed cleanly?

答:
The code you've posted here is perfectly fine and shouldn't cause any leaks, so there are a few possible culprits:

Some STL implementations use custom allocators that retain dynamically-allocated memory without freeing it in order to make future allocations faster.  It's possible that you have such an implementation and that it's using this optimization, which would look like a leak from the perspective of a memory-checker.

If the program terminates abnormally, then the map destructor (or any object destructor, for that matter) won't be invoked, which would definitely cause the memory leak.

Body:
I'm using Visual Leak Detector to detect memory leaks, and have encountered many instances of memory leaks in lines such as:

class SomeClass
{
    // ...
    std::map<long,long> some_map;

    void func(long a_long, long b_long)
    {
        some_map[a_long] = b_long;  // here be a memory leak
    }
}

How is this even possible? there are no pointers here, no object instantiation.

Could it be a memory leak that is a side-effect of having the program crash due to something else? Would a program crash or exit(1) cause the map to not be destructed cleanly?


问:
why the list returned from the API deployed alphabetically?
I am using an C# API to return Contest datas.I have a List and returning this  as Output from API.

API Url :API Url

In this output the List is sorted in Alphabetical order.I want the List in the below mentioned Contest class order ,without sorting.

Contest Class:

```<code>public class Contest
{
    public int ContestID { get; set; }
    public string MovieName { get; set; }
    public string MovieImage { get; set; }
    public string RegionalMovieName{get;set;}
    public string Question { get; set; }
    public string Answer1 { get; set; }
    public string Answer2 { get; set; }
    public string Answer3 { get; set; }
    public string Ad1ImageUrl { get; set; }
    public string Ad2ImageUrl { get; set; }
    public string Ad3ImageUrl { get; set; }
    public string AdText { get; set; }
    public DateTime? StartDate { get; set; }
    public DateTime? EndDate { get; set; }
}
</code>```

Using the above class in Output List.

Controller Code:

```<code>public class ContestController : ApiController
{
    MMProvider.ContestProvider Provider = new MMProvider.ContestProvider();
    [HttpGet]
    [Route("GetContestDetails")]
    public IHttpActionResult GetContestDetail(string ContestId)
    {
        Contest _contest = new Contest();
        if (!string.IsNullOrEmpty(ContestId.ToString()))
        {
            List<Contest> ContestDetailsList = Provider.GetContestDetail(ContestId);
                return Ok(ContestDetailsList);
        }
        else
        {
            return NotFound();
        }
    }
</code>```

}

StoredProcedure:

```<code>ALTER PROCEDURE [dbo].[Proc_GetMblContest]
@ContestID INT
AS
BEGIN

IF EXISTS (SELECT COUNT(ContestID) FROM  Mbl_Contest WHERE ContestID = @ContestID AND Status='A')
BEGIN
    SELECT ContestID,MovieName,RegionalLanguage,MovieImage,Ad1ImageUrl,Ad2ImageUrl,Ad3ImageUrl,AdText,Question,Answer1,Answer2,Answer3,StartDate,EndDate FROM Mbl_Contest WHERE ContestID = @ContestID
END
END
</code>```

答:
There is no such thing as "class order". Class members exist without any internal order, no matter what order you type them in.

Assuming you are using the default serializers for WebApi, you need to specify which order you want:

```<code>[DataContract]
public class Contest
{
    [DataMember(Order = 0)]
    public int ContestID { get; set; }

    [DataMember(Order = 1)]
    public string MovieName { get; set; }

    [DataMember(Order = 2)]
    public string MovieImage { get; set; }

    [DataMember(Order = 3)]
    public string RegionalMovieName{get;set;}

    // ... the pattern should be clear
}
</code>```

Body:
I am using an C# API to return Contest datas.I have a List and returning this  as Output from API.

API Url :API Url

In this output the List is sorted in Alphabetical order.I want the List in the below mentioned Contest class order ,without sorting.

Contest Class:

public class Contest
{
    public int ContestID { get; set; }
    public string MovieName { get; set; }
    public string MovieImage { get; set; }
    public string RegionalMovieName{get;set;}
    public string Question { get; set; }
    public string Answer1 { get; set; }
    public string Answer2 { get; set; }
    public string Answer3 { get; set; }
    public string Ad1ImageUrl { get; set; }
    public string Ad2ImageUrl { get; set; }
    public string Ad3ImageUrl { get; set; }
    public string AdText { get; set; }
    public DateTime? StartDate { get; set; }
    public DateTime? EndDate { get; set; }
}

Using the above class in Output List.

Controller Code:

public class ContestController : ApiController
{
    MMProvider.ContestProvider Provider = new MMProvider.ContestProvider();
    [HttpGet]
    [Route("GetContestDetails")]
    public IHttpActionResult GetContestDetail(string ContestId)
    {
        Contest _contest = new Contest();
        if (!string.IsNullOrEmpty(ContestId.ToString()))
        {
            List<Contest> ContestDetailsList = Provider.GetContestDetail(ContestId);
                return Ok(ContestDetailsList);
        }
        else
        {
            return NotFound();
        }
    }

}

StoredProcedure:

ALTER PROCEDURE [dbo].[Proc_GetMblContest]
@ContestID INT
AS
BEGIN

IF EXISTS (SELECT COUNT(ContestID) FROM  Mbl_Contest WHERE ContestID = @ContestID AND Status='A')
BEGIN
    SELECT ContestID,MovieName,RegionalLanguage,MovieImage,Ad1ImageUrl,Ad2ImageUrl,Ad3ImageUrl,AdText,Question,Answer1,Answer2,Answer3,StartDate,EndDate FROM Mbl_Contest WHERE ContestID = @ContestID
END
END

Body:
There is no such thing as "class order". Class members exist without any internal order, no matter what order you type them in.

Assuming you are using the default serializers for WebApi, you need to specify which order you want:

[DataContract]
public class Contest
{
    [DataMember(Order = 0)]
    public int ContestID { get; set; }

    [DataMember(Order = 1)]
    public string MovieName { get; set; }

    [DataMember(Order = 2)]
    public string MovieImage { get; set; }

    [DataMember(Order = 3)]
    public string RegionalMovieName{get;set;}

    // ... the pattern should be clear
}


问:
Bulk import CSV file into a single sheet in a Google Sheet file
I'm trying to write a Google Sheet App script that bulk import CSV files into a single sheet in a google sheet.

Every week my server is sending me a CSV file reporting with some updated data from my database. Each CSV file has exactly the same structure, since it's the same report and only date is changing.

I automatically download all the csv in a single Folder on Google Drive
Is there a way to build a script that scans the folder, open the first CSV file fills a Google sheet with the data (and the date of the CSV report) deletes the current CSV from the folder then moves to the next CSV files.

答:
To scan/search for files in the drive, here is what you need.

You can search for files with the files.list method of the Drive
  API. Domain administrators may also search for Team Drives in the
  organization with the teamdrives.admin.list method.

Open and convert Google Docs in your app.

An app registered with the Import option enabled in the Drive UI
  Integration tab within the Drive API in the API Console can import
  supported Google Doc formats. This means that if a user selects Open
  with for a Google doc, the app can convert it to a format that the
  app can handle. When Open with triggers a conversion this way,
  Drive evaluates the MIME types an app can open (set during
  registration) and extrapolates the list of formats that the app
  can import.

Google doc formats are listed in the documentation.

And to manipulate the sheets you will open, you can refer here.

The Sheets API allows you to create sheets, delete sheets, and control
  their properties. The examples on this page illustrate how some common
  sheet operations can be achieved with the API.

For further info, you can refer from here and here.


问:
How to convert logical conditions to a variable of a function
I would like to achieve the above for the following:

```<code>Rn = 0.009; % Resolution of simulation (in m^3)
Xs = -1 : Rn : 1;
Ys = -1 : Rn : 1;
Zs =  0 : Rn : 1;

[X Y Z] = meshgrid(Xs, Ys, Zs);
alpha   = atan2(Z,X);
ze      = x.^2 + y.^2; % define some condition
m       = 0.59; % manual input
cond    = (pi/3 <= alpha)     & ...
          (alpha <= (2*pi/3)) & ...
          (m <= Z)            & ...
          (Z <= ze); % more conditions

xl = nnz(cond);        % the number of non-zero elements
f  = abs(xl*1000 - 90) % guessing m to get f as low as possible
</code>```

How do I turn m into a variable for some f function so I can call fminsearch to quickly find the corresponding m for f ≈ 0?

答:
In order to use m as a variable, you need to define a function handle. So you need to write:

```<code> cond = @(m) ((pi/3) <= alpha) & (alpha <= (2*pi/3)) & (m <= Z) & (Z <= ze);
</code>```

However, you cannot use a function handle in the nnz routine, since it only accepts matrices as inputs. But, the solution to the problem is that you only have Boolean variables in cond. This means, you can simply sum over cond and get the same result as with nnz.

The only issue I see is how to implement the sum in fminsearch. Unfortunately, I do not have access to fminsearch, however I would assume that you can do something with reshape and then multiply with dot (i.e. .*) with the unity vector to get a sum. But you'll have to try that one out, not sure about it.

Body:
I would like to achieve the above for the following:

Rn = 0.009; % Resolution of simulation (in m^3)
Xs = -1 : Rn : 1;
Ys = -1 : Rn : 1;
Zs =  0 : Rn : 1;

[X Y Z] = meshgrid(Xs, Ys, Zs);
alpha   = atan2(Z,X);
ze      = x.^2 + y.^2; % define some condition
m       = 0.59; % manual input
cond    = (pi/3 <= alpha)     & ...
          (alpha <= (2*pi/3)) & ...
          (m <= Z)            & ...
          (Z <= ze); % more conditions

xl = nnz(cond);        % the number of non-zero elements
f  = abs(xl*1000 - 90) % guessing m to get f as low as possible

How do I turn m into a variable for some f function so I can call fminsearch to quickly find the corresponding m for f ≈ 0?

Body:
In order to use m as a variable, you need to define a function handle. So you need to write:

 cond = @(m) ((pi/3) <= alpha) & (alpha <= (2*pi/3)) & (m <= Z) & (Z <= ze);

However, you cannot use a function handle in the nnz routine, since it only accepts matrices as inputs. But, the solution to the problem is that you only have Boolean variables in cond. This means, you can simply sum over cond and get the same result as with nnz.

The only issue I see is how to implement the sum in fminsearch. Unfortunately, I do not have access to fminsearch, however I would assume that you can do something with reshape and then multiply with dot (i.e. .*) with the unity vector to get a sum. But you'll have to try that one out, not sure about it.


问:
TypeError: __init__() missing 1 required positional argument: 'on_delete' in remote server CentOS7.2
In my Mac I use PyCharm run my Django project very well.

But in the remote server I use the same commands to run my project:

```<code>python3 manage.py runserver 8001
</code>```

The there comes the issue:

```<code>File "/var/www/html/Qiyun02//user_admin_productmanage_cloudserver/models.py", line 3, in <module>
        from xxx.qiyun_admin_productconfig_cloudserver.models import (
      File "/var/www/html/Qiyun02/qiyun_admin_productconfig_cloudserver/models.py", line 109, in <module>
        class Disk(models.Model):
      File "/var/www/html/Qiyun02/qiyun_admin_productconfig_cloudserver/models.py", line 110, in Disk
        diskEssenceType = models.ForeignKey(to=DiskEssenceType, related_name='disks')  #  "SAS", "SSD" and so on
    TypeError: __init__() missing 1 required positional argument: 'on_delete'
</code>```

I know the on_delete error means. but I mean, in my Mac why there do not shows the error? whether this is related to django version?

My local Mac Django version is 1.11.2.

The remote server CentOS7.2 version is python-django-1.8.14-1.el7.noarch

EDIT

Please, I know the on_delete error in there, I mean, in my Mac, there is no the reminds, why I copy to the CentOS7.2 remote server there comes this issue?  whether this is caused by django version?

EDIT -2

I upgrade the remote server django version to 1.11.2 too. but still have the same error.

EDIT -3

From the document:

A many-to-one relationship. Requires two positional arguments: the class to which the model is related and the on_delete option. (on_delete isn’t actually required, but not providing it gives a deprecation warning. It will be required in Django 2.0.)

You know, my django version is 1.11.2 now in my CentOS7.2 remote server, why there have the issue there?

EDIT -4

I don't have a virtual environment.

I use bellow command:

```<code>python3 manage.py shell
</code>```

get the same issue.

EDIT -5

In the end, I find my python3 use django 2.0. this is the issue.

```<code>python3 -m django --version
2.0
</code>```

答:
As per the doc, the error you are seeing will happen only for Django 2.0. Please check your Django version using shell

```<code>python manage.py shell
>>> import django
>>> django.VERSION
</code>```

Also consider using a virtual environment. That is how a project should be set up.

Body:
In my Mac I use PyCharm run my Django project very well.

But in the remote server I use the same commands to run my project:

python3 manage.py runserver 8001

The there comes the issue:

File "/var/www/html/Qiyun02//user_admin_productmanage_cloudserver/models.py", line 3, in <module>
        from xxx.qiyun_admin_productconfig_cloudserver.models import (
      File "/var/www/html/Qiyun02/qiyun_admin_productconfig_cloudserver/models.py", line 109, in <module>
        class Disk(models.Model):
      File "/var/www/html/Qiyun02/qiyun_admin_productconfig_cloudserver/models.py", line 110, in Disk
        diskEssenceType = models.ForeignKey(to=DiskEssenceType, related_name='disks')  #  "SAS", "SSD" and so on
    TypeError: __init__() missing 1 required positional argument: 'on_delete'

I know the on_delete error means. but I mean, in my Mac why there do not shows the error? whether this is related to django version?

My local Mac Django version is 1.11.2.

The remote server CentOS7.2 version is python-django-1.8.14-1.el7.noarch

EDIT

Please, I know the on_delete error in there, I mean, in my Mac, there is no the reminds, why I copy to the CentOS7.2 remote server there comes this issue?  whether this is caused by django version?

EDIT -2

I upgrade the remote server django version to 1.11.2 too. but still have the same error.

EDIT -3

From the document:

A many-to-one relationship. Requires two positional arguments: the class to which the model is related and the on_delete option. (on_delete isn’t actually required, but not providing it gives a deprecation warning. It will be required in Django 2.0.)

You know, my django version is 1.11.2 now in my CentOS7.2 remote server, why there have the issue there?

EDIT -4

I don't have a virtual environment.

I use bellow command:

python3 manage.py shell

get the same issue.

EDIT -5

In the end, I find my python3 use django 2.0. this is the issue.

python3 -m django --version
2.0

Body:
As per the doc, the error you are seeing will happen only for Django 2.0. Please check your Django version using shell

python manage.py shell
>>> import django
>>> django.VERSION

Also consider using a virtual environment. That is how a project should be set up.


问:
How to remove #symbol from laravel pagination url
I my laravel project i was using the pagination of the laravel.and call through the ajax but now i want to add the sorting searching and something. so i want my url like http://localhost:8000/test/sites?page=2&sort=name&order=asc
but i am getting url like http://localhost:8000/test/sites#?page=2 so how can i remove the # wich is coming from laravel caode.

```<code>  $sites = DB::table('to_jobs')
  ->select(array(
      'to_jobs.rec_id',
      'to_jobs.contarct_code',
      'to_jobs.job_num',
      'to_sites.site_name',
      'to_sites.postcode',
      'to_sites.site_id'
  ))
  ->leftjoin('to_sites', 'to_jobs.fk_site_id', '=', 'to_sites.site_id')
  /* ->join(DB::raw('(SELECT rec_id FROM   to_jobs LIMIT  299990, 10) AS t'), function($join) {
      $join->on('t.rec_id', '=', 'to_jobs.rec_id');
  })*/
  ->paginate(10);

  if (Request::ajax()) {
      return Response::json(View('sites/site_data',compact('sites'),compact('user_data'))->render());
  }
</code>```

Have i need to change in render().

答:
You can just remove give line from your script.</p>

```<code>`location.hash= '?page=' + page;`
</code>```

Body:
I my laravel project i was using the pagination of the laravel.and call through the ajax but now i want to add the sorting searching and something. so i want my url like http://localhost:8000/test/sites?page=2&sort=name&order=asc
but i am getting url like http://localhost:8000/test/sites#?page=2 so how can i remove the # wich is coming from laravel caode.

  $sites = DB::table('to_jobs')
  ->select(array(
      'to_jobs.rec_id',
      'to_jobs.contarct_code',
      'to_jobs.job_num',
      'to_sites.site_name',
      'to_sites.postcode',
      'to_sites.site_id'
  ))
  ->leftjoin('to_sites', 'to_jobs.fk_site_id', '=', 'to_sites.site_id')
  /* ->join(DB::raw('(SELECT rec_id FROM   to_jobs LIMIT  299990, 10) AS t'), function($join) {
      $join->on('t.rec_id', '=', 'to_jobs.rec_id');
  })*/
  ->paginate(10);

  if (Request::ajax()) {
      return Response::json(View('sites/site_data',compact('sites'),compact('user_data'))->render());
  }

Have i need to change in render().

Body:
You can just remove give line from your script.

`location.hash= '?page=' + page;`


问:
SQL Join table-valued function with table where table field is a function input
I have a table-valued function called fn_SplitCommaSep, which comma-separates a text field (from 'a, b, c' to 3 rows: a b c)

How can I join this to a table, taking a table column as an input?

For the purpose of this, say the table MyTable has 2 columns, Id and TextWithCommas, and that table-valued function fn_SplitCommaSep produces one column called TextWithoutComma

eg. something like one of these

```<code>select fs.TextWithoutComma
  from fn_SplitCommaSep(select mt.TextWithCommas from MyTable) fs
</code>```

or

```<code>select fs.TextWithoutComma, mt.Id
  from MyTable mt
    inner join fn_SplitCommaSep(mt.TextWithCommas) fs on (something)
</code>```

答:
Storing comma-separated values in a DB aside, take a look at APPLY

So something like:

```<code>SELECT fs.TextWithoutComma, mt.Id
FROM   MyTable mt
    CROSS APPLY fn_SplitCommaSep(mt.TextWithCommas) AS fs
</code>```

Body:
I have a table-valued function called fn_SplitCommaSep, which comma-separates a text field (from 'a, b, c' to 3 rows: a b c)

How can I join this to a table, taking a table column as an input?

For the purpose of this, say the table MyTable has 2 columns, Id and TextWithCommas, and that table-valued function fn_SplitCommaSep produces one column called TextWithoutComma

eg. something like one of these

select fs.TextWithoutComma
  from fn_SplitCommaSep(select mt.TextWithCommas from MyTable) fs

or

select fs.TextWithoutComma, mt.Id
  from MyTable mt
    inner join fn_SplitCommaSep(mt.TextWithCommas) fs on (something)

Body:
Storing comma-separated values in a DB aside, take a look at APPLY

So something like:

SELECT fs.TextWithoutComma, mt.Id
FROM   MyTable mt
    CROSS APPLY fn_SplitCommaSep(mt.TextWithCommas) AS fs


答:
```<code>ResponseMessageResult responseMessageResult;

using (MemoryStream stream = new MemoryStream(textAsBytes))
using (HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK))
{
    httpResponseMessage.Content = new StreamContent(stream);
    httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
    {
        FileName = "main-theme.scss"
    };
    httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("text/css");

    responseMessageResult = ResponseMessage(httpResponseMessage);
}

return responseMessageResult;
</code>```

Title: how to download a css file from a style string in asp.net web api

Body: I want to download a file (css type) from a concatenated style string from the database.I want to  return a new file created with the given stylestrings and return on http get request


问:
Send message to discord via google apps script
I'd like to send a bot message in a discord channel via google apps script when a certain event is triggered, but I don't know where to start. Is this even possible? If not, is there a way to do it via github?

EDIT: I have figured out how to get the OAuth tokens, now how do I make the bot send a message?

答:
To start with, here is a documentation from discord.js.

To let your apps script communicate with discord, you can check the External APIs

Google Apps Script can interact with APIs from all over the web. This
  guide shows how to work with different types of APIs in your scripts.

Examples are available in the provided documentations.

See these useful links for further details.

Website (source)

Documentation

Discord.js server

Discord API server

GitHub

NPM

Related libraries (see also discord-rpc)


问:
Xpages view panel - How to Open New Browser Tab
To do:

I want my view panel to open mail that send.

i able to open the mailbox, but i not be able to open it new tab, even i update the view with "_blank"

Script:
I put the script in "At runtime, open selected document using"

```<code>var ve:NotesViewEntry = rowData;
if (ve.isDocument()) {
    var doc:NotesDocument = ve.getDocument();

    var unid = doc.getItemValue("Notification_UNID2");
    if (unid != null && unid != "") {
        var trimmed = @Trim(unid);
        if (trimmed != "") {
            var mailsetdoc:NotesDocument = database.getProfileDocument("Mail Settings", "");
            var mailinsvr = mailsetdoc.getItemValueString("MailInDbSvr");
            var mailinpath = mailsetdoc.getItemValueString("MailInDbPath");
            var mailindb = session.getDatabase(mailinsvr, mailinpath, false);
            try {
                var notifydoc:NotesDocument = mailindb.getDocumentByUNID(trimmed);
                if (notifydoc != null) {
                    @ClientType() == "Notes" ? notifydoc.getNotesURL() : notifydoc.getHttpURL();
                }
            } catch(e) {
                if (@ClientType() == "Notes") {
                    "notes://" + @Name("[CN]", database.getServer()) + "/" + database.getFilePath().replace("\\", "/") + "/notification_deleted.xsp?OpenXPage";
                } else {
                    database.getHttpURL().replace("?OpenDatabase", "/notification_deleted.xsp");
                }
            }
        }
    }

}
</code>```

sample photo:

*This is list of person email image

*This is properties of photo

答:
Wrap the URL into javascript code, that launches the URL into new window/tab, but stays in current page.

Something like this:

```<code>javascript:window.open('YOUR URL HERE','_blank');void(0);
</code>```

Body:
To do:

I want my view panel to open mail that send.

i able to open the mailbox, but i not be able to open it new tab, even i update the view with "_blank"

Script:
I put the script in "At runtime, open selected document using"

var ve:NotesViewEntry = rowData;
if (ve.isDocument()) {
    var doc:NotesDocument = ve.getDocument();

    var unid = doc.getItemValue("Notification_UNID2");
    if (unid != null && unid != "") {
        var trimmed = @Trim(unid);
        if (trimmed != "") {
            var mailsetdoc:NotesDocument = database.getProfileDocument("Mail Settings", "");
            var mailinsvr = mailsetdoc.getItemValueString("MailInDbSvr");
            var mailinpath = mailsetdoc.getItemValueString("MailInDbPath");
            var mailindb = session.getDatabase(mailinsvr, mailinpath, false);
            try {
                var notifydoc:NotesDocument = mailindb.getDocumentByUNID(trimmed);
                if (notifydoc != null) {
                    @ClientType() == "Notes" ? notifydoc.getNotesURL() : notifydoc.getHttpURL();
                }
            } catch(e) {
                if (@ClientType() == "Notes") {
                    "notes://" + @Name("[CN]", database.getServer()) + "/" + database.getFilePath().replace("\\", "/") + "/notification_deleted.xsp?OpenXPage";
                } else {
                    database.getHttpURL().replace("?OpenDatabase", "/notification_deleted.xsp");
                }
            }
        }
    }

}

sample photo:

*This is list of person email image

*This is properties of photo

Body:
Wrap the URL into javascript code, that launches the URL into new window/tab, but stays in current page.

Something like this:

javascript:window.open('YOUR URL HERE','_blank');void(0);


问:
How can i invoke a paper scanner using php code?
How can I invoke a paper scanner using php code?

I have already used Dynamic Web TWAIN for scanning, but it is not free.

I need an open source code to scan.

Please help me. Thank you in advance.

答:
PHP is a server side language and cannot interact with client side hardware. You can use a web-based TWAIN SDK to scan documents in your PHP app. Check out this article which might help: http://www.dynamsoft.com/blog/document-imaging/how-to-scan-documents-in-php

You can also use Scanner.js: https://github.com/Asprise/scannerjs.javascript-scanner-access-in-browsers-chrome-ie.scanner.js

Maybe you can try phpSANE: https://sourceforge.net/projects/phpsane/

phpSANE is a web-based frontend for SANE written in HTML/PHP so you
  can scan with your web-browser. It also supports OCR.

PHP Printer library: https://github.com/mike42/escpos-php