text:
Q: Adding +1 every time radiobox is used I'm wanting to add +1 every time a radiobox or checkbox is used. This happens when calculate is pressed and putting it into a string then when the summary button is pushed it displays it in a messagebox with the final total of times it was pushed.
this is my code so far but it doesnt seem to work,
This is my Calculate button
        int Quantity;
        int Finalprice;

        if (lunchRadioButton.Checked == true)
        {
           Meal = Lunch;

        }
        else if (tableCheckBox.Checked && waiterCheckBox.Checked)
        {
            Extras = Waiter + Table;

        }
        else if (waiterCheckBox.Checked)
        {
            Extras = Waiter;

        }
        else if (tableCheckBox.Checked)
        {
            Extras = Table;

        }

        //Early Evening Meal
        if (earlyEveningRadioButton.Checked == true)
        {
            Meal = Early;

        }

        else if (tableCheckBox.Checked && waiterCheckBox.Checked)
        {
           Extras = Table + Waiter;

        }
        else if (waiterCheckBox.Checked)
        {
            Extras = Waiter;

        }
        else if (tableCheckBox.Checked)
        {
            Extras = Table;

        }

        //Late evening options
        if (lateEveningRadioButton.Checked == true)
        {
            Meal = Late;

        }

        //Late Evening, Corner table and Dedicated waiter selected.
        else if (tableCheckBox.Checked && waiterCheckBox.Checked)
        {
            Extras = Table + Waiter;

        }

        //Late Evening and Dedicated waiter selected.
        else if (waiterCheckBox.Checked)
        {
           Extras = Waiter;

        }

        //Late Evening and Corner Table
        else if (tableCheckBox.Checked)
        {
            Extras = Table;
            ;
        }

        try
        {
            Quantity = int.Parse(guestTextBox.Text);
            Mealprice = (Meal * Quantity);
            Finalprice = (Mealprice + Extras);
            finalAmountLabel.Text = Finalprice.ToString("C");

        }
        catch
        {
            guestTextBox.Focus();
            guestTextBox.SelectAll();
           MessageBox.Show("Please enter a quantity in numerical form","Quantity Error!");
        }

This is the Summary Button
        int TotalLunch = 0;
        int TotalEarly = 0;
        int TotalLate = 0;
        int TotalBookings = 0;

        int TotalWaiters = 0;
        int LateWaiters = 0;
        int EarlyWaiters = 0;
        int LunchWaiters = 0;

        int TotalCornerTables = 0;
        int EarlyCornerTables = 0;
        int LateCornerTables = 0;
        int LunchCornerTables = 0;

        if (earlyEveningRadioButton.Checked == true)
        {
            TotalEarly = +1;
            TotalEarly.ToString();
        }
        else if (earlyEveningRadioButton.Checked && waiterCheckBox.Checked)
        {
            EarlyWaiters = +1;
            EarlyWaiters.ToString();
        }
        else if (tableCheckBox.Checked && earlyEveningRadioButton.Checked)
        {
            EarlyCornerTables = +1;
            EarlyCornerTables.ToString();
        }
        else if (waiterCheckBox.Checked && tableCheckBox.Checked)
        {
            EarlyWaiters = +1;
                EarlyCornerTables = +1;
                EarlyWaiters.ToString();
                EarlyCornerTables.ToString();
        }
        MessageBox.Show("Number of Early Bookings" + " " + TotalEarly + "   " +
                        "Number of Early Evening Waiters" + " " + EarlyWaiters
                        + "number of Early Evening Corner Tables tables" + " " + EarlyCornerTables

                         );

Any suggestions or help would be greately appriciated :)

A: The best way you can do this, is using the eventhandler CheckedChanged foreach checkbox.
in the event do this:
if(checkBox.Checked)
{
    //int +1
}

A: I'll start with an answer to your question...
Your code will not increment TotalEarly by one, but it will assign +1 to the variable.
TotalEarly = +1;

For incrementing you should either use the ++ or the += operator:
TotalEarly++; // increments by 1
TotalEarly += 1; // also increments by 1, but += can be used with other numbers

Some other notes, not related to your question:
TotalEarly.ToString();

This will not do anything since you do not assign the result to a variable. This will not convert TotalEarly to a string variable! The type of TotalEarly is fixed to int as you specified.
You would have to write
var totalEarlyString = TotalEarly.ToString();

to be able to use the result afterwards. You might wonder why your MessageBox still displays that number as a string although you use the int variable:
"Number of Early Bookings" + " " + TotalEarly

This is because the ToString() method is called automatically in this case. So, you can really save some lines by removing your calls to ToString() after the assignments.

One more thing: local variables are typically named using camelCase. That means, the first character is lower case and every additional word starts with an uppercase character. PascalCase (i.e. also starting with uppercase character) is typically used for properties, methods, class names etc, but not for local or member variables.

It seems like you want each value in the MessageBox to be on a separate line (at least I assume that is why you added some spaces at the end of the first line:
MessageBox.Show("Number of Early Bookings" + " " + TotalEarly + "   " +
                    "Number of Early Evening Waiters" + " " + EarlyWaiters
                    + "number of Early Evening Corner Tables tables" + " " + EarlyCornerTables
                     );

This might not work on all machines. The MessageBox has different sizing behavior on differnt versions of Windows. Some will wrap the text to multiple lines, some will not, or at least at different widths!
Therefore, you better add an Environment.NewLine at the end of each line. This will add a line break to your string which will be interpreted as such by the MessageBox:
MessageBox.Show("Number of Early Bookings " + TotalEarly + Environment.NewLine +
                "Number of Early Evening Waiters " + EarlyWaiters + Environment.NewLine +
                "Number of Early Evening Corner Tables tables " + EarlyCornerTables);

A: Accordion to your comments in your code I think the problem is that your if else statements are wrong.
Q1: Should it calculate on every checkbox click or only when you click calculate?
- if it should calculate on every checkbox click then you have to use the CheckedChanged event as RaZor points out.
Q2: Is it true that de client can have a lunch + waiter + table?
- if that is true then your if else statement should be as follows:
if (lunchRadioButton.Checked == true)
{
    Meal = Lunch;

    if (tableCheckBox.Checked && waiterCheckBox.Checked)
    {
        Extras = Waiter + Table;
    }
    else if (waiterCheckBox.Checked)
    {
        Extras = Waiter;

    }
    else if (tableCheckBox.Checked)
    {
        Extras = Table;

    }
}


text:
Q: connect() to unix:/var/run/php/php7.2-fpm.sock failed (11: Resource temporarily unavailable) I have a question about nginx. I have some webservers on my environment using nginx  and they are behind Load balancer. Suddenly, all web services are down and I found this error log on nginx:

[error] 7097#7097: *44471950 connect() to unix:/var/run/php/php7.2-fpm.sock failed (11: Resource temporarily unavailable) while connecting to upstream, client: xxx.xxx.xxx.xxx, server: *.web.com, request: "HEAD /3.1?language=id&app=ios HTTP/1.0", upstream: "fastcgi://unix:/var/run/php/php7.2-fpm.sock:", host: "web01.com"

Can anybody help me?

A: Please check Below Value, Default must be 128.
sysctl net.core.somaxconn

Increase this value by running the following command.
echo "net.core.somaxconn=65536" >> /etc/sysctl.conf
sysctl -p

Then restart PHP-FPM to take effect of new changes (Depends on Version of PHP-FPM).
service php-fpm restart
service php7.2-fpm restart

redpajama_set_name: RedPajamaStackExchange


text:
Q: ProxySQL user is not authenticated by MySQL I have a container for ProxySQL 2.2.4 and another for MySQL 8.0.31. Both containers are using same network name. So from ProxySQL container I can access MySQL running in another container.
Even, ProxySQL Admin can show the MySQL service as ONLINE and ping/connect in Admin has no errors.
ProxySQL Admin>
select hostgroup,srv_port,status from stats_mysql_connection_pool;

hostgroup
srv_port
status

1
3306
ONLINE

1
3306
ONLINE

Now, when from outside the ProxySQL container, I try to run following command to access MySQL services thru proxySQL, it fails.
Note: The user "ravi" exists on  both mysql and proxysql side, with same password.
$ sudo mysql -u ravi -pravi123 -h 0.0.0.0 -P16033   -e "SELECT @@port"
Warning] Using a password on the command line interface can be insecure.
ERROR 1045 (28000) at line 1: Access denied for user 'ravi'@'172.18.0.2' (using password: YES)

The ProxySQL log in container shows:

2022-11-12 08:31:24 mysql_connection.cpp:1063:handler(): [ERROR] Failed to mysql_real_connect() on 1:mysql:3306 , FD (Conn:42 , MyDS:42) , 1045: Access denied for user 'ravi'@'172.18.0.2' (using password: YES).

The same user gets connected with same password from the ProxySQL container shell.
$ sudo docker exec -it proxysql bash
root@34c06973094d:/# mysql -u ravi -p -h mysql
Enter password:
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MySQL connection id is 4352
Server version: 8.0.31 MySQL Community Server - GPL
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MySQL [(none)]>
what is the error behind it? why is not ProxySQL able to authenticate the user, while the same user is able to login to MySQL from shell.
Expected : The user should be able to run the SQL queries using ProxySQL which is already connected and being monitored without connection and monitoring errors.

A: Please verify that you have added the "ravi" user to the mysql_users table on proxysql e.g.:
INSERT INTO mysql_users VALUES (username, password) ('ravi', 'super_secret_password')

You can use the hashed password in the mysql_users password column, but you have to use the mysql_native_password authentication plugin in MySQL. Otherwise, you will need to enter the password in plaintext. (related GitHub issue)
Afterwards, you will need to run:
LOAD mysql users TO RUNTIME;
SAVE mysql users TO DISK;

This is important, because changes to the mysql_users table will not take place until you load them to runtime, and will not persist after a crash unless you save them to disk.
Please note, you can configure quite a lot in the mysql_users table, please check the proxysql user configuration documentation for more details.

A: In regards to the default_authentication_plugin, please run the following command:
SQL> show global variables like '%authentication%';

If you were using caching_sha2_password, try using mysql_native_password instead of caching_sha2_password as ProxySQL does not fully support the caching_sha2_password mechanism internally.
There is a trick to make it work, but it's not highly recommended because the password will be in plain-text and insecure on the ProxySQL side. You can disable the hashing password in ProxySQL by executing the following command:
SQL> update global_variables set Variable_Value='false' where Variable_name='admin-hash_passwords';

At this point, you will be able to connect to MySQL 8 using the caching_sha2_password, but the password is visible in ProxySQL.
For this, you can refer to the documentation here: ProxySQL Support for MySQL caching_sha2_password - Percona Database Performance Blog


text:
Q: Can't pause mediaplayer from adapter I have the listview in my activity. Each listview item contains play/pause buttons, and these buttons start audio playback by calling activity method, like MainActivity.play(), but when i press stop button, it doesn't work. Why?
I tried to put pause button on the Activity and it works great.
Here is my button's onClickListener, which is in adapter
            view.findViewById(R.id.btnPause).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ((MainActivity)context).pause();
                }
            });

Here is pause method from activity
    public void pause() {
                if(mediaPlayer.isPlaying()){
                    mediaPlayer.pause();
                } else {
                    mediaPlayer.start();
                }
    }

