text:
Q: What are the main benefits of comparing SQL schemas? So I'v been having a little look around the interwebs and i cant seem to find any information on the benefits of doing a schema comparison.
I'm sure there is plenty of information out there, but i thought it would be a good idea to ask on S/O.
Can you please outline the main benefits of comparing SQL schemas.


text:
Q: Ioc container for Web Api 2.2 I'm looking into using a IOC container for Web Api 2.2 (recently released). I want to use it as a dependency resolver for Web API controllers along with injecting my own dependencies.
I've tried using Unity and Autofac, using there Web Api nuget packages, without success. I've come to conclusion that they doesn't support Web Api 2.2 (yet).
Is there any other known IOC container that support Web Api 2.2?

A: Added assembly redirects to System.Web.Http 5.2.0.0 and got rid of the exceptions. Also noted that I hadn't registered all types (dependencies of the controller) and therefore the controller wasn't instantiated.
Thanks, works fine now. Is it possible to get Unity to throw exception if it fails to instantiate due to lacking dependencies instead of being silent?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Java - Rule-based sorting using bellman-held-karp algorithm I asked the following question on CS SE, and have no idea as to how to implement the answer in java (let alone make out what it is actually saying):
I am trying to plant a row in a garden. Certain plants are good for some plants and bad for others, and I am trying to find the best order of plants: most adjacent friends and no adjacent foes, as defined in this table (I have one of each):
Num Vegetable     Friends      Foes
1   Watermelon    7,4,3        8,6
2   Tomatoes      9,8,6,5,1    7
3   Sunflowers    7,6,11
4   Zucchini      9,7,3
5   Eggplant      9,6,2        7,10
6   Cucumbers     9,7,3        8,1
7   Corn          8,6,4,3,1    5,2
8   Cantaloup     7,4,3        6,1
9   Bell peppers  6,5,11,10,2
10  Swiss chard   2            5
11  Rhubarb       9,3

How do I find the arrangement?
"Jakube" answered:

You can solve such a problem by simply iterating over all n! different
permutations, and checking each if any of the arrangements is allowed
and how good it is. This has complexity O(n⋅n!).
Much faster (but still exponential complexity) will be a variation to
the Bellman–Held–Karp algorithm. Compute for each pair (V,v) with V
being a subset of all vegetables and and v∈V, if it is possible to
arrange the vegetables V in a way such that v is the last one and what
it's best value is. You can define a recursive formula for this
function, and apply dynamic programming, like in the BHK algorithm.
That should run in O(n2⋅2n)."

I originally asked the question for a case where I had one of each, but now realize that I need an answer which can take more an occasional duplicate. I am not sure if the answer he gave is applicable to a case where I have more than one of a given plant.

A: I know you tagged this Java, but here's some Python implementing that dynamic program.
import collections

Plant = collections.namedtuple("Plant", ("id", "name", "friends", "foes"))

def extend(first_plant, result):
    objective, other_plants = result
    return (
        (first_plant.id in other_plants[0].friends)
        + (other_plants[0].id in first_plant.friends)
        + objective,
        [first_plant] + other_plants,
    )

def best_order_recursive(first_plant, other_plants, cache):
    if not other_plants:
        return 0, [first_plant]
    cache_key = (first_plant.id, frozenset(plant.id for plant in other_plants))
    if cache is None:
        cache = {}
    else:
        cache_value = cache.get(cache_key)
        if cache_value is not None:
            return cache_value
    value = max(
        (
            extend(
                first_plant,
                best_order_recursive(
                    next_plant, other_plants[:i] + other_plants[i + 1 :], cache
                ),
            )
            for (i, next_plant) in enumerate(other_plants)
            if first_plant.id not in next_plant.foes
            and next_plant.id not in first_plant.foes
        ),
        default=(float("-inf"), [first_plant]),
    )
    cache[cache_key] = value
    return value

def best_order(plants):
    cache = {}
    return max(
        best_order_recursive(first_plant, plants[:i] + plants[i + 1 :], cache)
        for (i, first_plant) in enumerate(plants)
    )

def main():
    objective, plants = best_order(
        [
            Plant(1, "Watermelon", {7, 4, 3}, {8, 6}),
            Plant(2, "Tomatoes", {9, 8, 6, 5, 1}, {7}),
            Plant(3, "Sunflowers", {7, 6, 11}, set()),
            Plant(4, "Zucchini", {9, 7, 3}, set()),
            Plant(5, "Eggplant", {9, 6, 2}, {7, 10}),
            Plant(6, "Cucumbers", {9, 7, 3}, {8, 1}),
            Plant(7, "Corn", {8, 6, 4, 3, 1}, {5, 2}),
            Plant(8, "Cantaloupe", {7, 4, 3}, {6, 1}),
            Plant(9, "Bell peppers", {6, 5, 11, 10, 2}, set()),
            Plant(10, "Swiss chard", {2}, {5}),
            Plant(11, "Rhubarb", {9, 3}, set()),
        ]
    )
    print(objective)
    print(*(plant.name for plant in plants), sep=", ")

if __name__ == "__main__":
    main()


text:
Q: When should I go Frozen Mallet or Trinity Force on Riven? Recently I've been getting Trinity Force on Riven. Should I get a Frozen Mallet instead, or stay with the Tri-force?

A: Usually on Riven, you shouldn't get either one of them.
You can get Frozen Mallet against enemies with true damage (Irelia/Olaf), or if the enemy is really mobile (Ezreal, Corki, Ahri et al.) so you can slow them and chase them down.
Triforce on Riven is a snowball item (get ahead, buy Triforce, get ahead even more) but Brutalizer and Bloodthirster do this even better. So instead of getting Triforce, try to get Brutalizer (if ahead) or just get BT, and after that get Guardian's Angel. You will do way more damage with BT, have more sustain (life leech), be tankier (shield stronger cause you got more AD) and if you get GA soon afterwards, you wont even get focused.

A: Please refer to this astounding build guide for Riven. It helps me out quite a lot! I currently have won nearly every single game as Riven thanks to Goldfather8.
After the beginning buy, I usually go TriDorans, then sell one Dorans for a Wriggles, and then get a Bloodthirster if its an AD champ, or a Hexdrinker if its an AP champ in my lane. If its Double AP, I get GA then FoN. If its just one AP I get GA then Thornmail.
My end build:
Defensive Lv 2 boots
Wriggles
Bloodthirster
GA
FoN / Thornmail / Warmogs

if you get really fed and dominate the game:
Bloodthirster

If your team has very little CC:
Frozen Mallet

If both are true, Sell the Wriggles and buy both.
That's just me though.

A: Frozen Mallet gives you very little over Trinity Force. Trinity force you are getting way more damage, and the bonus hp from Frozen Mallet is not worth much without armor and magic resist to back it up. There are many better items to go for than Frozen Mallet; you are paying 3250 gold for an item that gives 20 AD, which is not a smart choice given Riven scales extremely well with AD. You can get that AD for less than 1k gold with double Doran's or something else.
In case you think that Frozen Mallet buffs Atma's Impaler nicely, Frozen Mallet only provides a bonus 10.5 AD with Atma's, which is pitiful at best. Trinity matches that 10 AD inherently.
So maybe you want to pay for the reliable slow. That is reasonable, although with Trinity Force Riven has a ~58% chance of triggering the slow in 3 attacks factoring in attack speed. This means that every 2.5 seconds you have a ~58% chance of applying the slow again before the previous slow wears off. Those chances aren't that bad, and in practice if your target gets away it's likely not only because you didn't slow them. Dashes, knockback, and flashing all will render slows less than effective for chasing.
Having said all that, even choosing Trinity Force is not the best move. Although the stats are amazing for one item slot, you are sinking at lot of gold into Sheen, which remains next to useless until finally built into Trinity Force (you have no mana or AP scaling, and base damage bonus is low before Trinity Force). There are many better items for early-mid game you should be considering, like The Brutalizer or Wriggle's Lantern. You are typically in the jungle or top lane as Riven, so both of those items will help you do better in lane then a Phage, Sheen, or Zeal will by providing a larger damage boost and in the case of Wriggle's a lot of needed sustain.

A: I would recommend going Frozen mallet if you want a safe lane/team fight, frozen mallet gives a lot of utility since all your attacks slows by 40%, and since you wont get any Attack speed items as riven you wont proc Trinitys slow very often which is bad. So I would definitely go for Frozen Mallet unless you totally dominate and just stomp them in teamfights.

A: I agree with Peter, frozen mallet is almost necessary on a lot of AD bruisers right now as the slow, health, and damage it gives is really really good. trinity force would be good for her if the cost wasn't so astronomical. instead you could get a bloodthirster and frozen mallet for just a bit more than a trinity force and get more out of it in the long run. so my money goes to frozen mallet.

A: Get frozen mallet and Atma's impaler; you don't want AS on Riven and the sheen doesn't help much.

A: Trinity force is pretty useless on Riven. She doesn't need the attack speed very much, and Sheen is not useful on her compared to other champions. The only useful item is Phage, which should be built into the Frozen Mallet.
Riven is a tanky DPS, and Frozen Mallet suits that role well, providing amazing health, a little bit of damage, and a very useful slow that works well with her kit.
Personally though, I prefer Warmog's over all three.

A: trin force is just useless cause you normaly attack just 1x or 2x with the effect.
frozen mallet can be usefull cause riven is after she used spells kill able if she didnt got a good position/hp/armor ... but i think bloodthirster shild > hp from frozen mallet in the end but its just my personal way to play i pref to play shoes+blood+maw+ga+lastw+blood/frozenheart/omen

A: You shouldn't really ever purchase these items on Riven. Bloodthirster x 3 - Merc - LW - GA. If you're getting bursted, Replace a Bloodthirster lategame with a Warmogs.


text:
Q: Replication not updating XML Schema collection So the problem I'm facing is that replication from our Main instance to our Data Warehouse instance is failing because it isn't picking up XML schema updates. Thus, when it tries to bulk copy the data from the Main table that utilizes it, it fails because XML validation fails due to the XMLSchemaCollection not containing any of the updates.
The behavior that we've observed in the last couple months is that if the XML schema is new, then replication picks it up. However, from that point forward, it ignores it. This smells like a deficiency in the way it detects updates. But I'm hoping that someone else has figure this out.


text:
Q: Кол-во строк с одинаковым значением поля Есть такой запрос
SELECT
    salesorderid,
    integration_betapost.goods_to_products.shipping_order_row_good_id,
    vtiger_inventoryproductrel.quantity
