问:
Managing multiple threads at the console
When I run multiple threads I get lost in System.out.println output because I suppose each thread has to be in a different consoles.

Is there an easy way to manage it using Eclipse?

EDIT: The problem is not to know which message belongs to each thread. The exact problem is that the console stops printing when a new thread is called, and the same happens with log4j too.

答:
I suggest you switch to a better logging facility than System.out.println, log4j is one popular option.

If you don't want to include another library for this purpose, I suggest you

give all threads meaningful names (see Thread.setName)

wrap the log statements in your own static logging function

prefix each line of output with Thread.currentThread().getName().

If you think that is too "invasive" or if you're dealing with legacy code, you could create your own PrintStream which prefixes each argument to println with current thread name (as above) and then do System.setOut(new YourThreadLoggingPrintStream());.


来源: stackexchange

问:
Java BigDecimal vs R vs Java Float, Double
I am working on a financial system where precision required is 6 decimal places only.  We are currently using R but converting to Java.  I had a debate with a colleague over whether we should go with BigDecimals or double / float primitive in Java.  I was in favor of BigDecimal but his point was that R would be using primitives same as Java primitives so we would have already noticed if there were any issues with the precision.  It should be noted that the end result we would convert to BigDecimal anyway this is just for the calculation itself.  Who is correct here?</p>

答:
Accuracy

Accountants want accuracy. They don’t care about speed of execution. For accounting purposes, always use BigDecimal in Java.

An alternative is using integers. If you want to represent pennies on the dollar (USD), multiply by a hundred, and then do further math with that integer. BigInteger may be helpful.

Speed

Statisticians want speed of execution. They don’t care about minor inaccuracies. For such work, floating-point in R makes sense.

You can export from BigDecimal to double or to float.

ContentLicense: CC BY-SA 4.0


问:
Copy the File Structure from one Team to another with Powershell using MS Graph
I was trying to copy the whole Team with a folderstructur to another. However, I ran into the problem that I don't know how to copy the whole structure.

The first part with the channels I do with the /teams/{teamsid}/clone

The second part I create in a first step the channel folders to fill them with the subfolders.

What I tried: But this Script just creates the Channel Folders and their direct subfolders

```<code>#Update Variables
$customername = $customername.replace(' ','')
$URLCloneFolder        = "https://graph.microsoft.com/v1.0/groups/?" + "$" + "filter=displayName eq '$customername'"
# Give MS Graph Time to create Group
$group = ''
Do {
    $group = Invoke-RestMethod -Uri $URLCloneFolder -ContentType application/json -Headers $headerParams -Method GET
    Start-Sleep -s 5
}
while ($group.value.Length -eq 0)
$groupid = $group.value.id
$URLBaseTeamChannels = "https://graph.microsoft.com/v1.0/teams/$teamid/channels"
$BaseTeamChannelNames = Invoke-RestMethod -Uri $URLBaseTeamChannels -ContentType application/json -Headers $headerParams -Method GET

$i=0
while ($i -lt $BaseTeamChannelNames.'@odata.count'){
    $URLCloneFolder = "https://graph.microsoft.com/v1.0/groups/$groupid/drive/root/children"
    $body = '{
    "name": "' + $BaseTeamChannelNames.value.displayName.Get($i) + '",
    "folder": {},
    "@microsoft.graph.conflictBehavior": "rename"
}'
    Invoke-RestMethod -Uri $URLCloneFolder -Headers $headerParams -Body $body -Method POST -ContentType “application/json; charset=utf-8”
    $URLCloneFolder = "https://graph.microsoft.com/v1.0/groups/$teamid/drive/root/children"
    $children = Invoke-RestMethod -Uri $URLCloneFolder -Headers $headerParams -Method GET -ContentType “application/json; charset=utf-8”
    $childCount = $children.value.folder.childCount.Get($i)
    while ($childCount -gt 0) {
        $childCount -= 1
        $URL = "https://graph.microsoft.com/v1.0/groups/$teamid/drive/root:/" + $BaseTeamChannelNames.value.displayName.Get($i) + ":/children"
        $childrenObjects = Invoke-RestMethod -Uri $URL -Headers $headerParams -Method GET -ContentType “application/json; charset=utf-8”
        $childrenname = $childrenObjects.value.name.Get($childCount)
        $URL = "https://graph.microsoft.com/v1.0/groups/$groupid/drive/root:/" + $BaseTeamChannelNames.value.displayName.Get($i) + "/" + $childrenname
        Invoke-RestMethod -Uri $URL -Headers $headerParams -Body "{""folder"": {}}" -Method PUT -ContentType “application/json; charset=utf-8”
    }
    $i++
}
</code>```

答:
You cannot copy the whole structure of Team.
You can copy the following parts in Team using POST /teams/{id}/clone Graph API

apps - Copies Microsoft Teams apps that are installed in the team.

channels – Copies the channel structure (but not the messages in the channel).

members – Copies the members and owners of the group.

settings – Copies all settings within the team, along with key group settings.

tabs – Copies the tabs within channels.

Ref doc: https://learn.microsoft.com/en-us/graph/api/team-clone?view=graph-rest-1.0&tabs=http

Body:
I was trying to copy the whole Team with a folderstructur to another. However, I ran into the problem that I don't know how to copy the whole structure.

The first part with the channels I do with the /teams/{teamsid}/clone

The second part I create in a first step the channel folders to fill them with the subfolders.

What I tried: But this Script just creates the Channel Folders and their direct subfolders

#Update Variables
$customername = $customername.replace(' ','')
$URLCloneFolder        = "https://graph.microsoft.com/v1.0/groups/?" + "$" + "filter=displayName eq '$customername'"
# Give MS Graph Time to create Group
$group = ''
Do {
    $group = Invoke-RestMethod -Uri $URLCloneFolder -ContentType application/json -Headers $headerParams -Method GET
    Start-Sleep -s 5
}
while ($group.value.Length -eq 0)
$groupid = $group.value.id
$URLBaseTeamChannels = "https://graph.microsoft.com/v1.0/teams/$teamid/channels"
$BaseTeamChannelNames = Invoke-RestMethod -Uri $URLBaseTeamChannels -ContentType application/json -Headers $headerParams -Method GET

$i=0
while ($i -lt $BaseTeamChannelNames.'@odata.count'){
    $URLCloneFolder = "https://graph.microsoft.com/v1.0/groups/$groupid/drive/root/children"
    $body = '{
    "name": "' + $BaseTeamChannelNames.value.displayName.Get($i) + '",
    "folder": {},
    "@microsoft.graph.conflictBehavior": "rename"
}'
    Invoke-RestMethod -Uri $URLCloneFolder -Headers $headerParams -Body $body -Method POST -ContentType “application/json; charset=utf-8”
    $URLCloneFolder = "https://graph.microsoft.com/v1.0/groups/$teamid/drive/root/children"
    $children = Invoke-RestMethod -Uri $URLCloneFolder -Headers $headerParams -Method GET -ContentType “application/json; charset=utf-8”
    $childCount = $children.value.folder.childCount.Get($i)
    while ($childCount -gt 0) {
        $childCount -= 1
        $URL = "https://graph.microsoft.com/v1.0/groups/$teamid/drive/root:/" + $BaseTeamChannelNames.value.displayName.Get($i) + ":/children"
        $childrenObjects = Invoke-RestMethod -Uri $URL -Headers $headerParams -Method GET -ContentType “application/json; charset=utf-8”
        $childrenname = $childrenObjects.value.name.Get($childCount)
        $URL = "https://graph.microsoft.com/v1.0/groups/$groupid/drive/root:/" + $BaseTeamChannelNames.value.displayName.Get($i) + "/" + $childrenname
        Invoke-RestMethod -Uri $URL -Headers $headerParams -Body "{""folder"": {}}" -Method PUT -ContentType “application/json; charset=utf-8”
    }
    $i++
}


问:
How to setup python flask web project with react on glitch?
I want to build a static web page based on python as server side and React for frontend on glitch online programming environment but unable to do .
I tried to implement by using CDN link but unable to use efficiently . Apart from this, I also wanted to use MATERIAL UI but according to there website it says

Using this approach in production is discouraged though - the client has to download the entire library, regardless of which components are actually used, affecting performance and bandwidth utilization.

Please elaborate steps to do the same.

答:
Im sorry if that's too simple, but I managed to do it reading this article:

https://towardsdatascience.com/build-deploy-a-react-flask-app-47a89a5d17d9

I use the framework Flask, but if you are using Django the process must be similar.

But I recomend building a API with python and communicate with the front-end through the fecth API from javascript, or axios on react. You'll even be able to work on the frontend and backend in two different servers if you want.


问:
Struggling to get str_replace to work in R
I'm struggling to get str_replace to work:

Data :

```<code>test <- structure(list(id_number = 101:106, why_join = c("Support for college success (examples: class selection, managing coursework, time management)",
"Support for college success (examples: class selection, managing coursework, time management)",
"Assistance with applying to (and enrolling in) college, Assistance with FASFA/financial aid, Support for college success (examples: class selection, managing coursework, time management), Identifying and enrolling in apprenticeship opportunities, Identifying and enrolling in certification programs",
"Support for college success (examples: class selection, managing coursework, time management)",
"Assistance with securing quality employment/career launch, Assistance with applying to (and enrolling in) college, Assistance with FASFA/financial aid, Support for college success (examples: class selection, managing coursework, time management), Identifying and enrolling in apprenticeship opportunities, Identifying and enrolling in certification programs, Interest in military service, Unsure/Exploratory",
"Assistance with applying to (and enrolling in) college, Assistance with FASFA/financial aid, Support for college success (examples: class selection, managing coursework, time management), Identifying and enrolling in certification programs"
)), row.names = c(NA, 6L), class = "data.frame")
</code>```

I'm trying to use str_replace to remove "(examples: class selection, managing coursework, time management)" from the strings "Support for college success (examples: class selection, managing coursework, time management)"

Code:

```<code>test$why_join <- str_replace(test$why_join, "Support for college success (examples: class selection, managing coursework, time management)", "Support for college success")
</code>```

My output is not removing that part of the string. Where am I going wrong?

答:
By default, the str_replace is in regex mode.  Wrap with fixed or else the (, ) are judged as metacharacters for capturing groups

```<code>library(stringr)
str_replace(test$why_join,
   fixed("Support for college success (examples: class selection, managing coursework, time management)"),
    "Support for college success")
</code>```

-output

```<code>[1] "Support for college success"
[2] "Support for college success"
[3] "Assistance with applying to (and enrolling in) college, Assistance with FASFA/financial aid, Support for college success, Identifying and enrolling in apprenticeship opportunities, Identifying and enrolling in certification programs"
[4] "Support for college success"
[5] "Assistance with securing quality employment/career launch, Assistance with applying to (and enrolling in) college, Assistance with FASFA/financial aid, Support for college success, Identifying and enrolling in apprenticeship opportunities, Identifying and enrolling in certification programs, Interest in military service, Unsure/Exploratory"
[6] "Assistance with applying to (and enrolling in) college, Assistance with FASFA/financial aid, Support for college success, Identifying and enrolling in certification programs"
</code>```

Body:
I'm struggling to get str_replace to work:

Data :

test <- structure(list(id_number = 101:106, why_join = c("Support for college success (examples: class selection, managing coursework, time management)",
"Support for college success (examples: class selection, managing coursework, time management)",
"Assistance with applying to (and enrolling in) college, Assistance with FASFA/financial aid, Support for college success (examples: class selection, managing coursework, time management), Identifying and enrolling in apprenticeship opportunities, Identifying and enrolling in certification programs",
"Support for college success (examples: class selection, managing coursework, time management)",
"Assistance with securing quality employment/career launch, Assistance with applying to (and enrolling in) college, Assistance with FASFA/financial aid, Support for college success (examples: class selection, managing coursework, time management), Identifying and enrolling in apprenticeship opportunities, Identifying and enrolling in certification programs, Interest in military service, Unsure/Exploratory",
"Assistance with applying to (and enrolling in) college, Assistance with FASFA/financial aid, Support for college success (examples: class selection, managing coursework, time management), Identifying and enrolling in certification programs"
)), row.names = c(NA, 6L), class = "data.frame")

I'm trying to use str_replace to remove "(examples: class selection, managing coursework, time management)" from the strings "Support for college success (examples: class selection, managing coursework, time management)"

Code:

test$why_join <- str_replace(test$why_join, "Support for college success (examples: class selection, managing coursework, time management)", "Support for college success")

My output is not removing that part of the string. Where am I going wrong?

Body:
By default, the str_replace is in regex mode.  Wrap with fixed or else the (, ) are judged as metacharacters for capturing groups

