问:
read from cap file with ascii output without -z option
I have been using this script to automatically split a pcap file into single tcp streams:

```<code>for stream in $(tshark -r $1 -T fields -e tcp.stream | sort -n | uniq)
do
    echo $stream
    tshark -r $1 -w $2/stream-$stream.cap -Y "tcp.stream==$stream"
done
</code>```

now, for each single capture file that represents a stream I can read them with

```<code>tshark -r somefile.cap
</code>```

but I get this kind of output:

```<code>1   0.000000   172.18.0.4 → 172.18.0.5   HTTP 386 GET /eureka/apps/delta HTTP/1.1
    2   0.001457   172.18.0.5 → 172.18.0.4   HTTP 466 HTTP/1.1 200 OK  (application/json)
    3   0.001490   172.18.0.4 → 172.18.0.5   TCP 66 37830 → 8761 [ACK] Seq=321 Ack=401 Win=287 Len=0 TSval=330522 TSecr=330522
...
</code>```

I would like to read it with the same format that you get when you follow a stream using -z, for example

```<code>tshark -r somefile.pcap -z "follow,http,ascii,172.18.0.6:57238,172.18.0.4:8081"
</code>```

which gives you the same as above, plus

```<code>===================================================================
Follow: http,ascii
Filter: ((ip.src eq 172.18.0.6 and tcp.srcport eq 57238) and (ip.dst eq 172.18.0.4 and tcp.dstport eq 8081)) or ((ip.src eq 172.18.0.4 and tcp.srcport eq 8081) and (ip.dst eq 172.18.0.6 and tcp.dstport eq 57238))
Node 0: 172.18.0.6:57238
Node 1: 172.18.0.4:8081
821
POST /api/cars?cacheBuster=1511774200847 HTTP/1.1
Origin: http://localhost:8080
Authorization: Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImF1dGgiOiJST0xFX0FETUlOLFJPTEVfVVNFUiIsImV4cCI6MTUxMzI1NzU5MX0.xyXj0-7xjluW0jB9y2UGzcZcruADHkgTH_mnTIYsSmggqDW7XIeHC7ftKPmaMjozLhpIGofHAbrXj6TOTQlvXQ
Accept: application/json, text/plain, */*
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36
Referer: http://localhost:8080/
Accept-Language: en-US,en;q=0.9,it;q=0.8,ru;q=0.7
Accept-Encoding: gzip
Content-Type: application/json;charset=UTF-8
x-forwarded-host: localhost:8080
x-forwarded-proto: http
x-forwarded-prefix: /carapp
x-forwarded-port: 8080
x-forwarded-for: 172.18.0.1
Content-Length: 61
Host: 172.18.0.4:8081
Connection: Keep-Alive
...
</code>```

at the end.

does some option that does this exist?

答:
Maybe something like the following would help?

```<code>tshark -r somefile.pcap -Y "http and (((ip.src eq 172.18.0.6 and tcp.srcport eq 57238) and (ip.dst eq 172.18.0.4 and tcp.dstport eq 8081)) or ((ip.src eq 172.18.0.4 and tcp.srcport eq 8081) and (ip.dst eq 172.18.0.6 and tcp.dstport eq 57238)))" -O http
</code>```

... or a bit more simply, which should accomplish the same thing:

```<code>tshark -r somefile.pcap -Y "http and (ip.addr eq 172.18.0.6 and tcp.port eq 57238 and ip.addr eq 172.18.0.4 and tcp.port eq 8081)" -O http
</code>```

... or even simpler if you know the TCP stream number associated with this conversation:

```<code>tshark -r somefile.pcap -Y "http and tcp.stream eq 0" -O http
</code>```