This is my whole adapter
public class lvAdapter extends BaseAdapter {
    Context ctx;
    LayoutInflater lInflater;
    ArrayList<m> objects;
    lvAdapter(Context context, ArrayList<m> products) {
        ctx = context;
        objects = products;
        lInflater = (LayoutInflater) ctx
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    // кол-во элементов
    @Override
    public int getCount() {
        return objects.size();
    }

    // элемент по позиции
    @Override
    public Object getItem(int position) {
        return objects.get(position);
    }

    // id по позиции
    @Override
    public long getItemId(int position) {
        return position;
    }

    // пункт списка
    @SuppressLint("SetTextI18n")
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        View view = convertView;
        if (view == null) {
                view = lInflater.inflate(R.layout.audioItem, parent, false);
        }
        final View finalView = view;
        view.findViewById(R.id.btnPlay).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    File file = new File(ctx.getFilesDir() + "/voices/" + objects.get(position).t);
                    if (file.exists()) {
                            ((MainActivity)ctx).play(file.getPath());
                    }
                }
            });
        view.findViewById(R.id.btnPause).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((MainActivity)context).pause();
            }
        });
        return view;
    }
    m getProduct(int position) {
        return ((m) getItem(position));
    }
}

And it is just doesn't work. mediaplayer is not pausing.


text:
Q: HTML: перебор произвольных DOM-элементов клавишей Tab Допустим, я хочу чтобы чтобы на любые DOM-элементы (например, на
ы указанного класса) можно было наводиться клавишей Tab, как это можно делать со ссылками и полями ввода. Соответственно, если таких элементов несколько, то при повторном нажатии на клавишу tab должен быть выделен следующий элемент.
Уже знаю, что что внешний вид предстоит выделенного объекта нужно будет прописать самому (так как таковой определён по умолчанию лишь для полей ввода и ссылок). Также предполагаю, что атрибут для полей, отвечающий за порядок их перебора клавишей Tab, использовать для других элементов нельзя.

A:

Первый див

Второй див

Третий див


text:
Q: JavaScript get date and time from timestamp I have this field as part of a web response:
datetime_local: "2015-02-16T19:00:00"

Can I extract the date and time? For instance I would like to display
February 16th at 7pm

Is this possible?

A: Use this function
function getFormattedDate(date)
{
var fortnightAway = new Date(date),
        date = fortnightAway.getUTCDate(),
        hour = fortnightAway.getUTCHours(),
        month = "January,February,March,April,May,June,July,August,September,October,November,December"
      .split(",")[fortnightAway.getUTCMonth()];

    function nth(d) {
      if(d>3 && d<21) return 'th'; // thanks kennebec
      switch (d % 10) {
            case 1:  return "st";
            case 2:  return "nd";
            case 3:  return "rd";
            default: return "th";
        }
    }

return month+" "+date+nth(date) +" at "+(hour<12?hour+"am":(hour-12)+"pm");
}

Call it like getFormattedDate("2015-02-16T19:00:00")
Working Fiddle

A: You can using momentjs.com for formatting:
moment(Date.parse("2015-02-16T19:00:00")).format("MMMM Do [at] hhA");
// February 16th at 10PM


text:
Q: pause when having columns I have this slide that works fine.
---
format:
  revealjs
---

## title

::: columns
::: {.column width="35%"}
```{.python code-line-numbers="2"}
def cal(C):
  return 2 + C
```
:::

::: {.column width="10%"}
:::

::: {.column  width="55%"}
```{python}
def cal(C):
  res = 2 + C
  return res
```

```{python}
#| echo: true
F = 0
def cal(C):
  res = F + C
  print('res', res)
  return res
```

```{python}
print(F)
```

:::
:::

Now, I want to present the left column , then pause, then present the right column and pause before the result of print(F) appears.
I tried putting the . . . in order to pause but it seems it doesn't work when you have colunms defined.

A: So, after reading this
I managed to do it using fragments.
---
format:
  revealjs
---

## title

::: columns
::: {.column width="35%"}
```{.python code-line-numbers="2"}
def cal(C):
  return 2 + C
```
:::

::: {.column width="10%"}
:::

::: {.column  width="55%"}
::: {.fragment}
```{python}
def cal(C):
  res = 2 + C
  return res
```

```{python}
#| echo: true
F = 0
def cal(C):
  res = F + C
  print('res', res)
  return res
```
:::

::: {.fragment}
```{python}
print(F)
```
:::

:::
:::


text:
Q: What name describes the theory of the strength of a logical statement? Most people on this site are familiar with the idea of the "strength" of a statement. Ignoring the validity of the statements themselves, "All primes are even." is a logically weaker statement than "All integers are even." Even the statement "All integers except 7 are even." still seems qualitatively stronger than "All primes are even." even though neither implies the other.
What name describes the theory of the relative strength of logical statements? I've tried searching for a variety of keywords but have turned up surprisingly little besides references to the "intuitive" definitions like that above.

A: I agree with the above comments; $B{\implies}A$ in conjunction with $A\not\equiv B$ is the only context I can think of offhand where it is unambiguous to say that statement $B$ is stronger than $A,$ so I think that's a fair characterisation of statement strength. If there is a specific descriptor for this, I have never heard of it.

Addendum
I think the more interesting cases are where one statement is not a clear superset of the other. I've updated my question to clarify this.
In this case (including in your specified example), any assertion about the two statements' relative strength would be ambiguous in sense; on the other hand, there is no controversy in claiming that one statement is satisfied by more entities than the other statement.


text:
Q: Skip empty cell after the specified word using Xpath I'm use Xpath to extract data from Excel files. I use the below Xpath code to get the values under a specific word.
Code:
//tr[position() > count(//tr[contains(.,'Tariff')]/preceding-sibling::tr)+1]/td[position() = count(//tr/td[contains(.,'Tariff')]/preceding-sibling::td)+1]

This is working but I came across some Excels that adds an empty  right after word "Tariff". Which actually mess up the end result. Below is part of the Excel which is converted to HTML source I work with.
Code:

               22
               Tariff
               Description
               Country of origin
               Quantity
               Amount DKK
               Net weight kg

               23

               24
               42022290
               BAG
               CN
               2
               147,06
               0,558

               25
               61043900
               JACKET
               CN
               1
               146,14
               0,364

The
 I want skip is this one,
Code:

               23

I tried using //tr[contains(.,'Tariff') and (text()!='')]/preceding-sibling::tr)+1 and the I tried not(contains(.,'')) but that also didn't work. Can some one help me to figure this out.

A: Your XPath is a bit complicated. You want to get value under the specific word "Traffic".
If you really want to keep your XPath, add a condition at the end of it :
//tr[position() > count(//tr[contains(.,'Tariff')]/preceding-sibling::tr)+1]/td[position() = count(//tr/td[contains(.,'Tariff')]/preceding-sibling::td)+1][contains(@data-cell,"A")]

But shorter XPath also work :
//td[contains(.,"Tariff")]/following::td[contains(@data-cell,"A")]

If you need something without having to specify the name of the column ("A" for Traffic), then use :
//td[contains(.,"Tariff")]/following::td[contains(@data-cell,substring(//td[contains(.,"Tariff")]/@data-cell,1,1))]


text:
Q: How to merge lists in a specific order python How can I merge these 3 lists in this specific way?
Input:
l1 = [0, 0]
l2 = [1, 1, 1]
l3 = [2, 2, 2]

Output:
merged = [0, 1, 2, 0, 1, 2, 1, 2]

A: If your lists don't contain Nones, itertools.zip_longest will produce these tuples:
>>> for t in itertools.zip_longest(l1, l2, l3):
...     print(t)
(0, 1, 2)
(0, 1, 2)
(None, 1, 2)

which you can then chain together and filter the Nones out of:
merged = [x for x in itertools.chain.from_iterable(itertools.zip_longest(l1, l2, l3))
          if x is not None]

Or shorter, since there's already a list comprehension:
merged = [x for t in itertools.zip_longest(l1, l2, l3) for x in t
          if x is not None]

A: Try this:
from functools import partial
from operator import is_not
import itertools
list(filter(partial(is_not, None), itertools.chain.from_iterable(itertools.zip_longest(l1,l2,l3))))

# [0, 1, 2, 0, 1, 2, 1, 2]


text:
Q: How to load XML nodes and content into variables dynamically I have a very long list of XML separated into sections. For each page it loads content from the XML based on a category node (list_node). For now I am grabbing the content by referencing the nodes directly, but I don't want to have to put in a line for every single node.
Is there a way to just read the XML, loads the nodes into an array, then set a new variable as the node name and loads in the contents? This is my current setup:
<media_item>
<title>temporary title</title>
<key>652843722</key>
<path>/states/CA</path>
<filename>climate-pollution-harmful.html</filename>
<link>http://a-url-goes-here.com</link>
<blank>yes</blank>
<author/>
<date>August 15, 2015</date>
</media_item>

