text:
Q: How to stop adding duplicate values in select list box I'm new to java script. I want prevent adding duplicate values to fourth list box. For example, It would not be same like below i) Paper Manufacturers << Paper Converters << Molded Pulp Products ii) Paper Manufacturers << Paper Converters << Molded Pulp Products And If there is no values in the fourth box, The "Remove Category" Button should be in disabled mode. If there is values & if i select any values in 4th box, The "Remove Category" Button should be enabled & "Add Category" button should be disabled.

$(document).ready(function() {
  var firstCategorySelector = '.select-manage-category';
 var secondCategorySelector = '.select-manage-category1';
 var thirdCategorySelector = '.select-manage-category2';
 var firstCategory = $(firstCategorySelector);
 var secondCategory = $(secondCategorySelector);
 var thirdCategory = $(thirdCategorySelector);
 var addCategoryButton = $("#add-category");
 var removeCategoryButton = $('#remove-category');
 var selectedList = $('#selected-lst-values');
 var choice = $("#tget");
 $('.select-manage-category, .select-manage-category1, .select-manage-category2').change(function() {
  AddCategoryButtonEnable();
 });

 function getCategoryValues() {
  var firstCategoryValue = firstCategory.val();
  var secondCategoryValue = secondCategory.val();
  var thirdCategoryValue = thirdCategory.val();
  return [firstCategoryValue, secondCategoryValue, thirdCategoryValue];
 }

 function isDisableAddButton() {
  var values = getCategoryValues();
  return (!values[0] || !values[1] || !values[2]);
 }

 function AddCategoryButtonEnable() {
  var isDisableAddCategoryButton = isDisableAddButton();
  addCategoryButton.prop("disabled", isDisableAddCategoryButton).toggleClass('text-bold', isDisableAddCategoryButton);
 }

 function getNumberOfSelectedOption() {
  return selectedList.find("option").length;
 }

 function getAvailableChoice() {
  return 20 - parseInt(getNumberOfSelectedOption());
 }

 function setAvailableChoice($numChoice) {
  var strText = ($numChoice !== 20) ? $numChoice + " more " : "up to 20 ";
   choice.text(strText);
 }

 function appendChoice() {
   var count="";
   var givenCategoryArrayValue = getCategoryValues();
   if ($('#selected-lst-values option:contains("' + givenCategoryArrayValue[0] + ' << ' + givenCategoryArrayValue[1] + ' << ' + givenCategoryArrayValue[2] + '")').length > 0) {alert('This category has already been added.');
   return count=1;
  }
   else {
    selectedList.append('<option value="'+ givenCategoryArrayValue[0] + ' << ' + givenCategoryArrayValue[1] + ' << ' + givenCategoryArrayValue[2] +'">' + givenCategoryArrayValue[0] + ' << ' + givenCategoryArrayValue[1] + ' << ' + givenCategoryArrayValue[2] + '</option>');
      return count=2;
           }
  }
 addCategoryButton.click(function() {
   var availableChoice = getAvailableChoice();
   if (availableChoice >= 1) {
    var a=appendChoice();
    if(a==2){
    setAvailableChoice(availableChoice - 1);
    }
   } else {
    setAvailableChoice(0);
   }
  });
  var option = selectedList.find('option:selected');
  selectedList.change(function() {
   removeCategoryButton.prop("disabled", false);
   addCategoryButton.prop("disabled", true);
   _addRemoveButtonClickListener();
  });

 function _addRemoveButtonClickListener() {
   removeCategoryButton.click(function() {
    selectedList.find('option:selected').remove();
    var availableChoice = getAvailableChoice();
    if (0 < availableChoice < 6) {
     setAvailableChoice(availableChoice);
    } else {
     setAvailableChoice(0);
    }
    removeCategoryButton.prop("disabled", true);
   });
  }
 });
.select-manage-category,
.select-manage-category1,
.select-manage-category2 {
  width: 100px;
  float: left;
  margin-right: 4px;
}

p {
  clear: left;
  text-align: center;
}

#selected-lst-values {
  width: 100%;
}

<select class="form-control select-manage-category" size="5">
  <option value="1">Paper Manufacturers</option>
  <option value="2">Paper Products Suppliers</option>
  <option value="3">Paper Chemicals Suppliers</option>
 </select>

<select class="form-control select-manage-category1" size="5">
  <option value="1">Paper Converters</option>
  <option value="2">Lab Apparatus & Supplies</option>
  <option value="3">Service Providers</option>
 </select>

<select class="form-control select-manage-category2" size="5">
  <option value="1">Molded Pulp Products</option>
  <option value="2">Software Vendors</option>
  <option value="3">Information Services</option>
 </select>

You can add up to 5 categories

<input id="add-category" name="add" type="button" value="Add Category" disabled="true">
<input id="remove-category" name="add" type="button" value="Remove Category" disabled="true">

<select id="selected-lst-values" class="form-group percent-100" size="7" multiple="multiple">
</select>

<button id="mnage-category-savebtn" class="btn btn-md btn-radius pi-btn prodetails-btn" type="button">Save Categories </button>

A: Use this script. It will show alert if try to add duplicate entry. I have changed in function appendChoice().
    $(document).ready(function () {
        var firstCategorySelector = '.select-manage-category';
        var secondCategorySelector = '.select-manage-category1';
        var thirdCategorySelector = '.select-manage-category2';

        var firstCategory = $(firstCategorySelector);
        var secondCategory = $(secondCategorySelector);
        var thirdCategory = $(thirdCategorySelector);

        var addCategoryButton = $("#add-category");
        var removeCategoryButton = $('#remove-category');
        var selectedList = $('#selected-lst-values');
        var choice = $("#target");

        $('.select-manage-category, .select-manage-category1, .select-manage-category2').change(function () {
            AddCategoryButtonEnable();
        });

        function getCategoryValues() {
            var firstCategoryValue = firstCategory.val();
            var secondCategoryValue = secondCategory.val();
            var thirdCategoryValue = thirdCategory.val();
            return [firstCategoryValue, secondCategoryValue, thirdCategoryValue];
        }

        function isDisableAddButton() {
            var values = getCategoryValues();
            return (!values[0] || !values[1] || !values[2]);
        }

        function AddCategoryButtonEnable() {
            var isDisableAddCategoryButton = isDisableAddButton();

            addCategoryButton.prop("disabled", isDisableAddCategoryButton).toggleClass('text-bold', isDisableAddCategoryButton);
        }

        function getNumberOfSelectedOption() {
            return selectedList.find("option").length;
        }

        function getAvailableChoice() {
            return 5 - parseInt(getNumberOfSelectedOption());
        }

        function setAvailableChoice($numChoice) {

            var strText = ($numChoice !== 5) ? $numChoice + " more " : "up to 5 ";

            choice.text(strText);
        }

        function appendChoice() {
            var givenCategoryArrayValue = getCategoryValues();
            if ($('#selected-lst-values option:contains("' + givenCategoryArrayValue[0] + ' << ' + givenCategoryArrayValue[1] + ' << ' + givenCategoryArrayValue[2] + '")').length > 0)
                alert('Duplicate value not allowed.');
            else
                selectedList.append('<option value="">' + givenCategoryArrayValue[0] + ' << ' + givenCategoryArrayValue[1] + ' << ' + givenCategoryArrayValue[2] + '</option>');
        }

        addCategoryButton.click(function () {
            var availableChoice = getAvailableChoice();
            if (availableChoice >= 1) {
                appendChoice();
                setAvailableChoice(availableChoice - 1);
            } else {
                setAvailableChoice(0);
            }
        });

        var option = selectedList.find('option:selected');

        selectedList.change(function () {
            removeCategoryButton.prop("disabled", false);
            _addRemoveButtonClickListener();
        });

        function _addRemoveButtonClickListener() {
            removeCategoryButton.click(function () {
                selectedList.find('option:selected').remove();
                var availableChoice = getAvailableChoice();
                if (0 < availableChoice < 6) {
                    setAvailableChoice(availableChoice);
                } else {
                    setAvailableChoice(0);
                }
            });
        }
    });

A: Check the working code snippet

 $(document).ready(function() {
  var firstCategorySelector = '.select-manage-category';
  var secondCategorySelector = '.select-manage-category1';
  var thirdCategorySelector = '.select-manage-category2';

  var firstCategory = $(firstCategorySelector);
  var secondCategory = $(secondCategorySelector);
  var thirdCategory = $(thirdCategorySelector);

  var addCategoryButton = $("#add-category");
  var removeCategoryButton = $('#remove-category');
  var selectedList = $('#selected-lst-values');
  var choice = $("#target");

  $('.select-manage-category, .select-manage-category1, .select-manage-category2').change(function() {
   AddCategoryButtonEnable();
  });

  function getCategoryValues() {
   var firstCategoryValue  = firstCategory.val();
   var secondCategoryValue = secondCategory.val();
   var thirdCategoryValue = thirdCategory.val();
   return [firstCategoryValue, secondCategoryValue, thirdCategoryValue];
  }

  function isDisableAddButton(){
   var values = getCategoryValues();
   return (!values[0] || !values[1] || !values[2]);
  }

  function AddCategoryButtonEnable() {
   var isDisableAddCategoryButton = isDisableAddButton();

   addCategoryButton.prop("disabled", isDisableAddCategoryButton).toggleClass('text-bold', isDisableAddCategoryButton );
  }

  function getNumberOfSelectedOption(){
   return selectedList.find("option").length;
  }

  function getAvailableChoice(){
   return 5 - parseInt(getNumberOfSelectedOption());
  }

  function setAvailableChoice($numChoice){

     var strText = ($numChoice !== 5) ? $numChoice + " more " : "up to 5 ";

   choice.text(strText);
  }

  function appendChoice(){
   var givenCategoryArrayValue = getCategoryValues();
              if ($('#selected-lst-values option:contains("' + givenCategoryArrayValue[0] + ' << ' + givenCategoryArrayValue[1] + ' << ' + givenCategoryArrayValue[2] + '")').length > 0)
                alert('Duplicate value not allowed.');
            else
      selectedList.append('<option value="">' + givenCategoryArrayValue[0] + ' << ' + givenCategoryArrayValue[1] + ' << ' + givenCategoryArrayValue[2] + '</option>');
  }

  addCategoryButton.click(function() {
   var availableChoice = getAvailableChoice();
   if(availableChoice >= 1){
    appendChoice();
    setAvailableChoice(availableChoice - 1);
   } else {
    setAvailableChoice(0);
   }
  });

  var option = selectedList.find('option:selected');

  selectedList.change(function(){
   removeCategoryButton.prop("disabled", false);
            addCategoryButton.prop("disabled", true);
   _addRemoveButtonClickListener();
  });

  function _addRemoveButtonClickListener(){
   removeCategoryButton.click(function() {
    selectedList.find('option:selected').remove();
    var availableChoice = getAvailableChoice();
    if(0 < availableChoice < 6){
     setAvailableChoice(availableChoice);
    } else {
     setAvailableChoice(0);
    }
                removeCategoryButton.prop("disabled", true);
   });
  }
 });
.select-manage-category,
.select-manage-category1,
.select-manage-category2 {
  width: 100px;
  float: left;
  margin-right: 4px;
}

p {
  clear: left;
  text-align: center;
}

#selected-lst-values {
  width: 100%;
}

<select class="form-control select-manage-category" size="5">
  <option>Paper Manufacturers</option>
  <option>Paper Products Suppliers</option>
  <option>Paper Chemicals Suppliers</option>
 </select>

<select class="form-control select-manage-category1" size="5">
  <option>Paper Converters</option>
  <option>Lab Apparatus & Supplies</option>
  <option>Service Providers</option>
 </select>

