text:
Q: Constraint via Foreign Key I have the following schema in SQLite:
CREATE TABLE calendars
  (
     id    INTEGER PRIMARY KEY,
     title TEXT NOT NULL
  );

CREATE TABLE entry_types
  (
     id          INTEGER PRIMARY KEY,
     red         INTEGER NOT NULL CHECK(red BETWEEN 0 AND 255),
     green       INTEGER NOT NULL CHECK(green BETWEEN 0 AND 255),
     blue        INTEGER NOT NULL CHECK(blue BETWEEN 0 AND 255),
     description TEXT NOT NULL
  );

CREATE TABLE entries
  (
     id            INTEGER PRIMARY KEY,
     calendar_id   INTEGER NOT NULL,
     entry_type_id INTEGER NOT NULL,
     date          TEXT NOT NULL,
     FOREIGN KEY(calendar_id) REFERENCES calendars(id),
     FOREIGN KEY(entry_type_id) REFERENCES entry_types(id),
     UNIQUE(calendar_id, date)
  );

CREATE TABLE calendars_entry_types
  (
     calendar_id   INTEGER NOT NULL,
     entry_type_id INTEGER UNIQUE NOT NULL,
     FOREIGN KEY(calendar_id) REFERENCES calendars(id),
     FOREIGN KEY(entry_type_id) REFERENCES entry_types(id)
  );

Each entry_type can only be used for one particular calendar, which is encoded as the UNIQUE constraint in the calendars_entry_types table, restricting that many-to-many pattern to only one-to-many.

SIDEBAR: Originally I defined the entry_type table like this:
CREATE TABLE entry_types
  (
     id          INTEGER PRIMARY KEY,
     -- SNIP color & description columns
     calendar_id INTEGER NOT NULL,
     FOREIGN KEY(calendar_id) REFERENCES calendars(id)
  );

This obviated the need for the calendars_entry_types table but then the calendar_id data was in two places: in the row in entries and in the row in entry_types, so I decided to change. Perhaps this was the wrong decision? I needed to keep the calendar_id in the entries table in order to keep the UNIQUE(calendar_id, date) constraint. /SIDEBAR

This is all well and good, but I now have nothing preventing a situation like
INSERT INTO calendars (id, title) VALUES (1, 'test1'), (2, 'test2');
INSERT INTO entry_types (id, red, green, blue, description) VALUES (1, 0, 0, 0, 'entrytype1');

-- entry_type id 1 goes with calendar id 1
INSERT INTO calendars_entry_types (calendar_id, entry_type_id) VALUES (1, 1);

-- this shouldn't work... calendar 2 doesn't go with entry_type 1
INSERT INTO entries (calendar_id, entry_type_id, date) VALUES (2, 1, 'entry1');  -- (I know that's not a date but this is just an example...)

Is it possible to write a constraint that would prevent the insertion of rows to the entries table that match this query?
SELECT id
FROM   entries
WHERE  ( calendar_id, entry_type_id ) NOT IN (SELECT calendar_id,
                                                     entry_type_id
                                              FROM   calendars_entry_types);

If not, is there a better or alternative way to design my schema that takes the "each entry type is only valid for a certain calendar" constraint into account?

A: You only need some small changes. First add a UNIQUE constraint on calendars_entry_types (this is needed for the new foreign key below):
UNIQUE (calendar_id, entry_type_id)

Then remove these two foreign keys from entries:
FOREIGN KEY (calendar_id) REFERENCES calendars (id),
FOREIGN KEY (entry_type_id) REFERENCES entry_types (id),

and replace them with a composite one:
FOREIGN KEY (calendar_id, entry_type_id)
    REFERENCES calendars_entry_types (calendar_id, entry_type_id),


text:
Q: In command line, what does "python file.py shell" do? I have run into a Django tutorial where the instructor is running python manage.py shell.
This yields:
(env) MBP:Project user$ python3 manage.py shell

Python 3.7.6 (default, Jan  8 2020, 13:42:34)
[Clang 4.0.1 (tags/RELEASE_401/final)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)

Couple questions:

*

*What does shell do in python manage.py shell?

*What does (InteractiveConsole) in the above mean ? I don't see this when I run python without the shell. I have googled InteractiveConsole to no avail.

*What is "being done" to manage.py here? Is it being "run" or "served"?

A: *

*When you run python manage.py shell you run a python (or IPython) interpreter but inside it load all your Django project configurations so you can execute commands against the database or any other resources that are available in your Django project.

*If you run python manage.py you only display all the options available to use with the 'manage.py' script in your project (like runserver or migrate)

*In the shell, your project is not running as a http service but you can perform operations like querying the database or calling internal functions.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use "open in..." feature to iOS app? I'm not looking to add my app to the "open in..." list, but to get the list itself. And sending the file to another app.
I'm working on internal communication app, so when user receive a file attachment, s/he can open the file with whatever app is installed on each devices...

A: Look at UIDocumentInteractionController  https://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIDocumentInteractionController_class/Reference/Reference.html and here https://developer.apple.com/library/ios/#documentation/FileManagement/Conceptual/DocumentInteraction_TopicsForIOS/Articles/OpeningSupportedFileTypes.html#//apple_ref/doc/uid/TP40010412-SW1

A: UIDocumentInteractionController *controller = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:appFile]];
        self.controller.delegate = self;
CGRect navRect = self.view.frame;
[self.controller presentOptionsMenuFromRect:navRect inView:self.view animated:YES];

Implement following UIDocumentInteractionControllerDelegate methods
#pragma mark - UIDocumentInteractionControllerDelegate

//===================================================================
- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller
{
    return self;
}

- (UIView *)documentInteractionControllerViewForPreview:(UIDocumentInteractionController *)controller
{
    return self.view;
}

- (CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController *)controller
{
    return self.view.frame;
}

A: Another option :
use UIActivityViewController as available from iOS 6.0 > version
//create instance with file URL
UIActivityViewController *activity = [[UIActivityViewController alloc] initWithActivityItems:@[fileURLHere] applicationActivities:nil];
//present it
[self presentViewController:activity animated:YES completion:NULL];

Note : There might be problem using UIDocumentInteractionController. Check uidocumentinteractioncontroller-stopped-working-ios-8


text:
Q: Checking integer lists under a column for each record to tag/classify each record (SQL) - reverse index match (or some other way)? I have a problem I'm trying to resolve. I'd love to get your ideas or help with the method I have in my mind. I created a good analogy for it: I need to tag each record in a table if they're partial purchases or not. It is clearer if you can look at the example below:
I have products classified as Level 2 and Level 1. And each Level 1 product is associated with one or more level 2 products. I only need to check Level 1 purchases, because Level 2 ones can't be partial purchase.
Partial purchase: If a customer who purchased Level 1 product didn't purchase any of the associated Level 2 products, that purchase is partial.
It should be simple, but the columns I have hold the necessary information in a weird way.
Method I have in mind:
For each level 1 purchase

*

*Get all the Level 2 purchases from that customer with a cte

*Check the product dependency columns of those:
if this level 1 product's product ID is in any of those lists(!) it's not a partial purchase. If not it's partial.

This should work, but I can't get it to work in SQL.
My question:

*

*How can I check the each element in each list in the entire column for all the Level 2 purchases from that customer? Because I don't have any way of associating these level 1 & level 2 purchases based on their product dependencies.

example image showing the columns etc. - first three records here should explain enough about the problem & the expected result
Any help is appreciated, I'm a bit slow on SQL
What we have is PostgreSQL through Redash

A: You can do it using unnest() function of postgresql. This function are converted array list to row for easily using.
I don't know type of your product_dependency field. If this field is not a int array so you can convert this field to array using string_to_array() function and after then use unnest().
I wrote an example for you:
select * from your_table t1
where
    t1.product_level = 'Level 1' and
    t1.product_id not in (select unnest(product_dep) from your_table where customer_id = t1.customer_id)

And result (gets only partial purchases):
id  customer_id product_id  product_level
3   B           1           Level 1
6   D           5           Level 1

A: I will write an alternative query for you:
Example:
select
    t1.id, t1.customer_id, t1.product_id, t1.product_level,
    case when product_level = 'Level 1' then (t1.product_id not in (select unnest(product_dep) from your_table where customer_id = t1.customer_id)) else false end as partial_purchase
from your_table t1

Result:
id  customer_id product_id  product_level   partial_purchase
1   A           1           Level 1         false
2   A           2           Level 2         false
3   B           1           Level 1         true
4   C           3           Level 2         false
5   C           4           Level 1         false
6   D           5           Level 1         true
7   D           6           Level 2         false

You can use this query in your subquery for easily filtering like as:
where partial_purchase = true
or
where partial_purchase = false
or
where product_id = <id>


text:
Q: Using column index, how to copy specific columns New day, new problem.
I have received much help, and hope you can help me with this too. Have searched around for solutions to my problem but not found.
Here is my code:
SearchString = "start"
    Set aCell = phaseRange.Find(What:=SearchString, LookIn:=xlValues, _
            LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
            MatchCase:=False, SearchFormat:=False)
If Not aCell Is Nothing Then
    Set bCell = aCell
    ReDim Preserve arrStart(nS)
    arrStart(nS) = aCell.Row
    nS = nS + 1
    Do While ExitLoop = False
        Set aCell = phaseRange.FindNext(After:=aCell)
        If Not aCell Is Nothing Then
            If aCell.Row = bCell.Row Then Exit Do
            ReDim Preserve arrStart(nS)
            arrStart(nS) = aCell.Row
            nS = nS + 1
        Else
            ExitLoop = True
        End If
    Loop
Else
End If

And to write it out:
For i = 1 To nS - 1
        Sheets("DataSheet").Select
        Sheets("raw_list").Rows(arrStart(i)).Copy
        Cells(i, 1).Select
        ActiveSheet.Paste
Next

As you see, I seek in a column for a String. When I get a result, row number is stored in an array. In the next code snippet, I write out hits in entire rows. Is it possible that instead of taking the entire row, choose which columns in that row you want to copy in a simple way?
Grateful for assistance

A: If you already know the Column number and you have the rows in array then try this
Sheets("raw_list").Cells(arrStart(i),5).Copy

This will copy the cell from the 5th Column (Col E) in a specific row.


text:
Q: Dynamically selecting multiple values from XML in SQL Server I have many large XML documents with totally different structure with many differing levels of elements that I want to select several dozen items from. The issue is there are many different document types in entirely different namespaces that I all have similar information. So I wanted to make the select data driven.
I have a table, let's call it metadata. Imagine f1 might be someone's name, f2 their account number, f3 a telephone number, etc.:
doctype    fldid     xpath
---------  --------  --------------------------
abc        f1        /document/g/h[1]
abc        f2        /document/k/j/p/r/p[1]
abc        f3        /document/a/e/d[1]
def        f1        /info/d[1]
def        f2        /info/r/e/d[1]
def        f3        /info/e/s[1]

And we have the data table, called mydatatable:
docid    doctype    docfield
-------  ---------  ------------------------
1        abc        <document><n>.....

So I figured I could just do a query:
select
    metadata.fldid as fldid,
    mydatatable.docfield.value(metadata.xpath, 'nvarchar(max)') as data
from
    mydatatable
inner join
    metadata on mydatatable.doctype = metadata.doctype
where
    mydatatable.docid = 1

I was expecting output:
fldid   data
------  --------------
f1      Tom
f2      344534534
f3      999-555-1212

But instead, I get this error:

The argument 1 of the XML data type method "value" must be a string literal.

So this means I need to know all the document structure ahead of time or I need to cursor through the metadata table and put the query into dynamic SQL in order to create this query?
Please note, I'm not talking about multiple nodes with the same element names. I'm talking about all different element names with differing (or similar) xpaths.