(The XML has a lot more nodes then that, and different categories all specified by the "list_node" call earlier up in my code)
 $.ajax({
        type: "GET",
        url: "http://url-of/file.xml,
        dataType: "xml",
        success: function(xml){
            $(xml).find(list_node).each(function(i){
                var title = $(this).find('title').text();
                var url = $(this).find('link').text();
                var date = $(this).find('date').text();
                var author = $(this).find('author').text();
                var org = $(this).find('org').text();

So instead of "var title = $(this).find('title').text();" for every single node, I'd just like it to do it automatically.

A: If all the nodes are simply text nodes you can loop over children() and create an array of objects using the tagName's as property names
$.get('data.xml', function (xml) {

    var results = $(xml).find('media_item').map(function () {
        var row = {}
        $(this).children().each(function () {
            row[this.tagName] = $(this).text();
        });
        return row;
    }).get();

    console.log(results);

}, 'xml');

This can easily be adapted to include attributes as well.
The above code converts the xml shown to:
[
 {
  "title": "temporary title",
  "key": "652843722",
  "path": "/states/CA",
  "filename": "climate-pollution-harmful.html",
  "link": "http://a-url-goes-here.com",
  "blank": "yes",
  "author": "",
  "date": "August 15, 2015"
 }
]

DEMO


text:
Q: Listing the exported functions of a DLL I'm looking for a way (in C++/Windows) to list the exported functions of a DLL (and maybe even methods which are not exported) using dbgHelp.
Does anybody know which method can do it?

A: If you're content with other tools then there are a number that do list exported functions. One is Microsoft's dumpbin, use the /exports option.

A: There is code here to do this.  I have cleaned it up a bit and it worked in the scenario shown below, retrieving function names from Kernel32.Dll.
#include "imagehlp.h"

void ListDLLFunctions(string sADllName, vector<string>& slListOfDllFunctions)
{
    DWORD *dNameRVAs(0);
    _IMAGE_EXPORT_DIRECTORY *ImageExportDirectory;
    unsigned long cDirSize;
    _LOADED_IMAGE LoadedImage;
    string sName;
    slListOfDllFunctions.clear();
    if (MapAndLoad(sADllName.c_str(), NULL, &LoadedImage, TRUE, TRUE))
    {
        ImageExportDirectory = (_IMAGE_EXPORT_DIRECTORY*)
            ImageDirectoryEntryToData(LoadedImage.MappedAddress,
            false, IMAGE_DIRECTORY_ENTRY_EXPORT, &cDirSize);
        if (ImageExportDirectory != NULL)
        {
            dNameRVAs = (DWORD *)ImageRvaToVa(LoadedImage.FileHeader,
                LoadedImage.MappedAddress,
            ImageExportDirectory->AddressOfNames, NULL);
            for(size_t i = 0; i < ImageExportDirectory->NumberOfNames; i++)
            {
                sName = (char *)ImageRvaToVa(LoadedImage.FileHeader,
                        LoadedImage.MappedAddress,
                       dNameRVAs[i], NULL);
             slListOfDllFunctions.push_back(sName);
            }
        }
        UnMapAndLoad(&LoadedImage);
    }
}

int main(int argc, char* argv[])
{
    vector<string> names;
    ListDLLFunctions("KERNEL32.DLL", names);

    return 0;
}


text:
Q: Trying to control an application using its command line interface using python's subprocess module So I use a program DSI Studio and I am doing a lot of repetitive tasks that I would like to automate. It has a command line interface that works for me with the command
dsi_studio --action=trk -source=HarveyReg2.hdr.src.gz.odf4.f5rec.012fx.rdi.gqi.0.2.fib.gz --method=0 --
seed=leftprechiasm.nii.gz --roi=1.nii.gz --fiber_count=100 --output=track5.trk

it does exactly what I want and outputs a file.
However when I try
import subprocess

subprocess.call("dsi_studio --action=trk --source=HarveyReg2.hdr.src.gz.odf4.f5rec.012fx.rdi.gqi.0.2.fib.gz --method=0 --fa_threshold=0.00000 --turning_angle=70 --step_size=0.01 --smoothing=0 --min_length=0.0 --max_length=300.0 --initial_dir=0 --seed_plan=0 --interpolation=0 --thread_count=12 --seed=leftprechiasm.nii.gz --roi=1.nii.gz --fiber_count=100 --output=track4.trk", shell=True)

I get back return code 1. The same thing happens if I use subprocess.run. I have dinked around with different permutations to no avail. the only thing I have managed to get a 0 return code from is
subprocess.call('cd /d G:\Programs\dsi_studio_64', shell=True)

which I attempted because that is the directory I need to be in for the command to work in cmd. but even after doing that it still doesn't work. I'm pretty novice at python and I have spent a few days reading questions like mine but when I try to implement their solutions by template matching I have had no luck.

A: Each subprocess call makes its own shell, so your cd isn't actually affecting your later call, which is then breaking because you're in the wrong directory. Try
os.chdir("G:\Programs\dsi_studio_64")
subprocess.call("dsi_studio --action=trk --source=HarveyReg2.hdr.src.gz.odf4.f5rec.012fx.rdi.gqi.0.2.fib.gz --method=0 --fa_threshold=0.00000 --turning_angle=70 --step_size=0.01 --smoothing=0 --min_length=0.0 --max_length=300.0 --initial_dir=0 --seed_plan=0 --interpolation=0 --thread_count=12 --seed=leftprechiasm.nii.gz --roi=1.nii.gz --fiber_count=100 --output=track4.trk", shell=True)

you can also do it with the cwd argument to call(), like
subprocess.call("your long command", cwd="directory")

A: You can use subprocess.Popen.
#!/usr/bin/env python
#  -*- coding: utf-8 -*-

import subprocess

def run_process(exe):
    'Define a function for running commands and capturing stdout line by line'
    p = subprocess.Popen(exe.split(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    return iter(p.stdout.readline, b'')

if __name__ == '__main__':
    for line in run_process("G:\Programs\dsi_studio_64\dsi_studio --action=trk --source=HarveyReg2.hdr.src.gz.odf4.f5rec.012fx.rdi.gqi.0.2.fib.gz --method=0 --fa_threshold=0.00000 --turning_angle=70 --step_size=0.01 --smoothing=0 --min_length=0.0 --max_length=300.0 --initial_dir=0 --seed_plan=0 --interpolation=0 --thread_count=12 --seed=leftprechiasm.nii.gz --roi=1.nii.gz --fiber_count=100 --output=track4.trk"):
        print(line)


text:
Q: Azure + Terraform and Multiple Bastion Instances Wondering, if it is possible to setup mulitple Bastion servers  + availability set on Azure using Terraform. I want to enumerate bastion nodes within given availability set, but do not want to use load balancer. Any examples, one could share?
Thanks!!

A: Answering my question:
Yes it is possible to have multiple bastion nodes with Public IP addresses.
Sample configuration:
File: nic.tf
resource "azurerm_network_interface" "bastion_nic" {   name
= "bastionnic${count.index + 1}"   location                  = "${azurerm_resource_group.rg.location}"   resource_group_name       = "${azurerm_resource_group.rg.name}"   network_security_group_id = "${azurerm_network_security_group.broker_nsg.id}"   count
= "${var.bastion_instance_count}"

  ip_configuration {
    name                          = "bastionip${count.index + 1}"
    subnet_id                     = "${azurerm_subnet.broker_subnet.id}"
    private_ip_address_allocation = "Dynamic"
    public_ip_address_id          = "${element(azurerm_public_ip.bastion_pip.*.id, count.index + 1)}"    } }

File: ip.tf
resource "azurerm_public_ip" "bastion_pip" {
  name                         = "bastionpip${ count.index + 1}"
  resource_group_name          = "${azurerm_resource_group.rg.name}"
  location                     = "${azurerm_resource_group.rg.location}"
  public_ip_address_allocation = "Static"
  domain_name_label            = "${var.kafka_cluster_prefix}-bastion${ count.index + 1}"
  count                          = "${var.bastion_instance_count}"
}

File: bastion.tf
resource "azurerm_virtual_machine" "bastion" {
  name                             = "bastion${count.index + 1}"
  count                            = "${var.bastion_instance_count}"
  location                         = "${azurerm_resource_group.rg.location}"
  availability_set_id              = "${azurerm_availability_set.bastion.id}"
  resource_group_name              = "${azurerm_resource_group.rg.name}"
  network_interface_ids            = ["${element(azurerm_network_interface.bastion_nic.*.id, count.index + 1)}"]
  vm_size                          = "${var.bastion_vm_size}"
  delete_os_disk_on_termination    = true
  delete_data_disks_on_termination = true
}

File: availability.tf
resource "azurerm_availability_set" "bastion" {
  name                = "bastionavailabilityset"
  managed             = "true"
  resource_group_name = "${azurerm_resource_group.rg.name}"
  location            = "${azurerm_resource_group.rg.location}"
}

If you follow the example, you will able to deploy multiple bastion nodes with public IP address in availability set. You need to define the following:
variable "bastion_instance_count" in your variables.tf
Cheers. Ping me if you need help.


text:
Q: Alternative to multidex-android for compiling POI libraries in build.gradle I've compiled the POI library like this:
compile group: 'org.apache.poi', name: 'poi', version: '3.17'

But i found this problem during the building:

Error:The number of method references in a .dex file cannot exceed
  64K. Learn how to resolve this issue at
  https://developer.android.com/tools/building/multidex.html

So instead of enabling the multidex that causes me many other problems, I'm searching for an alternative solution like including only a part of the POI library since I use it only for .xls (Excel file) parsing.
(I have already found the Jxl library, but I have also already written some code using POI).


text:
Q: Cant send the right key to the servlet I can`t seem to send the right entity key to servlet in my web app. I am using  javascript method to submit the form with the data via a button.
The code is divide into jstl code:
  <c:if test="${!empty MOFornecedorList}">

                              <%-- Search Box --%>

                                              <form id="formsearch" name="formsearch" method="post" action="<c:url value='FProcurar'/>">

                                                    <input  name="searchBox" class="editbox_search" id="editbox_search"  size="80" maxlength="100" value="Pesquisa" type="text" />

                                                <input name="btnsearch" class="button_search" value="Pesquisa" type="button"/>
                                              </form>

                                             <h>Criterio de Pesquisa: </h>
                                             <select name="Type">
                                                 <option value="1">ID</option>
                                                 <option value="2">Nome</option>
                                                 <option value="3">Email</option>
                                                 <option value="4">Fax</option>
                                                 <option value="5">Endereço</option>
                                             </select>

                                 <%-- END Search Box --%>

                                    Modificar Fornecedor

                                    ID
                                    Nome
                                    Endereço
                                    Nº de Celular
                                    Nº de Telefone
                                    Email
                                    Fax
                                    Descrição

                                <c:forEach var="MOForn" items="${MOFornecedorList}" varStatus="iter">

                                        ${MOForn.getFid()}
                                        ${MOForn.getFNome()}
                                        ${MOForn.getFEndereco()}
                                        ${MOForn.getFNCel()}
                                        ${MOForn.getFNTel()}
                                        ${MOForn.getFEmail()}
                                        ${MOForn.getFFax()}
                                        ${MOForn.getFDescricao()}

                                            <form action="<c:url value='FMOb'/>" method="post" name="FModifi">
                                                <input type="hidden"
                                                       name="MOForn"
                                                       value="${MOForn.fid}">
                                                <input type="button"
                                                       value="Modificar" onclick="ModF()">
                                            </form>

                                </c:forEach>

                        </c:if>

the javascript method
 function ModF() {
                    jConfirm('Modificar o Fornecedor?', 'Confirmação', function(r) {

                             if (r == true) {
                                 $("form[name='FModifi']").submit();
                                } else {
                                  return false;
                                }
                    });
                }

and the controller code:
//Check if fornecedor as been selected
            int Fid = Integer.parseInt(request.getParameter("MOForn"));

          //Get fornecedor object and set it to variable
          Forn = transManager.getEnt(Fid,"fornecedor");

          request.setAttribute("Forn",Forn);

          PagesInF="FModificar";
          request.setAttribute("PagesInF", PagesInF);
          userPath = "/Fornecedor";

Now when i test the code the jstl will read 5  records in the item MOFornecedorList in ascending order and a button will be created in the last column.
When the button is pressed for example in the third record the JavaScript method Modf() is invoked  and a confirm dialog is shown.
When the user presses the OK button the form FModifi is submitted.
Then the servlet will receive a the request to open the page FMOb where the hidden input for the button pressed will be retrieved and put in a variable type int and some other code will execute.
But the value that the form submit's is the wrong one. ex:
1 - button - MOforn = 1
2 - button - MOforn = 2
3 - button - MOforn = 3 (clicked)
4 - button - MOforn = 4
5 - button - MOforn = 5
The Form should send the value of 3 but sends the value of 5.
So please if anyone as any ideas please share.

A: You've multiple forms with the same name. Your JS function isn't submitting the form from which it was been called, but it is submitting the last occurrence of the form with that name in the HTML DOM tree.
You need to replace
<input type="button" value="Modificar" onclick="ModF()">

by
<input type="button" value="Modificar" onclick="confirmSubmit(this.form)">

and rewrite the function as follows:
function confirmSubmit(form) {
    jConfirm('Modificar o Fornecedor?', 'Confirmação', function(confirmed) {
        if (confirmed) {
            form.submit();
        }
    }
}

I'd also suggest to use more self-documenting variable and function names like presented above, so that your code is easier understandable and maintainable in long term (not only for yourself, but also for others, for example the ones on Stackoverflow.com from who you expect an answer when you post a question...)


text:
Q: How to check if two time ranges are overlapping in an efficient manner (Python) I have a list with a set of particular time ranges as such:
['ARTS  111  A', 'M', '09:00 - 12:00', 'W', '09:00 - 12:00', 'F', '02:00 - 12:00', 'COMP 111  A', 'M', '09:00 - 12:00', 'W', '09:00 - 12:00']

Now, I wish to compare these ranges with another set of day and date ranges as so:
['COMP 200 A', 'M', '09:30 - 11:30', 'W', '09:00 - 12:00']

If it helps, here's the raw version of the dictionary:
dict = {
    'ARTS  111  A': {'course_code': 'ARTS  111  A', 'course_final': 'Fundam. of Drawing I', 'course_credits': '3 ',
                      'course_type': 'SBLOCK', 'course_room': 'S008', 'start_date': 'start:03/07/2022', 'days': 'M W',
                      'time': '09:00 - 12:00', 'instructor': 'John', 'capacity': '20', 'enrolled': '15', 'days_2': 'F',
                      'time_2': '02:00 - 12:00'
                     },
    'COMP  111  A': {'course_code': 'COMP 111  A', 'course_final': 'Fundam. of Drawing I', 'course_credits': '3 ',
                      'course_type': 'SBLOCK', 'course_room': 'S008', 'start_date': 'start:03/07/2022', 'days': 'M W',
                      'time': '09:00 - 12:00', 'instructor': 'John', 'capacity': '20', 'enrolled': '15'}
}

clash = {

'SCI 100  A': {'course_code': 'SCI  100  A', 'course_final': 'Fundam. of Drawing I', 'course_credits': '3 ',
                      'course_type': 'SBLOCK', 'course_room': 'S008', 'start_date': 'start:03/07/2022', 'days': 'M W',
                      'time': '09:00 - 12:00', 'instructor': 'John', 'capacity': '20', 'enrolled': '15'}
}

I have constructed the following function in order to 'clean' things up leading to the output mentioned above:
def date_time(dict):
    lst = []
    for x in dict:
        lst.append(dict[x]['course_code'])
        days = dict[x]['days']
        days = days.split()
        for y in days:
            lst.append(y)
            lst.append(dict[x]['time'])
        return lst

As apparent, just equating these two would not work. I am creating a timetable that would check for clashes between pre-existing classes and would compare them with the one new class that the user wishes to select.
Would appreciate some help on what I need to do!

A: So after some working and sleep in between
I've managed to fetch you up with a solution
there's a function that breaks the given lists to comfy dictionary
and then a function that checks if they overlap
exisitng_classes=['ARTS  111  A', 'M', '09:00 - 12:00', 'W', '09:00 - 12:00', 'F',
                  '02:00 - 12:00', 'COMP 111  A', 'M', '09:00 - 12:00', 'W', '09:00 - 12:00']

proposed_class=['COMP 200 A', 'M', '09:30 - 11:30', 'W', '09:00 - 12:00']

def check_time_overlap(time1,time2):
    """
    returns boolean whether these times overlap or not, True if overlap
    """
    split=time1.split("-")
    min1=int(split[0].replace(":",""))
    max1=int(split[-1].replace(":",""))
    split=time2.split("-")
    min2=int(split[0].replace(":",""))
    max2=int(split[-1].replace(":",""))

    return not ((max2 - min1) * (min2 - max1) >= 0)

def where_overlapping(existing,proposed):
    """
    This function checks whether or not
    and where the classes are overlapping

    gets 1 list of all lessons and their hours
    and 1 list of new single proposed lesson and its hours

    returns a list of all overlaps, if empty = no overlaps
    """
    name_of_class=""
    sliced=existing[0].split(" ")[1:]
    for item in sliced[:-1]:
        name_of_class+=item+" "
    name_of_class+=sliced[-1]

    indexes=[]
    counter=0
    for each in existing:

        if name_of_class in each:
            indexes.append((counter,each))

        counter+=1

    class_dictionary={}
    index=0
    while index<len(indexes)-1:
        class_dictionary[indexes[index][1]]=existing[indexes[index][0]+1:indexes[index+1][0]]
        index+=1

    class_dictionary[indexes[-1][1]]=existing[indexes[-1][0]+1:]

    overlaps=[]

    for classroom in class_dictionary:
        prop_counter=0
        while prop_counter<len(proposed[1:]):
            counter=0
            while counter<len(class_dictionary[classroom]):
                if class_dictionary[classroom][counter]==proposed[1:][prop_counter]:

                    if check_time_overlap(class_dictionary[classroom][counter+1],proposed[1:][prop_counter+1]):

                        overlaps.append(classroom+" of "+ class_dictionary[classroom][counter+1]
                                        +" with "+proposed[0]+" at "+proposed[1:][prop_counter+1]+" at day "
                                        +proposed[1:][prop_counter])

                counter+=2
            prop_counter+=2

    return overlaps

if __name__ == "__main__":

    for x in where_overlapping(exisitng_classes,proposed_class):
        print(x)
    print(check_time_overlap("12:00 - 14:00","13:00-17:00"))
    print(check_time_overlap("12:00 - 14:00","15:00-17:00"))
    print(check_time_overlap("12:00 - 14:00","12:00-14:00"))
    print(check_time_overlap("12:00 - 14:00","11:00-15:00"))
    print(check_time_overlap("12:00 - 14:00","10:00-16:00"))

A: import datetime
import re
from dataclasses import dataclass, field

raw_data = ['ARTS  111  A', 'M', '09:00 - 12:00', 'W', '09:00 - 12:00', 'F', '02:00 - 12:00',
            'COMP 111  A', 'M', '09:00 - 12:00', 'W', '09:00 - 12:00',
            'COMP 200 A', 'M', '09:30 - 11:30', 'W', '09:00 - 12:00']

# the data is not structured, so let's parse it !

days_letters = ('M', 'T', 'W', 'H', 'F')  # 'H' used for tHursday
timerange_pattern = re.compile(r"(\d\d):(\d\d) - (\d\d):(\d\d)")
#                        group(1) ^^^^  2^^^^    3^^^^  4^^^^
coursename_pattern = re.compile(r"(\w+\s+\d+\s+\w)")
#                         group(1) ^^^^^^^^^^^^^^

@dataclass
class Course:
    name: str
    slots: list = field(default_factory=list)

@dataclass
class CourseSlot:
    day: str
    time_start: datetime.time
    time_end: datetime.time

tokens = list(raw_data)
courses = []
while tokens:
    token = tokens.pop(0)  # get the first string

    course_name_match = coursename_pattern.fullmatch(token)
    assert course_name_match is not None
    course_name = course_name_match.group(1)

    course = Course(name=course_name)

    # then read the days and hours
    while tokens:
        if tokens[0] in days_letters:
            day = tokens.pop(0)
            timerange_match = timerange_pattern.fullmatch(tokens.pop(0))
            assert timerange_match is not None

            start_hour = int(timerange_match.group(1))
            start_minute = int(timerange_match.group(2))
            end_hour = int(timerange_match.group(3))
            end_minute = int(timerange_match.group(4))

            course.slots.append(CourseSlot(
                day=day,
                time_start=datetime.time(hour=start_hour, minute=start_minute),
                time_end=datetime.time(hour=end_hour, minute=end_minute),
            ))

        else:
            break
    courses.append(course)

print(courses)
# [Course(name='ARTS  111  A', slots=[CourseSlot(day='M', time_start=datetime.time(9, 0), time_end=datetime.time(12, 0)),
#                                     CourseSlot(day='W', time_start=datetime.time(9, 0), time_end=datetime.time(12, 0)),
#                                     CourseSlot(day='F', time_start=datetime.time(2, 0), time_end=datetime.time(12, 0))]),
#  Course(name='COMP 111  A', slots=[CourseSlot(day='M', time_start=datetime.time(9, 0), time_end=datetime.time(12, 0)),
#                                    CourseSlot(day='W', time_start=datetime.time(9, 0), time_end=datetime.time(12, 0))]),
#  Course(name='COMP 200 A', slots=[CourseSlot(day='M', time_start=datetime.time(9, 30), time_end=datetime.time(11, 30)),
#                                   CourseSlot(day='W', time_start=datetime.time(9, 0), time_end=datetime.time(12, 0))])]

@dataclass
class Clash:
    course1_name: str
    course2_name: str
    course1_slot: CourseSlot
    course2_slot: CourseSlot

# now search for overlap :
clashes = []
for i, first_course in enumerate(courses[:-1], start=1):  # from first to last-1
    for second_course in courses[i:]:  # from after the first to the last
        for first_slot in first_course.slots:
            for second_slot in second_course.slots:
                if first_slot.day == second_slot.day:
                    if first_slot.time_start <= second_slot.time_end and \
                            second_slot.time_start <= first_slot.time_end:  # see https://stackoverflow.com/a/3269471/11384184
                        # we have a match !
                        clashes.append(Clash(course1_name=first_course.name,
                                             course2_name=second_course.name,
                                             course1_slot=first_slot,
                                             course2_slot=second_slot))

print(clashes)
# [
#   Clash(course1_name='ARTS  111  A',
#         course2_name='COMP 111  A',
#         course1_slot=CourseSlot(day='M', time_start=datetime.time(9, 0), time_end=datetime.time(12, 0)),
#         course2_slot=CourseSlot(day='M', time_start=datetime.time(9, 0), time_end=datetime.time(12, 0))
#   ),
#   Clash(course1_name='ARTS  111  A',
#         course2_name='COMP 111  A',
#         course1_slot=CourseSlot(day='W', time_start=datetime.time(9, 0), time_end=datetime.time(12, 0)),
#         course2_slot=CourseSlot(day='W', time_start=datetime.time(9, 0), time_end=datetime.time(12, 0))
#   ),
#   Clash(course1_name='ARTS  111  A',
#         course2_name='COMP 200 A',
#         course1_slot=CourseSlot(day='M', time_start=datetime.time(9, 0), time_end=datetime.time(12, 0)),
#         course2_slot=CourseSlot(day='M', time_start=datetime.time(9, 30), time_end=datetime.time(11, 30))
#   ),
#   Clash(course1_name='ARTS  111  A',
#         course2_name='COMP 200 A',
#         course1_slot=CourseSlot(day='W', time_start=datetime.time(9, 0), time_end=datetime.time(12, 0)),
#         course2_slot=CourseSlot(day='W', time_start=datetime.time(9, 0), time_end=datetime.time(12, 0))
#   ),
#   Clash(course1_name='COMP 111  A',
#         course2_name='COMP 200 A',
#         course1_slot=CourseSlot(day='M', time_start=datetime.time(9, 0), time_end=datetime.time(12, 0)),
#         course2_slot=CourseSlot(day='M', time_start=datetime.time(9, 30), time_end=datetime.time(11, 30))
#   ),
#   Clash(course1_name='COMP 111  A',
#         course2_name='COMP 200 A',
#         course1_slot=CourseSlot(day='W', time_start=datetime.time(9, 0), time_end=datetime.time(12, 0)),
#         course2_slot=CourseSlot(day='W', time_start=datetime.time(9, 0), time_end=datetime.time(12, 0))
#   )
# ]


text:
Q: Unclear about releasing CFDictionaryRef I'm unclear about the memory management implications of the following:
NSDictionary* props = (__bridge NSDictionary*) CGImageSourceCopyPropertiesAtIndex(imageSource, 0, NULL);

Since the CGImageSourceCopyPropertiesAtIndex function has Copy in the name, I own the CFDictionaryRef and must release it. However, since it's cast to an NSDictionary, I can't call [props release]. What's the proper way to treat this?

A: Use CFBridgingRelease to transfer the ownership into ARC
CFDictionaryRef cfDict = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, NULL);
NSDictionary *dict = (NSDictionary *)CFBridgingRelease(cfDict);

Otherwise you would need to call CFRelease when you have finished with the dictionary.


text:
Q: Adding commas, decimal to number output javascript I'm using the following code to count up from a starting number.  What I need is to insert commas in the appropriate places (thousands) and put a decimal point in front of the last two digits.
function createCounter(elementId,start,end,totalTime,callback)
{
    var jTarget=jQuery("#"+elementId);
    var interval=totalTime/(end-start);
    var intervalId;
    var current=start;
    var f=function(){
        jTarget.text(current);
        if(current==end)
        {
            clearInterval(intervalId);
            if(callback)
            {
                callback();
            }
        }
        ++current;
    }
    intervalId=setInterval(f,interval);
    f();
}
jQuery(document).ready(function(){
    createCounter("counter",12714086+'',9999999999,10000000000000,function(){
        alert("finished")
    })
})

Executed here: http://jsfiddle.net/blackessej/TT8BH/3/

A: var s = 121221;

Use the function insertDecimalPoints(s.toFixed(2));
and you get 1,212.21
function insertDecimalPoints(s) {
    var l = s.length;
    var res = ""+s[0];
    console.log(res);
    for (var i=1;i<l-1;i++)
    {
        if ((l-i)%3==0)
            res+= ",";
        res+=s[i];
    }
    res+=s[l-1];

    res = res.replace(',.','.');

    return res;
}

A: Check out this page for explanations on slice(), split(), and substring(), as well as other String Object functions.
var num = 3874923.12 + ''; //converts to a string
numArray = num.split('.'); //numArray[0] = 3874923 | numArray[1] = 12;

commaNumber = '';
i = numArray[0].length;
do
{
    //we don't want to start slicing from a negative number. The following line sets sliceStart to 0 if i < 0. Otherwise, sliceStart = i
    sliceStart = (i-3 >= 0) ? i-3 : 0;

    //we're slicing from the right side of numArray[0] because i = the length of the numArray[0] string.
    var setOf3 = numArray[0].slice(sliceStart, i);

    commaNumber = setOf3 + ',' + commaNumber; //prepend the new setOf3 in front, along with that comma you want

    i -= 3; //decrement i by 3 so that the next iteration of the loop slices the next set of 3 numbers
}
while(i >= 0)

//result at this point: 3,874,923,

//remove the trailing comma
commaNumber = commaNumber.substring(0,commaNumber.length-1);

//add the decimal to the end
commaNumber += '.' + numArray[1];

//voila!

A: This function can be used for if not working  locale somite
       number =1000.234;
       number=insertDecimalPoints(number.toFixed(3));
   function insertDecimalPoints(s) {
   console.log(s);
    var temaparray = s.split(".");
    s = temaparray[0];
    var l = s.length;
    var res = ""//+s[0];
    console.log(res);
    for (var i=0;i<l-1;i++)
    {
        if ((l-i)%3==0 && l>3)
            res+= ",";
        res+=s[i];
    }
    res+=s[l-1];
    res =res +"."+temaparray[1];
    return res;
}

A: function convertDollar(number) {
    var num =parseFloat(number);
    var n = num.toFixed(2);
    var q =Math.floor(num);
    var z=parseFloat((num).toFixed(2)).toLocaleString();
    var p=(parseFloat(n)-parseFloat(q)).toFixed(2).toString().replace("0.", ".");
    return z+p;
}


text:
Q: How to retrieve values from multiple rows of the same column in SQL Server I need to search booked patients for the given date. I don"t know what the error in my code is. But I could retrieve only 1 row from the table. Please help
string sp = textBox1.Text;

SqlConnection con1 = new SqlConnection();
con1.ConnectionString = "Data Source=SWATHI-PC\\NM;Initial Catalog=clinic;Persist Security Info=True;User ID=sa;Password=sqlpass";
con1.Open();

string query = "select Booking_dt,Name from patients1 WHERE  Booking_dt=@dt ";

SqlCommand cmd = new SqlCommand(query, con1);
cmd.Parameters.Add(new SqlParameter("@dt", sp));

SqlDataReader dr = cmd.ExecuteReader();

if (dr.Read())
{
    listView1.Items.Add(dr[1].ToString());
}

A: I'd say that it's your
if (dr.Read()) { }

block only running once.  I don't know the specifics of whichever language you're using, but I'm guessing you need something along the lines of
while (dr.Read())
{
    listView1.Items.Add(dr[1].ToString());
}

which should iterate through dr.


text:
Q: cmake: get list of all add_executable names I have a set of tests like this :
enable_testing()

add_executable(first_test tests/first.cpp)
add_test(NAME FIRST COMMAND first_test)

add_executable(second_test tests/second.cpp)
add_test(NAME SECOND COMMAND second_test)

I want to get all of theses tests (*_test) inside a variable for other function dependencies.
For now, I have :
set(DEPENDENCIES first_test second_test)

A way to do that ?


text:
Q: Finding items with attribute value match excluding another value in Sequelize I have this code :
module.exports.MyFunction= async (req, res) => {
  let token = req.body.token;
  let decoded = jwt_decode(token);
  let email = decoded.email;
  let data = req.body;
  let searchUser = data.user;

  try {
    let user = await User.findAll({
      where: {
        [Op.or]: [
          { firstName: searchUser },
          { lastName: searchUser },
          { email: searchUser },
          { publicKey: searchUser },
        ],
      },
      attributes: ["firstName", "lastName", "email", "publicKey", "avatar"],
    }).then((response) => {
      return response;
    });

    res.json({ user });
  } catch (err) {
    res.json({ err });
  }
};

If I run that code, I get all the users that match with the value passed in searchUser.
What I want to do is to exclude the user object that have a specific email.
For instance, if have multiple users named Michel, I want to get all the users with an email address different of the email variable declared at the top of the function, even if their fisrtName matches.

A: Problem solved by doing this :
module.exports.MyFunction = async (req, res) => {
  let token = req.body.token;
  let decoded = jwt_decode(token);
  let loggedUserEmail = decoded.email;
  let data = req.body;
  let searchUser = data.user;
  console.log(searchUser);

  try {
    let user = await User.findAll({
      where: {
        [Op.or]: [
          {
            firstName: {
              [Op.startsWith]: searchUser,
            },
          },
          {
            lastName: {
              [Op.startsWith]: searchUser,
            },
          },
          {
            email: {
              [Op.startsWith]: searchUser,
            },
          },
          {
            publicKey: {
              [Op.startsWith]: searchUser,
            },
          },
        ],
        email: {
          [Op.ne]: loggedUserEmail,
        },

      },
      attributes: ["firstName", "lastName", "email", "publicKey", "avatar"],
    }).then((response) => {
      return response;
    });

    res.json({ user });
  } catch (err) {
    res.json({ err });
  }
};


text:
Q: How to emulate file directory of a URL using Php -S? My task is like:
Kannel exposes a status xml.
Services before interacting the kannel usually query its status before engaging with it.
The library should query the xml, parse it's content and create a structure to access it's values by name.
The library construction options should include kannel host, port and password.

The query uri is as : http://{host}:{port}/status.xml?password={password}

What can I do to emulate the file directory(status.xml) of a URL as shown above? (my manager told me to use php -s)
public function __construct($host, $port, $password=""){
$this->$host= $host;
$this->$port= $port;
$this->$password= $password;
$this->$url =  $host . $port . $password ;

$this->$response_xml_data = file_get_contents($url);
$this->$data = simplexml_load_string($response_xml_data);

}
My constructur parameters like :
$XmlClass = new XmlReaderClass('localhost', '8000');

But I take the warning :

Warning: file_get_contents(): Filename cannot be empty

A: "-s" flag in the PHP terminal helps to run a built-in webserver.(PHP Built-in web server)
Think like you have a status.xml in your public_html folder. You can run it in a directory like the following code through terminal:
cd ~/public_html
php -S localhost:8000

When you request for localhost:8000/status.xml, you get status.xml content through to your client.
Also, you can use a specified file as a default page through the built-in webserver.
cd ~/public_html
php -S localhost:8000 status.xml

When you request for localhost:8000, you get status.xml content through to your client.


text:
Q: Listing Parameters of an Object in an ArrayList I am trying to create a method to list the elements in an ArrayList, but the method only returns the values of the most recent object:
The object:
//Constructor for guests at the hotel
public Guest (String name, String checkinDate, String checkoutDate, double depAmt)
{
    gstName = name;
    checkIn = checkinDate;
    checkOut = checkoutDate;
    deposit = depAmt;
}

Current objects in the ArrayList:
//Fills the roster with three guests to start the program
public static void fillGuest()
{
    Guest guest1 = new Guest("Mike P.", "2/13/16", "2/23/16", 360.00);
    guestList.add(guest1);
    Guest guest2 = new Guest("Randall M.", "4/10/16", "4/17/16", 120.00);
    guestList.add(guest2);
    Guest guest3 = new Guest("Bo-Diddly.", "4/20/16", "4/23/16", 600.00);
    guestList.add(guest3);
}

Method to list the objects in the ArrayList:
public static void returnGuests()
{
    System.out.println("Currently checked in "  + guestList.size() + " guests:");
    for (int i = 0; i <= guestList.size() - 1; i++)
    {
        System.out.println(guestList.get(i));
    }
}

The output:
Currently checked in 3 guests:
Bo-Diddly. 4/20/16 4/23/16 600.0
Bo-Diddly. 4/20/16 4/23/16 600.0
Bo-Diddly. 4/20/16 4/23/16 600.0

Enter command:

How do I display the individual object parameters of each Guest object?

A: Your Guest object should look like below. Note the lack of the static modifier on the fields. Also, note the use of the this keyword. If you use that with a static variable, then your IDE should give you a warning that it will be interpreted as a MyClass.var instead of this.var.
Your problem is that all Guest objects will have the last set of variables as you create new Guest objects. You need to use "instance" variables instead of "class" variables.
If you would like to read more on the topic of static "class" variables, please see Understanding Class Members.
public class Guest {

    String gstName, checkIn, checkOut;
    double deposit;

    public Guest (String name, String checkinDate, String checkoutDate, double depAmt)
    {
        this.gstName = name;
        this.checkIn = checkinDate;
        this.checkOut = checkoutDate;
        this.deposit = depAmt;
    }
}


text:
Q: mysql query - to echo groups of products with foreach in stylable divs hope somone can help me - I have this code:
$query = "SELECT * FROM `products` WHERE `category` = 100 AND `showme` = 1 `ORDER BY `nr` ASC";`
$result = mysql_query($query);
while($row = mysql_fetch_object($result)){
echo '
design.'">
  img.'" width="100%">

  '.$row->name.'
'.$row->descr.'

    '.$row->preprice.' '.$row->price.' '.$row->unit.'

';
}

It displays like this: http://gartenundhof.de/gartenundhof-produkte5.php
It should look about like:http://gartenundhof.de/gartenundhof-produkte.php (which has 3 separate queries)

A: "SELECT * FROM 'products' ORDER BY 'category' ASC";

Try this

A: You can try it:
$query = "SELECT * FROM `products` WHERE `showme` = 1 `ORDER BY category,`nr` ASC";
$result = mysql_query($query);
$category = -1;
while($row = mysql_fetch_object($result)){
    if($category != $row->category) {
        $category = $row->category;
        eho "
$category
";
    }
    echo '
design.'">
    img.'" width="100%">

    '.$row->name.'
'.$row->descr.'

    '.$row->preprice.' '.$row->price.' '.$row->unit.'
';
}

A: Assuming you have 2 tables Products and Categories:
$categories_query = "SELECT * FROM categories ORDER BY id ASC";
$categories = mysql_query($categories_query);

while($category = mysql_fetch_object($categories)) {

  echo "Category: " . $category->name . "
";

  $products_query = "SELECT * FROM products WHERE category_id = " . $category->id . " AND showme = 1 ORDER BY nr ASC";

  while($product = mysql_fetch_object($products_query)) {
    echo "Product: " . $product->name . "
";
  }
}


text:
Q: Applying XML schema on XML document If you have two tags with the same name in an XML document, do you have to use two different schema's for each tag or can you use 1 schema, would it validate? below is an example where it is using 2 schema's, but I am using only 1 schema, which one is correct?
XML Document Using 2 Schema's
    <?xml version="1.0" encoding="ISO-8859-1"?>
<receipt xmlns: cu="http://www.mydomain.com/customer"
 xmlns: pr="http://www.mydomain.com/product">  <!--two schema's being referenced-->

<cu:customer> <!--Using Schema 1-->
<cu:name> Michael Johnson </cu:name>
<cu:areaCode> BH2 3XY </cu:areaCode>
</cu:customer>

<products>
<pr:product>  <!--Using Schema 2-->
<pr:name>RAM</pr:name>
<pr:quantity>100</pr:quantity>
</pr:product>
</products>
</receipt>

My XML Document Using 1 Schema (has 2 tags with the same name, called item)
    <?xml version=" 1.0" encoding="UTF-8"?>

<shiporder orderid="889923" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="shiporder.xsd">
    <orderperson>John Smith</orderperson>
        <shipto>
            <name>Ola Nordmann</name>
            <address>Langgt 23</address>
            <city>4000 Stavanger</city>
            <country>Norway</country>
        </shipto>
        <item>
            <title>Empire Burlesque</title>
            <note>Special Edition</note>
            <quantity>1</quantity>
            <price>10.90</price>
        </item>
        <item>
            <title>Hide your heart</title>
            <quantity>1</quantity>
            <price>9.90</price>
        </item>
</shiporder>

XML Schema:
    <xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="shiporder">
    <xs:complexType >
        <xs:sequence>
            <xs:element type="xs:string" name="orderperson"/>
            <xs:element name="shipto">
                <xs:complexType>
                  <xs:sequence>
              <xs:element type="xs:string" name="name"/>
              <xs:element type="xs:string" name="address"/>
              <xs:element type="xs:string" name="city"/>
              <xs:element type="xs:string" name="country"/>
                    </xs:sequence>
                </xs:complexType>
            </xs:element>
            <xs:element name="item"  maxOccurs="unbounded" minOccurs="0">
                <xs:complexType>
                    <xs:sequence>
                        <xs:element name="title" type="xs:string"/>
                        <xs:element name="note" type="xs:string" minOccurs="0"/> <!--optional-->
                        <xs:element name="quantity" type="xs:integer"/>
                        <xs:element name="price" type="xs:decimal"/>
                    </xs:sequence>
                </xs:complexType>
            </xs:element>
        </xs:sequence>
    <xs:attribute name="orderid" type="xs:int" /> <!--must be required-->
    </xs:complexType>
</xs:element>

A: You can define item in a third schema, then include it in the other schemas.
See Can I have one XML Schema (XSD) include another XML-Schema?.  And http://www.w3schools.com/schema/el_include.asp

A: the first xml uses two different schemas hence uses two different name spaces.
yes you can have xml derive from different schemas
the second xml has two elements and is nothing wrong. repeatable elements is how you represent a list of objects or something similar in this case a list of items.
<item> is defined to be occurring more than once as per the schema.
maxOccurs="unbounded" so it is valid xml as per the schema.

Is that not true?

<xs:element name="item"  maxOccurs="unbounded" minOccurs="0">
                <xs:complexType>
                    <xs:sequence>
                        <xs:element name="title" type="xs:string"/>
                        <xs:element name="note" type="xs:string" minOccurs="0"/> <!--optional-->
                        <xs:element name="quantity" type="xs:integer"/>
                        <xs:element name="price" type="xs:decimal"/>
                    </xs:sequence>
                </xs:complexType>
            </xs:element>


text:
Q: TCPDF + pure HTML ... Create table of contents I want to print HTML to PDF using TCPDF so I do this:
$html = '
Hello

How are you?

Answer

I am well, thanks';
// ... etc. Long HTML document.
$pdf->writeHTML($html);

The question is if there is a way how to add a table of contents. If TCPDF can recognize page numbers of headings.
I also sometimes use HTML page breaks:

I understand that I need bookmarks. But in this case TCPDF would have to create them automatically. If I add an ID to html-heading-tag, TCPDF probably does not find it and cannot use it.

header1

// but following does not do anything:
$pdf->addTOC()

A: Since the ToC page is created as the very last it will show that as the last page.
So instead use
$this->Cell(0, 12, ' '.$this->getAliasNumPage().' of '.$this->getAliasNbPages(), 0, false, 'C', 0, '', 0, false, 'T', 'M');
//It will show page numbers


text:
Q: Get Facebook ad videos under a specific campaign My requirement is to get total_video_views_unique, total_video_complete_views_paid_unique, total_video_10s_views_unique of ad videos under a specific campaign.
Is there a way to get all the ad videos under a campaign? There is a service that returns all the ad videos under the ad account.


text:
Q: Use derived class to add properties and maintain compatibility with existing classes I'm writing a Qt 6.2.0 application running in Ubuntu 20.04.
My goal is to add a property to the existing class QtOpcUaNode.
So I wrote:
class MyOpcUaNode : public QOpcUaNode
{
    Q_OBJECT

public:
    explicit MyOpcUaNode(QOpcUaNode *parent = nullptr) : QOpcUaNode(parent) { }
    bool updated;
};

But here the first error:
error: no matching function for call to 'QOpcUaNode::QOpcUaNode(QOpcUaNode*&)'
In file included from ../MyProject/myproject.cpp:1:
../MyProject/myproject.h: In constructor 'MyOpcUaNode::MyOpcUaNode(QOpcUaNode*)':
../MyProject/myproject.h:16:73: error: no matching function for call to 'QOpcUaNode::QOpcUaNode(QOpcUaNode*&)'
   16 |     explicit MyOpcUaNode(QOpcUaNode *parent = nullptr) : QOpcUaNode(parent) { }
      |                                                                         ^

I want to use my class in this way:
QList<MyOpcUaNode *> _listOpcNodes;

_listOpcNodes.append(MyOpcUaNode(_opcUaClient->node("ns=4;s=MEM_RUN_LINE")));
...
_listOpcNodes[x]->updated = true;

Is it correct my approach?
I tried without the copy-constructor but I was not sure how to convert a QOpcUaNode * to MyOpcUaNode *. Trying with:
MyOpcUaNode *node = qobject_cast<MyOpcUaNode *>(_opcUaClient->node("ns=4;s=MEM_RUN_LINE"));

lead node to be a null pointer (even if the _opcUaClient->node was correct).

A: If you want to add property to class which inherits from QObject, you can do it with setProperty() https://doc.qt.io/qt-5/qobject.html#setProperty. Well, it is not type-safe but it is very simple. Sometimes pragmatism beats purism.


text:
Q: How do I get the response from a URLSession before the rest of my code executes? I have a problem with my URLSession in Swift. No matter what I try (or how many tutorials I read through), I cannot find a way to get the network request to finish before executing the rest of my code. I was under the impression that a completion handler would do the trick, but this has not proven to be the case. What am I doing wrong here?
struct DataManager {

    let eventsURL = URL(string: "https://spreadsheets.google.com/feeds/list/blablabla/1/public/full?alt=json")!
    let decoder = JSONDecoder()
    var data = Data()

    func downloadEvents() -> [Event] {
        var events: [Event] = []
        var downloadedEvents: [[String: Any]] = []

        getDataFromServer(forURL: eventsURL) { result in
            downloadedEvents = result
        }

        // This next part always executes before the response is receive, which means the downloadedEvents variable is always empty.

        for downloadedEvent in downloadedEvents {
            if let event = Event(fromJSON: downloadedEvent) {
                events.append(event)
            }
        }

        return events
    }

    func getDataFromServer(forURL url: URL, completion: @escaping (_ result: [[String: Any]]) -> Void) {
        URLSession.shared.dataTask(with: url) { data, response, error in
            if let jsonData = data {
                let jsonObject = try? JSONSerialization.jsonObject(with: jsonData, options: [])
                if let dictionary = jsonObject as? [String: Any] {
                    if let feed = dictionary["feed"] as? [String: Any] {
                        if let entry = feed["entry"] as? [[String: Any]] {
                            DispatchQueue.main.async {
                                completion(entry)
                            }
                        }
                    }
                }
            }
        }.resume()
    }
}

A: Your downloadEvents function need to be asynchronous because its calls another asynchronous function getDataFromServer.
The solution may be to move the part for calculating Events to the asynchronous block and provide a completion parameter:
func downloadEvents(completion: @escaping ([Event]) -> ()) {
    var events: [Event] = []
    var downloadedEvents: [[String: Any]] = []

    getDataFromServer(forURL: eventsURL) { result in
        downloadedEvents = result
        for downloadedEvent in downloadedEvents {
            if let event = Event(fromJSON: downloadedEvent) {
                events.append(event)
            }
        }
        completion(events)
    }
}

Note
Your code may actually be simplified to:
func downloadEvents(completion: @escaping ([Event]) -> ()) {
    getDataFromServer(forURL: eventsURL) { completion($0.compactMap(Event.init(fromJSON:))) }
}


text:
Q: bootstrap rows not folding properly on mobile I am using bootstrap to make rows of images. On phone screens, there should be 2 images per row. On every screen size larger than phones, there should be 3 images per row.  The code below works for screens larger than a phone, but on a phone it leaves a blank space after the 3rd image.  How do I make it so on mobile there are no missing spaces?

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">

A: Is there any reason to have two rows? If not, this is the solution.
See the snippet below.

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">

A: You probably want raw flexbox rather than rows and columns. Use flex-basis on a custom class to handle wrapping.
Since "larger than phones" isn't particularly specific I went with the medium breakpoint (768px) to correspond with Bootstrap's native breakpoints. You may prefer 992px or even 1200px.
Protip: Bootstrap already has a class for image max-width (and you shouldn't use inline styles anyway--create custom classes where needed).

.img-box {
  flex-basis: calc(100%/2);
}

@media (min-width: 768px) {
  .img-box {
    flex-basis: calc(100%/3);
  }
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">


text:
Q: Processing: Performance issues with background() I'm creating a stereoscopic test application where the scene is rendered into a PGraphics left and a PGraphics right with different camera angles for the two eye points. The two images is then combined into a side-by-side output in the draw() function.
The scene consists of a pre-rendered background, stored in a separate PGraphics, rendered once, and a rotating box() rendered for each frame.
The problem is that the call to gfx.background(gfxBackground); in render() is very CPU intensive. If I replace it with a gfx.background(0); call, the sketch runs smoothly.
My assumption was that blit'ing data from one PGraphics to another would be done with hardware acceleration, but it seems it isn't. Am I doing something wrong?
My sketch:
PGraphics leftBackground;
PGraphics rightBackground;
PGraphics left;
PGraphics right;

int sketchWidth()       { return 1920; }
int sketchHeight()      { return 1200; }
int sketchQuality()     { return 8;    }
String sketchRenderer() { return P3D;  }

void setup()
{
  noCursor();

  leftBackground = createGraphics(width / 2, height, P3D);
  renderBackground(leftBackground, "L");

  rightBackground = createGraphics(width / 2, height, P3D);
  renderBackground(rightBackground, "R");

  left  = createGraphics(width / 2, height, P3D);
  left.beginDraw();
  left.endDraw();
  left.camera(-10, 0, 220,
                0, 0,   0,
                0, 1,   0);

  right = createGraphics(width / 2, height, P3D);
  right.beginDraw();
  right.endDraw();
  right.camera( 10, 0, 220,
                 0, 0,   0,
                 0, 1,   0);

}

void draw()
{
  render(left, leftBackground);
  render(right, rightBackground);
  image(left, 0, 0);
  image(right, left.width, 0);
}

void renderBackground(PGraphics gfx, String str)
{
  gfx.beginDraw();
  gfx.background(0);

  gfx.stroke(255);
  gfx.noFill();
  gfx.rect(0, 0, gfx.width, gfx.height);

  gfx.scale(0.5, 1.0, 1.0);
  gfx.textSize(40);
  gfx.fill(255);
  gfx.text(str, 30, 40);
  gfx.endDraw();
}

void render(PGraphics gfx, PGraphics gfxBackground)
{
  gfx.beginDraw();
  gfx.background(gfxBackground);
  gfx.scale(0.5, 1, 1);
  gfx.rotateY((float)frameCount / 100);
  gfx.rotateX((float)frameCount / 90);
  gfx.stroke(255);
  gfx.fill(0);
  gfx.box(30);
  gfx.endDraw();
}

A: You've got multiple options to achieve the same visual output.
Here are a few options:
Simply overlay the "L"/"R" text:
in draw():
  render(left, bgl);
  render(right, bgr);
  image(right, 0, 0);
  image(right, left.width, 0);
  text("L",100,100);
  text("R",width/2+100,100);

using gfx.background(0) in render().
PGraphics extends PImage so instead of
gfx.background(gfxBackground);
you can use
gfx.image(gfxBackground,xoffset,yoffset);

You will need to offset because of the camera call, also, you will need to translate the box in Z direction since by default it will be at (0,0,0) and will intersect with the quad rendering the background image.
If you want to go deeper and find other bottlenecks sample the CPU using jvisualvm (if you have the JDK installed and PATH set to it you should be able to run this from terminal/commandline, otherwise there's an application in YOUR_JDK_INSTALL_PATH\bin).
Take a couple snapshots at different intervals and compare performance. You might find some other draw commands that could be changed to gain a few ms per frame.


text:
Q: AWS Amazon Athena impossible to partitioning data with a BOOLEAN field I'm trying to partition my data on Amazon Athena with a boolean field but it doesn't seem to be working.
My data (in JSON) looks like this schema :
{
    "name": "apple",
    "size": "L",
    "color": "red",
    "fruit": true
}

or

{
    "name": "brocolis",
    "size": "L",
    "color": "green",
    "fruit": false
}

I created the table on Amazon athena as follows:
CREATE EXTERNAL TABLE fruits (
  name string,
  color string,
  size string
)
PARTITIONED BY (fruit boolean)
ROW FORMAT SERDE
  'org.openx.data.jsonserde.JsonSerDe'
LOCATION
  's3://bucket-for-athena-test/'

Then I try to create a first partition like this:
ALTER TABLE fruits ADD PARTITION (fruit = true) LOCATION 's3://bucket-for-athena-test/fruits/'

And I get an error message:
Your query has the following error(s):

FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.DDLTask. MetaException(message:One or more parameter values were invalid: An AttributeValue may not contain an empty string (Service: AmazonDynamoDBv2; Status Code: 400; Error Code: ValidationException; Request ID: FI07HJFNAKH3HLUU5DATP2G4LJVV4KQNSO5AEMVJF66Q9ASUAAJG))

This query ran against the "fruits_database" database, unless qualified by the query. Please post the error message on our forum or contact customer support with Query Id: 3aa0434e-b492-4090-8dd6-24e498a0e1fa.

Could somebody please help me?
Thank you in advance.

A: The partition style used by Athena is derived from Hive style. You cannot create a table with partition column as column from actual data. Rather this partition should be a part of your location for example in your case the s3 path should be some thing like 's3://bucket-for-athena-test/fruit=mango' or 's3://bucket-for-athena-test/fruit=apple' .
So this path 's3://bucket-for-athena-test/fruit=mango' will have the data with all mangoes and 's3://bucket-for-athena-test/fruit=apple' will have apples.
When you run a query on top this table applying a filter like select * from table where fruit = 'mango' this will only scan mango data and leave other folders untouched.This is the actual benefit of partitioning where it skip scanning unnecessary data.
To read more about partitioning refer to this.
So if you want to create partitioned table from normal table then you can use CTAS example as shown here
CREATE TABLE fruits_partitioned
WITH (
     format = 'TEXTFILE',
     external_location = 's3://bucket-for-athena-test/',
     partitioned_by = ARRAY['fruit'])
AS SELECT column1, column2, column3, fruit
FROM fruit_unpartitioned;

A: The source error is:
One or more parameter values were invalid: An AttributeValue may not contain an empty string
This means that the partition query was attempted on a column (attribute value) that does not exist.
The column name specified in the partition query is 'fruit'.
However, the column named 'fruit' is not defined in the table structure. This is the root cause of the error.
How to fix the problem?
The fix can be done in 2 ways -

*

*Run the partition query on one of the column names that exists in table structure (Example: color)

*Alter the table structure to include 'fruit' as a column.


text:
Q: How can you repair damaged sound file? I have a problem with my wav file. We played with our band (@bataty on instagram)in a club and we asked soundman to record the audio of our show. He gave us a record in wav but we cant play it anywhere.
Is the file damaged? Can somebody help me please?
https://drive.google.com/open?id=11ODe-3MUOIkbDomzNBnzt3DnSTr9j8qx

A: Your audio file isn't broken.  It plays fine.  It's just silent.
Your sound tech made a mistake and didn't record anything but silence.


text:
Q: Scheduled Newsletters with Products.EasyNewsletter in Plone How do I set up automated newsletters with EasyNewsletter in Plone?
I know Singing & Dancing has this function however EasyNewsletter has the following features which Singing & Dancing doesn't

*

*Better breadcrumbs/urls for subscribe links

*More admin control over templates/subscribe/thank you pages etc.

*Doesn't require admin permission

A: As long as EasyNewsletter doesn't provide a mail queue you will have to cheat: I would implement a browser view that checks for "issues" in state draft (maybe using a topic to help the search) and simply trigger the "send" transition. Then, using Products.cron4plone, you add a cron job that calls that page anytime you prefer.


text:
Q: Ballistic Electrons in Ballistic Electron Emission Microscopy (BEEM) This is for an exam that i have in the near future.
Would someone be able to explain what a Ballistic electron is in terms of BEEM. From my understanding ballistic would mean only acted upon by gravity.Can someone either correct me or expand on what i said if its right.
Thank you

A: I use BEEM everyday. "Ballistic Electron" in this sense means that the electron is able to go travel between two scattering events and remain unscattered in a metal. There is a lot of high level theory that can go into describing the motion of these electrons in a BEEM measurement, but generally you should think of it as an electron that is not scattered in a metal as it conducts through the metal to the semiconductor interface.
What you describe as "Ballistic" motion is really just projectile motion of an object and that its an object that is given some energy and it falls in a parabolic arc.
In depth answer: In a metal electronic states are occupied up to and at the fermi level of the metal. This means that electrons as they conduct through a metal must scatter into unoccupied states with energies of a few $k_bT$ (25meV) above or below the fermi level. So electrons as they conduct through the metal must have sufficient energy to scatter into these unoccupied states and generally have the same amount of energy. When you perform BEEM measurements though you are giving the electrons a boost to their kinetic energy by applying a bias between the STM tip and the metal, these electrons are now around a $1~eV$ higher than the fermi level of the metal and are considered "hot" electrons. "hot" electrons refer to the fact that when measuring energies in relation to $$E = k_bT$$ which at room temperature (300K) have an energy of 25meV, you have an energy of $1eV = k_b T$, $k_b$ is the boltzmann constant in eV, so your temperature of the electron is considered "hot" or 12000K. This is not a real temperature of the electron or of the material, but a guideline of the kinetic energy in relation to electrons conducting within a few k_b*T of the fermi level.
So these "hot" electrons have a lot of energy and because of this their scattering interactions are different. An electron with energy much greater than that of the fermi level is going to have more inelastic scattering events such as electron electron scattering and less energy loss from phonon interactions since electron-phonon energy loss is on the order of $k_bT$. If these electrons travel through the metal without very few scattering events they are considered "ballistic" electrons.
de Andres, P. L., F. J. Garcia-Vidal, K. Reuter, and F. Flores, 2001, Prog. Surf. Sci. 66, 3.
D. A. Pearson and L. J. Sham, Theory of ballistic electron emission microscopy. Phys. Rev. B 2001, 64, 125408. http://dx.doi.org/10.1103/PhysRevB.64.125408
http://www.rug.nl/research/portal/files/2372254/Chapter_2.pdf


text:
Q: Subtract two dataframes to get the value difference I have a dataframe on which I get a daily aggregate for particular dates.Below is the dataframe for the date 2018-02-11 where I have found out the mean, min, max, std
    cpu cpu cpu cpu mem mem mem mem load    load    load    load    drops   drops   drops   drops   latency latency latency latency gw_latency  gw_latency  gw_latency  gw_latency  upload  upload  upload  upload  download    download    download    download    sap_drops   sap_drops   sap_drops   sap_drops   sap_latency sap_latency sap_latency sap_latency
    mean    min max std mean    min max std mean    min max std mean    min max std mean    min max std mean    min max std mean    min max std mean    min max std mean    min max std mean    min max std
date
2018-02-11  4.282442748 0   17  4.361148065 13.61068702 0   27  6.123815451 3.891450382 0   47.62   6.426298507 1.526717557 0   100 12.30842628 0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0

Similarly I have another dataframe for the date 2018-02-12 for which I found the mean, min, max, std
    cpu cpu cpu cpu mem mem mem mem load    load    load    load    drops   drops   drops   drops   latency latency latency latency gw_latency  gw_latency  gw_latency  gw_latency  upload  upload  upload  upload  download    download    download    download    sap_drops   sap_drops   sap_drops   sap_drops   sap_latency sap_latency sap_latency sap_latency
    mean    min max std mean    min max std mean    min max std mean    min max std mean    min max std mean    min max std mean    min max std mean    min max std mean    min max std mean    min max std
date
2018-02-12  5.726315789 0   21  2.938315053 22.30526316 0   23  3.581474037 6.06    0   44.75   6.798944285 0.5263157895    0   100 7.254762501 0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0

Here is code below
import pandas as pd
df = pd.read_csv("metrics.csv", parse_dates=["date"])
df.set_index("date", inplace=True)
df_prev = df.loc['2018-02-11'].resample('D')['cpu', 'mem', 'load', 'drops', 'latency',
                                             'gw_latency', 'upload', 'download', 'sap_drops',
                                             'sap_latency'].agg(['mean', 'min', 'max', 'std']).fillna(0)

df_next = df.loc['2018-02-12'].resample('D')['cpu', 'mem', 'load', 'drops', 'latency',
                                             'gw_latency', 'upload', 'download', 'sap_drops',
                                             'sap_latency'].agg(['mean', 'min', 'max', 'std']).fillna(0)

Now I want to subtract the two dataframes to get the value difference for each of the column.This is what I do
df_diff = df_next.sub(df_prev, fill_value=0)
print(df_diff)

But it doesn't subtract anything and I also get the dates which doesn't make any sense since I only want the stats difference.
    cpu cpu cpu cpu mem mem mem mem load    load    load    load    drops   drops   drops   drops   latency latency latency latency gw_latency  gw_latency  gw_latency  gw_latency  upload  upload  upload  upload  download    download    download    download    sap_drops   sap_drops   sap_drops   sap_drops   sap_latency sap_latency sap_latency sap_latency
    mean    min max std mean    min max std mean    min max std mean    min max std mean    min max std mean    min max std mean    min max std mean    min max std mean    min max std mean    min max std
date
2018-02-11  -4.282442748    0   -17 -4.361148065    -13.61068702    0   -27 -6.123815451    -3.891450382    0   -47.62  -6.426298507    -1.526717557    0   -100    -12.30842628    0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
2018-02-12  5.726315789 0   21  2.938315053 22.30526316 0   23  3.581474037 6.06    0   44.75   6.798944285 0.5263157895    0   100 7.254762501 0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0

As you can see it doesn't do any subtraction at all.Why is that happening?
PS I ultimately want to find out the percentage difference between the stats of the two dates.Is there any direct way to do that?

A: To get the difference
df_next - df_prev.values

To get the % change,
(df_next - df_prev.values)/(df_prev.values) * 100


text:
Q: How to group rows by either permutation of a two column composite key Not sure the wording for the question is as clear as it should be (it's the best I could come up with) but here's an example to clear things up. I have a view, Chats, which is supposed to summarize the conversation history between two people. The view comprises of the following columns: Sender, Recipient, Timestamp, LatestMessage and UnreadMessageCount.
The Chats view's columns are all derived from a table, Direct_Messages which stores details about individual chat messages exchanged between users of the system. Here are its columns:
ID, Sender, Recipient, Body, Timestamp, TimeRead (is null if message hasn't been read by recipient). The view's Timestamp and LatestMessage columns have the values of the latest direct message between the two participants (latest by Timestamp FWIW).
The problem is really stemming from the fact that only one permutation of the Sender, Recipient composite columns should exist in the Chats view i.e. that of the latest exchange between the two participants. For example, if Gary sent a 'Hi' message to Barry, then Barry replied with 'Hello'--the only entry in Chats between these two guys should have the Sender as 'Barry', the Recipient as 'Gary', the Timestamp as the timestamp of Barry's reply, the LatestMessage as 'Hello' and the UnreadMessageCount as the number of messages the Recipient hasn't read.
I have tried to use GROUP BY "Sender", "Recipient" OR "Recipient", "Sender" but it just returns two columns: one grouped by Barry, Gary; and the other grouped by Gary, Barry
Here's my code:
SELECT Sender AS Sender,
       Recipient AS Recipient,
       Timestamp AS Timestamp,
       Body AS LatestMessage,
       (SUM(CASE WHEN TimeRead IS NULL THEN 1 ELSE 0 END) ) AS UnreadMessageCount
FROM Direct_Messages
GROUP BY Sender, Recipient OR Recipient, Sender
ORDER BY Timestamp DESC

EDIT: Here's the sample data in the Direct_Messages table and the corresponding output in the Chats view
From Direct_Messages
ID          Sender  Recipient   Body    Timestamp                   TimeRead
148567984   Gary    Barry       Hi      2018-12-12 23:53:39.487     2018-12-12 23:55:45
1668701120  Barry   Gary        Hello   2018-12-12 23:54:49.326     NULL

Result in Chats:
Sender  Recipient   Timestamp                 LatestMessage UnreadMessageCount
Gary    Barry       2018-12-12 23:53:39.487   Hi            0
Barry   Gary        2018-12-12 23:54:49.326   Hello         1

A: You can 'pre-coock' your data in order to have always messages in same direction from every combination of users.
Sample, if your data is:
Sender Recipient
A ---> B
B ---> A

You change it to:
U1     U2
B ---> A (changed)
B ---> A

Like this:
SELECT (case when Sender > Recipient then Sender else Recipient end) AS u1,
       (case when Sender > Recipient then Recipient else Sender end) AS u2,
       Timestamp AS Timestamp,
       Body AS LatestMessage,
       (SUM(CASE WHEN TimeRead IS NULL THEN 1 ELSE 0 END) ) AS UnreadMessageCount
FROM Direct_Messages_cooked
GROUP BY
     (case when Sender > Recipient then Sender else Recipient end),
     (case when Sender > Recipient then Recipient else Sender end)
ORDER BY Timestamp DESC

Notice: Be careful with performance ( I guess it is not important because you are tagged question as sqlite )
You can use CTE to pre-coock your data and get a more readable query:
with Direct_Messages_coocked as
(
    select
      (case when Sender > Recipient then Sender else Recipient end) AS U1,
      (case when Sender > Recipient then Recipient else Sender end) AS U2,
      *
    from Direct_Messages
)
SELECT U1 AS U1,
       U2 AS U2,
       Timestamp AS Timestamp,
       Body AS LatestMessage,
       (SUM(CASE WHEN TimeRead IS NULL THEN 1 ELSE 0 END) ) AS UnreadMessageCount
FROM Direct_Messages_coocked
GROUP BY U1, U2
ORDER BY Timestamp DESC

A: You can get most of what you want by using MIN() and MAX() with multiple arguments.  With multiple arguments, these are scalar functions that operate like LEAST() and GREATEST() in other databases:
SELECT MIN(Sender, Recipient) AS u1,
       MAX(Sender, Recipient) AS u2,
       MAX(Timestamp) AS Timestamp,
       -- Body AS LatestMessage,
       (COUNT(*) - COUNT(TimeRead)) as UnreadMessageCount
FROM Direct_Messages_cooked
GROUP BY u1, u2
ORDER BY MAX(Timestamp) DESC

The challenge is getting the latest method.  You can get this with conditional aggregation and an additional JOIN:
SELECT MIN(dmc.Sender, dmc.Recipient) AS u1,
       MAX(dmc.Sender, dmc.Recipient) AS u2,
       MAX(dmc.Timestamp) AS Timestamp,
       MAX(CASE WHEN dmc.Timestamp = dmc2.Timestamp THEN Body END) AS LatestMessage,
       (COUNT(*) - COUNT(dmc.TimeRead)) as UnreadMessageCount
FROM Direct_Messages_cooked dmc JOIN
     (SELECT MIN(Sender, Recipient) AS u1,
             MAX(Sender, Recipient) AS u2,
             MAX(Timestamp) AS Timestamp
      FROM Direct_Messages_cooked
      GROUP BY u1, u2
     ) dmc2
     ON dmc2.u1 = MIN(dmc.Sender, dmc.Recipient) AND
        dmc2.u2 = MAX(dmc.Sender, dmc.Recipient)
GROUP BY u1, u2
ORDER BY dmc2.Timestamp DESC

A: Building on @Gordon Linoff's and @dani herrera's insightful answers I managed to tweak about and come up with a succinct solution to my specific problem, though in the broader context of my initial question, @Gordon's answer seems, from my observation, to address the problem more fully. Here's what I managed to come up with:
SELECT Sender AS Sender,
       Recipient AS Recipient,
       Timestamp AS Timestamp,
       Body AS LatestMessage,
       (COUNT( * ) - COUNT(TimeRead) ) AS UnreadMessageCount
  FROM Direct_Messages
 GROUP BY (
              SELECT MAX(Sender, Recipient)
          ),
          (
              SELECT MIN(Sender, Recipient)
          )
 ORDER BY Timestamp DESC


text:
Q: union returns 2 rows in table instead of one I have this table in my database , and I am trying to get 2 sets of value and put them in a union.
Here is the table.
My union basically has two terms where interest_payment > 0 and interest_paid > 0 ,  if interest_payment is greater than zero, it takes that row and adds it with the next row, and if the next row has interest_payment > 0 it adds it with that row, but if interest_payment < 0 , it should add interest_paid in that same row. But Right now when I run the query I get it this.
Basically the netInterest shouldn't show Null since I am using sum, so it should return me just one row.

here is the sql for all this.
Select sum(investedMoney) as investMoney , sum(estimatedEarning) as estimatedEarning , sum(NetInterest) as NetInterest, Eurosymbol
                from
                (
                select  sum(round(a.Amount * e.average_rate / f.average_rate, 2)) as investedMoney ,
                        sum(round((d.interest_payment + d.overdue_payment) * e.average_rate / f.average_rate, 2)) as estimatedEarning,
                        0 as NetInterest,
                        c.symbol as Eurosymbol
                from   investment a
                inner join money_offer b
                on a.ORIG_ID = b.investment_orig_id and b.UPDATE_DT is null
                inner   join payment_plan d
                on d.offer_orig_id = b.ORIG_ID and d.interest_payment > 0 and d.UPDATE_DT is null
                inner   join currency c
                        on  d.currency = c.ID
                inner join exchange_rates e
                        on  e.currency_id = a.Currency
                inner join exchange_rates f
                        on  f.currency_id = a.Currency
                where   a.Owner = 533  and
                                a.UPDATE_DT is null

                        union

                select  0 as investedMoney ,
                        0 as estimatedEarning,
                        sum(round((d.interest_paid+ d.overdue_paid) * e.average_rate / f.average_rate, 2)) as NetInterest,
                        c.symbol as Eurosymbol
                from   investment a
                inner join money_offer b
                on a.ORIG_ID = b.investment_orig_id and b.UPDATE_DT is null
                inner   join payment_plan d
                on d.offer_orig_id = b.ORIG_ID and d.interest_paid > 0 and d.UPDATE_DT is null
                inner   join currency c
                        on  d.currency = c.ID
                inner join exchange_rates e
                        on  e.currency_id = a.Currency
                inner join exchange_rates f
                        on  f.currency_id = a.Currency
                where   a.Owner = 533  and
                                a.UPDATE_DT is null
                )tmptbl
                group by Eurosymbol;

A: In either the case of d.interest_payment > 0 or d.interest_paid > 0 you store a different Currency in the payment_plan table. My guess is that you have dummy ID to indicate "no currency". Assuming that you have a NULL value stored for that particular dummy currency in currency.symbol, you could just take the max of it in your overall query.
Also, I think for your purposes you should combine the union queries into one. This way you can deal with cases where both conditions are true in the same record: they will then not be duplicated. The distinction between the two types of figures can be made with a case when construct, like this:
  select      sum(case when d.interest_payment > 0
                    then round(a.Amount * e.average_rate / f.average_rate, 2)
                    else 0
                  end) as investedMoney,
              sum(case when d.interest_payment > 0
                    then round((d.interest_payment + d.overdue_payment)
                               * e.average_rate / f.average_rate, 2)
                    else 0
                  end) as estimatedEarning,
              sum(case when d.interest_paid > 0
                    then round((d.interest_paid + d.overdue_paid)
                               * e.average_rate / f.average_rate, 2)
                    else 0
                  end) as NetInterest,
              max(c.symbol) as Eurosymbol
  from        investment a
  inner join  money_offer b
          on  a.ORIG_ID = b.investment_orig_id and b.UPDATE_DT is null
  inner join  payment_plan d
          on  d.offer_orig_id = b.ORIG_ID and d.UPDATE_DT is null
          and (d.interest_payment > 0 or d.interest_paid > 0)
  inner join  currency c
          on  d.currency = c.ID
  inner join  exchange_rates e
          on  e.currency_id = a.Currency
  inner join  exchange_rates f
          on  f.currency_id = a.Currency
  where       a.Owner = 533
      and     a.UPDATE_DT is null

You should also review why you join the exact same record twice from exchange_rates (as e and f) which makes the expression e.average_rate / f.average_rate always evaluate to 1 (assuming the rates are never zero).