text:
Q: different ylabel for each subplot in pandas.DataFrame.plot() I have a data frame df with two columns: df['A'] and df['B']. I am plotting my dataframe with df.plot(subplots=True). This produces a figure with two subplots, one for A and one for B.
Is there a way to use the ylabel keyword to assign different ylabel values to the two subplots? I tried with df.plot(subplots=True,ylabel=['A','B']) and hoped that the first element of the list was assigned to the first subplot and the second element to the second subplot. However, the labels of both subplots are set to '[A,B]'.

A: You can use the axes handles returned by df.plot:
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({"A": [1, 2, 3], "B": [2, 4, 1]})

axes = df.plot(subplots=True)
axes[0].set_ylabel("label1")
axes[1].set_ylabel("label2")
plt.show()


text:
Q: how to close a excel file without crashing if error occurs in the below code The below code i am trying to execute is corrupting the excel file whenever an exception occurs before closing the FileInputStream and FileOutPutStream. So i tried keeping try catch block and in the catch block closed FileInputStream and FileOutPutStream, still excel is getting crashed.
So i thought something like this if FileInputStream is not closed then close in catch block . If FileOutPutStream is not closed then close in catch block. But how to achieve this?
or
Is there any better way to handle this situation?
public void checkingAccountNumber() throws InterruptedException, IOException {

        WebDriverWait wait = new WebDriverWait(driver, 5);

        FileInputStream fis= new FileInputStream("C:\\Users\\vyerrami\\Desktop\\MA_Conversion_Data.xlsx");

        XSSFWorkbook wb= new XSSFWorkbook(fis);

        XSSFSheet sheet = wb.getSheet("DEFERRED");

        int noOfRows=sheet.getPhysicalNumberOfRows();

        try {

        for(int i=1; i<noOfRows; i++) {
            DataFormatter d = new DataFormatter();
            String cellvalue = d.formatCellValue(sheet.getRow(i).getCell(5));

            String firstcellvalue=d.formatCellValue(sheet.getRow(i).getCell(0));

            if(firstcellvalue.isEmpty()) {
                driver.findElement(quickJump).click();
                driver.findElement(quickJump).sendKeys("AccountSearch");
                Thread.sleep(2000);
                driver.findElement(quickJump).sendKeys(Keys.ENTER);

                wait.until(ExpectedConditions.invisibilityOf(driver.findElement(loading)));

                driver.findElement(accountSearchAccountNumberField).clear();
                driver.findElement(accountSearchAccountNumberField).sendKeys(cellvalue);
                driver.findElement(accountSearchAccountNumberField).sendKeys(Keys.TAB);

                driver.findElement(accountSearchSearchButton).click();
                wait.until(ExpectedConditions.invisibilityOf(driver.findElement(loading)));

                    if (driver.findElements(By.id("AccountSearch:AccountSearchScreen:AccountSearchResultsLV:0:AccountNumber")).size() > 0) {
                        if (driver.findElement(By.id("AccountSearch:AccountSearchScreen:AccountSearchResultsLV:0:AccountNumber")).getText().contains(cellvalue)) {
                            driver.findElement(By.id("AccountSearch:AccountSearchScreen:AccountSearchResultsLV:0:AccountNumber"))
                                    .click();

                                fis.close();
                                FileOutputStream out = new FileOutputStream(
                                        "C:\\Users\\vyerrami\\Desktop\\MA_Conversion_Data.xlsx");

                                if(driver.findElements(policyFilePolicyNumber).size()>0) {

                                    sheet.getRow(i).createCell(0)
                                            .setCellValue(driver.findElement(policyFilePolicyNumber).getText());

                                    sheet.getRow(i).createCell(1)
                                            .setCellValue(driver.findElement(policyFileEffectiveDate).getText());
                                    wb.write(out);
                                    out.close();
                                }
                                else {
                                    sheet.getRow(i).createCell(0)
                                    .setCellValue("Policy Number is not present");
                                    wb.write(out);
                                    out.close();
                                }

                        }

                        }

                    else {
                        FileOutputStream out = new FileOutputStream(
                                "C:\\Users\\vyerrami\\Desktop\\MA_Conversion_Data.xlsx");
                        sheet.getRow(i).createCell(0)
                        .setCellValue("Account Number is not present");
                        wb.write(out);
                        out.close();

                    }

            }

        }
        }

    catch(Exception e)
    {

    //i want to write the code if fis is not closed then i have to close
    //i want to write the code is out is not closed then i have to close

    }

}

EDIT CODE WHICH IS WORKING IS BELOW:
FileInputStream fis=null;
        FileOutputStream out1=null;
        XSSFWorkbook workbook= null;
        XSSFSheet sheet = null;

try {
            fis = new FileInputStream("C:\\Users\\vyerrami\\Desktop\\VINS.xlsx");
            out1 = new FileOutputStream("C:\\Users\\vyerrami\\Desktop\\VINS.xlsx");
            workbook = new XSSFWorkbook(fis);
            sheet = workbook.getSheet("VINS");

            int noOfRows = sheet.getPhysicalNumberOfRows();

            for (int i = 0; i < 100; i++) {
                driver.findElement(createVehicleButton).click();
                wait.until(ExpectedConditions.invisibilityOf(driver.findElement(loading)));

                driver.findElement(EnterVinNumber).clear();

                driver.findElement(EnterVinNumber).sendKeys(sheet.getRow(i).getCell(0).getStringCellValue());
                driver.findElement(EnterVinNumber).sendKeys(Keys.TAB);
                wait.until(ExpectedConditions.invisibilityOf(driver.findElement(loading)));

                driver.findElement(vehicleInquiryButton).click();
                wait.until(ExpectedConditions.invisibilityOf(driver.findElement(loading)));

                System.out.println(driver
                        .findElement(By.xpath(
                                "//*[@id='VehicleInquiryReportPopup:2-body']/div/div/table[2]/tbody/tr/td[2]/div"))
                        .getText());
                System.out.println(driver
                        .findElement(By.xpath(
                                "//*[@id='VehicleInquiryReportPopup:2-body']/div/div/table[2]/tbody/tr/td[3]/div"))
                        .getText());

                if (driver
                        .findElement(By.xpath(
                                "//*[@id='VehicleInquiryReportPopup:2-body']/div/div/table[2]/tbody/tr/td[2]/div"))
                        .getText().equalsIgnoreCase("null null")
                        || !driver.findElement(By.xpath(
                                "//*[@id='VehicleInquiryReportPopup:2-body']/div/div/table[2]/tbody/tr/td[3]/div"))
                                .getText().equalsIgnoreCase("null null") && (sheet.getRow(i).getCell(1).getStringCellValue().isEmpty())) {
                    fis.close();
                    sheet.getRow(i).createCell(1).setCellValue("Not Leased");
                    workbook.write(out1);
                    out1.close();
                    workbook.close();

                }

                else {
                    fis.close();
                    sheet.getRow(i).createCell(1).setCellValue("Leased");
                    workbook.write(out1);
                    out1.close();
                    workbook.close();
                }

                driver.findElement(By.id("VehicleInquiryReportPopup:__crumb__")).click();
                wait.until(ExpectedConditions.invisibilityOf(driver.findElement(loading)));

                driver.findElement(By.xpath(
                        "//*[@id='SubmissionWizard:LOBWizardStepGroup:LineWizardStepSet:PAVehiclesScreen:PAVehiclesPanelSet:VehiclesListDetailPanel:VehiclesLV-body']/div/div/table/tbody/tr/td/div/img"))
                        .click();
                driver.findElement(By.id(
                        "SubmissionWizard:LOBWizardStepGroup:LineWizardStepSet:PAVehiclesScreen:PAVehiclesPanelSet:VehiclesListDetailPanel_tb:Remove"))
                        .click();
                wait.until(ExpectedConditions.invisibilityOf(driver.findElement(loading)));

            }

        }

        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            if(fis!=null) {
                fis.close();
            }
            if(out1!=null) {
                out1.close();
            }
        }

    }

A: I think, that you are looking for try with resource. It's sugar syntax for opening stream in try block and closing it in finally block. This way whatever happens in try block, stream is closed.
In most cases, you should open streams as late as possible and close them as soon as possible. Try to make smaller methods, so it is easier to debug them later.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Control high order moments by lower order moment? Let $X$ be a random variable and suppose that we have $E(|X|) <+\infty$ and $E(|X|^2)<+\infty$. In particulary, I can find a constant C such that
$$
E(|X|^2) < C\quad\quad (1)
$$
I consider the higher moments of $X$ as $E(|X|^{2p})$ where $p>1$. I have two questions:
1) Can we always conclude that $E(|X|^{2p}) < + \infty$ by using (1) (maybe not!) or it depends on the properties of $X$?
2) Suppose that $E(|X|^{2p}) < + \infty$ and if I want to find an upper bound for $E(|X|^{2p})$. Is there any inequality that allow us to find the upper bound by using (1)?
Thank you in advance for any answer.

A: To see the answer is no to both questions, you can consider the following counter examples
1. We can have $\mathbb E(X^{2p})=\infty$
Let us assume $P(X)\propto\frac1{|X|^\nu+1}$. If $\nu>1$, it is a well defined probability distribution, which has a finite $\mathbb{E}(|X|)$ for $\nu>2$ and a finite  $\mathbb{E}(|X|^2)$ for $\nu>3$.
Actually we have
\begin{align}
  \mathbb{E}(|X|^\mu)&\text{ finite} & \text{if }&\mu<\nu\\
  \mathbb{E}(|X|^\mu)&=+\infty & \text{if }&\mu\ge\nu,
\end{align}
therefore, a good choice of $\nu$ allows set the rank after which all moments are infinite, even if all the lower moments are bounded
2. We can have really high finite $\mathbb E(X^{2p})$, even when  $\mathbb E(X^{2p})\le C$
Just look at the following simple probability distribution for $X$, defined for $\varepsilon>0$:
\begin{align}
 P(X=0)&=1-\varepsilon; &
 P\left(X=\sqrt{\frac C\varepsilon}\right)&=\varepsilon.
\end{align}
We have then, assuming $\varepsilon\ll 1$ and $p>1$
\begin{align}
  \mathbb E(|X|)&=\sqrt{\varepsilon C}&\ll \sqrt{C}\\
  \mathbb E(|X|^2)&=\varepsilon C&\\
  \mathbb E(|X|^{2p})&=\frac{C^p}{\varepsilon^{p-1}}& \gg C^p
\end{align}
Chosing a small enough $\varepsilon$ allows to choose a $E(|X|^{2p})$ arbitrary large, but finite, while keeping the first two moments below $C$.


text:
Q: $a^n+ b^n$ is not a prime number when $n$ is not a power of $2$. Suppose $a, b$ and $n$ are positive integers, $a+b>2$, and $n$ is not a power of $2$. Prove that $a^n+ b^n$ is not a prime number.

A: You can't "assume $n$ to be odd", but you can say that it has an odd factor $> 1$.

