问:
Can't connect to twilsoc
I am getting this bizarre twilsoc error when trying to connect to twilio through node and react. I cannot figure out how to fix this. This seems to be happening on the server side of my application. I have generated the token based on the instructions on the website.

```<code>index.js:1437 Error: Can't connect to twilsock
        at Upstream.send (upstream.js:245)
        at TwilsockClient.post (client.js:280)
        at network.js:176
        at Retrier.<anonymous> (network.js:114)
        at Retrier.emit (events.js:136)
        at Retrier.attempt (retrier.js:56)
        at retrier.js:111
</code>```

Here is on the front end

```<code>    componentDidMount() {
    fetch("http://localhost:3001/chat/token", {
      headers: { 'Content-Type': 'application/x-www-form-urlencoded',
     'Access-Control-Allow-Origin': "*",
     'Access-Control-Allow-Headers': "*"
     },
      method: 'POST',
      body: `identity=${encodeURIComponent(this.props.username)}`
    })
      .then(res => res.json())
      .then(data => Chat.create(data.token))
      .then(this.setupChatClient)
      .catch(this.handleError);
  }
</code>```

here is the server

```<code>app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(pino);
app.use(cors());
const sendTokenResponse = (token, res) => {
  res.set('Content-Type', 'application/json');
  res.send(
    JSON.stringify({
      token: token.toJwt()
    })
  );
};

app.get('/api/greeting', (req, res) => {
  const name = req.query.name || 'World';
  res.setHeader('Content-Type', 'application/json');
  res.send(JSON.stringify({ greeting: `Hello ${name}!` }));
});

app.get('/chat/token', (req, res) => {
  const identity = req.query.identity;
  const token = chatToken(identity, config);
  sendTokenResponse(token, res);
});

app.post('/chat/token', (req, res) => {
  console.log('this is firing on the backend')
  const identity = req.query.identity;
  const token = new AccessToken('AC821b3924fcf9577a0eb017c4b21b----', "SK8c95cf6ba0e4a0ec5499d12ae4d----", "o4x7JC9xTEAsZC06SVsnfb2xZU9n----");
  const chatGrant = new ChatGrant({
  serviceSid:"ISdd3f2b55594f45038ac88d84b78e----" ,
});
  token.addGrant(chatGrant);
  token.identity = identity;
  sendTokenResponse(token, res);
});

app.get('/video/token', (req, res) => {
  const identity = req.query.identity;
  const room = req.query.room;
  const token = videoToken(identity, room, config);
  sendTokenResponse(token, res);
});

app.post('/video/token', (req, res) => {
  const identity = req.body.identity;
  const room = req.body.room;
  const token = videoToken(identity, room, config);
  sendTokenResponse(token, res);
});

app.listen(3001, () =>
  console.log('Express server is running on localhost:3001')
);
</code>```

答:
If you're using express, the easiest way to achieve this is using the cors module.

First, install it using the next code:

```<code>npm install cors
</code>```

Next, put the cors middleware in the express app:

```<code>app.use(cors())
</code>```

If you want to learn more, read the cors module docs https://www.npmjs.com/package/cors

Title: Can't connect to twilsoc

Body:
I am getting this bizarre twilsoc error when trying to connect to twilio through node and react. I cannot figure out how to fix this. This seems to be happening on the server side of my application. I have generated the token based on the instructions on the website.

index.js:1437 Error: Can't connect to twilsock
        at Upstream.send (upstream.js:245)
        at TwilsockClient.post (client.js:280)
        at network.js:176
        at Retrier.<anonymous> (network.js:114)
        at Retrier.emit (events.js:136)
        at Retrier.attempt (retrier.js:56)
        at retrier.js:111

Here is on the front end

    componentDidMount() {
    fetch("http://localhost:3001/chat/token", {
      headers: { 'Content-Type': 'application/x-www-form-urlencoded',
     'Access-Control-Allow-Origin': "*",
     'Access-Control-Allow-Headers': "*"
     },
      method: 'POST',
      body: `identity=${encodeURIComponent(this.props.username)}`
    })
      .then(res => res.json())
      .then(data => Chat.create(data.token))
      .then(this.setupChatClient)
      .catch(this.handleError);
  }

here is the server

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(pino);
app.use(cors());
const sendTokenResponse = (token, res) => {
  res.set('Content-Type', 'application/json');
  res.send(
    JSON.stringify({
      token: token.toJwt()
    })
  );
};

app.get('/api/greeting', (req, res) => {
  const name = req.query.name || 'World';
  res.setHeader('Content-Type', 'application/json');
  res.send(JSON.stringify({ greeting: `Hello ${name}!` }));
});

app.get('/chat/token', (req, res) => {
  const identity = req.query.identity;
  const token = chatToken(identity, config);
  sendTokenResponse(token, res);
});

app.post('/chat/token', (req, res) => {
  console.log('this is firing on the backend')
  const identity = req.query.identity;
  const token = new AccessToken('AC821b3924fcf9577a0eb017c4b21b----', "SK8c95cf6ba0e4a0ec5499d12ae4d----", "o4x7JC9xTEAsZC06SVsnfb2xZU9n----");
  const chatGrant = new ChatGrant({
  serviceSid:"ISdd3f2b55594f45038ac88d84b78e----" ,
});
  token.addGrant(chatGrant);
  token.identity = identity;
  sendTokenResponse(token, res);
});

app.get('/video/token', (req, res) => {
  const identity = req.query.identity;
  const room = req.query.room;
  const token = videoToken(identity, room, config);
  sendTokenResponse(token, res);
});

app.post('/video/token', (req, res) => {
  const identity = req.body.identity;
  const room = req.body.room;
  const token = videoToken(identity, room, config);
  sendTokenResponse(token, res);
});

app.listen(3001, () =>
  console.log('Express server is running on localhost:3001')
);

Body:
If you're using express, the easiest way to achieve this is using the cors module.

First, install it using the next code:

npm install cors

Next, put the cors middleware in the express app:

app.use(cors())

If you want to learn more, read the cors module docs https://www.npmjs.com/package/cors


来源: stackexchange

问:
Loop items in a list into ViewBag in Controller
I will like add all the items in the list into the ViewBag. I want something like:

ViewBag.Date = item1, item2, item3.....

My code only return one item (first index) in the list into the ViewBag. I want it separate because I want to use the item to plot a bar-chart in the view. I don't also mind to loop in the Razor View.

Controller

```<code>   public  ActionResult RimChart()
    {

        List<RimCalcs> listOfCategggories = null;

        Connectors aConn = Connectors.GetInstance();
        listOfCategggories = aConn.GetRimCalc();
        //var dates = listOfCategggories.Select(x => x.Date);
       // var profits = listOfCategggories.Select(y => y.Rprofit);
        ViewBag.list  = listOfCategggories;

        foreach (RimCalcs c in listOfCategggories)
        {

            ViewBag.Date = c.Date;
        }

        foreach (RimCalcs d in listOfCategggories)
        {

            ViewBag.profit = d.Rprofit;

        }
        return View();
    }
</code>```

Razor View

```<code>@Html.Raw(@ViewBag.Date);

@using Newtonsoft.Json;

 @{
var profit = JsonConvert.SerializeObject(ViewBag.profit);
var date = JsonConvert.SerializeObject(ViewBag.Date);

}

<!DOCTYPE html>
 <html>
 <head>
 <meta name="viewport" content="width=device-width" />
<title>Charts</title>
<script  src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.2/Chart.bundle.min.js"></script>
<script>

        var barChartData =
            {
                labels: [@Html.Raw(date)], //the names displayed on the x-axis, see images below
            datasets: [{
                label: 'ProductWise Sales Count',
                backgroundColor: [
                    "#f990a7",
                    "#aad2ed",
                    "#9966FF",
                    "#99e5e5",
                    "#f7bd83",
                ],
                borderWidth: 2,
                data: [@profit]  //what you returned back from controller. values displayed on the y-axis, see images below
                }]
            };

                window.onload = function () {
                    var ctx1 = document.getElementById("barcanvas").getContext("2d");
                    window.myBar = new Chart(ctx1,
                        {
                            type: 'bar',
                            data: barChartData,
                            options:
                            {
                                title:
                                {
                                    display: true,
                                    text: "ProductWise Sales Count"
                                },
                                responsive: true,
                                maintainAspectRatio: true
                            }
                        });
                }
</script>
</head>
<body>
 <div style="text-align: center">
    <canvas id="barcanvas"></canvas>
 </div>
  <div style="text-align: center">
     Disclaimer:- This data is for demo it is
    not real data it wont relate to any company
 </div>
 </body>
 </html>
</code>```

答:
why not pass the whole listOfCategggories to the view. then just serialize the model in json. then you can just use the model as a JSON object in your script

controller

```<code>  public ActionResult RimChart()
        {
            return View(aConn.GetRimCalc());
        }
</code>```

view

```<code>  @model List<RimCalcs>
    @{
     var jsonData = @Html.Raw(Json.Serialize(@Model));
    }

<script>
// do your thing
</script>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I will like add all the items in the list into the ViewBag. I want something like:

ViewBag.Date = item1, item2, item3.....

My code only return one item (first index) in the list into the ViewBag. I want it separate because I want to use the item to plot a bar-chart in the view. I don't also mind to loop in the Razor View.

Controller

   public  ActionResult RimChart()
    {

        List<RimCalcs> listOfCategggories = null;

        Connectors aConn = Connectors.GetInstance();
        listOfCategggories = aConn.GetRimCalc();
        //var dates = listOfCategggories.Select(x => x.Date);
       // var profits = listOfCategggories.Select(y => y.Rprofit);
        ViewBag.list  = listOfCategggories;

        foreach (RimCalcs c in listOfCategggories)
        {

            ViewBag.Date = c.Date;
        }

        foreach (RimCalcs d in listOfCategggories)
        {

            ViewBag.profit = d.Rprofit;

        }
        return View();
    }

Razor View

@Html.Raw(@ViewBag.Date);

@using Newtonsoft.Json;

 @{
var profit = JsonConvert.SerializeObject(ViewBag.profit);
var date = JsonConvert.SerializeObject(ViewBag.Date);

}

<!DOCTYPE html>

 <meta name="viewport" content="width=device-width" />
<title>Charts</title>

    <canvas id="barcanvas"></canvas>

     Disclaimer:- This data is for demo it is
    not real data it wont relate to any company

Body:
why not pass the whole listOfCategggories to the view. then just serialize the model in json. then you can just use the model as a JSON object in your script

controller

  public ActionResult RimChart()
        {
            return View(aConn.GetRimCalc());
        }

view

  @model List<RimCalcs>
    @{
     var jsonData = @Html.Raw(Json.Serialize(@Model));
    }

<script>
// do your thing
</script>


问:
How I find the total area of a triangle from the areas of three sections out of six created by concurrent lines one from each vertex?
In this triange:

Given the areas of triangles UPZ ZPW and WPY, how do you calculate the total area?

I've already found the solution from the available submissions at the website. But I want to know how to derive that solution.

```<code>    cin >> a >> b >> c;
    // a is UPZ, b is ZPW, c is WPY

    double n = b*(a+b)*(a+b+c);
    double d = b*(a+b)-(a*c);

    cout << (n / d) ;
