问:
Copying Files Using AzCopy C#
I'm having an issue when copying blob containers from one storage account to another using AzCopy.

When trying to start the process I get this error Error:

Any idea why I'm having this issue?

```<code>    unknown command "/Source:https://pslfilestore.blob.core.windows.net/downloads" for "azcopy"
    Run 'azcopy --help' for usage.
    System.IO.StreamWriterdownloads
    unknown command "/Source:https://pslfilestore.blob.core.windows.net/downloads" for "azcopy

"
</code>```

Please see code below

```<code>foreach (CloudBlobContainer items in containers)
  {
    var AzCopyProcess = new Process();
    AzCopyProcess.StartInfo.UseShellExecute = false;
    AzCopyProcess.StartInfo.RedirectStandardOutput = true;
    AzCopyProcess.StartInfo.FileName = strCommand;
    //pass storage account name, container and the key
    AzCopyProcess.StartInfo.Arguments = $"/Source:https://{storageAccountName}.blob.core.windows.net/{items.Name} /Dest:{dayBlob.Uri}/{storageAccountName}/{items.Name} /SourceKey:{accountKey.ToString()} /DestKey:{pslFileStoreBackUpKey.ToString()} /S";

     AzCopyProcess.Start();

       StreamWriter stdOut = new StreamWriter(Console.OpenStandardOutput());
       stdOut.AutoFlush = true;
       Console.Write(stdOut);
       var output = AzCopyProcess.StandardOutput.ReadToEnd();
       Console.WriteLine($"{items.Name} {output}");
}
</code>```

答:
From your error report, you are using the AzCopy V10 however your code is in V8 format. I think this is the problem.

In V10 the copy usage should be: azcopy copy [source] [destination] [flags].

And the copy container syntax should be: azcopy cp "https://<source-storage-account-name>.blob.core.windows.net/<container-name>" "https://<destination-storage-account-name>.blob.core.windows.net/<container-name>" --recursive.

For more details you could refer to this doc: Transfer data with AzCopy and Blob storage. Or you could use like azure cp --help to get the details.

Title: Copying Files Using AzCopy C#

Body:
I'm having an issue when copying blob containers from one storage account to another using AzCopy.

When trying to start the process I get this error Error:

Any idea why I'm having this issue?

    unknown command "/Source:https://pslfilestore.blob.core.windows.net/downloads" for "azcopy"
    Run 'azcopy --help' for usage.
    System.IO.StreamWriterdownloads
    unknown command "/Source:https://pslfilestore.blob.core.windows.net/downloads" for "azcopy

"

Please see code below

foreach (CloudBlobContainer items in containers)
  {
    var AzCopyProcess = new Process();
    AzCopyProcess.StartInfo.UseShellExecute = false;
    AzCopyProcess.StartInfo.RedirectStandardOutput = true;
    AzCopyProcess.StartInfo.FileName = strCommand;
    //pass storage account name, container and the key
    AzCopyProcess.StartInfo.Arguments = $"/Source:https://{storageAccountName}.blob.core.windows.net/{items.Name} /Dest:{dayBlob.Uri}/{storageAccountName}/{items.Name} /SourceKey:{accountKey.ToString()} /DestKey:{pslFileStoreBackUpKey.ToString()} /S";

     AzCopyProcess.Start();

       StreamWriter stdOut = new StreamWriter(Console.OpenStandardOutput());
       stdOut.AutoFlush = true;
       Console.Write(stdOut);
       var output = AzCopyProcess.StandardOutput.ReadToEnd();
       Console.WriteLine($"{items.Name} {output}");
}


来源: stackexchange

问:
How to create dynamic WHERE select without COALESCE
I have found out that my SQL 2008 R2 database is really struggling with COALESCE function if used within search.

CODE:

```<code>where
    i.id_categ = COALESCE(@id_categ, i.id_categ )
    and i.id_brand = COALESCE(@id_brand , i.id_brand )
    and i.id_model = COALESCE(@id_model , i.id_model )
    and i.id_type = COALESCE(@id_karoseria, i.id_type )
    and i.id_fuel = COALESCE(@id_palivo, i.id_fuel )
    and (i.year between @year_from and @year_to)
    and (i.price between @price_from and @price_to)
</code>```

DYNAMIC variables:

```<code>ALTER PROCEDURE [dbo].[spInzeratSelect]
     @id_categ int = null,
     @id_brand int = null,
     @id_model int = null,
     @id_fuel int = null,
     @id_type int = null,
</code>```

Search should work with or without these variables.

Benchmark:

```<code>  with COALESCE = Total Execution Time: 3582
  without COALESCE conditions = Total Execution Time: 13
</code>```

You get the difference ...

Is there a nice solution how to ignore COALESCE and create dynamic SQL select with different approch ?

Thanks.

答:
tIn your very specific case you should replace all your COALESCE search parameters with the following pattern:

```<code> AND ( (@id_brand IS NULL) OR (i.id_brand = @id_brand) )
</code>```

etc

The parameter is evaluated as a literal before execution, so doing it this way makes the condition sargable.
This is functionally equivalent to your query except you're first checking against the literal value, which can be optimized away if it is, in fact, null.

EDIT: Apparently this is the approach recommended in @Joe Stefanelli's link as well. I originally poached it from Erland Sommerskog.

EDIT2: And I always forget to mention OPTION (RECOMPILE) too.

ContentLicense: CC BY-SA 3.0

Body:
I have found out that my SQL 2008 R2 database is really struggling with COALESCE function if used within search.

CODE:

where
    i.id_categ = COALESCE(@id_categ, i.id_categ )
    and i.id_brand = COALESCE(@id_brand , i.id_brand )
    and i.id_model = COALESCE(@id_model , i.id_model )
    and i.id_type = COALESCE(@id_karoseria, i.id_type )
    and i.id_fuel = COALESCE(@id_palivo, i.id_fuel )
    and (i.year between @year_from and @year_to)
    and (i.price between @price_from and @price_to)

DYNAMIC variables:

ALTER PROCEDURE [dbo].[spInzeratSelect]
     @id_categ int = null,
     @id_brand int = null,
     @id_model int = null,
     @id_fuel int = null,
     @id_type int = null,

Search should work with or without these variables.

Benchmark:

  with COALESCE = Total Execution Time: 3582
  without COALESCE conditions = Total Execution Time: 13

You get the difference ...

Is there a nice solution how to ignore COALESCE and create dynamic SQL select with different approch ?

Thanks.

Body:
tIn your very specific case you should replace all your COALESCE search parameters with the following pattern:

 AND ( (@id_brand IS NULL) OR (i.id_brand = @id_brand) )

etc

The parameter is evaluated as a literal before execution, so doing it this way makes the condition sargable.
This is functionally equivalent to your query except you're first checking against the literal value, which can be optimized away if it is, in fact, null.

EDIT: Apparently this is the approach recommended in @Joe Stefanelli's link as well. I originally poached it from Erland Sommerskog.

EDIT2: And I always forget to mention OPTION (RECOMPILE) too.


问:
Parsing data in Google Sheets
I have customer data from PayPal formatted like this for their recurring payments:

```<code>john doe: john.doe@gmail.comCustomer ID: I-1ABCDE123ABCDescription: ABC 123
</code>```

I want to parse this in a column to get just the email address.

答:
You could use FIND to get the position number of the @ in the string, and then also use FIND to get the position number of the first blank space before and after the position of the @.  Now let's say the @ is in position 26 of the cell, and from position 26, the next blank space in the cell going right is 37, and the next blank space going left from position 26 is at position 15, then you'll know that your email address starts at position 16 to 36.  Now all you have to do is use the MID formula from there to get your email address.

Also, I just noticed you dont have a space at the end of the email address... if the word Customer  ID always follows the email address, then instead of finding the next space to the right of the @, you could use the FIND to get the position number of this word instead, and do the same.

Title: Parsing data in Google Sheets

Body:
I have customer data from PayPal formatted like this for their recurring payments:

john doe: john.doe@gmail.comCustomer ID: I-1ABCDE123ABCDescription: ABC 123

I want to parse this in a column to get just the email address.

ContentLicense: CC BY-SA 4.0


问:
Node.js - Parsing Images from JSON Object Reference
I am parsing JSON data from a remote API. The particular endpoint I am using returns all the values I want like title, description, summary and cover. I was hoping the cover field would be a string with the jpg url, but instead returns an object reference id. If you make another request and pass the object ID, the url string is there. How can I parse the image data without making another call to a different endpoint? I am using the IGDB API and following their documentation.
Here is my code

```<code>    const axios = require('axios');
axios({
  url: "https://api-v3.igdb.com/games",
  method: 'GET',
  headers: {
      'Accept': 'application/json',
      'user-key': 'xxxx'
  },
  data: "fields name,summary,url,cover,popularity;sort popularity desc;limit 13;"
})
  .then(response => {
    /* GET home page. */
    router.get('/', (req, res, next) => {
      res.render('index', { pageId: 'index',
                        title: 'Homepage',
                        cards: homeCards
        });
    });
    //Iterate through the JSON array
    let r = response.data;
    console.log(response.data);
    for (i=0; i<r.length; ++i){
      //Store json values
        var title = r[i].name;
        var description = r[i].summary;
        var link = r[i].url;
        var imageId = r[i].cover;
        //Push values onto homeCards
        homeCards.push({
          title: title,
          link: link,
          description: description,
        });
      }

  })
  .catch(err => {
      console.error(err);
  });
</code>```

I store the cover id in a variable imageId. How can I use this to show the corresponding object reference for each game?

答:
Here is an example of performing the two requests using async/await and matching the cover based on the gameId.

const axios = require('axios');

