text:
Q: Solving 2Sat CNF form using brute force I'm currently studying the 2SAT problem for an exam and I don't really understand how to check if a solution exists using the brute force. I know this seems a bit strange but I understand how to implement the implication graph a bit better but I'm not too sure how to implement a brute force strategy.
Could anyone share some insight? Maybe in pseudo code or java.
Thanks

A: The variables in a formula can be encoded as bits in an integral value. The brute force method then boils down to range over all possible values that the integral "container" may take.
In other words, you have an array of integers, which represents all your formula's variables, and you increment the integers with carry, and at each step check the solution it represents against your formula. You stop when the solution is a match.
Here's a dead simple implementation for such a variable container:
class OverflowException extends RuntimeException {}

public class Variables {
    int[] data;
    int size;

    public Variables(int size_){
        size = size_;
        data = new int[1 + size/32];
    }
    public boolean get(int i){
         return (data[i/32] & (1 << i%32)) != 0;
    }
    public void set(int i, boolean v){
        if (v)
            data[i/32] |= (1 << i%32);
        else
            data[i/32] &= ~(1 << i%32);
    }
    public void increment(){
         int i;
         for (i=0; i < size/32; i++){
             data[i]++;
             if (data[i] != 0) return;
         }
         if (size%32 != 0){
             data[i]++;
             if ((data[i] & ~((1 << (size%32)) - 1)) != 0)
                 throw new OverflowException();
        }
    }
}

(Caveat emptor: code untested).
The variable array can also be more simply represented as a boolean container, but you might lose a bit in performance, because of the increment step (although that could be perhaps mitigated by using gray code instead of plain binary encoding for the increment operation, but the complexity of this implementation seems to indicate the contrary, and if you go for a complex solution, it might as well be a good sat2 solver instead).

A: This is the reason we don't use brute force solutions :) , they consume to much resources.
My algorithm would be not to create a matrix with all possibilities. But to create one assignment and then test it immediately. Then create the next one. You can halt when you found the first solution.


text:
Q: How full is my ZFS pool? (not sure how to read command output) I'm using ZFS on FreeBSD to store several TB of data.
If stored as non-dedup, about 25% of the raw data would be unique enough that compression helps but dedup is wasted.
The other 75% contains a lot of dedup-able data, and I've had ratios of 2x - 8x with this dataset in the past. So my NAS was specced from the start to be able to handle compressed dedup if needed: 96GB 2400 ECC (more can be added if stats show dedup table pressure), 3.5GHz quad core Xeon, mirrored disks, NVMe L2ARC, and Intel P3700 NVMe ZIL.
The raw pool capacity is currently 22 GB before formatting (3 x 6TB vdevs + 1 x 4TB vdev) and intuitively I think I'm physically using about 7 - 14 TB of it right now. It contains both Samba file share datasets and fixed-size ESXi iSCSI zvols (mostly empty, at least one sparse). But because I don't understand the difference between these outputs, they are confusing me, and I'm not sure how much free space I actually have, and therefore whether I want to add more disks to keep it below my target of 65% usage:
# zpool list -v
NAME                                     SIZE  ALLOC   FREE  EXPANDSZ   FRAG    CAP  DEDUP  HEALTH  ALTROOT
tank                                    19.9T  14.0T  5.93T         -    53%    70%  2.30x  ONLINE  /mnt
  mirror                                5.44T  4.18T  1.26T         -    59%    76%
    gptid/6c62bc1a-0b7b-11e7-86ae-000743144400      -      -      -         -      -      -
    gptid/94cad523-0b45-11e7-86ae-000743144400      -      -      -         -      -      -
  mirror                                5.41T  4.38T  1.03T         -    62%    80%
    ada0p2                                  -      -      -         -      -      -
    gptid/e619dab7-03f1-11e7-8f93-000743144400      -      -      -         -      -      -
  mirror                                5.44T  4.12T  1.32T         -    56%    75%
    gptid/c68f80ae-01da-11e7-b762-000743144400      -      -      -         -      -      -
    da0                                     -      -      -         -      -      -
    da1                                     -      -      -         -      -      -
  mirror                                3.62T  1.31T  2.32T         -    29%    36%
    da3                                     -      -      -         -      -      -
    da4                                     -      -      -         -      -      -

