问:
Fetch the lastest ban from the audit logs
I'm trying to code a discord bot that looks for the latest ban in the audit logs.

I currently have:

client.on('guildBanAdd', guild => {
  guild.fetchAuditLogs().then(logs => {
    logs.entries.filter(l => l.action === 'MEMBER_BAN_ADD')
      .forEach(log => {
        if (Date.now() - log.createdTimestamp > 1000) return

        const logsChannel = guild.channels.find(ch => ch.name === 'bans-logs')
        const embed = new Discord.RichEmbed()
          .setDescription(`**New Ban**
            **${log.executor.tag}** banned **${log.target.tag}**`)
          .setColor("RED")
          .setTimestamp(log.createdTimestamp)

        logsChannel.send(embed)
      })
  })
})
```

I thought about using .first() because this is a Collection, but I'm not sure the logs are ordered by date...

答:
I think the best way would be to fetch the audit logs and sort them by date since, as you also said, I'm not sure you'll always get them in chronological order.

You need to:

Fetch all the audit logs

Sort the entries by date: you can use the Dates you find in the createdAt properties

Get the latest one, which should now be the first

Here's how I would do it:

client.on('guildBanAdd', guild => {
  guild.fetchAuditLogs()
    .then(logs => {
      let ban = logs.entries
        .filter(e => e.action === 'MEMBER_BAN_ADD')
        .sort((a, b) => b.createdAt - a.createdAt) // Reverse chronological order
        .first() // Get the first, which is the latest

      // You can now send your embed using the entry stored in 'ban'
    })
})
```

Body:
I'm trying to code a discord bot that looks for the latest ban in the audit logs.

I currently have:

client.on('guildBanAdd', guild => {
  guild.fetchAuditLogs().then(logs => {
    logs.entries.filter(l => l.action === 'MEMBER_BAN_ADD')
      .forEach(log => {
        if (Date.now() - log.createdTimestamp > 1000) return

        const logsChannel = guild.channels.find(ch => ch.name === 'bans-logs')
        const embed = new Discord.RichEmbed()
          .setDescription(`**New Ban**
            **${log.executor.tag}** banned **${log.target.tag}**`)
          .setColor("RED")
          .setTimestamp(log.createdTimestamp)

        logsChannel.send(embed)
      })
  })
})

I thought about using .first() because this is a Collection, but I'm not sure the logs are ordered by date...


来源: stackexchange

问:
Checking server-side ad viewing (php)
I have an application using php backend.  Let's say this is an app for cheating views on YouTube, or something else where points are very important.  I want to realize crediting points for viewing ads, but don’t know how to do it.  Of course, I can send a request to the server when an advertisement has been viewed,

```<code>   @Override
    public void onAdOpened() {
        if (sampleInterstitial != null) {
            //something code
        }
    }
</code>```

but I'm afraid that a person rummaging in the code of my application will easily find which request I am sending and will be able to easily emulate my requests for building up points.  How can I avoid this?  For example, is it possible to somehow check from the server whether an ad was viewed?  Thanks for answers)

答:
First of all the client cannot check the server side code , you do something like getting the ip address , time .. etc of anyone who views the ad , and inject it in a database or a file , and in this way you can know how many people did and give it credits

Your Php Ad page :

```<code>$ip = $_SERVER['REMOTE_ADDR']; // gets ip address
$time = date_default_timezone_get(); // gets time
// insert it in your file or database
</code>```

ContentLicense: CC BY-SA 4.0

Title: Checking server-side ad viewing (php)

Body:
I have an application using php backend.  Let's say this is an app for cheating views on YouTube, or something else where points are very important.  I want to realize crediting points for viewing ads, but don’t know how to do it.  Of course, I can send a request to the server when an advertisement has been viewed,

   @Override
    public void onAdOpened() {
        if (sampleInterstitial != null) {
            //something code
        }
    }

but I'm afraid that a person rummaging in the code of my application will easily find which request I am sending and will be able to easily emulate my requests for building up points.  How can I avoid this?  For example, is it possible to somehow check from the server whether an ad was viewed?  Thanks for answers)

Body:
First of all the client cannot check the server side code , you do something like getting the ip address , time .. etc of anyone who views the ad , and inject it in a database or a file , and in this way you can know how many people did and give it credits

Your Php Ad page :

$ip = $_SERVER['REMOTE_ADDR']; // gets ip address
$time = date_default_timezone_get(); // gets time
// insert it in your file or database


问:
How would I be able to extract data from an API and display it in a webpage, using DJANGO?
I received a task that asks me to create a webpage and populate it with data from a given API.

The API data is in a REST JSON format. Furthermore,  I am using Django as a framework, so that I avoid any issues with cross-origin requests.

I've been looking into the request module and have got as far as:

```<code>import requests
import pprint
url = ''
r = requests.get(url)
pprint.pprint(r.json()['results'][1])
</code>```

I am able to get the information printed in the terminal. However, I am confused about how I would implement this into an HTML page.

I am new to working with APIs so any help would be appreciated.

thank you

答:
I would use ajax to go about working with api in the front-end. Using the Pokemon API to practice. Of course first see what you are working with by console.log for api. Once you have the data then assign it to an html element. Here's how I'd go about it using jquery.

```<code><script
    src="https://code.jquery.com/jquery-3.5.1.js"
    integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="
    crossorigin="anonymous">
</script>

<script type="text/javascript">
$.ajax({
    url: 'https://pokeapi.co/api/v2/pokemon/ditto',
    type: 'GET',
    // headers: { "X-CSRFToken" : getCookie("csrftoken") },
    success: function(data) {
        // console.log("sucess From Name choosing", serverResponse);
        // globe variables for clearing table and adding to it
        console.log(data.name);
        document.getElementById("pokemonName").innerHTML = data.name;
        }
})
</script>
<body>
<h1 id = "pokemonName">This is a Pokemon API playground</h1>
</code>```

Ajax "GET" the api and if success then so and so happens to the api.
There are other tools you could use when using the ajax for api. Like when if fails.

Body:
I received a task that asks me to create a webpage and populate it with data from a given API.

The API data is in a REST JSON format. Furthermore,  I am using Django as a framework, so that I avoid any issues with cross-origin requests.

I've been looking into the request module and have got as far as:

import requests
import pprint
url = ''
r = requests.get(url)
pprint.pprint(r.json()['results'][1])

I am able to get the information printed in the terminal. However, I am confused about how I would implement this into an HTML page.

I am new to working with APIs so any help would be appreciated.

thank you

Body:
I would use ajax to go about working with api in the front-end. Using the Pokemon API to practice. Of course first see what you are working with by console.log for api. Once you have the data then assign it to an html element. Here's how I'd go about it using jquery.

<script
    src="https://code.jquery.com/jquery-3.5.1.js"
    integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="
    crossorigin="anonymous">
</script>

<script type="text/javascript">
$.ajax({
    url: 'https://pokeapi.co/api/v2/pokemon/ditto',
    type: 'GET',
    // headers: { "X-CSRFToken" : getCookie("csrftoken") },
    success: function(data) {
        // console.log("sucess From Name choosing", serverResponse);
        // globe variables for clearing table and adding to it
        console.log(data.name);
        document.getElementById("pokemonName").innerHTML = data.name;
        }
})
</script>
<body>
<h1 id = "pokemonName">This is a Pokemon API playground</h1>

Ajax "GET" the api and if success then so and so happens to the api.
There are other tools you could use when using the ajax for api. Like when if fails.


问:
How do I get valid lastActivityTime and cloudToDeviceMessageCount values for an IoTHub device?
When I query the device twins for my active devices, either in code (via the C# SDK or in the Device Explorer), lastActivityTime is always "0001-01-01T00:00:00Z" and cloudToDeviceMessageCount is always 0. Valid fields appear to be deviceId, the etags, status, connectionState, and lastUpdated on the properties metadata fields. Is there additional configuration or provisioning I need to do to obtain the additional information?</p>

答:
We can start to see the Device twins get updated only if we have any status updated from any particular devices, Please see the below images for a detailed steps to demonstrate the device twin updated properties. For example if your device is shutdown or disabled as explained in the below images.

Steps: VS code the easy way.

1) Go to the Azure portal-->IoT Hub -->Device and 'Disable' its connection

2) Go to VS code , right click the device and select 'Get Device Info'

3) You will see the device twin is reported as the status is "Disconnected" and even the 'StatusUpdatedTime and 'LastActivity' are also reported for the first time and will continue to keep reporting if there is an activity on the particular device.

Steps: Device Explorer, the easy way

1) Open the Device Explorer Twin, Messages to Device-->Select your device and send a Message. You can use the VS Code to Get Device info again as showed in the previous step. Here in the below image you can see the "cloudToDeviceMessageCount":1 , keep on sending further messages from Device explorer and check the message count.

More info can be obtained from Understand and use device twins in IoT Hub.

Step: Cloud to device messaging: Azure Portal

Please read more info about Cloud to device Messaging

Step: Using Azure IoT service SDK NuGet package. C# Sample App C2D

Happy Azure IoT Learning


问:
problem comparing two dates in mysql
I m using below query from c# to compare current date with date stored in database as string.but it do not show the proper output even though it is not showing any error.

```<code>Select * from tblconcertdetail
WHERE STR_TO_DATE(Concert_Date,'%m/%d/%Y')>="+DateTime.Now.ToString("yyyy-MM-dd")+";
</code>```

first argument shows as: 2011-06-10
second shows ; 2011-06-02

it shows all rows of table

答:
The output of STR_TO_DATE(Concert_Date,'%m/%d/%Y') depends on Concert_Date.
Its different values will produce different results if compared to the second date.

I think you should try to use this portion of code:

```<code>STR_TO_DATE('2011-06-10','%Y-%m-%d');
</code>```

IMHO if Concert_Date is equal to 2011-06-10 you cannot read it correctly with '%m/%d/%Y' patern.

ContentLicense: CC BY-SA 3.0

Title: problem comparing two dates in mysql

Body:
I m using below query from c# to compare current date with date stored in database as string.but it do not show the proper output even though it is not showing any error.

Select * from tblconcertdetail
WHERE STR_TO_DATE(Concert_Date,'%m/%d/%Y')>="+DateTime.Now.ToString("yyyy-MM-dd")+";

first argument shows as: 2011-06-10
second shows ; 2011-06-02

it shows all rows of table

Body:
The output of STR_TO_DATE(Concert_Date,'%m/%d/%Y') depends on Concert_Date.
Its different values will produce different results if compared to the second date.

I think you should try to use this portion of code:

STR_TO_DATE('2011-06-10','%Y-%m-%d');

IMHO if Concert_Date is equal to 2011-06-10 you cannot read it correctly with '%m/%d/%Y' patern.


问:
Alternating buy and sell order using mql4
Please can someone help me with the mql4 code for alternating buy and sell order.that is if buy order hit a stop loss a sell order should be executed and if a sell order hit a stop loss buy order should be executed.</p>

答:
If your request to loop over orders and do action based on type, then the below might help:</p>

```<code>// We go through all the open orders
   for(int b = OrdersTotal()-1; b>=0; b--)
     {
      // we select an order
      if(OrderSelect(b,SELECT_BY_POS, MODE_TRADES))
        {
         if(OrderSymbol()==Symbol())
           {
            if(OrderType()==OP_BUY)
              {
                // Do something on buy trades
              }
              }
            if(OrderType()==OP_SELL)
              {
                // Do something on buy trades
               }
            }
        }
    }
</code>```