(async () => {
  const links = (await axios({
      url: "https://api-v3.igdb.com/covers",
      method: 'GET',
      headers: {
          'Accept': 'application/json',
          'user-key': 'xxxx'
      },
      data: "fields game,url"
    }).catch(err => {
        console.error(err);
    })).data

  const response = await axios({
    url: "https://api-v3.igdb.com/games",
    method: 'GET',
    headers: {
        'Accept': 'application/json',
        'user-key': 'xxxx'
    },
    data: "fields dlcs,name,summary,url,cover,popularity;sort popularity desc;limit 13;"
  }).catch(err => {
      console.error(err);
  })

  /* GET home page. */
  router.get('/', (req, res, next) => {
    res.render('index', { pageId: 'index',
                      title: 'Homepage',
                      cards: homeCards
      });
  });
  //Iterate through the JSON array
  let r = response.data;
  console.log(response.data);
  for (i=0; i<r.length; ++i){
    //Store json values
      var title = r[i].name;
      var description = r[i].summary;
      //Find the cover based on the game id
      var link = links.find(l => l.game === r[i].dlcs).url
      var imageId = r[i].cover;
      //Push values onto homeCards
      homeCards.push({
        title: title,
        link: link,
        description: description,
      });
    }
})()```
</div>
</div>
</p>

<p>Edit:
To answer your question in the comments. Array.prototype.find takes a callback function as its first argument. In the code snippet above I have used an ES6 Arrow Function to pass in as the callback to find which is equivalent to:</p>

```links.find(function(l) {
  var boolean = l.game === r[i].dlcs
  return boolean
}).url
```

Body:
I am parsing JSON data from a remote API. The particular endpoint I am using returns all the values I want like title, description, summary and cover. I was hoping the cover field would be a string with the jpg url, but instead returns an object reference id. If you make another request and pass the object ID, the url string is there. How can I parse the image data without making another call to a different endpoint? I am using the IGDB API and following their documentation.
Here is my code

    const axios = require('axios');
axios({
  url: "https://api-v3.igdb.com/games",
  method: 'GET',
  headers: {
      'Accept': 'application/json',
      'user-key': 'xxxx'
  },
  data: "fields name,summary,url,cover,popularity;sort popularity desc;limit 13;"
})
  .then(response => {
    /* GET home page. */
    router.get('/', (req, res, next) => {
      res.render('index', { pageId: 'index',
                        title: 'Homepage',
                        cards: homeCards
        });
    });
    //Iterate through the JSON array
    let r = response.data;
    console.log(response.data);
    for (i=0; i<r.length; ++i){
      //Store json values
        var title = r[i].name;
        var description = r[i].summary;
        var link = r[i].url;
        var imageId = r[i].cover;
        //Push values onto homeCards
        homeCards.push({
          title: title,
          link: link,
          description: description,
        });
      }

  })
  .catch(err => {
      console.error(err);
  });

I store the cover id in a variable imageId. How can I use this to show the corresponding object reference for each game?

Body:
Here is an example of performing the two requests using async/await and matching the cover based on the gameId.

const axios = require('axios');

(async () => {
  const links = (await axios({
      url: "https://api-v3.igdb.com/covers",
      method: 'GET',
      headers: {
          'Accept': 'application/json',
          'user-key': 'xxxx'
      },
      data: "fields game,url"
    }).catch(err => {
        console.error(err);
    })).data

  const response = await axios({
    url: "https://api-v3.igdb.com/games",
    method: 'GET',
    headers: {
        'Accept': 'application/json',
        'user-key': 'xxxx'
    },
    data: "fields dlcs,name,summary,url,cover,popularity;sort popularity desc;limit 13;"
  }).catch(err => {
      console.error(err);
  })

  /* GET home page. */
  router.get('/', (req, res, next) => {
    res.render('index', { pageId: 'index',
                      title: 'Homepage',
                      cards: homeCards
      });
  });
  //Iterate through the JSON array
  let r = response.data;
  console.log(response.data);
  for (i=0; i<r.length; ++i){
    //Store json values
      var title = r[i].name;
      var description = r[i].summary;
      //Find the cover based on the game id
      var link = links.find(l => l.game === r[i].dlcs).url
      var imageId = r[i].cover;
      //Push values onto homeCards
      homeCards.push({
        title: title,
        link: link,
        description: description,
      });
    }
})()

Edit:
To answer your question in the comments. Array.prototype.find takes a callback function as its first argument. In the code snippet above I have used an ES6 Arrow Function to pass in as the callback to find which is equivalent to:

links.find(function(l) {
  var boolean = l.game === r[i].dlcs
  return boolean
}).url


问:
how we can specify input language for specific EditText(not for whole app) any help will be appreciated
how we can specify input language for specific EditText(not for the whole app) any help will be appreciated ..for example, for EditText1, I want to open the English keyboard and for EditText2 want to open some other language any help...</p>

答:
As far as I know you can't change the user's keyboard, it has to be changed by the user itself.

If you want to control if the user is introducing specific characters (f.e. chinese characters in an EditText), I would use a TextWatcher and apply a Regex pattern to evaluate the introduced String.


问:
npm install doesn't work in Docker
This is my Dockerfile:

```<code>FROM node:7

