text:
Q: get singleton instance I am testing Ninject and trying to understand how to inject repository to singleton class.
Below is working repository and singleton class example...
public interface ITestRepository
{
   void TestRepositoryMethod();
}

public class TestRepository:ITestRepository
{
    public void TestRepositoryMethod()
    {

    }
}

public class TestSingletonInjectionClass
{
    private readonly ITestRepository _repository;

    public TestSingletonInjectionClass(
        ITestRepository repository)
    {
        _repository = repository;
    }

    public void TestMethod()
    {

    }
}

The test method which pass sucesfully
[TestMethod]
public void SimpleTestSingleton()
{
    using (IKernel kernel = new StandardKernel())
    {
        kernel.Bind<ITestRepository>().To<TestRepository>();
        var testSingletonInjectionClass =
            kernel.Get<TestSingletonInjectionClass>();\

        Assert.IsNotNull(testSingletonInjectionClass);
    }
}

I have two questions
1. Is this correct method to get singleton class instance?
 kernel.Get<TestSingletonInjectionClass>()

2. How to get singleton instance class from app code. In test method I create Ninject Kernel and access Get method. How to access ninject kernel form code?

A: You have to configure the the class is a singleton:
kernel.Bind<TestSingletonInjectionClass>().ToSelf().InSingletonScope();

In the implementations you get it by passing it to the constructor of the consuming class.
public class Foo
{
    public Foo(TestSingletonInjectionClass testSingletonInjectionClass)
    {
        this.testSingletonInjectionClass = testSingletonInjectionClass;
    }
}

A: As you can read on ninject documentation (https://github.com/ninject/ninject/wiki/Object-Scopes) a "InSingletonScope" creates a "Singleton Style of life", not a traditional singleton. The documentation says:
"Only a single instance of the type will be created, and the same instance will be returned for each subsequent request."
This means you will have only one instance x container. If anyone uses another container, will get another instance.


text:
Q: Why there is an extra index when using apply in Pandas When I use apply to a user defined function in Pandas, it looks like python is creating an additional array. How could I get rid of it? Here is my code:
def fnc(group):
    x = group.C.values
    out = x[np.where(x < 0)]
    return pd.DataFrame(out)

data = pd.DataFrame({'A':np.random.randint(1, 3, 10),
                     'B':3,
                     'C':np.random.normal(0, 1, 10)})

data.groupby(by=['A', 'B']).apply(fnc).reset_index()

There is this weird Level_2 index created. Is there a way to avoid creating it when running my function?
    A   B   level_2   0
0   1   3   0        -1.054134802
1   1   3   1        -0.691996447
2   2   3   0        -1.068693768
3   2   3   1        -0.080342046
4   2   3   2        -0.181869799

A: As such, you will have no way to avoid level_2 appearing. This is because the result of your grouping is a dataframe with several items in it: pandas is cool enough to understand your wish is to broadcast these items across the grouped keys, yet it is taking the index of the dataframe as an additional level to guarantee coherent output data. So dropping level=-1 at the end of your processing explicitly is expected.
If you want to avoid to reset that extra index, but still have some post processing, another way would be to call transform instead of apply, and get the returned data from fnc being the entire group vector where you put np.nan for results to exclude. Then, your dataframe will not have an extra level, but you'll need to call dropna() afterwards.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why can't I step into this line? Math.Sign(int.MaxValue);

I hit F11 to step into it and it steps right over it. I have all the options set for debugging .NET framework source (I think).
Edit: for someone with Visual Studio 2008 SP1 and .NET 3.5 SP1 who can step into this line successfully: what is the size of your .pdb file?
Edit 2: because I can successfully step into System.Windows.Forms, I'm fairly certain I have a corrupted symbol cache, but every time I try to reload the symbols, it re-downloads as only 763KiB.
Edit 3: Is it possible that it I can't step into System.Math.Sign because System.Math source code simply isn't released/available?

A: You need to load the symbols for mscorlib.dll first.
Click Debug, Windows, Modules, then right-click on mscorlib.dll and click Load Symbols.
Then, try again.  FYI, the simplest way to make sure that .Net source debugging is working is to try to view the source of a method in your call stack.

A: I couldn't step into some code because I didn't realise I was using a mock. :)


text:
Q: Why MD5 hashing is being frequently used for preventing of loading of outdated CSS, JavaScript and media files? I understand why we need to make the names of CSS, JavaScript and media files like images unique when building the project for production. I don't understand why the using of MD5 for this effect reaching is so popular, for example:

*

*In Webpack

*In Gulp
To generate the filename like main.7e2c49a622975ebd9b7e.js, we need to read the file and create the MD5 has of the content. Seems like it will take a lot of time, especially in HD images and videos case.
There are some other alternatives how to generate the unique file name:

*

*Using the UNIX timestamp

*Using the Math.random()
Just two instances, but I don't see the reason to explore more.

A: A primary reason is that if the files contents don't change, the hash won't change. And if the hash doesn't change that means your users' browsers won't have to download the files after your next deployment (as the browser has cached the file from a previous pageload).
If you used timestamp, every filename would change for every deployment, resulting in your users' browsers having to redownload every file in your project...even files whose content did not change. This can have a hugely negative performance hit if you are deploying code frequently.


text:
Q: Grouping by partial value I'm very new to SQL and I have no clue how to even begin with this one.
I've got two tables: Warehouse and Items. Here's how they look like(simplified):
Warehouse
ItemID | QuantityInStock | QuantityOnOrder | QuantityOnOrder2 | QuantityOnOrder3 | QuantityOnOrder4
-------+-----------------+-----------------+------------------+------------------+-----------------
1111   |               8 |               1 |                0 |                1 |               0
2222   |               3 |               0 |                0 |                0 |               0
3333   |               4 |               0 |                1 |                0 |               0

Items
ItemID | Code
-------+-----------------
  1111 | abc123456-111-01
  2222 | abc123456-111-02
  3333 | abc123457-112-01

What I need to return via SQL query is this:
ShortCode | Quantity
----------+---------
abc123456 | 9
abc123457 | 3

*

*ItemID is the key to join both tables

*Code in the Items table include main product code (abc123456) and variants (-111-01). I need to group the lines by main product code only

*Quantity I need comes from Warehouse table and it equals "QuantityInStock - QuantityOnOrder - QuantityOnOrder2 - QuantityOnOrder3 - QuantityOnOrder4". Using this we get abc123456 (comes in two variants in Items table with ItemId 1111 and 2222) and Quantity is equal 8 minus 1 minus 0 minus 1 minus 0 for 1111, and 3 minus 0 minus 0 minus 0 minus 0 for 2222 which together gives 9

This is probably the worst explanation ever, so I hope there is someone that can understand it.
Please help.

A: Assuming that you can always count on matching the first 9 characters of the Code column then the following query should work.
/// note that the SUM method may return a negative (-) number
SELECT LEFT(I.[Code], 9) AS 'ShortCode', SUM([QuantityInStock] - [QuantityOnOrder] - [QuantityOnOrder2] - [QuantityOnOrder3] - [QuantityOnOrder4]) AS 'Quantity'
FROM [dbo].[Warehouse] AS W
INNER JOIN [dbo].[Items] AS I ON I.[ItemId] = W.[ItemId]
GROUP BY LEFT(I.[Code], 9)

A: Using standard SQL:
SELECT
  LEFT(Items.Code, 9) AS ShortCode,
  SUM(T.remaining) AS Quantity
FROM Items
JOIN (
  SELECT
    ItemID,
    QuantityInStock - QuantityOnOrder - QuantityOnOrder2 - QuantityOnOrder3 - QuantityOnOrder4 AS remaining
  FROM Warehouse
) AS T ON (T.ItemID = Items.ItemID)
GROUP BY LEFT(Items.Code, 9);