A: You can not assume it's odd, but you can assume it contains an odd factor.
Consider $n=2^k\cdot x$ where $x$ is odd.
$$a^n+b^n=a^{2^k\cdot x}+b^{2^k\cdot x}=(a^{2^k}+b^{2^k})(a^{2^k\cdot(x-1)}-a^{2^k\cdot(x-2)}b^{2^k}+...-b^{2^k\cdot(x-2)}a^{2^k}+b^{2^k\cdot(x-1)})$$
Since both brackets are greater than $1$, $a^n+b^n$ is composite.


text:
Q: How to remove /etc/udev/rules.d/70-persistent-net.rules CentOS I have a server that we are testing a stretched network failover with VMware Recover Point.  When the server moves over to the alternate site, the MAC address changes causing my network interface (eth0) to become eth1 due to the regeneration of the 70-persistent-net.rules file creating the new eth0 with a new MAC Address.
I would like to write a script at boot up that removes this file so udev creates it new, but am having difficulty knowing where to place it.  I tried /etc/rc1.d/S25_70, which is above the /etc/rc1.d/S26_udev-post, but it isn't working.
Thank you for any help!

A: The easiest solution is to have two rules defining eth0 in the 70-persistent-net.rules file, one each for the relevant MAC addresses in each server.  This version of the file should be the same on both servers.
When booted on server1, server1's MAC address gets eth0.
When booted on server2, server2's MAC address gets eth0.
e.g.
SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="11:11:11:11:11:11", ATTR{type}=="1", KERNEL=="eth*", NAME="eth0"
SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="22:22:22:22:22:22", ATTR{type}=="1", KERNEL=="eth*", NAME="eth0"

Change "11:11:11:11:11:11" and "22:22:22:22:22:22" to match the hardware in your servers.

BTW, if using systemd, have two files in /etc/systemd/network, one for each matching MAC address.  e.g.
/etc/systemd/network/10-eth0-1.link:
[Match]
MACAddress=11:11:11:11:11:11

[Link]
Name=eth0

/etc/systemd/network/10-eth0-2.link:
[Match]
MACAddress=22:22:22:22:22:22

[Link]
Name=eth0

From man 5 systemd.network:

[MATCH] SECTION OPTIONS
The network file contains a [Match] section, which determines if a given network file may be applied to a given device; and a [Network] section specifying how the device should be configured.
The first (in lexical order) of the network files that matches a given device is applied, all later files are ignored, even if they match as well.

A: You could try modifying the start-up script for udev to delete the file 70-persistent-net.rules before it does anything else.
Or add a custom hook/script to your initramfs (generation).


text:
Q: Power BI - Getting data from sources with no direct API I am working on designing a Power BI dashboard and would require some insights on the source of data. My source of financial data comprises of Kyriba, Bloomberg and ClearWater Analytics. However, no API exists for either of these in Power BI. What's the best way to pull data from these sources into PowerBI? Manual generation of excel always? Need assistance in understanding the best way to automate this process? Thank You!

A: unfortunately or maybe fortunately these sites are highly secured, so at the moment there is no connector to these companies' data. But I am quite sure that there are some automatic extraction in csv files or even excel files. Once you have these files you can do everything you want in your Power BI.
Maybe you can contact your IT to check if there is any ftp channel possible to automate the import.
Good luck!


text:
Q: MySQL said: Documentation #2002 - The server is not responding + windows 8 + wampserver I have wampserver 2.2, PHP 5.3.9, Mysql 5.0.8 and windows 8 as an operating system. I have installed wampsever recently and localhost is working fine with it but when I am trying to open phpadmin through wamp system tray icon it showing the following error :

Error

MySQL said: Documentation
 #2002 - The server is not responding (or the local MySQL server's socket is not correctly configured)

I am searching from last couple of days in google to resolve this issue but not getting any solution. Following is my config.inc.php file
<?php

/* Servers configuration */
$i = 0;

/* Server: localhost [1] */
$i++;
$cfg['Servers'][$i]['verbose'] = 'localhost';
$cfg['Servers'][$i]['host'] = '127.0.0.1';
$cfg['Servers'][$i]['port'] = '3306';
$cfg['Servers'][$i]['socket'] = '/tmp/mysql.sock';
$cfg['Servers'][$i]['connect_type'] = 'socket';
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = 'root';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['AllowNoPassword'] = true;

/* End of servers configuration */

$cfg['DefaultLang'] = 'en-utf-8';
$cfg['ServerDefault'] = 1;
$cfg['UploadDir'] = '';
$cfg['SaveDir'] = '';

/* rajk - for blobstreaming */
$cfg['Servers'][$i]['bs_garbage_threshold'] = 50;
$cfg['Servers'][$i]['bs_repository_threshold'] = '32M';
$cfg['Servers'][$i]['bs_temp_blob_timeout'] = 600;
$cfg['Servers'][$i]['bs_temp_log_threshold'] = '32M';

?>

Need help for this. Thanks in advance.

A: Did you run the setup script for the first time?, in order to allow access to local-server (specially in win 8) & make sure you always run it as admin.
If you have access to phpmyadmin you can do the above step from setting tab, in more setting option.
If you are having trouble setting this up, let me know and i will tell you more details about it.
This might be not the best answer for your questions, but i am trying to help as much as i can.
All right, Do the following steps , i assume that you have access to phpmyadmin, if not go to wamp directory -> alias -> open phpmyadmin.conf
Change the following code :
Order Deny,Allow
Deny from all
Allow from 127.0.0.1

To
Order Allow,Deny
Allow from all

Then save it.
Afterwards, Go to wamp tray icon -> right click -> put the server online
That should allow you to have access in both localhost and phpmyadmin

*

*Instead of manually editing config.inc.php, you can use the Setup
Script. First you must manually create a folder config in the
phpMyAdmin directory (you can find it on wamp/apps/phpmyadmin/). This is a security measure and should be deleted after finishing the setupscript.

*Then open localhost/phpmyadmin on your web browser

*Go to settings tab

*in more settings you will find link to SetupScript , should be in
localhost/phpmyadmin/setup/index.php

*under servers, hit new server

*Type your host name which should be localhost since you are running on local machine

*In Authentication Settings right the user and password to access phpmyadmin

*There are a lot of other settings you may use depends on your needs

*hit save button

*Note that changes are not saved to disk until explicitly choose Save from the Configuration area of the screen. Normally the script saves the new config.inc.php to the config/ directory, but if the webserver does not have the proper permissions you may see the error "Cannot load or save configuration." Ensure that the config/ directory exists and has the proper permissions - or use the Download link to save the config file locally and upload (via FTP or some similar means) to the proper location.

*Once the file has been saved, it must be moved out of the config/ directory to phpmyadmin main directory and the permissions must be reset, again as a security measure.

*Now the file is ready to be used. You can choose to review or edit the file with your favorite editor, if you prefer to set some advanced options

*If you are using the auth_type "config", it is suggested that you protect the phpMyAdmin installation directory because using config does not require a user to enter a password to access the phpMyAdmin installation. Use of an alternate authentication method is recommended, for example with HTTP–AUTH in a .htaccess file or switch to using auth_type cookie or http.

*Open the main phpMyAdmin directory in your browser. phpMyAdmin should now display a welcome screen and your databases, or a login dialog if using HTTP or cookie authentication mode.

*You should deny access to the ./libraries and ./setup/lib subfolders in your webserver configuration. For Apache you can use supplied .htaccess file in that folder, for other webservers, you should configure this yourself. Such configuration prevents from possible path exposure and cross side scripting vulnerabilities that might happen to be found in that code.

*It is generally good idea to protect public phpMyAdmin installation against access by robots as they usually can not do anything good there. You can do this using robots.txt file in root of your webserver or limit access by web server configuration.

I hope that helps, if you need further information, Dont hesitate to ask :)