RUN apt-get update && apt-get install -y --no-install-recommends \
    rubygems build-essential ruby-dev \
    && rm -rf /var/lib/apt/lists/*

RUN npm install -gq gulp bower

RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
COPY . /usr/src/app

RUN npm install

CMD ["gulp", "start:dev"]
</code>```

When I build the image, the npm install command executes with little output and really quickly. I actually build it through docker-compose which does have a volume mounted - and I cannot see the node_modules folder being created on my hose. When I launch a container on this image, I can see there is no node_modules folder. I then execute npm install and things start working - it takes 2-3 minutes to install all the packages and the node_modules folder is indeed created.

What is happening here? What am I doing wrong? Why doesn't npm install work at build time, but then it works at run time?

答:
Also copying up the source and running npm install means that whenever the source code changes, the npm install step cache becomes invalid.

Instead, separate the steps/caches like so;

```<code>COPY package*.json ./
RUN npm install
</code>```

Title: npm install doesn't work in Docker

Body:
This is my Dockerfile:

FROM node:7

RUN apt-get update && apt-get install -y --no-install-recommends \
    rubygems build-essential ruby-dev \
    && rm -rf /var/lib/apt/lists/*

RUN npm install -gq gulp bower

RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
COPY . /usr/src/app

RUN npm install

CMD ["gulp", "start:dev"]

When I build the image, the npm install command executes with little output and really quickly. I actually build it through docker-compose which does have a volume mounted - and I cannot see the node_modules folder being created on my hose. When I launch a container on this image, I can see there is no node_modules folder. I then execute npm install and things start working - it takes 2-3 minutes to install all the packages and the node_modules folder is indeed created.

What is happening here? What am I doing wrong? Why doesn't npm install work at build time, but then it works at run time?

Body:
Also copying up the source and running npm install means that whenever the source code changes, the npm install step cache becomes invalid.

Instead, separate the steps/caches like so;

COPY package*.json ./
RUN npm install


问:
pipe data from 1 stream to 2 different streams depending on the data
I have 1 stream that has data coming that is prefixed with 2 different prefixes. let us say 1 and 0. I want all data that is prefixed with 1 to get piped only to stream A and 0 to stream B.

I have thought of just using 2 transforms that only allows data to pass if it has the correct prefix. I was just wondering if there was a more elegant way of doing this.

```<code>//an idea

//transformA is a transform that only pushes data that is prefixed with 1
//transformB is a transformt hat only pushes data that is prefixed with 2
incomingStream.pipe(transformA).pipe(destinationA)
incomingStream.pipe(transformB).pipe(destinationB)
</code>```

答:
Use for-await and if maybe?

```<code>for await (const chunk of incomingStream) {
    if(chunk.startsWith("1")) {
        destinationA.write(transformA(chunk));
        continue;
    }

    if(chunk.startsWith("2")) {
        destinationB.write(transformB(chunk));
        continue;
    }

    destinationElse.write(chunk);
}
</code>```

Body:
I have 1 stream that has data coming that is prefixed with 2 different prefixes. let us say 1 and 0. I want all data that is prefixed with 1 to get piped only to stream A and 0 to stream B.

I have thought of just using 2 transforms that only allows data to pass if it has the correct prefix. I was just wondering if there was a more elegant way of doing this.

//an idea

//transformA is a transform that only pushes data that is prefixed with 1
//transformB is a transformt hat only pushes data that is prefixed with 2
incomingStream.pipe(transformA).pipe(destinationA)
incomingStream.pipe(transformB).pipe(destinationB)

Body:
Use for-await and if maybe?

for await (const chunk of incomingStream) {
    if(chunk.startsWith("1")) {
        destinationA.write(transformA(chunk));
        continue;
    }

    if(chunk.startsWith("2")) {
        destinationB.write(transformB(chunk));
        continue;
    }

    destinationElse.write(chunk);
}


问:
setState() or markNeedsBuild() called during build exception prevents me from executing callback
I'm trying to execute a callback function once a timer ends in a particular widget but I keep getting this exception:

I/flutter (16413): Another exception was thrown: setState() or markNeedsBuild() called during build.

So I have this widget called countdown:

class Countdown extends StatefulWidget {
  final VoidCallback onCountdownExpire;

  Countdown(this.onCountdownExpire);

  @override
  CountdownState createState() => CountdownState();
}

class CountdownState extends State<Countdown> with TickerProviderStateMixin {
  AnimationController controller;

  String get timerString {
    Duration duration = controller.duration * controller.value;
    return '${duration.inMinutes}:${(duration.inSeconds % 60).toString()}';
  }

  @override
  void initState() {
    super.initState();
    controller = AnimationController(
      vsync: this,
      duration: Duration(seconds: 2),
    )..addStatusListener((AnimationStatus status){
        if (status == AnimationStatus.completed)
          widget.onCountdownExpire();
    });
    controller.reverse(from: 1.0);
  }
   ...
   ...
   ... // omitted code
}
```

<p>So once the animation is completed it will call the callback function:</p>

<pre class="lang-dart prettyprint-override"><code>class _QuizPageState extends State<QuizPage> {
  ... // omitted code

  @override
  void initState() {
   ... // omitted code
  }

  void onCountdownExpire() {
    setState(() {
      _topContentImage =  AssetImage(questions[questionNum++].imagePath);
    });
  }
  ... // omitted code
}
</code>```

I've tried to follow a solution but it does not work and gives me the same exception:

  void onCountdownExpire() =>
    setState(() {
      _topContentImage =  AssetImage(questions[questionNum++].imagePath);
    });
```

<p>I also tried this but to no avail:</p>

<pre class="lang-dart prettyprint-override"><code>  @override
  void initState() {
    super.initState();
    controller = AnimationController(
      vsync: this,
      duration: Duration(seconds: 2),
    )..addStatusListener((AnimationStatus status) =>
        (status == AnimationStatus.completed) ?
          widget.onCountdownExpire():null
    );
    controller.reverse(from: 1.0);
  }
</code>```

答:
maybe try including 'dart:async':

```<code>import 'dart:async';
</code>```

then try wrapping your call of the onCountdownExpire function in a short-lived Timer():

```<code>...
        Timer(
          Duration(milliseconds:50),
          () {
            if (status == AnimationStatus.completed)
              widget.onCountdownExpire();
          },
        );
...
</code>```

this will make the setState() happen outside the build phase of the last frame of your animation.

The error occurs most likely because the Countdown() is being redrawn as part of the redraw of the QuizPage() widget. Adding the Timer() will force the update to happen outside of the build() scope, in an async fashion, and will still achieve the same results without the error.

Body:
I'm trying to execute a callback function once a timer ends in a particular widget but I keep getting this exception:

I/flutter (16413): Another exception was thrown: setState() or markNeedsBuild() called during build.

So I have this widget called countdown:

class Countdown extends StatefulWidget {
  final VoidCallback onCountdownExpire;

  Countdown(this.onCountdownExpire);

  @override
  CountdownState createState() => CountdownState();
}

class CountdownState extends State<Countdown> with TickerProviderStateMixin {
  AnimationController controller;

  String get timerString {
    Duration duration = controller.duration * controller.value;
    return '${duration.inMinutes}:${(duration.inSeconds % 60).toString()}';
  }

  @override
  void initState() {
    super.initState();
    controller = AnimationController(
      vsync: this,
      duration: Duration(seconds: 2),
    )..addStatusListener((AnimationStatus status){
        if (status == AnimationStatus.completed)
          widget.onCountdownExpire();
    });
    controller.reverse(from: 1.0);
  }
   ...
   ...
   ... // omitted code
}

So once the animation is completed it will call the callback function:

class _QuizPageState extends State<QuizPage> {
  ... // omitted code

  @override
  void initState() {
   ... // omitted code
  }

  void onCountdownExpire() {
    setState(() {
      _topContentImage =  AssetImage(questions[questionNum++].imagePath);
    });
  }
  ... // omitted code
}

I've tried to follow a solution but it does not work and gives me the same exception:

  void onCountdownExpire() =>
    setState(() {
      _topContentImage =  AssetImage(questions[questionNum++].imagePath);
    });

I also tried this but to no avail:

  @override
  void initState() {
    super.initState();
    controller = AnimationController(
      vsync: this,
      duration: Duration(seconds: 2),
    )..addStatusListener((AnimationStatus status) =>
        (status == AnimationStatus.completed) ?
          widget.onCountdownExpire():null
    );
    controller.reverse(from: 1.0);
  }

Body:
maybe try including 'dart:async':

import 'dart:async';

then try wrapping your call of the onCountdownExpire function in a short-lived Timer():

...
        Timer(
          Duration(milliseconds:50),
          () {
            if (status == AnimationStatus.completed)
              widget.onCountdownExpire();
          },
        );
...

this will make the setState() happen outside the build phase of the last frame of your animation.

The error occurs most likely because the Countdown() is being redrawn as part of the redraw of the QuizPage() widget. Adding the Timer() will force the update to happen outside of the build() scope, in an async fashion, and will still achieve the same results without the error.


问:
When is it "acceptable" to use ViewBag/ViewData in ASP.NET MVC?
I realize that the best practice is to use strongly typed Views and pass in all needed data in a ViewModel, but I am curious if there are situations where it is actually considered "best practice" to pass data in the ViewBag/ViewData.

In what scenarios is the ViewBag/ViewData preferred for passing data to a view?

update

It's great to hear the various uses everyone has come up with for ViewBag/ViewData. We may never arrive at a "best practice" but it will be great to see the different solutions people have come up with that rely on the ViewBag/ViewData.

答: I use them rarely, for bits of information that are totally unrelated to the model or view model that I'm passing to the view, again, most of the times I use a view model</p>


问:
Parameter is string but still getting this warning: Warning: mysqli::query() expects parameter 1 to be string
I want to update my mysql database of username however, whenever my username contains any numbers (despite being overall a string), it will still output
Warning: mysqli::query() expects parameter 1 to be string, object given in

I've tried to use it without prepare and bind param, which works.

function setUsername($guid, $username2) {
        global $serverName, $username, $password, $database;
        $conn = new mysqli($serverName, $username, $password, $database);
        $username2 = $username2 . "";
        $query = $conn->prepare("UPDATE players SET username = ? WHERE guid = ?");
        $query->bind_param("si", $username2, $guid);
        $conn->query($query);
    }
```

I expected this to update successfully. However, if I include any numbers within the string, such as
awefw1afweaw, it will output Warning: mysqli::query() expects parameter 1 to be string, object given in

答:
You can't use $conn->query() with a prepared statement. $conn->prepare() returns a mysqli_stmt object, that you are passing to $conn->query(mysqli_stmt), and is the cause of your error message.

Instead you would need to replace $conn->query() with $query->execute();

```<code>function setUsername($guid, $username2) {
    global $serverName, $username, $password, $database;
    $conn = new mysqli($serverName, $username, $password, $database);
    $username2 = $username2 . "";
    $query = $conn->prepare("UPDATE players SET username = ? WHERE guid = ?");
    $query->bind_param("si", $username2, $guid);
    $query->execute();
}
</code>```

Body:
I want to update my mysql database of username however, whenever my username contains any numbers (despite being overall a string), it will still output
Warning: mysqli::query() expects parameter 1 to be string, object given in

I've tried to use it without prepare and bind param, which works.

function setUsername($guid, $username2) {
        global $serverName, $username, $password, $database;
        $conn = new mysqli($serverName, $username, $password, $database);
        $username2 = $username2 . "";
        $query = $conn->prepare("UPDATE players SET username = ? WHERE guid = ?");
        $query->bind_param("si", $username2, $guid);
        $conn->query($query);
    }

I expected this to update successfully. However, if I include any numbers within the string, such as
awefw1afweaw, it will output Warning: mysqli::query() expects parameter 1 to be string, object given in

Body:
You can't use $conn->query() with a prepared statement. $conn->prepare() returns a mysqli_stmt object, that you are passing to $conn->query(mysqli_stmt), and is the cause of your error message.

Instead you would need to replace $conn->query() with $query->execute();

function setUsername($guid, $username2) {
    global $serverName, $username, $password, $database;
    $conn = new mysqli($serverName, $username, $password, $database);
    $username2 = $username2 . "";
    $query = $conn->prepare("UPDATE players SET username = ? WHERE guid = ?");
    $query->bind_param("si", $username2, $guid);
    $query->execute();
}


问:
How to make sure the following function did not over-allocate?
I'm trying to make a function that gets number of columns and rows (width and height), build a 2D matrix, and then return the address of Matrix[0][0] back to a pointer in the original caller-function.

```<code>int **allocateMatrix(int width, int height) // function that allocate
//memory for 2D matrix and check that memory allocation was successful
{
    int **Matrix;
    int row;
    Matrix = (int**)malloc(sizeof(int*)*height);
    if (!Matrix)
    {
        printf("failed to allocate memory. this program is over.\n");
        exit(1);
    }
    for (row = 0; row < height; row++)
    {   Matrix[row] = (int*)malloc(sizeof(int)*width);
      if (!Matrix[row])
      {
        printf("failed to allocate memory. this program is over.\n");
        exit(1);
      }
    }
    return Matrix;
}
</code>```

during the allocating i watched the whole thing through the debugger and it seems to create a way-too-big matrix then i intended, and an unexpected behavior in general.
such as: height =5, width =5,
though Matrix[0][30] - exist and reachable.

moreover, Im not sure about the address im returning.

答:
There is nothing wrong with your allocation scheme, but there are a number of improvements than can be made. If your debugger is reporting a 30-element row is reachable -- there is something wrong with how you are looking at the information.

First, there is no need to cast the return of malloc, it is unnecessary. See: Do I cast the result of malloc?.

Avoid exit in allocation functions. The caller should have the option of gracefully handling the failure-to-allocate rather than your program exiting at that point. While exit is valid, it severely limits your options for handling the failure. Instead, return a valid pointer on success, or NULL otherwise, and let the caller handle the error. In the case of a failed allocation, it is up to you to free() all previous allocations before returning NULL.

Consider using calloc to allocate storage for matrix[row]. calloc sets all bytes allocated to zero effectively initializing each element for each row to 0 preventing Undefined Behavior on the inadvertent access of an uninitialized element after return.

Putting all the pieces together, you could do something similar to:

```<code>/* allocatematrix allocates storage for a width x height matrix of type int.
 * all elements are initialized zero. on success returns a pointer to pointer
 * to type, otherwise all allocations are freed and NULL is returned.
 */