Not tested, but should work. Only potential issue is that you use uppercase letters in your table and column names, so you might have to enclose all table and column names in backticks (`) or square brackets depending on your DB server.
EDIT: If you want to filter those with less than a certain number of pieces left, just add:
HAVING SUM(T.remaining) > xxx

Where xxx is the minimum quantity you want


text:
Q: How can I specify a typed object literal in TypeScript? Is there a way to make a typed object literal directly?
By directly I mean without having to assign it to a variable which is type annotated.
For example, I know I can do it like this:
export interface BaseInfo { value: number; }

export interface MyInfo extends BaseInfo { name: string; }

function testA(): BaseInfo = {
   const result: MyInfo = { value: 1, name: 'Hey!' };
   return result;
}

I also can do it like this:
function testB(): BaseInfo = {
   return { value: 1, name: 'Hey!' };
}

But what I need is something like:
function testC(): BaseInfo = {
   return { value: 1, name: 'Hey!' }: MyInfo; // <--- doesn't work
}

Or like this:
function testD(): BaseInfo = {
   return MyInfo: { value: 1, name: 'Hey!' }; // <--- doesn't work
}

A: Intellisense for members of object literals is provided by the contextual type (see section 4.19 of the spec) of the expression.
You can acquire a contextual type in a variety of ways. Some of the most common places where a contextual type is applied are:

*

*The initializer of a variable with a type annotation

*The expression in a return statement in a function or getter with a return type annotation

*The expression in a type assertion expression (<T>expr)

In your example, you can use a type assertion to force your object literal to have a contextual type:
function testB() {
   return <IMyInfo>{ name: 'Hey!' };
}

A: Remember that that interfaces follow duck typing: if an object looks like it matches the interface, it does match the interface.
So
function testB(): IBaseInfo = {
   return { name: 'Hey!' };
}

is exactly the same as
function testA(): IBaseInfo = {
   var result: IMyInfo = { name: 'Hey!' };
   return result;
}

Either way, the returned object looks like an IMyInfo, so it is an IMyInfo. Nothing that happens inside the function affects what interfaces it matches.
However, in your examples, the return value of the function is IBaseInfo, so the compiler and intellisense will assume that the object is just an IBaseInfo. if you want the caller of the function to know that the return value is an IMyInfo, you need to make the return value of the function IMyInfo:
function testB(): IMyInfo = {
   return { name: 'Hey!' };
}

or using type inference, simply
function testB() = {
   return { name: 'Hey!' };
}

A: To be really type-safe there are these ways:
Example interface:
interface IFoo {
  firstName: string;
  lastName: string;
}

specify the function result type
function useResultType(): IFoo {
  return {
    firstName: 'mars'
    // compile error, when lastName is missing
    // , lastName: 'xx'
  };
}

return a constant
function resultVariable() {
  const result: IFoo = {
    firstName: 'mars'
    // compile error, when lastName is missing
    // , lastName: 'xx'
  };
  return result;
}

use a generic identity function (note: rxjs has an identity function)
function ident<T>(value: T): T {
  return value;
}
function identityFunction() {
  return ident<IFoo>({
    firstName: 'mars'
    // compile error, when lastName is missing
    // , lastName: 'xx'
  });
}

when you just use type assertions - the compiler will not show an error when you return any other type (e.g. in the examples, I "forgot" the lastName member)
function asCast() {
  return {
      firstName: 'mars'
    // NO error
  } as IFoo;
}

function cast() {
  return <IFoo>{
      firstName: 'mars'
    // NO error
  };
}

you can check the examples in the Typescript Playground

A: Answer is to use the identity function:
function to<T>(value: T): T { return value; }
const instance = to<MyInfo>({
    value: 1,
    name: 'Hey!',
});

there should be no performance impact for an unnecessary call the to function, it should be optimized away by the JIT compiler
UPDATED on Sept 22, 2022:
At last TypeScript team made a tool for it:
const instance = { value: 1, name: 'Hey!' } satisfies MyInfo;

Read more: https://github.com/microsoft/TypeScript/issues/47920
Some screenshots:

A: Your first and second examples fail, so yo can't do that. :)
Pretty sure you don't have to specify any types on your literal. As long as your literal meets the interface requirements, you're good.
interface IMyInfo { name: string; }
var asdf = {
   name: "test"
}

var qwer: IMyInfo = asdf;

If you want intellisense, you have to do something like:

Or maybe this is what you're looking for. Intellisense works here, at least on the playground.

Or maybe this. :)


text:
Q: Why is the instance variable not getting changed? class Player:
    def __init__(self, Name, Age, Sex):
        self.Name = Name
        self.Age = Age
        self.Sex = Sex

        self.validate(Name,Age,Sex)

    @classmethod
    def validate(cls, Name, Age, Sex):
        if (not isinstance(Age,int)) or Age < 0:
            Age = int(input('Please input a valid integer greter than 0'))
            return cls(Name,Age,Sex)

    def showDetails(self):
        return f'Player name: {self.Name}. Player age: {self.Age}'

a = Player('Nail',-25,'F')
a.showDetails()

Output:
Please input a valid integer greter than 0 20
'Player name: Nail. Player age: -25'

The variable Age is not changing. It remains on its initial state.

A: You almost got it. As some comments point, validate can't have access to the specific member of an instance of the object because it is a class method. You can do instead
def __init__(self, Name, Age, Sex):
    self.Name = Name
    self.Age = self.validate(Age)
    self.Sex = Sex

def validate(self, Age):
    while (not isinstance(Age, int)) or Age < 0:
        Age = int(input('Please input a valid integer greter than 0: '))
    return Age

That said, if the validation is as simple as checking inequalities, you could just stick the operation inside of the constructor without the need for an auxiliary function. Something like this:
def __init__(self, Name, Age, Sex):
    while (not isinstance(Age, int)) or Age < 0):
        Age = int(input('Please input a valid integer greter than 0: '))

    self.Name = Name
    self.Age = Age
    self.Sex = Sex

A: The main problem with your code is that you are incorrectly using a class method, which doesn't have access to the instance variables that needs to be validated and replaced. Review the related post on the Difference between class and instance methods to understand what a class method is and what it's for.
Furthermore, your code
return cls(Name,Age,Sex)

instantiates a new, different object, different from the original one that was just instantiated with the invalid Age, and, as tadman pointed out in the comments, can lead to a continuous chain of instantiation, validation, instantiation, ... etc. which doesn't even modify the original instance. This is definitely not what you want.
The simple, yet a bit naive solution, would be to replace your class method with an instance method and then use a regular while loop to keep prompting for input until you get a valid Age, similar to what's demonstrated in JustLearning's answer:
In [4]: class Player:
   ...:     def __init__(self, Name, Age, Sex):
   ...:         self.Name = Name
   ...:         self.Age = Age
   ...:         self.Sex = Sex
   ...:
   ...:         self.validate()
   ...:
   ...:     def validate(self):
   ...:         while (not isinstance(self.Age, int)) or self.Age < 0:
   ...:             self.Age = int(input('Please input a valid integer greter than 0'))

But, while that certainly works, it's highly unusual and a bit of code smell to have an input prompt as part of instantiating a class. The better practice would be prompting for Age and getting all the other variables before instantiating the class, as part of a separate function. Your class should just act like a container for a Player's details and functions, and this would also make it much easier to write unit tests for the Player class.
Furthermore, doing int(input(...) can possibly raise a ValueError Exception if the input isn't a valid integer. Checking with isinstance would not properly handle non-integer inputs. See Asking the user for input until they give a valid response for better ways to validate.
My alternative solution would be:
In [22]: class Player:
    ...:     def __init__(self, Name, Age, Sex):
    ...:         self.Name = Name
    ...:         self.Age = Age
    ...:         self.Sex = Sex
    ...:
    ...:     def showDetails(self):
    ...:         return f'Player name: {self.Name}. Player age: {self.Age}'
    ...:

In [23]: def get_age():
    ...:     while True:
    ...:         try:
    ...:             Age = int(input('Please input a valid integer greater than 0 '))
    ...:         except ValueError:
    ...:             continue
    ...:         if Age < 0:
    ...:             continue
    ...:         else:
    ...:             break
    ...:     return Age
    ...:

In [24]: Age = get_age()
Please input a valid integer greater than 0 -5
Please input a valid integer greater than 0 -16
Please input a valid integer greater than 0 notinteger
Please input a valid integer greater than 0 22

In [25]: a = Player('Nail',Age,'F')

In [26]: a.showDetails()
Out[26]: 'Player name: Nail. Player age: 22'

If somehow you really still want your class to do some validation, it should just raise some form of an Exception if it gets invalid input, and then let your outer code handle it.
In [32]: class Player:
    ...:     def __init__(self, Name, Age, Sex):
    ...:         self.Name = Name
    ...:         self.Age = Age
    ...:         self.Sex = Sex
    ...:         self.validate()
    ...:
    ...:     def validate(self):
    ...:         if (not isinstance(self.Age, int)) or self.Age < 0:
    ...:             raise ValueError("Age should be int and >0")

In [36]: try:
    ...:     Age = get_age()
    ...:     a = Player('Nail', Age, 'F')
    ...: except ValueError:
    ...:     print("Cannot instantiate Player, invalid details")

Finally, since this answer is all about best practices, you should follow PEP8 Style Guide for Naming Conventions and use all-lowercase for function parameters and instance variable names:
class Player:
    def __init__(self, name, age, sex):
        self.name = name
        self.age = age
        self.sex = sex

Only use uppercase/CapWords style Age only if Age is a class.


text:
Q: Elasticsearch find by field if exist. Native or Yii2 how i can create a query for next case:
i have few types: posts, comments, users and other
And need search by room_id IN(1,2,3,4) and query = ***
But if field room_id not exist - just skip it. For example type "user" without room_id and i whant select all user data only by query. But if this field exist - then check room_id
I use PHP + Yii2, but native code will be ok too
How create this query? Thanks
PS: more simple description
need select data from different types, by different conditions
Example:
Select * from post, comment, user where (post.id > 10 OR comment.count <30 OR user.age = 15) AND title = 'test'

A: 'filter' => [
  'or' => [
    ['missing' => ['field' => 'room_id']],
    ['terms' => ['room_id' => $roomIds]]
  ],
]

it`s works correct


text:
Q: Arduino Nano Gnss Software Serial I want to connect Arduino nano and GNSS (SIMCom's SIM33ELA standalone GNSS module).
First I wrote a program for rx/tx, which is worked well, but now I want to use Software Serial and I got something wrong data.
#include <SoftwareSerial.h>
char incomingByte;   // for incoming serial data
double tbs;
SoftwareSerial mySerial(8, 9); // RX, TX
void setup() {
   Serial.begin(115200);
   while (!Serial) {
  }
  mySerial.begin(115200);
  while (!mySerial) {

  }
}

void loop() {
    if (mySerial.available()) {
      tbs = mySerial.read();
      incomingByte = (char)tbs;
     Serial.print(incomingByte);
    }

   /*if (Serial.available() > 0) {
      incomingByte = Serial.read();
      Serial.print(incomingByte);
      }*/

}

Any Idea?
Pictures about results:
Wrong data with Software serial
Good data with Serial

A: Mostly, don't read one character into a double floating-point variable.  Just do this:
void loop()
{
  if (mySerial.available()) {
    char c = mySerial.read();
    Serial.write( c );
  }
}

You should also use AltSoftSerial on those two pins.  SoftwareSerial is very inefficient, because it disables interrupts for long periods of time.  It cannot transmit and receive at the same time.  In fact, the Arduino can do nothing else while a character is transmitted or received.
For a GPS library, you could try NeoGPS.  It's the only Arduino library that can parse the sentences from the newest devices.  It's also smaller, faster, more reliable and more accurate than all other libraries.


text:
Q: Mysql C# update int value by 1 I use this method to increase value of logins column by one:
MySqlConnection connect = new MySqlConnection(connectionStringMySql);
MySqlCommand cmd = new MySqlCommand();

cmd.Connection = connect;
cmd.Connection.Open();

string commandLine = null;
commandLine = "UPDATE Users SET logins = (@cur_value := logins) + 1 WHERE id = @id;";

cmd.CommandText = commandLine;

cmd.Parameters.AddWithValue("@id", userId);

cmd.ExecuteNonQuery();
cmd.Connection.Close();

And i get this Exception:

Fatal error encountered during command execution.

A: Just try this code
string commmandLine = "UPDATE Users SET logins = logins + 1 WHERE id = @id";
cmd.Set

A: First try this code
commandLine = "UPDATE Users SET logins =1 WHERE id = @id";
If above code is does not threw any error, then  try below code
commandLine = "UPDATE Users SET **logins =@YourValue** WHERE id = @id";

cmd.CommandText = commandLine;
cmd.Parameters.AddWithValue("@id", userId);

cmd.Parameters.AddWithValue("@YourValue", 1);//**Put your logins value**

A: Add following line:
 cmd.Parameters.AddWithValue("@cur_value", yourValue);

Also make more clear sql statement:
UPDATE Users
SET logins = @cur_value + 1
WHERE id = @id;

It is good practice to enclose problematic pieces of code with try/catch. Classes which represents unmanaged resources like Stream or SqlConnection are implementing IDisposable interface. They are usually need to be enclosed with using statement to be able to correctly release their resources even if exception was thrown (or use try/finally and in finally block call to method Close or Dispose). Then your code will be nice and clear :)


text:
Q: Ramsey Theorem: $R(3,4)\le 10$ Proof: Why is the number of friends be at-least 6 instead of 5(by pigeon rule, $\lceil 9/2\rceil=5$)? In this webpage, https://plus.maths.org/content/friends-and-strangers under the section, FINDING $R(3,4)$,
The author assumes that 10 people/points are necessary and takes out one point, say A. This A is connected to 9 other points. Now by pigeon hole rule, at least $\left\lceil \frac{9}{2} \right\rceil$. So at least 5 must be connected via blue. But the author writes, "There must either be at least 6 red ones, or at least 4 blue ones (otherwise there won't be 9 in all!) " I am trying hard to understand why it is so, can anyone help?

A: If there are fewer than $6$ red edges and fewer than $4$ blue edges, then the total number of edges incident to $A$ is strictly less than $5+3=8$, which is a contradiction.
We could prove similar claims by the same reasoning ("there must be at least $5$ red edges or at least $5$ blues edges", or "there must be at least $8$ red edges or at least $2$ blues edges", etc.), but the author has chosen these numbers in particular for the purpose of finding a Ramsay structure of the necessary form.

A: If I am understanding the problem based on the very quick skim I gave it, it's about connected graphs with coloring. It doesn't have to be at least 5 blue. For example, all 9 could be red. We know, however that there has to be at least 5 of one of the colours, be it blue or red. Whatever configuration we have, it is either the case that at least 6 or red, or less than six are red (meaning at least 4 are blue). As one of these is true, we can consider both cases, and show that in each case, you will find the shape you need.


text:
Q: Python script run on command line can't find site packages I've written a Python application with Python 2.7 using PyDev for Eclipe, where the script executes perfectly. However, if I try to run it on the command line, I get the following error:
importError: No module named openpyxl

openpyxl is one of the external libraries I use in my application. I searched for solutions and found multiple threads, some of which on this site. All of them handled modules that were created by the programmer himself and requires appending the src folder to the path. This doesn't work for me. I also tried adding the site package directory to my Python Path, but still the error remains.
Also, the script that is run (main.py) is located in the src directory, like so:
/Crawler/
    /src
        __init__.py
        main.py
        /Crawlers
            __init__.py
            Crawler1.py
            Crawler2.py

How do I configure my script so it finds all external libraries when executed from the command line?

A: Check whether the default python version is actually 2.7. Run python --version. If the default is not 2.7, call the script with the 2.7 interpreter;
python2.7 <yourscriptname>

Or if you are on UNIX or OSX, change the first line of the script to actually call python 2.7;
#!/usr/bin/env python2.7

Edit: If the python version is correct, check that you can import the module from the interactive interpreter. If you get output similar to the one below, openpyxl isn't installed correctly.
python
Python 2.7.8 (default, Jul 20 2014, 12:09:51)
[GCC 4.2.1 Compatible FreeBSD Clang 3.4 (tags/RELEASE_34/final 197956)] on freebsd10
Type "help", "copyright", "credits" or "license" for more information.
>>> import openpyxl
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named openpyxl
>>>

A: You can check the path variable to find out where python is looking for installed modules
import sys
print(sys.path)

Your openpyxl module has to be in a subfolder of one of them. If this package is not in one of the subfolders there are several solutions. One is as your pointed out to use PYTHONPATH and add the folder containing the openpyxl on the cmd-line or your can also the sys module to add the folder at runtime.
import sys
sys,path.append('/path/to/module/')

Another method is to install the module into the python-path using the setup.py that comes with it, python setup.py install --user. Or install it from PyPi with pip, pip install --user openpyxl

A: I had similar problem because of virtual environment. If you're using venv you have to activate it first in terminal. Go to your project directory, execute venv\Scripts\activate and then run your script.


text:
Q: How would I get a button to change stylesheets, be saved to local storage, and appear on all pages of a website? So I'm currently very new to code and understand very little terminology and I'm kinda scared to ask for help but here it goes.
Here is what I'm trying to accomplish:
I'm currently trying to create a website with multiple pages. One of the pages I want to be reserved for Settings where you can change the theme of all the pages to night or day mode. I have one button on the page and when you click it I'd like the entire website (every page) to go into "Night mode" by reading a dark mode css I made. If night mode is disabled I'd like it to be in day mode by reading a day mode css I also have made. I'd also like to save your preference as a cookie in local storage so if a user returns to the website it is still in the mode the user left the website in.
I'm unsure if this is all possible but it would be amazing if anyone could help me figure it out as I feel as though I have almost got it to work but have been stuck for ages! I'll add my html, javascript, and both css files so you can kind of see what I have made so far.
<!DOCTYPE html>

    <meta charset="utf-8">
    <link rel="stylesheet" href="default.css">

Veracity

Settings

        Home
        Articles
        News
        Pictures
        Contact Us
        Settings

    <button id="change-theme-btn">Night Mode</button>

Next is the Javascript:
document.getElementById("change-theme-btn").addEventListener("click",
function () {
let darkThemeEnabled = document.body.classList.toggle("pagestyle");
window.localStorage.setItem("pagestyle-enabled", darkThemeEnabled)
});

if (JSON.parse(window.localStorage.getItem("pagestyle-enabled"))) {
    document.body.classList.add("pagestyle");
}

Finally, Here is my day time/default css file:
#lightSwitchOff{ display:inline; }
#lightSwitchOn{ display:none; }

#span{
    font-family:Times New Roman;
    color: black;
    font-size: 25px;
}