(Here, I've just assumed the stream index is 0.)

Refer to the tshark man page for more information.

Body:
I have been using this script to automatically split a pcap file into single tcp streams:

for stream in $(tshark -r $1 -T fields -e tcp.stream | sort -n | uniq)
do
    echo $stream
    tshark -r $1 -w $2/stream-$stream.cap -Y "tcp.stream==$stream"
done

now, for each single capture file that represents a stream I can read them with

tshark -r somefile.cap

but I get this kind of output:

1   0.000000   172.18.0.4 → 172.18.0.5   HTTP 386 GET /eureka/apps/delta HTTP/1.1
    2   0.001457   172.18.0.5 → 172.18.0.4   HTTP 466 HTTP/1.1 200 OK  (application/json)
    3   0.001490   172.18.0.4 → 172.18.0.5   TCP 66 37830 → 8761 [ACK] Seq=321 Ack=401 Win=287 Len=0 TSval=330522 TSecr=330522
...

I would like to read it with the same format that you get when you follow a stream using -z, for example

tshark -r somefile.pcap -z "follow,http,ascii,172.18.0.6:57238,172.18.0.4:8081"

which gives you the same as above, plus

===================================================================
Follow: http,ascii
Filter: ((ip.src eq 172.18.0.6 and tcp.srcport eq 57238) and (ip.dst eq 172.18.0.4 and tcp.dstport eq 8081)) or ((ip.src eq 172.18.0.4 and tcp.srcport eq 8081) and (ip.dst eq 172.18.0.6 and tcp.dstport eq 57238))
Node 0: 172.18.0.6:57238
Node 1: 172.18.0.4:8081
821
POST /api/cars?cacheBuster=1511774200847 HTTP/1.1
Origin: http://localhost:8080
Authorization: Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImF1dGgiOiJST0xFX0FETUlOLFJPTEVfVVNFUiIsImV4cCI6MTUxMzI1NzU5MX0.xyXj0-7xjluW0jB9y2UGzcZcruADHkgTH_mnTIYsSmggqDW7XIeHC7ftKPmaMjozLhpIGofHAbrXj6TOTQlvXQ
Accept: application/json, text/plain, */*
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36
Referer: http://localhost:8080/
Accept-Language: en-US,en;q=0.9,it;q=0.8,ru;q=0.7
Accept-Encoding: gzip
Content-Type: application/json;charset=UTF-8
x-forwarded-host: localhost:8080
x-forwarded-proto: http
x-forwarded-prefix: /carapp
x-forwarded-port: 8080
x-forwarded-for: 172.18.0.1
Content-Length: 61
Host: 172.18.0.4:8081
Connection: Keep-Alive
...

at the end.

does some option that does this exist?

Body:
Maybe something like the following would help?

tshark -r somefile.pcap -Y "http and (((ip.src eq 172.18.0.6 and tcp.srcport eq 57238) and (ip.dst eq 172.18.0.4 and tcp.dstport eq 8081)) or ((ip.src eq 172.18.0.4 and tcp.srcport eq 8081) and (ip.dst eq 172.18.0.6 and tcp.dstport eq 57238)))" -O http

... or a bit more simply, which should accomplish the same thing:

tshark -r somefile.pcap -Y "http and (ip.addr eq 172.18.0.6 and tcp.port eq 57238 and ip.addr eq 172.18.0.4 and tcp.port eq 8081)" -O http

... or even simpler if you know the TCP stream number associated with this conversation:

tshark -r somefile.pcap -Y "http and tcp.stream eq 0" -O http

(Here, I've just assumed the stream index is 0.)

Refer to the tshark man page for more information.


来源: stackexchange

问:
unable to install tensorflow using pip on windows
i have tried the whl file also but the every time same error pops up

```<code>-> pip install tensorflow
</code>```

Could not find a version that satisfies the requirement tensorflow (from versions: )
  No matching distribution found for tensorflow

```<code>->pip install --upgrade https://storage.googleapis.com/tensorflow/windows/cpu/tensorflow-0.12.1-cp35-cp35m-win_amd64.whl
</code>```

tensorflow-0.12.1-cp35-cp35m-win_amd64.whl is not a supported wheel on this platform.

答:
I've been looking all over the interwebs, and I see dropping from v3.6 to v3.5 to be the most suggested workaround for this.  However, The tensorflow site says this:

TensorFlow supports Python 3.5.x and 3.6.x on Windows. Note that
  Python 3 comes with the pip3 package manager, which is the program
  you'll use to install TensorFlow.

I can't seem to get 3.6 to work.  Anyone know if 3.6 is now actually supported, or is that possible fake news on the tensorflow site?

ContentLicense: CC BY-SA 3.0

Body:
i have tried the whl file also but the every time same error pops up

-> pip install tensorflow

Could not find a version that satisfies the requirement tensorflow (from versions: )
  No matching distribution found for tensorflow

->pip install --upgrade https://storage.googleapis.com/tensorflow/windows/cpu/tensorflow-0.12.1-cp35-cp35m-win_amd64.whl

tensorflow-0.12.1-cp35-cp35m-win_amd64.whl is not a supported wheel on this platform.


问:
Java - Generate a web form using CICS API
I have a task which  needs to place a random 8-digit numeric token, rtok, in a
container of the process (call it TOKEN) and notify user a URL where they can go to and tick an option. The URL should be of the form
https://zeuszos.edu.ihost.com:8005/afcheck/customer/she00nn?proc=AFCnnnnnnnn&token=rtok

The AFCnnnnnnnn, the nnnnnnnn is the random 8-digit numeric token. I have gone through this tutorial but it doesn't help much. Can anyone suggest anything? Thanks.

答:
If you are looking to create a web app in CICS, then the CICS Liberty support, which enables the JEE6 & 7 Web profile and is a lot easier (and more standard) than using JCICS web and document classes, which is what the  old examples.web.Sample1 one uses. Liberty is supported in CICS since CICS TS V5.1 See this video for some high level info Architecting Java solutions for CICS.

You can find information on developing a simple Liberty web app here on our CICS developer center and there is a tutorial here on using the JCICS APIs

There is also a suite of sample Liberty apps here on our CICSDev GitHub.

Let us know how you get on.


问:
Kafka Producer and Broker Throughput Limitations
I have configured a two node six partition Kafka cluster with a replication factor of 2 on AWS. Each Kafka node runs on a m4.2xlarge EC2 instance backed by an EBS.

I understand that rate of data flow from Kafka producer to Kafka broker is limited by the network bandwidth of producer.

Say network bandwidth between Kafka producer and broker is 1Gbps ( approx. 125 MB/s) and bandwidth between Kafka broker and storage ( between EC2 instance and EBS volume ) is 1 Gbps.

I used the org.apache.kafka.tools.ProducerPerformance  tool for profiling the performance.

I observed that a single producer can write at around 90 MB/s to the broker when a message size is 100 bytes.( hence network is not saturated)

I also observed that disk write rate to EBS volume is around 120 MB/s.

Is this 90 MB/s due to some network bottleneck or is it a limitation of Kafka ?  (forgetting batch size and compression etc. for simplicity )

Could this be due to the bandwidth limitation between broker and ebs volume?

I also observed that when two producers ( from two separate machines ) produce data, throughput of one producer dropped to around 60 MB/s.

What could be the reason for this? Why doesn't that value reach 90 MB/s ? Could this be due to the network bottleneck between broker and ebs volume?

What confuses me is that in both cases (single producer and two producers ) disk write rate to ebs stays around 120 MB/s ( closer to its upper limit ).

Thank you

答:
There are a couple things to consider:

There are separate disk and network limits that apply to both the instance and the volume.

You have to account for replication.  If you have RF=2, the amount of write traffic taken by a single node is 2*(PRODUCER_TRAFFIC)/(PARTITION_COUNT) assuming even distribution of writes across partitions.


问:
How to reload data in candle chart? AmChart library
I'm developing application based on REST architecture and CRUD assumptions using Java, Spring, Hibernate, and AmCharts Library.

But in my project I have a problem with reloading data in a candle chart (stock chart) from AmCharts.

My JavaScript code:

```<code>var request;
firstDeploy();

function firstDeploy() {
  request = 'http://localhost:8080/v1/crypto/getCandles?currencyPair=tBTCUSD&timeFrame=1D';
}

var candleChart = AmCharts.makeChart("chartdiv", {
  type: "stock",

  dataSets: [{
    fieldMappings: [{
      fromField: "open",
      toField: "open"
    }, {
      fromField: "close",
      toField: "close"
    }, {
      fromField: "high",
      toField: "high"
    }, {
      fromField: "low",
      toField: "low"
    }, {
      fromField: "volume",
      toField: "volume"
    }, {
      fromField: "value",
      toField: "value"
    }],

    color: "#7f8da9",
    dataLoader: {
      url: request,
      format: 'json'
    },
    title: "tBTCUSD",
    categoryField: "date"
  }],

  panels: [{
      title: "Value",
      showCategoryAxis: false,
      percentHeight: 70,
      valueAxes: [{
        id:"v1",
        dashLength: 5
      }],

      categoryAxis: {
        dashLength: 5
      },

      stockGraphs: [{
        type: "candlestick",
        id: "g1",
        openField: "open",
        closeField: "close",
        highField: "high",
        lowField: "low",
        valueField: "close",
        lineColor: "#7f8da9",
        fillColors: "#7f8da9",
        negativeLineColor: "#db4c3c",
        negativeFillColors: "#db4c3c",
        fillAlphas: 1,
        useDataSetColors: false,
        comparable: true,
        compareField: "value",
        showBalloon: false
      }],

      stockLegend: {
        valueTextRegular: undefined,
        periodValueTextComparing: "[[percents.value.close]]%"
      }
    },

    {
      title: "Volume",
      percentHeight: 30,
      marginTop: 1,
      showCategoryAxis: true,
      valueAxes: [{
        id:"v2",
        dashLength: 5
      }],

      categoryAxis: {
        dashLength: 5
      },

      stockGraphs: [{
        valueField: "volume",
        type: "column",
        showBalloon: false,
        fillAlphas: 1
      }],

      stockLegend: {
        markerType: "none",
        markerSize: 0,
        labelText: "",
        periodValueTextRegular: "[[value.close]]"
      }
    }
  ],

  chartCursorSettings: {
    valueLineEnabled:true,
    valueLineBalloonEnabled:true
  },

  chartScrollbarSettings: {
    graph: "g1",
    graphType: "line",
    usePeriod: "WW",
    updateOnReleaseOnly:false
  },

  periodSelector: {
    position: "bottom",
    periods: [{
      period: "DD",
      count: 10,
      label: "10 days"
    }, {
      period: "MM",
      selected: true,
      count: 1,
      label: "1 month"
    }, {
      period: "YYYY",
      count: 1,
      label: "1 year"
    }, {
      period: "YTD",
      label: "YTD"
    }, {
      period: "MAX",
      label: "MAX"
    }]
  }
});

$(options)

function options() {
  var handler = handleDropdown(handleResults)
  handler('#time-frame-list', 'time')
  handler('#currency-pair-list', 'currency')

}

function handleResults(results) {
  var mainRequest = 'http://localhost:8080/v1/crypto/getCandles?currencyPair=t';
  var resultsArray = JSON.stringify(results);
  var currencyPair = resultsArray.substr(25,6);
  var timeFrame = resultsArray.substr(9,2);
  request = mainRequest + currencyPair + '&timeFrame=' + timeFrame;
  candleChart.dataLoader.url = request;
  candleChart.dataLoader.loadData();
  console.log(request);
}

function handleDropdown(handler) {
  var options = {}

  return function(selector, key) {
    options[key] = $(selector).val()
    $(selector).change(function(event) {
      options[key] = this.options[event.target.selectedIndex].value
      handler(options)
    })
  }
}
</code>```

My HTML code:

```<code><html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>amStock Example</title>
        <link rel="stylesheet" href="style.css">
        <script src="amcharts.js" type="text/javascript"></script>
        <script src="serial.js" type="text/javascript"></script>
        <script src="amstock.js" type="text/javascript"></script>
        <script src="dataloader.min.js" type="text/javascript"></script>
        <script src="jquery-3.2.1.min.js" type="text/javascript"></script>
    <script src="cryptoscript.js" type="text/javascript"></script>
</head>
<body style="background-color:#FFFFFF">
<center>
<div class="chart-background">
  <div class="drop-down-menus">
    <div  class="time-frame-dropdown">
      <select id="time-frame-list">
        <option value="1D" selected>1D</option>
        <option value="1h">1H</option>
      </select>
    </div>
    <div  class="currency-pair-dropdown">
      <select id="currency-pair-list">
        <option value="BTCUSD" selected>BTCUSD</option>
        <option value="ETHUSD">ETHUSD</option>
      </select>
    </div>
  </div>
    </div>
        <div id="chartdiv" class="chart-candle" style="width:50%; height:600px;"></div>
    </div>
</center>
</body>

</html>
</code>```

My RestController:

```<code>@RestController
@RequestMapping("v1/crypto")
public class CandleRestController {

    @Autowired
    private DbService service;

    @Autowired
    private CandleMapper candleMapper;

    @RequestMapping(method = RequestMethod.GET, value = "getCandles")
    public CandleDtoCharts[] getCandleList(@RequestParam String currencyPair, @RequestParam String timeFrame) {
        System.out.println(currencyPair + " " + timeFrame);
        return candleMapper.mapToCandleDtoChartsList(service.getCandlesByCurrencyPairAndTimeFrame(currencyPair, timeFrame));
    }
}
</code>```

I know that my RestController is receiving all the time the same "request" (url) after choosing other currency pair/or time frame and I don't know why?

答:
You have to update the dataLoader url inside the dataSet. You're updating it at the chart level, which doesn't work in the stock chart.

```<code>candleChart.dataLoader.url = request; //this doesn't work in a stock chart
candleChart.dataSets[0].dataLoader.url = request; //this does.
</code>```

Body:
I'm developing application based on REST architecture and CRUD assumptions using Java, Spring, Hibernate, and AmCharts Library.

But in my project I have a problem with reloading data in a candle chart (stock chart) from AmCharts.

My JavaScript code:

var request;
firstDeploy();

function firstDeploy() {
  request = 'http://localhost:8080/v1/crypto/getCandles?currencyPair=tBTCUSD&timeFrame=1D';
}

var candleChart = AmCharts.makeChart("chartdiv", {
  type: "stock",

  dataSets: [{
    fieldMappings: [{
      fromField: "open",
      toField: "open"
    }, {
      fromField: "close",
      toField: "close"
    }, {
      fromField: "high",
      toField: "high"
    }, {
      fromField: "low",
      toField: "low"
    }, {
      fromField: "volume",
      toField: "volume"
    }, {
      fromField: "value",
      toField: "value"
    }],

    color: "#7f8da9",
    dataLoader: {
      url: request,
      format: 'json'
    },
    title: "tBTCUSD",
    categoryField: "date"
  }],

  panels: [{
      title: "Value",
      showCategoryAxis: false,
      percentHeight: 70,
      valueAxes: [{
        id:"v1",
        dashLength: 5
      }],

      categoryAxis: {
        dashLength: 5
      },

      stockGraphs: [{
        type: "candlestick",
        id: "g1",
        openField: "open",
        closeField: "close",
        highField: "high",
        lowField: "low",
        valueField: "close",
        lineColor: "#7f8da9",
        fillColors: "#7f8da9",
        negativeLineColor: "#db4c3c",
        negativeFillColors: "#db4c3c",
        fillAlphas: 1,
        useDataSetColors: false,
        comparable: true,
        compareField: "value",
        showBalloon: false
      }],

      stockLegend: {
        valueTextRegular: undefined,
        periodValueTextComparing: "[[percents.value.close]]%"
      }
    },

    {
      title: "Volume",
      percentHeight: 30,
      marginTop: 1,
      showCategoryAxis: true,
      valueAxes: [{
        id:"v2",
        dashLength: 5
      }],

      categoryAxis: {
        dashLength: 5
      },

      stockGraphs: [{
        valueField: "volume",
        type: "column",
        showBalloon: false,
        fillAlphas: 1
      }],

      stockLegend: {
        markerType: "none",
        markerSize: 0,
        labelText: "",
        periodValueTextRegular: "[[value.close]]"
      }
    }
  ],

  chartCursorSettings: {
    valueLineEnabled:true,
    valueLineBalloonEnabled:true
  },

  chartScrollbarSettings: {
    graph: "g1",
    graphType: "line",
    usePeriod: "WW",
    updateOnReleaseOnly:false
  },

  periodSelector: {
    position: "bottom",
    periods: [{
      period: "DD",
      count: 10,
      label: "10 days"
    }, {
      period: "MM",
      selected: true,
      count: 1,
      label: "1 month"
    }, {
      period: "YYYY",
      count: 1,
      label: "1 year"
    }, {
      period: "YTD",
      label: "YTD"
    }, {
      period: "MAX",
      label: "MAX"
    }]
  }
});

$(options)

function options() {
  var handler = handleDropdown(handleResults)
  handler('#time-frame-list', 'time')
  handler('#currency-pair-list', 'currency')

}

function handleResults(results) {
  var mainRequest = 'http://localhost:8080/v1/crypto/getCandles?currencyPair=t';
  var resultsArray = JSON.stringify(results);
  var currencyPair = resultsArray.substr(25,6);
  var timeFrame = resultsArray.substr(9,2);
  request = mainRequest + currencyPair + '&timeFrame=' + timeFrame;
  candleChart.dataLoader.url = request;
  candleChart.dataLoader.loadData();
  console.log(request);
}

function handleDropdown(handler) {
  var options = {}

  return function(selector, key) {
    options[key] = $(selector).val()
    $(selector).change(function(event) {
      options[key] = this.options[event.target.selectedIndex].value
      handler(options)
    })
  }
}

My HTML code:

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>amStock Example</title>
        <link rel="stylesheet" href="style.css">

      <select id="time-frame-list">
        <option value="1D" selected>1D</option>
        <option value="1h">1H</option>
      </select>

      <select id="currency-pair-list">
        <option value="BTCUSD" selected>BTCUSD</option>
        <option value="ETHUSD">ETHUSD</option>
      </select>

My RestController:

@RestController
@RequestMapping("v1/crypto")
public class CandleRestController {

    @Autowired
    private DbService service;

    @Autowired
    private CandleMapper candleMapper;

    @RequestMapping(method = RequestMethod.GET, value = "getCandles")
    public CandleDtoCharts[] getCandleList(@RequestParam String currencyPair, @RequestParam String timeFrame) {
        System.out.println(currencyPair + " " + timeFrame);
        return candleMapper.mapToCandleDtoChartsList(service.getCandlesByCurrencyPairAndTimeFrame(currencyPair, timeFrame));
    }
}

I know that my RestController is receiving all the time the same "request" (url) after choosing other currency pair/or time frame and I don't know why?

Body:
You have to update the dataLoader url inside the dataSet. You're updating it at the chart level, which doesn't work in the stock chart.

candleChart.dataLoader.url = request; //this doesn't work in a stock chart
candleChart.dataSets[0].dataLoader.url = request; //this does.


问:
JQuery remove button from td cell?
I have table where user can click to unlock the record. I want to remove Unlock button and replace with the text. For example once they click unlock button will be removed and text will show up like 'Record is unlocked'. I'm not sure why my current code doesn't remove button. If anyone can help please let me know. Thank you.

$('.unlockBtn').on('click',unlockRecord);

function unlockRecord(){
 var trID = $(this).parents("tr").prop('id');

 if(confirm("Are you sure you want to unlock this record?")){
  $.ajax({
   type: 'POST',
   url: 'Application.cfc?method=unlockRec',
   data: {'recID':trID},
      dataType: 'json'
  }).done(function(obj){
   var numRecs = obj.RECORDCOUNT;

   if(obj.STATUS == 200){
    $('#' + trID).closest('.unlockBtn').remove();
   }else{
    alert('Error')
   }
  }).fail(function(jqXHR, textStatus, errorThrown){
       alert("Error: "+errorThrown);
  });
 }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th>User Name</th>
      <th>Status</th>
      <th>Date</th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr id="11">
      <td>Jack, Smith</td>
      <td>Active</td>
      <td>12/01/2017</td>
      <td>01:16 PM</td>
      <td class="unlockBtn" style="text-align: center;">
        <input name="unlock" id="unlock" value="Unlock" type="button">
      </td>
    </tr>
  </tbody>
</table></code>```

答:
Just add back your ajax call and you will be done.

$('.unlockBtn').on('click',unlockRecord);

function unlockRecord(){
 var trID = $(this).parents("tr").prop('id');

 if(confirm("Are you sure you want to unlock this record?")){
  var cell = $(event.srcElement);

   $( cell ).replaceWith( "
Record Unlocked
" );
 }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th>User Name</th>
      <th>Status</th>
      <th>Date</th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr id="11">
      <td>Jack, Smith</td>
      <td>Active</td>
      <td>12/01/2017</td>
      <td>01:16 PM</td>
      <td class="unlockBtn" style="text-align: center;">
        <input name="unlock" id="unlock" value="Unlock" type="button">
      </td>
    </tr>
  </tbody>
</table></code>```

Title: JQuery remove button from td cell?

Body:
I have table where user can click to unlock the record. I want to remove Unlock button and replace with the text. For example once they click unlock button will be removed and text will show up like 'Record is unlocked'. I'm not sure why my current code doesn't remove button. If anyone can help please let me know. Thank you.

$('.unlockBtn').on('click',unlockRecord);

function unlockRecord(){
 var trID = $(this).parents("tr").prop('id');

 if(confirm("Are you sure you want to unlock this record?")){
  $.ajax({
   type: 'POST',
   url: 'Application.cfc?method=unlockRec',
   data: {'recID':trID},
      dataType: 'json'
  }).done(function(obj){
   var numRecs = obj.RECORDCOUNT;

   if(obj.STATUS == 200){
    $('#' + trID).closest('.unlockBtn').remove();
   }else{
    alert('Error')
   }
  }).fail(function(jqXHR, textStatus, errorThrown){
       alert("Error: "+errorThrown);
  });
 }
}

      User Name
      Status
      Date

      Jack, Smith
      Active
      12/01/2017
      01:16 PM

        <input name="unlock" id="unlock" value="Unlock" type="button">

Body:
Just add back your ajax call and you will be done.

$('.unlockBtn').on('click',unlockRecord);

function unlockRecord(){
 var trID = $(this).parents("tr").prop('id');

 if(confirm("Are you sure you want to unlock this record?")){
  var cell = $(event.srcElement);

   $( cell ).replaceWith( "<div>Record Unlocked</div>" );
 }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th>User Name</th>
      <th>Status</th>
      <th>Date</th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr id="11">
      <td>Jack, Smith</td>
      <td>Active</td>
      <td>12/01/2017</td>
      <td>01:16 PM</td>
      <td class="unlockBtn" style="text-align: center;">
        <input name="unlock" id="unlock" value="Unlock" type="button">
      </td>
    </tr>
  </tbody>
</table>


问:
Watching the output of a bash script
I'm trying to use watch to look at the output of a shell script, executing /bin/bash and holding the script itself in a heredoc.

The booger is only executing once though. It gives the correct output, then watch refreshes and the screen goes blank. Upon exiting watch there are no errors listed.

I can't figure out where the issue is since it's getting difficult to debug with watch > bash > heredoc > ugly code.

The good news is that ugly code in the heredoc works fine.

```<code>function show_users {

    [[ -z $1 ]] && watchtime=1 || watchtime=$1
    [[ -z $2 ]] && export userToShow="mydefaultuser" || export userToShow=$2

    echo "Setting up watch for user ${userToShow}"

    watch -n $watchtime --no-title /bin/bash <<-'EOF'
        #Show finger results of requested user
        finger ${userToShow}

        #show list of users su'd into requested user
        echo "************************************************************************************"
        echo "users logged in as ${userToShow}"

        #get the parent PIDS of any process belonging to requested user
        #into a list that can be read by grep
        parentPIDs=$(ps -ef | grep "su - ${userToShow}" | grep -v 'grep\|finger' | awk 'NR>1{printf " %s \\|",parentpid}{parentpid=$3}END{printf " %s\n", parentpid}')

        #get usersnames associated to those parent PIDS
        parentUsers=$(ps -ef | grep "${parentPIDs}" | grep -v "grep\|${userToShow}" | awk '{print $1}' | sort | uniq)

        #finger each of these users and get their full name
        while IFS= read -r line ; do
            printf "%s: " $line
            parentName=$(finger $line | awk -F":" 'NR==1{print $3}')
            echo $parentName
        done <<< "${parentUsers}"

        #show tree for all proceses being run by requested user up to root.
        echo "************************************************************************************"
        ps -ef --forest | egrep -e "sshd:|-ksh|$userToShow" | grep -v grep | awk 'root==1{print ""} NR>1{print line} {line=$0;root=($1=="root") ? 1 : 0}'
    EOF
}
</code>```

called like:

```<code>show_users 2 "username"
</code>```

答:
You can put the code in a function. With export -f func you make the function definition available to subprocesses of the current script, so that you can then say

```<code>watch bash -c func
</code>```

In OP's example:

```<code># don't use bash-only (IMHO ugly) function syntax
get_user_info () {
    local userToShow=$1

    # No need for braces around variable names unless disambiguation is required
    finger "$userToShow"

    echo "lots of ugly asterisks"
    echo "users logged in as ${userToShow}"

    # avoid grep | grep | awk
    # field specifier can probasbly be made more strict
    # (match only $2 instead of $0)?
    parentPIDs=$(ps -ef |
        awk -v user="$userToShow" 'NR>1 && ($0 ~ "su - " user) {
                printf " %s \\|",parentpid}
            {parentpid=$3}
            END{printf " %s\n", parentpid}')

    # Would be better if parentPIDs was a proper regex
    # Assumes you are looking for the PPID in column 3
    parentUsers=$(ps -ef |
        awk -v pids="$parentPIDs" 'parentPIDs ~$3 {print $1}' |
        # prefer sort -u over sort | uniq
        sort -u)

    while IFS= read -r line ; do
        printf "%s: " "$line"
        # No need to capture output just to echo it
        finger "$line" | awk -F":" 'NR==1{print $3}'
    done <<< "${parentUsers}"

    echo "Another ugly lot of asterisks"
    # Again, the regex can probably be applied to just one field
    ps -ef --forest |
        awk -v re="sshd:|-ksh|$userToShow"  '$0 !~ re { next }
            root==1{print ""}
            NR>1{print line}
            {line=$0;root=($1=="root" || $3==1) ? 1 : 0}'
}

export -f get_user_info

show_users () {
     # Avoid complex [[ -z ... ]]; use defaults with ${var-"value if unset"}
     # Mark these as local to avoid polluting global namespace
     local watchtime={$1-1}
     local userToShow=${2-mydefaultuser}
     # no need to export these variables

     echo "$mycommand"
     echo "Setting up watch for user ${userToShow}"

     watch -n $watchtime --no-title bash -c get_user_info "$userToShow"
}
</code>```

Title: Watching the output of a bash script

Body:
I'm trying to use watch to look at the output of a shell script, executing /bin/bash and holding the script itself in a heredoc.

The booger is only executing once though. It gives the correct output, then watch refreshes and the screen goes blank. Upon exiting watch there are no errors listed.

I can't figure out where the issue is since it's getting difficult to debug with watch > bash > heredoc > ugly code.

The good news is that ugly code in the heredoc works fine.

function show_users {

    [[ -z $1 ]] && watchtime=1 || watchtime=$1
    [[ -z $2 ]] && export userToShow="mydefaultuser" || export userToShow=$2

    echo "Setting up watch for user ${userToShow}"

    watch -n $watchtime --no-title /bin/bash <<-'EOF'
        #Show finger results of requested user
        finger ${userToShow}

        #show list of users su'd into requested user
        echo "************************************************************************************"
        echo "users logged in as ${userToShow}"

        #get the parent PIDS of any process belonging to requested user
        #into a list that can be read by grep
        parentPIDs=$(ps -ef | grep "su - ${userToShow}" | grep -v 'grep\|finger' | awk 'NR>1{printf " %s \\|",parentpid}{parentpid=$3}END{printf " %s\n", parentpid}')

        #get usersnames associated to those parent PIDS
        parentUsers=$(ps -ef | grep "${parentPIDs}" | grep -v "grep\|${userToShow}" | awk '{print $1}' | sort | uniq)

        #finger each of these users and get their full name
        while IFS= read -r line ; do
            printf "%s: " $line
            parentName=$(finger $line | awk -F":" 'NR==1{print $3}')
            echo $parentName
        done <<< "${parentUsers}"

        #show tree for all proceses being run by requested user up to root.
        echo "************************************************************************************"
        ps -ef --forest | egrep -e "sshd:|-ksh|$userToShow" | grep -v grep | awk 'root==1{print ""} NR>1{print line} {line=$0;root=($1=="root") ? 1 : 0}'
    EOF
}

called like:

show_users 2 "username"

Body:
You can put the code in a function. With export -f func you make the function definition available to subprocesses of the current script, so that you can then say

watch bash -c func

In OP's example:

# don't use bash-only (IMHO ugly) function syntax
get_user_info () {
    local userToShow=$1

    # No need for braces around variable names unless disambiguation is required
    finger "$userToShow"

    echo "lots of ugly asterisks"
    echo "users logged in as ${userToShow}"

    # avoid grep | grep | awk
    # field specifier can probasbly be made more strict
    # (match only $2 instead of $0)?
    parentPIDs=$(ps -ef |
        awk -v user="$userToShow" 'NR>1 && ($0 ~ "su - " user) {
                printf " %s \\|",parentpid}
            {parentpid=$3}
            END{printf " %s\n", parentpid}')

    # Would be better if parentPIDs was a proper regex
    # Assumes you are looking for the PPID in column 3
    parentUsers=$(ps -ef |
        awk -v pids="$parentPIDs" 'parentPIDs ~$3 {print $1}' |
        # prefer sort -u over sort | uniq
        sort -u)

    while IFS= read -r line ; do
        printf "%s: " "$line"
        # No need to capture output just to echo it
        finger "$line" | awk -F":" 'NR==1{print $3}'
    done <<< "${parentUsers}"

    echo "Another ugly lot of asterisks"
    # Again, the regex can probably be applied to just one field
    ps -ef --forest |
        awk -v re="sshd:|-ksh|$userToShow"  '$0 !~ re { next }
            root==1{print ""}
            NR>1{print line}
            {line=$0;root=($1=="root" || $3==1) ? 1 : 0}'
}

export -f get_user_info

show_users () {
     # Avoid complex [[ -z ... ]]; use defaults with ${var-"value if unset"}
     # Mark these as local to avoid polluting global namespace
     local watchtime={$1-1}
     local userToShow=${2-mydefaultuser}
     # no need to export these variables

     echo "$mycommand"
     echo "Setting up watch for user ${userToShow}"

     watch -n $watchtime --no-title bash -c get_user_info "$userToShow"
}


问:
Caching variables in a `for` loop
I've been reading tips about Javascript performance boosting and one tip said to cache all the variables (that don't change) in the loops comparer statement and I was wondering if this also applied to .NET.

Assuming I had a simple for loop, which one of the following would be faster or would they be the same?

No Cache:

```<code>for (int i = 0; i < someArray.Length; i++)
{

}
</code>```

With Cache:

```<code>for (int i = 0, count = someArray.Length; i < count; i++)
{

}
</code>```

According to the article "caching" the value of Length cuts out one operation in the loop because its faster to access local variables compared to accessing members of an object.
Is it actually faster declaring a local variable compared to simply accessing the member? Does the compiler pick up on this and automatically cache the value? Is there any negatives in declaring a local variable over accessing the member?

Whilst speed is probably a key factor here, its not the only one. My next question would probably be which one is more efficient. Which uses less memory allocations? Which performs less stack manipulation? etc...

From comments, it seems accessing array lengths is pretty fast. Lets say I use an IList<> instead. Would caching the value of Count be faster than retrieving it each iteration?

答:
Just to provide a different answer. Caching the length value may help you in some particular cases.

In my case, we were using a sample code with selenium for ui tests. The code looked like this:

```<code>for (int i = 0; i < Grid.VisibleRows.Length; i++) {
    // do something
}
</code>```

Our grid was just a class representing an html table. The VisibleRows was getting a IWebElement[] and then using Length property. Each iteration implied to go the UI and get all rows.

Of course another implementation might be to just go to the UI once and get the length (instead of counting the rows in memory), but still moving the code out of the for loop implied an improvement on performance - I reduced the number of roundtrips to the UI from many to just one.

So code now looks like this:

```<code>var rowsLength = Grid.VisibleRows.Length;
 for (int i = 0; i < rowsLength ; i++) {
        // do something
    }
</code>```

For us, the manual caching worked out. Using a stopwatch we checked that we were able to reduce the time of that part of code from 32993 ms to 12020 MS

Title: Caching variables in a `for` loop

Body:
I've been reading tips about Javascript performance boosting and one tip said to cache all the variables (that don't change) in the loops comparer statement and I was wondering if this also applied to .NET.

Assuming I had a simple for loop, which one of the following would be faster or would they be the same?

No Cache:

for (int i = 0; i < someArray.Length; i++)
{

}

With Cache:

for (int i = 0, count = someArray.Length; i < count; i++)
{

}

According to the article "caching" the value of Length cuts out one operation in the loop because its faster to access local variables compared to accessing members of an object.
Is it actually faster declaring a local variable compared to simply accessing the member? Does the compiler pick up on this and automatically cache the value? Is there any negatives in declaring a local variable over accessing the member?

Whilst speed is probably a key factor here, its not the only one. My next question would probably be which one is more efficient. Which uses less memory allocations? Which performs less stack manipulation? etc...

From comments, it seems accessing array lengths is pretty fast. Lets say I use an IList<> instead. Would caching the value of Count be faster than retrieving it each iteration?

Body:
Just to provide a different answer. Caching the length value may help you in some particular cases.

In my case, we were using a sample code with selenium for ui tests. The code looked like this:

for (int i = 0; i < Grid.VisibleRows.Length; i++) {
    // do something
}

Our grid was just a class representing an html table. The VisibleRows was getting a IWebElement[] and then using Length property. Each iteration implied to go the UI and get all rows.

Of course another implementation might be to just go to the UI once and get the length (instead of counting the rows in memory), but still moving the code out of the for loop implied an improvement on performance - I reduced the number of roundtrips to the UI from many to just one.

So code now looks like this:

var rowsLength = Grid.VisibleRows.Length;
 for (int i = 0; i < rowsLength ; i++) {
        // do something
    }

For us, the manual caching worked out. Using a stopwatch we checked that we were able to reduce the time of that part of code from 32993 ms to 12020 MS


问:
In writing a purely relational prolog program, is it ok to use a carefully placed cut?
I am trying my hand in writing a relational prolog program that manages a key, value store. The initial code is taken from some lecture slides i found on the internet (http://people.eng.unimelb.edu.au/pstuckey/book/course.html -- see: using data structure slides).

```<code>newdic([]).
addkey(D0,K,I,D) :- D = [p(K,I)|D0].
delkey([],_,[]).
delkey([p(K,_)|D],K,D).
delkey([p(K0,I)|D0],K,[p(K0,I)|D]) :-
    dif(K, K0), delkey(D0,K,D).
</code>```

This code allows adding more than one value with the same key -- which, is fine with me. However, it also adds the same key, value pair twice, e.g.

```<code>?- newdic(D), addkey(D, a, 1, D2), addkey(D2, a, 1, D3), lookup(D3, a, X).
D = [],
D2 = [p(a, 1)],
D3 = [p(a, 1), p(a, 1)],
X = 1
</code>```

D3 includes p(a,1) twice.

To ensure that this doesn't happen i added the following code; and to ensure that backtracking doesn't find the alternative addkey clause, I added a cut in the end of the first clause.

Is this fair game for a purely relational program -- or are the better ways to ensure that no duplicate key,value pairs are added --without the use of a cut.

```<code>newdic([]).
addkey(D0,K,I,D0) :- lookup(D0, K, I), !.   % if the key already do nothing
addkey(D0,K,I,D) :- D = [p(K,I)|D0].
delkey([],_,[]).
delkey([p(K,_)|D],K,D).
delkey([p(K0,I)|D0],K,[p(K0,I)|D]) :-
    dif(K, K0), delkey(D0,K,D).
</code>```

this leads to the following:

```<code>?- newdic(D), addkey(D, a, 1, D2), addkey(D2, a, 1, D3), lookup(D3, a, X).
D = [],
D2 = D3, D3 = [p(a, 1)],
X = 1.
</code>```

No, more solutions are available -- the program returns immediately.

any suggestions are much appreciated,

Daniel

Note: as an aside: that if i add for the same key different values, the cut does allow to backtrack to identify the second value for the same key:

```<code>?- newdic(D), addkey(D, a, 1, D2), addkey(D2, a, 1, D3), addkey(D3, a, 2, D4), lookup(D4, a, X).
D = [],
D2 = D3, D3 = [p(a, 1)],
D4 = [p(a, 2), p(a, 1)],
X = 2 ;
D = [],
D2 = D3, D3 = [p(a, 1)],
D4 = [p(a, 2), p(a, 1)],
X = 1.
</code>```

答:
SWI Prolog has library predicates for dealing with key-value pairs and associations. I haven't looked at them closely to see what might match your situation, but something to consider.

If you want to roll your own solution, you could write addkey/4 out recursively and maintain the relational behavior:

```<code>addkey([], K, V, [p(K,V)]).             % Add to empty dict
addkey([p(K,V)|T], K, _, [p(K,V)|T]).   % Don't add
addkey([p(K,V)|T], Kadd, Vadd, [p(K,V)|TK]) :-
    dif(Kadd, K),
    addkey(T, Kadd, Vadd, TK).
</code>```

This implementation adds if the key is unique. It ignores the addition and yields the same dictionary back if you try the same key even with different a value (which is usually how a dictionary of key-value pairs behaves). You can enhance it for the uniqueness of the key-value pair pretty easily. Of course, the Prolog you're using would need to include dif/2, or you'd need to roll your own dif/2. :)

Body:
I am trying my hand in writing a relational prolog program that manages a key, value store. The initial code is taken from some lecture slides i found on the internet (http://people.eng.unimelb.edu.au/pstuckey/book/course.html -- see: using data structure slides).

newdic([]).
addkey(D0,K,I,D) :- D = [p(K,I)|D0].
delkey([],_,[]).
delkey([p(K,_)|D],K,D).
delkey([p(K0,I)|D0],K,[p(K0,I)|D]) :-
    dif(K, K0), delkey(D0,K,D).

This code allows adding more than one value with the same key -- which, is fine with me. However, it also adds the same key, value pair twice, e.g.

?- newdic(D), addkey(D, a, 1, D2), addkey(D2, a, 1, D3), lookup(D3, a, X).
D = [],
D2 = [p(a, 1)],
D3 = [p(a, 1), p(a, 1)],
X = 1

D3 includes p(a,1) twice.

To ensure that this doesn't happen i added the following code; and to ensure that backtracking doesn't find the alternative addkey clause, I added a cut in the end of the first clause.

Is this fair game for a purely relational program -- or are the better ways to ensure that no duplicate key,value pairs are added --without the use of a cut.

newdic([]).
addkey(D0,K,I,D0) :- lookup(D0, K, I), !.   % if the key already do nothing
addkey(D0,K,I,D) :- D = [p(K,I)|D0].
delkey([],_,[]).
delkey([p(K,_)|D],K,D).
delkey([p(K0,I)|D0],K,[p(K0,I)|D]) :-
    dif(K, K0), delkey(D0,K,D).

this leads to the following:

?- newdic(D), addkey(D, a, 1, D2), addkey(D2, a, 1, D3), lookup(D3, a, X).
D = [],
D2 = D3, D3 = [p(a, 1)],
X = 1.

No, more solutions are available -- the program returns immediately.

any suggestions are much appreciated,

Daniel

Note: as an aside: that if i add for the same key different values, the cut does allow to backtrack to identify the second value for the same key:

?- newdic(D), addkey(D, a, 1, D2), addkey(D2, a, 1, D3), addkey(D3, a, 2, D4), lookup(D4, a, X).
D = [],
D2 = D3, D3 = [p(a, 1)],
D4 = [p(a, 2), p(a, 1)],
X = 2 ;
D = [],
D2 = D3, D3 = [p(a, 1)],
D4 = [p(a, 2), p(a, 1)],
X = 1.

Body:
SWI Prolog has library predicates for dealing with key-value pairs and associations. I haven't looked at them closely to see what might match your situation, but something to consider.

If you want to roll your own solution, you could write addkey/4 out recursively and maintain the relational behavior:

addkey([], K, V, [p(K,V)]).             % Add to empty dict
addkey([p(K,V)|T], K, _, [p(K,V)|T]).   % Don't add
addkey([p(K,V)|T], Kadd, Vadd, [p(K,V)|TK]) :-
    dif(Kadd, K),
    addkey(T, Kadd, Vadd, TK).

This implementation adds if the key is unique. It ignores the addition and yields the same dictionary back if you try the same key even with different a value (which is usually how a dictionary of key-value pairs behaves). You can enhance it for the uniqueness of the key-value pair pretty easily. Of course, the Prolog you're using would need to include dif/2, or you'd need to roll your own dif/2. :)


问:
Difference between RDD.foreach() and RDD.map()
I am learning Spark in Python and wondering can anyone explain the difference between the action foreach() and transformation map()?

rdd.map() returns a new RDD, like the original map function in Python. However, I want to see a rdd.foreach() function and understand the differences. Thanks!

答:
Map is a transformation, thus when you perform a map you apply a function to each element in the RDD and return a new RDD where additional transformations or actions can be called.

Foreach is an action, it takes each element and applies a function, but it does not return a value. This is particularly useful in you have to call perform some calculation on an RDD and log the result somewhere else, for example a database or call a REST API with each element in the RDD.

For example let's say that you have an RDD with many queries that you wish to log in another system. The queries are stored in an RDD.

```<code>queries = <code to load queries or a transformation that was applied on other RDDs>
</code>```

Then you want to save those queries in another system via a call to another API

```<code>import urllib2

def log_search(q):
    response = urllib2.urlopen('http://www.bigdatainc.org/save_query/' + q)

queries.foreach(log_search)
</code>```

Now you have executed the log_query on each element of the RDD. If you have done a map, nothing would have happened yet, until you called an action.

Body:
Map is a transformation, thus when you perform a map you apply a function to each element in the RDD and return a new RDD where additional transformations or actions can be called.

Foreach is an action, it takes each element and applies a function, but it does not return a value. This is particularly useful in you have to call perform some calculation on an RDD and log the result somewhere else, for example a database or call a REST API with each element in the RDD.

For example let's say that you have an RDD with many queries that you wish to log in another system. The queries are stored in an RDD.

queries = <code to load queries or a transformation that was applied on other RDDs>

Then you want to save those queries in another system via a call to another API

import urllib2

def log_search(q):
    response = urllib2.urlopen('http://www.bigdatainc.org/save_query/' + q)

queries.foreach(log_search)

Now you have executed the log_query on each element of the RDD. If you have done a map, nothing would have happened yet, until you called an action.

ContentLicense: CC BY-SA 4.0


问:
Elastic Beanstalk Node.Js needs PM2 or Forever
In my local node server , it fails on any uncaught exception and has to be manually restarted. So local was run using either forever or pm2.
But my development server is AWS Elastic Beanstalk with Node.Js environment .Though it logs uncaught exceptions and throws it , it never terminates.Even if it terminates , it starts automatically.
So is there a need for PM2 or Forever to keep node.js running for ever in AWS Elastic Beanstalk environment.</p>

答:
My 2 cents:

There are many advantages for PM2 over EBS:

with PM2 you can control and manage many applications (processes) with different platforms (JS, Ruby, ...).
Where in EBS you can deploy only one application at a time to an EBS.

PM2 gives you direct control over all running process, where you can reload/restart/stop one process and keep other intact.

EBS can fix only few problems for you, like restart on crash, or limit memory leaks. But PM2 gives you control over many other problems (graceful reload, 0 latency reload, ...)
Now, I might be a little bit wrong about the full functionalities of EBS, and it might be providing more


问:
SVN "repair move" from the command-line
My IDE doesn't know that I use Subversion, and any time I rename a class (Java) it renames the file without notifying the version control system. I would of course like the file's history to be retained. I understand that in TortoiseSVN there is an option called "repair move" that fixes the move, but that's not an option since I'm on Ubuntu. Is there a way to repair the move from the command-line?</p>

答:
If you remember the old name/location of the file:

```<code>mv new-filename old-filename
svn mv old-filename new-filename
</code>```

You, of course, need the Subversion command-line client installed, which you probably have.  If not, sudo aptitude install subversion subversion-client should do the trick.

Per your comment, no, I don't know that there is an easier way than this.  If you're not sure what your old filename was, svn stat may give you a hint.

ContentLicense: CC BY-SA 2.5

Title: SVN "repair move" from the command-line

Body:
If you remember the old name/location of the file:

mv new-filename old-filename
svn mv old-filename new-filename

You, of course, need the Subversion command-line client installed, which you probably have.  If not, sudo aptitude install subversion subversion-client should do the trick.

Per your comment, no, I don't know that there is an easier way than this.  If you're not sure what your old filename was, svn stat may give you a hint.


问:
Manage UDP packets with IDAS fiware device manager
I am trying to make my own LoRa server at fiware.
I have bought a Gateway(Lorank8v1) which catches LoRa RF packets and send their data to Cloud through UDP protocol.

I would like to ask which IOT agent should I use at Fiware in order to succeed it. There are 3 IOT agents which support different protocols(LWM2M/COAP transport, UL2.0/HTTP or MQTT transport, JSON/MQTT transport).

I am new in this field and i find the protocol compatibility a little bit complicated.

答:
You can use the LoRa Gateway Bridge:

LoRa Gateway Bridge is a service which abstracts the packet-forwarder UDP protocol into JSON over MQTT. The package-forwarder software is running on most gateways and its purpose is to communicate with the LoRa chipset.

With this, you can use the MQTT IoT Agent. I think this is a good choice, because MQTT seems to be the most used between the three protocols.

Also, you can take a look at FIWARE LoRa IoT Agent:

This project is a bridge between the Orange LoRa®* network and the OMA NGSIv1 protocol used by the Orion Context Broker as well as by other components of the FIWARE ecosystem.

I hope this can help you.


问:
Python If statement in view using queryset
I'm attempting to use the following if statement which will display an empty set if the reportaccess is equal to All Reports using the following.

```<code>if reportaccess == 'All Reports':
    bhreportgrouplist = None
    cereportgrouplist = None
    finreportgrouplist = None
    careportgrouplist = None
    pireportgrouplist = None
    screportgrouplist = None
    dssreportgrouplist = None
    psgreportgrouplist = None
    othreportgrouplist = None

else:
    bhreportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 200)
    cereportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 500)
    finreportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 600)
    careportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 800)
    pireportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 1100)
    screportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 1200)
    dssreportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 1300)
    psgreportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 1400)
    othreportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 99999)
</code>```

When the view goes through it is always displaying the Else, but when I view the print of reportaccess it displays as :

```<code> <QuerySet ['All Reports']>
</code>```

Why is my if condition not being met?  How can I make it met

答:
The check for if reportaccess == 'All Reports' does not return True because, from your print, reportaccess is a Queryset, and you are comparing it to a string, which will never be equal.

You can verify this by running

```<code>from django.db.models.query import QuerySet
isinstance(reportaccess, QuerySet)
</code>```

It seems like what you want is to check if your Queryset reportaccess contains 'All Reports', so something like this:

```<code>something = 'All Reports'
if something in reportaccess:
    #do stuff
</code>```

Body:
I'm attempting to use the following if statement which will display an empty set if the reportaccess is equal to All Reports using the following.

if reportaccess == 'All Reports':
    bhreportgrouplist = None
    cereportgrouplist = None
    finreportgrouplist = None
    careportgrouplist = None
    pireportgrouplist = None
    screportgrouplist = None
    dssreportgrouplist = None
    psgreportgrouplist = None
    othreportgrouplist = None

else:
    bhreportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 200)
    cereportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 500)
    finreportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 600)
    careportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 800)
    pireportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 1100)
    screportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 1200)
    dssreportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 1300)
    psgreportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 1400)
    othreportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 99999)

When the view goes through it is always displaying the Else, but when I view the print of reportaccess it displays as :

 <QuerySet ['All Reports']>

Why is my if condition not being met?  How can I make it met

Body:
The check for if reportaccess == 'All Reports' does not return True because, from your print, reportaccess is a Queryset, and you are comparing it to a string, which will never be equal.

You can verify this by running

from django.db.models.query import QuerySet
isinstance(reportaccess, QuerySet)

It seems like what you want is to check if your Queryset reportaccess contains 'All Reports', so something like this:

something = 'All Reports'
if something in reportaccess:
    #do stuff


问:
setOnClickListener Not working in particular class
Here is my code for a one of many buttons within my UserActivity class that don't seem to work even though they have exactly the same implementation in other classes and work there.

```<code>Button test = findViewById(R.id.btn_test);
    test.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(UserActivity.this, "An error occurred.", Toast.LENGTH_LONG).show();
}
});
</code>```

Here is the same implementation that works in SignUp class

```<code>    Button btnLinkToLogIn = findViewById(R.id.btn_link_login);
    btnLinkToLogIn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(SignUpActivity.this, LoginActivity.class);
            startActivity(intent);
        }
    });
</code>```

If any other code is needed please let me know, I am new to this site as well so please be nice and thanks for your help and taking time to read through this!

UserActivity.java

SignUpActivty.java

Project Zip

答:
You have given onClick = "buttonClicked" in your UserActivity's XML file and you have implemented as shown below. Use either onClick in XML or set onClickListener in your Java file. Dont do both.

```<code>public void buttonClicked(View view) {
            aiService.startListening();
        }
</code>```

Body:
Here is my code for a one of many buttons within my UserActivity class that don't seem to work even though they have exactly the same implementation in other classes and work there.

Button test = findViewById(R.id.btn_test);
    test.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(UserActivity.this, "An error occurred.", Toast.LENGTH_LONG).show();
}
});

Here is the same implementation that works in SignUp class

    Button btnLinkToLogIn = findViewById(R.id.btn_link_login);
    btnLinkToLogIn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(SignUpActivity.this, LoginActivity.class);
            startActivity(intent);
        }
    });

If any other code is needed please let me know, I am new to this site as well so please be nice and thanks for your help and taking time to read through this!

UserActivity.java

SignUpActivty.java

Project Zip

Body:
You have given onClick = "buttonClicked" in your UserActivity's XML file and you have implemented as shown below. Use either onClick in XML or set onClickListener in your Java file. Dont do both.

public void buttonClicked(View view) {
            aiService.startListening();
        }


问:
R: Matching sample label order to hierarchically clustered order
I have data called cleaned_mayo that looks like:

```<code>                        Source         Tissue RIN Diagnosis Gender  AgeAtDeath ApoE   FLOWCELL PMI N_unmapped N_multimapping N_noFeature N_ambiguous ENSG00000223972
1924_TCX MayoBrainBank_Dickson TemporalCortex 5.6   Control      F 90_or_above   33 AC5R6PACXX   2    2773880        9656114     8225967     2876479               1
1926_TCX MayoBrainBank_Dickson TemporalCortex 7.8   Control      F          88   33 AC44HKACXX   2    2279283       12410116     9503353     3600252               2
1935_TCX MayoBrainBank_Dickson TemporalCortex 8.6   Control      F          88   33 AC5T2GACXX   3    3120169        8650081     9640468     4603751               0
1925_TCX MayoBrainBank_Dickson TemporalCortex 6.6   Control      F          89   33 BC6178ACXX   4    2046886       10627577     7533671     3361385               1
1963_TCX MayoBrainBank_Dickson TemporalCortex 9.7   Control      M 90_or_above   33 AC5T1WACXX   4    1810116        9611375     5343437     2983079               2
         ENSG00000227232 ENSG00000278267 ENSG00000243485 ENSG00000274890 ENSG00000237613 ENSG00000268020 ENSG00000240361 ENSG00000186092 ENSG00000238009 ENSG00000239945
1924_TCX              80               7               1               0               0               0               0               0               3               0
1926_TCX             113              22               9               0               0               0               0               0               0               0
1935_TCX             181              21               2               0               0               0               0               0               0               0
1925_TCX              75               9               5               0               0               0               0               0               2               0
1963_TCX              73              14               1               0               0               0               0               0               3               0
         ENSG00000233750
1924_TCX              18
1926_TCX               2
1935_TCX               8
1925_TCX              20
1963_TCX              13
</code>```

I hierarchically cluster the expression columns of this data using the following code:

```<code># Create the dendrogram for visualization
dend_expr<- cleaned_mayo[,14:60738] %>% # Isolate expression data
                  scale %>% # Normalize
                  dist  %>% # Compute distance measure
                  hclust %>% # Cluster hierarchically
                  as.dendrogram %>% # Convert to dendrogram type
                  assign_values_to_leaves_edgePar(value= cleaned_mayo$Diagnosis, edgePar= "col") %>% # Color branches by diagnosis
                  as.ggdend()
</code>```

I then visualize this dendrogram using:

```<code># Plot dendrogram
ggplot(dend_expr, horiz= T, theme= NULL, labels= F) +
  ggtitle("Mayo Cohort: Hierarchical Clustering of Patients Colored by Diagnosis")
</code>```

My problem is that using this assign_values_to_leaves_edgePar branch coloring technique, the order of my diagnoses no longer matches the clustered expression data. Thus my branches are colored according to the diagnosis order, which is not correct for the now permuted samples.

How can I match the order of these dataframes after clustering or otherwise correctly label the branches?

Thank you!

答:
I have found a solution to this issue myself and will post it here in case it helps anyone in the future.

Starting with creating the dendrogram:

```<code># Create the dendrogram for visualization
dend_expr<- cleaned_mayo[,15:60739] %>% # Isolate expression data
                  scale %>% # Normalize
                  dist  %>% # Compute distance measure
                  hclust %>% # Cluster hierarchically
                  as.dendrogram()
</code>```

I can then arrange my original data in the same order as the new hierarchically clustered data:

```<code># Arrange labels in order with tree
tree_labels<- cleaned_mayo[order.dendrogram(dend_expr),]
</code>```

I can then color the branches of the dendrogram using this order:

```<code># Color branches by diagnosis
dend_expr<- assign_values_to_leaves_edgePar(dend_expr, value= tree_labels$Diagnosis, edgePar= "col") %>%
            as.ggdend()
</code>```

And then visualize the result:

```<code># Plot dendrogram
ggplot(dend_expr, horiz= T, theme= NULL, labels= F) +
  ggtitle("Mayo Cohort: Hierarchical Clustering of Patients Colored by Diagnosis")
</code>```

Body:
I have data called cleaned_mayo that looks like:

                        Source         Tissue RIN Diagnosis Gender  AgeAtDeath ApoE   FLOWCELL PMI N_unmapped N_multimapping N_noFeature N_ambiguous ENSG00000223972
1924_TCX MayoBrainBank_Dickson TemporalCortex 5.6   Control      F 90_or_above   33 AC5R6PACXX   2    2773880        9656114     8225967     2876479               1
1926_TCX MayoBrainBank_Dickson TemporalCortex 7.8   Control      F          88   33 AC44HKACXX   2    2279283       12410116     9503353     3600252               2
1935_TCX MayoBrainBank_Dickson TemporalCortex 8.6   Control      F          88   33 AC5T2GACXX   3    3120169        8650081     9640468     4603751               0
1925_TCX MayoBrainBank_Dickson TemporalCortex 6.6   Control      F          89   33 BC6178ACXX   4    2046886       10627577     7533671     3361385               1
1963_TCX MayoBrainBank_Dickson TemporalCortex 9.7   Control      M 90_or_above   33 AC5T1WACXX   4    1810116        9611375     5343437     2983079               2
         ENSG00000227232 ENSG00000278267 ENSG00000243485 ENSG00000274890 ENSG00000237613 ENSG00000268020 ENSG00000240361 ENSG00000186092 ENSG00000238009 ENSG00000239945
1924_TCX              80               7               1               0               0               0               0               0               3               0
1926_TCX             113              22               9               0               0               0               0               0               0               0
1935_TCX             181              21               2               0               0               0               0               0               0               0
1925_TCX              75               9               5               0               0               0               0               0               2               0
1963_TCX              73              14               1               0               0               0               0               0               3               0
         ENSG00000233750
1924_TCX              18
1926_TCX               2
1935_TCX               8
1925_TCX              20
1963_TCX              13

I hierarchically cluster the expression columns of this data using the following code:

# Create the dendrogram for visualization
dend_expr<- cleaned_mayo[,14:60738] %>% # Isolate expression data
                  scale %>% # Normalize
                  dist  %>% # Compute distance measure
                  hclust %>% # Cluster hierarchically
                  as.dendrogram %>% # Convert to dendrogram type
                  assign_values_to_leaves_edgePar(value= cleaned_mayo$Diagnosis, edgePar= "col") %>% # Color branches by diagnosis
                  as.ggdend()

I then visualize this dendrogram using:

# Plot dendrogram
ggplot(dend_expr, horiz= T, theme= NULL, labels= F) +
  ggtitle("Mayo Cohort: Hierarchical Clustering of Patients Colored by Diagnosis")

My problem is that using this assign_values_to_leaves_edgePar branch coloring technique, the order of my diagnoses no longer matches the clustered expression data. Thus my branches are colored according to the diagnosis order, which is not correct for the now permuted samples.

How can I match the order of these dataframes after clustering or otherwise correctly label the branches?

Thank you!

Body:
I have found a solution to this issue myself and will post it here in case it helps anyone in the future.

Starting with creating the dendrogram:

# Create the dendrogram for visualization
dend_expr<- cleaned_mayo[,15:60739] %>% # Isolate expression data
                  scale %>% # Normalize
                  dist  %>% # Compute distance measure
                  hclust %>% # Cluster hierarchically
                  as.dendrogram()

I can then arrange my original data in the same order as the new hierarchically clustered data:

# Arrange labels in order with tree
tree_labels<- cleaned_mayo[order.dendrogram(dend_expr),]

I can then color the branches of the dendrogram using this order:

# Color branches by diagnosis
dend_expr<- assign_values_to_leaves_edgePar(dend_expr, value= tree_labels$Diagnosis, edgePar= "col") %>%
            as.ggdend()

And then visualize the result:

# Plot dendrogram
ggplot(dend_expr, horiz= T, theme= NULL, labels= F) +
  ggtitle("Mayo Cohort: Hierarchical Clustering of Patients Colored by Diagnosis")


问:
How to access Windows.Services.Store from Delphi 7
I am selling Delphi app in Win 10 Store and like to start to use new buy in-app features. How to use Windows.Services.Store from Delphi 7 ?

Is there example code  for accessing StoreContext COM interface  ?

答:
You have to build a wrapper C++ component that makes the API calls into Windows.Services.Store.* APIs and exports entry points for your app to call. Then you include this component in your Delphi app package and call from your Delphi code into the exported entry points.

I don't have a Delphi 7 sample available, but here is a sample that is applying the same concept with a VB6 app:
https://github.com/Microsoft/DesktopBridgeToUWP-Samples/tree/master/Samples/VB6withXaml


问:
How to write a nice Low-Pass-Filter in Scala
I needed a Low-Pass-Filter in one of my Scala projects and came up with this:

```<code>def filter(numbers: Seq[Double], filterSize: Int): Seq[Double] = {
  assert(filterSize > 0)
  val ringBuffer = new Array[Double](filterSize)
  var ringBufferIndex = 0

  numbers.map(x => {
    // update ring buffer
    ringBuffer(ringBufferIndex) = x

    // increase ring index
    ringBufferIndex += 1
    if (ringBufferIndex == filterSize) {
      ringBufferIndex = 0
    }

    // get avarage
    ringBuffer.foldLeft(0.0)(_ + _) / filterSize
  })
}
</code>```

However, there are some things I don't like about it:

It uses map (nicely functional) but needs a mutable variable (ringBufferIndex - BAD).

It work's on Seq[Double] (which is fine), but returns Seq[Double], which is bad cause it requires the caller to call .toList or whatever he actually uses. I tried using Generics here like this:

def filter\[T <% Seq[Double]](numbers: T, filterSize: Int): T

but that would not compile.

Does anyone have suggestionts how to improve those two issues?

答:
OK, so I cleaned those up a little. There are three functions for three possible datatypes (which solves problem #2 automatically). I took those all from above (one for Array, one for List, one for Seq.):</p>

```<code>def filter(numbers: Seq[Double], filterSize: Int): Seq[Double] = {
  require(filterSize > 0)
  val ringBuffer = new Array[Double](filterSize)
  var ringBufferIndex = 0

  numbers.map(x => {
    // update ring buffer
    ringBuffer(ringBufferIndex) = x

    // increase ring index
    ringBufferIndex += 1
    if (ringBufferIndex == filterSize) {
      ringBufferIndex = 0
    }

    // get avarage
    ringBuffer.foldLeft(0.0)(_ + _) / filterSize
  })
}

def filter(numbers: Array[Double], filterSize: Int): Array[Double] = {
  require(filterSize > 0)
  (0 until numbers.length).map(x => {
    (((x - filterSize) max 0) to x).foldLeft(0.0)((sum, index) => sum + numbers(index)) / filterSize
  }).toArray
}

def filter(numbers: List[Double], filterSize: Int): List[Double] = {
  require(filterSize > 0)
  val ringBuffer = new Array[Double](filterSize)
  numbers.zipWithIndex.map(pair => {
    val (value, index) = pair
    // update ring buffer
    ringBuffer(index % filterSize) = value
    // get avarage
    ringBuffer.foldLeft(0.0)(_ + _) / filterSize
  })
}
</code>```

OwnerDisplayName: Lemmy

Body:
I needed a Low-Pass-Filter in one of my Scala projects and came up with this:

def filter(numbers: Seq[Double], filterSize: Int): Seq[Double] = {
  assert(filterSize > 0)
  val ringBuffer = new Array[Double](filterSize)
  var ringBufferIndex = 0

  numbers.map(x => {
    // update ring buffer
    ringBuffer(ringBufferIndex) = x

    // increase ring index
    ringBufferIndex += 1
    if (ringBufferIndex == filterSize) {
      ringBufferIndex = 0
    }

    // get avarage
    ringBuffer.foldLeft(0.0)(_ + _) / filterSize
  })
}

However, there are some things I don't like about it:

It uses map (nicely functional) but needs a mutable variable (ringBufferIndex - BAD).

It work's on Seq[Double] (which is fine), but returns Seq[Double], which is bad cause it requires the caller to call .toList or whatever he actually uses. I tried using Generics here like this:

def filter\[T <% Seq[Double]](numbers: T, filterSize: Int): T

but that would not compile.

Does anyone have suggestionts how to improve those two issues?

Body:
OK, so I cleaned those up a little. There are three functions for three possible datatypes (which solves problem #2 automatically). I took those all from above (one for Array, one for List, one for Seq.):

def filter(numbers: Seq[Double], filterSize: Int): Seq[Double] = {
  require(filterSize > 0)
  val ringBuffer = new Array[Double](filterSize)
  var ringBufferIndex = 0

  numbers.map(x => {
    // update ring buffer
    ringBuffer(ringBufferIndex) = x

    // increase ring index
    ringBufferIndex += 1
    if (ringBufferIndex == filterSize) {
      ringBufferIndex = 0
    }

    // get avarage
    ringBuffer.foldLeft(0.0)(_ + _) / filterSize
  })
}

def filter(numbers: Array[Double], filterSize: Int): Array[Double] = {
  require(filterSize > 0)
  (0 until numbers.length).map(x => {
    (((x - filterSize) max 0) to x).foldLeft(0.0)((sum, index) => sum + numbers(index)) / filterSize
  }).toArray
}

def filter(numbers: List[Double], filterSize: Int): List[Double] = {
  require(filterSize > 0)
  val ringBuffer = new Array[Double](filterSize)
  numbers.zipWithIndex.map(pair => {
    val (value, index) = pair
    // update ring buffer
    ringBuffer(index % filterSize) = value
    // get avarage
    ringBuffer.foldLeft(0.0)(_ + _) / filterSize
  })
}


问:
Move a div using keypresses and jquery?
Alright, so I'm trying to make a simple script that moves down a div when I press 's' but it's not firing at all. I got Jquery installed, and the error-console in FF isn't saying anything. Can someone tell me what I'm doing wrong?

http://prime.programming-designs.com/designs/map/

Title: Move a div using keypresses and jquery?

Body:
You forgot to put // before your HTML open comment tag <!--

You shouldn't use HTML comment tags for scripts anyway, the best method for inline styles/scripts is to use the CDATA element as follows:

/* <![CDATA[ */
//your code in here
/* ]]> */

This does a number of things:

allows XML entities to not need to be escaped

use of multi-line comments prevents any newline issues that may result in your script being parsed (CMS's will often adjust white-space)

creates valid XML when used in XHTML


问:
Reading & Breaking CSV File in Java:
I am editing this question to be more specific and I've learned some Jave to find the solution to my problem. I have a file in CSV format like this:
or in excel like this:
Now I am using Java program to read the second line of file and separate each Comma Separated Value and write it to console as well as on other output file and it was done easily. Now I'm trying to break the last value of:

S/1,M/1,L/1,XL/1 | 2XL/1,3XL/1,4XL/1,5XL/1 | MT/1,LT/1 (Original)
S/1,M/1,L/1,XL/1,2XL/1,3XL/1,4XL/1,5XL/1,MT/1,LT/1 (Modified using program to remove spaces and replacing the Pipes (|) with comma.

In each value, There is the size name before Forward Slash (/) and its quantity is after that. What I'm trying is using the Forward Slash (/) to separate the size with its quantity. And the problem is that the size may contain the forward slash as well (e.g. 12/BT or 2BT/2x). I've tried many algorithms like reversing the whole array or storing the slash count but not getting the success. The whole code to read file and break the comma separated values into separate columns of file is as following:

```<code>import java.io.*;
import javax.swing.*;
public class ReadFile3c{
public static void main(String args[]){
    try{
        //Getting File Name
        String fileName = JOptionPane.showInputDialog("Enter File Name") + ".csv";
        //Creating Stream with File
        FileReader fr = new FileReader(fileName);
        //Applying Buffer Filter
        BufferedReader br = new BufferedReader(fr);

        //Reading First line then Second Line
        String s = br.readLine();
        s = br.readLine();
        s = s + ",";//adding comma at the end of the file
        s = s.replaceAll("\\s",""); //Eliminating Spaces
        s = s.replaceAll("\\|",",");    //Replacing Pipes with comma
        char charArray[] = s.toCharArray();

        //Declaring Strings and variablse for value separating function
        int n = 0;                              //Array Variable
        int m = 0;                              //Array Variable
        String[] inverted = new String[3];      //String to store inverted Commas Values
        String[] comma = new String[10];        //String to store comma Values
        String value = "";                      //Storing character values

        try{
            //Loop to cycle each character of file
            for(int j = 0; j<charArray.length;j++){

                //Inverted comma value separator
                if (charArray[j] == '"') {
                    j++;
                    //loop to gather values b/w invreted comma
                    while((charArray[j] != '"')){
                        value = value + charArray[j];
                        j++;
                    }
                    inverted[n] = value;
                    n++;
                    j++;
                    value = "";
                }else{
                    j = j - 1;
                    //comma Value separator
                    if (charArray[j] == ','){
                        j++;
                        //loop to gether values b/w commas
                        while((charArray[j] !=',')){
                            value = value + charArray[j];
                            j++;
                        }
                        comma[m] = value;
                        m++;
                        value = "";
                    }
                }
            }
        }catch(Exception ex){
            System.out.println("in inner Exception Block" + ex);
        }

        //declaring variables to storing values
        String name, patternCode, placeSizeQty,width,length,utill,pArea,pPerimeter,totalPcs,placePcs,tSizes;
        name = inverted[0];
        patternCode = inverted[1];
        placeSizeQty = inverted[2];
        width = comma[0];
        length = comma[1];
        utill = comma[2];
        pArea = comma[3];
        pPerimeter = comma[4];
        totalPcs = comma[5];
        placePcs = comma[6];
        tSizes = comma[7];

        //printing all values on Console
        System.out.println("\nMarkerName: " + name);
        System.out.println("Width :" + width);
        System.out.println("Length :" + length);
        System.out.println("Utill :" + utill);
        System.out.println("Place Area :" + pArea);
        System.out.println("Place Perimeter :" + pPerimeter);
        System.out.println("PatternCode: " + patternCode);
        System.out.println("PlaceSizeQty: " + placeSizeQty);
        System.out.println("Total Pcs :" + totalPcs);
        System.out.println("Place Pcs :" + placePcs);
        System.out.println("Total Sizes :" + tSizes);

        //Creating Output file
        String fileOutput = JOptionPane.showInputDialog("Enter Output File Name") + ".txt";
        //File Writer
        try{
            //Creating Stream with output file
            FileWriter fw = new FileWriter(fileOutput);
            //Applying Buffring Stream
            PrintWriter pw = new PrintWriter(fw);
            //Declaration
            String outputLine = null;
            //Writing Inverted inputs
            for (int u = 0; u <=2 ;u++ ) {
                outputLine = inverted[u];
                pw.println(outputLine);
                System.out.println("Writing: " + outputLine);
            }//end of for
            //writing comma inputs
            for (int t = 0;t <=7  ; t++ ) {
                outputLine = comma[t];
                pw.println(outputLine);
                System.out.println("Writing: " + outputLine);
            }//end of for

            pw.flush();
            pw.close();
            fw.close();
            fr.close();
            br.close();

        }catch(Exception ex){
            System.out.println("Output: " + ex);
        }//End of output catch

    }catch(IOException ex){
        System.out.println(ex);
    }//end of catch
}//end of catch
}//end of Class
</code>```

And the code to Break the Size and quantity and store it in Double array (Not completed) is as Following:

```<code>import java.io.*;
import javax.swing.*;
public class ReadFileInvert{
public static void main(String args[]){
    try{
        String fileName = JOptionPane.showInputDialog("Enter File Name") + ".csv";
        FileReader fr = new FileReader(fileName);
        BufferedReader br = new BufferedReader(fr);
    String s = br.readLine();
        System.out.println(s);
        s = s.replaceAll("\\s","");
        s = s.replaceAll("\\|",",");
    System.out.println(s);

        char charArray[] = s.toCharArray();
        char charArrayI[] = new char[charArray.length + 1];

        int j = 0;
        String value = "";

        for(int i = charArray.length; i > 0; i--){
            charArrayI[j] = charArray[i];
            value = value + charArrayI[j];
            j++;
        }
        System.out.println("1" + value);

    }catch(Exception ex){
        System.out.println(ex);
    }
}
}
</code>```

Now in simple I just want to Separate the sizes (Which may contains the Forward Slashes) with its quantity (After last slash of each value) and store it in double array Like charArray[sizeName][Qty]. Sorry if i didn't explained my problem well as I'm Learning the Coding. but I'll provide as much info as you want.

答: Have you considered looking at the CAD software export to see if there is a solution on the file creation side? Or is this file coming from a third party?</p>

Title: Reading & Breaking CSV File in Java:

Body:
I am editing this question to be more specific and I've learned some Jave to find the solution to my problem. I have a file in CSV format like this:
or in excel like this:
Now I am using Java program to read the second line of file and separate each Comma Separated Value and write it to console as well as on other output file and it was done easily. Now I'm trying to break the last value of:

S/1,M/1,L/1,XL/1 | 2XL/1,3XL/1,4XL/1,5XL/1 | MT/1,LT/1 (Original)
S/1,M/1,L/1,XL/1,2XL/1,3XL/1,4XL/1,5XL/1,MT/1,LT/1 (Modified using program to remove spaces and replacing the Pipes (|) with comma.

In each value, There is the size name before Forward Slash (/) and its quantity is after that. What I'm trying is using the Forward Slash (/) to separate the size with its quantity. And the problem is that the size may contain the forward slash as well (e.g. 12/BT or 2BT/2x). I've tried many algorithms like reversing the whole array or storing the slash count but not getting the success. The whole code to read file and break the comma separated values into separate columns of file is as following:

import java.io.*;
import javax.swing.*;
public class ReadFile3c{
public static void main(String args[]){
    try{
        //Getting File Name
        String fileName = JOptionPane.showInputDialog("Enter File Name") + ".csv";
        //Creating Stream with File
        FileReader fr = new FileReader(fileName);
        //Applying Buffer Filter
        BufferedReader br = new BufferedReader(fr);

        //Reading First line then Second Line
        String s = br.readLine();
        s = br.readLine();
        s = s + ",";//adding comma at the end of the file
        s = s.replaceAll("\\s",""); //Eliminating Spaces
        s = s.replaceAll("\\|",",");    //Replacing Pipes with comma
        char charArray[] = s.toCharArray();

        //Declaring Strings and variablse for value separating function
        int n = 0;                              //Array Variable
        int m = 0;                              //Array Variable
        String[] inverted = new String[3];      //String to store inverted Commas Values
        String[] comma = new String[10];        //String to store comma Values
        String value = "";                      //Storing character values

        try{
            //Loop to cycle each character of file
            for(int j = 0; j<charArray.length;j++){

                //Inverted comma value separator
                if (charArray[j] == '"') {
                    j++;
                    //loop to gather values b/w invreted comma
                    while((charArray[j] != '"')){
                        value = value + charArray[j];
                        j++;
                    }
                    inverted[n] = value;
                    n++;
                    j++;
                    value = "";
                }else{
                    j = j - 1;
                    //comma Value separator
                    if (charArray[j] == ','){
                        j++;
                        //loop to gether values b/w commas
                        while((charArray[j] !=',')){
                            value = value + charArray[j];
                            j++;
                        }
                        comma[m] = value;
                        m++;
                        value = "";
                    }
                }
            }
        }catch(Exception ex){
            System.out.println("in inner Exception Block" + ex);
        }

        //declaring variables to storing values
        String name, patternCode, placeSizeQty,width,length,utill,pArea,pPerimeter,totalPcs,placePcs,tSizes;
        name = inverted[0];
        patternCode = inverted[1];
        placeSizeQty = inverted[2];
        width = comma[0];
        length = comma[1];
        utill = comma[2];
        pArea = comma[3];
        pPerimeter = comma[4];
        totalPcs = comma[5];
        placePcs = comma[6];
        tSizes = comma[7];

        //printing all values on Console
        System.out.println("\nMarkerName: " + name);
        System.out.println("Width :" + width);
        System.out.println("Length :" + length);
        System.out.println("Utill :" + utill);
        System.out.println("Place Area :" + pArea);
        System.out.println("Place Perimeter :" + pPerimeter);
        System.out.println("PatternCode: " + patternCode);
        System.out.println("PlaceSizeQty: " + placeSizeQty);
        System.out.println("Total Pcs :" + totalPcs);
        System.out.println("Place Pcs :" + placePcs);
        System.out.println("Total Sizes :" + tSizes);

        //Creating Output file
        String fileOutput = JOptionPane.showInputDialog("Enter Output File Name") + ".txt";
        //File Writer
        try{
            //Creating Stream with output file
            FileWriter fw = new FileWriter(fileOutput);
            //Applying Buffring Stream
            PrintWriter pw = new PrintWriter(fw);
            //Declaration
            String outputLine = null;
            //Writing Inverted inputs
            for (int u = 0; u <=2 ;u++ ) {
                outputLine = inverted[u];
                pw.println(outputLine);
                System.out.println("Writing: " + outputLine);
            }//end of for
            //writing comma inputs
            for (int t = 0;t <=7  ; t++ ) {
                outputLine = comma[t];
                pw.println(outputLine);
                System.out.println("Writing: " + outputLine);
            }//end of for

            pw.flush();
            pw.close();
            fw.close();
            fr.close();
            br.close();

        }catch(Exception ex){
            System.out.println("Output: " + ex);
        }//End of output catch

    }catch(IOException ex){
        System.out.println(ex);
    }//end of catch
}//end of catch
}//end of Class

And the code to Break the Size and quantity and store it in Double array (Not completed) is as Following:

import java.io.*;
import javax.swing.*;
public class ReadFileInvert{
public static void main(String args[]){
    try{
        String fileName = JOptionPane.showInputDialog("Enter File Name") + ".csv";
        FileReader fr = new FileReader(fileName);
        BufferedReader br = new BufferedReader(fr);
    String s = br.readLine();
        System.out.println(s);
        s = s.replaceAll("\\s","");
        s = s.replaceAll("\\|",",");
    System.out.println(s);

        char charArray[] = s.toCharArray();
        char charArrayI[] = new char[charArray.length + 1];

        int j = 0;
        String value = "";

        for(int i = charArray.length; i > 0; i--){
            charArrayI[j] = charArray[i];
            value = value + charArrayI[j];
            j++;
        }
        System.out.println("1" + value);

    }catch(Exception ex){
        System.out.println(ex);
    }
}
}

Now in simple I just want to Separate the sizes (Which may contains the Forward Slashes) with its quantity (After last slash of each value) and store it in double array Like charArray[sizeName][Qty]. Sorry if i didn't explained my problem well as I'm Learning the Coding. but I'll provide as much info as you want.


问:
Add multiple Layers to audio recording with PyAudio
Im been experimenting with audio recording and playback using pyaudio.

I'm able to record a file but I need to be able to add layers on top of it.  What I'm trying to do is record a 10 second file then start playing.

While its playing I want to continue to record additional 10 sec layers and add them over top of the prior recording.

Is there a way to do this with Python?

```<code>import pyaudio
import wave

CHUNK = 2
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 3
WAVE_OUTPUT_FILENAME = "output.wav"

p = pyaudio.PyAudio()

stream = p.open(format=FORMAT,
                channels=CHANNELS,
                rate=RATE,
                input=True,
                frames_per_buffer=CHUNK)

print("* recording")

frames = []

for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream.read(CHUNK)
    frames.append(data)

print(int(RATE / CHUNK * RECORD_SECONDS))

print("* done recording")

stream.stop_stream()
stream.close()
p.terminate()

wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()
</code>```

答:
I found a module called "PyDub" which does this easily.

http://pydub.com/

```<code>from pydub import AudioSegment

track1 = AudioSegment.from_file(track1wav)
track2 = AudioSegment.from_file(track2wav)

combined = track1.overlay(track2)
print ("overlaying recording")
combined.export(track1wav, format='wav')
</code>```

Body:
Im been experimenting with audio recording and playback using pyaudio.

I'm able to record a file but I need to be able to add layers on top of it.  What I'm trying to do is record a 10 second file then start playing.

While its playing I want to continue to record additional 10 sec layers and add them over top of the prior recording.

Is there a way to do this with Python?

import pyaudio
import wave

CHUNK = 2
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 3
WAVE_OUTPUT_FILENAME = "output.wav"

p = pyaudio.PyAudio()

stream = p.open(format=FORMAT,
                channels=CHANNELS,
                rate=RATE,
                input=True,
                frames_per_buffer=CHUNK)

print("* recording")

frames = []

for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream.read(CHUNK)
    frames.append(data)

print(int(RATE / CHUNK * RECORD_SECONDS))

print("* done recording")

stream.stop_stream()
stream.close()
p.terminate()

wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()

Body:
I found a module called "PyDub" which does this easily.

http://pydub.com/

from pydub import AudioSegment

track1 = AudioSegment.from_file(track1wav)
track2 = AudioSegment.from_file(track2wav)

combined = track1.overlay(track2)
print ("overlaying recording")
combined.export(track1wav, format='wav')


问:
How to extract and format the string in a python data-frame
I am new in Python and I would like to extract a certain kind of string data from my data frame. Here is my data frame:

I want to extract the first letter in the cabin column(like A,B,C,D...) and add it as a new feature column named as CabinCapital in the data frame. How could I do it? For instance, row 460 should have a feature CabinCapital which contains a letter "E".(if the cabin value is empty("NAN"), the cabinCapital is empty as well)

答:
Assuming the letter to extract is always the first character in the string, the following should help.

```<code>df['CabinCapital'] = df['Cabin'].str[0]
</code>```

This also assumes your DataFrame is called df.

Body:
Assuming the letter to extract is always the first character in the string, the following should help.

df['CabinCapital'] = df['Cabin'].str[0]

This also assumes your DataFrame is called df.


问:
openssl: how to find the config options that openssl was compiled with
Is there an easier way to figure out the options specified during building openssl such as whether OPENSSL_NO_SRTP was defined at that time?
I can only gleam limited information from the:

```<code>openssl version -a
</code>```

command. However if I have just the binaries, is there a way to figure out options such as these? The reason behind this question is that there is a vulnerability "CVE-2014-3513" that is introduced if openssl is not compiled with this option.

答:
You can get most (all?) of the configuration information about the installed openssl via the version command. In particular,

```<code>openssl version -f
</code>```

will list all the complier flags that were specified at build time.

Body:
Is there an easier way to figure out the options specified during building openssl such as whether OPENSSL_NO_SRTP was defined at that time?
I can only gleam limited information from the:

openssl version -a

command. However if I have just the binaries, is there a way to figure out options such as these? The reason behind this question is that there is a vulnerability "CVE-2014-3513" that is introduced if openssl is not compiled with this option.

Body:
You can get most (all?) of the configuration information about the installed openssl via the version command. In particular,

openssl version -f

will list all the complier flags that were specified at build time.


问:
how to say 60 seconds with currentTimeMilis()
I'm trying to type out a code that outputs random words from a list, the user must type back as many words as possible before 60 seconds has elapsed I am using currentTimeMillis() to keep track of time so this is difficult for me to figure out I tried the code below and it said 6000000000000 is too large of a number but when I output the current/start time, it output 1512409897444 so this doesn't make sense to me.

```<code>long currentTime = System.currentTimeMillis();
long startTime = System.currentTimeMillis();
System.out.println(currentTime);
System.out.println(startTime);
while (startTime <= 6000000000000)
{
    (etc.  ect.)
}
</code>```

答:
As others have already answered you have to subtract the starting time to the current time to determine if the difference is greather than 60 seconds (60,000 milliseconds). Also you can use TimeUnit to get a more readeable code:

```<code>long startTime = System.currentTimeMillis();
while (TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - startTime) <= 60) {
    //do stuff
}
</code>```

EDIT

If you are wondering why 6000000000000 gives you an error and the result of currentTimeMillis() (1512409897444) doesn't, is because they are different datatypes: int (32 bits) vs long (64 bits). The literal value 6000000000000 is interpreted as an int value which is greather than the max supported 32-bit signed int value (2,147,483,647) and the compiler doesn't allow that. It would work if you use a long literal instead 6000000000000L (note the L at the end).  Signed long's max supported value is 9,223,372,036,854,775,807. The result of System.currentTimeMillis() is a long value hence 1512409897444 is valid. Read Primitive Data Types for further information.

Body:
I'm trying to type out a code that outputs random words from a list, the user must type back as many words as possible before 60 seconds has elapsed I am using currentTimeMillis() to keep track of time so this is difficult for me to figure out I tried the code below and it said 6000000000000 is too large of a number but when I output the current/start time, it output 1512409897444 so this doesn't make sense to me.

long currentTime = System.currentTimeMillis();
long startTime = System.currentTimeMillis();
System.out.println(currentTime);
System.out.println(startTime);
while (startTime <= 6000000000000)
{
    (etc.  ect.)
}

Body:
As others have already answered you have to subtract the starting time to the current time to determine if the difference is greather than 60 seconds (60,000 milliseconds). Also you can use TimeUnit to get a more readeable code:

long startTime = System.currentTimeMillis();
while (TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - startTime) <= 60) {
    //do stuff
}

EDIT

If you are wondering why 6000000000000 gives you an error and the result of currentTimeMillis() (1512409897444) doesn't, is because they are different datatypes: int (32 bits) vs long (64 bits). The literal value 6000000000000 is interpreted as an int value which is greather than the max supported 32-bit signed int value (2,147,483,647) and the compiler doesn't allow that. It would work if you use a long literal instead 6000000000000L (note the L at the end).  Signed long's max supported value is 9,223,372,036,854,775,807. The result of System.currentTimeMillis() is a long value hence 1512409897444 is valid. Read Primitive Data Types for further information.