text:
Q: Boiling water at low pressure with heat supply I understand that water boils at lower temperatures at lower pressures, but I want to know what happens when external heat is supplied to a body of water at low pressure. Suppose I have a hot object in an enclosed chamber. I then cover the hot object with water, then vacuum the air out so the pressure drops. I know that with out the help of any additional heat the water can boil at low temperature because i have dropped the pressure, but what happens when I introduce the hot object? Does the water boil even faster because of the exchange of heat between the water and the hot object? What is the boiling point of the water at low pressure and the help of additional heat VS. the boiling point at just vacuum pressure?

A: Added heat doesn't change the boiling point, it just makes the water reach it faster. Once it has reached boiling point, the rate of boiling also increases with an increased heat source. Without the hot object, heat is extracted from the remaining liquid body by the vapour that leaves it (enthalphy of vaporization) during boiling, in effect causing evaporative cooling to the rest of the water. This will cause the water to drop below the boiling point eventually unless air pressure is further lowered, or the water is allowed time to absorb heat and warm up (essentially using the environment as an added heat source for boiling). Having a hot object accelerates the process.


text:
Q: celda de TABLA excel con lista desplegable no muestra flecha indicadora Tengo lista de datos con A1 a1 D1 encabezados. quiero cargar datos a partir de fila 2, con lista desplegable en columna A, el origen de la lista está en otro rango, funciona todo perfecto.
Ahora bien, cuando transformo la lista de datos en tabla excel 2013, me valida el ingreso pero no me muestra la flecha de la lista para elegir opciones.
Les agradeceré me orienten como proceder para tener una tabla excel y un ingreso de datos validados, que se vea la lista desplegable dentro de la celda de la tabla
Muchas gracias

A: No sé si puede audarte, pero acabo de probar con el Excel 2019 y he podido crear una tabla con las celdas en la columna A con validaciones. Te dejo na imagen de como me ha quedado:

A lo mejor es cuestión de versiones porque la verdad que con el 2019 no he tenido ningún problema en hacerlo.
Espero te sirva. Un saludo.

A: Al configurar la validación, es necesario indicar que las celdas deben tener lista desplegable.
Puedes editar la validación seleccionado cualquiera de las celdas del rango que ya tienen la validación, luego en la ficha datos da click en "Validación de datos" y activa la casilla "Celda con lista desplegable", click en aceptar.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to create regex for retrieving HTML code in Java? Piece of html code :

so i use regex to get link from code :
String pat = "<a\\s+class=\"context_link\"\\s+href=\"(.+)\"";
   Pattern pattern = Pattern.compile(pat,Pattern.DOTALL | Pattern.UNIX_LINES);
   Matcher math = pattern.matcher(source);
   while(math.find()){Log.i("Value",math.group(1));}

When i check is match or not, result always is false.
Who can help me fix error it ?

A: If you're trying to extract HREF then you should use Jsoup library
Jsoup
Now working example:
import java.io.IOException;

import org.jsoup.Jsoup;

public class Test {

    public static void main(String args[]) throws IOException {

        String source = "        ";
        String link = Jsoup.parse(source).select("a").first().attr("href");
        System.out.println("Your link  :" + link);

    }

}


text:
Q: Flow type failures in Reducer? I am pretty sure I am following the instructions correctly on how to type my actions and reducers:
ActionTypes.js
// @flow
import type Product from "../../models/Product";

type ActionNamesObject = {
  [key: string]: { [key: string]: { [key: string]: string } }
};

export const Actions: ActionNamesObject = {
  Product: {
    Fetch: {
      start: "PRODUCT_FETCH_START",
      success: "PRODUCT_FETCH_SUCCESS"
    }
  }
};

export type ProductAction =
  | { type: "PRODUCT_FETCH_START" }
  | {
      type: "PRODUCT_FETCH_SUCCESS",
      products: Product[]
    };

reducer
// @flow
import type Product from "../../models/Product";
import type { ProductAction } from "../actions/ActionTypes";
import { Actions } from "../actions/ActionTypes";

type ProductState = {
  +products: Product[]
};

const initialState = {
  products: []
};

export default function productsReducer(
  state: ProductState = initialState,
  action: ProductAction .   // LINE 16
): ProductState {
  switch (action.type) {
    case Actions.Product.Fetch.success:
      return { ...state, products: action.products };   // ERROR HERE
    default:
      (action: empty);   // ERROR HERE
      return state;
  }
}

But I'm getting flow errors where I've marked them in the reducer file.
The first error is on products: Cannot get action.products because property products is missing in object type. Referring to line 16.
The second error is on action: Cannot cast action to empty because object type is incompatible with empty. Also referring to line 16.
What am I missing?

A: Your ProductActionType is returning two possible shapes and one doesn't have products
I'm not super familiar with typescript but I think you want something more like:
export type ProductAction = {
    type: "PRODUCT_FETCH_START" | "PRODUCT_FETCH_SUCCESS"
    products: Product[]
}

I'm not sure if that second line of code that is failing is even necessary.


text:
Q: How do i use SharePoint Client Object Model and PowerShell to upload documents to libraries? I've tried converting these code snippets to PowerShell:
ClientContext context = new ClientContext("http://spdevinwin");
   2:
   3: Web web = context.Web;
   4:
   5: FileCreationInformation newFile = new FileCreationInformation();
   6: newFile.Content = System.IO.File.ReadAllBytes(@"C:\Work\Files\17580_FAST2010_S05_Administration.pptx");
   7: newFile.Url = "17580_FAST2010_S05_Administration 4MB file uploaded via client OM.pptx";
   8:
   9: List docs = web.Lists.GetByTitle("Documents");
  10: Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(newFile);
  11: context.Load(uploadFile);
  12: context.ExecuteQuery();
  13: Console.WriteLine("done");

and:
// FileInfo in System.IO namespace
var fileCreationInformation = new FileCreationInformation();

byte[] bytefile = System.IO.File.ReadAllBytes("c:\\test\Test2.txt");
fileCreationInformation.Content = bytefile;
fileCreationInformation.Overwrite = true;
fileCreationInformation.Url = "http://astro/MyLibrary/MyFolder/Test2.txt";

// CurrentList is a client OM List object
CurrentList.RootFolder.Files.Add(fileCreationInformation);
Context.ExecuteQuery();

But I get errors on the Update() and Add($file) methods

A: Rather than using the Client Object Model, the accepted way to upload files to SharePoint with PowerShell is to use the SharePoint PowerShell Cmdlts. You can use something similar to the following code:
Add-PSSnapin Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue

$Library = "My Library"
$siteurl = "http://MyWebApp/sites/SiteName"
$FilePath = "C:\Test\test2.txt"

# Get Web site
$Web = Get-SPWeb $SiteUrl

# Get Library
$docLibrary = $web.Lists[$Library]
$folder = $docLibrary.RootFolder

# Get the file
$File = Get-ChildItem $FilePath

# Build the destination SharePoint path
$SPFilePath = ($folder.URL + "/" + $File.Name)

$spFile = $folder.Files.Add($SPFilePath, $File.OpenRead(), $true)  #Upload with overwrite = $true (SP file path, File stream, Overwrite?)

For a reusable function that you can use to upload files, overwrite, approve, and check in, use the cmdlet that I created here:
http://pastebin.com/Tvb4LfZV

A: You'll only be able to use the SharePoint PowerShell cmdlets if you are running on the server.  They don't work remotely, especially for SharePoint Online.
You didn't include all of your PowerShell code but I'll guess you weren't calling ClientContext.Load and ClientContext.ExecuteQuery after each step of getting the list and loading the file to the server.
Reference for using many PowerShell CSOM scenarios


text:
Q: Mass SNMP updates? Is there an easy way to update over 1000 Windows hosts with an additional permitted manager? I have tools to remotely run scripts on hosts, but it is a little bit difficult to filter out specific hosts, and you end up having to type each hostname into the program then add it to a list of hosts to run the script on. I have scripts that will update permitted managers, and other SNMP settings in the registry; but I need a better way to run the script on multiple hosts. Does anyone know of an easy way to do this?

A: Why don't you just put the list of servers in a text file and delete the ones that you don't want it to run on. Then just use psexec's @file feature to feed the list of servers to psexec. It will then iterate through the list of servers, running the specified command(s) on each.
Or, even better, put all of the machines in an AD security group and use Group Policy Preferences Registry Settings to push the change out to the servers. You can use Item Level Targeting to apply it only to servers in the specified security group. When new servers get spun up, just make including them in this group part of the provisioning process.


text:
Q: Using Hugging Face Transformers library how can you POS_TAG French text I am trying to POS_TAG French using the Hugging Face Transformers library. In English I was able to do so given a sentence like e.g:

The weather is really great. So let us go for a walk.

the result is:
    token   feature
0   The     DET
1   weather NOUN
2   is      AUX
3   really  ADV
4   great   ADJ
5   .       PUNCT
6   So      ADV
7   let     VERB
8   us      PRON
9   go      VERB
10  for     ADP
11  a       DET
12  walk    NOUN
13  .       PUNCT

Does anyone have an idea how a similar thing could be achieved for French?
This is the code I used for the English version in a Jupyter notebook:
!git clone https://github.com/bhoov/spacyface.git
!python -m spacy download en_core_web_sm

from transformers import pipeline
import numpy as np
import pandas as pd

nlp = pipeline('feature-extraction')
sequence = "The weather is really great. So let us go for a walk."
result = nlp(sequence)
# Just displays the size of the embeddings. The sequence
# In this case there are 16 tokens and the embedding size is 768
np.array(result).shape

import sys
sys.path.append('spacyface')

from spacyface.aligner import BertAligner

alnr = BertAligner.from_pretrained("bert-base-cased")
tokens = alnr.meta_tokenize(sequence)
token_data = [{'token': tok.token, 'feature': tok.pos} for tok in tokens]
pd.DataFrame(token_data)

The output of this notebook is above.

A: We have ended up training a model for POS Tagging (part of speech tagging) with the Hugging Face Transformers library. The resulting model is available here:
https://huggingface.co/gilf/french-postag-model?text=En+Turquie%2C+Recep+Tayyip+Erdogan+ordonne+la+reconversion+de+Sainte-Sophie+en+mosqu%C3%A9e
You can basically see how it assigns POS tags on the webpage mentioned above. If you have the Hugging Face Transformers library installed you can try it out in a Jupyter notebook with this code:
from transformers import AutoTokenizer, AutoModelForTokenClassification
from transformers import pipeline

tokenizer = AutoTokenizer.from_pretrained("gilf/french-postag-model")
model = AutoModelForTokenClassification.from_pretrained("gilf/french-postag-model")

nlp_token_class = pipeline('ner', model=model, tokenizer=tokenizer, grouped_entities=True)
nlp_token_class('En Turquie, Recep Tayyip Erdogan ordonne la reconversion de Sainte-Sophie en mosquée')