body {
    background-color: white;

}

button {
    background-color: teal;
    border-radius: 12px;
    color: white;
    padding: 15px 32px;
    text-align: center;
    display: inline-block;
    font-size: 16px;
    margin: 4px 2px;
    cursor: pointer;
    font-family:Cooper Black;
}

h1 {
    color:teal;
    font-size: 60px;
    font-family:Magneto;

}

h2 {
    color:black;
    font-family:Magneto;

}

p {
    color:teal;
    font-size:20px;
    font-family:Courier New;

}

.div{
    border:10px solid teal;
    width:200px;
    border-radius: 10px;
    margin:20px;
    padding:10px;

}

.navbar {
    overflow: hidden;
    background-color: #a0a0a0;
    font-family: Cooper Black;
}

.navbar a {
    float: none;
    font-size: 25px;
    color: teal;
    text-align: center;
    padding: 50px 50px;
    text-decoration: none;

}

.navbar a:hover, .dropdown:hover .dropbtn, .dropbtn:focus {
    background-color: white;

}

.show {
    display: block;
}

And here's the night mode css file:
#lightSwitchOff{ display:none; }
#lightSwitchOn{ display:inline; }

#span{
    font-family:Times New Roman;
    color: #30d110;
    font-size: 25px;
}

body {
    background-color: black;

}

button {
    background-color: #30d110;
    color: black;
    border-radius: 12px;
    padding: 15px 32px;
    text-align: center;
    display: inline-block;
    font-size: 16px;
    margin: 4px 2px;
    cursor: pointer;
    font-family:Cooper Black;
}

h1 {
    color:#30d110;
    font-size: 60px;
    font-family:Magneto;
}

h2 {
    color:white;
    font-family:Magneto;

}

p {
    color:#30d110;
    font-size:20px;
    font-family:Courier New;
}

body {
    background-color: black;

}

.div{
    border:10px solid #30d110;
    width:200px;
    border-radius: 10px;
    margin:20px;
    padding:10px;

}

.navbar {
    overflow: hidden;
    background-color: #a0a0a0;
    font-family: Cooper Black;
}

.navbar a {
    float: none;
    font-size: 25px;
    color: #30d110;
    text-align: center;
    padding: 50px 50px;
    text-decoration: none;

}

.navbar a:hover, .dropdown:hover .dropbtn, .dropbtn:focus {
    background-color: white;

}

.show {
    display: block;
}

I dunno if I've posted too much of my code or too little but like I said I'm new and would like to provide as much information as possible. I think I'm really close but I cannot for the life of me figure out a way to have the css file switch with a single button and have the switch happen across all of my pages on my website. Any advice is appreciated and if I have left out any thing else that would help lead to an answer let me know and I can try to help out! Thanks so much!

A: If the css files are separate, then it sounds like you should want your Javascript to dynamically link the proper CSS file at runtime. You should keep your state in your Javascript alone if possible, and not depend on the HTML for it:
// defaults to false when LS not populated
let darkEnabled = Boolean(localStorage.darkEnabled);
const cssElem = document.querySelector('link[rel="stylesheet"]');
if (!darkEnabled) cssElem.href = 'default.css';
else cssElem.href = 'darktheme.css';
document.getElementById("change-theme-btn")
  .addEventListener('click', function () {
    darkEnabled = !darkEnabled;
    localStorage.darkEnabled = darkEnabled;
    if (!darkEnabled) cssElem.href = 'default.css';
    else cssElem.href = 'darktheme.css';
  });

(assuming you name the dark CSS file darktheme.css)

A: To solve this problem i would approach setting cookies.
Lets assume that your user has selected "night mode" then you can set a cookie with the new styelsheet and you can check if that new cookie exists on every page, if the cookie exists then you can replace your existing style.css with the new nightmode.css file
setting the cookie
    function setCookie(cname, cvalue, exdays) {
        var d = new Date();
        d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
        var expires = "expires="+d.toUTCString();
        document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
    }

    setCookie('stylesheet', 'main.css', 365);

Getting the cookie
function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

// if cookie exists then change the css file
console.log(getCookie('stylesheet'));


text:
Q: Сan't get a SAML response from ADFS server We have ADFS server (windows server 2012 R2).
Need to add authorization in custom application (lib spring-security-saml2-core).
Authentication steps:
1) create SAML AuthRequest and send to ADFS server
2) User is automatically redirected to the login page of the server, enters the correct credentials
3) No response from server. Error in log:
The Federation Service encountered an error while processing the SAML authentication request.

Additional Data
Exception details:
Microsoft.IdentityModel.Protocols.XmlSignature.SignatureVerificationFailedException: ID4037: The key needed to verify the signature could not be resolved from the following security key identifier 'SecurityKeyIdentifier
    (
    IsReadOnly = False,
    Count = 1,
    Clause[0] = Microsoft.IdentityServer.Tokens.MSISSecurityKeyIdentifierClause
    )
'. Ensure that the SecurityTokenResolver is populated with the required key.
   at Microsoft.IdentityModel.Protocols.XmlSignature.EnvelopedSignatureReader.ResolveSigningCredentials()
   at Microsoft.IdentityModel.Protocols.XmlSignature.EnvelopedSignatureReader.OnEndOfRootElement()
   at Microsoft.IdentityModel.Protocols.XmlSignature.EnvelopedSignatureReader.Read()
   at System.Xml.XmlReader.ReadEndElement()
   at Microsoft.IdentityServer.Protocols.Saml.SamlProtocolSerializer.ReadAuthnRequest(XmlReader reader)
   at Microsoft.IdentityServer.Protocols.Saml.HttpSamlBindingSerializer.ReadProtocolMessage(String encodedSamlMessage)
   at Microsoft.IdentityServer.Protocols.Saml.Contract.SamlContractUtility.CreateSamlMessage(MSISSamlBindingMessage message)
   at Microsoft.IdentityServer.Web.Protocols.Saml.SamlProtocolManager.Issue(HttpSamlRequestMessage httpSamlRequestMessage, SecurityTokenElement onBehalfOf, String sessionState, String relayState, String& newSamlSession, String& samlpAuthenticationProvider, Boolean isUrlTranslationNeeded, WrappedHttpListenerContext context, Boolean isKmsiRequested)

Can anyone help with this error?
 How to get a response?
We use this article to configure certificates and jks file: https://docs.microfocus.com/SM/9.61/Hybrid/Content/security/tasks/configure_saml_setup_relationship_between_idm_adfs.htm
Security XML:
   <!-- ADFS filter -->
   <bean id="adfsAuthenticationProcessingFilter"
      class="com.webapp.filter.ADFSAuthenticationProcessingFilter">
    <property name="authenticationManager" ref="samlAuthenticationManager"/>
    <property name="authenticationSuccessHandler" ref="logAuthenticationSuccessHandler"/>
    <property name="authenticationFailureHandler" ref="authenticationFailureHandler"/>
    <property name="sessionAuthenticationStrategy" ref="sessionFixationProtectionStrategy"/>
    <property name="SAMLProcessor" ref="processor"/>
    <property name="contextProvider" ref="contextProvider"/>
    <property name="userManager" ref="userManager"/>
</bean>

<!-- Filter automatically generates default SP metadata -->
<bean id="metadataGeneratorFilter"
      class="org.springframework.security.saml.metadata.MetadataGeneratorFilter">
    <constructor-arg>
        <bean class="org.springframework.security.saml.metadata.MetadataGenerator">
            <property name="entityId"
                      value="http://{ADFS server}/adfs/services/trust"/>
            <property name="requestSigned" value="false"/>
            <property name="extendedMetadata">
                <bean class="org.springframework.security.saml.metadata.ExtendedMetadata">
                    <property name="signMetadata" value="false"/>
                    <property name="idpDiscoveryEnabled" value="false"/>
                </bean>
            </property>
        </bean>
    </constructor-arg>
    <property name="manager" ref="metadata"/>
</bean>

