What is a 5-point play in basketball?

Question: I heard of how a 5-point play could be possible, but when I mentioned it people told me it's not possible -- and I can't remember how this would work.
Comment: @New-To-IT You should post that as an answer as it's well... the answer :-)
Comment: If a guy makes a 3 pointer, gets fouled, then the team that fouled gets called for a technical, technically it's a 5 point play, because they'd get the 3, the foul shot, and the technical shot.
Comment: While it's not technically a single play, I use the phrase to refer to a 5-point possession when a team makes a 3 or 2, is fouled, misses the free throw, gets the rebound, and makes a 2 or 3, thus scoring 5 points. It's also possible to make two 3 pointers in a possession in this way, but I've never seen it personally.
Comment: Couldn't you make a three while getting fouled, and then the defender is called for a flagrant, wouldn't you get 3 more free throws?
Answer: I can remember 2 in recent history and they were both pretty strange.
Nuggets vs Clippers
March 17, 2014

Chris Paul (Clippers) fouled Ty Lawson (Nuggets) while shooting a 3.
Lawson made the 3.
Paul received a tech (probably for cursing at the referee for the foul call).

End result: 3 pointer, 2 free throws
https://www.youtube.com/watch?v=aglwmgENwwM
Jazz vs Mavericks
March 24, 2013

Shawn Marion (Mavs) fouled by Derrick Favors (Jazz) while shooting a 2.
Enes Kanter (Jazz) blocks the shot
Referee rules that Kanter touched the net (goaltending)
Blocked shot counts as 2 points
Kanter given a tech for interference
Tyrone Corbin (Jazz coach) is given a tech when the play is explained to him (probably more cursing).

End result: Goaltending (2 points), 3 free throws
http://www.deseretnews.com/article/865576634/Utah-Jazz-notebook-Jazz-puzzled-by-rare-5-point-play-in-5-point-loss-to-Mavericks.html
Comment: Good info but I don't get it.  The tech is a "new play" and can be shot by anyone.
Answer: A four-point play usually refers to when a single player scores four points on a single possession. We may thus analogously define a five-point play as when a single player scores five points on a single possession.
By this definition, a five-point play can only arise in tandem with technical or flagrant fouls. (And indeed, with the aid of technical and flagrant fouls, it is, by my reckoning, possible to have a 66-point play. See the end of this answer for my calculations.)
According to Harvey Pollack,† there have only ever been two five-point plays:
1. Kobe Bryant, LAL @ SAC, 2003-03-20
Q4, 8:28.

Jim Jackson fouls Bryant on a made three-pointer (+3).
Jackson is assessed a technical foul.
Bryant makes the technical free throw (+1).
Bryant then makes the free throw for the foul (+1).

2. Dell Curry, MIN @ CHH, 1995-01-11
Play-by-play data are not available that far back, but Googling you can find some newspaper reports on this. For example, from SF Gate:

MInnesota guard J.R. Rider, of Alameda, relentlessly taunted Charlotte sharpshooter Dell Curry throughout a recent game, then fouled Curry on a 3-pointer, and on top of that, got a technical for complaining, creating a five-point play for Charlotte. Said Curry of Rider, "He's stupid."

If we use the broader definition where a five-point play is whenever a team scores five points in a single possession, then there have been somewhat more instances. In addition to @SteveJackson's two examples, we have more recently:
BOS @ NYK, 2016-02-02
Q1, 7:27. Carmelo Anthony commits Flagrant One Foul on Jae Crowder, who makes both free throws (+2). A technical foul is called on NYK (on the coach Derek Fisher, according to NESN) — Isaiah Thomas makes free throw (+1). Then Jae Crowder makes jumper (+2).

By NBA Official Rules 7 Sec. II:

(f) Team possession ends when:
(1) The ball hits the rim of the offensive team
  (2) The opponent gains possession. and

And so by (1), a possession ends even when a team gets an offensive rebound.
Going by this definition, Kyrie Irving's five consecutive points on 2017-11-13, Q4, 4:17, (OKC @ BOS) does not count as a 5-point play. (He was fouled by Westbrook on a made three-pointer, missed the free throw, caught his own rebound, then made a two-pointer.)
(Note though that many folks in the "analytics" business consider it to be the same possession even after an offensive rebound. This probably makes sense for the purpose of "analytics", but is not how possessions are counted according to the official NBA rules.)

†2010-2011 Harvey Pollack NBA Statistical Yearbook (p. 336), which in turn quotes Dennis D'Agostino.

66-point play
In a single possession, each active player (max 12) can get a Flagrant One foul plus two technicals before being ejected. That generates 4 FTs each.
Each inactive player (max 3), each coach (max 3), and each trainer (one) can get two technicals before being ejected (see Rule 3, Section IV, d; and Rule 12, Section V, b). That generates 2 FTs each.
Altogether then, within a single play, we can have as many as 4 × 12 + 2 × (3 + 3 + 1) = 62 Flagrant One and Technical FTs. Add that to your "regular" four-point play and in theory, we can have as much as a 66-point play, where a single player scores 66 points on a single possession.
This of course is pretty unlikely. Indeed, I do not know if there has even ever been a 6-point play in the NBA.

What is a 5-point play in basketball?


name 'sc' is not defined,

Question: 2 days back I could run pyspark basic actions.
now spark context is not available sc.
I tried multiple blogs but nothing worked.
currently I have python 3.6.6, java 1.8.0_231, and apache spark( with hadoop) spark-3.0.0-preview-bin-hadoop2.7
I am trying to run simple command on Jupyter notebook
data = sc.textfile('airline.csv')
==> getting following error.
NameError                                 Traceback (most recent call last)
<ipython-input-2-572751a2bc2a> in <module>
----> 1 data = sc.textfile('airline.csv')

NameError: name 'sc' is not defined

i have set following system variable set
HADOOP_HOME = C:\spark-3.0.0-preview-bin-hadoop2.7
PYSPARK_DRIVER_PYTHON = ipython
PYSPARK_DRIVER_PYTHON_OPTS = notebook
SPARK_HOME = C:\spark-3.0.0-preview-bin-hadoop2.7
(java and python system variables are already set)
path = C:\spark-3.0.0-preview-bin-hadoop2.7\bin ( i have loaded winutils.exe in this folder)

Now if I remove my PYSPARK_DRIVER_PYTHON and PYSPARK_DRIVER_PYTHON_OPTS variables and run pyspark on my command prompt, then i get following error.
C:\spark-3.0.0-preview-bin-hadoop2.7>pyspark
Python 3.6.6 (v3.6.6:4cf1f54eb7, Jun 27 2018, 03:37:03) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
19/12/25 23:28:36 WARN NativeCodeLoader: **Unable to load native-hadoop library for your platform... using builtin-java classes where applicable**
Setting default log level to "WARN".
To adjust logging level use sc.setLogLevel(newLevel). For SparkR, use setLogLevel(newLevel).
19/12/25 23:28:42 WARN Utils: Service 'sparkDriver' could not bind on a random free port. You may check whether configuring an appropriate binding address.
19/12/25 23:28:42 WARN Utils: Service 'sparkDriver' could not bind on a random free port. You may check whether configuring an appropriate binding address.
19/12/25 23:28:42

I tried to find workaround for this too but couldn't get it. Please help
Comment: are you sure you have above sc = spark.sparkContext??
Comment: add from pyspark import SparkContext
sc = SparkContext("local[*]", "spark_context")
Answer: i dont know why but this is how it works
i am using my company's laptop.
when i connect to company's network using Pulse secure, my spark context connects successfully. and when i connect to my home network then it doesn't.
strange but that's how it is working for me.
Answer: @GiovaniSalazar is right. You need to import
from pyspark.sql import SQLContext, Row, SparkSession

and define sc
spark = SparkSession.builder.getOrCreate()
sc = spark.sparkContext

then refer to sc
data = sc.textfile('airline.csv')

in your case.

name 'sc' is not defined,


Challenging query in COREDATA

Question: In my Core Data application I have only one table like this:

What I want is a query which returns all rows group by subject in the ascending order of date,
ie
I am not familiar with Core Data predicates. How can I accomplish this?
Comment: http://stackoverflow.com/questions/13667288/how-to-sort-nsmutablearray-of-date-objects
Comment: Please refere below link,it may help you. http://stackoverflow.com/questions/14942912/how-to-group-by-day-in-nsdate-with-nspredicate-needed-to-create-multiple-uitab
Comment: `SELECT * FROM YOUR TABLE_NAME GROUP BY Subject WHERE Date ASC;`
Comment: @Jeff why minus vote? i tried to help you by giving some example.
Comment: @Hemang When I used your code app crashes with following exception *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format string "SELECT * FROM Message GROUP BY Subject WHERE Date ASC"'
Answer: you can write the code like this :-
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"Subject == 'Leave'"];

you will get the list of Subjects with title Leave.Now you can Modify the code as per your requirement.
This will help you to get them in ascending order:-
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"date"
ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];

For   references:-https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Predicates/Articles/pSyntax.html
Comment: please comment what is wrong here for minus vote?
Comment: Atleast read the question before giving answer
Comment: @Jeff  i read the question..if so,please don't tag with iOS,tag it with mac OS.

Challenging query in COREDATA


Encoding problem with node.tpl.php

Question: I am new in Drupal theming and I would like to control the "submitted by" part of a node. I want to remove the name of the author and stylize the created_date of the node. The problem is that I also echo some greek characters that show up in weird symbols in my site. I tried changing the encoding to utf-8 but it won't work. I am not even sure what the original encoding of node.tpl.php is. How would I go inserting my own custom text inside node.tpl.php and printing it correctly?
<?php if ($display_submitted): ?>
  <?php $posted="Δημοσιεύτηκε στις "; echo mb_convert_encoding($posted, "UTF-8", "Windows-1252") . date( "d F, Y",$node->created); ?>
<?php endif; ?>

The code above returns:

Äçìïóéåýôçêå óôéò 12 January, 2012

I also tried utf8_encode function but that was a long shot since it converts ISO-8859-1 strings to UTF-8.
Answer: If the file is correctly saved as UTF-8, it should correctly handle Unicode characters. So far, I have had a problem with the saved file just because the editor I was using added the BOM ("Byte Order Mark") used to identify the encoding of the file, but the error was a different one.
Generally speaking, the Drupal way to have a translatable site is to use t() in your code, which requires the English string that will then be translated to the language set as default, basing on the translation provided to the Language module.
The code should be rather be similar to the following one:
<?php if ($display_submitted): ?>
  <?php t('Submitted by !username on !datetime', array('!username' => $name, '!datetime' => $date)););