FROM
    vtiger_salesorder
INNER JOIN vtiger_inventoryproductrel ON vtiger_salesorder.salesorderid = vtiger_inventoryproductrel.id
INNER JOIN vtiger_products ON vtiger_inventoryproductrel.productid = vtiger_products.productid
INNER JOIN integration_betapost.goods_to_products ON vtiger_products.productid = integration_betapost.goods_to_products.productid
WHERE
    sostatus = 'Отправлять'

Который выводит результат вида result
Вопрос, как посчитать сумму строк с одинаковым salesorderid и сумму строк с одинаковыми salesorderid и  shipping_order_row_good_id?

A: SELECT
    salesorderid,
    integration_betapost.goods_to_products.shipping_order_row_good_id,
    sum(Quantity)
FROM
    vtiger_salesorder
INNER JOIN vtiger_inventoryproductrel ON vtiger_salesorder.salesorderid = vtiger_inventoryproductrel.id
INNER JOIN vtiger_products ON vtiger_inventoryproductrel.productid = vtiger_products.productid
INNER JOIN integration_betapost.goods_to_products ON vtiger_products.productid = integration_betapost.goods_to_products.productid
WHERE
    sostatus = 'Отправлять'
GROUP BY
    salesorderid
    ,integration_betapost.goods_to_products.shipping_order_row_good_id
order by salesorderid desc


text:
Q: Creating dynamic tables in HTML using MySQL and PHP I've seen many posts about how to build a table in HTML with PHP and MysSQL, but I often change the headers of MySQL columns after creating a table.
Is there any way for PHP to update the code automatically so that I can just put in the table name and it prints the table without me having to put in all the  tags?
<?php

$table = "user";
$database = "database";
$conn = mysqli_connect("localhost", "username", "password", "database", "3306");

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT * FROM $table";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        echo "
" . $row["id"] . "	" . $row["first_name"] . "	" . $row["last_name"] . "	" . $row["birthday"] . "
";
    }
    echo "
";
} else {
    echo "0 result";
}

$conn->close();

A: If you want to display the full contents of the database table as an HTML table, I suggest you make a function that will do all of this dynamically for you. This function should check that the table exists, fetch all the data, and fetch output HTML table with headers.
MySQLi solution
Here is my suggestion using MySQLi. First of all, you must make sure that the table actually exists. Then you can fetch all the data from the table. The object returned by mysqli::query() will have all metadata information about column names which you can use to display the header row. You can use fetch_fields() to iterate over each column metadata. The data can be fetched using fetch_all() method.
<?php

// create global connection using mysqli
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = mysqli_connect("localhost", "username", "password", "database", "3306");
$mysqli->set_charset('utf8mb4'); // always set the charset

function outputMySQLToHTMLTable(mysqli $mysqli, string $table)
{
    // Make sure that the table exists in the current database!
    $tableNames = array_column($mysqli->query('SHOW TABLES')->fetch_all(), 0);
    if (!in_array($table, $tableNames, true)) {
        throw new UnexpectedValueException('Unknown table name provided!');
    }
    $res = $mysqli->query('SELECT * FROM '.$table);
    $data = $res->fetch_all(MYSQLI_ASSOC);

    echo '
';
    // Display table header
    echo '
';
    echo '
';
    foreach ($res->fetch_fields() as $column) {
        echo ''.htmlspecialchars($column->name).'	';
    }
    echo '
';
    echo '
';
    // If there is data then display each row
    if ($data) {
        foreach ($data as $row) {
            echo '
';
            foreach ($row as $cell) {
                echo ''.htmlspecialchars($cell).'	';
            }
            echo '
';
        }
    } else {
        echo '
field_count.'">No records in the table!
';
    }
    echo '
';
}

outputMySQLToHTMLTable($mysqli, 'user');

PDO Solution
Using PDO is very similar but you have to pay attention to the differences in the APIs.
To get the table names, you can use fetchAll(PDO::FETCH_COLUMN) instead of array_column(). To get the column metadata, you need to use getColumnMeta() function.
<?php

$pdo = new PDO("mysql:host=localhost;dbname=test;charset=utf8mb4", 'username', 'password', [
    \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
    \PDO::ATTR_EMULATE_PREPARES => false
]);

function outputMySQLToHTMLTable(pdo $pdo, string $table)
{
    // Make sure that the table exists in the current database!
    $tableNames = $pdo->query('SHOW TABLES')->fetchAll(PDO::FETCH_COLUMN);
    if (!in_array($table, $tableNames, true)) {
        throw new UnexpectedValueException('Unknown table name provided!');
    }
    $stmt = $pdo->query('SELECT * FROM '.$table);
    $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $columnCount = $stmt->columnCount();

    echo '
';
    // Display table header
    echo '
';
    echo '
';
    for ($i = 0; $i < $columnCount; $i++) {
        echo ''.htmlspecialchars($stmt->getColumnMeta($i)['name']).'	';
    }
    echo '
';
    echo '
';
    // If there is data then display each row
    if ($data) {
        foreach ($data as $row) {
            echo '
';
            foreach ($row as $cell) {
                echo ''.htmlspecialchars($cell).'	';
            }
            echo '
';
        }
    } else {
        echo '
No records in the table!
';
    }
    echo '
';
}

outputMySQLToHTMLTable($pdo, 'user');

P.S. The table existence check can be optimized with the following code instead:
$tableNames = $pdo->prepare('SELECT COUNT(1) FROM information_schema.TABLES WHERE TABLE_SCHEMA = SCHEMA() AND TABLE_NAME=?');
$tableNames->execute([$table]);
if (!$tableNames->fetchColumn()) {
    throw new UnexpectedValueException('Unknown table name provided!');
}

A: I just read your question, and coded to meet your needs, but I used PDO and not MYSQLI, maybe it is better for you to understand the code, because with PDO everything is simpler. And the way I did it, you don't need to put all the tags, PHP will update automatically, and know that the file must end with the extension .php!
<?php

$conn = new PDO("mysql:host=localhost;dbname=YOUR_DATABASE_HERE", "USERNAME", "PASSWORD");

if(!$conn){
    echo "Could not connect!";
}

?>

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

            ID
            FirstName
            LastName
            Birthday

        <?php

        $sql = "SELECT * FROM user";
        $result = $conn->prepare($sql);
        $result->execute();

        if($result->rowCount() > 0):
            $rows = $result->fetchAll();
            foreach($rows as $row):
        ?>

            <?php echo $row['id'];  ?>
            <?php echo $row['first_name']; ?>
            <?php echo $row['last_name']; ?>
            <?php echo $row['birthday']; ?>

        <?php
        endforeach;
    endif;
        ?>


text:
Q: get wrong ogtype in object debugger my tested page is here.
http://smartphone.mn/news/2110 . I'm using facebook object debugger, Debugger return og:type = website and 4 Inferred property warning (og:url,or:img, og:description, og:image).
How can fix this. Why object type return wrong?

A: You using OpenGraph meta-tags in a wrong manner. This is a code you have in page:
<meta name="fb:app_id" content="..." />
<meta name="og:type" content="article" />
...

But the fact is you MUST use property named property instead of name to specify the name of the OpenGraph data...
So to solve this you just need to replace name to property for OpenGraph meta-tags:
<meta property="fb:app_id" content="..." />
<meta property="og:type" content="article" />
...


text:
Q: Create subfolders/zip every 20 files automatically I have a huge folder that I would like to transform into several small ones of 20 files each and compressed. I would like to do this automatically with a batch file and 7zip.
To achieve this I thought about 2 steps:
1. Create a sub-folder for each 20 files (source) :
@echo off
set /a counter=1
set /a filesperfolder=20
cd "C:\Users\Desktop\dir\"
:loopstart
set dirname=dir_%counter%
md %dirname%
echo %dirname%

dir /b | findstr /v /i "dir_*"> %temp%\temp.txt && for /l %%l in (1,1,%filesperfolder%) do @for /f "tokens=1,2* delims=:" %%a in ('findstr /n /r "^" %temp%\temp.txt ^| findstr /r "^%%l:"') do @move %%b %dirname%\%%b >nul

set /a counter=%counter%+1
for /f "tokens=*" %%a in ('type %temp%\temp.txt ^| find /c /v ""') do set _filesmoved=%%a
del %temp%\temp.txt
IF %_filesmoved% LSS 20 goto done

goto loopstart

:done
cls
echo All files were moved!!
pause
exit

Unfortunately this does not work : The syntax of the command is incorrect.. I've tried debugging the script by removing the @echo off and it tells me that the dir /b | findstr /v /i "dir_*"> %temp%\temp.txt && for /l %%l in (1,1,%filesperfolder%) do @for /f "tokens=1,2* delims=:" %%a in ('findstr /n /r "^" %temp%\temp.txt ^| findstr /r "^%%l:"') do @move %%b %dirname%\%%b >nul part is not working (same error). This part is quite fuzzy for me and a little help would be welcome.
I specify that the file temp.txt contains my complete list of files, without any separator (one file per line).
--- UPDATE: filenames must not contain spaces ---
2. Compress all these subfolders one by one with (source) :
for /D %d in (*.*) do 7z a -tzip "%d.zip" ".\%d\*"
Do you have an idea for (I summarize) : create, for a large number of files, subfolders of 20 files in order to compress each subfolder one by one.
If you have any idea on how to compress each 20 files directly (without going through the creation of subfolders) I also agree!
Thank you in advance for your help!

A: Resolved!
I found my mistake. In reality my files included spaces that the script could not fit.
So, to answer my basic question which was: in a big folder filled with thousands of files, how to compress each 20 files in subfolders? it is necessary (to my knowledge) to:

*

*Create a sub-folder for each 20 files whose name does not have spaces (code in my question)

*Compress all these subfolders one by one (code in my question)

And it's done!
Do not hesitate to suggest a solution if you know of a "faster" one.

A: No need to create folders. Just iterate over the files and add every single file to it's designated zip file (instead of copying every 20 files into a folder and zip that folder)
Use two counters to keep track of (source)files and zip files. One counter for the files (use the Modulo-operator to check for each 20) and one for the zip filenames. I started the zip filenames with 10001 instead of 1 and took the last four chars of it to get sortable file names (0001.zip etc).
@echo off
setlocal enabledelayedexpansion
set filesperfolder=20
cd /d "%cd%"
set "zipDest=C:\temp"
set filecounter=0
set foldercounter=10001