<bean id="metadata" class="org.springframework.security.saml.metadata.MetadataManager">
    <constructor-arg>
        <list>
            <bean class="org.springframework.security.saml.metadata.ExtendedMetadataDelegate">
                <constructor-arg>
                    <bean class="org.opensaml.saml2.metadata.provider.FilesystemMetadataProvider">
                        <constructor-arg name="metadata" type="java.io.File"
                                         value="/WEB-INF/saml/sp_metadata.xml"/>
                        <property name="parserPool" ref="parserPool"/>
                    </bean>
                </constructor-arg>
                <constructor-arg>
                    <bean class="org.springframework.security.saml.metadata.ExtendedMetadata">
                        <property name="local" value="true"/>
                        <property name="securityProfile" value="metaiop"/>
                        <property name="sslSecurityProfile" value="metaiop"/>
                        <property name="signMetadata" value="true"/>
                        <property name="signingKey" value="keyName"/>
                        <property name="encryptionKey" value="keyName"/>
                        <property name="requireArtifactResolveSigned" value="true"/>
                        <property name="requireLogoutRequestSigned" value="true"/>
                        <property name="requireLogoutResponseSigned" value="true"/>
                        <property name="idpDiscoveryEnabled" value="false"/>
                    </bean>
                </constructor-arg>
                <property name="requireValidMetadata" value="false"/>
            </bean>
            <bean class="org.springframework.security.saml.metadata.ExtendedMetadataDelegate">
                <constructor-arg>
                    <bean class="org.opensaml.saml2.metadata.provider.FilesystemMetadataProvider">
                        <constructor-arg name="metadata" type="java.io.File"
                                         value="/WEB-INF/saml/ip_metadata.xml"/>
                        <property name="parserPool" ref="parserPool"/>
                    </bean>
                </constructor-arg>
                <constructor-arg>
                    <bean class="org.springframework.security.saml.metadata.ExtendedMetadata">
                        <property name="local" value="false"/>
                        <property name="securityProfile" value="metaiop"/>
                        <property name="sslSecurityProfile" value="metaiop"/>
                        <property name="signMetadata" value="true"/>
                        <property name="signingKey" value="keyName"/>
                        <property name="encryptionKey" value="keyName"/>
                        <property name="requireArtifactResolveSigned" value="false"/>
                        <property name="requireLogoutRequestSigned" value="false"/>
                        <property name="requireLogoutResponseSigned" value="false"/>
                        <property name="idpDiscoveryEnabled" value="false"/>
                    </bean>
                </constructor-arg>
                <property name="requireValidMetadata" value="false"/>
            </bean>

        </list>
    </constructor-arg>
    <property name="keyManager" ref="keyManager"/>
    <property name="TLSConfigurer">
        <bean class="org.springframework.security.saml.trust.httpclient.TLSProtocolConfigurer">
            <property name="keyManager" ref="keyManager"/>
            <property name="trustedKeys">
                <set>

                </set>
            </property>
        </bean>
    </property>
    <property name="hostedSPName"
              value="http://{ADFS server}/adfs/services/trust"/>
    <property name="defaultIDP"
              value="http://{ADFS server}/adfs/services/trust"/>
</bean>

<bean id="logAuthenticationSuccessHandler" parent="txProxyTemplate">
    <property name="target">
        <bean class="com.webapp.security.login.LogAuthenticationSuccessHandler">
            <property name="defaultTargetUrl" value="/startPage.htm"/>
            <property name="requestCache" ref="savedRequestCache"/>
            <property name="userDao" ref="userDao"/>
            <property name="attemptsManager" ref="authenticationAttemptsManager"/>
            <property name="userManager" ref="userManager"/>
        </bean>
    </property>
    <property name="transactionAttributes">
        <props>
            <prop key="onAuthenticationSuccess">PROPAGATION_REQUIRED</prop>
        </props>
    </property>
</bean>

<!--  SAML 2.0 -->
<!-- Secured pages with SAML as entry point -->

<sec:http pattern="/saml/**" entry-point-ref="samlEntryPoint">
    <sec:custom-filter before="FIRST" ref="metadataGeneratorFilter"/>
    <sec:custom-filter after="BASIC_AUTH_FILTER" ref="samlFilter"/>
</sec:http>

<sec:http entry-point-ref="samlEntryPoint" use-expressions="false" pattern="/">
    <sec:csrf/>
    <sec:intercept-url pattern="/**" access="IS_AUTHENTICATED_FULLY"/>
    <sec:custom-filter before="FIRST" ref="metadataGeneratorFilter"/>
    <sec:custom-filter after="BASIC_AUTH_FILTER" ref="samlFilter"/>
</sec:http>

<!-- Filters for processing of SAML messages -->
<bean id="samlFilter" class="org.springframework.security.web.FilterChainProxy">
    <sec:filter-chain-map request-matcher="ant">
        <sec:filter-chain pattern="/saml/login" filters="samlEntryPoint"/>
        <sec:filter-chain pattern="/saml/metadata/**" filters="metadataDisplayFilter"/>
        <sec:filter-chain pattern="/saml/SSO" filters="samlWebSSOProcessingFilter"/>
        <sec:filter-chain pattern="/saml/SSOHoK/**" filters="samlWebSSOHoKProcessingFilter"/>
        <sec:filter-chain pattern="/saml/SingleLogout/**" filters="samlLogoutProcessingFilter"/>
    </sec:filter-chain-map>
</bean>

<!-- Handler deciding where to redirect user after successful login -->
<bean id="successRedirectHandler"
      class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
    <property name="defaultTargetUrl" value="/"/>
</bean>

<!-- Handler deciding where to redirect user after failed login -->
<bean id="failureRedirectHandler"
      class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">
    <property name="useForward" value="true"/>
    <property name="defaultFailureUrl" value="/error/403.jsf"/>
</bean>

<!-- Handler for successful logout -->
<bean id="successLogoutHandler"
      class="org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler">
    <property name="defaultTargetUrl" value="/logout"/>
</bean>

<sec:authentication-manager alias="samlAuthenticationManager">
    <!-- Register authentication manager for SAML provider -->
    <sec:authentication-provider ref="samlAuthenticationProvider"/>
    <!-- Register authentication manager for administration UI -->
    <sec:authentication-provider>
        <sec:user-service id="adminInterfaceService">
            <sec:user name="admin" password="admin" authorities="ROLE_ADMIN"/>
        </sec:user-service>
    </sec:authentication-provider>
</sec:authentication-manager>

<!-- Logger for SAML messages and events -->
<bean id="samlLogger" class="org.springframework.security.saml.log.SAMLDefaultLogger"/>

<bean id="keyManager" class="org.springframework.security.saml.key.JKSKeyManager">
    <constructor-arg value="/WEB-INF/saml/samlKeystore.jks"/>

    <constructor-arg type="java.lang.String" value="123456"/>
    <constructor-arg>
        <map>
            <entry key="keyName" value="1234567"/>
        </map>
    </constructor-arg>
    <constructor-arg type="java.lang.String" value="keyName"/>
</bean>

<!-- Entry point to initialize authentication, default values taken from properties file -->
<bean id="samlEntryPoint" class="org.springframework.security.saml.SAMLEntryPoint">
    <property name="defaultProfileOptions">
        <bean class="org.springframework.security.saml.websso.WebSSOProfileOptions">
            <property name="includeScoping" value="false"/>
            <property name="nameID"
                      value="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"/>
            <property name="binding" value="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"/>
            <property name="allowCreate" value="true"/>
            <property name="assertionConsumerIndex" value="0"/>
            <property name="passive" value="false"/>
            <property name="relayState"
                      value="https://{application URL}/saml/SSO/login.htm"/>
            <property name="forceAuthN" value="true"/>
            <property name="authnContexts">
                <list>
                    <value>urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport
                    </value>
                </list>
            </property>
        </bean>
    </property>
    <property name="metadata" ref="metadata"/>
    <property name="samlLogger" ref="samlLogger"/>
    <property name="webSSOprofile" ref="webSSOprofile"/>
    <property name="contextProvider" ref="contextProvider"/>
    <property name="filterProcessesUrl" value="/login.htm"/>
</bean>

<!-- The filter is waiting for connections on URL suffixed with filterSuffix and presents SP metadata there -->
<bean id="metadataDisplayFilter"
      class="org.springframework.security.saml.metadata.MetadataDisplayFilter">
    <property name="manager" ref="metadata"/>
    <property name="contextProvider" ref="contextProvider"/>
    <property name="keyManager" ref="keyManager"/>
</bean>

<!-- SAML Authentication Provider responsible for validating of received SAML messages -->
<bean id="samlAuthenticationProvider"
      class="org.springframework.security.saml.SAMLAuthenticationProvider">

    <property name="userDetails" ref="userDetails"/>
    <property name="consumer" ref="webSSOprofileConsumer"/>
    <property name="hokConsumer" ref="hokWebSSOprofileConsumer"/>
    <property name="samlLogger" ref="samlLogger"/>
    <property name="forcePrincipalAsString" value="false"/>
</bean>

<bean id="userDetails" parent="txProxyTemplate">
    <property name="target">
        <bean class="com.webapp.security.SAMLUserDetails">
            <property name="userDao" ref="userDao"/>
        </bean>
    </property>
    <property name="transactionAttributes">
        <props>
            <prop key="load*">PROPAGATION_REQUIRED</prop>
        </props>
    </property>
</bean>

<!-- Provider of default SAML Context -->
<bean id="contextProvider"
      class="org.springframework.security.saml.context.SAMLContextProviderImpl">
    <property name="keyManager" ref="keyManager"/>
    <property name="metadata" ref="metadata"/>
</bean>

<!-- Processing filter for WebSSO profile messages -->
<bean id="samlWebSSOProcessingFilter"
      class="org.springframework.security.saml.SAMLProcessingFilter">
    <property name="authenticationManager" ref="samlAuthenticationManager"/>
    <property name="authenticationSuccessHandler" ref="successRedirectHandler"/>
    <property name="authenticationFailureHandler" ref="failureRedirectHandler"/>
    <property name="contextProvider" ref="contextProvider"/>
    <property name="SAMLProcessor" ref="processor"/>
</bean>

<!-- Processing filter for WebSSO Holder-of-Key profile -->
<bean id="samlWebSSOHoKProcessingFilter"
      class="org.springframework.security.saml.SAMLWebSSOHoKProcessingFilter">
    <property name="authenticationManager" ref="samlAuthenticationManager"/>
    <property name="authenticationSuccessHandler" ref="successRedirectHandler"/>
    <property name="authenticationFailureHandler" ref="failureRedirectHandler"/>
    <property name="contextProvider" ref="contextProvider"/>
    <property name="SAMLProcessor" ref="processor"/>
</bean>

<!-- Logout handler terminating local session -->
<bean id="logoutHandler"
      class="org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler">
    <property name="invalidateHttpSession" value="false"/>
</bean>

<!--Filter processing incoming logout messages -->
<!--First argument determines URL user will be redirected to after successful global logout -->
<bean id="samlLogoutProcessingFilter"
      class="org.springframework.security.saml.SAMLLogoutProcessingFilter">
    <constructor-arg index="0" ref="successLogoutHandler"/>
    <constructor-arg index="1" ref="logoutHandler"/>
    <property name="SAMLProcessor" ref="samlProcessor"/>
    <property name="contextProvider" ref="contextProvider"/>
    <property name="logoutProfile" ref="logoutProfile"/>
    <property name="samlLogger" ref="samlLogger"/>