</code>```

答:
Indeed, this question is kind of off topic, it is a geometry problem. The way to find the area of the big triangle UVW is to apply the link between areas and ratioes of lengths of the segments of the triangle UYW and then to apply Menelaus' theorem to derive the ratio
WY/WV which reveals the ratio between the areas of the triangle UYW and UVW.

Let h_p be the length of the height from point P to the edge UW. Then

```<code>a = UZ * h_p / 2   and   b = ZW * h_p / 2
</code>```

Thus:

```<code>a / b = (UZ * h_p / 2) / (ZW * h_p / 2) = UZ / ZW
</code>```

Let h_W be the length of the height from point W to the line UY

```<code>a + b = Area(WPU) = PU * h_W / 2   and   c = YP * h_w / 2
</code>```

Thus:

```<code>c / (a + b) = (YP * h_W / 2) / (PU * h_W / 2) = YP / PU
</code>```

By Menelaus' theorem for the triangle UWY and the line VZ, with P on VZ, we get:

```<code>1 = ( VW / VY ) * ( YP / PU ) * ( UZ / ZW ) = ( VW / WY ) * (c / (a + b)) * (a / b)
so
VY / VW = (c * a) / ( b * (a + b))
</code>```

and therefore:

```<code>WY / VW = 1 - (VY / VW) = 1 - (c*a) / ( b*(a + b)) = (a*b + b^2 - a*c ) / (a*b + b^2)
</code>```

Let h_U be the length of the height from the point U to the edge VW. Then

```<code>Area(UVW) =  VW * h_U / 2
and
Area(UYW) = a + b + c = WY * h_U / 2
</code>```

Hence

```<code>Area(UVW) / Area(UYW) = Area(UVW) / (a + b + c) = (VW * h_U / 2) / (WY * h_U / 2) = VW / WY
</code>```

so

```<code>Area(UVW) / Area(UYW) = VW / WY = (a*b + b^2) / (a*b + b^2 - a*c)
Area(UVW) / Area(UYW) = Area(UVW) / (a + b + c) = (a*b + b^2) / (a*b + b^2 - a*c)
</code>```

Finally, we obtain the formula:

```<code>Area(UVW) = (a + b + c) * (a*b + b^2) / (a*b + b^2 - a*c)
Area(UVW) = b * (a + b) * (a + b + c) / (b*(a + b) - a*c)
</code>```

Body:
In this triange:

Given the areas of triangles UPZ ZPW and WPY, how do you calculate the total area?

I've already found the solution from the available submissions at the website. But I want to know how to derive that solution.

    cin >> a >> b >> c;
    // a is UPZ, b is ZPW, c is WPY

    double n = b*(a+b)*(a+b+c);
    double d = b*(a+b)-(a*c);

    cout << (n / d) ;

Body:
Indeed, this question is kind of off topic, it is a geometry problem. The way to find the area of the big triangle UVW is to apply the link between areas and ratioes of lengths of the segments of the triangle UYW and then to apply Menelaus' theorem to derive the ratio
WY/WV which reveals the ratio between the areas of the triangle UYW and UVW.

Let h_p be the length of the height from point P to the edge UW. Then

a = UZ * h_p / 2   and   b = ZW * h_p / 2

Thus:

a / b = (UZ * h_p / 2) / (ZW * h_p / 2) = UZ / ZW

Let h_W be the length of the height from point W to the line UY

a + b = Area(WPU) = PU * h_W / 2   and   c = YP * h_w / 2

Thus:

c / (a + b) = (YP * h_W / 2) / (PU * h_W / 2) = YP / PU

By Menelaus' theorem for the triangle UWY and the line VZ, with P on VZ, we get:

1 = ( VW / VY ) * ( YP / PU ) * ( UZ / ZW ) = ( VW / WY ) * (c / (a + b)) * (a / b)
so
VY / VW = (c * a) / ( b * (a + b))

and therefore:

WY / VW = 1 - (VY / VW) = 1 - (c*a) / ( b*(a + b)) = (a*b + b^2 - a*c ) / (a*b + b^2)

Let h_U be the length of the height from the point U to the edge VW. Then

Area(UVW) =  VW * h_U / 2
and
Area(UYW) = a + b + c = WY * h_U / 2

Hence

Area(UVW) / Area(UYW) = Area(UVW) / (a + b + c) = (VW * h_U / 2) / (WY * h_U / 2) = VW / WY

so

Area(UVW) / Area(UYW) = VW / WY = (a*b + b^2) / (a*b + b^2 - a*c)
Area(UVW) / Area(UYW) = Area(UVW) / (a + b + c) = (a*b + b^2) / (a*b + b^2 - a*c)

Finally, we obtain the formula:

Area(UVW) = (a + b + c) * (a*b + b^2) / (a*b + b^2 - a*c)
Area(UVW) = b * (a + b) * (a + b + c) / (b*(a + b) - a*c)


问:
How to align 2 forms in the same line?
I'm trying to make the login view of a web page, this login view have two forms (one for register and another for login) and I want to align them and put them in the same line.

At first I've tried to use a table in order to achieve this, but this was unsuccessful, so I used some bootstrap form groups (rows and cols) but I was unsuccessful as well, in the end I managed to put them in the same line using the float attribute, but the result that I got it wasn't good enough.

            Inicio
            Nuevas Adiciones

                <button class="dropbtn">Categoría

                </button>

                    Punk
                    Rock
                    Emo

                <button class="dropbtn">Tipo de Material

                </button>

                    Vinilos
                    Discos Compactos
                    Casetes

                    Iniciar Sesión

    <form class="bord" style="float: left;">
        <legend>Crear Cuenta</legend>

            Example label
            <input type="text" class="form-control" id="formGroupExampleInput" placeholder="Example input">

            Another label
            <input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Another input">

    </form>

    <form class="bord" style="float: right;">
        <legend>Registrarse</legend>

            Example label
            <input type="text" class="form-control" id="formGroupExampleInput" placeholder="Example input">

            Another label
            <input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Another input">

    </form>

Contacto

Email: pedidos@vinilos.pe

Teléfono: 3291177

Vinilos.Pe © 2019 Derechos Reservados

```

<pre class="lang-css prettyprint-override"><code>
/* THIS IS MY CSS */

.bord {
    display: block;
    margin-top: 15px;
    padding-top: 0.35em;
    padding-bottom: 0.625em;
    padding-left: 0.75em;
    padding-right: 0.75em;
    border-style: solid;
    border-width: 2.5px;
    text-align: center;
  }
</code>```

I was trying to achieve the look of this mockup, but instead for some reason the footer comes up and it looks like this.

答:
You haven't added your footer's display to none.

Update your CSS to this:

```<code>.bord {
    display: block;
    margin-top: 15px;
    padding-top: 0.35em;
    padding-bottom: 0.625em;
    padding-left: 0.75em;
    padding-right: 0.75em;
    border-style: solid;
    border-width: 2.5px;
    text-align: center;
  }
  footer{;
    display:inline-block;
    width:100%;
  }
</code>```

Here's a fiddle.

Title: How to align 2 forms in the same line?

Body:
I'm trying to make the login view of a web page, this login view have two forms (one for register and another for login) and I want to align them and put them in the same line.

At first I've tried to use a table in order to achieve this, but this was unsuccessful, so I used some bootstrap form groups (rows and cols) but I was unsuccessful as well, in the end I managed to put them in the same line using the float attribute, but the result that I got it wasn't good enough.

            Inicio
            Nuevas Adiciones

                <button class="dropbtn">Categoría

                </button>

                    Punk
                    Rock
                    Emo

                <button class="dropbtn">Tipo de Material

                </button>

                    Vinilos
                    Discos Compactos
                    Casetes

                    Iniciar Sesión

    <form class="bord" style="float: left;">
        <legend>Crear Cuenta</legend>

            Example label
            <input type="text" class="form-control" id="formGroupExampleInput" placeholder="Example input">

            Another label
            <input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Another input">

    </form>

    <form class="bord" style="float: right;">
        <legend>Registrarse</legend>

            Example label
            <input type="text" class="form-control" id="formGroupExampleInput" placeholder="Example input">

            Another label
            <input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Another input">

    </form>

Contacto

Email: pedidos@vinilos.pe

Teléfono: 3291177

Vinilos.Pe © 2019 Derechos Reservados

/* THIS IS MY CSS */

.bord {
    display: block;
    margin-top: 15px;
    padding-top: 0.35em;
    padding-bottom: 0.625em;
    padding-left: 0.75em;
    padding-right: 0.75em;
    border-style: solid;
    border-width: 2.5px;
    text-align: center;
  }

I was trying to achieve the look of this mockup, but instead for some reason the footer comes up and it looks like this.

Body:
You haven't added your footer's display to none.

Update your CSS to this:

.bord {
    display: block;
    margin-top: 15px;
    padding-top: 0.35em;
    padding-bottom: 0.625em;
    padding-left: 0.75em;
    padding-right: 0.75em;
    border-style: solid;
    border-width: 2.5px;
    text-align: center;
  }
  footer{;
    display:inline-block;
    width:100%;
  }

Here's a fiddle.


问:
Example code for jquery dialog
I need to create a jquery modal dialog with an image inside the modal box.
The dialog box should be closed only when user click on the image.

I never use jquery;Can someone provide me an example code?

答: Checkout code examples @ http://docs.jquery.com/UI/Dialog</p>

ContentLicense: CC BY-SA 3.0

Title: Example code for jquery dialog


问:
Vector iterator not dereferencable error during push_back()
The below code works during release mode and raising an error at g_ItemList.push_back() during  debug mode only, I went through few SO posts and forums.  Somebody mentioned "You can't iterate through a vector while pushing back, as push_back may invalidate iterators". But it's not clear for me. Could somebody explain the logic behind it and How to fix this?  I am using Visual Studio 2010 (v100) to compile the program

```<code>std::vector<class PPart> VECT_ITEMS;
VECT_ITEMS g_ItemList;
g_ItemList.clear();

for (i = 0; i < n; i++)
    g_ItemList.push_back (temp[i]);     //where PPart *temp;