<select class="form-control select-manage-category2" size="5">
  <option>Molded Pulp Products</option>
  <option>Software Vendors</option>
  <option>Information Services</option>
 </select>

You can add up to 5 categories

<input id="add-category" name="add" type="button" value="Add Category" disabled="true">
<input id="remove-category" name="add" type="button" value="Remove Category" disabled="true">

<select id="selected-lst-values" class="form-group percent-100" size="7" multiple="multiple">
</select>

<button id="mnage-category-savebtn" class="btn btn-md btn-radius pi-btn prodetails-btn" type="button">Save Categories </button>


text:
Q: Finding Factorial using Integral Definition $n! = \int_{0}^{\infty} {e}^{-x}{x}^{n} \,dx$
How can we find $400!$?
$400! = \int_{0}^{\infty} {e}^{-x}{x}^{400} \,dx$
Integration by parts is way too complicated, what are the other options?

A: Integration by parts will only tell you that $400!=400\cdot 399!$, which we know from the definition of a factorial; in fact, this is one way to prove the integral definition. Using the integral to calculate the factorial is rarely the most efficient method, particularly when $n$ is an integer, as in your example. The fastest method of calculating a factorial with integer $n$ is through its prime factors, which are easily calculable by the formula $n!$ divides $p$ precisely $\displaystyle \sum_{k=1}^{\lfloor \log_p(n) \rfloor} \left \lfloor \frac n{p^k} \right \rfloor$ times. See here for a proof (of the complexity; the formula is due to Legendre). If you want to be able to calculate $\Gamma(z)$ for all complex $z$, see this post.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Accumulo's createtable command gets stuck and does not create a table I was trying to create a table inside Accumulo using the createtable command and found out that it was getting stuck. I waited for around 20 mins before cancelling the createtable command.
createtable test_table

I have one master and 2 tablet servers and found out that my master and one of the tablets died. I could not telnet to port 9997 of that particular tablet server and I could not even telnet to port 29999 (master.port.client in accumulo-site.xml). When I saw the tserver logs of the dead server, I saw the following entries.
2016-05-10 02:12:07,456 [zookeeper.DistributedWorkQueue] INFO : Got unexpected z
ookeeper event: None for /accumulo/be4f66be-1508-4314-9bff-888b56d9b0ce/recovery
2016-05-10 02:12:23,883 [zookeeper.ZooCache] WARN : Saw (possibly) transient exc
eption communicating with ZooKeeper, will retry
org.apache.zookeeper.KeeperException$SessionExpiredException: KeeperErrorCode =
Session expired for /accumulo/be4f66be-1508-4314-9bff-888b56d9b0ce/tables
        at org.apache.zookeeper.KeeperException.create(KeeperException.java:127)
        at org.apache.zookeeper.KeeperException.create(KeeperException.java:51)
        at org.apache.zookeeper.ZooKeeper.getChildren(ZooKeeper.java:1472)
        at org.apache.accumulo.fate.zookeeper.ZooCache$1.run(ZooCache.java:210)
        at org.apache.accumulo.fate.zookeeper.ZooCache.retry(ZooCache.java:162)
        at org.apache.accumulo.fate.zookeeper.ZooCache.getChildren(ZooCache.java
:221)
        at org.apache.accumulo.core.client.impl.Tables.exists(Tables.java:142)
        at org.apache.accumulo.server.tabletserver.LargestFirstMemoryManager.tab
leExists(LargestFirstMemoryManager.java:149)
        at org.apache.accumulo.server.tabletserver.LargestFirstMemoryManager.get
MemoryManagementActions(LargestFirstMemoryManager.java:175)
        at org.apache.accumulo.tserver.TabletServerResourceManager$MemoryManagem
entFramework.manageMemory(TabletServerResourceManager.java:408)
        at org.apache.accumulo.tserver.TabletServerResourceManager$MemoryManagem
entFramework.access$400(TabletServerResourceManager.java:318)
        at org.apache.accumulo.tserver.TabletServerResourceManager$MemoryManagem
entFramework$2.run(TabletServerResourceManager.java:346)
        at org.apache.accumulo.fate.util.LoggingRunnable.run(LoggingRunnable.jav
a:35)
        at java.lang.Thread.run(Thread.java:745)
2016-05-10 02:12:23,884 [zookeeper.ZooCache] WARN : Saw (possibly) transient exc
eption communicating with ZooKeeper, will retry
org.apache.zookeeper.KeeperException$SessionExpiredException: KeeperErrorCode =
Session expired for /accumulo/be4f66be-1508-4314-9bff-888b56d9b0ce/tables/!0/con
f/table.classpath.context
        at org.apache.zookeeper.KeeperException.create(KeeperException.java:127)
        at org.apache.zookeeper.KeeperException.create(KeeperException.java:51)
        at org.apache.zookeeper.ZooKeeper.exists(ZooKeeper.java:1045)
        at org.apache.accumulo.fate.zookeeper.ZooCache$2.run(ZooCache.java:264)
        at org.apache.accumulo.fate.zookeeper.ZooCache.retry(ZooCache.java:162)
        at org.apache.accumulo.fate.zookeeper.ZooCache.get(ZooCache.java:289)
        at org.apache.accumulo.fate.zookeeper.ZooCache.get(ZooCache.java:238)
        at org.apache.accumulo.server.conf.ZooCachePropertyAccessor.get(ZooCache
PropertyAccessor.java:117)
        at org.apache.accumulo.server.conf.ZooCachePropertyAccessor.get(ZooCache
PropertyAccessor.java:103)
        at org.apache.accumulo.server.conf.TableConfiguration.get(TableConfigura
tion.java:99)
        at org.apache.accumulo.tserver.constraints.ConstraintChecker.classLoader
Changed(ConstraintChecker.java:93)
        at org.apache.accumulo.tserver.tablet.Tablet.checkConstraints(Tablet.jav
a:1225)
        at org.apache.accumulo.tserver.TabletServer$8.run(TabletServer.java:2848
)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:51
1)
        at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.
access$301(ScheduledThreadPoolExecutor.java:180)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.
run(ScheduledThreadPoolExecutor.java:294)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.
java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor
.java:617)
        at java.lang.Thread.run(Thread.java:745)
2016-05-10 02:12:23,887 [zookeeper.ZooReader] WARN : Saw (possibly) transient ex
ception communicating with ZooKeeper
org.apache.zookeeper.KeeperException$SessionExpiredException: KeeperErrorCode =
Session expired for /accumulo/be4f66be-1508-4314-9bff-888b56d9b0ce/tservers/accu
mulo.tablet.2:9997
        at org.apache.zookeeper.KeeperException.create(KeeperException.java:127)
        at org.apache.zookeeper.KeeperException.create(KeeperException.java:51)
        at org.apache.zookeeper.ZooKeeper.exists(ZooKeeper.java:1045)
        at org.apache.accumulo.fate.zookeeper.ZooReader.getStatus(ZooReader.java
:132)
        at org.apache.accumulo.fate.zookeeper.ZooLock.process(ZooLock.java:383)
        at org.apache.zookeeper.ClientCnxn$EventThread.processEvent(ClientCnxn.j
ava:522)
        at org.apache.zookeeper.ClientCnxn$EventThread.run(ClientCnxn.java:498)
2016-05-10 02:12:24,252 [watcher.MonitorLog4jWatcher] INFO : Changing monitor lo
g4j address to accumulo.master:4560
2016-05-10 02:12:24,252 [watcher.MonitorLog4jWatcher] INFO : Enabled log-forward
ing

Even the master server's logs had the same stacktrace. My zookeeper is running.
At first, I thought it was a disk issue. Maybe there was no space. But that was not the case. I ran the fsck on the accumulo instance.volumes and it returned the HEALTHY status.
Does anyone know what exactly happened and if possible, how to avoid it?
EDIT : Even the tracer_accumulo.master.log had the same stacktrace.

A: ZooKeeper session expirations occur when a thread inside the ZooKeeper client does not get run within the necessary time (by default, 30s) to maintain the session which is an in-memory state between ZooKeeper client and server. There is no single explanation for this, but many common culprits:

*

*JVM garbage collection pauses in the client. Accumulo should log a warning if it experienced a pause.

*Lack of CPU time. If the host itself is overburdened, Accumulo might not have the cycles to run all of the tasks it needs to in a timely manner.

*Lack of sockets/filehandles, Accumulo could be trying to connect to ZooKeeper, but be unable to open new connections

*ZooKeeper might be rate-limiting connections as a denial-of-service prevention. Check the zookeeper logs for errors about dropping/denying new connections from a specific IP, and, if you see these errors, consider increasing maxClientCnxns in zoo.cfg.


text:
Q: Combine multiple AJAX calls to one with PHP I have a script that retrieves PHP variables using the $get() function but I have multiple requests for each variable. I want to do this because I want the calls to be individual and not waiting to load all variables.
Here is my simple code:
FUNCTIONS.PHP
$content1 = 'This is a good solution.';
$content2 = 'This is another good solution.';

if(preg_match('[good]', $content1)) {

$result1 = "
Great, we found something here.
";

}else{

$result1 = "
Oops, nooooo.
";
}
/////////////////////////////////

if(preg_match('[another]', $content2)) {

$result2 = "
Great, we found something here.
";

}else{

$result2 = "
Oops, nooo.
";
}

$action = $_GET['action'];

switch ($action) {
case 'result1':
echo $result1;
break;
case 'result2':
echo $result2;
break;
default:
echo 'Test';

}

GET.PHP

........

So how can I "combine" all javascript calls to one (using parameters, I do not know) so will not be necesary to create a call for each variable.

A: Try this:
//PHP: put the varibles into an array
$variables = array('result1'=> $result1, 'result2'=> $result2);
echo json_encode($variables);

//JS: change the ajax call to get an json object
$.get('functions.php', function(data) {

$('.result1').html(data.result1);
$('.result2').html(data.result2);

}, 'json');

Hope it can help.

A: Do you mean, something like this?
function ajaxcall(action, div) {
    $.get('functions.php?action='+ action, function(data) {

        $(div).html(data);

    });
}

You would make your calls as
ajaxcall('result1','.result1');
ajaxcall('result2','.result2');
ajaxcall('result3','.result3');

... and so on.