</bean>

<bean id="logoutProfile"
      class="org.springframework.security.saml.websso.SingleLogoutProfileImpl">
    <property name="metadata" ref="metadata"/>
    <property name="processor" ref="samlProcessor"/>
</bean>

<!-- Class loading incoming SAML messages from httpRequest stream -->
<bean id="processor" class="org.springframework.security.saml.processor.SAMLProcessorImpl">
    <constructor-arg>
        <list>
            <ref bean="redirectBinding"/>
            <ref bean="postBinding"/>
            <ref bean="artifactBinding"/>
            <ref bean="soapBinding"/>
            <ref bean="paosBinding"/>
        </list>
    </constructor-arg>
</bean>

<!-- Initialization of OpenSAML library-->
<bean class="org.springframework.security.saml.SAMLBootstrap"/>

<!-- SAML 2.0 WebSSO Assertion Consumer -->
<bean id="webSSOprofileConsumer"
      class="org.springframework.security.saml.websso.WebSSOProfileConsumerImpl">
    <property name="metadata" ref="metadata"/>
    <property name="processor" ref="samlProcessor"/>

    <property name="responseSkew" value="600"/>
    <property name="maxAuthenticationAge" value="7200"/>
</bean>

<!-- SAML 2.0 Holder-of-Key WebSSO Assertion Consumer -->
<bean id="hokWebSSOprofileConsumer"
      class="org.springframework.security.saml.websso.WebSSOProfileConsumerHoKImpl">
    <property name="metadata" ref="metadata"/>
    <property name="processor" ref="samlProcessor"/>
</bean>

<!-- SAML 2.0 Web SSO profile -->
<bean id="webSSOprofile" class="com.webapp.filter.CustomWebSSOProfileImpl">
    <property name="metadata" ref="metadata"/>
    <property name="processor" ref="samlProcessor"/>
    <!-- property name="metadataIssuerUrl" value="https://{ADFS server}/FederationMetadata/2007-06/FederationMetadata.xml" / -->
</bean>

<!-- SAML 2.0 Holder-of-Key Web SSO profile -->
<bean id="hokWebSSOProfile"
      class="org.springframework.security.saml.websso.WebSSOProfileConsumerHoKImpl">
    <property name="metadata" ref="metadata"/>
    <property name="processor" ref="samlProcessor"/>
</bean>

<!-- SAML 2.0 ECP profile -->
<bean id="ecpprofile" class="org.springframework.security.saml.websso.WebSSOProfileECPImpl">
    <property name="metadata" ref="metadata"/>
    <property name="processor" ref="samlProcessor"/>
</bean>

<!-- SAML 2.0 Logout Profile -->
<bean id="logoutprofile"
      class="org.springframework.security.saml.websso.SingleLogoutProfileImpl">
    <property name="metadata" ref="metadata"/>
    <property name="processor" ref="samlProcessor"/>
    <property name="responseSkew" value="600"/>
</bean>

<!-- Bindings, encoders and decoders used for creating and parsing messages -->
<bean id="postBinding" class="org.springframework.security.saml.processor.HTTPPostBinding">
    <constructor-arg ref="parserPool"/>
    <constructor-arg ref="velocityEngine"/>
</bean>

<bean id="redirectBinding"
      class="org.springframework.security.saml.processor.HTTPRedirectDeflateBinding">
    <constructor-arg ref="parserPool"/>
</bean>

<bean id="artifactBinding"
      class="org.springframework.security.saml.processor.HTTPArtifactBinding">
    <constructor-arg ref="parserPool"/>
    <constructor-arg ref="velocityEngine"/>
    <constructor-arg>
        <bean class="org.springframework.security.saml.websso.ArtifactResolutionProfileImpl">
            <constructor-arg>
                <bean class="org.apache.commons.httpclient.HttpClient">
                    <constructor-arg>
                        <bean class="org.apache.commons.httpclient.MultiThreadedHttpConnectionManager"/>
                    </constructor-arg>
                </bean>
            </constructor-arg>
            <property name="processor" ref="samlProcessor"/>
            <property name="metadata" ref="metadata"/>
        </bean>
    </constructor-arg>
</bean>

<bean id="samlProcessor" class="org.springframework.security.saml.processor.SAMLProcessorImpl">
    <constructor-arg ref="httpPostBinding"/>
</bean>

<bean id="httpRedirectBinding"
      class="org.springframework.security.saml.processor.HTTPRedirectDeflateBinding">
    <constructor-arg ref="parserPool"/>
</bean>

<bean id="httpPostBinding" class="org.springframework.security.saml.processor.HTTPPostBinding">
    <constructor-arg ref="parserPool"/>
    <constructor-arg ref="velocityEngine"/>
</bean>

<bean id="xmlHttpPostBinding"
      class="org.springframework.security.saml.processor.HTTPPostBinding">
    <constructor-arg ref="parserPool"/>
    <constructor-arg>
        <bean class="org.opensaml.saml1.binding.decoding.HTTPPostDecoder">
            <constructor-arg ref="parserPool"/>
        </bean>
    </constructor-arg>
    <constructor-arg>
        <bean class="com.webapp.filter.HttpRedirectDeflateAsHttpPostEncoder"/>
    </constructor-arg>
</bean>

<bean id="soapBinding" class="org.springframework.security.saml.processor.HTTPSOAP11Binding">
    <constructor-arg ref="parserPool"/>
</bean>

<bean id="paosBinding" class="org.springframework.security.saml.processor.HTTPPAOS11Binding">
    <constructor-arg ref="parserPool"/>
</bean>

<!-- Initialization of OpenSAML library-->
<bean class="org.springframework.security.saml.SAMLBootstrap"/>

<!-- Initialization of the velocity engine -->
<bean id="velocityEngine" class="org.springframework.security.saml.util.VelocityFactory"
      factory-method="getEngine"/>

<bean id="parserPool" class="org.opensaml.xml.parse.StaticBasicParserPool"
      init-method="initialize"/>

<bean id="parserPoolHolder" class="org.springframework.security.saml.parser.ParserPoolHolder"/>

SAML AuthRequest:
  <!-- ADFS filter -->
  <?xml version="1.0" encoding="UTF-8"?>
  <saml2p:AuthnRequest
AssertionConsumerServiceURL="https://{application URL}/saml/SSO/login.htm"
Destination="https://{ADFS server}/adfs/ls/" ForceAuthn="true"
ID="ID" IsPassive="false" IssueInstant="2019-08-28T07:36:16.121Z"
ProtocolBinding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" Version="2.0"
xmlns:saml2p="urn:oasis:names:tc:SAML:2.0:protocol">
<saml2:Issuer xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion">http://{ADFS server URL}/adfs/services/trust</saml2:Issuer>
<ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
    <ds:SignedInfo><ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
    <ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
        <ds:Reference URI="#ID">
            <ds:Transforms><ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
            <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/></ds:Transforms>
            <ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
            <ds:DigestValue>pA3hIQrobfvJmjpV76SuMhfD5Ig=</ds:DigestValue>
        </ds:Reference>
    </ds:SignedInfo>
    <ds:SignatureValue>...==</ds:SignatureValue>
    <ds:KeyInfo>
        <ds:X509Data>
            <ds:X509Certificate>...</ds:X509Certificate>
        </ds:X509Data>
    </ds:KeyInfo>
</ds:Signature><saml2p:NameIDPolicy AllowCreate="true"
    Format="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"/>
<saml2p:RequestedAuthnContext Comparison="exact">
    <saml2:AuthnContextClassRef xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion">urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport</saml2:AuthnContextClassRef>
</saml2p:RequestedAuthnContext>

A: I recently worked on a project where we set up KeyCloak to act as an SP to ADFS IdP.
We were only able to get the SAML requests to process correctly when the following settings were set:

IdP URL: ${IDP_URL}/adfs/ls/
NameID Policy Format: persistent
WantAuthnRequestsSigned: true
WantAssertionsSigned: true
SignatureAlgorithm: RSA_SHA256
SAMLSignatureKeyName: CERT_SUBJECT

In addition to updating the NameID Policy on our side (as SP), we also had to have custom settings on the IdP side to ensure the NameID was sent back as format persistent.
I see from your authn request that the NameID Policy is currently set to emailAddress.


text:
Q: Cannot create queue connection factory in Apache Camel I am using Apache Camel in my project and embedding that in Spring Boot application. My requirement is to read message from an Apache Active MQ Artemis (Embedded in JBoss EAP 7.2.0) write message to an IBM MQ. Both the queues are remote to my current server. The Spring Boot project will be deployed as a war file to JBoss EAP 7.2.0 server.
I have developed a standalone program that would read message from and write message to an Apache Active MQ Artemis. I have created the connection factory in Spring Boot configuration class. Below is my Spring Boot configuration class and route class:
@SpringBootApplication
@EnableJms
public class SpringMqDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringMqDemoApplication.class, args);
    }

    private static final String INITIAL_CONTEXT_FACTORY = "org.wildfly.naming.client.WildFlyInitialContextFactory";
    private static final String CONNECTION_FACTORY = "jms/RemoteConnectionFactory";

    @Bean
    public ConnectionFactory connectionFactory() {
        try {
            System.out.println("Retrieving JMS queue with JNDI name: " + CONNECTION_FACTORY);
            JndiObjectFactoryBean jndiObjectFactoryBean = new JndiObjectFactoryBean();
            jndiObjectFactoryBean.setJndiName(CONNECTION_FACTORY);

            jndiObjectFactoryBean.setJndiEnvironment(getEnvProperties());
            jndiObjectFactoryBean.afterPropertiesSet();

            return (QueueConnectionFactory) jndiObjectFactoryBean.getObject();

        } catch (NamingException e) {
            System.out.println("Error while retrieving JMS queue with JNDI name: [" + CONNECTION_FACTORY + "]");
        } catch (Exception ex) {
            System.out.println("Error");
        }
        return null;
    }

    public Properties getEnvProperties() {
        Properties env = new Properties();
        env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY);
        env.put(Context.PROVIDER_URL, "http-remoting://<<IP>>:8080");
        env.put(Context.SECURITY_PRINCIPAL, "username");
        env.put(Context.SECURITY_CREDENTIALS, "password");
        return env;
    }

    @Bean
    public DefaultJmsListenerContainerFactory jmsListenerContainerFactory(ConnectionFactory connectionFactory) {

        DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        JndiDestinationResolver jndiDestinationResolver = new JndiDestinationResolver();

        jndiDestinationResolver.setJndiEnvironment(getEnvProperties());
        factory.setDestinationResolver(jndiDestinationResolver);
        return factory;
    }

@Component
public class Route extends RouteBuilder {

    @Override
    public void configure() throws Exception {
        from("direct:producer")
            .log("Camel route")
            .to("jms:queue:queue1");

        from("jms:queue:queue2")
            .log("Camel route: ${body}")
            .to("someEndpoint");
    }

}

With this sample program, I was able to write to queue1 and read from queue2, but here I am using the same ConnectionFactory for both the queues. In my project, I will have to use two connection factories, can anyone please guide me how to use two connection factories for both the queues?
I went through the documentation of JMS endpoint but am not sure what value should I use for the parameter "connectionFactory" on camel jms endpoint.


text:
Q: attaching a null character to a character array for using strcmp later Why is it that the I seem not be able to use strcmp to compare two strings if I first create an array that just holds enough characters without the \0 character at the end and then put in the \0 at a later step like the following?
    // The following from strcmp returns non-zero, so the two strings buff, t1 are
    // not equal
    char buff[4] = "K7Ag";
    buff[4] = '\0';
    char t1[5] = "K7Ag";
    if(strcmp(buff, t1) == 0) {
        printf("they are equal\n");
    }