Body:
If your request to loop over orders and do action based on type, then the below might help:

// We go through all the open orders
   for(int b = OrdersTotal()-1; b>=0; b--)
     {
      // we select an order
      if(OrderSelect(b,SELECT_BY_POS, MODE_TRADES))
        {
         if(OrderSymbol()==Symbol())
           {
            if(OrderType()==OP_BUY)
              {
                // Do something on buy trades
              }
              }
            if(OrderType()==OP_SELL)
              {
                // Do something on buy trades
               }
            }
        }
    }


问:
How to append to a list from a csv reading a column with operators appearing in line ; getting "invalid literal for float()" error
I am appending to a list from a csv which looks like this

SampleA,Type,3.782*0.0627

then vals = line.split(',')

So, I ve tried something like
value = float(str(vals[2]))
or
value = float(vals[2])

but I get errors like ValueError: invalid literal for float(): 3.782*0.0627

So what I want, is to basically store to value = 0.237 ie the result of the mutlipication

TIA

答:
You need to execute the operation 3.782*0.0627 "manually".
You can do it like so:

```<code>value1, value2 = map(float, vals[2].split("*"))
value = value1 * value2
</code>```

But if there is a possibility that you can encounter any other operation under vals[2] then you should implement a handling logic for every case.

Also, if you are parsing csv consider using python standart csv library

Body:
You need to execute the operation 3.782*0.0627 "manually".
You can do it like so:

value1, value2 = map(float, vals[2].split("*"))
value = value1 * value2

But if there is a possibility that you can encounter any other operation under vals[2] then you should implement a handling logic for every case.

Also, if you are parsing csv consider using python standart csv library


问:
can't access class variable python
I'm building a desktop app with python and have some issues getting a class variable I set up.

My program is built like this:

CharCreator.py

```<code>class MainWindow(QtWidgets.QMainWindow):
    charName = ""

    def __init__(self):
        super().__init__()

    def editCharClick(self):
        from CharEdit import editUi

        MainWindow.charName = self.getSelected()
        print(MainWindow.charName)
        if(MainWindow.charName is not None):
            self.editWin = editUi()
            self.editWin.show()
        else:
            print("charName is none")

def main():
    app = QtWidgets.QApplication(sys.argv)
    main = MainWindow()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()

</code>```

So I've got my main window class, with a charName class variable.
Then I have the typical methods(init, main etc) and have an editCharClick method that takes the selected row of my table, gets the name of my desired cell and assigns its string content to my class variable.
This part works well in my CharCreator.py file.

The problem comes in my second file. As seen in my editCharClick method, it opens a second window (CharEdit.py file). That's where I need to get the MainWindow.charName class variable.

CharEdit.py

```<code>class editUi(QtWidgets.QMainWindow):
    def __init__(self):
        super(editUi, self).__init__()
        uic.loadUi("./ui/new.ui", self)

        from CharCreator import MainWindow
        print(MainWindow.charName)

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    newwindow = editUi()
    sys.exit(app.exec_())
</code>```

I've simplified this file just to get my class variable right, yet can't seem to make it happen.

Any help would be appreciated, thanks.

答:
I tried changing my code to work with event/signals but didn't quite like it.
So I just went the easy way and changed the editUi class constructor so it would accept another argument.
Then, when creating the editUi object in MainWindow.editCharClick(), you can pass the variable in the editUi object as an argument.

CharCreator.py

```<code>class MainWindow(QtWidgets.QMainWindow):
    charName = ""

    def __init__(self):
        super().__init__()

    def editCharClick(self):
        from CharEdit import editUi

        MainWindow.charName = self.getSelected()
        print(MainWindow.charName)
        if(MainWindow.charName is not None):
            self.editWin = editUi(MainWindow.charName)
            self.editWin.show()
        else:
            print("charName is none")

def main():
    app = QtWidgets.QApplication(sys.argv)
    main = MainWindow()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()
</code>```

CharEdit.py

```<code>class editUi(QtWidgets.QMainWindow):
    def __init__(self, ch):
        super(editUi, self).__init__()
        uic.loadUi("./ui/new.ui", self)

        from CharCreator import MainWindow
        print(ch)

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    newwindow = editUi()
    sys.exit(app.exec_())
</code>```

Title: can't access class variable python

Body:
I'm building a desktop app with python and have some issues getting a class variable I set up.

My program is built like this:

CharCreator.py

class MainWindow(QtWidgets.QMainWindow):
    charName = ""

    def __init__(self):
        super().__init__()

    def editCharClick(self):
        from CharEdit import editUi

        MainWindow.charName = self.getSelected()
        print(MainWindow.charName)
        if(MainWindow.charName is not None):
            self.editWin = editUi()
            self.editWin.show()
        else:
            print("charName is none")

def main():
    app = QtWidgets.QApplication(sys.argv)
    main = MainWindow()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()

So I've got my main window class, with a charName class variable.
Then I have the typical methods(init, main etc) and have an editCharClick method that takes the selected row of my table, gets the name of my desired cell and assigns its string content to my class variable.
This part works well in my CharCreator.py file.

The problem comes in my second file. As seen in my editCharClick method, it opens a second window (CharEdit.py file). That's where I need to get the MainWindow.charName class variable.

CharEdit.py

class editUi(QtWidgets.QMainWindow):
    def __init__(self):
        super(editUi, self).__init__()
        uic.loadUi("./ui/new.ui", self)

        from CharCreator import MainWindow
        print(MainWindow.charName)

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    newwindow = editUi()
    sys.exit(app.exec_())

I've simplified this file just to get my class variable right, yet can't seem to make it happen.

Any help would be appreciated, thanks.

Body:
I tried changing my code to work with event/signals but didn't quite like it.
So I just went the easy way and changed the editUi class constructor so it would accept another argument.
Then, when creating the editUi object in MainWindow.editCharClick(), you can pass the variable in the editUi object as an argument.

CharCreator.py

class MainWindow(QtWidgets.QMainWindow):
    charName = ""

    def __init__(self):
        super().__init__()

    def editCharClick(self):
        from CharEdit import editUi

        MainWindow.charName = self.getSelected()
        print(MainWindow.charName)
        if(MainWindow.charName is not None):
            self.editWin = editUi(MainWindow.charName)
            self.editWin.show()
        else:
            print("charName is none")

def main():
    app = QtWidgets.QApplication(sys.argv)
    main = MainWindow()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()

CharEdit.py

class editUi(QtWidgets.QMainWindow):
    def __init__(self, ch):
        super(editUi, self).__init__()
        uic.loadUi("./ui/new.ui", self)

        from CharCreator import MainWindow
        print(ch)

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    newwindow = editUi()
    sys.exit(app.exec_())


问:
Correct way to declare an Array member in a class
I have a class that looks like this

```<code>class StatisticsQuantiles : public StatisticsMC
{
public:
    StatisticsQuantiles(double p_, unsigned long NumberOfPaths);
    virtual void DumpOneResult(double result);
    virtual std::vector<std::vector<double>> GetResultsSoFar() const;
    virtual StatisticsMC* clone() const;
private:
    std::vector<double> ResultList;
    double p;
    unsigned long PathsDone;
};
</code>```

Currently it has a vector ResultList which I populate with values in my class when a function is called with a value like so:

```<code>void StatisticsQuantiles::DumpOneResult(double result)
{
    ResultList.push_back(result);
    PathsDone++;
}
</code>```

Now I know that I will fill this vector with exactly NumberOfPaths many values, so I would like to use an array of a fixed size instead. How do I go about getting an array as a member of this class with size NumberOfPaths? I'm trying to do something like this which doesn't work of course but you get the idea:

```<code>class StatisticsQuantiles : public StatisticsMC
{
public:
    StatisticsQuantiles(double p_, const unsigned long NumberOfPaths);
    virtual void DumpOneResult(double result);
    virtual std::vector<std::vector<double>> GetResultsSoFar() const;
    virtual StatisticsMC* clone() const;
private:
    std::array<double, NumberOfPaths> ResultList;
    double p;
    unsigned long PathsDone;
};
</code>```

答:
the size of std::array must be known at compile time, which is not the case here.
So std::vector is your option I believe.

If you are worried about the efficiency of push_back re-sizing, you can reserve the memory in your constructor.

```<code>ResultList.reserve(NumberOfPaths);
</code>```

push_back then won't re-size unless you insert more than NumberOfPaths elements. So you don't have the un-necessary resizing.

Body:
I have a class that looks like this

class StatisticsQuantiles : public StatisticsMC
{
public:
    StatisticsQuantiles(double p_, unsigned long NumberOfPaths);
    virtual void DumpOneResult(double result);
    virtual std::vector<std::vector<double>> GetResultsSoFar() const;
    virtual StatisticsMC* clone() const;
private:
    std::vector<double> ResultList;
    double p;
    unsigned long PathsDone;
};

Currently it has a vector ResultList which I populate with values in my class when a function is called with a value like so:

void StatisticsQuantiles::DumpOneResult(double result)
{
    ResultList.push_back(result);
    PathsDone++;
}

Now I know that I will fill this vector with exactly NumberOfPaths many values, so I would like to use an array of a fixed size instead. How do I go about getting an array as a member of this class with size NumberOfPaths? I'm trying to do something like this which doesn't work of course but you get the idea:

class StatisticsQuantiles : public StatisticsMC
{
public:
    StatisticsQuantiles(double p_, const unsigned long NumberOfPaths);
    virtual void DumpOneResult(double result);
    virtual std::vector<std::vector<double>> GetResultsSoFar() const;
    virtual StatisticsMC* clone() const;
private:
    std::array<double, NumberOfPaths> ResultList;
    double p;
    unsigned long PathsDone;
};

Body:
the size of std::array must be known at compile time, which is not the case here.
So std::vector is your option I believe.

If you are worried about the efficiency of push_back re-sizing, you can reserve the memory in your constructor.

ResultList.reserve(NumberOfPaths);

push_back then won't re-size unless you insert more than NumberOfPaths elements. So you don't have the un-necessary resizing.


问:
Starship symbols in Powershell
Is it at all possible to get a nice look, with symbols, with starship in PowerShell?
I've tried everything imaginable to get Fira Code font to show symbols in the console but always end up with ?? instead.

I know that the font is installed properly, because i can use Fira Code in notepad and other apps. But even when i select the correct font for PowerShell, it won't show any symbols. I've enabled the "Use unicode for world-wide language support" in Windows 10, and running chcp in Powershell returns Active code page: 65001.

Has anyone actually succeeded with this? Works great in Macos and Ubuntu, but i cannot get it right in Powershell. And by the way, i've tried both Powershell and Powershell Core.

答: Try the ISE, Vscode, or Windows Terminal.  Powershell 7 vs Powershell 5.</p>

Title: Starship symbols in Powershell


问:
Calling Functions Based on Content of a Dictionary C#
I'm working on a program that will have a dictionary storing commands. There are two dictionaries, one of executables and one of internal functions. Right now, I'm just using the executable one, which has a command name attached to the path of the executable. It will check for the input in the dictionary and run the attached exe if possible and run that command. I started the function dictionary because there are some functions that are not executables. Would it be possible to do the same thing I did with the executables with functions inside the program?</p>