library(stringr)
str_replace(test$why_join,
   fixed("Support for college success (examples: class selection, managing coursework, time management)"),
    "Support for college success")

-output

[1] "Support for college success"
[2] "Support for college success"
[3] "Assistance with applying to (and enrolling in) college, Assistance with FASFA/financial aid, Support for college success, Identifying and enrolling in apprenticeship opportunities, Identifying and enrolling in certification programs"
[4] "Support for college success"
[5] "Assistance with securing quality employment/career launch, Assistance with applying to (and enrolling in) college, Assistance with FASFA/financial aid, Support for college success, Identifying and enrolling in apprenticeship opportunities, Identifying and enrolling in certification programs, Interest in military service, Unsure/Exploratory"
[6] "Assistance with applying to (and enrolling in) college, Assistance with FASFA/financial aid, Support for college success, Identifying and enrolling in certification programs"


问: Using <component> :is in Vue

答:
This seems to work for me:

Use a components object and have the component name key (sheetView in your case) used to target the key in the component :is value

example:

<template>
  <button @click="switchSheet">{{ currentSheet }}</button>
  <component :is="components[currentSheet]" :key="currentSheet" />
</template>

```

Title: Using <component> :is in Vue <script setup>

Body:
I want a button to toggle between two views on click. The code is:

<template>
  <button @click="switchSheet">{{ currentSheet }}</button>
  <component :is="sheetView" :key="componentKey" />
</template>

Body:
This seems to work for me:

Use a components object and have the component name key (sheetView in your case) used to target the key in the component :is value

example:

<template>
  <button @click="switchSheet">{{ currentSheet }}</button>
  <component :is="components[currentSheet]" :key="currentSheet" />
</template>

<script setup>
import DisplaySheetClassrooms from "./components/ds-classrooms.vue";
import DisplaySheetChromebooks from "./components/ds-chromebooks.vue";

let currentSheet = ref("DisplaySheetChromebooks");

// create an object key (doesn't need to be a ref)
const components = {
  DisplaySheetChromebooks,
  DisplaySheetClassrooms,
}

const switchSheet = () => {
  if (currentSheet === "DisplaySheetClassrooms) {
    currentSheet = "DisplaySheetChromebooks";
  } else {
    currentSheet = "DisplaySheetClassrooms";
  }
};
</script>


问:
Get the position of points on a line segment with constraints
I am designing a layout engine for ZenUML. One requirement (after simplification) is this:

There a line segment;

There are n (n < 100, it can be reduced to n < 30 if that makes difference in performance) points on this line segment, the order is fixed; (e.g. P1 ~ Pn)

There are known minimum distances between some points; (e.g. m_d(P2,P4)=500)

The length of the line segment should be as small as possible;

(nice to have) The gaps between neighbour points should be as even as possible (measured by standard deviation^, and must not violate 1~4).

(newly added) it must give result in no longer than 1s for 30 points in worst case (more or less constraints).

^ standard deviation is used as a best alternative that I can precisely describe with my limited math knowledge. However as Roman and David pointed out, there is more appealing result in some cases that does not satisfy lowest standard deviation. See this comment

A sister questions is asked at https://math.stackexchange.com/q/4377433. It is the same problem described with math language (matrix).

For example, for a line segment that has 4 points on it (P1 ~ P4).

m_d(P1, P3) = 200, m_d(P1, P4) = 900.

a. One solution would be P1 = 0, P2 = 0, P3 = 200, P4 = 900.

b. A better solution would be P1 = 0, P2 = 100, P3 = 200, P4 = 900. (put P3 at the middle)

c. A even better solution would be P1 = 0, P2 = 300, P3 = 600, P4 = 900. (evenly distribute P2 and P3).

Some background of this problem. Have a look at the following diagram.

We need to create a layout for all the lifelines (vertical lines). #1, #2

The gap between those line are decided by the length of messages. #3

We need to make sure the total width of the diagram is small (to save space when there are many participants). #4

In this diagram, B should be moved to closer to C. #5

I have implemented the following which satisfies constraints #1~#4. Can some please help with constraint #5? It can be partially met (like b in the example) or fully met (like c in the example). We can use standard deviation to measure the quality of the solution.
Updated: thanks to Roman Svistunov, the base implementation to get non-optimal position is dramatically simplified.

```<code>// Known minimum distance is stored in a matrix
// e.g.
//    m = [
//      [0, 100, 0, 900],
//      [0, 0,   0, 0],
//      [0, 0,   0, 0],
//      [0, 0,   0, 0],
//    ]

let f = function (n: number, m: Array<Array<number>>): number {
  let array = Array(n).fill(0);
  for (let i = 0; i < n; i++) {
    array[i] = f(i, m) + m[i][n];
  }
  return Math.max(0, ...array);
}
</code>```

答:
I’ll work through some theory and then give some JavaScript code that meets 1–4 and 6, a modified version of 5, and additionally

is robust to numerical issues

has no external dependencies.

We can express 1–4 as a linear program. Your sample instance, for example, would translate as

```<code>minimize x4 - x1
subject to

(known minimum distances)
a: x3 - x1 >= 200
b: x4 - x1 >= 900

(fixed order)
c: x2 - x1 >= 0
d: x3 - x2 >= 0
e: x4 - x3 >= 0

x1, x2, x3, x4 unbounded
</code>```

Every linear program has a dual program with the same optimum objective value (under conditions that are met here). The dual of the program above is below:

```<code>maximize 200 a + 900 b
subject to

x1: -a - b - c = -1
x2: c - d = 0
x3: a + d - e = 0
x4: b + e = 1

a, b, c, d, e >= 0
</code>```

This is a max-cost flow problem with no capacity constraints. In consequence, some path is an optimal flow, so we can understand criteria 1–4 as a longest path problem.

Once we have the optimal objective, 900 here, we can shift criterion 4 to a constraint

```<code>x4 - x1 <= 900
</code>```

and think about how to make the most pleasing layout. As written, we can achieve criterion 5 by solving a quadratic program:

```<code>minimize (x2 - x1)**2 + (x3 - x2)**2 + (x4 - x3)**2
subject to

(most efficient layout)
x4 - x1 <= 900

(known minimum distances)
x3 - x1 >= 200
x4 - x1 >= 900

(fixed order)
x2 - x1 >= 0
x3 - x2 >= 0
x4 - x3 >= 0

x1, x2, x3, x4 unbounded
</code>```

The objective that I’ve written is not the standard deviation, but it doesn’t matter. Minimizing the standard deviation is equivalent to minimizing the variance. In turn, the variance of a random variable X is E[X**2] - E[X]**2, and E[X]**2 is a constant here (E[X] = 900/4 = 150 in the example). Finally, maximizing E[X**2] is equivalent to maximizing the sum of squares of the equally likely outcomes.

I would propose a different criterion however.

5′. Maximize (in lexicographic order) the list of gap lengths sorted small to large.

What this means is that we try as hard as possible to avoid small gaps. In an example from Roman Svistunov, suppose that we have constraints

```<code>x3 - x1 >= 2
x4 - x2 >= 5.5
x5 - x3 >= 8
</code>```

The solution with minimum standard deviation sets

```<code>x1 = 0
x2 = 0.75
x3 = 2
x4 = 6.25
x5 = 10
</code>```

whereas the solution that optimizes the replacement objective sets

```<code>x1 = 0
x2 = 1
x3 = 2
x4 = 6.5
x5 = 10
</code>```

We’ve made x2 more centered at the cost of making x4 less centered. Since x2 is closer to its neighbors than x4, this seems like a reasonable trade to me, but you obviously have the final say.

To optimize 5′, we proceed as follows. Start by formulating a linear program like

```<code>maximize z
subject to

(most efficient layout)
x5 - x1 <= 10

(known minimum distances)
x3 - x1 >= 2
x4 - x2 >= 5.5
x5 - x3 >= 8

(fixed order)
x2 - x1 >= z
x3 - x2 >= z
x4 - x3 >= z
x5 - x4 >= z

x1, x2, x3, x4, x5 unbounded
</code>```

We solve for the optimum, z = 1 here, and also record which gaps prevented it from being larger. We replace those z variables and solve again, repeating until there is no occurrence of z.

```<code>maximize z
subject to

(most efficient layout)
x5 - x1 <= 10

(known minimum distances)
x3 - x1 >= 2
x4 - x2 >= 5.5
x5 - x3 >= 8

(fixed order)
x2 - x1 = 1
x3 - x2 = 1
x4 - x3 >= z
x5 - x4 >= z

x1, x2, x3, x4, x5 unbounded
</code>```

The optimum is z = 3.5.

```<code>maximize z
subject to

(most efficient layout)
x5 - x1 <= 10

(known minimum distances)
x3 - x1 >= 2
x4 - x2 >= 5.5
x5 - x3 >= 8

(fixed order)
x2 - x1 = 1
x3 - x2 = 1
x4 - x3 >= z
x5 - x4 = 3.5

x1, x2, x3, x4, x5 unbounded
</code>```

The optimum is z = 4.5, and that’s the last iteration.

As observed earlier, we can solve these linear programs using an extended longest path algorithm. In JavaScript:

```<code>// Dual numbers represent linear functions of time.
function Dual(p, v) {
  return { position: p, velocity: v };
}

// Adds dual numbers x and y.
function dualPlus(x, y) {
  return Dual(x.position + y.position, x.velocity + y.velocity);
}

const epsilon = Math.sqrt(Number.EPSILON);

// Compares dual numbers x and y by their position at a time infinitesimally
// after now.
function dualLessThan(x, y) {
  let d = x.position - y.position;
  return d < -epsilon || (Math.abs(d) <= epsilon && x.velocity < y.velocity);
}

// Tracks delta, the length of time for which every pair of arguments to
// .dualLessThan() maintains the present relation.
function DeltaTracker() {
  return {
    delta: Infinity,
    dualLessThan: function (x, y) {
      let lessThan = dualLessThan(x, y);
      if (lessThan) {
        [x, y] = [y, x];
      }
      if (x.velocity < y.velocity) {
        this.delta = Math.min(
          this.delta,
          (x.position - y.position) / (y.velocity - x.velocity)
        );
      }
      return lessThan;
    },
  };
}

// Converts the adjacency matrix to an adjacency list representation.
function graphFromMatrix(n, matrix) {
  let graph = [];
  for (let j = 0; j < n; j++) {
    graph.push([]);
    for (let i = 0; i < j; i++) {
      if (matrix[i][j] > 0) {
        graph[j].push({ i: i, length: Dual(matrix[i][j], 0) });
      }
    }
  }
  return graph;
}

// Essentially the usual algorithm for longest path, but tracks delta.
function longestPathTable(graph, gaps) {
  let tracker = DeltaTracker();
  let maximum = Dual(0, 0);
  let table = [];
  for (let j = 0; j < graph.length; j++) {
    let argument = null;
    if (j > 0) {
      maximum = dualPlus(maximum, gaps[j - 1]);
    }
    for (let edge of graph[j]) {
      let x = dualPlus(table[edge.i].maximum, edge.length);
      if (tracker.dualLessThan(maximum, x)) {
        argument = edge.i;
        maximum = x;
      }
    }
    table.push({ argument: argument, maximum: maximum });
  }
  return [tracker.delta, table];
}

// Essentially the usual algorithm for decoding the longest path from the
// dynamic program table.
function freezeCriticalGaps(table, graph, gaps) {
  let j = table.length - 1;
  while (j > 0) {
    let critical = true;
    let argument = table[j].argument;
    if (argument !== null) {
      j = argument;
    } else {
      j--;
      gaps[j].velocity = 0;
    }
  }
}

// Changes the time from now to now + delta.
function advanceGaps(gaps, delta) {
  for (let i = 0; i < gaps.length; i++) {
    gaps[i].position += gaps[i].velocity * delta;
  }
}

// Extracts the final result from the dynamic program table.
function positionsFromTable(table) {
  let positions = [];
  for (let entry of table) {
    positions.push(entry.maximum.position);
  }
  return positions;
}

// Entry point for the layout algorithm.
function layOut(n, matrix) {
  let graph = graphFromMatrix(n, matrix);
  let gaps = [];
  for (let j = 1; j < n; j++) {
    gaps.push(Dual(0, 1));
  }
  while (true) {
    let [delta, table] = longestPathTable(graph, gaps);
    if (delta == Infinity) {
      return positionsFromTable(table);
    }
    if (table[n - 1].maximum.velocity > 0) {
      freezeCriticalGaps(table, graph, gaps);
    } else {
      advanceGaps(gaps, delta);
    }
  }
}