But if I do this:
// strcmp shows they are equal
    char buff[5] = "K7Ag";

    char t1[5] = "K7Ag";
    if(strcmp(buff, t1) == 0) {
        printf("they are equal\n");
    }

I know I need a null character at the end of each string for strcmp to work properly. So why is it that I first create buff as:
char buff[4] = "K7Ag"

then append "\0" like:
buff[4] = '\0'
then call
strcmp(buff, t1) would not work?

Finally, can I assume that when I create a buff like
char b1[100] = "Abcd"
then I will have 96 null characters (i.e., 96 of those \0)
right after the character d in the b1 buffer?
So if I initialize a buffer with less than the allocated size, can I assume the rest of the buffer holds the \0 character?


text:
Q: How to get original size of image in imageFallback Magento? How to get the original size of image in imageFallback? I used the below code to get the images.
My code:
echo $imageFallback['image_fallback'];

Return:
http:\/\/www.xxxxxx.com\/media\/catalog\/product\/cache\/6\/image\/500x800\/602f0fa2c1f0d1b8sa098a09s9856ff9\/c\/o\/car1.png

But i need return the original file, without resize:
Ex:
http:\/\/www.xxxxxx.com\/media\/catalog\/product\/c\/o\/car1.png

Thank you


text:
Q: grid_columnconfigure() Not Working Inside my Frame Here is My Code
from tkinter import *

root = Tk()

myframe = Frame(root, bg="red")
myframe.pack()

btn1 = Button(myframe, text="Button 1", font="Comicsans 15 bold")
btn1.grid(row=0, column=0)

btn2 = Button(myframe, text="Button 2", font="Comicsans 15 bold")
btn2.grid(row=0, column=1)

root.grid_columnconfigure((0, 1), weight=1)

root.mainloop()

How do I make grid_columnconfigure() work ?

A: You're calling it on root, but the widget inside root is using pack. If you expect it to affect the buttons, you need to call it on myframe:
myframe.grid_columnconfigure((0,1), weight=1)


text:
Q: Capybara: после создания объекта, не происходит перенаправление на action show e 'rails_helper'

feature 'add lost pet' do
  given(:data) {attributes_for(:lost_pet)}

  scenario 'add new lost pet with valid data' do
    visit  root_path
    click_on 'Register new lost pet'
      fill_in 'Name', with: data[:name]
      fill_in 'Type', with: data[:type]
      fill_in 'Breed', with: data[:breed]
      fill_in 'Gender', with: data[:gender]
      fill_in 'Size', with: data[:size]
      fill_in 'Colour', with: data[:colour]
      fill_in 'Age', with: data[:age]
      fill_in 'Age unit', with: data[:age_unit]
      fill_in 'Description', with: data[:description]
      fill_in 'Collar description', with: data[:collar_description]
      check 'Desexed', :checked
      check 'Microchipped', :checked
      fill_in 'Microchip number', with: data[:microchipped_number]
      select '2015', from: "lost_pet[date_missing(1i)]"
      select 'October', from: 'lost_pet[date_missing(2i)]'
      select '10', from: 'lost_pet[date_missing(3i)]'
      fill_in 'Rewald', with: data[:rewald]
      fill_in 'Image', with: data[:image]
      fill_in 'Adress lost', with: data[:adress_lost]
      click_on 'Create'

      lost_pet = LostPet.last

      expect(current_path).to eq lost_pet_path(lost_pet)
      expect(page).to have_content('Oskar')
  end
end

** контроллер: **
class LostPetsController < ApplicationController
  before_action :load_lost_pet, only: [:show, :edit, :update, :destroy]

  respond_to :html

  def index
      @lost_pets = LostPet.all
  end

  def new
    respond_with(@lost_pet = LostPet.new)
  end

  def create
    respond_with(@lost_pet = LostPet.create(lost_pet_params))
  end

  def show
    respond_with(@lost_pet)
  end

  def edit
    @lost_pet
  end

  def update
    @lost_pet.update(lost_pet_params)
    respond_with(@lost_pet)
  end

  def destroy
    respond_with(@lost_pet.destroy)
  end

  private

  def load_lost_pet
    @lost_pet = LostPet.find(params[:id])
  end

  def lost_pet_params
    params.require(:lost_pet).permit([:id, :name, :type_pet, :breed, :gender, :size,
      :colour, :age, :age_unit, :description, :collar_description, :desexed,
      :microchipped, :microchip_number, :date_missing, :rewald, :image, :adress_lost,
      :name_host, :telephone, :email])
  end
end

Перехожу в метод new, создаю новый объект, далее после сохранения происходит редирект на метод show. Запускаю, создаю новый объект, меня перекидывает в show. Все работает. Но! Почему то в самом тесте, после click_on 'Create'LostPet.last равен nill
А также проверка expect(page).to have_content('Oskar') выдает след ошибку:
** add lost pet add new lost pet with valid data
     Failure/Error: expect(page).to have_content('Oskar')
       expected to find text "Oskar" in "Register new lost pet Name Breed Type Gender Size Colour Age Age unit Description Collar description Desexed Microchipped Microchip number Date missing 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 January February March April May June July August September October November December 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 Rewald Image Adress lost Name host Telephone Email"
     # ./spec/acceptance/lost_pet/create_spec.rb:33:in `block (2 levels) in ' **
Получается в тесте не происходит редиректа в action show. Как решить данную проблему? Заранее спасибо за ответ.

A: Пропишите в rails_helper (найдите в файле строку и измените в ней или в spec_helper)
config.use_transactional_fixtures = true

на
config.use_transactional_fixtures = false

Это потому что когда вы создаете запись она записывается в память а не в базу (Существует виртуально скажем так, не персистентная)
Установите гем Database-Cleaner
gem 'database_cleaner', group :test

Чтоб данные всегда по окончанию тестов из неё удалялись нужен этот гем. Если этого не делать могут произойти коллизии с данными в тестовой базе (остаточные записи в базе с предыдущих тестов могут к примеру).
Опять же, в rails_helper перед окончанием блока RSpec.configure do |config| пропишите следующий код :
# Настройки для удаления данных из базы данных после тестирования
  config.before(:suite) do # выполняеться этот код перед запуском всего файла со спеками
    DatabaseCleaner.clean_with(:truncation) #удаляются все данные при помощи стратегии truncation
  end

  config.before(:each) do # перед каждым тестом сохраняем данные в положении ТРАНЗАКЦИИ, когда данные реально НЕ ЗАПИСЫВАЮТЬСЯ в базу.
    DatabaseCleaner.strategy = :transaction
  end

  config.before(:each, js:true) do # для каждой спеки помеченной JS-TRUE, используем стратегию truncation. Которая создаёт данные в таблице для теста и очишает её по окончанию
    DatabaseCleaner.strategy = :truncation
  end

  config.before(:each) do # в начале каждого теста устанавливаем чистильшик базы для отслеживания изменений в базе
    DatabaseCleaner.start
  end

  config.after(:each) do # ну и после каждого теста чистильшик подчишает базу
    DatabaseCleaner.clean
  end

Этот код,будет работать как описано. в комментариях.


text:
Q: Spark Shuffle Memory Overhead Issues I have some recurring problems in designing Spark Jobs (using Spark 2.3.x).
In a nutshell:

*

*job is essentially some expensive shuffle operation ( .groupby or .join operations on large dataframes with fine granularity). Afterwards results are written to disk (parquet)

*most tasks succeed very quickly

*there are few, hard to solve tasks, that take very long and sometimes fail

*even if the job succeeds the few long task make up for the majority of runtime

*Yarn occasionally kills some executors because they exceed memory limits yarn.YarnAllocator: Container killed by YARN for exceeding memory limits. 18.0 GB of 18 GB physical memory used. Consider boosting spark.yarn.executor.memoryOverhead.

*Yarn occasionally kills the job after those tasks failed multiple times org.apache.spark.SparkException: Job aborted due to stage failure: Task 175 in stage 92.0 failed 4 times
I wonder how single tasks can have such a high memory consumption. In my understanding of how Spark work, it should be possible to make the tasks sufficiently small so that they fit into memory.
Also the fact that few tasks make up for the majority of runtime is a sign of sub-optimal parallelization.
The data within a grouping unit (group -> all that matches key for groupBy or join) is not very large. (Aggregation of a single group key cannot cause the memory issues alone)
Things I already tried:

*

*increased executor memory and memory overhead -> reduced failrate, increased runtime, but also did not resolve the issues, I run into the next limits. also there are hardware restrictions

*changed partitioning of my DataFrames -> no visible effects

*increased shuffle service partitions spark.sql.shuffle.partitions -> reduced the fail rate, but also increased runtime

Any ideas to improve performance & stability?
edit:
Some further investigation revealed, we have indeed very skewed datasets. It seems that the map operations for some few very large rows are very much to large for the spark-executors to handle.

A: i increased shuffle partition count. i massively increased executor memory. and i changed the configuration settings that were recommended in the spark error logs. for now the job runs without warnings/ errors, but the runtime is severely increased.
--executor-memory 32g
--driver-memory 16g
--conf spark.executor.memoryOverhead=8g
--conf spark.driver.maxResultSize=4g
--conf spark.sql.shuffle.partitions=3000


text:
Q: How do I impersonate SAML/SSO from a computer? I have a website that I need to access periodically. From the browser it works fine. The site gives me a cookie which expires in 15 minutes. If I go back to the server after an hour, it redirects me to login.microsoft.com which redirects me back to the server.
I need to do the same thing from an unattended computer. Is there a document that discribes what information I need to capture from my destination server and from the the Microsoft IDP server to allow my computer to renew its authentication when the session cookie times out?

A: To authenticate with Azure AD IDP I ended up using Puppeteer Sharp (which controls a headless version of Chromium) and the following function (which steps it through its pases) for authentication. The parameter for SSOLogin are as follows:

*

*destination - is the REST API that resides behind SSO

*email - the email address used to authenticate

*password - the password associated with the email address

*selector - an element selector that is present in the API

*cookieParams - the cookies sent by the API and the IDP

Initially there are no cookies. However, SSOLogin returns the current set of cookies. If the cookies for the API have not expired login is quick and easy. If the IDP cookies have not expired you get redirected back to the API. If the cookies on the IDP have expired then you get to login using the email address and password.
In any case you can extract the cookies from the API and use them to make the call.
Nuget packages used:

*

*Microsoft.AspNet.WebApi.Client (5.2.7)

*PuppeteerSharp (5.0.0)