for %%a in (*) do (
  set /a filecounter+=1
  set /a check=filecounter %% filesperfolder
  if !check! == 0 set /a foldercounter+=1
  ECHO 7z a -tzip "%zipDest%\!foldercounter:~-4!.zip" "%%a"
)

Obviously adapt the cd /d line (source folder), destination folder (Attention: don't use the source folder, or your zip files might be zipped again into other zip files), and maybe the zip-filename (like "%zipDest%\MyZips-!foldercounter:~-4!.zip")
NOTE: I disarmed the 7zip command with ECHO for testing and troubleshooting. Remove the ECHO when the output satisfies you.
To delete each file after successfully zipping them, change the zip line to:
7z a -tzip "%zipDest%\!foldercounter:~-4!.zip" "%%a" && del "%%a"

The quotes should take care of any spaces.


text:
Q: VB6 Application ODBC Error I have a VB6 application working with.
This application uses ODBC to access a Microsoft Access database.
I am sure that the database string is correct as the database contains the information used to login and the login works just fine. I also have the same string at every instance.
However, at a certain point the ODBC driver error-"Data source name not found and no default driver specified" appears...The issue is:
This occurs whenever I press a specific button. This button opens a form:
Private sub Munubttn_Click()
frmLog.Show
End Sub

However, in the form frmLog, I placed a message box as the first command under the Form_Load() sub. Now whenever the button is clicked, I get the error, just before the message box. As such, I do not know where this error originates. So I suppose the question is, what code does the form execute just before it loads? Any help would be appreciated.

A:
So I suppose the question is, what code does the form execute just before it loads?

The only code that would be executed would be the class initialize sub.  Given your described scenario, the problematic logic is likely in a Class_Initialize sub within the frmLog Form.


text:
Q: Prove that $(S')' = S$ I would like to ask if my solution, which is presented below, is correct.
$S' = ${$x \in U: x \notin S$}
$(S')' = ${$x  \in U: x \notin S'$}
$ \implies (S')' = \hspace{1mm}${$x \in U: (x \notin U  \hspace{1mm} or  \hspace{1mm}  x \notin S')$}
$ \implies (S')' = \hspace{1mm} ${$x \in U: (x \notin U  \hspace{1mm} or  \hspace{1mm}  (x \in S \hspace{1mm} or \hspace{1mm}x \notin U)$}
$x \notin U $ is always false
$\implies (S')' = \hspace{1mm} ${$x \in U: x \in S $}
$\implies (S')' = \hspace{1mm}S$
Kindly suggest any necessary changes if this doesn't work.

A: More directly :
$$x \in S' \Longleftrightarrow x \notin S$$
So applying this to $S'$, you get
$$x \in (S')' \Longleftrightarrow x \notin S' \Longleftrightarrow x \in S$$
So $(S')'=S$.


text:
Q: Cannot change font & font size in JTextArea using JComboBoxes I have created a JFrame where the user can edit text in a JTextArea. There is a JComboBox to change font type, a JComboBox to change font size, and 2 JCheckBoxes to make the text Bold and Italic. I have finished the JCheckBoxes, but I cannot figure out how to allow change font and font size by using the JComoboBoxes. Any help would be appreciated.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;

    public class SetFontModified extends JFrame
    {
        private JPanel p1, p2;
        private JLabel jlblFontName, jlblFontSize;
        private JComboBox jcbFonts, jcbSizes;
        private JTextArea jtxtWelcome;
        private JCheckBox  jckbBold, jckbItalic;

        public SetFontModified()
        {
        p1 = new JPanel();
        jlblFontName = new JLabel("Font Name");

        GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
        String[] fontNames = e.getAvailableFontFamilyNames();
        jcbFonts = new JComboBox(fontNames);

        jlblFontSize = new JLabel("Font Size");// add 2nd JLabel

        jcbSizes = new JComboBox(); // create 2nd JComboBox
        for(int i = 1; i < 101; i ++) // populate JComboBox with array of font sizes 1-100
        {
            jcbSizes.addItem(i);
        }

        p1.add(jlblFontName); // add all 4 components to p1
        p1.add(jcbFonts);
        p1.add(jlblFontSize);
        p1.add(jcbSizes);

        jtxtWelcome = new JTextArea("Welcome to Java", 3, 20);// add a JTextArea
        add(jtxtWelcome);

        p2 = new JPanel(); // create p2 & add JCheckBoxes
        p2.add(jckbBold = new JCheckBox("Bold"));
        jckbBold.setMnemonic('B');
        p2.add(jckbItalic = new JCheckBox("Italic"));
        jckbItalic.setMnemonic('I');

        add(p1,BorderLayout.NORTH);
        add(p2,BorderLayout.SOUTH);

        ListenerClass listener = new ListenerClass();
        jcbFonts.addActionListener(listener);
        jcbSizes.addActionListener(listener);
        jckbBold.addActionListener(listener);
        jckbItalic.addActionListener(listener);
        }

        public static void main(String[] args)
        {
       SetFontModified frame = new SetFontModified();
       frame.setTitle("Set Font Details");
       frame.pack();
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       frame.setLocationRelativeTo(null);
       frame.setVisible(true);
    }

    private class ListenerClass implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            jcbSizes.getFontSize();

            Font plainFont = new Font("serif", Font.PLAIN, size);
            Font boldFont = new Font("serif", Font.BOLD, 14);
            Font italicFont = new Font("serif", Font.ITALIC, 14);
            Font boldItalicFont = new Font("serif", Font.BOLD + Font.ITALIC, 14);

            if (jckbBold.isSelected() && jckbItalic.isSelected())
                jtxtWelcome.setFont(boldItalicFont);

            else if (jckbBold.isSelected())
                jtxtWelcome.setFont(boldFont);

            else if (jckbItalic.isSelected())
                jtxtWelcome.setFont(italicFont);

            else jtxtWelcome.setFont(plainFont);
        }
    }
}

A: import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Test extends JFrame
{
    private JPanel p1, p2;
    private JLabel jlblFontName, jlblFontSize;
    private JComboBox jcbFonts, jcbSizes;
    private JTextArea jtxtWelcome;
    private JCheckBox  jckbBold, jckbItalic;

    public Test()
    {
    p1 = new JPanel();
    jlblFontName = new JLabel("Font Name");

    GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
    String[] fontNames = e.getAvailableFontFamilyNames();
    jcbFonts = new JComboBox(fontNames);

    jlblFontSize = new JLabel("Font Size");                                               // add 2nd JLabel

    jcbSizes = new JComboBox();                                                               // create 2nd JComboBox
    for(int i = 1; i < 101; i ++)                                                                 // populate JComboBox with array of font sizes 1-100
    {
        jcbSizes.addItem(i);
    }

    p1.add(jlblFontName);                                                                         // add all 4 components to p1
    p1.add(jcbFonts);
    p1.add(jlblFontSize);
    p1.add(jcbSizes);

    jtxtWelcome = new JTextArea("Welcome to Java", 3, 20);                            // add a JTextArea
    add(jtxtWelcome);

    p2 = new JPanel();                                                                            // create p2 & add JCheckBoxes
    p2.add(jckbBold = new JCheckBox("Bold"));
    jckbBold.setMnemonic('B');
    p2.add(jckbItalic = new JCheckBox("Italic"));
    jckbItalic.setMnemonic('I');

    add(p1,BorderLayout.NORTH);
    add(p2,BorderLayout.SOUTH);

    ListenerClass listener = new ListenerClass();
    jcbFonts.addActionListener(listener);
    jcbSizes.addActionListener(listener);
    jckbBold.addActionListener(listener);
    jckbItalic.addActionListener(listener);
    }

    public static void main(String[] args)
    {
   Test frame = new Test();
   frame.setTitle("Set Font Details");
   frame.pack();
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.setLocationRelativeTo(null);
   frame.setVisible(true);
}

private class ListenerClass implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
        //jcbSizes.getFontSize();

        Font plainFont = new Font("serif", Font.PLAIN, Integer.parseInt(jcbSizes.getSelectedItem().toString()));
        Font boldFont = new Font("serif", Font.BOLD, 14);
        Font italicFont = new Font("serif", Font.ITALIC, 14);
        Font boldItalicFont = new Font("serif", Font.BOLD + Font.ITALIC, 14);

        if (jckbBold.isSelected() && jckbItalic.isSelected())
            jtxtWelcome.setFont(boldItalicFont);

        else if (jckbBold.isSelected())
            jtxtWelcome.setFont(boldFont);

        else if (jckbItalic.isSelected())
            jtxtWelcome.setFont(italicFont);

        else jtxtWelcome.setFont(plainFont);

    }
}
}

A: The compiler is complaining about an undefined variable size. You can add this declaration to your ActionListener:
int size = (Integer)jcbSizes.getSelectedItem();

A: You need the correct method for jcbSizes:
int size = (Integer) jcbSizes.getSelectedItem();

A:
but I cannot figure out how to allow change font  and font size by
  using the JComoboBoxes.

For this to happen you have to change your else block like follows.
else {

    // jcbFonts.getSelectedItem().toString()
    // gets font string selected in font combobox
    // -------------------------------------
    // jcbSizes.getSelectedIndex())
    // get font size selected in size combobox

    jtxtWelcome.setFont(new Font(jcbFonts.getSelectedItem()
                    .toString(), Font.PLAIN, jcbSizes.getSelectedIndex()));

    System.out.println("Font Name: " + jcbFonts.getSelectedItem()
                + " Font Size:" + jcbSizes.getSelectedIndex());
}

Class Font API


text:
Q: Node.js mysql query syntax for retrieving I am using nodejs with MySQL nom to retrieve date.
currently select * from table works fine but if I want to query db and retrieve date between 2 values it's not working.
The node code is
app.get('/api',function(req,res)
{

  var startDate = req.param('startDate');
  var endDate = req.param('endDate');
  var sqlQuery =null;
  var message ={};
  message.status=false;

  log("Params Found Changing SQL Queries For Start And End Date");
    sqlQuery ="SELECT * from sentiment_data where *file_ts* >= "+startDate+" and *file_ts* <= "+endDate+" order by file_ts";
    log(sqlQuery);
    if(user.isDB)
    {
      connection.query(sqlQuery, function(err, rows, fields)
      {
        if (!err)
        {
          message = rows;
          res.send(message);
        }
      });
    }
    else
    {
      log("DB Error");
    }

});

The SQL statement I am executing when building it with start time and end time is
SELECT * from sentiment_data
 where *file_ts* >= "+startDate+"
  and *file_ts* <= "+endDate+"
 order by file_ts

I am building this query and its not working.

A: *file_ts* is not valid SQL; nor is it possible to just plonk an unquoted date into a query. Use parameter binding; it will also protect you from Bobby Tables.
var sqlQuery = "SELECT * FROM sentiment_data WHERE file_ts >= ? AND file_ts <= ? ORDER BY file_ts";
// ...
connection.query(sqlQuery, [startDate, endDate], function(err, results) {
  // ...
});

And depending on what is in startDate and endDate, you might need to use Date.parse to make them understandable.


text:
Q: Want to make sure the Username is unique I am trying to add a little feature to my Spring boot application where I want to username to be unique for that I am calling my get List Students method and checking if the newly added user name matches any other user username then it should give an error to the user for that I am getting an error of antlr.NoViableAltException: unexpected token: s Please help me here What I am doing wrong and what should be the best practice for this.. here is my code:
GetListOfStudents:
@SuppressWarnings("unchecked")
    @Override
    @Transactional
    public List<Student> getListOfStudent(Student studentModel) {
        List<Student> students =null;
        try {

            StringBuilder stringBuild = new StringBuilder("SELECT s FROM Student s WHERE s.id !=0 AND s.status="+Constants.StudentStatus.ACTIVE);
            if(studentModel !=null) {
                if(studentModel.getId()!=null) {
                    stringBuild.append("AND s.id =:id");
                }
                if(studentModel.getCourse()!=null) {
                    stringBuild.append("AND s.course =:course");
                }
                if(studentModel.getFirstName()!=null) {
                    stringBuild.append("AND s.firstName =:firstName");
                }
                if(studentModel.getLastName()!=null) {
                    stringBuild.append("AND s.lastName =:lastName");
                }
                if(studentModel.getEmail()!=null) {
                    stringBuild.append("AND s.email =:email");
                }
                if(studentModel.getDateOfBirth()!=null) {
                    stringBuild.append("AND s.dateOfBirth =:dateOfBirth");
                }
                if(studentModel.getStatus()!=null) {
                    stringBuild.append("AND s.status =:status");
                }
                if(studentModel.getAddedAt()!=null) {
                    stringBuild.append("AND s.addedAt =:addedAt");
                }
                if(studentModel.getUserName()!=null) {
                    stringBuild.append("AND s.userName =:userName");
                }
                if(studentModel.getPassword()!=null) {
                    stringBuild.append("AND s.password =:password");
                }
                if(studentModel.getUserType()!=null) {
                    stringBuild.append("AND s.userType =:userType");
                }
            }else {
                throw new Exception("Model is null  ===================" );
            }
            Query query = entityManage.createQuery(stringBuild.toString());

            if(studentModel !=null) {
                if(studentModel.getId()!=null) {
                    query.setParameter("id", studentModel.getId());
                }
                if(studentModel.getCourse()!=null) {
                    query.setParameter("course", studentModel.getCourse());
                }
                if(studentModel.getFirstName()!=null) {
                    query.setParameter("firstName", studentModel.getFirstName());
                }
                if(studentModel.getLastName()!=null) {
                    query.setParameter("lastName", studentModel.getLastName());
                }
                if(studentModel.getEmail()!=null) {
                    query.setParameter("email", studentModel.getEmail());
                }
                if(studentModel.getDateOfBirth()!=null) {
                    query.setParameter("dateOfBirth", studentModel.getDateOfBirth());
                }
                if(studentModel.getStatus()!=null) {
                    query.setParameter("status", studentModel.getStatus());
                }
                if(studentModel.getAddedAt()!=null) {
                    query.setParameter("addedAt", studentModel.getAddedAt());
                }
                if(studentModel.getUserName()!=null) {
                    query.setParameter("userName", studentModel.getUserName());
                }
                if(studentModel.getPassword()!=null) {
                    query.setParameter("password", studentModel.getPassword());
                }
                if(studentModel.getUserType()!=null) {
                    query.setParameter("userType", studentModel.getUserType());
                }
            }
            students = query.getResultList();
        }catch(Exception exe) {
            exe.printStackTrace();
        }
//      LOGGER.info("Students are : " + students);
        return students;
    }

StudentController (Where I am trying to check the username)
@RequestMapping(value="/saveStudent",method = {RequestMethod.POST,RequestMethod.GET})
    public String SaveStudent(@ModelAttribute("studentFormData") Student student,BindingResult errorList) {
        List<Student> students= new ArrayList<Student>();
        try {
            students =studentService.getListOfStudent(student);

            for(Student sts: students ) {
                LOGGER.info("STUDENTS USER NAME :::::::::::::::::::::::" + sts.getUserName());
                if(sts.getUserName().equals(student.getUserName())) {
//                  errorList.addError(new ObjectError("error" , " Username is already taken try this user name " + utils.RandomAlphaString()));
                    LOGGER.info("USER NAME  MATCHED _______________________________________________________________________");
                    errorList.rejectValue("userName", "User name is already in use try with this username : "+ Utils.RandomAlphaString());
                }
            }
            studentService.SaveStudent(student);
            if(errorList.hasErrors()) {
                return "student/studentForm";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/Students/list";
    }

Console:
    antlr.NoViableAltException: unexpected token: s
    at org.hibernate.hql.internal.antlr.HqlBaseParser.queryRule(HqlBaseParser.java:864) [hibernate-core-5.4.30.Final.jar:5.4.30.Final]
    at org.hibernate.hql.internal.antlr.HqlBaseParser.selectStatement(HqlBaseParser.java:336) [hibernate-core-5.4.30.Final.jar:5.4.30.Final]
    at org.hibernate.hql.internal.antlr.HqlBaseParser.statement(HqlBaseParser.java:200) [hibernate-core-5.4.30.Final.jar:5.4.30.Final]
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:294) [hibernate-core-5.4.30.Final.jar:5.4.30.Final]
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:189) [hibernate-core-5.4.30.Final.jar:5.4.30.Final]
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:144) [hibernate-core-5.4.30.Final.jar:5.4.30.Final]
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:113) [hibernate-core-5.4.30.Final.jar:5.4.30.Final]
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:73) [hibernate-core-5.4.30.Final.jar:5.4.30.Final]
    at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:162) ~[hibernate-core-5.4.30.Final.jar:5.4.30.Final]
    at org.hibernate.internal.AbstractSharedSessionContract.getQueryPlan(AbstractSharedSessionContract.java:613) ~[hibernate-core-5.4.30.Final.jar:5.4.30.Final]

java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: s near line 1, column 116 [SELECT s FROM com.Library.LibraryManagement.Entity.Student s WHERE s.id !=0 AND s.status=0AND s.course =:courseAND s.firstName =:firstNameAND s.lastName =:lastNameAND s.email =:emailAND s.dateOfBirth =:dateOfBirthAND s.userName =:userNameAND s.password =:passwordAND s.userType =:userType]
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:138)
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:181)
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:188)
    at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:734)
    at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:114)
    at jdk.internal.reflect.GeneratedMethodAccessor109.invoke(Unknown Source)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:362)
    at com.sun.proxy.$Proxy94.createQuery(Unknown Source)
    at jdk.internal.reflect.GeneratedMethodAccessor109.invoke(Unknown Source)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:311)
    at com.sun.proxy.$Proxy94.createQuery(Unknown Source)
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: s near line 1, column 116 [SELECT s FROM com.Library.LibraryManagement.Entity.Student s WHERE s.id !=0 AND s.status=0AND s.course =:courseAND s.firstName =:firstNameAND s.lastName =:lastNameAND s.email =:emailAND s.dateOfBirth =:dateOfBirthAND s.userName =:userNameAND s.password =:passwordAND s.userType =:userType]
    at org.hibernate.hql.internal.ast.QuerySyntaxException.convert(QuerySyntaxException.java:74)
    at org.hibernate.hql.internal.ast.ErrorTracker.throwQueryException(ErrorTracker.java:93)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:301)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:189)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:144)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:113)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:73)
    at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:162)
    at org.hibernate.internal.AbstractSharedSessionContract.getQueryPlan(AbstractSharedSessionContract.java:613)
    at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:725)
    ... 128 more