A: Use jQuery deferred to bind multiple async callback into one.
first_ajax = function(){
  return $.get("your_url.php", function(){ //blah });
}

second_ajax = function(){
  return $.get("your_second_url.php", function(){ //blah });
}

combine_two_ajax = function(){
  $.when(first_ajax(), second_ajax())
    .done( function(ret_from_first, ret_from_second){
             //something to do
             …
           }
}

Calling combine_two_ajax() will trigger two async and callback to you when two async tasks are all done.


text:
Q: What is the collation we have to use for ½ symbol in SQL Server 2008? How to change a collation for a column , for ½ symbol in SQL Server 2008 ??

A: I made a quick test and for example collation SQL_Latin1_General_CP1_CI_AS can store that symbol.
create table test1(
    symbol varchar(10) -- SQL_Latin1_General_CP1_CI_AS
)

insert test1(symbol) values ('½')

select * from test1

symbol
½


text:
Q: Newlines as line breaks instead of new paragraphs When I paste a simple bare text like this
set1:  7-mild1_spatial-CV
set2:  7-mild1_spatial-CV-noStarting

  var                mean1 mean2 meanDif  pairTtestP set1ge set2gt diffMin diffMax
1 CV_AUC_1h          0.783 0.777 -0.00584 0.003  **  12     1      -0.0183  0.00132
2 CV_AUC_1h_weighted 0.778 0.772 -0.00607 0.005  **  12     1      -0.0217  0.00187
3 CV_R2_dev          0.234 0.224 -0.00981 0.000 ***  13     0      -0.0182 -0.00154
4 CV_R2_devTsc       0.220 0.210 -0.01042 0.000 ***  13     0      -0.0184 -0.00282
5 CV_R2_LR           0.204 0.196 -0.00844 0.000 ***  13     0      -0.0161 -0.00135
6 CV_R2_LRtsc        0.175 0.167 -0.00812 0.000 ***  13     0      -0.0153 -0.00232
7 CV_R2_avgScore     0.173 0.166 -0.00697 0.000 ***  13     0      -0.0162 -0.00270

into my Word 2016, looks like this:

I.e., Word treats every line of this bare text as new paragraph. I would like it to treat the line as line, so that instead of those paragraph breaks it would insert just line breaks. The desired result should look like this:

How do I achieve this in Word? It's very simple and intuitive, Word should be able to do that.

A:
It's very simple and intuitive, Word should be able to do that

Word pastes what it receives from clipboard.
Many programs doesn't have different line- and paragraph breaks, in those programs the same character (e.g. CR LF in Windows) is used as "break" which is used in Word as paragraph break, therefore it's copied to Word (and other programs too) as paragraph break.
From programs supporting both type of breaks copy & paste is correct.
As a workaround you can select the text after inserting, than replace paragraph marks (^p) to manual line breaks (^l)


text:
Q: how to set ServicePointManager.ServerCertificateValidationCallback in web.config How do I set this in web.config file
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) =>true;

A: Try this;
Write your code in Application_Start of Global.asax.
It should work..!!!
OR
In Config file;
<configuration>
 <system.net>
   <settings>
     <servicePointManager
        checkCertificateName="false"
        checkCertificateRevocationList="false"
     />
  </settings>
</system.net>
</configuration>

you can also VISIT MSDN for the same.


text:
Q: Optimization - Saving into Database takes too much time ASP.NET Core 3.1 I am working on .NET Core 3.1 with TravelPort API.
I want to store the flight request and flight response into our database. Saving data into database takes too much time.
await context.Logs.AddAsync(new Log()
                {
                    Request = JsonSerializer.Serialize(seatMapReq),
                    Response = JsonSerializer.Serialize(res.SeatMapRsp),
                    ReqFileName = reqFileName,
                    ResFileName = resFileName,
                    RequestType = "Air_Seat_Map",
                    Success = true,
                });

await context.SaveChangesAsync();  // in this line API take 5s-6s

How can I optimize this?


text:
Q: awk math: check result before printing My input is:
cat input
   1
   4
  -2

I want to subtract some value (e.g., 2) from column 1. If result is > 0 print it or else print 0. In other words, I don't want any negative numbers.
My try is:
 awk '{NUMBER=$1-2} if (NUMBER > 0) print NUMBER; else print 0'

But I am probably making some syntax mistake.
Wanted ouput is:
0
2
0

A: This can be an option:
$ awk '{$1=$1-2>0?$1-2:0; print $1}' file
0
2
0

$1=$1-2>0?$1-2:0 is a ternary operator and is read like this:
Set $1 to:

    if ($1-2 > 0)
         ==> $1-2
    else ==> 0

and then it is printed out print $1.

A: With this:
awk '{NUMBER=$1-2} if (NUMBER > 0) print NUMBER; else print 0'

you're putting the if... statement in the condition part of the awk body instead of the action part because it's not enclosed in curly brackets. This is the correct syntax for what you wrote:
awk '{NUMBER=$1-2; if (NUMBER > 0) print NUMBER; else print 0}'

but in reality I'd write it as:
awk '{NUMBER=$1-2; print (NUMBER > 0 ? NUMBER : 0)}'


text:
Q: Lack of ripples in Bootstrap Material Design I am trying to implement the bootstrap-material-design theme to my existing Bootstrap site.
In my main.blade.php, I have this on top to denote the stylesheets.
<!-- CSS -->
<link href="/css/all.css" rel="stylesheet">
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/bootstrap-material-design/0.2.1/css/material.min.css" />
{{--<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-material-design/0.3.0/css/material-fullpalette.min.css" />--}}

<!-- Scripts -->
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src='http://code.jquery.com/ui/1.10.2/jquery-ui.js'></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.1/js/bootstrap.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/bootstrap-material-design/0.3.0/js/material.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/bootstrap-material-design/0.3.0/js/ripples.min.js'></script>
<script type="text/javascript"></script>

Here is in my main blade file - this is the blade wrapper file that exists across all my views.
At the bottom of this main blade, I have this JS as instructed by the docs:
<script>
    $(document).ready(function() {
        $.material.init();
    });
</script>

However, when I try to click on my button or nav bar elements, there is no ripple effect. I do not see any errors on my console either.
Do I need to add any additional code to my button classes?
EDIT:
Here's the Network tab:

A: Please try this one. i change order or scripts and add one css
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-material-design/0.3.0/css/ripples.min.css">

    <!DOCTYPE html>
<html lang="en">
<head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
        <title></title>

    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-material-design/0.3.0/css/roboto.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-material-design/0.3.0/css/material-fullpalette.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-material-design/0.3.0/css/ripples.min.css">

    <script type="text/javascript"></script>

    <link href='http://fonts.googleapis.com/css?family=Roboto:400,300' rel='stylesheet' type='text/css'>
</head>
<body>
        <div class="container">
            <button class="btn btn-success ripple-effect">Wow.!</button>
            <button class="btn btn-info ripple-effect">Ripple Work.!</button>
        </div>
</body>
</html>
 <script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src='http://code.jquery.com/ui/1.10.2/jquery-ui.js'></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-material-design/0.3.0/js/material.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-material-design/0.3.0/js/ripples.min.js"></script>
<script>
$( document ).ready(function()
{
    $(function()
    {
        $.material.init();
    });
});
</script>

A: Load arrive.js before the material-design.js
Install using bower bower install arrive --save


text:
Q: Python super class error here i m posting a part of code which i don't understand.
Please help me with that:
Code-
def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.filters['assigned'].extra.update(
            {'to_field_name': User.USERNAME_FIELD})

But when i try this code i got syntax error on super(), i don't know why??

python version 2.7 doesn't support this syntax super should have
  argument in python2

And what actually this code is mean??
thanks in advance

A: From the docs on super:
super(type, obj) -> bound super object; requires isinstance(obj, type)
   super(type) -> unbound super object
   super(type, type2) -> bound super object; requires issubclass(type2, type)
   Typical use to call a cooperative superclass method:
   class C(B):
       def meth(self, arg):
           super(C, self).meth(arg)

You gave no arguments to super, so it does not know what to do on Python2.  For a solution that works on Python2 and Python3, try super(C, self)


text:
Q: vba end if without block if I keep getting this error, but can't figure out why. It looks like all rules are followed.
The structure as I read is the following - If -> ElseIf -> End If. But here I get an error though it's all the same.
Sub hide()
        Application.ScreenUpdating = False
        Dim wRange As Range
        Set wRange = Range("A5:B10")

        Dim mergedRows As Integer
        Dim mergedColumns As Integer

        Dim cellFirst As Range

        For Each cell In wRange
            If IsEmpty(cell) Then
                cell.EntireRow.Hidden = True
            ElseIf cell.MergeCells Then
                mergeRows = cell.MergeArea.Rows.Count
                mergeColumns = cell.MergeArea.Columns.Count
                With cell.MergeArea
                    Set cellFirst = cell.MergeArea(Cells(1, 1))
                    If IsEmpty(cellFirst) Then
                        cellFirst.EntireRow.Hidden = True
                    End If
            End If
        Next
End Sub

A: You need to also close your With statement.
With cell.MergeArea
   Set cellFirst = cell.MergeArea(Cells(1, 1))
   If IsEmpty(cellFirst) Then
      cellFirst.EntireRow.Hidden = True
   End If
End With


text:
Q: Can't Find Blank Activity in Eclipse New android Application Hi all my problem is I was setting the eclipse environment for Ubuntu 13.10 with eclipse, SDK and JDK 7.
Normally when I create New->Android Application Project and going through this process I supposed to see:

*

*Blank Activity

*FullScreen Activity

*Master/Detail Flow

Problem:
First option (1- Blank Activity) don't show up and I don't know why.
I hope anyone can help in this problem or tell me how to create an activity in an empty project.
I've tried:
I tried to install another copy of eclipse and link it with the SDK but that didn't work also.

A: ok you must extend you AndroidManifest.xml file, the reply function is too small for a full reply, so i'll post this solution :-~
<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <!-- Main (starter) Activity -->
    <activity
        android:name="cn.brandhook.apps.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <!-- blank (new created) Activity -->
    <activity
        android:name="cn.brandhook.apps.NewBlankActivity"
        android:label="@string/title_new_blank_activity"
        android:parentActivityName="MainActivity" >
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="MainActivity" />
    </activity>

</application>

having problems with R.Java not created/reCreated you should check Developing for Android in Eclipse: R.java not regenerating
i guess this won't help you much, but it was supposed to be a mere reply (comment)

A: I just reinstalled Everything and it worked very well.
Any way now the official Version for Android Development is Android Studio.


text:
Q: How to change Collection View Cell background color with Pan Gesture I've created collection view and added UIView onto it for pan gesture recognition squared view image
.
I have an array of indexPaths and compare all cell frames to gestureLocation to change its color.
 @objc private func handleTapGesture() {
    let gestureLocation = self.tapGesture.location(in: gestureView)

    for item in self.collectionViewCellIndexPathes {
        if let cell = (collectionView.cellForItem(at: item) as? CollectionViewCell) {

            if ((gestureLocation.x > cell.frame.origin.x && gestureLocation.x < cell.frame.origin.x+20) && (gestureLocation.y > cell.frame.origin.y && gestureLocation.y < cell.frame.origin.y+20)) {

                if cell.isColored {
                    cell.backgroundColor = .red
                    cell.isColored = false

                }
                else {
                    cell.backgroundColor = .black
                    cell.isColored = true
                }
            }

        }

    }
}

This code works but cell background color changes several times if gesture location is inside cell's frame. What's the way to change cell background color and don't change it until pan gesture hovers it another time.


text:
Q: Extension of a linear transformation and Zorn's lemma
Let $V,W$ be vector spaces over some field $\mathbb{F}$ and $B$ a subspace of $V$ and $T:B \longrightarrow W$ a linear transformation.Then $T$ can be extended to a linear transformation $L$ on $V$,i.e there is a linear transformation $L:V \longrightarrow W$ such that $L|_B=T$.

This is an exercise from Derek Goldray's book, Classical set theory.
I would like to show my attempt to prove this:
$Proof:$
Let $A$ be the family of pairs $(S,L)$ where $S \supseteq B$ and $S$ is a linear subspace of $V$ and $L:S \longrightarrow W$ a linear transformation such that $L|_B=T$
We now partially order $A$ in this way: $(S_1,L_1) \leqslant (S_2,L_2) \Longleftrightarrow S_1 \subseteq S_2$ and $L_2|_{S_1}=L_1$
We have that $A \neq \emptyset$ because $(B,T) \in A$.
Let $C=\{(S_i,L_i)|i \in I\}$ be a chain in $A$ and let $(M,F)$ be the pair where $M=\bigcup_{i \in I}S_i$ and $F:M \longrightarrow W$ such that $F(x)=L_i(x),x \in S_i$.
We can easily see that $M$ is a linear subspace of $V$ using the fact that any two elements in a chain are comparable.
Also let $x,y \in M$. So $x \in S_i$ and $y \in S_j$ for some $i,j \in I$.But $S_i \subseteq S_j$ or $S_j \subseteq S_i$.
Assume that $S_j \subseteq S_i$. We know that $S_i$ is a subspace of $V$ thus $x,y \in S_i \Longrightarrow x+y \in S_i$ and $F(x+y)=L_i(x+y)=L_i(x)+L_i(y)=F(x)+F(y)$.
In the same way we can prove that $F(ax)=aF(x),\forall x \in M,\forall a \in \mathbb{F}$. Thus $F$ is a linear transformation and an extension of $T$.
Clearly $(M,F)$ is an upperbound of $C$ because $\forall (S_i,L_i) \in C$ we have that $S_i \subseteq M$ and $F|_{S_i}=L_i \Longrightarrow (S_i,L_i) \leqslant (M,F), \forall i \in I$ and $(M,F)\in C$ ,thus form Zorn's lemma exists a maximal element $(S_0,L_0) \in A$
Now we need to show that $S_0=V$.
Let $S_0 \subsetneq V$ and $z \in V$ \ $S_0$.
Let $Y=<S_0,z>=\{s+az|s \in S_0,a \in \mathbb{F}\}$.Clearly $S_0 \subsetneq Y$ and $Y$ is a proper  subspace of $V$.
Let $L_1: Y \longrightarrow W$ such that $L_1(s+az)=L_0(s)+av$ for some $v \in W$
$L_1$ is a linear transformation.
$$L_1(s)=L_1(s+0z)=L_0(s)$$ $$L_1(z)=L_1(\bar{0}+1z)=L_0(\bar{0})+v=\bar{0}+v=v$$
We have that $L_1(S_0)=L_0(S_0)$ \Longrightarrow $(S_0,L_0)<(Y,L_1)$
This is a contradiction because of the maximality of $(S_0,L_0)$ thus $$S_0=V$$
Is my attempt correct?
Thnak you in advance!

A: I think there is a problem, but is easy to fix. You can't define $L_1 : Y \rightarrow W$ as $ L_1(s + az) = L_0 (s) + a z$ because you don't know if $z$ $\in$ $W$ ($W$ and $V$ may be diferent vector spaces) an easy way to solve this is defining $ L_1(s + az) = L_0 (s) + a v$, for some $v$ $\in$ $W$.

A: You have essentially proved Baer's Criterion for fields.
A different strategy is to prove $B$ has a complement and you might think to the similarities in the two approaches.

Consider the family $\mathcal{A}$ of all subspaces $C$ of $V$ such that $C\cap B=\{0\}$, ordered by inclusion.
The union of a chain in $\mathcal{A}$ is again a member of $\mathcal{A}$ (prove it). By Zorn's lemma, $\mathcal{A}$ has a maximal element $M$.
Suppose $B+M\ne V$ and let $v\in V$, $v\notin B+M$. Let's prove that $(M+\langle v\rangle)\cap B=\{0\}$. Suppose $a\in\mathbb{F}$, $x\in M$, and $y\in B$ with $av+x=y$, so $av=y-x\in B+M$.
If $a\ne0$, then $v=a^{-1}(y-x)\in B+M$, a contradiction. So $a=0$, hence $x=y$, so $x=y=0$.
This contradicts the maximality of $M$. Therefore $B+M=V$ and we can define $L$ to be $T$ on $B$ and $0$ on $M$.


text:
Q: programa en java que eleve 100 numeros al cubo package pow;
import java.util.*;
/**
 *
 * @author Cuenta Casa
 */
public class Pow {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
        int num;
        do{
           System.out.print("Introduce un numero entero >=0 ");
           num = sc.nextInt();
        }while(num<0);
        System.out.println("3 ^ " + num + " = " + potencia(num));
    }
    public static double potencia(int n){
           if(n==0)   //caso base
              return 1;
           else
              return 3 * potencia(n-1);
    }

}`introducir

el código aquí`

A: Tú puedes usar el método pow de la clase Math para calcular cualquier potencia.
Veamos un programa con un método:
calcularPotencia(int intValor, int intPotencia)

Recibirá dos parámetros, el valor y la potencia que queremos calcular.
Este sería el código:
public class Main {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        String strMensaje = "Escriba un número: ";
        for (int i = 0; i < 100; i++) {
            System.out.print(strMensaje);

            while (!input.hasNextInt()) {
                strMensaje = "No escribió un número. Escriba un número: ";
                System.out.print(strMensaje);
                input.next();
            }
            int intValor = input.nextInt();
            if (intValor == 0) {
                strMensaje = "El número debe ser mayor que 0. Escriba un número: ";

                i = i - 1;
            } else {
                strMensaje = "Escriba un número: ";
                calcularPotencia(intValor, 3);
            }
        }
        input.close();

    }

    public static void calcularPotencia(int intValor, int intPotencia) {

        double dblPotencia = Math.pow(intValor, intPotencia);
        System.out.println("Potencia " + intPotencia + " de " + intValor + " es " + dblPotencia);

    }

}

Ejemplo del resultado:
Escriba un número: 27
Potencia 3 de 27 es 19683.0
Escriba un número: a
No escribió un número. Escriba un número: 90
Potencia 3 de 90 es 729000.0
Escriba un número: 0
El número debe ser mayor que 0. Escriba un número: 43
Potencia 3 de 43 es 79507.0


text:
Q: Testing 2FA With Daylight Saving I have tested 2FA to be working with server timezone: (UTC) Dublin, Edinburgh, Lisbon, London and device timezone: (UTC +08:00) Kuala Lumpur, Singapore with current datetime. Daylight Saving will end on October 30, 2016 at 2:00 AM and clock will go back 1 hour.
When the server auto adjust the clock, will our device still be able to authenticate? Is it possible to test this capability now before the Daylight Saving end on October 30, 2016 at 2:00 AM?

A: Yes, your device should still be able to authenticate after the Daylight Saving time change.  Most time-based two factor authentication implementations (e.g. Google Authenticator) use the TOTP algorithm defined by RFC 6238.  This RFC requires that the T counter value be time-based:

...the current Unix time (i.e., the number of seconds elapsed since midnight UTC of January 1, 1970) for OTP generation.

Since the T value is based on UTC timestamps, those timestamps will not be affected by local timezones or by things like Daylight Savings time changes.
Hope this helps!


text:
Q: ELMAH - Email not received in production environment I have integrated ELMAH library for logging the error. I have integrated email code for getting error list but unable to get those errors. Can anyone help me for same. Below is my configuration code in web.config
Web.config File
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <sectionGroup name="elmah">

    </sectionGroup>
  </configSections>

  <system.web>
    <compilation debug="true" targetFramework="4.5.2" />
    <httpRuntime targetFramework="4.5.2" />
    <httpModules>
      <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" />
      <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" />
      <add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" />
    </httpModules>
  </system.web>

  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <modules>
      <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" preCondition="managedHandler" />
      <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" preCondition="managedHandler" />
      <add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" preCondition="managedHandler" />
    </modules>
  </system.webServer>

  <elmah>

    <errorLog type="Elmah.XmlFileErrorLog, Elmah" logPath="~/ElmahLog" />
    <errorMail from="error@devtracker.com"
     to="ankitkanojia.rs@gmail.com"
     subject="Devtracker - Error occurs"
     async="true" />

    <security allowRemoteAccess="false" />
  </elmah>

  <location path="elmah.axd" inheritInChildApplications="false">
    <system.web>
      <httpHandlers>
        <add verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" />
      </httpHandlers>
    </system.web>
    <system.webServer>
      <handlers>
        <add name="ELMAH" verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" preCondition="integratedMode" />
      </handlers>
    </system.webServer>
  </location>

</configuration>

A: After going through your question, I've found that you just forgot to add an email setting. Add the below lines in your web.config. Make sure to change the hostname, port, username, and password.
<system.net>
    <mailSettings>
      <smtp deliveryMethod="Network">
        <network host="host address" port="12345" userName="username here" password="password here"/>
      </smtp>
    </mailSettings>
</system.net>


text:
Q: How large can a circle's radius be in an ellipse? I have an ellipse centered on the origin parameterized by $a$ and $b$. Given its $x$ coordinate, how large can its radius be and still have the circle inside the ellipse?

A: The maximal radius is the minor axis of the ellipse. You can derive this by first picking the $x$ coordinate, then optimizing.


text:
Q: How to remove http(s) off of a URL on the page? I am dynamically pulling in a URL from my CMS onto the page to be part of the page content, but I want to display it without the http:// (or https://) portion by using javascript.
Basically I want this:

To render on the page as:

Please see my HTML:

      Visit https://www.theurl.com

Please note I added the ID of "partner-website-element" to the first div (I can only add a class or an ID to that element).
Here is my javascript so far:

When I load the page I get the error in the console:
Uncaught TypeError: Cannot read property 'replace' of undefined

PS: I'm not sure if my regex is right yet since so far I have only tried replacing http with '', ie cleanurl.replace(/http/gi, '');

A: Here is the vanilla JS for it:

console.log( `https://www.theurl.com`.replace(/https?:\/\/(www\.)?/gi, '') );
console.log( `http://www.theurl.com`.replace(/https?:\/\/(www\.)?/gi, '') );
console.log( `https://theurl.com`.replace(/https?:\/\/(www\.)?/gi, '') );

Your cleanurl is failing because you are calling .innerHTML on an object which doesn't provide that method. You need to loop cleanurl and use .innerHTML against each member.

A: I'm not sure if I understand but you should use .innerText, also if you want to use that query you should use cleanurl[0] the error is because  cleanurl it is not a String so .replace() does not work.

var a = document.querySelector("#partner-website-element a");
var url = a.innerText;
a.innerText = url.replace(/https?:\/\/w{3}\./gi,"");

      Visit https://www.theurl.com

A: *

*Wait until the page loads before accessing the DOM

*Access the first element of the NodeList returned by getElementsByTagName

*Clean the url and set it back
 document.onLoad = function () {

       var ele = document.getElementById("partner-website-element").getElementsByTagName('a');

       ele[0].innerHTML = ele[0].innerHTML.replace(/http(s):\/\/(www)/gi, '');
 }

A: Answering My Own Question Here.
Here is my working code / what I ended up doing (welcome criticism/improvement ideas), including my own comments added:


text:
Q: Stackable Panel Delphi Component does anyone know of a Delphi component that implements something similar to what jquery sortable does, but for a desktop application?
i.e. a vertical control that contains a number of panels that can be reordered and also used as containers for other components (specifically TMemos containing different bits of text).
Thanks for any info,
Breandan.

A: While I do it from code, and not designtime, this is what I would use a TScrollbox or TPanel containing some Frames or Panels, which are all aligned top, for.  If I want a collapse/expand for the frames, I just put a button in the frame that allows you to collapse the frame to a minimal height such as 20 pixels when collapsed, and something taller when expanded.
the frames inside could really be any control you want, even Panels containing a few other controls. The top level controls can be reordered within the parent panel or scrollbox.

A: TMS Has TAdvPanelGroup that can be collapsed/expanded.  See screenshot in the lower-right:
http://www.tmssoftware.com/site/advpanel.asp

A: Only one run, then I move and resize them from the running application.

Here's the dfm:
object Form2: TForm2
  Left = 0
  Top = 0
  Caption = 'Form2'
  ClientHeight = 337
  ClientWidth = 635
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'Tahoma'
  Font.Style = []
  OldCreateOrder = False
  PixelsPerInch = 96
  TextHeight = 13
  object clbr1: TCoolBar
    Left = 0
    Top = 0
    Width = 635
    Height = 313
    Bands = <
      item
        Control = gb1
        ImageIndex = -1
        MinHeight = 123
        Width = 629
      end
      item
        Control = pnl1
        ImageIndex = -1
        MinHeight = 112
        Width = 629
      end>
    object gb1: TGroupBox
      Left = 11
      Top = 0
      Width = 620
      Height = 123
      Caption = 'gb1'
      TabOrder = 0
      object lbledt1: TLabeledEdit
        Left = 112
        Top = 40
        Width = 121
        Height = 21
        EditLabel.Width = 32
        EditLabel.Height = 13
        EditLabel.Caption = 'lbledt1'
        TabOrder = 0
      end
    end
    object pnl1: TPanel
      Left = 11
      Top = 125
      Width = 620
      Height = 112
      Caption = 'pnl1'
      TabOrder = 1
      object rg1: TRadioGroup
        Left = 128
        Top = 4
        Width = 185
        Height = 105
        Caption = 'rg1'
        Items.Strings = (
          'dsfsdf'
          'sdfsdfsd')
        TabOrder = 0
      end
    end
  end
end

A: I haven't found a standard control that does what you want in Delphi 2007, but I would offer a custom solution similar to the one Warren suggested.  The main difference is that I would create it within a TFrame so you could more easily maintain the code that allows you to manipulate the controls and their interaction with each other.  You could also create methods within the frame for adding new panels (with memos and the text to display), move them around, etc.
It's a bit of work but it can also be a great learning experience.  The best part is once you are done you can reuse that frame anywhere you want on any form or within another frame.  If you do it right it will work without hassle as well.


text:
Q: Tracking goals with the same destination URL I have three goals that have the same destination URL. They all have different funnels but report the same number of conversions in the past 7 days in the Admin > Goals screen. When I verify the goal they all have the same percentage of completions. If I look at the goal funnel visualization it will show different numbers as the final outcome over what I believe is the same past 7 days for each goal.
Shouldn't the outcome of the goal funnel visualization be the same conversion number on the Admin > Goals screen?
Is the tracking of what's on the Admin > Goals screen past 7 day conversions and the final value of the goal funnel visualization just inherently different?

A: In all reports you will see the same number of Goal Completions and CR for all your 3 goals.
Only in report 'Funnel Visualization' you will see conversions for each funnel separately.

A: The Funnel Visualization has a logic of its own, read the documentation for differences with the most reliable Goal Flow in Analytics:
https://support.google.com/analytics/answer/2976313?hl=en
Here you will find more information about the inconsistencies of the Funnel Visualization:
https://www.analyticstraps.com/stesso-obiettivo-ma-totale-completamento-diverso/
https://www.analyticstraps.com/quando-la-visualizzazione-canalizzazione-mente/


text:
Q: Grant the server the permission of creating a folder I have a Ubuntu Server on DigitalOcean, which hosts some websites. I just built a mean.js stack app on my mac, and I plan to deploy it to production, thus to this existing server.
I followed this link to install node.js and mongodb, etc. Then, rather than cloning the sample app of mean.js, I cloned my own app from the github:
sudo git clone https://github.com/softtimur/myapp.git /opt/myapp
cd /opt/myapp
sudo mkdir public/tmp/
sudo npm install
npm start

Then, in a browser, I entered https://xxx.xx.xx.xx:3000/#/new. On the server side, I got an error:
router.post /mkdir
{ Error: EACCES: permission denied, mkdir 'public/tmp/sAlTI6NDo5NQcO-lAAAA/'
    at Error (native)
  errno: -13,
  code: 'EACCES',
  syscall: 'mkdir',
  path: 'public/tmp/sAlTI6NDo5NQcO-lAAAA/' }

This is because in the backend of my app, it tries to create a folder in public/tmp/ by fs.mkdir(...) where fs = require('fs').
So does anyone know to how to give the server this permission?
PS: I also tried to run
sudo chown -R $USER:$GROUP ~/.npm
sudo chown -R $USER:$GROUP ~/.config

but it did not help.

A: The issue is that you created public/tmp/ as root:
sudo mkdir public/tmp/

But you're running the app as $USER, which will most likely not be allowed to write to that directory.
To fix:
sudo chown -R $USER:$GROUP public/tmp/


text:
Q: Traverse Matrix in adjacent diagonals I need to traverse a matrix on diagonals as in the following example.
I tried to adapt the code from Traverse Matrix in Diagonal strips but I didnt succed.
Its a matrix of ints: int M[n][n];
example to traverse
order of diagonals to traverse:

*

*d(0)

*d(+1)

*d(-1)

*d(+2)

*d(-2)

*d(+3)

*d(-3)
and so on

lets take this example:
00 01 02 03
10 11 12 13
20 21 22 23
30 31 32 33
so the output required will be:
slice 1: 00 11 22 33
slice 2: 01 12 23
slice 3: 10 21 32
slice 4: 02 13
slice 5: 20 31
slice 6 : 03
slice 7: 30

A: You could try the following code, replacing printf by whatever you want.
#define N 4

int M[N][N];
//populate the array
for(int i=0; i<N; ++i)
{
    printf("slice %d:", 2*i+1);
    for(int j=0; j<N-i; ++j)
        printf(" %d", M[j][j+i]);
    printf("\n");
    if(i > 0)
    {
        printf("slice %d:", 2*i+2);
        for(int j=0; j<N-i; ++j)
            printf(" %d", M[j+i][j]);
        printf("\n");
    }
}


text: Q: What's the distribution of the euclidean distance between a fixed point a bivariate normal distribution? I have a problem where I'm interested in the distance between a fixed point and a bivariate normal distribution (where the two random variables are correlated). How does one find the distribution of that euclidean distance? The mahalanobis distance may seem appropriate, but it's scaled. I'd like to have a distance in terms of the right units.


text:
Q: Editing system-connections/Hotspot file gives authorisation error while connecting Ubuntu Hotspot I have successfully created hotspot in Ubuntu to share my wired internet connection.
Newly formed connection works fine with WPA.
I edited hotspot connection using nm-connection-editor command.
When I change the ssid or WPA password and try to connect to hotspot it gives authorisation error. In the same case when I change the security to none it works fine.
I am using Ubuntu 18.04.1 LTS.
Also the hotspot config file (location:/etc/NetworkManager/system-connections/Hotspot) shows the following..
[connection]
id=Hotspot
uuid=a7ff7e83-72b8-479a-9445-7b2cf9e4dd78
type=wifi
autoconnect=false
permissions=

[wifi]
mac-address=74:DA:38:1A:C0:BD
mac-address-blacklist=
mode=ap
ssid=chetan-desktop

[wifi-security]
key-mgmt=wpa-psk
psk=Co0zdbbO

[ipv4]
dns-search=
method=shared

[ipv6]
addr-gen-mode=stable-privacy
dns-search=
method=auto

A: Try setting these specific parameters:
[wifi-security]
group=ccmp;
key-mgmt=wpa-psk
pairwise=ccmp;
proto=rsn;
psk=YOUR_WIFI_AP_PASSWORD

If you still get errors try viewing the log output to see what is failing:
sudo journalctl -u NetworkManager.service


text:
Q: Converting byte array to decimal Was wondering if someone could explain this snippet to me in depth
(my $bytearray_val_ascii = $in) =~ s/([a-fA-F0-9]{2})/chr(hex $1)/eg;

A: The s/// is a regex substitution operator which the =~ operator binds to a variable on its left-hand side, so a statement
$var =~ s/pattern/replacement/;

matches the pattern in the variable $var and performs a substitution of it by the replacement string, evaluated in a double-quoted context. The operation can be  tuned and tweaked by modifiers that follow the closing delimiter (and which can also be embedded in the pattern).†
This changes the variable "in-place" -- after this statement $var is changed.  An idiom to preserve $var and store the changed string in another variable is to assign $var to that other variable and "then" change it (by ordering operations by parenthesis), all in one statement.  And the commonly used idiom is to also introduce a new variable in that statement
(my $new_var = $original) =~ s/.../.../;

Now $original is unchanged, while the changed string is in $new_var (if the pattern matched).
This idiom is nowadays unneeded since a r (non-destructive) modifier was introduced in 5.14
my $new_var = $original =~ s/.../.../r;

The $original is unchanged and the changed string returned, then assigned to $new_var.

The regex itself matches and captures two consecutive alphanumeric characters, runs hex on them and then chr on what hex returns, and uses that result to replace them. It keeps going through the string to do that with all such pairs that it finds.
If this is indeed precisely all that there is to do then it is more simply done using pack
my $bytearray_val_ascii = pack( "H*", $in );

†
Here the modifiers are: e, which makes is so that the replacement side is evaluated as code so that what that code evaluates to is used for replacement; and g which makes it continue searching and replacing through the whole string (not just the first occurrence of pattern that is found).


text:
Q: Change the color of input when theres an error on submit click How can i change the color of the input box in red if  there's an error when i hit the SUBMIT button?
<form method="post" action="" ">

Add users

        <div class="form-group <?php echo (!empty($error_user) || ($error_taken)) ? 'has-error' : ''; ?>">
  Username: *
  <input type="text" name="username" value="<?php echo $username; ?>" />
  <?php echo $error_user; ?>

  <?php echo $error_taken; ?>

  <div class="form-group <?php echo (!empty($error_name)) ? 'has-error' : ''; ?>">
    Name: *
    <input type="text" name="name" value="<?php echo $name; ?>" />
    <?php echo $error_name; ?>

  <div class="form-group <?php echo (!empty($error_pass)) ? 'has-error' : ''; ?>">
    Password: *
    <input type="text" name="password" value="<?php echo $password; ?>" />
    <?php echo $error_pass; ?>

  <input type="submit" name="submit" value="Add">

</form>

A: You can use simple CSS
.form-group.has-error input {
  border: 1px solid red;
}

A: You have two different CSS options.
First use:
.has-error input{
border: 1px solid red;
}
.has-error .error{
color:red;
}

Second:
.has-error>input{
border: 1px solid red;
}
.has-error>.error{
color:red;
}

just apply any of the CSS and you will be fine. The second one will find input and class error just into the class has-error. If there will be another
 covering them then it will not work.
If you want to live check for errors and display it and change colors etc then you have to use AJAX

A: You can handle that with javascript or jquery sending POST request with ajax
and before that you can create error handling function


text:
Q: Extracting last 4 characters from a string in C Been working on a requirement to connect to the servers running on a system. I have 2 hosts, Host A and Host B.
Host A("hostname: o755-gksr") contains two servers running at ports 4840 and 4841. the server running on port 4840, has mDNS enabled and advertises packets for the network.
I have a server running at 4840 on Host B. It is also mDNS enabled. Now when running the client API from the Host B, it will check all the servers which are announced on the network and get the information on the list of servers.
Now, on top of this API, I am trying to connect to each of the servers individually(to check if the servers are still running on a network breakdown).
I am able to extract the hostname and figure the IP and try to connect to it.
But I am not able to extract the port information.
For eg: if URL is opc.tcp://o755-gksr:4840, I want to extract the port information in an character array or integer..
Would be really grateful for the guidance.
    printf("--Checking for network connectivity--\n");
    for (size_t i = 0; i < serverOnNetworkSize; i++) {
        UA_ServerOnNetwork *server = &serverOnNetwork[i];
        A[i] = (char *)UA_malloc(server->discoveryUrl.length + 1);
        memcpy(A[i], server->discoveryUrl.data, server->discoveryUrl.length);
        A[i][server->discoveryUrl.length] = 0;
        int length = strlen(A[i]);  //URL is of the form A[1] = "opc.tcp://o755-gksr:4840"
        //removing the port and extracting hostname to find IP
        A[i][length - 5] = '\0';
        //without initial tcp binding
        B[i] = A[i] + 10;
        // printf("Hostname: %s\n", B[i]);
        if (i != 0) { //because i=0 will be the server running on the same machine
            char ip_address[50];
            find_ip_address(B[i], ip_address);
            socketCommunication(ip_address, B[i]);   ///,&B[i]);
        }
    }

Finding IP:
int find_ip_address(char *hostname, char *ip_address) {
    struct hostent *host_name;
    struct in_addr **ipaddress;
    int count;

    if ((host_name = gethostbyname(hostname)) == NULL) {
        herror("\nIP Address Not Found\n");
        return 1;
    } else {
        ipaddress = (struct in_addr **)host_name->h_addr_list;
        for (count = 0; ipaddress[count] != NULL; count++) {
            strcpy(ip_address, inet_ntoa(*ipaddress[count]));
            return 0;
        }
    }
    return 1;
}

socket communication:
void socketCommunication(char *ip_address, char *hostname) {
    int clientSocket, ret;
    struct  sockaddr_in serverAddr;
    char buffer[1024];

    clientSocket = socket(AF_INET, SOCK_STREAM, 0);
    if (clientSocket < 0) {
        printf("Error in connection \n");
        exit(1);
    }

    //printf("Client socket is created\n");

    memset(&serverAddr, '\0', sizeof(serverAddr));
    // printf("MEMSET DONE\n");

    serverAddr.sin_port = htons(4844);
    //printf("PORT DONE\n");
    serverAddr.sin_family = AF_INET;
    //printf("afnet DONE\n");
    serverAddr.sin_addr.s_addr = inet_addr(ip_address);

    //printf("%s\n", *ip_address);

    //printf("Config done: \n");

    ret = connect(clientSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr));
    if (ret < 0) {
        printf("LOOKS LIKE NETWORK CONNECTION HAS FAILED. HAVE A LOOK AT THE NETWORK CONNECTIVITY at host : %s\n",hostname);
        printf("----Updated Status Information----:\n");
        printf("\tHostname :%s\n", hostname);
        printf("\tStatus:CONNECTON TIMED OUT");
        //exit(1);
    }
    //printf("Connected to Server\n");
}

Currently I am hardcoding the port in socket communication. Please guide me to extract the port information from the URL so that I can pass it as parameters in the function to dynamically allocate the port to the socket communication.

A: You most likely want to use a function like strrchr(const char *, int c) . this will search for the last occurrence of a character and return a pointer to it.
You can search for the colon and then use the pointer to copy your last 4 chars or use a function like strtol to transform the chars into an integer.
char *p = strrchr(input_buffer, ':');
unsigned long port = strtoul(p+1, NULL, 10);

You could also use strlen to get the length of the string and use the end as your offset, however ports are in the range 0...65535 I believe? So you're most likely going to be better off with the first option, unless you know it will always be 4 digits long.


text:
Q: How do I convert an AHK script to registry? I have this AHK script. How do I convert this into windows registry?
SetCapsLockState, alwaysoff
CapsLock & u::Send {Home}
CapsLock & o::Send {End}
CapsLock & i::Send {Up}
CapsLock & j::Send {Left}
CapsLock & k::Send {Down}
CapsLock & l::Send {Right}

A: You cannot set hotkeys like these in the registry, you can only remap individual keys. E.g. turn Capslock into another Backspace or RShift. Read this.


text:
Q: Prevent pages form automatically linking to email addresses and urls Is there a way to prevent pages from automatically turning anything that looks like an email address or a url into a hyperlink?

A: Go to the menu found at "Edit" > "Substitutions" > "Smart Links" and you can edit automatic hyperlinking.
More information can be found in the Apple knowledge base.


text:
Q: Spring Cloud Netflix apps running on Docker are killed by the container why? I am testing some Spring Cloud Netflix microservices running them as individual Docker containers on Windows.
There are quite a few of them, ten or more. The point is that after running some of them 7, 8... the applications' performance start to decline and some of the containers are killed, for instance I see:
2017-01-24 14:05:52.165  INFO 5 --- [nfoReplicator-0] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@67b129a3: startup date [Tue Jan 24 14:05:52 GMT 2017]; root of context hierarchy
Killed

*

*Why is the performance being affected?

*Is it a memory issue? How can I solve it?

*How can I prevent my containerized java apps from being killed?

I am using the same Dockerfile for the applications (each of them changes the ADD command):
FROM frolvlad/alpine-oraclejdk8:slim
VOLUME /tmp
ADD archimedes-0.0.1-SNAPSHOT.jar app.jar
RUN sh -c 'touch /app.jar'
ENV JAVA_OPTS=""
ENTRYPOINT [ "sh", "-c", "java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar /app.jar" ]

I am wondering if it is necessary to provide the -Xms and -Xmx flags to force a minimum/maximum available memory...
On the other hand, the more containers I start, the less responsive the applications are...but Window's task manager doesn't show any CPU/RAM exhaustion. Maybe I have to tune the Windows Docker installation?
The code is available here: https://github.com/codependent/storyteller-microservices/tree/high-availability-rxjava
To start every microservice, under every folder there's a startContainer.sh that shows the docker commands I am using, for instance:
mvn clean package docker:build -DskipTests
docker run -e "SPRING_PROFILES_ACTIVE=archimedes1" -p 8761:8761 \
  --name archimedes1 --add-host archimedes1:192.168.99.100 --add-host archimedes2:192.168.99.100 --add-host my-rabbit:192.168.99.100 \
  -d storyteller/archimedes
docker run -e "SPRING_PROFILES_ACTIVE=archimedes2" -p 8762:8762 \
  --name archimedes2 --add-host archimedes1:192.168.99.100 --add-host archimedes2:192.168.99.100 --add-host my-rabbit:192.168.99.100 -d storyteller/archimedes

A: I fixed it by assigning more memory to the VirtualBox: in the settings view, System tab --> Base Memory 4GB.
With this the containers run smoothly and aren't being killed.


text:
Q: How to print subcommand result automatically? I have Java CLI application based on cliche library and I want to migrate it to picocli.
My application was based on cliche so I have a lot of methods with asg.cliche.Command annotation which return some result. cliche prints command methods's result automatically so result was printed in command line. I replaced asg.cliche.Command annotations by picocli.CommandLine.Command and I see that picocli does not print command methods's results.
I have following class:
import picocli.CommandLine;

@CommandLine.Command(subcommandsRepeatable = true)
public class Foo
{

    public static void main( String[] args )
    {
        new CommandLine( new Foo() ).execute( args );
    }

    @CommandLine.Command
    public String sayHello()
    {
        return "Hello";
    }

    @CommandLine.Command
    public String sayGoodbye()
    {
        return "GoodBye";
    }
}

when I call java -cp myJar.jar Foo sayHello sayGoodbye I do not see any output.
I see three solutions:
 1. Modify each methods to print result instead of return it.
import picocli.CommandLine;

@CommandLine.Command( subcommandsRepeatable = true )
public class Foo2
{

    public static void main( String[] args )
    {
        new CommandLine( new Foo2() ).execute( args );
    }

    @CommandLine.Command
    public void sayHello()
    {
        System.out.println( "Hello" );
    }

    @CommandLine.Command
    public void sayGoodbye()
    {
        System.out.println( "GoodBye" );
    }
}

I am not happy with this solution. I prefer not modify my methods.

*Retrieve results after execution.

public static void main( String[] args )
    {
        final CommandLine commandLine = new CommandLine( new Foo() );
        commandLine.execute( args );
        CommandLine.ParseResult parseResult = commandLine.getParseResult();
        for( CommandLine.ParseResult pr : parseResult.subcommands() )
        {
            System.out.println( pr.commandSpec().commandLine()
                .getExecutionResult()
                .toString() );
        }
    }

I see a few problems with this solution. The main problem is formatting. Execution result can be null, array, collection. The second problem is that results are printed after execution of all subcommands. If second subcommand throws exception then I firstly see exception stack trace  and after that I see result of first subcommand.

*Ask on stackoverflow if there is some better solution. I do not believe that there is no any configuration option in picocli which enable results printing.

A: Personally, I like your first solution best, it is simple and easy to maintain. Maybe introduce a helper method for the printing and formatting so the command methods can look like this:
    @CommandLine.Command
    public String sayGoodbye()
    {
        return printValue("GoodBye");
    }

You already found the CommandLine.getParseResult method; perhaps a helper method could assist with the formatting there as well.
There is a third option, but it is unfortunately quite a bit more complex: you can create a custom IExecutionStrategy that prints the result of each command after executing it. It involves copying a lot of code from the picocli internals and it's not really a realistic solution; I just mention it for completeness.
// extend RunLast to handle requests for help/version and exit code stuff
class PrintingExecutionStrategy extends CommandLine.RunLast {
    @Override
    protected List<Object> handle(ParseResult parseResult) throws ExecutionException {
        // Simplified: executes only the last subcommand (so no repeating subcommands).
        // Look at RunLast.executeUserObjectOfLastSubcommandWithSameParent if you need repeating subcommands.
        List<CommandLine> parsedCommands = parseResult.asCommandLineList();
        CommandLine last = parsedCommands.get(parsedCommands.size() - 1);
        return execute(last, new ArrayList<Object>());
    }

    // copied from CommandLine.executeUserObject,
    // modified to print the execution result
    private List<Object> execute(CommandLine cmd, List<Object> executionResultList) throws Exception {
        Object command = parsed.getCommand();
        if (command instanceof Runnable) {
            try {
                ((Runnable) command).run();
                parsed.setExecutionResult(null); // 4.0
                executionResultList.add(null); // for compatibility with picocli 2.x
                return executionResultList;
            } catch (ParameterException ex) {
                throw ex;
            } catch (ExecutionException ex) {
                throw ex;
            } catch (Exception ex) {
                throw new ExecutionException(parsed, "Error while running command (" + command + "): " + ex, ex);
            }
        } else if (command instanceof Callable) {
            try {
                @SuppressWarnings("unchecked") Callable<Object> callable = (Callable<Object>) command;
                Object executionResult = callable.call();

                System.out.println(executionResult); <-------- print result

                parsed.setExecutionResult(executionResult);
                executionResultList.add(executionResult);
                return executionResultList;
            } catch (ParameterException ex) {
                throw ex;
            } catch (ExecutionException ex) {
                throw ex;
            } catch (Exception ex) {
                throw new ExecutionException(parsed, "Error while calling command (" + command + "): " + ex, ex);
            }
        } else if (command instanceof Method) {
            try {
                Method method = (Method) command;
                Object[] parsedArgs = parsed.getCommandSpec().argValues();
                Object executionResult;
                if (Modifier.isStatic(method.getModifiers())) {
                    executionResult = method.invoke(null, parsedArgs); // invoke static method
                } else if (parsed.getCommandSpec().parent() != null) {
                    executionResult = method.invoke(parsed.getCommandSpec().parent().userObject(), parsedArgs);
                } else {
                    executionResult = method.invoke(parsed.factory.create(method.getDeclaringClass()), parsedArgs);
                }

                System.out.println(executionResult); <-------- print result

                parsed.setExecutionResult(executionResult);
                executionResultList.add(executionResult);
                return executionResultList;
            } catch (InvocationTargetException ex) {
                Throwable t = ex.getTargetException();
                if (t instanceof ParameterException) {
                    throw (ParameterException) t;
                } else if (t instanceof ExecutionException) {
                    throw (ExecutionException) t;
                } else {
                    throw new ExecutionException(parsed, "Error while calling command (" + command + "): " + t, t);
                }
            } catch (Exception ex) {
                throw new ExecutionException(parsed, "Unhandled error while calling command (" + command + "): " + ex, ex);
            }
        }
        throw new ExecutionException(parsed, "Parsed command (" + command + ") is not a Method, Runnable or Callable");
    }
}

Use it like this:
public static void main(String... args) {
    new CommandLine(new Foo())
        .setExecutionStrategy(new PrintingExecutionStrategy())
        .execute(args);
}

I wouldn't recommend the above.
Update: I thought of another, fourth, option (actually a variation of your 2nd solution). You can specify a custom IExecutionExceptionHandler that doesn't print the stacktrace, but instead stores the exception so you can print the stacktrace after printing the command results. Something like this:
class MyHandler extends IExecutionExceptionHandler() {
    Exception exception;
    public int handleExecutionException(Exception ex,
                                         CommandLine commandLine,
                                         ParseResult parseResult) {
         //ex.printStackTrace(); // no stack trace
         exception = ex;
    }
}

Use it like this:
public static void main(String... args) {
    MyHandler handler = new MyHandler();
    CommandLine cmd = new CommandLine(new Foo())
        .setExecutionExceptionHandler(handler);
    cmd.execute(args);

    ParseResult parseResult = cmd.getParseResult();
    for( ParseResult pr : parseResult.subcommands() )
    {
        System.out.println( pr.commandSpec().commandLine()
                .getExecutionResult()
                .toString() );
    }

    if (handler.exception != null) {
        handler.exception.printStackTrace();
    }
}


text:
Q: Regex to Filter string with unicode characters and emojis for java I'm developing a Spring boot chat application. How can I create a regex to achieve followings,

*

*Remove special characters

*remove newlines tabs etc..

*Accept Unicode characters

*Accept for emojis

further,
DB tables CHARACTER SET utf8mb4 and COLLATE utf8mb4_bin.

A: *

*Remove special characters
s = s.replaceAll("[\\p{P}\\p{S}]", "")

*remove newlines tabs etc..
s = s.replaceAll("[\\p{C}\\p{Zl}\\p{Zp}]", "")

*Accept Unicode characters
Java already does this.

*Accept for emojis
Emojis are Unicode characters, so Java already does this.
All-in-all:
s = s.replaceAll("[\\p{P}\\p{S}\\p{C}\\p{Zl}\\p{Zp}]", "")

For list of Unicode Categories and the Characters in each Category, see Unicode Character Categories.
With the above regex, the following categories are retained: L (Letter), M (Mark), N (Number), Zs (Separator, Space).


text:
Q: forcing a page break in the middle of a long footnote in LaTeX My supervisor has a LaTeX page that has a small amount of body
text and a long footnote consisting of two paragraphs. Is there
any way to force the footnote to break across two pages
and to choose the break point to be between the two
paragraphs.
I did some google searches related to this and most people
seemed to have the opposite problem; they didn't want
a long footnote to be broken across two pages.
But from one google result, it might help to put
\interfootnotelinepenalty=0
in the preamble. But that doesn't solve the problem of
choosing the break point to be between the two
paragraphs.

A: In all probability, Ulrike's answer is what you really want.  However, in order to do literally what your question asks for, that is, to force a page break between two paragraphs of a footnote (for example, because you don't want the footnote to take up so much vertical space on that particular page), you should simply write
\vspace{\maxdimen}

between the two paragraphs in question.  The two methods (Ulrike's and this one) can also be combined:
% My standard header for TeX.SX answers:
\documentclass[a4paper]{article} % To avoid confusion, let us explicitly
                                 % declare the paper format.

\usepackage[T1]{fontenc}         % Not always necessary, but recommended.
% End of standard header.  What follows pertains to the problem at hand.

\usepackage{lipsum}

\begin{document}

Blah blah.\footnote{\interlinepenalty = 10000
\lipsum[1-2]

\vspace{\maxdimen}

\lipsum[3-4]
}

\end{document}

Note that replacing
\vspace{\maxdimen}

with
\pagebreak[4]

is not guaranteed to work in every situation, not even if you use
\par \penalty -1000000000

in lieu of \pagebreak[4].  The reason is explained on p. 123 of The TeXbook: whenever Step 3 applies, Step 4 is not even tried.
More generally, you could force a page break after a certain line in a footnote by placing
\vadjust{\vskip\maxdimen}

somewhere on that line; this will overcome any other setting that might be in force.  For example:
% My standard header for TeX.SX answers:
\documentclass[a4paper]{article} % To avoid confusion, let us explicitly
                                 % declare the paper format.

\usepackage[T1]{fontenc}         % Not always necessary, but recommended.
% End of standard header.  What follows pertains to the problem at hand.

\usepackage{lipsum}

\begin{document}

Blah blah.\footnote{\interlinepenalty = 10000 \clubpenalty = 10000
\lipsum[1-2]

I~want this footnote to be broken across pages right after the line that
contains \emph{this}\vadjust{\vskip\maxdimen} word.  \lipsum*[3]

\lipsum[4]
}

\end{document}

Finally, it should be noted that, if the problem is that you want to limit the vertical space on a page devoted to footnotes, you can do so by setting the value of a length that can be named as \dimen\footins.  For example,
% My standard header for TeX.SX answers:
\documentclass[a4paper]{article} % To avoid confusion, let us explicitly
                                 % declare the paper format.

\usepackage[T1]{fontenc}         % Not always necessary, but recommended.
% End of standard header.  What follows pertains to the problem at hand.

\usepackage{lipsum}

\begin{document}

\setlength{\dimen\footins}{200pt}

Blah blah.\footnote{\lipsum[1-4]}

\end{document}

A: You can set \interlinepenalty10000 in the footnote:
\documentclass{article}

\usepackage{lipsum}

\begin{document}
\vspace*{10cm}
blalbl\footnote{\interlinepenalty10000 \lipsum[1]\lipsum[1]\lipsum[1]\lipsum[1]}
\end{document}


text:
Q: How to rotate a 3D matrix along X,Y, or Z axial plane? I have a 3D matrix with size DxHxW. I want to rotate it 90 degrees along the (1) X-axis, (2) Y-axis and (3) Z-axis. I just completed Y-axis. How can I do it with X and Z-axis? I am using python 2.7. Thanks all
rotate_90Y=numpy.rot90(input)

A: numpy.rot90 has an axes argument. You can use it to rotate about all tree axes,
m = np.arange(8).reshape((2,2,2))
m1 = np.rot90(m, axes=(0,1))
m2 = np.rot90(m, axes=(1,2))
m3 = np.rot90(m, axes=(0,2))

(Since it's not clear what x,y,z axis are from the question, you need to decide for yourself, which one you need)


text:
Q: Implement Asymmetrical Grid Layout Manager Like Instagram Search I Created a RecyclerView And Set layoutManager Of My Adapter To GridLayout .
But I Want GridLayout Like Instagram Search below image,

I Want A GridView Like This :

Please Help Me . Thanks .
i tried SpanSizeLookup But i Have Still My Problem And i Cant Control My Items to laying out exactly that way . . .

A: please take a look  this answer
and for show Your list in Span
val manager = SpannedGridLayoutManager(object : SpannedGridLayoutManager.GridSpanLookup{
        override fun getSpanInfo(position: Int): SpannedGridLayoutManager.SpanInfo {
            // Conditions for 2x2 items
            return if (position % 12 == 0 || position % 12 == 7) {
                SpannedGridLayoutManager.SpanInfo(2, 2)
            } else {
                SpannedGridLayoutManager.SpanInfo(1, 1)
            }
        }

    },3/*column*/,1f/*how big is default item*/)

    binding.feedHome.setHasFixedSize(true)
    binding.feedHome.layoutManager = manager
    binding.feedHome.adapter = adapter

and this image help you how to calculate item in show big image

A: For the newest instagram layout in 2022, try this:
layoutManager.spanSizeLookup = IGLayoutManager.SpanSizeLookup { position ->

            // 0  1  2
            // s  s  b
            // 3  4  5  6  7  8  9  10 11
            // s  s  s  s  s  s  s  s  b
            // 12 13 14 15 16 17 18 19 20 21 22 23 24
            // s  s  s  s  s  s  s  s  s  s  s  s  b
            // 25 26 27 28 29 30 31 32 33
            // s  s  s  s  s  s  s  s  b
            // 34 35 36 37 38 39 40 41 42 43 44 45 46
            // s  s  s  s  s  s  s  s  s  s  s  s  b
            // 47 48 49 50 51 52 53 54 55
            // s  s  s  s  s  s  s  s  b
            // 56 57 58 59 60 61 62 63 64 65 66 67 68
            // s  s  s  s  s  s  s  s  s  s  s  s  b
            // 69 70 71 72 73 74 75 76 77
            // s  s  s  s  s  s  s  s  b
            // 78 79 80 81 82 83 84 85 86 87 88 89 90
            // s  s  s  s  s  s  s  s  s  s  s  s  b
            // 91 92 93 94 95 96 97 98 99
            // s  s  s  s  s  s  s  s  b
            // 100 101 102 103 104 105 106 107 108 109 110 111 112
            // s   s   s   s   s   s   s   s   s   s   s   s   b
            // 113 114 115 116 117 118 119 120 121
            // s   s   s   s   s   s   s   s   b

            if (position < 2) {
//                ILog.debug("???", "$position is small")
                bigItemFlag = 0
                SpanSize(1, 1)
            }
            else if (position == 2) {
//                ILog.debug("???", "$position is big")
                bigItemFlag = 11
                SpanSize(1, 2)
            }
            else if (position % 11 == 0 && position == bigItemFlag) {
                bigItemFlag += 13
//                ILog.debug("???", "$position is big, $position mod 11 is ${position % 11}")
                SpanSize(1, 2)
            }
            else if (position % 11 == 2 && position == bigItemFlag) {
                bigItemFlag += 9
//                ILog.debug("???", "$position is big, $position mod 11 is ${position % 11}")
                SpanSize(1, 2)
            }
            else {
//                ILog.debug("???", "$position is small")
                SpanSize(1, 1)
            }
        }


text:
Q: AVAssetReaderTrackOutput sometimes delivers blank video frames I'm writing an application that reads a video file using AVKit, and does something to each frame, finally producing an output image.
First I load the asset, with the AVURLAssetPreferPreciseDurationAndTimingKey set to YES, then I find the first video track, and create an asset reader and an asset reader output with the decompression settings set to kCVPixelFormatType_32BGRA - according to the docs this is one of the few allowed values here.
Then I call copyNextSampleBuffer in a loop, and do the following with the resulting CMSampleBufferRef:
CVImageBufferRef movieFrame = CMSampleBufferGetImageBuffer(sampleBuffer);
NSCIImageRep *imageRep = [NSCIImageRep
  imageRepWithCIImage:[CIImage imageWithCVImageBuffer:movieFrame]];

NSImage *image = [[NSImage alloc] initWithSize:[imageRep size]];
[image addRepresentation:imageRep];

For the most part, this works fine. However there are some videos that generate the occasional blank frame, and yet others for which every frame is blank. Am I doing something obviously wrong here?

A: Well, I solved this one eventually. The occasional blank frames were due to a threading issue, and the always blank frames were solved by using the following to create the NSImage:
CVPixelBufferLockBaseAddress(movieFrame,0);
uint8_t *baseAddress = (uint8_t *)CVPixelBufferGetBaseAddress(movieFrame);
size_t bytesPerRow = CVPixelBufferGetBytesPerRow(movieFrame);
size_t width = CVPixelBufferGetWidth(movieFrame);
size_t height = CVPixelBufferGetHeight(movieFrame);

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef newContext = CGBitmapContextCreate(baseAddress,
                                                width, height, 8,
                                                bytesPerRow,
                                                colorSpace,
                                      kCGBitmapByteOrder32Little |
                                      kCGImageAlphaNoneSkipFirst);
CGImageRef frame = CGBitmapContextCreateImage(newContext);

CVPixelBufferUnlockBaseAddress(movieFrame,0);
CGContextRelease(newContext);
CGColorSpaceRelease(colorSpace);

NSImage *image = [[NSImage alloc] initWithCGImage:frame size:NSMakeSize(width,height)];

CGImageRelease(frame);

I wish I understood why, but at least it works now.


text:
Q: Is there any other way to sort numbers in ascending or descending order without using arrays? int sortDigit(int number, bool order){

    if (order == ASCENDING && number>0) {
            for (int j = number; j>0; j/=10) {
                if (j%10==i) {
                    cout << i;
                }
            }
    }

    if (order == DESCENDING && number>0) {
            for (int j = number; j>0; j/=10) {
                if (j%10==i) {
                    cout << i;
                }
            }
    }

}

I am trying to arrange the numbers in arranging or descending order.
This code returns the sorted numbers, but due to no return value, the answer is followed by 32767:-
Ex:-
cout << "sortDigit(54321, ASCENDING) = " << sortDigit(54321, ASCENDING) << endl;

output:
 sortDigit(54321, ASCENDING) = 1234532767

Could anyone please help me as what return value shall I use to solve this bug? or is there any better method to sort digits without using arrays?
Thanks a lot

A: You could store the value in a variable:
int sortDigit(int number, bool order){
    int ret = 0;
    if (order == ASCENDING && number>0) {
        for (int i = 1; i<=9; i++) {
            for (int j = number; j>0; j/=10) {
                if (j%10==i) {
                    ret = 10 * ret + i;
                }
            }
        }
    }

    if (order == DESCENDING && number>0) {
        for (int i = 9; i>=0; i--) {
            for (int j = number; j>0; j/=10) {
                if (j%10==i) {
                    ret = 10 * ret + i;
                }
            }
        }
    }
    return ret;
}

Or you could call the the function without cout:
cout << "sortDigit(54321, ASCENDING) = ";
sortDigit(54321, ASCENDING);
cout << endl;


text:
Q: Electron not executing my JS I have my electron window, it loads all right except that the JS is not run. I can't find out why. Here is my code:
...
<head>
  <meta name="viewport" content="width=device-width">
  <link href="./assets/default.css" rel="stylesheet"></link>
  <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'unsafe-inline';">
  <script>
    (function() {
      "use_strict";
      console.log('lul'); // Doesn't log 'lul'
      var jq = require("./assets/jquery.min.js");
    });
  </script>
</head>
...

This has been frustrating my for a while. I get no errors in the console, and no log. I am new to electron.

A: That is because your function is declared but never invoked. Try:
(function() {
  "use_strict";
  console.log('lul'); // Doesn't log 'lul'
  var jq = require("./assets/jquery.min.js");
}());

The () at the end makes it an IIFE (Immediately Invoked Function Expression).
As a side note, I believe the require is going to throw an error if you run it in a browser without converting it with babel or some other transpiler.


text:
Q: Get type of value within JSON object using Groovy I'm having the following JSON object which I want to check
import groovy.json.JsonSlurper
def jsonSlurper = new JsonSlurper()
import groovy.json.JsonOutput;

def object = jsonSlurper.parseText '''
{
  "id" : 10,
  "docType" : "PDF",
  "values" : {
      "color" : "red",
      "pages" : 2,
    },
  "versions" : [
    {
      "verNum" : 1,
      "desc" : "This is the description for it"
    }
  ]
}
'''
// def data = new JsonSlurper().parseText("""[{"a": 1, "b": 2, "c": 3, "x": true}, {"a": 4, "b": 5, "c": 6, "d": "Hello"}]""")
// def content = object.collectEntries{
//    it.collectEntries{
//        [it.key, it.value.class.name]
//    }
//}

//println content

I want to iterate through each of the keys and check for the type using Groovy, for example:
id - java.lang.Integer, docType - java.lang.String, values.color - java.lang.String, verNum within the object within the array will be java.lang.Integer
I have searched for a few different ways but most of them won't work in my case. One of them are now commented on as in the code above.
Any suggestion would be much appreciated!

A: Something like this:
import groovy.json.JsonSlurper

def object = new JsonSlurper().parseText '''
{
  "id" : 10,
  "docType" : "PDF",
  "values" : {
      "color" : "red",
      "pages" : 2,
    },
  "versions" : [
    {
      "verNum" : 1,
      "desc" : "This is the description for it"
    }
  ]
}
'''

def res = [:]
def traverser
traverser = { Map m ->
  m.each{ k, v ->
    switch( v ){
      case Map:
        res[ k ] = Map
        traverser v
        break
      case List:
        res[ k ] = List
        v.each traverser
        break
      default:
        res[ k ] = v?.getClass()
    }
  }
}

traverser object

def simple = res.collectEntries{ k, v -> [ k, v.simpleName ] }
assert simple.toString() == '[id:Integer, docType:String, values:Map, color:String, pages:Integer, versions:List, verNum:Integer, desc:String]'

A: I think you should use data variable instead of object in your sample.
def data = new JsonSlurper().parseText("""[{"a": 1, "b": 2, "c": 3, "x": true}, {"a": 4, "b": 5, "c": 6, "d": "Hello"}]""");

def content = data.collectEntries{
    it.collectEntries{
        [it.key, it.value.class.name];
    }
}

println content;

The output will be;
[a:java.lang.Integer, b:java.lang.Integer, c:java.lang.Integer, x:java.lang.Boolean, d:java.lang.String]


text:
Q: Get a list of all keys in an Array of Hashes What I have: An array of hashes with different sizes.
hashes = [{:a => 0}, {:a => 0, :b => 1}, {:a => 1, :c => 1}]

What I need: I need a list of all keys. EDIT: An actual list, not a Hash.
[:a, :b, :c]

Is this the right approach? This feels a bit heavy.
hashes.flat_map(&:keys).uniq

Or any other ideas? Thanks!

A: You were pretty close
hashes.flat_map(&:to_a).reverse.to_h
#=> {:c=>1, :a=>0, :b=>1}

A: Your way is a good balance between performance and being idiomatic. I tried a few other approaches.
# with reduce
hashes.map(&:keys).reduce(:|)
# with merge
hashes.each_with_object({}) { |memo, h| memo.merge! h }.keys
# manually
set = {}
hashes.each { |h| h.each_key { |k| set[k] = nil } }
set.keys

the time in seconds for merging 1000 hashes with ~8 keys per hash 1000 times
uniq   0.539034
reduce 2.194463
merge  0.090131
manual 0.911875

For readability, your approach wins. Reducing sucks. Manual is ugly and slow.
I would go with the merge approach since it isn't very ugly and is super fast.


text:
Q: low level graphics in Blackberry hi everyone I am new to blackebrry. I want to use low level graphics for drawing a bitmapfield. On this bitmapfield i need to take three action-

*

*pick the bitmapfield,

*drag it in the screen in any direction and

*finally release it at any point on the screen.

how can I do this.
if 'Canvas' can be a solution... can any one help me with some sample code for how to use 'Canvas'.
Also is there any other method for making a draggable bitmapfield..??
Please help

A: Firstly, you can create a bitmap and get a graphics object from it to do custom drawing on it.
Bitmap myBitmap = new Bitmap(widht, height);
Graphics graphics = Graphics.create(myBitmap);

// now you can draw anything on graphics supported by API

[Edited]
I have added a code snippet for drag an image on a screen. You can check this code if it works on your side.
class MyScreen extends MainScreen {
    private final Bitmap myBm;
    private int wBm;
    private int hBm;
    private int xBm;
    private int yBm;
    private boolean dragStarted;

    public MyScreen() {
        myBm = Bitmap.getBitmapResource("img/myBitmap.png");
        if (myBm != null) {
            wBm = myBm.getWidth();
            hBm = myBm.getHeight();
        }
    }

    protected void paint(Graphics graphics) {
        // need to adjust z-index of the items added on screen.
        super.paint(graphics);
        if (myBm != null) {
            graphics.drawBitmap(xBm, yBm, wBm, hBm, myBm, 0, 0);
        }
    }

    protected boolean touchEvent(TouchEvent event) {
        int x = event.getX(1);
        int y = event.getY(1);
        int eventCode = event.getEvent();

        if (dragStarted == false & (eventCode == TouchEvent.DOWN)) {
            if (isDragActivated(x, y)) {
                // need to adjust offset.
                dragStarted = true;
                updateBitmapLocation(x, y);
            }
        }

        if (eventCode == TouchEvent.MOVE && dragStarted) {
            updateBitmapLocation(x, y);
        }

        if (eventCode == TouchEvent.UP && dragStarted) {
            dragStarted = false;
            updateBitmapLocation(x, y);
        }

        // need to decide what to return
        return true;
    }

    private void updateBitmapLocation(int xTouch, int yTouch) {
        if (xTouch != xBm && yTouch != yBm) {
            xBm = xTouch;
            yBm = yTouch;
            invalidate();
        }
    }

    private boolean isDragActivated(int x, int y) {
        return (x >= xBm && x <= xBm + wBm && y >= yBm && y <= yBm + hBm);
    }
}


text:
Q: What is the name of this android menu view? What is the name of this menu view and how can I make one just like it?

A: This is a subclass of Dialog called AlertDialog
You can follow the official documentation to create it on yourself:
https://developer.android.com/reference/android/app/AlertDialog.html
Also check this example of "Building an Alert Dialog"
https://developer.android.com/guide/topics/ui/dialogs.html#AlertDialog

A: Its just a Dialog in android. You can make it by AlertDialog
Follow this official documentation. It may help you:
https://developer.android.com/guide/topics/ui/dialogs.html


text:
Q: How to show direction between current location and target location in android ? I have a list of places in listview which i got from parsing JSON.
When user clicks in one of the listview, google maps open (Which i already done).
What I want is that when user clicks one of list items, Then google map opens with marking current position and user clicked place in list item, Then show direction between them, which i couldnot do.
I had googled alot but can not find the appropriate answer.
I'm newbie to google map, Please note me down clearly.
Help me Stackoverflow-ians !!!

A: Easiest way would be to call the URL:
http://ditu.google.cn/maps?f=d&source=s_d&saddr=" + point1lat + ","+ point1long+ "&" + "daddr=" + point2lat+ "," + point2long+ "&hl=zh"

This opens GoogleMaps on android phones and shows you the route from point1 to point2.

A: Please check the below google map's webservice for fetching both the directions and also the route between then in the poly line points format.
http://maps.google.com/maps/api/directions/xml?origin=XXXXXX&destination=XXXXXX&sensor=false
Please replace the above Origin and Destination and parse it and use it


text:
Q: Date object in JSON schema I have my json schema for createdAt as
{
  "title": "details",
  "definitions": {
    "dateTime": {
      "type": "string",
      "format": "date-time"
    },
  "properties" : {
    "createdAt": { "$ref": "#/definitions/dateTime" }
  }
}

and when I try to create Object
Details details = ImmutableDetails.builder()
         .createdAt(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
           .parse("2021-11-30T00:22:11.454Z"))
         .build();

I am getting the error as
createDate: [Nov 30, 2021, 0:22:11 AM] is not a valid date-time.
Expected [yyyy-MM-dd'T'HH:mm:ssZ, yyyy-MM-dd'T'HH:mm:ss.[0-9]{1,9}Z,
          yyyy-MM-dd'T'HH:mm:ss[+-]HH:mm, yyyy-MM-dd'T'HH:mm:ss.[0-9]{1,9}[+-]HH:mm]

How do I specify my JSON schema to accept java.util.Date object ?

A: The "date-time" format in JSON Schema follows RFC3339.  That's timestamps that look like 2021-12-31T23:59:59Z or 2021-12-31T23:59:59-05:30, which is exactly what the error message says.
You're already starting out with timestamps in the correct format, and then converting them to an unacceptable format -- so just remove that part.