// Various test cases.
console.log(
  layOut(4, [
    [0, 200, 0, 900],
    [0, 0, 0, 0],
    [0, 0, 0, 0],
    [0, 0, 0, 0],
  ])
);

console.log(
  layOut(5, [
    [0, 0, 2, 0, 0],
    [0, 0, 0, 5.5, 0],
    [0, 0, 0, 0, 8],
    [0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0],
  ])
);

console.log(
  layOut(4, [
    [0, 0, 200, 0],
    [0, 0, 0, 150],
    [0, 0, 0, 0],
    [0, 0, 0, 0],
  ])
);

console.log(
  layOut(4, [
    [0, 0, 200, 0],
    [0, 0, 0, 200],
    [0, 0, 0, 0],
    [0, 0, 0, 0],
  ])
);

console.log(
  layOut(4, [
    [0, 0, 200, 0],
    [0, 0, 0, 300],
    [0, 0, 0, 0],
    [0, 0, 0, 0],
  ])
);
</code>```

Body:
I am designing a layout engine for ZenUML. One requirement (after simplification) is this:

There a line segment;

There are n (n < 100, it can be reduced to n < 30 if that makes difference in performance) points on this line segment, the order is fixed; (e.g. P1 ~ Pn)

There are known minimum distances between some points; (e.g. m_d(P2,P4)=500)

The length of the line segment should be as small as possible;

(nice to have) The gaps between neighbour points should be as even as possible (measured by standard deviation^, and must not violate 1~4).

(newly added) it must give result in no longer than 1s for 30 points in worst case (more or less constraints).

^ standard deviation is used as a best alternative that I can precisely describe with my limited math knowledge. However as Roman and David pointed out, there is more appealing result in some cases that does not satisfy lowest standard deviation. See this comment

A sister questions is asked at https://math.stackexchange.com/q/4377433. It is the same problem described with math language (matrix).

For example, for a line segment that has 4 points on it (P1 ~ P4).

m_d(P1, P3) = 200, m_d(P1, P4) = 900.

a. One solution would be P1 = 0, P2 = 0, P3 = 200, P4 = 900.

b. A better solution would be P1 = 0, P2 = 100, P3 = 200, P4 = 900. (put P3 at the middle)

c. A even better solution would be P1 = 0, P2 = 300, P3 = 600, P4 = 900. (evenly distribute P2 and P3).

Some background of this problem. Have a look at the following diagram.

We need to create a layout for all the lifelines (vertical lines). #1, #2

The gap between those line are decided by the length of messages. #3

We need to make sure the total width of the diagram is small (to save space when there are many participants). #4

In this diagram, B should be moved to closer to C. #5

I have implemented the following which satisfies constraints #1~#4. Can some please help with constraint #5? It can be partially met (like b in the example) or fully met (like c in the example). We can use standard deviation to measure the quality of the solution.
Updated: thanks to Roman Svistunov, the base implementation to get non-optimal position is dramatically simplified.

// Known minimum distance is stored in a matrix
// e.g.
//    m = [
//      [0, 100, 0, 900],
//      [0, 0,   0, 0],
//      [0, 0,   0, 0],
//      [0, 0,   0, 0],
//    ]

let f = function (n: number, m: Array<Array<number>>): number {
  let array = Array(n).fill(0);
  for (let i = 0; i < n; i++) {
    array[i] = f(i, m) + m[i][n];
  }
  return Math.max(0, ...array);
}

Body:
I’ll work through some theory and then give some JavaScript code that meets 1–4 and 6, a modified version of 5, and additionally

is robust to numerical issues

has no external dependencies.

We can express 1–4 as a linear program. Your sample instance, for example, would translate as

minimize x4 - x1
subject to

(known minimum distances)
a: x3 - x1 >= 200
b: x4 - x1 >= 900

(fixed order)
c: x2 - x1 >= 0
d: x3 - x2 >= 0
e: x4 - x3 >= 0

x1, x2, x3, x4 unbounded

Every linear program has a dual program with the same optimum objective value (under conditions that are met here). The dual of the program above is below:

maximize 200 a + 900 b
subject to

x1: -a - b - c = -1
x2: c - d = 0
x3: a + d - e = 0
x4: b + e = 1

a, b, c, d, e >= 0

This is a max-cost flow problem with no capacity constraints. In consequence, some path is an optimal flow, so we can understand criteria 1–4 as a longest path problem.

Once we have the optimal objective, 900 here, we can shift criterion 4 to a constraint

x4 - x1 <= 900

and think about how to make the most pleasing layout. As written, we can achieve criterion 5 by solving a quadratic program:

minimize (x2 - x1)**2 + (x3 - x2)**2 + (x4 - x3)**2
subject to

(most efficient layout)
x4 - x1 <= 900

(known minimum distances)
x3 - x1 >= 200
x4 - x1 >= 900

(fixed order)
x2 - x1 >= 0
x3 - x2 >= 0
x4 - x3 >= 0

x1, x2, x3, x4 unbounded

The objective that I’ve written is not the standard deviation, but it doesn’t matter. Minimizing the standard deviation is equivalent to minimizing the variance. In turn, the variance of a random variable X is E[X**2] - E[X]**2, and E[X]**2 is a constant here (E[X] = 900/4 = 150 in the example). Finally, maximizing E[X**2] is equivalent to maximizing the sum of squares of the equally likely outcomes.

I would propose a different criterion however.

5′. Maximize (in lexicographic order) the list of gap lengths sorted small to large.

What this means is that we try as hard as possible to avoid small gaps. In an example from Roman Svistunov, suppose that we have constraints

x3 - x1 >= 2
x4 - x2 >= 5.5
x5 - x3 >= 8

The solution with minimum standard deviation sets

x1 = 0
x2 = 0.75
x3 = 2
x4 = 6.25
x5 = 10

whereas the solution that optimizes the replacement objective sets

x1 = 0
x2 = 1
x3 = 2
x4 = 6.5
x5 = 10

We’ve made x2 more centered at the cost of making x4 less centered. Since x2 is closer to its neighbors than x4, this seems like a reasonable trade to me, but you obviously have the final say.

To optimize 5′, we proceed as follows. Start by formulating a linear program like

maximize z
subject to

(most efficient layout)
x5 - x1 <= 10

(known minimum distances)
x3 - x1 >= 2
x4 - x2 >= 5.5
x5 - x3 >= 8

(fixed order)
x2 - x1 >= z
x3 - x2 >= z
x4 - x3 >= z
x5 - x4 >= z

x1, x2, x3, x4, x5 unbounded

We solve for the optimum, z = 1 here, and also record which gaps prevented it from being larger. We replace those z variables and solve again, repeating until there is no occurrence of z.

maximize z
subject to

(most efficient layout)
x5 - x1 <= 10

(known minimum distances)
x3 - x1 >= 2
x4 - x2 >= 5.5
x5 - x3 >= 8

(fixed order)
x2 - x1 = 1
x3 - x2 = 1
x4 - x3 >= z
x5 - x4 >= z

x1, x2, x3, x4, x5 unbounded

The optimum is z = 3.5.

maximize z
subject to

(most efficient layout)
x5 - x1 <= 10

(known minimum distances)
x3 - x1 >= 2
x4 - x2 >= 5.5
x5 - x3 >= 8

(fixed order)
x2 - x1 = 1
x3 - x2 = 1
x4 - x3 >= z
x5 - x4 = 3.5

x1, x2, x3, x4, x5 unbounded

The optimum is z = 4.5, and that’s the last iteration.

As observed earlier, we can solve these linear programs using an extended longest path algorithm. In JavaScript:

// Dual numbers represent linear functions of time.
function Dual(p, v) {
  return { position: p, velocity: v };
}

// Adds dual numbers x and y.
function dualPlus(x, y) {
  return Dual(x.position + y.position, x.velocity + y.velocity);
}

const epsilon = Math.sqrt(Number.EPSILON);

// Compares dual numbers x and y by their position at a time infinitesimally
// after now.
function dualLessThan(x, y) {
  let d = x.position - y.position;
  return d < -epsilon || (Math.abs(d) <= epsilon && x.velocity < y.velocity);
}

// Tracks delta, the length of time for which every pair of arguments to
// .dualLessThan() maintains the present relation.
function DeltaTracker() {
  return {
    delta: Infinity,
    dualLessThan: function (x, y) {
      let lessThan = dualLessThan(x, y);
      if (lessThan) {
        [x, y] = [y, x];
      }
      if (x.velocity < y.velocity) {
        this.delta = Math.min(
          this.delta,
          (x.position - y.position) / (y.velocity - x.velocity)
        );
      }
      return lessThan;
    },
  };
}

// Converts the adjacency matrix to an adjacency list representation.
function graphFromMatrix(n, matrix) {
  let graph = [];
  for (let j = 0; j < n; j++) {
    graph.push([]);
    for (let i = 0; i < j; i++) {
      if (matrix[i][j] > 0) {
        graph[j].push({ i: i, length: Dual(matrix[i][j], 0) });
      }
    }
  }
  return graph;
}

// Essentially the usual algorithm for longest path, but tracks delta.
function longestPathTable(graph, gaps) {
  let tracker = DeltaTracker();
  let maximum = Dual(0, 0);
  let table = [];
  for (let j = 0; j < graph.length; j++) {
    let argument = null;
    if (j > 0) {
      maximum = dualPlus(maximum, gaps[j - 1]);
    }
    for (let edge of graph[j]) {
      let x = dualPlus(table[edge.i].maximum, edge.length);
      if (tracker.dualLessThan(maximum, x)) {
        argument = edge.i;
        maximum = x;
      }
    }
    table.push({ argument: argument, maximum: maximum });
  }
  return [tracker.delta, table];
}

// Essentially the usual algorithm for decoding the longest path from the
// dynamic program table.
function freezeCriticalGaps(table, graph, gaps) {
  let j = table.length - 1;
  while (j > 0) {
    let critical = true;
    let argument = table[j].argument;
    if (argument !== null) {
      j = argument;
    } else {
      j--;
      gaps[j].velocity = 0;
    }
  }
}

// Changes the time from now to now + delta.
function advanceGaps(gaps, delta) {
  for (let i = 0; i < gaps.length; i++) {
    gaps[i].position += gaps[i].velocity * delta;
  }
}

// Extracts the final result from the dynamic program table.
function positionsFromTable(table) {
  let positions = [];
  for (let entry of table) {
    positions.push(entry.maximum.position);
  }
  return positions;
}

// Entry point for the layout algorithm.
function layOut(n, matrix) {
  let graph = graphFromMatrix(n, matrix);
  let gaps = [];
  for (let j = 1; j < n; j++) {
    gaps.push(Dual(0, 1));
  }
  while (true) {
    let [delta, table] = longestPathTable(graph, gaps);
    if (delta == Infinity) {
      return positionsFromTable(table);
    }
    if (table[n - 1].maximum.velocity > 0) {
      freezeCriticalGaps(table, graph, gaps);
    } else {
      advanceGaps(gaps, delta);
    }
  }
}

// Various test cases.
console.log(
  layOut(4, [
    [0, 200, 0, 900],
    [0, 0, 0, 0],
    [0, 0, 0, 0],
    [0, 0, 0, 0],
  ])
);

console.log(
  layOut(5, [
    [0, 0, 2, 0, 0],
    [0, 0, 0, 5.5, 0],
    [0, 0, 0, 0, 8],
    [0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0],
  ])
);

console.log(
  layOut(4, [
    [0, 0, 200, 0],
    [0, 0, 0, 150],
    [0, 0, 0, 0],
    [0, 0, 0, 0],
  ])
);

console.log(
  layOut(4, [
    [0, 0, 200, 0],
    [0, 0, 0, 200],
    [0, 0, 0, 0],
    [0, 0, 0, 0],
  ])
);

console.log(
  layOut(4, [
    [0, 0, 200, 0],
    [0, 0, 0, 300],
    [0, 0, 0, 0],
    [0, 0, 0, 0],
  ])
);


问:
Plugin to commit hudson build artifact
Are there any plugins available which will commit the build artifact back to SVN?</p>

答:
Unfortunately Svn Publisher is not really finished and requires quite a bit more work before I can use it in anger.

I've found I can do what I need with a shell/cmd script executed as a build action (or of course post-build would work), although it's not really ideal. The script just uses standard svn command line functions and looks something like:

```<code>svn mkdir http://my.server:port/project/branches/buildArtifacts/${BUILD_ID}/ --username USERNAME --password PASSWORD -m "JIRA_ISSUE This is a commit message"

svn co http://my.server:port/project/branches/buildArtifacts/${BUILD_ID}/ BuildArtifacts --username USERNAME --password PASSWORD