A: This applies to the same under Linux Debian based systems.
Probably this error will happen when you have mysql installed separately. Just remove it [if you don't need it] by the following commands and then you can use mysql via phpmyadmin. This worked for me:
sudo apt-get remove --purge mysql-server mysql-client mysql-common
sudo apt-get autoremove
sudo apt-get autoclean

A: You can follow the below to resolve the problem.
Step1: Go to the my.ini file and changed the setting for mysql socket = "MySQL" to "/tmp/mysql.sock".
Step2: Then do the same in the php ini file and restart the Web server whether it  is WAMP or XAMP!
If you are using XAMP then you can try one more thing:
To fix the #2002 problem, open your config.inc.php with path:
\xampp\phpMyAdmin at your XAMPP directory and add the following code:
$cfg['Servers'][$i]['socket'] = '/var/run/mysql/mysql.sock';
or
$cfg['Servers'][$i]['connect_type'] = 'tcp';

Hope using the above steps, you will get the solution.
Please mark the answer resolved if it is relevant to solve the problem.

A: I have encounter the same problem and did the following to solve it:

*

*Take the SETUP file in your pen drive

*Uninstall completely the WAMP server from your computer with icon too

*Then Restart the system then install the setup file whatever you have taken as backup in pendrive

*Then launch by clicking next next next....

*Then your WAMP is ready for your use

A: "Error
MySQL said:
2002 - The server is not responding (or the local MySQL server's socket is not correctly configured)"
This happened to me today, and it turned out to be simply that MySQL had not started, even though it's configured to start automatically.
Search for Services, find MySQL in the list, and click on Start the service.
(Don't ask me why this fault is suddenly happening).


text:
Q: jQuery Mobile is removing my classes I have the following piece of HTML:

            Expand

and JS that expands the footer:
toggleFooter: function(e) {
        e.preventDefault();
        var $footer = $('footer');

        if(footer_expanded) {
            $footer.animate({height:'50px'}, 500, function() {
                $('#expand-footer').toggleClass('expanded');
            });
        } else {
            $footer.animate({height:'550px'}, 500, function() {
                $('#expand-footer').toggleClass('expanded');
            });
        }
        footer_expanded = !footer_expanded;
    }

the toggleFooter function is called by this:
$('#expand-footer').on('click', events.toggleFooter);

the problem I am having is that as soon as the expanded class is added, JQuery Mobile removes it.
Thanks

A: I ended up doing this, as I didn't have time to really dig into the issue:
toggleButton: function() {
        var $btn = $('#expand-footer');

        if(footer_expanded) {
            $btn.css({'background-position':'left bottom'});
        } else {
            $btn.css({'background-position':'left top'});
        }
    }

this works, as there's no class for jQuery Mobile to remove :)

A: I 've built a JSFiddle from your question. The class expanded is not removed by this code. There must be something else (other code), which triggers this, if expanded is really removed.


text:
Q: Do I have to subscribe for services such as Amazon S3 to use Filepicker? Bit of a noob here. I was wondering if I have to subscribe to a cloud storage service to use filepicker.io.

A: You do not have to subscribe to S3 to use Filestack, however your app gets a lot more powerful if you do. Thanks to that, you can store your files directly to your storage so you will never lose access to them.  If you haven't put in your storage credentials your files will be stored on Filestack's server.


text:
Q: ImportError: cannot import name 'Serial' from 'serial' (unknown location) Whenever i execute the code below it gives me following Error:
ImportError: cannot import name 'Serial' from 'serial' (unknown location)

Code:
  from serial import Serial

  arduinodata = Serial('com4',9600)

  print("Enter n to ON LED and f to OFF LED")

  while 1:
    input_data = raw_input()
    print ("You Entered"+input_data)

    if (input_data == 'n'):
        arduinodata.write(b'1')
        print("LED ON")

    if (input_data == 'f'):
        arduinodata.write(b'0')
        print("LED OFF")

I have installed all the required python modules. Like pyserial, pyfirmata etc but it is continuously giving me this error.

A: I encountered the same problem. I first uninstalled pyserial from all pip, pip3, and conda (I had it on all 3), and then re-installed it. It then worked fine for me. Hope that helps!

A: I got exactly this problem, as well. It was caused by the "pyserial" and "serial" libraries installed on per-user basis with pip while pyserial was also installed system-wide (possibly in a different version, using the Linux package manager).
Solution
Removing the per-user version fixed the problem in my case.

A: Most likely missing an
 __init__.py

file or the module, or the file sub-directory for the module (Serial) is on a different layer than the file executable. Hope that helps :).

A: I got same problem while try to install serrial on rpi4
In this tutorial
http://wiki.ros.org/rosserial_arduino/Tutorials/Arduino%20IDE%20Setup
if you install by:

*

*2.1.1(RECOMMENDED) Installing Binaries on the ROS workstation

It work well
But if you install follow:

*

*2.1.2 Installing from Source onto the ROS workstation

It said : ImportError: cannot import name 'Serial' from 'serial'
I dont know why, but when install by 2.1.1 it worked well.

A: Uninstalling serial, pyserial
pip uninstall serial

And
pip uninstall pyserial

Then reinstalling pySerial
pip install pySerial

Worked for me.
Note however that I am using a virtual environment

A: I had to rename serial.py to something else (serial0.py) in my C:/python39 folder and it fixed the problem.


text:
Q: Flutter - How to give progress bar to on:Pressed() function of a button? I am fetching data from firebase database in a async function which triggers when the button is pressed. When the data fetching is complete it moves to the next page(next acitivty). So, in this whole process the async on pressed function takes time to execute the whole code. So, i wanted to show a progress bar until the whole code is executed. Can anyone suggest me how can i show a progress bar until the new activity starts.
Here is my code:
FlatButton(

              child: Text("Next",style: TextStyle(
              color: Colors.white,
                  fontWeight: FontWeight.bold,
                  fontFamily: "Calibri",
                  fontSize: 20)),
              color: Colors.blue,
              onPressed:() {
                elist.then((value)
             async {

                 for (var item in value) {
                   alleyes.add(new facial(criminal_id: item.criminal_id,
                       part_size: item.part_size,
                       link: item.link));
                   Uint8List bytes = (await NetworkAssetBundle(Uri.parse(item.link)).load(item.link)).buffer.asUint8List();
                   eye_str.add(String.fromCharCodes(bytes));

                 }
                 Navigator.push(context,
                     MaterialPageRoute(builder: (context)=>App()));
             }
                );
              },
            )

A: You can start by creating a variable called loading.
bool loading = false;

After this, you can set the loading to true when the button gets tapped and display a progress indicator when the loading variable is true
loading
      ? Center(child: CircularProgressIndicator())
      : FlatButton(
    child: Text("Next",style: TextStyle(
        color: Colors.white,
        fontWeight: FontWeight.bold,
        fontFamily: "Calibri",
        fontSize: 20)),
    color: Colors.blue,
    onPressed:() {
      setState((){
        loading = true;
      }); // set loading to true here
      elist.then((value)
      async {
        for (var item in value) {
          alleyes.add(new facial(criminal_id: item.criminal_id,
              part_size: item.part_size,
              link: item.link));
          Uint8List bytes = (await NetworkAssetBundle(Uri.parse(item.link)).load(item.link)).buffer.asUint8List();
          eye_str.add(String.fromCharCodes(bytes));
        }

        setState((){
          loading = false;
        }); // set it to false after your operation is done
        Navigator.push(context,
            MaterialPageRoute(builder: (context)=>App()));
      }
      );
    },
  )


text:
Q: Example Highcharts in ionic 4 I'm trying to add to my ionic4 project High-charts  (https://www.highcharts.com/)
with this tutorial
https://www.highcharts.com/blog/tutorials/setting-chart-ionic-app-using-highcharts/
Doing it, I get this error can someone help me pls
ionic info
Ionic:

   ionic (Ionic CLI)             : 4.12.0 (C:\****\*****\*****\*****\npm\node_modules\ionic)
   Ionic Framework               : @ionic/angular 4.3.1
   @angular-devkit/build-angular : 0.13.8
   @angular-devkit/schematics    : 7.3.8
   @angular/cli                  : 7.3.8
   @ionic/angular-toolkit        : 1.5.1

System:

   NodeJS : v11.10.0 (D:\*****\nodejs\node.exe)
   npm    : 6.7.0
   OS     : Windows 10

package.json
"highcharts": "^7.1.1",

tab2page.html
<ion-header>
    <ion-toolbar>
        <ion-title>
            Tab Two
        </ion-title>
    </ion-toolbar>
</ion-header>

<ion-content>

</ion-content>

tab2page.ts
import { Component } from '@angular/core';
import * as HighCharts from 'highcharts';
import { NavController } from '@ionic/angular';

@Component({
  selector: 'app-tab2',
  templateUrl: 'tab2.page.html',
  styleUrls: ['tab2.page.scss']
})
export class Tab2Page {

  constructor(public navCtrl: NavController) {}

  ionViewDidLoad() {
    var myChart = HighCharts.chart('container', {
      chart: {
        type: 'bar'
      },
      title: {
        text: 'Fruit Consumption'
      },
      xAxis: {
        categories: ['Apples', 'Bananas', 'Oranges']
      },
      yAxis: {
        title: {
          text: 'Fruit eaten'
        }
      },
      series: [{
        name: 'Jane',
        data: [1, 0, 4]
      }, {
        name: 'John',
        data: [5, 7, 3]
      }]
    });
  }

}

tab2.module.ts
import { IonicModule } from '@ionic/angular';
import { RouterModule } from '@angular/router';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { Tab2Page } from './tab2.page';

@NgModule({
  imports: [
    IonicModule,
    CommonModule,
    FormsModule,
    RouterModule.forChild([{ path: '', component: Tab2Page }])
  ],
  declarations: [Tab2Page]
})
export class Tab2PageModule {}

app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';

import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule],
  providers: [
    StatusBar,
    SplashScreen,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

Got this error on tab2.page.ts
{
    "resource": "/ionic/new/myApp/src/app/tab2/tab2.page.ts",
    "owner": "typescript",
    "code": "2322",
    "severity": 8,
    "message": "Type '{ name: string; data: number[]; }' is not assignable to type 'SeriesAbandsOptions | SeriesAdOptions | SeriesAoOptions | SeriesApoOptions | SeriesAreaOptions | SeriesArearangeOptions | SeriesAreasplineOptions | SeriesAreasplinerangeOptions | ... 88 more ... | SeriesZigzagOptions'.\n  Property 'type' is missing in type '{ name: string; data: number[]; }' but required in type 'SeriesZigzagOptions'.",
    "source": "ts",
    "startLineNumber": 30,
    "startColumn": 16,
    "endLineNumber": 33,
    "endColumn": 8,
    "relatedInformation": [
        {
            "startLineNumber": 249559,
            "startColumn": 5,
            "endLineNumber": 249559,
            "endColumn": 9,
            "message": "'type' is declared here.",
            "resource": "/ionic/new/myApp/node_modules/highcharts/highcharts.d.ts"
        }
    ]
}

Image from error:

(source: imgbbb.com)

A: You have to declare the type for each series or set type = undefined:
ionViewDidLoad() {
  var myChart = HighCharts.chart('container', {
    chart: {
      type: 'bar'
    },
    title: {
      text: 'Fruit Consumption'
    },
    xAxis: {
      categories: ['Apples', 'Bananas', 'Oranges']
    },
    yAxis: {
      title: {
        text: 'Fruit eaten'
      }
    },
    series: [{
      name: 'Jane',
      type: undefined,
      data: [1, 0, 4]
    }, {
      name: 'John',
      type: undefined,
      data: [5, 7, 3]
    }]
  });
}

The better solution is to use highcharts-angular official Highcharts wrapper for Angular. It can be downloaded here: https://github.com/highcharts/highcharts-angular.
home.page.html:
<ion-header>
  <ion-toolbar>
    <ion-buttons slot="start">
      <ion-menu-button></ion-menu-button>
    </ion-buttons>
    <ion-title>
      Home
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>

      <highcharts-chart
        style="margin: 30px;"
        [Highcharts]="Highcharts"
        [constructorType]="chartConstructor"
        [options]="chartOptions"
        [callbackFunction]="chartCallback"
        [(update)]="updateFlag"
        [runOutsideAngular]="runOutsideAngularFlag"
      ></highcharts-chart>

</ion-content>

home.page.ts
import { Component } from '@angular/core';

import * as Highcharts from 'highcharts';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {

  chart;
  updateFromInput = false;
  Highcharts = Highcharts;
  chartConstructor = 'chart';
  chartCallback;
  chartOptions = {
    chart: {
      type: 'bar'
    },
    title: {
      text: 'Fruit Consumption'
    },
    xAxis: {
      categories: ['Apples', 'Bananas', 'Oranges']
    },
    yAxis: {
      title: {
        text: 'Fruit eaten'
      }
    },
    series: [{
      name: 'Jane',
      data: [1, 0, 4]
    }, {
      name: 'John',
      data: [5, 7, 3]
    }]
  };

  constructor() {
    const self = this;

    this.chartCallback = chart => {
      self.chart = chart;
    };
  }
}

home.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { IonicModule } from '@ionic/angular';
import { RouterModule } from '@angular/router';

import { HighchartsChartModule } from 'highcharts-angular';

import { HomePage } from './home.page';

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    IonicModule,
    HighchartsChartModule,
    RouterModule.forChild([
      {
        path: '',
        component: HomePage
      }
    ])
  ],
  declarations: [HomePage]
})
export class HomePageModule {}

A: I had the same error, I leave the code waiting for it to work. Now the problem I have is that the graph does not fit the device. I wait your answer

  this.chartOptions = HighCharts.chart('container', {
    chart: {
      type: 'pie',
      backgroundColor: '#E6ECF3',
    },
    title: {
      text: ''
    },
    yAxis: {
      title: {
        text: 'Fruit eaten'
      }
    },
    colors: ['#086d54', '#097f62', '#0b9270', '#0ca47e', '#0db68c', '#0fc89a', '#10dba8', '#11edb7'],
    series: [{
        name: 'test',
        data: [{
          name: 'Parte 1',
          y: 61.41
        }, {
            name: 'Parte 2',
            y: 11.84
        },{
          name: 'Chrome',
          y: 61.41
        }, {
            name: 'Internet Explorer',
            y: 11.84
        }],
        type: undefined
      }]
    });