org.springframework.transaction.UnexpectedRollbackException: Transaction silently rolled back because it has been marked as rollback-only
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:752)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:711)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:654)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:407)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:750)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:692)
    at com.Library.LibraryManagement.Serviceimpl.StudentServiceImpl$$EnhancerBySpringCGLIB$$9986e406.getListOfStudent(<generated>)
    at com.Library.LibraryManagement.Controller.StudentController.SaveStudent(StudentController.java:66)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:197)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:141)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:894)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1060)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:962)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:652)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:327)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:115)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:81)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:119)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:126)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:81)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:105)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:149)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.base/java.lang.Thread.run(Thread.java:844)

A: I would suggest you - follow another approach to do this work.
Apply a unique constraint to a username column in your database table.
Below is an example of how you can set a unique constraint:
ALTER TABLE Students
ADD CONSTRAINT UC_Username UNIQUE (Username);

For more details, you can refer: https://www.w3schools.com/sql/sql_unique.asp
While saving a new object, if an exception is thrown, then you can simply cancel/ the transaction.
Writing extra code for checking if the username exists or not is not a recommended practice. Simply use database features. It not only serves your purpose but also improves the quality of your database validations.

A: a) SELECT s FROM Student s - that makes even me confused.  select * from ...
b) when you are doing stringBuild.append("AND s.id =:id"); you need to allow for spaces so change to
stringBuild.append(" AND s.id =:id ");
and finally use a NativeQuery
Query query = entityManage.createNativeQuery(stringBuild.toString());


text:
Q: Identify sequential time slots across multiple collections I have a requirement as part of developing a .Net appointment booking engine that is that if someone requires scheduling for multiple, separate, activities that the system suggests potential periods of time where the appointments for all the activities occur sequentially so that the person can attend and do all the activities in one visit.
I have the booking engine working that calculates the available times for individual activities, so if for example someone was doing 3 activities, I would have 3 collections of appointment times. I could use a brute force approach to iterate over the collections, but I wondered if anyone could suggest a more elegant approach to identitfy sequential appointments across all 3 lists?


text:
Q: How to close specific Chrome profile that was opened with cmd/bat? I need to close all windows of a specific Chrome profile. Suppose I execute:
chrome.exe -remote-debugging-port=4000 --user-data-dir=F://chrome