# zdb -bDDD tank
DDT-sha256-zap-duplicate: 39468847 entries, size 588 on disk, 190 in core

     [duplicate bucket data cut as it isn't relevant and repeats in the totals below]

DDT-sha256-zap-unique: 60941882 entries, size 526 on disk, 170 in core

bucket              allocated                       referenced
______   ______________________________   ______________________________
refcnt   blocks   LSIZE   PSIZE   DSIZE   blocks   LSIZE   PSIZE   DSIZE
------   ------   -----   -----   -----   ------   -----   -----   -----
     1    58.1M   1.21T    964G   1005G    58.1M   1.21T    964G   1005G
     2    25.0M   1.10T    784G    807G    58.5M   2.69T   1.87T   1.92T
     4    10.4M    393G    274G    282G    48.4M   1.85T   1.29T   1.34T
     8    1.70M   51.1G   37.7G   39.7G    16.5M    487G    353G    372G
    16     456K   9.85G   5.73G   6.44G    10.1M    212G    121G    138G
    32    67.0K   1.73G    998M   1.07G    2.77M   77.1G   44.6G   48.6G
    64    23.7K    455M    327M    350M    1.98M   36.1G   25.8G   27.7G
   128    3.47K   75.7M   48.0M   54.5M     557K   12.1G   7.68G   8.70G
   256      610   46.9M   12.3M   13.6M     216K   16.9G   4.14G   4.61G
   512      211   14.8M   2.46M   3.01M     145K   10.2G   1.72G   2.10G
    1K       57   1.10M     38K    228K    77.7K   1.45G   49.3M    311M
    2K       42    456K     22K    168K     118K   1.17G   61.3M    474M
    4K       18    108K      9K     72K     104K    574M   52.1M    417M
    8K       11    128K   5.50K     44K     117K   1.29G   58.3M    467M
   16K        7    152K      4K     28K     155K   2.60G   85.6M    619M
  128K        1     16K     512      4K     137K   2.14G   68.4M    548M
  256K        1      4K     512      4K     302K   1.18G    151M   1.18G
 Total    95.8M   2.76T   2.02T   2.09T     198M   6.59T   4.65T   4.83T

dedup = 2.31, compress = 1.42, copies = 1.04, dedup * compress / copies = 3.15

*

*The first output seems to be saying that the formatted pool capacity is 19.9TB (sounds about right) of which space in use is around 14TB and 5.93TB is spare. If so, I'll add more disks.

*The second output seems to be saying that the actual allocated physical space is around 2.02TB (or 6.59TB with 3.15x saving due to compression+dedup).
The two numbers are wildly different, and I don't understand how to reconcile them.
Hint appreciated please!

A:
The two numbers are wildly different, and I don't understand how to reconcile them.
Hint appreciated please!

The zpool output is correct.
The other command you might be interested in is zfs list.

A: The definitive way to check how full your pool is, is to ask it:
$ zpool get capacity tank
NAME      PROPERTY  VALUE  SOURCE
tank      capacity  60%    -

If you prefer, you can do the math yourself:
$ zpool get -p allocated,size tank
NAME      PROPERTY   VALUE         SOURCE
tank      allocated  596675149824  -
tank      size       987842478080  -
$ bc
scale=4
59667514982400/987842478080
60.4018

redpajama_set_name: RedPajamaStackExchange


text:
Q: Classical models with unbounded particle number Is there any classical model which deals with the birth, life and death of particles? What application could it have?
I am talking about a 'billiard-ball' kind of model, but the kind in which balls keep popping in and out.
What would the configuration space of such a system be like if particle number was not conserved? How would the Hamiltonian evolve with time?
I am not interested in a statistical models.
I can't think of any real world application of such a model. But perhaps there is a mathematical apparatus to deal with the continuous evolution of such systems?


text:
Q: TextWatcher - addTextChangedListener add several listeners I need to add some text update for an edit text after a user enters in input. I thought about using another TextWatcher to existing ones. Is there a way to be sure my TextWatcher occurs before the other one that was used (when I have several TextWatchers)

A: They should trigger in the order that you added them. But this is not guaranteed. If you need a guarantee just chain them manually i.e. have one 'SuperTextWatcher' that delegates the event to the others. See code where the watchers are called


text:
Q: Long polling timer I am new to long polling and don't quite grasp it's method. I already have a timer function in javascript that is controlled with buttons on one page [Code Below]. I want the same timer to run simultaneously on multiple pages (that can be on different computers and browsers). Except it will be controlled with buttons only from this page (timerMode.php). How could I do this with long pooling?
Note: I use phpMyAdmin SQL Database. The same svg will be used for every timer
timerMode.php:

var timerMode = function() {
  var timergc;
  var runningsc = false;
  var runninggc = false;
  var endedsc = false;
  var edndedgc = false;
  var startTimer = function(seconds, container, oncomplete, type) {
    var startTime, timer, obj, ms = seconds * 1000;
    var paused = false;
    var display = document.getElementById(container);
    obj = {};
    obj.resume = function() {
      paused = false;
      startTime = new Date().getTime();
      timer = setInterval(obj.step, 100);
    };
    obj.pause = function() {
      if (!paused) {
        paused = true;
        ms = obj.step();
        clearInterval(timer);
      }
    };
    obj.reset = function(res) {
      ms = res * 1000;
      m = Math.floor(ms / 60000), s = Math.floor(ms / 1000) % 60;
      switch (type) {
        case "game":
          if (m == 0) {
            var mili = String(now % 1000).charAt(0);
            display.innerHTML = s + "." + mili;
          } else {
            s = (s < 10 ? "0" : "") + s;
            display.innerHTML = m + ":" + s;
          }
          break;
        case "shot":
          if (s <= 4) {
            var mili = String(now % 1000).charAt(0);
            display.innerHTML = s + "." + mili;
          } else display.innerHTML = s;
          break;
      }
    };
    obj.modify = function(diff) {
      if (diff == 1) {
        if (ms < seconds * 1000) {
          ms += diff * 1000;
          m = Math.floor(ms / 60000), s = Math.floor(ms / 1000) % 60;
          if (type == "shot") {
            if (s <= 4) {
              var mili = String(ms % 1000).charAt(0);
              display.innerHTML = s + "." + mili;
            } else display.innerHTML = s;
          } else {
            if (m == 0) {
              var mili = String(now % 1000).charAt(0);
              display.innerHTML = s + "." + mili;
            } else {
              s = (s < 10 ? "0" : "") + s;
              display.innerHTML = m + ":" + s;
            }
          }
        }
      } else {
        if (Math.floor(ms / 1000) % 60 > 0) {
          ms += diff * 1000;
          m = Math.floor(ms / 60000), s = Math.floor(ms / 1000) % 60;
          if (type == "shot") {
            if (s <= 4) {
              var mili = String(ms % 1000).charAt(0);
              display.innerHTML = s + "." + mili;
            } else display.innerHTML = s;
          } else {
            if (m == 0) {
              var mili = String(now % 1000).charAt(0);
              display.innerHTML = s + "." + mili;
            } else {
              s = (s < 10 ? "0" : "") + s;
              display.innerHTML = m + ":" + s;
            }
          }
        }
      }
    };
    obj.step = function() {
      var now = Math.max(0, ms - (new Date().getTime() - startTime)),
        m = Math.floor(now / 60000),
        s = Math.floor(now / 1000) % 60;
      switch (type) {
        case "game":
          if (m == 0) {
            var mili = String(now % 1000).charAt(0);
            display.innerHTML = s + "." + mili;
          } else {
            s = (s < 10 ? "0" : "") + s;
            display.innerHTML = m + ":" + s;
          }
          break;
        case "shot":
          if (s <= 4) {
            var mili = String(now % 1000).charAt(0);
            display.innerHTML = s + "." + mili;
          } else display.innerHTML = s;
          break;
      }
      if (now == 0) {
        clearInterval(timer);
        if (type == "shot") {
          runningsc = false;
          runninggc = false;
          endedsc = true;
        }
        if (oncomplete) oncomplete();
      }
      return now;
    };
    obj.resume();
    return obj;
  };
  $(document).on("click", "#start", function() {
    timergc = startTimer(600, "game_clock", function() {}, "game");
    timersc = startTimer(24, "shot_clock", function() {}, "shot");
    runningsc = true;
    runninggc = true;
    $(".gcbtn_main").text("Pause");
    $(".gcbtn_main").attr("id", "pausegc");
    $(".scbtn_main").text("Pause");
    $(".scbtn_main").attr("id", "pausesc");
  });
  $(document).on("click", "#pausegc", function() {
    timergc.pause();
    timersc.pause();
    runningsc = false;
    runninggc = false;
    $(".gcbtn_main").text("Resume");
    $(".gcbtn_main").attr("id", "resumegc");
    $(".scbtn_main").text("Resume");
    $(".scbtn_main").attr("id", "resumesc");
  });
  $(document).on("click", "#resumegc", function() {
    timergc.resume();
    runninggc = true;
    if (!runningsc) {
      timersc.resume();
      runningsc = true;
    }
    $(".gcbtn_main").text("Pause");
    $(".gcbtn_main").attr("id", "pausegc");
    $(".scbtn_main").text("Pause");
    $(".scbtn_main").attr("id", "pausesc");
  });
  $(document).on("click", "#resetgc", function() {
    timergc.pause();
    timergc.reset(600);
    timersc.pause();
    timersc.reset(24);
    $(".gcbtn_main").text("Start");
    $(".gcbtn_main").attr("id", "resumegc");
    $(".scbtn_main").text("Pause");
    $(".scbtn_main").attr("id", "pausesc");
  });
  $(document).on("click", "#upgc", function() {
    console.log(runninggc);
    timergc.pause();
    timergc.modify(1);
    if (runninggc) {
      timergc.resume();
    }
  });
  $(document).on("click", "#downgc", function() {
    timergc.pause();
    timergc.modify(-1);
    if (runninggc) {
      timergc.resume();
    }
  });
  $(document).on("click", "#pausesc", function() {
    timersc.pause();
    runningsc = false;
    $(".scbtn_main").text("Resume");
    $(".scbtn_main").attr("id", "resumesc");
  });
  $(document).on("click", "#resumesc", function() {
    timersc.resume();
    runningsc = true;
    $(".scbtn_main").text("Pause");
    $(".scbtn_main").attr("id", "pausesc");
  });
  $(document).on("click", "#reset14", function() {
    timersc.pause();
    timersc.reset(14);
    if (runningsc) {
      timersc.resume();
    }
    if (endedsc) {
      $(".scbtn_main").text("Resume");
      $(".scbtn_main").attr("id", "resumesc");
    }
  });
  $(document).on("click", "#reset24", function() {
    timersc.pause();
    timersc.reset(24);
    if (runningsc) {
      timersc.resume();
    }
    if (endedsc) {
      $(".scbtn_main").text("Resume");
      $(".scbtn_main").attr("id", "resumesc");
    }
  });
  $(document).on("click", "#upsc", function() {
    timersc.pause();
    timersc.modify(1);
    endedsc = false;
    if (runningsc) {
      timersc.resume();
    }
  });
  $(document).on("click", "#downsc", function() {
    timersc.pause();
    timersc.modify(-1);
    endedsc = false;
    if (runningsc) {
      timersc.resume();
    }
  });
  $(document).on("click", "#upqrt", function() {
    console.log("Works");
    var quarter = $("#quarter").text();
    console.log(quarter);
    if (quarter == 4) {
      $("#quarter").text("E");
    }
    if (quarter < 4) {
      console.log(quarter);
      quarter++;
      $("#quarter").text(quarter);
    }
  });
  $(document).on("click", "#downqrt", function() {
    var quarter = $("#quarter").text();
    if (quarter == "E") {
      $("#quarter").text(4);
    }
    if (quarter > 1) {
      quarter--
      $("#quarter").text(quarter);
    }
  });
};
$(document).ready(function() {
  timerMode();
});

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

      <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 432.7 198" style="enable-background:new 0 0 432.7 198;background:white;" xml:space="preserve">

        <path id="XMLID_12_" class="st0" d="M125.9,114.8H44.1c-2.3,0-4.2-1.9-4.2-4.2V73.4c0-2.3,1.9-4.2,4.2-4.2h81.8c2.3,0,4.2,1.9,4.2,4.2v37.2C130.1,112.9,128.2,114.8,125.9,114.8z" />
        <rect id="XMLID_9_" x="39.9" y="69.2" class="st1" width="90.2" height="45.6" />
        <text id="XMLID_10_" transform="matrix(1 0 0 1 99.3335 111.792)" class="st2 st3">0</text>
        <path id="XMLID_16_" class="st0" d="M387.9,114.8h-81.8c-2.3,0-4.2-1.9-4.2-4.2V73.4c0-2.3,1.9-4.2,4.2-4.2h81.8
      c2.3,0,4.2,1.9,4.2,4.2v37.2C392.1,112.9,390.2,114.8,387.9,114.8z" />

        <rect id="home_rect" x="7.1" y="6.8" class="st1" width="129.8" height="36.3"></rect>
        <text id="home_name" transform="matrix(1 0 0 1 7.0877 38.7791)" class="st2 st5">HOME</text>
        <rect id="XMLID_20_" x="42" y="159.5" class="st1" width="60.9" height="16.5" />
        <text id="XMLID_19_" transform="matrix(1 0 0 1 42.0301 173.6536)" class="st2 st6">FOULS:</text>
        <rect id="XMLID_22_" x="112.5" y="160.5" class="st1" width="10.7" height="16" />
        <text id="XMLID_21_" transform="matrix(1 0 0 1 112.4562 174.6557)" class="st2 st6">0</text>
        <rect id="XMLID_33_" x="186.7" y="145.9" class="st1" width="59.4" height="36.6" />
        <text id="shot_clock" transform="matrix(1 0 0 1 191.8234 179.9915)" class="st2 st7">24</text>
        <rect id="away_rect" x="295.1" y="6.8" class="st1" width="129.8" height="36.3" />
        <text id="away_name" transform="matrix(1 0 0 1 295.0877 38.7791)" class="st2 st5">AWAY</text>
        <rect id="XMLID_5_" x="153.2" y="6.8" class="st1" width="125.6" height="36.3" />
        <text id="game_clock" transform="matrix(0.8828 0 0 1 165.1738 43.0225)" class="st2 st8">10:00</text>
        <rect id="XMLID_15_" x="301.9" y="69.2" class="st1" width="90.2" height="45.6" />
        <text id="XMLID_14_" transform="matrix(1 0 0 1 301.8873 111.792)" class="st2 st3">0</text>
        <g id="XMLID_11_">
          <text id="quarter" transform="matrix(1 0 0 1 209.3371 99.3377)" class="st9 st2 st10">1</text>
        </g>
        <path id="XMLID_13_" class="st11" d="M221,103.6h-10.4c-2.3,0-4.2-1.9-4.2-4.2V83.2c0-2.3,1.9-4.2,4.2-4.2H221
      c2.3,0,4.2,1.9,4.2,4.2v16.2C225.2,101.7,223.3,103.6,221,103.6z" />
        <path id="XMLID_18_" class="st11" d="M123,180.7h-10.4c-2.3,0-4.2-1.9-4.2-4.2v-16.2c0-2.3,1.9-4.2,4.2-4.2H123
      c2.3,0,4.2,1.9,4.2,4.2v16.2C127.2,178.9,125.3,180.7,123,180.7z" />
        <path id="XMLID_31_" class="st11" d="M245.2,186.3h-57.3c-2.3,0-4.2-1.9-4.2-4.2v-36.7c0-2.3,1.9-4.2,4.2-4.2h57.3
      c2.3,0,4.2,1.9,4.2,4.2v36.7C249.4,184.4,247.5,186.3,245.2,186.3z" />
        <rect id="XMLID_30_" x="300.7" y="158.7" class="st1" width="60.9" height="16.5" />
        <text id="XMLID_29_" transform="matrix(1 0 0 1 300.6767 172.9018)" class="st2 st6">FOULS:</text>
        <rect id="XMLID_28_" x="371.1" y="159.7" class="st1" width="10.7" height="16" />
        <text id="XMLID_26_" transform="matrix(1 0 0 1 371.1028 173.9038)" class="st2 st6">0</text>
        <path id="XMLID_23_" class="st11" d="M381.7,180h-10.4c-2.3,0-4.2-1.9-4.2-4.2v-16.2c0-2.3,1.9-4.2,4.2-4.2h10.4
      c2.3,0,4.2,1.9,4.2,4.2v16.2C385.9,178.1,384,180,381.7,180z" />
        <circle id="XMLID_17_" cx="155" cy="91.3" r="2.5" />
        <circle id="XMLID_35_" cx="165" cy="91.3" r="2.5" />
        <circle id="XMLID_36_" cx="175" cy="91.3" r="2.5" />
        <circle id="XMLID_39_" cx="257" cy="91.3" r="2.5" />
        <circle id="XMLID_38_" cx="267" cy="91.3" r="2.5" />
        <circle id="XMLID_37_" cx="277" cy="91.3" r="2.5" />

      </svg>

Game Clock

                <button id="start" type="button" class="btn btn-default btn-lg gcbtn_main">Start</button>
                <button id="resetgc" type="button" class="btn btn-default btn-lg">Reset</button>

                  <button id="upgc" type="button" class="btn btn-default">
                  </button>
                  <button id="downgc" type="button" class="btn btn-default">
                  </button>

:24

                <button id="pausesc" type="button" class="btn btn-default btn-lg scbtn_main">Pause</button>

                  <button id="reset14" type="button" class="btn btn-default btn-lg">:14</button>
                  <button id="reset24" type="button" class="btn btn-default btn-lg">:24</button>

                  <button id="upsc" type="button" class="btn btn-default">
                  </button>
                  <button id="downsc" type="button" class="btn btn-default">
                  </button>

Quarter

                  <button id="upqrt" type="button" class="btn btn-default">
                  </button>
                  <button id="downqrt" type="button" class="btn btn-default">
                  </button>


text:
Q: Updating a highchart line using a button I'd like to update the red dashed line on this highchart plot using the text box and button below it.  I'm stuck on how to get it to work.  Right now I'm just trying to get the button press to move the line up slightly just so I can see if it's working.
http://jsfiddle.net/tZ8GM/
This is the function I'm trying to use to update it.
$("#setPtButton").click(function() {
    Highcharts.setOptions({
    yAxis: {
        plotLines: [{
            value : 68.1,
            color : 'red',
            dashStyle : 'longdash',
            width : 2
        }]
    }
    });
});

A: You should be using a combination of addPlotLine and removePlotLine.
$("#setPtButton").click(function() {
    var chart = Highcharts.charts[0];
    chart.yAxis[0].removePlotLine('setline');
    chart.yAxis[0].addPlotLine({
            value: $('#setPoint').val(),
            color: 'red',
            width: 2,
            id: 'setline',
            dashStyle : 'longdash'
     });
});

Updated fiddle.


text:
Q: @ngxs/form-plugin: handling single field change Form plugin provides UpdateFormValue action that allows to handle changes in form fields. However it's dispatched for every field change of the form. So if I have multiple fields in a form (e.g. email and name) and I want to do something on email change but ignore name change I have to subscribe to valueChanges observable in the component like this:
...
this.myForm.controls.email.valueChanges.subscribe(emailValue => {
    /* dispatch my special action Actions.UserChangedEmail or something */
}

Is this the correct approach or is it possible to handle it in a state with a method that uses @Action(UpdateFormValue) or seomthing like that?

A: you can use this
 this.myForm.get('email').valueChanges.subscribe(value => {
    this.myForm.get('email').setValue(value, { onlySelf: true, emitEvent: false, emitModelToViewChange: true });
}, error => { }, () => { });


text:
Q: Simply connected surfaces and torsion in Grothendieck group Let $X$ be a projective complex surface (complex manifold of dimension 2). In a paper I met the following claim: if $X$ is simply connected $\pi_1(X) \cong \{1\}$ then the torsion of the Grothendieck group vanishes $K_0(X)_{tors} \cong 0$.
How one can prove this claim? If this is well-known what is a reference?

A: Let $F^i$ denote the subgroup generated by sheaves $S$ on $X$ with $\operatorname{codim}_X \operatorname{Supp} S \leq i$. Then $F^i\supset F^{i+1}$ and these form a filtration of $K_0(X)$. By Riemann-Roch without denominators (Fulton's Intersection Theory, Section 15.3), assuming $X$ is a smooth projective surface, we have that $F^0/F^1 \cong \Bbb Z$, $F^1/F^2 \cong Pic(X)$, and $F^2\cong CH_0(X)$.
Proposition: for $X$ simply connected, then $K_0(X)$ torsion-free is equivalent to $CH_0(X)$ torsion-free.
Proof: If $X$ is simply connected, then $Pic(X)$ is a finitely generated free abelian group.
Any extension $0\to F^1\to F^0\to \Bbb Z\to 0$ will split, so we have that $K_0(X)\cong \Bbb Z \oplus F^1$. So it remains to see that $F^1$ is torsion-free. Since $0\to CH_0(X) \to F^1\to Pic(X)\to 0$ is exact, this shows that $F^1$ is torsion-free iff $CH_0(X)$ is, so we're done.
So the problem is equivalent to showing that $CH_0(X)$ is torsion-free. By Rojtman's theorem, the homomorphism $CH_0(X)\to Alb(X)(\Bbb C)$ is an isomorphism on torsion subgroups. Since $\dim Alb(X) = h^{1,0} = h^{0,1}$, we have that $\dim Alb(X) = \frac{1}{2}b_1 = 0$, where this last equality comes from $H_1(X)=\pi_1(X)^{ab}=0$ by simply connectedness. Thus $Alb(X)(\Bbb C)$ is torsion-free and so is $CH_0(X)$, so $K_0(X)$ is torsion-free.


text:
Q: WebApi 2 POST result for Edit operation In my WebApi 2 service i have a controller which allows to edit member data.
    [Authorize]
    [HttpPost]
    [Route("Members/Member")]
    public async Task<IHttpActionResult> EditMember([FromBody] Member editedMember)
    {
        var member = await _membersRepository.GetMembersById(editedMember.MemberId);

        if (member == null)
        {
            return NotFound();
        }

        member = await _membersRepository.EditMember(editedMember);

        Uri locationHeader = new Uri(Url.Link("MemberById", new { id = editedMember.MemberId }));

        return Ok();
    }

According to HATEOAS i should return an URI of the resource i POSTed to. I would think that the correct result if everything went well is OK. But it does not allow to include the URI in it.
What am I doing wrong?

A: All you need to do is this:
return Ok( new { locationHeader });


text:
Q: Mongodb insert document via shell I want to perform crud operation on my collection. To automate this, I wrote a script for inserting documents on my collection.
This script should basically read the data from a json file and insert it into my db-collection.
'use strict';
const fs = require('fs');
const path = require('path');
const { spawn }= require('child_process');

(function () {
    const username = process.env.DB_USERNAME,
        password = process.env.DB_PASSWORD,
        args = process.argv.slice(3),
        log = console.log,
        mongoServer = "mongodb+srv://***server-name***/";

    let database,
        documents,
        collection;

    if (args.length === 2) {
        database = args[0];
        collection = args[1];

        const raw = fs.readFileSync(path.join(__dirname, 'documents.json'));
        documents = JSON.parse(raw);

        log(documents)
        const writeAction = spawn('mongo', [`\"${mongoServer}${database}\" -u ${username} -p ${password} --eval \"db.${collection}.insert(${documents})\"  `], {shell: true});
        writeAction.stdout.on('data', data => log((`stout: ${data}`));
        writeAction.stderr.on('data', data => log((`StdErr: ${data}`)));
        writeAction.on('close', (code) => log(`Child process exited with code: ${code}.`));
    } else {
        log('A database and a collection has to be specified!\n In Order:\n 1. Database\n 2. Collection');
        process.exit(1);
    }
})();

If I read the json file the console log the following:
[ { id: '3685b542-61d5-45da-9580-162dca725966',
    mission:
     'The American Red Cross prevents and alleviates human suffering in the face of emergencies by mobilizing the power of volunteers and the generosity of donors.',
    street1: '2025 E Street, NW',
    profile_url:
     'https://www.pledgeling.com/organizations/42/american-red-cross' } ]

So the json looks fine to me but if I execute the script it throws me the error:
stout: 2019-11-08T18:08:33.901+0100 E  QUERY    [js] uncaught exception: SyntaxError: missing ] after element list :
@(shell eval):1:23
2019-11-08T18:08:33.901+0100 E  -        [main] exiting with code -4

Does any of you know how to overcome this error?

A: It clearly does not see the closing brackets. So first thing try to lose the brackets and test. Also, do not forget to force 'utf8' encoding.
const raw = fs.readFileSync(path.join(__dirname, 'documents.json'), 'utf8');
documents = JSON.parse(raw);

A: the line...
writeAction.stdout.on('data', data => log((`stout: ${data}`));

... is missing a parenthesis.


text:
Q: how Hexadecimal string to Bytes how hexadecimal string to Bytes and Bytes to hexadecimal string?
I have oc code but I can not to write in swift
can u help me ?
thanks so much
+ (NSData *)convertHexToDataBytes:(NSString *)hexStr {
    NSMutableData *dataBytes = [NSMutableData data];
    int idx;
    for (idx = 0; idx + 2 <= hexStr.length; idx += 2) {
        NSRange range = NSMakeRange(idx, 2);
        NSString *singleHexStr = [hexStr substringWithRange:range];
        NSScanner *scanner = [NSScanner scannerWithString:singleHexStr];
        unsigned int intValue;
        [scanner scanHexInt:&intValue];
        [dataBytes appendBytes:&intValue length:1];
    }
    return dataBytes;
}

+ (NSString *)convertDataBytesToHex:(NSData *)dataBytes {
    if (!dataBytes || [dataBytes length] == 0) {
        return @"";
    }
    NSMutableString *hexStr = [[NSMutableString alloc] initWithCapacity:[dataBytes length]];
    [dataBytes enumerateByteRangesUsingBlock:^(const void *bytes, NSRange byteRange, BOOL *stop) {
        unsigned char *dataBytes = (unsigned char *)bytes;
        for (NSInteger i = 0; i < byteRange.length; i ++) {
            NSString *singleHexStr = [NSString stringWithFormat:@"%x", (dataBytes[i]) & 0xff];
            if ([singleHexStr length] == 2) {
                [hexStr appendString:singleHexStr];
            } else {
                [hexStr appendFormat:@"0%@", singleHexStr];
            }
        }
    }];
    return hexStr;
}

I write in swift like this
    class func convertHex(toDataBytes hexStr: String?) -> Data? {
        var dataBytes = Data()
        var idx: Int
        idx = 0
        while idx + 2 <= (hexStr?.count ?? 0) {
            let range = NSRange(location: idx, length: 2)
            let singleHexStr = (hexStr as NSString?)?.substring(with: range)
            let scanner = Scanner(string: singleHexStr ?? "")
            var intValue: UInt
            scanner.scanHexInt32(&UInt32(intValue))
            dataBytes.append(&intValue, count: 1)
            idx += 2
        }
        return dataBytes
    }

its error says:Cannot pass immutable value as inout argument: function call returns immutable value how to fix it?

A: To answer your immediate question: UInt32(intValue) creates a new (constant) value whose address cannot be taken with &.  So
var intValue: UInt
scanner.scanHexInt32(&UInt32(intValue))

should be
var intValue: UInt32 = 0
scanner.scanHexInt32(&intValue)

And
dataBytes.append(&intValue, count: 1)

does not compile because &intValue is a pointer to an integer, not to an UInt8. Here you can do
dataBytes.append(UInt8(intValue))

because the value is known to fit in a single byte.
Having said that, all the conversions from String to NSString are not needed. A more "Swifty" translation of that Objective-C code to Swift would be
func convertHex(toDataBytes hexStr: String) -> Data {
    var dataBytes = Data()
    var startPos = hexStr.startIndex
    while let endPos = hexStr.index(startPos, offsetBy: 2, limitedBy: hexStr.endIndex) {
        let singleHexStr = hexStr[startPos..<endPos]
        let scanner = Scanner(string: String(singleHexStr))
        var intValue: UInt32 = 0
        scanner.scanHexInt32(&intValue)
        dataBytes.append(UInt8(intValue))
        startPos = endPos
    }
    return dataBytes
}

For an alternative approach (which includes error checking) see for example
hex/binary string conversion in Swift


text:
Q: How to print a long string of numbers neatly in python 3.6? >>> text = [ str(i) for i in range(1, 100)]
>>> print( " {}".format( ", ".join( str(i) for i in text ) ) )
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99

Instead of printing a long text string, I would like a neater print out of text with 80 characters width for each line, each line is indented with 2 character space and each element to be equally spaced like so:
   1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
  21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
  41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60,
  61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
  81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99

Is there a ready python object that I can use to do this? If not, what is the pythonic way of achieving this in python 3.6?

A: As Saelyth pointed out, use textwrap to format this, but before that, you need to format each number right justified and take up 2 spaces:
import textwrap

text = [str(i) for i in range(1, 100)]
one_line = ', '.join('{:>2}'.format(e) for e in text)
# one_line == ' 1,  2,  3, ...'
print('\n'.join(textwrap.wrap(one_line, width=80)))

Output:
 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60,
61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99

Update
If you want 2-space indent, the first way is to print each line with the indentation:
import textwrap

text = [str(i) for i in range(1, 100)]
one_line = ', '.join('{:>2}'.format(e) for e in text)
# one_line == ' 1,  2,  3, ...'
for line in textwrap.wrap(one_line, width=78):
    print('  {}'.format(line))

The second way is to use textwrap.indent:
import textwrap

text = [str(i) for i in range(1, 100)]
one_line = ', '.join('{:>2}'.format(e) for e in text)
# one_line == ' 1,  2,  3, ...'
block = '\n'.join(textwrap.wrap(one_line, width=78))
print(textwrap.indent(block, '  '))

Note that because of the 2-space indentation, I reduced the width from 80 down to 78.
Update 2
Thanks to Tomerikoo for the suggestion to use textwrap.fill, the code is now simpler:
import textwrap

text = [str(i) for i in range(1, 100)]
one_line = ', '.join('{:>2}'.format(e) for e in text)
# one_line == ' 1,  2,  3, ...'

print(textwrap.fill(one_line,
                    width=80,
                    initial_indent='  ',
                    subsequent_indent='  '))

Update 3
In this updated, I added advice from Tim to reduce the steps further.
import textwrap

one_line = ', '.join('{:>2}'.format(e) for e in range(1, 100))
# one_line == ' 1,  2,  3, ...'

print(textwrap.fill(one_line,
                    width=80,
                    initial_indent='  ',
                    subsequent_indent='  '))

A: From the textwrap library:
>>> text = [str(i) for i in range(1, 100)]
>>> print(textwrap.fill(" {}".format(", ".join(str(i) for i in text)), width=80))

The description of textwrap.fill:
textwrap.fill(text, width=70, **kwargs)

Wraps the single paragraph in text, and returns a single string containing the wrapped paragraph. fill() is shorthand for
"\n".join(wrap(text, ...))

Basically this function wraps the text to the given width. If you are willing to accept the default width of 70, you can ommit the width keyword argument entirely.

A: Many of the other answers are missing the power of the Python formatting mini-language also, as you are using Python 3.6 f-strings!
# Format range into a spaced-out string
formatted_range = ", ".join(f"{x:2d}" for x in range(0, 100))

# Split into lines and print
print(textwrap.fill(formatted_range, width=80))

f{x:2d} will format an integer to take up 2 characters (padded with spaces). More info here
Again textwrap is used to split across lines, I have used textwrap.fill which is a shorthand for "\n".join(wrap(text, ...))

A: import textwrap
maximum = 100
text = str([str(i).zfill(len(str(maximum))) for i in range(1, maximum)])[1:-1]
text = textwrap.wrap(text, width=20)
for i in text:
    print(i)

This would do the trick, the textwrap module makes "lists" of your desired width in case you want to work with those lines. So you just need to feed it some text and get your result.
Also added zfill so all numbers are of the same lenght as the maximum number.
If you just need the text, other answers are better.

A: Using only format. We first pack all the elements to one long line while fixing their length to 2. Then just joining the lines with '\n' using cs_in_line jumps with added 2-spaces:
text = [str(i) for i in range(1, 100)]

one_line = ", ".join("{:>2}".format(num) for num in text)

print("\n".join("  "+one_line[i:i+cs_in_line] for i in range(0, len(one_line), cs_in_line)))

And this gives:
   1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
  21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
  41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60,
  61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
  81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99


text:
Q: Include custom exception files in controllers I'm trying to use Exceptions within my Models and Controllers. In the application, directory, I created a directory Exceptions that has some exception classes in files 'CustomException1.php' and 'CustomException2.php'.
I defined MY_Controller in application/core
class MY_Controller extends CI_Controller {

    public function __construct() {
        parent::__construct();

        // include Exception files
        require_once(APPPATH . 'Exceptions/CustomException1.php');
        require_once(APPPATH . 'Exceptions/CustomException2.php');
    }

}

In my controller Test :
class Test extends MY_Controller {
   public function index() {
      try {
         throw new CustomException1('This is a custom exception');
      } catch (CustomException1 $e) {
         $this->output->set_status_header('500');
         echo $e->message;
      }
}

Now, I would expect this to work since I'm requiring all the files that define the Exception classes, but I still get an error stating
Class CustomException1 not found on line xx

A: throw new CustomException1('This is a custom exception');

and
    catch (CustomException $e)
tbh, this more looks like a typo. The thrown exception CustomException1 should be CustomException

A: For whatever reason, including the files from the Exceptions directory just wouldn't work in CI. Placing them in the libraries directory and loading them in using $this->load->library() also would not have worked because CI attempts to instantiate the libraries at the time of loading in, which of course, I did not want.
I ended up putting them in a directory exceptions within helpers, and load them in at MY_Controller using $this->load->helper('Exceptions/CustomException');.
It is important to note that when loading in a helper, CI converts the entire path to lowercase and appends _helper to the end of the filename, so the exact path of my exception class on the server is
APPPATH . 'helpers/exceptions/customexception_helper.php'
This is my modified base class controller:
class MY_Controller extends CI_Controller {

    public function __construct() {
        parent::__construct();

        $this->load->helper("Exceptions/CustomException1.php");
        // includes file APPPATH . 'helpers/exceptions/customexception1_helper.php'

        $this->load->helper("Exceptions/CustomException2.php");
        // includes file APPPATH . 'helpers/exceptions/customexception2_helper.php'
    }
}

Once included this way using MY_Controller, these exceptions can then be used in models as well without needing to re-load them in MY_Model.
PS - I'm not completely satisfied with this solution, and it seems a little hack-y, but this might be the only way to integrate exceptions into CodeIgniter.


text:
Q: How to separate a executing path to file path and parameter? There are such lines as
C:\Program Files\Realtek\Audio\HDA\RAVCpl64.exe -s

in the registry key
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run

Now I want to separate the absolute path and parameters from the line.
If the line is
C:\Space Dir\Dot.Dir\Sample Name.Dot.exe param path."C:\Space Dir\Dot.Dir\Sample Name.Dot.exe"

Which separator should I use to deal with this line? Is there any Windows API function to solve this problem?

A: The function you want is in the standard C library that you can use in Windows.
char theDrive[5],thePath[MAX_PATH],theFilename[MAX_PATH],theExtension[MAX_PATH];

_splitpath(theSCTDataFilename,theDrive,thePath,theFilename,theExtension);

You can also use a more general tokenizing function like this which takes any string, a char and a CStringArray..
void tokenizeString(CString theString, TCHAR theToken, CStringArray *theParameters)
{
CString temp = "";
int i = 0;

for(i = 0; i < theString.GetLength(); i++ )
    {
    if (theString.GetAt(i) != theToken)
       {
       temp += theString.GetAt(i);
       }
     else
       {
       theParameters->Add(temp);
       temp = "";
       }

         if(i == theString.GetLength()-1)
      theParameters->Add(temp);
    }
}

CStringArray thePathParts;
tokenizeString("your\complex\path\of\strings\separated\by\slashes",'/',&thePathParts);

This will give you an array of CString (CStringArray object) that contains each      section of the input string.  You can use this function to parse the major chunks then the minor ones as long as you know the seperator charactor you want to split the string on.


text:
Q: Unbalanced keys lead to performance problems in Spark I have an issue where I have a set of keys, and a (larger) set of records that I want to aggregate across keys. The issue I have is that the number of records per key varies wildly. A single key can have millions of records that map to it, whereas plenty of the keys only have a 1-5 records that map to them. The end goal is to aggregate the values (stored in a list). Right now, this is what I am doing:
data = sc.textFile("my/path/to/file/*).map(lambda x: x.split(","))
kv = data.map(lambda x: (x[0],x[1:])

kv.take(4) looks like this:
("key1", [1, 2, 3, 4]), ("key1", [1, 2, 3, 4]), ("key2", [1, 1, 1, 1]), ("key2", [0, 1, 0, 1])
Right now, I am performing kv.reduceByKey(lambda a,b: a+b). Then I perform an iterative addition method to yield the following output:
("key1", [2, 4, 6, 8]), ("key2", [1, 2, 1, 2])
However, I noticed that reduceByKey is taking extremely long. Given, it is a shuffle operation and these take time. But I'm also aware that the severe imbalance in the number of records per key could be causing less than ideal thread handling, since the records are not evenly distributed across keys.
Am I correct in thinking that the imbalance in records / key could be causing the slowdown? And what can I do to fix this? I've heard of salting mentioned in passing, but I'm not sure how to implement that.


text:
Q: C# My BindingSource filter won't seems to update dataGrid I've tried updating dynamically my datasource on my datagrid, but it keeps returning no value... Note : i've already closed my connection to my SQL database and am tried to filter it through a textbox textchanged method (at each change, it would dynamically filter the Binding).
It seems my textbox and everything is populated at each step i've checked each propert, and yes, my column to be filtered is verb
void txtChanged(object sender, EventArgs e)
{
   TextBox tbTemp = (TextBox)sender;
                        DataTable dt = new DataTable();
                        dataSet.dataAdapter.Fill(dt);

                        BindingSource bs = new BindingSource();
                        bs.DataSource = dt;
                        bs.Filter = string.Format("[{0}] LIKE '%{1}%'", "Verb", tbTemp.Text);

                        dataGrid.DataSource = bs;
                    }
                }

Thanks in advance for the help!

A: Oh my god, guys. it works like a charm now! Thanks for the help, i would like to help any other people with this issue. It was sooooo complex... Your solution guided me towards the truth :
BindingSource datamember property needs to be set to table. Here is my correct code :
void txtChanged(object sender, EventArgs e)
{

    TextBox tbTemp = (TextBox)sender;
    dataSet.bdSource.Filter = string.Format("[{0}] LIKE '%{1}%'",
    strTemp[Int16.Parse(tb.Name)], tbTemp.Text);
    //Use table name instead of verb
    dataSet.bdSource.DataMember = "Verbe";

    dataGrid.DataSource = null;
    dataGrid.DataSource = dataSet.bdSource;
    dataGrid.Refresh();
}


text:
Q: org.datanucleus.exceptions.NucleusUserException: Error : Could not find API definition for name "JPA" Trying to create a java-se application using DataNucleus for dinamic generation of persistance unit by this code (which is in main method of Main class):
PersistenceUnitMetaData pumd = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null);
pumd.addClassName("my.homework.entity.Procurement");
pumd.addProperty("datanucleus.ConnectionDriverName", "com.mysql.cj.jdbc.Driver");
pumd.addProperty("datanucleus.ConnectionURL", "jdbc:mysql://localhost:3306/" + schemaName + "?serverTimezone=Asia/Yekaterinburg");
pumd.addProperty("datanucleus.ConnectionUserName", login);
pumd.addProperty("datanucleus.ConnectionPassword", password);
pumd.addProperty("datanucleus.schema.autoCreateTables", "true");

EntityManagerFactory emf = new JPAEntityManagerFactory(pumd, null);
entityManager = emf.createEntityManager();
ProcurementService procurementService = new ProcurementService(entityManager);

In idea the code works well. But when I'm trying to run application as an .exe file in Windows, I'm getting the error:
ш■ы 21, 2020 11:46:04 PM org.datanucleus.api.ApiAdapterFactory getApiAdapter
SEVERE: Error : Could not find API definition for name "JPA". Perhaps you dont have the requisite datanucleus-api-XXX jar in the CLASSPATH?
Exception in thread "main" Error : Could not find API definition for name "JPA". Perhaps you dont have the requisite datanucleus-api-XXX jar in the CLASSPATH?
org.datanucleus.exceptions.NucleusUserException: Error : Could not find API definition for name "JPA". Perhaps you dont have the requisite datanucleus-api-XXX jar in the CLASSPATH?
        at org.datanucleus.api.ApiAdapterFactory.getApiAdapter(ApiAdapterFactory.java:93)
        at org.datanucleus.AbstractNucleusContext.<init>(AbstractNucleusContext.java:118)
        at org.datanucleus.PersistenceNucleusContextImpl.<init>(PersistenceNucleusContextImpl.java:185)
        at org.datanucleus.PersistenceNucleusContextImpl.<init>(PersistenceNucleusContextImpl.java:174)
        at org.datanucleus.api.jpa.JPAEntityManagerFactory.initialiseNucleusContext(JPAEntityManagerFactory.java:909)
        at org.datanucleus.api.jpa.JPAEntityManagerFactory.initialise(JPAEntityManagerFactory.java:515)
        at org.datanucleus.api.jpa.JPAEntityManagerFactory.<init>(JPAEntityManagerFactory.java:380)
        at my.homework.Main.main(Main.java:109)

Main.java:109:
EntityManagerFactory emf = new JPAEntityManagerFactory(pumd, null);

POM file:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>my.homework</groupId>
    <artifactId>Dinar8</artifactId>
    <version>1.0</version>

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <repositories>
        <repository>
            <id>AsposeJavaAPI</id>
            <name>Aspose Java API</name>
            <url>https://repository.aspose.com/repo/</url>
        </repository>

        <repository>
            <id>akathist-repository</id>
            <name>Akathist Repository</name>
            <url>http://www.9stmaryrd.com/maven</url>
        </repository>
    </repositories>

    <dependencies>
        <dependency>
            <groupId>com.aspose</groupId>
            <artifactId>aspose-cells</artifactId>
            <version>20.3</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.20</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>5.4.15.Final</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.10</version>
        </dependency>
        <dependency>
            <groupId>org.datanucleus</groupId>
            <artifactId>datanucleus-core</artifactId>
            <version>5.2.3</version>
        </dependency>
        <dependency>
            <groupId>org.datanucleus</groupId>
            <artifactId>datanucleus-api-jpa</artifactId>
            <version>5.2.4</version>
        </dependency>
        <dependency>
            <groupId>org.datanucleus</groupId>
            <artifactId>datanucleus-rdbms</artifactId>
            <version>5.2.3</version>
        </dependency>
    </dependencies>

    <pluginRepositories>
        <pluginRepository>
            <id>akathist-repository</id>
            <name>Akathist Repository</name>
            <url>http://www.9stmaryrd.com/maven</url>
        </pluginRepository>
    </pluginRepositories>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>3.2.0</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                        <configuration>
                            <archive>
                                <manifest>
                                    <mainClass>
                                        my.homework.Main
                                    </mainClass>
                                </manifest>
                            </archive>
                            <descriptorRefs>
                                <descriptorRef>jar-with-dependencies</descriptorRef>
                            </descriptorRefs>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>com.akathist.maven.plugins.launch4j</groupId>
                <artifactId>launch4j-maven-plugin</artifactId>
                <version>1.7.25</version>
                <executions>
                    <execution>
                        <id>l4j-console</id>
                        <phase>package</phase>
                        <goals>
                            <goal>launch4j</goal>
                        </goals>
                        <configuration>
                            <headerType>console</headerType>
                            <outfile>target/Project13.exe</outfile>
                            <jar>target/Dinar8-1.0-SNAPSHOT-jar-with-dependencies.jar</jar>
                            <dontWrapJar>false</dontWrapJar>
                            <errTitle>Error in launch4j plugin</errTitle>
                            <classPath>
                                <mainClass>my.homework.Main</mainClass>
                                <addDependencies>true</addDependencies>
                            </classPath>
                            <jre>
                                <path>%JAVA_HOME%</path>
                                <jdkPreference>jdkOnly</jdkPreference>
                                <minVersion>1.7.0</minVersion>
                                <runtimeBits>64/32</runtimeBits>
                                <maxHeapPercent>100</maxHeapPercent>
                            </jre>
                            <icon>src/main/resources/icon13.ico</icon>
                            <versionInfo>
                                <fileVersion>1.0.0.0</fileVersion>
                                <txtFileVersion>1.0.0.0</txtFileVersion>
                                <fileDescription>Excel file analysis</fileDescription>
                                <copyright>Khmelev Stanislav</copyright>
                                <companyName>comp</companyName>
                                <productVersion>1.0.0.0</productVersion>
                                <txtProductVersion>${project.version}</txtProductVersion>
                                <productName>Project13</productName>
                                <internalName>Project13</internalName>
                                <originalFilename>Project13.exe</originalFilename>
                            </versionInfo>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.datanucleus</groupId>
                <artifactId>datanucleus-maven-plugin</artifactId>
                <version>5.0.2</version>
                <configuration>
                    <api>JPA</api>
                    <log4jConfiguration>${basedir}/log4j.properties</log4jConfiguration>
                    <verbose>true</verbose>
                </configuration>
                <executions>
                    <execution>
                        <phase>process-classes</phase>
                        <goals>
                            <goal>enhance</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

What should I do to remove this error?

A: Putting all three jar files:
   datanucleus-api-jpa-5.2.4.jar,
   datanucleus-core-5.2.3.jar,
   datanucleus-rdbms-5.2.3.jar

into the directory with .exe solving the problem.


text:
Q: Cloud Messaging using GCM I am trying Notifications task using Pushbots. I was follow what are the steps to do in Android Manifest file. My device registered successfully but messages not sent to my device. Its Checking on Pushbots sand box I got Notification deilvery failed to 1 devices.and in my android studio console AndroidManifest.xml missing required permission: android.permission.GET_ACCOUNTS.....

A: Take a look at this page (step 2): https://pushbots.com/developer/docs/android-sdk-integration
Alter your AndroidManifest.xml file, and add the following permissions:
<!-- GCM connects to Google Services. -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<!-- GCM requires a Google account. -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<permission android:name="com.example.sampleapp.permission.C2D_MESSAGE" android:protectionLevel="signature" />
<uses-permission android:name="com.example.sampleapp.permission.C2D_MESSAGE" />
<!-- This app has permission to register and receive dataf message. -->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />


text:
Q: In my django app , I am making test script for my api but I am getting AssertionError: 401 != 201 , I am giving sample code We have created django app ,
I am making test script for my api but I have getting AssertionError: 401 != 201 , I am giving sample code
error :-
Traceback (most recent call last):
File "C:\Abhishek\Git\taskManagement\tests.py", line 108, in test_auth_user_can_create_project
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
AssertionError: 401 != 201
views.py
class Projects(APIView):
authentication_classes = [authentication.TokenAuthentication]
permission_classes = [permissions.IsAuthenticated]
"""
To create the project
"""
def post(self, request):

    request.data['created_by'] = request.user.id
    request.data['username'] = request.user.username
    serializer = ProjectSerializer(data=request.data)
    if not serializer.is_valid():
        print(serializer.errors)
        return Response({
            'success': False,
            'errors': serializer.errors,
            'message': _("something is wrong")
        })
    serializer.save()
    return Response({
        'success': True,
        'Project': serializer.data,
        'message': _("Project create successfully")
    })

tests.py
def test_auth_user_can_create_project(self):
client = APIClient()
    data = {
        "project_name": "Test project testscript",
        "project_description": "test project desc",
    }

    response = self.client.post('/api/project/', data, format='json')
    self.assertEqual(response.status_code, status.HTTP_201_CREATED)


text:
Q: Creating VSIX extension for a C++ project in a solution Currently I have 2 separate solutions for my C++ project and for C# VSIX extension. I export my C++ project template as .zip archive, and in VSIX extension solution I add it as a file asset. Works fine, however I need to handle .zip manually all the time.
To avoid that I've tried to merge the projects (C++ + VSIX) into a single solution, and instead of adding file asset I've tried to add project asset, selecting my C++ project.
The problem is that doesn't work, VSIX project gives error when trying to compile it: "error MSB4057: no target "TemplateProjectOutputGroup"." and I haven't found anything describing how exactly must it be done.
VS2019 Community.

A: You really only need a single solution here that contains multiple projects.
The way I've done this in the past, was to first create an Empty .VSIX project (to be used for deploying the templates).
Then add new "C# Project Template" projects, and modify them to create a C++ project instead of a C# project. Note the core .csproj file still makes the Template Project C# project, but the templates payload (.vcxproj, .h, .cpp, etc are added, and the C# files removed. So that the end result is that the template produced a C++ project instead of a C# project.
These Project Template projects will generate .zip files, which can then be added to your .VSIX project, by first Referencing the Project Template projects (aka a Project to Project refernce), and then editing the vsixmanifest to include the output of the referenced project (the zip file) as an asset.
I wrote up a blog entry on this some years back, that does this. Though the focus was on the custom wizard used to set the Windows SDK Version, for the resulting C++ project created with the template. The code article also has a link to the source code, which you might find useful for additional guidance.
Creating a VSIX Deployable C++ project template
Sincerely,


text:
Q: Charter font shape undefined with LuaLaTeX I have to use a publisher style (link) and I have problems with the basic example. I am using LuaTeX as suggested. The same happens with XeTeX, but not with pdfTeX.
Here is a MWE, extracted from the provided template:
\documentclass{article}
\usepackage[charter]{mathdesign}
\begin{document}
\end{document}

Problem:
LaTeX Font Warning: Font shape `TU/mdbch/m/n' undefined
(Font)              using `TU/lmr/m/n' instead on input line 105.

Is there something I can do, or this font is simply not available in this setting? If so, what would be the best thing to do, ask the template authors? I am saying this because I would expect the provided example to work flawlessly, at least in the recommended setting (LuaTeX).
My understanding is that /m/n is not some weird combination that does not work but rather the "normal" font, and that the problem is in the encoding (TU), but I don't know much about this stuff.

A: The default output font encoding with LuaLaTeX is TU, but you want T1:
\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage[charter]{mathdesign}

\begin{document}

Hello

\end{document}

The warning you get when fontspec is loaded is spurious and should have no consequence. Loading fontenc is not needed and might even lead to bad output.
\documentclass{article}

% fix for the spurious warning issued by
\DeclareFontFamily{TU}{mdbch}{}
\DeclareFontShape{TU}{mdbch}{m}{n}{
 <-> \UnicodeFontFile{lmroman10-regular}{\UnicodeFontTeXLigatures}
}{}

\usepackage[charter]{mathdesign}
\usepackage{fontspec}

\setmainfont{XCharter}

\begin{document}

Hello

\end{document}

A: In the latest version of the style file, there is a different workaround for the problem. It turns out that not all fonts or packages are not yet ready for the TU encoding. In this case, everything works fine with the EU encoding, hence, for the time being, EU encoding is being forced for fontspec
The workaround used but for the current version would entail the following:
\PassOptionsToPackage{euenc}{fontspec}
\documentclass[english,submission]{programming}

%...

The variant by @egreg seems correct when using the TU encoding, but I'd rather wait for the XCharter package to be actually compatible with TU.
edit: Disclaimer: I am the author of the style.


text:
Q: How to build automatically resizable image view inside a recycler view Hi guys I am still new to Android and I am trying to build a small project for test. What I am trying to do is to build a card game. For the bottom player I want to display a recycler view with all cards in his hand. I want the card images to be overlapping one on another and when a card is played to recalculate the overlapping to match parent width of the recycler view. And when the sum of card width is less than recycler views width i want them to be show without overlapping and center in the recycle view.
I just can't find out what method to use. I am using the ItemDecoration to create overlapping, but when i add overlapping match_parent doesn't work.
This is my recycler view for the game.
<RelativeLayout>
    <!-- Bottom Player -->
    <LinearLayout android:id="@+id/bottom"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_alignParentBottom="true"
        android:layout_below="@+id/middle_section"
        android:orientation="vertical"
        android:paddingLeft="2dip"
        android:paddingRight="2dip">

        <TextView android:id="@+id/player1_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center" />

        <android.support.v7.widget.RecyclerView
            android:id="@+id/player1_cards_container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center" />
    </LinearLayout>
</RelativeLayout>

This is the player hand layout:
<android.support.v7.widget.CardView
android:id="@+id/player_hand"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/player_card"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:adjustViewBounds="true" />

</RelativeLayout>
</android.support.v7.widget.CardView>

Then i have a recycler view adapter:
public class PlayerHandRecyclerViewAdapter extends      RecyclerView.Adapter<PlayerHandRecyclerViewHolder> {
private ArrayList<Card> _cards = new ArrayList<Card>();
private Context _context;

public PlayerHandRecyclerViewAdapter(Context context, ArrayList<Card> cards) {
    this._context = context;
    this._cards = cards;
}

@Override
public PlayerHandRecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    //Inflate the layout, initialize the View Holder
    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.player_hand, parent, false);
    PlayerHandRecyclerViewHolder holder = new PlayerHandRecyclerViewHolder(v, parent);
    return holder;

}

@Override
public void onBindViewHolder(PlayerHandRecyclerViewHolder holder, int position) {
    int width = holder.playerHandView.getWidth();
    int height = holder.playerHandView.getHeight();
    //Use the provided View Holder on the onCreateViewHolder method to populate the current row on the RecyclerView
    holder.imageView.setImageResource(_cards.get(position).getImageResourceId());
}

@Override
public int getItemCount() {
    //returns the number of elements the RecyclerView will display
    return _cards.size();
}

@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
    super.onAttachedToRecyclerView(recyclerView);
}

// Insert a new item to the RecyclerView on a predefined position
public void insert(int position, Card card) {
    _cards.add(position, card);
    notifyItemInserted(position);
}

// Remove a RecyclerView item containing a specified Data object
public void remove(Card card) {
    int position = _cards.indexOf(card);
    _cards.remove(position);
    notifyItemRemoved(position);
}

}

Then i have a holder:
public class PlayerHandRecyclerViewHolder extends RecyclerView.ViewHolder {

RecyclerView playerHandView;
CardView cv;
ImageView imageView;

PlayerHandRecyclerViewHolder(View itemView, ViewGroup parent) {
    super(itemView);

    String parentId = String.valueOf(parent.getId());
    int resId = parent.getContext().getResources().getIdentifier(parentId, "id", parent.getContext().getPackageName());
    playerHandView = (RecyclerView) parent.findViewById(resId);
    cv = (CardView) itemView.findViewById(R.id.player_hand);
    imageView = (ImageView) itemView.findViewById(R.id.player_card);
}
}

And this is my Item Decoration class
public class PlayerHandRecyclerViewDecoration extends RecyclerView.ItemDecoration {
private final static int vertOverlap = -20;

@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
    int position = parent.getChildAdapterPosition(view);
    if (position != 0) {
        outRect.right = vertOverlap;
        view.invalidate();
    }
}
}

A: You can create a custom ImageView such as:
public class DynamicHeightImageView extends ImageView {

    private double mHeightRatio;

    public DynamicHeightImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public DynamicHeightImageView(Context context) {
        super(context);
    }

    public void setHeightRatio(double ratio) {
        if (ratio != mHeightRatio) {
            mHeightRatio = ratio;
            requestLayout();
        }
    }

    public double getHeightRatio() {
        return mHeightRatio;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (mHeightRatio > 0.0) {
            // set the image views size
            int width = MeasureSpec.getSize(widthMeasureSpec);
            int height = (int) (width * mHeightRatio);
            setMeasuredDimension(width, height);
        }
        else {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }
}

You should call setHeightRatio() and pass to it the ratio which you can calculate from the given acquired Image.
In the layout file you can just replace ImageView with DynamicHeightImageView as below:
  <com.......DynamicHeightImageView
       />

The Image will now adjust based on the height of any Image.


text:
Q: Spring Data JDBC aggregate ID in child objects I was playing with Spring-Data-JDBC and encountered 2 issues. I have following entities with 1:N relationship.
------

DROP TABLE IF EXISTS product;

CREATE TABLE product (
    product_id int AUTO_INCREMENT  PRIMARY KEY,
    name varchar(250) not null,
    description varchar(512) not null
);

DROP TABLE IF EXISTS product_line;

CREATE TABLE product_line (
    product_id int constraint fk_product_line_product references product(product_id),
    label varchar(250) not null
);

----------

@Data
@Builder
public class Product {

    @Id
    private Long productId;

    private String name;

    private String description;

    @Singular
    @MappedCollection(idColumn = "product_id", keyColumn = "product_id")
    private Set<ProductLine> lines;
}

@Data
@Builder
public class ProductLine {

    private Long productId;

    private String label;

}

Problem 1: Following test case fails because I was expecting to have the productId populated in the ProductLine object but it is not. Is this the expected behavior of Spring Data JDBC?
@SpringBootTest
class SpringDataJdbcApplicationTests {

    @Autowired
    private ProductRepository productRepository;

    @Test
    void saveTest() {

        Product product = Product.builder()
                .name("Product-1")
                .description("Description")
                .line(ProductLine
                        .builder()
                        .label("Line-label")
                        .build())
                .build();

        this.productRepository.save(product);

        assertThat(product.getProductId()).isNotNull();
        assertThat(product.getLines()).isNotNull().isNotEmpty().hasSize(1);
        assertThat(product.getLines().stream().findFirst()).isPresent();
        assertThat(product.getLines().stream().findFirst().get().getProductId()).isNotNull().isEqualTo(product.getProductId()); // -----> Fails here.

    }

}

Problem 2: If I change Set<ProductLine> to List<ProductLine>, it fails due to JdbcSQLIntegrityConstraintViolationException, which means the product id set to 0 as seen in the log snippet below.
2022-09-10 22:33:12.393 DEBUG 18460 --- [           main] o.s.jdbc.core.JdbcTemplate               : Executing prepared SQL statement [INSERT INTO "PRODUCT_LINE" ("LABEL", "PRODUCT_ID") VALUES (?, ?)]
2022-09-10 22:33:12.393 TRACE 18460 --- [           main] o.s.jdbc.core.StatementCreatorUtils      : Setting SQL statement parameter value: column index 1, parameter value [Line-label], value class [java.lang.String], SQL type 12
2022-09-10 22:33:12.393 TRACE 18460 --- [           main] o.s.jdbc.core.StatementCreatorUtils      : Setting SQL statement parameter value: column index 2, parameter value [0], value class [java.lang.Integer], SQL type 4

A:
Following test case fails because I was expecting to have the productId populated in the ProductLine object but it is not. Is this the expected behavior of Spring Data JDBC?

Yes, if you want a productId you have to (and can easily) populate it yourself using plain Java code.
But you really shouldn't need the productId in the first place since if you follow Domain Driven Design, you will access a ProductLine exclusively from a Product which already has the id at hand.
The article https://spring.io/blog/2021/09/22/spring-data-jdbc-how-do-i-make-bidirectional-relationships might be helpful.

If I change Set<ProductLine> to List<ProductLine>, it fails due to JdbcSQLIntegrityConstraintViolationException, which means the product id set to 0 as seen in the log snippet below.

You have two problems here:

*

*You already have two sources for the product_id field: The relation from the aggregate root and the simple field, which may cause problems.

*You mapped both the back reference to the aggregate root idColumn and the index of the list keyColumn to the same database column. Together with the simple field from above these are three values all mapped to the same column. Not good.
The value that seems to win is the list index, resulting in the exception.
In order to fix that, create an additional column in the product_line table and map the list index to it.


text:
Q: Aliasing of symbol using GCC/binutils works intermittently I'm working on some software which for a limited time runs bare-metal until the Linux port is ready for prime time. The software is being linked against uClibc which provides implementations of malloc, clock_gettime etc, but the problem is that they all rely on syscalls which will just trap the hardware since we don't have a kernel to handle them yet.
I have been using aliasing to override the functions that we need, i.e.
our_mem.c:
void* our_malloc(size_t size) { .. }
void* malloc(size_t size) __attribute__ ((malloc, weak, alias("our_malloc")));

The problem is that this seems to work somewhat randomly. I can have one build where all the calls are aliased properly, in the next build where I modified something in an unrelated file it suddenly works up until a point and then one of the calls go to uClibc malloc instead.
At first I thought it was a matter of link order but the build system always links in the same order and the same call will work in one build and fail in the next.
The binaries are (obviously) statically linked.
I'm not sure this is exactly how aliasing is meant to be used since I haven't found much documentation on it but I have successfully used this technique a few years before on malloc and friends (also with uClibc) and then it worked consistently.


text:
Q: How to cast 'Any?' to a struct with flexible generic properties? I'm using a 3rd party library that in my use case is handing me down a '[Any?]' array. This array contains equatable struct objects which are defined as follows:
struct SplitValue<L: Equatable, R: Equatable> {
    public var left: L?
    public var right: R?

    public init(left: L?, right: R?){
        self.left = left
        self.right = right
    }
}

extension SplitValue: Equatable {
    public static func ==(lhs: SplitValue, rhs: SplitValue) -> Bool {
        return lhs.left == rhs.left && lhs.right == rhs.right
    }
}

And this is a simple example of the array I'm dealing with:
var values = [Any?]()
values.append(SplitValue<String, Int>(left: "a", right: 12))
values.append(SplitValue<Double, String>(left: 33.1, right: "b"))

Now let's say I cannot predict which value types are found in the SplitValue.left and SplitValue.right properties. It could be a String, Int, NSManagedObject, or anything else equatable. All I have is the values array.
Next I want to loop through this array and read out the left and right values. For this I believe I have to cast 'Any?' to 'SplitValue' because the following doesn't work:
print(values.first!.left)
// error: value of type 'Any?' has no member 'left'

I also tried things like this, but that obviously doesn't work either:
print(values.first! as SplitValue<Any, Any>)
// error: type 'Any' does not conform to protocol 'Equatable'

So the problem is that I can't cast 'Any?' to the right type since I don't know what it will be. What might be the solution to this, preferably without having to change the definition of the struct or values array?

A: What you can do is to create a protocol without the generic types and have SplitValue implement that:
protocol AnySplitValue {
    var l: Any? { get }
    var r: Any? { get }
}

Then, conform SplitValue to the protocol:
extension SplitValue: AnySplitValue {
    var l: Any? {
        return self.left
    }

    var r: Any? {
        return self.right
    }
}

Now, you can do this to print all the left values out:
values.forEach { print(($0 as! AnySplitValue).l!) }

We have kind of "erased" the generic types!


text:
Q: How to read Network Response (PAYLOAD) from GET API call using Java I want to read the Network Response after API GET call using
URL obj = new URL("https://URLGoesHere");
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");

Refer attached image to understand what actually I want to read in Response
after API GET call.


text:
Q: -[UITableView _createPreparedCellForGlobalRow:withIndexPath:willDisplay:] + 1256 Over the last week, I've noticed a lot of -[UITableView _createPreparedCellForGlobalRow:withIndexPath:willDisplay:] + 1256 crashes on iPhone 14 Pro devices running iOS 16.1.1.
The tableView where this problem originates has a constant number of rows and sections, so the datasource is never modified.
The crashes are also being reported to Crashlytics and Sentry, but never make it into the Apple Organizer.
Any idea what's going on? How can I resolve this issue?
Crashed: com.apple.main-thread
0  App                            0x90e74 SettingsViewController.tableView(_:cellForRowAt:) + 4374285940 (SettingsViewController.swift:4374285940)
1  App                            0x91210 @objc SettingsViewController.tableView(_:cellForRowAt:) + 4374286864 (<compiler-generated>:4374286864)
2  UIKitCore                      0x14beec -[UITableView _createPreparedCellForGlobalRow:withIndexPath:willDisplay:] + 1256
3  UIKitCore                      0x11f844 -[UITableView _updateVisibleCellsForRanges:createIfNecessary:] + 596
4  UIKitCore                      0x59350 -[UITableView _updateVisibleCellsNow:] + 1088
5  UIKitCore                      0x58e44 -[UITableView layoutSubviews] + 148
6  UIKitCore                      0x5020 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1980
7  QuartzCore                     0x99ec CA::Layer::layout_if_needed(CA::Transaction*) + 500
8  UIKitCore                      0xd21dc -[UIView(Hierarchy) layoutBelowIfNeeded] + 292
9  UIKitCore                      0x3dc0c -[UINavigationController _layoutViewController:] + 816
10 UIKitCore                      0x3d8d8 -[UINavigationController _layoutTopViewControllerLookForNested:] + 436
11 UIKitCore                      0x1506dc -[UINavigationController navigationTransitionView:didEndTransition:fromView:toView:] + 892
12 UIKitCore                      0x150324 -[UINavigationTransitionView _notifyDelegateTransitionDidStopWithContext:] + 296
13 UIKitCore                      0x14f8e4 -[UINavigationTransitionView _cleanupTransition] + 536
14 UIKitCore                      0x14f634 +[UIView(UIViewAnimationWithBlocks) conditionallyAnimate:withAnimation:layout:completion:] + 136
15 UIKitCore                      0x1a8c0c -[UINavigationTransitionView transition:fromView:toView:] + 1612
16 UIKitCore                      0x1a8270 -[UINavigationController _startTransition:fromViewController:toViewController:] + 2104
17 UIKitCore                      0x1a6fb4 -[UINavigationController _startDeferredTransitionIfNeeded:] + 608
18 UIKitCore                      0x1a6604 -[UINavigationController __viewWillLayoutSubviews] + 96
19 UIKitCore                      0x1a6568 -[UILayoutContainerView layoutSubviews] + 172
20 UIKitCore                      0x5020 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1980
21 QuartzCore                     0x99ec CA::Layer::layout_if_needed(CA::Transaction*) + 500
22 QuartzCore                     0x1d0a0 CA::Layer::layout_and_display_if_needed(CA::Transaction*) + 148
23 QuartzCore                     0x2e5b0 CA::Context::commit_transaction(CA::Transaction*, double, double*) + 456
24 QuartzCore                     0x635ec CA::Transaction::commit() + 652
25 QuartzCore                     0x4c8cc CA::Transaction::flush_as_runloop_observer(bool) + 88
26 UIKitCore                      0x504b44 _UIApplicationFlushCATransaction + 52
27 UIKitCore                      0x652740 _UIUpdateSequenceRun + 84
28 UIKitCore                      0xc99fd0 schedulerStepScheduledMainSection + 172
29 UIKitCore                      0xc9919c runloopSourceCallback + 92
30 CoreFoundation                 0xd5f54 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 28
31 CoreFoundation                 0xe232c __CFRunLoopDoSource0 + 176
32 CoreFoundation                 0x66210 __CFRunLoopDoSources0 + 244
33 CoreFoundation                 0x7bba8 __CFRunLoopRun + 836
34 CoreFoundation                 0x80ed4 CFRunLoopRunSpecific + 612
35 GraphicsServices               0x1368 GSEventRunModal + 164
36 UIKitCore                      0x3a23d0 -[UIApplication _run] + 888
37 UIKitCore                      0x3a2034 UIApplicationMain + 340
38 App                            0x8020 main + 41 (AppDelegate.swift:41)
39 ???                            0x1aa7e0960 (Missing)

A: I discovered that there was a forced unwrapping deep inside my codebase. I would encourage you to search for any forced unwrapping.


text:
Q: IntelliJ 2018.1.3 shows all the methods from the interfaces, why? Lets say we have the following code:
public interface Dvd {
   void startDvd();
}

and another interface:
public interface Tv {
    void startTv();
}

and a class:
public class Logitech implements Dvd, Tv {
    @Override
    public void startDvd() {

    }

    @Override
    public void startTv() {

    }
}

then when you make an instance:
public class Demo {
    public static void main(String[] args) {
        Tv tv = new Logitech();
        tv.  //here when we click the . we expect to see only the startTv()
             //method, as the type of our reference is Tv
    }
}

however what is shown is:
an image of my intellij code complete
isn't this kind of invalidating the abstraction OOP concept as it will always show me all of the methods from the interfaces that my class implements, and sometimes this can be tons of methods will not hide any complexity for me?
Why do I see both methods and NOT only startTv()?

A: This only works for local variables, and only when IntelliJ is able to be sure that the type of the variable is always actually a certain concrete type (in this case Logitech).
If we add another class which implements Tv
class Foo implements Tv {
    @Override
    public void startTv() { }
}

and then assign to the variable conditionally:
class Demo
{
    private static int bar()
    {
        return 3;
    }

    public static void main(Tv args) {
        Tv tv = new Logitech();

        if (bar() > 2)
        {
            tv = new Foo();
        }

        tv. //only has startTv method
    }
}

then IntelliJ is no longer able to infer the type, so it won't prompt us with methods from Logitech (or from Foo either).
This is also true for method arguments - IntelliJ does not know the true concrete type, so it won't provide you any additional methods.

A: It's kind of assistance provided by IntelliJ, if you press enter after select startDvd(), it'll replace your code in         ((Logitech) tv).startDvd();
If you remove this cast, you'll get classic cannot resolve method 'startDvd()'

A: Secretly the tv object is an instance of the Logitech class. Intellij is trying to help by letting you know that you can access the startDvd() method if you want to by using a cast.
Kind of a long way of telling you that you can cast the Tv back into a Logitech.
However if all the program needs at that time is a TV object probably better to set tv to a class that implements the Tv interface directly.
Alternatively you might want to implement it anonymously:
    Tv tv = new Tv() {
        public void startTv() {
            //code to start the tv
        }
    }


text:
Q: Squid 3.4.6 Transparent proxy issues I'm trying to implement a Transparent Squid Proxy for a wireless network where it mainly serve for mobile devices.  The software I'm using is squid 3.4.6 (latest version compiled from source) in Debian 7.6 server and IPTables. My Network is composed of many VLAN's witch all get controlled by a central firewall by CheckPoint, witch also allow's us to control who goes where and witch servers go directly to the internet.  Here's a small diagram I created:

So, what I did so far is I isolated one VLAN just for the mobile devices where they get DHCP/DNS requests redirected to our data center where all the servers are.  Finally using an option of that redirects all HTTP and HTTPS traffic (http mapped) from that Wireless dedicated VLAN to a single Squid server on the datacenter.
I installed the squid server with one NIC (which gets all squid traffic connected directly to the internet using the Checkpoint firewall) Debian with all updates and I logged my installation process so it's easier to replicate.  All of this is made on the same machine:
Install VMWARE Tools
apt-get install -y build-essential linux-headers-amd64
mount /dev/cdrom /mnt/
cp /mnt/VMwareTools-4.0.0-236512.tar.gz /tmp/
umount /mnt/
tar -zxvf /tmp/VMwareTools-4.0.0-236512.tar.gz --directory=/tmp/
mkdir -pv /usr/lib64
/tmp/vmware-tools-distrib/vmware-install.pl --default
rm /tmp/WM* /tmp/vm* -rf

Install SQUID
apt-get install -y libtool libssl-dev libcrypto++-dev devscripts fakeroot htop ssl-cert squid-langpack && apt-get build-dep -y squid3
sysctl -w net.ipv4.ip_forward=1
nano /etc/sysctl.conf
- net.ipv4.ip_forward=1
- net.ipv4.conf.default.rp_filter = 0
- net.ipv4.conf.default.accept_source_route = 0
wget http://www.squid-cache.org/Versions/v3/3.4/squid-3.4.6.tar.gz
tar -zxvf squid-3.4.6.tar.gz
cd squid-3.4.6
nano configure.sh
chmod +x configure.sh
./configure.sh
make
make install

Content of the configure.sh
#!/bin/sh
'./configure' \
'--build=x86_64-linux-gnu' \
'--srcdir=.' \
'--prefix=/usr' \
'--includedir=/usr/include' \
'--localstatedir=/var' \
'--mandir=/usr/share/man' \
'--infodir=/usr/share/info' \
'--libexecdir=/usr/lib/squid' \
'--datadir=/usr/share/squid' \
'--sysconfdir=/etc/squid' \
'--localstatedir=/var' \
'--bindir=/usr/sbin' \
'--enable-inline' \
'--enable-ssl' \
'--enable-ssl-crtd' \
'--enable-icap-client' \
'--enable-follow-x-forwarded-for' \
'--enable-removal-policies=heap,lru' \
'--enable-delay-pools' \
'--enable-cache-digests' \
'--enable-storeio=ufs,aufs,diskd,rock' \
'--enable-disk-io' \
'--disable-eui' \
'--disable-snmp' \
'--disable-wccp' \
'--disable-wccpv2' \
'--disable-http-violations' \
'--disable-translation' \
'--disable-auto-locale' \
'--disable-htcp' \
'--disable-internal-dns' \
'--with-default-user=proxy' \
'--with-logdir=/var/log/squid/' \
'--with-pidfile=/var/run/squid.pid' \
'--with-filedescriptors=65536' \
'--with-cppunit-basedir=/usr' \
'--with-large-files' \
"$@"

Configuring SQUID
nano /etc/init.d/squid
chmod +x /etc/init.d/squid
chown -R proxy:proxy /var/log/squid/
update-rc.d squid defaults
mkdir -p /etc/squid/ssl
openssl genrsa -des3 -out openssl.key 1024
openssl req -new -key openssl.key -out openssl.csr
cp openssl.key openssl.key.old
openssl rsa -in openssl.key.old -out openssl.key
openssl x509 -req -days 365 -in  openssl.csr -signkey openssl.key -out openssl.crt
/usr/lib/squid/ssl_crtd -c -s /etc/squid/ssl/db
nano /etc/squid/squid.conf

Content of squid.conf
http_port 3128
http_port 3129 transparent
https_port 3130 intercept ssl-bump generate-host-certificates=on dynamic_cert_mem_cache_size=8MB cert=/etc/squid/ssl/openssl.crt key=/etc/squid/ssl/openssl.key version=3
visible_hostname proxyc.domain.com
dns_nameservers 8.8.8.8 8.8.4.4
strip_query_terms on
access_log stdio:/var/log/squid/access.log
cache_log /var/log/squid/cache.log
coredump_dir /var/cache/squid
shutdown_lifetime 1 second
ssl_bump server-first all
always_direct allow all
sslcrtd_program /usr/lib/squid/ssl_crtd -s /etc/squid/ssl/db -M 8MB
sslcrtd_children 5
sslproxy_cert_error allow all
sslproxy_flags DONT_VERIFY_PEER,NO_DEFAULT_CA
http_access allow all
http_reply_access allow all

This is where I believe the problem is but I have no idea what to do:
IPTABLES configuration
iptables -P INPUT ACCEPT
iptables -P FORWARD ACCEPT
iptables -P OUTPUT ACCEPT
iptables -A INPUT -i lo -j ACCEPT
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -i eth0 -p tcp --dport 22 -j ACCEPT
iptables -A INPUT -i eth0 -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -i eth0 -p tcp --dport 443 -j ACCEPT
iptables -A INPUT -i eth0 -p tcp --dport 3128 -j ACCEPT
iptables -A INPUT -i eth0 -p tcp --dport 3129 -j ACCEPT
iptables -A INPUT -i eth0 -p tcp --dport 3130 -j ACCEPT
iptables -t nat -I PREROUTING -i eth0 ! -s 192.168.1.1 -p tcp --dport 80 -j DNAT --to-destination 192.168.1.1:3129
iptables -t nat -I PREROUTING -i eth0 ! -s 192.168.1.1 -p tcp --dport 443 -j DNAT --to-destination 192.168.1.1:3130

How do I get the IPTables to redirect the incoming HTTP/HTTPS traffic as DNAT into the Squid Port on 3129 and 3130 ... the port 3128 works in any browser that I can configure the proxy but the redirects with IPTables are driving me NUTS!
What I posted above in the IPTables doesn't work.  I keep getting error 111 connection refused, and if I install some web browser any URL I place there I keep getting Apache welcome page of "It Works!!". if anyone could enlighten me what I'm doing wrong I would appreciate it.


text:
Q: ReactJS local class variable geting cleared on ComponentUpdate Trying to use a local variable for setting coloring the proper row in a table:
class CoaDataGrid extends Component {
    constructor(props){
        super(props)
        this.selected = "" <======= Local Class Variable
        this.state = {
            showinactive: false,
            search: "",
            sort: "account",
            sortdir: "asc",
        }
    }
    componentDidMount = () => {
        this.selected = "TEST"
    }
    componentDidUpdate = () => {
        console.log(this.selected) <======= Checking the Value Here
    }
    selectRecord = (e) => {
        this.selected = e.id <====== Setting the Value Here
        // Do Something Here to update the component
    }
    .....

I understand that this is just pseudoode; however if I set a local class variable and something causes the component to update, the class variable gets wiped out.  Is this by design?  Is there a workaround if it IS by design?


text:
Q: Load code when I open a popup I need to load some code JS when I load a popup window. I've tried with:
mypopup.ready(function...

But nothing.
Here's my code.
  function popup(){
   mypopup = window.open('http://33bits.es/foro/masiconos.php', 'popup', 'width=400','height=300','status=no', 'scrollbars=yes', 'toolbars=no', 'menubar=no', 'location=no');

}

 $('#mas').click(function(evt) { popup();  });

mypopup.ready(function() {

//Más Iconos
$('img').click(function (evt) {
   var clase =  $(this).attr('class');
   insertar_popup(clase);
});
$('.cerrar').click(function(evt) { window.close(); });

//Mas Iconos CSS
$('.cerrar').css("font-family", "Arial");
$('.cerrar').css("cursor", "pointer");
$('.cerrar').css("margin", "50%");
$('.pop').css("background", "url(http://www.33bits.es/foro/Themes/epic_2_0/images/id/abgg.png)");
$('.iconos_pop > img').css("margin", "5px");
$('.iconos_pop > img').css("cursor", "pointer");
$('.iconos_pop').css("border-radius", "10px");
$('.iconos_pop').css("padding", "10px");
$('.iconos_pop').css("background", "white");
$('.iconos_pop').css("margin", "5% auto");
$('.iconos_pop').css("width", "95%");
});

I want to load the popup and then, load this part of my code, it will give style to the popup. But it doesn't load and my popup doesn't have style, it seems empty and shabby.

A: A potential solution to your problem could be the use of jQuery Dialogs. It appears the code that you want to load styles the dialog on open, but using jQuery Dialogs allows you to style it with CSS directly. Follow the link below for examples, as well as source code for initializing it.
http://jqueryui.com/dialog
The basic setup uses jQuery notation, you create a  in your html page and add a "dialog" class to it:
$(function(){
    $("#yourDialog").dialog();
})

Now to have it open on click of a link, you will need to add some options to the code so that it does not open by default and only when you click on a button that activates it:
Javascript
$(function(){
    $("#yourDialog").dialog({
        autoOpen: false
    });

    $("#yourButton").click(function(){
       $("#yourDialog").dialog("open");
    });
})

Html

This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.

<button id="yourButton">Button</button>

For a more complete example, visit the link http://jqueryui.com/dialog/#modal-form.

A: Because you're modifying attribues of DOM elements in your main page, not the popup.
Moreover, mypopup variable isn't set when you attempt to call its ready method. You could try the following:
function popup() {
  var mypopup = window.open('http://33bits.es/foro/masiconos.php', 'popup', 'width=400', 'height=300', 'status=no', 'scrollbars=yes', 'toolbars=no', 'menubar=no', 'location=no');

  mypopup.onload = function() {
      var doc = mypopup.document,
          $popDocument = $(doc);

      // Everything you want
      $popDocument.find('.popClass').click(function() {
        alert('Hey you clicked in the popup!');
      });
  };
}

$('#mas').click(popup);

See it in action: http://plnkr.co/edit/u4YvcFtL1aUiVdmCMVhU?p=preview
Note that you should not manipulate your popup's contents by doing like $('selector') because it will search in you main page. Instead in the example above, do $popDocument.find('selector').
Here is an answer that wraps the popup in an object in a nice way: Get DOM elements of a popup for jQuery manipulation

A: That's becaus you can not edit the styling of another webpage that your request in your popup. That would be a security issue if it where possible.
if "http://33bits.es/foro/masiconos.php" is one of your own pages you could edit that and use
document.ready to do the styling


text:
Q: How to duplicate values in a flat, indexed array? (Append all elements to end of array in order) Say I had this code
$x = array("a", "b", "c", "d", "e");

Is there any function that I could call after creation to duplicate the values, so in the above example $x would become
array("a", "b", "c", "d", "e", "a", "b", "c", "d", "e");

I thought something like the following but it doesn't work.
$x = $x + $x;

A: php > $x = array("a", "b", "c", "d", "e");
php > print_r(array_merge($x, $x));

Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
    [4] => e
    [5] => a
    [6] => b
    [7] => c
    [8] => d
    [9] => e
)

A: $x = array("a", "b", "c", "d", "e");

$x = array_merge($x,$x);

Merging an array onto itself will repeat the values as duplicates in sequence.

A: This should do the trick:
$x = array("a", "b", "c", "d", "e");
$x = array_merge($x,$x);

A: You could loop through the array and that each variable to a separate duplicate array. Here is some code off the top of my head:
$x = array("a", "b", "c", "d", "e");
$duplicateArray = $array;

foreach ($x as $key) {
    $duplicateArray[] = $key;
}

foreach ($x as $key) {
    $duplicateArray[] = $key;
}

A: $x = array_merge($x, $x);

Or you could go looping and duplicating, if you preferred.

A: First and foremost, it should be asked: Why is it beneficial to push redundant data into your input array?
If you need to access the data in a loop for presentation purposes, you can spare the array bloat and merely change how the elements are iterated.
For instance, you could just call two separate foreach() loops on the original array.
foreach ($x as $v) {
    echo "$v\n";
}
foreach ($x as $v) {
    echo "$v\n";
}

Or with a single for() loop, you could use a modulus calculation to access the appropriate element. Demo
$count = count($x);
for ($i = 0, $limit = $count * 2; $i < $limit; ++$i) {
    echo $x[$i % $count] . "\n";
}

Now, if you do, indeed, need to append the array's values after the original indexed array and maintain the flat, indexed structure, then array_merge() is sensible and intuitive, but not the only way.
With the spread/splat operator (...), you can unpack the input elements twice inside of a new array. While this is a functionless approach and uses less characters, it has a habit of not being terribly efficient. Demo
$result = [...$x, ...$x];

Perhaps my most-preferred approach would be to call array_push() and unpack the elements of the array when pushing data into the original array. I don't know how it performs versus array_merge(), but I find it intuitive/literal about the operation of appending data to the original array. Demo
array_push($x, ...$x);

For a functional-style approach, array_reduce() can have its initial data payload set via its third parameter (in this case the whole input array), then merely push each element one-at-a-time into the result array. Demo
var_export(
    array_reduce(
        $x,
        function($result, $v) {
            $result[] = $v;
            return $result;
        },
        $x
    )
);

Although it is unintuitive to use for this task, array_merge_recursive() works just like array_merge() when fed the indexed array twice. Demo
$result = array_merge_recursive($x, $x)

After all that, I should warn that there are some techniques to avoid.

*

*$result = array_replace($x, $x); is pointless.

*The array union operator is useless.

*array_pad() is unsuitable because its third parameter can only receive one value.

*array_map() returns the same number of elements in its result as its input array.

*array_merge(...array_fill(0, 2, $x)) works, but why call 2 functions when there 0 and 1-function techniques to enjoy.