This is the result on the console:
[{'entity_group': 'PONCT', 'score': 0.11994100362062454, 'word': '[CLS]'},
{'entity_group': 'P', 'score': 0.9999570250511169, 'word': 'En'},
{'entity_group': 'NPP', 'score': 0.9998692870140076, 'word': 'Turquie'},
{'entity_group': 'PONCT', 'score': 0.9999769330024719, 'word': ','},
{'entity_group': 'NPP',   'score': 0.9996993020176888,  'word': 'Recep Tayyip Erdogan'},
{'entity_group': 'V', 'score': 0.9997997283935547, 'word': 'ordonne'},
{'entity_group': 'DET', 'score': 0.9999586343765259, 'word': 'la'},
{'entity_group': 'NC', 'score': 0.9999251365661621, 'word': 'reconversion'},
{'entity_group': 'P', 'score': 0.9999709129333496, 'word': 'de'},
{'entity_group': 'NPP', 'score': 0.9985082149505615, 'word': 'Sainte'},
{'entity_group': 'PONCT', 'score': 0.9999614357948303, 'word': '-'},
{'entity_group': 'NPP', 'score': 0.9461128115653992, 'word': 'Sophie'},
{'entity_group': 'P', 'score': 0.9999079704284668, 'word': 'en'},
{'entity_group': 'NC', 'score': 0.8998225331306458, 'word': 'mosquée [SEP]'}]


text:
Q: MySQL function does not return correct result The function below always returns ELSE value (which is 6) even if the SELECT query itself returns value 30.00 for example. In that case, the function should return number 4. Can anyone help me please?
DELIMITER $$
CREATE FUNCTION znamka(id_testu INT, id_studenta INT)
    RETURNS TINYINT
BEGIN
    DECLARE percenta FLOAT;
    SET percenta=
    (
        SELECT ROUND(tv.pocet_bodov/t.max_body*100, 2)
        FROM test t JOIN test_vysledky tv ON (tv.fk_test=t.id_test)
        WHERE tv.fk_test=id_testu AND tv.fk_student=id_studenta
    );
    RETURN CASE
        WHEN percenta>=90 THEN 1
        WHEN percenta<90 >=75 THEN 2
        WHEN percenta<75 >=50 THEN 3
        WHEN percenta<50 >=30 THEN 4
        WHEN percenta<30 THEN 5
        ELSE 6
    END;
END;
$$
DELIMITER ;

A: Change your CASE statement to this:
RETURN CASE
    WHEN percenta >= 90 THEN 1
    WHEN (percenta < 90 AND percenta >=75) THEN 2
    WHEN (percenta < 75 AND percenta >=50) THEN 3
    WHEN (percenta < 50 AND percenta >=30) THEN 4
    WHEN percenta < 30 THEN 5
    ELSE 6
END;

Comments:
As @Drew mentioned in his comment, you will never hit your ELSE condition.  In addition, I'm surprised that MySQL was executing this function at all without any error.

A: What's the datatype of those pocet_bodov and max_body columns? If it's INT you might get a truncated result. Try multiplication first:
SELECT ROUND(100*tv.pocet_bodov/t.max_body, 2)

Edit: Previous can't cause a problem in MySQL because it's not doing INTEGER calculation.
The SQL CASE statement is not the same as a C SWITCH; it stops at the first matching condition, there is no need to use BETWEEN:
RETURN CASE
    WHEN percenta >= 90 THEN 1
    WHEN percenta >=75) THEN 2
    WHEN percenta >=50) THEN 3
    WHEN percenta >=30) THEN 4
    WHEN percenta < 30 THEN 5
    ELSE 6 -- this will only be returned for NULLs
END;


text:
Q: Generate unique alpha-numeric object ID, like Parse I already asked what I needed at the title. I want to generate using either  PHP or javascript.
I think the class name and some properties are used to build the objectId but someone may already know how its done that could share here?

A: The Parse Server generates the objectId. It is a randomly generated String of 10 chars length. You can see their implementation at cryptoUtils.newObjectId(). From the code we can conclude that they are not enforcing uniqueness.
https://github.com/ParsePlatform/parse-server/blob/master/src/cryptoUtils.js

A: Parse is probably using ids generated in Mongodb. They are not random and can be potentially predicted :

A BSON ObjectID is a 12-byte value
  consisting of a 4-byte timestamp
  (seconds since epoch), a 3-byte
  machine id, a 2-byte process id, and a
  3-byte counter

http://www.mongodb.org/display/DOCS/Object+IDs


text:
Q: Linking mysql tables i'm fairly new to mysql/php and i', trying to grab data from 2 tables:

*

*organization_dep (id, orgid, depname )

*organization (id, orgname )

what I am trying to do is link the tables and echo the results so it comes as table with two columns: organization Name and organization Department Name
Thanks for any help!

A: The "JOIN" tag on your question is actually the right key word.
SELECT
    org.orgname,
    dep.depname
FROM
    organization_dep dep
    INNER JOIN organization org
        ON dep.orgid = org.id

Read more about joining tables in the MySQL Documentation.


text:
Q: How to debug a Chrome extension in WebStorm? I loaded a Chrome extension in Chrome using load unpacked in developer mode.
I know how to debug inside Devtools.
How does one develop and debug an extension using WebStorm where WebStorm's breakpoints in the extension's Javascript get hit?

A: No special support for debugging Chrome extensions is currently provided, see WEB-9708.
The IDE can attach a debugger to a running Chrome instance started with --remote-debugging-port option using Attach to Node.js\Chrome run configuration; see if it works for you


text:
Q: Export Power BI Report from SharePoint Online Power BI report can be exported from https://app.powerbi.com/ page using inbuilt Export feature.
I have a requirement to provide same functionality from within SharePoint Online page, where this report is embedded. Please let me know the steps.

A: You can use Export To File / Export To File In Group API.

*

*When the Export-To-File API is called, it triggers an export job.

*After triggering the export job, you can use the Polling API (Get Export To File Status / Get Export To File Status In Group) to track the job until it is complete.

*When the export job is complete, the Polling API call returns a Power BI URL for getting the file (the URL is available for 24 hours). You can also download it by calling Get File Of Export To File / Get File Of Export To File In Group API.
The API supports concurrent export job requests. The number of jobs you can run at the same time, depends on the SKU your report resides on, as detailed in this table (i.e. it requires a dedicated capacity - Power BI Premium or Power BI Embedded).
For example, here is how you can use the API with PowerShell code:
Import-Module MicrosoftPowerBIMgmt
$username = "account@example.com"
$password = "SuperStrongPassword" | ConvertTo-SecureString -asPlainText -Force
$groupId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
$reportId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
$format = "PDF" # or PNG, or PPTX. For paginated reports can be CSV, DOCX, IMAGE (i.e. page definition plus file format - BMP, EMF, etc.), MHTML, XLSX or XML
$saveToFolder = "D:\"

$credential = New-Object System.Management.Automation.PSCredential($username, $password)
Connect-PowerBIServiceAccount -Credential $credential
$settings = @{ includeHiddenPages = $false; locale = "en-us" }
$powerBIReportConfiguration = @{ settings = $settings }
$export_body = @{ format = $format; powerBIReportConfiguration = $powerBIReportConfiguration }
$export_response = Invoke-PowerBIRestMethod -Url "https://api.powerbi.com/v1.0/myorg/groups/$groupId/reports/$reportId/ExportTo" -Method Post -Body ($export_body | ConvertTo-Json)
$export_response_json = ConvertFrom-Json $export_response
$exportId = $export_response_json.id

Write-Output "Polling export status..."
$maxPollCount = 500
$exportSucceeded = $false
do
{
    $maxPollCount = $maxPollCount - 1
    Start-Sleep -Seconds 5
    $status_response = Invoke-PowerBIRestMethod -Url "https://api.powerbi.com/v1.0/myorg/groups/$groupId/reports/$reportId/exports/$exportId" -Method Get
    $status_response_json = ConvertFrom-Json $status_response
    $status = $status_response_json.status
    $percentComplete = $status_response_json.percentComplete
    Write-Output "Status: $status, percent complete: $percentComplete (retries left: $maxPollCount)"
    if ($status -eq "Succeeded")
    {
        $exportSucceeded = $true
        $resourceLocation = $status_response_json.resourceLocation
        $reportName = $status_response_json.reportName
        $resourceFileExtension = $status_response_json.resourceFileExtension
        $outFile = [IO.Path]::Combine($saveToFolder, $reportName + $resourceFileExtension)
    }
}
until($exportSucceeded -or $maxPollCount -le 0)

Write-Output "Downloading export..."
$download_response = Invoke-PowerBIRestMethod -Url $resourceLocation -Method Get -OutFile $outFile
Write-Output "Download completed."
Disconnect-PowerBIServiceAccount


text:
Q: Suppose that the maximum degree of a graph is less or equal to 2, then all components are path or cycles There is a claim on Pg. 109 of West's graph theory book

Let $F$ be the symmetric difference of two matchings $M, M'$, then,
"Suppose that the maximum degree of a $F$ is less or equal to 2, then
  all components are path or cycles"

How would one go about proving this claim? It seems intuitive that the only components obtainable from a graph with degree $\leq$2 is either a path or a cycle. How does one go about ruling out the other cases?

A: Let $G$ be a graph with maximum degree $2$, and take any maximal path $x_1, x_2, \dots, x_k$ in $G$. (By "maximal" I just mean that it cannot be extended from either endpoint.)
Then the interior vertices of that path $x_2, \dots, x_{k-1}$ already have degree $2$ just considering the edges used by the path. So they have no more edges out of them. The endpoints $x_1$ and $x_k$ don't have edges to any other vertices of $G$ (or the path wouldn't be maximal), so $\{x_1, x_2, \dots, x_k\}$ induce a connected component of $G$.
This connected component cannot have any edges $(x_i, x_j)$ with $1 < i < k$ or $j < i < k$, beyond what's already in the path, since that would boost the degree of $x_i$ or $x_j$ to 3. This rules out all but one potential edge: the edge $(x_1, x_k)$. If it is present, then the connected component induced by $\{x_1, x_2, \dots, x_k\}$ is a cycle; if it is absent, then the connected component is a path.


text:
Q: DSTAT output scrambled on Ubuntu 20.04 LTS using macOS Monterey terminal The problem
When I logon to a machine running Ubuntu 20.04 LTS and run 'dstat' I get this kind of output:
garbled dstat output
So regular dstat output is ok, but as soon as you enter 'dstat ' things go wrong. Instead of updating the line in-place, the screen gets shuffled.
What I have tried

*

*Using a different mac running Monterey resulted in the same problem

*Using a different terminal app iTerm solved the problem*

*running dstat under screen or tmux solved the problem*

*starting a screen on macos and then ssh into the linux system solved the problem*

*clearing the environment on the Ubuntu resulted in the same problem

*using a different shell on the Ubuntu system resulted in the same problem

[*] I don't see these options as solutions.
Screen / tmux are terminal substitutions and every time they are used, like iTerm, the problem is solved it seems, but that's not a definitive solution for me. I'd like to understand what's going on and what screen/tmux/iTerm fixes that is causing this issue.
Does anyone have an idea?


text:
Q: What is a terminal plane in high frequency circuits? The term "terminal planes" come up very frequently in books on microwave circuits. What exactly does the term mean?
The closest answer I have got is

A terminal plane, or reference plane, is the  equivalent of a terminal
  pair in a low-frequency network
  -Foundations of microwave engineering, Robert E Collins

But I don't understand what a "plane" is in this sense, and I don't understand why we couldn't just use the term terminal port?

A: It's called a reference plane because, for both coaxial cable and hollow rectangular waveguides, an ideal connector cuts across the guide in a plane cut.
This is what a waveguide connector looks like, a flange with a plane cut across the guide.

This is a pair of APC-7 (A Precision Connector - 7mm) connectors, designed for precision measurement specifically so that the breaks in the inner and the outer line up to form a plane.