in cmd/bat to open a new Chrome profile. I need to close this specific Chrome profile from cmd/bat.
I have tried this:
taskkill /IM chrome.exe -remote-debugging-port=4000 --user-data-dir=F://chrome

but it's not working.

A: You can accomplish this using the batch file below:
for /f "tokens=3 delims=," %%a in ('wmic process where "caption='chrome.exe'" get processID^,commandline /format:csv ^| FIND "-remote-debugging-port=4000 --user-data-dir=F://chrome"') do set _pid=%%a
taskkill /f /pid %_pid% /t

Explanation

*

*wmic process where "caption='chrome.exe'" get processID^,commandline /format:csv lists all chrome.exe processes with the command line used to launch them and the process ID that we will use to kill it.

*Piping (|) this into FIND "-remote-debugging-port=4000 --user-data-dir=F://chrome" will return only the chrome.exe process started with the command you used.

*for /f "tokens=3 delims=," %%a in ("...") do set _pid=%%a will set the _pid environment variable to the process ID of the process we want to kill.
The wmic command combined with the find command should only give us a single result. If you used the command multiple times, then this will only find the process ID of the last process in the list.

*taskkill /f /pid %_pid% /t:

*

*/f forces the task to end, because otherwise Chrome will remain open.

*/pid %_pid% will supply the process ID we got in the for loop.

*/t tells taskkill to kill the entire process tree.
Since every Chrome tab and extension runs in its own process, we want to make sure these get killed as well.


text:
Q: Row number in Dax I have following DAX code. I need auto increment row number where FileNo and CI_No code are same. I tired with RANKX function but it return rank as 1 for all records. Any one have any idea how we can achieve this using DAX.
Thanks in advance.
Dax code:
DEFINE
VAR A = UNION(   ROW ("FileNo",  10, "CI_No", 101, "Amount" ,100)
                ,ROW ("FileNo",  10, "CI_No", 101, "Amount" ,100)
                ,ROW ("FileNo",  10, "CI_No", 101, "Amount" ,100)
                ,ROW ("FileNo",  20, "CI_No", 201, "Amount" ,200)
                ,ROW ("FileNo",  20, "CI_No", 201, "Amount" ,200)
                ,ROW ("FileNo",  20, "CI_No", 301, "Amount" ,300))

VAR B=  ADDCOLUMNS(A,
         "RowNo", RANKX(
        FILTER(A,
               [FileNo]=EARLIER([FileNo]) &&  [CI_No]=EARLIER([CI_No])
                ),
        [Amount], , DESC
        )        )

 EVALUATE B

Expected Result

A: You can try with mix of AddIndexColumn (from TransformData) and new Calculated column:

RowNo =
          RANKX(
        FILTER( ALLEXCEPT('sample','sample'[RowNo]) , [FileNo] = EARLIER('sample'[FileNo]) &&  [CL_No] = EARLIER('sample'[CL_No]) ),

        [DummySum], , DESC
        )

DummySum = sum('sample'[Index])
EDIT:
Table = VAR A = ADDCOLUMNS(UNION(   ROW ("FileNo",  10, "CI_No", 101, "Amount" ,100)
                ,ROW ("FileNo",  10, "CI_No", 101, "Amount" ,100)
                ,ROW ("FileNo",  10, "CI_No", 101, "Amount" ,100)
                ,ROW ("FileNo",  20, "CI_No", 201, "Amount" ,200)
                ,ROW ("FileNo",  20, "CI_No", 201, "Amount" ,200)
                ,ROW ("FileNo",  20, "CI_No", 301, "Amount" ,300)), "Index", [Amount]+RAND())

VAR B=  ADDCOLUMNS(A,
         "RowNo", RANKX(
        FILTER(A,
               [FileNo]=EARLIER([FileNo]) &&  [CI_No]=EARLIER([CI_No])
                ),
        [Index], , DESC
        )        )

return B


text:
Q: "Detected use of SPRequest for previously closed SPWeb object" within Event receiver but no error when run in test harness I have a very strange issue which I cannot explain. We have and event receiver and within this we instantiate our own class that does all the work we need it to do. As part of this we pass in an SPWEB that we create. The code runs fine but when the code tries to get a list from the passed in SPWEB we get the "Detected use of SPRequest for previously closed SPWeb object" error being shown in the ULS logs.
The SPWeb is only being closed within the event receiver code after our class has done the work.
What is really strange is that if i run the same code from a Unit test no such error occurs so i am wondering if it is either an issue with the W3P process of the way sharepoint handles the threads of event receivers.
Here is the event receiver code
SPSecurity.RunWithElevatedPrivileges(delegate()
{

    SPSite elevatedSite = new SPSite(properties.SiteId);
    SPWeb elevatedWeb = elevatedSite.OpenWeb(properties.RelativeWebUrl);
    try
    {
                  MYClass myCLass = new MyCLass();
                  myClass.DoWork(elevatedWeb); // Cause error in ULS log
            }
            finally
            {
                if (elevatedWeb != null)
                {
                    elevatedWeb.Dispose();
                }
                if (elevatedSite != null)
                {
                    elevatedSite.Dispose();
                }
            }
});

If I run the same code in a unit test where I create a SPWeb object then the code run as I expect without any issues in the ULS logs.
nothing within MYClass calls dispose on the web object
I know I could but the Site and Web in a  using, this does not make a difference to the error appearing or not
I have already used SPDisposeChecker and this shows no issues.
I have gone through a number of posts around correctly disposing of SPWeb objects and believe that my code is doing this correctly
My code is working as expected but I have no idea how to solve this issue or if an issue actually exists. I do not want to release code that may cause a problem on production systems.

A: It looks OK to me, but you could try this:
using (var elevatedSite = new SPSite(properties.SiteId))
{
    using (var elevatedWeb = elevatedSite.OpenWeb(properties.RelativeWebUrl))
    {
        var myCLass = new MyCLass();
        myClass.DoWork(elevatedWeb);
    }
}


text:
Q: get keyerror when trying to remap the keys of a dictionary in python I want to remap or change the keys of a dictionary to 1,2,3,..., since the keys themselves are a bit complicated. Following this post, How do I re-map python dict keys
this is what I did.
tmp=0
for keys in population.items():
        tmp+=1
        population[tmp]=population.pop(keys)

However, I got keyerrors, which generally means the keys does not exist. Can anyone help me please? PS. I did a random sampling with respect to the items of the dictionary population. So I am not exactly sure about what the keys of the dictionary population are.
EDIT: I changed the code. Then it works for a small data set, while it does not quite work for a large one. I added the following code.
for keys, vs in population.items():
        print str(keys)+ "corresponding to" + str(vs)

Here is what I got:
1024corresponding to10
7corresponding to2
855corresponding to4
13corresponding to310
686corresponding to6
22corresponding to172
24corresponding to214
25corresponding to62
26corresponding to18
28corresponding to9
29corresponding to435
30corresponding to210
32corresponding to243
34corresponding to450
859corresponding to8
37corresponding to1
689corresponding to3
43corresponding to53
46corresponding to8
47corresponding to2
48corresponding to7
52corresponding to254
54corresponding to441
820corresponding to3
57corresponding to19
59corresponding to9
61corresponding to3
63corresponding to1
65corresponding to1
66corresponding to6
(0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0)corresponding to7
68corresponding to46842
73corresponding to8
74corresponding to513
75corresponding to52
866corresponding to10
79corresponding to5
80corresponding to712
81corresponding to1
82corresponding to118
83corresponding to15
84corresponding to9
87corresponding to1
88corresponding to7
868corresponding to24
93corresponding to133
94corresponding to9
97corresponding to355
98corresponding to10
99corresponding to9
101corresponding to1
103corresponding to93
114corresponding to3
702corresponding to5
119corresponding to1
121corresponding to1
123corresponding to5
124corresponding to3
125corresponding to3
819corresponding to5
127corresponding to8
131corresponding to137
133corresponding to3
138corresponding to145
139corresponding to3
142corresponding to14
145corresponding to3
147corresponding to6
149corresponding to6
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 3, 0, 0)corresponding to1

EDIT EDIT: I wanted to change all the tuples to numbers to denote the keys of the population dictionary. But after I made the change, and then print out all the keys and values, it still gave me tuples, as you can see from the print out.

A: dict.items() returns a list of key/value pairs (which is why you get the KeyError error when trying to lookup the dict for the tuple instead of the key), what you need is just the keys:
tmp = 0
for k in population.keys():
    tmp += 1
    population[tmp] = population.pop(k)

EDIT: Since for k in dict iterates through a generator of keys, you might get weird behavior when modifying the keys at the same time. To avoid this, I modified the code to use population.keys() instead which returns a list of keys (in python2) instead of a keys generator. In python3 dict.keys() returns a view object instead which should be safe as long as the dict's size isn't changed during iteration (safer to iterate over list(population))

A: Just remove the .items() and this should work.  As larsks says, items returns tuples, but you just want the keys.

A: I still don't undestand this. You have a dict, then you pack all values into a list. By this you already loose all relation between key and value. What would be the purpose for the dict then?
However, to get a list of all values as you seem to want (but also need?), you just do:
my_list = list(my_dict.values())

No need for a loop or anything else.


text:
Q: Find the rows that has the same column I want to know how to do the following in SQL :
SELECT *
FROM table_A
WHERE id IN(:myValues)
AND other_colum has the same value

For example, if i've a conversation table(iduser,idconversation), I want SQL query that returns some of Ids that have the same conversation id. It should return
35;105
37;105
35;106
37;106

With 35,37 the idUsers and 105,106 the conversations they have in common.
To go further, i work with Doctrine and PostegreSQL, and the table that I want to query is generated (many to many relation) but i've difficulty to integrate sub-query.
  **public function getAllCommonConversationByUserId($ids)
  {
      return $this->createQueryBuilder('c')
          ->select('c.id')
          ->innerJoin('c.idUser', 'recievedConversation')
          ->where('recievedConversation IN (:ids)')
          ->andWhere('$qb->expr()->eq("SELECT id FROM table GROUP BY(id) HAVING COUNT(*) >1")')
          ->setParameter(':ids', $ids)
          ->getQuery()
          ->getResult();
  }**

A: Just:
SELECT *
FROM table_A
WHERE idconversation in ('105','106') and iduser in ('35','37')

UPDATE:
Are you saying if the idconversation is duplicate? (showing multiple times?)
If so:
Select *
From table
where idconversation in
(
Select idconversation
From table
group by (idconversation)
Having count(*) >1
)
--where iduser in ('35','37')