int **allocatematrix (int width, int height)
{
    int **matrix;
    int row;    /* declare row in for loop declaration, unless c89 support needed */

    matrix = malloc (height * sizeof *matrix);  /* allocate pointers */
    if (!matrix) {                  /* validate */
        perror ("malloc-matrix");   /* malloc failure set errno, use it */
        return NULL;                /* evaluate return in caller */
    }

    for (row = 0; row < height; row++) {    /* for each pointer */
        matrix[row] = calloc (width, sizeof *matrix[row]);  /* alloc rows */
        if (!Matrix[row]) {         /* validate */
            perror ("calloc-matrix[row]");  /* ditto for calloc */
            while (row--)           /* loop over previous rows */
                free (matrix[row]); /* free previously allocated rows */
            free (matrix);          /* free pointers */
            return NULL;            /* evaluate return in caller */
        }
    }

    return matrix;  /* return initial pointer address */
}
</code>```

(note: while not an error, C generally avoids the use of camelCase or MixedCase variable and function names in favor of all lower-case while reserving upper-case names for use with macros and constants. It is a matter of style -- so it is completely up to you)

(also note: the use of perror instead of printf for error reporting. When a function sets errno on failure, perror should be used. Further it already provides output on stderr. If dealing with a failure where errno isn't set, the use fprintf (if a conversion is needed) or fputs otherwise and report the error on stderr instead of stdout)

Look things over and let me know if you have further questions.

Body:
I'm trying to make a function that gets number of columns and rows (width and height), build a 2D matrix, and then return the address of Matrix[0][0] back to a pointer in the original caller-function.

int **allocateMatrix(int width, int height) // function that allocate
//memory for 2D matrix and check that memory allocation was successful
{
    int **Matrix;
    int row;
    Matrix = (int**)malloc(sizeof(int*)*height);
    if (!Matrix)
    {
        printf("failed to allocate memory. this program is over.\n");
        exit(1);
    }
    for (row = 0; row < height; row++)
    {   Matrix[row] = (int*)malloc(sizeof(int)*width);
      if (!Matrix[row])
      {
        printf("failed to allocate memory. this program is over.\n");
        exit(1);
      }
    }
    return Matrix;
}

during the allocating i watched the whole thing through the debugger and it seems to create a way-too-big matrix then i intended, and an unexpected behavior in general.
such as: height =5, width =5,
though Matrix[0][30] - exist and reachable.

moreover, Im not sure about the address im returning.

Body:
There is nothing wrong with your allocation scheme, but there are a number of improvements than can be made. If your debugger is reporting a 30-element row is reachable -- there is something wrong with how you are looking at the information.

First, there is no need to cast the return of malloc, it is unnecessary. See: Do I cast the result of malloc?.

Avoid exit in allocation functions. The caller should have the option of gracefully handling the failure-to-allocate rather than your program exiting at that point. While exit is valid, it severely limits your options for handling the failure. Instead, return a valid pointer on success, or NULL otherwise, and let the caller handle the error. In the case of a failed allocation, it is up to you to free() all previous allocations before returning NULL.

Consider using calloc to allocate storage for matrix[row]. calloc sets all bytes allocated to zero effectively initializing each element for each row to 0 preventing Undefined Behavior on the inadvertent access of an uninitialized element after return.

Putting all the pieces together, you could do something similar to:

/* allocatematrix allocates storage for a width x height matrix of type int.
 * all elements are initialized zero. on success returns a pointer to pointer
 * to type, otherwise all allocations are freed and NULL is returned.
 */
int **allocatematrix (int width, int height)
{
    int **matrix;
    int row;    /* declare row in for loop declaration, unless c89 support needed */

    matrix = malloc (height * sizeof *matrix);  /* allocate pointers */
    if (!matrix) {                  /* validate */
        perror ("malloc-matrix");   /* malloc failure set errno, use it */
        return NULL;                /* evaluate return in caller */
    }

    for (row = 0; row < height; row++) {    /* for each pointer */
        matrix[row] = calloc (width, sizeof *matrix[row]);  /* alloc rows */
        if (!Matrix[row]) {         /* validate */
            perror ("calloc-matrix[row]");  /* ditto for calloc */
            while (row--)           /* loop over previous rows */
                free (matrix[row]); /* free previously allocated rows */
            free (matrix);          /* free pointers */
            return NULL;            /* evaluate return in caller */
        }
    }

    return matrix;  /* return initial pointer address */
}

(note: while not an error, C generally avoids the use of camelCase or MixedCase variable and function names in favor of all lower-case while reserving upper-case names for use with macros and constants. It is a matter of style -- so it is completely up to you)

(also note: the use of perror instead of printf for error reporting. When a function sets errno on failure, perror should be used. Further it already provides output on stderr. If dealing with a failure where errno isn't set, the use fprintf (if a conversion is needed) or fputs otherwise and report the error on stderr instead of stdout)

Look things over and let me know if you have further questions.


问:
Is there any way to make Visual Studio C++ error output useful?
I find VS19 output quite useless when working on C++ project. Consider running the example code on freshly installed VS19:

```<code>#include <iostream>

using namespace std;
class My
{
    public:
    void f() noexcept
    {
        throw exception{"A problem sir!"};
    }
};

int main()
{
    try
    {
        My m;
        m.f();
    }
    catch (exception& ex)
    {
        cout << "exception caught! " << ex.what() << endl;
    }
    return 0;
}
</code>```

What I would like to receive is: "Function throws an exception while marked as noexcept", and the cursor set on the problematic line. What I get is a new window with some general text, none of which mentions the problem, or where the problem is.

答:
Trying to resolve your puzzle in your question:

What I get is a new window with some general text, none of which
  mentions the problem, or where the problem is.

I find 90% of output useless for me.

I think what you mean is the Output window, it is always used to display output about build process.

Also, You can also program your own applications to write diagnostic messages at run time to an Output pane. To do this, use members of the Debug class or Trace class in the System.Diagnostics namespace of the .NET Framework Class Library.

For those large solution or large project, which has plenty of resource files. The build sometimes fail with unknown error. The output window is necessary for trouble-shooting.

If you think most of its info is useless,like P.PICARD suggests: Go Tools=>Projects and Solutions=>Build and Run to set its build output verbosity(!Not build log file verbosity) I suggest you change it to Minimal.

If you have a failed build and want to watch the details of the whole build process. Change it to Detailed and rebuild the project or solution.

What I would like to receive is: "Function throws an exception while
  marked as noexcept", and the cursor set on the problematic line.

Have you checked the Error List window? If it disappeared,choose View > Error List, or press Ctrl++E.

Add two lines to your code sample:

```<code>int main()
{
    int a = 2;
    int b;
...
}
</code>```

Navigate to the Error List window(I suggest you set it as Build and Intellisense):

I think it's what you want. And error list window also indicates the Variable which is not initialized or not referenced for improving your coding.

Also, you can see their line numbers. And Double-click the error message, the cursor will navigate to that line.

For C++ program, the warning level is from w0 to w4, you can set it w4 to get the high warning level.(By default it should be w3)

Right-click project=>properties=>Configuration Properties=>C/C++=>Warning Level to set it. (Have been described by Blastfurance, thanks to him!)

Change it to w0, nothing shows. Change it to w3, and it will show warnings about My::f and b but not a.(Actually I don't think you make changes to that, because w3 is by default) Change it to w4 then get the high warning level and all associated warnings display.

Body:
I find VS19 output quite useless when working on C++ project. Consider running the example code on freshly installed VS19:

#include <iostream>

using namespace std;
class My
{
    public:
    void f() noexcept
    {
        throw exception{"A problem sir!"};
    }
};

int main()
{
    try
    {
        My m;
        m.f();
    }
    catch (exception& ex)
    {
        cout << "exception caught! " << ex.what() << endl;
    }
    return 0;
}

What I would like to receive is: "Function throws an exception while marked as noexcept", and the cursor set on the problematic line. What I get is a new window with some general text, none of which mentions the problem, or where the problem is.

Body:
Trying to resolve your puzzle in your question:

What I get is a new window with some general text, none of which
  mentions the problem, or where the problem is.

I find 90% of output useless for me.

I think what you mean is the Output window, it is always used to display output about build process.

Also, You can also program your own applications to write diagnostic messages at run time to an Output pane. To do this, use members of the Debug class or Trace class in the System.Diagnostics namespace of the .NET Framework Class Library.

For those large solution or large project, which has plenty of resource files. The build sometimes fail with unknown error. The output window is necessary for trouble-shooting.

If you think most of its info is useless,like P.PICARD suggests: Go Tools=>Projects and Solutions=>Build and Run to set its build output verbosity(!Not build log file verbosity) I suggest you change it to Minimal.

If you have a failed build and want to watch the details of the whole build process. Change it to Detailed and rebuild the project or solution.

What I would like to receive is: "Function throws an exception while
  marked as noexcept", and the cursor set on the problematic line.

Have you checked the Error List window? If it disappeared,choose View > Error List, or press Ctrl++E.

Add two lines to your code sample:

int main()
{
    int a = 2;
    int b;
...
}

Navigate to the Error List window(I suggest you set it as Build and Intellisense):

I think it's what you want. And error list window also indicates the Variable which is not initialized or not referenced for improving your coding.

Also, you can see their line numbers. And Double-click the error message, the cursor will navigate to that line.

For C++ program, the warning level is from w0 to w4, you can set it w4 to get the high warning level.(By default it should be w3)

Right-click project=>properties=>Configuration Properties=>C/C++=>Warning Level to set it. (Have been described by Blastfurance, thanks to him!)

Change it to w0, nothing shows. Change it to w3, and it will show warnings about My::f and b but not a.(Actually I don't think you make changes to that, because w3 is by default) Change it to w4 then get the high warning level and all associated warnings display.


问:
Check if two rows in pandas DataFrame has same set of values regard & regardless of column order
I have two dataframe with same index but different column names. Number of columns are the same. I want to check, index by index, 1) whether they have same set of values regardless of column order, and 2) whether they have same set of values regarding column order.

ind = ['aaa', 'bbb', 'ccc']
df1 = pd.DataFrame({'old1': ['A','A','A'], 'old2': ['B','B','B'], 'old3': ['C','C','C']}, index=ind)
df2 = pd.DataFrame({'new1': ['A','A','A'], 'new2': ['B','C','B'], 'new3': ['C','B','D']}, index=ind)
```

