问:
Parsing a file in backward and forward direction
I have a very long file with a periodical structure (the three dots resembles numbers of lines not necessarily equal, and n is just an index):

```<code>...
string bar text1 (n-2)
...
string bar text1 (n-1)
...
string bar text1 (n)
...
STRING FOO
elements1
elements1
...
string bar text2 (n-2)
...
string bar text2 (n-1)
...
string bar text2 (n)
...
STRING FOO
elements2
elements2
...
</code>```

I am trying to make a bash script to parse this file, and print to another file the following information: find all the appearances of STRING FOO and print to the new file the elements (which can be two, for example) plus the string bar n. In order to achieve that, I have tried the following commands:

```<code>grep -A 2 "STRING FOO"  input_file.txt   >> output_file.txt
grep -B 200 "STRING FOO" input_file.txt | tac | sed -n '/'string bar n'/ { p ; q }' >> output_file.txt
</code>```

Expected output:

```<code>STRING FOO
elements1
elements1
string bar text1
STRING FOO
elements2
elements2
string bar text2
</code>```

Where the number 200 is just a "guess" of how many lines I need to go back. Those commands, besides inefficient, are not working properly. I would really appreciate someone else's help.

答:
With :

```<code>grep "STRING FOO\|string bar" file.out | grep -B 1 STRING FOO | head -n 1
</code>```

You will have your "string bar text1 (n)"

And repeat the same logic for your "elements".

Sincerely.

Body:
I have a very long file with a periodical structure (the three dots resembles numbers of lines not necessarily equal, and n is just an index):

...
string bar text1 (n-2)
...
string bar text1 (n-1)
...
string bar text1 (n)
...
STRING FOO
elements1
elements1
...
string bar text2 (n-2)
...
string bar text2 (n-1)
...
string bar text2 (n)
...
STRING FOO
elements2
elements2
...

I am trying to make a bash script to parse this file, and print to another file the following information: find all the appearances of STRING FOO and print to the new file the elements (which can be two, for example) plus the string bar n. In order to achieve that, I have tried the following commands:

grep -A 2 "STRING FOO"  input_file.txt   >> output_file.txt
grep -B 200 "STRING FOO" input_file.txt | tac | sed -n '/'string bar n'/ { p ; q }' >> output_file.txt

Expected output:

STRING FOO
elements1
elements1
string bar text1
STRING FOO
elements2
elements2
string bar text2

Where the number 200 is just a "guess" of how many lines I need to go back. Those commands, besides inefficient, are not working properly. I would really appreciate someone else's help.

Body:
With :

grep "STRING FOO\|string bar" file.out | grep -B 1 STRING FOO | head -n 1

You will have your "string bar text1 (n)"

And repeat the same logic for your "elements".

Sincerely.


来源: stackexchange

问:
Unable to print array into HTML
I have a program which is pulling data from the database like so.

Views.py

```<code>def final(request):
total = []
name = []
k = 0
for i in Question.objects.raw("SELECT name, question1, question2, question3, question4, question5, question6, question7, question8, question9, question10 FROM music_question"):
    name.append(str(i.name))
    total.append(int(i.question1) + int(i.question2) + int(i.question3) + int(i.question4) + int(i.question5)
                 + int(i.question6) + int(i.question7) + int(i.question8) + int(i.question9) + int(i.question10))
return render(request, 'music/final.html', {"totals": total, "names": name, "rows": Question.objects.all()})
</code>```

From here I'm trying to print into HTML like so

final.HTML

```<code>    </body>
<script type=text/javascript>
data = {{totals}}
console.log(data)
</script>
</html>
</code>```

I can see that the data from the database has returned to the console in Chrome but it won't persist onto the web page and I'm not sure where I'm going wrong.

答: Maybe you should put data = {{totals}} before  tag, or I did not understand you ?

ContentLicense: CC BY-SA 3.0

Title: Unable to print array into HTML

Body:
I have a program which is pulling data from the database like so.

Views.py

def final(request):
total = []
name = []
k = 0
for i in Question.objects.raw("SELECT name, question1, question2, question3, question4, question5, question6, question7, question8, question9, question10 FROM music_question"):
    name.append(str(i.name))
    total.append(int(i.question1) + int(i.question2) + int(i.question3) + int(i.question4) + int(i.question5)
                 + int(i.question6) + int(i.question7) + int(i.question8) + int(i.question9) + int(i.question10))
return render(request, 'music/final.html', {"totals": total, "names": name, "rows": Question.objects.all()})

From here I'm trying to print into HTML like so

final.HTML

I can see that the data from the database has returned to the console in Chrome but it won't persist onto the web page and I'm not sure where I'm going wrong.

Body: Maybe you should put data = {{totals}} before </body> tag, or I did not understand you ?


问:
Left function in sql server
In table 'Period' there is a column 'Date' ,example data is FEBRUARY 3,2010

Now in where condition Left(Date,3)='Feb' also gives results,Is the Left function case insensitive?

答:
You ca also use below query:

```<code>select *
from table_name
where left(lower(column_name),3)  = 'feb'
</code>```

EDIT:
if you don't care about case sensitivity and not sure about collation, if collation is CI (case insensitive) then "lower" is not needed however there is no harm to use it as this function seems to be not expensive one.

Title: Left function in sql server

Body:
You ca also use below query:

select *
from table_name
where left(lower(column_name),3)  = 'feb'

EDIT:
if you don't care about case sensitivity and not sure about collation, if collation is CI (case insensitive) then "lower" is not needed however there is no harm to use it as this function seems to be not expensive one.


问:
Appending to XML with XMLStreamWriter
Basically the app writes the contents of a Collection to XML. I'm using XMLStreamWriter (XMLOutputFactory.newInstance().createXMLStreamWriter(...)) for this purpose.

Works great except for the fact that I can't get how to append data to an existing file. Don't really like the idea of reading all of it first, appending the data in memory and then overwriting. Or is it the only way?

答: Another approach is to build a new XML file and then merge it with the previous one by means of XSLT transformations. To apply XSLT stylesheets you should use Java XML Transformation API.</p>

OwnerDisplayName: gsmd

ContentLicense: CC BY-SA 2.5

Title: Appending to XML with XMLStreamWriter

OwnerDisplayName: Fernando Miguélez


答:
You need to pass axis=1 to concat if you want to concatenate columns. In addition, you don't need to initialize your data frame with data in the beginning (except you want to have the 0 value):

```<code>def dummy_historical(seclist, dates, startvalues):

    dfHist = pd.DataFrame()

    for sec in seclist:
        svalue   = startvalues[sec].max()
        dfRandom = pd.DataFrame(np.random.randint(svalue-10,svalue+10, size=(dates.size, 1 )), index=dates, columns=[sec])
        dfHist = pd.concat([ dfHist , dfRandom ], axis=1)

    return dfHist
</code>```

You can even write in a more concise way avoiding concat like:

```<code>def generate(sec):
    svalue = startvalues[sec].max()
    return np.random.randint(svalue-10,svalue+10, size=dates.size)

dfHist = pd.DataFrame({sec: generate(sec) for sec in seclist}, index=dates)
</code>```

Title: pandas.concat() does not fill the columns

Body:
I am trying to create dummy data as follows:

import numpy as np
import pandas as pd

def dummy_historical(seclist, dates, startvalues):

    dfHist = pd.DataFrame(0, index=[0], columns=seclist)

    for sec in seclist:

        # (works fine)
        svalue   = startvalues[sec].max()

        # this creates a random sequency of 84 rows and 1 column (works fine)
        dfRandom = pd.DataFrame(np.random.randint(svalue-10,svalue+10, size=(dates.size, 1 )), index=dates, columns=[sec])

        # does not work
        dfHist[sec] = pd.concat([ dfHist[sec] , dfRandom ])

return dfHist

When I print dfHist, it only shows me the first row (as when initiated). Thus nothing has been filled.

Here is an example of the data:

seclist = ['AAPL', 'GOOGL']

# use any number for startvalues

dates = DatetimeIndex(['2017-01-05', '2017-01-06', '2017-01-07', '2017-01-08',
                   '2017-01-09', '2017-01-10', '2017-01-11', '2017-01-12',
                   '2017-01-13', '2017-01-14', '2017-01-15', '2017-01-16',
                   '2017-01-17', '2017-01-18', '2017-01-19', '2017-01-20',
                   '2017-01-21', '2017-01-22', '2017-01-23', '2017-01-24',
                   '2017-01-25', '2017-01-26', '2017-01-27', '2017-01-28',
                   '2017-01-29', '2017-01-30', '2017-01-31', '2017-02-01',
                   '2017-02-02', '2017-02-03', '2017-02-04', '2017-02-05',
                   '2017-02-06', '2017-02-07', '2017-02-08', '2017-02-09',
                   '2017-02-10', '2017-02-11', '2017-02-12', '2017-02-13',
                   '2017-02-14', '2017-02-15', '2017-02-16', '2017-02-17',
                   '2017-02-18', '2017-02-19', '2017-02-20', '2017-02-21',
                   '2017-02-22', '2017-02-23', '2017-02-24', '2017-02-25',
                   '2017-02-26', '2017-02-27', '2017-02-28', '2017-03-01',
                   '2017-03-02', '2017-03-03', '2017-03-04', '2017-03-05',
                   '2017-03-06', '2017-03-07', '2017-03-08', '2017-03-09',
                   '2017-03-10', '2017-03-11', '2017-03-12', '2017-03-13',
                   '2017-03-14', '2017-03-15', '2017-03-16', '2017-03-17',
                   '2017-03-18', '2017-03-19', '2017-03-20', '2017-03-21',
                   '2017-03-22', '2017-03-23', '2017-03-24', '2017-03-25',
                   '2017-03-26', '2017-03-27', '2017-03-28', '2017-03-29'],
                  dtype='datetime64[ns]', freq='D')

Body:
You need to pass axis=1 to concat if you want to concatenate columns. In addition, you don't need to initialize your data frame with data in the beginning (except you want to have the 0 value):

def dummy_historical(seclist, dates, startvalues):

    dfHist = pd.DataFrame()

    for sec in seclist:
        svalue   = startvalues[sec].max()
        dfRandom = pd.DataFrame(np.random.randint(svalue-10,svalue+10, size=(dates.size, 1 )), index=dates, columns=[sec])
        dfHist = pd.concat([ dfHist , dfRandom ], axis=1)

    return dfHist

You can even write in a more concise way avoiding concat like:

def generate(sec):
    svalue = startvalues[sec].max()
    return np.random.randint(svalue-10,svalue+10, size=dates.size)

dfHist = pd.DataFrame({sec: generate(sec) for sec in seclist}, index=dates)


Title: pyspark dataframe from rdd containing key and values as list of lists

Body:
I have a RDD like below with keys and values as list of list containing some parameters.