A: Yes, you would need dynamic SQL to do this. But you do not need a cursor, just build up the query and execute it one go.
I think you could probably just build up a series of if else XQuery expressions, in your case the code would produce
if(sql:column("md.xpath") = "/document/g/h[1]") then '/document/g/h[1]'
else if(sql:column("md.xpath") = "/document/k/j/p/r/p[1]") then '/document/k/j/p/r/p[1]'
else if(sql:column("md.xpath") = "/document/a/e/d[1]") then '/document/a/e/d[1]'
else if(sql:column("md.xpath") = "/info/d[1]") then '/info/d[1]'
else if(sql:column("md.xpath") = "/info/r/e/d[1]") then '/info/r/e/d[1]'
else if(sql:column("md.xpath") = "/info/e/s[1]") then '/info/e/s[1]'
else ()

So you could use dynamic SQL like this:

I've parameterized @docid, you don't have to do this, you could enter a literal like you hav done, but don't directly inject data from elsewhere.

Note correct use of QUOTENAME to escape the strings

DECLARE @xq nvarchar(max) = (
    SELECT STRING_AGG(CAST(
      'if(sql:column("md.xpath") = ' + QUOTENAME(md.xpath, '"') + ') then ' + QUOTENAME(md.xpath, '''')
      AS nvarchar(max)), '
else ')
      + '
else ()'
    FROM metadata md
);

DECLARE @sql nvarchar(max) = N'
select
  md.fldid,
  dt.docfield.value(''(
' + @xq + ''')[1]'',''nvarchar(max)'') as data
from mydatatable dt
inner join metadata md on dt.doctype = md.doctype
where dt.docid = @docid;
';

PRINT @sql;  -- for testing

DECLARE @docid int = 1;

EXEC @sp_executesql
  @sql,
  N'@docid int',
    @docid = @docid;


text:
Q: Running exe in Powershell with parameters I am trying to change from using a cmd file to Powershell script so that I can include email alerting on failure.
Current script looks like this:
"C:\Program Files\Actian\PSQL\PBA\BIN\pvbackup64.exe" -on
"C:\Program Files\Actian\PSQL\PBA\BIN\pvbackup64.exe" -status > $Log

I tried using Start-Process, but cannot get it working

A: What you need is the invocation operator (&):
$Log = "path\to\log.file"
& "C:\Program Files\Actian\PSQL\PBA\BIN\pvbackup64.exe" -on
& "C:\Program Files\Actian\PSQL\PBA\BIN\pvbackup64.exe" -status > $Log

Beware that the > file redirection operator in Windows PowerShell always uses unicode encoding, and you might want to replace it with the Set-Content cmdlet instead:
$Log = "path\to\log.file"
& "C:\Program Files\Actian\PSQL\PBA\BIN\pvbackup64.exe" -on
& "C:\Program Files\Actian\PSQL\PBA\BIN\pvbackup64.exe" -status |Set-Content -LiteralPath $Log


text:
Q: Need to add text file entries to simple one line/command bash script Basically I need to execute a curl command multiple times and redirect the output to a .csv file, each time the command is executed a term that is used in two separate places in the command is changed.  I do have a list of these terms (arguments?) contained in a separate text file.  Each time the command runs for a different term, the output needs to be appended to the file.
The command is basically:
curl "http://someURL/standardconditions+AND+(TERM_exact+OR+TERM_related)" > testfile.csv

So each time the command is run, TERM changes in both places (TERM_exact and TERM_related).  As I mentioned, I have a text file that has a list of all 60 or so terms, what I want is the script to execute the command using the first term on the list, write the output to the specified .csv file and then repeat with the second term on the list, append that to the file and so on and so forth until it's been run for every single term.
I imagine there is a simple way to do this, I'm just not sure how.

A: Here's one way to do it,
This assumes that listFile.csv is your list of 60 items, and that each line is a comma-separated pair of values (no commas allowed in values!)
while IFS=, read exact related ; do
   curl "http://someURL/standardconditions+AND+(TERM_${exact}+OR+TERM_${related})" >> testfile.csv
done < listFile.csv

It's not clear if you wanted one output file, or multiple.
You could replace the >> testfile.csv with >>testfile.${exact}_${related}.csv
to have separate files.
IHTH

A: You can set a variable to store TERM, and use concat function to get a string like
"http://someURL/standardconditions+AND+(TERM_exact+OR+TERM_related)", and run a python(may be other language)script including loop structure to handle 60 terms.


text:
Q: Typescript - extending object's type progressively I am trying to achieve the following with TS:
let m: Extendable
m.add('one', 1)
// m now has '.one' field
m.add('two', 2)
// 'm' now has '.one' and '.two' fields

I'm familiar with returning extended types in TS via:
function extend<T, V>(obj: T, val: V): T & {extra: V} {
    return {
        ...obj,
        extra: val
    }
}

Now, there are two issues in my case:
1) object m needs to update its type after the add() has been called to reflect addition of a new field
2) new field's name is parameterized (ain't always extra e.g.)
First issue might be resolved by using class definition and somehow using TypeThis utility to re-adjust the type, but I wasn't able to find enough documentation about how to use it.
Any help or guidance is welcome. Thanks!

A: TypeScript 3.7 introduced assertion functions which can be used to narrow the type of passed-in arguments or even this.  Assertion functions look kind of like user-defined type guards, but you add an asserts modifier before the type predicate.   Here's how you could implement Extendable as a class with add() as an assertion method:
class Extendable {
    add<K extends PropertyKey, V>(key: K, val: V): asserts this is Record<K, V> {
        (this as unknown as Record<K, V>)[key] = val;
    }
}

When you call m.add(key, val) the compiler asserts that m will have a property with key with the type of key and a corresponding value with the type of val. Here's how you'd use it:
const m: Extendable = new Extendable();
//     ~~~~~~~~~~~~ <-- important annotation here!
m.add('one', 1)
m.add('two', 2)

console.log(m.one.toFixed(2)); // 1.00
console.log(m.two.toExponential(2)); // 2.00e+0

That all works as you expect.  After you call m.add('one', 1), you can refer to m.one with no compiler warning.
Unfortunately there's a fairly major caveat; assertion functions only work if they have an explicitly annotated type.  According to the relevant pull request, "this particular rule exists so that control flow analysis of potential assertion calls doesn't circularly trigger further analysis."
That means the following is an error:
const oops = new Extendable(); // no annotation
  oops.add("a", 123); // error!
//~~~~~~~~ <-- Assertions require every name in the call target to be declared with
// an explicit type annotation.

The only difference is that the type of oops is inferred to be Extendable instead of annotated as Extendable as m is.  And you get an error calling oops.add().  Depending on your use case this could either be no big deal or a showstopper.

Okay, hope that helps; good luck!
Link to code


text:
Q: python code for multiple ode I want to write a fourth order Adams Bashforth to solve the system. And the following is what I have :
the system is in the following link:
system we have
def AdamsBashforth4( f, x0, t ):
    """
    Fourth-order Adams-Bashforth method::

    u[n+1] = u[n] + dt/24.*(55.*f(u[n], t[n]) - 59*f(u[n-1], t[n-1]) +
                            37*f(u[n-2], t[n-2]) - 9*f(u[n-3], t[n-3]))

    for constant time step dt.

    RK2 is used as default solver for first steps.
    """
    n = len( t )
    x = numpy.array( [ x0 ] * n )

    for i in xrange( n - 1 ):
        h = t[i+1] - t[i]
        f0 = f( x[i], t[i] )
        k1 = h * f0
        k2 = h * f( x[i] + 0.5 * k1, t[i] + 0.5 * h )
        k3 = h * f( x[i] + 0.5 * k2, t[i] + 0.5 * h )
        k4 = h * f( x[i] + k3, t[i+1] )
        x[i+1] = x[i] + h * ( 55.0 * f0 - 59.0 * k1 + 37.0 * k2 - 9.0 * k3 ) / 24.0

    return x

Am I right?
When I execute it, it gives me the following error message (P.S.: defining the system using the link: link)
>>>X = AdamsBashforth4(equation, init, t)

Traceback (most recent call last):
  File "<pyshell#21>", line 1, in <module> X = AdamsBashforth4(equation, init, t)
  File "<pyshell#20>", line 15, in AdamsBashforth4 f0 = f( x[:-1], t[:-1] )
  File "<pyshell#11>", line 2, in equation x, y = X
  ValueError: too many values to unpack


text:
Q: Java catch different exceptions public class ExceptionHandler {

    public static void main(String[] args) throws FileNotFoundException, IOException {
    // write your code here
        try {
            testException(-5);
            testException(11);
        } catch (FileNotFoundException e){
            System.out.println("No File Found");
        } catch (IOException e){
            System.out.println("IO Error occurred");
        } finally { //The finally block always executes when the try block exits.
            System.out.println("Releasing resources");
            testException(15);
        }
    }

    public static void testException(int i) throws FileNotFoundException, IOException {
        if (i < 0) {
            FileNotFoundException myException = new FileNotFoundException();
            throw myException;
        }
        else if (i > 10) {
            throw new IOException();
        }
    }
}

The output of this code gives
No File Found
Releasing resources
Is it possible to have java catch both IOException as well as FileNotFoundException? It seems to be only able to catch the first exception and doesn't catch the IOException

A: The try block stops at the first exception thrown, therefore the second call of testException() is never executed.

A: You should enclose your try/catch/finally block inside another try/catch block because your finally block can throw exceptions that must be captured.
Here is how your code works:

*

*testException(-5) throws a FileNotFoundException

*FileNotFoundExceptionis catched by catch (FileNotFoundException e)

*No File Found is printed into the standard output

*Then finally block is executed (the testException(10) sentence is not executed).

*So Releasing resources is printed

*And testException(15) is executed throwing an IOException that is not captured anyway (the program will be interrupted).

If you remove the throws FileNotFoundException, IOException from your main method the compiler will alert you that an exception is not being captured (the one in the finally block).


text:
Q: Angular application in custom url path, with ServiceWorker I am developing a Angular 10 application.
It uses the Angular "service worker" to create a PWA.
The compiled application is in "c:\-website-folder-\ng-app\dist". Then the user can access to App with a URL like this: "https://website.com/ng-app/dist".
Configuration of ServiceWorker
Angular ServiceWorker is configured in "app.module":
@NgModule({
    imports: [
        CommonModule,
        BrowserModule,
        ServiceWorkerModule.register(
            `/ng-app/dist/ngsw-worker.js`,
            {
                enabled: true,
                scope: "/ng-app/"
            }
        ),
        ...
    ]
})
export class AppModule {}