<p>This is the output I need.</p>

```     OpX   OpY
-------------
aaa  True  True
bbb  False True
ccc  False False
```

Could anyone help me with OpX and OpY?

答:
For item 2):

```<code>(df1.values == df2.values).all(axis=1)
</code>```

This checks element-wise equality of the dataframes, and gives True when all entries in a row are equal.

For item 1), sort the values along each row first:

```<code>import numpy as np
(np.sort(df1.values, axis=1) == np.sort(df2.values, axis=1)).all(axis=1)
</code>```

Body:
I have two dataframe with same index but different column names. Number of columns are the same. I want to check, index by index, 1) whether they have same set of values regardless of column order, and 2) whether they have same set of values regarding column order.

ind = ['aaa', 'bbb', 'ccc']
df1 = pd.DataFrame({'old1': ['A','A','A'], 'old2': ['B','B','B'], 'old3': ['C','C','C']}, index=ind)
df2 = pd.DataFrame({'new1': ['A','A','A'], 'new2': ['B','C','B'], 'new3': ['C','B','D']}, index=ind)

This is the output I need.

     OpX   OpY
-------------
aaa  True  True
bbb  False True
ccc  False False

Could anyone help me with OpX and OpY?

Body:
For item 2):

(df1.values == df2.values).all(axis=1)

This checks element-wise equality of the dataframes, and gives True when all entries in a row are equal.

For item 1), sort the values along each row first:

import numpy as np
(np.sort(df1.values, axis=1) == np.sort(df2.values, axis=1)).all(axis=1)


问:
What dependency is missing for org.springframework.web.bind.annotation.RequestMapping?
What dependency am I missing? I am currently using:

```<code><dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>3.0.5.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>3.0.5.RELEASE</version>
</dependency>
</code>```

The error Im getting is:
The import org.springframework.web.bind cannot be resolved

答:
Add this below dependency in your pom.xml

```<code><dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
</dependency>
</code>```

This is used for @RestController, @RequestMapping

Body:
What dependency am I missing? I am currently using:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>3.0.5.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>3.0.5.RELEASE</version>
</dependency>

The error Im getting is:
The import org.springframework.web.bind cannot be resolved

Body:
Add this below dependency in your pom.xml

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
</dependency>

This is used for @RestController, @RequestMapping


问:
Update by query not working, elastic search python
I have about 2000+ documents with the file name 'Contact.txt', I am trying to amend a field called text: {class: 'contact'} for all of these files, by doing the following:

```<code>    q = {
        "script": {
            "inline": "ctx._source.text.class='contact'",
            "lang": "painless"
        },
        "query": {
            "match": {
                "name": "Contact.txt"
            },

        }
    }

    try:
        es.update_by_query(body=q, index='index_name')
    except Exception as e:
        print(e)
</code>```

My try/catch is giving me the error:

```<code>TransportError(500, 'script_exception', 'runtime error')
</code>```

答:
The text field doesn't exist in the documents so, the update script should be as below:

```<code>{
  "script": {
    "source": "ctx._source['text'] = params.text",
    "params": {
      "text": {
        "class": "contact"
      }
    },
    "lang": "painless"
  },
  "query": {
    "match": {
      "name": "Contact.txt"
    }
  }
}
</code>```

Body:
I have about 2000+ documents with the file name 'Contact.txt', I am trying to amend a field called text: {class: 'contact'} for all of these files, by doing the following:

    q = {
        "script": {
            "inline": "ctx._source.text.class='contact'",
            "lang": "painless"
        },
        "query": {
            "match": {
                "name": "Contact.txt"
            },

        }
    }

    try:
        es.update_by_query(body=q, index='index_name')
    except Exception as e:
        print(e)

My try/catch is giving me the error:

TransportError(500, 'script_exception', 'runtime error')

Body:
The text field doesn't exist in the documents so, the update script should be as below:

{
  "script": {
    "source": "ctx._source['text'] = params.text",
    "params": {
      "text": {
        "class": "contact"
      }
    },
    "lang": "painless"
  },
  "query": {
    "match": {
      "name": "Contact.txt"
    }
  }
}


问:
instance of class held by composition container in mef
I understand that a MEF CompositionContainer creates and keeps instances of classes. I don't know under what circumstances a CompositionContainer has a class instance in its bowels.

Can anybody list operations performed on the CompositionContainer or methods of the CompositionContainer class that cause the CompositionContainer to store an instance of a class within the CompositionContainer.

Is it possible to view class instances held within a CompositionContainer in the debugger or any other fashion?

答:
The CompositionContainer will keep references to all shared parts for the lifetime of the CompositionContainer.  (The default CreationPolicy is Any for both imports and exports, which means by default all parts will be shared unless otherwise specified.)

References to NonShared parts will be kept if the part implements IDisposable.  The reference will be released when the root export that was pulled from the container is released (if that export was from a NonShared part).  Exports can be released either by calling CompositionContainer.ReleaseExport, or ExportLifetimeContext.Dispose for exports created with an ExportFactory.

I don't think there's any simple way to view what's held by the CompositionContainer.  The source code is available so you could theoretically dive into it and figure out exactly where it's stored.


问:
What is the format of azure "scopes"?
In the description of the az ad sp create-for-rbac command there is a --scopes parameter. It is defined as:

--scopes
  Space-separated list of scopes the service principal's role assignment applies to. Defaults to the root of the current subscription.

There is also an example given:

```<code>--scopes /subscriptions/{SubID}/resourceGroups/{ResourceGroup1}
</code>```

However it is not clear what is the general format of the scopes. That is can to level be something else than resource groups? Can we drill down to individual resources withing a resource group? How?

How do I get the correct value for this parameter to be able to scope the account access to a particular individual resource? How do I specify the path?

Is it possible somehow to list children of an arbitrary scope?

答:
The scopes are IDs of resources that you want to grant access to. They can be obtained with the help of the az resource list command. For example:

az resource list --location westus
```

<p>The result will contain an <code>id</code> field, that will contain the scope you are looking for, such as:</p>

<pre class="lang-sh prettyprint-override"><code>"/subscriptions/0db1a886-c5b6-49fb-a7de-23f5cd6579d3/resourceGroups/hugo-blog/providers/microsoft.cdn/profiles/hugo-cdn"
</code>```

Title: What is the format of azure "scopes"?

Body:
In the description of the az ad sp create-for-rbac command there is a --scopes parameter. It is defined as:

--scopes
  Space-separated list of scopes the service principal's role assignment applies to. Defaults to the root of the current subscription.

There is also an example given:

--scopes /subscriptions/{SubID}/resourceGroups/{ResourceGroup1}

However it is not clear what is the general format of the scopes. That is can to level be something else than resource groups? Can we drill down to individual resources withing a resource group? How?

How do I get the correct value for this parameter to be able to scope the account access to a particular individual resource? How do I specify the path?

Is it possible somehow to list children of an arbitrary scope?

Body:
The scopes are IDs of resources that you want to grant access to. They can be obtained with the help of the az resource list command. For example:

az resource list --location westus

The result will contain an id field, that will contain the scope you are looking for, such as:

"/subscriptions/0db1a886-c5b6-49fb-a7de-23f5cd6579d3/resourceGroups/hugo-blog/providers/microsoft.cdn/profiles/hugo-cdn"


问:
HTML5 email input cannot assign ID and RUNAT="Server" ASP.NET 4
Hi I am trying to assign an ID to an HTML5 input so that i can access its value from the code behind in the web form. However with the this code:

```<code> <input type="email" required autofocus placeholder="Email Address" class="txt-input txt-input-username" ID="myTextBox" runat="server" />
</code>```

Visual Studio 2010 is telling me that it cannot resolve the symbol ID="myTextBox".

Any ideas on how i can fix this because i have been searching for an answer for nearly a day? thanks

答:
If you are using vb.net :

In .aspx page

```<code>   <input id="myTextBox" runat="server"/>
</code>```

Avoid type="email/date/mob" in  input tag, it may produce parse error

In .vb page, in PageLoad()

```<code>   myTextBox.Attributes.Add("type","email")
</code>```

Body:
Hi I am trying to assign an ID to an HTML5 input so that i can access its value from the code behind in the web form. However with the this code:

 <input type="email" required autofocus placeholder="Email Address" class="txt-input txt-input-username" ID="myTextBox" runat="server" />

Visual Studio 2010 is telling me that it cannot resolve the symbol ID="myTextBox".

Any ideas on how i can fix this because i have been searching for an answer for nearly a day? thanks

Body:
If you are using vb.net :

In .aspx page

   <input id="myTextBox" runat="server"/>

Avoid type="email/date/mob" in  input tag, it may produce parse error

In .vb page, in PageLoad()

   myTextBox.Attributes.Add("type","email")


问:
RDCOMClient + Outlook email search using date interval in R
I am trying to search outlook mail giving date as parameter in search.

right now I am searching full mailbox then filtering on the basis of received date but problem is by this way it is reading all mail each time. I want a solution where I can search directly by date interval so that it will return mails falling in between date interval.

```<code>library(RDCOMClient)

outlook_app <- COMCreate("Outlook.Application")
search<-outlook_app$AdvancedSearch("Inbox","urn:schemas:mailheader:date > '2019-05-22 00:14:10 IST'")
results <- search$Results()
results$Count()
</code>```

I tried this but it is not working for me. I want all mails came after mentioned date.

答: Do not specify the time zone (IST). '2019-05-22 00:14:10' is what you need.</p>

Body:
I am trying to search outlook mail giving date as parameter in search.

right now I am searching full mailbox then filtering on the basis of received date but problem is by this way it is reading all mail each time. I want a solution where I can search directly by date interval so that it will return mails falling in between date interval.

library(RDCOMClient)

outlook_app <- COMCreate("Outlook.Application")
search<-outlook_app$AdvancedSearch("Inbox","urn:schemas:mailheader:date > '2019-05-22 00:14:10 IST'")
results <- search$Results()
results$Count()