```<code>    private Dictionary<string, string> ExternalCommands = new Dictionary<string, string>
    {
        {"help", @".\help.exe"}
    };

    private Dictionary<string, string> InternalFunctions = new Dictionary<string, string>
    {
        **{"exit", function()}**
    };
    public int Execute(string input)
    {
        try
        {
            if (ExternalCommands.Keys.Contains(input))
            {
                var process = new Process();
                process.StartInfo = new ProcessStartInfo(ExternalCommands[input])
                {
                    UseShellExecute = false
                };

                process.Start();
                process.WaitForExit();

                return 0;
            }
            Console.WriteLine($"{input} NOT FOUND");
            return 1;
        }
        catch
        {
            return 1;
        }
</code>```

答:
For voids you can use Action, if the function has parameters you use Action<T> where T is it the type, for example: Action<string>. If your functions return something you can use Func, example for a function which takes a string as an input and returns int: Func<string, int>. You can use these as values for the dictionary.
Here is an example code for a hello world application:

```<code>    class Program
    {
        public static Dictionary<string, Action> FunctionsInDictionary = new Dictionary<string, Action>()
        {
            { "helloworld", HelloWorld }
        };

        static void Main(string[] args)
        {

            FunctionsInDictionary["helloworld"].Invoke();

            Thread.Sleep(-1);
        }

        static void HelloWorld()
        {
            Console.WriteLine("Hello World!");
        }
    }
</code>```