The registration ask the path of ServiceWorker.
Project compilation
The Angular project is compiled with ng build command.
It create and fill the "dist" folder. It contains "ng-app.webmanifest" and "ngsw.json".
"ngsw.json" file
The "ngsw.json" file contains a list of all compiled JS and Assets, like GIF, CSS.  The Angular ServiceWorker uses this file to cache resources.
{
  "configVersion": 1,
  "timestamp": 1613033261333,
  "index": "/index.html",
  "assetGroups": [
    {
      "name": "app",
      "installMode": "prefetch",
      "updateMode": "prefetch",
      "cacheQueryOptions": {
        "ignoreVary": true
      },
      "urls": [
        "/address-book-editor-address-book-editor-module-es2015.51b00058cbaa9682510e.js",
        "/address-book-editor-address-book-editor-module-es5.51b00058cbaa9682510e.js",
        "/article-editor-article-editor-module-es2015.e4540348b2495fd50875.js",
        "/article-editor-article-editor-module-es5.e4540348b2495fd50875.js",
        "/berry-editor-berry-editor-module-es2015.8cc1850fb1455965c490.js",
        "/berry-editor-berry-editor-module-es5.8cc1850fb1455965c490.js",
        ...
      ],
      "patterns": []
    },
    {
      "name": "assets",
      "installMode": "lazy",
      "updateMode": "prefetch",
      "cacheQueryOptions": {
        "ignoreVary": true
      },
      "urls": [
        "/assets/components/fontawesome/fonts/fontawesome-webfont.eot",
        "/assets/components/fontawesome/fonts/fontawesome-webfont.svg",
        "/assets/components/fontawesome/fonts/fontawesome-webfont.ttf",
        ...
      ],
      "patterns": []
    }
  ],
  "dataGroups": [],
  "hashTable": {
    "/address-book-editor-address-book-editor-module-es2015.51b00058cbaa9682510e.js": "4e6b67457c4b7549f331e6c2cbe3334d13129386",
    "/address-book-editor-address-book-editor-module-es5.51b00058cbaa9682510e.js": "886188af27941dad766bcdcb3e2880b790cf32de",
    "/article-editor-article-editor-module-es2015.e4540348b2495fd50875.js": "985558c2949d9b34d3cdc9e0b7d556d54508b208",
    ...
  },
  "navigationUrls": [
    {
      "positive": true,
      "regex": "^\\/.*$"
    },
    {
      "positive": false,
      "regex": "^\\/(?:.+\\/)?[^/]*\\.[^/]*$"
    },
    {
      "positive": false,
      "regex": "^\\/(?:.+\\/)?[^/]*__[^/]*$"
    },
    {
      "positive": false,
      "regex": "^\\/(?:.+\\/)?[^/]*__[^/]*\\/.*$"
    }
  ]
}

The problem
As you can see, the resources are referenced to ROOT, and Angular ServiceWorker will try to download theese with URL like this

*

*https://website.com/---resource---
instead of

*

*https://website.com/ng-app/dist/---resource---
Help
There is a solution to say to Angular Builder to specify the right URL path?
I am try to change the "ngsw.json" file with right path, and now it works. But it is a Trick...
Thanks very much

A: One way to modify paths that Angular generates while building is to use the --deploy-url option with CLI's ng build. In combination with --base-href you can modify paths to some degree but might still get stuck if you use server-side rendering or server-side locales/cultures for instance. But for simple deployment combination of both should work.
That said, unfortunately, only the value of --base-href is included in paths that get generated within the ngsw.json file. This is a problem with Angular CLI and so far hasn't been addressed.
A workaround is to run the ngsw-config command providing it with base href parameter as the last parameter/option.
For example, what you could do is
if your --base-href is /web/ and your --deploy-url is dist/ which when deployed results in your paths being /web/dist/
so for these kinds of paths getting generated correctly in ngsw.json file you'd have to run the following command manually:
./node_modules/.bin/ngsw-config ./dist/ ./ngsw-config.json "/web/dist/"