I tried this but it is not working for me. I want all mails came after mentioned date.


问:
Convert a Long/ULong to an unsigned hexadecimal string with padding zeros
How to convert a Long/ULong representing an unsigned long to an unsigned hexadecimal string with padding zeros (a 16-digit hexadecimal string)?

I am looking for a simple and neat solution in Kotlin or Java.

答:
```<code>val mutableList = listOf(121212L, 121212121212L,-1L)
mutableList.forEach {
    println(it.toULong().toString(16).padStart(16, '0'))
}
</code>```

it gives

```<code>000000000001d97c
0000001c38ce307c
ffffffffffffffff
</code>```

Edited: Credit to Ilya in the comment for the missing toULong part.

Body:
val mutableList = listOf(121212L, 121212121212L,-1L)
mutableList.forEach {
    println(it.toULong().toString(16).padStart(16, '0'))
}

it gives

000000000001d97c
0000001c38ce307c
ffffffffffffffff

Edited: Credit to Ilya in the comment for the missing toULong part.


答:
Construct a new DataFrame and check the equality:

```<code>df3 = pd.DataFrame(index=ind)
df3['OpX'] = (df1.values == df2.values).all(1)
df3['OpY'] = (df1.apply(np.sort, axis=1).values == df2.apply(np.sort, axis=1).values).all(1)
print(df3)
</code>```

Output:

```<code>       OpX    OpY
aaa   True   True
bbb  False   True
ccc  False  False
</code>```

Title: Check if two rows in pandas DataFrame has same set of values regard & regardless of column order

Body:
Construct a new DataFrame and check the equality:

df3 = pd.DataFrame(index=ind)
df3['OpX'] = (df1.values == df2.values).all(1)
df3['OpY'] = (df1.apply(np.sort, axis=1).values == df2.apply(np.sort, axis=1).values).all(1)
print(df3)

Output:

       OpX    OpY
aaa   True   True
bbb  False   True
ccc  False  False


问:
How do I get this javascript to run every second?
How do I get this javascript to run every second?

source code:

```<code><script type="text/javascript">
$(function() {
    //More Button
    $('.more').live("click",function()  {
        var ID = $(this).attr("id");
        if(ID) {
            $("#more"+ID).html('<img src="moreajax.gif" />');

            $.ajax({
                type: "POST",
                url: "ajax_more.php",
                data: "lastmsg="+ ID,
                cache: false,
                success: function(html){
                    $("ol#updates").prepend(html);
                    $("#more"+ID).remove();
                }
            });
        } else {
            $(".morebox").html('no posts to display');
        }

        return false;

    });
});

</script>
</code>```

答:
```<code>window.setTimeout(func,1000);
</code>```

This will run func after 1000 milliseconds. So at the end of func you can call window.setTimeout again to go in a loop of 1 sec. You just need to define a terminate condition.

Reference

Body:
window.setTimeout(func,1000);

This will run func after 1000 milliseconds. So at the end of func you can call window.setTimeout again to go in a loop of 1 sec. You just need to define a terminate condition.

Reference


问:
How to make field visibility in Kentico forms work based on two conditions
I am trying to make field visibility in my online form show up based on two criteria.
I have a check box with 4 items and I want the next field to show up if either field one or field one and two are selected.

The right dependent field boxes are all ticked.

I have tried the following:

```<code>aquatic_type.Value == "25m pool" || aquatic_type.Value == ("50m pool","25m pool")

aquatic_type.Value == "25m pool" || aquatic_type.Value == ("50m pool" && "25m pool")
</code>```

It will then work if I only select 25m pool but if I select 25m and 50m the field won't show up at all.

Can someone provide me with the structure for how OR works, and two criteria?

答:
Your macro should look like this:

```<code>aquatic_type.Value == "25m pool" || aquatic_type.Value == "50m pool"
</code>```

Kentico K# Macro syntax is very similar in nature to C#

Also since your field can contain both "25m pool" and "50m pool" you might try checking either value like so:

```<code>aquatic_type.Value.Contains("25m pool") || aquatic_type.Value.Contains("50m pool")
</code>```

Body:
I am trying to make field visibility in my online form show up based on two criteria.
I have a check box with 4 items and I want the next field to show up if either field one or field one and two are selected.

The right dependent field boxes are all ticked.

I have tried the following:

aquatic_type.Value == "25m pool" || aquatic_type.Value == ("50m pool","25m pool")

aquatic_type.Value == "25m pool" || aquatic_type.Value == ("50m pool" && "25m pool")

It will then work if I only select 25m pool but if I select 25m and 50m the field won't show up at all.

Can someone provide me with the structure for how OR works, and two criteria?

Body:
Your macro should look like this:

aquatic_type.Value == "25m pool" || aquatic_type.Value == "50m pool"

Kentico K# Macro syntax is very similar in nature to C#

Also since your field can contain both "25m pool" and "50m pool" you might try checking either value like so:

aquatic_type.Value.Contains("25m pool") || aquatic_type.Value.Contains("50m pool")


问:
Could the STAN number be repeteable and random?
I'm developing a Connector with some bank, and we're using the ISO8583 protocol, right now, i'm setting the STAN(field 11) with some random number generated with a random generator but sometimes I have some number collisions, the question is, could I safely use this generator or do I need to make the STAN a sequential number?

Thanks in advance.

答: Depends on your remote endpoint, but I've seen many requiring sequential numbers, and detecting duplicates.</p>


问:
cocoapods can't find simulators, pod repo push fails
I'm trying to push a private pod. When I do it, I get this error:

- ERROR | [iOS] unknown: Encountered an unknown error (Could not find aiossimulator (valid values: ). Ensure that Xcode -> Window -> Devices has at least oneiossimulator listed or otherwise add one.) during validation.

I'm running Xcode 10, and I recently had Xcode 10.1 beta on my machine.
Also, I had regular cocoapods (1.5.3) and the latest beta of that (1.6.0.beta.1).

To reduce complexity, I removed both betas from my machine. So, just the released versions. I'm still seeing this error.

I can't imagine what could've happened here. But something is out of whack. I'd really prefer to not completely remove Xcode, or do something else more drastic. But I'm totally stuck.

Other people on my team are able to pull the code, and do a pod repo push, but I can't from my own machine.

Thanks for any help/advice.

答:
even i try to use $gem insall cocoapods but cocoapods version is still the low version , at last i find the way to update your cocoapods

```<code>$ sudo gem install -n /usr/local/bin cocoapods --pre
</code>```

and then my cocoapod --version show out  is 1.7.1
wonderful so i fix the question!

Body:
even i try to use $gem insall cocoapods but cocoapods version is still the low version , at last i find the way to update your cocoapods

$ sudo gem install -n /usr/local/bin cocoapods --pre

and then my cocoapod --version show out  is 1.7.1
wonderful so i fix the question!


问:
Is it possible to deep link to a specific revision of an Azure DevOps wiki page?
I would like to generate a hyperlink to a read-only view of a specific revision of an Azure DevOps wiki page.  The links provided on the Revisions page navigate to a commit review page with compare and preview tabs and include a Revert button (when permitted).

I have tried

https://dev.azure.com/[organization]/[project]/_wiki/wikis/[project].wiki?pagePath=%2Fpath%2Fto%2Fpage&version=[ETag] but the version is ignored and the latest revision is displayed.

https://dev.azure.com/[organization]/[project]/_wiki/wikis/[project].wiki?pagePath=%2Fpath%2Fto%2Fpage&version=[commithash] but the version is ignored and the latest revision is displayed.

https://dev.azure.com/[organization]/[project]/_wiki/wikis/[project].wiki?_a=compare&wikiVersion=GBwikiMaster&pagePath=%2Fpath%2Fto%2Fpage&version=[ETag]&view=preview which is viable but undesirable due to the risk of misguided reverts.

答: If you only set read-only permissions on Wiki security, the page you get using the third form of link has no Revert button, so there should be no risk of misguided reverts.


问:
How to filter data properties coming from API in PHP?
I have this data coming from an API, the tmdb api, and I want to create an api to filter the data and expose just the properties I need. In this case I just want my endpoint to expose id, title, and overview and nothing else. How can filter these properties with PHP in order to get and expose just the properties I need?

```<code>"results:[{
"vote_count": 779,
"id": 420817,
"video": false,
"vote_average": 7.2,
"title": "Aladdin",
"popularity": 476.676,
"poster_path": "/3iYQTLGoy7QnjcUYRJy4YrAgGvp.jpg",
"original_language": "en",
"original_title": "Aladdin",
"genre_ids": [
12,
14,
10749,
35,
10751
],
"backdrop_path": "/v4yVTbbl8dE1UP2dWu5CLyaXOku.jpg",
"adult": false,
"overview": "A kindhearted street..."
}],
</code>```

The expected result should be:
myapi.com/api

```<code>"results:[{
"id": 420817,
"title": "Aladdin",
"overview": "A kindhearted street ..."
}],
</code>```

答:
You can filter the array like this:

```<code>function myFilter($result) {

    $filtered_array = array();

    foreach($result as $movie) {

        $filtered_movie = array();

        $filtered_movie['id'] = $movie['id'];
        $filtered_movie['title'] = $movie['title'];
        $filtered_movie['overview'] = $movie['overview'];

        array_push($filtered_array, $filtered_movie);

    }

    return $filtered_array;
}

</code>```

Just pass the unfiltered array to the function and you'll get the filtered one back.

EDIT:

If your data is in JSON format you will need to use json_decode() to turn it in to an array in PHP. And if you want to return it as JSON then use json_encode() for that.

Body:
I have this data coming from an API, the tmdb api, and I want to create an api to filter the data and expose just the properties I need. In this case I just want my endpoint to expose id, title, and overview and nothing else. How can filter these properties with PHP in order to get and expose just the properties I need?