A: You can get the conversations using group by and having:
SELECT conversationid
FROM table_A
WHERE userid in (35, 37)
GROUP BY userid
HAVING count(distinct userid) = 2;

If you want the original rows, you can join back to the original table.

A: Try to do this:
select id, conversation
from [your table name]
where
    conversation in (
        select conversation
        from [your table name]
        where id in (35)
    )

It return all of the participants of the conversation with user id = 35
If you have duplicates in your table, please add distinct to select statement.


text:
Q: Plotting density plots on Shiny in R; getting "Error: non-numeric argument to mathematical function" I am building a shiny app and a feature of it involves using density plots to look at the distribution of numerical data. The problem is that when the app is running, I receive this error message when I try to plot:-
Error: non-numeric argument to mathematical function

Here is some mock data:-

outcome<-c("Answered","Abandoned","Engaged")
Duration_A<-floor(runif(300,min=1,max = 2000))
Duration_A
Duration_B<-floor(runif(300,min=200,max = 5000))
Duration_B
Duration_C<-floor(runif(300,min=400,max = 8000))
Duration_C
Center<-c("Center A","Center B","Center C","Center D","Center E","Center F")

df<-as.data.frame(cbind(outcome,Center,Duration_A,Duration_B,Duration_C))
df$Duration_A<-as.numeric(df$Duration_A)
df$Duration_B<-as.numeric(df$Duration_B)
df$Duration_C<-as.numeric(df$Duration_C)

df$Date<-structure(c(18191, 17659, 17592, 18392, 17799, 17781, 18398,
                     17636, 17719, 18085, 18505, 18494, 17580, 18507, 18270, 17613,
                     17559, 17731, 17619, 17578, 17678, 18434, 18265, 18210, 18380,
                     17696, 17617, 17755, 18246, 17684, 18424, 17701, 18236, 17567,
                     18416, 18222, 18293, 18136, 18315, 17762, 17999, 17824, 17715,
                     18487, 18398, 17702, 18428, 18478, 18178, 18110, 18042, 18029,
                     17559, 18281, 18025, 17769, 18160, 17665, 17589, 17867, 18065,
                     18357, 18154, 18483, 18021, 17902, 18527, 17966, 18249, 17751,
                     17971, 18177, 17959, 18522, 18068, 17566, 17973, 18127, 18265,
                     17552, 17889, 18395, 17812, 17898, 18357, 18442, 18454, 17659,
                     17644, 18519, 18547, 17591, 18095, 17847, 17700, 17584, 17745,
                     18182, 18246, 18102, 17689, 17822, 17804, 17597, 18159, 17555,
                     17566, 17770, 17572, 17720, 17753, 18237, 18308, 18410, 17805,
                     17579, 17857, 17698, 17865, 18342, 18338, 17998, 17817, 18128,
                     18249, 18104, 17731, 18418, 17796, 18477, 17824, 17939, 17546,
                     18059, 18496, 18056, 18488, 18394, 18526, 17945, 17998, 18402,
                     17882, 18325, 17744, 18422, 18300, 17601, 18451, 17852, 17560,
                     18238, 17923, 18267, 17593, 18342, 18021, 18075, 18243, 17688,
                     18519, 17737, 17786, 17648, 17705, 18221, 17680, 17631, 17601,
                     17612, 18043, 17534, 17881, 17783, 17716, 17665, 18260, 17918,
                     17805, 18155, 18423, 17688, 17642, 17890, 17953, 17772, 18315,
                     18389, 18167, 18463, 18294, 17773, 18215, 17999, 18520, 17687,
                     17961, 17955, 17955, 17758, 18029, 18055, 17769, 17975, 18556,
                     17745, 17883, 18500, 17812, 18448, 18121, 17740, 18082, 17613,
                     17761, 18030, 18321, 17755, 18047, 18180, 17848, 17756, 17784,
                     18401, 17634, 17823, 18458, 18159, 17753, 17813, 17822, 17685,
                     18374, 18505, 18104, 18501, 17856, 17932, 18246, 18465, 18098,
                     17934, 17737, 17731, 18471, 17899, 18342, 18077, 18317, 17639,
                     17540, 17971, 17798, 17827, 18121, 17641, 18469, 17686, 18239,
                     18309, 18081, 17908, 17897, 18092, 18510, 18551, 17822, 18557,
                     17904, 18170, 18246, 18382, 17766, 18511, 18105, 18381, 18369,
                     17952, 18274, 17709, 18403, 17686, 18401, 17700, 17954, 18217,
                     17935, 17811, 17719, 17885, 17771, 17735, 17555, 17555, 18446,
                     17928, 17748, 17547, 18487, 18221), class = "Date")

Here is the UI:-
ui<-fluidPage(
  titlePanel('Minimal example'),
  tabsetPanel(
    tabPanel("Duration analysis",
             sidebarLayout(
               sidebarPanel(width = 4,
                            dateRangeInput("duration_daterange","Select date range", format="yyyy-mm-dd",
                                           start=min(df$Date),
                                           end=max(df$Date)),
                            pickerInput("duration_col", "Select duration column",
                                        choices = c("Duration_A",
                                                    "Duration_B",
                                                    "Duration_C")),
                            pickerInput("contactoutcome", "Select contact outcome",
                                        choices=c("Answered", "Abandoned", "Engaged")),
                            pickerInput("center_choice", "Select centers",
                                        choices = c("Do not specify",
                                                    "Center A",
                                                    "Center B",
                                                    "Center C",
                                                    "Center D",
                                                    "Center E",
                                                    "Center F"),options = list('actions-box'=TRUE, 'live-search'=TRUE), multiple = T),
                            actionButton("runduration", "Run analysis")

               ),

               mainPanel(
                 column(width = 8, box("Plot", plotOutput("densityplot"), width = "100%"))
               )
             )

    )

  ))#end of fluidpage

And my server:-
  server<-function(input,output,session){

    observeEvent(input$runduration,{

      outcome<-as.character(input$contactoutcome)
      durationcolumn<-as.character(input$duration_col)

        reactiveDF<-reactive({

        if(input$center_choice=="Do not specify"){

          df%>%
            filter(Date>=input$duration_daterange[1] & Date<=input$duration_daterange[2])

        }  else
          if(input$center_choice!="Do not specify"){

            df%>%
              filter(Date>=input$duration_daterange[1] & Date<=input$duration_daterange[2])%>%
              filter(Center %in% input$center_choice)

          }

        })

      output$densityplot<-renderPlot({

      ggplot(reactiveDF(), aes(x=input$duration_col))+
        geom_density()+scale_x_log10()

      })

    })

  }

  shinyApp(ui,server)

Note: if I want to select all centers for analysis, I want it to be executed by stating "Do not specify" in the pickerInput. I'm sure I've made a simple error somewhere but it's not so obvious to me. Any help would be greatly appreciated :)

A: Perhaps you should try this
server<-function(input,output,session){

  observeEvent(input$runduration,{

    outcome<-as.character(input$contactoutcome)
    durationcolumn<-as.character(input$duration_col)

    reactiveDF <- reactive({
      if (is.null(input$center_choice)) {
        data <- NULL
      }else if(length(input$center_choice)==1 &  input$center_choice=="Do not specify") {

        data <- df %>% filter(Date>=input$duration_daterange[1] & Date<=input$duration_daterange[2])

      }else {

        data <- df %>% filter(Date>=input$duration_daterange[1] & Date<=input$duration_daterange[2])%>%
                       filter(Center %in% input$center_choice)

        }
      return(data)

    })

    output$densityplot<-renderPlot({

      ggplot(data=req(reactiveDF()), aes(x=as.numeric(.data[[as.name(input$duration_col)]]))) +
        geom_density()+scale_x_log10()

    })

  })

}


text:
Q: Rails Thinking Sphinx All Results I'm not sure if accomplishing problem is impossible, so help me out. If running a search like this
@things = Thing.search params[:search]

for 'jack' returns all results with relevance 'jack'. and 'sushi' returns all results with relevance 'sushi'. But if i type 'jack sushi' i get only results with both relevance 'jack' and 'sushi'. What if i want all results with either relevance but most relevance higher in my results. (so i if i typed in 'jack sushi' then if something relates to 'jack' but not 'sushi' i still get it as a result)

A: Try a different match_mode.  You could use :any which matches any of the words you type in, or :boolean and search for "jack or sushi".
Example
@things = Thing.search params[:search], :match_mode => :any

Hope this helps.


text:
Q: How to: On click open new page in new tab and redirect the old one Been trying to find some solution but I wasn't able to. I need to get a button to fire two events on one click. This code worked for firefox but it doesn't on Chrome:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>EXAMPLE</title>
  <script type="text/javascript">
      function changeLocation (){
  window.location = "https://www.bing.com";
      }
  </script>
</head>
<body>
<form action="https://www.google.com" target="_blank">
  <input type="text">
  <button onclick="changeLocation()">Submit</button>
</form>
</body>
</html>

I'm trying to redirect users to a new page in new tab and redirect the main page (old one) after the button has been clicked.
Is there any solution which would also work on Chrome?
Would really appreciate any kind of help!

A:

function changeLocation() {
document.getElementById("form").submit();
window.open("https://www.bing.com","_blank");
}
<form id="form" action="https://www.google.com">
<input type="text">
<button onclick="changeLocation()">Submit</button>
</form>

This will help you. By the way you need to use the name attribute in the input tag to submit the data.


text:
Q: Program/script to limit cronjob output Short version: Is there an off-the-shelf program to avoid being pinged repeatedly be frequent cron jobs in periods when they fail? I have a custom implementation but it seems like something someone would have dealt with already.
I have a script on my home server to fetch my mail from my ISP server to store locally. More often than I'd like, Comcast goes down for an hour or so and I get dozens of messages from cron (one every two minutes) reporting that fetchmail failed. I set up a script to read the output of the cron job (blank on success) and always put it into a log file, but only put it to stdout -- and, therefore, my email -- if it's been at least 20 minutes since the last error occurred.
I can't be the only sysadmin with this issue. In short, the job runs frequently and I only want periodic updates while it's failing, not a constant stream of errors. Is there an off-the-shelf solution that I've missed?
Script is as follows; As you can see it's pretty basic, e.g. no indication when the errors stop:
#!/bin/bash
logpath=/var/log/$1.log
minutes=$2
latestlogpath=${logpath}.latest