*System.Net.Http.Json (5.0.0)
 public static async Task<CookieParam[]> SSOLogin(CookieParam[] cookieParams, string destination, string email, string password, string selector)
 {
     var options = new LaunchOptions { Headless = true };  // Set to false to watch browser step through activities
     var selectorOption = new WaitForSelectorOptions { Visible = true, Timeout = 10000 };
     await new BrowserFetcher().DownloadAsync();  // Only needed the first time through

     using var browser = await Puppeteer.LaunchAsync(options);
     using var page = await browser.NewPageAsync();
     await page.SetCookieAsync(cookieParams);
     await page.GoToAsync(destination);

     try
     {
         await page.WaitForSelectorAsync($"{selector}, input[name='loginfmt']", selectorOption);
     }
     catch (Exception e)
     {
         Console.WriteLine($"First page error: {e.Message}");
     }
     var url = page.Url;
     if (url.StartsWith("https://login.microsoftonline.com/"))
     {
         if (await page.QuerySelectorAsync($"div[data-test-id='{email}']") != null)
         {
             await page.ClickAsync($"div[data-test-id='{email}']");
         }
         else
         {
             await page.WaitForSelectorAsync("input[name='loginfmt']:not(.moveOffScreen)", selectorOption);
             await page.FocusAsync("input[name='loginfmt']");
             await page.Keyboard.TypeAsync(email);

             await page.WaitForSelectorAsync("input[type=submit]", selectorOption);
             await page.ClickAsync("input[type=submit]");
         }
         await page.WaitForSelectorAsync("input[type=password]:not(.moveOffScreen)", selectorOption);
         await page.FocusAsync("input[type=password]");
         await page.Keyboard.TypeAsync(password);

         await page.WaitForSelectorAsync("input[type=submit]", selectorOption);
         await page.ClickAsync("input[type=submit]");

         await page.WaitForSelectorAsync("input[name='DontShowAgain']:not(.moveOffScreen)", selectorOption);
         await page.ClickAsync("input[name='DontShowAgain']");

         await page.WaitForSelectorAsync("input[type=submit]", selectorOption);
         await page.ClickAsync("input[type=submit]");

         await page.WaitForSelectorAsync(selector, selectorOption);
     }
     return await page.GetCookiesAsync("https://login.microsoftonline.com/", destination);
 }


text:
Q: Can you use the attribute-based routing of WebApi 2 with WebForms? As the title states, I'm wondering if you can use the attribute-based routing of WebAPI 2 with WebForms.  I feel like this can obviously be done given you can use WebAPI2 just fine in a WebForms application...  I just can't figure out how to enable attribute-based routing.
Based on this article, I understand you normally enable it via a call to MapHttpAttributeRoutes() prior to setting up your convention-based routes.  But I'm guessing this is the MVC way - I need to know the equivalent for WebForms.
I currently use MapHttpRoute() to set up my convention-based routes, and I'd like to try out the attribute-based routing in WebAPI2.  I have updated my project with WebAPI2 - I just need to know how to enable the attribute-based routing feature.
Any info would be appreciated.

A: You need not do anything special in case of WebForms. Web API attribute routing should work just as in MVC.
If you are using VS 2013, you can test this easily by create a project using "Web Forms" template and then choose "Web API" check box and you should see all the following code generated by this.
WebApiConfig.cs
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

Global.asax
public class Global : HttpApplication
{
    void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup
        GlobalConfiguration.Configure(WebApiConfig.Register);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }
}

WebForm's RouteConfig
public static class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        var settings = new FriendlyUrlSettings();
        settings.AutoRedirectMode = RedirectMode.Permanent;
        routes.EnableFriendlyUrls(settings);
    }
}


text:
Q: How to set Virtual Keyboard style from .qrc in QtWidgets application with CMake I have tried for a couple of days to setup Virtual Keyboards in a Linux application. My application contains a .qrc file containing keyboard layout and styles. I tried following tons of forums to no avail, but I believe the closest I came is through following https://forum.qt.io/topic/93279/how-to-custom-qml-virtual-keyboard. Now all links on Google are purple. Many of the guides and forums expect a QML application written in QMake, and I have not succeeded in translating these to my problem using CMake.
I have also asked this question here but haven't gotten answers in days.
My .qrc file is the following (with the default-style taken from here):
<RCC>
    <qresource prefix="/">
        <file>virtual_keyboard/QtQuick/VirtualKeyboard/layouts/en_GB/main.qml</file>
        <file>virtual_keyboard/QtQuick/VirtualKeyboard/layouts/en_GB/numbers.qml</file>
        <file>virtual_keyboard/QtQuick/VirtualKeyboard/Styles/style/images/textmode-fff.svg</file>
        <file>virtual_keyboard/QtQuick/VirtualKeyboard/Styles/style/images/shift-fff.svg</file>
        <file>virtual_keyboard/QtQuick/VirtualKeyboard/Styles/style/images/shift-c5d6b6.svg</file>
        <file>virtual_keyboard/QtQuick/VirtualKeyboard/Styles/style/images/shift-80c342.svg</file>
        <file>virtual_keyboard/QtQuick/VirtualKeyboard/Styles/style/images/settings-fff.svg</file>
        <file>virtual_keyboard/QtQuick/VirtualKeyboard/Styles/style/images/selectionhandle-bottom.svg</file>
        <file>virtual_keyboard/QtQuick/VirtualKeyboard/Styles/style/images/search-fff.svg</file>
        <file>virtual_keyboard/QtQuick/VirtualKeyboard/Styles/style/images/hidekeyboard-fff.svg</file>
        <file>virtual_keyboard/QtQuick/VirtualKeyboard/Styles/style/images/handwriting-fff.svg</file>
        <file>virtual_keyboard/QtQuick/VirtualKeyboard/Styles/style/images/globe-fff.svg</file>
        <file>virtual_keyboard/QtQuick/VirtualKeyboard/Styles/style/images/enter-fff.svg</file>
        <file>virtual_keyboard/QtQuick/VirtualKeyboard/Styles/style/images/check-fff.svg</file>
        <file>virtual_keyboard/QtQuick/VirtualKeyboard/Styles/style/images/backspace-fff.svg</file>
        <file>virtual_keyboard/QtQuick/VirtualKeyboard/Styles/style/style.qml</file>
    </qresource>
</RCC>

I know I need the following lines to use my custom layout and specify my style, here just named 'style'. The custom layout is loaded properly, but the style is not:
qputenv("QT_VIRTUALKEYBOARD_LAYOUT_PATH", "qrc:/virtual_keyboard/QtQuick/VirtualKeyboard/layouts");
qputenv("QT_VIRTUALKEYBOARD_STYLE", "style");

QApplication a(argc, argv);
...
return a.exec();

What I get from running my application in the following, which suggests that I am not importing from the right directory for whatever reason:
WARNING: Cannot find style "style" - fallback: "default"

What I've tried
As can be seen in the .qrc-file, I use the same path as they expect, e.g. .../QtQuick/VirtualKeyboard/Styles/_MYSTYLENAME_/..., where _MYSTYLENAME_ = style.
I tried putting qputenv("QML_IMPORT_PATH", "qrc:/virtual_keyboard") and qputenv("QML2_IMPORT_PATH", "qrc:/virtual_keyboard") before the lines above to enforce using styles from the .qrc-file, with no luck.
I've tried adding the following lines (below QApplication a(argc, argv) or else it wouldn't run):
QQmlEngine qml_engine;
qml_engine.addImportPath("qrc:/virtual_keyboard");

Thanks in advance for any help!


text:
Q: HTML & CSS - layout questions (using grid & flexbox) Codepen: https://codepen.io/pprunesquallor/pen/qKxvrX
I'm a beginner playing around with grid and flexbox.
I'd like the height of the article element (yellow) to be only just as long as the text requires (so in this case cca half as long), and therefore the aside element (grey) should be of the same height depending on the height of the article, and scrollable.
Thank you in advance!!

html, body {
    height: 100%;
}

body {
  display: grid;
  grid-template-columns: 1fr;
  grid-template-areas:
    "header"
    "main"
    "footer";
  align-items: stretch;
}

header {
  grid-area: header;
  display: flex;
  flex-direction: column;
  background-color: lime;
}

header > h1 {
  margin: 0;
  background-color: brown;
}

nav {
    display: flex;
    flex-direction: row;
    background-color: orange;
}

main {
  grid-area: main;
  display: flex;
  flex-direction: row;
  background-color: red;
}

article {
  background-color: yellow;
}

aside {
  width: 50%;
  overflow: auto;
  overflow-y: scroll;
  background-color: grey;
}

footer {
  grid-area: footer;
  background-color: pink;
}

Header Title

        <form style="display: inline" action="http://google.com" target="_blank">
          <button>Link 1</button>
        </form>
        <form style="display: inline" action="http://google.com" target="_blank">
          <button>Link 2</button>
        </form>
        <form style="display: inline" action="http://google.com" target="_blank">
          <button>Link 3</button>
        </form>

Article Title

        "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
        Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute Link irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean leo urna, porta ac interdum placerat, rhoncus vel lectus. Aenean consectetur condimentum augue fringilla elementum. Mauris vel fermentum nisi. Donec nec condimentum sapien. Donec feugiat consequat est ac hendrerit. Phasellus nec turpis ex. Vestibulum malesuada leo mauris. Proin posuere ultricies mauris, at varius lorem laoreet sed. Nam congue, arcu sed feugiat scelerisque, massa turpis convallis ante, eu lobortis orci leo et ex. Vivamus ut aliquet massa.

        Curabitur placerat gravida est, eu rutrum metus suscipit sit amet. Mauris placerat nibh felis, sit amet semper dolor facilisis ornare. Proin ut ultrices nisl. Aliquam laoreet porttitor ex quis elementum. Nullam nibh metus, convallis nec lectus vel, sollicitudin malesuada diam. Quisque nec semper turpis. Etiam vel eros porta, tincidunt nisl at, luctus elit. Fusce tristique nulla pharetra sagittis fermentum. Duis eget pharetra dolor, sagittis venenatis purus. Sed volutpat nisl et turpis consectetur blandit. In nunc eros, vehicula eu augue non, vehicula varius arcu. Mauris ut est elementum, tempus tellus pharetra, pretium urna. Nunc hendrerit finibus enim at efficitur. Vestibulum sagittis dolor et vehicula feugiat.

Aside

          Quisque volutpat turpis eu turpis elementum placerat. Integer auctor venenatis turpis, sit amet accumsan mi sagittis a. In scelerisque tempor dolor, sit amet mattis mi accumsan porta. Integer lacinia lobortis est sit amet bibendum. Vivamus faucibus aliquet odio vel vestibulum. Proin sit amet accumsan eros, hendrerit posuere magna. Ut et odio ac velit congue tincidunt. Suspendisse quis ex egestas, facilisis turpis id, cursus neque. Donec vulputate urna vel nisl convallis, pellentesque egestas felis placerat. Curabitur sit amet odio eget ante porttitor convallis et tempus leo. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Etiam tellus sem, pharetra ut odio id, lobortis volutpat sem. In dictum at eros at vulputate. Morbi vel dui non erat vehicula suscipit quis eu ante. Proin condimentum sem dui, at mollis justo sollicitudin quis. Duis hendrerit tempus felis.

          Morbi eget libero tristique eros porta tincidunt in et eros. Fusce tincidunt sit amet leo eu gravida. Maecenas ac imperdiet magna. Nullam tincidunt ultricies dignissim. Sed placerat leo in libero dignissim, sit amet volutpat arcu posuere. Sed consectetur eu arcu eu pulvinar. Integer varius rutrum orci, ac maximus nibh laoreet in. Duis laoreet elit quis erat fermentum luctus. Aliquam sollicitudin id odio sit amet vehicula. Sed tempor id quam vel lobortis.

          Duis accumsan, sem et suscipit dictum, enim magna ornare justo, condimentum vulputate eros felis at ex. Nulla facilisi. Nunc porttitor semper est, eget accumsan ex accumsan quis. Integer tincidunt dignissim nisl. Sed ultrices venenatis massa, sed maximus massa pharetra ac. Sed tempus tempus dolor id pulvinar. Donec rutrum, diam et condimentum sollicitudin, ex nulla faucibus quam, quis eleifend risus ante aliquam turpis.

    Footer