Distances from the 'connector' are measured from this plane.
In a more conventional RF connector like BNC, N-type or SMA, the break in the outer defines the plane.
Any plane across the guide can be taken as a reference plane when doing maths with the phase of RF waves propagating along the guide.
The most usually used planes are those of the connectors, as we are usually interested in reflection coefficients of components with respect to their connectors.
You will however sometimes see evaluation boards for RF components, with a line drawn on the board across a microstrip line, with a note that some S-Parameters are quoted with reference to this plane. This can be useful when you will be copying the reference design, and can choose that cut point as your virtual connector.

A: The reference plane is exactly that: The plane relative to which distances, and hence phases, etc are described.
This often goes a bit beyond the strict meaning of the word "plane": it often also comes with an (usually very explicitly stated) understanding that a wave front "comes in" through that plane, and that the plane is at a given reference impedance \$Z_0\$. Think of it as a "cut" through the path a wave travels, especially in closed wave guides.
This becomes especially relevant with measurement equipment, where "phase obtained through a system" really has no meaning until you specify at which point you define your zero-phase to be.


text:
Q: Does mediaResponse really support array of mediaObject? As the document says, MediaResponse contains mediaObjects property, and mediaObjects is array of mediaObject, but when I tried to put multiple mediaObjects, I got this error:

MalformedResponse at
  expected_inputs[0].input_prompt.rich_initial_prompt.items1.media_response:
  Only 1 media_object is allowed. First media_object will be used while
  rest will be filtered.

Then what is the point of having an array of mediaObject?

A: There are several places in the protocol that contain an array where only one object is permitted in the array. One assumes that the designers wanted to make it expandable in the future without having to add special casing.
In this case, it sorta makes sense - right now we can only send one media object as part of the reply. It might be reasonable that, in the future, we could send one or more without having to come back to our webhook.


text:
Q: Handling of global roles directory with ansible-lint I have split my custom ansible roles and the ones downloaded from ansible-galaxy into seperate directories (./roles and ~/.ansible/roles).
In .ansible.cfg I have added the following configuration:
[...]
roles_path = ~/.ansible/roles:./roles
[...]

Ansible-lint reads my ansible.cfg and scans both directories as expected.
Since I just want to lint my own ansible roles, I have added the following line to my .ansible-lint configuration:
[...]
exclude_paths:
    - ~/.ansible/roles
[...]

This unfortunately does not work, ansible-lint still scans both directories.
If I expand the username explictly (e.g. - /root/.ansible/roles), ansible-lint ignores the directory correctly.
Is it somehow possible to ignore my shared roles directory without using an absolute path (since the user accounts differ between my local machine and the ci server)?

A: Ansible-lint will respect ANSIBLE_ROLES_PATH if you define it.
Newer versions of the linter will not report problems from files not tracked by the current repository. Almost for sure you can get around without having to add stuff to exclude_paths.


text:
Q: Python multiprocessing shared memory: list of lists Is it possible to share memory for a list of lists using multiprocessing.Array() or something similar? Also, is it possible to share a more complex object such as a scipy.sparse.lil_matrix? How would I go about doing that? Are there any examples for either? This variable doesn't have to be modified, but it consumes a lot of memory (~1GB per process), and I'm hoping shared memory will cut back the memory usage. Or is that incorrect?