"results:[{
"vote_count": 779,
"id": 420817,
"video": false,
"vote_average": 7.2,
"title": "Aladdin",
"popularity": 476.676,
"poster_path": "/3iYQTLGoy7QnjcUYRJy4YrAgGvp.jpg",
"original_language": "en",
"original_title": "Aladdin",
"genre_ids": [
12,
14,
10749,
35,
10751
],
"backdrop_path": "/v4yVTbbl8dE1UP2dWu5CLyaXOku.jpg",
"adult": false,
"overview": "A kindhearted street..."
}],

The expected result should be:
myapi.com/api

"results:[{
"id": 420817,
"title": "Aladdin",
"overview": "A kindhearted street ..."
}],

Body:
You can filter the array like this:

function myFilter($result) {

    $filtered_array = array();

    foreach($result as $movie) {

        $filtered_movie = array();

        $filtered_movie['id'] = $movie['id'];
        $filtered_movie['title'] = $movie['title'];
        $filtered_movie['overview'] = $movie['overview'];

        array_push($filtered_array, $filtered_movie);

    }

    return $filtered_array;
}

Just pass the unfiltered array to the function and you'll get the filtered one back.

EDIT:

If your data is in JSON format you will need to use json_decode() to turn it in to an array in PHP. And if you want to return it as JSON then use json_encode() for that.


问:
SDL 2, how use the event system and draw asynchronously
You can only use the event system and the drawing system where it's initialized, and they have to be on the same thread,

wondering how if the polling system yields until an event is fired via

```<code>SDL_WaitEvent(&event);
</code>```

how would I say, draw something at 60fps whilst still being able to take input from the user? I assume there's a timer event? Or are you not even supposed to use SDL_WaitEvent....

Wondering how I should structure my game

答:
Most game engines don't require asynchronous rendering, you typically have a loop where you update then render (more practically you have a fixed number of updates and a dynamic number of renders). SDL_WaitEvent is blocking and probably isn't what you want. You probably want SDL_PollEvent which is non blocking. You typically keep polling events until there are no more events.

The general loop looks something like

```<code>void gameLoop()
{
    while(true)
    {
        update();
        render();
    }
}
</code>```

and you would have your update function be something like

```<code>void update()
{
    SDL_Event event;
    while(SDL_PollEvent(&event))
    {
        // Handle Event
    }
    // Other Update Logic
}
</code>```

This will keep calling polling events until there are no more in the queue, at which point SDL_PollEvent returns 0 thus ending the event loop. From there you can go on to perform other update logic that isn't dependent on system events.

Body:
You can only use the event system and the drawing system where it's initialized, and they have to be on the same thread,

wondering how if the polling system yields until an event is fired via

SDL_WaitEvent(&event);

how would I say, draw something at 60fps whilst still being able to take input from the user? I assume there's a timer event? Or are you not even supposed to use SDL_WaitEvent....

Wondering how I should structure my game

Body:
Most game engines don't require asynchronous rendering, you typically have a loop where you update then render (more practically you have a fixed number of updates and a dynamic number of renders). SDL_WaitEvent is blocking and probably isn't what you want. You probably want SDL_PollEvent which is non blocking. You typically keep polling events until there are no more events.

The general loop looks something like

void gameLoop()
{
    while(true)
    {
        update();
        render();
    }
}

and you would have your update function be something like

void update()
{
    SDL_Event event;
    while(SDL_PollEvent(&event))
    {
        // Handle Event
    }
    // Other Update Logic
}

This will keep calling polling events until there are no more in the queue, at which point SDL_PollEvent returns 0 thus ending the event loop. From there you can go on to perform other update logic that isn't dependent on system events.


问:
AJAX - Using POST instead of GET
Up until now I have been using:

```<code>xmlhttp.open("GET","server_script.php?q="+str,true);
</code>```

Thanks

Edit:
I am providing a solution for anyone that may come across this page to demonstrate how to use POST instead of GET. If you are new to AJAX I would recommend this tutorial http://www.w3schools.com/PHP/php_ajax_php.asp using the GET method first.

Solution-

javascript:

```<code>xmlhttp.open("POST","script.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send('var_name='+str);
</code>```

php:

```<code>$var_name = GET['var_name'];

echo $var_name;
</code>```

For reasons regarding the use of POST and GET - see comments blow.

答:
this is how you would use post:

```<code>var url = "server_script.php";
var params = "q="+str;
xmlhttp.open("POST", url, true);

//Send the proper header information along with the request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");

xmlhttp.onreadystatechange = function() {//Call a function when the state changes.
    if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        alert(xmlhttp.responseText);
    }
}
xmlhttp.send(params);
</code>```

source

Title: AJAX - Using POST instead of GET

Body:
Up until now I have been using:

xmlhttp.open("GET","server_script.php?q="+str,true);

Thanks

Edit:
I am providing a solution for anyone that may come across this page to demonstrate how to use POST instead of GET. If you are new to AJAX I would recommend this tutorial http://www.w3schools.com/PHP/php_ajax_php.asp using the GET method first.

Solution-

javascript:

xmlhttp.open("POST","script.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send('var_name='+str);

php:

$var_name = GET['var_name'];

echo $var_name;

For reasons regarding the use of POST and GET - see comments blow.

Body:
this is how you would use post:

var url = "server_script.php";
var params = "q="+str;
xmlhttp.open("POST", url, true);

//Send the proper header information along with the request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");

xmlhttp.onreadystatechange = function() {//Call a function when the state changes.
    if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        alert(xmlhttp.responseText);
    }
}
xmlhttp.send(params);

source


问:
How to choose dimensionality of the Dense layer in LSTM?
I have a task of multi-label text classification. My dataset has 1369 classes:

```<code># data shape
print(X_train.shape)
print(X_test.shape)
print(Y_train.shape)
print(Y_test.shape)
(54629, 500)
(23413, 500)
(54629, 1369)
(23413, 1369)
</code>```

For this task, I've decided to use LSTM NN with the next parameters:

```<code># define model
maxlen = 400
inp = Input(shape=(maxlen, ))
embed_size = 128
x = Embedding(max_features, embed_size)(inp)
x = LSTM(60, return_sequences=True,name='lstm_layer')(x)
x = GlobalMaxPool1D()(x)
x = Dropout(0.1)(x)
x = Dense(2000, activation="relu")(x)
x = Dropout(0.1)(x)
x = Dense(1369, activation="sigmoid")(x)
model = Model(inputs=inp, outputs=x)
model.compile(loss='binary_crossentropy',
                  optimizer='adam',
                  metrics=['accuracy']
batch_size = 32
epochs = 2
model.fit(X_train, Y_train, batch_size=batch_size, epochs=epochs, validation_split=0.1)
</code>```

Question: Are there any scientific methods for determining Dense and LSTM dimensionality (in my example, LSTM dimension=60, I Dense dimension=2000, and II Dense dimension=1369)?

If there are no scientific methods, maybe there are some heuristics or tips on how to do this with data with similar dimension.

I randomly chose these parameters. I would like to improve the accuracy of the model and correctly approach to solving similar problems.

答:
I heard that optimizing hyper parameters is an np problem, even there is a better way to do it, it may not worth it for your project given the overhead cost.

For the dimension of LSTM layer, I heard some empirically well working numbers from some conference talks, such as 128 or 256 units and 3 stacked layers. If you can plot your loss along training, and you saw the loss decrease dramatically in the first several epoch but then stopped decreasing, you may want to increase the capacity of your model. This means to make it either deeper or wider. Otherwise, should have less parameters as possible.

For the dimension of dense layer, if your task is many-to-many which means you have a label of certain dimension, then you have to have same number of that dimension as number of units in the dense layer.

Body:
I have a task of multi-label text classification. My dataset has 1369 classes:

# data shape
print(X_train.shape)
print(X_test.shape)
print(Y_train.shape)
print(Y_test.shape)
(54629, 500)
(23413, 500)
(54629, 1369)
(23413, 1369)

For this task, I've decided to use LSTM NN with the next parameters:

# define model
maxlen = 400
inp = Input(shape=(maxlen, ))
embed_size = 128
x = Embedding(max_features, embed_size)(inp)
x = LSTM(60, return_sequences=True,name='lstm_layer')(x)
x = GlobalMaxPool1D()(x)
x = Dropout(0.1)(x)
x = Dense(2000, activation="relu")(x)
x = Dropout(0.1)(x)
x = Dense(1369, activation="sigmoid")(x)
model = Model(inputs=inp, outputs=x)
model.compile(loss='binary_crossentropy',
                  optimizer='adam',
                  metrics=['accuracy']
batch_size = 32
epochs = 2
model.fit(X_train, Y_train, batch_size=batch_size, epochs=epochs, validation_split=0.1)

Question: Are there any scientific methods for determining Dense and LSTM dimensionality (in my example, LSTM dimension=60, I Dense dimension=2000, and II Dense dimension=1369)?

If there are no scientific methods, maybe there are some heuristics or tips on how to do this with data with similar dimension.

I randomly chose these parameters. I would like to improve the accuracy of the model and correctly approach to solving similar problems.


问:
How can I exclude watched resources from the automatic publishing in eclipse embedded tomcat server
I am working on a GWT project in eclipse, using an embedded Tomcat server with auto publishing 'on'.

Some of the maintained java sources are subject to the GWT compiler (which produces javascript for the client side) and not part of the server side code. Nevertheless, changing such client side sources triggers the auto publish to tomcat server (i.e. Tomcat restarts the application), which takes about 30 seconds. Which is really annoying because these files are never deployed to the server side.

How can I exclude these resources from beeing watched by the auto publisher?

Versions:

eclipse: 2018-12 (4.10.0)

GWT: 2.8.1

Tomcat: 8.0

答: In the build area (".../target/project-name/" if using maven), you want just the "server" code compiled to the WEB-INF directory, because like all servlet containters tomcat looks for server code in WEB-INF/classes.


问:
Having trouble deciphering my teachers pseudo code
Im working on a Binary Search Tree assignment for class and for this function I need to follow my professor's pseudo code. Unfortunately, I'm not sure about one specific detail, and she refuses to clarify.

Link to the pseudo code is here:
https://imgur.com/a/rhjhEIa

```<code>SUBROUTINE insert(current, parent, node)
    IF current is null
        IF parent is null
            root = node
        ELSE
            ID node.value < parent.value
                parent.left = node
            ELSE
                parent.right = node
            END IF
            RETURN true
        END IF
    ELSE IF node.value = current.=value
        RETURN false
    ELSE IF ode.value < current.value
        insert(current.left, current, node)
    ELSE
        insert(current.right, current, node)
    END IF
END SUBROUTINE
</code>```

In place of node, I've tried seemingly most of the allowed variables, including current, parent, (and even value, which didn't work. Shocker.)