<?php endif; ?>

The alternative is implementing hook_preprocess_node(&$variables) (template_preprocess_page() in a theme), and initialize the variable $variables['submitted'] to the string you want to appear ("Submitted by !username on !datetime" in the code I shown before).
Comment: When opening node.tpl.php with notepad++, under the encoding menu the Encode in ANSI is enabled. Not sure if this could be causing the problem since I tried enconding the string from ANSI to utf-8 without luck. But the hook_preprocess solution seems to be a good one. I need to learn how to do it and come back with the results. Thanks for pointing me towards the right direction.
Comment: I tried adding a preprocess function  `biztech_alpha_preprocess_node(&$vars) { $variables['submitted'] = t('Submitted by !datetime', array('!datetime' => $variables['created'])); }`  But i got the same unreadable symbols. Makes sense since you said I need to provide the english string to be translated by the Language module. I guess my best shot is to go and manually add a unique english string through locale and provide its greek translation. So much trouble for changing one line..
Answer: You might want to try the submitted_by module. Since all entered strings go through the Drupal system you shouldn't need to use any encoding functions in your template.
Comment: I was looking for a way to do this without a module but I will definitely give it a try to see if it meets my needs. Thanks.

Encoding problem with node.tpl.php


Github Access Error - AggregateException encountered

Question: I am using a github Repo for almost one year and since this morning I am not able to push my code to the remote repo. I get following error in the command line:

fatal:  AggregateException encountered. Mindestens ein Fehler ist aufgetreten.

The credentials.log contains following error:
<code>System.AggregateException: Mindestens ein Fehler ist aufgetreten. ---> System.Net.Http.HttpRequestException: Fehler beim Senden der Anforderung. ---> System.Net.WebException: Die Anfrage wurde abgebrochen: Es konnte kein geschützter SSL/TLS-Kanal erstellt werden..
</code>
Apparently, yesterday were some releases. See here for more information: https://developer.github.com/changes/2018-02-01-weak-crypto-removal-notice/
Maybe, this could be the reason, but I don't know how to solve it.  Can you help me please? I use Windows 10.
Comment: seems to be the same origin cause..thanks for your hint.
Answer: You need to update git. See here: The last comment from Whoisj. I had the same problem in the morning. It's easy: just download and install git again. See for example here
Comment: Thanks, Christoph :) You saved my day
Comment: Was having the same problem, thanks @Christoph!
Comment: Thanks, It worked for me
Comment: Thanks, that would explain why it worked inside a docker image but not inside my working machine. I had also along ' Permission denied (publickey)' error but within a docker I was able to supply a github token, whereas in the working machine with the old git version it was not possible to supply.


How to mock a function varying the number of invocations and optional arguments?

Question: I want to write a test for "A" function which calls another "B" function in it. B function looks like this:
def Bfuncion(self, city: Optional[str], name: Optional[str]):

in A function I use B function two times, first time I use it in this way:
cities = self.Bfunction(name=None, city="ny", page=page)

and the second time in this way:
cities = self.Bfunction(name="Tom", city=None, page=page)