</code>```

Error Message

答:
A vector is essentially a wrapper around an array. The given array has a particular size, and the vector's data is stored as the first n elements of this array, where n is the size of the vector and the size of the array is greater than or equal to n. When you call push_back and the vector does not have enough space in its internal array, it creates a new one of a greater size (often double the now-insufficiently-sized array) and copies all of the vectors elements into that array before deleting the old one (these arrays are stored on the heap and created via new and delete).

Iterators are essentially pointers into this internal array¹. As such, when you call push_back, all current iterators may be invalidated. This is because a new array may have been created, and pointers into the old array refer to now-freed memory. Technically, when you call push_back and then dereference an iterator that was created before that call, it is undefined behavior.

1: Technically, they are class wrappers of pointers to the internal array, but the principle stands either way. It is often, but not always, useful to think of them as just pointers.

Body:
The below code works during release mode and raising an error at g_ItemList.push_back() during  debug mode only, I went through few SO posts and forums.  Somebody mentioned "You can't iterate through a vector while pushing back, as push_back may invalidate iterators". But it's not clear for me. Could somebody explain the logic behind it and How to fix this?  I am using Visual Studio 2010 (v100) to compile the program

std::vector<class PPart> VECT_ITEMS;
VECT_ITEMS g_ItemList;
g_ItemList.clear();

for (i = 0; i < n; i++)
    g_ItemList.push_back (temp[i]);     //where PPart *temp;

Error Message


问:
Automated Number in Custom-List SharePoint Online
Is there a way to automate a number in sharepoint online, custom list? the format is should be like this NUM-(year)-000

For example

```<code>NUM-2019-001
NUM-2019-002
...
</code>```

so that there's no need for the user to fill this column for the Number of the item.

答:
There is a Document ID feature in SharePoint, however it really only allows you to define a prefix.  Potentially you could use it and update it each year, but I think you'd be better off creating a workflow or us MS Flow.

I'd look to do the following:

Create a Site Field under Site Settings - make it a single line text field and enforce unique values but don't make it required

Add the field to the list

Create a workflow for that list and set it to run on Created / New Items

The workflow would update the new field you've added and set the value.

Workflow isn't the easiest thing to use if you haven't used it before.
I'd look to configure the workflow to build a few variables.  Firstly the year of the current date.  Then use the ID of the list item for the last part of your value.  eg; it would be formed like "NUM-YYYY-ID".
There are commands to read data, get the current date and update the list item from within the workflow designer using SharePoint Designer.

Alternatively you could do a similar thing with MS Flow.

Another option would be a remote event receiver but that's more difficult again and probably overkill for this requirement.

Body:
Is there a way to automate a number in sharepoint online, custom list? the format is should be like this NUM-(year)-000

For example

NUM-2019-001
NUM-2019-002
...

so that there's no need for the user to fill this column for the Number of the item.


问:
Do Self Hosted Agents require dedicated machines?
I am migrating XAML Builds to Azure Devops. Goal is to remove the dedicated Build Staging server to cut costs.

Following is the process:
1) Build ASP.NET Web Application.
2) Copy configs, assemblies, WebPackage from Build output to various folders in UNC share which will be later picked up by a Release Pipeline Job.

Since Microsoft Hosted Agents dont allow usage of UNC share, I wanted to use Self Hosted Agent.

Question:
Can I use a Self Hosted Agent without the necessity of a dedicated server to hold the Build Output in Image or Container which can then be copied to the UNC Share? I am new to Devops and hence the articles on MS confused me if I need a dedicated server or not.

Tried to set up a Self Hosted Agent pool, but the steps suggest that I require a machine where the Self Hosted Agent need to be setup. If this is the case then it means I will be requiring a dedicated machine like in XAML process. Am I blabbering? Please excuse if yes :-)

Expected Result: Run a Build Pipeline with Self Hosted Agents on Cloud without the requirement of a Dedicated Server.

答:
UNC Shares or not, the "self hosted agent" is an agent you install on your own server, there can be multiple reasons for that, for example accessing an sql server for testing that is on your own local network, to perform tests against during builds.

If you are trying to reduce costs, a self-hosted agent can be benefitial if you already have server hardware it can run on. If not, you might aswell just use a hosted build agent, anything build on that can be published directly azure devops or other places though various build tasks.


问:
Dynamic Tables with Struts 2
What would be the best way to create a dynamic HTML table using the JQuery plugin? What I want to do is be able to pull data from my action class and be able  to perform CRUD operations on that data which is presented in a table. I also want to be able to dynamically add rows to the table as well and have it saved server side.

I found this example but it uses Dojo and I'm trying to stay away from using the Dojo Struts plugin since it is so old.

The Struts2 JQuery Grid plugin looks like a possible solution.

Would this be a good use case to use a plugin like Freemarker?

答: I used jquery Gridnic. It is very easy to start with</p>

ContentLicense: CC BY-SA 2.5

Title: Dynamic Tables with Struts 2


问:
Hiding select list option values while using jQuery Chosen
I have created a simple app containing <select> lists which hide() or show() option values based on previous selections.

There are two lists, one with vehicle Makes and the other with vehicle Models. When a certain Make is selected, i.e. BMW, the next Make <select> appears only showing BMW models. And vice versa with Audi and so on.

Within the Models list, I have attached an ID to every <option> value and show or hide those <option> values based on previous selections. For example if BMW is selected, it will hide the two Audi model <option>'s, Q1 and Q3. If Audi is selected, it will hide the two BMW model <option>'s, X1 and X2.

I was successful in achieving this basic functionality; however, when I integrated jQuery's Chosen, it no longer worked. I really like Chosen and once I build out this app it will be very useful, so I would love to achieve the same functionality with it integrated.

Here is the simple code file:

<!DOCTYPE html>

 <link type="text/css" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.css">

   <select data-placeholder="Select Brand" class="chosen-select" id="s1">
    <option disabled selected></option>
    <option value="BMW">BMW</option>
    <option value="AUDI">AUDI</option>
    <option value="nothing" id="nothing">Nothing</option>
   </select>

   <select data-placeholder="Select Model" class="chosen-select" id="s2">
    <option disabled selected></option>
    <option value="nothing" id="nothing">Nothing</option>
    <option value="X1" id="X1">X1</option>
    <option value="X2" id="X2">X2</option>
    <option value="Q1" id="Q1">Q1</option>
    <option value="Q3" id="Q3">Q3</option>
   </select>

```

Any help would be greatly appreciated! Thanks so much.

答:
$(".chosen-select").trigger('chosen:updated'); You need to notify Chosen that your options have updated. This code updated Chosen to take care of updated options.

One thing to note however that it dont work to remove pre-select, you need to find solution within Chosen on how to remove pre-selection.

$(document).ready(function() {

  var $models = $('#s2');
  var $drivetrain = $('#s3');

  var $bmwmodels = $('#X1, #X2');
  var $audimodels = $('#Q1, #Q3');

  console.log( $bmwmodels, $audimodels);
  $('#s1').change(function() {
    var selectedValue = $(this).val();

    if (selectedValue == 'BMW') {
      $audimodels.hide();
      $drivetrain.parent().hide();
      $models.parent().show();
      $bmwmodels.show();
    } else if (selectedValue == 'AUDI') {
      $bmwmodels.hide();
      $drivetrain.parent().hide();
      $models.parent().show();
      $audimodels.show();
    } else {
      $bmwmodels.hide();
      $audimodels.hide();
      $models.parent().hide();
      $drivetrain.parent().hide();
    }

     $(".chosen-select").trigger('chosen:updated');
  });

  //Hide onload
  function hide() {
    $models.parent().hide();
    $drivetrain.parent().hide();
    $bmwmodels.hide();
    $audimodels.hide();
  }

  // call hide AFTER .chosen() has been invoked on the visible elements
  $(".chosen-select").chosen({
    disable_search_threshold: 4
  });

  hide();

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.chosen-select {
  width: 200px
}

.hidden {
  display: none;
}</code>```

<!DOCTYPE html>

  <title>Test</title>

  <link type="text/css" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.css">

        <select data-placeholder="Select Brand" class="chosen-select" id="s1">
          <option disabled selected></option>
          <option value="BMW">BMW</option>
          <option value="AUDI">AUDI</option>
          <option value="nothing" id="nothing">Nothing</option>
        </select>

        <select data-placeholder="Select Model" class="chosen-select" id="s2">
          <option disabled selected></option>
          <option value="nothing" id="nothing">Nothing</option>
          <option value="X1" id="X1">X1</option>
          <option value="X2" id="X2">X2</option>
          <option value="Q1" id="Q1">Q1</option>
          <option value="Q3" id="Q3">Q3</option>
        </select>

```

Body:
I have created a simple app containing <select> lists which hide() or show() option values based on previous selections.

There are two lists, one with vehicle Makes and the other with vehicle Models. When a certain Make is selected, i.e. BMW, the next Make <select> appears only showing BMW models. And vice versa with Audi and so on.

Within the Models list, I have attached an ID to every <option> value and show or hide those <option> values based on previous selections. For example if BMW is selected, it will hide the two Audi model <option>'s, Q1 and Q3. If Audi is selected, it will hide the two BMW model <option>'s, X1 and X2.

I was successful in achieving this basic functionality; however, when I integrated jQuery's Chosen, it no longer worked. I really like Chosen and once I build out this app it will be very useful, so I would love to achieve the same functionality with it integrated.

Here is the simple code file:

<!DOCTYPE html>

 <link type="text/css" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.css">

   <select data-placeholder="Select Brand" class="chosen-select" id="s1">
    <option disabled selected></option>
    <option value="BMW">BMW</option>
    <option value="AUDI">AUDI</option>
    <option value="nothing" id="nothing">Nothing</option>
   </select>

   <select data-placeholder="Select Model" class="chosen-select" id="s2">
    <option disabled selected></option>
    <option value="nothing" id="nothing">Nothing</option>
    <option value="X1" id="X1">X1</option>
    <option value="X2" id="X2">X2</option>
    <option value="Q1" id="Q1">Q1</option>
    <option value="Q3" id="Q3">Q3</option>
   </select>

Any help would be greatly appreciated! Thanks so much.

Body:
$(".chosen-select").trigger('chosen:updated'); You need to notify Chosen that your options have updated. This code updated Chosen to take care of updated options.

One thing to note however that it dont work to remove pre-select, you need to find solution within Chosen on how to remove pre-selection.

$(document).ready(function() {

  var $models = $('#s2');
  var $drivetrain = $('#s3');

  var $bmwmodels = $('#X1, #X2');
  var $audimodels = $('#Q1, #Q3');

  console.log( $bmwmodels, $audimodels);
  $('#s1').change(function() {
    var selectedValue = $(this).val();

    if (selectedValue == 'BMW') {
      $audimodels.hide();
      $drivetrain.parent().hide();
      $models.parent().show();
      $bmwmodels.show();
    } else if (selectedValue == 'AUDI') {
      $bmwmodels.hide();
      $drivetrain.parent().hide();
      $models.parent().show();
      $audimodels.show();
    } else {
      $bmwmodels.hide();
      $audimodels.hide();
      $models.parent().hide();
      $drivetrain.parent().hide();
    }

     $(".chosen-select").trigger('chosen:updated');
  });

  //Hide onload
  function hide() {
    $models.parent().hide();
    $drivetrain.parent().hide();
    $bmwmodels.hide();
    $audimodels.hide();
  }

  // call hide AFTER .chosen() has been invoked on the visible elements
  $(".chosen-select").chosen({
    disable_search_threshold: 4
  });

  hide();

});

.chosen-select {
  width: 200px
}

.hidden {
  display: none;
}

<!DOCTYPE html>
<html>

<head>
  <title>Test</title>

  <link type="text/css" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.css">
  <script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.jquery.min.js"></script>
</head>

<body>

  <table>
    <tr>
      <td>
        <select data-placeholder="Select Brand" class="chosen-select" id="s1">
          <option disabled selected></option>
          <option value="BMW">BMW</option>
          <option value="AUDI">AUDI</option>
          <option value="nothing" id="nothing">Nothing</option>
        </select>
      </td>
    </tr>

    <tr>
      <td>
        <select data-placeholder="Select Model" class="chosen-select" id="s2">
          <option disabled selected></option>
          <option value="nothing" id="nothing">Nothing</option>
          <option value="X1" id="X1">X1</option>
          <option value="X2" id="X2">X2</option>
          <option value="Q1" id="Q1">Q1</option>
          <option value="Q3" id="Q3">Q3</option>
        </select>
      </td>
    </tr>

  </table>

</body>

</html>


问:
How do I render multiple partials based off of JSON data?
I have a database with user data, If I wanted to render a partial for each document in my MongoDB collection how would I do that?

I can render one partial by just adding it to my view but how do I make it render multiple ones automatically without me retyping this {{>somePartial}} for each new document added?

I looked around and found something suggesting AJAX they were not completely similar to my problem. If this is the solution is there another way other then AJAX?

every time a new document is added to MongoDB I'd like a new partial added to my view (I don't mind if it only shows when the page is refreshed)

```<code>{{>somePartial}} // Different data
{{>somePartial}} // Different data
{{>somePartial}} // Different data
</code>```

答:
You can make an array of all the data from your monogdb then you can render your page and pass your data to the ejs template and add dynamic includes and pass different data e.g.

```<code><% for (let i = 1; i <= <length>; i++) { %>
    <%- include("<partial>",{data:"your_data_for_this_index"}) %>
<% } %>
</code>```

Body:
I have a database with user data, If I wanted to render a partial for each document in my MongoDB collection how would I do that?

I can render one partial by just adding it to my view but how do I make it render multiple ones automatically without me retyping this {{>somePartial}} for each new document added?

I looked around and found something suggesting AJAX they were not completely similar to my problem. If this is the solution is there another way other then AJAX?

every time a new document is added to MongoDB I'd like a new partial added to my view (I don't mind if it only shows when the page is refreshed)