A: Use as any after option object of charts (cast it to any)
like this

   this.chartOptions = HighCharts.chart('container', {
    chart: {
      type: 'pie',
      backgroundColor: '#E6ECF3',
    },
    title: {
      text: ''
    },
    yAxis: {
      title: {
        text: 'Fruit eaten'
      }
    },
    colors: ['#086d54', '#097f62', '#0b9270', '#0ca47e', '#0db68c', '#0fc89a', '#10dba8', '#11edb7'],
    series: [{
        name: 'test',
        data: [{
          name: 'Parte 1',
          y: 61.41
        }, {
            name: 'Parte 2',
            y: 11.84
        },{
          name: 'Chrome',
          y: 61.41
        }, {
            name: 'Internet Explorer',
            y: 11.84
        }]
      }]
    } as any);


text:
Q: How to sync Google Calendar with Radicale, 2 way? I have my own calendar that works with Radicale server, i want to sync my calendar with my google calendar, if i create an event in my calendar i want to see it in my google calendar and if i edit that event in google calendar i want to see the change in my calendar.
I know that using the google calendar api i can set event from my calendar, but can't do it from google to my calendar.
I'm using this client to connect with radicale: https://github.com/gaye/dav
There is a way to do this?


text:
Q: Blocked by CORS policy: Response to preflight request
Error:Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource

ASP.NET MVC Core 3.1 API cors config:
services.AddCors(options => options.AddPolicy(CorsPolicy,
                       builder =>
                       {    builder
                                  .AllowAnyMethod()
                                  .AllowAnyHeader()
                                   .WithOrigins("https://www.hotff.com",
   "https://www.hotff.com:44389","https://localhost:4200",
   "http://localhost:4200","https://localhost:44371",
   "http://localhost:4300","http://127.0.0.1:8080") //.AllowAnyOrigin()

                                   .SetIsOriginAllowedToAllowWildcardSubdomains()
                                   .AllowCredentials();
                       }));

This config works from  Angular 8 client, no issue on port http://localhost
When the API is deployed on an IIS 10 server the request works from an Edge browser fine but not from Android or Chrome browsers. Tried all solutions I could find, read everything I could find.
I think the issue is the pre-flight request...


text:
Q: How to define the constant _DEBUG in c++ When I compile and execute thes code, I get...
_DEBUG IS NOT defined

Why isn't the constant being shown as defined?
using namespace std;

int main() {
  const bool _DEBUG = true;
  #if defined _DEBUG
    std::cout << "_DEBUG IS defined\n";
  #else
    std::cout << "_DEBUG IS NOT defined\n";
  #endif // _DEBUG
}

A: #define _DEBUG

or
#define _DEBUG       1

The second method can be checked with #ifdef _DEBUG or #if _DEBUG. Usually _DEBUG is defined in compiler IDE profile.

A: #if defined TOKEN only checks if TOKEN is defined as a preprocessor macro, i.e. with #define TOKEN ....  Here you have defined it as a (constant) variable, which is not the same thing.

A: const bool _DEBUG = true; defines a constant which is known to the compiler and not to the preprocessor.
The following check is executed by the preprocessor before the compiler kicks in, therefore it never sees _DEBUG constant.
  #if defined _DEBUG
    std::cout << "_DEBUG IS defined\n";
  #else
    std::cout << "_DEBUG IS NOT defined\n";
  #endif // _DEBUG

To get rid of the issue, you should #define _DEBUG so that the preprocessor knows about the token.


