Left arm Leg Spinner - A term not used. Why?

Question: Why is not a left arm bowler who turns the ball away from left-handed batsman not called a left arm leg spinner, just like the right arm leg spinner? A left arm bowler who turns the ball into the left hand batsman is called a left arm off break bowler just like the right arm off spinner.
I'd also be interested in the origin of the name "chinaman".
Comment: You can check [this article as well](http://www.espncricinfo.com/magazine/content/story/310734.html).
Comment: Does [this](http://sports.stackexchange.com/questions/1601/why-are-left-arm-spinners-called-differently?rq=1) ask the same question you're asking?
Comment: @edmastermind29 : Its only a part of my question. And i honestly doesn't know which of the 2 was asked first.
Answer: Left arm bowlers who turn the ball away from a left hand batsman or into a right hand batsman are called leg spinners.
This is how the ball will spin after it pitches.

But the time, the term Left-arm unorthodox spinners or Chinaman has become popular and is basically the norm now. However, it is not incorrect to use the term left arm leg spinners as few cricket writers still use this term.
We do not hear much of this term as there are very few crickets who fall under this category. The most famous ones being South African, Paul Adams and Australian, Brad Hogg.
Wikipedia quotes the origin of the term chinaman as below:

The name has its origins in a Test match played between the West Indies and England at Old Trafford, Manchester, in the year 1933. Elliss "Puss" Achong, a player of Chinese origin, was a left-arm orthodox spinner, playing for the West Indies at the time. According to folklore, Achong is said to have had Walter Robins stumped off a surprise delivery that spun into the right-hander from outside the off stump. As he walked back to the pavilion, Robins said to the umpire, "fancy being done by a bloody Chinaman!", leading to the popularity of the term in England, and subsequently, in the rest of the world.


simplify if-statement in Javascript

Question: $scope.vergleich = function () {
    if ($scope.relrechtsform.indexOf(dataService.dic.alt.rechtsformKanlei || dataService.dic.neu.rechtsformKanlei ) !== -1) {
        return true
    } else {
        return false;                   }
    }
}

I am currently student and intelliJ tells me I have to simplify this if-statement but I have no idea how. Maybe somebody can help me.
Comment: You don't need the if just return the condition.
Comment: IntelliJ usually offers to simplify itself, by clicking on the light bulb near the gutter!
Comment: Why is there a `||` inside `indexOf`? Just to be clear, it will check if the first [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) value of the 2 expressions exists in `relrechtsform`. It will NOT check if either of the values exists in `relrechtsform`.
Comment: It would have been a good idea to write with your own words what that condition was supposed to check. Just the user is gone as I see.
Answer: The simplification is probably that, if condition is a boolean, :
if (condition) {
  return true;
}
else {
  return false;
}

is equivalent to
return condition;

However there also seems to be a logical error in your test.
$scope.relrechtsform.indexOf(dataService.dic.alt.rechtsformKanlei ||
                        dataService.dic.neu.rechtsformKanlei ) !== -1

Does not mean the same thing as :
$scope.relrechtsform.indexOf(dataService.dic.alt.rechtsformKanlei) !== -1 ||
$scope.relrechtsform.indexOf(dataService.dic.neu.rechtsformKanlei) !== -1

Comment: The second part of your answer [is wrong](https://jsfiddle.net/ulysse_bn/7Lnrv45u/3/) because of how `||` reacts to truthy values.
Comment: @UlysseBN, well, actually, it's not equivalent :

`const a = [false, "blah"]
console.log(a.includes(1 || "blah") === (a.includes(1) || a.includes("blah")))`
Comment: That is exactly what my example is about ^^.
Comment: @UlysseBN mmm I forgot to write "Not" in my answer, -_-
Answer: Maybe you're looking for this:
 $scope.vergleich = function () {
  return $scope.relrechtsform.indexOf(dataService.dic.alt.rechtsformKanlei || dataService.dic.neu.rechtsformKanlei ) !== -1;
};

Answer: Tân's version is a correct answer to your question. However, with recent JavaScript you can simplify even more thanks to array.includes:
$scope.vergleich = () =>
    $scope.relrechtsform.includes(dataService.dic.alt.rechtsformKanlei || dataService.dic.neu.rechtsformKanlei)

Answer: You can just use your condition instead of using IF else statement -:
$scope.vergleich = function () {
    return ($scope.relrechtsform.indexOf(dataService.dic.alt.rechtsformKanlei ||
                        dataService.dic.neu.rechtsformKanlei ) !== -1);
};

simplify if-statement in Javascript


how to find the number of a specific data in SQL(MySQL)

Question: Suppose I have a data set called table which has 7 data such as [a,b,c,d,e,f,g]. I want to write a query to find out the number of a specific data. For example,I want to find 'd'.The sql should give me a number '3'. If I want to find 'g'.The sql should give me a number '6'.
Please help.Thank you.
Comment: What RDBMS you are using? SQL Server, MySQL, or what?
Comment: This is a very poor question. To improve it: post a real table with create table. Also specify a database brand or just say 'agnostic sql'. Take in mind than the answer is different for each database branch. Also explain what did you tried.
Comment: So the array is stored in db?
Comment: May be this will help you [https://stackoverflow.com/questions/8738785/how-to-find-row-number-of-a-record](https://stackoverflow.com/questions/8738785/how-to-find-row-number-of-a-record)
Comment: thank you siva.That's is useful and help me a lot.
Comment: @siva, yes, this is nice explained. Michael, you can learn how to make question here: [How to find row number of a record?](https://stackoverflow.com/questions/8738785/how-to-find-row-number-of-a-record)
Answer: Since you are using Mysql which doesn't support ranking functions, then you can do this:
<code>SELECT col, rank -1 as rownumber
FROM
(
  SELECT col,
         @rownum := (@rownum + 1) AS rank
    FROM Table1 t,
         (SELECT @rownum := 0) r
) AS t
</code>
mysql demo
This will give you:
<code>| col | RowNumber |
|-----|-----------|
|   a |         0 |
|   b |         1 |
|   c |         2 |
|   d |         3 |
|   e |         4 |
|   f |         5 |
|   g |         6 |
</code>
Then you can just filter on the the value you want.
Comment: Thank you Damien.
Comment: @Michael - You're welcome, please accept the answer if you found it helpful, thanks.


If $ -3\left(x-\lfloor x \rfloor \right)^2+2(x-\lfloor x \rfloor )+a^2=0$ has no integral solution, then $a$ is

Question: if $a$ is real number and $\displaystyle -3\left(x-\lfloor x \rfloor \right)^2+2(x-\lfloor x \rfloor )+a^2=0$.has no real integral solution,
Then all possible values of $a$ lie in the interval..
(where $\lfloor x \rfloor $ means floor function of $x$)
$\bf{My\; Solution::}$ Let $x-\lfloor x \rfloor  = \{x\}= y$, where $ 0 \leq \{x\}<1\Rightarrow 0\leq y<1$. Then equation..
$$\Rightarrow -3y^2+2y+a^2 = 0\Rightarrow 3y^2-2y-a^2 = 0$$
$$\displaystyle \Rightarrow y = \frac{2\pm \sqrt{4+12a^2}}{6} = \frac{1\pm \sqrt{1+3a^2}}{3}$$
Now If equation has no real solution , Then $y<0 \;\; \cup \;\; y\geq 1$.
So $$\Rightarrow \frac{1\pm \sqrt{1+3a^2}}{3}<0\;\; \cup \;\; \frac{1\pm \sqrt{1+3a^2}}{3}\geq 1$$
Now how can I calculate value of $a,$ after that
Help me
Thanks
Comment: See also: [If $a\in R$ and the equation $-3(x-\lfloor x \rfloor)^2+2(x-\lfloor x \rfloor)+a^2=0$ has no integral solution,then all possible values of $a$](https://math.stackexchange.com/q/1691347)
Answer: Since  $$\frac{1- \sqrt{1+3a^2}}{3}<0,\quad \forall a\neq 0$$
then you only need to find $a$ such that
$$\frac{1+\sqrt{1+3a^2}}{3}>1\iff \sqrt{1+3a^2}>2\iff a^2\ge 1\iff a\le -1 \vee a\ge 1.$$
So, your equation has no solutions for $a\le -1 \vee a\ge 1$.


Simple key => value array with QueryInterface

Question: I'm looking at building a simple key => value array with a certain type of node I have in order to generate a select list in a form.
The thing is that I have thousands of nodes of this type and the page takes forever to load with the current code I have.
Is there a way to load only certain fields using the QueryInterface in order to cut on loading times? Is there a more efficient way to do this?
$query = \Drupal::entityQuery('node')
  ->condition('type', 'product')
  ->condition('status', 1)
;

$nids = $query->execute();

$nodeStorage = \Drupal::entityTypeManager()->getStorage('node');

// Load multiple nodes
$nodes = $nodeStorage->loadMultiple($nids);

$list = array();

foreach ($nodes as $node) {
  $list[$node->field_code->value] = $node->title->value . ' (' . $node->field_code->value . ')';
}

Comment: Even if you optimize the query, adding thousands of options to a select is really a bad idea. Entity autocomplete fields are *really* easy to use in d8. See https://api.drupal.org/api/drupal/core%21modules%21taxonomy%21src%21Plugin%21views%21filter%21TaxonomyIndexTid.php/function/TaxonomyIndexTid%3A%3AvalueForm/8 for example. just specifiy #target_type and use bundle selection settings to limit it to your node type. And as a result, you get the selected node. it does also validates.
Comment: entity query will give you only nids or whole nodes. So in order to get nid and title you have to use basic query. But if you have a lot of nodes I would suggest entity reference field instead.
Answer: The only way I know to do this is similar to what @Ivan Jaros mentions in the comment above. That is to use a Database service instead of EntityQuery service. There is a handy method on the query Statement, fetchAllKeyed, that I use all of the time in Drupal 7.
$database = \Drupal::service('database');
$query = $database->select('node', 'n');
$query->join('node_field_data', 'nfd', 'n.nid = n.nfd.nid');
$query
  ->fields('n', ['nid']),
  ->fields('nfd', ['title'])
  ->condition('n.type', 'product')
  ->condition('nfd.status', 1)
  ->execute()
  ->fetchAllKeyed();

Unfortunately this has drawbacks:

Multilingual - you need to do this manually in the query above.
Probably not going to work well with non-SQL drivers.
Might run into performance issues still because the data is not cached.


Can Pandas DataFrame.sort_index() performance be improved on sorted data?

Question: Is there any way to improve the performance of DataFrame.sort_index() when the data is already sorted by the columns that are used for the index? On a dataset with 40 mio records, sort_index() takes 3.25 mins for me, independent on whether the data is sorted already or not.
If there is no intended way high level way to do it, is there maybe a low level way of changing the DataFrame state to sorted by index without actually sorting it?
Answer: If I understood you correctly, you can verify that the index is sorted prior to actually sorting it with DataFrame.index.is_monotonic_increasing, which should be faster. So you could do something like:
if not df.index.is_monotonic_increasing:
    df = df.sort_index()

Comment: Ha, thank you, after trying I figured that `is_lexsorted()` is aware of the sort state after reading the data. I somehow assumed that it wouldn't be, because if it is I would have expected `sort_index()` to be aware of it and not do anything on a pre-sorted index.


Granting Access to Reporting Services to create custom Roles

Question: See image.
How does a dba go about granting access to the screen shown.
This is for a generic user using their AD credentials to access the 'Reporting Services' on a particular server. This is so that the generic user is able to create new 'roles' for SSRS. Currently only the administrator has access.
Answer: Looks to be assigned to the System Administrator System Role by default:
Connect to a Report Server in Management Studio.

So adding users/groups to that role should allow them to connect and create new roles. They'll be admins on the Report Server itself, but at least not on the underlying server.
Comment: I spun up a VM to test this out; with a non-administrator user I could log into Reporting Services but couldn't create roles. With System Administrator I could both log in and create roles. So in a simple test it seemed to make a difference, but I understand that there's not necessarily a comparison between an artifical environment and a live implementation. Sorry it didn't help.
Comment: So if my dba put my AD login in the box above and ticked the System Administrator box, I would be able to log in as myself in the window attached to my question?
Comment: Yes. By default the privilege is assigned to the BUILTIN\Administrators group, i.e. server admins only. Getting yourself assigned as above will give you certain admin privileges over Reporting Services but not the server itself - better for security that way.
Comment: Did you have any luck resolving this issue?
Comment: My AD login does have 'System Administrator' however I can not log into reporting services through the window in my question still.
Answer: The image you showed belongs to connection to SQL Server which manage sql databases.
In most cases the reporting services installed on the SQL SERVER but it not mandatory. The reporting services server can be a dedicated one apart of the SQL Server.
The image you shown is the connection window to SQL SERVER
There Two option to perform a login:

Windows Authentication - (Uses the loged on user to the machine) A DBA needs to allow this user or a group which this user is a memeber in to connect the SQL server. In addition he need to configure which database is available to him.
The second option is to set a SQL User and to give him permission to manage databases.

Setup a login on SQL SERVER
The Reporting services has Report manager URL, which allows to manage report existing or add new reports ect..
In order to allow users to access the URL, you need to allow a specific user or a group to access the report server manager
Granting permission to the report manager
How to grant YOU access to a database

Open SQL Management Studio
Your DBA should login with his permission (sa/admin permission)
Expand "Security" Tab
Right click on "Login" folder and choose "New Login"
Click on the "Search" button next to the "login name:" field
In the text area search for you AD username
Click "Ok"
Choose desire master database
On the left panel choose the "User Mapping" option
Choose desire Database on the upper section
Select proper permission on the bottom section for example "db_owner"

After this you can create a data source with Yours user name
Does it what have you looked for?
Comment: OP is looking to eventually create custom Roles in SSRS - this is performed through Management Studio - see http://msdn.microsoft.com/en-us/library/ms156293.aspx. You can see in the screen shot Management Studio is explicitly connecting to a Reporting Services instance. The question is what permission is required to be able to connect this way.
Comment: I understand that a user can log in using their AD credentials or a user name and password that does have access. My question is, how does MY dba grant ME access, as currently I cannot log in using my AD credentials and my dba has not been able to grant me access. I need to advise him where he needs to go....
Comment: I have added the steps for adding user to connect a database, let me know if that what you looked for.


dynamically push object into nested array based on key,value pair condition

Question: I have the following object:
{type=stuff, name=blablabla, variableId=x, fingerprint=xxxx, containerId=xxxx, accountId=xxxx, workspaceId=xxx, path=accounts/xxxx/containers/xxxx/workspaces/xx/variables/x, parentFolderId=x, parameter=[{value=auto, type=template, key=xxxxx}, {type=boolean, key=asdasdf, value=false}, {value=false, type=boolean, key=adasdasd}, {type=boolean, value=false, key=asdasdasd}, {type=list, key=fieldsToSet, list=[{map=[{value=asdasdas, type=template, key=asdasdas}, {value=asdasdas, type=template, key=value}], type=map}, {type=map, map=[{type=template, value=page, key=fieldName}, {type=template, key=value, value=asdasdasd}]}]}, {value=false, type=boolean, key=asdasd}, {type=boolean, value=false, key=asdasdasd}, {value=false, type=boolean, key=adasdasd}, {key=dimension, type=list, list=[{type=map, map=[{value=2, key=index, type=template}, {value=asdasd, type=template, key=dimension}]}, {type=map, map=[{value=3, type=template, key=index}, {value=asdasdasd, type=template, key=dimension}]}, {map=[{type=template, value=4, key=index}, {key=dimension, type=template, value=asdasdasd / asdasdasd}], type=map}, {map=[{type=template, value=5, key=index}, {value=asdasd, type=template, key=dimension}], type=map}, {type=map, map=[{value=6, type=template, key=index}, {key=dimension, type=template, value=asdasdasd}]}, {map=[{type=template, key=index, value=7}, {value=asdasd, type=template, key=dimension}], type=map}, {type=map, map=[{key=index, value=8, type=template}, {value=asdasdasd, key=dimension, type=template}]}]}, {key=enableEcommerce, type=boolean, value=false}, {value=asdasdasd, type=template, key=asdasdasd}], tagManagerUrl=https://blabla.com/#/asdasd/accounts/asdasd/containers/xxxxx/workspaces/xxxx/variables/x?apiLink=variable}

I want to modify it and add this object {type=map, map=[{key=fieldName, value=cookieExpires, type=template}, {key=value, value=33696000, type=template}]} into the nested object with the key fieldsToSet.
So far I've tried something like this but it doesn't work:
element.parameter.filter(obj => { return obj.key === "fieldsToSet" }).push(newObject);

I need something dynamic as the number of object and arrays always change.
Comment: Assign it to in list array variable. And run loop and in that loop use if condition for your require array format and store it in dictionary variable
Answer: I believe your goal as follows.

You want to add newObject to element.parameter[] using Google Apps Script.

Modification points:

In your script, element.parameter.filter(obj => { return obj.key === "fieldsToSet" }) returns the object including obj.key === "fieldsToSet". By this, when push(newObject) is used for this, newObject is added to the retrieved element. I think that this might be the reason of your issue.

In this answer, I would like to propose the following modified script. In this sample script, I converted your value to the JSON object because I thought that your sample value might be directly obtained from the object with Logger.log.
Modified script:

var element = {"type":"stuff","name":"blablabla","variableId":"x","fingerprint":"xxxx","containerId":"xxxx","accountId":"xxxx","workspaceId":"xxx","path":"accounts/xxxx/containers/xxxx/workspaces/xx/variables/x","parentFolderId":"x","parameter":[{"value":"auto","type":"template","key":"xxxxx"},{"type":"boolean","key":"asdasdf","value":false},{"value":false,"type":"boolean","key":"adasdasd"},{"type":"boolean","value":false,"key":"asdasdasd"},{"type":"list","key":"fieldsToSet","list":[{"map":[{"value":"asdasdas","type":"template","key":"asdasdas"},{"value":"asdasdas","type":"template","key":"value"}],"type":"map"},{"type":"map","map":[{"type":"template","value":"page","key":"fieldName"},{"type":"template","key":"value","value":"asdasdasd"}]}]},{"value":false,"type":"boolean","key":"asdasd"},{"type":"boolean","value":false,"key":"asdasdasd"},{"value":false,"type":"boolean","key":"adasdasd"},{"key":"dimension","type":"list","list":[{"type":"map","map":[{"value":2,"key":"index","type":"template"},{"value":"asdasd","type":"template","key":"dimension"}]},{"type":"map","map":[{"value":3,"type":"template","key":"index"},{"value":"asdasdasd","type":"template","key":"dimension"}]},{"map":[{"type":"template","value":4,"key":"index"},{"key":"dimension","type":"template","value":"asdasdasd / asdasdasd"}],"type":"map"},{"map":[{"type":"template","value":5,"key":"index"},{"value":"asdasd","type":"template","key":"dimension"}],"type":"map"},{"type":"map","map":[{"value":6,"type":"template","key":"index"},{"key":"dimension","type":"template","value":"asdasdasd"}]},{"map":[{"type":"template","key":"index","value":7},{"value":"asdasd","type":"template","key":"dimension"}],"type":"map"},{"type":"map","map":[{"key":"index","value":8,"type":"template"},{"value":"asdasdasd","key":"dimension","type":"template"}]}]},{"key":"enableEcommerce","type":"boolean","value":false},{"value":"asdasdasd","type":"template","key":"asdasdasd"}],"tagManagerUrl":"https://blabla.com/#/asdasd/accounts/asdasd/containers/xxxxx/workspaces/xxxx/variables/x?apiLink=variable"};

var newObject = {"type":"map","map":[{"key":"fieldName","value":"cookieExpires","type":"template"},{"key":"value","value":33696000,"type":"template"}]};

element.parameter.forEach(({key},_,a) => {
  if (key === "fieldsToSet") {
    a.push(newObject);
  }
});
console.log(element);

Note:

Above sample value of element was converted from your sample value in your question. So when my conversion is not correct, please modify or replcace with your actual value.

For example, when you add newObject to element.parameter[].list[], you can use the following script.
  element.parameter.forEach(obj => {
    if (obj.key === "fieldsToSet") {
      obj.list.push(newObject);
    }
  });

References:

filter()
forEach()


What do those double dots mean (in Trois mouvements de Petrouchka, Stravinsky)

Question: What do those double dots mean ?
Do they apply to the whole chord ? Or just the right hand chord or just the top D ? Does it have a musical meaning or interpretative meaning or both ? How is it different from staccato ?
in Semaine grasse (5th page of the movement, 2nd line or bars 57,58), Trois mouvements de Petrouchka, Stravinsky:

To my knowledge there is only one edition (I do not count localisation as an edition).
In the original, those bars correspond to the 95 or bars 3,4 in the following extract:

The transcription (which is not a transcription, as stated by Stravinsky), has changed the text slightly.
Comment: Oh great, now I'm wondering whether those dots merely emphasize that those are 16th notes in the tremolo, the dots mean that those are all played staccato, or I am supposed to play 2 of each chord in the tremolo in a row (so the tremolo goes A-A-G-G instead of A-G-A-G).
Comment: @Aaron The original and 3 movements do not match since there are many cuts, simplifications, and addendi. It's mm 57,58
Comment: Closely related [question](https://music.stackexchange.com/q/94311/2600) if not even duplicate.
Comment: @guidot - I'd say that's only a closely related question since such dots for a single tremolo beam are a *lot* less confusing than those for a double tremolo.
Comment: @guidot dup for only one part of my questions, the case is more complicated here.
Answer: I think this is a not very good shorthand for
Comment: This works as a transcription of the flute and clarinet parts (remembering to transpose the clarinet). Note that I am not the Peter who answered the question.
Answer: The notation is very ambiguous, but it's most likely that something like this is intended:

This preserves the legato tremolo of the original.
Comment: Do you mean the staccato is only for the D ?
Comment: @Soleil Yes. I think that's the most likely interpretation, and it makes the most musical sense.
Comment: This is probably the best answer given the notation and the orchestral context, but is hell to play.
Comment: @Peter Stravinsky gives a tempo of half-note=69. It's hard enough to play those repeated notes at all, let alone make them staccato.
Comment: @PiedPiper I'd not looked for the metronome mark in the orchestral score (I don't have a copy of the piano version - is it the same?). I take your point.
Answer: The double dots indicate that each chord should be played twice within the tremolo (see below). Stravinsky is attempting to incorporate both the smooth tremolos in the woodwinds with the pizzicato in the violins. Note that the violins play each pitch (chord) twice before changing.
<code>X: 1
T: Petrouchka tremolos
K: F
M: 6/4
L: 1/16
([Acfa]d[Acfa]d) .[Acd].[Acd].[GBd].[GBd] ([Acfa]d[Acfa]d) .[Acd].[Acd].[GBd].[GBd] ([Acfa]d[Acfa]d) .[Acd].[Acd].[GBd].[GBd] |
</code>
Comment: If this is what's intended, then the tremolo marking would be unnecessary.
Comment: Peter's answer comes closer to the original and preserves the tremolo.
Comment: But we have that also without the double dot, isn't it a staccato for each "play" of the chord ?
Comment: @Aaron We seem to have almost coincided with the same answer!
Comment: @Soleil Without the dots, you wouldn't play it so staccato. As a rule of thumb, without the dots each note is about 3/4 the length of the notated value, with the dots it's about 1/2. Adjust to fit the tempo of the piece, the acoustic of the hall, the responsiveness of the piano and the flexibility of your wrist.
Comment: @Peter Yeah, at first I thought we were exactly the same, but then I saw we differ on whether or not to repeat each chord. I think you hit the nail on the head with "not a very good shorthand."
Comment: @Soleil The double dot indicates the repetition of the chord as well as staccato.
Comment: @PiedPiper I think the tremolo is just there for consistency of notation across the passage as well as to clarify the relationship to the original score.
Comment: I don't think it's correct, it would not match the tremolo writing AND the left hand AND the original score.
Comment: @PiedPiper Look at the pizzicato violin in the original score. They repeat each chord. Otherwise there's no need for the double dot.
Comment: @Soleil It corresponds to the violin part in the original score, but as sixteenths instead of eighths to preserver the overall rhythm.
Comment: @Aaron Your proposal does not respect the harmony, the tremolo does as well as the rythm.
Comment: @PiedPiper The violins play eighths, pizzicato. Stravinsky is trying to have it both ways: preserving some of the pizzicato contrast with the smoother tremolos but in a way that makes rhythmic sense.
Comment: @PiedPiper You are 2 bars too much forward, there is no trumpet at sign 95. Aaron is doubling the speed of the violins for some reason. The tremolos are from the clarinets.
Comment: @Soleil How does it not respect the harmony? The harmony is the same either way.
Comment: @Soleil The speed is doubled because the overall feel of the passage is sixteenths. To suddenly switch to eighths would be jarring and would lose the overall feel. It's a compromise between wanting to contrast the smooth and pizz. tremolos while maintaining an overall rhythmic consistency.
Comment: @Aaron Check the harmony of clarinets.
Comment: @Soleil Don't forget this is an arrangement. The trumpet part is the only part playing those staccato sixteenths, and it looks like the arrangement  refers to that a couple of bars earlier.
Answer: To add some "weight" to the answers that say this means each note is played twice, here's an example from a G&S score. You can see they explicitly wrote in the "slash" so you know there are two notes to be played per written flag.
I agree that the OP's example is already pretty crowded, so sticking in the slashes is pretty much redundant with the tremolo markings.


como esperar um metodo terminar para execultar o proximo em angular?

Question: Bom, estou fazendo um curso de Angular, estou tentando entender o conceito de Observables e Promisses, porém estou um pouco confuso, estou utilizando o Firebase para criar uma simples aplicação, onde eu utilizo autenticação por e-mail e senha
e para salvar os demais dados do usuário tenho que utilizar o id desse usuário autenticado e cadastrar no Banco.
Feito isso tenho então que utilizar o método do meu serviço que cria esse usuário e depois utilizar o método que salva os dados.
Seguindo essa ordem tenho que fazer o método de SignUp(email,senha) ser executado primeiro do que o metodo setUserData(User).
> Metodos

SetUserData(user) {
    const itemsRef = this.db.object(`usu/${user.uid}`);
    return itemsRef.set(user);
  }

SignUp(email, password) {
    return this.afAuth.auth.createUserWithEmailAndPassword(email, password)
      .then((result) => {
        this.SendVerificationMail();
        window.alert("BEM VINDO");
      }).catch((error) => {
        window.alert(error.message)
      })
  }

Obs: Os métodos são chamados no componente onde faço o two-way data binding com o formulário utilizando um método 'onSubmit'
Answer: JS é assíncrono, você pode trabalhar com callback pra isso, o primeiro método recebe o segundo método como argumento, após o termino do processamento do primeiro, ele encerra chamando o segundo:
function segundo(login) {
  console.log('segundo');
}

function primeiro(callback) {
  console.log('primeiro');
  callback();
}

primeiro(segundo);

Também rola fazer isso com observable, com promise:

https://developer.mozilla.org/pt-BR/docs/Glossario/Callback_function
https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Promise
https://rxjs-dev.firebaseapp.com/guide/observable
Comment: Muito Obrigado, cara, funcionou aqui, dei um jeitinho e boa, funcionou perfeitamente
Answer: O que você pode fazer é utilizar o subscribe, dentro dele você faz as chamadas. O subscribe vai esperar a função ser executada pra depois executar o que está dentro dele. Segue um link de um tutorial mais fácil de entender:

https://medium.com/tableless/entendendo-rxjs-observable-com-angular-6f607a9a6a00
Comment: Muito obrigado ajudou muito, haha valeu mano !!
Comment: Por nada amigo!


Can I access individual list item during LINQ Join?

Question: I have two lists. I want to join them through LINQ. I hope below code snippet should give the idea, what I am trying to achieve.
var lst = from param in Parameters join rule in parameterMap.MappingRules on param.Name equals rule.CompareLHS(param.Name) where rule.Compare<double>(param.Value.Value) select new { param.Name, param.Value };

Above statement doesn't get compile as I am trying to use 'param' on both sides of 'equals'.
Is there any possibility that I can access 1st list individual item (here param) again while comparing with 2nd list individual item like this(param.Name equals rule.CompareLHS(param.Name))?
Comment: Which part doesn't compile? The Join? The Where, or the Select? Can you give the parts of your classes that are involved in this statement? What is your goal in this statement: you want the combination of all parameters and rules where the name of the paremeter is ...
Answer: You can convert the inner join to a cross join with a condition:
var lst = from param in Parameters
          from rule in parameterMap.MappingRules
          where param.Name == rule.CompareLHS(param.Name)
          where rule.Compare<double>(param.Value.Value)
          select new { param.Name, param.Value };


I fill in all the values on my form and my PHP still returns Undefined Index

Question: I starting to learn PHP and I open my website up in localhost (I am using xampp) I get an undefined index error for every input tag, however, when using the website I make sure to fill everything in so that there is no missing value. Why does it still produce an Undefined Index Error? I've looked through other questions and tried repeating their code but it stil doesn't work.
<form id="myForm" action="test.php">

First Name:

                    <input type="text" class="Level1InputTxt" id="fName"/>

Last Name:

                    <input type="text" class="Level1InputTxt" id="lName"/>

E-Mail:

                    <input type="text" class="Level1InputTxt" id="eMail"/>

Phone Number:

                    <input type="text" class="Level1InputTxt" id="phoneNumber"/>

Street Address:

                    <input type="text" class="Level2InputTxt" id="address"/>

Town:

                    <input type="text" class="Level2InputTxt"  id="town"/>

Zip Code:

                    <input type="text" class="Level2InputTxt"  id="zip"/>

State:

                    <select id="State_Select" class="Select">
                      <option value="NH">New Hampshire</option>
                      <option value="ME">Maine</option>
                      <option value="MA">Massachusetts</option>
                    </select>

Date:

                        <select id="Month_Select" class="Select">
                            <option value="1">January</option>
                            <option value="2">February</option>
                            <option value="3">March</option>
                            <option value="4">April</option>
                            <option value="5">May</option>
                            <option value="6">June</option>
                            <option value="7">July</option>
                            <option value="8">August</option>
                            <option value="9">September</option>
                            <option value="10">October</option>
                            <option value="11">November</option>
                            <option value="12">December</option>
                        </select>
                        <select id="Day_Select" class="Select">
                            <option value="1">1</option>
                            <option value="2">2</option>
                            <option value="3">3</option>
                            <option value="4">4</option>
                            <option value="5">5</option>
                            <option value="6">6</option>
                            <option value="7">7</option>
                            <option value="8">8</option>
                            <option value="9">9</option>
                            <option value="10">10</option>
                            <option value="11">11</option>
                            <option value="12">12</option>
                            <option value="13">13</option>
                            <option value="14">14</option>
                            <option value="15">15</option>
                            <option value="16">16</option>
                            <option value="17">17</option>
                            <option value="18">18</option>
                            <option value="19">19</option>
                            <option value="20">20</option>
                            <option value="21">21</option>
                            <option value="22">22</option>
                            <option value="23">23</option>
                            <option value="24">24</option>
                            <option value="25">25</option>
                            <option value="26">26</option>
                            <option value="27">27</option>
                            <option value="28">28</option>
                            <option value="29">29</option>
                            <option value="30">30</option>
                            <option value="31">31</option>
                        </select>
                        <select id="Year_Select" class="Select">
                        <option value="2017">2017</option>
                      <option value="2018">2018</option>
                      <option value="2019">2019</option>
                        <option value="2020">2020</option>
                        <option value="2021">2021</option>
                    </select>

Number of People:

                    <input type="text" id="NumOfPeople" value="Integer Value Only"/>

Event Type:

                    <input type="text" id="eventType" value="Wedding, Family Reunion, etc..."/>

Inside or Outside:

                    <select id="InOrOut_Select" class="Select">
                        <option value="1">Inside</option>
                      <option value="2">Outside</option>
                    </select>

Requests/Specific Details:

                <textarea id="requests" rows="5" cols="100" style="resize: none;"/></textarea>

                    <input type="submit" id="Submit_Button" onclick="process()" value="Submit"/>

        </form>

<?php
$path = "C:\\Users\\Connor\\Desktop\\Coding\\Rick's Bar Service\\JSON\\Request.json";

$myObj->FName = $_POST['fName'];
$myObj->LName = $_POST['lName'];
$myObj->EMail = $_POST['eMail'];
$myObj->PhoneNumber = $_POST['phoneNumber'];
$myObj->State = $_POST['State_Select'];
$myObj->Town = $_POST['town'];
$myObj->Zip = $_POST['zip'];
$myObj->Address = $_POST['address'];
$myObj->Month = $_POST['Month_Select'];
$myObj->Day = $_POST['Day_Select'];
$myObj->Year = $_POST['Year_Select'];
$myObj->NumOfPeople = $_POST['NumOfPeople'];
$myObj->EventType = $_POST['eventType'];
$myObj->InOrOut = $_POST['InOrOut_Select'];
$myObj->Requests = $_POST['requests'];

$myJSON = json_encode($myObj);

$myfile = fopen($path, "w");
fwrite($myfile, $myJSON);
fclose($myfile);
?>

The errors:
Notice: Undefined index: fName in C:\xampp\htdocs\test.php on line 6

Notice: Undefined index: lName in C:\xampp\htdocs\test.php on line 7

Notice: Undefined index: eMail in C:\xampp\htdocs\test.php on line 8

Notice: Undefined index: phoneNumber in C:\xampp\htdocs\test.php on line 9

Notice: Undefined index: State_Select in C:\xampp\htdocs\test.php on line 10

Notice: Undefined index: town in C:\xampp\htdocs\test.php on line 11

Notice: Undefined index: zip in C:\xampp\htdocs\test.php on line 12

Notice: Undefined index: address in C:\xampp\htdocs\test.php on line 13

Notice: Undefined index: Month_Select in C:\xampp\htdocs\test.php on line 14

Notice: Undefined index: Day_Select in C:\xampp\htdocs\test.php on line 15

Notice: Undefined index: Year_Select in C:\xampp\htdocs\test.php on line 16

Notice: Undefined index: NumOfPeople in C:\xampp\htdocs\test.php on line 17

Notice: Undefined index: eventType in C:\xampp\htdocs\test.php on line 18

Notice: Undefined index: InOrOut_Select in C:\xampp\htdocs\test.php on line 19

Notice: Undefined index: requests in C:\xampp\htdocs\test.php on line 20

Comment: Add `method="POST"` to your `` element.  The default method is `GET`.
Comment: I added method="POST" and still got the error. I also tried using GET instead of POST (I made sure to remove method="POST" from the form)and still got the same answer. Any other thoughts?
Comment: Put method="post" back. All your inputs are missing the name attribute i.e name="fName" etc for each one... The Name attribute is what creates the corresponding $_POST[] index. If you had performed a var_dump($_POST) to debug, you would find it empty...
Answer: Try this ..
Change this line from
<form id="myForm" action="test.php">

to
<form id="myForm" method="POST" action="test.php">

and do these lines from
<?php
$path = "C:\\Users\\Connor\\Desktop\\Coding\\Rick's Bar Service\\JSON\\Request.json";

$myObj->FName = $_POST['fName'];
$myObj->LName = $_POST['lName'];
$myObj->EMail = $_POST['eMail'];
$myObj->PhoneNumber = $_POST['phoneNumber'];
$myObj->State = $_POST['State_Select'];
$myObj->Town = $_POST['town'];
$myObj->Zip = $_POST['zip'];
$myObj->Address = $_POST['address'];
$myObj->Month = $_POST['Month_Select'];
$myObj->Day = $_POST['Day_Select'];
$myObj->Year = $_POST['Year_Select'];
$myObj->NumOfPeople = $_POST['NumOfPeople'];
$myObj->EventType = $_POST['eventType'];
$myObj->InOrOut = $_POST['InOrOut_Select'];
$myObj->Requests = $_POST['requests'];

$myJSON = json_encode($myObj);

$myfile = fopen($path, "w");
fwrite($myfile, $myJSON);
fclose($myfile);

to
<?php

if($_SERVER['REQUEST_METHOD'] == 'POST'){

$path = "C:\\Users\\Connor\\Desktop\\Coding\\Rick's Bar Service\\JSON\\Request.json";

$myObj->FName = $_POST['fName'];
$myObj->LName = $_POST['lName'];
$myObj->EMail = $_POST['eMail'];
$myObj->PhoneNumber = $_POST['phoneNumber'];
$myObj->State = $_POST['State_Select'];
$myObj->Town = $_POST['town'];
$myObj->Zip = $_POST['zip'];
$myObj->Address = $_POST['address'];
$myObj->Month = $_POST['Month_Select'];
$myObj->Day = $_POST['Day_Select'];
$myObj->Year = $_POST['Year_Select'];
$myObj->NumOfPeople = $_POST['NumOfPeople'];
$myObj->EventType = $_POST['eventType'];
$myObj->InOrOut = $_POST['InOrOut_Select'];
$myObj->Requests = $_POST['requests'];

$myJSON = json_encode($myObj);

$myfile = fopen($path, "w");
fwrite($myfile, $myJSON);
fclose($myfile);

}

Thank you .. :)
Answer: You should check first whether really data was posted ( form submitted or not ),
// Check if there's ANY post data at all
// whether posted data
if (!empty($_POST))
{

    // this is a way to get out of undefined index error
    if( isset($_POST['fName']) )
    {
        $myObj->FName = $_POST['fName'];
    }else{
           // firstname doesn't exist
    }

    if( isset($_POST['lName']) )
    {
        $myObj->LName = $_POST['lName'];
    }

    // remaining goes here

}

and in form
<form id="myForm" action="test.php" method="POST">


Laravel - Getting all records not just the first and putting together?

Question: I have tried asking this question to everyone but nobody can see why I am trying to do it or why its not working but I will try my best to explain it properly this time.
I have a simple government page on my website that shows 3 panels in bootstrap with Higher Government, Senior Ministers and Junior Ministers. Inside each of them panels it shows a list of accounts assigned to that government rank.
Here is my government.blade.php:
@include('frontend.header')

  The Monarch/PM

  Seniors

  Juniors

                            higher gov here

                            senior gov here

                            @foreach ($juniorGovernment as $governmentMember)
                                {{ $governmentMember->user_id }}

                            @endforeach

@include('frontend.footer')

Here is my controller for displaying the page:
<?php

namespace App\Http\Controllers\Frontend\User;

use Auth;
use Cache;
use Illuminate\Http\Request;
use App\Database\Website\User\Roleplay;
use App\Database\Website\Roleplay\GovernmentRole;
use App\Database\Website\Roleplay\Life\LifeEvents;

class GovernmentController
{
    public function getView()
    {
        $higherGovernment = Cache::remember('government.higher_government', 1, function() {
            return GovernmentRole::where('government_type', 'higher_government')->first()->stats;
        });

        $seniorGovernment = Cache::remember('government.senior_government', 1, function() {
            return GovernmentRole::where('government_type', 'senior_ministers')->first()->stats;
        });

        $juniorGovernment = Cache::remember('government.junior_government', 1, function() {
            return GovernmentRole::where('government_type', 'junior_ministers')->first()->stats;
        });

        return view('frontend.community.government', compact('juniorGovernment', 'seniorGovernment', 'higherGovernment', 'royalty'));
    }
}

Now as you can see, I only select the first record where government_type matches. But the issue is I have multiple government roles with that government type and I want to get all the account stats for all records with that government type. I have looked at others suggestions and none of them work, either throwing an error or don't do what I want to do.
Now, I have modals for each Roleplay and GovernmentRoles, I have posted them both below.
GovernmentRole:

namespace App\Database\Website\Roleplay;

use Eloquent;

class GovernmentRole extends Eloquent
{
    protected $primaryKey   = 'id';
    protected $table        = 'srp_government_roles';
    public $timestamps      = false;
    protected $fillable     = [];

    public function stats(){
       return $this->hasMany('App\Database\Website\User\Roleplay', 'government_id');
   }
}

Roleplay:

use Eloquent;

class Roleplay extends Eloquent
{
    protected $primaryKey   = 'id';
    protected $table        = 'srp_user_statistics';
    public $timestamps      = false;
    protected $fillable     = [];

    public function user()
    {
        return $this->belongsTo('App\Database\Website\User\Player', 'user_id', 'id');
    }

    public function government_role()
    {
        return $this->belongsTo('App\Database\Website\Roleplay\GovernmentRole', 'government_id');
    }
}

So what I am trying to achieve is not just grabbing all the Roleplay instances for the FIRST government role record in the database it finds but putting together ALL roleplay instances for ALL records that match government_type either higher_government, senior_ministers, or junior_ministers.
Answer: If I understand what you are asking, can you not do something like fetching the stats on your loop through in blade? For example (I removed the cache, its adding complexity to the question/answer without any benefit):
// controller
$higherGovernment = GovernmentRole::where('government_type', 'higher_government')->get();

// blade
@foreach($higherGovernment as $g)
    {{ $g->id }}
    {{ $g->name }}
    @foreach($g->stats as $stat)
      {{ $stat->id }}
      {{ $stat->something }}
    @endforeach
@endforeach

Comment: No worries. Glad we got it sorted
Comment: Your answer does not work. When I apply your code I receive the following: You cannot serialize or unserialize PDO instances

PDOException in FileStore.php line 103:
You cannot serialize or unserialize PDO instances
Comment: I have tried your updated answer but it still shows the error to do with PDO.
Comment: That kind of error suggests something else is going on. Its hard to tell, but do any other queries in the app work? Do you still get the error without the blade loops
Comment: After removing the caching it works, but the blade loop is empty. I also know for a fact it shouldn't be empty.
Comment: Which loop is empty? Both? One? The other?
Comment: Both, the content box is totally empty.
Comment: `var_dump($higherGovernment);` before you return the view.
Comment: It returns a very very large array, unfortunately I can't paste it because it is about 2,000 lines worth but I have pasted the start of it if that helps.

object(Illuminate\Database\Eloquent\Builder)#190 (8) { ["query":protected]=> object(Illuminate\Database\Query\Builder)#189 (24)
Comment: Edited. Can you update, then paste the first few lines in a gist. Might need to swap to chat if this doesn't work
Comment: Here is a fair bit of the array that was posted: https://gist.githubusercontent.com/anonymous/33fa08b5ad52c21b63fffa53f5717436/raw/db28893ac0327884d1cc431b9a833846b4aa1887/gistfile1.txt
Comment: Your last update has made it work 100%, thank you. I have marked your answer as the accepted answer.


Memory Address and values in memory address

Question: I have a little confusion.
struct node *p; and if(p==NULL)

Now what I have gathered based upon my studies is that NULL is not a memory address but a value (i.e 0) in the memory address. When I use if(*p==NULL) it gives an error - no match for 'operator=='. But doesn't *p gives the value in the memory address. If we just use p aren't we comparing a memory address with a value in the memory address. Why is p==NULL correct while *p=NULL is not.
Comment: `NULL` is used with pointers. Here `if(p==NULL)` , `p` is a pointer and can be compared with `NULL` (assuming `p` is a global variable so that it is auto-initialized to `NULL`). But here `if(*p==NULL)` , `*p` is of type `struct node` and that is not a pointer.
Comment: You really need better study materials, if you gathered that.
Comment: the notion of NULL is a predefined area of memory which is unreferencable. it is ( ideally ) where you initialise pointers to before you allocate them properly. the traditional null check is applied to the pointer itself not dereferencing it ( which is UB and could cause a segfault )
Comment: @M.M I was really looking for an answer but I will act upon your suggestion.
Answer: Yes, *p gives the value in a memory address. But in this case, that value is a struct node because p is of type "pointer to struct node". You can't compare a structure's value to NULL.
Answer:
If we just use p aren't we comparing a memory address with a value in the memory address

No. When we talk about NULL, as per the C11 standard, chapter §7.19, <stddef.h>, (emphasis mine)

NULL
  which expands to an implementation-defined null pointer constant;[...]

So, NULL is a pointer and in your code, so is p. So, you can compare them.
OTOH, *p is a value, and you cannot compare that with NULL.
Comment: My idea of null wasn't proper. Got it finally.
Comment: @Rishab Note: null and NULL are **not** the same thing.
Answer: I think you have a misunderstanding about NULL here. NULL does in fact function as an address — it is a value for which a pointer is not valid. The memory at address NULL cannot be retrieved. NULL is NOT a value stored in a pointer. NULL is a pointer, and though it is system dependent, it usually points to the memory address 0, which I think is the source of the confusion.
NULL is comparable to pointers ( often defined as (void *)0 ). the conversion from void * to struct node will give a compiler warning and doesnt make sense.
Additionally comparing *p to NULL involves first dereferencing p ( which is UB )
NULL may have the value of 0, but it isn't meant to be compared to anything that isn't a pointer. So to fix your problem, as the commenters said, you must change your comparison from
if (*p == NULL)

a comparison of a struct to a memory address, to
if (p == NULL)

which compares memory address p to the address value stored in NULL.
Comment: @forsooth it does make sense for pointers to store NULL ( usually defined as zero ). and the usual object checking code will use something like `pointer = malloc(20*sizeof(char)); if(!pointer)...`. so in practical usage we do have pointers with a value of zero which we are comparing to NULL as standard practice. the c standard does not define NULL as zero but in most implementations it is
Comment: this sentence : `If NULL was equal to zero, and was stored at a certain memory address, then any time you had a pointer to some variable with a value of zero it would be equal to NULL and that just doesn't make sense`
Comment: I was trying to fix the confusion in the original post. Rishab said his understanding was that NULL was a value, i.e. 0, and that by dereferencing a pointer and comparing it to NULL he could tell if something existed or not. My attempt was to make it clear that, for example if you had int *i = 0, in his view comparing the dereferencing of that pointer to NULL would tell him if it was a valid pointer. If his view was correct, it would be impossible to tell if a pointer was NULL if it pointed to any value equal to zero. I'm sorry if the original sentence was worded confusingly.
Comment: Damn, my bad. I actually read [link]http://www.cplusplus.com/reference/cstring/NULL/ thats why I said NULL is zero.
Comment: I know, I understand why you voted down, no worries. I was more trying to correct the misunderstanding that NULL should be compared to the dereferencing of anything that's not a pointer to a pointer. I meant "NULL is not equal to zero" in the sense of NULL not being a mystical value of 0 that can compare to the contents of any pointer, but  rather a pointer to the address 0 (usually) in memory.
Comment: Deal, I hope that's clear enough. It's a tricky concept to explain. Thanks for the discussion anyway, if anything it probably elucidated the use of NULL a little more.


Restore common variables between inherited types

Question: I have two classes: GameObject and SampleObject : GameObject and a list of type GameObject. I've serialized instances of these classes into a XML document. My problem occurs once I deserialize (load) this document.
In XML file instances are serialized as:
<Root>
 <GameObject>
  <Type>Namespace.MyType</Type>
 </GameObject>
</Root>

Where Type represents desired type. And each instance is serialized under GameObject tag.
After parsing this document I obtain a list of GameObject. Now I need to restore correct type:
foreach (GameObject g in myList)
{
  GameObject tempObject = (GameObject)Activator.CreateInstance(Type.GetType(g.TypeString));
}

Problem is that tempObject is blank (which is correct). I'd like to (with some shorthand) restore common (shared) variables between g and tempObject. Ex:
tempObject.Property1 = g.Property1
tempObject.Property2 = g.Property2

Comment: Wouldn't you need to deserialize `SampleObject`-specific properties as well?
Comment: I would. @C.Evenhuis
Comment: In that case I wouldn't deserialize as `GameObject` first at all - what type of serializer do you use? `XmlSerializer` for instance has some built-in support for this.
Comment: I'm using XmlSerializer
Answer: XmlSerializer supports polymorphism, but you'll have to indicate up front which types to exprect. You can do this using an attribute on the base type:
[XmlInclude(typeof(SampleObject))]
public class GameObject
{
}

You can also pass these types to the constructor of XmlSerializer, for instance if you don't own the GameObject class. Full example:
Root root = new Root();
root.Objects.Add(new GameObject { Property1 = 2 });
root.Objects.Add(new SampleObject { Property1 = 5, Property2 = 12 });

XmlSerializer ser = new XmlSerializer(typeof(Root), new Type[] { typeof(SampleObject) });
using (MemoryStream stream = new MemoryStream())
{
    ser.Serialize(stream, root);
    stream.Position = 0;
    Root deserialized = (Root)ser.Deserialize(stream);
}

It outputs the following xml:
<?xml version="1.0"?>
<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <GameObject>
    <Property1>2</Property1>
  </GameObject>
  <GameObject xsi:type="SampleObject">
    <Property1>5</Property1>
    <Property2>12</Property2>
  </GameObject>
</Root>

I used the below classes for this example:
[XmlRoot]
public class Root
{
    public Root()
    {
        Objects = new List<GameObject>();
    }

    [XmlElement("GameObject")]
    public List<GameObject> Objects { get; set; }
}

public class GameObject
{
    public int Property1 { get; set; }
}

public class SampleObject : GameObject
{
    public int Property2 { get; set; }
}

Comment: You could use reflection on startup to collect all types inheriting from `GameObject` and store them in a `Type[]` - which you can then supply to the `XmlSerializer` constructor.
Comment: This actually connected gaps in my knowledge. I already had output in format of  but had no idea how to use this xsi:type. Just for clarification, could you extend your answer with how'd the situation change if there was one more type, ex. SampleObject2?
Comment: And one more question. Imagine that there are plenty of these types inheriting from GameObject. Is there any way to automate extension of [XmlInclude(typeof(SampleObject))] or do I have to add every type by hand?


Argument #1 ($callback) must be a valid callback, class Drupal\node\Entity\Node does not have a method "getCurrentUserId"

Question: I upgraded from Drupal 8.9.20 to Drupal 9.59. All modules seem compatible (upgrade manager). The site is up and running, but if I try to add new content via node/add/article, this error appears.

TypeError: call_user_func(): Argument #1 ($callback) must be a valid callback, class Drupal\node\Entity\Node does not have a method "getCurrentUserId" in call_user_func() (line 400 of /html/core/lib/Drupal/Core/Field/FieldConfigBase.php)
#0 /html/core/lib/Drupal/Core/Field/FieldConfigBase.php(400): call_user_func('...', Object(Drupal\node\Entity\Node), Object(Drupal\Core\Field\Entity\BaseFieldOverride))
#1 /html/core/lib/Drupal/Core/Field/FieldItemList.php(169): Drupal\Core\Field\FieldConfigBase->getDefaultValue(Object(Drupal\node\Entity\Node))
#2 /html/core/lib/Drupal/Core/Entity/ContentEntityStorageBase.php(271): Drupal\Core\Field\FieldItemList->applyDefaultValue()
#3 /html/core/lib/Drupal/Core/Entity/ContentEntityStorageBase.php(129): Drupal\Core\Entity\ContentEntityStorageBase->initFieldValues(Object(Drupal\node\Entity\Node), Array)
#4 /html/core/lib/Drupal/Core/Entity/ContentEntityStorageBase.php(94): Drupal\Core\Entity\ContentEntityStorageBase->doCreate(Array)
#5 /html/core/lib/Drupal/Core/Entity/EntityForm.php(370): Drupal\Core\Entity\ContentEntityStorageBase->create(Array)
#6 /html/core/lib/Drupal/Core/Entity/HtmlEntityFormController.php(73): Drupal\Core\Entity\EntityForm->getEntityFromRouteMatch(Object(Drupal\Core\Routing\RouteMatch), '...')
#7 /html/core/lib/Drupal/Core/Controller/FormController.php(58): Drupal\Core\Entity\HtmlEntityFormController->getFormObject(Object(Drupal\Core\Routing\RouteMatch), '...')
#8 [internal function]: Drupal\Core\Controller\FormController->getContentResult(Object(Symfony\Component\HttpFoundation\Request), Object(Drupal\Core\Routing\RouteMatch))
#9 /html/core/lib/Drupal/Core/EventSubscriber/EarlyRenderingControllerWrapperSubscriber.php(123): call_user_func_array(Array, Array)
#10 /html/core/lib/Drupal/Core/Render/Renderer.php(580): Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber{closure}()
#11 /html/core/lib/Drupal/Core/EventSubscriber/EarlyRenderingControllerWrapperSubscriber.php(124): Drupal\Core\Render\Renderer->executeInRenderContext(Object(Drupal\Core\Render\RenderContext), Object(Closure))
#12 /html/core/lib/Drupal/Core/EventSubscriber/EarlyRenderingControllerWrapperSubscriber.php(97): Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext(Array, Array)
#13 /html/vendor/symfony/http-kernel/HttpKernel.php(169): Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber{closure}()
#14 /html/vendor/symfony/http-kernel/HttpKernel.php(81): Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object(Symfony\Component\HttpFoundation\Request), 1)
#15 /html/core/lib/Drupal/Core/StackMiddleware/Session.php(58): Symfony\Component\HttpKernel\HttpKernel->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#16 /html/core/lib/Drupal/Core/StackMiddleware/KernelPreHandle.php(48): Drupal\Core\StackMiddleware\Session->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#17 /html/core/modules/page_cache/src/StackMiddleware/PageCache.php(106): Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#18 /html/core/modules/page_cache/src/StackMiddleware/PageCache.php(85): Drupal\page_cache\StackMiddleware\PageCache->pass(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#19 /html/core/modules/ban/src/BanMiddleware.php(50): Drupal\page_cache\StackMiddleware\PageCache->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#20 /html/core/lib/Drupal/Core/StackMiddleware/ReverseProxyMiddleware.php(48): Drupal\ban\BanMiddleware->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#21 /html/core/lib/Drupal/Core/StackMiddleware/NegotiationMiddleware.php(51): Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#22 /html/vendor/stack/builder/src/Stack/StackedHttpKernel.php(23): Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#23 /html/core/lib/Drupal/Core/DrupalKernel.php(718): Stack\StackedHttpKernel->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#24 /html/index.php(19): Drupal\Core\DrupalKernel->handle(Object(Symfony\Component\HttpFoundation\Request))
#25 {main}

Do you know how to fix that?
Comment: See the instructions in https://www.drupal.org/project/drupal/issues/3153455
Answer: Probably you are missing an update hook (did you run update.php on every update step?), but if this is the only problem it can be easily fixed:
drush cedit | grep core.base_field_override.node.*.uid

Now you see base field overrides of the uid field (one for each content type).
Enter the number of the first item listed. You have to enter it blindly because we grepped the prompt.
Correct this line:
default_value_callback: 'Drupal\node\Entity\Node::getDefaultEntityOwner'

Save the file and repeat the procedure for the other base fields.
You can also do this by copy-pasting the configuration in the admin config UI (single export and import).


Radiobutton variable does not update

Question: I know a question similar to this has been asked and I have tried everything that was suggested to fix the problem but I can not solve this issue. I am making a document that when a radiobutton is pushed a second radiobutton appears, which has options that will vary based on response to the first radiobutton. The problem is that nothing happens after the first radiobutton is chosen, the variable is not set equal to the value, which it should if I understand correctly.. I have even gotten rid of my loops that created the buttons and added a secondary function in the command line in an effort to set the variable but no luck... I am beginning to think that this cannot be done using radiobuttons... Does anyone know if I am missing something that is not allowing the variable to be set?
<code>from tkinter import Tk, Label, IntVar, Radiobutton

class pricingDoc:

    def __init__(self, master):
        self.master = master
        master.title("Dyna-Vac Equipment Pricing GUI")

        models = ["DJ5.636", "DJ1225", "DJ2040", "DJ4020", "DJ4030", "DJ6520"]
        model_prices = [8139.00, 23770.00, 48050.00, 48040.00, 48030.00, 66050.0]
        reels = ["""3/8" x 150'""", """1/2" x 300'""", """1/2" x 500'""", """3/4" x 600'""",
                 """3/4" x 800'""", """1" x 600'""", """1" x 800'"""]
        reel_prices = [0.00, 0.00, 850.00, 0.00, 1050.00, 0.00, 850.00]

        self.label1 = Label(master, text="Jet Trailer Model")
        self.label1.grid(row=1, column=1)
        self.label2 = Label(master, text="Price, in USD")
        self.label2.grid(row=1, column=3)

        def showchoice(var1, updateint):
            var1.set(updateint)

        var1 = IntVar(master)

        row_counter = 2
        self.modelbutton = Radiobutton(master, text=models[0], variable=var1, value=0, indicatoron=False,
                                           activebackground="green", width=12, command=lambda: showchoice(var1, 0))
        self.modelbutton.grid(row=row_counter, column=1)
        row_counter += 1
        self.modelbutton = Radiobutton(master, text=models[1], variable=var1, value=1, indicatoron=False,
                                         activebackground="green", width=12, command=lambda: showchoice(var1, 1))
        self.modelbutton.grid(row=row_counter, column=1)
        row_counter += 1
        self.modelbutton = Radiobutton(master, text=models[2], variable=var1, value=2, indicatoron=False,
                                         activebackground="green", width=12, command=lambda: showchoice(var1, 2))
        self.modelbutton.grid(row=row_counter, column=1)
        row_counter += 1
        self.modelbutton = Radiobutton(master, text=models[3], variable=var1, value=3, indicatoron=False,
                                         activebackground="green", width=12, command=lambda: showchoice(var1, 3))
        self.modelbutton.grid(row=row_counter, column=1)
        row_counter += 1
        self.modelbutton = Radiobutton(master, text=models[4], variable=var1, value=4, indicatoron=False,
                                         activebackground="green", width=12, command=lambda: showchoice(var1, 4))
        self.modelbutton.grid(row=row_counter, column=1)
        row_counter += 1
        self.modelbutton = Radiobutton(master, text=models[5], variable=var1, value=5, indicatoron=False,
                                         activebackground="green", width=12, command=lambda: showchoice(var1, 5))
        self.modelbutton.grid(row=row_counter, column=1)

        row_counter = 2

        for price in model_prices:
            self.label3 = Label(master, text=price)
            self.label3.grid(row=row_counter, column=3)
            row_counter += 1

        self.label4 = Label(master, text="model {} is chosen".format(var1.get()))
        self.label4.grid(row=row_counter, column=1)
        row_counter += 1

        self.label5 = Label(master, text="Reel Size Selection")
        self.label5.grid(row=row_counter, column=1)
        row_counter += 1

        var2 = IntVar(master)

        if var1.get() == 0:
            self.reelbutton = Radiobutton(master, text=reels[0], variable=var2, value=0, indicatoron=False,
                                                activebackground="green", width=12)
            self.reelbutton.grid(row=row_counter, column=1)
            row_counter += 1
            row_counter = 10
            self.label6 = Label(master, text=reel_prices[0])
            self.label6.grid(row=row_counter, column=3)

        elif 1 <= var1.get() <= 2:
            self.reelbutton = Radiobutton(master, text=reels[1], variable=var2, value=1, indicatoron=False,
                                                activebackground="green", width=12)
            self.reelbutton.grid(row=row_counter, column=1)
            self.label6 = Label(master, text=reel_prices[1])
            self.label6.grid(row=row_counter, column=3)
            row_counter += 1
            self.reelbutton = Radiobutton(master, text=reels[2], variable=var2, value=2, indicatoron=False,
                                            activebackground="green", width=12)
            self.reelbutton.grid(row=row_counter, column=1)
            self.label7 = Label(master, text=reel_prices[2])
            self.label7.grid(row=row_counter, column=3)
            row_counter += 1

        elif 3 <= var1.get() <= 4:
            self.reelbutton = Radiobutton(master, text=reels[3], variable=var2, value=3, indicatoron=False,
                                                activebackground="green", width=12)
            self.reelbutton.grid(row=row_counter, column=1)
            self.label6 = Label(master, text=reel_prices[3])
            self.label6.grid(row=row_counter, column=3)
            row_counter += 1
            self.reelbutton = Radiobutton(master, text=reels[4], variable=var2, value=4, indicatoron=False,
                                            activebackground="green", width=12)
            self.reelbutton.grid(row=row_counter, column=1)
            self.label7 = Label(master, text=reel_prices[4])
            self.label7.grid(row=row_counter, column=3)
            row_counter += 1

        elif var1.get() == 5:
            self.reelbutton = Radiobutton(master, text=reels[5], variable=var2, value=5, indicatoron=False,
                                                activebackground="green", width=12)
            self.reelbutton.grid(row=row_counter, column=1)
            self.label6 = Label(master, text=reel_prices[5])
            self.label6.grid(row=row_counter, column=3)
            row_counter += 1
            self.reelbutton = Radiobutton(master, text=reels[6], variable=var2, value=6, indicatoron=False,
                                            activebackground="green", width=12)
            self.reelbutton.grid(row=row_counter, column=1)
            self.label7 = Label(master, text=reel_prices[6])
            self.label7.grid(row=row_counter, column=3)
            row_counter += 1

        row_counter += 1
        self.label8 = Label(master, text="Total unit price as built: {}".format(model_prices[var1.get()] +
                                                                                reel_prices[var2.get()]))
        self.label8.grid(row=row_counter, column=3)
        row_counter += 1

root = Tk()
my_gui = pricingDoc(root)
root.mainloop()
</code>
Comment: I second what Bryan said.  An MCVE for this might be only 10 lines.  After years of using tkinter, I still use simple minimal programs to experiment and debug problems.
Comment: Please try to reduce this code down to a [mcve]. Can you illustrate the problem with just one or two Radiobuttons instead of five? Do you really need the labels if the problem is with a Radiobutton?
Comment: At least part of the problem is that you're calling `var1.get()` about a millisecond after creating the radiobutton. The user won't have had a chance to click on anything.
Comment: thanks for the criticism, will definitely keep this in mind!
Answer: From what I see and have tested in your code, it does not look to me like the elifs are encapsulated in a function that is called when a radio button is being clicked.
To test this theory, I threw a print(var1.get()) into the showchoice function and it prints out the new index with each click.  So to take that further I moved the label4 creation lines into that function as well and it updates the form properly.
So to me it just looks like the block of elifs need to be encapsulated into a function that is called (and thus updated) every time the radio buttons are clicked.
I Hope this helps or at least puts you on the right path.  I see no reason why radio buttons couldn't or shouldn't be used for what you're doing!
~Cheers!
Comment: ahhh, makes sense, I am going to give that a try, Thanks!
Comment: My pleasure, Hal!  Best of luck!

Radiobutton variable does not update


MySQL search for multiple keywords and order by best match

Question: I currently have a tag system for my blog.
Each blog is inserted in the blog table, and the tags are inserted in the tag table.
The tag table has a column blog_id to link each tag to a blog item.
So let's say we have:
Blog table:
id - name
20 - a nice blog post about product x

Tag table:
id - blog_id - tag
12 - 20 - nice
13 - 20 - product x

I have a search function that searches through the tags based on a search string and that works fine.
But I would like to expand the query to search for multiple tags, and order it by the best match. Searching for multiple tags will not be a problem, because I could just explode the search string and loop through it, but ordering it by the best match is something I can not figure out.
So let's say I have 3 blog posts, with each the following tags:
1. sunny, in-ear, earphones, review
2. pear, out-ear, earphones, review
3. pear, in-ear, earphones, review
And a user searches for "pear in-ear earphones", I would like the order of the result to be:
3. (because 3 tags match)
1. (because 2 tags match)
2. (because 1 tags match)
This is what the query looks like:

SELECT `b`.*
FROM (`blog` b)
WHERE (
    b.name LIKE '%pear in-ear earphones%'
    OR
    b.id IN (
        SELECT bt.blog_id
        FROM blog_tags bt
        WHERE bt.tag LIKE '%pear in-ear earphones%'
        AND bt.blog_id = b.id
        )
    )
ORDER BY `b`.`date` desc

Who could help me out?
I've looked at "Full Text Search" but that is not an option, because my table is InnoDB.

Thanks in advance!
Comment: MySQL 5.6 has FULLTEXT mechanism for InnoDB (but I didn't check it myself yet, therefore that's all I can say about it...)
Comment: Thanks, but unfortunately my server runs MySQL client version: 5.5.20.
Answer: I personally love using Solr for text matching. You can create these complex formulas that will weight matches in the name higher than matches in the tags or vice versa. It also matches pluralizations too. So if I search butterflies it will find the butterfly matches.
Here's another query that may help you with order blog tags by frequency. This query will get all of the blog items with at least one match in the tags. It will order by the number of tags that matches
SELECT *
FROM blog b
JOIN (
    SELECT blog_id, COUNT(*) as matches
    FROM tags
    WHERE tag in ('pear', 'in-ear', 'earphones')
    GROUP BY blog_id
) t
ON t.blog_id = b.blog_id
ORDER BY matches desc

You can add the number of matches for a particular string like this:
SELECT *,
    t.matches +
    COALESCE((LENGTH(b.`title`)-LENGTH(REPLACE(b.`title`,'pear','')))/LENGTH('pear'),0) +
    COALESCE((LENGTH(b.`title`)-LENGTH(REPLACE(b.`title`,'in-ear','')))/LENGTH('in-ear'),0) +
    COALESCE((LENGTH(b.`title`)-LENGTH(REPLACE(b.`title`,'earphones','')))/LENGTH('earphones'),0) AS total_matches,
FROM blog b
LEFT JOIN (
    SELECT blog_id, COUNT(*) as matches
    FROM tags
    WHERE tag in ('pear', 'in-ear', 'earphones')
    GROUP BY blog_id
) t
ON t.blog_id = b.blog_id
ORDER BY total_matches desc
ORDER BY

Just a note this query will probably be pretty slow with all of these matching and things. I still recommend using an indexing software like Solr
Comment: Thanks! And what about searching for the title? Could I do that the same way? The more words match the title, the higher that one should also be shown.
Comment: Yes, the question now is do you want it weighted meaning a match in the title is worth more than a match in a tag? I'll update my answer shortly to include title search matches
Comment: Hmm.. would it also be possible to let them both weigh in the total match? So if the title has 3 matches, and the tags have 3 matches, the total "rating" would be 6. That should weigh more then a result with a title match of "2", and a tag match of "3". If that makes sense.
Comment: @JohnHeroHD, that is how it's currently set up :)
Comment: I just tried it out and it's awesome! Thanks a lot! I am just having 1 issue with it: if there is a title match, but no tag match, it does not find records. How can I fix this?
Comment: Yup, it works like a charm! Thank you for the wonderful help!
Answer: The following query counts the number of tags that match a particular list and orders by the number of matches:
select b.*
from blog b join
     blog_tags bt
     on b.id = bt.blog_id
where bt.tag in ('pear', 'in-ear', 'earphones')
group by blog_id
order by COUNT(*) desc;

Note that the use of like in your original query is incorrect.  None of the tags contain the string 'pear in-ear earphones'.


NFS: Permissions to write/create?

Question: I have setup a server and client (both LinuxMint 21.3) with NFS so that the client should have read-write access.  However, it successfully reads but cannot write.  I've searched through lots of questions here and elsewhere but not seen anything that seems to clearly provide a solution.  I've ran through this page which confirmed what I have done.
Here's the setup:
Server /etc/exports is set for read/write:
/exports  192.168.0.0/28(rw,no_subtree_check)

Client /etc/fstab is set to mount at boot:
media:/exports /mnt/nfs/media-server  nfs      auto,noatime,defaults,x-gvfs-show    0       0

Permissions on the server exports (selecting just one directory for this example):
root@media:~# ls -al /exports/Software
total 16
drwxr-xr-x 4 root root 4096 Mar 28 11:56 .
drwxr-xr-x 8 root root 4096 Mar 28 11:55 ..
drwxr-xr-x 2 root root 4096 Mar 28 11:56 Linux
drwxr-xr-x 2 root root 4096 Mar 28 11:56 Windows

Permissions on the client mounts:
root@brawn:~# ls -al /mnt/nfs/media-server/Software
total 16
drwxr-xr-x 4 root root 4096 Mar 28 11:56 .
drwxr-xr-x 8 root root 4096 Mar 28 11:55 ..
drwxr-xr-x 2 root root 4096 Mar 28 11:56 Linux
drwxr-xr-x 2 root root 4096 Mar 28 11:56 Windows

But attempts to copy from the client to the server -- or to create a folder on the server from the client -- fail.
Attempting to copy as my user (which has the same uid, gid on both systems)
:~$ cp /media/<user>/Storage/Software/Linux/zoom*.deb /mnt/nfs/media-server/Software/Linux
cp: cannot create regular file '/mnt/nfs/media-server/Software/Linux/zoom_amd64.deb': Permission denied

Even trying as root fails:
:~# cp /media/<user>/Storage/Software/Linux/zoom_amd64.deb /mnt/nfs/media-server/Software/Linux
cp: cannot create regular file '/mnt/nfs/media-server/Software/Linux/zoom_amd64.deb': Permission denied

UPDATE
Using info provided in @vidarlo's answer, I did the following:
On the server:
sudo groupadd -g 1003 nfsshare
sudo usermod -a -G nfsshare <user>
cd /exports
sudo chgrp -R nfsshare /exports
sudo chmod -R 775 /exports
sudo exportfs -ar

On the client:
sudo groupadd -g 1003 nfsshare
sudo usermod -a -G nfsshare <user>
mount -a

My user now has full access to the exported contents.
Answer: First of all, it fails as user because the folder is owned by root, and only root has write permissions.
Second, it fails for root because NFS doesn't trust root on remote systems by default.
You have two choices:

Give users access by a combination of changing owner and permissions
Export the directory with no_root_squash-option to give root full permissions.

The latter is not a good idea from a security perspective - at least not without any further actions, as it will allow remote root to create suid binaries on the server...
Comment: So, create a separate network user that would be used for that purpose and add that user to both the server and client(s) with the same uid/gid.  Is that correct?
Comment: Or, maybe a network group to which I would add my user?
Comment: NFS works by UID and GID, yes. How you solve that is up to you.

NFS: Permissions to write/create?


Why does 'Search Question' of the Answers module not show any results?

Question: The "Search Questions" view page which is provided by the Answers module does not show any results. I am pasting the typed question as it is yet it just shows "No questions match".
What could be the issue?
Edit: I did get the solution just now, I was trying other related modules Best Answer and Answers Userpoints and after enabling them the Search feature started working. Probably some other module which is mutual between them gets enabled and start working, But I could not figured it out, as the Answers module list was showing all dependency modules enabled prior to all this. Any way it start working.
Comment: Have you tried playing with its options a bit? Setting the algorithm a bit manually to make it more flexible?
Comment: I did got the solution just now, I was trying other related modules [Best Answer](https://www.drupal.org/project/best_answer) and [Answers Userpoints](https://www.drupal.org/project/aup) and after enabling them the Search feature started working. probably some other module which is mutual between them is gets enabled and start working, But I could not figured it out, as Answers module list was showing all dependency modules enabled prior to all this. Any way it start working. Will figure out after uninstalling all and if found will raise a issue on module page. Thanks
Comment: How did you get a "search questions" feature? My installation of answers didn't come with anything like that.
Answer: Have a look at Comment #1 in issue 1619676, which states:

One hypothesis: have you run cron?
The way content gets indexed is during cron runs ... not immediately when new content is created.

It could well be that "in the meantime" cron was run, which would explain why "... the Search feature started working..." (as in your comment).
Disclosure; I'm a co-maintainer of the Answers module.
Comment: `run cron`, could be the reason, as I installed other module, I did run cron afterward. Thanks


how to check if variable is blank or undefined in node js

Question: I want to check my data is blank or undefined but my if block execute even my data is not blank ...
Code is :
router.post('/addNewGrade',function(req , res){
    var errorMsg = [];
    console.log(req.body.gradeName)
    if(req.body.gradeName == '' || req.body.gradeName === undefined){
        errorMsg.push("please enter grade name");
    }
    if(req.body.gradeDescription == '' || req.body.gradeDescription === undefined){
        errorMsg.push("please enter description about your grade");
    }
    if(errorMsg !=''){
        res.send({errorMessage :errorMsg});
        return;
    }

});

what is the best way to check variable is undefined or not
Comment: You could check if errorMsg.length > 0 show the error?
Comment: Please log the values of `req.body.gradeName` etc. to confirm their value.
Comment: What does "blank" mean?
Answer: Because an undefined variable is "falsey", you can simple do
if (body.req.gradeName) {
  // do normal stuff
} else {
  // do error stuff
}

Or if you don't need to do anything if it is defined, then you can do
if (!(body.req.gradeName)) {
 // do error stuff
}

Comment: CAREFUL with this, if body.req.gradeName is false ("false" or false), you're not in an error situation, false can be a value too.
Comment: This will go to the error branch for several "normal" values
Comment: If body.req.gradeName cames with '0' will do the 'error stuff', sometimes is not the expectd behavior
Comment: Sure, but how does this explain the behavior reported by the OP?
Comment: Apologies! I missed that. I agree with you torazaburo, I would like to see what the console.log value of gradeName is.
Answer: You can do it like this
if(typeof variable === 'undefined'){
//Variable isn't defined
}

Answer: it is working
if(req.body.gradeDescription == '' || req.body.gradeDescription === undefined)

Comment: that seems to be the exact same thing as your starting post...


Template 10 and netstandard 2.0

Question: I wonder if template 10 is compatible with netstandard2.0. I have a very simple library listed below:
using Microsoft.EntityFrameworkCore;
using System;
using System.ComponentModel.DataAnnotations;

namespace TransactionModel
{
    public class MyTransaction
    {
        [Key]
        public Guid TransactionId { get; set; }
        public string BankID { get; set; }
        public string MerchantID { get; set; }
        public DateTime TransactionDate { get; set; }
        public string TransactionDescription { get; set; }
        public float TransactionAmount { get; set; }
        public string TransactionComments { get; set; }

    }
    public class TransactionContext : DbContext
    {
        public DbSet<MyTransaction> transactionBatch { get; set; }
        protected override void OnConfiguring(DbContextOptionsBuilder optionBuilder)
        {
            optionBuilder.UseSqlite("Data source=transactions.db");
        }
    }
}

This library csproj file listed below:
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
        <TargetFrameworks>netcoreapp2.0;netstandard2.0</TargetFrameworks>

        <RuntimeFrameworkVersion>2.0.3</RuntimeFrameworkVersion>
        <GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
    </PropertyGroup>

    <ItemGroup>
    <PackageReference Include="microsoft.entityframeworkcore.Sqlite" Version="2.0.1" />
    <PackageReference Include="microsoft.entityframeworkcore.tools" Version="2.0.1" />
  </ItemGroup>

</Project>

I have installed package Microsoft.EntityFrameworkCore.Sqlite and Microsoft.EntityFrameworkCore.Tools and then add-migration to scaffold the database successfully.
But when I tried to make reference to TransactionModel, the compiler generated a bunch of errors, but I think this is the main error:
" Cannot resolve Assembly or Windows Metadata file.."

I have attached a image of my vs2017 solution. I have written no code on T10 yet, I have just created T10 template, made reference to my library and vs2017 has generated the errors. If I use UWP, I did not get such error...
So my question is whether it is possible to use T10 with EntityFrameworkCore and netstandard2.0? Is there a way to go around the error?
Comment: correct it isn't compat., #soon when 10.2 releases, which is heavily in refactor development.  But you don't need .netstandard 2 to use sqlite in uwp...  if you are merely using EFCore previous versions work.
Comment: You can check out the current rev of Template 10 at http://aka.ms/template10 and see for yourself. The next version is imminent.
Answer: It is not possible to create a dependency FROM a .NET Core project ON the Template 10 library because the Template 10 library is a Universal Windows Library. This is true with the current version of Template 10. This will also be true with the next version of Template 10. Why? Because Template 10 is a library built to enhance UWP application development, and, as a result, requires the Windows namespace which, as you know, is not part of .NET Standard. How could it be? The Windows namespace could never be cross-platform. That being said, the fundamental interfaces of Windows 10 (new version) are not derived from Prism.Core which is a .NET Standard library. This means the navigation interfaces and MVVM classes are all external and can be inherited side-stepping Template 10. This answers your question, I hope you understand the technical reasons things are as they are.
Comment: Nixon: Got it. Thanks! Now if I want to use SQLite with template 10 what should I do? Do you have  or know a sample project for my reference? Template 10 should be able to be used with an EntityFramework? If not, how do we persist data in Template 10?

Template 10 and netstandard 2.0


Forcing ansible to print on console exatly what I want

Question: I have several tasks to do with ansible ( because it is great environment).
However I want to achieve two things:

have on stdout only exactly what I want ( I mean only this output which I place in msg variable, and NOTHING ELSE)
I would like to be able to use this output as input via pipe to other tools like grep, awk, sed etc.

Is there any way ( without writing my own C++, Perl, Cobol, SQL, VisualBasic and Java whatever, code) to do it? As the only option if You have to write eternal code - I allow assembler code, so if You would like to propose something like that: feel free!
Comment: Not exactly a duplicate, but pretty close: https://serverfault.com/questions/640130/display-output-with-ansible
Comment: It is not about pretty printing. It is about usability and integration withn linux/unix tools
Comment: I'm aware of that. That's why I didn't vote to close your question as a duplicate. Nevertheless the linked question contains some pointers how you could achieve what you want.
Comment: There is no point in pretty printing - it is just aesthetic expectation. But imagine You have to check 300 switches for given config... If tool have to be used it have to work with grep/awk/sed tools without any friction.
Comment: why down-vote? Because nobody knows how to do it? Maybe the correct answer is: not possible at all?
Comment: Possible progress: You can quiet some ansible by setting [defaults]
stdout_callback = full_skip in ansible.cfg. At least You will see only the "working part" of your playbook.
Comment: Ansible is not a scripting language, and it isn't intended to be one. It is an orchestration tool.  You are trying to use ansible in a way that it wasn't meant to be used. You don't pipe output from ansible to other tools you use ansible to run those other tools.  Run a task register the results, run a second task, perhaps a shell task doing your sed/awk/group and pass in the previous results.
Comment: `I allow assembler code,`-  BTW, this makes your question seem like a troll.  Expecting someone to give you assembly code for a project that is mostly python is just silly.  It is part of why I gave you a downvote.
Comment: Orchestration tool should integrate with much more mature tools, just for giving ability for checking results in automated way. It is just stupid philosophy to build something like Microsoft does.
Comment: I have wrote about assembler because all of ansible power users immediately answer: write a fragment of python code and this is solution. I just think that building such great tool even without simple clear stout and simple stderr is result of lack of broader picture
Comment: So basically there is nobody who knows, by nobody is able to say: it is not possible because of design?
Answer: It is not possible by design.
Ansible is written without clear separation of stout, stderr and even output from ansible itself versus output from external execution procedures/functions.
It is debatable why such design is used, however society around ansible is even not able to discuss possiblity it is not very well suited for enterprise use.
Comment: It is only a proposal. Maybe it is even not true!
Answer: Write your own custom stdout callback plugin. This type of plugin (although not to stdout) is how reporting tools like ARA work.
Possibly ansible-runner will be interesting as a stable interface designed for automation, one if its output options is JSON.

By default an adhoc ansible command looks vaguely JSON-ish and parsable, but it isn't entirely due to human readable headers at the beginning.
Comment: As i'm saying above, I will accept such kind of answer only if assembler code is provided. All other way for me is incomplete.
Comment: How far would be it world now if ls command would give you jsonish output connected with cows...
Answer: I think you may try to register to get stdout of your command. For example when you using shell. Basically it creates structure which you can iterate or even update. There are lots of examples how to work with variables:
ansible print debug msg variable
Regarding second part, you also may place ansible variable in shell as part of command. Example. But it is better to use native ansible module if such exist for you task.
Comment: The question is about how to print only the result, and nothing else of the ansible output.


Midi keyboard key count

Question: I was looking at some midi keyboards, I already have an Akai MPK Mini MKII
It's a 2 octave keyboard but It has an extra key off the right side
C,D,E,F,G,A,B | C,D,E,F,G,A,B | C
Here's it in an image:

What's the purpose of that extra C key? Couldn't they have removed it to make the dimensions smaller?
While there are keyboards like this M-Audio Keystation Mini:
It has two octave of keys without the extra key. Are these just design decisions?

Would there be any benefits/drawbacks to having that extra key as in the Akai device?
Answer: Looking closely, the M-Audio device actually have 8 extra keys (on top of the two octaves).  I think adding extra keys at the top always improves usability.  Since I mostly play in C, I use the extra key at the top quite often; I think it's a practical consideration.
Answer: Modern electronic keyboard instruments smaller than 88 keys mostly come in N octaves + 1 key sizes: 25-, 37-, 49-, or 61- key; they're more or less industry standards. These are also referred to as 2-octave, 3-octave, 4-octave, and 5-octave after the largest interval that can be played on them. The M-Audio mini-32 is a bit of an oddball.
There's no compelling reason for this structure other than allowing stacked octave intervals to make use of the whole keyboard. This mostly favors the key of C, but since most synthesizers have some sort of transposition facility, if you absolutely need to play a 2-octave G-G interval on the Akai MPK Mini MKII, you can arrange it.

Midi keyboard key count


Exchange data recovery

Question: I'm trying to do something a little bit obscure, if not to other people at least to me.
My current task: Sneak into the (possibly corrupted) data of a Windows 2003 server hard drive, and extract the Exchange data from it, for one or more accounts. I say one or more, because if I succeed, I'll probably have to repeat the feat.
Then I have to hand-pick the data, and import it back into the user's Outlook profile, so that he has access to his old e-mail data, contacts, and so on and so forth.
Things that are <code>_NOT_</code> included in my options:
-Installing a new box with Windows Server 2003
-Installing Exchange on my desktop from a sane backup to properly export data
-Any other thing implying a proper backup system and/or disaster recovery plan.
Tools I have at my disposal:
-External USB hard drives
-The Windows Server 2003 hard-drive
-A live ubuntu disk
-Time, but it seems I have to not use that alot.
Answer: Assuming the files are intact on the servers hard drive, then Ontracks Power Controls will allow you to extract mailboxes from the exchange .mdb files. They have a demo which will allow you to see if recovery is possible. See here
Edit: Looking at your previous posts, it looks like your boss will learn the hard way why proper backups and proper server hardware RAID are important.
Comment: OKay, that seems nice enough, and which database file should I pick?
Comment: @ your edit: Yes, yes, or not. He decided that the date of our upcoming meeting about that would be "later".
Answer: If the machine boots up and has exchange installed, installing exmerge you can extract a mailbox to a pst on the machine and then copy that pst to a local workstation whose matching inbox in order to upload the mail items for this user.
Answer: Check out this software, since you didn't mention cost.
http://www.officerecovery.com/mail/index.htm
This software package works killer on things like .edb and .ost files, which are normally inaccessible.
Answer: First thing... If it's a RAID volume, DO NOT use chkdsk.
You'll need to find your exchange database obviously.  Depending on what kind of hard drive set up you have, you may be able to get an SATA/IDE to USB converter to extract the information on the hard drive.
If you can boot into safe mode, then my best bet would be to attach an internal hard drive in the computer, granting that you can format it before hand.  You may need to disassemble the USB drive to get to the innards.  If you can into safe mode, copy all of the data from the corrupt drives to your new one.
In order to extract from EDB databases, you HAVE to install some form of Exchange on a stable machine.  If you're going away from exchange, then installing the management tools on your laptop may be the only option you have.  However, if your going to reinstall exchange, you can get the data off, then recover it after you have reinstalled.
MORE than likely, you'll need to repair the database to get anything out of it.  Check this out: https://community.spiceworks.com/how_to/166394-recover-mailbox-from-edb-file-with-eseutil

Exchange data recovery