text:
Q: Understanding of the definition "statistical experiment" (Blackwell, 1951) I'm interesting for the understanding of the definition "statistical experiment".
Formally statistical experiment, statistical model or just experiment was defined as a triple
$$\mathscr{P}=(\Omega,\mathscr{F}, \{ P_{\theta}:\theta \in \Theta \}),$$
where $\Omega,\mathscr{F}$ is a sample space, $\Theta$ is a parameter spase and $\{ P_{\theta}:\theta \in \Theta \}$ is family of probability measures, defined on the given sample space.
My question is: why it is a family of probability measures? What is/are an example(s) of this abstaction?
Especially we could interesting for the parameters estimation. Let me give an example as the (real-valued) mean estimation problem of the random variables, that are normally distributed with known variance equals one. More precise: we have some i.i.d. r.v.'s $X_1,X_2,...,X_n$ (given observations) with $X_1 \sim \mathscr{N}(\theta, 1)$. Then we could formulate related statistical experiment as $$\mathscr{P}=(\Bbb{R}^n,\mathscr{B}(\Bbb{R}^n), \{ P_{\theta}^{\times{n}}:\theta \in \Theta=\Bbb{R} \}).$$
So, we define our statistical experiment as the infinite set of possible distributions (i.e. as a set $\{\mathscr{N}(\theta, 1)^{\times{n}}:\theta \in \Bbb{R}\}$). Why do we need a set? Why we can not say, that we are looking for some estimation of the "true" distribution, which is unique?


text:
Q: Running a php script as a background process using unix I am trying to run the php script (below) named daemon.php as a back ground process using unix.
#!/usr/bin/php
<?php
$count = 0;
while(true){
    $count = $count + 1;
    file_put_contents('daemon1.log', $count, FILE_APPEND);
    sleep(1);
}
?>

If I run it in the foreground using the command below
php daemon.php

The file deamon1.log starts getting written to. Also if I enter the command:
ps | grep php

I get the out put
10573 ttys000    0:00.20 php daemon.php

If I try to run it as a background process using the command
php daemon.php &

I get the console out put
[1] 10584

And the command
ps | grep php

Returns
10584 ttys000    0:00.02 php daemon.php

But nothing is written to deamon1.log. Can anyone tell me what I'm doing wrong?

A: Try a different approach.
$file_handler = fopen( 'daemon1tempname.log', 'a+') or die ('Can not work with the File!');

$count = 0;
while(true){
    $count = $count + 1;
    fwrite($file_handler, "Test {$count}\n" );
    sleep(1);
}
fclose($file_handler);

Notice the different name of the file. Just make sure you work with a new file.
If that works, test it with the file you want.
If that does not work, then you know it's a permission issue.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Multiple "More" links for the_excerpt(); in Wordpress I've changed my excerpt link in wordpress from "[...]" to "Read More" with the code below. I want to know if there is a way to use more than one link for the excerpt. Let's say for posts in one category have "Read More" for their excerpt, and then posts in another category have "See Photos" for their excerpt link. is this possible?
remove_filter('get_the_excerpt', 'wp_trim_excerpt');
add_filter('get_the_excerpt', 'custom_trim_excerpt');