cat >> "${latestlogpath}"
([ ! -e "${logpath}" ] || [[ $(date +%s -r "${logpath}") -lt $(date +%s --date="${minutes} min ago") ]] ) && {
  cat "${latestlogpath}"
  cat "${latestlogpath}" >> "${logpath}"
  rm "${latestlogpath}"
}


text:
Q: first_or_create causing issues when creating object with non-valid parameters Good morning,
Trying to find the best way to avoid the current situation I am in so..
I have a class A
which has the following attributes a,b,c,d
When create is called on A, I first check to see if an instance of A exists with the following parameters a,b,c.
Now the line I am using to check the database and create if necessary is
@foo = A.where(:a => params[:A][:a], :b => params[:A][:b],:c => params[:A][:c]).first_or_create!

Class A has the following validations for a,b,c
a's length > 3 & < 15
b must be true (checkbox must be checked)
c's length >50 & < 500

When a user is passing in a blank form I will receive errors generated from the above line.
I understand that it is caused by the controller attempting to create an object A that does not meet the validations.
Is the best way to go about this using begin rescue end or error checking pre-first_or_create! ?

A: From your two options is better begin rescue end so you don't repeat code you already have in model.
Another option is to use first_or_create without exclamation mark, so your code does not raise error, and then you could show errors in view. I would say this is equivalent to begin rescue end because you could show show errors in your view in rescue part.


text:
Q: ASP.NET Identity - Get Saved third-party access tokens I have an app that will operate almost entirely on Spotify OAuth, that will have features to alter the playback of your music.
I'm able to get Spotify OAuth working perfectly such that I can log into my app, but after I've logged in, I need access to the current user's spotify access_token so that I can forward it to my spotify requests.
I followed this guide from ms to try to save the tokens: https://learn.microsoft.com/en-us/aspnet/core/security/authentication/social/?view=aspnetcore-6.0&tabs=visual-studio
And I have tried all these ways to then save that token into the HttpContext such that I can access it:
            options.Events.OnCreatingTicket = ctx =>
            {
                List<AuthenticationToken> tokens = ctx.Properties.GetTokens().ToList();

                tokens.Add(new AuthenticationToken()
                {
                    Name = "TicketCreated",
                    Value = DateTime.UtcNow.ToString()
                });
                var spotifyAccessToken = tokens.FirstOrDefault(x => x.Name == "access_token").Value;
                tokens.Add(new AuthenticationToken()
                {
                    Name = "SpofityAccessToken",
                    Value = spotifyAccessToken
                });

//store all the tokens as directed by MS
                ctx.Properties.StoreTokens(tokens);

//store the properties into the HttpContext in 2 different ways
                ctx.HttpContext.Items["Properties"] = ctx.Properties;
                ctx.HttpContext.Features.Set(ctx.Properties);

//try adding a claim to the user
                ctx.Identity.AddClaims(new[] { new Claim("SpotifyAccessToken", spotifyAccessToken) });

                return Task.CompletedTask;
            };

The problem I'm having is how do I then get this token out? all of these methods are not working:
        [HttpGet]
        public async Task Get()
        {
            await HttpContext.SignInAsync(User);
// try to re-run Authenticate, even though i'm already in an [Authorize] controller
            var res = await HttpContext.AuthenticateAsync();
//props2 does not have the tokens i set
            var props2 = res.Properties;

           //props comes back null
            var props = HttpContext.Features.Get<AuthenticationProperties>();

//claims has no SpotifyAccessToken claim
            var claims = User.Claims.ToList();

            var token = "hard-coded";
//here is where i need the token to then query spotify
            var client = new SpotifyAPI.Web.SpotifyClient(token);
            var res2 = await client.Player.GetCurrentPlayback();
        }

I feel like I've tried everything, what am i doing wrong?
This is in a .NET 6 blazor wasm, .net core hosted app.
Also tried the solutions here to no avail Get AuthenticationProperties in current HttpRequest after HttpContext.SignInAsync

A: signInManager.UpdateExternalAuthenticationTokensAsync adds the the authentication tokens in [dbo].[AspNetUserTokens]
External login is where I call it:
// Sign in the user with this external login provider if the user already has a login.
        var signInResult = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: true, bypassTwoFactor: true);
        if (signInResult.Succeeded)
        {
            await _signInManager.UpdateExternalAuthenticationTokensAsync(info);
            _logger.LogInformation("{Name} logged in with {LoginProvider} provider.", info.Principal.Identity.Name, info.LoginProvider);
            return LocalRedirect(returnUrl);
        }

Later on you can get it by using :
            var token = await userManager
            .GetAuthenticationTokenAsync(user, "Spotify", "access_token");

        var expiresAtStr = await userManager
            .GetAuthenticationTokenAsync(user, "Spotify", "expires_at");

A: If the token is stored in the Cookie then you can access the various tokens using:
string accessToken = await HttpContext.GetTokenAsync("access_token");
string idToken = await HttpContext.GetTokenAsync("id_token");
string refreshToken = await HttpContext.GetTokenAsync("refresh_token");
string tokenType = await HttpContext.GetTokenAsync("token_type");
string accessTokenExpire = await HttpContext.GetTokenAsync("expires_at");

However, you can not store data in ctx.HttpContext and assume it will be persisted across requests. either you sign-in the user using the cookie middleware or you store the tokens in the UserSession object.
See this article on how to configure and store data in the session, that will be persisted across requests.
Session and state management in ASP.NET Core
If you configure it properly, then you can use it like:
HttpContext.Session.SetString("token", token.Trim());