I went a step further and used npm post scripts (https://michael-kuehnel.de/tooling/2018/03/22/helpers-and-tips-for-npm-run-scripts.html) and configured my package.json like this
...
"build:prod": "ng build --prod --base-href=\"/web/\" --deploy-url=\"dist/\"",
"postbuild:prod": "ngsw-config ./dist/ ./ngsw-config.json \"/web/dist/\"",
...

That way the postbuild:prod always runs after the build:prod cmd.
Hope that helps. I too wish Angular CLI would offer more options for customizing paths in deployed files.


text:
Q: http/post Anti-forgery token with :edn-params I have the following setup:

*

*Macchiato framework for the backend (i.e. ClojureScript on node.js), which models handling  on Ring.

*Frontend consisting of a small React App to edit data stored in an atom (tracking various inputs).

I want to make the data stored in that atom persistent by posting it to a handler in my back end. The most straightforward way of doing this would seem to just take the data straight from the atom and do the following:
(http/post "https://post.here.url"
                                {:edn-params
                                 @my-atom})

However: By default Macchiato requires POST requests to include an anti-forgery token (which I'm currently storing as an attribute to one of my HTML elements; please tell me in case this is bad practice). So I tried the following:
(http/post "https://post.here.url"
                                {:edn-params
                                 {:data @my-atom
                  :__anti-forgery-token "SuperSecretToken"}})

This doesn't work, however, since the token is rejected as invalid. The anti-forgery token seems to be processed correctly only if I declare the data as :form-params:
(http/post "https://post.here.url"
                                {:form-params
                                 {:data (str @my-atom)
                  :__anti-forgery-token "SuperSecretToken"}})

The method above does work, but ,of course, the MIME type is not set correctly and I have to do some hula-hooping to make the EDN data available on the server side. The approach simply does seem wrong. Is there a way to serialize the EDN data properly and still transmit the anti-forgery token?
I'm still quite new to this stuff, so maybe I'm missing something basic. Am I wrong about the purpose of the anti-forgery token in general? Does it only make sense when transmitting form data (which my data actually is; it's just that posting the atom directly would make reloading the stored data much easier).
Many thanks for any input you may give me!
Oliver

A: This is a bit tricky to figure out with how the docs are set up right now, but here are 3 useful pieces of information:

*

*https://macchiato-framework.github.io/api/core/macchiato.middleware.anti-forgery.html

*https://github.com/macchiato-framework/macchiato-core/blob/master/src/macchiato/middleware/defaults.cljs#L83

*https://macchiato-framework.github.io/docs/restful-middleware.html
If you use the wrap-defaults middleware wrapper then, you can pass in an options value, which is either truthy (enabling the default anti forgery behavior as you observe), or an option map, which the doc in [1] says takes an optional :read-token function.
Put together, plus the rest-middleware in [3], here's one way to implement the anti-forgery check that accepts the default (form params) or a json payload (body-params):
(-> handler
    ;; note: the wrapped middleware request processing
    ;; is handled _bottom-up_ in this chain
    (defaults/wrap-defaults
     (-> defaults/site-defaults
         (assoc-in [:security :anti-forgery]
                   {:read-token (fn [request]
                                  (or
                                   ;; check the custom key we set upstream (but in the block below)
                                   (get-in request [:anti-forgery-payload])
                                   ;; default behavior
                                   (anti-forgery/default-request-token request)))})))
    (middleware/wrap
     (fn extract-anti-forgery-payload [handler]
       (fn [request respond raise]
         (handler
          (if-let [anti-forgery-payload
                   (get-in request [:body "__anti-forgery-token"])]
            (-> request
                ;; add our custom anti-forgery key to the request
                (assoc :anti-forgery-payload anti-forgery-payload)
                ;; remove the special key from the request to downstream handlers
                (update :body dissoc "__anti-forgery-token"))
            request)
          respond raise)))
     {})
    ;; decodes the json input into maps
    (macchiato.middleware.restful-format/wrap-restful-format))


text:
Q: Spring Boot App can't access PostgreSQL using credentials from Kubernetes secret I'm not an expert when it comes to Kubernetes so, for learning, I started building a simple Spring Boot web application (called meal-planner) which reads and writes to a PostgreSQL database.
PostgreSQL and Spring Boot app are deployed in Kubernetes which is running on (currently) two Raspberry Pis (model 3 and 3B+).
I work in the namespace home and have created a Deployment and Service for each (Postgres and Spring Boot application.).
I have created a secret defining credentials which I use to create the database and as database credentials in the Spring Boot application.
Productively, I wouldn't put the database in the Kubernetes cluster, but with the Raspberry Pi, I don't care since the data is worthless.
Describing the secret yields:
Name:         dev-db-secret
Namespace:    home
Labels:       <none>
Annotations:  <none>

Type:  Opaque

Data
====
password:  20 bytes
username:  7 bytes

The application.yaml is the following:
spring:
  jpa:
    database-platform: org.hibernate.dialect.PostgreSQLDialect
    open-in-view: false
    hibernate:
      ddl-auto: update
  datasource:
    url: "jdbc:postgresql://postgres:5432/home"
    username: ${DB_USER}
    password: ${DB_PASSWORD}

I used the following Dockerfile for building the Spring Boot application:
FROM arm32v7/openjdk:11-jdk
ARG JAR_FILE=target/*.jar
COPY ${JAR_FILE} app.jar
ENTRYPOINT ["java","-jar","/app.jar"]

And I build it on a Windows 10 PC using docker buildx build --platform linux/arm/v7 -t ... --push.
Kubernetes finds and deploys it just fine.
The following is the Service and Deployment for the PostgreSQL DB:
kind: Service
apiVersion: v1
metadata:
  name: postgres
  namespace: home
  labels:
    app: postgres
spec:
  type: NodePort
  selector:
    app: postgres
  ports:
    - port: 5432
      targetPort: 5432
      name: postgres
---
kind: Deployment
apiVersion: apps/v1
metadata:
  name: postgres
  namespace: home
spec:
  replicas: 1
  selector:
    matchLabels:
      app: postgres
  template:
    metadata:
      labels:
        app: postgres
    spec:
      containers:
        - name: postgres
          image: postgres:13.2
          imagePullPolicy: IfNotPresent
          env:
            - name: POSTGRES_USER
              valueFrom:
                secretKeyRef:
                  name: dev-db-secret
                  key: username
            - name: POSTGRES_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: dev-db-secret
                  key: password
            - name: POSTGRES_DB
              value: home
          ports:
            - containerPort: 5432
          volumeMounts:
            - mountPath: /var/lib/postgresql/data
              name: postgres-data
      volumes:
        - name: postgres-data
          persistentVolumeClaim:
            claimName: postgres-pv-claim
---

The deployment works fine and I can access the database using an SQL client (like DBeaver) using the credentials in the dev-db-secret secret (when I port-forward the service using kubectl port-forward service/postgres -n home 5432:5432).
I use the following deployment descriptor for the Spring-Boot application.
kind: Service
apiVersion: v1
metadata:
  name: meal-planner
  namespace: home
  labels:
    app: meal-planner
spec:
  type: NodePort
  selector:
    app: meal-planner
  ports:
    - port: 8080
      targetPort: 8080
      name: meal-planner
---
kind: Deployment
apiVersion: apps/v1
metadata:
  name: meal-planner
  namespace: home
spec:
  replicas: 1
  selector:
    matchLabels:
      app: meal-planner
  template:
    metadata:
      labels:
        app: meal-planner
    spec:
      containers:
        - name: meal-planner
          image: 08021986/meal-planner:v1
          imagePullPolicy: Always
          env:
            - name: DB_USER
              valueFrom:
                secretKeyRef:
                  name: dev-db-secret
                  key: username
            - name: DB_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: dev-db-secret
                  key: password
          ports:
            - containerPort: 8080
---

The application deploys and starts just fine. However, when I kubectl port-forward service/meal-planner -n home 8080:8080 and call the "Read all data from DB"-Endpoint, I get the following error:
...
Caused by: org.hibernate.exception.GenericJDBCException: Unable to open JDBC Connection for DDL execution
...
Caused by: org.postgresql.util.PSQLException: FATAL: password authentication failed for user "<<username from secret>>"

When I start the application locally, port-forward the DB-Service (and replace the datasource URL in the application.yaml file with jdbc:localhost://postgres:5432/home), everything works perfectly.
I don't understand why the PostgreSQL uses the secret to create the credentials - which are clearly working, since I can access the database using a client or with the application running locally, but the authentication fails for the Spring Boot service (which still seems to be able to fetch the username from the secret).
What am I doing wrong?
For completeness of the deployment descriptors, here the namespace, persistent volume and claim descriptor:
apiVersion: v1
kind: Namespace
metadata:
  name: home
---
apiVersion: v1
kind: PersistentVolume
metadata:
  name: pv-volume
  namespace: home
  labels:
    type: local
spec:
  storageClassName: manual
  capacity:
    storage: 10Gi
  accessModes:
    - ReadWriteOnce
  hostPath:
    path: "/mnt/data"
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: postgres-pv-claim
  namespace: home
spec:
  storageClassName: manual
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 5Gi

Code can be found on https://github.com/Urr4/deployments and https://github.com/Urr4/meal-planner
Update:
After completely removing the secret and adding the credentials by hand to the application.yaml file, I still get the same error.
I'm now assuming, that I can't reach the PostgreSQL service from the meal-planner pod, meaning the service can't connect to the database and thus fails authentication, not because of credentials.
I tried kubectl exec <<meal-planner-pod-id>> -n home -- ping postgres:5432 and got ping: postgres:5432: Name or service not known.
I also tried postgres.default:5432 and postgres.home:5432 without success.
Running k exec <<meal-planner-pod-id>> -n home -- wget -O- postgres yields Connecting to postgres (postgres)|10.43.62.32|:80... failed: Network is unreachable. which sounds like an error, which I don't know how to fix.
I still don't know what the problem is.
Update:
I've started a BusyBox, because I can't prevent the meal-planer from crashing and kubectl exec -it into the BusyBox pod and execute telnet postgres.home 5432 which yields telnet connected. wget -O- postgres.home still yields Network is unreachable.
I tried telnet on the meal-planer pod, but it just tells me telnet: not found.
I think postgres (or postgres.home) is the right DNS name, since in that case I get the Network is unreachable. For non-existent services I get Name or service not known.
I currently think there is some kind of network issue which prevents pods from communicating, but I don't know how to find and fix this.
After debugging in the completely wrong direction, I'm going to close this question in favor of asking it again, but more precisely and smaller. The new question can be found here.

A: The service created for PostgreSQL should be of type ClusterIP. If you are using NodePort, you will be able to access PostgreSQL using NodeIP:NodePort. Since both the instances are within the namespace, you can change type to ClusterIP.
Also, you can change the environment variable name in the deployment meal-planner.
DB_USER -> username
DB_PASSWORD -> password


text:
Q: preg replace with method inside it echo preg_replace("#\[map\](.+)\[\/map\]#e", '[link=maps.php/".$map_id[array_search("$1", $map_name)]."/$1/]$1[/link]', $text);

is my try.
I want to replace
[map]map_name[/map]

to
[link]maps.php/id/map_name[/link]

I have two arrays, $map_id and $map_name. They contain the exact same items and items are connected with the same key, eg: $map_id[123] that ID is for that map: $map_name[123].
My preg_replace does not work as it returns: Failed evaluating code: [link=maps.php/".in_array("ksz_luminous", $map_name)."/ksz_luminous/]ksz_luminous[/link]

A: You should not use the e flag. Suppose I used this:
[map]",array())].shell_exec("evil command of evil").$map_id[array_search("[/map]

Or something like that.
Anyway, try this:
echo preg_replace_callback("(\[map\](.+?)\[/map\])i",
    function($m) use ($map_id,$map_name) {
        return "[link=maps.php/"
           .$map_id[array_search($m[1], $map_name)]
           ."/".$m[1]."/]".$m[1]."[/link]";
    }, $text);


text:
Q: Get Error when i ADD CONSTRAINT ON DELETE CASCADE in SQL Server I am trying to create CONSTRAINT but sql server gives me an error.

Msg 1750, Level 16, State 0, Line 3
  Introducing FOREIGN KEY constraint 'FK_Product_SubCategory' on table
  'Product' may cause cycles or multiple cascade paths. Specify ON
  DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY
  constraints.

and here is my table
CREATE TABLE [dbo].[Product]
(
    [ProductId]       INT          IDENTITY (1, 1) NOT NULL,
    [ProductName]     NCHAR (30)   NOT NULL,
    [ProductPrice]    DECIMAL (18) NOT NULL,
    [ProductQuantity] INT          NULL,
    [SubCategoryId]   INT          NOT NULL,

    PRIMARY KEY CLUSTERED ([ProductId] ASC)
);

And
ALTER TABLE [dbo].[Product] WITH NOCHECK
ADD CONSTRAINT [FK_Product_SubCategory]
    FOREIGN KEY ([SubCategoryId])
    REFERENCES [dbo].[SubCategory] ([SubCategoryId])
    ON DELETE CASCADE;


text:
Q: Angular. Module structuring May be I need only explanation (without answer to my question, it could be not valid in some explanation cases). Studying angular I've found how to create new module using angular-cli. ...but I have no idea how to use if from main module. To be close with angular I've tried next experiment.
I've generated a modules:
$  ng generate module myTestModule
installing module
  create src/app/my-test-module/my-test-module.module.ts

$  ng generate module myTestModule2
installing module
  create src/app/my-test-module2/my-test-module2.module.ts

1.
I have usual file describes the main module app.module.ts. I could register module my-test-module.module.ts in the app.module.ts and my-test-module2.module.ts in the my-test-module.module.ts. How could it make my application better?
2.
I red splitting application on many modules provides better performance. But I confused with this. If I use some data loading functionality to URI1 module1 loads data, I navigate to URI2 module1 is deactivated, but module2 loads data. If I navigate back module1 is staying active one more time and loads same data second time! Have I missed something in angular?
3.
How I can get benefits from module structuring with angular?

A: On #2 - could you give more details? Do module1 and module2 execute same request and you want to have result shared? If so, then you have to create Service and put in core.module, that module has to be imported only once per application. angular.io has documentation page called Style Guide, please read it, it has few very important and useful notes regarding structuring of your project (especially concept of core and shared modules).
If module1 and module2 execute different requests and you want to have that request cached (i.e. do not execute 2nd time, when navigate back to module1) - you have to "cache" that data manually (just save results to variable in service).
As per my understanding, when you have multi-module structure you can:
 - do Lazy Load (or prevent loading at all, e.g. if user doesn't have permissions) - files (js/html) will be loaded only when user request them or after main page is loaded (deffered loading). It increase start-up time
 - in general, when module/component is unloaded from page, all observers/watcher/other zone-ng stuff is kinda "garbage collected", which decrease memory usage

A: hi talking about benefits you have:

*

*Modules are independent and can be moved or used in multiple sides, this avoids code duplication more info here https://angular.io/guide/styleguide#application-structure-and-angular-modules.

*Another advantage is the ability to use lazy loading. More info here https://angular.io/guide/ngmodule#lazy-loading-modules-with-the-router this will make you import the thinks you need based on the router.For example a homescreen only needs to load a component and it should be as quick as possible.

*Smart imports, when importing libraries we usually make mistakes and we don't need the whole import one example is.
import { Observable } from 'rxjs/Observable';
import * from "rxjs";

in this example we use only the observable and don't need to import the whole library because it will make our bundle size bulkier. Splitting our code in modules will allow to make smart imports like this example.
 import { MdToolbarModule} from '@angular/material';
 // import { MaterialModule } from '@angular/material';
 imports: [
   // MaterialModule.forRoot(),
   MdToolbarModule,
 ],

we could have imported the whole library but as this is a simple component we only need a short module.


text:
Q: Android Does not stay connected to ESP8266 in Soft Ap mode So basically I'm creating a Wireless Weight Scale using a esp. I have built a android app that pulls the data from esp and displays and logs into a local database.
Problem I'm facing is that the wifi does not stay connected in my android device as it does not have access to the internet.
I have tried using multiple devices from various manufactures. In some there is a way to turn of "WiFi Assitant" or "Smart WiFi" but even with those turned off, It automatically switches to a network with active internet access or mobile data.
I have tried to forcefully connect to the esp ssid from inside my app but as most of the apis are depreceated on android 10 onwards, that does'nt work either.
Is there anything that can be done in this matter or do I have to switch to bluetooth.


text:
Q: In R, how do you classify your data into different classes based on certain standards? For example, I want to classify R1 based on R2.
R1 is like
# A tibble: 5 x 2
    lon   lat
  <dbl> <dbl>
1     1     2
2     3     5
3     6     8
4     5    10
5     3     2

and R2 is like
# A tibble: 3 x 3
    lon   lat place
  <dbl> <dbl> <chr>
1     1     2 A
2     3     6 B
3     5     8 C

R2 is like a standard. I want to find the corresponding place for my observations in R1. Suppose the 1st place in R1 is graded like:

*

*scores of A: (1-1)^2 + (2-2)^2 = 0

*scores of B: (1-3)^2 + (2-6)^2 = 20

*scores of C: (1-5)^2 + (2-8)^2 = 52
If the scores of any place may be smaller than 3, we classify this place into the class.
The final result should be like this

# A tibble: 5 x 2
    lon   lat   place
  <dbl> <dbl>   <chr>
1     1     2   A
2     3     5   B
3     6     8   C
4     5    10   NA
5     3     2   NA

A: There might be a neater way to do this with some purrr mapping, but using a couple of loops instead could get you the desired results:
library(tidyverse)

## Create R1 and R2 as tibbles, with place as a row name
R1 <- tribble(~lon, ~lat,
              1,2,
              3,5,
              6,8,
              5,10,
              3,2)

R2 <- tribble(~lon, ~lat,~place,
              1,2,"A",
              3,6,"B",
              5,8,"C") %>% column_to_rownames(var = "place")

## Create a results tibble
results <- R1 %>% mutate(A = NaN, B = NaN, C = NaN, match = "NA")

## Function to calculate place scores
place_scores <- function(vec){
apply(R2,1,function(x) x-vec) %>%
apply(.,2,function(x) x^2) %>%
colSums()
}

## Run function in a loop for each row in R1
for(i in 1:nrow(R1)){
  res <- place_scores(as.numeric(R1[i,]))
  results[i,3:5] <- res
}

## Run another loop to match the column with the lowest score and < 3
for(i in 1:nrow(results)){
  match <- ifelse(any( results[i,3:5] < 3), colnames(results[,3:5])[which.min(as.numeric(results[i,3:5]))], NA)
  results$match[i] <- match
}
results

# A tibble: 5 x 6
    lon   lat     A     B     C match
  <dbl> <dbl> <dbl> <dbl> <dbl> <chr>
1     1     2     0    20    52 A
2     3     5    13     1    13 B
3     6     8    61    13     1 C
4     5    10    80    20     4 NA
5     3     2     4    16    40 NA

A: I also came up with a way to do this using for-loop:
class = R2$place
for (i in 1:length(R1$place))
{
dist = rep(0, length(R2$place))
for (j in 1:length(R2$place))
   {
      dist[j] = (R1[i, 1] - R2[j,1])^2 + (R1[i, 2] - R2[j, 2])^2
   }
R1$class[i] = class[which(dist <= 3)]
}


text:
Q: How to I properly install Docker and VirtualBox? I've run into quite a few problems trying to test my code done with this cookiecutter template: https://github.com/Dekalabs/cookiecutter-backend
It keeps freezing so I thought the issue would be related to docker.
I get the following error when I run $ docker-compose -f local.yml up -d :
$ docker-compose -f local.yml up -d
Traceback (most recent call last):
  File "/usr/bin/docker-compose", line 11, in <module>
    load_entry_point('docker-compose==1.25.0', 'console_scripts', 'docker-compose')()
  File "/usr/lib/python3/dist-packages/compose/cli/main.py", line 72, in main
    command()
  File "/usr/lib/python3/dist-packages/compose/cli/main.py", line 125, in perform_command
    project = project_from_options('.', options)
  File "/usr/lib/python3/dist-packages/compose/cli/command.py", line 53, in project_from_options
    return get_project(
  File "/usr/lib/python3/dist-packages/compose/cli/command.py", line 145, in get_project
    client = get_client(
  File "/usr/lib/python3/dist-packages/compose/cli/command.py", line 116, in get_client
    client = docker_client(
  File "/usr/lib/python3/dist-packages/compose/cli/docker_client.py", line 127, in docker_client
    client = APIClient(**kwargs)
  File "/usr/lib/python3/dist-packages/docker/api/client.py", line 132, in __init__
    base_url = utils.parse_host(
  File "/usr/lib/python3/dist-packages/docker/utils/utils.py", line 286, in parse_host
    raise errors.DockerException(
docker.errors.DockerException: Invalid bind address format: port is required: 127.0.0.1

I have tried all solutions suggested here (https://askubuntu.com/questions/1064674/linux-headers-reinstall). I have tried several times to uninstall and reinstall vbox, run the dkms commands etc.
Please help, keeping in mind that I'm a beginner... feeling completely lost here!
Thank you!
Some more commands and error messages I have tried:
$ docker-machine create default

Running pre-create checks...
Wrapper Docker Machine process exiting due to closed plugin server (unexpected EOF)
Error with pre-create check: "We support Virtualbox starting with version 5. Your VirtualBox install is \"WARNING: The character device /dev/vboxdrv does not exist.\\n\\t Please install the virtualbox-dkms package and the appropriate\\n\\t headers, most likely linux-headers-Microsoft.\\n\\n\\t You will not be able to start VMs until this problem is fixed.\\n6.1.10_Ubuntur138449\". Please upgrade at https://www.virtualbox.org"

$ uname -r

4.4.0-19041-Microsoft

$ sudo apt install --reinstall linux-headers-Microsoft

Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package linux-headers-Microsoft

(I've tried the install --reinstall with several different endings, always get the same error.)
$ software-properties-gtk

Unable to init server: Could not connect: Connection refused
Unable to init server: Could not connect: Connection refused
WARNING:root:system-image-cli failed, using defaults: [Errno 13] Permission denied: 'system-image-cli'
WARNING:root:system-image-cli failed, using defaults: [Errno 13] Permission denied: 'system-image-cli'

(software-properties-gtk:21982): Gtk-CRITICAL **: 17:47:54.409: _gtk_style_provider_private_get_settings: assertion 'GTK_IS_STYLE_PROVIDER_PRIVATE (provider)' failed

(software-properties-gtk:21982): Gtk-CRITICAL **: 17:47:54.412: _gtk_style_provider_private_get_settings: assertion 'GTK_IS_STYLE_PROVIDER_PRIVATE (provider)' failed

(software-properties-gtk:21982): Gtk-CRITICAL **: 17:47:54.415: _gtk_style_provider_private_get_settings: assertion 'GTK_IS_STYLE_PROVIDER_PRIVATE (provider)' failed
Segmentation fault (core dumped)

$ apt-cache policy linux-generic

linux-generic:
  Installed: (none)
  Candidate: 5.4.0.48.51
  Version table:
     5.4.0.48.51 500
        500 http://archive.ubuntu.com/ubuntu focal-updates/main amd64 Packages
        500 http://security.ubuntu.com/ubuntu focal-security/main amd64 Packages
     5.4.0.26.32 500
        500 http://archive.ubuntu.com/ubuntu focal/main amd64 Packages

$ sudo apt install linux-headers-generic

Reading package lists... Done
Building dependency tree
Reading state information... Done
linux-headers-generic is already the newest version (5.4.0.48.51).
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.

$ sudo apt-get install build-essential linux-headers-`uname -r` dkms virtualbox-dkms

Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package linux-headers-4.4.0-19041-Microsoft
E: Couldn't find any package by glob 'linux-headers-4.4.0-19041-Microsoft'
E: Couldn't find any package by regex 'linux-headers-4.4.0-19041-Microsoft'

A: Ok, I've found the solution - reinstalled Docker and it seems I had skipped a couple of steps...


text:
Q: How to retry an InvokeHTTP processor specific number of time I am fetching JSON data from an API using the InvokeHTTP processor. The criteria are: if the data isn't fetched, it will retry 3 times and if it still fails, it will send a notification by email. I am new to NiFi, so how shall I implement this?

A: you can use a custom workflow to retry the specific number of times. After getting response from invoke HTTP you can set counter attribute having value as 0 and if you did not get response from API you can increase that attribute by one and send the flowfile back to input of invoke http. Every time you get the response of API you can check if this attribute reached the maximum retry value and if it did, you can terminate the data according to your requirement.

A: If anybody still interested to know, the Version 1.16.0 & above has a feature of straightforward retry process.

Framework Level Retry now supported.  For many years users build flows in various ways to make retries happen for a configured number of attempts.  Now this is easily and cleanly configured in the UI/API and simplifies the user experience and flow design considerably!  To those waiting for years for this thank you for your patience.

For eg. The following snapshot shows, the processor would attempt 3 retries after 2 mins of back off period.


text:
Q: python pandas delete row on string condition i have a data frame with a column of strings and integers.
On one of the columns containing strings I want to search all the items of that column for a specific substring let say "abc" and delete the row if the substring exists. How do I do that? It sounds easy but somehow I struggle with this.
The substring is always the last three characters.
I tried the following:
df1 = df.drop(df[df.Hostname[-4:]== "abc"])

which gives me

UserWarning: Boolean Series key will be reindexed to match DataFrame
  index

so I tried to modify the values in that column and filter out all values that do not have "abc" at the end:
red = [c for c in df.Hostname[-4:] if c != 'abc']

which gives me

KeyError('%s not in index' % objarr[mask])

What do I do wrong?
Thanks for your help!

A: Use boolean indexing, add indexing with str if need check last 4 (3) chars of column Hostname and change condition from == to !=:
df1 = df[df.Hostname.str[-4:] != "abc"]

Or maybe:
df1 = df[df.Hostname.str[-3:] != "abc"]

Sample:
df = pd.DataFrame({'Hostname':['k abc','abc','dd'],
                  'b':[1,2,3],
                  'c':[4,5,6]})
print (df)
  Hostname  b  c
0    k abc  1  4
1      abc  2  5
2       dd  3  6

df1 = df[df.Hostname.str[-3:] != "abc"]
print (df1)
  Hostname  b  c
2       dd  3  6

Also works str.endswith if need check last chars:
df1 = df[~df.Hostname.str.endswith("abc")]
print (df1)
  Hostname  b  c
2       dd  3  6

EDIT:
If need check in last 4 chars if abc and then remove rows first extract values and then use str.contains:
df1 = df[~df.Hostname.str[-4:].str.contains('abc')]
print (df1)
  Hostname  b  c
2       dd  3  6

EDIT1:
For default index add reset_index - python counts form 0, so values of index are 0,1,2,...:
df1 = df[df.Hostname.str[-3:] != "abc"].reset_index(drop=True)


text:
Q: range() keeps returning empty list I have a function:
def button_pressed():
    first_day = int(daterangeT1.get("1.0","end-1c"))
    last_day = int(daterangeT1.get("1.0","end-1c"))
    days = range(first_day, last_day)

So i have tried many different ways but the range() call doesn't seem to like the two variables above it. They are both integers. It is always returning an empty list when i do a print command. Simply: "[]"

A: It seems like first_day and last_day are equal (you are getting the same key from the daterangeT1 dictionary/object), and range(x, x) returns an empty list.
Also note that if daterangeT1 is indeed a dictionary, if the '1.0' key doesn't exist then get will return the string 'end-1c' which will cause a ValueError when trying to convert to int.


text:
Q: Unable to access Slicer Values using Asposecells but am on the slicer that has options I am trying to use asposecells to update a number of pivot tables by updating a single slicer with connections to all pviots. This is an OLAP datasouce.
The slicer in question has month start date as the values to select from.
enter image description here
My goal is to update this slicer to the last month date, but when I run the below code trying to access the indiviual values of the slicer (the month start dates), I am getting an empty list. Can someone explain why I am getting an empty list with a slicer that has values in workbook and show me the correct syntax to get the list output?
My code is as follows:
import jpype
import asposecells
import os

jpype.startJVM()
from asposecells.api import Workbook, SaveFormat

workbook = Workbook("Test.xlsx")

worksheet = workbook.getWorksheets().get(0)

slicer = worksheet.getSlicers().get(0)

print(slicer.getSlicerCache().getSlicerCacheItems())

for item in slicer.getSlicerCache().getSlicerCacheItems():
    print(item)

jpype.shutdownJVM()


text:
Q: rsExecutionNotFound error in SQL Server Reporting Services I have a SQL Server Reporting Services 2005 installation that has worked great for a few years now, but has been giving me occasional glitches recently.
I'm using the default reporting services website instead of embedding reports into my application, which has proven a very efficient way to deploy the reports. The OS is Windows Server 2003 and the reports are being viewed on IE8 running XP.
It's not a big deal. Refreshing the browser brings the report right up each time. I guess it might be a cacheing issue. It does scare users, so it would be nice to squash this bug.
Any ideas?
Server Error in '/Reports' Application.
Execution 'j0cnbcqzv5lxg1imzqouqxya' cannot be found (rsExecutionNotFound)
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: Microsoft.Reporting.WebForms.ReportServerException: Execution 'j0cnbcqzv5lxg1imzqouqxya' cannot be found (rsExecutionNotFound)
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[ReportServerException: Execution 'j0cnbcqzv5lxg1imzqouqxya' cannot be found (rsExecutionNotFound)]
   Microsoft.Reporting.WebForms.ServerReport.GetExecutionInfo() +289
   Microsoft.Reporting.WebForms.ServerReport.SetExecutionId(String executionId, Boolean fullReportLoad) +120
   Microsoft.Reporting.WebForms.ServerReport.LoadFromUrlQuery(NameValueCollection requestParameters, Boolean fullReportLoad) +101
   Microsoft.Reporting.WebForms.ReportDataOperation..ctor() +321
   Microsoft.Reporting.WebForms.HttpHandler.GetHandler(String operationType) +458
   Microsoft.Reporting.WebForms.HttpHandler.ProcessRequest(HttpContext context) +56
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +181
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75

Version Information: Microsoft .NET Framework Version:2.0.50727.3603; ASP.NET Version:2.0.50727.3082

A: Try this (extending the "report session" timeout)
http://blogs.msdn.com/b/jgalla/archive/2006/10/11/session-timeout-during-execution.aspx

A: Here is a thread that might help...not sure if you tried it already.
In this case updating Microsoft.ReportViewer.WebForms.dll was a fix.
I also saw where it could be caused by a problem with NT Authority\Network Service account.
A quick "Google" with SSRS 2005 Execution "cannot be found" produced quite a few other options as well.
HTH

A: Take a look here :
http://blogs.msdn.com/jgalla/archive/2006/10/11/session-timeout-during-execution.aspx
This can happen when a report takes a long time to run, using a script with rs.exe to increase the RS session lifetime may well help.

A: I have answered this question in this thread.
It is to do with the execution context in the Session expiring.

A: In my case, this error ocurred only in the Browsers Internet Explorer 8 and Internet Explorer 9 with reports that takes more than 20 minutes for execute.
I solved this problem optimizing the sql query procedure ( before optimize took 30 minutes to execute ) and now takes 3 minutes.
I tried to configure increasing the session timeout in ReportManager configuration but anything solve the problem.
This error is weird because in Google Chrome and Firefox works fine!

A: the reason of this issue may be below:
1 - > your login has expired OR
2 - > The server on which SSRS report deployed, below services has stopped
    a - > MS SQL SERVER
    b - > SQL Server Agent is not running

to resolve go to the server and start these services

A: None of the aforementioned things worked for me. My reports aren't working from the Report browser interface, even though it used to. It does however work from the server URL.
eg) The /ReportServer context works fine, and NOT the /Reports context whilst browsing to reports.
This is ok since I can still upload reports, and our applications use the server URL.


text:
Q: Prevent COUNT() Subquery using window functions A developer colleague of mine has asked me to optimize statements for him. I have had a brief introduction to current level SQL technology and functionality and have the feeling that especially the window functions could help me.
The query in question is currently like this:
SELECT
T1.FIELD1,
T1.FIELD2
...
(SELECT COUNT (T2.FIELD1) FROM OUTER_TABLE_NAME T2 WHERE T2.FOREIGN_KEY = T1.PRIMARY_KEY) AS COMMENTS
FROM T1
;

This forces the database to run the subquery for each record from the primary table T1, which is generally slow. A better way would be if there was a window function that could express the same. However, it must not multiply the records from the primary table T1.
I thought about something like this:
SELECT
T1.FIELD1,
T2.FIELD2
...
COUNT(T2.FOREIGN_KEY) OVER (PARTITION BY T2.FOREIGN_KEY)
FROM T1
LEFT OUTER JOIN T2 ON T2.FOREIGN_KEY = T1.KEY
;

It needs to be an OUTER JOIN as to not filter records from the primary table T1. However, this way would multiply the records from the primary table T1 for every matching record from the secondary table T2.
Is there a way to express the count() using either window functions or any other non-proprietary methodology in Oracle 12.2?

A: SELECT
T1.FIELD1,
T2.FIELD2,
...
NVL(T2.COMMENTS, 0) AS COMMENTS
FROM T1
LEFT OUTER JOIN
(SELECT FOREIGN_KEY, COUNT (FIELD1) AS COMMENTS FROM OUTER_TABLE_NAME GROUP BY FOREIGN_KEY) T2
ON T2.FOREIGN_KEY = T1.PRIMARY_KEY
;


text:
Q: Change String date to ISO date in MongoDB? In MongoDB, I have a document with a field called "date" and that is in array.
  {
"_id" : ObjectId("587627a2125a730f78a20859"),
"data" : [
    {
        "Number" : "359983007479839",
        "date" : "2016-02-10T21:56:33.000Z"
    }
]

after that I run this script:
db.dummy.find().forEach(function(doc){
doc.mongodbdate = ISODate(doc.mongodbdate);
db.dummy.save(doc);
})

And its giving me below output;
{
"_id" : ObjectId("588724ba2746360c04a51e4b"),
"data" : [
    {
        "Number" : "359983007479839",
        "mongodbdate" : "2016-02-12T18:01:06.000Z"
    }
],
"mongodbdate" : ISODate("2017-01-24T15:26:24.537+05:30")
}

I tried this also:
var bulk = db.dummy.initializeUnorderedBulkOp(),
count = 0;

db.dummy.find().forEach(function(doc) {
bulk.find({ "_id": doc._id }).updateOne({
    "$set": { "mongodbdate": ISODate(doc.mongodbdate) }
})
count++;
if (count % 1000 == 0) {
    // Execute per 1000 operations and re-init
    bulk.execute();
    bulk = db.dummy.initializeUnorderedBulkOp();
}
})

its throws Error:
       "message" : "invalid ISO date"

I want to convert that string date into ISO date.I have changed with some code but its adding new date with ISO format but I want to update which is already available no need to insert new one.
One solution I got on stackoverflow also, but that is adding new field in my document i think it is because  of array,I want to update my existing one.

A: You can use dateutil module (sudo pip install python-dateutil)
Following is the sample code which convert the ISO string into datatime object and then insert it into mongo database.
import datetime
import pymongo
import dateutil.parser

def getDatetimeFromISO(s):
    d = dateutil.parser.parse(s)
    return d

conn = pymongo.MongoClient()
db = conn.sampleDB
collection = db.test
post = {
    "user" : "test1",
    "date" : getDatetimeFromISO("2016-02-10T21:56:33.000Z")
}

collection.insert_one(post)
conn.close()

In MongoDB
> db.test.find().pretty()
{
    "_id" : ObjectId("5885b47156addb199a07bf26"),
    "date" : ISODate("2016-02-10T21:56:33Z"),
    "user" : "test1"
}

You can update the string dates to ISO format in mongoDB in similar fashion.

A: You just need to modify your code to loop over the array as well.
db.dummy.find().forEach(function (doc) {
  doc.data.forEach(function (currentValue, index) {
    doc.data[index].mongodbdate = ISODate(currentValue.mongodbdate);
  });
  db.dummy.save(doc);
})

A: Starting from version 4.0, $toDate aggregation is possible to convert fields.
General syntaxe :
db.collection.updateMany({your_field : {$type: "string"}}, [{"$set": {your_field :{"$toDate": "$your_field"}}}]);

first parameter is the filter.
Find more in official docs.


text:
Q: JQuery won't call on image click So I've created a jquery call to check if an image in a series of images with the same account name: .account-img, are clicked.
I load the images through PHP like so:
<?php
    foreach($accountsArray as &$acc) {
        echo ('

        ');
    }
?>

Shorthand for the image is as follows:

Here is the JQuery i use to call the image clicks:
$('.account-img').each(function() {
    var id = $(this).attr('id').split('-');
    var name = id[1];
    $(this).on('click', function() {
        alert(name);
    });
});

EDIT:
It won't be a single element because of the PHP code i'm actually using. it will be multiple elements and i want to perform an action based on each individual image. But because my ID isn't known beforehand, I need to do it this way

A: You have to user click trigger for that as below code.... And for get current image click you use this inside click trigger....
$('.account-img').click(function(){
   alert($(this).attr("id"));
});

A: There would be no reason to foreach the element if you're going to add a click handler on it. Removing the foreach would be enough.

$(document).ready(function () {
  $('.account-img').on('click', function() {
    var id = $(this).attr('id').split('-');
    var name = id[1];
    console.log(name);
  });
});

A: try this:
$(document).ready(function(){
    $('.account-img').each(function() {
        var id = $('#img-BBCNews').attr('id').split('-');
        var name = id[1];
        $('#img-BBCNews').on('click', function() {
            alert(name);
        });
    });
});


text:
Q: Jquery Tools Overlay - Deep Linking I have a webpage that has a page with many images that when clicked open separate JQuery Tools Overlays that display FlowPlayer videos.  We use these as tutorials of various features of the product my company offers.
What we're looking to do is in an email have a link that opens the website on the above page and automatically display the overlay (and therefor video) we require.
Does anyone know if this is possible?
I know with PrettyPhoto you can enable deeplinking to get the link, but what i can't figure out is how to do this with JQuery Tools Overlay.

A: idea can be ike that:
In your e-mails you can add GET values to links like www.yoursite.com?prodid=15&image=image4
(I assume id of your trigger image that you want to show video is image4)
like
<img src="/some.jpg" id="image4"/>

and in your hard coding you need to GET it like that (PHP);
// js codes that will run when your DOM is ready
<?
if ($_GET["image"]){ echo "$('#".$_GET["image"]."').click();";}
?>
//rest of your js code

see this fiddle for machanism (i mean you can fire element's trigger by click() method)


text:
Q: How to perform boxing in Scala? I'm trying to understand how casting works in Scala. Here is the example:
object Main extends App {
    val ai: Array[Any] = Array(1, 2, 3, 4, 5, 6)
    val ar: Array[AnyRef] = ai.map(_.asInstanceOf[AnyRef])
}

And it works fine. https://ideone.com/6PerTR
Now let's rewrite it as follows:
object Main extends App {
    val ai: AnyRef = Array(1, 2, 3, 4, 5, 6)
    val ar: Array[AnyRef] = ai.asInstanceOf[Array[Any]].map(_.asInstanceOf[AnyRef])
}

It does not work. It fails with ClassCastException now https://ideone.com/JbOQbb. Why? I thought adding cast is enough here? Why does the first example work?
How to make it work in the second case if we are casting AnyRef to Array[Any] first? How to add boxing here?
UPD: I also tried:
object Main extends App {
    val ai: AnyRef = Array(1, 2, 3, 4, 5, 6)
    val aii: Array[Any] = ai.asInstanceOf[Array[Any]]
    val ar: Array[AnyRef] = aii.map(_.asInstanceOf[AnyRef])
}

But got ClassCastException https://ideone.com/ZcgT6x. It looks very similar to the first example though. How to cast aii to Array[AnyRef] in the case?

A: TL;DR: The first snippet works because the autoboxing takes place already when the array is generated. The second snippet does not work, because the created array is an Array[Int].

Even though Int is subtype of Any, an Array[Int]
is not a subtype of Array[Any]. Therefore, when you write
scala> val ai: Array[Any] = Array(1, 2, 3, 4, 5, 6)
ai: Array[Any] = Array(1, 2, 3, 4, 5, 6)

this is essentially equivalent to
val ai: Array[Any] = Array[Any](1, 2, 3, 4, 5, 6)

so that all integers are already boxed. The result is:
scala> ai.getClass
res0: Class[_ <: Array[Any]] = class [Ljava.lang.Object;

that is, your ai is essentially an Array[Object] right from the beginning.
The crucial difference in the second snippet is that even though Array[Int]
is not subtype of Array[Any], it definitely is a subtype of AnyRef, so
no autoboxing takes place:
scala> val ai: AnyRef = Array(1, 2, 3, 4, 5, 6)
ai: AnyRef = Array(1, 2, 3, 4, 5, 6)

scala> ai.getClass
res2: Class[_ <: AnyRef] = class [I

as you can see, the AnyRef is an int-array with unboxed ints.
If you now try to cast an array of unboxed ints into an Array[Any], you
get a class cast exception.
You could fix your second example by enforcing immediate autoboxing like this:
object Main extends App {
    val ai: AnyRef = Array[Any](1, 2, 3, 4, 5, 6)
    val ar: Array[AnyRef] =
      ai.asInstanceOf[Array[Any]].map(_.asInstanceOf[AnyRef])
}

or alternatively you could cast your array to the right type, namely Array[Int]:
object Main extends App {
    val ai: AnyRef = Array(1, 2, 3, 4, 5, 6)
    val ar: Array[AnyRef] =
      ai.asInstanceOf[Array[Int]].map(_.asInstanceOf[AnyRef])
}

A: As there is no representation of Any type at bytecode level, both Array[Any] and Array[AnyRef] require the elements to be boxed. So, when trying to cast from Array[Int] to Array[Any], we're actually casting from [I to [java/lang/Object; which results as an exception.
The only general solution is specially handling arrays of each primitive type, which can be done quite easily using a WrappedArray:
val ai: AnyRef = Array(1, 2, 3, 4, 5, 6)
val ar: Array[AnyRef] = collection.mutable.WrappedArray.make(ai).toArray


text:
Q: DataTable custom filter dropdown i have a table with custom filter next to header

  Type
  Start
  End

    <select class="form-control" placeholder="Type">
      <option value="">Search</option>
    </select>

data from my database looks like this
    type     |   start    |    end
____________________________________
    orig     |    01      |    05
    classA   |    01      |    05
    classB   |    01      |    05
    classA   |    01      |    05
    classB   |    01      |    05
    orig     |    01      |    05
    orig     |    01      |    05

what i wanted to do was to get the data from the datatable then append it to my custom select element
which will get the value of orig, classA, classB so that my select element would look like this
<select class="form-control" placeholder="Type">
  <option value="">Search</option>
  <option value="orig">orig</option>
  <option value="classA">classA</option>
  <option value="classB">classB</option>
</select>

this is the script i use
$.each($('.select-filter', dataTable.table().header()), function () {
    var column = dataTable.column($(this).index());
    $( 'select', this).on( 'change', function () {
        if ( column.search() !== this.value ) {
            column
                .search( this.value )
                .draw();

        } else if ( column.search() !== "" ) {
            column
                .draw();
        }
    });
});

this is how i wanted to look like


text:
Q: Navigation Key lost after trying to delete I have code first entity framework.
when I'm trying to delete row from table that have foreign key to other table i get a exception. after handling the exception when I try load my data again the Navigation Key of selected item that i try to delete is become null
why this happen and how can i fix it.
the delete process is so simple :
public class Person
{
     public int ID {get;set;}
     public string Name {get;set;}

     public Something Something {get;set;}
     public ICollection<Profile> Profile {get;set;}
}

try
{
    var p = en.Person.First(t => t.ID == 14);
    //p.Something here is not null;
    en.Remove(p)
    en.SaveChanges(); // I'm get an exception here
}
catch { /*error handling */}
finally
{
    var p = en.Person.First(t => t.ID == 14);
    //but p.Something here is null;
}

but in en.SaveChange() i get an exception.

The DELETE statement conflicted with the FOREIGN KEY constraint
  "FK_person_profile

this is a sample of my class.
that SomeThing Property is a Navigation Key.
in first select the Something have value.
but in second select inside finally block its become null.
after fixing the delete problem now I got the same problem after adding object to database.
and that reload function doesn't help.
any suggestion?

A: I think I understand your problem - you're deleting an entity, it's causing an error and you want to recover.  However, in your finally block when you get your entity again from your current context again it's not correct.
The issue is that you're expecting your context to reload from the database, but that's not quite how it works. What you're actually doing is going back to your context, which is a unit of work and retrieving the entity in memory, because the entity your retrieving is flagged for deletion so it's properties are not being loaded. If you want to refresh from the database, you'll need to reload the entity fully using the Entry, using the DbEntityEntry.Reload.
Using your code an an example:
var p = en.Person.First(t => t.ID == 14);
en.Entry(p).Reload();


text:
Q: Trying to restrict math.pow value upto 4 decimal value I am trying to restrict value up to 4 decimal for Math.Pow((Density * 10), -12)
where double Density = 0; is defined as variable
now if Density=7;
then Math.Pow((Density * 10), -12) calculate as  7.22476158090089E-23
but I want it like 7.2247 E-8.
Any idea would be appreciated.

A: If you want to restrict the decimal precision to 4 decimal places you can use the Exponential Format Specifier, specifying the number of decimals to display "E4":
var answer = Math.Pow(70, -12);
var displayVal = string.Format("{0:E4}", answer);
// output
7.2248E-023

Note that

The exponent always consists of a plus or minus sign and a minimum of
three digits.

However, you can use the General Format Specifier which

If scientific notation is used ... The exponent contains a minimum
of two digits. This differs from the format for scientific notation
that is produced by the exponential format specifier, which includes a
minimum of three digits in the exponent.

You will need to use G5 to produce 5 significant digits:
var answer = Math.Pow(70, -12);
var displayVal = string.Format("{0:G5}", answer);
// output
7.2248E-23


text:
Q: Spring Boot Data JPA query doesn't work with LocalDateTime.MAX I have method:
@Query(value = "SELECT bs FROM BookedSlot bs WHERE bs.timeFrom >= :timeFrom AND bs.timeFrom < :timeTo")
Set<BookedSlot> test(@Param("timeFrom") LocalDateTime fromTime, @Param("timeTo") LocalDateTime timeTo);

And two tests
    @Sql(scripts = "/test-data.sql")
    @Test
    public void test1() {
        final Set<BookedSlot> res = unit.test(LocalDateTime.now(), LocalDateTime.MAX);
        assertNotNull(res);
        assertEquals(1, res.size());//fails
    }

    @Sql(scripts = "/test-data.sql")
    @Test
    public void test2() {
        final Set<BookedSlot> res = unit.test(LocalDateTime.now(), LocalDateTime.of(2050,1,1,1,1));
        assertNotNull(res);
        assertEquals(1, res.size());//ok
    }

And test-data.sql
INSERT INTO booked_slots (id, created_at, updated_at, time_from, time_to, user_id, service_box_id)
VALUES (1, NOW(), NOW(), '2040-01-01 08:30:00.0', '2040-01-01 10:00:00.0', 1, 1);

test1 - fails
test2 - ok
BookedSlots.java
@Entity
@Table(name = "booked_slots")
public class BookedSlot extends DbEntity implements Comparable<BookedSlot> {

    @Column(name = "time_from")
    private LocalDateTime timeFrom;
    @Column(name = "time_to")
    private LocalDateTime timeTo;
}

Database h2 (and the same is on MySQL 5.7, I just use H2 for integration tests)
test.properties
spring.datasource.url=jdbc:h2:mem:myDb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;MODE=MySQL
spring.datasource.username=sa
spring.datasource.password=sa
spring.datasource.initialization-mode=always
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect

Any thoughts on this?

A: The maximum supported LocalDateTime is 999999999-12-31T23:59:59.999999999. Database doesn't support dates that far into the future.
MySQL range for DATETIME values is 1000-01-01 00:00:00.000000 to 9999-12-31 23:59:59.999999

hibernate-core: LiteralType::objectToSQLString Convert the value into a string
  representation, suitable for embedding in an SQL statement as a
  literal.

Here you can see LocalDateTimeType::objectToSQLString method
public class LocalDateTimeType
        extends AbstractSingleColumnStandardBasicType<LocalDateTime>
        implements VersionType<LocalDateTime>, LiteralType<LocalDateTime> {

    public static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern( "yyyy-MM-dd HH:mm:ss.S", Locale.ENGLISH );

    //...

    @Override
    public String objectToSQLString(LocalDateTime value, Dialect dialect) throws Exception {
        return "{ts '" + FORMATTER.format( value ) + "'}";
    }

    //..
}

for LocalDateTime.MAX it returns {ts '+999999999-12-31 23:59:59.9'}


text:
Q: How to display a horizontal table next to a page of text I'm an entry-level LaTex user. I have a table in landscape orientation that spans a whole page, but as it's not very large, it would be nice to have the text next to it.
Here is my minimum working example:
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[a4paper, total={16.5cm, 23cm}]{geometry}
\usepackage{lipsum}
\usepackage{lscape}
\usepackage{graphicx}
\usepackage{wrapfig}

\begin{document}

\lipsum[2-8]

\begin{wraptable}{l}{0pt}% automatically uses minimum width
\begin{landscape}
\begin{table}[]
\resizebox{1.4\textwidth}{!}{%
\begin{tabular}{|llllllll|}
\hline
Header & Header & Header & Header & Header & Header & Header & Header  \\
\hline
LaTex  & LaTex  & LaTex  & LaTex  & LaTex  & LaTex  & LaTex  & LaTex   \\
\hline
LaTex  & LaTex  & LaTex  & LaTex  & LaTex  & LaTex  & LaTex  & LaTex   \\
\hline
\end{tabular}
}
\caption{This is a Caption}
\end{table}
\end{landscape}
\end{wraptable}

\end{document}

I tried wraptable, but it returned errors: improper \predevdepth. Missing \endgroup inserted. Missing } inserted at \begin{landscape} and Latex Error: Not in outer par mode. Undefined control sequence. Missing number, treated as 0 at \begin{table}.
This is an illustration of what I had in mind:

A: Here is a way ... but you have to know where to place the table and what to place next to it.
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[a4paper, total={16.5cm, 23cm}]{geometry}
\usepackage{lipsum}
\usepackage{lscape}
\usepackage{graphicx}
\usepackage{rotating}
\usepackage{capt-of}

\newsavebox{\testBox}

\begin{document}

\lipsum[2-8]

\savebox{\testBox}{\rotatebox{90}{%
\begin{minipage}[b]{\textheight}
\begin{tabular*}{\textheight}{|l@{\extracolsep{\fill}}lllllll|}
\hline
Header & Header & Header & Header & Header & Header & Header & Header  \\
\hline
LaTex  & LaTex  & LaTex  & LaTex  & LaTex  & LaTex  & LaTex  & LaTex   \\
\hline
LaTex  & LaTex  & LaTex  & LaTex  & LaTex  & LaTex  & LaTex  & LaTex   \\
\hline
\end{tabular*}
\captionof{table}{This is a Caption}
\end{minipage}
}}

\noindent\begin{minipage}[t]{\wd\testBox}\vspace{0pt}\usebox{\testBox}\end{minipage}\hfill\begin{minipage}[t]{\dimexpr\linewidth-\wd\testBox-5mm}\vspace{0pt}
\lipsum[1-3]
\end{minipage}

\end{document}

A: An other solution usign tcolorbox package :
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[a4paper, total={16.5cm, 23cm}]{geometry}
\usepackage{lipsum}
\usepackage{graphicx}
\usepackage{tcolorbox}
\tcbuselibrary{skins}

\begin{document}

\begin{tcolorbox}[enhanced, sidebyside, lefthand ratio=.3,
  sidebyside align=center]
    \rotatebox{90}{
      \begin{tabular}{|llllllll|}
        \hline
        Header & Header & Header & Header & Header & Header & Header & Header  \\
        \hline
        LaTex  & LaTex  & LaTex  & LaTex  & LaTex  & LaTex  & LaTex  & LaTex   \\
        \hline
        LaTex  & LaTex  & LaTex  & LaTex  & LaTex  & LaTex  & LaTex  & LaTex   \\
        \hline
      \end{tabular}
    }
    \tcblower
    \lipsum[2-5]
\end{tcolorbox}

\end{document}


text:
Q: Reduced Graphics Mode, No Wireless, No Bluetooth at boot, 16.04 LTS I've read many posts here and elsewhere on the topics mentioned in the Subject.  I've tried many of the proposed 'fixes' but, quite frankly, I couldn't repeat back to you what all I have tried.
This all seems to originate with an update that came through a couple of months ago.  No, I don't know exactly which one.
Nearly every boot, multiple times per day, the events occur in this order.
- Boot bring me to a black screen with a dialog box indicating that I will be in reduced graphics mode.  I click OK.
- Another dialog appears.  There are a number of options there, troubleshooting is one of them.  Again, click OK using the default.
- After maybe 15-20 seconds, I get the normal login screen.
- Once logged in I get several dialog boxes asking me if I want to report the problem.  I've reported each one since this first started occurring.
- Before I got the hang of restarting the wireless network, the reporting would fail due to lack of connectivity.
- If I don't restart the wireless by hand, I won't have any wireless connection.
- The Bluetooth will not restart.  I've tried stop, start and restart all without any results.
I'm happy to post any logs you need in order to help resolve this, I will just need the command line information.
The laptop is HP Probook 6570b.  4GB RAM.
Wireless Info: Broadcom BCM43228 802.11a/b/g/n
Dual boot with Windoze 10 on the other side.  Windoze has no issues that I am aware of but I don't use it much.
Ubuntu is 4.13.0-43-generic #48~16.04.1-Ubuntu
x86 64 x86_64 GNU/Linux
I know there are probably a ton of details missing here, so feel free to ask, I'll share whatever you need to help me figure out what is causing this craziness.
Thanks in advance for taking time to read and offer suggestions.


text:
Q: Find irreducible binary polynomial of degree 5 I'm trying a brute force approach, evaluating every single polynomial of degree 5. I was decomposing them using Ruffini in order to check if they are irriducible.
With this approach for example $x^5+x^4+1$ seems irreducible, but from the table it's not...
Is this approach valid? There is some better methods?


text:
Q: Binding Listview Item Count to Label Visibility in Xamarin Forms I have a problem with binding in Xamarin Forms. I want to set IsVisible property of Label to true/false according of count items of Listview. If Listview have any items, Label IsVisible will be false, otherwise will be true. Is it possible to make in Xamarin Forms with binding? I tried to do this but I don't know how to convert number 0 to boolean false in XAML.

A: It certainly is possible. I assume that you already have a way of getting the count of the items in the ListView so here's how to convert that number to a boolean value in XAML.
What you need, is a custom implementation of the IValueConverter interface. It can take a value provided by the binding and convert it to something else and back if needed.
In your case, you want to take an integer and return a boolean. If the value is zero, you'll return true and otherwise false.
public class CountToBoolenConverter : IValueConverter
{
    public object Convert (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return (int)value != 0;
    }

    public object ConvertBack (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException ();
    }
}

Next, you'll need to define the namespace in the XAML. On top of the file you should add something like this:
xmlns:local="clr-namespace:YourNameSpace;assembly=YourAssembly"

Add the converter to the page resources just after the opening <ContentPage> tag (or whatever type of page you have):
<ContentPage>
  <ContentPage.Resources>
    <ResourceDictionary>
      <CountToBoolenConverter x:Key="countToBoolean" />
    </ResourceDictionary>
  </ContentPage.Resources>

  <!-- Rest of the page -->

And then finally use the converter to set the IsVisible property to your Label:
<Label IsVisible="{Binding ItemCount, Converter={StaticResource countToBoolean}}">

ItemCount is an integer property in your viewmodel and it should contain the count of the ListView items. You probably already have a way of loading a collection of items for the ListView so it should be trivial to figure out how this property should be done.

A: You can do it purely in XAML using a DataTrigger:
<?xml version="1.0" encoding="utf-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 x:Class="ListViewTriggerToHideLabel.MainPage">
    <StackLayout>
        <Label Text="Welcome to Xamarin Forms!" IsVisible="False">
            <Label.Triggers>
                <DataTrigger TargetType="Label"
                             Binding="{Binding Source={x:Reference TheListView}, Path=ItemsSource.Count}"
                             Value="0">
                    <Setter Property="IsVisible" Value="True" />
                </DataTrigger>
            </Label.Triggers>
        </Label>
        <ListView x:Name="TheListView" />
        <Button Text="Add an item" Clicked="Button_OnClicked" />
    </StackLayout>
</ContentPage>

The code-behind to handle button clicks and initialise the list content (I normally use data binding, but for simplicity in the example I'm using code-behind):
using System;
using System.Collections.ObjectModel;
using Xamarin.Forms;

namespace ListViewTriggerToHideLabel {
  public partial class MainPage : ContentPage {
    private readonly ObservableCollection<string> _items = new ObservableCollection<string>();

    public MainPage() {
      InitializeComponent();
      TheListView.ItemsSource = _items;
    }

    private void Button_OnClicked(object sender, EventArgs e) {
      _items.Add("Ouch");
    }
  }
}

The binding to the Count property works because the ItemsSource is an ObservableCollection.

A: Try this:
XAML
   <StackLayout>
        <Label Text="Welcome to Xamarin Forms!" IsVisible="{Binding ShowLabel}">
        </Label>
        <ListView x:Name="TheListView" />

        <Button x:Name="btnAddItem" Text="Add an item" Clicked="btnAddItem_Clicked"   />
    </StackLayout>

 public partial class MainPage : ContentPage, INotifyPropertyChanged
    {
public event PropertyChangedEventHandler PropertyChanged;
    private ObservableCollection<string> _items = new ObservableCollection<string>();

    public bool ShowLabel
    {
        get
        {
            return !(Items.Count > 0);
        }
    }

    public ObservableCollection<string> Items
    {
        get { return _items; }

        set
        {
            _items = value;

        }
    }

    public MainPage()
    {
        InitializeComponent();
        TheListView.ItemsSource = _items;
        BindingContext = this;
    }

    private void btnAddItem_Clicked(object sender, EventArgs e)
    {
        Items.Add("Add a item");
        NotifyPropertyChanged("ShowLabel");
    }

    private void NotifyPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }}


text:
Q: Show that the operator norm is submultiplicative We had in our lecture on numerical analysis the following:
Let $\mathrm{Lin}(X,Y)$ be the set of all linear maps $X\rightarrow Y$. Let $A\in\mathrm{Lin}(\mathbb R^l,\mathbb R^n)$ and $B\in\mathrm{Lin}(\mathbb R^n,\mathbb R^m)$ and $\|C\|_{op}:=\max_{\|x\|\leq1}\|C(x)\|$.
Then our lecturer followed $\|A\circ B\|_{op}\leq\|A\|_{op}\cdot\|B\|_{op}$. So he didn't prove it and so I've tried it by my own.
My attempt:
$$\begin{aligned} \|A\circ B\|_{\mathrm{op}} &= \max_{\|x\| < 1}\|(A \circ B)(x)\| \\ & \leq \max_{\|x\| < 1} \|A\|_{\mathrm{op}} \|B(x)\| \\ &= \|A\|_{\mathrm{op}} \max_{\|x\|\leq1}\|B(x)\|\\ &= \|A\|_{\mathrm{op}}\|B\|_{\mathrm{op}} \end{aligned}$$
But this seems too easy. I am really interested in a nice proof so anybody could help? Thanks a lot!

A: This is strange to look for a nicer proof for such a simple problem. Your solution is correct and as short as it could be.

A: $$
||AB||=\max_{x \ne 0} \frac{||ABx||}{||x||}=\max_{Bx \ne 0}\frac{||ABx|| }{||x||} =\max_{ Bx\ne 0}\frac{||ABx||}{||Bx||} \frac{||Bx||}{||x||}\le \max_{y \ne 0} \frac{||Ay||}{||y||} \max_{x \ne 0} \frac{||Bx||}{||x||}
$$
It shows that:
$$
||AB||\le ||A|| ||B||
$$


text:
Q: Why the google.maps.places.Autocomplete generated search address gives ZERO_RESULT while geocoding? I have added below API link for google map:

On window load event map loads with default lat and long values specified hard coded in loadShowMap(). And also have register text box for AutoComplete.
google.maps.event.addDomListener(window, 'load', loadShowMap);

function loadShowMap() {
    var input = document.getElementById('txtSearch');
    var autocomplete = new google.maps.places.Autocomplete(input);
    var latlng = new google.maps.LatLng(41.4925374, -99.9018);
    var myOptions = {
        zoom: 11,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    geocoder = new google.maps.Geocoder();
    mapgoogle = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    NewMapLoad(mapgoogle, geocoder, '');

    $('#btnMapSearch').click(function () {
        geocoder = new google.maps.Geocoder();
        var address = $('#txtSearch').val();
        deleteOverlays();
        if (address != '') {
            NewMapLoad(mapgoogle, geocoder, $('#txtSearch').val());
        }
        else { alert('Please enter a Location to Search'); }
    });
}

As per auto complete feature it providing the match address as in below screen:

Then I select "Marketfair Mall, Skibo Road, Fayetteville, NC, United States". Then on search button click below function gets called. Which sets initial marker and the one which we currently searching.
function NewMapLoad(Nmapgoogle, geocoder, searchplace) {
    var strAddr = "Hollywood, LA"
    var strPopupDiv = "

" + "Initial Point" + "

 ";
    var strSearchDiv = "

" + "Search Point" + "

 ";
    var PointColor = "RED";

    var OrglatLon = document.getElementById('hdnactlocation');
    var Orglat = "", OrgLon = "";

    if (OrglatLon != null && OrglatLon.value.split('|').length > 1) {
        Orglat = OrglatLon.value.split('|')[0];
        OrgLon = OrglatLon.value.split('|')[1];
    }
    else if (OrglatLon != null && OrglatLon.value.trim() != "") {
        strAddr = OrglatLon.value;
    }

    AddMappointsNew(Orglat, OrgLon, strPopupDiv, geocoder, mapgoogle, PointColor, strAddr, "Initial Point");

    if (searchplace != '' && searchplace.toLowerCase() != 'clone') {
        AddMappointsNew('', '', strSearchDiv, geocoder, mapgoogle, "GREEN", searchplace, "Search Point");
    }
    if (searchplace.toLowerCase() == 'clone') {
        AddMappointsNew(orglat, orglon, strSearchDiv, geocoder, mapgoogle, "GREEN", strAddr, "Search Point");
    }

    overlay = new google.maps.OverlayView();
    overlay.draw = function () { };
    overlay.setMap(mapgoogle);
}

For that setting initial and searching marker over map below function gets called:
function AddMappointsNew(lat, lon, strpopup, geocoder, mapgoogle, pointcolor, address, title) {

    var point;
    var iconlnk = "http://maps.google.com/mapfiles/ms/icons/red-dot.png";

    if (pointcolor != "" && pointcolor == "GREEN") {
        iconlnk = "http://maps.google.com/mapfiles/ms/icons/green-dot.png";
    }

    geocoder = new google.maps.Geocoder();
    var addressdiv = $('
').html(strpopup).html();
        geocoder.geocode({ 'address': address }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                mapgoogle.setCenter(results[0].geometry.location);
                var marker = new google.maps.Marker({
                    map: mapgoogle,
                    icon: iconlnk,
                    position: results[0].geometry.location,
                    title: title
                });
                var infowindow = new google.maps.InfoWindow({
                    content: addressdiv,
                    maxWidth: 300,
                    maxHeight: 200
                });
                google.maps.event.addListener(marker, 'click', function () {
                    infowindow.open(mapgoogle, marker);
                });
                if (pointcolor != "" && pointcolor == "GREEN") {
                    setSearchmarker(marker);
                }

                markersArray.push(marker);
            } else {
                mapgoogle.setZoom(5);
                alert("Geocode was not successful for the following reason: " + status);

            }
        });
}

But only initial marker getting set over map and for the geocode address returned from auto complete feature gives an error "ZERO_RESULT".

A: If you have a look at the Places Autocomplete Example on Google Developers you will see that you don't need to Geocode twice which is essentially what you are doing. You run the autocomplete which actually returns the Place and then you have a search button to then to a search on the address again.
I have put together a small sample of what you should try out here
autocomplete.addListener('place_changed', function() {
    var place = autocomplete.getPlace();
    console.log(place);
    if (!place.geometry) {
        // User entered the name of a Place that was not suggested and
        // pressed the Enter key, or the Place Details request failed.
        window.alert("No details available for input: '" + place.name + "'");
        return;
    }

    // If the place has a geometry, then present it on a map.
    if (place.geometry.viewport) {
        mapgoogle.fitBounds(place.geometry.viewport);
    } else {
        mapgoogle.setCenter(place.geometry.location);
        mapgoogle.setZoom(17); // Why 17? Because it looks good.
    }
    marker = new google.maps.Marker({
        map: mapgoogle,
        anchorPoint: new google.maps.Point(0, -29)
    });
    marker.setIcon( /** @type {google.maps.Icon} */ ({
        url: place.icon,
        size: new google.maps.Size(71, 71),
        origin: new google.maps.Point(0, 0),
        anchor: new google.maps.Point(17, 34),
        scaledSize: new google.maps.Size(35, 35)
    }));
    marker.setPosition(place.geometry.location);
    marker.setVisible(true);

    var address = '';
    if (place.address_components) {
        address = [
            (place.address_components[0] && place.address_components[0].short_name || ''),
            (place.address_components[1] && place.address_components[1].short_name || ''),
            (place.address_components[2] && place.address_components[2].short_name || '')
        ].join(' ');
    }

});