A:
Is there a way to do this just with CSS?

You could use positioning.
HTML: Wrap the aside content in an additional container

    ...content...

CSS:
aside {
  position: relative;
}

.aside__inner {
  position: absolute;
}

codepen

*

*If you need the header and footer to expand so that the article is only as tall as its content, you can add grid-template-rows: auto min-content auto to body.

*I'd also suggest using min-width instead width on aside

html,
body {
  height: 100%;
}

body {
  display: grid;
  grid-template-columns: 1fr;
  grid-template-areas: "header" "main" "footer";
  align-items: stretch;
  /* added */
  grid-template-rows: auto min-content auto;
}

header {
  grid-area: header;
  display: flex;
  flex-direction: column;
  background-color: lime;
}

header>h1 {
  margin: 0;
  background-color: brown;
}

nav {
  display: flex;
  flex-direction: row;
  background-color: orange;
}

main {
  grid-area: main;
  display: flex;
  flex-direction: row;
  background-color: red;
}

article {
  background-color: yellow;
}

aside {
  width: 50%;
  overflow: auto;
  overflow-y: scroll;
  background-color: grey;
  position: relative;
}

.aside__inner {
  position: absolute;
}

footer {
  grid-area: footer;
  background-color: pink;
}

Header Title

      <form style="display: inline" action="http://google.com" target="_blank">
        <button>Link 1</button>
      </form>
      <form style="display: inline" action="http://google.com" target="_blank">
        <button>Link 2</button>
      </form>
      <form style="display: inline" action="http://google.com" target="_blank">
        <button>Link 3</button>
      </form>

Article Title

      "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute
      Link irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

 Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean leo urna, porta ac interdum placerat, rhoncus vel lectus. Aenean consectetur condimentum augue fringilla elementum. Mauris vel fermentum nisi. Donec nec condimentum sapien. Donec
        feugiat consequat est ac hendrerit. Phasellus nec turpis ex. Vestibulum malesuada leo mauris. Proin posuere ultricies mauris, at varius lorem laoreet sed. Nam congue, arcu sed feugiat scelerisque, massa turpis convallis ante, eu lobortis orci
        leo et ex. Vivamus ut aliquet massa.

 Curabitur placerat gravida est, eu rutrum metus suscipit sit amet. Mauris placerat nibh felis, sit amet semper dolor facilisis ornare. Proin ut ultrices nisl. Aliquam laoreet porttitor ex quis elementum. Nullam nibh metus, convallis nec lectus
        vel, sollicitudin malesuada diam. Quisque nec semper turpis. Etiam vel eros porta, tincidunt nisl at, luctus elit. Fusce tristique nulla pharetra sagittis fermentum. Duis eget pharetra dolor, sagittis venenatis purus. Sed volutpat nisl et turpis
        consectetur blandit. In nunc eros, vehicula eu augue non, vehicula varius arcu. Mauris ut est elementum, tempus tellus pharetra, pretium urna. Nunc hendrerit finibus enim at efficitur. Vestibulum sagittis dolor et vehicula feugiat.

Aside

        Quisque volutpat turpis eu turpis elementum placerat. Integer auctor venenatis turpis, sit amet accumsan mi sagittis a. In scelerisque tempor dolor, sit amet mattis mi accumsan porta. Integer lacinia lobortis est sit amet bibendum. Vivamus faucibus aliquet
        odio vel vestibulum. Proin sit amet accumsan eros, hendrerit posuere magna. Ut et odio ac velit congue tincidunt. Suspendisse quis ex egestas, facilisis turpis id, cursus neque. Donec vulputate urna vel nisl convallis, pellentesque egestas felis
        placerat. Curabitur sit amet odio eget ante porttitor convallis et tempus leo. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Etiam tellus sem, pharetra ut odio id, lobortis volutpat sem. In dictum
        at eros at vulputate. Morbi vel dui non erat vehicula suscipit quis eu ante. Proin condimentum sem dui, at mollis justo sollicitudin quis. Duis hendrerit tempus felis.

 Morbi eget libero tristique eros porta tincidunt in et eros. Fusce tincidunt sit amet leo eu gravida. Maecenas ac imperdiet magna. Nullam tincidunt ultricies dignissim. Sed placerat leo in libero dignissim, sit amet volutpat arcu posuere.
        Sed consectetur eu arcu eu pulvinar. Integer varius rutrum orci, ac maximus nibh laoreet in. Duis laoreet elit quis erat fermentum luctus. Aliquam sollicitudin id odio sit amet vehicula. Sed tempor id quam vel lobortis.

 Duis accumsan, sem et suscipit dictum, enim magna ornare justo, condimentum vulputate eros felis at ex. Nulla facilisi. Nunc porttitor semper est, eget accumsan ex accumsan quis. Integer tincidunt dignissim nisl. Sed ultrices venenatis massa,
        sed maximus massa pharetra ac. Sed tempus tempus dolor id pulvinar. Donec rutrum, diam et condimentum sollicitudin, ex nulla faucibus quam, quis eleifend risus ante aliquam turpis.

  Footer

A: Would this do what you want? https://codepen.io/anon/pen/OEZMwV
I just added the following JS, added an ID to , and changed the display of the #info id.
$("#aside").css({
    'height': ($("#info").height() + 'px')
});

A: Here's a pen where I have this working.
https://codepen.io/anon/pen/jKKvpb
Basically, what you're asking for is not possible given the HTML/CSS you provided. The grid rows will automatically size themselves according to the height of the tallest item in the column. There's no way to grab the natural height of the
 element due to the the flex css on .
The workaround is to add a wrapper
 around the
 element. I did this with jQuery because I'm lazy but you should probably add it to the HTML. I did add some css to make the colors of the divs match up.
Here's my code:
//wrap the article in a div
jQuery('#info').wrap('

');

//a function that gets the height of the article and sets the aside to the height of the article
function sizeMe() {
    var height= jQuery('#info').height();
    jQuery('#aside').css('height', height);
}

//run the function on page load
sizeMe();

//to make it responsive run the function if the page is resized.
jQuery(window).resize( function(){
     sizeMe();
});


text:
Q: Illegal string offset issue I am on localhost and trying to create a new site. I have the Avada theme with demo content. At the bottom of the page of the demo there are social links. This message is there: Warning: Illegal string offset 'color_type' in C:\xampp\htdocs\pappas\wordpress\wp-content\themes\Avada\includes\widget\class-fusion-widget-social-links.php on line (multiple)
I am not smooth with PHP and could use some help. Below is the code that appears in that mentioned file.
if ( ! isset( $instance['tooltip_pos'] ) || '' == $instance['tooltip_pos'] )     {
        $instance['tooltip_pos'] = 'top';
    }

    if ( ! isset( $instance['icon_color'] ) || '' == $instance['icon_color']  ) {
        $instance['icon_color'] = '#bebdbd';
    }

    if ( ! isset( $instance['boxed_icon'] ) || '' == $instance['boxed_icon'] ) {
        $instance['boxed_icon'] = 'Yes';
    }

    if ( ! isset( $instance['boxed_color'] ) || '' ==        $instance['boxed_color'] ) {
        $instance['boxed_color'] = '#e8e8e8';
    }

    if ( ! isset( $instance['boxed_icon_radius'] ) || '' == $instance['boxed_icon_radius'] ) {
        $instance['boxed_icon_radius'] = '4px';
    }

    if ( ! isset( $instance['linktarget'] ) || '' == $instance['linktarget'] ) {
        $instance['linktarget'] = '_self';
    }

    if ( ! isset( $instance['color_type'] ) || '' == $instance['color_type'] ) {
        $instance['color_type'] = 'custom';
    }

    if ( isset( $instance['boxed_icon'] ) && isset(  $instance['boxed_icon_radius'] ) && 'Yes' == $instance['boxed_icon'] && ( $instance['boxed_icon_radius'] || '0' === $instance['boxed_icon_radius'] ) ) {
        $instance['boxed_icon_radius'] = ( 'round' == $instance['boxed_icon_radius'] ) ? '50%' : $instance['boxed_icon_radius'];
        $style .= 'border-radius:' . $instance['boxed_icon_radius'] . ';';
    }

    if ( isset( $instance['boxed_icon'] )  && 'Yes' == $instance['boxed_icon'] && isset( $instance['boxed_icon_padding'] )  && isset( $instance['boxed_icon_padding'] ) ) {
        $style .= 'padding:' . $instance['boxed_icon_padding'] . ';';
    }

    if ( isset( $instance['boxed_icon'] ) && 'Yes' == $instance['boxed_icon'] ) {
        $add_class .= ' boxed-icons';
    }

    if ( ! isset( $instance['icons_font_size'] ) || '' == $instance['icons_font_size'] ) {
        $instance['icons_font_size'] = '16px';
    }

    $style .= 'font-size:' . $instance['icons_font_size'] . ';';

    $social_networks = array();
    foreach ( $instance as $name => $value ) {

Any help would be appreciated. Thank you.
As I am not very seasoned in coding, please feel free to dumb down the advice!


text:
Q: If $x+y+z=1$, prove that $9xyz+1\ge 4(xy+yz+zx)$
If $x+y+z=1$, prove that $9xyz+1\ge 4(xy+yz+zx)$ for $x,y,z\in \Bbb R^+$

I tried to solve this by splitting  $9xyz$  as $3xyz+3xyz+3xyz$ and taking all the terms to the LHS before factoring, but I was unable to.
Also tried using Schur's inequality, but that didn't work either.

A: Rearranging $$9xyz+(x+y+z)^3-4(x+y+z)(xy+xz+yz)$$ gives us
$$\sum_{cyc} (x^3+xyz-x^2y-x^2z) $$
which is $\ge 0$ because it is Schur's inequality


text:
Q: Trying to create a dynamic JPA query for postgres in spring boot I am expecting 4 arrays of string containing Ids of a,b,c and d.
{
    "employeeRoles": [
        "544af3c6-fef3-45e2-ad94-1a77214ee8e0"
    ],
    "employeeTypes": [
        "7711c29f-654e-4873-876f-f3ba6a3a447a"
    ],
    "costCenter": [
        "3964e49f-b66b-4c79-b565-14251d86e650"
    ],
    "employeeStatus": [
        "1163e3ec-ea46-450a-b6b7-523895386373"
    ]
}

1st Approach :: I have created a native query.
@Query(value = "select * from employee em where (:employeeRole is null or employee_role in :employeeRole) and (:employeeType is null or employee_type in :employeeType) and (:costCenter is null or cost_center in :costCenter) and (:employeeStatus is null or empstatus in :employeeStatus)", nativeQuery = true)
List<Employee> findEmployee(
            @Param("employeeRole") Set<String> employeeRoles, @Param("employeeType") Set<String> employeeTypes, @Param("costCenter")  Set<String> costCenters,@Param("employeeStatus") Set<String> employeeStatuses);

Works great If I pass all the 4 values, But Lets say I have a scenario where I want to pass employeeRoles as null,then it gives me an error. Error at position 65.
2nd Approach :: I created a JPA query.
List<Employee> findAllByEmployeeRoleIdInAndEmployeeTypeIdInAndCostCenterIdInAndEmpstatusIdIn(
                Set<String> employeeRoles, Set<String> employeeTypes, Set<String> costCenters, Set<String> employeeStatuses);

Works great If I pass all the 4 values, But Lets say I have a scenario where I want to pass employeeRoles as null, then it gives me an error,should not pass null as value.