Body:
I'm working on a program that will have a dictionary storing commands. There are two dictionaries, one of executables and one of internal functions. Right now, I'm just using the executable one, which has a command name attached to the path of the executable. It will check for the input in the dictionary and run the attached exe if possible and run that command. I started the function dictionary because there are some functions that are not executables. Would it be possible to do the same thing I did with the executables with functions inside the program?

    private Dictionary<string, string> ExternalCommands = new Dictionary<string, string>
    {
        {"help", @".\help.exe"}
    };

    private Dictionary<string, string> InternalFunctions = new Dictionary<string, string>
    {
        **{"exit", function()}**
    };
    public int Execute(string input)
    {
        try
        {
            if (ExternalCommands.Keys.Contains(input))
            {
                var process = new Process();
                process.StartInfo = new ProcessStartInfo(ExternalCommands[input])
                {
                    UseShellExecute = false
                };

                process.Start();
                process.WaitForExit();

                return 0;
            }
            Console.WriteLine($"{input} NOT FOUND");
            return 1;
        }
        catch
        {
            return 1;
        }

Body:
For voids you can use Action, if the function has parameters you use Action<T> where T is it the type, for example: Action<string>. If your functions return something you can use Func, example for a function which takes a string as an input and returns int: Func<string, int>. You can use these as values for the dictionary.
Here is an example code for a hello world application:

    class Program
    {
        public static Dictionary<string, Action> FunctionsInDictionary = new Dictionary<string, Action>()
        {
            { "helloworld", HelloWorld }
        };

        static void Main(string[] args)
        {

            FunctionsInDictionary["helloworld"].Invoke();

            Thread.Sleep(-1);
        }

        static void HelloWorld()
        {
            Console.WriteLine("Hello World!");
        }
    }


问:
ASIFormDataRequest JSON encoding issues
I seem to have run into a rather trivia issue that I can't figure out. I am using ASIFormDataRequest for interacting with my Ruby on Rails app. I have a REST API that accepts a User object. I am using JSONKit to get the JSONString from a NSDictionary.

However, when I do a
[request setPostValue:[userObj JSONString] forKey:@"user"];

The request on the server side ends up escaping the quotes. Basically,

{"password":"hello","name":"user","email":"user@foo.com"}

TO

"{\"password\":\"hello\",\"name\":\"user\",\"email\":\"user@foo.com\"}"

This ends up confusing rails and it complains of an invalid object. Can I force ASIFormDataRequest to not escape the quotes? I understand this might be an issue with the JSONString itself but I can't figure out a good solution here.

Thanks

答:
It's not usual to mix ASIFormDataRequest and JSON - normally people encode things in the HTML form data format or  they encode in JSON format. Not both!

Could you consider using pure JSON in this case? It might well make your life easier. Basically you would use an ASIHTTPRequest instead of an ASIFormDataRequest, and set it up like this:

```<code>NSString *postData = [userObj JSONString];
[request addRequestHeader: @"Content-Type" value: @"application/json; charset=utf-8"];
[request appendPostData:[postData dataUsingEncoding:NSUTF8StringEncoding]];
</code>```

Aside from that, it's not really clear why it's going wrong - can you use something like wireshark to capture the raw text of the http request you're sending and add that to your question?

How are you extracting the JSON data from the form data on the Ruby side?

Title: ASIFormDataRequest JSON encoding issues

Body:
It's not usual to mix ASIFormDataRequest and JSON - normally people encode things in the HTML form data format or  they encode in JSON format. Not both!

Could you consider using pure JSON in this case? It might well make your life easier. Basically you would use an ASIHTTPRequest instead of an ASIFormDataRequest, and set it up like this:

NSString *postData = [userObj JSONString];
[request addRequestHeader: @"Content-Type" value: @"application/json; charset=utf-8"];
[request appendPostData:[postData dataUsingEncoding:NSUTF8StringEncoding]];

Aside from that, it's not really clear why it's going wrong - can you use something like wireshark to capture the raw text of the http request you're sending and add that to your question?

How are you extracting the JSON data from the form data on the Ruby side?


问:
Set the last heading in a table to auto size to the button in the row
I have a table like this:

```<code><table class="table table-hover" id="myTable">
  <thead>
    <tr class="clickable-row">
      <th scope="col">#</th>
      <th scope="col">First</th>
      <th scope="col">Last</th>
      <th scope="col">Handle</th>
    </tr>
  </thead>
  <tbody>
    <tr class="clickable-row">
      <th scope="row">1</th>
      <td>Mark</td>
      <td>Otto</td>
      <td>@mdo</td>
    </tr>
    <tr class="clickable-row">
      <th scope="row">2</th>
      <td>Jacob</td>
      <td>Thornton</td>
      <td>@fat</td>
    </tr>
    <tr class="clickable-row">
      <th scope="row">3</th>
      <td colspan="2">Larry the Bird</td>
      <td><a class="btn btn-primary" href="#" target="_blank" role="button">Link</a></td>
    </tr>
  </tbody>
</code>```

Right now each heading takes up 25% of the table. Since the last heading is small and only contains a button in each row, I wanted to let the table autosize to the button or heading text. I could use a set width size but is it better to use another method?

答:
Use table-layout: fixed; property to the table.
To know more about it visit https://www.w3schools.com/cssref/pr_tab_table-layout.asp

Body:
I have a table like this:

      #
      First
      Last
      Handle

      1
      Mark
      Otto
      @mdo

      2
      Jacob
      Thornton
      @fat

      3
      Larry the Bird
      Link

Right now each heading takes up 25% of the table. Since the last heading is small and only contains a button in each row, I wanted to let the table autosize to the button or heading text. I could use a set width size but is it better to use another method?


问:
Rails 'remote:true' ignored when params provided
In a Rails (5.2.4.2) app

I am using button_to + remote: true, and this is working as expected -> ajax call fired, all is OK.

But then I add 'params' to the button_to. Params are added to the form as hidden input (as expected) but when I click on the button, the request made is not remote, and all the page content is updated.

Problematic: button_to + remote + params -> this code seems to ignore the remote:true, although I see data-remote="true" in the form tag

```<code><%= button_to ent_path(ent),
      {remote: true,
      method: :patch,
      class:"btn btn-primary",
      params: {ent: {active_a: false}}
    } do
%>
  <span>TEEEST</span>
<% end %>
</code>```

Working as expected:

```<code><%= button_to ent_path(ent),
      {remote: true,
      method: :patch,
      class:"btn btn-primary",
    } do
%>
  <span>TEEEST</span>
<% end %>
</code>```

So my purpose is to have the button_to remote and update the ent record, changing the active_a attribute depending on some logic

答: Turned out the remote:true was working properly. But there was a redirect_back in the controller that was executed in case of some custom logic, so that appeared as if the button is working without remote:true

Body:
In a Rails (5.2.4.2) app

I am using button_to + remote: true, and this is working as expected -> ajax call fired, all is OK.

But then I add 'params' to the button_to. Params are added to the form as hidden input (as expected) but when I click on the button, the request made is not remote, and all the page content is updated.

Problematic: button_to + remote + params -> this code seems to ignore the remote:true, although I see data-remote="true" in the form tag

<%= button_to ent_path(ent),
      {remote: true,
      method: :patch,
      class:"btn btn-primary",
      params: {ent: {active_a: false}}
    } do
%>
  TEEEST
<% end %>

Working as expected:

<%= button_to ent_path(ent),
      {remote: true,
      method: :patch,
      class:"btn btn-primary",
    } do
%>
  TEEEST
<% end %>

So my purpose is to have the button_to remote and update the ent record, changing the active_a attribute depending on some logic


问:
Amount not showing in PayPal payment in Braintree
Hi the amount does not display in paypal when making payment. The JavaScript code is shown below:

```<code>  var form = document.querySelector('#payment-form');
  var client_token = '{{ client_token }}';

  braintree.dropin.create({
    authorization: client_token,
    container: '#bt-dropin',
    card: {
    cardholderName: {
      required: true
    }
    },
    applePay: {
    displayName: 'Merchant Name',
    paymentRequest: {
    label: 'Localized Name',
    total: '10.00'
    }
    },
    paypal: {
    flow: 'checkout',
    amount: '10.00',
    currency: 'USD'
    },
    paypalCredit: {
    flow: 'checkout',
    amount: '10.00',
    currency: 'USD'
    },
    venmo: true

  }, function (createErr, instance) {
        if (createErr) {
        // Handle any errors that might've occurred when creating Drop-in
        console.error(err);
        return;
        }

    form.addEventListener('submit', function (event) {
      event.preventDefault();

      instance.requestPaymentMethod(function (err, payload) {
        if (err) {
          console.log('Error', err);
          return;
        }
        // Add the nonce to the form and submit
        document.querySelector('#nonce').value = payload.nonce;
        form.submit();
      });
    });
  });
</code>```

From the code, the amount is $10, but does not display in the PayPal payment page. Please what am i doing wrong?

答:
very simple. I included the following to paypal option in the code :

commit: true,

Body:
Hi the amount does not display in paypal when making payment. The JavaScript code is shown below:

  var form = document.querySelector('#payment-form');
  var client_token = '{{ client_token }}';

  braintree.dropin.create({
    authorization: client_token,
    container: '#bt-dropin',
    card: {
    cardholderName: {
      required: true
    }
    },
    applePay: {
    displayName: 'Merchant Name',
    paymentRequest: {
    label: 'Localized Name',
    total: '10.00'
    }
    },
    paypal: {
    flow: 'checkout',
    amount: '10.00',
    currency: 'USD'
    },
    paypalCredit: {
    flow: 'checkout',
    amount: '10.00',
    currency: 'USD'
    },
    venmo: true

  }, function (createErr, instance) {
        if (createErr) {
        // Handle any errors that might've occurred when creating Drop-in
        console.error(err);
        return;
        }

    form.addEventListener('submit', function (event) {
      event.preventDefault();

      instance.requestPaymentMethod(function (err, payload) {
        if (err) {
          console.log('Error', err);
          return;
        }
        // Add the nonce to the form and submit
        document.querySelector('#nonce').value = payload.nonce;
        form.submit();
      });
    });
  });

From the code, the amount is $10, but does not display in the PayPal payment page. Please what am i doing wrong?


问:
How do I use UserDefaults with SwiftUI?

struct ContentView: View {
@State var settingsConfiguration: Settings
    struct Settings {
        var passwordLength: Double = 20
        var moreSpecialCharacters: Bool = false
        var specialCharacters: Bool = false
        var lowercaseLetters: Bool = true
        var uppercaseLetters: Bool = true
        var numbers: Bool = true
        var space: Bool = false
    }
  var body: some View {
    VStack {
                HStack {
                    Text("Password Length: \(Int(settingsConfiguration.passwordLength))")
                    Spacer()
                    Slider(value: $settingsConfiguration.passwordLength, from: 1, through: 512)
                }
                Toggle(isOn: $settingsConfiguration.moreSpecialCharacters) {
                    Text("More Special Characters")
                }
                Toggle(isOn: $settingsConfiguration.specialCharacters) {
                    Text("Special Characters")
                }
                Toggle(isOn: $settingsConfiguration.space) {
                    Text("Spaces")
                }
                Toggle(isOn: $settingsConfiguration.lowercaseLetters) {
                    Text("Lowercase Letters")
                }
                Toggle(isOn: $settingsConfiguration.uppercaseLetters) {
                    Text("Uppercase Letters")
                }
                Toggle(isOn: $settingsConfiguration.numbers) {
                    Text("Numbers")
                }
                Spacer()
                }
                .padding(.all)
                .frame(width: 500, height: 500)
  }
}
```

So I have all this code here and I want to use UserDefaults to save settings whenever a switch is changed or a slider is slid and to retrieve all this data when the app launches but I have no idea how I would go about using UserDefaults with SwiftUI (Or UserDefaults in general, I've just started looking into it so I could use it for my SwiftUI app but all the examples I see are for UIKit and when I try implementing them in SwiftUI I just run into a ton of errors).

答:
If you are persisting a one-off struct such that a property wrapper is overkill, you can encode it as JSON. When decoding, use an empty Data instance for the no-data case.

final class UserData: ObservableObject {
    @Published var profile: Profile? = try? JSONDecoder().decode(Profile.self, from: UserDefaults.standard.data(forKey: "profile") ?? Data()) {
        didSet { UserDefaults.standard.set(try? JSONEncoder().encode(profile), forKey: "profile") }
    }
}
```

Title: How do I use UserDefaults with SwiftUI?

Body:
struct ContentView: View {
@State var settingsConfiguration: Settings
    struct Settings {
        var passwordLength: Double = 20
        var moreSpecialCharacters: Bool = false
        var specialCharacters: Bool = false
        var lowercaseLetters: Bool = true
        var uppercaseLetters: Bool = true
        var numbers: Bool = true
        var space: Bool = false
    }
  var body: some View {
    VStack {
                HStack {
                    Text("Password Length: \(Int(settingsConfiguration.passwordLength))")
                    Spacer()
                    Slider(value: $settingsConfiguration.passwordLength, from: 1, through: 512)
                }
                Toggle(isOn: $settingsConfiguration.moreSpecialCharacters) {
                    Text("More Special Characters")
                }
                Toggle(isOn: $settingsConfiguration.specialCharacters) {
                    Text("Special Characters")
                }
                Toggle(isOn: $settingsConfiguration.space) {
                    Text("Spaces")
                }
                Toggle(isOn: $settingsConfiguration.lowercaseLetters) {
                    Text("Lowercase Letters")
                }
                Toggle(isOn: $settingsConfiguration.uppercaseLetters) {
                    Text("Uppercase Letters")
                }
                Toggle(isOn: $settingsConfiguration.numbers) {
                    Text("Numbers")
                }
                Spacer()
                }
                .padding(.all)
                .frame(width: 500, height: 500)
  }
}

So I have all this code here and I want to use UserDefaults to save settings whenever a switch is changed or a slider is slid and to retrieve all this data when the app launches but I have no idea how I would go about using UserDefaults with SwiftUI (Or UserDefaults in general, I've just started looking into it so I could use it for my SwiftUI app but all the examples I see are for UIKit and when I try implementing them in SwiftUI I just run into a ton of errors).


问:
How to create different dataframes dynamically from a for loop for storing data
I have a code like below.

```<code>ind1=0
    for ind in df2.index:
                       df3 =df1[df2.iloc[ind1,2:].dropna().tolist()]
                       df3.insert(0,'Col',df2.loc[ind,1])
                       display(df3)
                       ind1=ind1+1
</code>```

Basically for each iteration the data will be stored into df3. However i want to dynamically create new DataFrames for each iteration in for loop.

Can anybody help me , how to generate new DataFrames dynamically using the for loop.

答:
You can have a list to store dataframes from each loop.

```<code>df_list = []

ind1=0
for ind in df2.index:
    df3 =df1[df2.iloc[ind1,2:].dropna().tolist()]
    df3.insert(0,'Col',df2.loc[ind,1])
    display(df3)
    df_list.append(df3) ## append this df in list
    ind1=ind1+1
</code>```

Then you can iterate on the list to get individual dataframe:

```<code>for df in df_list:
    print(df)
</code>```

You can concat all df's in df_list by doing this simply:

```<code>df = pd.concat(df_list)
</code>```

Body:
I have a code like below.

ind1=0
    for ind in df2.index:
                       df3 =df1[df2.iloc[ind1,2:].dropna().tolist()]
                       df3.insert(0,'Col',df2.loc[ind,1])
                       display(df3)
                       ind1=ind1+1

Basically for each iteration the data will be stored into df3. However i want to dynamically create new DataFrames for each iteration in for loop.

Can anybody help me , how to generate new DataFrames dynamically using the for loop.

Body:
You can have a list to store dataframes from each loop.

df_list = []

ind1=0
for ind in df2.index:
    df3 =df1[df2.iloc[ind1,2:].dropna().tolist()]
    df3.insert(0,'Col',df2.loc[ind,1])
    display(df3)
    df_list.append(df3) ## append this df in list
    ind1=ind1+1

Then you can iterate on the list to get individual dataframe:

for df in df_list:
    print(df)

You can concat all df's in df_list by doing this simply:

df = pd.concat(df_list)


问:
Problem with alias in join statiment
I have problem with following query:

```<code>SELECT
    g_contac.contid, g_contac.name, g_contac.email, f_sync.foreign_key,
    (
        SELECT COUNT(g_cpers.cpersid)
        FROM g_cpers
        WHERE g_cpers.contid = g_contac.contid
    ) AS employee_count
FROM f_sync
    FULL OUTER JOIN g_contac ON
    (
        g_contac.contid = f_sync.external_id AND
        model = case when f_sync.employee_count = 0 then 'PRIVATE' else 'COMPANY' end
    )
WHERE model = 'COMPANY' or model = 'PRIVATE' OR model IS null
</code>```

When I execute it, I get error:

Invalid column name 'employee_count'.

How to solve this problem?

答:
That's because you mention f_sync.employee_count in your query, but f_sync doesn't have a column called employee_count: you just created a dynamic column in the query with the alias  employee_count.

Simple fix is to repeat the calculation:

```<code>SELECT
g_contac.contid, g_contac.name, g_contac.email, f_sync.foreign_key,
(
    SELECT COUNT(g_cpers.cpersid)
    FROM g_cpers
    WHERE g_cpers.contid = g_contac.contid
) AS employee_count
FROM f_sync
FULL OUTER JOIN g_contac ON
(
    g_contac.contid = f_sync.external_id AND
    model = case when (SELECT COUNT(g_cpers.cpersid)
    FROM g_cpers
    WHERE g_cpers.contid = g_contac.contid) = 0 then 'PRIVATE' else 'COMPANY' end
)
WHERE model = 'COMPANY' or model = 'PRIVATE' OR model IS null;
</code>```

Better fix is to create a view that includes this column, which would mean it would only be calculated once;

Edit: Improved query and incorporated comments

You could improve the clarity a bit by using the SQL not exists instead of count(*) = 0:

```<code>SELECT
g_contac.contid, g_contac.name, g_contac.email, f_sync.foreign_key
FROM f_sync
FULL OUTER JOIN g_contac ON
(
    g_contac.contid = f_sync.external_id AND
    model = case when not exists (SELECT * FROM g_cpers
      WHERE g_cpers.contid = g_contac.contid) then 'PRIVATE' else 'COMPANY' end
)
WHERE model = 'COMPANY' or model = 'PRIVATE' OR model IS null;
</code>```

Title: Problem with alias in join statiment

Body:
I have problem with following query:

SELECT
    g_contac.contid, g_contac.name, g_contac.email, f_sync.foreign_key,
    (
        SELECT COUNT(g_cpers.cpersid)
        FROM g_cpers
        WHERE g_cpers.contid = g_contac.contid
    ) AS employee_count
FROM f_sync
    FULL OUTER JOIN g_contac ON
    (
        g_contac.contid = f_sync.external_id AND
        model = case when f_sync.employee_count = 0 then 'PRIVATE' else 'COMPANY' end
    )
WHERE model = 'COMPANY' or model = 'PRIVATE' OR model IS null

When I execute it, I get error:

Invalid column name 'employee_count'.

How to solve this problem?

Body:
That's because you mention f_sync.employee_count in your query, but f_sync doesn't have a column called employee_count: you just created a dynamic column in the query with the alias  employee_count.

Simple fix is to repeat the calculation:

SELECT
g_contac.contid, g_contac.name, g_contac.email, f_sync.foreign_key,
(
    SELECT COUNT(g_cpers.cpersid)
    FROM g_cpers
    WHERE g_cpers.contid = g_contac.contid
) AS employee_count
FROM f_sync
FULL OUTER JOIN g_contac ON
(
    g_contac.contid = f_sync.external_id AND
    model = case when (SELECT COUNT(g_cpers.cpersid)
    FROM g_cpers
    WHERE g_cpers.contid = g_contac.contid) = 0 then 'PRIVATE' else 'COMPANY' end
)
WHERE model = 'COMPANY' or model = 'PRIVATE' OR model IS null;

Better fix is to create a view that includes this column, which would mean it would only be calculated once;

Edit: Improved query and incorporated comments

You could improve the clarity a bit by using the SQL not exists instead of count(*) = 0:

SELECT
g_contac.contid, g_contac.name, g_contac.email, f_sync.foreign_key
FROM f_sync
FULL OUTER JOIN g_contac ON
(
    g_contac.contid = f_sync.external_id AND
    model = case when not exists (SELECT * FROM g_cpers
      WHERE g_cpers.contid = g_contac.contid) then 'PRIVATE' else 'COMPANY' end
)
WHERE model = 'COMPANY' or model = 'PRIVATE' OR model IS null;


问:
Does Typescript automatically detect void functions?
I’m a newbie in Typescript and in programming in general.

Instead of this:

```<code>function greet(greeting: string): void;
</code>```

Can I use something like this? Is there any kind of inference?

```<code>function greet(greeting: string)
</code>```

答:
Yes, in 95% of cases TypeScript will correctly infer the return type of a function. Exceptions to this include "tuples", which will be inferred as arrays, and anonymous objects which you may have already declared a type for.

In this case, no need to explicitly declare the return type as void, except for clarity of course.

Body:
I’m a newbie in Typescript and in programming in general.

Instead of this:

function greet(greeting: string): void;

Can I use something like this? Is there any kind of inference?

function greet(greeting: string)


问:
how to split a return text become individual string in extjs?
I want to split a returning text to become an individual string but i am noobie in extjs.Pls help me if any idea with it...thankz

my example code:

```<code>//my return "record" string is "1: 3-4-2011 to 9-4-2011"
Ext.getCmp('cboWeek').on('select', function(box, record, index)
{
    DateFrom = new Date(record).format('m/d/Y');//split to 3-4-2011
    DateTo = new Date(record).format('m/d/Y');  //split to 9-4-2011
    Store.load({ params: {dateFrom : DateFrom, dateTo: DateTo }});
});
</code>```

答:
i think what you want is:

```<code>// if record is "1: 3-4-2011 to 9-4-2011"
var matches = record.match(/[0-9]+-[0-9]+-[0-9]+/g);
// matches[0] will be 3-4-2011 and matches[1] will be 9-4-2011
Store.load({ params: {dateFrom : matches[0], dateTo: matches[1] }});
```
```

just a note: your dates are not what can be parsed using Date object neither using Ext.Date.parse, because month / day must be 2digits, if you manage to get 3-4-2011 to something like 03-04-2011 by doing "3-4-2011".replace(/([0-9]{1})[^0-9]+/g, '0$1-') you can get Date object using parse method of ext's date: Ext.Date.parse('03-04-2011', 'd-m-Y') then you can use format method on Date object

Body:
I want to split a returning text to become an individual string but i am noobie in extjs.Pls help me if any idea with it...thankz

my example code:

//my return "record" string is "1: 3-4-2011 to 9-4-2011"
Ext.getCmp('cboWeek').on('select', function(box, record, index)
{
    DateFrom = new Date(record).format('m/d/Y');//split to 3-4-2011
    DateTo = new Date(record).format('m/d/Y');  //split to 9-4-2011
    Store.load({ params: {dateFrom : DateFrom, dateTo: DateTo }});
});

Body:
i think what you want is:

// if record is "1: 3-4-2011 to 9-4-2011"
var matches = record.match(/[0-9]+-[0-9]+-[0-9]+/g);
// matches[0] will be 3-4-2011 and matches[1] will be 9-4-2011
Store.load({ params: {dateFrom : matches[0], dateTo: matches[1] }});
</pre>

just a note: your dates are not what can be parsed using Date object neither using Ext.Date.parse, because month / day must be 2digits, if you manage to get 3-4-2011 to something like 03-04-2011 by doing "3-4-2011".replace(/([0-9]{1})[^0-9]+/g, '0$1-') you can get Date object using parse method of ext's date: Ext.Date.parse('03-04-2011', 'd-m-Y') then you can use format method on Date object


问:
Converting oracle's "connect by prior" to mariaDB
I have to move from Oracle to MariaDB 10.3.21.
spent the whole day on this.
I made a query with "start with" and "connect by prior" and "order sibling by" for oracle.

```<code>        select * from (select * from table_name ";
        where num = 1045 ) ";
        start with parentid = 0 ";
        connect by prior id = parentid ";
        order siblings by parentid asc ";
</code>```

but MariaDB doesn't work.
used recursive but didn't go well.
anyone can share a good idea?

this is the original table.

```<code>------------------------------------
num     id   parentid       data1
------------------------------------
1045    11      4          zzzzz
1048    3       0          a3
1048    1       0          a1
1050    21      17         eeeee
1048    2       0          a2
1048    4       1          a1-1
1048    5       4          a1-1-1
1048    6       3          a3-1
------------------------------------
</code>```

and I won't make the same result with MariaDB.

```<code>------------------------------------
num     id   parentid       data1
------------------------------------
1048    1       0          a1
1048    4       1          a1-1
1048    5       4          a1-1-1
1048    2       0          a2
1048    3       0          a3
1048    6       3          a3-1
-------------------------------------
</code>```

any good ideas?
thanks always.

答:
I do not use MariaDB, but as I see in documentation it supports recursive common table expressions. So you can write something like:

```<code>with recursive rcte as (
  select num, id, parentid, data1 from table_name where parentid = 0 and num = 1048
  union all
  select t.num, t.id, t.parentid, t.data1
    from table_name t join rcte on t.parentid = rcte.id and t.num = rcte.num)
select * from rcte
</code>```

MariaDB dbfiddle

Oracle dbfiddle

If you want to reproduce Oracle order by siblings you need to create hierarchy column and use it for ordering:

```<code>with recursive rcte as (
  select cast(id as char) AS hierarchy, num, id, parentid, data1
    from table_name where parentid = 0 and num = 1048
  union all
  select concat(rcte.hierarchy, '-', t.id), t.num, t.id, t.parentid, t.data1
    from table_name t join rcte on t.parentid = rcte.id and t.num = rcte.num)
select *
   from rcte
   order by hierarchy
</code>```

Body:
I have to move from Oracle to MariaDB 10.3.21.
spent the whole day on this.
I made a query with "start with" and "connect by prior" and "order sibling by" for oracle.

        select * from (select * from table_name ";
        where num = 1045 ) ";
        start with parentid = 0 ";
        connect by prior id = parentid ";
        order siblings by parentid asc ";

but MariaDB doesn't work.
used recursive but didn't go well.
anyone can share a good idea?

this is the original table.

------------------------------------
num     id   parentid       data1
------------------------------------
1045    11      4          zzzzz
1048    3       0          a3
1048    1       0          a1
1050    21      17         eeeee
1048    2       0          a2
1048    4       1          a1-1
1048    5       4          a1-1-1
1048    6       3          a3-1
------------------------------------

and I won't make the same result with MariaDB.

------------------------------------
num     id   parentid       data1
------------------------------------
1048    1       0          a1
1048    4       1          a1-1
1048    5       4          a1-1-1
1048    2       0          a2
1048    3       0          a3
1048    6       3          a3-1
-------------------------------------

any good ideas?
thanks always.

Body:
I do not use MariaDB, but as I see in documentation it supports recursive common table expressions. So you can write something like:

with recursive rcte as (
  select num, id, parentid, data1 from table_name where parentid = 0 and num = 1048
  union all
  select t.num, t.id, t.parentid, t.data1
    from table_name t join rcte on t.parentid = rcte.id and t.num = rcte.num)
select * from rcte

MariaDB dbfiddle

Oracle dbfiddle

If you want to reproduce Oracle order by siblings you need to create hierarchy column and use it for ordering:

with recursive rcte as (
  select cast(id as char) AS hierarchy, num, id, parentid, data1
    from table_name where parentid = 0 and num = 1048
  union all
  select concat(rcte.hierarchy, '-', t.id), t.num, t.id, t.parentid, t.data1
    from table_name t join rcte on t.parentid = rcte.id and t.num = rcte.num)
select *
   from rcte
   order by hierarchy


问:
How to edit, compile and read MQL4 files using Python?
I am trying to automate the editing, compiling and reading of results of MQL4 file using python, are there any tools like selenium but targeted for UI?</p>

答:
What works for me is two things:

First option: clear the strategy tester logs, use comments in the code with specific string format, copy the logs and parse the data from the comments using python.

Second option: parse the expert advisor report using Python, from HTML to pandas dataframe for further processing.


问:
How can I reshape (120, 100, 100) shaped image data to (120, 10000) shape to undersample using "imblearn" library of Python?
I am working with imblearn library of Python for undersampling.

Necessary code:

```<code>undersample = RandomUnderSampler(sampling_strategy='majority')
X_under, y_under = undersample.fit_resample(X, y)
</code>```

Here X is my image dataset & of (120, 100, 100) shape and y is images' labels which is of (120,) shape. I am getting an error here.
But if I give X of shape (x_value, y_value) then it works.
Is there any way I can convert (120, 100, 100) shape of image data to (120, 10000) shape?

答:
convert the image data into an numpy array and then reshape, that would solve it </p>

```<code>import numpy as np
# assuming X is the image data of shape (120,100,100)
X = np.asarray(image)
X_reshape = X.reshape(120,10000)
</code>```

Body:
I am working with imblearn library of Python for undersampling.

Necessary code:

undersample = RandomUnderSampler(sampling_strategy='majority')
X_under, y_under = undersample.fit_resample(X, y)

Here X is my image dataset & of (120, 100, 100) shape and y is images' labels which is of (120,) shape. I am getting an error here.
But if I give X of shape (x_value, y_value) then it works.
Is there any way I can convert (120, 100, 100) shape of image data to (120, 10000) shape?

Body:
convert the image data into an numpy array and then reshape, that would solve it

import numpy as np
# assuming X is the image data of shape (120,100,100)
X = np.asarray(image)
X_reshape = X.reshape(120,10000)


问:
Can you translate this into ggplot?
So basically, I would like to use ggplot function geom_line + geom_point to create the same plots but with fancier graphics.

```<code>> a
          V1        V2        V3
1  0.8224887 0.7882316 0.7596440
2  0.7892779 0.7604186 0.7409430
3  0.8254516 0.8257800 0.8014778
4  0.8268519 0.7887464 0.7887322
5  0.8226651 0.7981079 0.7934783

plot(6:10, a$V1, type="l", xlab="Folds", ylab="Accuracy", col="Blue",ylim=c(0.7,0.9))
par(new=TRUE)
plot(6:10, a$V2, type="l", xlab="Folds", ylab="Accuracy", col="Orange",ylim=c(0.7,0.9))
par(new=TRUE)
plot(6:10, a$V3, type="l", xlab="Folds", ylab="Accuracy", col="Green",ylim=c(0.7,0.9))

</code>```

My main goal is to get a legend that helps to distinguish each variable.

I tried to plot just the first line:

```<code>ggplot(data = a)+
  theme_classic()+
  geom_line(aes(x=6:10, y = a$V1, color = "blue"))
</code>```

The problem is that i don't even get the color I want.

Thanks for reading and helping!

答:
```<code>library(tidyverse)

originalData <- tibble(
  V1=c(0.8224887, 0.7892779, 0.8254516, 0.8268519, 0.8226651),
  V2=c(0.7882316, 0.7604186, 0.8257800, 0.7887464, 0.7981079),
  V3=c(0.7596440, 0.7409430, 0.8014778, 0.7887322, 0.7934783)
)

# ggplot works best if your data is 'tidy'
tidyData <- originalData %>%
              pivot_longer(cols=c(V1, V2, V3), names_to="Variable") %>%
              add_column(X=rep(6:10, each=3))

tidyData

tidyData %>%
  ggplot(aes(x=X, y=value, colour=Variable)) +
    geom_line() +
    theme_classic()
</code>```

Giving

You can customise your plot from here as you like.

Title: Can you translate this into ggplot?

Body:
So basically, I would like to use ggplot function geom_line + geom_point to create the same plots but with fancier graphics.

> a
          V1        V2        V3
1  0.8224887 0.7882316 0.7596440
2  0.7892779 0.7604186 0.7409430
3  0.8254516 0.8257800 0.8014778
4  0.8268519 0.7887464 0.7887322
5  0.8226651 0.7981079 0.7934783

plot(6:10, a$V1, type="l", xlab="Folds", ylab="Accuracy", col="Blue",ylim=c(0.7,0.9))
par(new=TRUE)
plot(6:10, a$V2, type="l", xlab="Folds", ylab="Accuracy", col="Orange",ylim=c(0.7,0.9))
par(new=TRUE)
plot(6:10, a$V3, type="l", xlab="Folds", ylab="Accuracy", col="Green",ylim=c(0.7,0.9))

My main goal is to get a legend that helps to distinguish each variable.

I tried to plot just the first line:

ggplot(data = a)+
  theme_classic()+
  geom_line(aes(x=6:10, y = a$V1, color = "blue"))

The problem is that i don't even get the color I want.

Thanks for reading and helping!

Body:
library(tidyverse)

originalData <- tibble(
  V1=c(0.8224887, 0.7892779, 0.8254516, 0.8268519, 0.8226651),
  V2=c(0.7882316, 0.7604186, 0.8257800, 0.7887464, 0.7981079),
  V3=c(0.7596440, 0.7409430, 0.8014778, 0.7887322, 0.7934783)
)

# ggplot works best if your data is 'tidy'
tidyData <- originalData %>%
              pivot_longer(cols=c(V1, V2, V3), names_to="Variable") %>%
              add_column(X=rep(6:10, each=3))

tidyData

tidyData %>%
  ggplot(aes(x=X, y=value, colour=Variable)) +
    geom_line() +
    theme_classic()

Giving

You can customise your plot from here as you like.


问:
How to change Vector Objects into different colours?
I've been trying to get my code to change vectors objects into different colours. I've put an example of two of the methods I've used for vectors and getting colours. Does anyone have any information on how to do this?</p>

```<code>#include <iostream>
#include <vector>
#include <windows.h>

std::vector<std::string> playerInventory;

int main() {

    HANDLE color = GetStdHandle(STD_OUTPUT_HANDLE); //just once
    SetConsoleTextAttribute(color, 10);
    std::cout << "This";
    SetConsoleTextAttribute(color, 11);
    std::cout << " is";
    SetConsoleTextAttribute(color, 12);
    std::cout << " a";
    SetConsoleTextAttribute(color, 13);
    std::cout << " colour";
    SetConsoleTextAttribute(color, 14);
    std::cout << " combination" << std::endl;

    playerInventory.push_back("1");
    playerInventory.push_back("2");
    playerInventory.push_back("3");
    playerInventory.push_back("4");

    for (int x = 0; x != playerInventory.size(); ++x)
    {
        std::cout << playerInventory[x] << std::endl;
    }
}
</code>```

答:
You seem to already know how to change the colors, so what you need to do is just change the color inside your loop, for each element of the vector. Example:

```<code>for ( int x = 0; x != playerInventory.size(); ++x ) {
    SetConsoleTextAttribute( color, 10 + x );
    std::cout << playerInventory[x] << std::endl;
}
</code>```

Keep in mind though, that there's only so many valid values from SetConsoleTextAttribute's wAttribute parameter

Body:
I've been trying to get my code to change vectors objects into different colours. I've put an example of two of the methods I've used for vectors and getting colours. Does anyone have any information on how to do this?

#include <iostream>
#include <vector>
#include <windows.h>

std::vector<std::string> playerInventory;

int main() {

    HANDLE color = GetStdHandle(STD_OUTPUT_HANDLE); //just once
    SetConsoleTextAttribute(color, 10);
    std::cout << "This";
    SetConsoleTextAttribute(color, 11);
    std::cout << " is";
    SetConsoleTextAttribute(color, 12);
    std::cout << " a";
    SetConsoleTextAttribute(color, 13);
    std::cout << " colour";
    SetConsoleTextAttribute(color, 14);
    std::cout << " combination" << std::endl;

    playerInventory.push_back("1");
    playerInventory.push_back("2");
    playerInventory.push_back("3");
    playerInventory.push_back("4");

    for (int x = 0; x != playerInventory.size(); ++x)
    {
        std::cout << playerInventory[x] << std::endl;
    }
}

Body:
You seem to already know how to change the colors, so what you need to do is just change the color inside your loop, for each element of the vector. Example:

for ( int x = 0; x != playerInventory.size(); ++x ) {
    SetConsoleTextAttribute( color, 10 + x );
    std::cout << playerInventory[x] << std::endl;
}

Keep in mind though, that there's only so many valid values from SetConsoleTextAttribute's wAttribute parameter


问:
php project to connect to a hardware
i am trying to build a schedule system in php that on pre-specified times will trigger an alarm...
the programming part in php/html in order to create a schedule and to connect to a database is easy for me but what i have no idea what is the required hardware that i need.

i think i need some device that will be connected to the webserver and to the alarm that will "translate" php code to an electrical signal that will trigger the alarm.
have anyone got any idea what this device is? where can i acquire it? am i on the right track?
can i find something that has a php API ?

thanks in advance for your time and help

答:
You may try and use an alarm connected on the serial port(they should be pretty easy to master if you have some electrical skills).

There are relay boards that connect through the serial port, and you can trigger basically anything with them.

http://www.electronickits.com/kit/complete/elec/ck1610.htm

http://www.controlanything.com/Relay/Relay/CAT_RELAY16_RS232

Also take a look at http://www.serialporttool.com/RelayTimerInfo.htm

For comunicating with the serial port, you can try and use http://www.phpclasses.org/package/3679-PHP-Communicate-with-a-serial-port.html . I used this class once when trying to interface with a phone via serial commands and it did not work as expected, but i'm pretty sure it was the phone's fault (i had problems with other tools as well)

Title: php project to connect to a hardware


问:
How to write a function with a for loop to check tic tac toe wins
I want to write a function with a for loop that checks for wining combination for a tic tac toe game based on a given list (board) and a marker ('X','O').

I was able to achieve this for the row wins with this for loop statement

```<code>def win_check(board, mark):
    # Win tic tac toe?

    board = board[1:]

    # ALL ROWS, and check to see if they all share the same marker?
    # i used `for loop` to achieve the row wins check.
    # But if there is another way to achieve it with this `r_win = [[9,8,7],[6,5,4],[3,2,1]]`

    # This works fine for the row checks
    for i in reversed(range(3)):
        if board[i*3] in mark and board[i*3+1] in mark and board[i*3+2] in mark:
            return True
    else:
        return False

    # ALL COLUMNS, check to see if marker matches

    c_win = [[7,4,1],[8,5,2],[9,6,3]] # i created this list if it can be used to make check for column wins.

    for i in c_win:
        # if statement goes here to check columns wins
            return True # and return true if there is a match
    else:
        return False

    # 2 diagonals, check to see match
    d_win = [[9,5,1],[7,5,3]] # i created this list if it can be used to make check for diagonal wins.

    for i in d_win:
        # if statement goes here to check diagonal wins
            return True # and return true if there is a match
    else:
        return False

</code>```

example function call

test_board = ['#','X','O','X','X','X','X','O','X','X']

win_check(test_board,'X')

答:
For this case, use 'X' for a space occupied by X, 'O' for a space occupied by O, and None for an empty space.

def test_equal(index1, index2, index3):
    if index1 is not None and index1 == index2 and index2 == index3:
        return index1 # either 'X' or 'O'
    else:
        return False

def get_winner(board):
    '''Test for win, where board is a :list: [7, 8, 9, 4, 5, 6, 1, 2, 3]'''
    b1, b2, b3 = board[6:]
    b4, b5, b6 = board[3:6]
    b7, b8, b9 = board[:3]
    wins = (
        test_equal(b1, b2, b3),
        test_equal(b4, b5, b6),
        test_equal(b7, b8, b9),
        test_equal(b1, b4, b7),
        test_equal(b2, b5, b8),
        test_equal(b3, b6, b9),
        test_equal(b1, b5, b9),
        test_equal(b3, b5, b7)
        )
    return 'X' if 'X' in wins else ('O' if 'O' in wins else False)
```

<p>Function <code>get_winner()</code> will return <code>'X'</code> if X is the winner (or both sides win, but that should not be a problem as you should be checking for a winner every turn), <code>'O'</code> if O is the winner, and <code>False</code> if nobody wins. The code I wrote is case sensitive, so <code>'x'</code> or <code>'o'</code> won't work!</p>

<p>Here is sample output:</p>

<pre class="lang-py prettyprint-override"><code>>>> x = 'X'
>>> o = 'O'
>>> n = None
>>> get_winner((x,x,x, n,n,n, n,o,o))
'X'
>>> get_winner((x,n,n, o,x,o, o,o,x))
'X'
>>> get_winner((x,x,n, x,x,n, o,o,o))
'O'
>>> get_winner((x,o,o, x,o,o, n,x,n))
False
>>>
</code>```

Body:
I want to write a function with a for loop that checks for wining combination for a tic tac toe game based on a given list (board) and a marker ('X','O').

I was able to achieve this for the row wins with this for loop statement

def win_check(board, mark):
    # Win tic tac toe?

    board = board[1:]

    # ALL ROWS, and check to see if they all share the same marker?
    # i used `for loop` to achieve the row wins check.
    # But if there is another way to achieve it with this `r_win = [[9,8,7],[6,5,4],[3,2,1]]`

    # This works fine for the row checks
    for i in reversed(range(3)):
        if board[i*3] in mark and board[i*3+1] in mark and board[i*3+2] in mark:
            return True
    else:
        return False

    # ALL COLUMNS, check to see if marker matches

    c_win = [[7,4,1],[8,5,2],[9,6,3]] # i created this list if it can be used to make check for column wins.

    for i in c_win:
        # if statement goes here to check columns wins
            return True # and return true if there is a match
    else:
        return False

    # 2 diagonals, check to see match
    d_win = [[9,5,1],[7,5,3]] # i created this list if it can be used to make check for diagonal wins.

    for i in d_win:
        # if statement goes here to check diagonal wins
            return True # and return true if there is a match
    else:
        return False

example function call

test_board = ['#','X','O','X','X','X','X','O','X','X']

win_check(test_board,'X')

Body:
For this case, use 'X' for a space occupied by X, 'O' for a space occupied by O, and None for an empty space.

def test_equal(index1, index2, index3):
    if index1 is not None and index1 == index2 and index2 == index3:
        return index1 # either 'X' or 'O'
    else:
        return False

def get_winner(board):
    '''Test for win, where board is a :list: [7, 8, 9, 4, 5, 6, 1, 2, 3]'''
    b1, b2, b3 = board[6:]
    b4, b5, b6 = board[3:6]
    b7, b8, b9 = board[:3]
    wins = (
        test_equal(b1, b2, b3),
        test_equal(b4, b5, b6),
        test_equal(b7, b8, b9),
        test_equal(b1, b4, b7),
        test_equal(b2, b5, b8),
        test_equal(b3, b6, b9),
        test_equal(b1, b5, b9),
        test_equal(b3, b5, b7)
        )
    return 'X' if 'X' in wins else ('O' if 'O' in wins else False)

Function get_winner() will return 'X' if X is the winner (or both sides win, but that should not be a problem as you should be checking for a winner every turn), 'O' if O is the winner, and False if nobody wins. The code I wrote is case sensitive, so 'x' or 'o' won't work!

Here is sample output:

>>> x = 'X'
>>> o = 'O'
>>> n = None
>>> get_winner((x,x,x, n,n,n, n,o,o))
'X'
>>> get_winner((x,n,n, o,x,o, o,o,x))
'X'
>>> get_winner((x,x,n, x,x,n, o,o,o))
'O'
>>> get_winner((x,o,o, x,o,o, n,x,n))
False
>>>


问:
Compare 2 CSV Huge CSV Files and print the differences to another csv file using perl
I have 2 csv files of multiple fields(approx 30 fields), and huge size ( approx 4GB ).

```<code>File1:

EmployeeName,Age,Salary,Address
Vinoth,12,2548.245,"140,North Street,India"
Vivek,40,2548.245,"140,North Street,India"
Karthick,10,10.245,"140,North Street,India"

File2:

EmployeeName,Age,Salary,Address
Vinoth,12,2548.245,"140,North Street,USA"
Karthick,10,10.245,"140,North Street,India"
Vivek,40,2548.245,"140,North Street,India"
</code>```

I want to compare these 2 files and report the differences into another csv file. In the above example, Employee Vivek and Karthick details are present in different row numbers but still the record data is same, so it should be considered as match. Employee Vinoth record should be considered as a mismatch since there is a mismatch in the address.

Output diff.csv file can contain the mismatched record from the File1 and File 2 as below.

```<code>Diff.csv
EmployeeName,Age,Salary,Address
F1, Vinoth,12,2548.245,"140,North Street,India"
F2, Vinoth,12,2548.245,"140,North Street,USA"
</code>```

I've written the code so far as below. After this I'm confused which option to choose whether a Binary Search or any other efficient way to do this. Could you please help me?

```<code>My approach
1. Load the File2 in memory as hashes of hashes.
2.Read line by line from File1 and match it with the hash of hashes in memory.

use strict;
use warnings;
use Text::CSV_XS;
use Getopt::Long;
use Data::Dumper;
use Text::CSV::Hashify;
use List::BinarySearch qw( :all );

# Get Command Line Parameters

my %opts = ();
GetOptions( \%opts, "file1=s", "file2=s", )
  or die("Error in command line arguments\n");

if ( !defined $opts{'file1'} ) {
    die "CSV file --file1 not specified.\n";
}
if ( !defined $opts{'file2'} ) {
    die "CSV file --file2 not specified.\n";
}

my $file1 = $opts{'file1'};
my $file2 = $opts{'file2'};
my $file3 = 'diff.csv';

print $file2 . "\n";

my $csv1 =
  Text::CSV_XS->new(
    { binary => 1, auto_diag => 1, sep_char => ',', eol => $/ } );
my $csv2 =
  Text::CSV_XS->new(
    { binary => 1, auto_diag => 1, sep_char => ',', eol => $/ } );
my $csvout =
  Text::CSV_XS->new(
    { binary => 1, auto_diag => 1, sep_char => ',', eol => $/ } );

open( my $fh1, '<:encoding(utf8)', $file1 )
  or die "Cannot not open '$file1' $!.\n";
open( my $fh2, '<:encoding(utf8)', $file2 )
  or die "Cannot not open '$file2' $!.\n";
open( my $fh3, '>:encoding(utf8)', $file3 )
  or die "Cannot not open '$file3' $!.\n";
binmode( STDOUT, ":utf8" );

my $f1line   = undef;
my $f2line   = undef;
my $header1  = undef;
my $f1empty  = 'false';
my $f2empty  = 'false';
my $reccount = 0;
my $hash_ref = hashify( "$file2", 'EmployeeName' );
if ( $f1empty eq 'false' ) {
    $f1line = $csv1->getline($fh1);
}
while (1) {

    if ( $f1empty eq 'false' ) {
        $f1line = $csv1->getline($fh1);
    }
    if ( !defined $f1line ) {
        $f1empty = 'true';
    }

    if ( $f1empty eq 'true' ) {
        last;
    }
    else {
        ## Read each line from File1 and match it with the File 2 which is loaded as hashes of hashes in perl. Need help here.

        }
    }

print "End of Program" . "\n";
</code>```

答:
Storing data of such magnitude in database is most correct approach to tasks of this kind. At minimum SQLlite is recommended but other databases MariaDB, MySQL, PostgreSQL will work quite well.

Following code demonstrates how desired output can be achieved without special modules, but it does not take in account possibly messed up input data. This script will report data records as different even if difference can be just one extra space.

Default output is into console window unless you specify option output.

NOTE: Whole file #1 is read into memory, please be patient processing big files can take a while.

```<code>use strict;
use warnings;
use feature 'say';

use Getopt::Long qw(GetOptions);
use Pod::Usage;

my %opt;
my @args = (
            'file1|f1=s',
            'file2|f2=s',
            'output|o=s',
            'debug|d',
            'help|?',
            'man|m'
        );

GetOptions( \%opt, @args ) or pod2usage(2);

print Dumper(\%opt) if $opt{debug};

pod2usage(1) if $opt{help};
pod2usage(-exitval => 0, -verbose => 2) if $opt{man};

pod2usage(1) unless $opt{file1};
pod2usage(1) unless $opt{file2};

unlink $opt{output} if defined $opt{output} and -f $opt{output};

compare($opt{file1},$opt{file2});

sub compare {
    my $fname1 = shift;
    my $fname2 = shift;

    my $hfile1 = file2hash($fname1);

    open my $fh, '<:encoding(utf8)', $fname2
        or die "Couldn't open $fname2";

    while(<$fh>) {
        chomp;
        next unless /^(.*?),(.*)$/;
        my($key,$data) = ($1, $2);
        if( !defined $hfile1->{$key} ) {
            my $msg = "$fname1 $key is missing";
            say_msg($msg);
        } elsif( $data ne $hfile1->{$key} ) {
            my $msg = "$fname1 $key,$hfile1->{$key}\n$fname2 $_";
            say_msg($msg);
        }
    }
}

sub say_msg {
    my $msg = shift;

    if( $opt{output} ) {
        open my $fh, '>>:encoding(utf8)', $opt{output}
            or die "Couldn't to open $opt{output}";

        say $fh $msg;

        close $fh;
    } else {
        say $msg;
    }
}

sub file2hash {
    my $fname = shift;
    my %hash;

    open my $fh, '<:encoding(utf8)', $fname
        or die "Couldn't open $fname";

    while(<$fh>) {
        chomp;
        next unless /^(.*?),(.*)$/;
        $hash{$1} = $2;

    }

    close $fh;

    return \%hash;
}

__END__

=head1 NAME

comp_cvs - compares two CVS files and stores differense

=head1 SYNOPSIS

 comp_cvs.pl -f1 file1.cvs -f2 file2.cvs -o diff.txt

 Options:
    -f1,--file1 input CVS filename #1
    -f2,--file2 input CVS filename #2
    -o,--output output filename
    -d,--debug  output debug information
    -?,--help   brief help message
    -m,--man    full documentation

=head1 OPTIONS

=over 4

=item B<-f1,--file1>

Input CVS filename #1

=item B<-f2,--file2>

Input CVS filename #2

=item B<-o,--output>

Output filename

=item B<-d,--debug>

Print debug information.

=item B<-?,--help>

Print a brief help message and exits.

=item B<--man>

Prints the manual page and exits.

=back

=head1 DESCRIPTION

B<This program> accepts B<input> and processes to B<output> with purpose of achiving some goal.

=head1 EXIT STATUS

The section describes B<EXIT STATUS> codes of the program

=head1 ENVIRONMENT

The section describes B<ENVIRONMENT VARIABLES> utilized in the program

=head1 FILES

The section describes B<FILES> which used for program's configuration

=head1 EXAMPLES

The section demonstrates some B<EXAMPLES> of the code

=head1 REPORTING BUGS

The section provides information how to report bugs

=head1 AUTHOR

The section describing author and his contanct information

=head1 ACKNOWLEDGMENT

The section to give credits people in some way related to the code

=head1 SEE ALSO

The section describing related information - reference to other programs, blogs, website, ...

=head1 HISTORY

The section gives historical information related to the code of the program

=head1 COPYRIGHT

Copyright information related to the code

=cut
</code>```

Output for test files

```<code>file1.cvs Vinoth,12,2548.245,"140,North Street,India"
file2.cvs Vinoth,12,2548.245,"140,North Street,USA"
</code>```

Body:
I have 2 csv files of multiple fields(approx 30 fields), and huge size ( approx 4GB ).

File1:

EmployeeName,Age,Salary,Address
Vinoth,12,2548.245,"140,North Street,India"
Vivek,40,2548.245,"140,North Street,India"
Karthick,10,10.245,"140,North Street,India"

File2:

EmployeeName,Age,Salary,Address
Vinoth,12,2548.245,"140,North Street,USA"
Karthick,10,10.245,"140,North Street,India"
Vivek,40,2548.245,"140,North Street,India"

I want to compare these 2 files and report the differences into another csv file. In the above example, Employee Vivek and Karthick details are present in different row numbers but still the record data is same, so it should be considered as match. Employee Vinoth record should be considered as a mismatch since there is a mismatch in the address.

Output diff.csv file can contain the mismatched record from the File1 and File 2 as below.

Diff.csv
EmployeeName,Age,Salary,Address
F1, Vinoth,12,2548.245,"140,North Street,India"
F2, Vinoth,12,2548.245,"140,North Street,USA"

I've written the code so far as below. After this I'm confused which option to choose whether a Binary Search or any other efficient way to do this. Could you please help me?

My approach
1. Load the File2 in memory as hashes of hashes.
2.Read line by line from File1 and match it with the hash of hashes in memory.

use strict;
use warnings;
use Text::CSV_XS;
use Getopt::Long;
use Data::Dumper;
use Text::CSV::Hashify;
use List::BinarySearch qw( :all );

# Get Command Line Parameters

my %opts = ();
GetOptions( \%opts, "file1=s", "file2=s", )
  or die("Error in command line arguments\n");

if ( !defined $opts{'file1'} ) {
    die "CSV file --file1 not specified.\n";
}
if ( !defined $opts{'file2'} ) {
    die "CSV file --file2 not specified.\n";
}

my $file1 = $opts{'file1'};
my $file2 = $opts{'file2'};
my $file3 = 'diff.csv';

print $file2 . "\n";

my $csv1 =
  Text::CSV_XS->new(
    { binary => 1, auto_diag => 1, sep_char => ',', eol => $/ } );
my $csv2 =
  Text::CSV_XS->new(
    { binary => 1, auto_diag => 1, sep_char => ',', eol => $/ } );
my $csvout =
  Text::CSV_XS->new(
    { binary => 1, auto_diag => 1, sep_char => ',', eol => $/ } );

open( my $fh1, '<:encoding(utf8)', $file1 )
  or die "Cannot not open '$file1' $!.\n";
open( my $fh2, '<:encoding(utf8)', $file2 )
  or die "Cannot not open '$file2' $!.\n";
open( my $fh3, '>:encoding(utf8)', $file3 )
  or die "Cannot not open '$file3' $!.\n";
binmode( STDOUT, ":utf8" );

my $f1line   = undef;
my $f2line   = undef;
my $header1  = undef;
my $f1empty  = 'false';
my $f2empty  = 'false';
my $reccount = 0;
my $hash_ref = hashify( "$file2", 'EmployeeName' );
if ( $f1empty eq 'false' ) {
    $f1line = $csv1->getline($fh1);
}
while (1) {

    if ( $f1empty eq 'false' ) {
        $f1line = $csv1->getline($fh1);
    }
    if ( !defined $f1line ) {
        $f1empty = 'true';
    }

    if ( $f1empty eq 'true' ) {
        last;
    }
    else {
        ## Read each line from File1 and match it with the File 2 which is loaded as hashes of hashes in perl. Need help here.

        }
    }

print "End of Program" . "\n";

Body:
Storing data of such magnitude in database is most correct approach to tasks of this kind. At minimum SQLlite is recommended but other databases MariaDB, MySQL, PostgreSQL will work quite well.

Following code demonstrates how desired output can be achieved without special modules, but it does not take in account possibly messed up input data. This script will report data records as different even if difference can be just one extra space.

Default output is into console window unless you specify option output.

NOTE: Whole file #1 is read into memory, please be patient processing big files can take a while.

use strict;
use warnings;
use feature 'say';

use Getopt::Long qw(GetOptions);
use Pod::Usage;

my %opt;
my @args = (
            'file1|f1=s',
            'file2|f2=s',
            'output|o=s',
            'debug|d',
            'help|?',
            'man|m'
        );

GetOptions( \%opt, @args ) or pod2usage(2);

print Dumper(\%opt) if $opt{debug};

pod2usage(1) if $opt{help};
pod2usage(-exitval => 0, -verbose => 2) if $opt{man};

pod2usage(1) unless $opt{file1};
pod2usage(1) unless $opt{file2};

unlink $opt{output} if defined $opt{output} and -f $opt{output};

compare($opt{file1},$opt{file2});

sub compare {
    my $fname1 = shift;
    my $fname2 = shift;

    my $hfile1 = file2hash($fname1);

    open my $fh, '<:encoding(utf8)', $fname2
        or die "Couldn't open $fname2";

    while(<$fh>) {
        chomp;
        next unless /^(.*?),(.*)$/;
        my($key,$data) = ($1, $2);
        if( !defined $hfile1->{$key} ) {
            my $msg = "$fname1 $key is missing";
            say_msg($msg);
        } elsif( $data ne $hfile1->{$key} ) {
            my $msg = "$fname1 $key,$hfile1->{$key}\n$fname2 $_";
            say_msg($msg);
        }
    }
}

sub say_msg {
    my $msg = shift;

    if( $opt{output} ) {
        open my $fh, '>>:encoding(utf8)', $opt{output}
            or die "Couldn't to open $opt{output}";

        say $fh $msg;

        close $fh;
    } else {
        say $msg;
    }
}

sub file2hash {
    my $fname = shift;
    my %hash;

    open my $fh, '<:encoding(utf8)', $fname
        or die "Couldn't open $fname";

    while(<$fh>) {
        chomp;
        next unless /^(.*?),(.*)$/;
        $hash{$1} = $2;

    }

    close $fh;

    return \%hash;
}

__END__

=head1 NAME

comp_cvs - compares two CVS files and stores differense

=head1 SYNOPSIS

 comp_cvs.pl -f1 file1.cvs -f2 file2.cvs -o diff.txt

 Options:
    -f1,--file1 input CVS filename #1
    -f2,--file2 input CVS filename #2
    -o,--output output filename
    -d,--debug  output debug information
    -?,--help   brief help message
    -m,--man    full documentation

=head1 OPTIONS

=over 4

=item B<-f1,--file1>

Input CVS filename #1

=item B<-f2,--file2>

Input CVS filename #2

=item B<-o,--output>

Output filename

=item B<-d,--debug>

Print debug information.

=item B<-?,--help>

Print a brief help message and exits.

=item B<--man>

Prints the manual page and exits.

=back

=head1 DESCRIPTION

B<This program> accepts B<input> and processes to B<output> with purpose of achiving some goal.

=head1 EXIT STATUS

The section describes B<EXIT STATUS> codes of the program

=head1 ENVIRONMENT

The section describes B<ENVIRONMENT VARIABLES> utilized in the program

=head1 FILES

The section describes B<FILES> which used for program's configuration

=head1 EXAMPLES

The section demonstrates some B<EXAMPLES> of the code

=head1 REPORTING BUGS

The section provides information how to report bugs

=head1 AUTHOR

The section describing author and his contanct information

=head1 ACKNOWLEDGMENT

The section to give credits people in some way related to the code

=head1 SEE ALSO

The section describing related information - reference to other programs, blogs, website, ...

=head1 HISTORY

The section gives historical information related to the code of the program

=head1 COPYRIGHT

Copyright information related to the code

=cut

Output for test files

file1.cvs Vinoth,12,2548.245,"140,North Street,India"
file2.cvs Vinoth,12,2548.245,"140,North Street,USA"


问:
Dynamically Updating a Variable in JS
My page has multiple videos on it and I'm trying to enable seeking through the YouTube API on all of them. These videos are generated dynamically, so I can't pre-define them all at once, unfortunately. If I could, the following would work:

```<code><script>
function onYouTubePlayerAPIReady() {
      player = new YT.Player('ytplayer1', {
      });
      player2 = new YT.Player('ytplayer3', {
      });
      player3 = new YT.Player('ytplayer3', {
      });
      etc. etc.
}
function onPlayerReady(event) {
    event.target.playVideo();
}
function seek(sec){
    if(player){
        seconds += sec;
        player.seekTo(seconds, true);
    }
}

</script>
</code>```

But because each page will have a different number of dynamically generated videos, I'm running into an issue.

I can make the first and last videos work using the following code:

```<code>#Initial javascript + first video
<script>
function onYouTubePlayerAPIReady() {
      player = new YT.Player('ytplayer1', {
      });
}
function onPlayerReady(event) {
    event.target.playVideo();
}
function seek(sec){
    if(player){
        seconds += sec;
        player.seekTo(seconds, true);
    }
}
var old_foo = onYouTubePlayerAPIReady;
</script>

<iframe id="ytplayer1" width="789" height="444" src="https://www.youtube.com/embed/p4vLPmVAwlo?enablejsapi=1" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<button type="button" onclick="player.seekTo(60)">60s</button>
<button type="button" onclick="player.seekTo(120)">120s</button>

#Second video plus the JS to go with it
<iframe id="ytplayer2" width="789" height="444" src="https://www.youtube.com/embed/_9ahu4c5zdI?enablejsapi=1" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<button type="button" onclick="player2.seekTo(60)">60s</button>
<button type="button" onclick="player2.seekTo(120)">120s</button>

<script>
function onYouTubePlayerAPIReady() {
  old_foo();
  player2 = new YT.Player('ytplayer2', {
  });
}

</script>
</code>```

But whenever I try to add another, the middle ones stop working. It seems like my final call of the onYouTubePlayerAPIReady function is overwriting everything before it, without executing the function at each step. I've tried updating my old_foo var, the onYouTubePlayerAPIReady function, defining a new var, etc. None of it seems to work! But I also suck at javascript so I'm sure I'm just missing something simple.

Help?

答:
The onYouTubePlayerAPIReady() function is called automatically when the player API code has loaded, so you only need to define it once. Inside of that, you should be able to define your multiple players. Your JS could be condensed into the following:

```<code><script>
    function onYouTubePlayerAPIReady() {
      player = new YT.Player('ytplayer1', {
      });
      player2 = new YT.Player('ytplayer2', {
      });
    }
</script>
</code>```

Working CodePen using onYouTubeIframeAPIReady instead of onYouTubePlayerAPIReady: https://codepen.io/edlucas/pen/wvKVVaP

Also see: https://developers.google.com/youtube/iframe_api_reference

EDIT

If you need to create the markup on the fly and still want to load them all when the API is ready, one way is to queue the videos up in an array that's used when onYouTubePlayerAPIReady is called.

```<code>var videos = ['ytplayer1', 'ytplayer2'];
var players = [];

function onYouTubeIframeAPIReady() {
    videos.forEach((video, i) =>
        players[i] = new YT.Player(video, {
            events: {
                'onReady': onPlayerReady,
            }
        });
   };
}
</code>```

You can then use your favorite method to add videos to the array, (e.g. videos.push('ytplayer3')) as long as you do it before the API is added to the page, or at least before it's ready.

Title: Dynamically Updating a Variable in JS

Body:
My page has multiple videos on it and I'm trying to enable seeking through the YouTube API on all of them. These videos are generated dynamically, so I can't pre-define them all at once, unfortunately. If I could, the following would work:

But because each page will have a different number of dynamically generated videos, I'm running into an issue.

I can make the first and last videos work using the following code:

#Initial javascript + first video

<button type="button" onclick="player.seekTo(60)">60s</button>
<button type="button" onclick="player.seekTo(120)">120s</button>

#Second video plus the JS to go with it

<button type="button" onclick="player2.seekTo(60)">60s</button>
<button type="button" onclick="player2.seekTo(120)">120s</button>

But whenever I try to add another, the middle ones stop working. It seems like my final call of the onYouTubePlayerAPIReady function is overwriting everything before it, without executing the function at each step. I've tried updating my old_foo var, the onYouTubePlayerAPIReady function, defining a new var, etc. None of it seems to work! But I also suck at javascript so I'm sure I'm just missing something simple.

Help?

Body:
The onYouTubePlayerAPIReady() function is called automatically when the player API code has loaded, so you only need to define it once. Inside of that, you should be able to define your multiple players. Your JS could be condensed into the following:

<script>
    function onYouTubePlayerAPIReady() {
      player = new YT.Player('ytplayer1', {
      });
      player2 = new YT.Player('ytplayer2', {
      });
    }
</script>

Working CodePen using onYouTubeIframeAPIReady instead of onYouTubePlayerAPIReady: https://codepen.io/edlucas/pen/wvKVVaP

Also see: https://developers.google.com/youtube/iframe_api_reference

EDIT

If you need to create the markup on the fly and still want to load them all when the API is ready, one way is to queue the videos up in an array that's used when onYouTubePlayerAPIReady is called.

var videos = ['ytplayer1', 'ytplayer2'];
var players = [];

function onYouTubeIframeAPIReady() {
    videos.forEach((video, i) =>
        players[i] = new YT.Player(video, {
            events: {
                'onReady': onPlayerReady,
            }
        });
   };
}

You can then use your favorite method to add videos to the array, (e.g. videos.push('ytplayer3')) as long as you do it before the API is added to the page, or at least before it's ready.


问:
Combobox change value of other combobox
I have two comboboxes on an form. Each has the values Yes and No. What I want is when one is changed the other get the opposite (if the first is Yes the other is No).I need to do it with Javascript. I saw this question How to change "selected" value in combobox using JavaScript? but it is applied to only one combobox.

How can I do this?

LE:I need this example to be make with comboboxes. I can not use radio buttons

答:
I believe this is what you are looking for:

```<code><select id="combo1" onchange="FlipOtherCombo(this, 'combo2')">
    <option value="yes">yes</option>
    <option value="no">no</option>
</select>
<select id="combo2" onchange="FlipOtherCombo(this, 'combo1')">
    <option value="yes">yes</option>
    <option selected="selected" value="no">no</option>
</select>

<script>
    function FlipOtherCombo(objCombo, strOtherComboId){
        if (objCombo.value ==="yes"){
            document.getElementById(strOtherComboId).value = "no";
        } else {
            document.getElementById(strOtherComboId).value = "yes";
        }
    }
</script>
</code>```

Also at this JSFiddle.

Although, using radio buttons for simple yes/no options like this is better.

Title: Combobox change value of other combobox

Body:
I believe this is what you are looking for:

<select id="combo1" onchange="FlipOtherCombo(this, 'combo2')">
    <option value="yes">yes</option>
    <option value="no">no</option>
</select>
<select id="combo2" onchange="FlipOtherCombo(this, 'combo1')">
    <option value="yes">yes</option>
    <option selected="selected" value="no">no</option>
</select>

<script>
    function FlipOtherCombo(objCombo, strOtherComboId){
        if (objCombo.value ==="yes"){
            document.getElementById(strOtherComboId).value = "no";
        } else {
            document.getElementById(strOtherComboId).value = "yes";
        }
    }
</script>

Also at this JSFiddle.

Although, using radio buttons for simple yes/no options like this is better.