(32719, [[[u'200.73.55.34', u'192.16.48.217', 0, 6, 10163, 443, 0], [u'177.207.76.243', u'192.16.58.8', 0, 6, 59575, 80, 0]])
(32897, [[[u'200.73.55.34', u'193.16.48.217', 0, 6, 10163, 443, 0], [u'167.207.76.243', u'194.16.58.8', 0, 6, 59575, 80, 0]])

I want to create a dataframe with rows and columns as below

32719, '200.73.55.34', u'192.16.48.217', 0, 6, 10163, 443, 0
32719, '177.207.76.243', u'192.16.58.8', 0, 6, 59575, 80, 0
32897, 200.73.55.34', u'193.16.48.217', 0, 6, 10163, 443, 0

Or just a dataframe of all the values but grouped by the key. How can I do this.

Body:
You can map to add the key to each value and create dataframe. I tried in my way,

>>>dat1 = [(32719, [[u'200.73.55.34', u'192.16.48.217', 0, 6, 10163, 443, 0], [u'177.207.76.243', u'192.16.58.8', 0, 6, 59575, 80, 0]]),(32897, [[u'200.73.55.34', u'193.16.48.217', 0, 6, 10163, 443, 0], [u'167.207.76.243', u'194.16.58.8', 0, 6, 59575, 80, 0]])]

>>>rdd1 = sc.parallelize(dat1).map(lambda x : [[x[0]]+i for i in x[1]]).flatMap(lambda x : (x))
>>>df = rdd1.toDF(['col1','col2','col3','col4','col5','col6','col7','col8'])
>>> df.show()
+-----+--------------+-------------+----+----+-----+----+----+
| col1|          col2|         col3|col4|col5| col6|col7|col8|
+-----+--------------+-------------+----+----+-----+----+----+
|32719|  200.73.55.34|192.16.48.217|   0|   6|10163| 443|   0|
|32719|177.207.76.243|  192.16.58.8|   0|   6|59575|  80|   0|
|32897|  200.73.55.34|193.16.48.217|   0|   6|10163| 443|   0|
|32897|167.207.76.243|  194.16.58.8|   0|   6|59575|  80|   0|
+-----+--------------+-------------+----+----+-----+----+----+


问:
Importing data from multiple webpages using Excel VBA?
I have 2 URL's that I want to scrape the entire data off the landing page into one column in excel in a worksheet. URL's are;
    URL;http://www.chambersandpartners.com/Global/firm/257/hogan-lovells
    URL;http://www.chambersandpartners.com/Global/firm/3635/king-spalding

When I do it manually in excel via "data/from web" I can collect the data but when I try using VBA no data is returned. I am wanting a separate worksheet for each URL in a work book. I am then wanting to add more URL's to the list so that a programme can loop through them. Please can any one help? Thanks in advance.

The VBA code is below:

```<code>    Sub adds()
    For x = 1 To 5
    Worksheets("chambers").Select
    Worksheets("chambers").Activate
    mystr = "URL;http://www.chambersandpartners.com/Global/firm/257/hogan-     lovells"
    mystr = Cells(x, 1)
    Worksheets.Add(After:=Worksheets(Worksheets.Count)).Name = x
    With ActiveSheet.QueryTables.Add(Connection:=mystr,        Destination:=Range("$A$1"))
   'CommandType = 0
   .Name = "hogan-lovells"
   .FieldNames = True
   .RowNumbers = False
   .FillAdjacentFormulas = False
   .PreserveFormatting = True
   .RefreshOnFileOpen = False
   .BackgroundQuery = True
   .RefreshStyle = xlInsertDeleteCells
   .SavePassword = False
   .SaveData = True
   .AdjustColumnWidth = True
   .RefreshPeriod = 0
   .WebSelectionType = xlSpecifiedTables
   .WebFormatting = xlWebFormattingNone
   .WebPreFormattedTextToColumns = True
   .WebConsecutiveDelimitersAsOne = True
   .WebSingleBlockTextImport = False
   .WebDisableDateRecognition = False
   .WebDisableRedirections = False
   .Refresh BackgroundQuery:=False
    End With
   Next x
   End Sub
</code>```

These are the five URLs in Cells(x, 1) I am trying to grab with this code:

```<code>URL;chambersandpartners.com/Global/firm/257/hogan-lovells
URL;chambersandpartners.com/Global/firm/3635/king-spalding
URL;chambersandpartners.com/Global/firm/3636/kirkland-ellis
URL;chambersandpartners.com/Global/firm/3689/latham-watkins
URL;chambersandpartners.com/Global/firm/255/linklaters
</code>```

答:
If manually adding your data with the default Excel Webquery works, you can use VBA to simply refresh your queries.

This is the easiest way of doing automated Queries if you do not need dynamic URL handling or parsing.

Simply create all of your connections, then use Macro Recording to record your refreshes, then tweak the resulting VBA.

You can find all of your active connections under the Data tab -> Connections

Body:
I have 2 URL's that I want to scrape the entire data off the landing page into one column in excel in a worksheet. URL's are;
    URL;http://www.chambersandpartners.com/Global/firm/257/hogan-lovells
    URL;http://www.chambersandpartners.com/Global/firm/3635/king-spalding

When I do it manually in excel via "data/from web" I can collect the data but when I try using VBA no data is returned. I am wanting a separate worksheet for each URL in a work book. I am then wanting to add more URL's to the list so that a programme can loop through them. Please can any one help? Thanks in advance.

The VBA code is below:

    Sub adds()
    For x = 1 To 5
    Worksheets("chambers").Select
    Worksheets("chambers").Activate
    mystr = "URL;http://www.chambersandpartners.com/Global/firm/257/hogan-     lovells"
    mystr = Cells(x, 1)
    Worksheets.Add(After:=Worksheets(Worksheets.Count)).Name = x
    With ActiveSheet.QueryTables.Add(Connection:=mystr,        Destination:=Range("$A$1"))
   'CommandType = 0
   .Name = "hogan-lovells"
   .FieldNames = True
   .RowNumbers = False
   .FillAdjacentFormulas = False
   .PreserveFormatting = True
   .RefreshOnFileOpen = False
   .BackgroundQuery = True
   .RefreshStyle = xlInsertDeleteCells
   .SavePassword = False
   .SaveData = True
   .AdjustColumnWidth = True
   .RefreshPeriod = 0
   .WebSelectionType = xlSpecifiedTables
   .WebFormatting = xlWebFormattingNone
   .WebPreFormattedTextToColumns = True
   .WebConsecutiveDelimitersAsOne = True
   .WebSingleBlockTextImport = False
   .WebDisableDateRecognition = False
   .WebDisableRedirections = False
   .Refresh BackgroundQuery:=False
    End With
   Next x
   End Sub

These are the five URLs in Cells(x, 1) I am trying to grab with this code:

URL;chambersandpartners.com/Global/firm/257/hogan-lovells
URL;chambersandpartners.com/Global/firm/3635/king-spalding
URL;chambersandpartners.com/Global/firm/3636/kirkland-ellis
URL;chambersandpartners.com/Global/firm/3689/latham-watkins
URL;chambersandpartners.com/Global/firm/255/linklaters


问:
Asynchronous Json request not working with google motion chart
I'm using the following code to request for json file and parsing it

```<code>google.load('visualization', '1', {packages: ['controls', "motionchart", "table"]});
google.setOnLoadCallback(function(){
createTable($('#chart_div').width(),400);
})
var jsonData;
$.ajax({
 url: shapingTomorrowDataUrl,
 dataType: "json",
 async: true,
 success: function(data) {
  console.log("Data done");
  jsonData=data;
  createTable($('#chart_div').width(),400);
  }
});
</code>```

Now I initially used a synchronous call to json file and it worked perfectly. But now my client wants a loader gif to play while the data is being read. Synchronous request caused the gif to hang a lot. But my problem with asynchronous request is that on the first time that the user opens my dashboard, the chart function gets called before the json data is parsed. I changed the code a bit to call the function in the success function and commenting the callbackfunction.

But this causes the following error to pop up:

Uncaught TypeError: Cannot read property 'DataTable' of undefined

in the following line:

```<code>var chartData = new google.visualization.DataTable();
</code>```

So in essence my code only works after the first try i.e I'm guessing after the json file is stored in cache. During the first try, the loader gif keeps playing without ever drawing the chart. Would really appreciate some advice on how to solve it.

答:
wait until the callback is finished before making the <code>$.ajax</code> call...  </p>

```<code>var jsonData;
google.load('visualization', '1', {packages: ['controls', "motionchart", "table"]});
google.setOnLoadCallback(function(){
  $.ajax({
   url: shapingTomorrowDataUrl,
   dataType: "json",
   async: true,
   success: function(data) {
    console.log("Data done");
    jsonData=data;
    createTable($('#chart_div').width(),400);
    }
  });
});
</code>```

Body:
I'm using the following code to request for json file and parsing it

google.load('visualization', '1', {packages: ['controls', "motionchart", "table"]});
google.setOnLoadCallback(function(){
createTable($('#chart_div').width(),400);
})
var jsonData;
$.ajax({
 url: shapingTomorrowDataUrl,
 dataType: "json",
 async: true,
 success: function(data) {
  console.log("Data done");
  jsonData=data;
  createTable($('#chart_div').width(),400);
  }
});

Now I initially used a synchronous call to json file and it worked perfectly. But now my client wants a loader gif to play while the data is being read. Synchronous request caused the gif to hang a lot. But my problem with asynchronous request is that on the first time that the user opens my dashboard, the chart function gets called before the json data is parsed. I changed the code a bit to call the function in the success function and commenting the callbackfunction.

But this causes the following error to pop up:

Uncaught TypeError: Cannot read property 'DataTable' of undefined

in the following line:

var chartData = new google.visualization.DataTable();

So in essence my code only works after the first try i.e I'm guessing after the json file is stored in cache. During the first try, the loader gif keeps playing without ever drawing the chart. Would really appreciate some advice on how to solve it.

Body:
wait until the callback is finished before making the $.ajax call...

var jsonData;
google.load('visualization', '1', {packages: ['controls', "motionchart", "table"]});
google.setOnLoadCallback(function(){
  $.ajax({
   url: shapingTomorrowDataUrl,
   dataType: "json",
   async: true,
   success: function(data) {
    console.log("Data done");
    jsonData=data;
    createTable($('#chart_div').width(),400);
    }
  });
});


问:
How to create a AngularJS promise from a callback-based API
wifiservice.js:

```<code>angular.module('app.WifiServices', [])
    .factory('WifiService', function(){
        var unique_array = angular.fromJson('[]');

        function win_wifi(e){
        alert("Success");
        }

        function fail_wifi(e){
        alert("Error");
        }

        function connectWifi(wifi_ssid){
          WifiWizard.connectNetwork(wifi_ssid, win_wifi, fail_wifi);
        }

        function listHandler(a){

      var network_array = [];
      for(var i=0; i<a.length; i++){
        network_array.push("SSID: " + a[i].SSID + " Signal: " + a[i].level);
      }

      unique_array = network_array.filter(function(elem, pos) {
        return network_array.indexOf(elem) == pos;
      });

      // alert("Wifi List Ready!");
    }

    function getScanResult(){
      WifiWizard.getScanResults(listHandler, failNetwork);
    }

    function successNetwork(e){
      window.setTimeout(function(){
        getScanResult();
      }, 3000);
    }

    function failNetwork(e){
      alert("Network Failure: " + e);
    }

    window.setTimeout(function(){
      WifiWizard.startScan(successNetwork, failNetwork);
    }, 1000);

        return {
          list: function(){
            return unique_array;
          },

          connectionToWifi: function(name){
            connectWifi(name);
          }
        };
    });
</code>```

My whole controller:

```<code>app.controller('WifiController', ['$scope', 'WifiService', function($scope, WifiService) {

 $scope.wifiList = [];

 window.setTimeout(function() {
  $scope.wifiList = WifiService.list();
  // alert($scope.wifiList);
  $scope.$apply();
 }, 5000);

 $scope.getList = function() {
  $scope.wifiList = WifiService.list();
  return $scope.wifiList;
 }

 $scope.connectWifi = function(name) {
  WifiService.connectionToWifi(name);
 }

 $scope.checkin = function() {
  $scope.getList()
  .then(function(result) {
     console.log(result);
 });
}

}]);
</code>```

What I am trying to do is, to call the $scope.getList(), which returns a list of the surrounding wifi SSIDs, then within $scope.checkin() I would like to process those data.

Since scanning needs some time I have to wait the getList function to finish, thats Why I am trying to use .then, but it gives me the error says on the title. Any ideas?

答:
Well, I came up with something different:

```<code>var unique_array = [];
  $scope.wifiList = [];
  $ionicLoading.show({
    template: "Scanning surrounding AP's..."
  });

 window.setTimeout(function() {
  $scope.wifiList = WifiService.list();
  // alert($scope.wifiList);
  while ($scope.wifiList == []) {
    console.log('Scanning...');
  }
  $scope.$apply();
  $ionicLoading.hide();
 }, 5000);
</code>```

What I realize is that the scanning starts once I load the view. So, I added an IonicLoader to force the user to wait, and not be able to press any buttons till the scan is finished. So no function shall wait one another. Not quite code-wise correct, but it does what I need.

Body:
wifiservice.js:

angular.module('app.WifiServices', [])
    .factory('WifiService', function(){
        var unique_array = angular.fromJson('[]');

        function win_wifi(e){
        alert("Success");
        }

        function fail_wifi(e){
        alert("Error");
        }

        function connectWifi(wifi_ssid){
          WifiWizard.connectNetwork(wifi_ssid, win_wifi, fail_wifi);
        }

        function listHandler(a){

      var network_array = [];
      for(var i=0; i<a.length; i++){
        network_array.push("SSID: " + a[i].SSID + " Signal: " + a[i].level);
      }

      unique_array = network_array.filter(function(elem, pos) {
        return network_array.indexOf(elem) == pos;
      });

      // alert("Wifi List Ready!");
    }

    function getScanResult(){
      WifiWizard.getScanResults(listHandler, failNetwork);
    }

    function successNetwork(e){
      window.setTimeout(function(){
        getScanResult();
      }, 3000);
    }

    function failNetwork(e){
      alert("Network Failure: " + e);
    }

    window.setTimeout(function(){
      WifiWizard.startScan(successNetwork, failNetwork);
    }, 1000);

        return {
          list: function(){
            return unique_array;
          },

          connectionToWifi: function(name){
            connectWifi(name);
          }
        };
    });

My whole controller:

app.controller('WifiController', ['$scope', 'WifiService', function($scope, WifiService) {

 $scope.wifiList = [];

 window.setTimeout(function() {
  $scope.wifiList = WifiService.list();
  // alert($scope.wifiList);
  $scope.$apply();
 }, 5000);

 $scope.getList = function() {
  $scope.wifiList = WifiService.list();
  return $scope.wifiList;
 }

 $scope.connectWifi = function(name) {
  WifiService.connectionToWifi(name);
 }

 $scope.checkin = function() {
  $scope.getList()
  .then(function(result) {
     console.log(result);
 });
}

}]);

What I am trying to do is, to call the $scope.getList(), which returns a list of the surrounding wifi SSIDs, then within $scope.checkin() I would like to process those data.

Since scanning needs some time I have to wait the getList function to finish, thats Why I am trying to use .then, but it gives me the error says on the title. Any ideas?

Body:
Well, I came up with something different:

var unique_array = [];
  $scope.wifiList = [];
  $ionicLoading.show({
    template: "Scanning surrounding AP's..."
  });

 window.setTimeout(function() {
  $scope.wifiList = WifiService.list();
  // alert($scope.wifiList);
  while ($scope.wifiList == []) {
    console.log('Scanning...');
  }
  $scope.$apply();
  $ionicLoading.hide();
 }, 5000);

What I realize is that the scanning starts once I load the view. So, I added an IonicLoader to force the user to wait, and not be able to press any buttons till the scan is finished. So no function shall wait one another. Not quite code-wise correct, but it does what I need.


问:
SQL CREATE and SELECT processing simulation in Java
I want to simulate simple SQL statement (Create & Select) processing in Java.

For example, consider following two relations

```<code>CREATE TABLE X( a, b, c);
CREATE TABLE Y( c, d, e);
</code>```

Ques 1:
Now what data structures can I use to store the relation name X and Y along with their attributes .

Also consider the select statement:

```<code>SELECT a,d FROM X,Y WHERE X.c = Y.c ;
</code>```

Ques 2:
How to confirm whether a belongs to X or Y and d belongs to X or Y ?
How does this processing is taken care inside SQL query processing engine.

I can find numerous query evaluation plans that pushes the SELECT statement below JOIN operation if the Selection depends on only on a single relation. For this purpose I need to know How to confirm to which relation the attribute belongs to?

答:
Ques 1: Now what data structures can I use to store the relation name X and Y along with their attributes .

Use any structure you like, in Java you'd most probably use classes that correspond to X and Y and which have fields that correspond to a, b, c for X and c, d, e for Y.

SELECT a,d FROM X,Y WHERE X.c = Y.c ;

Ques 2: How to confirm whether a belongs to X or Y and d belongs to X or Y ? How does this processing is taken care inside SQL query processing engine.

Since a only exists in X and d only exists in Y the database knows what's meant. If they'd exist in the other table as well you'd need to specify which of them you mean (e.g. SELECT x.a, d FROM X x, Y y ...).

ContentLicense: CC BY-SA 4.0

Body:
I want to simulate simple SQL statement (Create & Select) processing in Java.

For example, consider following two relations

CREATE TABLE X( a, b, c);
CREATE TABLE Y( c, d, e);

Ques 1:
Now what data structures can I use to store the relation name X and Y along with their attributes .

Also consider the select statement:

SELECT a,d FROM X,Y WHERE X.c = Y.c ;

Ques 2:
How to confirm whether a belongs to X or Y and d belongs to X or Y ?
How does this processing is taken care inside SQL query processing engine.

I can find numerous query evaluation plans that pushes the SELECT statement below JOIN operation if the Selection depends on only on a single relation. For this purpose I need to know How to confirm to which relation the attribute belongs to?


问:
Delete row from database with form in the same page
In the same page I have a form that asks the user to confirm whether he wants to delete the data or not, and I have the PHP code. Now, I want to delete a row from database using superglobals, but I can't figure out the problem. It always echos "NOT DELETED". Also If the user chooses not to delete, I would like to perform a redirect to home.php.

```<code><body>

<h2>Are you sure you want to delete the student?</h2>
<form method="post" action="<?=$_SERVER['PHP_SELF']?>">
    <input type="submit" name="submit" value="YES" />
    <input type="submit" name="submit" value="NO" />
</form>

<?php

$fields = array('id', 'student', 'firstname', 'lastname', 'email');
$student= array();

foreach ($fields as $field) {
$student[$field]="";
}

if(isset($_POST['id'])) {
    $id = htmlspecialchars($_POST['id']);
}
else if(isset($_GET['id'])) {
    $id = htmlspecialchars($_GET['id']);
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if(!empty($id)) {

    include "inc_DBConnect.php";

    $SQLString = "DELETE FROM students WHERE id = '$id'";

    $SQLQueryResult = mysqli_query($DBConnection, $SQLString);
    if($SQLQueryResult === FALSE) {
        echo "<p>There was an error retrieving the record.<br />\n</p>";
    } else {
        echo "<p>Student deleted</p>";
    }
} else {
    echo "NOT DELETED";
 }

}

?>
</body>
</code>```

答:
Try to print your $_SERVER['REQUEST_METHOD'] variable before if

OR var_dump($_SERVER) and check what's wrong in this array - maybe your server don't set a REQUEST_METHOD key.

By other ways you should also try this way

```<code>if( count($_POST) ){/*....*/};
</code>```

Body:
In the same page I have a form that asks the user to confirm whether he wants to delete the data or not, and I have the PHP code. Now, I want to delete a row from database using superglobals, but I can't figure out the problem. It always echos "NOT DELETED". Also If the user chooses not to delete, I would like to perform a redirect to home.php.

Are you sure you want to delete the student?

<form method="post" action="<?=$_SERVER['PHP_SELF']?>">
    <input type="submit" name="submit" value="YES" />
    <input type="submit" name="submit" value="NO" />
</form>

<?php

$fields = array('id', 'student', 'firstname', 'lastname', 'email');
$student= array();

foreach ($fields as $field) {
$student[$field]="";
}

if(isset($_POST['id'])) {
    $id = htmlspecialchars($_POST['id']);
}
else if(isset($_GET['id'])) {
    $id = htmlspecialchars($_GET['id']);
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if(!empty($id)) {

    include "inc_DBConnect.php";

    $SQLString = "DELETE FROM students WHERE id = '$id'";

    $SQLQueryResult = mysqli_query($DBConnection, $SQLString);
    if($SQLQueryResult === FALSE) {
        echo "
There was an error retrieving the record.
\n
";
    } else {
        echo "
Student deleted
";
    }
} else {
    echo "NOT DELETED";
 }

}

?>

Body:
Try to print your $_SERVER['REQUEST_METHOD'] variable before if

OR var_dump($_SERVER) and check what's wrong in this array - maybe your server don't set a REQUEST_METHOD key.

By other ways you should also try this way

if( count($_POST) ){/*....*/};


问:
How do I strip all javascript out of an HTML document using PHP?
In my email program I use Tidy to clean up the HTML before I send out the emails. A problem is beginning to persist that if I send a mail fetching the html from a url on the web there may exist some javascript in the document.

I want to clean up this html document even more by stripping out all javascript, embedded, referenced and in any form so that the mail exist only of html.

I want to use php's preg_replace() to strip out all javascript from a mail and I need some help with the best regex because it's not my strongest point i must confess.

答: Look at Create a regex to strip javascript from Html article. And Part 2.</p>


问:
How to create or set a variable inside Direct Database Request (DDR) filter query?
I am unable to use a Direct Database Request (DDR) as a filter query.
The requirement is to filter postal codes in my main subject area-based query using a DDR-based query which performs a REGEXP function, explained below.

Is there any way to define or set the value of a presentation or request variable inside my filter query?

What other approaches could I try?
The REGEXP function is not function-shippable to the RPD via EVALUATE() in an OBIEE analysis, due to being not supported in my NQSConfig.INI file.
And, this is an Oracle Sales Cloud instance, so I do not have access to modify my NQSConfig.INI file.

What I've tried so far:

I've created a DDR in OBIEE using the Connection Pool defined in my RPD.

This query retrieves all postal codes that are non-numeric:

SELECT
hz_parties.party_id,
hz_parties.postal_code
FROM
HZ_PARTIES
where
REGEXP_INSTR(Substr(HZ_PARTIES.POSTAL_CODE,0,2), '[0-9]{2}') = 0

This works.

But I have an OBIEE subject-area based analysis which needs a filter using operator is based on results of another analysis, using the DDR and matches against its party_id column.

This is the generated error and SQL of my main OBIEE analysis:

Error Details
Error Codes: YQCO4T56:OPR4ONWY:U9IM8TAC:OI2DL65P
Location: saw.views.evc.activate, saw.httpserver.processrequest, saw.rpc.server.responder, saw.rpc.server, saw.rpc.server.handleConnection, saw.rpc.server.dispatch, saw.threadpool.socketrpcserver, saw.threads
Odbc driver returned an error (SQLExecDirectW).
State: HY000. Code: 10058. [NQODBC] [SQL_STATE: HY000] [nQSError: 10058] A general error has occurred. [nQSError: 43113] Message returned from OBIS. [nQSError: 27047] Nonexistent table: "EXECUTE". (HY000)
SQL Issued: {call NQSGetLevelDrillability('SELECT "Contact"."Contact Row ID" saw_0 FROM "Sales - CRM Customers and Contacts Real Time" WHERE "Contact"."Contact Row ID" IN (SELECT saw_0 FROM (EXECUTE PHYSICAL CONNECTION POOL "CRM_OLTP"."Connection Pool" SELECT hz_parties.party_id, hz_parties.postal_code FROM HZ_PARTIES where REGEXP_INSTR(Substr(HZ_PARTIES.POSTAL_CODE,0,2), ''[0-9]{2}'') = 0 ) nqw_1 )')}

答: Seeing as you're in a cloud product I'd say this sounds like you should open an SR :)</p>


答:
An AUC < 0.5 suggests that your predictions are worse than random - basically you are predicting the reverse class. This is caused by this line:

```<code>score = nbprediction$posterior[, 1]
</code>```

which gives you the probability that an observation belongs to class 0. This score will be high for class 0, and ROCR expects high values to represent class 1. Use the second column of the posterior matrix instead:

```<code>score = nbprediction$posterior[, 2]
</code>```

Title: Plot a Naive Bayes Curve Using klaR and ROCR package

Body:
Here I have a classification task and I need to use klaR and ROCR packages.
The probelm is that the ROC Curve has a very low performance.

Here is my code:

    #install the klaR package for naiveBayes
    install.packages('klaR')
    library(klaR)
    library(ROCR)

    #create data set
    train<-read.table(file="train.txt",header=TRUE,sep=",")
    test<- read.table(file="test.txt",header=TRUE,sep=",")
    train$Type <- as.factor((train$Type))
    test$Type <- as.factor((test$Type))

    #build nb model and make predictions
    nb <- NaiveBayes(Type ~ ., data = train)
    nbprediction = predict(nb, test, type='raw')

    #Plot Roc Curve
    score = nbprediction$posterior[, 1]
    actual.class = test$Type
    pred = prediction(score, actual.class)
    nb.prff = performance(pred, "tpr", "fpr")
    plot(nb.prff)

The ROC Curve I plotted:

The dataset looks like (only training dataset here):

    Area,Perimeter,Compactness,Length,Width,Asymmetry,Groove,Type
    14.8,14.52,0.8823,5.656,3.288,3.112,5.309,1
    14.79,14.52,0.8819,5.545,3.291,2.704,5.111,1
    14.99,14.56,0.8883,5.57,3.377,2.958,5.175,1
    19.14,16.61,0.8722,6.259,3.737,6.682,6.053,0
    15.69,14.75,0.9058,5.527,3.514,1.599,5.046,1
    14.11,14.26,0.8722,5.52,3.168,2.688,5.219,1
    13.16,13.55,0.9009,5.138,3.201,2.461,4.783,1
    16.16,15.33,0.8644,5.845,3.395,4.266,5.795,0
    15.01,14.76,0.8657,5.789,3.245,1.791,5.001,1
    14.11,14.1,0.8911,5.42,3.302,2.7,5,1
    17.98,15.85,0.8993,5.979,3.687,2.257,5.919,0
    21.18,17.21,0.8989,6.573,4.033,5.78,6.231,0
    14.29,14.09,0.905,5.291,3.337,2.699,4.825,1
    14.59,14.28,0.8993,5.351,3.333,4.185,4.781,1
    11.42,12.86,0.8683,5.008,2.85,2.7,4.607,1
    12.11,13.47,0.8392,5.159,3.032,1.502,4.519,1
    15.6,15.11,0.858,5.832,3.286,2.725,5.752,0
    15.38,14.66,0.899,5.477,3.465,3.6,5.439,0
    18.94,16.49,0.875,6.445,3.639,5.064,6.362,0
    12.36,13.19,0.8923,5.076,3.042,3.22,4.605,1
    14.01,14.29,0.8625,5.609,3.158,2.217,5.132,1
    17.12,15.55,0.8892,5.85,3.566,2.858,5.746,0
    15.78,14.91,0.8923,5.674,3.434,5.593,5.136,1
    16.19,15.16,0.8849,5.833,3.421,0.903,5.307,1
    14.43,14.4,0.8751,5.585,3.272,3.975,5.144,1
    13.8,14.04,0.8794,5.376,3.155,1.56,4.961,1
    14.46,14.35,0.8818,5.388,3.377,2.802,5.044,1
    18.59,16.05,0.9066,6.037,3.86,6.001,5.877,0
    18.75,16.18,0.8999,6.111,3.869,4.188,5.992,0
    15.49,14.94,0.8724,5.757,3.371,3.412,5.228,1
    12.73,13.75,0.8458,5.412,2.882,3.533,5.067,1
    13.5,13.85,0.8852,5.351,3.158,2.249,5.176,1
    14.38,14.21,0.8951,5.386,3.312,2.462,4.956,1
    14.86,14.67,0.8676,5.678,3.258,2.129,5.351,1
    18.45,16.12,0.8921,6.107,3.769,2.235,5.794,0
    17.32,15.91,0.8599,6.064,3.403,3.824,5.922,0
    20.2,16.89,0.8894,6.285,3.864,5.173,6.187,0
    20.03,16.9,0.8811,6.493,3.857,3.063,6.32,0
    18.14,16.12,0.8772,6.059,3.563,3.619,6.011,0
    13.99,13.83,0.9183,5.119,3.383,5.234,4.781,1
    15.57,15.15,0.8527,5.92,3.231,2.64,5.879,0
    16.2,15.27,0.8734,5.826,3.464,2.823,5.527,1
    20.97,17.25,0.8859,6.563,3.991,4.677,6.316,0
    14.16,14.4,0.8584,5.658,3.129,3.072,5.176,1
    13.45,14.02,0.8604,5.516,3.065,3.531,5.097,1
    15.5,14.86,0.882,5.877,3.396,4.711,5.528,1
    16.77,15.62,0.8638,5.927,3.438,4.92,5.795,0
    12.74,13.67,0.8564,5.395,2.956,2.504,4.869,1
    14.88,14.57,0.8811,5.554,3.333,1.018,4.956,1
    14.28,14.17,0.8944,5.397,3.298,6.685,5.001,1
    14.34,14.37,0.8726,5.63,3.19,1.313,5.15,1
    14.03,14.16,0.8796,5.438,3.201,1.717,5.001,1
    19.11,16.26,0.9081,6.154,3.93,2.936,6.079,0
    14.52,14.6,0.8557,5.741,3.113,1.481,5.487,1
    18.43,15.97,0.9077,5.98,3.771,2.984,5.905,0
    18.81,16.29,0.8906,6.272,3.693,3.237,6.053,0
    13.78,14.06,0.8759,5.479,3.156,3.136,4.872,1
    14.69,14.49,0.8799,5.563,3.259,3.586,5.219,1
    18.85,16.17,0.9056,6.152,3.806,2.843,6.2,0
    12.88,13.5,0.8879,5.139,3.119,2.352,4.607,1
    12.78,13.57,0.8716,5.262,3.026,1.176,4.782,1
    14.33,14.28,0.8831,5.504,3.199,3.328,5.224,1
    19.46,16.5,0.8985,6.113,3.892,4.308,6.009,0
    19.38,16.72,0.8716,6.303,3.791,3.678,5.965,0
    15.26,14.85,0.8696,5.714,3.242,4.543,5.314,1
    20.24,16.91,0.8897,6.315,3.962,5.901,6.188,0
    19.94,16.92,0.8752,6.675,3.763,3.252,6.55,0
    20.71,17.23,0.8763,6.579,3.814,4.451,6.451,0
    16.17,15.38,0.8588,5.762,3.387,4.286,5.703,0
    13.02,13.76,0.8641,5.395,3.026,3.373,4.825,1
    16.53,15.34,0.8823,5.875,3.467,5.532,5.88,0
    13.89,14.02,0.888,5.439,3.199,3.986,4.738,1
    18.98,16.57,0.8687,6.449,3.552,2.144,6.453,0
    17.08,15.38,0.9079,5.832,3.683,2.956,5.484,1
    15.03,14.77,0.8658,5.702,3.212,1.933,5.439,1
    16.14,14.99,0.9034,5.658,3.562,1.355,5.175,1
    18.65,16.41,0.8698,6.285,3.594,4.391,6.102,0
    20.1,16.99,0.8746,6.581,3.785,1.955,6.449,0
    17.99,15.86,0.8992,5.89,3.694,2.068,5.837,0
    15.88,14.9,0.8988,5.618,3.507,0.7651,5.091,1
    13.22,13.84,0.868,5.395,3.07,4.157,5.088,1
    18.3,15.89,0.9108,5.979,3.755,2.837,5.962,0
    19.51,16.71,0.878,6.366,3.801,2.962,6.185,0

Body:
An AUC < 0.5 suggests that your predictions are worse than random - basically you are predicting the reverse class. This is caused by this line:

score = nbprediction$posterior[, 1]

which gives you the probability that an observation belongs to class 0. This score will be high for class 0, and ROCR expects high values to represent class 1. Use the second column of the posterior matrix instead:

score = nbprediction$posterior[, 2]


问:
create new field based on multiple resident tables
Given multiple in-resident tables, I'd like to create a new field based on fields in different tables.

```<code>table1:
LOAD * INLINE [
id1,val1
a1,car1
a2,car1
];

table2:
LOAD * INLINE [
id2,id1,val2
b1,a1,type1
b2,a2,type2
];

table3:
LOAD * INLINE [
id3,id2,val3
c1,b1,mfr1
c2,b2,mfr2
];
</code>```

For the sake of argument, assume table1 has ~1M rows, table2 ~1K rows, and table3 ~10 rows. I'd like to create a new field that is either added to table1 or perhaps in a new table linked by id1, resulting in:

```<code>id1  val1  newval
a1   car1  car1type1mfr1
a2   car2  car2type2mfr2
</code>```

Efforts:

```<code>newtable:
load val1 & val2 & val3 as newval;
</code>```

No errors but no newtable or newval.

```<code>newtable:
left join (table2)
load val1&val2 as newval resident table1;
</code>```

Errs with Field not found - <val2>. (Obviously I want to extend this to include table3, but if I can't do it with 2 tables then 3 just won't work.

The real data includes seven tables for this new field (lots of foreign keys). The data is being loaded from QVDs (the data is shared across multiple QVWs), closely mimicking a SQL database; none of the tables are row-wise redundant, so combining db tables into a single QVD table may be inefficient. (Plus refreshing the data is incredibly easier one table at a time.) A colleague suggested I load-join each of the QVDs into one huge table, but that doesn't seem right (nor have I successfully chain-joined even a few tables).

Using QV 12.0 desktop on win10-x64 for deployment on QVS.

答:
Your join is the wrong way round and QlikView can only work results after they have been joined,not in process, so you will have to do another resident load to get the values concatenated into Newval. The drop table commands are important or you will end up with massive unintentional syn tables</p>

```<code>newtable:
left join (table1)
load * resident table2; drop table 2;

Resulttable:
load id1,
val1&val2 as NewVal
resident newtable; drop newtable;
</code>```

Body:
Given multiple in-resident tables, I'd like to create a new field based on fields in different tables.

table1:
LOAD * INLINE [
id1,val1
a1,car1
a2,car1
];

table2:
LOAD * INLINE [
id2,id1,val2
b1,a1,type1
b2,a2,type2
];

table3:
LOAD * INLINE [
id3,id2,val3
c1,b1,mfr1
c2,b2,mfr2
];

For the sake of argument, assume table1 has ~1M rows, table2 ~1K rows, and table3 ~10 rows. I'd like to create a new field that is either added to table1 or perhaps in a new table linked by id1, resulting in:

id1  val1  newval
a1   car1  car1type1mfr1
a2   car2  car2type2mfr2

Efforts:

newtable:
load val1 & val2 & val3 as newval;

No errors but no newtable or newval.

newtable:
left join (table2)
load val1&val2 as newval resident table1;

Errs with Field not found - <val2>. (Obviously I want to extend this to include table3, but if I can't do it with 2 tables then 3 just won't work.

The real data includes seven tables for this new field (lots of foreign keys). The data is being loaded from QVDs (the data is shared across multiple QVWs), closely mimicking a SQL database; none of the tables are row-wise redundant, so combining db tables into a single QVD table may be inefficient. (Plus refreshing the data is incredibly easier one table at a time.) A colleague suggested I load-join each of the QVDs into one huge table, but that doesn't seem right (nor have I successfully chain-joined even a few tables).

Using QV 12.0 desktop on win10-x64 for deployment on QVS.

Body:
Your join is the wrong way round and QlikView can only work results after they have been joined,not in process, so you will have to do another resident load to get the values concatenated into Newval. The drop table commands are important or you will end up with massive unintentional syn tables

newtable:
left join (table1)
load * resident table2; drop table 2;

Resulttable:
load id1,
val1&val2 as NewVal
resident newtable; drop newtable;


问:
GitHub Login and Enterprise URL issue
i used to connect to GIt from GIT win apps. now when i try connect it is asking to enter Enterprise URL. i really do not know what is Enterprise URL. so tell me what to enter for Enterprise URL. here is my screen shot.

答:
A small hint:

Don't forget to add 'https://', else it is possible it does not recognize it as a valid Enterprise URL.

Title: GitHub Login and Enterprise URL issue


问:
How can I find words in matrix of letters
This is another question I was asked in the telephonic interview:

Given a dictionary and a crossword(2d matrix of characters) find all the dictionary words which can be found in the crossword.

All I could think of was hash the dictionary, find every possible word in the crossword and search the hash. I could not optimize it all.

Must admit Microsoft interview questions are tough :(

Please give me the lines to think on.

答:
Suppose the dictionary contains n words of average length k, and the matrix contains m² characters.

Preprocess the dictionary into a prefix tree (aka trie). — O(kn)

For each position in the matrix, look up the strings across and down in the trie. — O(m³)

Total time: O(max(kn, m³))

In realistic word-searches, the average length of words found in the matrix is more like k than like m, so the time taken would be O(k max(n, m²)).


问:
How to pass sqlite db values to controller
Newbie in sqlite, web2py. Am trying to copy sqlite db contents to controller for another function.
My codes are these:
db.py

```<code>auth.define_tables(username=False, signature=False)

auth.settings.registration_requires_verification = False
auth.settings.registration_requires_approval = False
auth.settings.reset_password_requires_verification = True

db.define_table('chat',
        Field('me_from'),
        Field('me_body', 'text'),
</code>```

default:

```<code>@auth.requires_login()
def index():
    chats.index(db)
    body = db.chat.me_body()
    rows = db(db.chat.me_body).select()#(orderby=~db.chat.me_body.created_on)
    form1 = [body]
    form5 = form1#.split()
    name3 = ' '.join(form5)
</code>```

I want t retrieve a string posted to db..

```<code>    chat.id chat.me_from    chat.me_body    chat.me_html
1
2       maurice         hi              <div class="m...
3       maurice         whats up        <div class="m...
4       maurice         where are you.  <div class="m...
5       maurice         3i5ejp[eoityjdt <div class="m...
6       maurice         how are you d...<div class="m...
7       maurice         britam          <div class="m...
</code>```

From the table above, i want to retrieve from chat.me_body the posted words such as, 'hi', 'whats up', 'britam'... to default function. I instead keep getting the following errors:
If I use:
 body = db.chat.me_body()
the error is:

```<code>TypeError: 'Field' object is not callable
</code>```

If I use:

```<code>`body = db.chat.me_body
</code>```

The error is:

```<code>TypeError: sequence item 0: expected string, Field found
</code>```

If I use rows:

```<code>rows = db(db.chat.me_body).select()
</code>```

and

```<code>form1 = [rows]
</code>```

the error is:

```<code>name3 = ' '.join(form5)
TypeError: sequence item 0: expected string, Rows found
</code>```

I I'll appreciate your help

答:
The proper way to do a query to get records from the database is:

```<code>rows = db(db.chat).select(db.chat.me_body, db.chat.created_on,
                          orderby=~db.chat.created_on)
</code>```

Note, db(db.chat) is shorthand for the query db(db.chat.id != None) (i.e., selection of all records in the table).

Then, to extract just the me_body field values into a list, you can use a list comprehension:

```<code>me_body_values = [r.me_body for r in rows]
</code>```

Finally, you can join those values together:

```<code>name3 = ' '.join(me_body_values)
</code>```

Body:
Newbie in sqlite, web2py. Am trying to copy sqlite db contents to controller for another function.
My codes are these:
db.py

auth.define_tables(username=False, signature=False)

auth.settings.registration_requires_verification = False
auth.settings.registration_requires_approval = False
auth.settings.reset_password_requires_verification = True

db.define_table('chat',
        Field('me_from'),
        Field('me_body', 'text'),

default:

@auth.requires_login()
def index():
    chats.index(db)
    body = db.chat.me_body()
    rows = db(db.chat.me_body).select()#(orderby=~db.chat.me_body.created_on)
    form1 = [body]
    form5 = form1#.split()
    name3 = ' '.join(form5)

I want t retrieve a string posted to db..

    chat.id chat.me_from    chat.me_body    chat.me_html
1
2       maurice         hi              <div class="m...
3       maurice         whats up        <div class="m...
4       maurice         where are you.  <div class="m...
5       maurice         3i5ejp[eoityjdt <div class="m...
6       maurice         how are you d...<div class="m...
7       maurice         britam          <div class="m...

From the table above, i want to retrieve from chat.me_body the posted words such as, 'hi', 'whats up', 'britam'... to default function. I instead keep getting the following errors:
If I use:
 body = db.chat.me_body()
the error is:

TypeError: 'Field' object is not callable

If I use:

`body = db.chat.me_body

The error is:

TypeError: sequence item 0: expected string, Field found

If I use rows:

rows = db(db.chat.me_body).select()

and

form1 = [rows]

the error is:

name3 = ' '.join(form5)
TypeError: sequence item 0: expected string, Rows found

I I'll appreciate your help

Body:
The proper way to do a query to get records from the database is:

rows = db(db.chat).select(db.chat.me_body, db.chat.created_on,
                          orderby=~db.chat.created_on)

Note, db(db.chat) is shorthand for the query db(db.chat.id != None) (i.e., selection of all records in the table).

Then, to extract just the me_body field values into a list, you can use a list comprehension:

me_body_values = [r.me_body for r in rows]

Finally, you can join those values together:

name3 = ' '.join(me_body_values)


问:
XSL number() cannot preserve decimals
I have below XSL value-of tag in my XSL file which is trying to add huge numbers, but I need to preserve 3 decimal points, will number function be able to handle the decimal percision?  Currently its not.

<xsl:value-of select="xx:set_variable($_XDOCTX, 'v6t1', number(xx:get_variable($_xx, 'v6t1')) + number(xx:normalize_string($_xx, (.//.)[1])))"/>
```

答:
The number() function converts strings to IEEE double-precision floating point values, which retain about 16 decimal digits of accuracy. This is consistent with the rounding error you are seeing.

XSLT 2.0 offers a decimal data type which will typically maintain greater accuracy than this.

Title: XSL number() cannot preserve decimals


问:
How to decode MJPEG frame into JPEG
I'm writing an iOS app to fetch motion jpeg stream via a tcp connection as in-memory data.

but the frame couldn't just save as a jpg file.

From what I googled, it seems like MJPEG frame doesn't have DHT like JPEG does,

but how to generate a DHT and put it into a mjpeg frame.

I also found few third-party libs like libjpeg-turbo, ffmpeg may accomplish that.

But most of the examples only show how to do it simply give an URL not in-memory data.

If you've done this in C/Objective-C before, hope you can tell me.

In the meantime, I'll keep searching for the answer.

and thanks for your time!

UPDATE:

Now I'm using DFJPEGTurbo and replace its libjpeg-turbo with the latest version.

It's easy to re-wrap mjpeg frame to a UIImage object.

It's the best way I've found, don't know if there's a better way.

and how can I do "ffmpeg -i {MJPEG_FILE} outputframe%d.jpg" programmatically?

答:
I've already found the answer, which is quite easy to use.

Whomever need it, here it is :

JPEGFixer

Title: How to decode MJPEG frame into JPEG


问:
Equivalent of 'in' for comparing two Numpy arrays
In pure, unvectorised, Python I can use,

```<code>>>> a = 9
>>> b = [5, 7, 12]
>>> a in b
False
</code>```

I would like to do something similar for arrays in Numpy i.e.

```<code>>>> a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
>>> b = np.array([5, 7, 12])
>>> a in b
np.array([False, False, False, False, True, False, True, False, False, False])</code>```

... although this does not work.

Is there a function or method that achieves this? If not what is the easiest way to do this?

答:
You may want to implement some sort of string searching algorithms if you are going to test whether one sequence contains another sequence.
Reference from Wikipedia</p>

Body:
In pure, unvectorised, Python I can use,

>>> a = 9
>>> b = [5, 7, 12]
>>> a in b
False

I would like to do something similar for arrays in Numpy i.e.

>>> a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
>>> b = np.array([5, 7, 12])
>>> a in b
np.array([False, False, False, False, True, False, True, False, False, False])

... although this does not work.

Is there a function or method that achieves this? If not what is the easiest way to do this?


问:
Bash: Check if a string looks like a three part version number using a regular expression
I need bash to check whether CI_COMMIT_REF_NAME matches either the string master, or a three part version number like 1.3.5, 1.1.11 and so on.

Here's what I tried:

```<code>#!/bin/bash
CI_COMMIT_REF_NAME=1.1.4
if [ $CI_COMMIT_REF_NAME == 'master' ] || [[ $CI_COMMIT_REF_NAME =~ ^([0-9]{1,2}\.){2}[0-9]{1,2}$ ]]
 then
     echo "true"
 else
     echo "false"
fi
</code>```

The expected output is true, but I get false. Setting the variable to master works as intended, so the mistake must be my regex.

What am I doing wrong?

答:
You probably don't want to match the beginning of the line twice:</p>

```<code>$ CI_COMMIT_REF_NAME=1.1.4
$ [[ $CI_COMMIT_REF_NAME =~ (^[0-9]{1,2}\.){2}[0-9]{1,2}$ ]] && echo match
$ [[ $CI_COMMIT_REF_NAME =~ ^([0-9]{1,2}\.){2}[0-9]{1,2}$ ]] && echo match
match
</code>```

Body:
I need bash to check whether CI_COMMIT_REF_NAME matches either the string master, or a three part version number like 1.3.5, 1.1.11 and so on.

Here's what I tried:

#!/bin/bash
CI_COMMIT_REF_NAME=1.1.4
if [ $CI_COMMIT_REF_NAME == 'master' ] || [[ $CI_COMMIT_REF_NAME =~ ^([0-9]{1,2}\.){2}[0-9]{1,2}$ ]]
 then
     echo "true"
 else
     echo "false"
fi

The expected output is true, but I get false. Setting the variable to master works as intended, so the mistake must be my regex.

What am I doing wrong?

Body:
You probably don't want to match the beginning of the line twice:

$ CI_COMMIT_REF_NAME=1.1.4
$ [[ $CI_COMMIT_REF_NAME =~ (^[0-9]{1,2}\.){2}[0-9]{1,2}$ ]] && echo match
$ [[ $CI_COMMIT_REF_NAME =~ ^([0-9]{1,2}\.){2}[0-9]{1,2}$ ]] && echo match
match


问:
Why is the ternary operator used to define 1 and 0 in a macro?
I'm using an SDK for an embedded project. In this source code I found some code which at least I found peculiar. In many places in the SDK there is source code in this format:

```<code>#define ATCI_IS_LOWER( alpha_char )  ( ( (alpha_char >= ATCI_char_a) && (alpha_char <= ATCI_char_z) ) ? 1 : 0 )

#define ATCI_IS_UPPER( alpha_char )  ( ( (alpha_char >= ATCI_CHAR_A) && (alpha_char <= ATCI_CHAR_Z) ) ? 1 : 0 )
</code>```

Does the use of the ternary operator here make any difference?

Isn't

```<code>#define FOO (1 > 0)
</code>```

the same as

```<code>#define BAR ( (1 > 0) ? 1 : 0)
</code>```

?

I tried evaluating it by using

```<code>printf("%d", FOO == BAR);
</code>```

and get the result 1, so it seems that they are equal. Is there a reason to write the code like they did?

答:
One simple explanation is that some people either don't understand that a condition would return the same value in C, or they think that it is cleaner to write ((a>b)?1:0).

That explains why some also use similar constructs in languages with proper booleans, which in C-syntax would be (a>b)?true:false).

This also explains why you shouldn't needlessly change this macro.

Body:
I'm using an SDK for an embedded project. In this source code I found some code which at least I found peculiar. In many places in the SDK there is source code in this format:

#define ATCI_IS_LOWER( alpha_char )  ( ( (alpha_char >= ATCI_char_a) && (alpha_char <= ATCI_char_z) ) ? 1 : 0 )

#define ATCI_IS_UPPER( alpha_char )  ( ( (alpha_char >= ATCI_CHAR_A) && (alpha_char <= ATCI_CHAR_Z) ) ? 1 : 0 )

Does the use of the ternary operator here make any difference?

Isn't

#define FOO (1 > 0)

the same as

#define BAR ( (1 > 0) ? 1 : 0)

?

I tried evaluating it by using

printf("%d", FOO == BAR);

and get the result 1, so it seems that they are equal. Is there a reason to write the code like they did?


问:
F#, implement fold3, fold4, fold_n
I am interested to implement fold3, fold4 etc., similar to List.fold and List.fold2. e.g.

```<code>// TESTCASE
let polynomial (x:double) a b c = a*x + b*x*x + c*x*x*x
let A = [2.0; 3.0; 4.0; 5.0]
let B = [1.5; 1.0; 0.5; 0.2]
let C = [0.8; 0.01; 0.001; 0.0001]

let result = fold3 polynomial 0.7 A B C
// 2.0 * (0.7   ) + 1.5 * (0.7   )^2 + 0.8    * (0.7   )^3 -> 2.4094
// 3.0 * (2.4094) + 1.0 * (2.4094)^2 + 0.01   * (2.4094)^3 -> 13.173
// 4.0 * (13.173) + 0.5 * (13.173)^2 + 0.001  * (13.173)^3 -> 141.75
// 5.0 * (141.75) + 0.2 * (141.75)^2 + 0.0001 * (141.75)^3 -> 5011.964
//
// Output: result = 5011.964
</code>```

My first method is grouping the 3 lists A, B, C, into a list of tuples, and then apply list.fold

```<code>let fold3 f x A B C =
    List.map3 (fun a b c -> (a,b,c)) A B C
       |> List.fold (fun acc (a,b,c) -> f acc a b c) x

// e.g. creates [(2.0,1.5,0.8);  (3.0,1.0,0.01); ......]
</code>```

My second method is to declare a mutable data, and use List.map3

```<code>let mutable result = 0.7
List.map3 (fun a b c ->
               result <- polynomial result a b c  // Change mutable data
               // Output intermediate data
               result) A B C
// Output from List.map3: [2.4094; 13.17327905; 141.7467853; 5011.963942]
// result mutable: 5011.963942
</code>```

I would like to know if there are other ways to solve this problem. Thank you.

答:
There are many ways to solve this problem. Few are mentioned like first zip3 all three list, then run over it. Using Applicate Functors like Fyodor Soikin describes means you can turn any function with any amount of arguments into a function that expects list instead of single arguments. This is a good general solution that works with any numbers of lists.

While this is a general good idea, i'm sometimes shocked that so few use more low-level tools. In this case it is a good idea to use recursion and learn more about recursion.

Recursion here is the right-tool because we have immutable data-types. But you could consider how you would implement it with mutable lists and looping first, if that helps. The steps would be:

You loop over an index from 0 to the amount of elements in the lists.

You check if every list has an element for the index

If every list has an element then you pass this to your "folder" function

If at least one list don't have an element, then you abort the loop

The recursive version works exactly the same. Only that you don't use an index to access the elements. You would chop of the first element from every list and then recurse on the remaining list.

Otherwise List.isEmpty is the function to check if a List is empty. You can chop off the first element with List.head and you get the remaining list with the first element removed by List.tail. This way you can just write:

```<code>let rec fold3 f acc l1 l2 l3 =
    let h = List.head
    let t = List.tail
    let empty = List.isEmpty

    if   (empty l1) || (empty l2) && (empty l3)
    then acc
    else fold3 f (f acc (h l1) (h l2) (h l3)) (t l1) (t l2) (t l3)
</code>```

The if line checks if every list has at least one element. If that is true
it executes: f acc (h l1) (h l2) (h l3). So it executes f and passes it the first element of every list as an argument. The result is the new accumulator of
the next fold3 call.

Now that you worked on the first element of every list, you must chop off the first element of every list, and continue with the remaining lists. You achieve that with List.tail or in the above example (t l1) (t l2) (t l3). Those are the next remaining lists for the next fold3 call.

Creating a fold4, fold5, fold6 and so on isn't really hard, and I think it is self-explanatory. My general advice is to learn a little bit more about recursion and try to write recursive List functions without Pattern Matching. Pattern Matching is not always easier.

Some code examples:

```<code>fold3 (fun acc x y z -> x + y + z :: acc)   [] [1;2;3] [10;20;30] [100;200;300] // [333;222;111]
fold3 (fun acc x y z -> x :: y :: z :: acc) [] [1;2;3] [10;20;30] [100;200;300] // [3; 30; 300; 2; 20; 200; 1; 10; 100]
</code>```

Title: F#, implement fold3, fold4, fold_n

Body:
I am interested to implement fold3, fold4 etc., similar to List.fold and List.fold2. e.g.

// TESTCASE
let polynomial (x:double) a b c = a*x + b*x*x + c*x*x*x
let A = [2.0; 3.0; 4.0; 5.0]
let B = [1.5; 1.0; 0.5; 0.2]
let C = [0.8; 0.01; 0.001; 0.0001]

let result = fold3 polynomial 0.7 A B C
// 2.0 * (0.7   ) + 1.5 * (0.7   )^2 + 0.8    * (0.7   )^3 -> 2.4094
// 3.0 * (2.4094) + 1.0 * (2.4094)^2 + 0.01   * (2.4094)^3 -> 13.173
// 4.0 * (13.173) + 0.5 * (13.173)^2 + 0.001  * (13.173)^3 -> 141.75
// 5.0 * (141.75) + 0.2 * (141.75)^2 + 0.0001 * (141.75)^3 -> 5011.964
//
// Output: result = 5011.964

My first method is grouping the 3 lists A, B, C, into a list of tuples, and then apply list.fold

let fold3 f x A B C =
    List.map3 (fun a b c -> (a,b,c)) A B C
       |> List.fold (fun acc (a,b,c) -> f acc a b c) x

// e.g. creates [(2.0,1.5,0.8);  (3.0,1.0,0.01); ......]

My second method is to declare a mutable data, and use List.map3

let mutable result = 0.7
List.map3 (fun a b c ->
               result <- polynomial result a b c  // Change mutable data
               // Output intermediate data
               result) A B C
// Output from List.map3: [2.4094; 13.17327905; 141.7467853; 5011.963942]
// result mutable: 5011.963942

I would like to know if there are other ways to solve this problem. Thank you.

Body:
There are many ways to solve this problem. Few are mentioned like first zip3 all three list, then run over it. Using Applicate Functors like Fyodor Soikin describes means you can turn any function with any amount of arguments into a function that expects list instead of single arguments. This is a good general solution that works with any numbers of lists.

While this is a general good idea, i'm sometimes shocked that so few use more low-level tools. In this case it is a good idea to use recursion and learn more about recursion.

Recursion here is the right-tool because we have immutable data-types. But you could consider how you would implement it with mutable lists and looping first, if that helps. The steps would be:

You loop over an index from 0 to the amount of elements in the lists.

You check if every list has an element for the index

If every list has an element then you pass this to your "folder" function

If at least one list don't have an element, then you abort the loop

The recursive version works exactly the same. Only that you don't use an index to access the elements. You would chop of the first element from every list and then recurse on the remaining list.

Otherwise List.isEmpty is the function to check if a List is empty. You can chop off the first element with List.head and you get the remaining list with the first element removed by List.tail. This way you can just write:

let rec fold3 f acc l1 l2 l3 =
    let h = List.head
    let t = List.tail
    let empty = List.isEmpty

    if   (empty l1) || (empty l2) && (empty l3)
    then acc
    else fold3 f (f acc (h l1) (h l2) (h l3)) (t l1) (t l2) (t l3)

The if line checks if every list has at least one element. If that is true
it executes: f acc (h l1) (h l2) (h l3). So it executes f and passes it the first element of every list as an argument. The result is the new accumulator of
the next fold3 call.

Now that you worked on the first element of every list, you must chop off the first element of every list, and continue with the remaining lists. You achieve that with List.tail or in the above example (t l1) (t l2) (t l3). Those are the next remaining lists for the next fold3 call.

Creating a fold4, fold5, fold6 and so on isn't really hard, and I think it is self-explanatory. My general advice is to learn a little bit more about recursion and try to write recursive List functions without Pattern Matching. Pattern Matching is not always easier.

Some code examples:

fold3 (fun acc x y z -> x + y + z :: acc)   [] [1;2;3] [10;20;30] [100;200;300] // [333;222;111]
fold3 (fun acc x y z -> x :: y :: z :: acc) [] [1;2;3] [10;20;30] [100;200;300] // [3; 30; 300; 2; 20; 200; 1; 10; 100]


问:
PLSQL - Creating procedure with parameter, but only allowing 2 values
First off, I'm a DBA that dabbles in PL/SQL Programming.  I have some knowledge, but some is most certainly lacking.

```<code>CREATE OR REPLACE PROCEDURE TRIGGER_PRC (P_TRGNAME IN VARCHAR2, P_STATUS IN VARCHAR2)
AS ....
</code>```

I'd like to allow the P_STATUS parameter only be allowed values of 'E' or 'D' for enabling or disabling a trigger.  I've done some searching, but can't seem to find the solution for this.  Any help is greatly appreciated!

Thanks!

Jeremy

答:
A solution would also be to use a Boolean, since you have only two choices.

```<code>CREATE OR REPLACE PROCEDURE TRIGGER_PRC (P_TRGNAME IN VARCHAR2, P_STATUS IN BOOLEAN)
AS ....
</code>```

From this interesting article, it is advise to create a separate function to validate your input if you want some kind of ENUM in PLSQL (externalize the if GurV suggests).

So what is a guy to do?

If you want to use enum in a table, use a check constraint.

If you want to use enum in a stored procedure, write a separate procedure to validate the input.

What you could also do, if more than 2 values:
If you can afford to store global variables in a package and also advise your developers to look for constants in a defined package (GUI like PLSQL Developer or alike make it very easy to use):

```<code>CREATE OR REPLACE PACKAGE global_vars IS
  P_STATUS_enable  CONSTANT varchar2(2) := 'E';
  P_STATUS_disable CONSTANT varchar2(2) := 'D';
  P_STATUS_drop    CONSTANT varchar2(2) := 'Dr';
end global_vars;
/

  create or replace procedure TRIGGER_PRC (P_TRGNAME IN VARCHAR2, P_STATUS IN varchar2)
  AS
  begin
    if P_STATUS = global_vars.P_STATUS_enable then
        -- do something
        dbms_output.put_line('ENABLE');
    elsif P_STATUS = global_vars.P_STATUS_disable then
      --  p_status = P_STATUS_disable
        dbms_output.put_line('DISABLE');
    elsif P_STATUS = global_vars.P_STATUS_drop then
      -- do other stuff
        dbms_output.put_line('DROP?');
    end if;

  end TRIGGER_PRC;
/

begin
  TRIGGER_PRC ('TRIG', global_vars.P_STATUS_enable);
end;
/
</code>```

Body:
First off, I'm a DBA that dabbles in PL/SQL Programming.  I have some knowledge, but some is most certainly lacking.

CREATE OR REPLACE PROCEDURE TRIGGER_PRC (P_TRGNAME IN VARCHAR2, P_STATUS IN VARCHAR2)
AS ....

I'd like to allow the P_STATUS parameter only be allowed values of 'E' or 'D' for enabling or disabling a trigger.  I've done some searching, but can't seem to find the solution for this.  Any help is greatly appreciated!

Thanks!

Jeremy

Body:
A solution would also be to use a Boolean, since you have only two choices.

CREATE OR REPLACE PROCEDURE TRIGGER_PRC (P_TRGNAME IN VARCHAR2, P_STATUS IN BOOLEAN)
AS ....

From this interesting article, it is advise to create a separate function to validate your input if you want some kind of ENUM in PLSQL (externalize the if GurV suggests).

So what is a guy to do?

If you want to use enum in a table, use a check constraint.

If you want to use enum in a stored procedure, write a separate procedure to validate the input.

What you could also do, if more than 2 values:
If you can afford to store global variables in a package and also advise your developers to look for constants in a defined package (GUI like PLSQL Developer or alike make it very easy to use):

CREATE OR REPLACE PACKAGE global_vars IS
  P_STATUS_enable  CONSTANT varchar2(2) := 'E';
  P_STATUS_disable CONSTANT varchar2(2) := 'D';
  P_STATUS_drop    CONSTANT varchar2(2) := 'Dr';
end global_vars;
/

  create or replace procedure TRIGGER_PRC (P_TRGNAME IN VARCHAR2, P_STATUS IN varchar2)
  AS
  begin
    if P_STATUS = global_vars.P_STATUS_enable then
        -- do something
        dbms_output.put_line('ENABLE');
    elsif P_STATUS = global_vars.P_STATUS_disable then
      --  p_status = P_STATUS_disable
        dbms_output.put_line('DISABLE');
    elsif P_STATUS = global_vars.P_STATUS_drop then
      -- do other stuff
        dbms_output.put_line('DROP?');
    end if;

  end TRIGGER_PRC;
/

begin
  TRIGGER_PRC ('TRIG', global_vars.P_STATUS_enable);
end;
/


问:
Encoding AES output: Is there a standard way to add the IV to the cyphertext?
Are there any widely recognized standards around encoding the output of AES encryption?

More specifically, I'm looking for a standards based approach to encoding the IV with the cyphertext. i.e. is the IV pre-pended to the cyphertext byte array, appended, or stored seperatley. My end goal is to have a Base64 encoded string containing the IV and the cyphertext to allow for interoperability with other widely used AES libraries.

答:
A widely recognized method is to prepend the IV to the encrypted data, the IV does not need to be secret.  But there is no "standard", that implies specified by a standards body.

There is no "standard" and no method that has interoperability between implementations, it is still the "Wild West" on implementations.

One solution that is implemented for several languages/platforms: RNCryptor, it also includes key derivation, authentication and v versioning.


问:
Nginx Reverse proxy force https
We have a server setup for reverse proxy using nginx. This server will redirect visitors to the corresponding server in which path they are accessed. Now, I want to set up the nginx.conf to force redirect them to https. The problem is I am getting a "too many redirection" error. I tried using a rewrite and adding "proxy_set_header X-Forwarded-Proto https;" but none of it works. Is there a way we can achieve this?  We have set up a ssl cert on cloudflare so we won't need to add it on the config.

Below is the config setting of the current nginx.

```<code>   server {
    listen       80 default_server;
    listen       [::]:80 default_server;
    server_name  localhost;
    root         /usr/share/nginx/html;

   if ($http_x_forwarded_proto = "http") {
      rewrite  ^/(.*)$  https://development-link/$1 permanent;
   }

    # Load configuration files for the default server block.
    include /etc/nginx/default.d/*.conf;

    location / {
            proxy_set_header X-Real-IP  $remote_addr;
            proxy_set_header X-Forwarded-For $remote_addr;
            proxy_set_header Host $host;
            proxy_pass http://development-elb1;
            proxy_set_header X-Forwarded-Proto https;
    }

    location /en {
            proxy_set_header X-Real-IP  $remote_addr;
            proxy_set_header X-Forwarded-For $remote_addr;
            proxy_set_header Host $host;
            proxy_pass http://development-elb2;
            proxy_set_header    X-Forwarded-Proto https;
    }
</code>```

答:
So you are using cloudflare as your DNS.

There is a very easy hack to force the users to https even if you are using free version of cloudflare at the cloudflare end. And just host http version at your Nginx.

1- Open cloudflare and choose your domain.

2- Go to Page Rules tab.

3- Create page rule

4- for the url, put http://www.example.com/*

5- for setting, choose always use https

6- Click Save and deploy

Now you have configured at your cloudflare to force user to redirect to https url.

Title: Nginx Reverse proxy force https

Body:
We have a server setup for reverse proxy using nginx. This server will redirect visitors to the corresponding server in which path they are accessed. Now, I want to set up the nginx.conf to force redirect them to https. The problem is I am getting a "too many redirection" error. I tried using a rewrite and adding "proxy_set_header X-Forwarded-Proto https;" but none of it works. Is there a way we can achieve this?  We have set up a ssl cert on cloudflare so we won't need to add it on the config.

Below is the config setting of the current nginx.

   server {
    listen       80 default_server;
    listen       [::]:80 default_server;
    server_name  localhost;
    root         /usr/share/nginx/html;

   if ($http_x_forwarded_proto = "http") {
      rewrite  ^/(.*)$  https://development-link/$1 permanent;
   }

    # Load configuration files for the default server block.
    include /etc/nginx/default.d/*.conf;

    location / {
            proxy_set_header X-Real-IP  $remote_addr;
            proxy_set_header X-Forwarded-For $remote_addr;
            proxy_set_header Host $host;
            proxy_pass http://development-elb1;
            proxy_set_header X-Forwarded-Proto https;
    }

    location /en {
            proxy_set_header X-Real-IP  $remote_addr;
            proxy_set_header X-Forwarded-For $remote_addr;
            proxy_set_header Host $host;
            proxy_pass http://development-elb2;
            proxy_set_header    X-Forwarded-Proto https;
    }


问:
Get custom property set in Outlook Add-In via Microsoft Graph
Let's say I have in my Outlook Add-In (using Office.js) following code running on a compose form of an appointment:

const item = Office.context.mailbox.item;
item.loadCustomPropertiesAsync((result) => {
    const props = result.value;
    const testProp = props.get("my_prop");
    console.log("CUSTOM_PROP", testProp);
    props.set("my_prop", "test_value");
    props.saveAsync((saveResult) =>
        console.log("SAVE_CUSTOM_PROP", saveResult));
});
```

I see, that it actually is saved on the event.

And now a bunch of questions regarding those custom properties:

But are those somehow related to extended properties?

Are those properties somehow accessible through Outlook REST API or Microsoft Graph?

Can I create a push notifications subscription using Microsoft Graph with a filter based on those properties? (I know I can based on extended properties)

If the answer to above question is "no", and the custom properties are only accessible through the add-in which created them, is there a way to create a extended property to an event from the add-in, even if it's not saved?

To explain why I'm asking - I'm creating an add-in, which allows to "connect" an appointment with our 3rd party system, and keep that appointment in sync with our object.

So when a button is clicked on the compose form, I:

save the appointment and get the event-id,

store it in our system, to do the sync from our system to the appointment.

add an extended property in our system using Microsoft Graph for that appointment

In the first use of the add-in, the user authenticates, and I create a push notification subscription for events with our extended property, to do the sync from Outlook to our system.

It works great on OWA, but now as we really need to support desktop, two major issues are arising:

Outlook for Mac: no saveAsync method, thus no way to get the event's id, I was thinking about adding some custom property, and then let the push notification inform our system, that an event was created which needs to be synced with out system.

Outlook for PC: there is the saveAsync method, but the callback is executed when the appointment is saved locally, not on the server, thus I can't know when exactly the event has been created and I can do some Microsoft Graph calls on that event.

Answer to my first question, and/or any tips about my use case would be more than welcome.

答:
TL;DR;
Yes it is possible to read custom properties set by Office.js api loadCustomPropertiesAsync using REST APIs
You need to create a REST call query that looks like

```<code>string addinManifestId = "<your manifest guid here>";//lower cases
string prop = @"String {00020329-0000-0000-C000-000000000046} Name"+ string.Format(" cecp-{0}", addinManifestId );
var url = $"<apiEndpoint>/messages/<youritemid>?$expand=SingleValueExtendedProperties($filter=PropertyId eq '{propertyname}')";
</code>```

More info

The documentation is available here https://msdn.microsoft.com/en-us/library/hh968549(v=exchg.80).aspx

I had a similar problem when I needed to handle "sent mail" for my add-in Keluro.
I implemented something really close to your approach with a web hook on REST API. To my knowledge it is the only way to handle sent items.
Consider upvoting this
https://officespdev.uservoice.com/forums/224641-feature-requests-and-feedback/suggestions/10964871-add-itemsend-event-so-add-in-can-cancel-email

Body:
Let's say I have in my Outlook Add-In (using Office.js) following code running on a compose form of an appointment:

const item = Office.context.mailbox.item;
item.loadCustomPropertiesAsync((result) => {
    const props = result.value;
    const testProp = props.get("my_prop");
    console.log("CUSTOM_PROP", testProp);
    props.set("my_prop", "test_value");
    props.saveAsync((saveResult) =>
        console.log("SAVE_CUSTOM_PROP", saveResult));
});

I see, that it actually is saved on the event.

And now a bunch of questions regarding those custom properties:

But are those somehow related to extended properties?

Are those properties somehow accessible through Outlook REST API or Microsoft Graph?

Can I create a push notifications subscription using Microsoft Graph with a filter based on those properties? (I know I can based on extended properties)

If the answer to above question is "no", and the custom properties are only accessible through the add-in which created them, is there a way to create a extended property to an event from the add-in, even if it's not saved?

To explain why I'm asking - I'm creating an add-in, which allows to "connect" an appointment with our 3rd party system, and keep that appointment in sync with our object.

So when a button is clicked on the compose form, I:

save the appointment and get the event-id,

store it in our system, to do the sync from our system to the appointment.

add an extended property in our system using Microsoft Graph for that appointment

In the first use of the add-in, the user authenticates, and I create a push notification subscription for events with our extended property, to do the sync from Outlook to our system.

It works great on OWA, but now as we really need to support desktop, two major issues are arising:

Outlook for Mac: no saveAsync method, thus no way to get the event's id, I was thinking about adding some custom property, and then let the push notification inform our system, that an event was created which needs to be synced with out system.

Outlook for PC: there is the saveAsync method, but the callback is executed when the appointment is saved locally, not on the server, thus I can't know when exactly the event has been created and I can do some Microsoft Graph calls on that event.

Answer to my first question, and/or any tips about my use case would be more than welcome.

Body:
TL;DR;
Yes it is possible to read custom properties set by Office.js api loadCustomPropertiesAsync using REST APIs
You need to create a REST call query that looks like

string addinManifestId = "<your manifest guid here>";//lower cases
string prop = @"String {00020329-0000-0000-C000-000000000046} Name"+ string.Format(" cecp-{0}", addinManifestId );
var url = $"<apiEndpoint>/messages/<youritemid>?$expand=SingleValueExtendedProperties($filter=PropertyId eq '{propertyname}')";

More info

The documentation is available here https://msdn.microsoft.com/en-us/library/hh968549(v=exchg.80).aspx

I had a similar problem when I needed to handle "sent mail" for my add-in Keluro.
I implemented something really close to your approach with a web hook on REST API. To my knowledge it is the only way to handle sent items.
Consider upvoting this
https://officespdev.uservoice.com/forums/224641-feature-requests-and-feedback/suggestions/10964871-add-itemsend-event-so-add-in-can-cancel-email


问:
python pycparser setup error
I am seeing the following error while setting up pyparser on CentOS 7 via pip
```<code>
/usr/bin/python2 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-PMzCYU/pycparser/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-0bpBrX-record/install-record.txt --single-version-externally-managed --compile
Traceback (most recent call last):</p>

<p>File "", line 1, in init.py", line 12, in
    import setuptools.version
File "/usr/lib/python2.7/site-packages/setuptools/version.py", line 1, in
    import pkg_resources
  File "/usr/lib/python2.7/site-packages/pkg_resources/<strong>init</strong>.py", line 72, in
    import packaging.requirements
  File "/usr/lib/python2.7/site-packages/packaging/requirements.py", line 59, in
    MARKER_EXPR = originalTextFor(MARKER_EXPR())("marker")
TypeError: <strong>call</strong>() takes exactly 2 arguments (1 given)
```</code></p>

答:
same solution worked for me

pip install setuptools==33.1.1
and then sudo pip install -r requirements.txt

Title: python pycparser setup error

Body:
I am seeing the following error while setting up pyparser on CentOS 7 via pip

/usr/bin/python2 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-PMzCYU/pycparser/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-0bpBrX-record/install-record.txt --single-version-externally-managed --compile
Traceback (most recent call last):

File "", line 1, in init.py", line 12, in
    import setuptools.version
File "/usr/lib/python2.7/site-packages/setuptools/version.py", line 1, in
    import pkg_resources
  File "/usr/lib/python2.7/site-packages/pkg_resources/init.py", line 72, in
    import packaging.requirements
  File "/usr/lib/python2.7/site-packages/packaging/requirements.py", line 59, in
    MARKER_EXPR = originalTextFor(MARKER_EXPR())("marker")
TypeError: call() takes exactly 2 arguments (1 given)


问:
Python opencv and dicom files
while trying to use  opencv with a dicom monochrome file, i saw only one solution : first transform the monochrom  dicom file with pixel values between -2000( black) to 2000 (white)in RGB with
0<=R=G=B<=255. (To ensure grayscale, i have to set R=G=B)
So i made a linear interpolation to go
from first [-2000;2000] to [0, 255]. The results for my pictures were not good so i decided to put a black threeshlod under which all pixels are black and a white threeshol above which all pixels are white. Doing so, i could work with opencv but
1) I would like to automize the black thressholds and the white threesholds
2) since i have 512*512 pixels, the double for loop takes time to execute.

Do you have any idea how i could automize and speedup the process ? Or simply a good idea ?
the code is :

```<code>    # import the necessary packages
from imutils import contours
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import scipy
from skimage import measure
import numpy as np # numeric library needed
import pandas as pd #for dataframe
import argparse # simple argparser
import imutils
import cv2  # for opencv image recognising tool
import dicom
from tkinter import Tk
from tkinter.filedialog import askopenfilename
import pdb

#filename = askopenfilename() # show an "Open" dialog box and return the path to the selected file
#filename ="../inputs/12e0e2036f61c8a52ee4471bf813c36a/7e74cdbac4c6db70bade75225258119d.dcm"
dicom_file = dicom.read_file(filename) ## original dicom File
#### a dicom monochrome file has pixel value between approx -2000 and +2000, opencv doesn't work with it#####
#### in a first step we transform those pixel values in (R,G,B)
### to have gray in RGB, simply give the same values for R,G, and B,
####(0,0,0) will be black, (255,255,255) will be white,

## the threeshold to be automized with a proper quartile function of the pixel distribution
black_threeshold=0###pixel value below 0 will be black,
white_threeshold=1400###pixel value above 1400 will be white
wt=white_threeshold
bt=black_threeshold

###### function to transform a dicom to RGB for the use of opencv,
##to be strongly improved, as it takes to much time to run,
## and the linear process should be replaced with an adapted weighted arctan function.
def DicomtoRGB(dicomfile,bt,wt):
    """Create new image(numpy array) filled with certain color in RGB"""
    # Create black blank image
    image = np.zeros((dicomfile.Rows, dicomfile.Columns, 3), np.uint8)
    #loops on image height and width
    i=0
    j=0
    while i<dicomfile.Rows:
        j=0
        while j<dicomfile.Columns:
            color = yaxpb(dicom_file.pixel_array[i][j],bt,wt) #linear transformation to be adapted
            image[i][j] = (color,color,color)## same R,G, B value to obtain greyscale
            j=j+1
        i=i+1
    return image
##linear transformation : from [bt < pxvalue < wt] linear to [0<pyvalue<255]: loss of information...
def yaxpb(pxvalue,bt,wt):
    if pxvalue < bt:
        y=0
    elif pxvalue > wt:
        y=255
    else:
        y=pxvalue*255/(wt-bt)-255*bt/(wt-bt)
    return y

image=DicomtoRGB(dicom_file,bt=0,wt=1400)
>>image
array([[[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        ...,
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]],

       [[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        ...,
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]],

       [[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        ...,
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]],

       ...,
       [[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        ...,
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]],

       [[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        ...,
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]],

       [[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        ...,
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]]], dtype=uint8)

## loading the RGB in a proper opencv format
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
## look at the gray file
cv2.imshow("gray", gray)
cv2.waitKey(0)
cv2.destroyWindow("gray")
</code>```

答:
I think your problem come with this :

...  the double for loop takes time to execute.

You can use remap function from opencv:
See this example:

Title: Python opencv and dicom files

Body:
while trying to use  opencv with a dicom monochrome file, i saw only one solution : first transform the monochrom  dicom file with pixel values between -2000( black) to 2000 (white)in RGB with
0<=R=G=B<=255. (To ensure grayscale, i have to set R=G=B)
So i made a linear interpolation to go
from first [-2000;2000] to [0, 255]. The results for my pictures were not good so i decided to put a black threeshlod under which all pixels are black and a white threeshol above which all pixels are white. Doing so, i could work with opencv but
1) I would like to automize the black thressholds and the white threesholds
2) since i have 512*512 pixels, the double for loop takes time to execute.

Do you have any idea how i could automize and speedup the process ? Or simply a good idea ?
the code is :

    # import the necessary packages
from imutils import contours
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import scipy
from skimage import measure
import numpy as np # numeric library needed
import pandas as pd #for dataframe
import argparse # simple argparser
import imutils
import cv2  # for opencv image recognising tool
import dicom
from tkinter import Tk
from tkinter.filedialog import askopenfilename
import pdb

#filename = askopenfilename() # show an "Open" dialog box and return the path to the selected file
#filename ="../inputs/12e0e2036f61c8a52ee4471bf813c36a/7e74cdbac4c6db70bade75225258119d.dcm"
dicom_file = dicom.read_file(filename) ## original dicom File
#### a dicom monochrome file has pixel value between approx -2000 and +2000, opencv doesn't work with it#####
#### in a first step we transform those pixel values in (R,G,B)
### to have gray in RGB, simply give the same values for R,G, and B,
####(0,0,0) will be black, (255,255,255) will be white,

## the threeshold to be automized with a proper quartile function of the pixel distribution
black_threeshold=0###pixel value below 0 will be black,
white_threeshold=1400###pixel value above 1400 will be white
wt=white_threeshold
bt=black_threeshold

###### function to transform a dicom to RGB for the use of opencv,
##to be strongly improved, as it takes to much time to run,
## and the linear process should be replaced with an adapted weighted arctan function.
def DicomtoRGB(dicomfile,bt,wt):
    """Create new image(numpy array) filled with certain color in RGB"""
    # Create black blank image
    image = np.zeros((dicomfile.Rows, dicomfile.Columns, 3), np.uint8)
    #loops on image height and width
    i=0
    j=0
    while i<dicomfile.Rows:
        j=0
        while j<dicomfile.Columns:
            color = yaxpb(dicom_file.pixel_array[i][j],bt,wt) #linear transformation to be adapted
            image[i][j] = (color,color,color)## same R,G, B value to obtain greyscale
            j=j+1
        i=i+1
    return image
##linear transformation : from [bt < pxvalue < wt] linear to [0<pyvalue<255]: loss of information...
def yaxpb(pxvalue,bt,wt):
    if pxvalue < bt:
        y=0
    elif pxvalue > wt:
        y=255
    else:
        y=pxvalue*255/(wt-bt)-255*bt/(wt-bt)
    return y

image=DicomtoRGB(dicom_file,bt=0,wt=1400)
>>image
array([[[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        ...,
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]],

       [[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        ...,
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]],

       [[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        ...,
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]],

       ...,
       [[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        ...,
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]],

       [[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        ...,
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]],

       [[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        ...,
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]]], dtype=uint8)

## loading the RGB in a proper opencv format
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
## look at the gray file
cv2.imshow("gray", gray)
cv2.waitKey(0)
cv2.destroyWindow("gray")


问:
iPhone - Combining a Tab Bar with multiple navigation bars
I am trying to build an iPhone application that has a Tab bar as the root controller and several navigation bars. My doubt is, shall I create one NavigationBarController class for each navigation bar that I want to put in the application? Or is it possible to create only a single navigation controller that manages all the navigation bar controllers that exist in the application?

In the case that multiple navigation controllers exist in the application, can I use the "self" to access the correct navigation controller that pushes/pops the view? Or should I use the delegate of the Application delegate to access each navigation bar controllers?

(I am assuming that all navigation bar controllers are declared in the application delegate, is this approach correct or is there a more elegant approach?)

Thanks a lot in advance

答:
Watch out for possible leak in this part of the above code:

```<code>self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:tools];
</code>```

You could use this instead:

```<code>UIBarButtonItem* rightButtonBar = [[UIBarButtonItem alloc] initWithCustomView:tools];
self.navigationItem.rightBarButtonItem = rightButtonBar;
[rightButtonBar release];
</code>```

;) ... or use autorelease

Body:
Watch out for possible leak in this part of the above code:

self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:tools];

You could use this instead:

UIBarButtonItem* rightButtonBar = [[UIBarButtonItem alloc] initWithCustomView:tools];
self.navigationItem.rightBarButtonItem = rightButtonBar;
[rightButtonBar release];

;) ... or use autorelease


问:
Get locale specific directory in My documents
I have my custom application that generates a directory in My documents path, after installation the application uses that directory, but i got an issue in Chinese windows OS, where my application folder name appears in Chinese, so is there any way i can get the file name properly in "en" or some wordaround so that i can that directory name at runtime.</p>

答:
```<code>String path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
</code>```

then you can append folder name as

```<code>string folder ="\\YOUR_FOLDER_NAME\\";
</code>```

Then append to you path as

```<code>String full_path=path+folder;
</code>```

Body:
String path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

then you can append folder name as

string folder ="\\YOUR_FOLDER_NAME\\";

Then append to you path as

String full_path=path+folder;


问:
what do we use to define externals in webpack2?
I am trying to migrate an existing project from webpack 1 to webpack 2, I have been able to do it for the most part but not sure how we define externals in webpack 2.</p>

答:
It's very simple to use official doc paragraph Externals:

Example from doc:

```<code>externals : {
  lodash : {
    commonjs: "lodash",
    amd: "lodash",
    root: "_" // indicates global variable
  }
}
</code>```

Body:
It's very simple to use official doc paragraph Externals:

Example from doc:

externals : {
  lodash : {
    commonjs: "lodash",
    amd: "lodash",
    root: "_" // indicates global variable
  }
}


问:
C# Inheritance misconception
Let's say that we have 2 classes. The first one is Person

```<code>    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace People
    {
        class Person
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }
        }
    }
</code>```

The second one is Teacher

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace People
{
    class Teacher:Person
    {
        public string Position { get; set; }
    }
}
</code>```

And I want to make a teacher object using this syntax Person teacher = new Teacher(); When I make it and I try to refer to the Position property, I can't... Why does this happen? I can instead use this syntax Person teacher = new Teacher() {Position="boss" }; but even though, after that I can't refer to the teacher position using "teacher.Position".

答:
You can reach it this way:</p>

```<code>Person teacher = new Teacher() { Position="boss" };
var position = ((Teacher)teacher).Position;
</code>```

Title: C# Inheritance misconception

Body:
Let's say that we have 2 classes. The first one is Person

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace People
    {
        class Person
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }
        }
    }

The second one is Teacher

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace People
{
    class Teacher:Person
    {
        public string Position { get; set; }
    }
}

And I want to make a teacher object using this syntax Person teacher = new Teacher(); When I make it and I try to refer to the Position property, I can't... Why does this happen? I can instead use this syntax Person teacher = new Teacher() {Position="boss" }; but even though, after that I can't refer to the teacher position using "teacher.Position".

Body:
You can reach it this way:

Person teacher = new Teacher() { Position="boss" };
var position = ((Teacher)teacher).Position;