text:
Q: org-protocol and org-capture won't work together I used this manual to setup an org-protocol: http://orgmode.org/worg/org-contrib/org-protocol.html
But with (require 'org-protocol) the variable org-capture returns this error:
org-capture-select-template: Symbol's function definition is void: org-contextualize-keys

also by typing something like following in shell
emacsclient org-protocol://capture://http:%2F%2Flocalhost%2Findex.html/The%20title

same error happens. store-link protocol works though.
How can I make emacs undertand org-capture? I'm using emacs 24.2 on ubuntu 13.04.

A: I have no such problem with
emacs -q --eval "(require 'org)"
f1 f shows that org-contextualize-keys is defined.
The version is emacs 24.3.1 on ubuntu 13.04.
You should try to build your emacs from source: http://ftpmirror.gnu.org/emacs/.


text:
Q: Downloading a file from a SQL Database using Silverlight I'm trying to develop a Silverlight application that will download a specified file from a SQL database. I'm aware Silverlight can not do this independently, so I am wondering as to what the best way to accomplish this is.
The website that the Silverlight app will run on is asp.net with C# code behind.
Thank you.

A: An easy way would be to run a web application or service to grab the data. You could have the Silverlight application query the web app for the needed data which would trigger the app to query the database. You would program the web app to return the data in whatever format you needed, JSON, XML, etc.

A: One way to do this would be to write a simple Asp.Net Handler. The other would be to expose the download functionality via a WCF Service. If this download functionality would be implemented as WCF Rest Service, even non WCF Clients would be able to download the file.


text:
Q: Warn about unused imports in python with pycodestyle linter in vscode I cannot add warnings about unused imports (W0611 or W0614) in vscode with pycodestyle linter.
I have tried to add
"--enable=W0614"

or the same with W0611 in the user settings in
python.linting.pycodestyleArgs

But it does not work as should be. Instead all linting stops until I remove this additionnal argument.
Any help much appreciated !


text:
Q: How to go about extracting data from an api website? I have made an app where it opens up an online api(?) database. I used the ListView widget where each entry (name of something) clicks onto a new activity. I would like to know how to go about extracting data from the database and putting it in my app for example; if I were to get reviews about a shampoo showing on the page and also a picture of the shampoo etc.
Sorry if I make no sense.

A: It would have helped if you post some of your code.
According to what I understood is that you want to download data from server and show it into your list view.

What you can do is you can hit API in Asynctask. Put each item data like text, image URL etc into one bean class (setter getter) and add that bean into your list attached to your adapter.

Then you can call notifyDataSetChanged() on your adapter.


text:
Q: Maintaining two states of turtles netlogo I am doing a small university project. In which i have to maintain 2 states of turtles.
1. Disperse
2. Explore
Disperse :
 In dispersion, when at the start all the turtles (20 turtles) are at 0,0 they should disperse from each other. Every turtle has a radius of 2 patches around it, no other turtle should be in that radius. All turtles should go far until they all attain this radius. then other behavior will be called i.e. Explore.
Explore:
 In explore , they have to explore the world and avoid different types of obstacles. When ever two turtles come close to each other above mentioned radius then state should be changed to disperse.
I have procedures for obstacle avoidance, and move-speed, and all other individual behaviors under Disperse and Explore. But i don't know how to join all this in one simulation.

A: It is unclear that you really need to maintain turtle state, since you will have to repeatedly check for other turtles in any case.  But since you said you wanted that, you can use turtles-own.  For example:
turtles-own [state]

to setup
  ca
  crt 20
end

to go
  ask turtles [set-state]
  ask turtles [move]
end

to set-state ;;turtle proc
  ifelse (any? other turtles in-radius 2) [
    set state "disperse"
  ] [
    set state "explore"
  ]
end

to move ;;turtle proc
  if (not member? state ["disperse" "explore"]) [
    error "unknown state"
  ]
  if (state = "disperse") [
    disperse
  ]
  if (state = "explore") [
    explore
  ]
end

to disperse ;;turtle proc
  move-to one-of patch-set [neighbors] of neighbors
end

to explore
  move-to one-of neighbors
end

A: You might want to take a look at Moore machine and Automata, NetLogo works great with those.
A Moore machine can be seen as a set of 5 elements that interact with each other, in this particular example the start state(S0) would be Dispersing. In NetLogo you can use the word run that receives a string. You'd had to make a procedure that returns a string (say "explore") by checking the actual state of a turtle.
I made something like that a few months ago. We were trying to make a hunter-prey model for polar bears and seals (or wolves and sheeps) based on Moore Machines.
You can use the example of @Alan of course, I just skimmed through and I believe it was fine.
Here is my example based on Moore Machine. It's in spanish but the idea is the same.


text:
Q: How come these two matrices are not equivalent? Assume we have a 3 dimensional array F and 2 dimensional matrix S.
First I find a matrix Y which is F multiplied by S. Then I try to find an estimate of F (lets call it F_est) from Y as sanity check in my code.
Can anyone see a flaw in logic, I dont seem to know why F_est is not exactly F.
F= randn(2,4,600);
S= randn(4,600);
for i =1:size(F,1);
    for j=1:size(F,2)
        for k= 1:size(F,3)
            Y(i,k)= F(i,j,k) * S(j,k);
        end
    end
end

for i =1:size(F,1)
    for j=1:size(F,2)
        for k= 1:size(F,3)
            F_est(i,j,k)= Y(i,k) / S(j,k);
        end
    end
end

then I try to see if F_est - F is zero and it is not. Any ideas. Much aprreciated.
**** EDIT after comments
Based on the answers I got I am wondering if the code below makes any sense?
for k=1:size(F,3)
Y(:,k) = squeeze(F(:,:,k)* S(:,k)
end

Am I able to recover F if I have Y and S?

A: When you create Y, you are replacing its values continuously. For any value of pair of i,k you are overwriting Y jtimes!
Those 2 codes are not equivalent, as F_est(i,j,k) computed only once, but you have Y(i,k) j times.
I don't know what you are trying to do, but a multiplication of a 3D matrix by a 2D matrix is not defined, and its not a 2D matrix


text:
Q: Checking if one of more strings is empty in array/enum So I am making a small program to log in to. I have 4 forms that you need to fill in and if you click the button to login, then I want to check if the forms are filled and if not you get a message saying which form you still need to fill in. I thought of 2 ways for doing this. one easier way than the other.
The easy way:
static String [] Check = {SendMail.FEText, SendMail.FWText, SendMail.TEText, SendMail.TWText};

    public static boolean fullFilled() {
        for (String s: Check) {
            if (s.equals("")) {
                JOptionPane.showMessageDialog(null, "Je bent vergeten om iets in te vullen.", "Vergeten", JOptionPane.ERROR_MESSAGE);
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

And another one with an enum, but I have no idea how to finish this:
public enum Check {
        FACEBOOK_EMAIL("FaceBook emailadres", SendMail.FEText),
        FACEBOOK_WACHTWOORD("FaceBook wachtwoord", SendMail.FWText),
        TOTO_EMAIL("Toto emailadres", SendMail.TEText),
        TOTO_WACHTWOORD("Toto wachtwoord", SendMail.TWText);

        public String formName;
        public String stringName;

        Check(String formName, String stringName) {
            this.formName = formName;
            this.stringName = stringName;
        }

    }

    public static boolean fullFilled() {
        for (String s: Check) {
            if (s.equals("")) {
                JOptionPane.showMessageDialog(null, "Je bent vergeten om " + s.formName + "iets in te vullen.", "Vergeten", JOptionPane.ERROR_MESSAGE);
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

I want the message to say "Je bent vergeten om FaceBook emailadres in te vullen." if you forgot to fill in the facebookemail(FEText)

A: You can iterate over all the values of that enum, and then for each one, check if the stringName is blank.  If it is, you add it to a messageBody, and display that in the dialog if it isn't empty.
Note that the check below ignores all white space, which is probably what you want.
public static boolean fullFilled() {
    String messageBody = "";
    for (Check check: Check.values()) {
        if (check.stringName.trim().isEmpty()) {
            messageBody = messageBody + "Je bent vergeten om " + check.formName + "iets in te vullen." + "\n";
        }
    }
    if(!messageBody.trim().isEmpty()){
        JOptionPane.showMessageDialog(null, messageBody, "Vergeten", JOptionPane.ERROR_MESSAGE);
        return false;
    }
    return true;
}


text:
Q: Detect Push Notifications Android I am creating a chat application(kind of watsapp) in Android.
Here one of the core and important point is that , i need to use my own server instead of GCM.
So that , how can i code my manifest file so that whenever there is new message from server it will automatically detect in my broadcast receivers.?

A: The first thing you need to have is a good reason to not use GCM. If you are sure you want your own service, you will have to write a lot of code, on client side and on server side. Here is the general idea :

*

*Register a broadcast receiver to know when the device is connected or not to network.

*Create a service that will be launch and stop by the broadcast receiver accoding to the device network status.

*Choose a pattern for "push". You can use classic HTTP request with long-polling, or sockets to do real push. This link present the concept (for web use).

*Implement this pattern so you service will comunicate with your server.

*Make your service broadcast intent, so the rest of your app can receive push.

A: I agree with others on this. You should be using the GCM, even if it means adding your own custom server side code.
Here is what my broadcast receiver looked like with an test app for GCM push notifications.
public class GCMBroadcastReceiver extends WakefulBroadcastReceiver {
    public static final String TAG = "GCMBroadcastReceiver_";
    @Override
    public void onReceive(Context context, Intent intent){
        Log.v(TAG, "OnReceive was called.");
        ComponentName comp = new ComponentName(context.getPackageName(),
                GCMNotificationIntentService.class.getName());
        startWakefulService(context, (intent.setComponent(comp)));
        setResultCode(Activity.RESULT_OK);
    }
}

In the intent service (GCMNotificationIntentService), you create the actual notification.
Here is the example I've been working off:
https://github.com/kweaver00/android-learning/tree/master/Push
https://github.com/kweaver00/android-learning/blob/master/Push/GCMExample/app/src/main/java/com/expeditionlabs/gcmexample/lib/gcm/GCMBroadcastReceiver.java


text:
Q: Convert JSON format to Array to use in data I'm using Angular Material datatable that requires a table to display data.
I would convert this JSON data format that backend sends to frontend
[{"text":"HELEO"},{"text":"HELEO"},{"text":"popopo"},{"text":":kjnkjn"},{"text":"jhjh"}]

To this format
[ { text: 'HELEO' },
  { text: 'HELEO' },
  { text: 'popopo' },
  { text: 'jhjh' } ]

Here's my service:
test: nomchamp[];
gettext(): Observable<any> {

  return this.http.get<nomchamp[]>(this.url)
    .map(res => { console.log(res); return this.test = JSON.parse(res) });

}

In my back-end:
router
.route("/")
.get(function (req, res, err) {

  // Get a database reference to our posts
  var db = admin.database();
  var ref = db.ref("/");

  // Attach an asynchronous callback to read the data at our posts reference
  ref.once("value", function (snapshot) {
    var list = [];
    snapshot.forEach(function (elem) {
      list.push(elem.val());
    })

    console.log(list);
    console.log(JSON.stringify(list))

    res.send(list);

  }, function (errorObject) {
    console.log("The read failed: " + errorObject.code);
    res.status(500).send(errorObject.code);
  });
});

I'm using stringify to be able to send data via res.send
Using JSON.parse I get this error :

JSON.parse: unexpected character at line 1 column 2 of the JSON data

Without using parse , data is not printed in my datatable.
The only case where it's working is when I use res.send(res) in back end but what I would is using res.write(JSON.stringify(res));

A: On your list variable, you can try this:
let list = [];
snapshot.forEach(function (elem) {
  list.push(elem.val());
});

list = JSON.stringify(list);
list = JSON.parse(list);

res.send(list);

Basically, you stringify first, and then you parse it; this way, you get rid of the double quotes on each key in the key-value pairs within each object.

A: Edit I may have mistunderstood what you are asking for, if so my apologies
I believe you can simply feed an angular material datatable with a object array populated by a JSON GET, I had to do it for my website and didnt want the fuss of a data table
<mat-table #table [dataSource]="dataSource">

      <!-- Position Column -->
      <ng-container matColumnDef="name">
        <mat-header-cell *matHeaderCellDef> Name </mat-header-cell>
        <mat-cell *matCellDef="let project"> {{project.name}} </mat-cell>
      </ng-container>

      <!-- Name Column -->
      <ng-container matColumnDef="desc">
        <mat-header-cell *matHeaderCellDef> Description </mat-header-cell>
        <mat-cell *matCellDef="let project"> {{project.desc | slice:0:30}}... </mat-cell>
      </ng-container>

      <!-- Weight Column -->
      <ng-container matColumnDef="tags">
        <mat-header-cell *matHeaderCellDef> Tags </mat-header-cell>
        <mat-cell *matCellDef="let project"> {{project.tags}} </mat-cell>
      </ng-container>

      <!-- Symbol Column -->
      <ng-container matColumnDef="type">
        <mat-header-cell *matHeaderCellDef> Type </mat-header-cell>
        <mat-cell *matCellDef="let project"> {{project.type}} </mat-cell>
      </ng-container>

      <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
      <mat-row *matRowDef="let row; columns: displayedColumns;" (click)="editUser(row)"></mat-row>
    </mat-table>

The variables I have added to my component.ts:
    displayedColumns = ['name', 'desc', 'tags', 'type'];
    projectDataURL:string = global.url + '/api/projects';
    project:any;
    dataSource;

Then in the constructor I have this:
this.subscription = this.getData.getDATA(this.projectDataURL).subscribe(
            data => {
                this.dataSource = new MatTableDataSource<any>(data);
            });

And finally I needed an interface for the data table:
export interface project {
    name: string;
    desc: number;
    tags: string;
    type: string;
}

While this isnt perfect for all use cases, for mine it worked great, hope this helps


text:
Q: How to get the last url in a chain of redirects in vueJS I'm trying to follow through on a url that redirects me to another page using VueJS.
Combing through the docs I could not find anything that allows me to retrieve the last url after the redirect.

A: You can try document.referrer, it returns the URI of the page that linked to the current page.
If you're using VueRouter, you can also check https://router.vuejs.org/guide/advanced/navigation-guards.html#global-before-guards


text:
Q: SQL Replication "Row Not Found" Error I have transactional replication running between two databases.  I fear they have fallen slightly out of sync, but I don't know which records are affected.  If I knew, I could fix it manually on the subscriber side.
SQL Server is giving me this message:

The row was not found at the Subscriber when applying the replicated command. (Source: MSSQLServer, Error number: 20598)

I've looked around to try to find out what table, or even better what record is causing the issue, but I can't find that information anywhere.
The most detailed data I've found so far is:

Transaction sequence number: 0x0003BB0E000001DF000600000000, Command ID: 1

But how do I find the table and row from that?  Any ideas?

A: I'll answer my own question with a workaround I ended up using.
Unfortunately, I could not figure out which table was causing the issue through the SQL Server replication interface (or the Event Log for that matter).  It just didn't say.
So the next thing I thought of was, "What if I could get replication to continue even though there is an error?"  And lo and behold, there is a way.  In fact, it's easy.  There is a special Distribution Agent profile called "Continue on data consistency errors."  If you enable that, then these types of errors will just be logged and passed on by.  Once it is through applying the transactions and potentially logging the errors (I only encountered two), then you can go back and use RedGate SQL Data Compare (or some other tool) to compare your two databases, make any corrections to the subscriber and then start replication running again.
Keep in mind, for this to work, your publication database will need to be "quiet" during the part of the process where you diff and fix the subscriber database.  Luckily, I had that luxury in this case.

A: If your database is not prohibitively large, I would stop replication, re-snapshot and then re-start replication. This technet article describes the steps.
If it got out of sync due to a user accidently changing data on the replica, I would set the necessary permissions to prevent this.
This replication article is worth reading.

A: This gives you the table the error is against
use distribution
go

select * from dbo.MSarticles
where article_id in (
    select article_id from MSrepl_commands
    where xact_seqno = 0x0003BB0E000001DF000600000000)

And this will give you the command (and the primary key (ie the row) the command was executing against)
exec sp_browsereplcmds
@xact_seqno_start = '0x0003BB0E000001DF000600000000',
@xact_seqno_end = '0x0003BB0E000001DF000600000000'

A: Use this query to find out the article that is out of sync:
USE [distribution]

select * from dbo . MSarticles
where article_id IN ( SELECT Article_id from MSrepl_commands
where xact_seqno = 0x0003BB0E000001DF000600000000)

A: of course if you check the error when the replication fails it also tells you which record is at fault and you could extract that data from the core system and just insert it on the subscriber.
This is better than skipping errors as with the SQL Data Compare it will lock the table for the comparison and if you have millions of rows this can take a long time to run.
Tris

A: Changing the profile to "Continue on data consistency errors" won't always work. Obviously it reduces or nullifies an error, but you won't get the whole proper data. It will skip the rows by which an error occurs, and hence you fail to get accurate data.

A: the following checks resolve my problem

*

*check that all the replication SQL Agents jobs are working fine and if not start them.

*

*in my case it was stopped because of some killed session occurred a few hours before by Some DBA because of blocking issue

*after a very short time all data in subscription were updated and no
other error in replication monitor

*in my case all above queries did not returned nothing

A: This error usually comes when particular record does not exists on subscriber and a update or delete command executed for same record on primary server and which got replicated on subscriber as well.
As this records does not exists on subscriber, replication throws an error " Row Not Found"
Solution of this error to make replication work back to the normal running state:
We can check with following query, whether request at publisher was of update or delete statement:
USE [distribution]

SELECT *
FROM   msrepl_commands
WHERE  publisher_database_id = 1
       AND command_id = 1
       AND xact_seqno = 0x00099979000038D6000100000000

We can get artical id information from above query, which can be passed to below proc:
EXEC Sp_browsereplcmds
  @article_id = 813,
  @command_id = 1,
  @xact_seqno_start = '0x00099979000038D60001',
  @xact_seqno_end = '0x00099979000038D60001',
  @publisher_database_id = 1

Above query will give information about, whether it was a update statement or delete statement.

*

*In Case of Delete Statement

That record can be directly deleted from msrepl_commands objects so that  replication wont make retry attempts for the record
DELETE FROM msrepl_commands
WHERE  publisher_database_id = 1
       AND command_id =1
       AND xact_seqno = 0x00099979000038D6000100000000

*In case of update statement:

You need to insert that record manually from publisher DB to subscriber DB:


text:
Q: How to append a dynamic string to the end of a copy's filename Conside File is :
/home/dev/a1234.txt

I want to copy this file in /home/sys/  directory but I want to add some number on the file name while copying.
Date1=date +%Y%m%d_%H:%M:%S
Output should be :
/home/sys/a1234.txt.$Date1

Number on the filename "1234" will be different everytime. so File name is not fixed.
Please suggest.

A: Something like this should get you on the way:
for i in $( ls /home/dev | grep 'a[0-9]*.txt$'); do
    cp /home/dev/$i /home/sys/$i.`date +%Y%m%d_%H:%M:%S`;
done

You can improve it by seeing if the file has already been copied, and prevent it from being copied a second time.

A: In two steps:

*

*Copy the file to /home/sys.
cp /home/dev/a1234.txt /home/sys

*Move from a1234.txt to a1234.txt.130625. This way you can make it more general.
mv /home/sys/a1234.txt{,$date} #is expanded to mv /home/sys/a1234.txt /home/sys/a1234.$date

As you indicate your file name will change, you can generalise my answer with $file_name instead of a1234.txt.
Test
$ touch a
$ date=23
$ mv aa{,$date}
$ ls
aa23

A: NAME=a1234.txt
cp dev/$NAME sys/$NAME.$Date1

A: Use the date command to get the current date.
$ DATE=`date +%Y%m%d_%H:%M:%S`; NAME=a; EXT=txt; for i in {0..4}; do echo $NAME$i$.$EXT.$DATE; done
a0.txt.20130625
a1.txt.20130625
a2.txt.20130625
a3.txt.20130625
a4.txt.20130625

Change the echo line to be a cp:
$ DATE=`date +%Y%m%d_%H:%M:%S`; FROMDIR=/home/dev; TODIR=/home/sys; NAME=a; EXT=txt; for i in {0..4}; do cp $FROMDIR/$NAME$i.$EXT $TODIR/$NAME$i$.$EXT.$DATE; done

This is probably better in a bash script where you can modify it easier than a single liner:
#!/bin/bash

# get current date
DATE=`date +%Y%m%d_%H:%M:%S`;

# specify from directory and to directory for cp
FROMDIR=/home/dev;
TODIR=/home/sys;

# set base filename and extension
NAME=a;
EXT=txt;

# count from 0 to 4
for i in {0..4}; do
    # copy file and add date to end of new filename
    cp $FROMDIR/$NAME$i.$EXT $TODIR/$NAME$i$.$EXT.$DATE;
done

i increments from 0 to 4 in this example, while a filename of the form $NAME$i.$EXT is copied from $FROMDIR to TODIR -- with the current date in $DATE appended to the end of the copy's filename.


text:
Q: How to obtain the given "analytical" solution to the 4th order ODE? The 4th order ODE is
$$(D^2-k^2)^2f=0, \qquad (1)$$
where $f=f(y)$, $D\equiv\frac{d}{dy}$, and $k$ is a constant. It is subject to the boundary conditions $f(0)=f'(0)=f(1)=0$.
A solution to (1) is given by,
$$f=a\left(\sinh k\eta+\frac{k\cosh k-\sinh k}{\sinh k}\eta\sinh k\eta-k\eta\cosh k\eta\right), \qquad (2)$$
where $a$ is constant, $\eta=\frac{y}{d}$ with $d$ a constant.
If I consider its characteristic equation:
$$r^4-2r^2k^2+k^4=0,$$
its solutions are $r_{1,2}=r_{3,4}=\pm k$, they then given a general solution
$$f=(\sinh ky+\cosh ky)(c_1+c_2y)+(\cosh ky-\sinh ky)(c_3+c_4y)$$
But I can not figure out how to obtain the solution (2)?
Any suggestion? Thank you!


text:
Q: How to download .lnk file in html I've a shared directory reachable by html page in this way

Shared folder

This works with internet explorer, but not with Chrome browser (error: Not allowed to load local resource).
So I've thought of replacing the link with a tag to allow the download of a lnk file (created manually) containing the path of the shared directory like this
Shared folder

this tag works to download other kind of file (img,pdf,...), but not with lnk file; download in Chrome fails because doesn't find file mylinktofolder.download.
Is it possible to download such a file?
Thanks in advance

A: Chrome marks .lnk files as unsafe for download so you won't be able to workaround this using html/js unfortunately
Sources:

*

*https://stackoverflow.com/questions/55177641/lnk-file-downloading-as-download-in-chrome-and-it-failed-to-download-in-first\

*https://stackoverflow.com/a/34890432/2491027

A: Is it possible to download such a file?
Yes, sort off, here I show two tabs but the second is as you described a shared folder that was opened as second tab, however, has been torn off to show the two types of links in the first index.html

So to answer your question the second link tested with a range of LNK files lastly to a cmd.exe.lnk and onclick triggers a lnk download but as normal for windows the .lnk extension is not shown as actioned, so if the lnk is

*

*a file like svg.lnk it will open the linked svg in the second tab.

*a lnk to a folder it will open the folder

*a lnk to a command it in turn forces cmd.exe to be downloaded with a warning

and you can accept (keep) and run that copy of cmd !

All the above is possible using Chrome based browsers such as Edge or SlimJet or Ungoogled Chrome. and Chrome too.

Shared folder

downloads.lnk

.
As non admin user I can navigate to local shares or remoteshares or remote mapped drives without any authorisation, other than I have user read write permission for all those locations.

Local Shared folder


text:
Q: Navbar not responsive with bootstrap Im using a code found on the internet for a navbar using bootstrap. I like it I find it beautiful. However when I resize my screen I can watch that this is not responsive. Links disappears and it makes something strange.
Here is the code of the navbar :

.navbar-new-top{
    background: #fff;
}
.navbar-brand{
    font-weight: 600;
}
.navbar-brand img{
    width: 20%;
}
.navbar-new-top ul{
    margin-right: 9%;
}
.navbar-new-top ul li{
    margin-right: 8%;
}
.navbar-new-bottom{
    background-color: #f7f7f7;
    box-shadow: 0 5px 6px -2px rgba(0,0,0,.3);
    border-top: 1px solid #e0e0e0;
    margin-top: 4%;
    height: 40px;
}
.navbar-new-bottom ul li{
    margin-left: 2%;
    margin-right: 2%;
}
.navbar-nav .nav-item a {
    color: #333;
    font-size: 14px;
    font-weight: 600;
    transition: 1s ease;
}
.navbar-nav .nav-item a:hover{
    color: #0062cc;
}
.dropdown-menu.show{
    background: #f8f9fa;
    border-radius: 0;
}
.header-btn{
    width: 161%;
    border: none;
    border-radius: 1rem;
    padding: 8%;
    background: #0062cc;
    color: #fff;
    font-weight: 700;
    font-size: 13px;
    cursor: pointer;
}

            adopteunvpn.com

<?php echo 'Votre adresse IP : ❌ ' . getIp(); ?>

                    <button type="button"  class="header-btn">Button</button>

            <button class="navbar-toggler ml-auto" type="button" data-toggle="collapse" data-target="#navbar2">

            </button>

                        Link

                        Link

                        Link

                        Link

                        Link

                        Link

I included bootstrap 4 in header.
Can you explain to me whats wrong ? Im very new to css.
Thank you for your help

A: You can use display: inline; for Li tag  check code above :
.nav_display{

    display: inline;
}

You sould to add this class to Li Tag on ur nav bar :

                        Link

                        Link

                        Link

                        Link

                        Link

                        Link

Also for responsive remove this css   width: 161%; on .header-btn
also remove this class
 let just the id


text:
Q: Using List.nth on an 'a list list in SML I'm trying to declare a function takelist : 'a list list -> int -> 'a list, so that calling takelist xs n will return the elements in spot number n in the lists from xs.
takelist [[#"3", #"6"], [#"6", #"2"], [#"5", #"9"]] 1;

should return [#"6", #"2", #"9"].
This is what I have:
fun tagliste (x::xs) n = List.nth(x,n);

I does half of what I want, and I can't figure how to get everything. I'm just getting the n from the first list instead of all of them. I've been told that map will be able to help, but so far I haven't had any luck using it correctly.
Any help is appreciated!

A: map takes a function f and a list [x0, x1, ..., xn] and returns [f x0, f x1, ..., f xn].
So if we define f x to be List.nth(x,n), you get back [List.nth (x0, n), List.nth (x1, n), ..., List.nth (xn, n)], which is exactly what you want.


text:
Q: Live transcription using AWS Transcribe I'm working on a project that requires a live audio to be transcribed in real-time. I tried the AWS Transcribe with WebSockets using their starter code available on GitHub.
Currently, for testing I have an audio file from a YouTube which I'm streaming to an icecast2 server hosted on a Cloud VM.
The ffmpeg command for streaming to the icecast2 server is
ffmpeg -re -i yt.wav -ar 44100 -ac 1 -c:a libvorbis -aq 5 -content_type 'audio/ogg' -vn -f ogg icecast://source:hackme@serverIP:8000/mystream.ogg
I've modified the code from GitHub such that instead of reading audio data from a microphone it reads the audio from icecast2 server. The problem with this is all it sometimes doesn't return a transcript at all or returns the wrong transcript.
I'd really appreciate if anyone could help


text:
Q: How to execute an HTTP Get with Params, RequestHeaders and RequestContent I'm a couple of weeks into my Flutter journey. I have looked at a few tutorials on using a web service and returning data, but am unsure of a couple of things and how to apply to my web services.
I have completed my web app (written in Elevate Web Builder) and also my server side modules acting as my web services. Inside my web app I call the web service using a server request and the following parameters:
Params : Key and value pairs - used to pass authorization info
eg:
Params.Values['userid'] := 'test'
Params.Values['password'] := 'test-Password'

RequestHeaders - used to specify the content type
eg:
RequestHeaders.Values['Content-Type'] := 'text/plain'

RequestContent : Key and value pairs - used to send values to specify what to retrieve or what to save into the database
eg:
RequestContent.Values['webService'] := 'Get_StaffList'
RequestContent.Values['CompanyId'] := '123'
RequestContent.Values['OnlyActive'] := 'Y'

The Params are specified as URL parameters, but I'm not sure where I specify the RequestHeaders and RequestContent?
I have tried sending RequestHeaders and RequestContent as:
http.post('https://...', headers: {'Content-Type': 'text/plain',
           'webService': 'Get_StaffList',
           'CompanyId': '123',
           'OnlyActive': 'Y'
          });

but this didn't work. Any ideas how it should be sent in Flutter?
Thanks heaps,
Paul

A: Here is an example
String server = "http://localhost:8008";

userSearch(String accessToken, String searchTerm) async {

  String url = server + "/_matrix/client/r0/user_directory/search";

  Map<String, String> headers = {"content-type": "application/json", "authorization": "Bearer $accessToken"};

  String body = jsonEncode({"search_term": searchTerm});

  Response response = await post(url, headers: headers, body: body);

  UserSearchObj users = UserSearchObj.fromJson(jsonDecode(response.body));

  return users;
}

A: I just thought I'd let you know I got it working. I took what you suggested and looked at what the web service was receiving from the web app. Then modified the code in Flutter to send the data in the same format. This now works:
  final response = await http.post(
      Uri.encodeFull('http://mobileuser.pvapps.one:82/modules/rmo_daMLogin'),
      headers: {'Content-Type': 'text/plain'},
      body: 'rmoService=User_Login\n'
          'UserId=fred\n'
          'Password=abc123');

Thanks again for the help,
Paul


text:
Q: Executing an equijoin as a natural join I am new to SQL.
I wish to execute a query involving two tables as both an equijoin and a natural join, where I am counting the instances customers placed orders by city. I am assuming that a customer has placed an order if their customer ID is appearing in the ordertable relation.
I am trying to combine equijoin, COUNT() and GROUP BY in one query, then repeat the same query by using NATURAL JOIN in another.
Please refer to the code below for my attempts and their results.
The following equijoin:
SELECT customer.city, COUNT(*) AS total FROM customer, ordertable
WHERE customer.cust_id = ordertable.cust_id
GROUP BY customer.city
ORDER BY customer.city ASC
;

yields

*

*City |   Count

*SF   | 1

*SLC  | 7

*Tucson | 2

But:
SELECT city, COUNT(*) AS total
FROM customer
NATURAL JOIN orderline
GROUP BY customer.city, city
ORDER BY customer.city ASC
;

yields

*

*City| Total

*LA | 34

*SF |17

*SLC |    170

*Tucson | 34

I believe the first set of results are correct, but I don't understand why the two different approaches yield different results.

A: You are comparing apples and oranges and illustrating why natural joins should be avoided.  Simply do not use them.
The query that you should learn is:
SELECT c.city, COUNT(*) AS total
FROM customer c JOIN
     ordertable ot
     ON c.cust_id = ot.cust_id
GROUP BY c.city
ORDER BY c.city ASC;

Your second query is joining to a different table, orderline, which does not have a cust_id.  So, the "natural join" is generating a Cartesian product.
Note the following:

*

*The join is explicit in the from clause.

*The join conditions are explicit in the query.  No guessing.

*Table aliases make the query easier to write and to read.

I consider the natural join to be an abomination, because it does not take properly declared foreign key relationships into account.  Instead, it simply relies on the naming conventions of the columns to match tables.
And, problems that should result in an error -- such as a missing join key are not detected.


text:
Q: Resolve error not working I'm using ui.router and Restangular.
In $stateProvider I have state with
resolve: {
    dane: function (daneTematy) {
        var promise = daneTematy.getItem(-1);
        return promise;
    }
}

For tests it always gest error and execute $stateChangeError
Here is func from service:
function getItem(id, params) {
    return Restangular.one(zrodlo, id).get()
        .then(getItemSuccess)
        .catch(restangularError);

    function getItemSuccess(response) {
        $log.info('Mam dane elementu - Źródło: ' + zrodlo);
        response.doHistorii();
        return response;
    }
}

function restangularError(response) {
    $log.error("Error with status code", response.status);
    return response;
}

It's not working - it gets to restangularError but not to $stateChangeError. When I delete catch it works well:
function getItem(id, params) {
    return Restangular.one(zrodlo, id).get()
        .then(getItemSuccess);

    function getItemSuccess(response) {
        $log.info('Mam dane elementu - Źródło: ' + zrodlo);
        response.doHistorii();
        return response;
    }
}

What is a problem with restangularError? How to fix it?

A: Within your error handler, you mark the error as being resolved. So ui-router gets a resolved promise and therefore does not cause a $stateChangeError.
To solve this, you have to reject a promise within an error handler if you couldn't fix it. See this excerpt from the angular documentation:

When comparing deferreds/promises to the familiar behavior of
  try/catch/throw, think of reject as the throw keyword in JavaScript.
  This also means that if you "catch" an error via a promise error
  callback and you want to forward the error to the promise derived from
  the current promise, you have to "rethrow" the error by returning a
  rejection constructed via reject.

promiseB = promiseA.then(function(result) {
  // success: do something and resolve promiseB
  //          with the old or a new result
  return result;
}, function(reason) {
  // error: handle the error if possible and
  //        resolve promiseB with newPromiseOrValue,
  //        otherwise forward the rejection to promiseB
  if (canHandle(reason)) {
   // handle the error and recover
   return newPromiseOrValue;
  }
  return $q.reject(reason);
});

For your case this just means you have to modify your error handler as follows (make sure $q is available):
function restangularError(response) {
    $log.error("Error with status code", response.status);
    return $q.reject(response);
}


text:
Q: How do I center this div on the screen? The positioning seems to be off by a little bit

<!DOCTYPE html>

  <meta charset="ISO-8859-1">
  <title>Feet to Meter</title>

      Feet
 <input style="height: 40px;" type="number" name="feet">

      Meter
 <input style="height: 40px;" type="number" name="meter">

I was looking to see why the container DIV wont fully center on the screen. I have tried to adjust the css for the container but cant seem to get the div to stay in the center. It might have something to do with the padding as well.

A: Looks like you're trying to center the div using
  top: 50%;
  left: 50%;
  margin-top: -50px;
  margin-left: -100px;

This doesn't work because the div doesn't have dimensions 100x200. Use relative transform instead:
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);

A: From the .container class remove, the margins
margin-top: -50px; // remove
margin-left: -100px;  // remove

Add
transform: translate(-50%, -50%);

A: remove margin-left from .container and add transform: translateX(-50%);
Visit translate() by mdn to know more about css translate
      .container {
    background-color: #ffffff;
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translateX(-50%);
    margin-top: -50px;
    /* margin-left: -100px; */
    padding-top: 75px;
    padding-right: 50px;
    padding-bottom: 75px;
    padding-left: 50px;
    border-radius: 10px;
  }


text:
Q: How do I get a string value from its hex in PostgreSQL? I have a string value of '2.4.3369.6'. Using the command:
select encode('2.4.3369.6', 'hex') as string_to_hex
I translate this value into a hex and get the next value of
'322e342e333336392e36'

Which command or commands do I use to get the value '2.4.3369.6' from the value '322e342e333336392e36'?

A: Assuming that the encoding is UTF8, you could use the following to get it as text:
SELECT convert_from(decode('322e342e333336392e36','hex'), 'UTF8');

┌──────────────┐
│ convert_from │
├──────────────┤
│ 2.4.3369.6   │
└──────────────┘
(1 row)


text:
Q: How to Ignore specflow test using programing I want to execute specflow scenario based on some condition and skip test if condition is not met programmatically.
I have created one test which gets executed for different countries, but I want to execute test only for one country not all.
I tried scenariocontext.current.pending(); In this case steps are getting skipped but in Jenkins, test result is shown as failed.

A: Since SpecFlow 3.1 you can do it with the UnitTestRuntimeProvider.

    [Binding]
    public sealed class StepDefinitions
    {
        private readonly IUnitTestRuntimeProvider _unitTestRuntimeProvider;

        public CalculatorStepDefinitions(IUnitTestRuntimeProvider unitTestRuntimeProvider)
        {
            _unitTestRuntimeProvider = unitTestRuntimeProvider;
        }

        [When("your binding")]
        public void YourBindingMethod()
        {
            _unitTestRuntimeProvider.TestIgnore("This scenario is always skipped");
        }
    }

Ignoring is like skipping the scenario. Be careful, as it behaves a little bit different for the different unit test runners (xUnit, NUnit, MSTest, SpecFlow+ Runner).
Also, this works only in step definitions. It is not possible to use it in hooks.


text:
Q: What character_set and table collation should I use? I'm experiencing some problems with special characters. When a person tries to register on my site using for example the letter 'ö', I get this error message:
1366 - Incorrect string value: '\xF6m' for column 'username' at row 1

insert into phpbb3_users (username, username_clean, user_password) values ('Ström', 'Ström', '$H$9iK6K37VoHM//')

I understand the character settings could be the problem and when I check the database, I can see that some tables have collation:
latin1_swedish_ci

and some tables have collation (for example the table 'phpbb3_users' that is having problem in the example above):
utf8_bin

And when I check my MySql settings I see that I have these mixed settings:
| character_set_client | latin1 |
| character_set_connection | latin1 |
| character_set_database | latin1 |
| character_set_filesystem | binary |
| character_set_results | latin1 |
| character_set_server | latin1 |
| character_set_system | utf8 |
| character_sets_dir | /usr/share/mysql/charsets/ |
| collation_connection | latin1_swedish_ci |
| collation_database | latin1_swedish_ci |
| collation_server | latin1_swedish_ci

*

*What character_set do you recommend me to use? I have learned that changing character_set to utf8mb4 could solve the problem, but does my MySql version (5.1.4) support that?

*Were should I make character_set changes? In all instances of the /etc/my.cnf and all table collations?

Thanks.

A: You need to:

*

*set the character set of the column (or the next higher default charset of the table/database/server) to a character set that supports the character you want to store. If you want to store "ö", latin1 will do. If you want to store more "exotic" characters, utf8 is a great choice, because it support virtually everything.*
Note that the collation like latin1_swedish_ci is pretty much irrelevant. The collation follows from the charset you choose, but the charset is first and foremost the import variable here.

*set the connection charset to the charset you're going to send text in. If you're going to send UTF-8 encoded text to the database, you need to tell it that by setting the connection charset to utf8. This is most likely where your problem is. How to set it depends on how you connect to the database. mysql_set_charset, a charset parameter in your DSN connection string or a SET NAMES utf8 query will do.

*send text encoded in the encoding you declared in step 2.

* MySQL's utf8 is not "real" UTF-8, supporting only a subset of all of Unicode. utf8mb4 is "real" UTF-8, supporting everything. utf8mb4 is not available on MySQL 5.1, only 5.5+.
For more information, see UTF-8 all the way through, Handling Unicode Front To Back In A Web App, What Every Programmer Absolutely, Positively Needs To Know About Encodings And Character Sets To Work With Text.


text:
Q: Kubernetes - Is it possible to set one public FQDN for many nodes? Let's say I have a Kubernetes cluster with 1 master node Master and 2 worker nodes Worker 1 and Worker 2. All have publicly reachable IP addresses.

*

*Master has the IP 1.1.1.1

*Worker 1 has the IP 2.2.2.2

*Worker 2 has the IP 3.3.3.3

Additionally, let's assume my cluster exposes an nginx-webserver with a website on port 80 and I can reach it via any of the 3 nodes (e.g. 1.1.1.1:80 or 2.2.2.2:80 or 3.3.3.3:80 opens the same website).
However, remembering the IP addresses is "difficult" and I would much rather like to remember a domain name. So I choose "www.flying-circus.uk" as my domain. But there is a problem: A public domain name is only assigned to one IP address, multiple IPs cannot have the same FQDN.
How can I configure my cluster so that the website is reachable from any node via the FQDN?

A:
But there is a problem: A public domain name is only assigned to one IP address, multiple IPs cannot have the same FQDN

First, this statement is not absolutely true. An FQDN can point to multiple IP addresses. Something preventing you from doing that could be that your domain provider doesn't allow you to have the same FQDN with multiple DNS A pointers.
For example, yahoo.com, google.com point to different IPs:
$ dig yahoo.com

; <<>> DiG 9.10.6 <<>> yahoo.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 27299
;; flags: qr rd ra; QUERY: 1, ANSWER: 6, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;yahoo.com.         IN  A

;; ANSWER SECTION:
yahoo.com.      323 IN  A   98.138.219.231
yahoo.com.      323 IN  A   98.137.246.7
yahoo.com.      323 IN  A   98.138.219.232
yahoo.com.      323 IN  A   98.137.246.8
yahoo.com.      323 IN  A   72.30.35.10
yahoo.com.      323 IN  A   72.30.35.9

;; Query time: 51 msec
;; SERVER: 10.240.246.53#53(10.240.246.53)
;; WHEN: Tue Jun 23 18:41:03 PDT 2020
;; MSG SIZE  rcvd: 123

Secondly, Kubernetes has several tools/resources that can help you achieve your hypothetical case. For example, if you'd like to have a single externally available endpoint to pods running in any Kubernetes nodes you can use a Service combined with an Ingress and Ingress Controller.


text:
Q: Javascript: How to Save Image with a particular filename instead of download.png I am trying to download the file as helloWorld.png but it always saves as download.png.
Can you help me identify what i am missing?
var $container = $('#svg-container'),
        // Canvg requires trimmed content
    content = $container.html().trim(),
    canvas = document.getElementById('thecanvas');
    // Draw svg on canvas
    canvg(canvas, content);
    // Change img be SVG representation
    var theImage =  canvas.toDataURL('image/png');
    $('#svg-img').attr('src', theImage);

function downloadWithName(uri, name) {

    function eventFire(el, etype){
        if (el.fireEvent) {
            (el.fireEvent('on' + etype));
        } else {
            var evObj = document.createEvent('Events');
            evObj.initEvent(etype, true, false);
            el.dispatchEvent(evObj);
        }
    }

    var link = document.createElement("a");
    link.download = name;
    link.href = uri;
    eventFire(link, "click");

}

downloadWithName(theImage, "helloWorld.png")

http://jsfiddle.net/shanthisivanesan/a2FLx/22/

A: try this jquery code, it works on the latest Firefox, (where uri is the datauri and name is the image filename)
$('<a>',{
    type: "submit",
    download: name,
    href: uri,
    id: 'download_link'
}).appendTo('body');

$('a#download_link')[0].click();


text:
Q: Appendices title on first page of Appendices and not separate page I have used the appendix package like this.
\usepackage[toc, page]{appendix}

This puts the title 'appendix' on its own page.  Now I want to have this title, but I would rather if it put on the same page as the first chapter of the appendix, so you would have it just above chapter title of the first appendix.
I tried to read the manual, but I did not see an option for this.

A: A version with patching of \@makechapterhead:
The patch checks whether the chapter number is 1, i.e. meaning the first appendix chapter and insertes the Appendix line accordingly, taking the values of \abovefirstappchapskip etc. into account -- those values can be changed at will.
\documentclass{book}

\usepackage{xpatch}
\usepackage[toc]{appendix}

\makeatletter
\newlength{\abovefirstappchapskip}
\newlength{\belowfirstappchapskip}
\AtBeginEnvironment{appendices}{%
  \xpatchcmd{\@makechapterhead}{%
    \vspace*{50\p@}%
  }{%
    \ifnum1=\c@chapter
    \vskip\abovefirstappchapskip%
    \fi
  }{}{}
  \xpatchcmd{\@makechapterhead}{%
    \parindent \z@ \raggedright \normalfont
  }{%
    \parindent \z@ \raggedright \normalfont
    \ifnum1=\c@chapter
    \begingroup
    \centering \Huge\bfseries \appendixname
    \vskip\belowfirstappchapskip
    \endgroup
    \fi
  }{}{}
}
\makeatother

\setlength{\abovefirstappchapskip}{30pt}
\setlength{\belowfirstappchapskip}{30pt}

\begin{document}
\tableofcontents

\begin{appendices}
\chapter{Foo}

\chapter{Foobar}

\end{appendices}

\end{document}


text:
Q: With filePond how do I get custom data i.e. galleryId (custom) back to client when file(s) uploaded? Using filePond to upload image(s), how can I decorate the request with data such as for example galleryId, and respond with decorated data? Or is there an alternative solution?

A: You can do this with the ondata property:
pond.setOptions({
    server: {
        process: {
            url: './',
            ondata: (formData) => {
                formData.append('galleryId', 'galleryId');
                return formData;
            }
        }
    }
});

See the Docs: https://pqina.nl/filepond/docs/patterns/api/server/#configuration


text:
Q: Restrict to load netframework DLL in Visual Studio or other developer project I have a Netframework DLL project in Visual Studio and the DLL is compiled in Release mode and used in another project, how I can restrict to load or the use about the DLL by another person than could stolen my DLL and use in his/her project?

A: I found the solution with internal class and method:
Some class in My dll:
[assembly: InternalsVisibleTo("FriendAssembly")]
namespace MiLibrary
{

    internal class Class1
    {
        internal static string GetName()
        {
            return "My Name";
        }
    }
}

Another Project in some class:
namespace MyApp
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            txbText.Text = MiLibrary.Class1.GetName();
        }
    }
}

Only "FriendAssembly" has access to Class1. "Another Project" must have the assembly name as "FriendAssembly" (Menu Project -> Properties of "Another Project" -> Application -> Assembly Name)
InternalsVisibleToAttribute Class
Related questions in Stackoverflow:
Protect C# DLL from third party
How to protect dlls?


text:
Q: Error after adding gem 'mithril_rails' I add gem 'mithril_rails' in my Gemfile, make bundle install and bundle update, add //= require mithril in my application.js file, type rails s and get error:

/Users/myusername/.rvm/gems/ruby-2.2.2/gems/mithril_rails-0.0.7/lib/mithril_rails/rails/engine.rb:5:in block in <class:Engine>': undefined methodregister_engine' for
  nil:NilClass (NoMethodError)

I use rails 4.2.3, mongoid.
What can I do?

A: You can use 'sprockets 2.12.3'. The issue relating to sprockets and already reported.


text:
Q: How Do I Disable Remote Management and Enable Screen Sharing? I am connected to a headless remote Mac Mini. Under Sharing in the System Preferences both Remote Login and Remote Management are checked though Remote Mangement is "grayed out". I would like to disable Remote Management and enable Screen Sharing.
Currently the Screen Sharing checkbox is "grayed out". When I click on it, I get the following message: "Screen Sharing is currently being controlled by the Remote Management service." This warning to not continue makes sense if I would lose my current VNC connection and not be able to turn it back on remotely.
To access the remote server I Connect to Server (command-k) vnc://IPnumber
I would like just Remote Login and Screen Sharing enabled and Remote Management disabled.
Does anyone know the steps for me to accomplish this goal remotely?

A: I found the following code in a file I didn't open for a long time. It enables Remote Login on a remote device. Save the script somewhere (from now on referred to as /path/to/script/). Copy the script to the other device.
tell application "System Preferences" to set current pane to pane "com.apple.preferences.sharing"
tell application "System Events" to tell process "System Preferences"
    click checkbox 1 of row 6 of table 1 of scroll area 1 of group 1 of window "Sharing"
end tell

This enables remote login. Now, to disable remote management and enable screen sharing, use the same script, but remove the 3rd line and add these 2 lines:
tell application "System Preferences" to set current pane to pane "com.apple.preferences.sharing"
tell application "System Events" to tell process "System Preferences"
    click checkbox 1 of row 7 of table 1 of scroll area 1 of group 1 of window "Sharing"
    click checkbox 1 of row 2 of table 1 of scroll area 1 of group 1 of window "Sharing"
end tell

To copy this script on the remote device, use scp (secure copy). To use scp type
scp /path/to/script username@IP.of.other.device:/some/path
OR
scp username@hostnameOfDevice:/some/path/
The second option (using the device hostname) requires that the devices are on a computer-to-computer network, so it will not work on a normal wifi network. You will see a prompt requesting the password of username. When you type the password, you will not see any text appear (obviously to prevent people from seeing the password).
Once it is copied, remotely log into the device:
ssh username@IP.of.other.device
OR
ssh username@hostnameOfDevice
Again, the use of the hostname requires computer-to-computer network. Once logged in, run the script using osascript /some/path/theScript.scpt (remember that using scp we copied the script to /some/path, this will be different on your device). This will disable remote management and enable screen sharing.
Good luck!


text:
Q: JSF commandlink incorrect navigation Before asking this questions I have carefully assessed the feasibility to solve the following problem.
I have an external link being fired from an email viewRequest.xhtml?requestID=6. I use a filter to intercept the incoming request and in case the user is not authenticated it is forwarded to the login.xhtml page. After the user is authenticated the request is forwarded by FacesContext.getCurrentInstane().getExternalContext().redirect(redirected-url) Then it displays the page successfully.
Now if try to logout from same page i.e, viewRequest.xhtml page, the requested URI is viewRequest.xhtml again which takes me to the same page instead of logging out and redirect me to the login page.
I have the real concern of why the request.getRequestedURI in filter is still viewRequest.xhtml instead of login.xhtml
Code for reference
AuthenticationFilter - User is un-authenticated - Adding requested email link in session
String from = req.getRequestURI();
if (req.getQueryString() != null) from += "?" + req.getQueryString();
req.getSession().setAttribute("from", from);
res.sendRedirect(req.getContextPath() + "/faces/pages/login.xhtml");

After user is logged in
if (from != null && !from.isEmpty()) {
    externalContext.getSessionMap().remove("from");
    externalContext.redirect(from); *-----------Original URL re-direction---------*
    return null;
}
else{
       result = "adminHome";
    }

Now we are in viewRequest.xhtml page - loaded successfully - Now clicked on Log out
String from = req.getRequestURI();   <!--FILTER-->

The value of requestedURI is still viewRequest.xhtml
logout() in LoginController.java
FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
return login;

Please help. Thank you very much.


text:
Q: NGINX as SSL Proxy for Tomcat I've got an Angular site and Tomcat web service application installed on the same Linux RH7 EC2 host. I'm trying to serve the web site from / and redirect anything at /service to my tomcat instance, both over SSL.
The static site serving over SSL is working fine. Also if I hit http://mydomain:8080/mytomcatapp that's working fine too. Trying to setup reverse proxying for the tomcat app by going https://mydomain/service/mytomcatapp however is resulting in 502 responses. The other samples I've seen have more fancy settings for headers etc, not sure if I need that, advice would be handy. Also my webservice at mytomcatapp takes get parameters too, so not sure if anything special is required there either.
nginx conf snippet
server {
listen       80;
server_name mydomain   ;
root /var/www;
index index.html index.htm;

location / {
    # index  index.html index.htm;
    try_files $uri $uri$args $uri/index.html /index.html =404;
}

location /service {
    proxy_pass http://mydomain:8080;
}

...

tomcat server.xml snippet
<Connector port="8080" protocol="HTTP/1.1"
           connectionTimeout="20000"
           redirectPort="8443"
           proxyPort="443"
           scheme="https"
            />

Note: mydomain in the nginx conf has been swapped from my real domain (don't want to publish here). Also I have tried combinations of server.xml configuration with the proxyName attribute set but didn't seem to affect it.
Thanks!

A: Do you have implemented certificate for SSL ?? If you want to use HTTPS you will need certificate.

A: Ended up being the enhanced security posture of SELinux that was blocking proxying. See:
https://www.nginx.com/blog/nginx-se-linux-changes-upgrading-rhel-6-6/
You need to set it to permissive mode by running the command: setenforce 0
For reference, my final location block in the nginx config is below for anyone else attempting, took a few goes to get right. Note that the trailing slashes on the location and proxy_pass variables are very important.
location /service/ {
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-Proto https;
    proxy_pass http://example.com:8080/;
}


text:
Q: I'm having this error java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference enter image description here
How to solve this error? My app is not running

A: on your getcount method:
try doing -->return (dataList == null) ? 0 : dataList.size();