Now I want to write a test of A function. The test must to verify if there is only one use of the B function:
mocker.patch("Path.To.My.Function",return_value=[{"value1"},{"value2"},{"value3"}],...

How do I write call mocker(), as I use B function with different arguments in each call.
Answer: Use the side_effect keyword argument, not the return_value keyword argument.
>>> from unittest.mock import Mock
>>> m = Mock(return_value=[1,2,3])
>>> m()
[1, 2, 3]
>>> m = Mock(side_effect=[1,2,3])
>>> m()
1
>>> m()
2
>>> m()
3

(patch, of course, simply passes keyword arguments it does not itself recognize to Mock to configure the object that is used by the patched name.)
This requires you to know ahead of time the order of calls that will be made. If you need more flexibility, patch the name with a custom function that behaves the way you want, instead of a Mock object.
def my_func(self, name, city, page):
    ...
mocker.patch(
    "Path.To.My.Function",
    new=my_func
)

Answer: I try to suggest you a solution for your test; I don't know if it is suited for your need because I have tried to guess some details that you have omitted in your question.
The production code
I suppose that your production code is contained in a file called functions.py and the content of functions.py is the following:
from typing import Optional

class MyClass:

    def Bfunction(self, city: Optional[str], name: Optional[str]):
        return city

    def Afunction(self):
        cities = self.Bfunction(name=None, city="ny", page='page')
        print(cities)
        cities = self.Bfunction(name="Tom", city=None, page='page')
        print(cities)

Note that in functions.py:

I have defined a class because I have seen that your definition of the Bfunction contains the self argument.
The Afunction executes the two calls of Bfunction that you have written in your question.

The test file
The test file (which doesn't use pytest but only the module unittest) is the following:
import unittest
from unittest import mock
import functions

class MyTestCase(unittest.TestCase):

    def test_something(self):
        sut = functions.MyClass()
        with mock.patch.object(sut, 'Bfunction') as mock_b:
            # set values returned by Bfunction in the first and in the second call
            mock_b.side_effect = ['cityA', 'cityB']
            sut.Afunction()
            # here I verify that Bfunction is called 2 times
            self.assertEqual(2, mock_b.call_count)

            # here I verify the arguments of the Bfunction 2 calls
            self.assertDictEqual({'name': None, 'city': 'ny', 'page': 'page'},
                                 mock_b.call_args_list[0][1])
            self.assertDictEqual({'name': 'Tom', 'city': None, 'page': 'page'},
                                 mock_b.call_args_list[1][1])

if __name__ == '__main__':
    unittest.main()

The output of test file execution
The output of the test file execution is:
cityA
cityB
.
----------------------------------------------------------------------
Ran 1 test in 0.002s

OK

The output showes:

Afunction calls exactly two times the Bfunction
the test verify the arguments passed to Bfunction by the use of the attribute call_args_list
the presence of cityA and cityB in the output show you how to select different values returned by Bfunction (you have to use side_effect and not return_value).

I hope that this answer is useful for you.


Openstack: how object storage to be used by apps running on VM?

Question: I'm new to openstack, now reading some documentation. I have question about the object storage.
Could the swift object storage be used by apps running on virtual machine? I guess the answer should be YES. If so, do apps also use the Openstack HTTP based API to operate the storage? I'm afraid the performance issue.
Comment: Can you provide more details about the particular performance issues that you are worried about? Making requests against swift just involved HTTP calls, so it should not be compute-intensive, so CPU performance shouldn't be an issue. Are you worried about network performance of moving lots of data in and out of a VM?
Answer: Yep. You can. All external apps interact with OpenStack services via their HTTP API.
Probably the easiest way to interact with Swift is via the python-swiftclient. See
http://docs.openstack.org/cli/quick-start/content/install_openstack_swift_cli.html
If you're using PHP, you might want to consider php-opencloud. See
https://github.com/rackspace/php-opencloud/blob/master/README.md
If you're using Java, you might want to consider jclouds. See
http://www.jclouds.org/
If you're concerned about performance, I'd suggest doing some performance testing to see if they'll meet your needs.
HTH


Website owners to claim their websites by uploading control file ?

Question: For my website directory I would like users to be able to claim their own websites.
This is needed to allow only validated and authorized users to edit website-related content.
I would like the system to ask users automatically to upload a control file with a filename generated in Drupal 7.
Drupal will check automatically if the filename can be downloaded from the claimed website and if so it will assign authorization to the claimant to edit related content.
How to do this in D7, preferably with existing modules ?
Answer: It shouldn't be too difficult to code it:
If you have the website URL and the control file name stored in a node you can use drupal_http_request to perform a GET against the URL and filename.
If you get a status 200 returned the file exists and you can update another field on the node to indicate that the URL has been successfully validated.


Max acceptable key range in piano chords?

Question: I learning how to play the piano by myself, using an electronic keyboard and a software called Synthesia along with some books and online resources.
I am checking out some songs, and some have chords with a really long distance between keys. Like in this example:

As you can see, it is impossible for the average human hand to reach all these keys at the same time, the range between them is pretty big (11 1/2 keys).
So I have 2 questions. First is if there is a max limit distance between keys in piano chords, and secondly, if the image I posted is a correct and "playable" chord.
Comment: Do you have to play the chord with one hand?
Comment: Yes (blue lines represents one hand, green lines represent the other hand). Later in the song it becomes more obvious, see here: http://i.imgur.com/r2HGIxi.png
Answer:
First question: there is no rule, no "max limit" between notes. Sometimes you'll have to figure out yourself the way you spread the notes between your two hands (try the Bach chorales... you're a conductor with four voices, the relative heights of the notes are written relative to the singer's tessitura, not the keyboard player's hands). You'll also face these problems in orchestra piano reductions or in pieces written by composers with notoriously large hands. Everytime you'll have to do your best, just as people with short handspan would do (usually: quick arpeggios, using the pedals, or skipping notes).
Second question: to play the pictured chord I'd play the top F# with my right-hand 2nd finger, which will allow me to play the further coming E with the thumb. You don't have to follow your software colors for finger everytime, this is not what will help you in the long run.
Answer: Well, this is a stretch, but not all that unusual.  Note that the distances on a typical electronic keyboard are slightly smaller than on an upright piano and those are again slightly smaller than those on a grand piano.  Digital piano tends to be typically a bit larger than electric piano (like the Rhodes) or keyboard/synth.
Accordion keyboards are again smaller, with "lady accordions" being smallest.  Of course, carrying a capsized piano around does not make a whole lot of sense in the first place: my chromatic button accordion puts five octaves in less space than a "full-size" piano accordion takes for 3½, and it has no keyboard parts sticking out into airspace (and I can barely span 3 octaves with the right hand).  I digress.
So playability depends quite a bit on the exact type of piano.  Pretty much the only keyboard which tries following some standard is the grand piano keyboard, and it's pretty much the largest size of all.
Answer: Yes, different kinds of instruments have different spacing and different pianists have different hand sizes. And yes, it's often possible to find a fingering that can accommodate wider-spaced harmonies such as in Bach chorales. But, notably, those chorales weren't written to be played on piano. There are standard ranges that are considered appropriate for piano writing (not including electronic keyboards) that are quite useful to know.
First of all, I would say that the odds are good that you should be rolling the chord in one hand in your example. It is very common for composers to write chords that are too big for the hand to play, and what they mean is that you should quickly roll the notes from bottom to top (probably with the pedal down). This is especially common in Brahms, Chopin, Schumann and other Romantic composers. The widest comfortable range for either hand is generally considered to be the octave, and the widest stretch generally used with any expectation that the notes can be played without rolling is a 10th. There are still a number of detailed considerations—including how many and what notes are to be played in between the 10th, whether the 10th spans white key to white key, white to black, etc.—but that's the general rule. There are plenty of pianists who would still have to roll chords that span a 10th, if its very important to you that they don't roll, you have to keep it within an octave.
But that is the span within one hand. The distance between the two hands is, for all intents and purposes, unlimited. I think that the answer to your specific question is that you should roll the chord and use the pedal to create the sustain of the lower notes that you can't hold down. I think that's especially the case with the second example you posted in the comments. That being said, some of the other solutions being offered here are also good—I just disagree with the assertion that there is no limit or rule for hand span on the piano.


How to do color overlay between errorbar and bar in a bar chart?

Question: I have a bar chart with errorbars, and I want to use the same color for both bar and errorbar. However, this would mean that I could not see the bottom part of the errorbar.
library(ggplot2)
library(tibble)

my_df <-
  tibble::tribble(~response, ~estimate, ~lower_ci, ~upper_ci,
                  "little_bit", 0.353477, 0.255625, 0.451747,
                  "no", 0.307639, 0.250436, 0.375393,
                  "very", 0.338883, 0.301007, 0.37572310)

## compare this:
ggplot(my_df, aes(x = reorder(response, -estimate), y = estimate)) +
  geom_bar(stat = "identity", width = 0.9, fill = "#6EB3FF") +
  geom_errorbar(aes(ymin = lower_ci, ymax = upper_ci),
                width = 0.1, size = 3.5)

## with this:
ggplot(my_df, aes(x = reorder(response, -estimate), y = estimate)) +
  geom_bar(stat = "identity", width = 0.9, fill = "#6EB3FF") +
  geom_errorbar(aes(ymin = lower_ci, ymax = upper_ci),
                width = 0.1, size = 3.5, color = "#6EB3FF")

 My visual idea is to use overlay

Is there a way to achieve such overlay using ggplot?
Comment: @Emman It won't do much without changing the color brightness first (see my answer). Or, you add alpha to both.
Comment: You could use `alpha` to set the opacity, e.g. add `alpha = .7` to your geoms.
Comment: @stefan, can I set `alpha` for `geom_errorbar()` rather than for `geom_bar()`?
Answer: A simple alpha would do.
Note you technically have different colors. Another option would be to use color modifying packages such as shades or colorspaces. See one option with colorspaces below. shades is cool when you want to change entire palettes.
library(ggplot2)
library(tibble)

my_df <-
  tibble::tribble(~response, ~estimate, ~lower_ci, ~upper_ci,
                  "little_bit", 0.353477, 0.255625, 0.451747,
                  "no", 0.307639, 0.250436, 0.375393,
                  "very", 0.338883, 0.301007, 0.37572310)

# super easy, just make the bars mor transparent - not quite your desired look
ggplot(my_df, aes(x = reorder(response, -estimate), y = estimate)) +
  geom_bar(stat = "identity", width = 0.9, fill = "#6EB3FF", alpha  = 0.7) +
  geom_errorbar(aes(ymin = lower_ci, ymax = upper_ci),
                width = 0.1, size = 3.5,color = "#6EB3FF")

## darkening the color, and adding some alpha for your desired effect
ggplot(my_df, aes(x = reorder(response, -estimate), y = estimate)) +
  geom_bar(stat = "identity", width = 0.9, fill = "#6EB3FF") +
  geom_errorbar(aes(ymin = lower_ci, ymax = upper_ci),
                width = 0.1, size = 3.5,
                color = colorspace::darken("#6EB3FF"), alpha  = 0.7)

Comment: ((: Yep. We posted almost at the same time. Interesting second option. Maybe I find some time in the holidays to have a closer look at the colorspace pkg.
Comment: See my comment above. Technically, alpha makes your color "lighter", so without changing *both* alphas you would not be able to get the overlying error bars "darker"
Comment: @Tjebo, thank you! The first option is exactly what I'm looking for, just reversed :) It is the errorbar that I want to tweak its opacity, rather than the bar itself. Can this be achieved?
Comment: But then. is it even possible to achieve the same hue on both the top of the errorbar and the bar, as shown in the question?
Comment: @Emman if you give the same alpha, they would have the same appearance. yes. if you don't want alpha this would get very hacky. you would need to create two separat segments for that. Not sure this would be worth the effort
Answer: Perhaps, you should draw the bottom-half of the error bars a second time with a slightly darker color.
ggplot(my_df, aes(x = reorder(response, -estimate), y = estimate)) +
  geom_bar(stat = "identity", width = 0.9, fill = "#6EB3FF") +
  geom_errorbar(aes(ymin = lower_ci, ymax = upper_ci),
                width = 0.1, size = 3.5, color = "#6EB3FF") +
  geom_errorbar(aes(ymin = lower_ci, ymax = estimate-0.004),
                width = 0.1, size = 3.5, color="#3ba8ff")

Comment: @Tjebo, good idea.  I agree that there is no need to define colors. Just use alpha = 0.7 for the first two calls.
Comment: Thanks. I had thought about that too. One limitation with such approach is generalizability over colors. Although here I used a single color for all bars, it's pretty common to have different color for each bar, or simply having different sets of colors. Needing to find a darker color for the bottom segment in each case makes such solution non-practical. Can you think of a "rule" that will allow automation?
Comment: You can define a vector of named colors as a choice for users, say, `color1 <- c("green1","red1","blue1","purple1","steelblue1")`. Then use a slightly darker color for the bottom-half of the error-bar as `color3 <- c("green3","red3","blue3","purple3","steelblue3")`.  You should define large number of colors.
Comment: @Emman try to think outside single boxes! Combine YBS and my answer and you'll have the solution. I.e.., you can use the shades packages to darken/brigthen entire palettes. No need to manually specify colors. Simple.


S3 backup: bucket vs. volume

Question: I've inherited a project that has been pushing encrypted (GPG) DB backups via a backup script to an S3 bucket. That's all been well and good, but now that bootable EBS instances (where the project resides now) can have mounted S3 volumes, why not simply push to the volume? The script living on the server has the S3 credentials so I can't see where it is more secure to continue pushing to S3.
Also, is anyone can point me to a post or article about best practice for pushing backups off-site, I'd be much obliged.
Thanks!
Answer: fused creates a S3 filesystem.. I have never used it but I heard it works great.
http://code.google.com/p/s3fs/wiki/FuseOverAmazon
Best practices?

Don't lose your encryption private key, export it to something and put
it in a safety deposit box.
Don't lose your private key.
Don't lose your private key.

S3 backup: bucket vs. volume


How would I solve $\frac{(n - 10)(n - 9)(n - 8)\times\ldots\times(n - 2)(n - 1)n}{11!} = 12376$ for some $n$ without brute forcing it?

Question: Given this equation:
$$
\frac{(n - 10)(n - 9)(n - 8)\times\ldots\times(n - 2)(n - 1)n}{11!} = 12376
$$
How would I find $n$?
I already know the answer to this, all thanks toWolfram|Alpha, but just knowing the answer isn't good enough for me. I want to know on how I would go about figuring out the answer without having to multiply each term, then using algebra to figure out the answer.
I was hoping that there might be a more clever way of doing this.
Comment: Why not? Brute forcing is very effective, when you can count the number of values that you need to test with your fingers, as is the case here. If you can factor 12376, you will get a very good starting point, but that is a coincidence. Also, if your book has a largish part of Pascal's triangle printed out...
Answer: $12376=2^3\cdot 7\cdot 13\cdot 17$, so $17$ divides $(n-10)\cdots (n-1)n$. Let's start with $n=17$ :)
Edit. Also note that no primes larger than 17 (eg. 19, 23, 29, ...) divide $(n-10)\cdots (n-1)n$.
Comment: So n must be at least 17. From Yuval Filmus' answer, we have that n  must be under 22. As you note, n cannot be 19. So, it must be 17 or 18. 12376 is not divisible by 3, so the power of 3 in the numerator on the left must be the same as the power of 3 in 11!, which is 4. It's then easy to check that n=17 works, and n=18 has too many 3's. (You can also rule out 18 by considering powers of 7. You need two 7's in the numerator, and n=18 only gives one).
Comment: That was how I thought to approach it.It's still kind of tedious trial and error,but it gives you a logical starting point that shouldn't take a ridiculous amount of computation to solve.
Answer: HINT $\rm\displaystyle\ \ 12376\ =\ \binom{n}{11}\ =\ \frac{12}{1}\ \frac{13}{2}\ \frac{14}{3}\: \cdots\: \frac{n}{n-11}\ $ so moving fractions to the LHS yields
$$\displaystyle\quad 12376\bigg)\frac{1}{12} = \frac{3094}3\bigg) \frac{2}{13} = \frac{476}3\bigg)\frac{3}{14} = \frac{34}1\bigg)\frac{4}{15} = \frac{136}{15}\bigg)\frac{5}{16} = \frac{17}6\bigg)\frac{6}{17}\ =\ 1 $$
Hence we conclude $\rm\ n = 17\:.$
Comment: +1 for its simplicity.  But, why the strage notation for multiplication?
Comment: @DJC It omits 6 implicit left-paren's at the start. It's an equational analog of similar Horner form notation. It permits efficient display of computation of cumulative products.
Comment: Neat.  I knew there was a reason.
Answer: The equation implies
$$n\cdots(n-10) = 12376 \cdot 11!. $$
Estimating the LHS,
$$ (n-10)^{11} \leq 12376 \cdot 11! \leq n^{11}. $$
This gives you the value of $n$ up to $11$ values, and you can use binary search to find the correct $n$. Perhaps you could use divisibility properties, but it isn't worth the trouble here.
Comment: Combinatorics makes me feel like an idiot.I feel like an even bigger idiot for not thinking of approximation to set bounds and take it from there.Well done,sir!
Answer: Using @pharmine's factorization, we have
$$\begin{eqnarray*}
n(n-1)(n-2)\cdots(n-10) &=& 17\cdot 13 \cdot 7 \cdot 2^3 \cdot 11! \\
&=& 17\cdot 13 \cdot 7 \cdot 2^3 \cdot 11 \cdot 10 \cdot 9 \cdot 8 \cdot 7\cdot 6\cdot 5\cdot 4\cdot 3\cdot 2
\end{eqnarray*}$$
Now, $17$ divides the LHS, so LHS consists of eleven consecutive integers including a multiple of $17$; given the size of the product, that multiple is likely "$17$" itself. The prime $19$ isn't a factor, so the consecutive integers are either "$18$" through "$8$" (that is, $n=18$), or "$17$" through "$7$" ($n=17$). In either case, the list of integers contains "$17$" through "$8$"; constructing these uses up the RHS factors:
$$(17)\cdot 13 \cdot 7 \cdot 2^3 \cdot 11 \cdot 10 \cdot 9 \cdot 8 \cdot 7\cdot 6\cdot 5\cdot 4\cdot 3\cdot 2$$
$$(17\cdot 16)\cdot 13 \cdot 7 \cdot 2^3 \cdot 11 \cdot 10 \cdot 9 \cdot 7\cdot 6\cdot 5\cdot 4\cdot 3$$
$$(17\cdot 16 \cdot 15)\cdot 13 \cdot 7 \cdot 2^3 \cdot 11 \cdot 10 \cdot 9 \cdot 7\cdot 6\cdot 4$$
$$\cdots$$
$$(17\cdot 16 \cdot 15 \cdot 14\cdot 13\cdot 12\cdot 11\cdot 10\cdot 9\cdot 8) \cdot 7$$
... and we conclude that $n=17$.
Answer: The lefthand side of the equation is ${n \choose 11}$, where ${n \choose k}$ (read "$n$ choose $k$") is a binomial coefficient (see also here).  Since this grows fairly quickly in $n$, you can just start plugging in values.
Answer: First, it is clear that n is greater than 11 for a solution in this case (11 would yield 1 and negative n's would yield negative results).  Now, let's try to get an approximation of n by assuming it is an integer (this won't work if n was less than 11):
$$
\frac{(n - 10)(n - 9)(n - 8)\times\ldots\times(n - 2)(n - 1)n}{11!} = \frac{n!}{11!\times(n-11)!} = 12376
$$
At this point, we have a relatively quick way to check integer solutions, and thus approximate decimal solutions if needed.  For most of us nothing immediately stands as to how to solve this by algebra, so we plug in few guesses to get an approximation of what our answer will be:
$$
n=12:  \frac{12!}{11!\times(12-11)!} = 12
$$
$$
n=15:  \frac{15!}{11!\times(15-11)!} = 1365
$$
$$
n=17:  \frac{17!}{11!\times(17-11)!} = 12376
$$
And voilà, 17 is our answer!  We need not go further!
Comment: @GEdgar:  Thanks, it's probably not a good habit to answer questions with ["the word ignorant people use when they really meant to say voilà"](http://www.urbandictionary.com/define.php?term=wallah)   :)
Comment: wallah, sometimes spelled voila
Comment: It is interesting to look up the definition of "wallah" some time.
Answer: $n(n-1)\cdots(n-10)/11! = 2^3 \cdot 7 \cdot 13 \cdot 17$. It's not hard to see that $11! = 2^8 3^3 5^2 7^1 11^1$; this is apparently known as de Polignac's formula although I didn't know the name. Therefore
$n(n-1) \cdots (n-10) = 2^{11} 3^3 5^2 7^2 11^1 13^1 17^1$.
In particular 17 appears in the factorization but 19 does not. So $17 \le n < 19$. By checking the exponent of $7$ we see that $n = 17$ (so we have (17)(16)\cdots (7), which includes 7 and 14) not $n = 18$.
Alternatively, there's an analytic solution. Note that $n(n-1) \cdots (n-10) < (n-5)^{11}$ but that the two sides are fairly close together. This is because $(n-a)(n-(10-a)) < (n-5)^2$. So we have
$$ n(n-1) \cdots (n-10)/11! = 12376 $$
and using the inequality we get
$$ (n-5)^{11}/11! > 12376 $$
where we expect the two sides to be reasonably close. Solving for $n$ gives
$$ n > (12376 \times 11!)^{1/11} + 5 = 16.56.$$
Now start trying values of $n$ that are greater than 16.56; the first one is 17, the answer.
Implicit in here is the approximation
$$ {n \choose k} \approx {(n-(k-1)/2)^k \over k!} $$
which comes from replacing every factor of the product $n(n-1)\cdots(n-k)$ by the middle factor.


Flask-SQLAlchemy transform field in query

Question: For example I have simple model:
class A(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    value = db.Column(db.Float)
    # some other fields...

And I need sometimes (in the only one query) to get objects with value field multiplied by -1. In other queries I need to get objects with normal value field. How I can do this?
Thanks!
Comment: Do you mean that you'd like to fetch A entity objects that have their value attribute set to `value * -1`? That seems odd. Could you perhaps include a bit more background in your question?
Comment: Can you not just include that logic in the view?
Comment: Yes, I have special case, when I need to view of A entity objects with `value * -1`. In other cases I don't need this.
Comment: The implementation depends on logic of your special case, what it depends on. P.S. I agree with @IljaEverilä, models shouldn't contain data transformation logic and "Special cases aren't special enough to break the rules."
Answer: I suggest a @property approach, where you can assign a logical operation using the model's original attributes:
class A(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    value = db.Column(db.Float)
    # some other fields...

    @property
    def inverted_value(self):
        return self.value * -1

Now for any instance of A you can access the property inverted_value.
For example:
a = A(value=1)
a.value # 1
a.inverted_value # -1

Now, whenever you need the inverted value, just access the newly created property instead of the original one.


Path to inline image  inside page.tpl.php to theme/images/ dir?

Question: Simply  pasted to page.tpl.php doesn't work. It doesn't find the image and requires full path.
I know I've seen somewhere some PHP code which sets full path to image inside the theme's dir.
Answer: The following code will get you the path to your theme, together with your site's base path:
<?php print base_path() . path_to_theme(); ?>

Meaning that you should use something like this:
<img src="<?php print base_path() . path_to_theme(); ?>/images/your-image.jpg">

Note: the path_to_theme() will not have the trailing slash, so you have to add it yourself if your image is in a subfolder.
Comment: Thanks, I actually found a solution myself already. I used
Comment: Isn't the `print` supposed to be inside the `` tag?
Comment: In that case, post the solution and accept is as an answer. It will be useful for other people that have the same issue as you do.
Comment: Yes same as the one posted by @user13176
Comment: @Indrock this gives only image path - it should be used in `src=""` attribute.
Comment: @Topsitemakers Yeah, I'm aware of that! But, I think it'd be spot on if you mention it in you post. That would make it complete ;-)
Comment: Answer updated!


Am I doing this Time complexity for a while loop right?

Question: This is what I calculated, I find myself struggling when It comes to the while loops. Did I do this correctly?
<code>                        //Cost      Times
    count = 0;          //c1        //1
    int j = N;          //c2        //1
    while(j>1) {        //c3        //log2(N) + 1
        count += 1;     //c4        //log2(N)
        j= j/2;         //c5        //log2(N)
    }//T(N) = c1*1 + c2*1 + c3* (log2(N)+1) + c4 * log2(N) + c5*log2(N) =
    //O(log2(N))
</code>
Please help me in anyway possible.
Comment: The time complexity of the while loop is `O(log2(n))`. Not sure about your `T(N)` equation: I don't think you include setup and assignments unless they have non-constant time complexities and pertain to the time complexity being assessed. But I haven't done mathematical big-O analysis in quite some time.
Comment: Your thinking is too complicated. Write N as a binary number, composed of digits 0 and 1. j=j/2 is just shifting right. When the last digit 1 has vanished, the task is done. It's as easy as that.
Comment: Just nitpicking: as the length of an int is limited, the complexity is O(1). ;-)
Comment: Welcome to Stack Overflow! It's great to have you here. However, your question might benefit from some improvements. Could you provide more context and be more specific about your issue? This will help you get better responses. Please read following guide: [How To: Write a good answer](https://stackoverflow.com/help/how-to-answer). Afterwards [edit](https://stackoverflow.com/posts/77068047/edit) your post and improve it. Happy coding!
Answer: Yes, your analysis is correct.
Keep in mind though, when doing complexity analysis, normally you need a data set in order to establish a relationship between the data that is fed into an algorithm and the time needed to process it.
For example, if your input is an array, the time complexity will indeed be O(logN) where N = the size of the array. (The logarithm base is typically ommited because it is assumed to be 2 in CS)


All nearest neighbors in high dimensional space

Question: Suppose I have a very large binary matrix representing $n$ customers and the $m$ products they bought, with $n$ and $m$ both rather large (in the order of millions). The matrix is also pretty sparse.
As computing all (or even just the $k$) exact nearest neighbors for every customer is clearly an intractable problem, I'm looking for a way to approximate it.
One idea I had is to use minhashing/LSH to first segment the customers into approximately $\frac{n}{k}$ buckets (this can be done by tweaking the similarity threshold I assume) and then simply consider that the $k$ neighbors of any given point are the other members of its corresponding bucket. Another slightly less efficient variant that might produce better results would be to segment into $\frac{n}{2k}$ buckets (i.e. bigger ones), and then search for the closest $k$ neighbors by brute force, inside a single bucket.
These schemes would obviously not yield exact results, but I wonder if they might be acceptable nonetheless. I'd also be interested in any other method or idea to tackle this problem.
Answer: The segmented approaches you propose appears reasonable and as do your concerns about the limitations of them. I have not worked on this field but given you problem formulation have you considered K-SVD? I am proposing this because you can take advantage both of the numerical tools available for sparse SVD decompositions as well as the conceptual framework of using SVD information to construct a $k$-means clustering. There are quite a few papers already available where you can check if the assumptions behind this approach can be generalized to accommodate your situation's characteristics (eg. here and here); in addition MATLAB code is already available by the original authors' website. Finally, check this CV link on "https://stats.stackexchange.com/questions/43099/how-to-explain-the-connection-between-svd-and-clustering", it should give a a first helpful nudge.


Best day of the week

Question: I have table with three columns
order;
orderID | ordertotal | datetime

1       | 100.00     | 2015-03-01 17:48:14
2       | 150.00     | 2015-05-10 02:33:20
3       | 5982.23    | 2015-06-11 17:11:30
...

I am trying to find the records for SUM of ordertotals for the days of the week.
In other words, I want to see the best Monday (for sum of ordertotals), best Tuesday and the others.
Finally I will have a result like below for seven days of the week.
 DailyTotal    | DayOfTheWeek | ActualDate

     7500      | Monday       | 2015-03-01
     8000      | Tuesday      | 2015-05-10
     5000      | Wednesday    | 2015-06-11
...

I tried this query and it worked except for ActualDate;
SELECT
    MAX(o2.dailytotal) AS DailyTotal,
    DATE_FORMAT(o2.datetime2, '%W') AS DayOfTheWeek,
    o2.datetime2 AS ActualDate
FROM
    (
        SELECT
            SUM(s1.ordertotal) AS dailytotal,
            DATE(s1.datetime) AS datetime2
        FROM
            order AS o1
        GROUP BY
            DATE(o1.datetime)
    ) AS o2
GROUP BY DATE_FORMAT(o2.datetime2, '%W')
ORDER BY 1 DESC

I'm waiting for your solutions.
Answer: This is a case where the substring_index()/group_concat() trick is probably the best way to express the query:
SELECT MAX(o2.dailytotal) AS DailyTotal,
       DATE_FORMAT(o2.datetime2, '%W') AS DayOfTheWeek,
       SUBSTRING_INDEX(GROUP_CONCAT(o2.datetime2 ORDER BY o2.dailytotal DESC), ',', 1) AS ActualDate
FROM (SELECT DATE(s1.datetime) AS datetime2,
             SUM(s1.ordertotal) AS dailytotal
      FROM `order` o1
      GROUP BY DATE(o1.datetime)
     ) o2
GROUP BY DATE_FORMAT(o2.datetime2, '%W')
ORDER BY DailyTotal DESC;

There are issues with this (such as converting the date to a string and the possibility of the intermediate group_concat() string not being big enough -- which can be adjusted).  However, the alternatives result in much more complex queries.
Your version just returns an indeterminate date.

Best day of the week


Storing a string as a binary string of 'unsigned char's to in matters of compression

Question: I need to store a string of 8 chars (they're all digits) in a compressed method,
As I understand it, each char uses 8 bits which are 1 byte and since I only use digits I can use 4 bits (2^4=16 combinations) so for each unsigned char I can store two digits instead of one. Thus I need 4 bytes to store 8 digits instead of 8 bytes.
Until here am I right or wrong?
Now how am I storing this data in a string of 4 unsigned chars? I'm not looking for an explicit answer just a kick start to understand the motivation.
Comment: That is called [packed BCD](http://en.wikipedia.org/wiki/Binary-coded_decimal#Basics), it used to be rather common but is less so now. You could also consider converting it to a proper integer.
Comment: Yes, you can save your digits like this. A `char` would contain `c = digit1 + 16*digit2` (or similar). To extract the digits, you'd use `digit1 = c % 16; digit2 = c / 16`.
Comment: @Quaker You could, but the math stays the same. Shifting 4 bits to the left is the same as multiplying by 16 (also see nishant's comment).
Comment: @Carsten Ain't I supposed to convert the number to it's binary form using bitshifting from left to right?
Comment: Adding to @Carsten: Also digit1 = c & 0xf ; digit2 = c >> 4.
Answer: There are three obvious ways to store eight decimal digits in four eight-bit values.
One is to reduce each decimal digit to four bits and to store two four-bit values in eight bits.
Another is to combine each pair of decimal digits to make a number from 0 to 99 and store that number in eight bits.
Another is to combine all eight decimal digits to make a number from 0 to 99999999 and store that in 32 bits, treating the four eight-bit values as one 32-bit integer.
To decide between these, consider what operations you need to perform to encode the value (what arithmetic or bit operations are needed to combine two digits to make the encoded value) and what operations you need to perform to decode the value (given eight bits, how do you get the digits out of them?).
To evaluate this problem, you should know about the basic arithmetic operations and the bit operations such as bit-wise AND and OR, shifting bits, using "masks" with AND operations, and so on. It may also help to know that division and remainder are usually more time-consuming operations than other arithmetic and bit operations on modern computers.
Answer: I prefer you use unsigned int as suggested by harold in comments. In unsigned char[4] you may require additional one char for terminating '\0' character.
Use shifting as you yourself suggested for proper conversion from uchar to uint.
Comment: Assuming I had to convert 9 number, I should have converted number by number from right to left with leading 0's on the left. right?
Comment: @Quaker: Yeah, you will convert `"9"` (a string) to `0009` in int.
Comment: I actually have to do it using `uchar`s but I think I got the idea
Comment: @Quaker : **uchar** will make one thing easy: you will not need to go "right to left" you can use '\0' terminator of uncompressed number string as your end point of conversion.
Comment: I'm not sure I have to use the `'\0'` terminator since it's only saved as `uchar` for storing purposes. whenever one wants to use the data it will be converted back to a string of chars.
Comment: @Quaker: How are you keeping track of number of digits in string?
Comment: There will always be exactly 8 digits in the string
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/36320/discussion-between-nishant-and-quaker)
Comment: C has no requirement that an array of characters be terminated with a zero. This is only required for certain library routines. It is not relevant to this question.
Comment: @EricPostpischil : I know that, but I am not aware of how Quaker is implementing his code, that is why I wrote: _you may require..._
Comment: @nishant: And how would `unsigned int` fix that? If you do not know how many items are an `unsigned char [4]`, you would not know how many are in an `unsigned int`.
Comment: @EricPostpischil : I am sorry, but in my answer I meant one additional char to `unsigned char[4]` i.e. `unsigned char[5]` may be required. As Quaker has already said he needs 4 bytes to store, so `unsigned int` will be ok.
Comment: @nishant: How would `unsigned int` replace `unsigned char [5]`? If you need the additional byte to indicate the number of items, how is the number of items indicated in an `unsigned int`?
Comment: @EricPostpischil: Now I got what you want to say, Thanks. And Sorry because I was forgetting the counter that would be required if represented as `unsigned int`.


Problem with surface integral of a scalar function

Question: I have difficulties in integrating this scalar function over the assigned surface. I've tried with the standard method but I always obtain an integral which I don't think can be solved.
Let $\Sigma=\{(x,y,z):(x-2y)^2+(y-x)^2=1,\,0\le x+y+2z\le1\}$
Calculate $\int_\Sigma xdS$
Answer: Hints:
Using the Divergence Theorem, we get $\displaystyle\iint\limits_{\Sigma}x\,dS = \iiint\limits_{V}1\,dV$ where $V = \{(x,y,z) : (x-2y)^2+(y-x)^2 \le 1, 0 \le x+y+2z \le 1\}$.
To evaluate this integral, first use the substitution $u = x-2y$, $v = y-x$, $z = z$.
Then, convert the resulting integral to cylindrical coordinates.
Comment: Thanks, I tried elaborating on this and I think I got it right.
Comment: Are you dure the divergence theorem is applied correctly vere? A couple of colleagues told me it's wrong.


Weekly Calendar Block

Question: I'm looking to display a weekly events calendar. I've set up content type event and added a starting day field. What I'm essentially looking for is this:

So the interface is a tabbed one, so as long as I can get the current week and its events grouped by date I should be fine, but I need to be able to pull future weeks via ajax in a manner the Calendar View does. So the question is this: can this be done with some Calendar View template? How can this be put together with views? I tried to modify the Calendar block provided as Views Template, but all I ended up was a monthly block.
Thank you in advance.
Comment: Are you looking to do this in a block?
Comment: @mlibjh  Preferably yes, but any solution will work. I'm not picky :)
Answer: You can do something quite close to that with views.  When you set up your view (or just use the one that comes with the Calendar module and clone it and start editing your new copy).
Just make sure you go to the Calendar settings and choose 'Week' as your Calendar type:

Of course, you have to choose which fields to display for your event type and here's what you'll roughly end up with:

I've added css to my theme to change the look of this calendar page, and that's probably a separate topic.  Most of the functionality you want is available through the calendar module... just set your type!!
Hope this helps.
================= EDIT =========================
So, after reading your comment, here's how I'd modify the solution above.  Same calendar, but choose 'Day' as the calendar format.  Then under the 'Header' section, add a Header and choose "Global: text area".  Here, using php, we can output links to how many ever days you need before and after today's date... since this doesn't happen automatically.  You'd need to enable the php filter module to make this possible.
So, using the 'php filter' format for the global text, you can add the following code (I would check it to display even for empty views...):
<?php
print( "" . date('l') . " | ");
print( date("l",strtotime("+1 days")) . " | ");
print( date("l",strtotime("+2 days")) . " | ");
?>

The above just prints out today's week day, then tomorrow and the day after.  You can change to suite your needs.  I've also only printed the first one as a link.  You see, the day calendar format can be navigated by just going to /2012/11/23 to get to Nov. 23rd of this year, etc.  Very easy to figure out the links, so you can build your own menu using php in the header.
This is the output you'd get, and of course, you can always beautify with css:
Comment: thanks, this is what I did previously, but as you can see one of the problems is that the month appears at the top and not a date or week, and the other is the calendar layout. I need it to be just a simple list of events.
Comment: Oh, I'm sorry.  I think what may be confusing folks is your statement "...but all I ended up was a monthly block." It seemed to me that you simply weren't aware that you can change to a weekly.  Sorry for the misunderstanding.  I'll see if I can think of a way to get it closer to what you want...
Comment: I've edited my response above... Sorry if that's not quite what you need, but I think it's at least a little closer and may give you some ideas...
Comment: Thank you @Boriana. This got me much closer, although, I must say, I'm ending in writing a completely separate module for this. Just couldn't get along with the Views options. I'm upping your answer so you can get the bounty and will post a link to my module, once it's done. Thank you again for all your help. EDIT: Oh I was able to award the bounty without checking your answer as correct one. Cool.
Comment: Wow, and you've even decided in writing your own module?  You should definitely put that as an answer when you're done because it seems like a layout that many folks would be interested in using!  Good luck!
Comment: Yeah, had no choice but to do it. Views are not helping me here.
Answer: You must use views module with Calender module, see this video to learn how to do it, but after you fishing creating your calender view you must make some CSS changes.
Comment: Yeah, thanks @abd, this is what I've been using, but the available block defaults to monthly view. When I change that to weekly, it still displays the months, but without the events. What I'm actually asking is the correct procedure to create such a View with Calendar module. The CSS and the jQuery won't be a problem once I'll be able to pull the View correctly

Weekly Calendar Block


Drush migration no longer working in 8.5

Question: I've been migrating a site from Drupal 7 to Drupal 8. The site was 8.4 when I ran the migrations. I've since updated the site to Drupal 8.5. Now, when I type drush migration-status or any migration-related command, I get the following error:
[error]  The file_entity plugin must define the source_module property.

Answer: Ok answering this myself. I keep forgetting that Drupal often introduces breaking changes and treats comments as code. It looks like the annotation changed in 8.5
What was in 8.4:
/**
 * Drupal 7 file_entity source from database.
 *
 * @MigrateSource(
 *   id = "file_entity",
 *   source_provider = "file"
 * )
 */

in 8.5 should now be:
/**
 * Drupal 7 file_entity source from database.
 *
 * @MigrateSource(
 *   id = "file_entity",
 *   source_module = "file",
 * )
 */

Comment: Would a slight change in annotation really effect the functionality of Drush? Besides the references page and the given examples talk about 7, but you say you have 8.
Comment: @AltaGrade Not drush as a whole, but running any migration-related drush command threw an error. I fixed one annotation, and then drush migrations worked again.
Comment: Really strange as annotations are not part of executed code, they are just notes. So I do believe something else is going on here.
Comment: @AltaGrade If you find another way to resolve the issue, please let me know. https://www.drupal.org/docs/8/api/plugin-api/annotations-based-plugins


How can I convert 2's complement to decimal?

Question: Suppose I have the 2's complement, negative number 1111 1111 1011 0101 (0xFFBB5).  How can I represent this as a decimal number in base 10?
Answer: Here is the process to convert a negative two's complement number back to decimal:
(1) flip all the bits,
(2) add 1, and
(3) interpret the result as a binary representation of the magnitude and add a negative sign
So, for your example, we have:
$$1111~1111~1011~0101 \xrightarrow{(1)} 0000~0000~0100~1010 \xrightarrow{(2)} 0000~0000~0100~1011 \xrightarrow{(3)} -75$$
It looks like you wrote the wrong binary and meant:
$$1111~1111~1011~1011~0101 \xrightarrow{(1)} 0000~0000~0100~0100~1010 \xrightarrow{(2)} 0000~0000~0100~0100~1011 \xrightarrow{(3)} -1099$$
Of course, in Hex, you can invert all the bits and add 1 and take a negative magnitude.
Regards
Comment: Great outline of strategy, and followed by applying it (perfect combination) +1
Answer: If $x$ is an $n$ digit number written in two's complement, then ${\small\sim}x +1 = -x$, where ${\small\sim}x$ is the $n$-digit binary NOT of $x$. In your case, <code>~0xFFBB5 + 1 = 0x0044B = 1099</code>, so your number is $-1099$.
Answer: A very simple way of converting 2's complement negative number to decimal.
Let a number 11010110,
so the decimal representation of it is,
 –2^7 + 2^6 + 2^4 + 2^2 + 2^1 = – 128 + 64 + 16 + 4 + 2 = – 42
the idea is same as converting a normal binary number to decimal but with a negative sign with left most binary digit.


Only show app-settings for "special" users

Question: I'm using Settings.bundle for few configuration settings for my app.
Now I'm searching for a solution to hide all, or even better, some configuration parts for the casual users. Only a 'admin' should see and edit these fields.
Is it possible to check for a password before showing the settings-properties?
If not, what could be a suitable solution? (new view controller with secret gesture or button?)
Thx in advance!
Answer: You won't be able to do anything special in the settings bundle. It's static, whatever you compile is what all users will see. If you want special behavior, there are two ways to do it:

Put it in the app itself and only allow the user access if they have the right credentials. A secret gesture could work too, but is a little dangerous because users may accidentally find out about it.
Use a different target/scheme or compile-time conditionals (using <code>#if</code>) to build two different versions of the app, one that does include the special configuration and one that doesn't. Personally, I would go for this option, but it may be a little harder initially.
Comment: Ok, then I'll try to handle it over an login mask and disable the settings.bundle for my app.


naming a string array in a xml file in android studio gives me an error

Question: enter image description here
There is a problem in name = "pieces"
Comment: Thank you so much it is working now
Answer: if the studio is not giving you much error info try to clean and rebuild and see if that fixes your problem.
Pasting as answer in case in future someone refer this and miss the comment.


How to remove a role after a user adds a payment method in Commerce?

Question: I am trying to set up a subscription-based site in Drupal 8/Commerce 2.
I'm using Commerce Stripe to process payments.  I want to remove a role from a user ("needs to add new card" role) when the user adds a new payment method (credit card via Stripe) on the payment method page (user/UID/payment-methods).
I assume I need to write an event subscriber, but I don't know which event to use for adding a payment method.
I tried to read through the code in commerce/modules/payment/src/EventSubscriber, but I couldn't find the event I need to hook into to remove the role.
Background
When a user's credit card has expired, they need to add a new card (add a new payment method).  In this case, I have flagged the users with a role, Add new card role.
Then I show a block to users with the Add new card role that says "Please update your card info." with a link to add a card.
However, when the user adds a new card, they still see the block asking them to add a new card, which is confusing.  So I want to immediately remove the Add new card role (to hide the block) as soon as the user adds a new card.
Answer: commerce doesn't offer the (content-)entity create event. You could use a hook ..

hook_ENTITY_TYPE_create -> after the entity was created 8will suit your need I guess)
hook_ENTITY_TYPE_presave -> before the entity will be created

Or setup events for entity creation, see Does Drupal 8 entities have any events I can listen to?
Comment: Thanks, this is what I needed to know!  Note that in this case, it turns out that Commerce requires using `hook_ENTITY_TYPE_insert` instead of `create`; see my answer for details.
Answer: Based on the hint from rémy, here's the actual code I used.
Note that for commerce payment methods, you have to use hook_entity_insert() specifically instead of hook_entity_create() because hook_entity_create() gets called when you go to the payment method add page-- even if you immediately go back without entering any information.
/**
 * Remove the 'credit_card_update_role' upon adding a credit card.
 *
 * {@inheritDoc}
 */
function MYMODULE_commerce_payment_method_insert(\Drupal\Core\Entity\EntityInterface $entity) {
  $uid = \Drupal::currentUser()->id();
  $account = User::load($uid);
  if ($account->hasRole('credit_card_update')) {
    $account->removeRole('credit_card_update');
    $account->save();
  }
}

I added a redirect because by default users are redirected to the payment method edit page, which will result in an access denied error. To avoid this, I send them to the user profile page with a confirmation that the card was added.
/**
 * Redirect users to their profile pages after adding a new card.
 *
 * {@inheritDoc}
 */
function MYMODULE_form_commerce_payment_method_add_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // Redirect users to their profile pages.
  $form['actions']['submit']['#submit'][] = '_MYMODULE_commerce_payment_method_insert_form_submit';
}

/**
 * Redirect users to their profile pages when submitting the edit form.
 */
function _MYMODULE_commerce_payment_method_insert_form_submit($form, &$form_state) {
  \Drupal::messenger()->addStatus('Thank you for updating your credit card!');
  $form_state->setRedirect('entity.user.canonical', ['user' => \Drupal::currentUser()->id()]);
}

Comment: Thx for sharing :D


Reflect on y axis in 3D Matrix?

Question: I have a question saying "Define a 3D Matrix that performs a reflection in the y axis" but I don't know how to solve it.
So if we have a 2D matrix and we say 'reflection on the y axis' we mean that x becomes -x. So a point (x,y) will be (-x, y).
But what about in 3D? If we are reflecting on y, are both x and z negated?
I tried to look for solutions and found this website http://www.idomaths.com/linear_transformation_3d.php on which I can see it's talking about xy, xz and yz planes.
Does 'reflect on the y axis' mean the same thing as 'reflect against the xz plane'?
Thanks
Answer: When a question asks you to find a matrix representing a linear transformation $T$ that is only described geometrically, your task is to figure out how that $T$ transforms a basis for your domain.
Unfortunately I can't find a good image on Google Images to describe reflection through a line in $\Bbb R^3$ (and my pgfplots-fu is still pretty basic), but I'll try to describe what it means.  Consider an arbitrary point in $\Bbb R^3$.  Now connect that point to the $y$-axis by a line segment that is orthogonal to the $y$-axis.  Extend that line segment past $y$ by the same length as the distance from the point to the $y$-axis.  The far end of that line segment is then at the point that is the reflection of your point across the $y$-axis.
Let's see how this affects the standard basis $\{\hat x, \hat y, \hat z\}$.  $T(\hat x)$ goes back along the $x$-axis, goes through the $y$-axis at the origin, and then to $-\hat x$.  Thus $T(\hat x) = -\hat x$.  Likewise $T(\hat z) = -\hat z$.  $\hat y$ on the other hand is unaffected by this transformation -- it's its own reflection across the $y$-axis.
Thus, if $T(x) = Ax$ where $A$ is a $3\times 3$ matrix, then $$\begin{matrix}A \begin{bmatrix} 1 \\ 0 \\ 0\end{bmatrix} = \begin{bmatrix} -1 \\ 0 \\ 0\end{bmatrix}, & A \begin{bmatrix} 0 \\ 1 \\ 0\end{bmatrix} = \begin{bmatrix} 0 \\ 1 \\ 0\end{bmatrix}, & A \begin{bmatrix} 0 \\ 0 \\ 1\end{bmatrix} = \begin{bmatrix} 0 \\ 0 \\ -1\end{bmatrix}\end{matrix}$$
Therefore $$A = \begin{bmatrix} -1 & 0 & 0 \\ 0 & 1 & 0 \\ 0 & 0 & -1\end{bmatrix}$$

The difference between reflecting through a line vs a plane in $\Bbb R^3$ is comparable to reflecting through the origin vs a line in $\Bbb R^2$.  Go back and look up the geometric properties of even and odd functions if you don't remember how these reflections work in $\Bbb R^2$ (note however that you can still reflect through the origin in $\Bbb R^3$).
Try to visualize each of these reflections in $\Bbb R^2$ and $\Bbb R^3$.  Then consider how you think reflections would work in $\Bbb R^n$ for other values of $n$.
Comment: what does it mean to reflect on a line in three dimensions?
Comment: @abel I tried to explain what reflecting through a line in $\Bbb R^3$ means in my $2^{nd}$ paragraph (or at least one *specific* line, but the same technique applies to *any* line passing through the origin).
Comment: i understand that now. perhaps another way of seeing is to project onto the  $y$-axis and subtract the projection to get the normal component. that is $r = r_{\parallel} + r_\perp$ and $T(r) = r_{\parallel} - r_\perp.$
Comment: Mentally that's what I was describing, but I figured reflections probably come before projections in most linear algebra courses -- though I could be wrong.
Comment: no, you explained well(+1). i was just lazy to read through a whole paragraph.
Answer: No, these mean two different things;
the reflection in the y-axis takes $(x,y,z)\to(-x,y,-z)$.
You can write down the matrix from this fact, and you can also get it
using $R=2P-I$, where $P$ is the matrix that projects each point onto the y-axis.

Reflect on y axis in 3D Matrix?


ggplot2 different label for the first break

Question: Hi I am plotting events in ggplot2 and want to be able to tell the entire date time of the event, but not have cumbersome axis labels.
The events are normally a few hours up to a few days, possibly up to a couple of weeks, and are all in one data set. Sometimes I'm plotting them separately or faceting the plot, so hopefully any solution would work with either method. As many of the events only go for a few hours overall the default breaks are good (i.e. in my example below for an event 'a' break every 3 hours makes sense) but you cannot tell when they are, in this example these 9 hours could be on any day of any month of any year. I'm looking for a smart way to show that this is January the 1st 2001 without that having to be repeated for each break point. My idea was that the first break could have all the info but the ones after remain the same, but I'm not sure if that is the best approach or how to do it if so.
Example data and plot: (obviously not real data. In real life the events are calculated through an automatic process so I won't know the start or end dates or how long they go for, so can't have any hard coded breaks etc)
library(lubridate)
library(ggplot2)

testdata <- data.frame(
  DateTime = ymd_h("20010101 15", "20010102 00", "20030303 03",
                    "20030305 00","20070205 00","20070205 10"),
  Value = runif(6),
  Event = rep(letters[1:3], each = 2)
)

ggplot(testdata, aes(x = DateTime, y = Value))+
  geom_point()+
  facet_wrap(~Event, scale = "free")

I wondered about setting date_breaks and date_minor_breaks but it looks pretty bad even with only a few events of not that different lengths. If I added a long (say 10 day) event it would look really bad.
ggplot(testdata, aes(x = DateTime, y = Value))+
  geom_point()+
  facet_wrap(~Event, scale = "free")+
  scale_x_datetime(date_breaks = "day", date_minor_breaks = "3 hours"
                    )

Answer: One solution is to write a function for date_labels
This function gives the full date/time for the first label and then just the hours/minutes for the other labels. You could make the format an argument, or add some simple heuristics to change the format according to the duration.
first_date <- function(x){
  lab <- as.vector(x)
  lab[!is.na(x)] <- c(
    format(x = x[!is.na(x)][1], format = "%Y-%m-%d %H:%M"),
    format(x = x[!is.na(x)][-1], format = "%H:%M")
  )
  lab
}

ggplot(testdata, aes(x = DateTime, y = Value))+
  geom_point()+
  facet_wrap(~Event, scale = "free") +
  scale_x_datetime(labels = first_date) +
  theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust = 1))

Comment: Sweet thank you. I knew in theory that you could write your own functions for `date_labels` but never realised is was this simple/how you would make the first one different. Thanks!


Manage 2 separate page cache for the same URI

Question: We have a multilingual website build with Drupal 7.
We have a IP detection for detect Chinese users. Chinese laws do not allow the use of certain JS librairies. In our case, for one page, we use Google Map for all the users in the world, and we replace the library with Baidu Map for Chinese IP.
The problem is that if the first user is Chinese, then Drupal will cache the page with BaiduMap. Anonymous users from all the world will then have the page with Baidu Map even if there aren't Chinese (since it is the same URI).
We can detect if the IP is Chinese or not. So, how can we handle 2 separate page cache according to the user IP and then call the right cached page ?
Answer: This assumes that the theme is changing.
Settings.php file:
<code>// Check if cookie is set.
if (!empty($_COOKIE['custom_theme'])) {
  // Add theme name to page cache id.
  $_SERVER['REQUEST_URI'] .= '#' . $_COOKIE['custom_theme'];
  // Set Theme.
  $conf['theme_default'] = $_COOKIE['custom_theme'];
}
// Disable page cache if cookie not set so hook_init code can set the cookie.
else {
  $conf['cache'] = CACHE_DISABLED;
}
</code>
hook_init():
<code>  // If no cookie is set set a cookie with the value of theme_default.
  if (empty($_COOKIE['custom_theme'])) {
    $temp = empty($custom_theme) ? variable_get('theme_default') : $custom_theme;
    setcookie('custom_theme', $temp, time() + 60*60*24*30, ini_get('session.cookie_path'), ini_get('session.cookie_domain'));
  }
</code>
Comment: Very good idea ! I will try this tomorrow. 'Keep you in touch ! Thanks.
Comment: That's mean that page caching is based on $_SERVER['REQUEST_URI'] ? Didn't know that!
Comment: @Gaius Yep - Inside [drupal_page_get_cache()](https://api.drupal.org/api/drupal/includes!bootstrap.inc/function/drupal_page_get_cache/7.x) it calls [request_uri()](https://api.drupal.org/api/drupal/includes!bootstrap.inc/function/request_uri/7.x) which looks at $_SERVER['REQUEST_URI']. Append a custom string to the URL via an anchor [(#)](https://en.wikipedia.org/wiki/Fragment_identifier) and you're good to go!
Comment: Apparently, it doesn't work :(. Blank page with ERR_TOO_MANY_REDIRECTS error. This appends when I add an anchor on $_SERVER['REQUEST_URI'].
Comment: FYI we use URL aliases, is this related ? I've been testing during 2 hours but without succes.
Comment: @Gaius URL aliases should not effect this. Adding additional data to the `$_SERVER['REQUEST_URI']` shouldn't cause what you're describing unless you have some custom code doing something with it. Any custom redirect code? Most modules like [Global Redirect](https://www.drupal.org/project/globalredirect) don't use this variable.
Comment: Sorry for the delay, the problem was Global redirect indeed. I fix it when GR call request_uri(), I replace the anchor by an empty string. It works like a charm now ! Thanks you !


Geometric proof that the chord of a larger central angle is longer

Question: In a circle, as we increase a central angle from 0 to 180 degrees, the length of the subtended chord grows, from 0 to the diameter of the circle. My question is how to prove this. I.e., that the chord subtended by a larger central angle will be longer.
This is quite easy to see visually and easy to prove with trigonomry and calculus (e.g., see Will the chord of a larger central angle be longer than the chord of a smaller central angle?) but I was wondering how to prove it with much more basic geometry.
To use a specific example, consider a circle with radius R, and a central angle of 61 degrees. We want to prove that the length of the chord is more than R. Indeed, for a central angle of 60 degrees, the chord length is exactly R (the central angle and the chord make an equilateral triangle, so the chord length is also R), so because 61 > 60 the chord for 61 should be longer than R. The question is how to prove this without knowledge of trigonometric functions or their properties.
Comment: See Wikipedia: [Hinge Theorem](https://en.wikipedia.org/wiki/Hinge_theorem), or ProofWiki: https://proofwiki.org/wiki/Hinge_Theorem
Comment: It is true that the ***larger*** is the central angle $\theta$; where $0^0 \le \theta \le 180^0$, the ***larger*** is the subtended chord L. However, L is NOT directly proprotional to $\theta$!
Answer: Player3236's comment really says it all; I'm just going to place those links here so the question reads as "answered."
Wikipedia has an entry for the Hinge Theorem, and ProofWiki has a proof.
For the sake of completeness, I should mention that this theorem appeared in Euclid's Elements. You can see, for instance, this link for more from those books.


What should I consider before adding workers to my App Pool

Question: My Website is hosted across 3 production web servers and uses ASPNET Session management in the db. I have no sticky sessions on the load balancer so every other request goes around the servers in round robin.
Because of this I can't see a problem with allowing the app pool to use more than one worker.
What do I need to check first? Or should I just move forward?
Answer: What are you trying to achieve by using web gardens? If it is increased performance, then definitely do NOT do this. Web gardens, while advertised by Microsoft documentation and books as increasing performance, typically tend to decrease it - especially if the bottleneck in your application is the cpu.
What they are used for is if you are having reliability problems (your application pools keep crashing) - the web garden can make your application more reliable, but you will probably take a performance penalty for that.
Here is a great blog post that walks through whether you should use web gardens or not:
http://blogs.technet.com/mscom/archive/2007/07/10/gardening-on-the-web-server.aspx
Also, here is Microsoft's documentation on when it could make sense to use a web garden for performance reasons - but maybe take it with a grain of salt:
http://technet.microsoft.com/en-us/library/cc759278(WS.10).aspx
Comment: That blog post is very concise. My problem is that the application decreases in speed every few hours as it uses more memory. I have raised bugs with the development team but they are a way off. I thought that by shortening the recycle period I could add web gardens to keep the app up when one app pool worker recycles.
Comment: @Stewart Robinson: are you just letting the pools recycle when they run out of memory? If so, how about changing to some sort of staggered time-based recycle (server 1 recycles every hour on the hour, server 2 recycles every hour at 20 after, server 3 recycles every hour at 40 after).
Answer: In addition to MattB excellent answer you need to consider impact extra application pools will have on the number of available TCP ports.  Keep in mind that there are only so many ports on a server, no matter how many application pools you have.  They will all compete for these ports.
Comment: Did you really intend to say "impact that extra *Worker Processes* will have on the number of available TCP ports."?


404 error on localhost using flask and html

Question: I am attempting to create a form that takes user input, and gives its prediction. I used flask to create an API for my model, and send the user to another page displaying the prediction. I was able to get the code to work on the development server, but trying the website on localhost yielded a '404 not found` error. I've looked at similar problems, but haven't gotten the results I've wanted.
Have I setup my form correctly? Is my app.py missing information? Any help would be appreciated, thanks!
Comment: Can you include the full error message? Which url did you did the error?
Comment: Looking at the hints given my PyCharm, I think it might be because you did not create a separate folder called `templates` for the html files
Comment: I did create a templates folder, and the html pages are in it
Comment: I'm not getting an error in pycharm, but when I launch the page with the form and click submit, it redirects it to a page that says '404 not found'. This is the url that was on that page: http://localhost:63342/html5up-stellar/templates/%7B%7B%20url_for('predict')%20%7D%7D
Comment: The templates directory needs to be located in the app's root directory or search path needs to be adopted. https://flask.palletsprojects.com/en/1.1.x/tutorial/layout/ https://flask.palletsprojects.com/en/1.1.x/quickstart/
Comment: I may have misunderstood the structure, but I've added a picture of my directories, is it correct?
Answer: The template structure you're using is correct. Looking at the error and the url, I think this error is caused by you directly opening the html file in the browser from PyCharm rather than running the app. When you directly render the file from PyCharm, the app is not running, so it throws a 404 error when you're trying to link to other files.
What you need to do is in your terminal execute flask run and start from the url given - something similar to 127.0.0.1:5000.


Show right node revision for View Draft, View Publised links

Question: I am using panels to override node template and on panels I am adding views blocks for the node content. I have workbench moderation enabled for this node. Issue is in showing the appropriate revision of node for workbench for example

When I use View published or View Draft link, I am seeing all revisions of node field instead of current revision for View Draft and published revision for View published.

The view I have created is on base table: node_revision and fields I am adding are Content (historical data). from panel I am passing Revision ID as context to view and in view I have contextual filter set as Content revision: Nid
Do I need to create two separate views display filtered by Workbench moderation : current and Workbench moderation : published and switch between them on basis of URL having draft or not?
Answer: Make a clone of the view that workbench itself uses, and use that as a base to work from.
Answer: You need to use the 'Content revision' relationship on the field to get the correct link to the node.
Also make sure you have the correct relationship, there's two which both have the same name but are on different fields (nid and vid). There's an issue here that descibes the naming problem of these two relationships. The one on the nid is the one to use as it brings in all of the revisions for each node.
Then you can add a filter to the view to only show the current state (Workbench moderation : current).


How come Drupal Console is not downloading all commands?

Question: When adding Drupal Console using Composer, we are finding that the list of commands is not complete. How can I resolve the issue?
Installation steps:

change to root directory (/local/path/drupal-site)
run composer require drupal/console:~1.0 --prefer-dist --optimize-autoloader
run composer update drupal/console --with-dependencies

Steps to reproduce:

Change to either Change to drupal-site/vendor/bin/ or drupal-site/vendor/drupal/console/bin directory
run drupal generate:form
error message below is returned.
change to root directory (/local/path/drupal-site)
run vendor/bin/drupal generate:form
error message below is returned again.

[ERROR] Command "generate:form", is not a valid command name.

Versions:

Drupal core v8.5.5
Composer 1.6.3
Drupal console 1.8.0

output of drupal list
Comment: You're probably running it outside a bootstrapped Drupal - the list of available commands is substantially shorter when you do that
Comment: @Clive how would we install it otherwise? The Drupal site was installed using Composer.
Comment: You need to run the command inside the web folder, otherwise drupal console doesn't find the drupal installation
Answer: After spending hours on chasing this same issue, i quit and now use drush to create boilerplate stuff such as module, plugins etc.
After you install drupal site via composer with --dev try the following.
./vendor/drush/drush/drush generate module-standard # other generate commands there as well

Comment: Yes, Drush has generators now.


Lavaan growth model: to treat endogenous variable as ordinal or continuous

Question: I am modelling the trajectories of scores on two cognitive tests (i.e., PAL and SOS) measured at four time points. To do this I am creating separate latent growth curve models for each cognitive test, using the growth function from lavaan.
However, I am unsure whether I should treat the cognitive variables as ordinal or continuous - note they are endogenous variables within the models. I have a number of covariates as well, which are made up of both continuous, ordinal and dichotomous variables.
I am aware that it is possible to specify that variables are ordinal using the "ordered" argument.
The range of possible scores on both cognitive tests is integers 0-16 for PAL and integers 0-20 for SOS. Despite this, most scores make up only a narrow range of possible scores. The data does not appear to be normally distributed when looking at histograms (see below).
Should these variables be treated as continuous or ordinal? Are more checks needed?
Thank you in advance!
PAL:

SOS:
Answer: I'd treat this as continuous.
Treating data as ordinal where there are a large number of categories can lead to computation / identification problems.
Comment: To address non-normality you could use maximum likelihood estimation with robust standard errors and test statistics (e.g., Satorra-Bentler correction).
Comment: I have just found this previous answer which addresses my questions in the above comment: https://stats.stackexchange.com/questions/570637/path-analysis-with-missing-data-and-dichotomous-exogenous-variables-in-lavaan
Comment: If it's only 1 in 7000 that outlier won't make much difference anyway.
Comment: Thanks for your suggestion! I have incomplete data and will be completing my analysis using lavaan - will the "MLR" estimator option (i.e., Huber-White correction) be appropriate? And can this be used with FIML for missing data? For example, growth(model_PAL.noGrowth.FIML , data=data_wide, missing="fiml.x", estimator = "MLR")
Comment: Thanks, @ChristianGeiser, would the use of a robust estimator also help overcome issues resulting from outliers?

In the dataset I'm working with, all scores on the cognitive tests are plausible, however, there are only very few that obtain scores at the extremes (e.g., 1 person out of 7000 scored 16/16 on PAL at baseline, most people score 4 or 5 per image in the original question above).


How to get email addresses from an AD Security Group inside a SharePoint Group for a Workflow

Question: I have a workflow that is supposed to send an email to a list of users based on a SharePoint Group. The issue I'm having is the group is populated from an AD group.
So I'm not sure of how to filter the data coming into my workflow or if an HTTP Request is the proper way to pull in that information.

And this is the SharePoint Group where I am pulling the data from:
Answer: If you want to get users from the AD group, you need to use the Azure AD connector. You also have to parse the JSON returned by the REST API to test if principals in the SharePoint group are users or AD groups.

So, let's go!
After the REST API, add an action to parse JSON.

The schema is:
{
    "type": "object",
    "properties": {
        "d": {
            "type": "object",
            "properties": {
                "results": {
                    "type": "array",
                    "items": {
                        "type": "object",
                        "properties": {
                            "__metadata": {
                                "type": "object",
                                "properties": {
                                    "id": {
                                        "type": "string"
                                    },
                                    "uri": {
                                        "type": "string"
                                    },
                                    "type": {
                                        "type": "string"
                                    }
                                }
                            },
                            "Alerts": {
                                "type": "object",
                                "properties": {
                                    "__deferred": {
                                        "type": "object",
                                        "properties": {
                                            "uri": {
                                                "type": "string"
                                            }
                                        }
                                    }
                                }
                            },
                            "Groups": {
                                "type": "object",
                                "properties": {
                                    "__deferred": {
                                        "type": "object",
                                        "properties": {
                                            "uri": {
                                                "type": "string"
                                            }
                                        }
                                    }
                                }
                            },
                            "Id": {
                                "type": "integer"
                            },
                            "IsHiddenInUI": {
                                "type": "boolean"
                            },
                            "LoginName": {
                                "type": "string"
                            },
                            "Title": {
                                "type": "string"
                            },
                            "PrincipalType": {
                                "type": "integer"
                            },
                            "Email": {
                                "type": "string"
                            },
                            "Expiration": {
                                "type": "string"
                            },
                            "IsEmailAuthenticationGuestUser": {
                                "type": "boolean"
                            },
                            "IsShareByEmailGuestUser": {
                                "type": "boolean"
                            },
                            "IsSiteAdmin": {
                                "type": "boolean"
                            },
                            "UserId": {},
                            "UserPrincipalName": {}
                        },
                        "required": [
                            "__metadata",
                            "Alerts",
                            "Groups",
                            "Id",
                            "IsHiddenInUI",
                            "LoginName",
                            "Title",
                            "PrincipalType",
                            "Email",
                            "Expiration",
                            "IsEmailAuthenticationGuestUser",
                            "IsShareByEmailGuestUser",
                            "IsSiteAdmin",
                            "UserId",
                            "UserPrincipalName"
                        ]
                    }
                }
            }
        }
    }
}

Next, add a foreach on the previous result.
In the loop, add a condition to separate groups from users.

Condition is:
LoginName starts with c:0t.c|tenant|

If "yes", it's a group.
You have to get group id from the login.

Create a variable with this expression:
split(items('EachGroups')?['LoginName'], '|')[sub(length(split(items('EachGroups')?['LoginName'], '|')), 1)]

Next, add Azure AD connector to get group's users.
You can add a loop to get every user email.
items('EachUser')?['userPrincipalName']

Comment: I am having trouble with creating the variable within the condition. I dont have the option of the Group ID from the pull-down menu. I think I'm definitely missing something
Comment: You need to create a variable of type string at the beginning of your flow. At this step, you have to define the variable's value with the expression.


Gerar nome aleatório no MySQL - Stored Procedure

Question: Boa noite, há alguma maneira de gerar nomes aleatórios com stored procedure no MySQL?
Tenho a seguinte tabela:

ALUNO(id:int[PK], nome(varchar(100)), idade: int, Cr(float))

Preciso popular essa tabela com 10mil entradas.
Para gerar os números aleatórios encontrei a função RAND() do MySQL, porém não encontrei nada relacionado à VARCHAR aleatório com Store Procedure.
Comment: Dá uma olhada nessa aqui:http://thecodecave.com/downloads/NameGeneration.sql
Answer: Uma maneira que encontrei e nada elegante foi a seguinte.
Utilizar o a função substring() em conjunto com a rand() para selecionar uma letra aleatoriamente dentre todas as do alfabeto que passei como argumento.
Após isso usar a função concat() para concatenar todas as letras em uma só.
<code>delimiter $$
drop procedure if exists projBD.populaAluno $$
create procedure populaAluno()
begin
declare nome varchar(100);
declare idade int ;
declare cr float;
declare counter int default 0;
while counter <= 10000 do
    set nome = concat(substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ ', rand()*28, 1),
                  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ ', rand()*28, 1),
                  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ ', rand()*28, 1),
                  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ ', rand()*28, 1),
                  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ ', rand()*28, 1),
                  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ ', rand()*28, 1),
                  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ ', rand()*28, 1),
                  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ ', rand()*28, 1),
                  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ ', rand()*28, 1),
                  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ ', rand()*28, 1),
                  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ ', rand()*28, 1),
                  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ ', rand()*28, 1),
                  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ ', rand()*28, 1),
                  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ ', rand()*28, 1),
                  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ ', rand()*28, 1),
                  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ ', rand()*28, 1)
            ) ;
     set idade = floor(1 + (rand() * 99));
     set cr = rand()*10 ;
    insert into ALUNO (nome,idade,cr)
    values (nome,idade,cr);
    set counter = counter + 1;
    end while;
End $$
delimiter ;
</code>
Answer: Já pensou em utilizar uma ferramenta como o http://www.generatedata.com ? ele pode gerar saídas em vários formatos, inclusive SQL
Comment: Então, o exercício somente mencionava inserir 10k alunos aleatórios utilizando stored procedure. Não falava sobre inserção de dados de fora.
Contudo, essa é uma excelente ferramenta! Vou salvar aqui este link.