{{>somePartial}} // Different data
{{>somePartial}} // Different data
{{>somePartial}} // Different data

Body:
You can make an array of all the data from your monogdb then you can render your page and pass your data to the ejs template and add dynamic includes and pass different data e.g.

<% for (let i = 1; i <= <length>; i++) { %>
    <%- include("<partial>",{data:"your_data_for_this_index"}) %>
<% } %>


问:
What preprocessor macros can't be defined?
I noticed that trying to define defined as a macro in C/C++ gives an error:

```<code>error: "defined" cannot be used as a macro name
</code>```

This doesn't seem strange to me, since allowing the redefinition of defined would probably break #if defined(...)-like directives. However, It made me wonder what other keywords would give a compilation error1. I found that the C++ named operators also can't be used in a define, but I couldn't find a list of all impossible macros. Are there any other macros that cannot be defined?

1 while (re)defining keywords such as if, or int are about the worst thing one could do with the preprocessor, doing so does not cause a compilation error. I'm looking for keywords that won't compile at all.

答: Per gnu.org, "you may define any valid identifier as a macro, even if it is a C keyword. The preprocessor does not know anything about keywords. This can be useful if you wish to hide a keyword such as 'const' from an older compiler that does not understand it. However, the preprocessor operator 'defined' can never be defined as a macro."</p>

Body:
I noticed that trying to define defined as a macro in C/C++ gives an error:

error: "defined" cannot be used as a macro name

This doesn't seem strange to me, since allowing the redefinition of defined would probably break #if defined(...)-like directives. However, It made me wonder what other keywords would give a compilation error1. I found that the C++ named operators also can't be used in a define, but I couldn't find a list of all impossible macros. Are there any other macros that cannot be defined?

1 while (re)defining keywords such as if, or int are about the worst thing one could do with the preprocessor, doing so does not cause a compilation error. I'm looking for keywords that won't compile at all.


答:
Since you are using bootstrap you can use the power of flex. which will remove the problem of floating and is highly flexible and customizable.`

  <form class="loginform d-block">

  </form>

  <form class="signupform d-block"></form>

```

`

Title: How to align 2 forms in the same line?

Body:
Since you are using bootstrap you can use the power of flex. which will remove the problem of floating and is highly flexible and customizable.`

<div class="flex">
  <form class="loginform d-block">

  </form>

  <form class="signupform d-block"></form>
</div>

`


问:
Increase object quantity instead of creating a new object in array
First time working with a shopping cart component, I have my code structured like this..

```<code>let cartCount = document.getElementById("counter");
let isItemSelected = false;
let itemCount = 0;
let shoppingCart = [];
let selectedSize = "";
let displaySelectedSize = document.getElementById("selected");
let displayCart = document.getElementById("cart");

selectItem = () => {
  isItemSelected = true;
  selectedSize = event.srcElement.id;
  displaySelectedSize.innerHTML = `${selectedSize}`;
}

addItem = () => {
  if (isItemSelected === true) {

    const shopItem = {
      name: "Classic Tee",
      price: 75,
      size: `${selectedSize}`,
      quantity: 0
    }

    itemCount+= 1;
    cartCount.innerHTML = `( ${itemCount} )`;
    shopItem.quantity++
    shoppingCart.push(shopItem);
    console.log(shoppingCart);

    return itemSuccess();
  } else {
      return itemError();
  }
}
</code>```

What I basically need is for the shopItem.quantity to increase if I have multiple of the selected size.

At the moment I get this..

```<code>// Output
0: {name: "Classic Tee", price: 75, size: "small", quantity: 1}
1: {name: "Classic Tee", price: 75, size: "small", quantity: 1}

// Desired Output
0: {name: "Classic Tee", price: 75, size: "small", quantity: 2}
</code>```

I can see why my output is like that, it's creating a new object each time my addItem function is fired, but I would like to mutate my shopItem.quantity if there are duplicates...

How would I do that?

答:
I think you should filter your shoppingCart array and depending on it if you should add a new item to the array or increment the quantity of an existing item.

Here's a sample based on what you started. I removed some code so I can focus on the gist of what I mean

```<code>let shoppingCart = [];

addItem = (newItem) => {

    function itemFilter(item) {
        return item.name === newItem.name && item.price === newItem.price && item.size === newItem.size
    }
    let existingItems = shoppingCart.filter(itemFilter)

    if (existingItems.length > 0) {
        existingItems[0].quantity += newItem.quantity
    } else {
        shoppingCart.push(newItem)
    }

}

const shopItem = {
    name: "Classic Tee",
    price: 75,
    size: "small",
    quantity: 1
}

const shopItem2 = {
    name: "Classic Tee",
    price: 75,
    size: "big",
    quantity: 1
}

const shopItem3 = {
    name: "Classic Tee",
    price: 75,
    size: "small",
    quantity: 2
}

console.log('-----------')
console.log(shoppingCart)
addItem(shopItem)
console.log('-----------')
console.log(shoppingCart)
addItem(shopItem)
console.log('-----------')
console.log(shoppingCart)
addItem(shopItem2)
console.log('-----------')
console.log(shoppingCart)
addItem(shopItem)
console.log('-----------')
console.log(shoppingCart)
</code>```

output is:

```<code>-----------
[]
-----------
[ { name: 'Classic Tee', price: 75, size: 'small', quantity: 1 } ]
-----------
[ { name: 'Classic Tee', price: 75, size: 'small', quantity: 2 } ]
-----------
[ { name: 'Classic Tee', price: 75, size: 'small', quantity: 2 },
  { name: 'Classic Tee', price: 75, size: 'big', quantity: 1 } ]
-----------
[ { name: 'Classic Tee', price: 75, size: 'small', quantity: 4 },
  { name: 'Classic Tee', price: 75, size: 'big', quantity: 1 } ]
</code>```

Body:
First time working with a shopping cart component, I have my code structured like this..

let cartCount = document.getElementById("counter");
let isItemSelected = false;
let itemCount = 0;
let shoppingCart = [];
let selectedSize = "";
let displaySelectedSize = document.getElementById("selected");
let displayCart = document.getElementById("cart");

selectItem = () => {
  isItemSelected = true;
  selectedSize = event.srcElement.id;
  displaySelectedSize.innerHTML = `${selectedSize}`;
}

addItem = () => {
  if (isItemSelected === true) {

    const shopItem = {
      name: "Classic Tee",
      price: 75,
      size: `${selectedSize}`,
      quantity: 0
    }

    itemCount+= 1;
    cartCount.innerHTML = `( ${itemCount} )`;
    shopItem.quantity++
    shoppingCart.push(shopItem);
    console.log(shoppingCart);

    return itemSuccess();
  } else {
      return itemError();
  }
}

What I basically need is for the shopItem.quantity to increase if I have multiple of the selected size.

At the moment I get this..

// Output
0: {name: "Classic Tee", price: 75, size: "small", quantity: 1}
1: {name: "Classic Tee", price: 75, size: "small", quantity: 1}

// Desired Output
0: {name: "Classic Tee", price: 75, size: "small", quantity: 2}

I can see why my output is like that, it's creating a new object each time my addItem function is fired, but I would like to mutate my shopItem.quantity if there are duplicates...

How would I do that?

Body:
I think you should filter your shoppingCart array and depending on it if you should add a new item to the array or increment the quantity of an existing item.

Here's a sample based on what you started. I removed some code so I can focus on the gist of what I mean

let shoppingCart = [];

addItem = (newItem) => {

    function itemFilter(item) {
        return item.name === newItem.name && item.price === newItem.price && item.size === newItem.size
    }
    let existingItems = shoppingCart.filter(itemFilter)

    if (existingItems.length > 0) {
        existingItems[0].quantity += newItem.quantity
    } else {
        shoppingCart.push(newItem)
    }

}

const shopItem = {
    name: "Classic Tee",
    price: 75,
    size: "small",
    quantity: 1
}

const shopItem2 = {
    name: "Classic Tee",
    price: 75,
    size: "big",
    quantity: 1
}

const shopItem3 = {
    name: "Classic Tee",
    price: 75,
    size: "small",
    quantity: 2
}

console.log('-----------')
console.log(shoppingCart)
addItem(shopItem)
console.log('-----------')
console.log(shoppingCart)
addItem(shopItem)
console.log('-----------')
console.log(shoppingCart)
addItem(shopItem2)
console.log('-----------')
console.log(shoppingCart)
addItem(shopItem)
console.log('-----------')
console.log(shoppingCart)

output is:

-----------
[]
-----------
[ { name: 'Classic Tee', price: 75, size: 'small', quantity: 1 } ]
-----------
[ { name: 'Classic Tee', price: 75, size: 'small', quantity: 2 } ]
-----------
[ { name: 'Classic Tee', price: 75, size: 'small', quantity: 2 },
  { name: 'Classic Tee', price: 75, size: 'big', quantity: 1 } ]
-----------
[ { name: 'Classic Tee', price: 75, size: 'small', quantity: 4 },
  { name: 'Classic Tee', price: 75, size: 'big', quantity: 1 } ]


问:
Parsing HTML to get JSON swift
I'm new with Swift and am trying to get the JSON data from HTML I grabbed. I get the HTML from a website and there's one line in the whole result that has the data. Setup like: var obj = *JSON data*

How can I parse through the string results to only get that line and convert the data (right side of the equal sign) to JSON?

Here's my code to get the data (testURL is the url of the website):

```<code>if let url = testURL {
    do {
          let contents = try String(contentsOf: url)
          print(contents)
       } catch {
          // contents could not be loaded
       }
    } else {
       // the URL was bad!
 }
</code>```

答:
You can use this pod SwiftSoup to parse HTML

This block of code iterate over tags like script and get its attributes like src

```<code>if let url = testURL {
    do {
        let contents = try String(contentsOf: url)
        print(contents)
        do {
            let doc: Document = try SwiftSoup.parse(contents)
            for item in try doc.select("script") {
                let json = try item.attr("src")
                print(json)
            }
        } catch Exception.Error(let type, let message) {
            print(message)
        } catch {
            print("error")
        }
    } catch {
        // contents could not be loaded
    }
} else {
    // the URL was bad!
}
</code>```

Replace script with json tag and src with attribute containing json

Don't forget to add import SwiftSoup

Hope you get the desired result.

Title: Parsing HTML to get JSON swift

Body:
I'm new with Swift and am trying to get the JSON data from HTML I grabbed. I get the HTML from a website and there's one line in the whole result that has the data. Setup like: var obj = *JSON data*

How can I parse through the string results to only get that line and convert the data (right side of the equal sign) to JSON?

Here's my code to get the data (testURL is the url of the website):

if let url = testURL {
    do {
          let contents = try String(contentsOf: url)
          print(contents)
       } catch {
          // contents could not be loaded
       }
    } else {
       // the URL was bad!
 }

Body:
You can use this pod SwiftSoup to parse HTML

This block of code iterate over tags like script and get its attributes like src

if let url = testURL {
    do {
        let contents = try String(contentsOf: url)
        print(contents)
        do {
            let doc: Document = try SwiftSoup.parse(contents)
            for item in try doc.select("script") {
                let json = try item.attr("src")
                print(json)
            }
        } catch Exception.Error(let type, let message) {
            print(message)
        } catch {
            print("error")
        }
    } catch {
        // contents could not be loaded
    }
} else {
    // the URL was bad!
}

Replace script with json tag and src with attribute containing json

Don't forget to add import SwiftSoup

Hope you get the desired result.


问:
How to free a tree structure in C with a double pointer
I'm doing a code about the construction of a tree structure in C, which is not binary. The structure contains a horizontal, a vertical link and a char value. Now i'm trying to free every structure allocated to construct this tree but valgrind gives me an error. I am using a double pointer to point the head of the tree. In the function pile means stack so I stack every node vertically and then I search for the horizontal ones. I'm putting as a picture an example of a tree and its structure and the valgrind result. Can you please help me to understand what is wrong because I don't get it ? Thank you !

```<code>void libererArbre(cellule ** tete)
{
    cellule * cour = * tete;
    cellule ** temp = &cour;
    pile_t * pile;
    pile = initialisationPile(TAILLE_PILE);
    int fin = 0;
    while(fin == 0)
    {
        while(cour != NULL)
        {
            empiler(cour, pile);
            //printf("empilimi %c\n", cour->valeur);
            cour = cour->lienVertical;
        }
        if(!estVidePile(pile))
        {
            cour = depiler(pile);
            //printf("depilimi %c\n", cour->valeur);
            temp = &cour;
            free(temp);
            cour = cour->lienHorizontal;
        }
        else
        {
            fin = 1;
            printf("a futet ne fin 1 apo jo \n");
        }
    }
    libererPile(pile);
}
</code>```

Here's a picture of the result of valgrind:

Here's a picture of the explination of the structure:

答:
The problem is with these two lines:

```<code>        temp = &cour;
        free(temp);