A: In general, no (and Python is especially bad at copy-on-write multiprocessing, because even reading an object means changing its refcount, and that's a write operation).
You could, however, try to work with memory-mapped files. Dump your dataset in one, open it from multiple processes and reap the benefits of your OS's I/O caching.
What are you doing with your dataset?


text:
Q: Is it possible to use a portable library with localized resources in a Universal app? (There's a link at the bottom to a solution with repro of the problem.)
I've been using a portable library with .resx resources for quite some time as it worked for both Windows Store apps and Windows Phone apps. I tried to use it with a Universal app as well, and it works for the Windows Store part, but does not work for Windows Phone.
The problem occurs only when I try to deploy the app on a device (built with the Release configuration). If I just Build it, it does not give an error (but it still can't be deployed on the device successfully). I get the following error:
Error : DEP6810 : MdilXapCompile.exe failed with error code 1004. See log file
'...\Phone App Test\Phone App Test\obj\Release\MDIL\MDILXapCompileLog.txt' for more details.

And in that file:
Error: Compile filter argument specified non-existent file:
...\Phone App Test\Phone App Test\obj\Release\MSIL\en-US\PCL.resources.dll
Invalid argument

The file truly isn't there, but the app does not support the en-US culture anyway, only the library does, so I don't think this file should be needed.
Any idea how I can resolve this issue?
Here's a simple solution with the problem: link

A: Unfortunately the workaround described on Phil Hoff blog did not work for me too well. I have developed my own workaround. It turns out if you are using .resx files to store string values only, then you can easily convert them to .resw and use natively in Windows Phone 8.1.
So what I am doing is copying and converting resources from PCL and placing as native .resw resources in Windows Phone project every build automatically using the tool I made - ResxHell. Just follow the instructions on the repository and you can then reach resources like this
var resourceLoader = new ResourceLoader();
var localizedText = resourceLoader.GetString("MyCustomReswFile/MyStringId");

For nice binding I ended up creating ValueConventer and small localization helper class, take a look at this gist: Binding from .resw files example
With the use of that you can do following in your xaml pages:
//For resource in file Page.Login.resw and string ID "NotUserYet"
<TextBlock Text="{Binding ConverterParameter=Page.Login/NotUserYet, Converter={StaticResource ResString}, Mode=OneWay, Source={StaticResource ResString}}"/>

or
string localizedtext = LocalizationHelper.GetString("MyCustomReswFile", "MyStringId");

A: I found this is already reported to ms connect
https://connect.microsoft.com/VisualStudio/feedback/details/991028/issue-using-resx-files-on-winrt-apps-windows-phone-and-windows
and there is a workaround I haven't tried yet.
http://blogs.msdn.com/b/philliphoff/archive/2014/11/19/missingmanifestresourceexception-when-using-portable-class-libraries-in-winrt.aspx
Unfortunatelly it has not been fixed so far.

A: You can have .resx files in pcls, you just have to use the workaround explained on http://blogs.msdn.com/b/philliphoff/archive/2014/11/19/missingmanifestresourceexception-when-using-portable-class-libraries-in-winrt.aspx
Even with the latest VS 2013 (update 5) the mdil error will appear when trying to deploy Release packages.

MdilXapCompile.exe failed with error code 1004

To work around it you must compile your app using the store option and then use the Application Deployment tool to actually deploy it to the device.

A: You certainly unchecked the "Build" checkbox in the Configuration Manager, that's why the resources are not copied automatically. Check it and it will works.

A: In the end, it seems you can't use PCL library with localized resources using .resx files in the WP part of a Universal app. At least it's not trivial.
There were runtime problems when the app is build in Realese configuration, which I couldn't resolve, so I decided to change to .resw resources. This solved my problems, of course, but I had to duplicate the resources, which is what I was trying to avoid.

A: Had the same problem. I tried deploying via Windows Phone Deployment Tool and it worked.
So instead of using Visual Studio to deploy: create packages and put them on phone and it works!!


text:
Q: how to get application property from ConditionContext I am working on spring but not spring boot. I have a class marked as @Component (but not as @Configuration [it's not config class]). I would like to create it based on the serviceA.create property in app.properties. It the file it looks like this: serviceA.create=true. I would think, that in the code it narrows down to:
@Override
    public boolean matches(final ConditionContext context, final AnnotatedTypeMetadata metadata) {

        return Boolean.valueOf(context.getEnvironment().getProperty("serviceA.create"));
    }

But based on different questions/answers (f.e. this) on the same topic, it sounds like adding @PropertySource(value="classpath:config.properties") is mandatory for this to work (to actually read the property value).
Question is, if I am able to get property from ConditionContext without defining @PropertySource ? because currently I am getting null without that annotation.

It should be done in the following way:
@Component
@Conditional(ServiceACondition.class)
@PropertySource(value="classpath:app.properties")
public class ServiceA {
(...)
}

and the cond. class
public class ServiceACondition implements Condition {
    @Override
    public boolean matches(final ConditionContext context, final AnnotatedTypeMetadata metadata) {

        return Boolean.valueOf(context.getEnvironment().getProperty("serviceA.start"));
    }
}


text:
Q: Add 3 users to ReceipientID in flow builder I need to add 3 users to RecipientIds. i have taken collection Variable Error Occurred: Invalid parameter value for: RecipientIDs.
I need to send bell notifiacation to this three users only.
I have added three users in AND condition.used this {!RecipientIDs}
Getting error:Invalid parameter value for: RecipientIds
Please suggest on this it is working when i add one user.But not working for two and three users.


text:
Q: Get a value from SimpleXML from SOAP api response using PHP I am trying to get a value from SimpleXML SOAP api response using PHP.
This is the PHP code
<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "http://micros-hosting.com/EGateway/SimphonyPosApiWeb.asmx");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

curl_setopt($ch, CURLOPT_POST, TRUE);

curl_setopt($ch, CURLOPT_POSTFIELDS, "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">
  <soap:Body>
    <GetConfigurationInfo xmlns=\"http://micros-hosting.com/EGateway/\">
      <vendorCode />
      <employeeObjectNum>90009</employeeObjectNum>
      <configurationInfoType>
        <int>1</int>
      </configurationInfoType>
      <revenueCenter>11</revenueCenter>
      <configInfoResponse />
    </GetConfigurationInfo>
  </soap:Body>
</soap:Envelope>");

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  "Content-Type: text/xml;",
  "SOAPAction: http://micros-hosting.com/EGateway/GetConfigurationInfo"
));

$response = curl_exec($ch);

curl_close($ch);

$xml = simplexml_load_string($response, NULL, NULL, "http://micros-hosting.com/EGateway/");
$ns = $xml->getNamespaces(true);
$soap = $xml->children($ns['soap']);
$res = $soap->Body->children();
print_r($res);

This is the response
SimpleXMLElement Object
(
    [GetConfigurationInfoResponse] => SimpleXMLElement Object
        (
            [configInfoResponse] => SimpleXMLElement Object
                (
                    [OperationalResult] => SimpleXMLElement Object
                        (
                            [Success] => true
                            [ErrorCode] => Success
                            [ErrorMessage] => Success
                        )

                    [ConfigInfoType] => SimpleXMLElement Object
                        (
                            [EConfigurationInfoType] => MENUITEMDEFINITIONS
                        )

                    [MenuItemDefinitions] => <?xml version="1.0" encoding="utf-8"?><?micros-type Micros.PosCore.DataStore.DbRecords.DbMenuItemDefinition[], PosCore, Version=2.5.0.0, Culture=neutral, PublicKeyToken=null?><ArrayOfDbMenuItemDefinition xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><DbMenuItemDefinition><NameOptions>0000000</NameOptions><MenuItemDefID>3740</MenuItemDefID><HierStrucID>23</HierStrucID><MenuItemMasterID>1572</MenuItemMasterID><SequenceNum>1</SequenceNum><Name1><StringNumberId>7848</StringNumberId><StringText>=Salad & Appetizers=</StringText></Name1><Name2><StringNumberId>7849</StringNumberId><StringText /></Name2><SluSort>0</SluSort><NluNumber>0</NluNumber><Tare>0</Tare><Surcharge>0</Surcharge><IconNumber>0</IconNumber><OptionBits>00000000</OptionBits><SpecialCount>0</SpecialCount><PrepTime>0</PrepTime><Name3><StringNumberId>0</StringNumberId><StringText /></Name3><LongDescriptor><StringNumberId>0</StringNumberId><StringText /></LongDescriptor><MenuItemClassObjNum>0</MenuItemClassObjNum><NluGroupIndex>0</NluGroupIndex><SluIndex>0</SluIndex><HhtSluIndex>0</HhtSluIndex><MainLevels>00000000</MainLevels><SubLevels>00000000</SubLevels><PosRef>0</PosRef><PrintClassObjNum>0</PrintClassObjNum><PrefixLevelOverride>0</PrefixLevelOverride><GuestCount>0</GuestCount><MenuLevelEntries /><DefaultCondiments /><NextScreen /><MiMasterObjNum>10030000</MiMasterObjNum><CheckAvailability>false</CheckAvailability><OutOfMenuItem>false</OutOfMenuItem></DbMenuItemDefinition><DbMenuItemDefinition><NameOptions>0000000</NameOptions><MenuItemDefID>3741</MenuItemDefID><HierStrucID>23</HierStrucID><MenuItemMasterID>2090</MenuItemMasterID><SequenceNum>1</SequenceNum><Name1><StringNumberId>7850</StringNumberId><StringText>Chicken caesar salad</StringText></Name1><Name2><StringNumberId>7851</StringNumberId><StringText /></Name2><SluSort>0</SluSort><NluNumber>0</NluNumber><Tare>0</Tare><Surcharge>0</Surcharge><IconNumber>0</IconNumber><OptionBits>00000000</OptionBits><SpecialCount>0</SpecialCount><PrepTime>0</PrepTime><Name3><StringNumberId>0</StringNumberId><StringText /></Name3><LongDescriptor><StringNumberId>0</StringNumberId><StringText /></LongDescriptor><MenuItemClassObjNum>1000</MenuItemClassObjNum><NluGroupIndex>0</NluGroupIndex><SluIndex>4</SluIndex><HhtSluIndex>0</HhtSluIndex><MainLevels>11111111</MainLevels><SubLevels>11111111</SubLevels><PosRef>0</PosRef><PrintClassObjNum>503</PrintClassObjNum><PrefixLevelOverride>0</PrefixLevelOverride><GuestCount>0</GuestCount><MenuLevelEntries /><DefaultCondiments /><NextScreen /><MiMasterObjNum>10030002</MiMasterObjNum><CheckAvailability>false</CheckAvailability><OutOfMenuItem>false</OutOfMenuItem></DbMenuItemDefinition></ArrayOfDbMenuItemDefinition>
                )
        )
)

I need get a value from MenuItemDefinitions response XML. How can I get a get a value from SimpleXML? Can someone help me on this?


text:
Q: Error in adding django-axes to project I have installed django axes with this command in cmd :
pip install django-axes

Then i addes to my setting.py file this parts :
    INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'post_app',
    'axes',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'axes.middleware.FailedLoginMiddleware',
]

AXES_LOCK_OUT_AT_FAILURE = False
AXES_USE_USER_AGENT = True
AXES_COOLOFF_TIME = 1
AXES_LOGIN_FAILURE_LIMIT = 50

Now i want to runserver with this command :
python manage.py runserver

But i have this error in cmd :
  Unhandled exception in thread started by <function wrapper at 0x0000000004AA4908>
Traceback (most recent call last):
  File "D:\python\data\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper
    fn(*args, **kwargs)
  File "D:\python\data\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run
    autoreload.raise_last_exception()
  File "D:\python\data\lib\site-packages\django\utils\autoreload.py", line 251, in raise_last_exception
    six.reraise(*_exception)
  File "D:\python\data\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper
    fn(*args, **kwargs)
  File "D:\python\data\lib\site-packages\django\__init__.py", line 27, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "D:\python\data\lib\site-packages\django\apps\registry.py", line 116, in populate
    app_config.ready()
  File "D:\python\data\lib\site-packages\axes\apps.py", line 9, in ready
    from axes.decorators import watch_login
  File "D:\python\data\lib\site-packages\axes\decorators.py", line 3, in <module>
    from socket import inet_pton, AF_INET6, error
ImportError: cannot import name inet_pton

Is there any mistake?or any missed work?

A: Did you run python manage.py migrate to sync the database before you run the server? If you did, then you need to check your python version and django verison, check this for detail:https://github.com/jazzband/django-axes/blob/master/.travis.yml


text:
Q: Dnn Menu Control in IE I had a dnn slide menu where I am having the problem only in IE,
Only One of the sub item is not being displayed only in IE, when I inspect the element the structure is  as below in IE.,

In Firefox browser it is like this

E-Participation

any help would be appreciated

A: At last found the solution by changing the respective page setting, by unchecking the checkbox disabled it is working fine.
But still I didn't get why it is working fine in firefox and not working fine in IE7


text:
Q: Enable TLS 1.2 and disable SSL 3 on SQL Server 2008 I know similar questions have been asked. What I'm asking for are concrete instructions on what to do, or not do, for my particular installation. I have some questions that I can't find the answer to, and I need some answers before I can install Microsoft's hotfix.
The goal is to disable SSL 3 on the machine by adding the registry key HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\Schannel\Protocols\SSL 3.0\Server\ - add value Enabled = 0. However this causes SqlServerAgent to not start.
Running SQL Server 2008 R2 (SP3) build 10.50.6220.0 (X64).

Here's Microsoft's official download to enable TLS1.2 support: link to microsoft
The page reads First build that supports TLS 1.2 - 10.50.6542.0. This is higher than my build number. Does it mean the hotfix only is compatible with builds from 10.50.6542 and up? And so my build is not supported?
If my build is supported, then I supposed I should install it. Then what happens next?

A: In order to be compatible with TLS 1.2, you must be running SQL Server 2008 R2 version 10.50.6542.0 or later.
To get to that version level, you need to install Service Pack 3 for SQL Server 2008 R2, then install the hotfix from KB3144114 from https://support.microsoft.com/en-us/Hotfix/KbHotfix?kbnum=3144114&kbln=en-us which will update your SQL Server to v 10.50.6542.
Be aware, the above hotfix should never be installed on a production system unless you've extensively tested it in your test-environment first.


text:
Q: Unitary representation compact Lie Groups Let $G$ be a compact Lie group. I have to prove that for $n$ large I there is an immersion of $G$ in the unitary group $U(n)$. I know that any finite-dimensional representation of a compact Lie group is unitary and thus completely reducible. So I have to prove that this representation is faithful... right?

A: You need to prove that you group $G$ has a faithful representation.   This "is" Peter-Weyl theorem (or a corollary of, depending on how one states things).


text:
Q: In TypeScript, interface defines string, however returned type is string[]. How to properly access returned array? I have observed a strange behavior of my node application using GraphicsMagick.
I would like to identify the number of pages in a pdf file. Therefore, I use "identify" which returns an object of type gm.ImageInfo. Then I "destructure" the returned object to obtain an array of strings that describe the format of my input file. The length should be the number of pages (which it actually is).
What strikes me is that Format inside the interface gm.ImageInfo is defined as string, however "identify" returns an array of strings (in case the input file consists of multiple pages). Still, I cannot formally define my "Format" variable as "string[]" because TypeScript tells me that a string cannot be assigned to an array of strings (which is obviously correct). How can I solve that conflict an obtain the actual array of strings returned by "identify"?
Here is the relevant extract of my code:
This works but I do not formally get an array of strings:
import gm from 'gm';

gm('test.pdf').identify((err: any, value: gm.ImageInfo) => {
  const { Format, ...rest }: gm.ImageInfo = value;
  console.log(Format);
  console.log(Format.length);
  if (err) {
    console.log('err');
  }
});

This does not work since TypeScript complains:
import gm from 'gm';

gm('test.pdf').identify((err: any, value: gm.ImageInfo) => {
  const { Format, ...rest }: { Format: string[] } = value;
  console.log(Format);
  console.log(Format.length);
  if (err) {
    console.log('err');
  }
});

Format typically contains something like this (for example if the input pdf contains 7 pages):
[
  'PDF (Portable Document Format)',
  'PDF (Portable Document Format)',
  'PDF (Portable Document Format)',
  'PDF (Portable Document Format)',
  'PDF (Portable Document Format)',
  'PDF (Portable Document Format)',
  'PDF (Portable Document Format)'
]

This looks very much like an array. Format.length is 7 (= the number of pages). However, the type of Format is not string[]. How can I convert Format to a string[] to obtain an actual array?


text:
Q: Inter table joins for a relational chord diagram I have one question. It may be easy for you.
I am trying to build a d3js chord diagram - something like this (http://bl.ocks.org/4062006):

I am however getting the data from my mysql database
My table looks like this:
id gender_taker gender_giver
1     F            M
2     M            M
3     F            M
4     F            F

I want the output to look something like this:
gender_giver gender_taker count(*)
M            F            2
M            M            1
F            F            1

This is easy and can be produced by:
SELECT gender_giver, gender_taker, COUNT(*) FROM data WHEREclauses GROUP BY gender_taker, gender_giver

But I have another issue, I have two another tables that looks like this:
Table 1:
id entryid gender_taker
1   2       F
2   2       M
3   3       F

Table 2:
id entryid gender_giver
1   1       M
2   1       F
3   2       M

entryid is basically id of the first table suggesting that Table2 and Table3 are just subsets of table1
If you combine these three tables it might looks something like:
id gender_taker gender_giver
1     F            M,M,F
2     M,F,M        M,M
3     F,F          M
4     F            F

So as a result for the chord diagram I want all these tables taken into account eventually giving something like:
gender_giver gender_taker count(*)
M            F            6
M            M            4
F            F            2
F            M            0

Please help me out here.

A: DROP TABLE IF EXISTS core;
CREATE TABLE core
(entry_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,gender_taker CHAR(1) NOT NULL
,gender_giver CHAR(1) NOT NULL
);

INSERT INTO core VALUES
(1     ,'F','M'),
(2,'M','M'),
(3,'F','M'),
(4,'F','F');

DROP TABLE IF EXISTS table1;
CREATE TABLE table1
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,entryid INT NOT NULL
,gender_taker CHAR(1) NOT NULL
);

INSERT INTO table1 VALUES
(1   ,2       ,'F'),
(2   ,2       ,'M'),
(3   ,3       ,'F');

DROP TABLE IF EXISTS table2;
CREATE TABLE table2
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,entryid INT NOT NULL
,gender_giver CHAR(1) NOT NULL
);

INSERT INTO table2 VALUES

(1   ,1       ,'M'),
(2   ,1       ,'F'),
(3   ,2       ,'M');

SELECT entry_id
     , GROUP_CONCAT(gender_taker) gender_takers
     , GROUP_CONCAT(gender_giver) gender_givers
  FROM
     ( SELECT * FROM core
       UNION
       SELECT entryid,gender_taker,NULL FROM table1
       UNION
       SELECT entryid,NULL,gender_giver FROM table2
     ) x
 GROUP
    BY entry_id;
+----------+---------------+---------------+
| entry_id | gender_takers | gender_givers |
+----------+---------------+---------------+
|        1 | F             | M,M,F         |
|        2 | M,F,M         | M,M           |
|        3 | F,F           | M             |
|        4 | F             | F             |
+----------+---------------+---------------+

SELECT a.gender taker
     , b.gender giver
     , COUNT(*)
  FROM
     (
       SELECT entry_id,'taker' role, gender_taker gender FROM core
       UNION ALL
       SELECT entry_id,'giver', gender_giver FROM core
       UNION ALL
       SELECT entryid,'taker',gender_taker FROM table1
       UNION ALL
       SELECT entryid,'giver',gender_giver FROM table2
     ) a
  JOIN
     (
       SELECT entry_id,'taker' role, gender_taker gender FROM core
       UNION ALL
       SELECT entry_id,'giver', gender_giver FROM core
       UNION ALL
       SELECT entryid,'taker',gender_taker FROM table1
       UNION ALL
       SELECT entryid,'giver',gender_giver FROM table2
     ) b
    ON b.entry_id = a.entry_id
   AND b.role = 'giver'
   AND a.role = 'taker'
 GROUP
    BY taker
     , giver;
+-------+-------+----------+
| taker | giver | COUNT(*) |
+-------+-------+----------+
| F     | F     |        2 |
| F     | M     |        6 |
| M     | M     |        4 |
+-------+-------+----------+


text: Q: What are the improvements of Flask compared with traditional MAC? I know that traditional MAC has limitations, like that it provides poor support for data and application integrity, separation of duty, and least privilege requirements. So NSA and SCC developed a flexible MAC architecture called Flask to overcome the limitations of traditional MAC. Could someone explain what improvements Flask has made? Thank you!


text:
Q: How to hide the html body when using curl? Currently I am experimenting with curl flags, looking how to get only the  response headers, follow the redirection if any, encryption and authentication used and the round trip time.
What flag should I use to hide/disable the HTML body in the output?

A: How to make curl disable html output
Use the -s flag (for silent operation) and redirect stout (>) to (eg) /dev/null (or, if you're on Windows, simply NUL)
This, inc combination with -D <file> (aka --dump-header) may give you the output you are looking for.
The curl manpage has more information on the command-line options which may be helpful.
Example
$ curl -s https://superuser.com -D su.txt > /dev/null
$ less -FX su.txt
HTTP/2 200
date: Sun, 25 Feb 2018 17:24:30 GMT
content-type: text/html; charset=utf-8
x-frame-options: SAMEORIGIN
x-request-guid: e147da19-7cc9-42cd-8706-4204fd64d4a9
strict-transport-security: max-age=15552000
content-security-policy-report-only: default-src https: wss: data: blob: 'unsafe-eval' 'unsafe-inline'; report-uri https://stackoverflow.report-uri.io/r/default/csp/reportOnly
accept-ranges: bytes
via: 1.1 varnish
x-served-by: cache-lcy19224-LCY
x-cache: MISS
x-cache-hits: 0
x-timer: S1519579470.439587,VS0,VE88
vary: Fastly-SSL
x-dns-prefetch-control: off
set-cookie: prov=d007391b-afc2-4717-282a-287f18827242; domain=.superuser.com; expires=Fri, 01-Jan-2055 00:00:00 GMT; path=/; HttpOnly
cache-control: private
content-length: 101543

A: You can discard the body while still keeping the headers by telling curl to dump them on stdout:
$ curl -D/dev/stdout -o/dev/null -s https://superuser.com
HTTP/1.1 200 OK
Cache-Control: private
Content-Type: text/html; charset=utf-8
X-Frame-Options: SAMEORIGIN
X-Request-Guid: a599d44b-705c-4615-a8d8-80c7614bd64f
...

*

*-D/dev/stdout: dump the headers on standard output

*-o/dev/null: discard the body

*-s: disable the progress meter

A: Perharps you can use the -I option to show document info only.
curl -I www.google.com
HTTP/1.1 200 OK
Content-Type: text/html; charset=ISO-8859-1
P3P: CP="This is not a P3P policy! See g.co/p3phelp for more info."
Date: Fri, 22 May 2020 11:21:37 GMT
Server: gws
X-XSS-Protection: 0
X-Frame-Options: SAMEORIGIN
Transfer-Encoding: chunked
Expires: Fri, 22 May 2020 11:21:37 GMT
Cache-Control: private
Set-Cookie: 1P_JAR=2020-05-22-11; expires=Sun, 21-Jun-2020 11:21:37 GMT; path=/; domain=.google.com; Secure
Set-Cookie: NID=204=ijCC6L4JERmyB5I14nFMLKl91R8H5gD5thzU43L_s0AFuYDaVwmeYy4X3Sc_FHoY24AXdfpXOnpBNZsKTnlX612_tnnafOlsAThO6K3fXfRuyhU_o5_jVL3la6AK_fryMqYL5ErPmPoxX1-dwq-mQimbqUjY69n_JJYEGct5EuU; expires=Sat, 21-Nov-2020 11:21:37 GMT; path=/; domain=.google.com; HttpOnly

See more curl options by typing curl -h in your terminal


text:
Q: Are static members inherited? I have a static member variable in class A and class B derives from class A.
class A
{
  public:
    A()
    {
      a = 3;
    }
    static int a;
};

int A::a = 0;

class B : public A
{
  public:
    B()
    {
      a = 4;
    }
};

void main()
{
  A objA;
  cout << "Before:" << A::a;
  B obj;
  cout << endl << "After:" << A::a;
}

As per Are static fields inherited? when derived type object is made then it also creates base type.
I have following questions:

*

*How is it that instead of A::a I can also access objA.a? Static variables shouldn't be accessible through objects of that class.

*If for derived class also a new static variable is made (specific to class B) then why is it not necessary to initialize the static variable for class B?

*Why does the output of following shown as:

Before:3
After:4

When it is expected to show 3 for before and after?

A: The access to the static variable is what is inherited. Do note that static members with private access will not be accessible, as that is what the protected keyword is for.

A: *

*There's not objA.a, there's access to a inside B() constructor where A::a is visible and thus can be accessed as just "a".

*B::a refer to the same address in memory, there's no new static variable for B::a, it's same which you can check via &B::a.

*It is not expected to be 3 and 3, it is expected to be 3 and 4 because line "B obj;" changes A::a value, and because of (2) it's same variable as B::a (i.e. B() constructor changes A::a).

A: Your fundamental problem is that you have mis-interpreted the answers in the question to which you linked. When you derive the class B you do not make a new static variable a.
So, A::a and B::a are the same variable. Once you correct this mis-understanding everything else will be obvious and clear.
Looking at your code:
A objA; //A() executes which sets A::a to 3
cout << "Before:" << A::a; //outputs 3
B obj; //now B() executes and sets B::a to 4
cout << endl << "After:" << A::a; //outputs 4 since A::a is same variable as B::a

How is it that instead of A::a I can also access objA.a?

Because the language specification says that you can. The language specification says that A::a and objA.a are the same variable. This is covered in any good guide to the language. For example, online you can read cppreference.com which says it like this:

To refer to a static member n of class T, two forms may be used: qualified name T::m or member access expression e.m or e->m, where e is an expression that evaluates to T or T* respectively. When in the same class scope, the qualification is unnecessary.

A: *

*Static variables are accessible through objects of that class.  Why wouldn't they be?

*There is only one copy of any static variable.  If another class inherits it, it only gets access to the same static variable, not another copy.

*Because B::B() changed A::a to 4.  Both B and A share access to A::a.

A:
Are static members inherited?

In the sense that static members of the base class are also static members of any derived class, yes.

How is it that instead of A::a i can also access objA.a. Static variables shouldnt be accessible through objects of that class.

That's just how the language is defined. Both are equivalent, and the object style can be more convenient if you can't easily write the type of the object.

If for derived class also a new static variable is made (specific to class B) then why is it not necessary to initialize the static variable for class B?

There isn't a new static variable specific to class B; there's just one for class A. The inheritance means that it is also scoped within class B; but A::a and B::a both refer to the same variable.

Why does the output of following shown as [3,4] when it is expected to show 3 for Before and after?

As described above, there is only one variable, and the constructor of B sets it to 4.


text:
Q: Obtaining the P-value of a two-tailed t test The null hypothesis and the alternative one are stated, the null hypothesis is assumed to be true (reductio ad absurdum) and the value of significance level 0.05 is fixed. Finally, a two-tailed t test is conducted and the results are as follows:
Standard error: 46.8694
Degrees of freedom: 10
t: 0.18
Once at this point, the P-value can be obtained. The following reasoning was used to do so:
The P-value is the probability that a t having 10 degrees of freedom is more 'extreme' than -0.18. That is, less than -0.18 or greater than 0.18.
Thus P-value: 0.86
Therefore null hypothesis is accepted.
Are this reasoning and result right? If not how could P-value be obtained?

A: I'm assuming that you have $11$ pieces of data, since your degree of freedom is $10$. I'll be reffering to this data as 'sample', and its 'sample size' is $11$.
The sample size of n constitutes n pieces of information for estimating the mean of your sample and its variability. One degree of freedom is spent estimating the mean, and the remaining n-1 degrees of freedom estimate variability. Since we've already estimated the mean (the $t$ statistic does that in general, see below), I'll assume you have a sample with size of $11 \ (n=11)$.
The two-tailed t statistic of the $\mathbf{X} = (X_1, ...,X_{11})$ sample is:
$$t = t_{11-1} = \frac{EstimatedMean(\mathbf{X})-ActualMean(\mathbf{X})}{S_{11}^*}$$
Where $S_{11}^*$ is the corrected empiric variance:
$$S_{11}^* = \frac{1}{11-1} \sum_{i=1}^{11}\Bigr(X_i-EstimatedMean(\mathbf{X})\Bigl)$$
And obviously the Estimated Mean is just the regular average of your sample:
$$EstimatedMean(\mathbf{X}) = \frac{1}{11}\sum_{i=1}^{11} X_i$$
The t statistic calculates what it can from the sample provided, which only leaves the $ActualMean(\mathbf{X})$ needing to be estimated.
Here is the important part: We estimate the Actual Mean to be around the Estimated Mean, and we draw an interval centered around the Estimated Mean. The size of this interval depends on the significance level, commonly denoted as $\alpha$, in this case $\alpha = 0.05$. The (yet unkown) interval is commonly denoted as $(EstimatedMean(\mathbf{X}) - r_\alpha, EstimatedMean(\mathbf{X}) + r_\alpha)$. And we want our data to be in this interval with a $1-\alpha$ chance. This gives an equation for $r_\alpha$:
$$\Bbb{P}\Bigr(-\frac{r_\alpha}{S_{11}^*}\sqrt{11} \le t_{11-1} \le \frac{r_\alpha}{S_{11}^*}\sqrt{11}\ \Bigl) = 1-\alpha$$
Which can easily be transformed to:
$$t_{11-1}\Bigr(\frac{r_\alpha}{S_{11}^*}\sqrt{11}\Bigl) - t_{11-1}\Bigr(-\frac{r_\alpha}{S_{10}^*}\sqrt{11}\Bigl) = t_{11-1}\Bigr(\frac{r_\alpha}{S_{11}^*}\sqrt{11}\Bigl) - \biggl(1- t_{11-1}\Bigr(\frac{r_\alpha}{S_{11}^*}\sqrt{11}\Bigl)\biggr)= \\ = -1 + 2t_{10}\Bigl(\frac{r_\alpha}{S_{11}^*}\sqrt{11}\Bigr) = 1-\alpha \iff \\ \iff  t_{10}\Bigl(\frac{r_\alpha}{S_{11}^*}\sqrt{11}\Bigr) = 1 - \frac{\alpha}{2} \iff \\ \iff r_\alpha = \frac{t_{10}^{-1}\Bigl(\frac{\alpha}{2}\Bigr)S_{11}^*}{\sqrt{11}} = \frac{t_{10}^{-1}\Bigl(\frac{0.05}{2}\Bigr)S_{11}^*}{\sqrt{11}}$$
What is the p-value then? Simply put, the p-value$=\alpha$ substitution correctly solves the above equation for $r_\alpha$. This means, that the p-value is on the exact border on the interval, it's the $\alpha$, that's for which our null hypothesis is on the boarder of acceptance versus rejection.
Solving the equation for $\alpha$ gives you the p-value:
$$p-value = 2 - 2t_{10}\Bigl(\frac{r_\alpha}{S_{11}^*}\sqrt{11}\Bigr)$$
If the p-value is less than $\alpha$, then we reject the null hypothesis, if the p-value is greater than $\alpha$, then we accept the null hypothesis.
Additionally, the smaller the p-value is, the more we reject the null hypothesis, however, this is not true for the reverse. If the null hypothesis is right, then the distribution of the p-value is Uniform on $[0,1]$. That means that we have exactly an $\alpha$ chance to be wrong in acepting the null hypothesis.
Answering your original question: Your reasoning is not right. We accepted the null hypothesis because the p-value was greater than $\alpha$.


text:
Q: How to export selected rows to csv in magento 2 grid? I am trying to export the custom grid data to csv file. Its working fine in all grid data case, but when I am selecting the the rows and trying to export it exporting all grid data instead of specific records.

I am using below code to export the grid data.
class ExportCsv extends \Magento\Backend\App\Action
{
    /**
     * Default file name
     */
    const FILENAME = 'registration_code.csv';

    /**
     * @var Magento\Framework\App\Response\Http\FileFactory
     */
    protected $_fileFactory;

    public function __construct(Context $context, FileFactory $FileFactory)
    {
        parent::__construct($context);
        $this->_fileFactory = $FileFactory;
    }

    public function execute()
    {
        $this->_view->loadLayout(false);

        $fileName = self::FILENAME;

        $content = $this->_view->getLayout()
            ->createBlock('Medical\Groups\Block\Adminhtml\Code\Grid')
            ->setSaveParametersInSession(true)
            ->getCsv();

        return $this->_fileFactory->create(
            $fileName,
            $content,
            DirectoryList::VAR_DIR
        );
    }
}

For grid generation I am using below code in Grid.php
protected function _prepareColumns()
{
    $this->addColumn(
        'action',
        [
            'header' => __('Action'),
            'type' => 'action',
            'getter' => 'getId',
            'actions' => [
                [
                    'caption' => __('Edit'),
                    'url' => [
                        'base' => '*/*/edit'
                    ],
                    'field' => 'id'
                ]
            ],
            'filter' => false,
            'sortable' => false,
            'index' => 'stores',
            'header_css_class' => 'col-action',
            'column_css_class' => 'col-action',
            'is_system'   => true
        ]
    );

    $this->addColumn(
        'registration_code',
        [
            'header' => __('Registration Code'),
            'type' => 'text',
            'index' => 'registration_code',
            'header_css_class' => 'col-id',
            'column_css_class' => 'col-id'
        ]
    );

    $this->addColumn(
        'url',
        [
            'header' => __('Registration Url'),
            'type' => 'text',
            'index' => 'url',
            'header_css_class' => 'col-id',
            'column_css_class' => 'col-id',
            'editor' => 'text'
        ]
    );

    $this->addColumn(
        'customer_email',
        [
            'header' => __('Customer Email'),
            'type' => 'text',
            'index' => 'customer_email',
            'header_css_class' => 'col-id',
            'column_css_class' => 'col-id',
            //'renderer' => 'Medical\Groups\Block\Adminhtml\Code\Grid\Column\Renderer\Customer'
        ]
    );

    $this->addColumn(
        'used_customer',
        [
            'header' => __('Code used by Customer'),
            'type' => 'text',
            'index' => 'used_customer',
            'header_css_class' => 'col-id',
            'column_css_class' => 'col-id'
        ]
    );

    $this->addColumn(
        'customer_group_id',
        [
            'header' => __('Medical Group'),
            'type' => 'text',
            'index' => 'customer_group_id',
            'header_css_class' => 'col-id',
            'column_css_class' => 'col-id',
            'renderer' => 'Medical\Groups\Block\Adminhtml\Code\Grid\Column\Renderer\Customergroups'
        ]
    );

    $this->addColumn(
        'status',
        [
            'header' => __('Code Status'),
            'type' => 'text',
            'index' => 'status',
            'header_css_class' => 'col-id',
            'column_css_class' => 'col-id',
            'renderer' => 'Medical\Groups\Block\Adminhtml\Code\Grid\Column\Renderer\Status'
        ]
    );

    $this->addColumn(
        'expiry_date',
        [
            'header' => __('Code Expiry Date'),
            'type' => 'text',
            'index' => 'expiry_date',
            'header_css_class' => 'col-id',
            'column_css_class' => 'col-id'
        ]
    );

    $this->addExportType($this->getUrl('medicalgroups/*/exportCsv', ['_current' => true]),__('CSV'));

    $block = $this->getLayout()->getBlock('grid.bottom.links');
    if ($block) {
        $this->setChild('grid.bottom.links', $block);
    }

    return parent::_prepareColumns();
}

Am I missing something?


text:
Q: Magento 2 - Can't save custom Customer attribute value in observer customer_save_after_data_object I have created three custom attributes for Customer: myapp_id, codice_univoco and indirizzo_pec

If I enter a value in codice_univoco and/or indirizzo_pec, data is successfully saved:

However, when I insert a value for myapp_id (App ID), and then save, all custom attributes are emptied (including myapp_id):

If I check my database, I can see that custom attribute values are first added…

…and then deleted from customer_entity_varchar table

But I know the reason why.
It is because of the following observer I wrote to handle customer_save_after_data_object: (the culprit is the line $customer->save();):
   /**
     * Execute observer
     *
     * @param \Magento\Framework\Event\Observer $observer
     * @return $this
     */
    public function execute (\Magento\Framework\Event\Observer $observer) {

        //Return new customer data
        $customerDataObject = $observer->getData("customer_data_object");

        //Returns old customer data
        $origCustomerDataObject = $observer->getData("orig_customer_data_object");

        if (is_null($origCustomerDataObject)) {

            return;
        }

        //if is first update confirm and send email
        try {
            $customer = $this->customerRegistry->retrieve($customerDataObject->getId());

        } catch (Exception $e) {

            return $this;
        }

         if (!$this->isConfirmed($customer) &&
             $customer->getData("myapp_id") &&
            !$customer->getData("sent_email")
        ) {

            //confirm and send email
            $customer->setConfirmation(null);
            $customer->setData("sent_email",1);
            $customer->save();
        }

        return $this;
 }

Note: custom attribute sent_email is not saved too.
In other words, If I save a customer inside the observer, custom  data is not saved.
If I remove the line $customer->save(); everything works fine.
It is driving me crazy.
Additional information:
"app_id" custom attribute definition in InstallData.php
$customerSetup->addAttribute(

    Customer::ENTITY,
    'myapp_id',
    [
        'type' => 'int',
        'label' => 'App ID',
        'input' => 'text',
        'source' => '',
        'required' => false,
        'visible' => true,
        'position' => 333,
        'system' => false,
        'backend' => ''
    ]
);

$customerAttribute = $customerSetup->getEavConfig()->getAttribute(Customer::ENTITY, 'myapp_id');
$customerAttribute->addData([ 'used_in_forms' => [ 'adminhtml_customer' ] ]);
$customerAttribute->save();

"sent_email" custom attribute definition in InstallData.php
$customerSetup->addAttribute(\Magento\Customer\Model\Customer::ENTITY, 'sent_email', [
    'type' => 'int',
    'label' => 'Sent Email',
    'input' => 'boolean',
    'source' => '',
    'required' => true,
    'visible' => false,
    'position' => 333,
    'system' => false,
    'backend' => '',
    'default' => 0
]);

$attribute = $customerSetup->getEavConfig()->getAttribute('customer', 'sent_email')
->addData(['used_in_forms' => [
        'adminhtml_customer'
    ]
]);

$attribute->save();

"codice_univoco" custom attribute definition in UpgradeData.php
if (version_compare($context->getVersion(), '1.0.1') < 0) {

$codiceunivoco = $this->eavConfig->getAttribute(\Magento\Customer\Model\Customer::ENTITY, 'codice_univoco');

if (!$codiceunivoco->getId()) {

    $eavSetup->addAttribute(
        \Magento\Customer\Model\Customer::ENTITY,
        'codice_univoco',
        [
            'type'         => 'varchar',
            'label'        => 'Codice univoco',
            'input'        => 'text',
            'required'     => true,
            'visible'      => true,
            'user_defined' => false,
            'position'     => 999,
            'system'       => 0,
        ]
    );

    $codiceunivoco = $this->eavConfig->getAttribute(\Magento\Customer\Model\Customer::ENTITY, 'codice_univoco');
}

$codiceunivoco->setData(
    'used_in_forms',
    ['adminhtml_customer','customer_account_create']

);

$codiceunivoco->save();

"indirizzo_pec" custom attribute definition in UpgradeData.php
$indirizzopec = $this->eavConfig->getAttribute(\Magento\Customer\Model\Customer::ENTITY, 'indirizzo_pec');

if (!$indirizzopec->getId()) {

    // Add Indirizzo Pec

    $eavSetup->addAttribute(
        \Magento\Customer\Model\Customer::ENTITY,
        'indirizzo_pec',
        [
            'type'         => 'varchar',
            'label'        => 'Indirizzo Pec',
            'input'        => 'text',
            'required'     => false,
            'visible'      => true,
            'user_defined' => false,
            'position'     => 999,
            'system'       => 0,
        ]
    );

    $indirizzopec = $this->eavConfig->getAttribute(\Magento\Customer\Model\Customer::ENTITY, 'indirizzo_pec');

}

$indirizzopec->setData(
    'used_in_forms',
    [
        'adminhtml_customer',
        'customer_account_create'
    ]

);

$indirizzopec->save();

Note 2: don't know if it is important: I have assigned a custom attribute with the same name (app_id) to other two entities: Category and Customer Address

A: Many, many thanks to Devidas who pointed me in the  right direction (see first comment to my question) .
Here's what I've learned so far:
Consider two use-case scenario:

*

*Custom attribute is set by User in a form

*Custom attribute is set in code
Let's examine them in details
Scenario 1: Custom attribute set by User
Four conditions must be met in order for custom attribute values to be saved to database:

*

*Set the attribute option "system" => 0 in attribute parameters inside the install/upgrade script
       $customerSetup->addAttribute(
       Customer::ENTITY,
       'sent_email',
       [
            …

            'system' => 0,

            …
         ]
       );

*Assign your attribute to the entity attribute set inside the install/upgrade script

   $eavSetup->addAttributeToSet(
      CustomerMetadataInterface::ENTITY_TYPE_CUSTOMER,
      CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
      null,
      'sent_email');

      $customerSetup->getEavConfig()->getAttribute(
         Customer::ENTITY, 'sent_email')
            ->addData([
            …

            'attribute_set_id' => $attributeSetId,

            …
      ])->save();

*Assign your attribute to the entity attribute group inside the install/upgrade script

   $customerSetup->getEavConfig()->getAttribute(
      Customer::ENTITY, 'sent_email')
      ->addData([
      …

      'attribute_group_id' => $attributeGroupId,

      …
   ])->save();

In this case entity is Customer, but it could be Product, Category, etc.

*Avoid using getData() and/or setData() to access/change custom attribute values.
Use magic methods instead.
I.e. to get custom attribute sent_email do not use:
      $customer->getData('sent_email');

.     use:
      $customer->getSentEmail();

Scenario 2: Custom attribute set in code
In addition to meeting all conditions of the first use-case scenario, you must back your custom attribute with a custom field in the core entity table, like this:
   $setup->getConnection()->addColumn(
      $setup->getTable('customer_entity'),
      'sent_email',
      [
         'type' => Table::TYPE_INTEGER,
         'nullable' => true,
         'comment' => 'Sent email'
      ]
     );

Be sure to flush cache storage before data get persistently saved.
Although your attributes are created, the cache is what triggers the data to be saved afterwards.
Here is the full code of a sample module where the concepts discussed above are applied.
job_title is a custom Customer attribute whose value can be set by User in a form.
sent_email is a custom Customer attribute whose value is set programmatically in code inside an observer.
magentostackexchange\Sample\etc\events.xml
   <?xml version="1.0" ?>
   <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd>

   <event name="customer_save_after_data_object">

      <observer instance=
         "Magentostackexchange\Sample\Observer\Customer\SaveAfterDataObject" name="magentostackexchange_sample_observer_customer_saveafterdataobject_customer_save_after_data_object"/>

      </event>
   </config>

magentostackexchange\Sample\etc\module.xml
   <?xml version="1.0" ?>
   <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"           ù
      xsi:noNamespaceSchemaLocation=
         "urn:magento:framework:Module/etc/module.xs">

      <module name="Magentostackexchange_Sample" setup_version="1.0.0" schema_version="1.0.0">
         <sequence>
            <module name="Magento_Customer"/>
         </sequence>
      </module>
   </config>

magentostackexchange\Sample\Observer\Customer\SaveAfterDataObject.php
   <?php

   namespace Magentostackexchange\Sample\Observer\Customer;

   use \Exception;
   use Magento\Customer\Model\Authentication;
   use Magento\Customer\Model\CustomerRegistry;
   use Magento\Customer\Model\EmailNotification;

   class SaveAfterDataObject implements \Magento\Framework\Event\ObserverInterface
   {

      /**
      * @var CustomerRegistry  $customerRegistry
      */
      protected $customerRegistry;

      /**
      * @var EmailNotification $emailNotification
      */
      protected $emailNotification;

      /**
      * @var Authentication $customerAuthentication
      */
      protected $customerAuthentication;

      /**
      * Constructor
      *
      * @param CustomerRegistry  $customerRegistry
      * @param EmailNotification $emailNotification
      * @param Authentication    $customerAuthentication
      */
      public function __construct(
         CustomerRegistry $customerRegistry,
         EmailNotification $emailNotification,
         Authentication $customerAuthentication
      )
      {
         $this->customerRegistry = $customerRegistry;
         $this->emailNotification = $emailNotification;
         $this->customerAuthentication = $customerAuthentication;
      }

      /**
      * Execute observer
      *
      * @param \Magento\Framework\Event\Observer $observer
      * @return void
      */
      public function execute(
         \Magento\Framework\Event\Observer $observer
      ) {

            $customerDataObject = $observer->getCustomerDataObject();
            $origCustomerDataObject = $observer->getOrigCustomerDataObject();

            if (is_null($origCustomerDataObject)) {
               return;
            }

            //If is first update confirm and send email
            try {
                  $customer =
                     $this->customerRegistry
                        ->retrieve($customerDataObject->getId());

            } catch (Exception $e) {
               return $this;
         }

         if (!$customer->getSentEmail()) {
            //Confirm and send email
            $customer->setConfirmation(null);
            $customer->setSentEmail(1);
            $customer->save();

            //Send email
            $this->emailNotification->newAccount(
               $customerDataObject,
               $type = EmailNotification::NEW_ACCOUNT_EMAIL_REGISTERED,
               $backUrl = '',
               $customerDataObject->getStoreId()
            );
         }

         return $this;

      }
   }

magentostackexchange\Sample\Setup\InstallData.php
   <?php

   namespace Magentostackexchange\Sample\Setup;

   use Exception;
   use \Magento\Customer\Model\Customer;
   use Magento\Customer\Setup\CustomerSetupFactory;
   use Magento\Framework\Setup\InstallDataInterface;
   use Magento\Framework\Setup\ModuleContextInterface;
   use Magento\Framework\Setup\ModuleDataSetupInterface;
   use Magento\Eav\Model\Entity\Attribute\SetFactory as AttributeSetFactory;
   use Magento\Customer\Api\CustomerMetadataInterface;

   /**
    * @codeCoverageIgnore
    */
   class InstallData implements InstallDataInterface
   {
      /**
      * @var CustomerSetupFactory
      */
      private $customerSetupFactory;

      /**
      * @var AttributeSetFactory
      */
      private $attributeSetFactory;

    /**
     * @var \Magento\Eav\Setup\EavSetupFactory
     */
      private $eavSetupFactory;

      /**
      * InstallData constructor.
      * @param CustomerSetupFactory $customerSetupFactory
      * @param \Magento\Eav\Setup\EavSetupFactory $eavSetupFactory
      * @param \Magento\Eav\Model\Config $eavConfig
      * @param AttributeSetFactory $attributeSetFactory
      */
      public function __construct(
         CustomerSetupFactory $customerSetupFactory,
         \Magento\Eav\Setup\EavSetupFactory $eavSetupFactory,
         \Magento\Eav\Model\Config $eavConfig,
         AttributeSetFactory $attributeSetFactory
      ) {
            $this->customerSetupFactory = $customerSetupFactory;
            $this->eavSetupFactory = $eavSetupFactory;
            $this->eavConfig = $eavConfig;
            $this->attributeSetFactory = $attributeSetFactory;
        }

     /**
      * @param ModuleDataSetupInterface $setup
      * @param ModuleContextInterface $context
      */
      public function install(ModuleDataSetupInterface $setup,
         ModuleContextInterface $context) {

         echo "\n\n********** RUNNING INSTALL DATA (MAGENTOSTACKEXCHANGE_SAMPLE) **********\n";

         $installer = $setup;

         $installer->startSetup();

         echo "\n********** SETUP STARTED (MAGENTOSTACKEXCHANGE_SAMPLE) **********\n";

         try {

                /** @var CustomerSetup $customerSetup */
                $customerSetup =
                   $this->customerSetupFactory
                      ->create(['setup' => $setup]);

                $eavSetup = $this->eavSetupFactory
                   ->create(['setup' => $setup]);

                $customerEntity = $customerSetup
                   ->getEavConfig()->getEntityType('customer');

                $attributeSetId = $customerEntity
                   ->getDefaultAttributeSetId();

                $attributeSet = $this->attributeSetFactory->create();

                $attributeGroupId = $attributeSet
                   ->getDefaultGroupId($attributeSetId);

                // job_title for Customer

                echo "\n********** CREATING JOB_TITLE ATTR FOR CUSTOMER (MAGENTOSTACKEXCHANGE_SAMPLE) **********";

                $eavSetup->addAttribute(
                Customer::ENTITY,
                'job_title',
                [
                   'type'         => 'varchar',
                   'label'        => 'Job Title',
                   'input'        => 'text',
                   'required'     => true,
                   'visible'      => true,
                   'user_defined' => false,
                   'position'     => 999,
                   'system'       => 0,
                ]
             );

                $eavSetup->addAttributeToSet(
                   CustomerMetadataInterface::ENTITY_TYPE_CUSTOMER,
                   CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
                   null,
                   'job_title');

                $customerSetup->getEavConfig()
                   ->getAttribute(Customer::ENTITY, 'job_title')
                      ->addData([
                         'attribute_set_id' => $attributeSetId,
                         'attribute_group_id' => $attributeGroupId,

                         'used_in_forms' =>
                            ['adminhtml_customer',
                             'customer_account_create']

                ])->save();

                echo "\n********** JOB_TITLE ATTR FOR CUSTOMER CREATED SUCCESFULLY (MAGENTOSTACKEXCHANGE_SAMPLE) **********\n";

                // Sent Email for Customer

                echo "\n********** CREATING SENT_EMAIL ATTR FOR CUSTOMER (MAGENTOSTACKEXCHANGE_SAMPLE) **********";

                $customerSetup->addAttribute(
                Customer::ENTITY,
                'sent_email',
                [
                   'type' => 'int',
                   'label' => 'Sent Email',
                   'input' => 'boolean',
                   'source' => '',
                   'required' => true,
                   'visible' => false,
                   'position' => 333,
                   'system' => false,
                   'backend' => '',
                   'default' => 0
                ]
                );

                $eavSetup->addAttributeToSet(
                   CustomerMetadataInterface::ENTITY_TYPE_CUSTOMER,
                   CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
                   null,
                  'sent_email');

                $customerSetup->getEavConfig()
                   ->getAttribute(Customer::ENTITY,'sent_email')
                      ->addData([
                         'attribute_set_id' => $attributeSetId,
                         'attribute_group_id' => $attributeGroupId,
                         'used_in_forms' => ['adminhtml_customer'],
                      ])->save();

                echo "\n********** SENT_EMAIL ATTR FOR CUSTOMER CREATED SUCCESFULLY (MAGENTOSTACKEXCHANGE_SAMPLE) **********\n";

            } catch (Exception $ex) {

                echo "\n********** ERROR: LOGGING EXCEPTION (MAGENTOSTACKEXCHANGE_SAMPLE) **********\n";

                error_log('MAGENTOSTACKEXCHANGE_SAMPLE MODULE EXCEPTION: '
                   . $ex->getMessage());
            }
            finally{

               echo "\n********** EXITING INSTALL DATA (MAGENTOSTACKEXCHANGE_SAMPLE) **********\n";

               $installer->endSetup();

               echo "\n********** INSTALL DATA FINISHED (MAGENTOSTACKEXCHANGE_SAMPLE) **********\n\n";
         }
      }
   }

magentostackexchange\Sample\Setup\InstallSchema.php
   <?php

   namespace Magentostackexchange\Sample\Setup;

   use Exception;
   use Magento\Framework\DB\Ddl\Table;
   use Magento\Framework\Setup\InstallSchemaInterface;
   use Magento\Framework\Setup\SchemaSetupInterface;
   use Magento\Framework\Setup\ModuleContextInterface;

   /**
    * Class InstallSchema
    */
   class InstallSchema implements InstallSchemaInterface
   {
      /**
      * @param SchemaSetupInterface $setup
      * @param ModuleContextInterface $context
      */
      public function install(SchemaSetupInterface $setup,
            ModuleContextInterface $context)
      {
         echo "\n\n********** RUNNING INSTALL SCHEMA  (MAGENTOSTACKEXCHANGE_SAMPLE) **********\n";

         $setup->startSetup();

         try {

            echo "\n********** SETUP STARTED (MAGENTOSTACKEXCHANGE_SAMPLE) **********\n";

            // Used in UpgradeSchema.php
            // if (version_compare($context->getVersion(), '1.0.1') < 0) {

            // sent_email

            echo "\n********** ADDING COLUMN SENT_EMAIL TO CUSTOMER  (MAGENTOSTACKEXCHANGE_SAMPLE) **********";

            $setup->getConnection()->addColumn(
               $setup->getTable('customer_entity'),
                  'sent_email',
                  [
                     'type' => Table::TYPE_INTEGER,
                     'nullable' => true,
                     'comment' => 'Sent email'
                  ]
            );

            echo "\n********** COLUMN SENT_EMAIL ADDED SUCCESFULLY TO CUSTOMER (MAGENTOSTACKEXCHANGE_SAMPLE) **********\n";

         } catch (Exception $ex) {

            echo "\n********** ERROR: LOGGING EXCEPTION (MAGENTOSTACKEXCHANGE_SAMPLE) **********\n\n";

            error_log('MAGENTOSTACKEXCHANGE_SAMPLE MODULE EXCEPTION: '
               . $ex->getMessage());

         }

         // }

         echo "\n********** INSTALL SCHEMA FINISHED (MAGENTOSTACKEXCHANGE_SAMPLE) **********\n\n";
     }
   }

magentostackexchange\Sample\ registration.php
   <?php

   \Magento\Framework\Component\ComponentRegistrar::register(
      \Magento\Framework\Component\ComponentRegistrar::MODULE,
      'Magentostackexchange_Sample',
      __DIR__
   );

Tip: use Mage2Gen to develop the basics of your Magento 2 Modules
https://mage2gen.com/
It is possible to create Customer and other entity attributes through an easy interface.
You can generate modules for Magento 2.2 and 2.3:
In Modules generated for version 2.3, custom attribute definitions include partial assignment to the entity attribute set/group


text:
Q: Circular Reference of MessageTypes for MessageField In two of my message classes, I have two MessageFields that references each other. The server won't run this way, and in the meantime I've commented out one of the properties until I find a solution. Is there a Python solution to this problem?
class ChoiceMessage(messages.Message):

    code = messages.StringField(1, required=True)
    order = messages.IntegerField(2, required=True)
    text = messages.StringField(3, required=True)
    image = messages.EnumField(Image, 4)
    sub_question = messages.MessageField(QuestionMessage, 5)

class QuestionMessage(messages.Message):

    code = messages.StringField(1, required=True)
    type = messages.EnumField(Type, 2, required=True)
    order = messages.IntegerField(3, required=True)
    text = messages.StringField(4, required=True)
    choices = messages.MessageField(ChoiceMessage, 5, repeated=True)


text:
Q: How to generate tuple for variadic templates children? In brief : how to create variadic tuple from given types's child?
In code below there is erroneous type children in get_children call. The goal is to receive tuple with Child derived from given elements.
template<typename T>
class Elem{
public:
    T e;
    class Child{ public: T c; };

    Child child() { return Child{ .c = e}; };
};

template <typename... T>
class Collection{
public:
    using arr = std::tuple<T...>;
    arr elems;

    using children = std::tuple<T...::Child>;  /// **** HERE IS ERROR ***

    auto get_children(){
        children res;

        get_child<sizeof...(T)-1>( res );
        return res;
    }

private:
    template< size_t Num >
    auto get_child( children &res ){
        std::get<Num>(res) = std::get<Num>(elems).child();
        get_child<Num-1>(res);
    }

    template<>
    auto get_child<0>( children &res ){
        std::get<0>(res) = std::get<0>(elems).child();
    }
};

Thanks in advance!

A: Because you tagged c++17, use apply:
#include <iostream>
#include <tuple>
#include <boost/type_index.hpp>

template<typename T>
class Elem{
public:
    T e;
    class Child{ public: T c; };

    Child child() { return Child{ .c = e}; };
};

template <typename... T>
class Collection{
public:

    using arr = std::tuple<T...>;
    arr elems;

    auto get_children(){
        return std::apply( [](auto&&... e){ return std::make_tuple(  e.child()... ); } , elems);
    }

private:
};

int main()
{
    Collection<Elem<int>,Elem<char>,Elem<float>> c;
    auto t = c.get_children();
    std::cout << boost::typeindex::type_id_with_cvr<decltype(t)>().pretty_name() << std::endl;
     // std::tuple<Elem<int>::Child, Elem<char>::Child, Elem<float>::Child>
}

Demo

A: What about
using children = std::tuple<typename T::Child...>;

?
I mean... the single type is T::Child so, to repeat the types, you have to place the ellipsis (...) after the type, so T::Child....
But, given a generic type T, T::Child could be a type but also a member or a method. So you need typename before to inform the compiler that the following T::Child is a type and not a member or other.


text:
Q: Android / Java - How can I find the row in which a spinner is contained in a listView I have a listView where each row contains a textView and a Spinner. I can populate both and I can select from the Spinner with no problem. When the user selects from the spinner I can read the selection using onItemSelected().
My problem is that I can't figure out how to identify which row within the listView was selected.
I've tried using a setTag() and setId(), but can't get either of them to give me what I need.
I also tried placing a transparent button over the row and used an onClickListener, but the button obscures the spinner so you don't actually activate the spinner.
Below is my code. I'd be grateful for any help or pointers in the right direction.
I've viewed dozens of related posts on SO, but can't find one which actually answers this problem. Apologies if I've missed it.
Thanks
Code for getView() in adapter.
public class AdapterSelectEventPayment extends BaseAdapter {

    private ArrayList<String> mSpinnerItems;
    private ArrayList<String> mDataSource;

    private Context mContext;
    private AdapterView.OnItemSelectedListener mSpinnerItemSelectedListener;

    public AdapterSelectEventPayment(ArrayList<String> data, ArrayList<String> spinnerItems, Context context) {
        mDataSource = data;
        mContext = context;
        mSpinnerItems = spinnerItems;
    }

    @Override
    public int getCount() {
        return mDataSource.size();
    }

    @Override
    public Object getItem(int position) {
        return mDataSource.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;
        if (view == null) {
            LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(R.layout.select_event_charge_items, null);
        }

        TextView textView = (TextView) view.findViewById(R.id.row_item_textview);
        Spinner spinner = (Spinner) view.findViewById(R.id.row_item_spinner);

        textView.setText(mDataSource.get(position));
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_spinner_dropdown_item, mSpinnerItems);
        spinner.setAdapter(adapter);
        spinner.setTag(position);

        spinner.setOnItemSelectedListener(mSpinnerItemSelectedListener);

        return view;
    }

    public void setOnSpinnerItemSelectedListener(AdapterView.OnItemSelectedListener listener){
        this.mSpinnerItemSelectedListener = listener;
    }

}

Code in Main Activity
private void sortArrayList() {

            AdapterSelectEventPayment adapter = new AdapterSelectEventPayment(participants, chargeArray, this);

            adapter.setOnSpinnerItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
                    System.out.println("The spinner has been spun... and position is " + position + " and the id = " + id);
                    System.out.println("Tag is " + selectedItemView.getTag());
                }

                @Override
                public void onNothingSelected(AdapterView<?> parentView) {
                    System.out.println("The spinner has NOT been spun...");
                }
            });

            lvSpinner.setAdapter(adapter);
    }