```<code>bool recursiveInsert(Node* current, Node* parent, double value)
{

    if (current == NULL)
    {
        if (parent == NULL)
        {
        }
        else
        {
            if (current->value < parent->value)
            {
                parent->left = current;
            }
            else
            {
                parent->right = current;
            }
            return true;
        }
    }
    else if(parent->value == current->value)
    {
        return false;
    }
    else if (parent->value < current->value)
    {
        insert(current->left, current->value, current);
    }
    else
    {
        insert(current->right, current->value, current);
    }
}
</code>```

I expect the output to add the value to the binary search tree and return true, but the program currently just throws a error whenever I get to the parts that require "node".

答:
As you have mentioned, this is a function to insert a node in a binary search tree. The parameters are as follows

parent is the parent of the node being examined. This would be called with the root of the tree.

current is the left or right of the parent node being examined. While calling the function for the first time, you should use root->left if the value of the current node is less than root, or root->right if the value is greater than root. If root is null, then current should also be NULL

```<code>if (root == NULL)
{
    ret = recursiveInsert(NULL, NULL, node);
}
else if (root->value < node->value)
{
    ret = recursiveInsert(root->left, root, node);
}
else if (root-> value > node->value)
{
    ret = recursiveInsert(root->right, root, node);
}
else
{
    //same value, handle error
}
</code>```

node is the new node to be added to the tree. The memory allocation for this node should be done before the call to recursiveinsert and the value should be specified.

Now let us look at the code that you have written.

The first mistake is to have the third parameter as a double. This should be a parameter of type node which should have already been allocated before.

From the condition check that

```<code>ELSE IF node.value = current.=value
    RETURN false
</code>```

it seems that node->value is of integer type.

Taking all this into consideration, the updated code is below.

```<code>Node* root = NULL;  //global variable
...
bool recursiveInsert(Node* current, Node* parent, Node* node)
{

    if (current == NULL)
    {
        if (parent == NULL)
        {
            root = node;
        }
        else
        {
            if (current->value < parent->value)
            {
                parent->left = node;
            }
            else
            {
                parent->right = node;
            }
            return true;
        }
    }
    else if(node->value == current->value)
    {
        return false;
    }
    else if (parent->value < current->value)
    {
        recursiveInsert(current->left, current, node);
    }
    else
    {
        recursiveInsert(current->right, current, node);
    }
}
</code>```

Body:
Im working on a Binary Search Tree assignment for class and for this function I need to follow my professor's pseudo code. Unfortunately, I'm not sure about one specific detail, and she refuses to clarify.

Link to the pseudo code is here:
https://imgur.com/a/rhjhEIa

SUBROUTINE insert(current, parent, node)
    IF current is null
        IF parent is null
            root = node
        ELSE
            ID node.value < parent.value
                parent.left = node
            ELSE
                parent.right = node
            END IF
            RETURN true
        END IF
    ELSE IF node.value = current.=value
        RETURN false
    ELSE IF ode.value < current.value
        insert(current.left, current, node)
    ELSE
        insert(current.right, current, node)
    END IF
END SUBROUTINE

In place of node, I've tried seemingly most of the allowed variables, including current, parent, (and even value, which didn't work. Shocker.)

bool recursiveInsert(Node* current, Node* parent, double value)
{

    if (current == NULL)
    {
        if (parent == NULL)
        {
        }
        else
        {
            if (current->value < parent->value)
            {
                parent->left = current;
            }
            else
            {
                parent->right = current;
            }
            return true;
        }
    }
    else if(parent->value == current->value)
    {
        return false;
    }
    else if (parent->value < current->value)
    {
        insert(current->left, current->value, current);
    }
    else
    {
        insert(current->right, current->value, current);
    }
}

I expect the output to add the value to the binary search tree and return true, but the program currently just throws a error whenever I get to the parts that require "node".

Body:
As you have mentioned, this is a function to insert a node in a binary search tree. The parameters are as follows

parent is the parent of the node being examined. This would be called with the root of the tree.

current is the left or right of the parent node being examined. While calling the function for the first time, you should use root->left if the value of the current node is less than root, or root->right if the value is greater than root. If root is null, then current should also be NULL

if (root == NULL)
{
    ret = recursiveInsert(NULL, NULL, node);
}
else if (root->value < node->value)
{
    ret = recursiveInsert(root->left, root, node);
}
else if (root-> value > node->value)
{
    ret = recursiveInsert(root->right, root, node);
}
else
{
    //same value, handle error
}

node is the new node to be added to the tree. The memory allocation for this node should be done before the call to recursiveinsert and the value should be specified.

Now let us look at the code that you have written.

The first mistake is to have the third parameter as a double. This should be a parameter of type node which should have already been allocated before.

From the condition check that

ELSE IF node.value = current.=value
    RETURN false

it seems that node->value is of integer type.

Taking all this into consideration, the updated code is below.

Node* root = NULL;  //global variable
...
bool recursiveInsert(Node* current, Node* parent, Node* node)
{

    if (current == NULL)
    {
        if (parent == NULL)
        {
            root = node;
        }
        else
        {
            if (current->value < parent->value)
            {
                parent->left = node;
            }
            else
            {
                parent->right = node;
            }
            return true;
        }
    }
    else if(node->value == current->value)
    {
        return false;
    }
    else if (parent->value < current->value)
    {
        recursiveInsert(current->left, current, node);
    }
    else
    {
        recursiveInsert(current->right, current, node);
    }
}


问:
Unity, how to de/activated components in other scene
My problem is the following.

I'm in the main menu scene, and there are 2 buttons: one playerVSplayer and the other VScpu.

Now, I want enable/disable some component in the scene that will be loaded when one of the buttons will be pressed.

How can I solve this problem?

```<code>public void PlayerVsPlayer()
{
    GameObject[] objs = SceneManager.GetSceneByName("First Level").GetRootGameObjects();
    foreach(GameObject o in objs)
    {
        if(o.gameObject.tag == "--Gameplay")
        {
            o.gameObject.GetComponentInChildren<StaticPlayerCtr_p2>().enabled = true;
            o.gameObject.GetComponentInChildren<AI>().enabled = false;
            o.gameObject.GetComponentInChildren<UnityEngine.AI.NavMeshAgent>().enabled = false;
        }
    }
    SceneManager.LoadScene("First Level");
}

public void VsCPU()
{
    GameObject[] objs = SceneManager.GetSceneByName("First Level").GetRootGameObjects();
    foreach (GameObject o in objs)
    {
        if (o.gameObject.tag == "--Gameplay")
        {
            o.gameObject.GetComponentInChildren<StaticPlayerCtr_p2>().enabled = false;
            o.gameObject.GetComponentInChildren<AI>().enabled = true;
            o.gameObject.GetComponentInChildren<UnityEngine.AI.NavMeshAgent>().enabled = true;
        }
    }
    SceneManager.LoadScene("First Level");
}

public void QuitGame()
{
    Application.Quit();
}
</code>```

That's the error:

ArgumentException: The scene is invalid.

答:
As far as i know you cannot access scenes GameObjects from other scenes.

If you wish to have two different scenes depending on an option (Here it would be PvP & PvCpu) you must create two different scenes. Then depending on which option is chosen let's say PvP and PvCpu are buttons, then depending on which button is pressed you load the needed scene.

I hope i'v helped you. Good luck with your game !

Body:
My problem is the following.

I'm in the main menu scene, and there are 2 buttons: one playerVSplayer and the other VScpu.

Now, I want enable/disable some component in the scene that will be loaded when one of the buttons will be pressed.

How can I solve this problem?

public void PlayerVsPlayer()
{
    GameObject[] objs = SceneManager.GetSceneByName("First Level").GetRootGameObjects();
    foreach(GameObject o in objs)
    {
        if(o.gameObject.tag == "--Gameplay")
        {
            o.gameObject.GetComponentInChildren<StaticPlayerCtr_p2>().enabled = true;
            o.gameObject.GetComponentInChildren<AI>().enabled = false;
            o.gameObject.GetComponentInChildren<UnityEngine.AI.NavMeshAgent>().enabled = false;
        }
    }
    SceneManager.LoadScene("First Level");
}

public void VsCPU()
{
    GameObject[] objs = SceneManager.GetSceneByName("First Level").GetRootGameObjects();
    foreach (GameObject o in objs)
    {
        if (o.gameObject.tag == "--Gameplay")
        {
            o.gameObject.GetComponentInChildren<StaticPlayerCtr_p2>().enabled = false;
            o.gameObject.GetComponentInChildren<AI>().enabled = true;
            o.gameObject.GetComponentInChildren<UnityEngine.AI.NavMeshAgent>().enabled = true;
        }
    }
    SceneManager.LoadScene("First Level");
}

public void QuitGame()
{
    Application.Quit();
}

That's the error:

ArgumentException: The scene is invalid.


答:
```<code>$json = json_decode($data);
$results = $json->results;

$results= array_map(function($r){
   return ["id" => $r->id, "title" => $r->title, "overview" => $r->overview]
}, $results)

echo json_encode($results);

</code>```

Title: How to filter data properties coming from API in PHP?