function custom_trim_excerpt($text) { // Fakes an excerpt if needed
global $post;
if ( '' == $text ) {
$text = get_the_content('');
$text = apply_filters('the_content', $text);
$text = str_replace(']]>', ']]>', $text);
$text = strip_tags($text);
$excerpt_length = 24;
$words = explode(' ', $text, $excerpt_length + 1);
if (count($words) > $excerpt_length) {
array_pop($words);
array_push($words, '...
Read More');
$text = implode(' ', $words);
}
}
return $text;
}

A: yes you can do it. use excerpt_more filter to change the "[...]" and in_category function to check the category for read more text.
try this code.
function custom_excerpt_more( $more ) {
    $read_more_txt = 'Read More..';

    if (in_category('cat_slug'))
        $read_more_txt = 'See Photos..';
    else if (in_category('cat_slug2'))
        $read_more_txt = 'Something else..';

    return ' '.   $read_more_txt .'';
}
add_filter( 'excerpt_more', 'custom_excerpt_more' );


text:
Q: Isn't the Doctor entering his own timestream a paradox? There are multiple mentions across the series that the Doctor cannot cross his own timeline.
However, in the episode "The Name of the Doctor", where he comes to his tomb on Trenzalore, he willingly jumps into his own timestream[1] to "save" Clara.
Isn't that the one thing he cannot do? Crossing his own timeline?

[1] I did notice there is a (possible) intentional use of a different name (timeline vs. timestream) and I'm not sure if that makes a difference.

A: There's a couple of things going on here:
The Doctor Lies -- And Cheats
The Doctor breaks the rules all the time. Yes, he cannot cross his own timeline... except for the half-dozen times he does just that and gets away with it. This is part of the flexible, mutable nature of time travel rules in Doctor Who: there is no hard and fast rule.
Examples of The Doctor explicitly crossing his own timeline include "The Three Doctors", "The Five Doctors", and "Day of the Doctor". In all of those cases, he did the exact thing he claims he can never do, and ended up saving the day.
As viewers, we're supposed to mostly just accept that Time Lords instinctively know when it's safe to do these things, and when it's not. The one time The Doctor went against his instincts -- "Waters of Mars" -- the universe smacked him down anyway.
Timeline vs. Timestream
Second, there's a difference between the Doctor crossing his own timeline, and what he did in "Name of the Doctor". When the Doctor says he can't cross his own timeline, he's concerned with doing something that would alter his own history. That could create a paradox that the Universe cannot work around; we've seen that such paradoxes can result it very bad things for the people involved (e.g. in "Angels Take Manhatten", a huge stretch of time was just "undone" to resolve a paradox).
In the "Name of the Doctor", Clara had entered into some kind of energy manifestation of the Doctor's entire life, and dispersed herself across his timeline. Even though she was intentionally trying to interact with him, it seemed pretty difficult. The Doctor went into that same environment merely trying to pull Clara's pieces back together. He wasn't really in a position to interact with himself or cause major changes to his own timestream by accident, so the risk seemed a lot lower.


text:
Q: Is syntactic consequence required to define semantic consequence? I have read quite a number of the questions on stack exchange to try to understand the relationships/differences between syntactic consequence, semantic consequence, and material implication.
For example in this post: https://philosophy.stackexchange.com/questions/10785/semantic-vs-syntactic-consequence, the definition of semantic consequence is given as Γ ⊨ φ says: sentence φ is true in all models of Γ. A similar definition is given here: https://math.stackexchange.com/questions/365569/whats-the-difference-between-syntactic-consequence-⊢-and-semantic-consequence-⊨. In particular that we have to have the entailed sentence be 'true'.
From this I am wondering does 'truth' in the definition of semantic consequence require the use of syntactic consequence? That is, do we first need the notion of syntactic entailment in order to define this semantic consequence?

A: Any sensible system of logic (e.g. propositional calculus or predicate calculus) is sound ($p$ the syntactic consequence of $\Omega$ implies $p$ is the semantic consequence of $\Omega$. That means that if something is provable (from a set of premises) then it must be true (assuming the premises are true). This seems necessary if proof is going to mean anything. The non-trival theorem is whether $p$ being the semantic consequence of $\Omega$ implies that $p$ is the syntactic consequence of $\Omega$. i.e. if something is true then it is provable. This is true for the propositional calculus with a finite set of premises. It requires the axiom of choice to prove it for propositional calculus with an infinite set of premises and, of course, it is not true for any formal system that includes arithmetic (as shown by Godel).


text:
Q: Intel integrated graphics screen tearing I seem to be having problems with screen tearing on my Intel nuc5ppyh(n3700 quadcore) with intel integrated graphics. I'm using ubuntu 15.10 with gnome3 but the problem consists in unity or xfce as well. It's noticable when scrolling through webpages, watching fullscreen HD videos through pipelight, html5 or a local file.
I have tried the following to try and fix my problem:

*

*Installed latest intel graphics stack from 01.org

*My config file (/etc/X11/xorg.conf.d/20-intel.conf) looks like this:
Section "Device"
Identifier "Intel Graphics"
Driver "Intel"
Option "AccelMethod" "sna"
Option "TearFree" "true"
Option "TripleBuffer" "true"
Option "MigrationHeuristic" "greedy"
Option "Tiling" "true"
Option "Pageflip" "true"
Option "ExaNoComposite" "false"
Option "Tiling" "true"
Option "Pageflip" "true"
EndSection

I've decided to disable the tearfree and triplebuffer options, they do not have any result on my screen tearing but increase buffer times specifically on pipelight streams.
Furthermore I have tried the fix described in this link: http://www.rottenrei.be/posts/2014-12-23-fixing-ubuntu-s-screen-tearing-on-intel-hd-graphics/
and supposedly this package should have cleared my tearing as well but to no avail: https://launchpad.net/ubuntu/wily/+source/xserver-xorg-video-intel
I'm not really an expert at drivers and such as it comes to ubuntu, so don't expect me to fully understand the answers that may be given to me. English is also not my native language so expect some level of discrepancy.
Thanks in advance!

A: I was able to eliminate screen tearing by enabling DRI3 with SNA acceleration. According to the link below, option "TearFree" "true" is not necessary with option "DRI" "3".
https://wiki.archlinux.org/index.php/intel_graphics#Tear-free_video
Here is a method to turn on DRI3 by editing your xorg.conf file to something like this:
Section "Module"
    Load "dri3"
EndSection

Section "Device"
    Identifier  "Intel Graphics"
    Driver      "intel"
    Option      "DRI"   "3"
EndSection

A: Try to install and use Compiz windows manager. It works for me.


text:
Q: Python get specific data with Beautifulsoup Hey so i'm trying to get the value of wpid from this website https://www.scan.co.uk/products/1m-canyon-apple-lightning-to-usb-cable-for-apple-non-mfi-certified-iphones-5-6-7-8-x-11-black with python using beautifulsoup but i can't figure out how to only get the wpid and not the other stuff. help would be appreciated.
page = sess.get(url)
data = page.text
soup = BeautifulSoup(data, 'html.parser')
text = soup.find('div', class_='buyButton large')
text2 = text.find('a')['href']
text3 = (text.find('a').contents[0])
text4 = (soup.find('div', class_='buyButton large').contents[0])
#text3 = text.find('div')['data-wpid']
print(text)
print(text2)
print(text3)
print(text4)

this is the response i get:
Add To Basket
 https://secure.scan.co.uk/web/basket/addproduct/2951361 Add To Basket Add To Basket but i only want the value of the wpid which would be 2951361

A: Access the data-wpid attribute like you already do it, but on the correct element.
text is already the div with the attribute, therefore you don't need the extra find().
>>> print("wpid:", text["data-wpid"])
wpid: 2951361


text:
Q: Gradle plugin build pulls in wrong version of commons-io What appears to be happening is that compileJava pulls in commons-io-1.4.jar from the gradle distribution, in preference to my declared commons-io:commons-io:2.4. When I try to call a method (readLines(InputStream, Charset)) introduced in a later version, Gradle can't find it:
$ gradle compileJava
:compileJava
/home/dmoles/Projects/m12n-plugins/tools/m12n/multiproject-plugin/src/main/java/m12n/tools/multiproject/dependencies/DependencyExtractor.java:42: error: no suitable method found for readLines(ByteArrayInputStream,Charset)
            List<String> lines = IOUtils.readLines(new ByteArrayInputStream(stream.toByteArray()), Charsets.UTF_8);
                                        ^
    method IOUtils.readLines(Reader) is not applicable
      (actual and formal argument lists differ in length)
    method IOUtils.readLines(InputStream,String) is not applicable
      (actual argument Charset cannot be converted to String by method invocation conversion)
    method IOUtils.readLines(InputStream) is not applicable
      (actual and formal argument lists differ in length)
1 error
:compileJava FAILED

FAILURE: Build failed with an exception.

The dependencies section of my build.gradle (abbreviated):
dependencies {
  compile 'commons-io:commons-io:2.4'
  compile gradleApi()
  compile localGroovy()
}

gradle dependencies shows the right thing:
+--- commons-io:commons-io:2.4

Obviously in this specific case I can work around it by calling the older method, but is there a general fix for this? I don't want to have to individually track down every time I happen to use a library that's also used by Gradle itself.


text:
Q: How do you check if a html Meta tag exist using JavaScript? So I have the following Meta tag in the header of my HTML code
<html>
<head>
    <meta property="article:tag" content="This is an apple" />
    <meta property="article:tag" content="This is a pear" />
</head>

And I would like to check if the meta tag with the content "this is an apple" exists. But for some reason My alert box always runs true.
if (document.querySelectorAll('meta[content="This is an apple"]') != null) {
  alert('Its here!');
}

Any suggestions?

A: It will always return true because querySelectorAll return an empty array in case of 0 match. Documentation

You can use the length property of the NodeList object to determine the number of elements that matches the specified selector

try this:

if (document.querySelectorAll('meta[content="This is not an apple"]').length > 0) {
    alert('Its here!');
} else {
    alert('Its not here')
}
<head>
    <meta property="article:tag" content="This is an apple" />
    <meta property="article:tag" content="This is a pear" />
</head>

A: document.querySelectorAll returns an array. You want to check for its length, because if there are no matching elements, it returns [] (the empty array). So:
if (document.querySelectorAll('meta[content="This is an apple"]').length !== 0) {
    alert('Its here!');
}


text:
Q: PHP PDO Help Required I am trying to fetch the UserID of the user that has just logged in and store it in $_SESSION['UserID'], however it is not doing so.
Doesn't store it. Array ( [LoggedIn] => 1 [UserID] => )
// Database Connection File
    require("../system/config.php");

    $user['username'] = $_POST['username'];
    $user['password'] = md5($_POST['password']);

    $login_check = $DBH->prepare("SELECT Username, Password FROM Users WHERE Username = ? AND Password = ?");
    $login_check->execute(array($user['username'], $user['password']));

    if(count($login_check) == 1) {
        session_start();
        $row = $login_check->fetch();
        $_SESSION['LoggedIn'] = 1;
        $_SESSION['UserID'] = $row['UserID'];
        print_r($_SESSION);
    }

    else {
        echo "You have entered an incorrect Username and Password, please try again.";
    }

A: Edit: The answer you are probably looking for is that you aren't selecting UserID in your query. But you should still look at what I wrote below.

You'd should use if ($login_check->rowCount() == 1) instead of count()
Alternatively, it would be better to fetch() the password for the username and check it in php to see if it's correct because then you can detect and store bad password attempts for each user and possibly deny access for a while if there have been too many.
$login_check = $DBH->prepare("SELECT UserID, Password FROM Users WHERE Username = ?");
$login_check->execute(array($user['username']));
$row = $login_check->fetch();

if (!empty($row)) {
    // user exists
    if ($row['Password'] == $user['password']) {
        // login success
    }
    else {
        // bad password attempt
    }
}
else {
    // non-existant user
}


text:
Q: Dynamically add column to table and it's td's I have a table that is already defined and populated. Now what I'm trying to do is to find a specific column and after that create a new column, at the moment I have the code to handle this:

$(document).ready(function() {
  something();
});

function something() {
  var newTh = "";
  var th = $(`#tblTable th[data-something="1"]`).last();
  newTh = `
                        New Column
                    	`;

  th.after(newTh);
}

      Id
      Name
      Price

      1
      a
      100

      2
      a
      100

      3
      a
      100

The column is added properly but it's keeping the value from the pre-existing column. What can I do to move the content after/before adding a new column?

A: You can get the index of th element, and then you can find each tr to append New Column td value. Like below:

$(document).ready(function() {
    something();
});

function something() {
    var newTh = "";
    var th = $(`#tblTable th[data-something="1"]`).last();
    var index = th.index();
    newTh = `<th data-something="1-1">New Column</th>`;

    th.after(newTh);

    $("#tblBody").find("tr").each(function(){
        var tr = $(this);
        tr.find("td").eq(index).after(`<td>new column value</td>`);
    });
}

            Id
            Name
            Price

            1
            a
            100

            2
            a
            100

            3
            a
            100

A: The easiest method would be to add another  in each
 and copy the text into the new .
This works because each  must be at the same index as each
.

$(document).ready(function() {
  something();
});

function something() {
  const th = $('#tblTable th[data-something="1"]').last();
  th.after('New Column	');
  $('#tblTable tbody').children().each(function() {
    $(this).children().eq(th.index()).after('

');
  });
}

      Id
      Name
      Price

      1
      a
      100

      2
      a
      100

      3
      a
      100


text:
Q: dotnet webapp not running on localhost:5000 / 50001 I'm trying to run a dotnet webapp project in visual studio. When I run pops up a powershell window and it's saying that my application is running on https://localhost:5000 or localhost:5001. But when I try to access it appears: this localhost page can't be found. browser screen-shot
powershell screen-shot

A: I had the same problem like you.
Probably you have the problems with certificate.
So try to run this PowerShell script for that ports :
Start-Transcript -Path "$($MyInvocation.MyCommand.Path).log"
try {
    Write-Host "Creating cert resources"
    $ekuOidCollection = [System.Security.Cryptography.OidCollection]::new();
    $ekuOidCollection.Add([System.Security.Cryptography.Oid]::new("1.3.6.1.5.5.7.3.1","Server Authentication")) | Out-Null
    $sanBuilder = [System.Security.Cryptography.X509Certificates.SubjectAlternativeNameBuilder]::new();
    $sanBuilder.AddDnsName("localhost") | Out-Null

Write-Host "Creating cert extensions"
$certificateExtensions = @(
    # Subject Alternative Name
    $sanBuilder.Build($true),
    # ASP.NET Core OID
    [System.Security.Cryptography.X509Certificates.X509Extension]::new(
        "1.3.6.1.4.1.311.84.1.1",
        [System.Text.Encoding]::ASCII.GetBytes("IIS Express Development Certificate"),
        $false),
        # KeyUsage
        [System.Security.Cryptography.X509Certificates.X509KeyUsageExtension]::new(
            [System.Security.Cryptography.X509Certificates.X509KeyUsageFlags]::KeyEncipherment,
            $true),
            # Enhanced key usage
    [System.Security.Cryptography.X509Certificates.X509EnhancedKeyUsageExtension]::new(
        $ekuOidCollection,
        $true),
        # Basic constraints
        [System.Security.Cryptography.X509Certificates.X509BasicConstraintsExtension]::new($false,$false,0,$true)
    )
Write-Host "Creating cert parameters"
$parameters = @{
    Subject = "localhost";
    KeyAlgorithm = "RSA";
    KeyLength = 2048;
    CertStoreLocation = "Cert:\LocalMachine\My";
    KeyExportPolicy = "Exportable";
    NotBefore = Get-Date;
    NotAfter = (Get-Date).AddYears(1);
    HashAlgorithm = "SHA256";
    Extension = $certificateExtensions;
    SuppressOid = @("2.5.29.14");
    FriendlyName = "IIS Express Development Certificate"
}
Write-Host "Creating cert"
$cert = New-SelfSignedCertificate @parameters

$rootStore = New-Object System.Security.Cryptography.X509Certificates.X509Store -ArgumentList Root, LocalMachine
$rootStore.Open("MaxAllowed")
$rootStore.Add($cert)
$rootStore.Close()

Write-Host "Creating port bindings"
# Add an Http.Sys binding for port 44300-44399
$command = 'netsh'
for ($i=5000; $i -le 5002; $i++) {
    $optionsDelete = @('http', 'delete', 'sslcert', "ipport=0.0.0.0:$i")
    $optionsAdd = @('http', 'add', 'sslcert', "ipport=0.0.0.0:$i", "certhash=$($cert.Thumbprint)", 'appid={214124cd-d05b-4309-9af9-9caa44b2b74a}')
    Write-Host "Running $command $optionsDelete"
    & $command $optionsDelete
    Write-Host "Running $command $optionsAdd"
    & $command $optionsAdd
}
}
catch {
    Write-Error $_.Exception.Message
}
finally {
    Stop-Transcript
}

I hope that will work for you too!


text:
Q: "So" meaning "in such a way" A sentence:

These are the books so written that it can bewitch the readers.

Does this mean the same as:

"These are the books written in such a way that it can bewitch the readers."?

Is there any variation in formality?

A:
"These are the books so written that 'they' can bewitch the readers."

"These are the books written in such a way that 'they' can bewitch the readers."

I changed the 'it' to 'they'.
There is no significant difference between the 2 examples.


text:
Q: How to calculate current in a symmetric circuit diagram
I am relatively new to circuit diagram and I am trying to find out how I can calculate Io shown in the above diagram. From my understanding, this looks like a symmetric circuit diagram, however I can't wrap my head around it on how to calculate the current on that point.

A: redraw like this

simulate this circuit – Schematic created using CircuitLab


text:
Q: How can I make Excel a template only in Office 365/Share point When using tools such MS Forms (for surveys) or Mural/Miro I can create a template.
The template allows others to duplicate them for their own use with impacting the original.
I have an Excel, which so far, we use a naming convention of the file which is
_PLEASE_CREATE_A_COPY_BEFORE_MAKING_CHANGES.xls
Obviously there is risk because some one may simply not do this!
Is it possible to create 'duplicate' only versions of Excel?

A: Within Share point, you may have to edit the share options and un check the allow editing option

A: You can try IRM, which can be found at this link for details: https://docs.microsoft.com/en-us/microsoft-365/compliance/set-up-irm-in-sp-admin-center?view=o365-worldwide


text:
Q: kdiff3 giving error on "git difftool --dir-diff" I just upgraded kdiff3 on my mac (using brew).  Since I did that, everytime I run git difftool --dir-diff branch <branch2> I get a modal dialog box that has the title "Some files could not be processed." and has a text area with zero or more "Mix of links and normal files.".
If I omit the --dir-diff it works as expected.
I'm not sure what this means.  There are no symlinks in the directory (at least, find . -type l comes up empty).  Maybe I'm doing something dumb, but I don't know what it's trying to complain about.
I can click ok, and move forward, and I get the actual diff, with two hiccups (no idea if the hiccups are related or not).  For each of the files (but not directories)

*

*in the "Operation" column I get "Error: Conflicting File Types".

*in the "A" and "B" columns every square is black.

This looked similar, but is not, I tried the test case and it doesn't even bring up the error for me.
I can't follow this, maybe it's the issue I'm having, it certainly has a lot of the same symptoms.  But the only response I see is a request for a test case.
So:

*

*Does anyone know what this error even means?

*Does anyone know how to get rid of it?  The fact that it breaks my concentration is a much bigger problem than clicking the single button.

Thank you very much.

A: There is the answer to this error in KDiff3 Q&A
https://docs.kde.org/trunk5/en/kdiff3/kdiff3/faq.html#idm2019
Git has to create links and kdiff3 has to check if follows them or not. In an early version, this error (when there are links and files) was ignored. Now it is reported.
In Settings/Configure KDiff3/Folder you may switch from "Binary comparison" to "Full Analysis" to get probably desired behavior.


text:
Q: Single "mkdir" command to make a new directory and change to that directory at the same time? Quick question:
Is it possible to use "mkdir" to make a new directory AND change to that directory at the same time using a single 'mkdir' command?
Whole question:
I have this question:
What single Linux "mkdir" command could replace the sequence of commands?
         mkdir a
         cd a
         mkdir b
         cd b
         mkdir c
         cd ../..

My answer is:
         mkdir a b c && cd c

Is there a single "mkdir" command, without using any other commands, perhaps with some flags or something, I can use to make AND change directory at the same time?

A: The question you present of using a single mkdir command to do the same as the other steps doesn't really involve changing directories. It ends with cd ../.. which brings you back to the directory you were in at the start.
In effect, that sequence of commands creates a directory a, then a directory b within it (in other words, a/b), then a directory c within the just created b (in other words, a/b/c.)
You can do the same with a single mkdir command that creates the nested directories after creating their parents:
mkdir a a/b a/b/c

Another way is using mkdir's -p option, which will create the parent directories if necessary, so you don't need to specify them:
mkdir -p a/b/c

This doesn't answer your question in the title (for mkdir + cd look at the duplicates from the comments), but addresses the question in your text, about the equivalent single mkdir command for that sequence, in which at the end of the sequence the directory is the same as at the start of it.

A: Do it as a function:
mkcdir ()
{
    mkdir -p -- "$1" &&
      cd -P -- "$1"
}


text:
Q: Implementing iOS procotol - readonly property I have a protocol from QuickLook framework:
/*!
 * @abstract The QLPreviewItem protocol declares the methods that a QLPreviewController  instance uses to access the contents of a given item.
 */
@protocol QLPreviewItem <NSObject>

@required

/*!
 * @abstract The URL of the item to preview.
 * @discussion The URL must be a file URL.
 */
@property(readonly) NSURL * previewItemURL;

@optional

/*!
 * @abstract The item's title this will be used as apparent item title.
 * @discussion The title replaces the default item display name. This property is optional.
 */
@property(readonly) NSString * previewItemTitle;

@end

/*!
 * @abstract This category makes NSURL instances as suitable items for the Preview Controller.
 */
@interface NSURL (QLPreviewConvenienceAdditions) <QLPreviewItem>
@end

I'm trying to create the getter and setter for the readonly property previewItemTitle so I can add my custom tile:
.h
#import <Foundation/Foundation.h>
#import <QuickLook/QuickLook.h>

@interface QLPreviewItemCustom : NSObject <QLPreviewItem> {
    NSURL * previewItemURL;
    NSString *previewItemTitle;
}

@property(readonly) NSURL * previewItemURL;
@property (readonly) NSString *previewItemTitle;

@end

.m
#import "QLPreviewItemCustom.h"

@implementation QLPreviewItemCustom

@synthesize previewItemTitle;
@synthesize previewItemURL;

@end

This way, as I understand, I will create just the getter with the synthesize method. How can I create the setter?

A: If it's just in your implementation of QLPreviewItemCustom that you want to access the setter, then why not extend the property in a class continuation category to read-write:
QLPreviewItemCustom.m
#import "QLPreviewItemCustom.h"

@interface QLPreviewItemCustom ()

@property (readwrite) NSURL *previewItemURL;
@property (readwrite) NSString *previewItemTitle;

@end

@implementation QLPreviewItemCustom

@synthesize previewItemTitle;
@synthesize previewItemURL;

@end

If you want to use the setter everywhere then you'll have to use a different ivar name and write your getter for the original to pass through to your new one. Like this:
QLPreviewItemCustom.h
#import <Foundation/Foundation.h>
#import <QuickLook/QuickLook.h>

@interface QLPreviewItemCustom : NSObject <QLPreviewItem> {
    NSURL *url;
    NSString *title;
}

@property (readwrite) NSURL *url;
@property (readwrite) NSString *title;

@end

QLPreviewItemCustom.m
#import "QLPreviewItemCustom.h"

@implementation QLPreviewItemCustom

@synthesize url;
@synthesize title;

- (NSURL*)previewItemURL {
    return self.url;
}

- (NSString*)previewItemTitle {
    return self.title;
}

@end

It's worth also pointing out that it's not generally a good idea to use the same class prefix yourself as is used by another framework. i.e. don't call it QLPreviewItemCustom - call it something like ABCPreviewItemCustom.

A: You can write to it directly in variable, not in property. If you write self.previewItemURL you'll access property, but if you write just previewItemURL you'll access variable and you can write to it without any restrictions.
For more visibility you can name your field differently, for example
@interface QLPreviewItemCustom : NSObject <QLPreviewItem> {
    NSURL * _previewItemURL;
    NSString *_previewItemTitle;
}

@property(readonly) NSURL * previewItemURL;
@property (readonly) NSString *previewItemTitle;

@end

and implementation:
@implementation QLPreviewItemCustom

@synthesize previewItemTitle = _previewItemTitle;
@synthesize previewItemURL = _previewItemURL;

@end

Now, you can access field directly via _Name and property as self.Name


text:
Q: How do I write a Lambda function for my Stripe integration? Background: I am migrating our sales pages to a serverless CDN using Gatsby -> Netlify, and am trying to implement a Stripe customized payment flow because we want to customize our checkout form. I implemented the Stripe Checkout on one of our landing pages here, but it's not what we want. Landing Page
Stripe's documentation is very straightforward, but the documentation assumes one is running a server.
The below code is the server implementation snippet from their documentation.

const express = require("express");
const app = express();
// This is your real test secret API key.
const stripe = require("stripe")("sk_test_51J085aDDSnMNt7v1ZO3n5fxobP6hhEhf1uC2SDmkHGIX8fCnxFiSMrxITKu06ypYUHYAMHVZ1lhc5Fqm7UoVa6dx00XvV5PZzG");

app.use(express.static("."));
app.use(express.json());

const calculateOrderAmount = items => {
  // Replace this constant with a calculation of the order's amount
  // Calculate the order total on the server to prevent
  // people from directly manipulating the amount on the client
  return 1400;
};

app.post("/create-payment-intent", async (req, res) => {
  const { items } = req.body;
  // Create a PaymentIntent with the order amount and currency
  const paymentIntent = await stripe.paymentIntents.create({
    amount: calculateOrderAmount(items),
    currency: "usd"
  });

  res.send({
    clientSecret: paymentIntent.client_secret
  });
});

app.listen(4242, () => console.log('Node server listening on port 4242!'));

Here's Stripe's payment flow.
Stripe's Payment Processing Flow
Challenge: Since I am moving our content to Netlify, which is a serverless CDN, I need to use Lambda functions to interact with the Stripe API instead of the express server implementation in their example.
Netlify describes using serverless functions on their platform here.
I was able to run this silly little thing. But I know how request that output in my React app if I wanted to...

exports.handler = async function(event, context, callback) {
    const { STRIPE_PUBLISHABLE_KEY } = process.env;
    console.log("I am the Hello World Lambda function.")
    return {
        statusCode: 200,
        body: JSON.stringify({message: STRIPE_PUBLISHABLE_KEY})
    };
}

I know I'm displaying my level of skill here, but as my Dad would say: better shame than pain.
Question:/Ask Can someone help me understand how to think about this?
I don't know if this would be a help, but here's my git repository.
Any help would be incredibly appreciated. And if any of you have a few spare cycles and would consider mentoring me on this over a zoom meeting. I will absolutely pay you for your time.
Thanks much!
John

A: I can definitely help you get started with Serverless / Stripe. There are multiple APIs and libraries that are quite confusing at first, so this will hopefully be useful for others doing the same.
The Stripe API has a number of ways of doing similar things, but this is a basic flow you can use for accepting a credit card payment securely on a static site using Netlify Lambdas (or any similar solution).
I'll assume that you're using Stripe's Elements credit card form for react.
The basic principle is that we need to do actions which use the Stripe secret on the "server" side (i.e. in a lambda) and the rest we can do on the client.

*

*Install Stripe packages -  npm install stripe @stripe/react-stripe-js @stripe/stripe-js

*Follow the react package's instructions to create a basic payment form: https://github.com/stripe/react-stripe-js#using-hooks

import React from 'react';
import ReactDOM from 'react-dom';
import {loadStripe} from '@stripe/stripe-js';
import {
  CardElement,
  Elements,
  useStripe,
  useElements,
} from '@stripe/react-stripe-js';

const CheckoutForm = () => {
  const stripe = useStripe();
  const elements = useElements();

  // we will edit this
  const handleSubmit = async (event) => {
    event.preventDefault();
    const {error, paymentMethod} = await stripe.createPaymentMethod({
      type: 'card',
      card: elements.getElement(CardElement),
    });
  };

  return (
    <form onSubmit={handleSubmit}>
      <CardElement />
      <button type="submit" disabled={!stripe}>
        Pay
      </button>
    </form>
  );
};

const stripePromise = loadStripe('pk_test_abc123');

const App = () => (
  <Elements stripe={stripePromise}>
    <CheckoutForm />
  </Elements>
);

ReactDOM.render(<App />, document.body);

*

*Now we'll write a submit handler which will

*

*Create a paymentIntent securely using a lambda and stripe server-side

*Confirm the payment on the frontend with a user's credit card details using the javascript api
Lambda
Change the body of your lambda as follows:
  const stripe = require("stripe")(process.env.STRIPE_SECRET);
  const { amount, currency = "gbp" } = JSON.parse(event.body);

  try {
    const paymentIntent = await stripe.paymentIntents.create({
      amount,
      currency,
    });
    return {
      statusCode: 200, // http status code
      body: JSON.stringify({
        paymentIntent
      }),
    };
  } catch (e) {
    // handle errors
  }

Here we initialise the stripe library with your stripe secret key, we create a minimal paymentIntent using just amount and currency, and then we return it to the client.
Frontend
Assuming you've got Stripe and Elements loaded as in the linked example and have a basic credit card form, you'll just need to edit the submit handler.
First call your paymentIntents lambda:
// handleSubmit()
const intent = await fetch("/.netlify/functions/payment-intent", {
  method: "POST",
  body: JSON.stringify({
      amount: 500,
    }),
  });
const { paymentIntent } = await intent.json();

Now you can use the paymentIntent to confirm the card details the user has entered. (The paymentIntent contains a client_secret which is required to confirm a payment.)
// if you've followed the example, this is already done
import { CardElement, useStripe, useElements } from "@stripe/react-stripe-js";
const stripe = useStripe();
const elements = useElements();

// now back to handleSubmit()
await stripe.confirmCardPayment(paymentIntent.client_secret, {
  payment_method: {
    card: elements.getElement(CardElement),
    billing_details: {
      email: profile.email,
    },
  },
});

Here we use the javascript API's confirmCardPayment method to confirm the payment using the client_secret from the paymentIntent we just set up. The credit card details are taken care of by the elements.getElement method. We also provide the user's email so their receipt can be sent to them.
Next steps
This is a very basic serverless implementation of accepting payments via stripe. You can look at the different APIs to set up customers and use their IDs for payments, set up subscriptions, and much more.
Naturally you will also want to handle the many and various errors that I've ignored.
Versions used are latest versions of all stripe libraries listed as at 2021-06-12


text:
Q: Global Spec functor and base change Let $f:X \rightarrow Y$ be any morphism of schemes, $A$ be a quasi-coherent sheaf of $\mathcal{O}_X$ algebra (Or Noetherian schemes, coherent sheaf if you want), S be a scheme over $Y$ defined by $A$ using the global Spec. Now can we conclude that $X \times_Y S$ is isomorphic with the scheme defined by $f^*A$ ¿ I think that will be true to check locally but not that definite with that.

A: Question: "Now can we conclude that $X×_Y S$ is isomorphic with the scheme defined by $f_∗A$? I think that will be true to check locally but not that definite with that."
Answer: If $f: X:=Spec(B) \rightarrow S:=Spec(A)$ and if $A_S$ is any quasi coherent sheaf of $\mathcal{O}_S$-algebras it follows $R:=\Gamma(S,A_S)$ is an $A$-algebra with $A_X \cong \tilde{R}$ the sheafification of $R$. Let $T:=Spec(A_S)$. It follows
$$X\times_S T\cong Spec(B\otimes_A R).$$
And $f^*(A_S) \cong \tilde{B\otimes_A R}$ is the sheafification of $B\otimes_A R$, hence
$$Spec(f^*A_S) \cong Spec(B\otimes_A R) \cong X\times_S T.$$
This construction globalize.
If $A_X$ is a quasi coherent sheaf of $\mathcal{O}_X$-algebras, there is a map
$$f^{\#}: \mathcal{O}_S \rightarrow f_*\mathcal{O}_X$$
hence $f_*A_X$ is a quasi coherent sheaf of $\mathcal{O}_S$-algebras and you may construct $\pi: Spec(f_*A_X)\rightarrow S$ which is a scheme over $S$
Note: The push forward $g_*F$ of a quasi coherent sheaf $F$, where $g: Y \rightarrow Y'$ is a map of schemes, is not always quasi coherent. It is quasi coherent when $Y$ is Noetherian.


text:
Q: form.attr('action') how to get protocol of a relative url to send correct request I've a form as following:
<form action="/staffpanel/companies/2187/update/" method="post" id="cmpForm">
...
</form>

My js code is:
    $(document).on('submit', '#cmpForm', function () {
        var form = $('#cmpForm');
        var actionUrl = form.attr('action');

        ajax({
             url: actionUrl,
             type: 'POST',
             processData: false,
             contentType: false,
             success: function (data) {
                ...
             }}});

I'm facing this issue, ajax send the request to an url with the wrong protocol. This piece of code works well on local without SSL but not in production over HTTPS.
How can I handle ajax to request over HTTPS instead !
EDIT: Using .prop gives the correct URL. I figured out that my issue comes from the endpoint. The view returned by HttpResponseRedirect() to ajax is badly formed, using the bad protocol.
As all my views called in the browser (even with the wrong protocol) are turned correctly to HTTPS, might it be something related to the NGINX conf?


text:
Q: Create a Windows 7 install USB from OS X?
Possible Duplicate:
How to create a bootable USB Windows OS using Mac OS X

I am attempting to install Windows 7 on a system I've newly built, and I'm having a hell of a time of it. I need to create a USB stick which will install Windows 7. Apparently this would have been a lot easier to do from Windows, but at this point, I no longer have a working Windows install. I have only a Macbook Pro running OS X available (note: I am not trying to install Windows on the MBP.)
I've found reports that I claim I just need to dd the files over, but this does not work.
I also tried using Boot Camp Assistant (after hacking the Info.plist) to create install media.
In both of these cases, what has happened is that the bios (or the UEFI?) has recognized the disk, but all I get is a black screen and a flashing cursor (the underscore kind, not a mouse cursor.)
As I briefly noted, this system has a UEFI bios. I'm not really familiar with this, so I thought it might matter.

A: Okay, after much tribulation, I figured this out.
The best bet is simply to use that handy ISO you've got sitting around to create a Windows virtual machine and then use Microsoft's tool to create an installer USB stick.
You can use Virtual Box (free) to create the Windows VM (if you need help, there are somewhere around a million tutorials online.) The one little tricky bit was that you have to install Virtual Box's Extension Pack (also free!) in order to get USB drives to work in the Windows VM. Be sure to eject the USB stick in OS X, then you can go to the Devices menu in Virtual Box, and check the USB stick, and it'll appear in Windows.
Hurray!


text:
Q: SSH tunnel through middleman server - how to connect in one step (using key pair)? My question is basically how to turn my existing two steps into one step.
I have a working SSH tunnel set up between two computers using a middleman server like this:
Kubuntu_laptop--->nat_fw--->Debian_Server<--nat_fw<--Kubuntu_desktop

What I do presently is SSH from Kubuntu_laptop to Debian_Server and then from Debian_Server to Kubuntu_desktop. I would like to make that one SSH command, issued on my Kubuntu_laptop in bash that results in my being connected to the Kubuntu_desktop (shell/bash).
The commands I am using now are as follows. Step 1:
me@kubuntu_laptop:~$ ssh -i ~/.ssh/id_rsa admin@debian_server

Step 2:
admin@debian_server:$ ssh -p 1234 -i /home/admin/.ssh/id_rsa admin@localhost

Then I am connected to the kubuntu_desktop via SSH (from kubuntu_laptop).
RSA keys are required for all SSH connections. Password login is disabled all the way around. And notice that the computer user accounts are different at two of the computers.
Regarding the connection for this leg:
Debian_Server<--nat_fw<--Kubuntu_desktop

Here is how it is established:
autossh -M 5234 -N -f -R 1234:localhost:22 user@mydebian.com -p 22

Notice Kubuntu_desktop connects to middleman as user@mydebian.com (not admin@debian_server). But when I connect to Kubuntu_desktop, I connect as admin user.
I cannot change the existing monitoring port (5234) or the remote (- R) port number (1234 in this example). I cannot change the SSH security to allow password logins. I cannot open up any new firewall ports. I can't change user accounts (except on laptop).

A: Make sure netcat is installed on the Debian server, and use ProxyCommand in your local SSH configuration (~/.ssh/config).
Host Kubuntu_desktop
  ProxyCommand ssh Debian_Server nc localhost 1234

A: Thanks to @Ignacio Vazquez-Abrams here are all the steps:

Make sure netcat is installed on the Debian server, and use ProxyCommand in your local SSH configuration (~/.ssh/config).

I edited config as follows:
me@kubuntu_laptop:~/.ssh$ nano config

The contents are:
Host kubuntu_desktop
  ProxyCommand ssh debian_server_fqdn nc localhost 1234
  User admin
  PasswordAuthentication no
  IdentityFile ~/.ssh/my_id_rsa

Then just connect:
me@kubuntu_laptop:~$ ssh kubuntu_desktop

Connected to kubuntu_desktop via SSH in 1 step! Perfect
Update:
This makes it more flexible:
me@kubuntu_laptop:~/.ssh$ nano config

The new contents are:
Host family_desktops
  ProxyCommand ssh debian_server_fqdn nc localhost %p
  User admin
  PasswordAuthentication no
  IdentityFile ~/.ssh/my_id_rsa

Then just connect to Mom:
me@kubuntu_laptop:~$ ssh family_desktops -p 1234

And connect to Dad:
me@kubuntu_laptop:~$ ssh family_desktops -p 5678

Of course, Mom & Dad have to have Step 0 set up (from my original question) where each has their own -R port defined. Example for Dad:
Step 0 (for Dad):
autossh -M 6543 -N -f -R 5678:localhost:22 user@mydebian.com -p 22

Optional:
DAD=5678
ssh family_desktops -p $DAD


text:
Q: PHP-CPP Versão da Compilação Estou com problema com uma extensão que estou compilando em PHP-CPP, pois quando compilo no meu Mac, a versão local dele é a 20121212, mas o meu Xampp é a versão 20131226, o problema é que em cada versão do php que ter uma compilação própria, senão não funciona. Como posso fazer uma compilação "universal"?

A: Infelizmente não tem como criar uma compilação universal, cada versão do php realmente possui diferentes compilações, isso ocorre em qualquer software, não só php.
Este problema ocorre por causa tipos diferentes de arquiteturas, como por exemplo:

*

*Diferentes processadores

*Diferentes sistemas operacionais

*Diferentes compiladores (mingw, msvc)

*Diferentes versões dos compiladores

*Diferentes versões de um mesmo sistemas operacionais

A build de uma versão especifica do php compilada é baseado na "arquitetura que foi compilada". Veja um exemplo, os Androids usam Java como linguagem e "gerenciador", isto porque um programa compilado em java não roda no dispositivo diretamente, ele roda na "máquina virtual do java" e por isso mesmo com tantos celulares e tablets com arquiteturas diferentes podem rodar um programa em diferentes processadores como ARM e Intel, pois cada Android para cada arquitetura de celular (com diferentes processadores) tem a sua própria versão do Java que é compatível com o processador usado no dispositivo.
Voltando a falar sobre compilação, a unica maneira de se ter algo universal no PHP é não usar extensões criadas por você e passar a usar os .php que não são compilados, mas sim "interpretados" e vão rodar em qualquer compilação do PHP, mesmo que de diferentes processadores.

Note que muitas funcionalidades do php5.3 não funcionam no 5.2, como namespaces, assim como o php5.4 possui características que não são suportadas pelo 5.3, estamos aqui falando de arquitetura e não de versões do php.

Note que além de executar em servidores você pode executar o php por terminal e se for um ambiente like-unix ou uma "porta cgi" você pode criar um arquivo com uma extensão qualquer e aplicar o path do executável do php no inicio do código (eu não tenho certeza, me corrija se tiver confundido como preparar o script):
#!/usr/local/bin/php-cgi
<?php

Ou então configurar a variável de ambiente PATH com o caminho do executável do PHP.
Se isto não é uma opção, então realmente você terá que compilar a extensão para cada versão do PHP, note isto http://windows.php.net/download:

*

*php7:

*

*VC14 x86 Non Thread Safe

*VC14 x86 Thread Safe

*VC14 x64 Non Thread Safe

*VC14 x64 Thread Safe

*php5.6:

*

*VC11 x86 Non Thread Safe

*VC11 x86 Thread Safe

*VC11 x64 Non Thread Safe

*VC11 x64 Thread Safe

Note que temos os termos VC11, x86, x64, NonThreadSafe e Thread Safe:

*

*VC11 indica que foi compilado na versão 11 do VisualC++

*VC14 indica que foi compilado na versão 14 do VisualC++

*x86 indica que foi compilado em um processado "32bit" assim como x64 indica que foi compilado em um processado "64bit"

*ThreadSafe (TS) trabalha com servidores multi-thread (Apache2 no Windows por exemplo) e Non ThreadSafe (NTS) indica se foi compilado.
Thread Safety funciona criando uma cópia local em cada thread, de modo que os dados não colidirão com outra thread.
O NTS não tem isto e ele é voltado para FastCGI por exemplo.
Então você terá que fazer extensões muito mais do que só compatível com o tipo de versão do PHP. Esse build (20131226) é mesmo voltado para evitar problemas.
O ambiente de compilação para qualquer tipo de software pode ser um pouco complicado mesmo, o que você pode fazer para facilitar é distribuir o source (muitos desenvolvedores fazem isto) e compilar ele direto na máquina que vai ser instalado, criando um arquivo .bat (no windows é provável que precise instalar um compilador) ou um bash no Linux (esse é o lado bom do linux, geralmente ele já vem com compilador).
Um exemplo é o proprio PHP, ele é distribuido em source também http://php.net/downloads.php (os arquivo .gz), as versões binarias na verdade acho que só existem pra windows, quem mantem as versões binarias em sistemas linux são os repositórios (acho que existe distros que compilam só depois de baixar pra máquina o php, ou seja trabalham com o source).
Resumindo, as soluções são:

*

*Usar arquivos .php ao invés de extensões

*Compilar os sources diretamente nos servidores (se você pode instalar .so ou .dll em um servidor é bem provável que possa compilar algo nele também).


text:
Q: how to show child ul under parent ul horizontally i asked several times for my navigation here but didn't get my desire results so i thought one last time maybe someone help me to achieve like this!

as you can see in below code i have only 5 parent menus and each of them have at least 12 child or submenus. i want to show my 5 parent or main menus horizontally like as you can see above image where home video news world sport etc and display their related child menus right under of it also horizontally again you look at image and notice parent link news selected and their child links like politics investigations obits education etc shown below him horizontally. and also notice that parent link news and child link investigations both have active class at the same time and i also want this effect.
and if you please visit this link - the telegraph you can also see if you refresh the page both navigation's remain intact and also maintains their active state.
this is my attempt please check out this fiddle in this fiddle you notice that when page is refreshed child navigation disappears and also problem with active link state only one link remains active but as you now know i want parent link to remain active even when i am on any of his child links just like you seen on the telegraph site in above link.
notes

*

*i used jquery ajax to load pages dynamically to a div and also used hash in my urls.

*also used this jquery bbq html5 history api based jquery ajax plugin to load pages, browser history and browser back and forward buttons and everything working fine.

please feel free to use any jquery lib any hack or what ever you like but i need this badly. anyone who can help me to achieve this i really appreciate him with bottom of my heart and also mention him on credits section of my site. thanks
p.s: ask any time for any further details if needed.


text:
Q: Uncaught SyntaxError: Invalid regular expression: missing / I have a TableCell like this:
<asp:TableCell CssClass="plusTd button" ID="plusCell">
                        </asp:TableCell>

I added a property to it like this:
plusCell.Attributes.Add("onclick", "/Add.aspx");

when I click on that cell, i got this error on the console:
Uncaught SyntaxError: Invalid regular expression: missing /

what am i missing please?

A: To redirect on click event, use this
plusCell.Attributes.Add("onclick", "window.location='/Add.aspx'");


text:
Q: JS Discord Bot Get Role I'm trying to get a role without using messages, like:
     const Discord = require('discord.js');
     const Bot = new Discord.Client();
     const Role = Discord.roles.find('name,'Exemple')

     Role.delete()

Is this possible to do that?

A: Yes you can but you will need to have the guild id you want to get the role from. Also, you should put that part in the ready event.
const discord = require("discord.js");
const client = new discord.Client();

client.on("ready", () => {
    console.log("Bot online!");
    const guild = client.guilds.get("The_server_id");
    const role = guild.roles.find("name", "Your_role_name");

    console.log(`Found the role ${role.name}`);
})

A: I tried with the posted solution but client.guilds.get was not recognized as a function:

UnhandledPromiseRejectionWarning: TypeError: client.guilds.get is not a function at Client.

Checking the content of client.guilds I found 'cache' object:
GuildManager {
  cacheType: [Function: Collection],
  cache: Collection [Map] {
    '<discord server id>' => Guild {
      members: [GuildMemberManager],
      channels: [GuildChannelManager],
      (...)
     }
  }
}

The solution was:
const Discord = require('discord.js');
const client = new Discord.Client();

client.once('ready', () => {
    const myGuild = client.guilds.cache.get('<discord server id>');
    const myRole = myGuild.roles.cache.find(role => role.name === '<role name>');
    console.log(`Found the role ${myRole.name}`);
});

A: Using that way of Collection#find("key", "value") in Discord.JS is deprecated by the way,
You should use Collection#find(Obj => Obj.key == "value") instead.

A: Guild doesn't work unless you have it set up on the server. People keep suggesting this but you have to already have infrastructure set up in your discord server.

A: const role = guild.roles.cache.get('role_id');
This seems to be working in the latest API version.

A: To get an specific role i use this code.
Replace SERVER_ID with your server id and ROLE_NAME with the name of the role
const guild = client.guilds.cache.get("SERVER_ID");
const role = guild.roles.cache.find((r) => r.name === "ROLE_NAME");

console.log(`Found the role ${role.name}`);
console.log(`Found the role ${role.id}`);


text:
Q: Android Studio Eectric Eel Gradle build failes for task ':base:compileDebugAidl' on Windows but succeeds on Ubuntu I am trying to build an android application using android studio electric eel version on windows 10. Here are the build env details
Android Studio Electric Eel | 2022.1.1
OS : Windows 10
Java Version: JDK 11.0.15
Gradle Version : 7.4.2
Android BUild Tool Version : 33.0.0

with same configuration and and versions, I am able to build the project successfully on Ubuntu 20.04 but when I build it on windows It is giving me the below error. However gradle sync is successful on windows also. all the gradle build files are same on linux and windows.

Execution failed for task ':base:compileDebugAidl'.
> A failure occurred while executing com.android.build.gradle.tasks.AidlCompile$AidlCompileRunnable
> com.android.ide.common.process.ProcessException: Error while executing process C:\Users\raj\AppData\Local\Android\Sdk\build-tools\33.0.0\aidl.exe with arguments {-pC:\Users\raj\AppData\Local\Android\Sdk\platforms\android-33-2\framework.aidl -oD:\TestProject\base\build\generated\aidl_source_output_dir\debug\out -ID:\TestProject\base\src\main\aidl -ID:\TestProject\base\src\debug\aidl -IC:\Users\raj.gradle\caches\transforms-3\8356e5a323ca3e835d1b836d6453d6ad\transformed\sesl5-core-1.0.13\aidl -IC:\Users\raj.gradle\caches\transforms-3\7dba48773cdea191a2126a893c822c2b\transformed\versionedparcelable-1.1.1\aidl -ID:\TestProject\resources\build\intermediates\aidl_parcelable\debug\out -IC:\Users\raj.gradle\caches\transforms-3\f4c5a157ca235ec4937ec35f41dcfdf6\transformed\smartkit4-4.290.0\aidl -IC:\Users\raj.gradle\caches\transforms-3\b03d82a7dddce150042f59edaa58def7\transformed\plugin_platform-1.50.22\aidl -IC:\Users\raj.gradle\caches\transforms-3\37f1ed7269bbd1c70d052e4adfa3b9f1\transformed\contentstreamingstatus-debug\aidl -dC:\Users\SHARMA~1.RAJ\AppData\Local\Temp\aidl17464009878466698701.d D:\TestProject\base\src\main\aidl\com\org\android\library\beaconmanager\BleScanFilter.aidl}

Do  I need to do some configuration for windows to build the code?


text:
Q: Does the artisan's level carry through to higher acts? Before investing a small fortune into levelling up my artisan (currently on act I) I want to know if his level carries through to the next act, otherwise I'll just wait and level him in the last act.

A: Not only do the Artisans' levels carry through to higher acts, but they're shared across all characters on your account.
The one exception being that Hardcore characters have a separate set of Artisans. But as long as you stick to one "core" (either hard or soft), know that your Artisans will not lose levels when swapping difficulty, character, or act.

A: Artisans maintain their levels (and any learned recipes) not only across acts, but also across characters (with the exception of hardcore vs normal; artisans leveled by hardcore characters are not accessible to normal characters, and vice versa).

A: Yes, they carry through. They even carry between difficulties and characters: The artisan levels when you start a new game on nightmare will be the same as where you left it when you finished the game in the lower difficulty.


text:
Q: How to handle DB migration using AWS deployment tools Amazon Web Services offer a number of continuous deployment and management tools such as Elastic Beanstalk, OpsWorks, Cloud Formation and Code Deploy depending on your needs. The basic idea being to facilitate code deployment and upgrade with zero downtime. They also help manage best architectural practice using AWS resources.
For simplicity lets assuming a basic architecture where you have a 2 tear structure; a collection of application servers behind a load balancer and then a persistence layer using a multi-zone RDS DB.
The actual code upgrade across a fleet of instances (app servers) is easy to understand. For a very simplistic overview the AWS service upgrades each node in turn handing connections off so the instance in question is not being used.
However, I can't understand how DB upgrades are managed. Assume that we are going from version 1.0.0 to 2.0.0 of an application and that there is a requirement to change the DB structure. Normally you would use a script or a library like Flyway to perform the upgrade. However, if there is a fleet of servers to upgrade there is a point where both 1.0.0 and 2.0.0 applications exist across the fleet each requiring a different DB structure.
I need to understand how this is actually achieved (high level) to know what the best way/time of performing the DB migration is. I guess there are a couple of ways they could be achieving this but I am struggling to see how they can do it and allow both 1.0.0 and 2.0.0 to persist data without loss.
If they migrate the DB structure with the first app node upgrade and at the same time create a cached version of the 1.0.0. Users connected to the 1.0.0 app persist using the cached version of the DB and users connected to the 2.0.0 app persist to the new migrated DB. Once all the app nodes are migrated, the cached data is merged into the DB.
It seems unlikely they can do this as the merge would be pretty complex but I can't see another way. Any pointers/help would be appreciated.

A: This is a common problem to encounter once your application infrastructure gets into multiple application nodes. In the olden days, you could take your application offline for "maintenance windows" during which you could:

*

*Replace application with a "System Maintenance, back soon" page.

*Perform database migrations (schema and/or data)

*Deploy new application code

*Put application back online

In 2015, and really for several years this approach is not acceptable. Your users expect 24/7 operation, so there must be a better way. Of course there is, the answer is a series of patterns for Database Refactorings.
The basic concept to always keep in mind is to assume you have to maintain two concurrent versions of your application, and there can be no breaking changes between these two versions. This means that you have a current application (v1.0.0) currently in production and (v2.0.0) that is scheduled to be deployed. Both these versions must work on the same schema. Once v2.0.0 is fully deployed across all application servers, you can then develop v3.0.0 that allows you to complete any final database changes.


text:
Q: What is meant by a partial derivative of a ket? In my QM book I often see partial derivatives mixed with kets, like
$$
\frac{\partial}{\partial a} |\psi \rangle
$$
where $a \in \{x, y, z\}$.  Here I'm assuming that $| \psi \rangle \in \mathbb{C}^n$ for some arbitrary $n > 0$ (in particular $n$ can be much larger than $3$).
Question: What is a partial derivative of a ket?  Don't partial derivatives operate on functions?  What does it mean to operate on a complex n-tuple?
Example: Schrödinger's equation famously involves mixing partial derivatives with kets:

$$i\hbar\partial_t|\Psi\rangle=-\frac{\hbar^2\partial_i^2}{2m}|\Psi\rangle+V(\hat{x})|\Psi\rangle$$

Here there is a partial derivative operator $\partial_i$ as well as a partial time-derivative operator $\partial_t$.

A: The derivative operator $\frac{\partial}{\partial x^j}$ in the Dirac notation is ambiguous because it depends on whether the derivative is supposed to act to the right (on a ket) or to the left (on a bra). See also my Phys.SE answer here. In Ref. 1 the derivative operator came from the Schrödinger representation of the momentum operator
$$\begin{align}\hat{p}_j
~=~&\int_{\mathbb{R}^3} \mathrm{d}^3p~ |{\bf p}\rangle ~ p_j ~\langle {\bf p}|\cr
~=~&\int_{\mathbb{R}^3} \mathrm{d}^3x~ |{\bf x}\rangle ~ \frac{\hbar}{i}\frac{\stackrel{\rightarrow}{\partial}}{\partial x^j} ~\langle {\bf x}|\cr
~=~&\int_{\mathbb{R}^3} \mathrm{d}^3x~ |{\bf x}\rangle ~ i\hbar\frac{\stackrel{\leftarrow}{\partial}}{\partial x^j} ~\langle {\bf x}| ,\end{align}\tag{1}$$
so that
$$\begin{align}\langle \phi |\hat{p}_j|\psi \rangle
~\stackrel{(1)+(3)}{=}&\int_{\mathbb{R}^3} \mathrm{d}^3x~ \phi^{\ast}({\bf x}) ~ \frac{\hbar}{i}\frac{\partial \psi({\bf x})}{\partial x^j} \cr
~\stackrel{(1)+(3)}{=}&\int_{\mathbb{R}^3} \mathrm{d}^3x~ i\hbar \frac{\partial \phi^{\ast}({\bf x})}{\partial x^j} ~\psi({\bf x}) ,\end{align}\tag{2}$$
where we have defined the wavefunctions
$$ \begin{align}\psi({\bf x})~:=~& \langle {\bf x}|\psi \rangle, \cr \phi^{\ast}({\bf x})~:=~& \langle \phi |{\bf x}\rangle.\end{align}\tag{3}$$
References:

*

*J. Schwichtenberg, No-Nonsense Quantum Mechanics: A Student-Friendly Introduction, 2018; eq. (7.24) on p. 285.

A: The other two answers are both great and this may be unnecessary but it might be worth explicitly mentioning that in Dirac notation the Schrodinger equation looks like
$$i \hbar \partial_t \lvert \Psi \rangle = \hat{H} \lvert \Psi \rangle$$
where the Hamiltonian can be further split up by defining the momentum and potential energy operators as
$$ \hat{H} = \frac{\hat{p}^2}{2m} + \hat{V}.$$
The answer from Qmechanic gives a very comprehensive definition of each component of $\hat{p}$ in position basis and following in the same vein as Quillo the potential operator relates to the scalar function $V(x, t)$ as
$\langle x \rvert \hat{V} \lvert x \rangle = V(x,t)$ so that (using the identity operator) we have
$$V(x,t) \Psi(x,t) = \langle x \rvert \hat{V} \lvert \Psi \rangle$$
and likewise
$$\frac{-\hbar^2 \partial_i^2}{2m} \Psi(x,t) = \frac{1}{2m} \langle x \rvert \hat{p}_i^2 \lvert \Psi \rangle.$$
This hopefully will demonstrate the equivalence (in most straightforward cases) of the two formulations when the position basis is used for Dirac notation.
Note: one of the most powerful things about Dirac notation is its generality in not specifying a basis whereas the form of the Schrodinger equation that is most familiar is specifically in the position basis. If instead we chose to use momentum space we could still get a valid form of the Schrodinger equation by doing something like
$\langle p \rvert \hat{H} \lvert \Psi \rangle.$ However, the operators $\hat{p}$ and $\hat{V}$ will have different forms in this scenario as they will be expressed in terms of the momentum basis so you can't just jump straight to the familiar form of the equation.

A: It is an abuse of notation: it mixes the Schrodinger notation (i.e. the usual wave function representation) with the abstract Dirac notation (the bra-ket notation). In your example, the Hamiltonian operator is expressed in the Schrodinger notation (i.e. with position operator that is "diagonal" and the momentum operator represented by the gradient), while the "state" is expressed in the Dirac notation (it is an abstract ket).
Long story short:
State at a particular time $t$: it is an abstract container $| w, t \rangle$ for some information $w$ at time $t$ ($w$ is a collection of values and/or procedures that determines the state of your object.. some sort of recipe to "prepare" it).
Wave function relative to the info $w$ at time $t$: think about is as a complex function $\Psi_w(x,y,z,t) = \langle {\bf x}| w, t \rangle $. Usually $w$ is dropped (in fact you are not even able to write it down most of the times, and it is a formal label for the state) and the common notations $\Psi({\bf x},t) = \langle {\bf x}| \Psi, t \rangle$ or $\Psi({\bf x},t) = \langle {\bf x}| \Psi(t) \rangle$ are used. You can think of $\Psi$ (or whatever name you want to use as something that completely labels the state and that is directly used in place of $w$). Note: $| {\bf x}\rangle$ is the abstract eigenstate of the position operator relative to the eigenvalue ${\bf x}$ (in the case of this "position ket" the information $w$ is simply $w={\bf x}$, namely "the particle is in ${\bf x}$"). In other simple cases the label $w$ may be a  set of "quantum numbers" or eigenvalues.
Completeness: since (formally) you have that $\sum_{x,y,z}| {\bf x}\rangle \langle {\bf x}|$ is the identity operator,
$$
|\Psi,t\rangle  = \sum_{x,y,z} |{\bf x}\rangle  \langle {\bf x}| \Psi(t) \rangle
= \sum_{x,y,z} \Psi({\bf x},t)   |{\bf x}\rangle \, ,
$$
which means that the ket $|\Psi,t\rangle $ and the associated wave function carry the same info (are both complete and equivalent representations of the state.. the ket one by definition). Moreover,
$$
\partial_t |\Psi,t\rangle  =  \sum_{x,y,z} (\partial_t \Psi({\bf x},t) )   |{\bf x}\rangle
$$
Bad notation: on the other hand, $\nabla |\Psi,t\rangle$ is just abuse of notation. To make sense of this, the gradient must be understood as an "abstract operator", acting on kets, that has the effect of differentiating wave functions once the expression is projected onto the position basis: you can try to use the completeness to obtain the decomposition of the abstract momentum operator (EDIT: see the nice answer of Qmechanic for this point!).
Time VS space: the derivative in time, although formal, is not an abuse of notation if applied to kets. In fact, time is not the eigenvalue of something, position yes. QM treats time and space in fundamentally different ways. Time is just a parameter in QM, so you can think of $|\Psi,t\rangle$ as a curve in the abstract space of states, and this curve has a "tangent" that is formally indicated as $\partial_t |\Psi,t\rangle$.


text:
Q: vnc server setup in RHEL machines Lab setup
I recently setup a lab with 10 RHEL machines for big data computation using Map/Reduce frameworks. The lab was setup in a closed network in such a way that all the machines had static IP addresses assigned to them. They were connected through the switches to the router and the router was used as the default gateway to communicate with the outer world.
Ten Machines - One monitor
I had one monitor for all the 10 machines. During installation of the machines, I had to constantly switch between the machines by unplugging the monitor from one machine and connecting it to the other machine.
Is there an easy solution so that I can view all the machines using the single desktop? I need some solution like ssh which will enable me to view the desktops of all the machines using a single monitor.

A: VNC Server Installation
The VNC server is specifically designed for this purpose. The installation is pretty straight forward as mentioned in this link. However, there are chances you may encounter some issues while installing. So, I am describing the issues that I faced and how I resolved them.
yum install vnc vnc-server

We need to decide which user will be using the vnc-server.
su vncuser

Now, we need to set the password.
vncpasswd

As a root user, perform the below operation.
vim /etc/sysconfig/vncservers

Add the below 2 lines.
VNCSERVERS="1:vncuser"
VNCSERVERARGS[1]="-geometry 1600x1200"

Type the below commands.
service vncserver start
service vncserver stop
chkconfig vncserver on

If the above commands are successful, we need to edit the xstartup file for whom we have configured the vncserver. So, in our case, we have configured it for the user vncuser. So,
su vncuser
vi ~/.vnc/xstartup

Uncomment the below 2 lines.
unset SESSION_MANAGER
exec /etc/X11/xinit/xinitrc

If the above step is also successful, we are finished with the configuration of the VNC server. However, we need to configure the firewall to permit the vnc communication. In the link, it is mentioned to directly edit the /etc/sysconfig/iptables file which is a very wrong approach. Instead do the below step.
iptables -I INPUT 1 -p tcp --dport 5901 -j ACCEPT

We have made the changes. But we need to change them.
/etc/init.d/iptables save

service iptables restart
service vncserver start

Now, we can view this machine as vncuser from a network machine by typing the below commands.
vncviewer
#Enter the server name as,
servername:1 #1 because, we opened up port 5901.


text: Q: How are realms created in the browser? I'm trying to understand in depth the concept of Javascript realms. However, I'm still having many problems with getting it correctly. First of all, I do not know how does the browser, lets say - Chrome, is able to create different JS realms for each tab. I'm looking for a deep explanation. Is there some API (JS API or Web API) for that excluding iframes? Or maybe it is something internal to V8?


text:
Q: Updating Recurring vCalendar Event I am working on custom SharePoint calendar which uses .NET code to render VCALENDAR payload with the email which I send to all attendees.
So far my implementation is working great except for updating recurring events. Outlook didn't able to recognize modified DTSTART/DTEND when I send updated VCALENDAR with same UID. Look like I am missing particular field for recurring events.
Here is sample of my VCALENDAR which I am sending to all attendees to update existing recurring event:
BEGIN:VCALENDAR
METHOD:REQUEST
PRODID:Microsoft CDO for Microsoft Exchange
VERSION:2.0
BEGIN:VTIMEZONE
    TZID:tz
    X-MICROSOFT-CDO-TZID:10
    LAST-MODIFIED:20111229T172655Z
    BEGIN:STANDARD
        DTSTART:20111106T020000
        TZOFFSETTO:+0000
        TZOFFSETFROM:+0000
    END:STANDARD
    BEGIN:DAYLIGHT
        DTSTART:20120313T020000
        TZOFFSETTO:+0100
        TZOFFSETFROM:+0000
    END:DAYLIGHT
END:VTIMEZONE
BEGIN:VEVENT
    SUMMARY:Simple Event\, Attendees:Tin Tin
    ORGANIZER:MAILTO:tin.tin@acme.com
    ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE;CN=;X-NUM-GUESTS=0:mailto:tin.tin@acme.com
    ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE;CN=;X-NUM-GUESTS=0:mailto:tin.tin@acme.com
    LOCATION:Conference Room
    DTSTAMP:20111229T172652Z
    UID:D26B0632-8496-4E76-977F-E7A04AF4CF4D
    SEQUENCE:1
    URL;VALUE=URI:http://acme/Lists/Conf/DispForm.aspx?ID=1178
    DTSTART;TZID=tz:20111229T140000
    DTEND;TZID=tz:20111229T150000
    RRULE:FREQ=WEEKLY;INTERVAL=1;BYDAY=TH;WKST=SU
    END:VEVENT
END:VCALENDAR

A: To properly update any existing event through VCalendar, always make sure to increment the SEQUENCE value in VEVENT section:
BEGIN:VEVENT
    SUMMARY:Simple Event\, Attendees:Tin Tin
    ORGANIZER:MAILTO:tin.tin@acme.com
    ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE;CN=;X-NUM-GUESTS=0:mailto:tin.tin@acme.com
    ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE;CN=;X-NUM-GUESTS=0:mailto:tin.tin@acme.com
    LOCATION:Conference Room
    DTSTAMP:20111229T172652Z
    UID:D26B0632-8496-4E76-977F-E7A04AF4CF4D
    **SEQUENCE:2**
    URL;VALUE=URI:http://acme/Lists/Conf/DispForm.aspx?ID=1178
    DTSTART;TZID=tz:20111229T150000
    DTEND;TZID=tz:20111229T160000
    RRULE:FREQ=WEEKLY;INTERVAL=1;BYDAY=TH;WKST=SU
    END:VEVENT
END:VCALENDAR


text:
Q: Two trains at the speed of light Okay. Two trains travelling towards each other at the speed of light. So, from one train (let's call it train A), the other is moving towards it at the speed of light. The other train shines a torch. They are both moving at the same speed so they both reach train A at the same time.
From train B (the other train), A is moving towards it at the speed of light. It shines the torch, and the torch is moving faster than the train itself (since the train is stationary from it's own frame of reference). So the light should hit train A before train B does.
Obviously both of these scenarios cannot be true, so what happens from each frame of reference?

A: As dmckee comments, this questions is 'wrong' since the massive trains can't go at the speed of light.
But we can modify the question a bit to say that our 'trains' are massless.  And for simplicity, let's make these 'trains' massless point-particles A and B.
According to relativity, the plane of simultaneous events of train A is light-like, and also contains A's world-line.  Therefore, the event of shining the torchlight (emission of a massless photon), the collision of the light with B, and the collision of A and B are all simultaneous, in A's reference (which we can't boost into in the first place)
But non-trivial dynamical systems must carry a mass so this question is plainly absurd.


text:
Q: Netbeans/Java: reference a jar but not deploy it I want to build a jar containing a class which I have derived from a class in second jar. I add a reference to the second jar in my project but then Netbeans copies that jar to dist/lib which I don't really want. Is there a way to reference the second jar at compile time but not have it copied.
Specifically, I am making a custom task for Ant so I derive from org.apache.tools.ant.Task and I don't want ant.jar copied to dist/lib.
This is with Netbeans 7.0.

A: One way of achieving this is to 'Uncheck' the Copy Dependent Libraries check box, which will ensure that no JAR files are copied to dist folder.
Exact Steps:

*

*Right click on the project name and choose Properties option from the context menu, this will open the Project Properties dialog box.

*Select the Build > Packaging node from the Categories tree view and uncheck the Copy Dependent Libraries check box

*Now build the project and check that no JAR files for libraries are copied to dist folder.


text:
Q: How to phrase it if users participate less than the threshold vs equal to and higher than the threshold I have the following sentences and not sure if one of them is better than the others. So, there is a threshold for user participation. If user participation is less than the threshold then I call it they under-participate. I believe this is fine.
However, users can also just do the threshold or more. This is the part with which I have problems phrasing. Any of the followings is acceptable and conveys the meaning that I meant to:

... users who are likely to under-participate and users who are likely to participate as required or more
... users who are likely to under-participate and users who are likely to participate as required or go beyond/exceed the expectations
... users who are likely to under-participate and users who are likely to participate sufficiently as required for the worst case.

UPDATE: FURTHER DETAILS
Let's say users are supposed to post 3 replies in a discussion forum. However, some of them had less than 3 replies whereas others have posted at least 3 replies. Here is a more generic template:

... aims to identify users-with-less-than-3-replies versus users-with-3-or-more-replies.

So, the users belong to either group. First group under-participates. But, I am having trouble finding a phrase to concisely indicate the second group. For example, over-participate would not work since participation at threshold level is also fine actually. Also, it has negative connotations.

A: Instead of over-perform...

Outperform
[out-per-fawrm]
verb (used with object)

*

*to surpass in excellence of performance; do better than.

Source: Dictionary.com


text:
Q: onclick any input or textarea except one do something There are many input fields and textarea fields in my page.The task is if someone click's on anyone of those except one with id "xyz" event should fire but only first time(click).After first click if the user clicks in anyone of those input,textboxes event should not fire.
$("input[type=button], textarea").not("#xyz"){

//Event shout fire but only on first click
}

A: You can use easy condition for this.
let shouldFire = true;
$("input[type=button], textarea").not("#xyz"){
 if(!shouldFire) return;
 shouldFire = false;

// Code to be executed just once
}

A: Try using $(selector).one(event,callback):
$("input[type=button], textarea").not("#xyz").one("click", function(){
  //Event shout fire but only on first click
});


text:
Q: Django - There is a way to get the current database alias? I'm working in a django project with multiple databases and I'm searching a way to get the current database alias using an import or method.
I've been searching in the documentation, but I haven't find any useful information.

A: There is not exactly such thing as 'current' db alias in Django.
Have a look at the docs for db routers to understand why:
https://docs.djangoproject.com/en/1.8/topics/db/multi-db/#database-routers
(though @fasouto does correctly show 'current' alias, in context of a read operation on a particular model, by using private API of QuerySet)
try this:
from django.db import router

alias_for_read = router.db_for_read(MyModelClass)
# optionally:
alias_for_read = router.db_for_read(MyModelClass, instance=my_model_instance)

# similarly:
alias_for_write = router.db_for_write(MyModelClass)
alias_for_write = router.db_for_write(MyModelClass, instance=my_model_instance)

Regarding the instance parameter... spec for db router classes says that they should accept **hints kwargs. They also state that only supported hint currently is instance. But unless you have a custom router class that makes use of this hint you will not need to supply the current instance.

A: If you have a QuerySet you can retrieve the db name using the db property:
>>> f = Item.objects.all()
>>> f.db
'default'

If you have the model instance (you evaluated the QuerySet), you can query the ModelState (Note that this is not documented, so it could change in the future and not recommended to use in apps as @Weier said):
>>> f = Item.objects.all()[4]
>>> f._state.db
'default'


text:
Q: characteristic polynomial of a matrix which is "nearly" diagonal Is there an easy way to compute the characteristic polynomial of a matrix which is "nearly" diagonal? Example:
$$
\begin{pmatrix}0 & 0& 0& 1 & 0 & 0 & 0 & 0 & 0 & 0\\
0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\
0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0\\
0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0\\
0 &0 & 0& 0 & 0 & 1 & 0 & 0 & 0 & 0\\
0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0\\
0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 & 0\\
0& 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 & 1\\
1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\
0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0\end{pmatrix}
$$
it is "nearly" diagonal. If the both entries in the left lower corner would be 0, I just could compute the eigenvalues to be $0$ by
$$
det(A-\lambda I)=(-\lambda)^{10} =0
$$


text:
Q: Optimization of a sql-query with exists I have a table:
+----+---------+-----------+--------------+-----------+
| id | item_id | attr_name | string_value | int_value |
+----+---------+-----------+--------------+-----------+
|  1 |       1 |         1 | prop_str_1   | NULL      |
|  2 |       1 |         2 | prop_str_2   | NULL      |
|  3 |       1 |         3 | NULL         | 2         |
|  4 |       2 |         1 | prop_str_1   | NULL      |
|  5 |       2 |         2 | prop_str_3   | NULL      |
|  6 |       2 |         3 | NULL         | 2         |
|  7 |       3 |         1 | prop_str_4   | NULL      |
|  8 |       3 |         2 | prop_str_2   | NULL      |
|  9 |       3 |         3 | NULL         | 1         |
+----+---------+-----------+--------------+-----------+

And I want to select item_id with specific values for the attributes. But this is complicated by the fact that the fetching needs to do on several attributes. I've got to do it just using exists:
select *
  from item_attribute as attr
  where (name = 1 and string_value = 'prop_str_1')
  and exists
  (select item_id
  from item_attribute
  where item_id = attr.item_id and name = 2 and string_value = 'prop_str_2')

But the number of attributes can be increased, and therefore nested queries with exists will increase.
How can I rewrite this query to reduce the nested queries?
UPD:
create table item_attribute(
    id int not null,
    item_id int not null,
    attr_name int not null,
    string_value varchar(50),
    int_value int,
    primary key (id)
);

insert into item_attribute values (1, 1, 1, 'prop_str_1', NULL);
insert into item_attribute values (2, 1, 2, 'prop_str_2', NULL);
insert into item_attribute values (3, 1, 3, NULL, 2);
insert into item_attribute values (4, 2, 1, 'prop_str_1', NULL);
insert into item_attribute values (5, 2, 2, 'prop_str_3', NULL);
insert into item_attribute values (6, 2, 3, NULL, 2);
insert into item_attribute values (7, 3, 1, 'prop_str_4', NULL);
insert into item_attribute values (8, 3, 2, 'prop_str_2', NULL);
insert into item_attribute values (9, 3, 3, NULL, 1);

A: See if this works for you.  It in essence does the same thing... Your first qualifier is that a given attribute name = 1 and string = 'prop_str_1', but then self-joins to attribute table again on same ID but second attribute and string
select
      attr.*
   from
      item_attribute attr
         JOIN item_attribute attr2
            ON attr.item_id = attr2.item_id
            and attr2.name = 2
            and attr2.string_value = 'prop_str_2'
   where
          attr.name = 1
      and string_value = 'prop_str_1'

I would also have an index on your table on (name, string_value, item_id) to increase performance of where and join conditions.


text:
Q: Share pass store between two computers I recently switched to pass as password manager and I am very happy with it, but I would like to share the passwords between two machines (work and home). I duckduckgo-ed how to do it properly, But couldn't find any solutions. Am I particularly dumb, or is there a way to easily do this?
Best,
/E

A: I use LastPass (free version) which I can use on any device and my passwords are automatically synced across them including my mobile phone - handy for logins to online banking apps for example. The master password to access LastPass is extremely strong.
See this reference which explains how LastPass works and its benefits in the circumstances you describe.
What's included in LastPass Free?

*

*Access on all supported devices

*One-to-one password sharing

*An encrypted Vault to store and manage your site passwords, secure notes, and form fill items

*Save and fill site passwords

*Storage with secure notes

*Easy web form filling

*Secure password generator

*Extra security with Multifactor Authentication, including the use of the LastPass Authenticator

*Password auditing using the Security Challenge

If you don't already have a LastPass account, you can get started by signing up for a free trial here Once your free trial expires, your account will automatically convert to a LastPass Free account.

A: I guess you want it to be synced right?
you can connect a cloud space(Next-cloud for example) to your file browser and keep your "pass file" in there so you can access it from work and home and it will be synced.
how to add online accounts
Browse files on a server or network share


text:
Q: Add event and reminder not working in 6.0 marshmallow I am facing on weird issue.
I am trying to add events in calendar and also reminder. It's working fine in all devices except the one having Marshmallow - 6.0
When i try to add events, it also returns me event id here. And even though i am getting event id here, I can not see events added in my calendar
   ContentValues event = new ContentValues();
        event.put("calendar_id", 1);
        event.put("title", "Match");
        event.put("description",PTGConstantMethod.validateString(match.getMatch_name()));
        event.put("eventLocation", match.getVenue());
        event.put("eventTimezone", TimeZone.getDefault().getID());
        event.put("dtstart", startDate.getTime());
        event.put("dtend", endDate);

        event.put("allDay", 0); // 0 for false, 1 for true
        event.put("eventStatus", 1);
        event.put("hasAlarm", 1); // 0 for false, 1 for true

        Uri eventUri = context.getApplicationContext()
                .getContentResolver()
                .insert(Events.CONTENT_URI, event);
        long eventID = Long.parseLong(eventUri.getLastPathSegment());

I am adding reminder here,
        ContentValues reminders = new ContentValues();
            reminders.put("event_id", eventID);
            reminders.put("method", CalendarContract.Reminders.METHOD_ALERT);
            reminders.put("minutes", minutes);

            context.getApplicationContext().getContentResolver()
                    .insert(Reminders.CONTENT_URI, reminders);

But app crashes while adding reminder. Here are my logs.

android.database.sqlite.SQLiteException
  at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:179)
  at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:135)
  at android.content.ContentProviderProxy.insert(ContentProviderNative.java:476)
  at android.content.ContentResolver.insert(ContentResolver.java:1231)

In my build.gradle
  minSdkVersion 14
  targetSdkVersion 22

I finally found that there isn't any calendar with    event.put("calendar_id", 1);. So how could i get app default calendar?
I tried by adding new calendar and add events to that.
        ContentValues calendar = new ContentValues();
    calendar.put(CalendarContract.Calendars.NAME, context.getResources().getString(R.string.app_name));
    calendar.put(CalendarContract.Calendars.CALENDAR_DISPLAY_NAME, context.getResources().getString(R.string.app_name)+" Calendar");
    calendar.put(CalendarContract.Calendars.VISIBLE, true);

    Uri uri = context.getApplicationContext()
            .getContentResolver()
            .insert(CalendarContract.Calendars.CONTENT_URI, calendar);
    long calendarId = Long.parseLong(uri.getLastPathSegment());

But i am not able to see this calendar in my calendar app. When i try to add events using this new calendar. Events get display but on click of event, my default calendar app gets crashed. What i am doing wrong while adding new calendar to default calendar app? Thanks.

A: Sorry for posting answer in such a way,but what I found while adding event manually in Android M calendar, it says that we need to add account to calendar account in order to add events. So I am guessing that unless and until we do not add or map a calendar to at least one account, we cannot add events manually or programmatically to Android M device calendar.

A: Try below link:
How to add multiple event to android marshmallow Calendar?

A: Maybe you want to use inside Fragment.
At first use:
super.requestPermissions( new String[]{Manifest.permission.WRITE_CALENDAR}, MY_PERMISSIONS_REQUEST_WRITE_CALENDAR);

Inside fragment, you need to call:
FragmentCompat.requestPermissions(permissionsList, RequestCode)

Note:
ActivityCompat.requestPermissions(Activity, permissionsList, RequestCode);

add this library in gradle for FragmentCompat class .
compile 'com.android.support:support-v13:version_of_library'


text:
Q: .isAfter return even false I'm using momentjs with Eonasdan plugin and I'm trying to check if the end date is less than the start date, for doing this I'm using the method isAfter:
var start = moment($('#start-datetime').val());
var end = moment($('#end-datetime').val());
console.log((start).isAfter(end));

this will return even false, the values are so defined:

*

*start: 07/02/2019 19:58

*end: 31/01/2019 19:58

A: Try passing a specific format string and locale to moment to make sure the string is parsed correctly:
moment(..., "DD/MM/YYYY HH:mm", "en");

or
moment.locale("en");
...
moment(..., "DD/MM/YYYY HH:mm");

Demonstration:

moment.locale("en");
$("#test-button").click(function() {
  var start = moment($('#start-datetime').val(), "DD/MM/YYYY HH:mm");
  var end = moment($('#end-datetime').val(), "DD/MM/YYYY HH:mm");
  console.log((start).isAfter(end));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>
<input id="start-datetime" type="text" value="07/02/2019 19:58">
<input id="end-datetime" type="text" value="31/01/2019 19:58">
<button id="test-button">Test</button>


text:
Q: What are the risks of using an outdated Ubuntu version? Can anyone tell my of risks using an older version of Ubuntu (10.04) might have? I'm a simple user who uses a PC for web-surfing, Libreoffice and entertainment (watching movies, music, etc.).
P.S.: I'm already aware of lightweight distros and other desktops, but what I'm looking for is an older kernel which can support my old (unsupported) hardware.
P.S. II: While back in Windows, I was using XP and 7 with no antivirus for the same purposes. Is using older versions of Ubuntu riskier than that?
UPDATE: By risk I mean security risks like bugs, known issues or maybe become a victim of hackers and personal information get stolen! Things like these.

A: If you're offline, the risks are non-existent (though if you are using files transferred via usb-thumb-drive etc. they are no longer nill, but are still small).
I wouldn't browse the web from such a machine, and likely restrict it to a unique VLAN on the local network, as it's possible (you provided no details) some programs if they use network data, may cause increased risk to other machines on your network (the machine will be easier prey for attack, esp. targeted attacks).
You weren't specific to what use you intend for the machine, I've already mentioned I'd restrict it to it's own VLAN and not let other machines on my local network speak to it. I'd also look up what programs I was to use, and look for flaws that were detected in that software, but were never patched for your EOL system.  These checks (or homework) are time-consuming, and are part of why updating to supported software is easier & safer.
Many privacy attacks on browsers are specific to a browser, eg. if it targets chrome (or firefox), it'll impact users regardless of OS (so windows, mac & GNU/Linux users almost equally).  In these cases; using an older browser would increase the security risk in my opinion, unless using a atypical browser such as lynx that doesn't run any scripts usually used for such attacks (thus having a smaller attack risk).
You mention 10.04, which reached EOL on 2015-April-30 for servers, and 2013-May-9 for desktops (https://fridge.ubuntu.com/2015/04/30/ubuntu-10-04-lucid-lynx-end-of-life-reached-on-april-30-2015/ https://wiki.ubuntu.com/Releases) so that's a lot of potential security risks that you are un-patched for, and a lot of homework to ensure your system is safe.
If you were talking about say Lubuntu 16.04 LTS, where the desktop itself has been EOL since 2019-April, but the Ubuntu base still gets security patches, my concern would be lower, also the amount of homework I'd need to do to assess the risks is far less and I may consider it (I'd still treat the box with concern & be careful what I did on it; but I'm somewhat careful anyway, having multiple boxes I do things specific things on).
(Ubuntu 16.04 LTS can have extended security when it reaches EOL in 2019-April through the use of ESM which can involve paid subscriptions but is also available free of $cost. It doesn't include all packages, but is still of far lower security risk than say 10.04 LTS)
The risks will vary on your use-case, packages installed, protocols those packages use (using network traffic) plus what system you installed and what was detected since security maintenance ceased. Yes this can be assessed (the homework), but as time is often more expensive than hardware, is it worth it?

A: Security-wise, if all you do is web-surfing, Libreoffice and entertainment, and not running a server or anything, and you use it at home and not connected to public network all the time, there is very low risk of being hacked even without the security updates. Ubuntu systems are hardly ever targeted anyway. Just be smart when surfing the web. More importantly are the linux drivers, some of which might be proprietary. You might be missing some drivers for the latest hardware or peripherals but it shouldn't matter to you if you're just browsing the web all day. Even if you need them, you can just manually install them without upgrading the entire ubuntu version. Long story short, if you have constraints and do not want to upgrade ubuntu there are no significant risks.

A: as others have mentioned, we'll need to be rather generic in our responses without more information. But let's consider it to be a random desktop tower with a common intel CPU, a generic NVIDIA 304 driver as you had mentioned, and Ubuntu 16.10 or older.
I'm not going to bother inferring your use case, instead a more direct approach is to provide tools that can be used under any scenario- vulnerabilities and exploits lists! Every operating system will inevitably have software that will one day reveal a security vulnerability and perhaps someone will create an exploit for that vulnerability to truly take advantage of it, however the rate of these compromises is measured loosely by a number of websites through reporting. One such website, aptly named cvedetails.com https://www.cvedetails.com/index.php has been reliable for me in the past as a systems administrator.
Not all software is likely to have vulnerabilities or exploits, for example, the likelihood of a basic text editor or music player having the ability to let someone remotely access your system and gain increased privileges (access to root) or prevent you from using the computer (denial of service).
But let's put that last thought to the test, are the vulnerabilities for xed or Rhythmbox? According to CVE details, there are for Rhythmbox, but only in 2009 and 2012 as far as we know! Xed, on the other hand, doesn't even show up! So what about something like Ubuntu? Well, fortunately you don't need to search for every single available software under Ubuntu, you only need to look at two things:

*

*Ubuntu (Products and Vulnerabilities OR; Ubuntu Version, e.g. Ubuntu 16.04)

*Debian! Because it's the base/root and it maintains much of the software that Ubuntu uses.

Looking upstream is always important, even if your upstream is ahead or behind the downstream in version. For example, Debian is often behind Ubuntu in updates because that's simply how the project is run for stability- and yet because they're still the primary maintainers, you can clearly see that they have way more operating system specific vulnerabilities.
Something to note, the Ubuntu vulnerabilities and exploits page does not include anything from custom PPA's except for the built in system used to install PPAs.
Moving away from focussing on the user software, your old intel processor may have a number of vulnerabilities associated with it too. For example, Spectre has affected a number of operating systems and all the specified references for Spectre can be found in the link to cvedetails- but in future you can always use a search engine like Google to search "site:cvedetails product exploitname" if you don't know the specified CVE number. Newer operating systems, or operating systems that have received security updates, will have patched something like Spectre, so if you're out of security updates and you think that you may later be at risk of running exploit code for that vulnerability, then perhaps you should update.
If anyone has any questions, please let me know, happy to help!


text:
Q: append formData multiple files and other inputs - php processing I have multiple forms generated dynamically.
I need to build the formData for multiple files as well as a couple of extra hidden inputs.
This is what I have tried so far:
$(document).on('click', '.upload-btn', function(e){
    e.preventDefault();

    var formData = new FormData($(this).parents('form')[0]);

    $.ajax({
        method: "POST",
        url: "upload.php",
        dataType: 'text',
        cache: false,
        contentType: false,
        processData: false,
        data: formData,

        beforeSend: function(){
        ...
        },
        success: function(){
        ...
        }
    });
});

Oddly enough, this works somehow, and the files do get uploaded to the server, I can perform all sorts of operations on the temp files but...
the files are never a part of the $_POST array if I var_dump $_POST the files are not in there.
Is there a better way to build the formData? am I missing something on the php side when I'm testing for isset($_POST['file[]'])
Any help is greatly appreciated.

A: Use php's files array.  print_r($_FILES);
Doing the above print,  you'll be able to access every file sent from your form. This includes keys, tmp_name etc


text:
Q: Why is the (memoized) child component re-rendering? I have two React functional components: C1 and C2. C2 is nested inside C1:
const C2 = () => {
  console.log("C2 Render");
  return (

I am Component 2

  );
};

const C1 = () => {
  const [text, setText] = useState("Hello");
  const MC2 = React.memo(C2, () => true);

  return (

The Button

      <button
        onClick={() => {
          setText(`${text} b`);
        }}
        className="button">
          Click me
       </button>

        {text}

      <MC2 />

  );
}

CodePen here.
The problem
I know that a component gets re-rendered under different situations. Among those is the one when the parent re-renders.
That is why I am using a memoized component around C2. But still I can see the console displaying "C2 Render" every time I click the button.
Why?

A: C1 rerender because of state chnage, so your memoized component is redeclared every time.
just wrap C2 in a React.memo() & you would not see the rerenders
const MC2 = React.memo(() => {
  console.log("C2 Render");
  return (

I am Component 2

  );
}, () => true);

or if you want to memoize only one useCase put it outside the C1 component and have that component memoized:
const C2 = () => {
  console.log("C2 Render");
  return (

I am Component 2

  );
};

const MC2 = React.memo(C2, () => true);

& used it like this:
const C1 = () => {
  const [text, setText] = useState("Hello");

  return (

The Button

      <button
        onClick={() => {
          setText(`${text} b`);
        }}
        className="button">
          Click me
       </button>

        {text}

      <MC2 />

  );
}