A: I recommend you create an interface that calls you back with all the relevant information from the Spinner selection + the position of the item clicked
interface ListSpinnerListener() {
    void onSpinnerItemSelected(int rowPos, int selectedItemPos, ...);
}

that your Activity could assign the way your assigning the AdapterView.OnItemSelectedListener, and instead utilize that listener directly inside of you getView() method
Adapter:
private ListSpinnerListener listSpinnerListener;

...

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View view = convertView;
    if (view == null) {
        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(R.layout.select_event_charge_items, null);
    }

    TextView textView = (TextView) view.findViewById(R.id.row_item_textview);
    Spinner spinner = (Spinner) view.findViewById(R.id.row_item_spinner);

    textView.setText(mDataSource.get(position));
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_spinner_dropdown_item, mSpinnerItems);
    spinner.setAdapter(adapter);
    spinner.setTag(position);

    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int itemPosition, long id) {
            System.out.println("The spinner has been spun... and position is " + position + " and the id = " + id);
            System.out.println("Tag is " + selectedItemView.getTag());
            listSpinnerListener.onSpinnerItemSelectedListener(position, itemPosition, ...);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parentView) {
            System.out.println("The spinner has NOT been spun...");
        }
    });

    return view;
}

That way you make sure you get all of the relevant information you need all the time thru a simple interface and without having to hack your way into the answer thru tags and whatnot.