text:
Q: Complex vectors in Hilbert space, or, how much is 0.707^2 + (0.707i)^2? I am reading Hidden In Plain Sight 10: How To Program A Quantum Computer (https://www.amazon.com/Hidden-Plain-Sight-10-Computer-ebook/dp/B07GPRBYVC).
There is something I don't understand.
In chapter 5, the author presents the projection of a complex vector on a coordinate system in Hilbert space (I hope I expressed it correctly...).
As I understand, the author claims that the vector 0.707 + 0.707i has a magnitude of 1.0, because, supposedly, 0.707^2 + (0.707i)^2 = 1.0.
But, 0.707^2 + (0.707i)^2 equals 0 (according to my understanding, and according to https://www.google.com/search?q=0.707%5E2%2B%280.707i%29%5E2).
So there must be something I misunderstand in the explanation. The author's explanation includes a diagram, so I'm adding it here as an image:

What is my mistake?

A: A complex number $a + bi$ has a real part that is $a$.  $a$ is a real number.  And a complex number has an imaginary part that is $b$.  The imaginary part is also a real number.  It does not include the $i$.  It is the "coefficient" of the $i$.
When he says we square the real part and square the imaginary part and add them together you are squaring $a$ and $b$ and getting $a^2 + b^2$.  You are not squaring $a$ and $bi$.
So in this case $|0.707 + 0.707i| = \sqrt{ 0.707^2 +0.707^2} =\sqrt{\frac 12 + \frac 12} = 1$.


text:
Q: How to find an exact set of strings in a column of varied strings in R dataframe? I'm looking to find a match of an exact bunch of strings in a R dataframe column containing strings.
Here's the format in which I have my bunch of reference strings which will be stored in the variable splitval:
library(gsubfn)
#Splitting each rule into its individual parameter elements
str <- strsplit(gsub("\\,\\+"," +", gsub("=>","",  gsubfn(".", list("{" = "", "}" = ""), gsub("corpsi", "+corpsi", "{dog} => {pet}")))), split='+', fixed=TRUE)
parameters <- data.frame(do.call(rbind, str)) #Creating a df of the split parameters
parameters <- data.frame(t(parameters))
parameters <- parameters[parameters$t.parameters.!="",]
parameters <- trimws(parameters, "r")

#Applying filter on all the parameters of a single rule row
splitval = strsplit(parameters[1],split=' ', fixed=TRUE)
splitval = lapply(list(splitval[[1]]), function(z){ z[z != ""]}) #Eliminating the "" instances

So now, splitval has the following value:
[[1]]
[1] "dog" "pet"

Now my objective is to filter out all those row entries of the following dataframe where the string column's entries have both the exact words dog and pet.
Note: It should not filter out strings containing phrases like doganimal pets or dogsareanimals and petssss
This is my dataframe:
df <- data.frame(Srno = 1:5, Description = c("dog is my pet", "doganimal pets country", "my pet is my dog", "dogsareanimals and petssss", "a pet dog is great"))

Which looks like this:

Hence, I need only rows 1,3 & 5 in my extract since only these contain the exclusive strings "dog" and "pet" together (in no specific order)
But when I use the following code, I get all the rows of the dataframe since all the strings contain the two keywords of reference - grep is not serving the intended purpose.
extract_df <- df[(grep(splitval[[1]][1], df$Description)),]
  for(k in 2:length(splitval[[1]]))
  {
    extract_df  <- extract_df[(grep(splitval[[1]][k], df$Description)),]
  }

So can anyone help me to get only rows 1,3 & 5 in the output extracted dataframe?

A: Assuming that splitval can have many words in it and will not always have two fixed words in it you can split string for each word and select rows that have all the words in vec.
In base R you can do this as :
vec <- splitval[[1]]
#For this case
#vec <- c("dog", "pet")

subset(df, sapply(strsplit(df$Description, '\\s+'), function(x) all(vec %in% x)))

#  Srno        Description
#1    1      dog is my pet
#3    3   my pet is my dog
#5    5 a pet dog is great

Using tidyverse :
library(tidyverse)
df %>% filter(map_lgl(str_split(df$Description, '\\s+'), ~all(vec %in% .x)))


text:
Q: Can I use a std::string variable as an argument to an operator? For example, if I have:
#include <iostream>

using namespace std;

int main()
{
    int b = 1;
    int c = 2;
    string a = "(b + c)";

    cout << (4 * a) << "\n";

    return 0;
}

Is it possible to have string a interpreted literally as if the code had said cout << (4 * (b + c)) << "\n";?

A: No. C++ is not (designed to be) an interpreted language.
Although it's theoretically possible to override operators for different types, it's very non-recommended to override operators that don't involve your own types. Defining an operator overload for std::string from the standard library may break in future. It's just a bad idea.
But, let's say you used a custom type. You could write a program that interprets the text string as a arithmetic expression. The core of such program would be a parser. It would be certainly possible, but the standard library doesn't provide such parser for you.
Furthermore, such parser wouldn't be able to make connection between the "b" in the text, and the variable b. At the point when the program is running, it has no knowledge of variable names that had been used to compile the program. You would have to specify such information using some form of data structure.
P.S. You forgot to include the header that defines std::string.

A: #include<string>
///...
auto a=std::to_string(b+c);
std::cout<<4*std::stoi(a)<<std::endl;

You can just use std::string and std::stoi.


text:
Q: How many unused inputs are there in a BCD adder? My book provides this BCD adder with the truth table:

Since this is meant to add number in BCD there are combinations that aren't going to be used. My book asks to calculate how many of such combinations are there. I did:
$$[(6*9)*2+(6*6)*2]*2 = 360$$
6*9 is the valid ones times the invalid ones. 6*6 is the invalid ones. I multiply each of these by two because you can have them one way around or the other. Lastly I multiplied by 2 because the input carry can be either 1 or 0.  But my book says the solution is 312. What went wrong?

A: Like you commented, you have to multiply with 10 instead of 9.
There is however another point incorrect.
You need to add the invalid ones times the invalid ones once, so
$$[(6*\color{red}{10})*2+(6*6)*\color{red}{1}]*2 = 312$$
To link your approach with Jonk's approach:
Defining variable a the number of valid BCD codes (a=10), b the number of invalid BCD codes (b=6) and a+b (therefore) the total number of codes,
Jonk's approach is
$$ 2*((a+b)^2-a^2) $$
Rewriting
$$ 2*((a+b)^2-a^2) = $$
$$ 2*(a^2+2ab+b^2-a^2) = $$
$$2*( 2ab + b^2 ) $$
which is your approach.


text:
Q: Close submenu when clicked on other submenu I am using antd menu and submenu. and i am unable to close the submenu when other sumbenu is opened. I am using react js for the code.I am able to close main menu on other menu expansion. but have no idea how to close submenu on other submenu expansion. Here is my code
    <Menu
                    style={{ width: 220 }}
                    mode="inline"
                    openKeys={openKeys}
                    onOpenChange={onOpenChange}
                    selectedKeys={[location.pathname]}
                    title="Navigation"
                    className="custom-menu"
                  >
                    {navigationConfig.map((menu) => {
                      return (
                        <>
                          {menu.submenu.length > 0 ? (
                            <SubMenu
                              icon={menu.icon ? <Icon type={menu?.icon} /> : null}
                              key={menu.key}
                              title={menu.title}
                            >
                              {menu.submenu.map((submenu) => {
                                return (
                                  <Menu.Item
                                    key={submenu.key}
                                    onClick={submenu.onclick}
                                  >
                                    {submenu.icon ? (
                                      <Icon type={submenu?.icon} />
                                    ) : null}
                                    {submenu.title}
                                    {submenu.path ? (
                                      <Link
                                        to={{
                                          pathname: submenu.path,
                                          state: history.location.state,
                                        }}
                                        onClick={() => {
                                          setHeaderTitle(
                                            menu.hasOwnProperty("aliasTitle")
                                              ? menu.aliasTitle
                                              : menu.title
                                          );
                                        }}
                                      />
                                    ) : null}
                                  </Menu.Item>
                                );
                              })}
                            </SubMenu>

                            </Menu.Item>
                          )}
                        </>
                      );
                    })}
                  </Menu>


text:
Q: How to disable conversion of 0/1 to true/false in jackson 2.9.x I have a project that needs a strict json policy.
Example:
public class Foo {
    private boolean test;

    ... setters/getters ...
}

Following json should work:
{
    test: true
}

And following should fail (throw exception):
{
    test: 1
}

same for:
{
    test: "1"
}

Basically I want the deserialization to fail if someone provides something different than true or false. Unfortunately jackson treats 1 as true and 0 as false. I couldn't find a deserialization feature that disables that strange behavior.

A: Can disable MapperFeature.ALLOW_COERCION_OF_SCALARS
From docs

Feature that determines whether coercions from secondary
  representations are allowed for simple non-textual scalar types:
  numbers and booleans.

If you also want it to work for null, enable DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES (More Info)
ObjectMapper mapper = new ObjectMapper();

//prevent any type as boolean
mapper.disable(MapperFeature.ALLOW_COERCION_OF_SCALARS);

// prevent null as false
// mapper.enable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES);

System.out.println(mapper.readValue("{\"test\": true}", Foo.class));
System.out.println(mapper.readValue( "{\"test\": 1}", Foo.class));

Result:
 Foo{test=true}

 Exception in thread "main"
 com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot
 coerce Number (1) for type `boolean` (enable
 `MapperFeature.ALLOW_COERCION_OF_SCALARS` to allow)  at [Source:
 (String)"{"test": 1}"; line: 1, column: 10] (through reference chain:
 Main2$Foo["test"])


text:
Q: How can I find out what version of Debian a particular version of Ubuntu is based on? My understanding is that Ubuntu is based on Debian. For example, on the Wikipedia page for Ubuntu it states "It is a Linux distribution based on the Debian architecture." How can I find out what version of Debian a particular version of Ubuntu is based on (if any)?
For example, the current stable release of Ubuntu is "Artful Aardvark" (17.10) which announces that it is based on the Linux 4.13 kernel, but does not seem to say anything about the Debian version.
The current stable release of Debian is code named "Stretch" (9.2) which advertises a 4.9 kernel (on the afore-linked Stretch page). How can I find out the details of the relationship between them? Is there a particular command that will reveal this information?

A: Ubuntu normally imports packages from Debian unstable until the "Debian import freeze". For earlier LTS releases they chose to import from Debian testing instead but nowadays all releases (both LTS and non-LTS) import from unstable. You can find the date of the "Debian import freeze" by looking at the "release schedule" pages. For example according to https://wiki.ubuntu.com/ArtfulAardvark/ReleaseSchedule the Debian import freeze happened on the 24th August 2017.
However for many core packages Ubuntu makes their own descisions and often ends up with newer versions because they have less concerns about supporting esoteric architectures and configurations. For example at the time of Artful's Debian import freeze Debian sid had Linux kernel 4.12 but Ubuntu Artful shipped with 4.13.

A: Ubuntu releases aren't based on Debian releases. During the development of an Ubuntu release, packages are imported from Debian unstable, until the Debian import freeze (in the past, LTS releases imported from testing, and this is what the linked wiki page still suggests; however looking at my packages shows that 18.04 is importing packages from unstable). This means that a given Ubuntu release will have non-Ubuntu-maintained packages in whatever version was in Debian at the time of the import freeze (barring explicit sync requests); but that doesn't match what the next release of Debian will contain.
So trying to tie a release of Ubuntu to a release of Debian would just end up being misleading.
You can look at the contents of /etc/debian_version to see the Debian codename of the version (under construction) from which packages were pulled; you can also match Debian import freeze dates from the release schedules (for example, Artful's, Bionic's, Cosmic's, or Disco's). You'll see from this that the same Debian release feeds multiple Ubuntu releases (e.g. Stretch, which ended up being Debian 9, fed Xenial, Yakkety, Zesty and Artful; Buster, which will end up being Debian 10, fed Bionic and Cosmic, and is feeding Disco), with quite different package versions each time.


text:
Q: purpose of program I need to compile some code for a project and I am getting a lot of errors, not because the code is written wrong, but I think there are variables I am supposed to substitute in before attempting to compile. The actual code is a bit longer, as it was designed for parallel-computing, but below is a more simple version without parallelism.What is the purpose of this program and what are the input variables:
int main(int argc, char *argv[]) {
  int n = ...;
  float *x, *y;
  x = new float[n+1];
  y = new float[n+1];

  ... // fill x, y

  // do computation
  float e = 0;
  for (int i=1; i<n; ++i) {
   x[i] += ( y[i+1] + y[i-1] )*.5;
   e += y[i] * y[i];
  }

  ... // output x, e

  delete[] x, y;
  return 0;
}

A: OK. It seems that the code is mainly for example or proof-of-concept.
I guess Parallel For is about it's special "ForEach" Function, and some data grids...
I modified one of the samples on the site (if anyone would like a more readable example).
Taken from Here
int main(int argc, char *argv[]) {

    int Repeat = 100000;        // Will perform the computation 100,000 times.

    Grid1 *Grd = new Grid1(0, Repeat+1);
    DistArray X(Grd), Y(Grd);   // Some data grid arrays (used for the computations)

    // Set X and Y...
    ForEach(int i, it,
    X(i) = 0;
    Y(i) = 1*i; )

    Grid1IteratorSub it(1, Repeat, Grd);

    float E = 0;    // One of the return values

    // Do the computations:
    ForEach(int i, it,
    X(i) += ( Y(i+1) + Y(i-1) )*.5;
    E += sqr( Y(i) ); )

    // Output the modified data:
    cout << "X: " << X;
    cout << "E: " << E;

    return 0;

}

** Edited after seeing Parallel For


text:
Q: Recognize Image clicking over in Raphael I have a canvas where using raphael I'm going to draw some images.
The images's names are in a list: images_list and I will draw three images for row. All the images have the same dimensions, are equaly spaced and are .png files (no vector).
Some example code:
var paper_images_list = Raphael(canvas_images_list, '100%', '100%');
var images_for_row=3
var y_max=Math.ceil(image_list.length/images_for_row)*40
paper_images_list.setSize(div_width, y_max);
for (var i=0; i<image_list.length; i++) {
        var col=parseInt(i/images_for_row)
        var y=col*40
        var x=(i-images_for_row*col)*40
        var image = paper_images_list.image('/media/images/'+image_list[i], x, y, 33, 27);
    };

What I want: clicking on an image I want to know which image that is, for use it in another paper/canvas.
I'm using Raphael because I thinked it could make that easy but maybe I'm wrong. Is it possible to recognize the image just clicking over it?
If not, I can find the coordinates of the click and calculate which image there is, but I don't need Raphael for that, right? There are better solutions?
I'm using Phyton3.5, Django 1.9, Javascript/JQuery, Windows7

A: Thanks to Ian I found it's so simple like:
document.getElementById('canvas_images_list').onclick=function(event) {
    var myimage = event.target
    if (myimage.tagName == 'image') {
        myimage = myimage.href.baseVal;
    };
};

The if statement excludes the clicks outside any images


text:
Q: Node Postgres Multiple Queries I have a query:
const getRunsByProjectTable = {
  text: 'Select pvt(); Execute pvtstmt;'
} ;

const getRunsByProjectTable = (req, res) => {
    pool.query(queries.getRunsByProjectTable, (error, results) => {
        if (error) throw error;
        res.status(200).json(results.rows);
    })
}

It does not return anything but on pgAdmin, I am getting the desired table. Does anyone know what the problem may be?