cd BuildArtifacts
cp ../../build/${BUILD_ID}/*.xml .

svn add *

svn ci --username USERNAME --password PASSWORD -m "JIRA_ISSUE This is a commit message"
</code>```

So, we create the new folder for the build artifacts in Subversion, check it out to a local (in-workspace) folder, copy what we want in, svn add those items then commit everything back.

Personally, I am still not sold on the benefit of having build reports in Subversion, but we need to have persistent storage of this information -- the Jenkins server isn't a good repository for it.

Writing a custom plugin or actually fixing Svn Publisher would be a better solution long term.

ContentLicense: CC BY-SA 3.0

Title: Plugin to commit hudson build artifact

Body:
Unfortunately Svn Publisher is not really finished and requires quite a bit more work before I can use it in anger.

I've found I can do what I need with a shell/cmd script executed as a build action (or of course post-build would work), although it's not really ideal. The script just uses standard svn command line functions and looks something like:

svn mkdir http://my.server:port/project/branches/buildArtifacts/${BUILD_ID}/ --username USERNAME --password PASSWORD -m "JIRA_ISSUE This is a commit message"

svn co http://my.server:port/project/branches/buildArtifacts/${BUILD_ID}/ BuildArtifacts --username USERNAME --password PASSWORD

cd BuildArtifacts
cp ../../build/${BUILD_ID}/*.xml .

svn add *

svn ci --username USERNAME --password PASSWORD -m "JIRA_ISSUE This is a commit message"

So, we create the new folder for the build artifacts in Subversion, check it out to a local (in-workspace) folder, copy what we want in, svn add those items then commit everything back.

Personally, I am still not sold on the benefit of having build reports in Subversion, but we need to have persistent storage of this information -- the Jenkins server isn't a good repository for it.

Writing a custom plugin or actually fixing Svn Publisher would be a better solution long term.


问:
Using logical operators with expressions with multiple return values in lua
I'd like to do something like:

s,e = string.find(str, pattern1) or string.find(str, pattern2)
```

(because lua patterns don't have the equivalent of a regex |)

But this gives me nil for e even if one of the patterns matches.

How can I get both return values from the first function call to match?

答:
Both of your function calls are neither the only nor the last one in a list of expressions. Hence their list of return values is adjusted to 1 value.

See https://www.lua.org/manual/5.4/manual.html#3.4

hence

```<code>s,e = string.find(str, pattern1) or string.find(str, pattern2)
</code>```

is more or less equivalent to

```<code>do
  local v1 = string.find(str, pattern1)
  if v1 then
    s, e = v1, nil
  else
    local v2 = string.find(str, pattern2)
    if v2 then
      s, e = v2, nil
    else
     s, e = nil, nil
    end
  end
end
</code>```

Assuming the first pattern matches, then v1 is a true value. The or statement is being short-circuited so you assign

```<code>s, e = v1, nil
</code>```

If the first pattern does not match the second string.find is called. If there's a match it's return value is a true value

```<code>s, e = nil or v2, nil
</code>```

If the first pattern does not match and the second does not match you assign

```<code>s, e = nil, nil
</code>```

You need to handle both string.find calls separately in order to not lose any return values.

```<code>local v1, v2 = string.find(str, pattern1)
if not v1 then
  v1, v2 = string.find(str, pattern2)
end
s, e = v1, v2
</code>```

Body:
I'd like to do something like:

s,e = string.find(str, pattern1) or string.find(str, pattern2)

(because lua patterns don't have the equivalent of a regex |)

But this gives me nil for e even if one of the patterns matches.

How can I get both return values from the first function call to match?

Body:
Both of your function calls are neither the only nor the last one in a list of expressions. Hence their list of return values is adjusted to 1 value.

See https://www.lua.org/manual/5.4/manual.html#3.4

hence

s,e = string.find(str, pattern1) or string.find(str, pattern2)

is more or less equivalent to

do
  local v1 = string.find(str, pattern1)
  if v1 then
    s, e = v1, nil
  else
    local v2 = string.find(str, pattern2)
    if v2 then
      s, e = v2, nil
    else
     s, e = nil, nil
    end
  end
end

Assuming the first pattern matches, then v1 is a true value. The or statement is being short-circuited so you assign

s, e = v1, nil

If the first pattern does not match the second string.find is called. If there's a match it's return value is a true value

s, e = nil or v2, nil

If the first pattern does not match and the second does not match you assign

s, e = nil, nil

You need to handle both string.find calls separately in order to not lose any return values.

local v1, v2 = string.find(str, pattern1)
if not v1 then
  v1, v2 = string.find(str, pattern2)
end
s, e = v1, v2


问:
using same variable that is created in function into another function
I want to use 'number' variable that was created out of the function and use it in  couple functions and also give it an initial value 0, but it gives "local variable 'number' referenced before assignment" error at the last line of code.How could I fix it?Thanks in advance.</p>
```<code>lst_img=[img0,img1,img2,img3,img4]
number=0

def go_forward():

    global number
    number+=1
    shwimage.grid_forget()
    global shwimage1
    shwimage1=Label(image=lst_img[number])
    shwimage1.grid(row=0,column=0,columnspan=3)

def go_back():

   if number==0:
      shwimage.grid_forget()
   shwimage1.grid_forget()
   shwimage2=Label(image=lst_img[number-1])
   shwimage2.grid(row=0,column=0,columnspan=3)
   number-=1  # local variable 'number' referenced before assignment
</code>```

答:
The others answers' solution to add global number in go_back is working, but using global variables is really not a good practice when you can do otherwise.

What you could do here is use object oriented programming. Create a class with a number, lst_img and showimage properties and two class methods, go_forward and go_backward, that can modifiy the number and showimage properties.
How I would start :

```<code>class ImageViewer:
    # Class constructor
    def __init__(self, lst_img):
        self.lst_img = lst_img
        self.number = 0 # number is always 0 at the beginning
        self.showimage = None

    def go_forward(self):
        if self.number == len(self.lst_img)-1 :
            return
        else:
            self.number += 1

        # ... add your code ....
        if self.showimage is None:
            # code to create a showimage...
            self.showimage = .....
        else:
            # code to update the showimage...

    def go_backward(self):
        if self.number == 0:
            return
        else :
            self.number -= 1

        if self.showimage is None:
            # code to create a showimage...
            self.showimage = .....
        else:
        # code to update the showimage...

# Create an viewer instance with a list of images
lst_img  = [img1, img2, img3]
viewer = ImageViewer(lst_img)

# Now you can use the go_forward and go_backward methods to naviguate in your images
viewer.go_forward()
viewer.go_forward()
viewer.go_backward()
....
</code>```

Body:
I want to use 'number' variable that was created out of the function and use it in  couple functions and also give it an initial value 0, but it gives "local variable 'number' referenced before assignment" error at the last line of code.How could I fix it?Thanks in advance.

lst_img=[img0,img1,img2,img3,img4]
number=0

def go_forward():

    global number
    number+=1
    shwimage.grid_forget()
    global shwimage1
    shwimage1=Label(image=lst_img[number])
    shwimage1.grid(row=0,column=0,columnspan=3)

def go_back():

   if number==0:
      shwimage.grid_forget()
   shwimage1.grid_forget()
   shwimage2=Label(image=lst_img[number-1])
   shwimage2.grid(row=0,column=0,columnspan=3)
   number-=1  # local variable 'number' referenced before assignment

Body:
The others answers' solution to add global number in go_back is working, but using global variables is really not a good practice when you can do otherwise.

What you could do here is use object oriented programming. Create a class with a number, lst_img and showimage properties and two class methods, go_forward and go_backward, that can modifiy the number and showimage properties.
How I would start :

class ImageViewer:
    # Class constructor
    def __init__(self, lst_img):
        self.lst_img = lst_img
        self.number = 0 # number is always 0 at the beginning
        self.showimage = None

    def go_forward(self):
        if self.number == len(self.lst_img)-1 :
            return
        else:
            self.number += 1

        # ... add your code ....
        if self.showimage is None:
            # code to create a showimage...
            self.showimage = .....
        else:
            # code to update the showimage...

    def go_backward(self):
        if self.number == 0:
            return
        else :
            self.number -= 1

        if self.showimage is None:
            # code to create a showimage...
            self.showimage = .....
        else:
        # code to update the showimage...

# Create an viewer instance with a list of images
lst_img  = [img1, img2, img3]
viewer = ImageViewer(lst_img)

# Now you can use the go_forward and go_backward methods to naviguate in your images
viewer.go_forward()
viewer.go_forward()
viewer.go_backward()
....


问:
Using substring to extract part of a string
I have the following string:
https://dummycloud/image/fetch/f_webp,q_auto:best,w_1080,c_limit/auto/https://dummy.com/media/products/8/8/763160.jpg

And I am only interested in the this part that comes at the end: https://dummy.com/media/products/8/8/763160.jpg

I am using the following with StringBuilder

```<code>val url = imageUrl.substringAfterLast("https")

return StringBuilder()
    .append("https")
    .append(url)
    .toString()
</code>```

Just wondering if there is a substringAfterLast that would keep the prefix https. As I have to use StringBuilder manually to append it from the extract string.

答:
You could use</p>
```<code>imageUrl.substring(imageUrl.lastIndexOf(“https”));
</code>```

Body:
I have the following string:
https://dummycloud/image/fetch/f_webp,q_auto:best,w_1080,c_limit/auto/https://dummy.com/media/products/8/8/763160.jpg

And I am only interested in the this part that comes at the end: https://dummy.com/media/products/8/8/763160.jpg

I am using the following with StringBuilder

val url = imageUrl.substringAfterLast("https")

return StringBuilder()
    .append("https")
    .append(url)
    .toString()

Just wondering if there is a substringAfterLast that would keep the prefix https. As I have to use StringBuilder manually to append it from the extract string.

Body:
You could use

imageUrl.substring(imageUrl.lastIndexOf(“https”));


问:
Couchbase with Azure Linux VM
I installed ubuntu server VM on Azure there I installed couchbase community edition on  now i need to access the couchbase using dotnet SDK  but code gives me bucket not found or unreachable error.
even i try configuring a public dns and gave it as ip during cluster creation but still its giving the same.
even i added public dns to the host file like below
127.0.0.1 public dns
The SDK log includes below 2 statements
Attempted bootstrapping on endpoint "name.eastus.cloudapp.azure.com" has failed. (e80489ed)
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.

SDK Doctor Log:

```<code>09:51:20.331 INFO ▶ Parsing connection string `couchbases://hsotname.eastus.cloudapp.azure.com/travel-sample`
09:51:20.334 INFO ▶ Connection string was parsed as a potential DNS SRV record
09:51:31.316 INFO ▶ Connection string specifies to use secured connections
09:51:31.316 INFO ▶ Connection string identifies the following CCCP endpoints:
09:51:31.316 INFO ▶   1. hsotname.eastus.cloudapp.azure.com:11207
09:51:31.316 INFO ▶ Connection string identifies the following HTTP endpoints:
09:51:31.316 INFO ▶   1. hsotname.eastus.cloudapp.azure.com:18091
09:51:31.316 INFO ▶ Connection string specifies bucket `travel-sample`
09:51:31.316 WARN ▶ No certificate authority file specified (--tls-ca), skipping server certificate verification for this run.
09:51:42.453 WARN ▶ Your connection string specifies only a single host.  You should consider adding additional static nodes from your cluster to this list to improve your applications fault-tolerance
09:51:42.462 INFO ▶ Performing DNS lookup for host `hsotname.eastus.cloudapp.azure.com`
09:51:42.462 INFO ▶ Bootstrap host `hsotname.eastus.cloudapp.azure.com` refers to a server with the address `13.82.80.55`
09:51:42.462 INFO ▶ Attempting to connect to cluster via CCCP
09:51:42.463 INFO ▶ Attempting to fetch config via cccp from `hsotname.eastus.cloudapp.azure.com:11207`
09:51:44.474 ERRO ▶ Failed to fetch configuration via cccp from `hsotname.eastus.cloudapp.azure.com:11207` (error: dial tcp 13.82.80.55:11207: i/o timeout)
09:51:44.474 INFO ▶ Attempting to connect to cluster via HTTP (Terse)
09:51:44.474 INFO ▶ Attempting to fetch terse config via http from `hsotname.eastus.cloudapp.azure.com:18091`
09:51:46.480 ERRO ▶ Failed to fetch terse configuration via http from `hsotname.eastus.cloudapp.azure.com:18091` (error: Get "http://hsotname.eastus.cloudapp.azure.com:18091/pools/default/b/travel-sample": context deadline exceeded (Client.Timeout exceeded while awaiting headers))
09:51:46.480 INFO ▶ Attempting to connect to cluster via HTTP (Full)
09:51:46.480 INFO ▶ Failed to connect via HTTP (Full), as it is not yet supported by the doctor
09:51:46.481 INFO ▶ Selected the following network type:
09:51:46.481 ERRO ▶ All endpoints specified by your connection string were unreachable, further cluster diagnostics are not possible
09:51:46.481 INFO ▶ Diagnostics completed

Summary:
←[33m[WARN]←[0m No certificate authority file specified (--tls-ca), skipping server certificate verification for this run.
←[33m[WARN]←[0m Your connection string specifies only a single host.  You should consider adding additional static nodes from your cluster to this list to improve your applications fault-tolerance
←[31m[ERRO]←[0m Failed to fetch configuration via cccp from `hsotname.eastus.cloudapp.azure.com:11207` (error: dial tcp 13.82.80.55:11207: i/o timeout)
←[31m[ERRO]←[0m Failed to fetch terse configuration via http from `hsotname.eastus.cloudapp.azure.com:18091` (error: Get "http://hsotname.eastus.cloudapp.azure.com:18091/pools/default/b/travel-sample": context deadline exceeded (Client.Timeout exceeded while awaiting headers))
←[31m[ERRO]←[0m All endpoints specified by your connection string were unreachable, further cluster diagnostics are not possible

Found multiple issues, see listing above.
</code>```

Both 18091 and 11207 port i added as inbound rule.
my ufw status is inactive
The above mentioned 2 ports are not listening

couchbaseadm@couchbasedbserver:~$ sudo lsof -i -P -n | grep LISTEN

```<code>systemd-r   926 systemd-resolve   13u  IPv4   18715      0t0  TCP 127.0.0.53:53 (LISTEN)
sshd       1103            root    3u  IPv4   21086      0t0  TCP *:22 (LISTEN)
sshd       1103            root    4u  IPv6   21088      0t0  TCP *:22 (LISTEN)
beam.smp   6323       couchbase   17u  IPv4 3937812      0t0  TCP 127.0.0.1:21200 (LISTEN)
epmd       6354       couchbase    3u  IPv4 3937267      0t0  TCP *:4369 (LISTEN)
epmd       6354       couchbase    4u  IPv6 3937268      0t0  TCP *:4369 (LISTEN)
beam.smp   6465       couchbase   34u  IPv4 3943391      0t0  TCP *:21100 (LISTEN)
beam.smp   6465       couchbase   48u  IPv4 3938657      0t0  TCP *:8091 (LISTEN)
beam.smp   6514       couchbase   17u  IPv4 3938608      0t0  TCP 127.0.0.1:21300 (LISTEN)
beam.smp   6514       couchbase   27u  IPv4 3938628      0t0  TCP *:8092 (LISTEN)
prometheu  6563       couchbase    9u  IPv4 3938650      0t0  TCP 127.0.0.1:9123 (LISTEN)
goxdcr     6583       couchbase   11u  IPv4 3938705      0t0  TCP 127.0.0.1:9998 (LISTEN)
memcached  6592       couchbase    5u  IPv4 3938689      0t0  TCP 127.0.0.1:11280 (LISTEN)
memcached  6592       couchbase   12u  IPv4 3937931      0t0  TCP *:11210 (LISTEN)
memcached  6592       couchbase   13u  IPv4 3937932      0t0  TCP *:11209 (LISTEN)
memcached  6592       couchbase   14u  IPv6 3937933      0t0  TCP *:11210 (LISTEN)
memcached  6592       couchbase   15u  IPv6 3937934      0t0  TCP *:11209 (LISTEN)
indexer    6741       couchbase   16u  IPv4 3944492      0t0  TCP *:9101 (LISTEN)
indexer    6741       couchbase   19u  IPv4 3944066      0t0  TCP *:9100 (LISTEN)
indexer    6741       couchbase   20u  IPv4 3944500      0t0  TCP *:9102 (LISTEN)
indexer    6741       couchbase   69u  IPv4 3946013      0t0  TCP *:9105 (LISTEN)
projector  6762       couchbase    9u  IPv4 3944075      0t0  TCP *:9999 (LISTEN)
cbq-engin  6782       couchbase    7u  IPv6 3944534      0t0  TCP *:8093 (LISTEN)
cbq-engin  6782       couchbase    8u  IPv4 3944535      0t0  TCP *:8093 (LISTEN)
cbft       6799       couchbase    8u  IPv4 3944112      0t0  TCP *:9130 (LISTEN)
cbft       6799       couchbase    9u  IPv4 3944149      0t0  TCP *:8094 (LISTEN)
sync_gate 11950    sync_gateway    8u  IPv4 4119414      0t0  TCP 127.0.0.1:4985 (LISTEN)
sync_gate 11950    sync_gateway    9u  IPv6 4119422      0t0  TCP *:4984 (LISTEN)
</code>```

Here is the stacktrace:

```<code>StackTrace " at Couchbase.Core.ClusterContext.d__58.MoveNext()\r\n
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n
at System.Threading.Tasks.ValueTask1.get_Result()\r\n at System.Runtime.CompilerServices.ConfiguredValueTaskAwaitable1.ConfiguredValueTaskAwaiter.GetResult()\r\n
at Couchbase.Cluster.<>c__DisplayClass30_0.<b__0>d.MoveNext()\r\n
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n
at System.Threading.Tasks.ValueTask1.get_Result()\r\n at System.Runtime.CompilerServices.ConfiguredValueTaskAwaitable1.ConfiguredValueTaskAwaiter.GetResult()\r\n
</code>```

Dotnet SDK Log

```<code>2022-02-09T17:28:46.3409884+05:30  [DBG] Waiting for 00:00:02.5000000 before polling. (c8639b24)
2022-02-09T17:28:48.8643285+05:30  [DBG] Done waiting, polling... (93018145)
2022-02-09T17:28:48.8649060+05:30  [DBG] Waiting for 00:00:02.5000000 before polling. (c8639b24)
2022-02-09T17:28:51.3664735+05:30  [DBG] Done waiting, polling... (93018145)
2022-02-09T17:28:51.3667541+05:30  [DBG] Waiting for 00:00:02.5000000 before polling. (c8639b24)
2022-02-09T17:28:53.8811651+05:30  [DBG] Done waiting, polling... (93018145)
2022-02-09T17:28:53.8814100+05:30  [DBG] Waiting for 00:00:02.5000000 before polling. (c8639b24)
2022-02-09T17:28:56.3823825+05:30  [DBG] Done waiting, polling... (93018145)
2022-02-09T17:28:56.3826183+05:30  [DBG] Waiting for 00:00:02.5000000 before polling. (c8639b24)
2022-02-09T17:28:58.8964320+05:30  [DBG] Done waiting, polling... (93018145)
2022-02-09T17:28:58.8967224+05:30  [DBG] Waiting for 00:00:02.5000000 before polling. (c8639b24)
2022-02-09T17:29:01.4007664+05:30  [DBG] Done waiting, polling... (93018145)
2022-02-09T17:29:01.4010274+05:30  [DBG] Waiting for 00:00:02.5000000 before polling. (c8639b24)
2022-02-09T17:29:01.7019750+05:30  [INF] Error trying to retrieve DNS SRV entries. (addddf06)
DnsClient.DnsResponseException: Query 12389 => _couchbases._tcp.hsotname.eastus.cloudapp.azure.com IN SRV on 192.168.8.1:53 timed out or is a transient error.
 ---> System.OperationCanceledException: The operation was canceled.
   at System.Threading.Tasks.TaskExtensions.WithCancellation[T](Task`1 task, CancellationToken cancellationToken, Action onCancel)
   at DnsClient.LookupClient.ResolveQueryAsync(IReadOnlyList`1 servers, DnsQuerySettings settings, DnsMessageHandler handler, DnsRequestMessage request, LookupClientAudit audit, CancellationToken cancellationToken)
   --- End of inner exception stack trace ---
   at DnsClient.LookupClient.ResolveQueryAsync(IReadOnlyList`1 servers, DnsQuerySettings settings, DnsMessageHandler handler, DnsRequestMessage request, LookupClientAudit audit, CancellationToken cancellationToken)
   at DnsClient.LookupClient.QueryInternalAsync(DnsQuestion question, DnsQuerySettings queryOptions, IReadOnlyCollection`1 servers, CancellationToken cancellationToken)
   at Couchbase.DnsClientDnsResolver.GetDnsSrvEntriesAsync(Uri bootstrapUri, CancellationToken cancellationToken)
   at Couchbase.Core.ClusterContext.BootstrapGlobalAsync()
2022-02-09T17:29:01.7034867+05:30  [DBG] Bootstrapping with node "hsotname.eastus.cloudapp.azure.com" (98ca0e33)
2022-02-09T17:29:03.9124149+05:30  [DBG] Done waiting, polling... (93018145)
2022-02-09T17:29:03.9127285+05:30  [DBG] Waiting for 00:00:02.5000000 before polling. (c8639b24)
2022-02-09T17:29:06.4201295+05:30  [DBG] Done waiting, polling... (93018145)
2022-02-09T17:29:06.4205385+05:30  [DBG] Waiting for 00:00:02.5000000 before polling. (c8639b24)
2022-02-09T17:29:08.9317820+05:30  [DBG] Done waiting, polling... (93018145)
2022-02-09T17:29:08.9320832+05:30  [DBG] Waiting for 00:00:02.5000000 before polling. (c8639b24)
2022-02-09T17:29:11.4459313+05:30  [DBG] Done waiting, polling... (93018145)
2022-02-09T17:29:11.4463142+05:30  [DBG] Waiting for 00:00:02.5000000 before polling. (c8639b24)
2022-02-09T17:29:12.1488979+05:30  [DBG] Attempted bootstrapping on endpoint "hsotname.eastus.cloudapp.azure.com" has failed. (e80489ed)
System.Net.Sockets.SocketException (10060): A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
   at Couchbase.Core.IO.Connections.ConnectionFactory.CreateAndConnectAsync(HostEndpointWithPort hostEndpoint, CancellationToken cancellationToken)
   at Couchbase.Core.IO.Connections.ConnectionPoolBase.CreateConnectionAsync(CancellationToken cancellationToken)
   at Couchbase.Core.IO.Connections.DataFlow.DataFlowConnectionPool.<>c__DisplayClass30_0.<<AddConnectionsAsync>g__StartConnection|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Couchbase.Core.IO.Connections.DataFlow.DataFlowConnectionPool.AddConnectionsAsync(Int32 count, CancellationToken cancellationToken)
   at Couchbase.Core.IO.Connections.DataFlow.DataFlowConnectionPool.InitializeAsync(CancellationToken cancellationToken)
   at Couchbase.Core.ClusterNode.InitializeAsync()
   at Couchbase.Core.DI.ClusterNodeFactory.CreateAndConnectAsync(HostEndpointWithPort endPoint, BucketType bucketType, NodeAdapter nodeAdapter, CancellationToken cancellationToken)
   at Couchbase.Core.ClusterContext.BootstrapGlobalAsync()
2022-02-09T17:29:33.3259787+05:30  [DBG] Done waiting, polling... (93018145)
2022-02-09T17:29:33.3262710+05:30  [DBG] Waiting for 00:00:02.5000000 before polling. (c8639b24)
2022-02-09T17:29:35.8341848+05:30  [DBG] Done waiting, polling... (93018145)
2022-02-09T17:29:35.8343993+05:30  [DBG] Waiting for 00:00:02.5000000 before polling. (c8639b24)
2022-02-09T17:29:36.9552318+05:30  [DBG] Setting TCP Keep-Alives using SocketOptions - enable keep-alives True, time 00:01:00, interval 00:00:01. (d66a37aa)
2022-02-09T17:29:36.9596725+05:30  [DBG] Setting TCP Keep-Alives using SocketOptions - enable keep-alives True, time 00:01:00, interval 00:00:01. (d66a37aa)
2022-02-09T17:29:37.0170984+05:30  [INF] Cannot bootstrap bucket "travel-sample" as Couchbase. (1ecb21a9)
System.IO.IOException: The operation is not allowed on non-connected sockets.
   at System.Net.Sockets.NetworkStream..ctor(Socket socket, FileAccess access, Boolean ownsSocket)
   at Couchbase.Core.IO.Connections.ConnectionFactory.CreateAndConnectAsync(HostEndpointWithPort hostEndpoint, CancellationToken cancellationToken)
   at Couchbase.Core.IO.Connections.ConnectionPoolBase.CreateConnectionAsync(CancellationToken cancellationToken)
   at Couchbase.Core.IO.Connections.DataFlow.DataFlowConnectionPool.<>c__DisplayClass30_0.<<AddConnectionsAsync>g__StartConnection|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Couchbase.Core.IO.Connections.DataFlow.DataFlowConnectionPool.AddConnectionsAsync(Int32 count, CancellationToken cancellationToken)
   at Couchbase.Core.IO.Connections.DataFlow.DataFlowConnectionPool.InitializeAsync(CancellationToken cancellationToken)
   at Couchbase.Core.ClusterNode.InitializeAsync()
   at Couchbase.Core.DI.ClusterNodeFactory.CreateAndConnectAsync(HostEndpointWithPort endPoint, BucketType bucketType, NodeAdapter nodeAdapter, CancellationToken cancellationToken)
   at Couchbase.Core.ClusterContext.CreateAndBootStrapBucketAsync(String name, HostEndpointWithPort endpoint, BucketType type)
   at Couchbase.Core.ClusterContext.GetOrCreateBucketAsync(String name)
2022-02-09T17:29:38.3360012+05:30  [DBG] Done waiting, polling... (93018145)
2022-02-09T17:29:38.3361875+05:30  [DBG] Waiting for 00:00:02.5000000 before polling. (c8639b24)
2022-02-09T17:29:40.3244490+05:30  [DBG] Setting TCP Keep-Alives using SocketOptions - enable keep-alives True, time 00:01:00, interval 00:00:01. (d66a37aa)
2022-02-09T17:29:40.3507801+05:30  [DBG] Setting TCP Keep-Alives using SocketOptions - enable keep-alives True, time 00:01:00, interval 00:00:01. (d66a37aa)
2022-02-09T17:29:40.3525230+05:30  [INF] Cannot bootstrap bucket "travel-sample" as Memcached. (1ecb21a9)
System.IO.IOException: The operation is not allowed on non-connected sockets.
   at System.Net.Sockets.NetworkStream..ctor(Socket socket, FileAccess access, Boolean ownsSocket)
   at Couchbase.Core.IO.Connections.ConnectionFactory.CreateAndConnectAsync(HostEndpointWithPort hostEndpoint, CancellationToken cancellationToken)
   at Couchbase.Core.IO.Connections.ConnectionPoolBase.CreateConnectionAsync(CancellationToken cancellationToken)
   at Couchbase.Core.IO.Connections.DataFlow.DataFlowConnectionPool.<>c__DisplayClass30_0.<<AddConnectionsAsync>g__StartConnection|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Couchbase.Core.IO.Connections.DataFlow.DataFlowConnectionPool.AddConnectionsAsync(Int32 count, CancellationToken cancellationToken)
   at Couchbase.Core.IO.Connections.DataFlow.DataFlowConnectionPool.InitializeAsync(CancellationToken cancellationToken)
   at Couchbase.Core.ClusterNode.InitializeAsync()
   at Couchbase.Core.DI.ClusterNodeFactory.CreateAndConnectAsync(HostEndpointWithPort endPoint, BucketType bucketType, NodeAdapter nodeAdapter, CancellationToken cancellationToken)
   at Couchbase.Core.ClusterContext.CreateAndBootStrapBucketAsync(String name, HostEndpointWithPort endpoint, BucketType type)
   at Couchbase.Core.ClusterContext.GetOrCreateBucketAsync(String name)
2022-02-09T17:29:40.8385667+05:30  [DBG] Done waiting, polling... (93018145)
2022-02-09T17:29:40.8387609+05:30  [DBG] Waiting for 00:00:02.5000000 before polling. (c8639b24)
2022-02-09T17:29:43.3380840+05:30  [DBG] Done waiting, polling... (93018145)
2022-02-09T17:29:43.3382393+05:30  [DBG] Waiting for 00:00:02.5000000 before polling. (c8639b24)
2022-02-09T17:29:43.6633010+05:30  [DBG] Setting TCP Keep-Alives using SocketOptions - enable keep-alives True, time 00:01:00, interval 00:00:01. (d66a37aa)
2022-02-09T17:29:43.6842924+05:30  [DBG] Setting TCP Keep-Alives using SocketOptions - enable keep-alives True, time 00:01:00, interval 00:00:01. (d66a37aa)
2022-02-09T17:29:43.6862758+05:30  [INF] Cannot bootstrap bucket "travel-sample" as Ephemeral. (1ecb21a9)
System.IO.IOException: The operation is not allowed on non-connected sockets.
   at System.Net.Sockets.NetworkStream..ctor(Socket socket, FileAccess access, Boolean ownsSocket)
   at Couchbase.Core.IO.Connections.ConnectionFactory.CreateAndConnectAsync(HostEndpointWithPort hostEndpoint, CancellationToken cancellationToken)
   at Couchbase.Core.IO.Connections.ConnectionPoolBase.CreateConnectionAsync(CancellationToken cancellationToken)
   at Couchbase.Core.IO.Connections.DataFlow.DataFlowConnectionPool.<>c__DisplayClass30_0.<<AddConnectionsAsync>g__StartConnection|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Couchbase.Core.IO.Connections.DataFlow.DataFlowConnectionPool.AddConnectionsAsync(Int32 count, CancellationToken cancellationToken)
   at Couchbase.Core.IO.Connections.DataFlow.DataFlowConnectionPool.InitializeAsync(CancellationToken cancellationToken)
   at Couchbase.Core.ClusterNode.InitializeAsync()
   at Couchbase.Core.DI.ClusterNodeFactory.CreateAndConnectAsync(HostEndpointWithPort endPoint, BucketType bucketType, NodeAdapter nodeAdapter, CancellationToken cancellationToken)
   at Couchbase.Core.ClusterContext.CreateAndBootStrapBucketAsync(String name, HostEndpointWithPort endpoint, BucketType type)
   at Couchbase.Core.ClusterContext.GetOrCreateBucketAsync(String name)
</code>```

Thanks!!

答: Thank you for providing so much detailed information! I suspect the immediate issue is that you are trying to connect using TLS, which is not supported by Couchbase Community Edition (at least not as of February 2022). Ports 11207 and 18091 are for TLS connections; as you observed in the lsof output, the server is not listening on those ports.</p>

Title: Couchbase with Azure Linux VM

Body:
I installed ubuntu server VM on Azure there I installed couchbase community edition on  now i need to access the couchbase using dotnet SDK  but code gives me bucket not found or unreachable error.
even i try configuring a public dns and gave it as ip during cluster creation but still its giving the same.
even i added public dns to the host file like below
127.0.0.1 public dns
The SDK log includes below 2 statements
Attempted bootstrapping on endpoint "name.eastus.cloudapp.azure.com" has failed. (e80489ed)
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.

SDK Doctor Log:

09:51:20.331 INFO ▶ Parsing connection string `couchbases://hsotname.eastus.cloudapp.azure.com/travel-sample`
09:51:20.334 INFO ▶ Connection string was parsed as a potential DNS SRV record
09:51:31.316 INFO ▶ Connection string specifies to use secured connections
09:51:31.316 INFO ▶ Connection string identifies the following CCCP endpoints:
09:51:31.316 INFO ▶   1. hsotname.eastus.cloudapp.azure.com:11207
09:51:31.316 INFO ▶ Connection string identifies the following HTTP endpoints:
09:51:31.316 INFO ▶   1. hsotname.eastus.cloudapp.azure.com:18091
09:51:31.316 INFO ▶ Connection string specifies bucket `travel-sample`
09:51:31.316 WARN ▶ No certificate authority file specified (--tls-ca), skipping server certificate verification for this run.
09:51:42.453 WARN ▶ Your connection string specifies only a single host.  You should consider adding additional static nodes from your cluster to this list to improve your applications fault-tolerance
09:51:42.462 INFO ▶ Performing DNS lookup for host `hsotname.eastus.cloudapp.azure.com`
09:51:42.462 INFO ▶ Bootstrap host `hsotname.eastus.cloudapp.azure.com` refers to a server with the address `13.82.80.55`
09:51:42.462 INFO ▶ Attempting to connect to cluster via CCCP
09:51:42.463 INFO ▶ Attempting to fetch config via cccp from `hsotname.eastus.cloudapp.azure.com:11207`
09:51:44.474 ERRO ▶ Failed to fetch configuration via cccp from `hsotname.eastus.cloudapp.azure.com:11207` (error: dial tcp 13.82.80.55:11207: i/o timeout)
09:51:44.474 INFO ▶ Attempting to connect to cluster via HTTP (Terse)
09:51:44.474 INFO ▶ Attempting to fetch terse config via http from `hsotname.eastus.cloudapp.azure.com:18091`
09:51:46.480 ERRO ▶ Failed to fetch terse configuration via http from `hsotname.eastus.cloudapp.azure.com:18091` (error: Get "http://hsotname.eastus.cloudapp.azure.com:18091/pools/default/b/travel-sample": context deadline exceeded (Client.Timeout exceeded while awaiting headers))
09:51:46.480 INFO ▶ Attempting to connect to cluster via HTTP (Full)
09:51:46.480 INFO ▶ Failed to connect via HTTP (Full), as it is not yet supported by the doctor
09:51:46.481 INFO ▶ Selected the following network type:
09:51:46.481 ERRO ▶ All endpoints specified by your connection string were unreachable, further cluster diagnostics are not possible
09:51:46.481 INFO ▶ Diagnostics completed

Summary:
←[33m[WARN]←[0m No certificate authority file specified (--tls-ca), skipping server certificate verification for this run.
←[33m[WARN]←[0m Your connection string specifies only a single host.  You should consider adding additional static nodes from your cluster to this list to improve your applications fault-tolerance
←[31m[ERRO]←[0m Failed to fetch configuration via cccp from `hsotname.eastus.cloudapp.azure.com:11207` (error: dial tcp 13.82.80.55:11207: i/o timeout)
←[31m[ERRO]←[0m Failed to fetch terse configuration via http from `hsotname.eastus.cloudapp.azure.com:18091` (error: Get "http://hsotname.eastus.cloudapp.azure.com:18091/pools/default/b/travel-sample": context deadline exceeded (Client.Timeout exceeded while awaiting headers))
←[31m[ERRO]←[0m All endpoints specified by your connection string were unreachable, further cluster diagnostics are not possible

Found multiple issues, see listing above.

Both 18091 and 11207 port i added as inbound rule.
my ufw status is inactive
The above mentioned 2 ports are not listening

couchbaseadm@couchbasedbserver:~$ sudo lsof -i -P -n | grep LISTEN

systemd-r   926 systemd-resolve   13u  IPv4   18715      0t0  TCP 127.0.0.53:53 (LISTEN)
sshd       1103            root    3u  IPv4   21086      0t0  TCP *:22 (LISTEN)
sshd       1103            root    4u  IPv6   21088      0t0  TCP *:22 (LISTEN)
beam.smp   6323       couchbase   17u  IPv4 3937812      0t0  TCP 127.0.0.1:21200 (LISTEN)
epmd       6354       couchbase    3u  IPv4 3937267      0t0  TCP *:4369 (LISTEN)
epmd       6354       couchbase    4u  IPv6 3937268      0t0  TCP *:4369 (LISTEN)
beam.smp   6465       couchbase   34u  IPv4 3943391      0t0  TCP *:21100 (LISTEN)
beam.smp   6465       couchbase   48u  IPv4 3938657      0t0  TCP *:8091 (LISTEN)
beam.smp   6514       couchbase   17u  IPv4 3938608      0t0  TCP 127.0.0.1:21300 (LISTEN)
beam.smp   6514       couchbase   27u  IPv4 3938628      0t0  TCP *:8092 (LISTEN)
prometheu  6563       couchbase    9u  IPv4 3938650      0t0  TCP 127.0.0.1:9123 (LISTEN)
goxdcr     6583       couchbase   11u  IPv4 3938705      0t0  TCP 127.0.0.1:9998 (LISTEN)
memcached  6592       couchbase    5u  IPv4 3938689      0t0  TCP 127.0.0.1:11280 (LISTEN)
memcached  6592       couchbase   12u  IPv4 3937931      0t0  TCP *:11210 (LISTEN)
memcached  6592       couchbase   13u  IPv4 3937932      0t0  TCP *:11209 (LISTEN)
memcached  6592       couchbase   14u  IPv6 3937933      0t0  TCP *:11210 (LISTEN)
memcached  6592       couchbase   15u  IPv6 3937934      0t0  TCP *:11209 (LISTEN)
indexer    6741       couchbase   16u  IPv4 3944492      0t0  TCP *:9101 (LISTEN)
indexer    6741       couchbase   19u  IPv4 3944066      0t0  TCP *:9100 (LISTEN)
indexer    6741       couchbase   20u  IPv4 3944500      0t0  TCP *:9102 (LISTEN)
indexer    6741       couchbase   69u  IPv4 3946013      0t0  TCP *:9105 (LISTEN)
projector  6762       couchbase    9u  IPv4 3944075      0t0  TCP *:9999 (LISTEN)
cbq-engin  6782       couchbase    7u  IPv6 3944534      0t0  TCP *:8093 (LISTEN)
cbq-engin  6782       couchbase    8u  IPv4 3944535      0t0  TCP *:8093 (LISTEN)
cbft       6799       couchbase    8u  IPv4 3944112      0t0  TCP *:9130 (LISTEN)
cbft       6799       couchbase    9u  IPv4 3944149      0t0  TCP *:8094 (LISTEN)
sync_gate 11950    sync_gateway    8u  IPv4 4119414      0t0  TCP 127.0.0.1:4985 (LISTEN)
sync_gate 11950    sync_gateway    9u  IPv6 4119422      0t0  TCP *:4984 (LISTEN)

Here is the stacktrace:

StackTrace " at Couchbase.Core.ClusterContext.d__58.MoveNext()\r\n
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n
at System.Threading.Tasks.ValueTask1.get_Result()\r\n at System.Runtime.CompilerServices.ConfiguredValueTaskAwaitable1.ConfiguredValueTaskAwaiter.GetResult()\r\n
at Couchbase.Cluster.<>c__DisplayClass30_0.<b__0>d.MoveNext()\r\n
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n
at System.Threading.Tasks.ValueTask1.get_Result()\r\n at System.Runtime.CompilerServices.ConfiguredValueTaskAwaitable1.ConfiguredValueTaskAwaiter.GetResult()\r\n

Dotnet SDK Log

2022-02-09T17:28:46.3409884+05:30  [DBG] Waiting for 00:00:02.5000000 before polling. (c8639b24)
2022-02-09T17:28:48.8643285+05:30  [DBG] Done waiting, polling... (93018145)
2022-02-09T17:28:48.8649060+05:30  [DBG] Waiting for 00:00:02.5000000 before polling. (c8639b24)
2022-02-09T17:28:51.3664735+05:30  [DBG] Done waiting, polling... (93018145)
2022-02-09T17:28:51.3667541+05:30  [DBG] Waiting for 00:00:02.5000000 before polling. (c8639b24)
2022-02-09T17:28:53.8811651+05:30  [DBG] Done waiting, polling... (93018145)
2022-02-09T17:28:53.8814100+05:30  [DBG] Waiting for 00:00:02.5000000 before polling. (c8639b24)
2022-02-09T17:28:56.3823825+05:30  [DBG] Done waiting, polling... (93018145)
2022-02-09T17:28:56.3826183+05:30  [DBG] Waiting for 00:00:02.5000000 before polling. (c8639b24)
2022-02-09T17:28:58.8964320+05:30  [DBG] Done waiting, polling... (93018145)
2022-02-09T17:28:58.8967224+05:30  [DBG] Waiting for 00:00:02.5000000 before polling. (c8639b24)
2022-02-09T17:29:01.4007664+05:30  [DBG] Done waiting, polling... (93018145)
2022-02-09T17:29:01.4010274+05:30  [DBG] Waiting for 00:00:02.5000000 before polling. (c8639b24)
2022-02-09T17:29:01.7019750+05:30  [INF] Error trying to retrieve DNS SRV entries. (addddf06)
DnsClient.DnsResponseException: Query 12389 => _couchbases._tcp.hsotname.eastus.cloudapp.azure.com IN SRV on 192.168.8.1:53 timed out or is a transient error.
 ---> System.OperationCanceledException: The operation was canceled.
   at System.Threading.Tasks.TaskExtensions.WithCancellation[T](Task`1 task, CancellationToken cancellationToken, Action onCancel)
   at DnsClient.LookupClient.ResolveQueryAsync(IReadOnlyList`1 servers, DnsQuerySettings settings, DnsMessageHandler handler, DnsRequestMessage request, LookupClientAudit audit, CancellationToken cancellationToken)
   --- End of inner exception stack trace ---
   at DnsClient.LookupClient.ResolveQueryAsync(IReadOnlyList`1 servers, DnsQuerySettings settings, DnsMessageHandler handler, DnsRequestMessage request, LookupClientAudit audit, CancellationToken cancellationToken)
   at DnsClient.LookupClient.QueryInternalAsync(DnsQuestion question, DnsQuerySettings queryOptions, IReadOnlyCollection`1 servers, CancellationToken cancellationToken)
   at Couchbase.DnsClientDnsResolver.GetDnsSrvEntriesAsync(Uri bootstrapUri, CancellationToken cancellationToken)
   at Couchbase.Core.ClusterContext.BootstrapGlobalAsync()
2022-02-09T17:29:01.7034867+05:30  [DBG] Bootstrapping with node "hsotname.eastus.cloudapp.azure.com" (98ca0e33)
2022-02-09T17:29:03.9124149+05:30  [DBG] Done waiting, polling... (93018145)
2022-02-09T17:29:03.9127285+05:30  [DBG] Waiting for 00:00:02.5000000 before polling. (c8639b24)
2022-02-09T17:29:06.4201295+05:30  [DBG] Done waiting, polling... (93018145)
2022-02-09T17:29:06.4205385+05:30  [DBG] Waiting for 00:00:02.5000000 before polling. (c8639b24)
2022-02-09T17:29:08.9317820+05:30  [DBG] Done waiting, polling... (93018145)
2022-02-09T17:29:08.9320832+05:30  [DBG] Waiting for 00:00:02.5000000 before polling. (c8639b24)
2022-02-09T17:29:11.4459313+05:30  [DBG] Done waiting, polling... (93018145)
2022-02-09T17:29:11.4463142+05:30  [DBG] Waiting for 00:00:02.5000000 before polling. (c8639b24)
2022-02-09T17:29:12.1488979+05:30  [DBG] Attempted bootstrapping on endpoint "hsotname.eastus.cloudapp.azure.com" has failed. (e80489ed)
System.Net.Sockets.SocketException (10060): A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
   at Couchbase.Core.IO.Connections.ConnectionFactory.CreateAndConnectAsync(HostEndpointWithPort hostEndpoint, CancellationToken cancellationToken)
   at Couchbase.Core.IO.Connections.ConnectionPoolBase.CreateConnectionAsync(CancellationToken cancellationToken)
   at Couchbase.Core.IO.Connections.DataFlow.DataFlowConnectionPool.<>c__DisplayClass30_0.<<AddConnectionsAsync>g__StartConnection|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Couchbase.Core.IO.Connections.DataFlow.DataFlowConnectionPool.AddConnectionsAsync(Int32 count, CancellationToken cancellationToken)
   at Couchbase.Core.IO.Connections.DataFlow.DataFlowConnectionPool.InitializeAsync(CancellationToken cancellationToken)
   at Couchbase.Core.ClusterNode.InitializeAsync()
   at Couchbase.Core.DI.ClusterNodeFactory.CreateAndConnectAsync(HostEndpointWithPort endPoint, BucketType bucketType, NodeAdapter nodeAdapter, CancellationToken cancellationToken)
   at Couchbase.Core.ClusterContext.BootstrapGlobalAsync()
2022-02-09T17:29:33.3259787+05:30  [DBG] Done waiting, polling... (93018145)
2022-02-09T17:29:33.3262710+05:30  [DBG] Waiting for 00:00:02.5000000 before polling. (c8639b24)
2022-02-09T17:29:35.8341848+05:30  [DBG] Done waiting, polling... (93018145)
2022-02-09T17:29:35.8343993+05:30  [DBG] Waiting for 00:00:02.5000000 before polling. (c8639b24)
2022-02-09T17:29:36.9552318+05:30  [DBG] Setting TCP Keep-Alives using SocketOptions - enable keep-alives True, time 00:01:00, interval 00:00:01. (d66a37aa)
2022-02-09T17:29:36.9596725+05:30  [DBG] Setting TCP Keep-Alives using SocketOptions - enable keep-alives True, time 00:01:00, interval 00:00:01. (d66a37aa)
2022-02-09T17:29:37.0170984+05:30  [INF] Cannot bootstrap bucket "travel-sample" as Couchbase. (1ecb21a9)
System.IO.IOException: The operation is not allowed on non-connected sockets.
   at System.Net.Sockets.NetworkStream..ctor(Socket socket, FileAccess access, Boolean ownsSocket)
   at Couchbase.Core.IO.Connections.ConnectionFactory.CreateAndConnectAsync(HostEndpointWithPort hostEndpoint, CancellationToken cancellationToken)
   at Couchbase.Core.IO.Connections.ConnectionPoolBase.CreateConnectionAsync(CancellationToken cancellationToken)
   at Couchbase.Core.IO.Connections.DataFlow.DataFlowConnectionPool.<>c__DisplayClass30_0.<<AddConnectionsAsync>g__StartConnection|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Couchbase.Core.IO.Connections.DataFlow.DataFlowConnectionPool.AddConnectionsAsync(Int32 count, CancellationToken cancellationToken)
   at Couchbase.Core.IO.Connections.DataFlow.DataFlowConnectionPool.InitializeAsync(CancellationToken cancellationToken)
   at Couchbase.Core.ClusterNode.InitializeAsync()
   at Couchbase.Core.DI.ClusterNodeFactory.CreateAndConnectAsync(HostEndpointWithPort endPoint, BucketType bucketType, NodeAdapter nodeAdapter, CancellationToken cancellationToken)
   at Couchbase.Core.ClusterContext.CreateAndBootStrapBucketAsync(String name, HostEndpointWithPort endpoint, BucketType type)
   at Couchbase.Core.ClusterContext.GetOrCreateBucketAsync(String name)
2022-02-09T17:29:38.3360012+05:30  [DBG] Done waiting, polling... (93018145)
2022-02-09T17:29:38.3361875+05:30  [DBG] Waiting for 00:00:02.5000000 before polling. (c8639b24)
2022-02-09T17:29:40.3244490+05:30  [DBG] Setting TCP Keep-Alives using SocketOptions - enable keep-alives True, time 00:01:00, interval 00:00:01. (d66a37aa)
2022-02-09T17:29:40.3507801+05:30  [DBG] Setting TCP Keep-Alives using SocketOptions - enable keep-alives True, time 00:01:00, interval 00:00:01. (d66a37aa)
2022-02-09T17:29:40.3525230+05:30  [INF] Cannot bootstrap bucket "travel-sample" as Memcached. (1ecb21a9)
System.IO.IOException: The operation is not allowed on non-connected sockets.
   at System.Net.Sockets.NetworkStream..ctor(Socket socket, FileAccess access, Boolean ownsSocket)
   at Couchbase.Core.IO.Connections.ConnectionFactory.CreateAndConnectAsync(HostEndpointWithPort hostEndpoint, CancellationToken cancellationToken)
   at Couchbase.Core.IO.Connections.ConnectionPoolBase.CreateConnectionAsync(CancellationToken cancellationToken)
   at Couchbase.Core.IO.Connections.DataFlow.DataFlowConnectionPool.<>c__DisplayClass30_0.<<AddConnectionsAsync>g__StartConnection|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Couchbase.Core.IO.Connections.DataFlow.DataFlowConnectionPool.AddConnectionsAsync(Int32 count, CancellationToken cancellationToken)
   at Couchbase.Core.IO.Connections.DataFlow.DataFlowConnectionPool.InitializeAsync(CancellationToken cancellationToken)
   at Couchbase.Core.ClusterNode.InitializeAsync()
   at Couchbase.Core.DI.ClusterNodeFactory.CreateAndConnectAsync(HostEndpointWithPort endPoint, BucketType bucketType, NodeAdapter nodeAdapter, CancellationToken cancellationToken)
   at Couchbase.Core.ClusterContext.CreateAndBootStrapBucketAsync(String name, HostEndpointWithPort endpoint, BucketType type)
   at Couchbase.Core.ClusterContext.GetOrCreateBucketAsync(String name)
2022-02-09T17:29:40.8385667+05:30  [DBG] Done waiting, polling... (93018145)
2022-02-09T17:29:40.8387609+05:30  [DBG] Waiting for 00:00:02.5000000 before polling. (c8639b24)
2022-02-09T17:29:43.3380840+05:30  [DBG] Done waiting, polling... (93018145)
2022-02-09T17:29:43.3382393+05:30  [DBG] Waiting for 00:00:02.5000000 before polling. (c8639b24)
2022-02-09T17:29:43.6633010+05:30  [DBG] Setting TCP Keep-Alives using SocketOptions - enable keep-alives True, time 00:01:00, interval 00:00:01. (d66a37aa)
2022-02-09T17:29:43.6842924+05:30  [DBG] Setting TCP Keep-Alives using SocketOptions - enable keep-alives True, time 00:01:00, interval 00:00:01. (d66a37aa)
2022-02-09T17:29:43.6862758+05:30  [INF] Cannot bootstrap bucket "travel-sample" as Ephemeral. (1ecb21a9)
System.IO.IOException: The operation is not allowed on non-connected sockets.
   at System.Net.Sockets.NetworkStream..ctor(Socket socket, FileAccess access, Boolean ownsSocket)
   at Couchbase.Core.IO.Connections.ConnectionFactory.CreateAndConnectAsync(HostEndpointWithPort hostEndpoint, CancellationToken cancellationToken)
   at Couchbase.Core.IO.Connections.ConnectionPoolBase.CreateConnectionAsync(CancellationToken cancellationToken)
   at Couchbase.Core.IO.Connections.DataFlow.DataFlowConnectionPool.<>c__DisplayClass30_0.<<AddConnectionsAsync>g__StartConnection|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Couchbase.Core.IO.Connections.DataFlow.DataFlowConnectionPool.AddConnectionsAsync(Int32 count, CancellationToken cancellationToken)
   at Couchbase.Core.IO.Connections.DataFlow.DataFlowConnectionPool.InitializeAsync(CancellationToken cancellationToken)
   at Couchbase.Core.ClusterNode.InitializeAsync()
   at Couchbase.Core.DI.ClusterNodeFactory.CreateAndConnectAsync(HostEndpointWithPort endPoint, BucketType bucketType, NodeAdapter nodeAdapter, CancellationToken cancellationToken)
   at Couchbase.Core.ClusterContext.CreateAndBootStrapBucketAsync(String name, HostEndpointWithPort endpoint, BucketType type)
   at Couchbase.Core.ClusterContext.GetOrCreateBucketAsync(String name)

Thanks!!


问:
How to send messages to specific channels
How to send messages to specific channels:

@bot.command()
async def ticket(ctx):
    guild = ctx.guild
    user = ctx.author
    admin_role = get(guild.roles, name="admin")
    manager_role = get(guild.roles, name="manager")
    overwrites = {
        guild.default_role : nextcord.PermissionOverwrite(read_messages=False),
        user : nextcord.PermissionOverwrite(read_messages=True),
        admin_role : nextcord.PermissionOverwrite(read_messages=True),
        manager_role : nextcord.PermissionOverwrite(read_messages=True)
    }
    channel = await guild.create_text_channel(f'ticket-{user.name}', overwrites=overwrites)
    ch = guild.get_channel(f"{channel.id}")
    embed = nextcord.Embed(title="**repots!**", description=f"<@{user.id}>message", color=0x00ff40)
    mesg = await ch.send(embed=embed)
```
<p>Channel is created, but messages are not shown on the created channel.</p>
<p><strong>Error message:</strong></p>
<pre class="lang-py prettyprint-override"><code>mesg = await ch.message.send(embed=embed)
AttributeError: 'NoneType' object has no attribute 'message'
</code>```

答:
If you want to send a message to a channel, you just have to use the channel object with .send(message content). You don't need .message. You also don't have to use get_channel because you already store the created channel object in the variable channel.

Remove:

ch = guild.get_channel(f"{channel.id}")
```
<p>Change:</p>
<pre class="lang-py prettyprint-override"><code>mesg = await ch.message.send(embed=embed)
</code>```

To:

mesg = await channel.send(embed=embed)
```

Body:
How to send messages to specific channels:

@bot.command()
async def ticket(ctx):
    guild = ctx.guild
    user = ctx.author
    admin_role = get(guild.roles, name="admin")
    manager_role = get(guild.roles, name="manager")
    overwrites = {
        guild.default_role : nextcord.PermissionOverwrite(read_messages=False),
        user : nextcord.PermissionOverwrite(read_messages=True),
        admin_role : nextcord.PermissionOverwrite(read_messages=True),
        manager_role : nextcord.PermissionOverwrite(read_messages=True)
    }
    channel = await guild.create_text_channel(f'ticket-{user.name}', overwrites=overwrites)
    ch = guild.get_channel(f"{channel.id}")
    embed = nextcord.Embed(title="**repots!**", description=f"<@{user.id}>message", color=0x00ff40)
    mesg = await ch.send(embed=embed)

Channel is created, but messages are not shown on the created channel.

Error message:

mesg = await ch.message.send(embed=embed)
AttributeError: 'NoneType' object has no attribute 'message'

Body:
If you want to send a message to a channel, you just have to use the channel object with .send(message content). You don't need .message. You also don't have to use get_channel because you already store the created channel object in the variable channel.

Remove:

ch = guild.get_channel(f"{channel.id}")

Change:

mesg = await ch.message.send(embed=embed)

To:

mesg = await channel.send(embed=embed)


问:
redirect() function not working for external URL in CodeIgniter
I want to redirect to www.yahoo.com from my codeIgniter application. I write code like this :
redirect("http://www.yahoo.com");

It is working fine in my local computer (Windows vista / WAMP) but when I upload to linux server it just show blank screen and not redirect.

答:
Try using the refresh method:

redirect('http://www.yahoo.com', 'refresh');


问:
customise ant design's table search function so numeric search will return less than or greater than, not only equals
As far as I can see ant design's table currently doesn't ship with a specific numeric search, where I can return results within a specific range, example >10 or <=50.

Given the below example:
codesandbox

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import 'antd/dist/antd.css';
import './index.css';
import { Table, Input, Button, Icon } from 'antd';
import Highlighter from 'react-highlight-words';

const data = [
  {
    key: '1',
    name: 'John Brown',
    age: 32,
    address: 'New York No. 1 Lake Park',
  },
  {
    key: '2',
    name: 'Joe Black',
    age: 42,
    address: 'London No. 1 Lake Park',
  },
  {
    key: '3',
    name: 'Jim Green',
    age: 32,
    address: 'Sidney No. 1 Lake Park',
  },
  {
    key: '4',
    name: 'Jim Red',
    age: 32,
    address: 'London No. 2 Lake Park',
  },
];

class App extends React.Component {
  state = {
    searchText: '',
  };

  getColumnSearchProps = dataIndex => ({
    filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
      <div style={{ padding: 8 }}>
        <Input
          ref={node => {
            this.searchInput = node;
          }}
          placeholder={`Search ${dataIndex}`}
          value={selectedKeys[0]}
          onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
          onPressEnter={() => this.handleSearch(selectedKeys, confirm)}
          style={{ width: 188, marginBottom: 8, display: 'block' }}
        />
        <Button
          type="primary"
          onClick={() => this.handleSearch(selectedKeys, confirm)}
          icon="search"
          size="small"
          style={{ width: 90, marginRight: 8 }}
        >
          Search
        </Button>
        <Button onClick={() => this.handleReset(clearFilters)} size="small" style={{ width: 90 }}>
          Reset
        </Button>
      </div>
    ),
    filterIcon: filtered => (
      <Icon type="search" style={{ color: filtered ? '#1890ff' : undefined }} />
    ),
    onFilter: (value, record) =>
      record[dataIndex]
        .toString()
        .toLowerCase()
        .includes(value.toLowerCase()),
    onFilterDropdownVisibleChange: visible => {
      if (visible) {
        setTimeout(() => this.searchInput.select());
      }
    },
    render: text => (
      <Highlighter
        highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }}
        searchWords={[this.state.searchText]}
        autoEscape
        textToHighlight={text.toString()}
      />
    ),
  });

  handleSearch = (selectedKeys, confirm) => {
    confirm();
    console.log(selectedKeys);
    this.setState({ searchText: selectedKeys[0] });
  };

  handleReset = clearFilters => {
    clearFilters();
    this.setState({ searchText: '' });
  };

  render() {
    const columns = [
      {
        title: 'Name',
        dataIndex: 'name',
        key: 'name',
        width: '30%',
        ...this.getColumnSearchProps('name'),
      },
      {
        title: 'Age',
        dataIndex: 'age',
        key: 'age',
        width: '20%',
        ...this.getColumnSearchProps('age'),
      },
      {
        title: 'Address',
        dataIndex: 'address',
        key: 'address',
        ...this.getColumnSearchProps('address'),
      },
    ];
    return <Table columns={columns} dataSource={data} />;
  }
}

ReactDOM.render(<App />, document.getElementById('container'));
</code>```

Let's look at the age column, if we specify an exact age, exact results will be returned. On the input element when the value is keyed in, on either enter press or onClick, handleSearch is triggered, handleSearch then sets the react state, then the component is re-rendered, all basic react functionality.

I am unsure where is the logic that sets what supposed to be returned so unsure where and how should I implement custom logic to check for a specific range of numbers rather than an exact number. Any ideas?

Alternatively, I checked if a numeric search/filter already exists for ant-design, but I couldn't find anything.

For further reference, see ant-designs table documentation

答: i wonder if you still have the example, the link is broke</p>

Body:
As far as I can see ant design's table currently doesn't ship with a specific numeric search, where I can return results within a specific range, example >10 or <=50.

Given the below example:
codesandbox

import React from 'react';
import ReactDOM from 'react-dom';
import 'antd/dist/antd.css';
import './index.css';
import { Table, Input, Button, Icon } from 'antd';
import Highlighter from 'react-highlight-words';

const data = [
  {
    key: '1',
    name: 'John Brown',
    age: 32,
    address: 'New York No. 1 Lake Park',
  },
  {
    key: '2',
    name: 'Joe Black',
    age: 42,
    address: 'London No. 1 Lake Park',
  },
  {
    key: '3',
    name: 'Jim Green',
    age: 32,
    address: 'Sidney No. 1 Lake Park',
  },
  {
    key: '4',
    name: 'Jim Red',
    age: 32,
    address: 'London No. 2 Lake Park',
  },
];

class App extends React.Component {
  state = {
    searchText: '',
  };

  getColumnSearchProps = dataIndex => ({
    filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (

        <Input
          ref={node => {
            this.searchInput = node;
          }}
          placeholder={`Search ${dataIndex}`}
          value={selectedKeys[0]}
          onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
          onPressEnter={() => this.handleSearch(selectedKeys, confirm)}
          style={{ width: 188, marginBottom: 8, display: 'block' }}
        />
        <Button
          type="primary"
          onClick={() => this.handleSearch(selectedKeys, confirm)}
          icon="search"
          size="small"
          style={{ width: 90, marginRight: 8 }}
        >
          Search
        </Button>
        <Button onClick={() => this.handleReset(clearFilters)} size="small" style={{ width: 90 }}>
          Reset
        </Button>

    ),
    filterIcon: filtered => (
      <Icon type="search" style={{ color: filtered ? '#1890ff' : undefined }} />
    ),
    onFilter: (value, record) =>
      record[dataIndex]
        .toString()
        .toLowerCase()
        .includes(value.toLowerCase()),
    onFilterDropdownVisibleChange: visible => {
      if (visible) {
        setTimeout(() => this.searchInput.select());
      }
    },
    render: text => (
      <Highlighter
        highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }}
        searchWords={[this.state.searchText]}
        autoEscape
        textToHighlight={text.toString()}
      />
    ),
  });

  handleSearch = (selectedKeys, confirm) => {
    confirm();
    console.log(selectedKeys);
    this.setState({ searchText: selectedKeys[0] });
  };

  handleReset = clearFilters => {
    clearFilters();
    this.setState({ searchText: '' });
  };

  render() {
    const columns = [
      {
        title: 'Name',
        dataIndex: 'name',
        key: 'name',
        width: '30%',
        ...this.getColumnSearchProps('name'),
      },
      {
        title: 'Age',
        dataIndex: 'age',
        key: 'age',
        width: '20%',
        ...this.getColumnSearchProps('age'),
      },
      {
        title: 'Address',
        dataIndex: 'address',
        key: 'address',
        ...this.getColumnSearchProps('address'),
      },
    ];
    return
;
  }
}

ReactDOM.render(<App />, document.getElementById('container'));

Let's look at the age column, if we specify an exact age, exact results will be returned. On the input element when the value is keyed in, on either enter press or onClick, handleSearch is triggered, handleSearch then sets the react state, then the component is re-rendered, all basic react functionality.

I am unsure where is the logic that sets what supposed to be returned so unsure where and how should I implement custom logic to check for a specific range of numbers rather than an exact number. Any ideas?

Alternatively, I checked if a numeric search/filter already exists for ant-design, but I couldn't find anything.

For further reference, see ant-designs table documentation