</code>```

Since cour is a local variable, temp will point to that stack address.  When you call free(temp), you're trying to free a memory address that was not allocated with malloc.

You likely need to do something like

```<code>        temp2 = cour;
        cour = cour->lienHorizontal;
        free(temp);
</code>```

(where temp2 is declared as cellule *temp2) but it is impossible to know without seeing your allocation code.

Body:
I'm doing a code about the construction of a tree structure in C, which is not binary. The structure contains a horizontal, a vertical link and a char value. Now i'm trying to free every structure allocated to construct this tree but valgrind gives me an error. I am using a double pointer to point the head of the tree. In the function pile means stack so I stack every node vertically and then I search for the horizontal ones. I'm putting as a picture an example of a tree and its structure and the valgrind result. Can you please help me to understand what is wrong because I don't get it ? Thank you !

void libererArbre(cellule ** tete)
{
    cellule * cour = * tete;
    cellule ** temp = &cour;
    pile_t * pile;
    pile = initialisationPile(TAILLE_PILE);
    int fin = 0;
    while(fin == 0)
    {
        while(cour != NULL)
        {
            empiler(cour, pile);
            //printf("empilimi %c\n", cour->valeur);
            cour = cour->lienVertical;
        }
        if(!estVidePile(pile))
        {
            cour = depiler(pile);
            //printf("depilimi %c\n", cour->valeur);
            temp = &cour;
            free(temp);
            cour = cour->lienHorizontal;
        }
        else
        {
            fin = 1;
            printf("a futet ne fin 1 apo jo \n");
        }
    }
    libererPile(pile);
}

Here's a picture of the result of valgrind:

Here's a picture of the explination of the structure:

Body:
The problem is with these two lines:

        temp = &cour;
        free(temp);

Since cour is a local variable, temp will point to that stack address.  When you call free(temp), you're trying to free a memory address that was not allocated with malloc.

You likely need to do something like

        temp2 = cour;
        cour = cour->lienHorizontal;
        free(temp);

(where temp2 is declared as cellule *temp2) but it is impossible to know without seeing your allocation code.


问:
Using System.Speech with Kinect
I am developing a prototype speech to text captioning application for a University project. I am going to be using gesture recognition within my project late on, so I thought it would be a good idea to use the Kinect as the microphone source, rather than using an additional microphone. The idea of my application is to recognize spontaneous speeches such as long and complex sentences (I understand it won’t that the speech dictation will not be perfect however). I have seen many Kinect speech samples where it makes a reference to Microsoft.Speech, but not System.Speech. As I need to train the speech engine and load a DictationGrammar into the Speech Recognition Engine, Microsoft.Speech is the only option for me.

I have managed to get it working while using the Kinect as the direct microphone audio source, but since I am loading the Kinect for the video preview and gesture recognition, I am unable to access it as a direct microphone.

This is code accessing the microphone directly without loading the Kinect hardware for gesture, etc, and works perfectly:

```<code>private void InitializeSpeech()
{
    var speechRecognitionEngine = new SpeechRecognitionEngine();
    speechRecognitionEngine.SetInputToDefaultAudioDevice();
    speechRecognitionEngine.LoadGrammar(new DictationGrammar());
    speechRecognitionEngine.RecognizeAsync(RecognizeMode.Multiple);
    speechRecognitionEngine.SpeechRecognized += (s, args) => MessageBox.Show(args.Result.Text);
}
</code>```

And this is where I need to access the access source via the Kinect once it has been loaded, which isn't doing anything at all. This I want to be doing:

```<code>using (var audioSource = new KinectAudioSource())
{
    audioSource.FeatureMode = true;
    audioSource.AutomaticGainControl = false;
    audioSource.SystemMode = SystemMode.OptibeamArrayOnly;

    var recognizerInfo = GetKinectRecognizer();
    var speechRecognitionEngine = new SpeechRecognitionEngine(recognizerInfo.Id);

    speechRecognitionEngine.LoadGrammar(new DictationGrammar());
    speechRecognitionEngine.SpeechRecognized += (s, args) => MessageBox.Show(args.Result.Text);

    using (var s = audioSource.Start())
    {
        speechRecognitionEngine.SetInputToAudioStream(s, new SpeechAudioFormatInfo(EncodingFormat.Pcm, 16000, 16, 1, 32000, 2, null));
        speechRecognitionEngine.RecognizeAsync(RecognizeMode.Multiple);
    }
}
</code>```

So the question is, is it even possible to use System.Speech instead of Microsoft.Speech with the current Kinect SDK, and what am I doing wrong in the 2nd code sample?

GetKinectRecognizer Method

```<code>private static RecognizerInfo GetKinectRecognizer()
{
    Func<RecognizerInfo, bool> matchingFunc = r =>
    {
        string value;
        r.AdditionalInfo.TryGetValue("Kinect", out value);
        return "True".Equals(value, StringComparison.InvariantCultureIgnoreCase) && "en-US".Equals(r.Culture.Name, StringComparison.InvariantCultureIgnoreCase);
    };

    return SpeechRecognitionEngine.InstalledRecognizers().Where(matchingFunc).FirstOrDefault();
}
</code>```

答:
Try this code with a reference to System.Speech.</p>

```<code>using (var audioSource = new KinectAudioSource())
{
    audioSource.FeatureMode = true;
    audioSource.AutomaticGainControl = false;
    audioSource.SystemMode = SystemMode.OptibeamArrayOnly;

    System.Speech.Recognition.RecognizerInfo ri = GetKinectRecognizer();
    var speechRecognitionEngine = new SpeechRecognitionEngine(ri.Id);

    speechRecognitionEngine.LoadGrammar(new DictationGrammar());
    speechRecognitionEngine.SpeechRecognized += (s, args) => MessageBox.Show(args.Result.Text);

    using (var s = audioSource.Start())
    {
        speechRecognitionEngine.SetInputToAudioStream(s, new SpeechAudioFormatInfo(EncodingFormat.Pcm, 16000, 16, 1, 32000, 2, null));
        speechRecognitionEngine.RecognizeAsync(RecognizeMode.Multiple);
    }
}
</code>```

Title: Using System.Speech with Kinect

Body:
I am developing a prototype speech to text captioning application for a University project. I am going to be using gesture recognition within my project late on, so I thought it would be a good idea to use the Kinect as the microphone source, rather than using an additional microphone. The idea of my application is to recognize spontaneous speeches such as long and complex sentences (I understand it won’t that the speech dictation will not be perfect however). I have seen many Kinect speech samples where it makes a reference to Microsoft.Speech, but not System.Speech. As I need to train the speech engine and load a DictationGrammar into the Speech Recognition Engine, Microsoft.Speech is the only option for me.

I have managed to get it working while using the Kinect as the direct microphone audio source, but since I am loading the Kinect for the video preview and gesture recognition, I am unable to access it as a direct microphone.

This is code accessing the microphone directly without loading the Kinect hardware for gesture, etc, and works perfectly:

private void InitializeSpeech()
{
    var speechRecognitionEngine = new SpeechRecognitionEngine();
    speechRecognitionEngine.SetInputToDefaultAudioDevice();
    speechRecognitionEngine.LoadGrammar(new DictationGrammar());
    speechRecognitionEngine.RecognizeAsync(RecognizeMode.Multiple);
    speechRecognitionEngine.SpeechRecognized += (s, args) => MessageBox.Show(args.Result.Text);
}

And this is where I need to access the access source via the Kinect once it has been loaded, which isn't doing anything at all. This I want to be doing:

using (var audioSource = new KinectAudioSource())
{
    audioSource.FeatureMode = true;
    audioSource.AutomaticGainControl = false;
    audioSource.SystemMode = SystemMode.OptibeamArrayOnly;

    var recognizerInfo = GetKinectRecognizer();
    var speechRecognitionEngine = new SpeechRecognitionEngine(recognizerInfo.Id);

    speechRecognitionEngine.LoadGrammar(new DictationGrammar());
    speechRecognitionEngine.SpeechRecognized += (s, args) => MessageBox.Show(args.Result.Text);

    using (var s = audioSource.Start())
    {
        speechRecognitionEngine.SetInputToAudioStream(s, new SpeechAudioFormatInfo(EncodingFormat.Pcm, 16000, 16, 1, 32000, 2, null));
        speechRecognitionEngine.RecognizeAsync(RecognizeMode.Multiple);
    }
}

So the question is, is it even possible to use System.Speech instead of Microsoft.Speech with the current Kinect SDK, and what am I doing wrong in the 2nd code sample?

GetKinectRecognizer Method

private static RecognizerInfo GetKinectRecognizer()
{
    Func<RecognizerInfo, bool> matchingFunc = r =>
    {
        string value;
        r.AdditionalInfo.TryGetValue("Kinect", out value);
        return "True".Equals(value, StringComparison.InvariantCultureIgnoreCase) && "en-US".Equals(r.Culture.Name, StringComparison.InvariantCultureIgnoreCase);
    };

    return SpeechRecognitionEngine.InstalledRecognizers().Where(matchingFunc).FirstOrDefault();
}

Body:
Try this code with a reference to System.Speech.

using (var audioSource = new KinectAudioSource())
{
    audioSource.FeatureMode = true;
    audioSource.AutomaticGainControl = false;
    audioSource.SystemMode = SystemMode.OptibeamArrayOnly;

    System.Speech.Recognition.RecognizerInfo ri = GetKinectRecognizer();
    var speechRecognitionEngine = new SpeechRecognitionEngine(ri.Id);

    speechRecognitionEngine.LoadGrammar(new DictationGrammar());
    speechRecognitionEngine.SpeechRecognized += (s, args) => MessageBox.Show(args.Result.Text);

    using (var s = audioSource.Start())
    {
        speechRecognitionEngine.SetInputToAudioStream(s, new SpeechAudioFormatInfo(EncodingFormat.Pcm, 16000, 16, 1, 32000, 2, null));
        speechRecognitionEngine.RecognizeAsync(RecognizeMode.Multiple);
    }
}


问:
I am trying to store current date and time in asyncstorage, but the return value I get is a promise and I can't see the values
I tried passing the values as Json (key-pair values) but I don't get to to see the values in response.</p>

答:
Try to resolve the promise:</p>

```<code>getItem({ key: value}).then(data => console.log(data);
</code>```

Body:
Try to resolve the promise:

getItem({ key: value}).then(data => console.log(data);


问:
Correctly interpret Butterworth filter frequencies
I am using the butter function from the signal package in R to filter my data.

The data is Fourier-transformed (complex numbers) - and I want to filter out specific frequencies (I have a 256Hz sampling frequency, hence a 128Hz spectrum and say I want to filter only data from 4-8Hz).

I find conflicting documentation on what the correct values for W in this function should be:

```<code>butter(n, W, type = c("low", "high", "stop", "pass"),
plane = c("z", "s"), ...)
</code>```

should they be 4/256 and 8/256?

I find it hard to interpret whether my results with 4/256 and 8/256 are correct.

```<code>strength <- ftdata
low <- 4
high <- 8
bf <- butter(5, low/256, type="high")
bfsig <- filter(bf, strength)
bf <- butter(5, high/256, type="low")
bfsig <- filter(bf, bfsig)

plot(f,bfsig, type='l')

# Where ftdata is just the output from my Fourier transform. The 5 is the order of the filter.
</code>```

I just want to know whether the "/256" makes sense here.

EDIT:

Also, any idea why the below does not return the same result as the above?

```<code> filt <- butter(5,c(low/256,high/256), "pass")
 bfsig <- filter(filt, strength)
</code>```

It should just be a combination of the low and high-pass filters.

答: In DSP, frequency is treated as "Normalized frequency". Normalized frequency is calculated by scaling frequency range 0 to smapling frequency into 0 to 1.0 . So you have to divide specific frequencies by 256.</p>

Body:
I am using the butter function from the signal package in R to filter my data.

The data is Fourier-transformed (complex numbers) - and I want to filter out specific frequencies (I have a 256Hz sampling frequency, hence a 128Hz spectrum and say I want to filter only data from 4-8Hz).

I find conflicting documentation on what the correct values for W in this function should be:

butter(n, W, type = c("low", "high", "stop", "pass"),
plane = c("z", "s"), ...)

should they be 4/256 and 8/256?

I find it hard to interpret whether my results with 4/256 and 8/256 are correct.

strength <- ftdata
low <- 4
high <- 8
bf <- butter(5, low/256, type="high")
bfsig <- filter(bf, strength)
bf <- butter(5, high/256, type="low")
bfsig <- filter(bf, bfsig)

plot(f,bfsig, type='l')

# Where ftdata is just the output from my Fourier transform. The 5 is the order of the filter.

I just want to know whether the "/256" makes sense here.

EDIT:

Also, any idea why the below does not return the same result as the above?

 filt <- butter(5,c(low/256,high/256), "pass")
 bfsig <- filter(filt, strength)

It should just be a combination of the low and high-pass filters.


问:
Code with ?, Compile in Objective-C
So I'm jumping into iPhone development and I've begun looking into Objective-C and have noticed that... it sucks. Ultimately, there's all kinds of odd syntax requirements, ex:

```<code>NSString *city = @"Victoria";
</code>```

or

```<code>[MyClass myMethod]
</code>```

This is alien. The language should be smart enough to know what do do with a normal variable and string.

But, this is the language, and I can't do anything about it. So, my main question is: Is there any way to write my code in PHP/AS3/C# or some other normal language and then compile or convert it to legal Objective-C? I was going to use AS3 but necessary functionality like the Camera is not currently supported.

I know it's an odd question, but what about when I need to develop for Android or Windows 7? There are only so many languages one can learn before one loses his/her mind. I'd like to stop at 7.

答:
you cannot convert the code into objective C but the mono project enables you to develop iPhone apps in c# look at this

MONO TOUCH

MONO TOUCH for iphone 4

SOME OTHER INFO

get it from here

Title: Code with ?, Compile in Objective-C

Body:
So I'm jumping into iPhone development and I've begun looking into Objective-C and have noticed that... it sucks. Ultimately, there's all kinds of odd syntax requirements, ex:

NSString *city = @"Victoria";

or

[MyClass myMethod]

This is alien. The language should be smart enough to know what do do with a normal variable and string.

But, this is the language, and I can't do anything about it. So, my main question is: Is there any way to write my code in PHP/AS3/C# or some other normal language and then compile or convert it to legal Objective-C? I was going to use AS3 but necessary functionality like the Camera is not currently supported.

I know it's an odd question, but what about when I need to develop for Android or Windows 7? There are only so many languages one can learn before one loses his/her mind. I'd like to stop at 7.


问:
Is there a Module or Something Similar for Interactive Prompts in PowerShell?
Is there something we can use in PowerShell to ask users to select one item from an array of items? For example, I like how Inquirer.js can do it.

I have also seen PoshGui, but it seems too much work to create just a simple prompt.

The reason we want something similar is that we need to provide deployment scripts for our clients and make deployment guides as easy as possible. Asking users to select one item on a screen is much better than asking them to insert some guid to a config file.

Do you have any suggestions for user prompts for arrays?

答:
All of the answers are correct, but I also wrote a few reusable PowerShell helper functions. Readme. I auto-generate basic looking WinForms. Looks ugly, but works.

https://github.com/Zerg00s/powershell-forms

```<code>$selectedItem = Get-FormArrayItem (Get-ChildItem)
</code>```

```<code>$Delete = Get-FormBinaryAnswer "Delete file?"
</code>```

```<code>$newFileName = Get-FormStringInput "Enter new file name" -defaultValue "My new file"
</code>```

```<code># -------------------------------------------------------------------------------
# Prepare the list of inputs that user needs to populate using an interactive form
# -------------------------------------------------------------------------------
$preDeployInputs = @{
    suffix                       = ""
    SPSiteUrl                    = "https://ENTER_SHAREPOINT_SITE.sharepoint.com"
    TimeZone                     = "Central Standard Time"
    sendGridRegistrationEmail    = "ENTER_VALID_EMAIL_ADDRESS"
    sendGridRegistrationPassword = $sendGridPassword
    sendGridRegistrationCompany  = "Contoso & Tailspin"
    sendGridRegistrationWebsite  = "https://www.company.com"
    fromEmail                    = "no-reply@DOMAIN.COM"
}

$preDeployInputs = Get-FormItemProperties -item $preDeployInputs -dialogTitle "Fill these required fields"
</code>```

Body:
All of the answers are correct, but I also wrote a few reusable PowerShell helper functions. Readme. I auto-generate basic looking WinForms. Looks ugly, but works.

https://github.com/Zerg00s/powershell-forms

$selectedItem = Get-FormArrayItem (Get-ChildItem)

$Delete = Get-FormBinaryAnswer "Delete file?"

$newFileName = Get-FormStringInput "Enter new file name" -defaultValue "My new file"

# -------------------------------------------------------------------------------
# Prepare the list of inputs that user needs to populate using an interactive form
# -------------------------------------------------------------------------------
$preDeployInputs = @{
    suffix                       = ""
    SPSiteUrl                    = "https://ENTER_SHAREPOINT_SITE.sharepoint.com"
    TimeZone                     = "Central Standard Time"
    sendGridRegistrationEmail    = "ENTER_VALID_EMAIL_ADDRESS"
    sendGridRegistrationPassword = $sendGridPassword
    sendGridRegistrationCompany  = "Contoso & Tailspin"
    sendGridRegistrationWebsite  = "https://www.company.com"
    fromEmail                    = "no-reply@DOMAIN.COM"
}

$preDeployInputs = Get-FormItemProperties -item $preDeployInputs -dialogTitle "Fill these required fields"


问:
mvrnorm (from MASS) vs rmvnorm (from mvtnorm)
I am generating a large volume of data from the multivariate Normal distribution for simulation. I wonder if anyone is aware of which command is most efficient for this. If it is the mvrnorm (from the "MASS" package) or the rmvnorm (from the "mvtnorm" package).</p>

答:
Such questions can be easily answered by timing different approaches. Let

```<code>library(microbenchmark)
library(MASS)
library(mvtnorm)

n <- 10000
k <- 50
mu <- rep(0, k)
rho <- 0.2
Sigma <- diag(k) * (1 - rho) + rho
</code>```

In this way we have 50 variables with unit variance and correlation 0.2. Generating 10000 observations we get

```<code>microbenchmark(mvrnorm(n, mu = mu, Sigma = Sigma),
               rmvnorm(n, mean = mu, sigma = Sigma, method = "eigen"),
               rmvnorm(n, mean = mu, sigma = Sigma, method = "svd"),
               rmvnorm(n, mean = mu, sigma = Sigma, method = "chol"),
               times = 100)
# Unit: milliseconds
#                                                    expr      min       lq     mean   median        uq      max neval cld
#                      mvrnorm(n, mu = mu, Sigma = Sigma) 65.04667 73.02912 85.30384 81.70611  92.69137 148.6959   100  a
#  rmvnorm(n, mean = mu, sigma = Sigma, method = "eigen") 71.14170 81.08311 95.12891 88.84669 100.62174 237.0012   100   b
#    rmvnorm(n, mean = mu, sigma = Sigma, method = "svd") 71.32999 81.30640 93.40939 88.54804 104.00281 208.3690   100   b
#   rmvnorm(n, mean = mu, sigma = Sigma, method = "chol") 71.22712 78.59898 94.13958 89.04653 108.27363 158.7890   100   b
</code>```

Thus, possibly mvrnorm performs slightly better. As you have a specific application in mind, you should set n, k, and Sigma to values more adequate to this application.

As you don't seem to be restricted to those two approaches, you could look into Rcpp alternatives; see, e.g., 1, 2, 3.

Body:
Such questions can be easily answered by timing different approaches. Let

library(microbenchmark)
library(MASS)
library(mvtnorm)

n <- 10000
k <- 50
mu <- rep(0, k)
rho <- 0.2
Sigma <- diag(k) * (1 - rho) + rho

In this way we have 50 variables with unit variance and correlation 0.2. Generating 10000 observations we get

microbenchmark(mvrnorm(n, mu = mu, Sigma = Sigma),
               rmvnorm(n, mean = mu, sigma = Sigma, method = "eigen"),
               rmvnorm(n, mean = mu, sigma = Sigma, method = "svd"),
               rmvnorm(n, mean = mu, sigma = Sigma, method = "chol"),
               times = 100)
# Unit: milliseconds
#                                                    expr      min       lq     mean   median        uq      max neval cld
#                      mvrnorm(n, mu = mu, Sigma = Sigma) 65.04667 73.02912 85.30384 81.70611  92.69137 148.6959   100  a
#  rmvnorm(n, mean = mu, sigma = Sigma, method = "eigen") 71.14170 81.08311 95.12891 88.84669 100.62174 237.0012   100   b
#    rmvnorm(n, mean = mu, sigma = Sigma, method = "svd") 71.32999 81.30640 93.40939 88.54804 104.00281 208.3690   100   b
#   rmvnorm(n, mean = mu, sigma = Sigma, method = "chol") 71.22712 78.59898 94.13958 89.04653 108.27363 158.7890   100   b

Thus, possibly mvrnorm performs slightly better. As you have a specific application in mind, you should set n, k, and Sigma to values more adequate to this application.

As you don't seem to be restricted to those two approaches, you could look into Rcpp alternatives; see, e.g., 1, 2, 3.


问:
Fill a 2D matrix with given value in Prolog
I have an array like:

```<code>[[0,2,_9492],[2,_9510,_9516],[_9528,_9534,_9540]]
</code>```

i want to fill all unbound(i.e. have random values) element to -1

Needed result

```<code>[[0,2,-1],[2,-1,-1],[-1,-1,-1]]
</code>```

what i tried

```<code>fillArray([H|T],[H1|T1]):-fillRow(H,H1),fillArray(T,T1).
fillRow([H|_], _):-nonvar(H),fail.
fillRow([0|_], _).
fillRow([H|T],[-1|B]):-fillRow(T,B).
</code>```

What i got is false

答:
Using lambda expression in SWI-Prolog

An advanced solution in SWI-Prolog is:

```<code>set_unbound(Value, Matrix) :-
    Lambda = {Value} / [X]>>(var(X) -> X=Value ; true),
    maplist(maplist(Lambda), Matrix).
</code>```

Examples:

```<code>?- M = [[0,2,_],[2,_,_],[_,_,_]], set_unbound(-1, M).
Ma = [[0, 2, -1], [2, -1, -1], [-1, -1, -1]].

?- M = [[0,_],[_,2]], set_unbound(9, M).
M = [[0, 9], [9, 2]].

?- M = [[1,_],[_,3]], set_unbound(V, M).
M = [[1, V], [V, 3]].
</code>```

Body:
I have an array like:

[[0,2,_9492],[2,_9510,_9516],[_9528,_9534,_9540]]

i want to fill all unbound(i.e. have random values) element to -1

Needed result

[[0,2,-1],[2,-1,-1],[-1,-1,-1]]

what i tried

fillArray([H|T],[H1|T1]):-fillRow(H,H1),fillArray(T,T1).
fillRow([H|_], _):-nonvar(H),fail.
fillRow([0|_], _).
fillRow([H|T],[-1|B]):-fillRow(T,B).

What i got is false

Body:
Using lambda expression in SWI-Prolog

An advanced solution in SWI-Prolog is:

set_unbound(Value, Matrix) :-
    Lambda = {Value} / [X]>>(var(X) -> X=Value ; true),
    maplist(maplist(Lambda), Matrix).

Examples:

?- M = [[0,2,_],[2,_,_],[_,_,_]], set_unbound(-1, M).
Ma = [[0, 2, -1], [2, -1, -1], [-1, -1, -1]].

?- M = [[0,_],[_,2]], set_unbound(9, M).
M = [[0, 9], [9, 2]].

?- M = [[1,_],[_,3]], set_unbound(V, M).
M = [[1, V], [V, 3]].


问:
how to limit and clamp distance between two points in a Line renderer unity2d
I am making a game which let you click on a ball and drag to draw a line renderer with two points and point it to a specific direction and when release I add force to the ball,
for now, I just want to know how can I limit the distance between those two points like give it a radius.

答:
I've written the following pseudo code, which may help you </p>

```<code>float rang ;

Bool drag=true;
GameObject ball;

OnMouseDrag () {
if(drag) {
//Put your dragging code here

}

if (ball.transform.position>range)
     Drag=false;
else Drage=true;

}
</code>```

Body:
I've written the following pseudo code, which may help you

float rang ;

Bool drag=true;
GameObject ball;

OnMouseDrag () {
if(drag) {
//Put your dragging code here

}

if (ball.transform.position>range)
     Drag=false;
else Drage=true;

}


问:
D3js Grouped Scatter plot with no collision
I am using this example to make scatter plot:

https://www.d3-graph-gallery.com/graph/boxplot_show_individual_points.html

Now this example uses jitter to randomize x position of the dots for demonstration purpose, but my goal is to make these dots in that way so they don't collide and to be in the same row if there is collision.

Best example of what I am trying to do (visually) is some sort of beeswarm where data is represented like in this fiddle:

https://jsfiddle.net/n444k759/4/

Snippet of first example:

// set the dimensions and margins of the graph
var margin = {top: 10, right: 30, bottom: 30, left: 40},
    width = 460 - margin.left - margin.right,
    height = 400 - margin.top - margin.bottom;

// append the svg object to the body of the page
var svg = d3.select("#my_dataviz")
  .append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform",
          "translate(" + margin.left + "," + margin.top + ")");

// Read the data and compute summary statistics for each specie
d3.csv("https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/iris.csv", function(data) {

  // Compute quartiles, median, inter quantile range min and max --> these info are then used to draw the box.
  var sumstat = d3.nest() // nest function allows to group the calculation per level of a factor
    .key(function(d) { return d.Species;})
    .rollup(function(d) {
      q1 = d3.quantile(d.map(function(g) { return g.Sepal_Length;}).sort(d3.ascending),.25)
      median = d3.quantile(d.map(function(g) { return g.Sepal_Length;}).sort(d3.ascending),.5)
      q3 = d3.quantile(d.map(function(g) { return g.Sepal_Length;}).sort(d3.ascending),.75)
      interQuantileRange = q3 - q1
      min = q1 - 1.5 * interQuantileRange
      max = q3 + 1.5 * interQuantileRange
      return({q1: q1, median: median, q3: q3, interQuantileRange: interQuantileRange, min: min, max: max})
    })
    .entries(data)

  // Show the X scale
  var x = d3.scaleBand()
    .range([ 0, width ])
    .domain(["setosa", "versicolor", "virginica"])
    .paddingInner(1)
    .paddingOuter(.5)
  svg.append("g")
    .attr("transform", "translate(0," + height + ")")
    .call(d3.axisBottom(x))

  // Show the Y scale
  var y = d3.scaleLinear()
    .domain([3,9])
    .range([height, 0])
  svg.append("g").call(d3.axisLeft(y))

  // Show the main vertical line
  svg
    .selectAll("vertLines")
    .data(sumstat)
    .enter()
    .append("line")
      .attr("x1", function(d){return(x(d.key))})
      .attr("x2", function(d){return(x(d.key))})
      .attr("y1", function(d){return(y(d.value.min))})
      .attr("y2", function(d){return(y(d.value.max))})
      .attr("stroke", "black")
      .style("width", 40)

  // rectangle for the main box
  var boxWidth = 100
  svg
    .selectAll("boxes")
    .data(sumstat)
    .enter()
    .append("rect")
        .attr("x", function(d){return(x(d.key)-boxWidth/2)})
        .attr("y", function(d){return(y(d.value.q3))})
        .attr("height", function(d){return(y(d.value.q1)-y(d.value.q3))})
        .attr("width", boxWidth )
        .attr("stroke", "black")
        .style("fill", "#69b3a2")

  // Show the median
  svg
    .selectAll("medianLines")
    .data(sumstat)
    .enter()
    .append("line")
      .attr("x1", function(d){return(x(d.key)-boxWidth/2) })
      .attr("x2", function(d){return(x(d.key)+boxWidth/2) })
      .attr("y1", function(d){return(y(d.value.median))})
      .attr("y2", function(d){return(y(d.value.median))})
      .attr("stroke", "black")
      .style("width", 80)

var simulation = d3.forceSimulation(data)
    .force("x", d3.forceX(function(d) { return x(d.Species); }))
    // .force("y", d3.forceX(function(d) { return y(d.Sepal_lenght) }))
    .force("collide", d3.forceCollide()
             .strength(1)
             .radius(4+1))
    .stop();

      for (var i = 0; i < data.length; ++i) simulation.tick();

// Add individual points with jitter
var jitterWidth = 50
svg
  .selectAll("points")
  .data(data)
  .enter()
  .append("circle")
    .attr("cx", function(d){return( d.x )})
    .attr("cy", function(d){return(y(d.Sepal_Length))})
    .attr("r", 4)
    .style("fill", "white")
    .attr("stroke", "black")

})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- Load d3.js -->
<script src="https://d3js.org/d3.v4.js"></script>

<!-- Create a div where the graph will take place -->
<div id="my_dataviz"></div></code>```

I tried to make something like this:

```<code>var simulation = d3.forceSimulation(data)
  .force("x", d3.forceX(function(d) { return x(d.Species); }))
  .force("collide", d3.forceCollide(4)
            .strength(1)
            .radius(4+1))
  .stop();

  for (var i = 0; i < 120; ++i) simulation.tick();

// Append circle points
svg.selectAll(".point")
.data(data)
.enter()
.append("circle")
    .attr("cx", function(d){
        return(x(d.x))
    })
    .attr("cy", function(d){
        return(y(d.y))
    })
    .attr("r", 4)
    .attr("fill", "white")
    .attr("stroke", "black")
</code>```

but it does not even prevent collision and I am a bit confused with it.

I also tried to modify plot from this example:

http://bl.ocks.org/asielen/92929960988a8935d907e39e60ea8417

where beeswarm looks exactly what I need to achieve. But this code is way too expanded as it is made to fit the purpose of reusable charts and I can't track what exact formula is used to achieve this:

Any help would be great..
Thanks

答:
Here's a quick example which combines the ideas of your beeswarm example with your initial boxplot.  I've commented the tricky parts below:

<!DOCTYPE html>

```

Body:
I am using this example to make scatter plot:

https://www.d3-graph-gallery.com/graph/boxplot_show_individual_points.html

Now this example uses jitter to randomize x position of the dots for demonstration purpose, but my goal is to make these dots in that way so they don't collide and to be in the same row if there is collision.

Best example of what I am trying to do (visually) is some sort of beeswarm where data is represented like in this fiddle:

https://jsfiddle.net/n444k759/4/

Snippet of first example:

// set the dimensions and margins of the graph
var margin = {top: 10, right: 30, bottom: 30, left: 40},
    width = 460 - margin.left - margin.right,
    height = 400 - margin.top - margin.bottom;

// append the svg object to the body of the page
var svg = d3.select("#my_dataviz")
  .append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform",
          "translate(" + margin.left + "," + margin.top + ")");

// Read the data and compute summary statistics for each specie
d3.csv("https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/iris.csv", function(data) {

  // Compute quartiles, median, inter quantile range min and max --> these info are then used to draw the box.
  var sumstat = d3.nest() // nest function allows to group the calculation per level of a factor
    .key(function(d) { return d.Species;})
    .rollup(function(d) {
      q1 = d3.quantile(d.map(function(g) { return g.Sepal_Length;}).sort(d3.ascending),.25)
      median = d3.quantile(d.map(function(g) { return g.Sepal_Length;}).sort(d3.ascending),.5)
      q3 = d3.quantile(d.map(function(g) { return g.Sepal_Length;}).sort(d3.ascending),.75)
      interQuantileRange = q3 - q1
      min = q1 - 1.5 * interQuantileRange
      max = q3 + 1.5 * interQuantileRange
      return({q1: q1, median: median, q3: q3, interQuantileRange: interQuantileRange, min: min, max: max})
    })
    .entries(data)

  // Show the X scale
  var x = d3.scaleBand()
    .range([ 0, width ])
    .domain(["setosa", "versicolor", "virginica"])
    .paddingInner(1)
    .paddingOuter(.5)
  svg.append("g")
    .attr("transform", "translate(0," + height + ")")
    .call(d3.axisBottom(x))

  // Show the Y scale
  var y = d3.scaleLinear()
    .domain([3,9])
    .range([height, 0])
  svg.append("g").call(d3.axisLeft(y))

  // Show the main vertical line
  svg
    .selectAll("vertLines")
    .data(sumstat)
    .enter()
    .append("line")
      .attr("x1", function(d){return(x(d.key))})
      .attr("x2", function(d){return(x(d.key))})
      .attr("y1", function(d){return(y(d.value.min))})
      .attr("y2", function(d){return(y(d.value.max))})
      .attr("stroke", "black")
      .style("width", 40)

  // rectangle for the main box
  var boxWidth = 100
  svg
    .selectAll("boxes")
    .data(sumstat)
    .enter()
    .append("rect")
        .attr("x", function(d){return(x(d.key)-boxWidth/2)})
        .attr("y", function(d){return(y(d.value.q3))})
        .attr("height", function(d){return(y(d.value.q1)-y(d.value.q3))})
        .attr("width", boxWidth )
        .attr("stroke", "black")
        .style("fill", "#69b3a2")

  // Show the median
  svg
    .selectAll("medianLines")
    .data(sumstat)
    .enter()
    .append("line")
      .attr("x1", function(d){return(x(d.key)-boxWidth/2) })
      .attr("x2", function(d){return(x(d.key)+boxWidth/2) })
      .attr("y1", function(d){return(y(d.value.median))})
      .attr("y2", function(d){return(y(d.value.median))})
      .attr("stroke", "black")
      .style("width", 80)

var simulation = d3.forceSimulation(data)
    .force("x", d3.forceX(function(d) { return x(d.Species); }))
    // .force("y", d3.forceX(function(d) { return y(d.Sepal_lenght) }))
    .force("collide", d3.forceCollide()
             .strength(1)
             .radius(4+1))
    .stop();

      for (var i = 0; i < data.length; ++i) simulation.tick();

// Add individual points with jitter
var jitterWidth = 50
svg
  .selectAll("points")
  .data(data)
  .enter()
  .append("circle")
    .attr("cx", function(d){return( d.x )})
    .attr("cy", function(d){return(y(d.Sepal_Length))})
    .attr("r", 4)
    .style("fill", "white")
    .attr("stroke", "black")

})

I tried to make something like this:

var simulation = d3.forceSimulation(data)
  .force("x", d3.forceX(function(d) { return x(d.Species); }))
  .force("collide", d3.forceCollide(4)
            .strength(1)
            .radius(4+1))
  .stop();

  for (var i = 0; i < 120; ++i) simulation.tick();

// Append circle points
svg.selectAll(".point")
.data(data)
.enter()
.append("circle")
    .attr("cx", function(d){
        return(x(d.x))
    })
    .attr("cy", function(d){
        return(y(d.y))
    })
    .attr("r", 4)
    .attr("fill", "white")
    .attr("stroke", "black")

but it does not even prevent collision and I am a bit confused with it.

I also tried to modify plot from this example:

http://bl.ocks.org/asielen/92929960988a8935d907e39e60ea8417

where beeswarm looks exactly what I need to achieve. But this code is way too expanded as it is made to fit the purpose of reusable charts and I can't track what exact formula is used to achieve this:

Any help would be great..
Thanks

Body:
Here's a quick example which combines the ideas of your beeswarm example with your initial boxplot.  I've commented the tricky parts below:

<!DOCTYPE html>
<html>

<head>
</head>

<body>
  <!-- Load d3.js -->
  <script src="https://d3js.org/d3.v4.js"></script>

  <!-- Create a div where the graph will take place -->
  <div id="my_dataviz"></div>

  <script>
    // set the dimensions and margins of the graph
    var margin = {
        top: 10,
        right: 30,
        bottom: 30,
        left: 40
      },
      width = 460 - margin.left - margin.right,
      height = 400 - margin.top - margin.bottom;

    // append the svg object to the body of the page
    var svg = d3.select("#my_dataviz")
      .append("svg")
      .attr("width", width + margin.left + margin.right)
      .attr("height", height + margin.top + margin.bottom)
      .append("g")
      .attr("transform",
        "translate(" + margin.left + "," + margin.top + ")");

    // Read the data and compute summary statistics for each specie
    d3.csv("https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/iris.csv", function(data) {

      // Compute quartiles, median, inter quantile range min and max --> these info are then used to draw the box.
      var sumstat = d3.nest() // nest function allows to group the calculation per level of a factor
        .key(function(d) {
          return d.Species;
        })
        .rollup(function(d) {
          q1 = d3.quantile(d.map(function(g) {
            return g.Sepal_Length;
          }).sort(d3.ascending), .25)
          median = d3.quantile(d.map(function(g) {
            return g.Sepal_Length;
          }).sort(d3.ascending), .5)
          q3 = d3.quantile(d.map(function(g) {
            return g.Sepal_Length;
          }).sort(d3.ascending), .75)
          interQuantileRange = q3 - q1
          min = q1 - 1.5 * interQuantileRange
          max = q3 + 1.5 * interQuantileRange
          return ({
            q1: q1,
            median: median,
            q3: q3,
            interQuantileRange: interQuantileRange,
            min: min,
            max: max
          })
        })
        .entries(data)

      // Show the X scale
      var x = d3.scaleBand()
        .range([0, width])
        .domain(["setosa", "versicolor", "virginica"])
        .paddingInner(1)
        .paddingOuter(.5)
      svg.append("g")
        .attr("transform", "translate(0," + height + ")")
        .call(d3.axisBottom(x))

      // Show the Y scale
      var y = d3.scaleLinear()
        .domain([3, 9])
        .range([height, 0])
      svg.append("g").call(d3.axisLeft(y))

      // Show the main vertical line
      svg
        .selectAll("vertLines")
        .data(sumstat)
        .enter()
        .append("line")
        .attr("x1", function(d) {
          return (x(d.key))
        })
        .attr("x2", function(d) {
          return (x(d.key))
        })
        .attr("y1", function(d) {
          return (y(d.value.min))
        })
        .attr("y2", function(d) {
          return (y(d.value.max))
        })
        .attr("stroke", "black")
        .style("width", 40)

      // rectangle for the main box
      var boxWidth = 100
      svg
        .selectAll("boxes")
        .data(sumstat)
        .enter()
        .append("rect")
        .attr("x", function(d) {
          return (x(d.key) - boxWidth / 2)
        })
        .attr("y", function(d) {
          return (y(d.value.q3))
        })
        .attr("height", function(d) {
          return (y(d.value.q1) - y(d.value.q3))
        })
        .attr("width", boxWidth)
        .attr("stroke", "black")
        .style("fill", "#69b3a2")

      // Show the median
      svg
        .selectAll("medianLines")
        .data(sumstat)
        .enter()
        .append("line")
        .attr("x1", function(d) {
          return (x(d.key) - boxWidth / 2)
        })
        .attr("x2", function(d) {
          return (x(d.key) + boxWidth / 2)
        })
        .attr("y1", function(d) {
          return (y(d.value.median))
        })
        .attr("y2", function(d) {
          return (y(d.value.median))
        })
        .attr("stroke", "black")
        .style("width", 80)

      var r = 8;
      // create a scale that'll return a discreet value
      // so that close y values fall in a line
      var yPtScale = y.copy()
        .range([Math.floor(y.range()[0] / r), 0])
        .interpolate(d3.interpolateRound)
        .domain(y.domain());

      // bucket the data
      var ptsObj = {};
      data.forEach(function(d,i) {
        var yBucket = yPtScale(d.Sepal_Length);
        if (!ptsObj[d.Species]){
          ptsObj[d.Species] = {};
        }
        if (!ptsObj[d.Species][yBucket]){
          ptsObj[d.Species][yBucket] = [];
        }
        ptsObj[d.Species][yBucket].push({
          cy: yPtScale(d.Sepal_Length) * r,
          cx: x(d.Species)
        });
      });

      // determine the x position
      for (var x in ptsObj){
        for (var row in ptsObj[x]) {
          var v = ptsObj[x][row], // array of points
              m = v[0].cx, // mid-point
              l = m - (((v.length / 2) * r) - r/2); // left most position based on count of points in the bucket

          v.forEach(function(d,i){
            d.cx = l + (r * i); // x position
          });
        }
      }

      // flatten the data structure
      var flatData = Object.values(ptsObj)
                      .map(function(d){return Object.values(d)})
                      .flat(2);

      svg
        .selectAll("points")
        .data(flatData)
        .enter()
        .append("circle")
        .attr("cx", function(d) {
          return d.cx;
        })
        .attr("cy", function(d) {
          return d.cy;
        })
        .attr("r", 4)
        .style("fill", "white")
        .attr("stroke", "black")

    })
  </script>
</body>

</html>


问:
Realtime Single Object Tracking with TensorFlow.js
I'm putting my first steps in Machine Learning, I went through many TensorFlow.js tutorials already and I'm trying to achieve this: "Realtime Single Object Tracking/Detection"

Something like this -> input: webcam/video -> output: object bounding box

I know there are SSD and YOLO, and other libraries to predict & locate the objects. But the predicted time is very slow (in browser), I guessed it's because the Neural Network have to predict between so many objects.

https://github.com/ModelDepot/tfjs-yolo-tiny
https://github.com/tensorflow/models/tree/master/research/object_detection

What if I just want to track a single object? Would it be possible? Will the performance be better? Where should I start?

I've been thinking about extract the pre-trained class (object) from a SavedModel, then start training more from it. But there don't seems to be any instructions around Google.

答:
I found some fantastic code by IBM, which I used in the video in this tweet:  https://twitter.com/GantLaborde/status/1125735283343921152?s=20

I extracted that code to make a ReactJS component for detecting Rock/Paper/Scissors here: https://github.com/GantMan/rps_tfjs_demo/blob/master/src/AdvancedModel.js

If you'd like to play with the demo, it's at the bottom of this page: https://rps-tfjs.netlify.com/

All of this is open source and seems to work perfectly fast for detecting a single object in realtime.


问:
Is there a way to modify the brightness of LEDs in rpi-ws281x-go library after calling MakeWS2811()?
I've been playing with a Raspberry Pi and Golang to animate some WS2812 LEDs. I've been using the rpi-ws281x-go (https://github.com/rpi-ws281x/rpi-ws281x-go) library which is a Go wrapper around a C library (https://github.com/jgarff/rpi_ws281x). I'm not extremely familiar with C let alone Go wrappers of C libraries.

I can see that in the C code, I can access and change the brightness of the LEDs which is applied every time the render function is called. However, in the Go wrapper library, I don't see a way to access that variable. I can see that when I call ws2811.MakeWS2811(&opt), I can set the brightness in the opt struct. How can I change that brightness after calling MakeWS2811()?

I know how to apply my own brightness in my own animation functions in Go, but that seems redundant since the C function is going to do the same thing.

答:
@Clifford MakeWS2811(...) does take a pointer, but it looks like it makes a copy of the options in C.

However the returned instance has a Leds(nChannel) method, giving direct access to set the colours of LEDs. You can reduce the colour value to reduce the brightness (approximately).

```<code>...
opt.Channels[0].Brightness = ... original value 0 to 255
ws, err := MakeWS2811(&opts)
...

ws.Leds(0)[0] = 0xff //bright red
ws.Leds(0)[1] = 0x7f //half as bright
ws.Render()
</code>```

Note each time the C lib renders, it still scales the colours you set by the original brightness.

Body:
@Clifford MakeWS2811(...) does take a pointer, but it looks like it makes a copy of the options in C.

However the returned instance has a Leds(nChannel) method, giving direct access to set the colours of LEDs. You can reduce the colour value to reduce the brightness (approximately).

...
opt.Channels[0].Brightness = ... original value 0 to 255
ws, err := MakeWS2811(&opts)
...

ws.Leds(0)[0] = 0xff //bright red
ws.Leds(0)[1] = 0x7f //half as bright
ws.Render()

Note each time the C lib renders, it still scales the colours you set by the original brightness.


问:
What is Kotlin equivalent of funtion openssl_private_decrypt?
I have used openssl_public_encrypt function in a PHP-based server to encrypt a message with a public key. The crypted message is sent to a Kotlin-based server. If it were in PHP, the decryption would be done by using openssl_private_decrypt. How can I decrypt the message in Kotlin?

答:
So I found the equivalent code in Kotlin:</p>

```<code>private fun decrypt(cryptedData: ByteArray): String {
    val cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding")  //"PKCS1Padding" is the default padding
    cipher.init(Cipher.DECRYPT_MODE, key)
    val res = cipher.doFinal(cryptedData).toHexString()
    val decrypted = hexToAscii(res)
    return decrypted
}
</code>```

Body:
So I found the equivalent code in Kotlin:

private fun decrypt(cryptedData: ByteArray): String {
    val cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding")  //"PKCS1Padding" is the default padding
    cipher.init(Cipher.DECRYPT_MODE, key)
    val res = cipher.doFinal(cryptedData).toHexString()
    val decrypted = hexToAscii(res)
    return decrypted
}