A: Instead of calling getTag on selectedItemView call it on  parentView


text:
Q: Is there an algorithm to check whether a subset generates a group? I'm new to abstract algebra, so recently, I came up with a curious question: Given a group $G$ and a subset $S$ of $G$, is there a general algorithm to decide whether $\langle S \rangle = G$?
A special case which I find interesting is when $G = S_n$ (finite symmetric groups), can we still come up with such algorithm to decide this problem? If possible, is the algorithm efficient (i.e in polynomial time)?
(I think if the search space $G$ is finite, I might be able to come up with an exponential time brute force algorithm which takes $g_1, g_2 \in S$ and put $g_1g_2, g_2g_1$ back to $S$ repeatedly until there is no more new elements; not sure though if this is correct.)
A concrete formulation of this question is more like: "Does the problem of checking whether $S$ generates $G$ in P, EXP, or even decidable or not?" for $G = S_n$, for finite $G$, and for general $G$.

A: In the Cayley (multiplication) table model, this problem reduces to membership testing (Cayley Group Membership, or CGM).
Instance: Let $G$ be a finite group given by its multiplication table. Let $S \subseteq G$, and let $x \in G$.
Decision: Is $x \in \langle S \rangle$?
It is known that CGM belongs to $\textsf{L}$. We may use a logspace transducer to write down the Cayley graph $\text{Cay}(G, S)$. We then apply Reingold's logspace pathfinding algorithm to decide if there is a path from the identity element of $G$ to $x$.
To test whether $G = \langle S \rangle$, we apply the above algorithm for each $x \in G$.
In certain cases, we can achieve alternate parallel bounds (uniform $\textsf{AC}$ circuits of depth $\text{poly } \log \log |G|$). See: https://www.sciencedirect.com/science/article/pii/S0022000001917647
Edit: Even in the permutation group setting, membership testing is in $\textsf{NC}$ (https://ix.cs.uoregon.edu/~luks/NC.pdf). If I remember correctly from the last time I did the analysis, at most $O(\log m)$ iterations suffice (where $m$ is the number of generators- i.e., the size of the input), and each iteration is $\textsf{AC}^{1}$-computable. This gives us a bound of $\textsf{AC}^{2}$. Multiplying permutations is $\textsf{FL}$-complete ($\textsf{FL}$ is the class of logspace-computable functions, as opposed to decision problems); see Cook--McKenzie (https://www.cs.utoronto.ca/~sacook/homepage/cook_mckenzie.pdf). So we have a lower bound on how much better we can do.
This technique is still theoretical. I would be surprised if it led to efficient practical implementations.

A: Good question! The answer depends delicately on how you are given $G$; for computational questions about groups "given a group $G$" is subtle. If $G$ is given by a finite presentation then this problem is already undecidable if $S$ is empty; that is, it's undecidable whether a finite presentation presents the trivial group.
More generally we have the following theorem analogous to Rice's theorem for finite presentations of groups:

A property $\mathcal{P}$ of finitely presentable groups is Markov if

*

*There exists $G_+ \in \mathcal{P}$ (a positive witness).

*There exists a finitely presented group $G_-$ (a negative witness) such that if $G_- \leq G$, then $G \notin \mathcal{P}$.
(Our sources for this post are again Notes of Gilbert Baumslag and a survey by Chuck Miller.)

Theorem (Adyan–Rabin 1957/58). If a property $\mathcal{P}$ of finitely presented groups is Markov, then there is no algorithm to decide $\mathcal{P}$ among all finitely presented groups.

Things are probably better for $G$ finite; I think the Todd-Coxeter algorithm might do it but I haven't checked the details carefully. I don't know what its runtime is. "Polynomial time" is a bit ambiguous here because it's not clear what parameter we want a polynomial in.
Reading about the unsolvability of the word problem might also be useful context.