Day Scrolling para Mês Scrolling

Question: Boa noite!
Tenho este exemplo de day scrolling que faz o usuário percorrer pelas datas do mês a cada clique tanto para frente quanto para trás. Porém, gostaria de que, em vez de a cada clique avançar o dia, ser avançado o mês para frente ou para trás. É possível?
Segue abaixo meu código:
pagina2.dart
import 'package:flutter/material.dart';
import 'package:king_app/pages/calendar/scrolling.dart';
class Pagina2 extends StatelessWidget {

  DateTime selectedDate = DateTime.now();
  DateTime startDate = DateTime.now().subtract(Duration(days: 50));
  DateTime endDate = DateTime.now().add(Duration(days: 50));
  Map<String, Widget> widgets = Map();
  String widgetKeyFormat = "yyyy-MM-dd";

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: PreferredSize(
          preferredSize: Size.fromHeight(0),
          child: AppBar(
            backgroundColor: Color(0xFF11c76f),
            elevation: 0,
          ),
        ),
      body: Container(
        padding: EdgeInsets.only(top: 0),
        child: ScrollingDayCalendar(
          startDate: startDate,
          endDate: endDate,
          selectedDate: selectedDate,
          dateStyle: TextStyle(
            fontWeight: FontWeight.bold,
            color: Colors.white,
          ),
          displayDateFormat: "dd/MM/yyyy",
          dateBackgroundColor: Color(0xFF11c76f),
          forwardIcon: Icons.arrow_forward,
          backwardIcon: Icons.arrow_back,
          pageChangeDuration: Duration(
            milliseconds: 700,
          ),
          widgets: widgets,
          widgetKeyFormat: widgetKeyFormat,
          noItemsWidget: Center(
            child: Text(
                "teste " ),
          ),
        ),
      )
    );
  }
}

scrolling.dart
library scrolling_day_calendar;

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

typedef ScrollingDayCalendarBuilder = Widget Function(
    BuildContext context,
    DateTime startDate,
    DateTime endDate,
    DateTime selectedDate,
    Function onDateChange,
    );

class ScrollingDayCalendar extends StatefulWidget {
  // first date on the pages
  final DateTime startDate;
  // last date on the pages
  final DateTime endDate;
  // the active date
  final DateTime selectedDate;
  // what to do then the date changes
  final Function onDateChange;
  // page widgets to display
  final Widget pageItems;
  // date format
  final String displayDateFormat;
  // date style
  final TextStyle dateStyle;
  // background color for date container
  final Color dateBackgroundColor;
  // forward icon
  final IconData forwardIcon;
  // back icon
  final IconData backwardIcon;
  // page change duration
  final Duration pageChangeDuration;

  final Map<String, Widget> widgets;
  final Widget noItemsWidget;
  final String widgetKeyFormat;

  ScrollingDayCalendar({
    @required this.pageItems,
    @required this.startDate,
    @required this.endDate,
    @required this.selectedDate,
    this.onDateChange,
    this.widgets,
    this.noItemsWidget,
    this.widgetKeyFormat,
    this.displayDateFormat,
    this.dateStyle,
    this.dateBackgroundColor,
    this.forwardIcon,
    this.backwardIcon,
    this.pageChangeDuration,
  });

  @override
  _ScrollingDayCalendarState createState() => _ScrollingDayCalendarState();
}

class _ScrollingDayCalendarState extends State<ScrollingDayCalendar> {
  PageController _pageController;
  int _totalPages;
  int _currentPage;
  int _previousPage;
  DateTime _selectedDate;

  _onPageChange(direction) {
    _currentPage = _pageController.page.round();

    if (_currentPage > _previousPage) {
      // went forward
      DateTime newDate = _selectedDate.add(
        Duration(days: 1),
      );

      setState(() {
        _selectedDate = newDate;
      });
    } else {
      // went back
      DateTime newDate = _selectedDate.subtract(
        Duration(days: 1),
      );

      setState(() {
        _selectedDate = newDate;
      });
    }

    _previousPage = _pageController.page.round();

    // run page update sent by user
    if (widget.onDateChange != null) {
      widget.onDateChange(direction, _selectedDate);
    }
  }

  Widget _buildPage(index) {
    if (widget.pageItems != null) {
      return widget.pageItems;
    }
    DateTime dateTime = widget.startDate;
    index = index + 1;

    dateTime = widget.startDate.add(Duration(days: index));
    String key = DateFormat(widget.widgetKeyFormat).format(dateTime);

    if (widget.widgets != null && widget.widgets.containsKey(key)) {
      return widget.widgets[key];
    }

    return widget.noItemsWidget;
  }

  @override
  void dispose() {
    _pageController.dispose();
    super.dispose();
  }

  @override
  void initState() {
    // set the selected date
    _selectedDate = widget.selectedDate;

    // calculate the start page
    int startingPage =
    _selectedDate.difference(widget.startDate).inDays.floor();

    setState(() {
      // set the total number of pages based on start date and end date
      _totalPages = widget.endDate.difference(widget.startDate).inDays.floor();

      // set starting page
      _pageController = PageController(initialPage: startingPage);

      // set previous page
      _previousPage = startingPage;
    });

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold (
      body: Column(
        children: <Widget>[
          Row(
            children: <Widget>[
              Container(
                height: 60.0,
                width: 60.0,
                color: widget.dateBackgroundColor != null
                    ? widget.dateBackgroundColor
                    : Colors.red,
                child: Center(
                  child: MaterialButton(
                    onPressed: () {
                      _pageController.previousPage(
                        duration: widget.pageChangeDuration != null
                            ? widget.pageChangeDuration
                            : Duration(microseconds: 700),
                        curve: Curves.easeIn,
                      );
                    },
                    child: Icon(
                      widget.backwardIcon == null
                          ? Icons.arrow_back
                          : widget.backwardIcon,
                      color: Colors.white,
                    ),
                  ),
                ),
              ),
              Expanded(
                child: Container(
                  height: 60.0,
                  color: widget.dateBackgroundColor != null
                      ? widget.dateBackgroundColor
                      : Colors.red,
                  child: Padding(
                    padding: EdgeInsets.only(top: 15.0, bottom: 15.0),
                    child: Center(
                      child: Text(
                        DateFormat(widget.displayDateFormat != null
                            ? widget.displayDateFormat
                            : "MM/yyyy")
                            .format(_selectedDate),
                        style: widget.dateStyle != null
                            ? widget.dateStyle
                            : TextStyle(
                          fontWeight: FontWeight.w500,
                          color: Colors.white,
                          fontSize: 18.0,
                        ),
                      ),
                    ),
                  ),
                ),
              ),
              Container(
                height: 60.0,
                width: 60.0,
                color: widget.dateBackgroundColor != null
                    ? widget.dateBackgroundColor
                    : Colors.red,
                child: Center(
                  child: MaterialButton(
                    onPressed: () {
                      _pageController.nextPage(
                        duration: widget.pageChangeDuration != null
                            ? widget.pageChangeDuration
                            : Duration(milliseconds: 200),
                        curve: Curves.easeIn,
                      );
                    },
                    child: Icon(
                      widget.forwardIcon == null
                          ? Icons.arrow_forward
                          : widget.forwardIcon,
                      color: Colors.white,
                    ),
                  ),
                ),
              ),
            ],
          ),
          Expanded(
            child: PageView.builder(
              controller: _pageController,
              scrollDirection: Axis.horizontal,
              itemCount: _totalPages, // Can be null
              onPageChanged: (direction) => _onPageChange(direction),
              itemBuilder: (context, index) {
                return _buildPage(index);
              },
            ),
          ),
        ],
      )
    );
  }
}

Answer: Uma das formas de se fazer é criar uma nova data quando clicar na seta para "trás" ou para "frente".
Exemplo:
Declare alguns atributos na sua classe para montar a data
// Depende da sua regra identificar a data inicial
// Aqui recuperei a data atual do dispositivo
DateTime data = DateTime.now();

int dia;
int mes;
int ano;
DateTime novaData;

No initState() preencha os atributos de dia, mês e ano utilizando como referência a data inicial que você planejar utilizar. Aqui no caso é com base na data atual.
@override
void initState() {
  super.initState();

  dia = data.day;
  mes = data.month;
  ano = data.year;
}

Crie um método para montar a data
_montarNovaData(){
  setState(() {
    novaData = DateTime(ano, mes, dia);
  });
}

Dentro da função de clique do botão implemente uma pequena lógica para somar o dia e o ano quando clicar no botão > e outra quando o clique for no botão < e em ambas faça a solicitação para que a tela seja redesenhada chamando o método de montagem da nova data. Como ele tem o setState() dentro dele a tela vai ser redesenhada.
// Função que passa para o próximo mês
_clickProximoMes(){
  if(mes == 12){
    ano++;
    mes = 1;
  } else {
    mes++;
  }

  _montarNovaData();
}

// Função que passa para o mês anterior
_clickMesAnterior(){
  if(mes == 1){
    ano--;
    mes = 12;
  } else {
    mes--;
  }

  _montarNovaData();
}

Com essa novaData o que precisa é somente utilizar no local que está montando seu Widget.
Essa é uma das maneiras de implementar o comportamento desejado. Não cheguei a rodar o código em um projeto mas é uma estrutura semelhante a uma implementação que fiz em um app que já está em produção e tem funcionado tranquilamente pra mim.
Sobre a lógica das funções de mês seguinte e anterior, poderia ser melhorada colocando tratamento para ano negativo por exemplo ou até mesmo limitando a um determinado período mas aí tudo fica a seu critério.
No mais acredito que com isso é possível que faça a adaptação ao seu código.
Comment: Consegui implementar sua solução, apenas tive que fazer uma modificação no if pois estava avançado tanto o mês quanto o ano, muito obrigado!
Comment: @denis de fato a lógica de alterar o ano estava incorreta. Editei a resposta para que fique correta fazendo a mudança de ano somente quando pular de dezembro pra janeiro e de janeiro pra dezembro. Obrigado pelo feedback.

Day Scrolling para Mês Scrolling


How to get the name of the month in local language in Drupal?

Question: I want to display in a tpl.php file:

30 maart 2015, 11: 34

Currently i'm using below code
    <?php print  date("j-F-Y H:i") ?>

1) How to get the name of the month in dutch instead of english?
2) How to add the comma easily ?
Answer: Don't use the PHP date function, use the Drupal API: format_date. To add the comma, make it part of the pattern. To match your example 30 maart 2015, 11: 34, the pattern is j F Y, H: i:
$timestamp = strtotime('2015-03-30 11:34');
print format_date($timestamp, 'custom', 'j F Y, H: i', NULL, 'nl');

For this to work, you need to have the core locale module enabled and Dutch translations on your site should be up to date (check that the names of months are translated inthe translation UI).  The module Localization Update will help you with updating translations if you need to.
You can skip the last argument ('nl') if the default language of your site is dutch.


Can a content entity type have a bundle which is a configuration entity type as with the contact form?

Question: What is bundle_entity_type for @ContentEntityType when id = contact_message and where contact_message is @ConfigEntityType?
Can a configuration entity Type be a bundle of a content entity type?
core/modules/contact/src/Entity/Message.php
/**
 * Defines the contact message entity.
 *
 * @ContentEntityType(
 *   id = "contact_message",
 *   label = @Translation("Contact message"),
 *   label_collection = @Translation("Contact messages"),
 *   label_singular = @Translation("contact message"),
 *   label_plural = @Translation("contact messages"),
 *   label_count = @PluralTranslation(
 *     singular = "@count contact message",
 *     plural = "@count contact messages",
 *   ),
 *   bundle_label = @Translation("Contact form"),
 *   handlers = {
 *     "access" = "Drupal\contact\ContactMessageAccessControlHandler",
 *     "storage" = "Drupal\Core\Entity\ContentEntityNullStorage",
 *     "view_builder" = "Drupal\contact\MessageViewBuilder",
 *     "form" = {
 *       "default" = "Drupal\contact\MessageForm"
 *     }
 *   },
 *   admin_permission = "administer contact forms",
 *   entity_keys = {
 *     "bundle" = "contact_form",
 *     "uuid" = "uuid",
 *     "langcode" = "langcode"
 *   },
 *   bundle_entity_type = "contact_form",
 *   field_ui_base_route = "entity.contact_form.edit_form",
 * )
 */
class Message extends ContentEntityBase implements MessageInterface {

core/modules/contact/src/Entity/ContactForm.php
which says bundle_of ==> contact_message
/**
 * Defines the contact form entity.
 *
 * @ConfigEntityType(
 *   id = "contact_form",
 *   label = @Translation("Contact form"),
 *   label_collection = @Translation("Contact forms"),
 *   label_singular = @Translation("contact form"),
 *   label_plural = @Translation("contact forms"),
 *   label_count = @PluralTranslation(
 *     singular = "@count contact form",
 *     plural = "@count contact forms",
 *   ),
 *   handlers = {
 *     "access" = "Drupal\contact\ContactFormAccessControlHandler",
 *     "list_builder" = "Drupal\contact\ContactFormListBuilder",
 *     "form" = {
 *       "add" = "Drupal\contact\ContactFormEditForm",
 *       "edit" = "Drupal\contact\ContactFormEditForm",
 *       "delete" = "Drupal\Core\Entity\EntityDeleteForm"
 *     }
 *   },
 *   config_prefix = "form",
 *   admin_permission = "administer contact forms",
 *   bundle_of = "contact_message",
 *   entity_keys = {
 *     "id" = "id",
 *     "label" = "label"
 *   },
 *   links = {
 *     "delete-form" = "/admin/structure/contact/manage/{contact_form}/delete",
 *     "edit-form" = "/admin/structure/contact/manage/{contact_form}",
 *     "collection" = "/admin/structure/contact",
 *     "canonical" = "/contact/{contact_form}",
 *   },
 *   config_export = {
 *     "id",
 *     "label",
 *     "recipients",
 *     "reply",
 *     "weight",
 *     "message",
 *     "redirect",
 *   }
 * )
 */
class ContactForm extends ConfigEntityBundleBase implements ContactFormInterface {

Comment: The Contact module uses a mockup content entity type with no storage and a bundle config entity to configure fields for forms. So the resulting front end contact form is technically the same as a back end node add form.
Answer: This may be easier to understand with Nodes, since Nodes have been used by almost every Drupal site builder.
Nodes are a Content Entity. Nodes have bundles (aka content types). For example, a blog. Now, to define the blog type, a new Config Entity is created - the Node Type entity. Config entities have keys. The key for the blog Node type is 'blog'. This key identifies the node type. But the blog bundle is still a Node entity, and therefore is a Content Entity.
The contact form works the same way.
So to answer your question, no, bundles of Content entities cannot be config entities, as bundles are just a subset of the original entity, which is a Content entity. But a Config entity is used to define the bundle (allowing the types to be exported as configuration).
You could almost compare it to the 'type' field on a Content Entity being an Entity Reference to a Config entity that defines the type.
Comment: You have two entity types: `node` and `node_type`. For each bundle of Node in the system, there will be a `node_type` entity, defining that bundle (eg. blog). When you create a new blog on your system, you create a new entity of type `node`. If you create another entity of type `node`. You create as many of these as you want, and there will still be only the one `node_type` entity that defines the blog type.
Comment: Thanks for replying but in the contact , you can see that ConfigEntityType contact_form is a bundle of ContentEntityType contact_message whereas a Node node  which is ContentEntityType is a bundle of ConfigEntityType node_type ?
So here node is a bundle of entity type which is a configentity similarly for Contact ?
Comment: No. Nodes are not bundles. They are Content Entities. Nodes have bundles, they cannot be bundles.
Comment: As per your answer, you are saying that Content Entities can only have bundles which will be Content Entities whereas Config Entities can have bundles which can be either Content Entity or Config Entity? is that correct ?
Comment: The bundles are sub-types of an Entity. A blog bundle IS a node. So it cannot become a config entity.
Comment: So when it says in NodeType.php ==> ConfigEntityType id="node_type"  and bundle_of = "node" whereas in Node.php ==> ContentEntityType id="node" and bundle_entity_type=node_type ?
can you elaborate on this so I can understand it completely, thanks again !!!


Geweke diagnostic of a Markov chain: why does the first window have to cover the burn-in?

Question: I read the following statement in this document$^{[1]}$, at the bottom of page 11:

Too wide A will some times "hide" the burn in part within the converged part of the chain and the difference in means may not be large enough for the diagnostic to give an indication of non convergence.

where A is the first window in Geweke diagnostic. Geweke statistic is defined as:
$$Z_n=\frac{(\bar \theta_A - \bar \theta_B)}{\sqrt{\hat S_\theta^A(0)/n_A+\hat S_\theta^B(0)/n_B}}$$
where $A$ and $B$ refers to the first window and second window respectively, $\bar \theta$ is the mean value, $\hat S_\theta(0)$ is spectrum density, $n$ is the number of data points.
What I don't understand here is: since this quantity should converge to $N(0,1)$ if the two intervals have the same distribution, why does interval A have to cover the burn-in to give an indication of non-convergence?
[1] Sahlin, Kristoffer (2011),
'Estimating convergence of Markov chain Monte Carlo simulations',
Masters thesis, Stockholms universitet, Stockholm
Comment: You should give a full reference for your link. Links can disappear. You should also mention the page number that your quote is taken from.
Comment: @Glen_b I didn't see any reference I can use for this article. Do you have any idea of this?
Answer: I believe the idea is that if there's been convergence, we could tell the initial burn-in period from the stationary distribution.
If you take the initial period too long - e.g. much wider than the actual period it takes to effectively be sampling from the stationary distribution - then your initial period statistics will be a mixture consisting mostly of sampling the stationary distribution and may not look different from a sample of the stationary distribution only.
Comment: If I understand correctly, if the first window is large enough to bury the burn-in, it is still feasible to use Geweke diagnostic to tell whether the chain has converged, but cannot tell how long the initial burn-in period is? In other words, if I don't care about the burn-in period, it doesn't matter if I choose a large first window?
Comment: Problem solved here -- I simply misunderstood the fact that the diagnostic is to test the convergence of the whole selected range, not the window B. Thanks for your answer!


Equalizer: choosing frequencies

Question: I'm dealing with computer-based sound treatments (building "guitar-pedals" with computer).
Most of it is fine, but I want to include various EQ possibilities. So far I can create LowPassFilter, HighPassFilter and BandPassFilter, so I have all the bricks to create equalization or graphical equalization.
My question is how to compute the relevant parameters for a given N-band equalizer? I need to choose frequency and Q value for each filter.
My guess is that it depends on the target instrument (i.e. bass/guitar/voice), and that there is no "absolute" answer.
Thanks.
Comment: http://static1.1.sqspcdn.com/static/f/308931/4998939/1260244832493/Hertz-Chart.png?token=nleLTAM8R9VgEKcaz9%2BqxUMbJf4%3D: does such graphic a decent start to adapt ranges to different instruments?
Comment: Thanks - yes, that is now definitely answerable. Your graphic in the last comment is useful - broadly, but I'll touch on why it isn't as helpful as you'd think.
Comment: @DoktorMayhem doesn't this question belong in Signal Processing Stack Exchange?
Comment: It could also fit there, yes, but we don't migrate because something is on-topic elsewhere, only when it is off topic here
Answer: For this question I'll stay away from parametric equalisers that allow you to alter f and Q, which can be very useful for electric guitars, as you may want these in different places when you change the effects/distortion used, and stick to the "classic" graphic equaliser used to just use a high pass filter at the lowest frequency you want to control, a low pass filter at your top frequency, and a range of bandpass filters usually logarithmically spaced between those two extremes. And this works reasonably well for a large range of use cases.
There are some straightforward equations that give you your 3dB bandwidth frequencies, and Q factor, and this page is an excellent resource, but before you get to that you need to be aware there is no right answer to how much overlap each band should have, so it is worth looking at examples.
From your building blocks, you will be able to alter your frequency and Q factor. The 3dB bandwidth from a particular Q factor is outlined in this table from the page I linked to:

But that won't tell you whether you should choose 3 octaves or 1 octave. That is very much down to what you prefer. Looking further down that page, you will see a Yamaha Parametric EQ example. I tend to err on the side of slightly more overlap to avoid unwanted notches if I use this type of EQ, but I prefer the greater control and tweakability of a full parametric EQ.
The sengpielaudio.com site actually has all the equations you would need to work this out yourself, and most importantly, has one of the two simple cutoff frequency calculators I have used when needed. If you can I would build a set and experiment with a range of inputs, both single instruments, and entire orchestras and everything in between to see what works in different situations.
Comment: Thanks! I still has a fully usable effects-chain program with graphical interface, that can work on guitar or micro, or directly from an audio file. So I will play around with various settings to listen the results.
Comment: BTW, if I want to build a EQ dedicated to voice channel, does it makes sense to use something like 100Hz-17kHz for bounds (I read somewhere that it's voice bounds, including harmonics)? Or is it totaly useless and a generic 20-20k (with enough bands of course) is fine?
Comment: For voice I'd typically drop off from 150Hz, and at the top end yeah 17k will be fine
Comment: For those who are interested, here a way to compute num frequencies between f0 and f1: rf0=log2(f0); rf1=log2(f1); sp=(fr1-fr0)/num; for(i=0; i<=num; i++) { x = exp2(fr0+i*sp); }. It gives results very similar than existing stuff. It divides the range in equal parts in the logarithm space.
Answer: I post an answer (even if the selected answer is fine) for readability about a way to compute frequencies. It may help future readers. Code is in pseudo-code.
f0 and f1 are frequency bounds, and num the number of frequencies to compute
rf0 = log2(f0)
rf1 = log2(f1)
sp = (rf1-rf0) / num
for(i=0; i<=num; i++) {
  fres[i] = exp2(rf0 + i*sp)
}

where log2 is the logarithm in base 2, and exp2 is the exponential in base 2.
This algorithm gives frequencies equally distributed in the log space. Results are very similar with existing examples (see example, but I tested it also for other values of num, such as 16, 32…). For num=11, f0=16, f1=16000 algorithm gives:
16 31.92 63.69 127.09 253.58 505.96 1.009k 2.014k 4.019k 8.018k 16k

and what I found from existing stuff is:
16 32 63 125 250 500 1k 2k 4k 8k 16k

Hope it can help someone.

Equalizer: choosing frequencies


Apache user can't write after chown

Question: I want to allow a directory to be writable by my apache user. I'm using centos 7. Apache user is just apache.
From my webroot I've created a write test, and it is returning that the directory is not writable:
/dir/webroot/write-test.php
<?php
$filename = 'test';
if (is_writable($filename)) {
    echo 'The file is writable';
} else {
    echo 'The file is not writable';
}
?>

When visiting write-test from the browser, I get 'not writable' as the result.
This is the ls -al in my webroot/ dir:
drwxr-xr-x.  6 root   root   4096 Jul 22 05:05 .
drwxr-xr-x.  4 root   root     31 Jul 21 18:06 ..
drwxr-xr-x.  2 apache apache    6 Jul 22 05:05 test
-rw-r--r--.  1 root   root    144 Jul 22 05:06 write-test.php

Comment: @PaulCrovella Ah, didn't realize it needs to exist as well. I've created the file; the problem persists. I updated my `ls -al`.
Comment: @PaulCrovella Mostly because I'm not familiar with `is_writable()` and I didn't want to worry about whether I was using it wrong so I tried to follow the example in the doc as close as possible. I've updated my post to what I believe is testing the directory.
Answer: you can try $filename = '/test.txt';

Apache user can't write after chown


On partitions of integers

Question: In an example in my textbook, I came across a question where it was asked to find the generating function for the number of partitions of  ${n \in N}$ into summands that (a) cannot occur more than 5 times; and (b) cannot exceed 12 and cannot occur more than 5 times.
The proposed solution for (a) is:
${f(x)=(1+x+x^2+...+x^5)(1+x^2+x^4+...+x^{10})...=\Pi_{i=1}^\infty(1+x^i+x^{2i}+...+x^{5i})}$
And the solution for (b) is proposed as:
${\Pi_{i=1}^{12}(1+x^i+x^{2i}+...+x^{5i})}$
However, the book fails to elaborate on what these problems concretely represent in practical terms.
For instance, when it says, it cannot occur more than 5 times, would it mean that we cannot repeat the same part of the partition more than 5 times?  And what exactly does it mean when it says, it cannot exceed 12 in practical terms?
Answer: If $n=72$, the partition $7+2+3+7+7+7+9+13+10+7=72$ doesn't answer (b) because $13>12$, but it answers (a) because, although the summand 7 appears five times, it doesn't appear more than five times.
Answer: Think of playing a solitaire game where you have $5$ identical decks of $m$ cards; the cards are numbered $1,\ldots,m$. You mix the decks together and try to find sets adding up to $n$.  The question is how many solutions there are.
For (a), you can think of $m$ as being $\infty$, i.e. there's no bound on the numbers on the cards. Or you can take $m=n$, since cards with labels greater than $n$ can't be in a solution.
For (b) we are fixing $m=12$.

On partitions of integers


How do I create a manual recommendation engine that recommends content to user's followers once this user clicks in a button?

Question: I am creating a system where I have something like a "manual recommendation system". It works like this: if a user thinks something inside the system is interesting, it can "recommend" this content. This content will then be recommended to all the user's followers (they will appear in their "wall"). (I don't care about who visited or any kind of automation, for me it is only important that the user is able to share comments by clicking in a button).
Let's say a user I follow recommends a blog post, a link to this post will appear in my "wall". This link contains the post title, description and so on.
He could also recommend videos, photos and users profiles and so on.
For each kind of content which is recommended, I will have a different layout and different information will be displayed, and here is where my problem lies:
I am having some issues creating the approach so solve this problem: How can I keep track of what was recommended, keep the information updated (if the post title was changed, it should change in the recommendation) and keep my solution clean?
These are the approaches I've though and the reasons I don't like them:

Create a "general" table, called Recommendation. This would have recommendation title, recommendationInfo_1, recommendationInfo_2, recommendationInfo_3,..., recommendationInfo_N.
This is a nice approach because it would be easy to retrieve and all recommendation types would be able to use the same columns.
I didn't like it because it doesn't keep the information updated (it is somehow complex to do that, I would have to check for possible recommendations every time an object is updated) and it looks messy.
Create a recommendation table and a "value pair table". The recommendation table would have the fields which are common to all of the recommendation types, and the key value table would have specific information for each recommendation type.
I didn't like it because it has the same problems maintaining the fields updated, this second table looks messy for me, and it would not be as simple to perform queries to retrieve all kinds of recommendations at once.
Create a recommendation table which contains only the recommendation ID, recommendation Type and content id. The table looks cleaner, which is a plus point, and it also solves the updated information issue.
The problem here is: I'm afraid the retrieval query will be very complex, I will have to perform N "outer join", being N the number of content types I have and my select clause can grow pretty fast due to the different kinds of information coming from different content types.

Do you have any ideas/articles/design patterns that could help me?
ps: I don't know if this is important, but I'm using asp.net and msssql
Answer: So your users can recommend photos, videos, cars, bananas, etc. Make a table which has all these things listed. So all items that a user may recommend are in the Thing or Object table, with information on what kind of thing it is and where the additional information is.
When a user recommends a thing, you simply create a relation between the user and the thing. The Recommendation table would thus have userId, thingId and maybe a timestamp to indicate when the thing was recommended.
In your program, you would make a superclass Thing with subclasses Photo, Video, Car, Banana. Maybe all your things implement some interface, so that you can call thing.getName() no matter what kind of thing it is.
Comment: This is a similar to on of the approaches I described, thanks :)


Como mudar a base de um branch?

Question: Tenho um branch derivado da master, development, que nunca volta à master. Todos os branchs de features são derivados de development, mas após testados e validados, são combinados tanto com a development quando com a master. Não posso combinar diretamente a development com a master porque tenho features lá que ainda não devem ser mescladas com a master.
Gostaria de saber se há algum meio de mudar o branch base de uma feature sem ocasionar conflitos nos arquivos que não foram alterados apenas nessa feature.
Hoje posso fazer o git cherry-pick <commit> mas acredito que em uma árvore com muitos commits seja um tanto quanto trabalhoso.
O desenho dos fluxos das minhas branchs é mais ou menos o seguinte:
                                   .-[feature1]---o---o---o-.
                                  /                          \
                                 /   .-[feature2]---o-.       \
                                /   /                  \       \
             .-[development]---´---´--------------------+-------+
            /                                            \       \
[master]---´----------------------------------------------+-------+---...

o - commits                    + - merge

No desenho acima, hoje, o que seria o merge estou fazendo como cherry-pick.
Comment: Acho que não chega a ser uma resposta ideal, mas `git cherry-pick A^..B` faz o cherry-pick de todos os commits entre A a B (incluindo os próprios commits A e B)
Comment: É, também não sei. Eu costumo usar o git de um jeito mais "básico" (branch -> push -> pull request), de vez em quando eu faço um cherry-pick ou rebase aqui e ali, mas é só. Não sou de fazer muitos "malabarismos", e muito menos de sugerir que os outros o façam. Desculpe não poder ajudar mais...
Comment: Se for da forma que está na figura, acho que não. Se todos os commits entre A e B pertencem ao branch feature1, só vai pegar esses.
Comment: @hkotsubo mas o problema é que vai pegar de todos os `branchs` que tenham `commit` naquele período, não?
Comment: @hkotsubo então, mas não é o caso, porque o desenvolvimento da `feature1` e `feature2` ocorrem em paralelo. Me ocorreu agora que talvez eu possa dar `squash` no `pull request` ao colocar em `development` e depois fazer o `cherry-pick` apenas do `merge`. Não sei se dá pra fazer isso
Comment: Por favor, reformula sua pergunta porque não consigo entender o que você quer fazer exatamente. Idealmente, com um diagrama antes e depois.
Answer: Você pode usar o rebase com a opção --onto. Os nomes das branches abaixo são só exemplos.
git checkout feature-branch
git rebase --onto base-nova base-antiga feature-branch

Se as duas bases forem incompatíveis, ou os commits da feature-branch forem dependentes da base antiga, vão existir conflitos de merge. Como o rebase pode ser perigoso, aconselho deixar tudo no remoto antes das alterações para poder voltar se precisar. E pra voltar, é só fazer um hard reset.
git rebase --abort # se for necessário
git fetch --all
git reset --hard origin/feature-branch # ou qualquer outra branch que você esteja

Como mudar a base de um branch?


What is a fast way to force Python to find a module, without regard to virtualenv?

Question: I'm taking over a project. 5 engineers worked on this for several years, but they are all gone. I've been tasked with trying to revive this project and keep it going. It's a big Python project with several complicated install scripts which, nowadays, have many version errors, because the stuff that worked 3 or 4 years ago is all long since deprecated and possibly discontinued.
Buried deep in one of the many install scripts (they all call each other multiple times, in a spaghetti that I cannot figure out) there is probably an instruction that sets up a virtual environment, but I can't find the line and I don't care. This software is going onto a clean install of an EC2 (with Centos 7) that I control completely. And this piece of software is the only software that will ever run on this EC2 instance, so I'm happy to install everything globally.
The install script was unable to find Python 3.6 so I manually did this:
pip3 install astroid
pip3 install cycler
pip3 install decorator
pip3 install fancycompleter
pip3 install ipython
pip3 install isort
pip3 install kiwisolver
pip3 install lazy-object-proxy
pip3 install matplotlib
pip3 install numpy
pip3 install pillow
pip3 install platformdirs
pip3 install pluggy
pip3 install prompt-toolkit
pip3 install pygments
pip3 install pyparsing
pip3 install pytest
pip3 install tomli
pip3 install typed-ast
pip3 install typing-extensions
pip3 install asgiref
pip3 install charset-normalizer
pip3 install click
pip3 install django
pip3 install django-timezone-field
pip3 install idna
pip3 install markdown
pip3 install markupsafe
pip3 install pyodbc
pip3 install python-nmap
pip3 install pyyaml
pip3 install sqlparse
pip3 install uritemplate

If I go into the Python shell and run help(modules) I can see the Django is installed.
But when I run the final install script:
/home/centos/blueflow/blueflow/bin/blueflow-django-manage compilejsx -o ./blueflow/jsx/JSXRegistry.jsx

Part of the error reads:
Couldn't import Django. Are you sure it's installed

What would be the fastest way to get the code to see the right path to Django? Is there an obvious way I can break out of all virtual environments and force the code to use the global environment for everything (which I'm thinking would be the simplest approach)?
Courtesy Notice: Pipenv found itself running within a virtual environment, so it will automatically use that environment, instead of creating its own for any project. You can set PIPENV_IGNORE_VIRTUALENVS=1 to force pipenv to ignore that environment and create its own instead. You can set PIPENV_VERBOSITY=-1 to suppress this warning.
Loading .env environment variables...
Warning: There was an unexpected error while     activating your virtualenv. Continuing anyway...
Traceback (most recent call last):
 File "/home/centos/blueflow/blueflow/app/manage.py", line 20, in <module>
"Couldn't import Django. Are you sure it's installed and "
ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?

[[ Update ]]
Someone asked about the contents of:
/home/centos/blueflow/blueflow/bin/blueflow-django-manage

This is the whole file:
#!/bin/bash
#
# blueflow-django-manage
#
# Shim for Django's "python manage.py" that supports different plaforms

# Copyright (C) 2018 Virta Laboratories, Inc.  All rights reserved.

# Stop on errors
set -e

# Path to BlueFlow installation
BLUEFLOW_HOME=${BLUEFLOW_HOME:=`cd $(dirname $0)/.. && pwd -P`}

# Defaults
PIPENV=${BLUEFLOW_HOME}/bin/blueflow-pipenv
DJANGO_MANAGE="${PIPENV} run python ${BLUEFLOW_HOME}/app/manage.py"

# Platform-specific section
OS=`${BLUEFLOW_HOME}/bin/blueflow-os-detect`
case ${OS} in
  "Ubuntu-16.04")
    DJANGO_MANAGE="sudo -Eu blueflow ${DJANGO_MANAGE}"
  ;;
  "RHEL7")
    if [[ "${DJANGO_SETTINGS_MODULE}" != "app.settings.development" ]]; then
      DJANGO_MANAGE="sudo -Eu blueflow ${DJANGO_MANAGE}"
    else
      DJANGO_MANAGE="sudo -Eu $(id -un) ${DJANGO_MANAGE}"
    fi
  ;;
  "RHEL8")
    if [[ "${DJANGO_SETTINGS_MODULE}" != "app.settings.development" ]]; then
      DJANGO_MANAGE="sudo -Eu blueflow ${DJANGO_MANAGE}"
    else
      DJANGO_MANAGE="sudo -Eu $(id -un) ${DJANGO_MANAGE}"
    fi
  ;;
esac

# Replace this subshell with command
exec ${DJANGO_MANAGE} "$@"

Comment: I wonder what is inside the `/home/centos/blueflow/blueflow/bin/blueflow-django-manage`
Comment: I updated this to include the contents of `/home/centos/blueflow/blueflow/bin/blueflow-django-manage`
Comment: If you're trying to manually manage the packets that are in your django environment, you need to get rid of the `DJANGO_MANAGE="${PIPENV} run python ${BLUEFLOW_HOME}/app/manage.py"` in the `blueflow-django-manage` script, as [pipenv](https://github.com/pypa/pipenv) *automatically creates and manages a virtualenv for your projects*.  You could try something like `DJANGO_MANAGE="$python ${BLUEFLOW_HOME}/app/manage.py"`, but I still would recommend using at least normal `venv` virtual environments.
Comment: What is the advantage of "but I still would recommend using at least normal venv virtual environments"? I just want to run a command that will allow the software to find the packages that have been installed. What is the easiest way to do that?
Comment: Easiest way to do it is to use same `python` executable to install the packages (`python -m pip install ...`)  and then to run your script (`python myscript.py`). No other magic is needed.
Comment: Okay, so, as you can see, I installed everything with pip3, so I tried python3 and that did seem to get me past some install issues.
Answer: You can add any path like this:
import sys
sys.path.append("my/path/to/django")

Note, that this is not the recommended way, but rather a fallback option.
You could also do print(sys.path) and print(sys.executable) (taken from here) to find out which python you are actually executing.


wglCreateContext fails with error "The pixel format is invalid"

Question: I'm trying to access the entire screen with the context.
Here's my current code (currently only this file):
#include <stdio.h>
#include <Windows.h>
#include <GL/gl.h>
#include <gl/glu.h>
#include <GL/glext.h>

int main(int argc, char *argv[]) {
    HDC hdc = GetDC(NULL);
    HGLRC hglrc;
    hglrc = wglCreateContext(hdc);

    // Handle errors
    if (hglrc == NULL) {
        DWORD errorCode = GetLastError();
        LPVOID lpMsgBuf;
        FormatMessage(
            FORMAT_MESSAGE_ALLOCATE_BUFFER |
            FORMAT_MESSAGE_FROM_SYSTEM |
            FORMAT_MESSAGE_IGNORE_INSERTS,
            NULL,
            errorCode,
            MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
            (LPTSTR)&lpMsgBuf,
            0, NULL );
        printf("Failed with error %d: %s", errorCode, lpMsgBuf);
        LocalFree(lpMsgBuf);
        ExitProcess(errorCode);
    }

    wglMakeCurrent(hdc, hglrc);

    printf("%s\n", (char) glGetString(GL_VENDOR));

    wglMakeCurrent(NULL, NULL);
    wglDeleteContext(hglrc);

    return 0;
}

The problem is in this code at the start:
    HDC hdc = GetDC(NULL);
    HGLRC hglrc;
    hglrc = wglCreateContext(hdc);

and the program's output (printed in the error handling if statement) is
Failed with error 2000: The pixel format is invalid.

Calling GetDC(NULL) is specified as retrieving the DC of the entire screen, so I'm not sure what is going wrong here. How do I fix this?
EDIT: added more information
Comment: Where are you choosing and setting the pixel format?
Answer: You didn't set the pixel format.
Have a look at the documentation here.
You should declare a pixel format descriptor, for example:
PIXELFORMATDESCRIPTOR pfd =
{
    sizeof(PIXELFORMATDESCRIPTOR),
    1,
    PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,    // Flags
    PFD_TYPE_RGBA,        // The kind of framebuffer. RGBA or palette.
    32,                   // Colordepth of the framebuffer.
    0, 0, 0, 0, 0, 0,
    0,
    0,
    0,
    0, 0, 0, 0,
    24,                   // Number of bits for the depthbuffer
    8,                    // Number of bits for the stencilbuffer
    0,                    // Number of Aux buffers in the framebuffer.
    PFD_MAIN_PLANE,
    0,
    0, 0, 0
};

Then use the ChoosePixelFormat to obtain the pixel format number, e.g.:
int iPixelFormat = ChoosePixelFormat(hdc, &pfd);

and finally call the SetPixelFormat function to set the correct pixel format, e.g.:
SetPixelFormat(hdc, iPixelFormat, &pfd);

Only then, you can call the wglCreateContext function.
UPDATE
As pointed out by user Chris Becke one can not call SetPixelFormat on the screen hDC (obtained with GetDC(NULL) as per the OP code). This is reported also in the khronos wiki here.
Therefore, you must also create your own Window, obtain its DC and then use it to set the pixel format and create the GL context. If you want to render "fullscreen" you simply have to create a borderless window with the same size of the screen. I suggest to have a look at the answers to this old question here on SO about this matter.
Comment: Its worth adding to this that you cannot set the pixel format of the desktop window. You must create your own window.
Comment: Thanks, I didn't notice that. I updated my answer accordingly.


Does DHCP protocol allow a server to offer multiple addresses to clients instead of just one?

Question: This is an exam question of Internet Protocol.
I thought the answer is "NO" but I want to make sure.
Comment: RFC2131 is your friend.  "Homework Fault" - :)
Comment: Why would you send this to Superuser? Its not just a dumping ground for crap we don't like. The topic of this question is around DHCP, were it a valid question, it would belong on this site. It's a bad, do my homework for me question, so it should be closed as such, not sent over to SU for them to close it properly.
Comment: No. It doesn't belong on any of the three sites. (At most on superuser.) Serverfault _isn't_ about things that have to do with servers. Serverfault is about people who manage _more than one_ server professionally and not as a hobby.
Comment: See the FAQ http://serverfault.com/faq: Server Fault is for *system administrators and IT professionals*, people who manage or maintain computers in a professional capacity.
Comment: Obviously, what we need is "Homework Fault" to take care of questions like this.
Answer: You'll find what you're looking for here (and if you actually bother to read it you'll learn something, as opposed to just having the answer given to you).
Answer: A server of this protocol assigns an IP address per MAC address. So YES the protocol can support multiple IP addresses per Host given multiple NICs.
Answer: As far as I know the answer is no. not at the same time. (at least if the client have 1 nic)
Answer: Sure enough, a single DHCP server will not supply multiple addresses to one client and let it choose.
But if you have more than one DHCP servers on your network (for redundancy in legacy windows (2003) environments?) a client will often get one DHCPOFFER from each DHCP server. Then, the client chooses one server to send his DHCPREQUEST to. Usually the client takes the server which answered first.
Comment: hmmm.... there is a difference between a "Client" and a "Network Adapter" (NIC). A DHCP server doesn't really know about "Clients" per-se, just MAC addresses.  Have a look at the "byte level" protocol definition to make sure.


How would I prove ${n^{2n} \gt (2n)!}$ using mathematical induction?

Question: This is what I have done. I checked for $n=1,2$ and $3$ in the first step. I did the assumption for $n=k$ and the claim of $n=k+1$ in the second step, but I don't understand how the step no. $3$ works so if anyone can do this a description of what you are doing in each step would be really helpful.
Comment: For each integer $n>3$, the inequality is true by AM-GM.  We have $$\frac{n^2}{2}> (2n-1)\cdot 1$$ and $$n^2>(2n-j)j$$ for $j=2,3,\ldots,n-1$.  So, $$n^{2n}=(2n)\,\left(\frac{n^2}{2}\right)\,n\,\left(n^2\right)^{n-2}>(2n)\,\big((2n-1)\cdot 1)\,n\,\prod_{j=2}^{n-1}\,j(2n-j)=(2n)!\,.$$  It remains to check the cases $n=1,2,3$, but as Michael Rozenberg said, this is false for $n=1$, but also $n=2$.
Comment: It's wrong for $n=1$ and $n=2$.
Comment: @Batominovski It is a quite elegant way you provided there but the OP refers explicitly to the usage of the concept of mathematical induction.
Comment: @mrtaurho  That is why I posted it as a comment, not an answer.
Comment: @Batominovski Hm, okay. This is indeed a valid argumentation ^^ Sorry to bother you.
Answer: For $n=1$ and for $n=2$ it's wrong.
For $n\geq3$ by the assumption of the induction we obtain:
$$(2n+2)!=(2n+2)(2n+1)(2n)!<(2n+2)(2n+1)n^{2n}.$$
Thus, it's enough to prove that
$$(2n+2)(2n+1)n^{2n}<(n+1)^{2n+2}$$ or
$$\left(1+\frac{1}{n}\right)^n>\sqrt{\frac{4n+2}{n+1}}.$$
Can you end it now?
Now, since $f(x)=\left(1+\frac{1}{x}\right)^x$ increases on $[3,+\infty)$, we obtain:
$$\left(1+\frac{1}{n}\right)^n\geq\left(1+\frac{1}{3}\right)^3=\frac{64}{27}$$ and it's enough to prove that
$$\frac{64}{27}>\sqrt{\frac{4n+2}{n+1}},$$ which is true because
$$\frac{64}{27}>2=\sqrt{\frac{4n+4}{n+1}}>\sqrt{\frac{4n+2}{n+1}}.$$
Comment: not really, I cant
Comment: @Amir Handanovic I added something. See now.
Answer: Your approach is right. But you have to note that the inequality does not hold for $n=1$ and $n=2$ respectively. Therefore your base case is given by $n=3$. You proceeded right by considering the cases $n=k$ and $n=k+1$

$$\begin{align}
k^{2k}&>(2k)!\\
(k+1)^{2(k+1)}&>(2(k+1))!
\end{align}$$

Now the key behind proving inequlities via induction is to somehow multiply one side of the assumption with a proper factor in order to get the claim. Form hereon you can proceed by showing that the factor which does gets the other side form assumption to claim is either smaller or bigger than the other one respectively.
So lets start with the RHS of our assumption. By using the basic property of the factorial we can conclude that we need to multiply the RHS by the factor $(2k+2)(2k+1)$ to make this side equal to $(2(k+1))!$. So lets apply this multiplication to both sides within our assumption to get
$$\begin{align}
(2k)!(2k+2)(2k+1)&<k^{2k}(2k+2)(2k+1)\\
&<k^{2k}4(k+1)^2\\
&=(2k^k)^2(k+1)^2\\
&\stackrel{?}{<}
\end{align}$$
The next step is a little bit tricky. To show that the RHS is actually smaller than our claimed term for the RHS, $(k+1)^{2(k+1)}$, we need to show that $2k^k<(k+1)^k$. This can be easily done by considering Bernoullis inequality for $n=k$ and $x=1/k$ respectively. Thus we get
$$1+nx< (1+x)^n\Rightarrow 1+1<\left(1+\frac1k\right)^k\Leftrightarrow 2k^k<(k+1)^k$$
Plugging the last result within our calculation so far we get
$$\begin{align}
(2k)!(2k+2)(2k+1)&<k^{2k}(2k+2)(2k+1)\\
&<k^{2k}4(k+1)^2\\
&=(2k^k)^2(k+1)^2\\
&<((k+1)^k)^2(k+1)^2\\
&=(k+1)^{2(k+1)}\\
\Leftrightarrow (2(k+1))!&<(k+1)^{2(k+1)}
\end{align}$$
and now we are done!
Comment: Thanks everyone. Mrtaurho, your answer was the most understandable for me, but i didnt get it all. I will try to figure out everything you did and if I dont understand something I will ask
Comment: I dont understand the part where you multiplied by $(2k+2)(2k+1)$, why did you do it? and how did you get $ 4(k+1)^2$ or how did you get $(2k^k)^2$ from $k^{2k}$
Comment: I just multplied both side by the factor $(2k+2)(2k+1)$. I can do this without any problems. Furthermore form hereon the LHS automatically becomes our claim since $(2k!)(2k+2)(2k+1)=(2k+2)!=(2(k+1))!$ and so we are done with reshaping the LHS. Now we have to get the RHS in the right form. Therefore I argued that the factor $(2k+2)(2k+1)$ is smaller than the factor $(2k+2)(2k+2)$, which should be clear. Now $(2k+2)(2k+2)=2(k+1)2(k+1)=4(k+1)^2$ so I got this factor. For the first term I just applied the relation $4k^{2k}=2^2(k^k)^2=(2k^k)^2$ which are some basic properties of powers.
Comment: okay I think i get everything but the part where we use Bernoullis' inequality. What do we consider and how do we get these numbers?
Comment: As you can see within the [link](https://en.wikipedia.org/wiki/Bernoulli%27s_inequality) Bernoulli's inequality can be stated as $$ (1+x)^n>1+nx$$ for some $n\ge 2$ and $x\ge-1,x\ne 0$. Now in order to use this inequality here we can set $n=k$ and $x=1/k$. Since we introduced $k$ earlier with as subsitution for $n$ and furthermore $n$ has to be at least $3$ the conditions for the usage of Bernoulli's inequality are fulfilled. Therefore by plugging the values in we get $$1+k\frac1k<\left(1+\frac1k\right)^k\Leftrightarrow 2k^k<(k+1)^k$$ I hope everything is clear now.
Comment: Yes another question. How did you get $4(k+1)^2$ from $(2k+2)(2k+1) when (2k+2)(2k+2) = 4(k+1)^2$
Comment: To be precise I did not stated that $(2k+2)(2k+1)$ equals $4(k+1)^2$. In fact the statement is $(2k+2)(2k+1)\color{red}{<}(2k+2)(2k+2)=4(k+1)^2$ which is totally legitimate.
Comment: Did you take $2k^k<(k+1)^2$ in bernoulis from $(2k^k)^{2}(k+1)^2$ and how did you factor $(2k^k)^2 to (k(k+1)^k)^2$
Comment: oh i see. I thought you were working out the whole RHS and factoring everything as opposed to LHS
Comment: Is everything clear now or do want me to explain something further? In case you are satisfied you could mark my answer as accepted to show that you are not in need of more input :)
Comment: Yes the one i asked after you explained $4(k+1)^2$ please
Comment: Yes, actually I applied Bernoulli's inequality which gave us $2k^k<(k+1)^k$ - not $2k^k<(k+1)^2$ - squared both sides and multiplied by $(k+1)^2$ which leads us to $2k^{2k}(k+1)^2<(k+1)^{2k}(k+1)^2$. Again you have to watch out since there is no equal sign between these two lines.
Comment: thank you very much,everything is clear now.
Comment: Well, in this case I am happy that I could help you. Now you can mark my answer as accepted I would suggest :)


How to interpret xtologit output?

Question: so for my research project I am investigating effect a blood pressure diagnosis has on alcohol consumption frequency and physical activity. I have constructed 2 different models for both and I will be using xtologit command as I have panel data.
Please see my output below. My DV is alcohol_freq which is an ordinal variable of 4, which measures days per week the individual drinks. (0-1 1-2- 2 3-5 -3 6-7 -4).
My independent variables are gender (1 is female), net financial wealth, education level, waves( 3 4 5 6) (baseline wave is 2).
<code>. xtologit alcohol_freq ragender i.wave i.wealth_group i.raeduc_e   if r2hibps==1, vce(robust)

------------------------------------------------------------------------------------------
                         |               Robust
            alcohol_freq |      Coef.   Std. Err.      z    P>|z|     [95% Conf. Interval]
-------------------------+----------------------------------------------------------------
                ragender |  -1.779655   .4354061    -4.09   0.000    -2.633036    -.926275
                         |
                    wave |
                      3  |  -.2776735   .1835768    -1.51   0.130    -.6374775    .0821305
                      4  |  -.3572538    .193667    -1.84   0.065    -.7368342    .0223266
                      5  |  -.7242535   .2117997    -3.42   0.001    -1.139373   -.3091337
                      6  |  -.8055891   .2289829    -3.52   0.000    -1.254387   -.3567908
                         |
            wealth_group |
                      2  |   1.923992   .6102358     3.15   0.002     .7279517    3.120032
                      3  |   3.108671   .7094336     4.38   0.000     1.718207    4.499135
                      4  |   4.251541   .7972072     5.33   0.000     2.689043    5.814038
                         |
                raeduc_e |
 3.high-school graduate  |   1.213114   .5658486     2.14   0.032     .1040715    2.322157
         4.some college  |   1.909918   .5798655     3.29   0.001     .7734019    3.046433
    5.college and above  |   2.508408   .7991029     3.14   0.002     .9421947    4.074621
-------------------------+----------------------------------------------------------------
                   /cut1 |  -1.474018   .8762496    -1.68   0.093    -3.191435    .2434001
                   /cut2 |   1.684593   .8791786     1.92   0.055    -.0385653    3.407752
                   /cut3 |   4.320586   .8989051     4.81   0.000     2.558764    6.082408
-------------------------+----------------------------------------------------------------
               /sigma2_u |    14.7487   2.156123                      11.07429    19.64226
------------------------------------------------------------------------------------------
</code>
So from my output I guess I can conclude as time went on the no. of days of drinking per week decreased for my sample, and this became stat significant in wave 5.
However I am confused by the positive coefficients for wealth group, education. Does this mean having a higher net wealth would increase frequency of drinking per week over the study? Or I am interpreting this wrong?
Any help would be appreciated. Thanks
Answer:
Does this mean having a higher net wealth would increase frequency of
  drinking per week over the study?

Probably not over the study. The ORs depicted by the education and income variables are assumed to be independent from wave (aka time) in this model, so for example: it simply means compared with the wealth group 1, the log(odds) of advancing to higher level in the drinking frequency is 4.25 for wealth group 4, adjusted for education, sex, and wave. This 4.25 will be the same in waves 3, 4, 5, and 6.
If you want to look into the association between education and income overs time (aka, do some education groups tend to increase their drinking more than other groups over time?), then consider testing the interactions between wave and education and between wave and wealth.
Comment: Ok I will make sure to test the interaction terms, thank you!

How to interpret xtologit output?


Put the value of every field with the same name attribute into an array using PHP

Question: I have two fields (at minimum) that both have the same name attribute. Using a little jQuery, the user can add more text boxes using jQuery's .clone() feature. Every possible input they add will have the same name attribute as the first two.
I want to try to use php to create a comma separated list of every input value after the form is submitted.
$competitor_names = $_POST['competitor-name'];
$competitorList = '';
foreach($competitor_names as $competitorList) {
    $competitorList = $competitorList.', ';
}

Comment: Form input arrays, have a look at this: https://stackoverflow.com/questions/3314567/how-to-get-form-input-array-into-php-array
Comment: Try `$competitorList = implode(', ',$competitor_names);`
Comment: You use $competitorList for two different things. Probably you want to rename one of them.
Answer: The function implode() seems to be what you're looking for :
$competitor_names = $_POST['competitor-name'];
$competitorList = implode(',', $competitor_names);

Comment: Thank you! This works great.


If $Y$ is Poisson with parameter $\lambda$ and $X \vert Y$ Is binomial with parameters $(y,p)$ find the distribution of $X$.

Question: I was solving a problem where $Y$ is a random variable with Poisson distribution with parameter $\lambda$ and $X \vert Y$ is binomial with parameters $(y,p)$ I need to find the density function, the expected value and variance of $X$.
With the formulas $E(X)=E(E(X \vert Y))$ and $var(X)=E(var(X \vert Y))+var(E(X \vert Y))$ I know that $E(X)=var(X)=p \lambda$.
But my problem is the density function. With the formula $f_{X \vert Y}(x \vert y) =f_{X,Y}(x,y)/f_{Y}(y)$ I compute $f_{X,Y}$ and $f_{X}$ but the density function of $X$ gives me a Poisson with parameter $\lambda$ when I think it should be Poisson with parameter $\lambda p$ from the information of $E(X)$ and $var(X)$. What am I doing wrong?
Comment: $P(X=x)=\sum_{y=0}^\infty P(X=x|Y=y)P(Y=y)$. Now substitute the known formulas for $P(X=x|Y=y)$ and $P(Y=y)$, then evaluate the infinite sum.
Answer: Following your approach, lets try
$$
E(\exp(sX)) = E(E(\exp(sX)|Y)) = \sum_{i=0}^{\infty} E(\exp(sX)|Y=i)e^{-\lambda}\frac{\lambda^i}{k!}
$$
Because,
$$
E(\exp(sX)|Y=n) = \sum_{i=0}^{n} {n\choose{i}}p^iq^{n-i}e^{si} = \sum_{i=0}^{n} {n\choose{i}}(pe^{s})^i q^{n-i} = (pe^s+q)^n
$$ The toatal sum becomes
$$
E(\exp(sX)) = \sum_{i=0}^{\infty}(pe^s+q)^ie^{-\lambda}\frac{\lambda^i}{k!} = \sum_{i=0}^{\infty}e^{-\lambda}\frac{(\lambda(pe^s+q))^i}{k!}
$$
Use that this is essentially the taylor expansion of $e^x$ with matching
$$
x = \lambda(pe^s+q),
$$ and we conclude,
$$
E(\exp(sX)) = e^{-\lambda + \lambda p e^s + \lambda q} = e^{-p\lambda + \lambda p e^s}
$$
We identify this as the moment generating function of the poisson process.
This should with the help of a suitable theorem prove that $X\in Po(p\lambda)$
Answer: Evaluate \begin{align*}
P[X = k] &= \sum_{j = 0}^\infty P[Y=j]P[X=k|Y=j]\\
&= \sum_{j = k}^\infty e^{-\lambda} \frac{\lambda^j}{j!}\binom{j}{k}p^k(1 - p)^{j - k} \\
&= \frac{e^{-\lambda}p^k \lambda^k}{k!}\sum_{j = k}^\infty \frac{\lambda^{j - k} (1 - p)^{j-k} }{(j-k)!} \\
&=\frac{e^{-\lambda} p^k \lambda^k}{k!} e^{\lambda(1 - p)} \\
&= \frac{e^{-\lambda p} (p\lambda)^k}{k!}\,.
\end{align*}
Answer: $Y \in Po(\lambda)$ means that for large $N$ so that we can say that this is almost the same as $Bin(\frac{\lambda}{N},N)$ which means that
$$
   Y = \sum_{i=1}^{N}I_i,
$$ with $I_i$ i.i.d. and 1 with probability $\lambda / N$ and zero else. If we take
$$
   X = \sum_{i=1}^{N}J_iI_i,
$$ with $J_i$ i.i.d and 1 with probability $p$ and 0 else. Then $X$ is $Bin(p\lambda / N,N)$ and given $Y=y$, $\in Bin(y,p)$ all prerequisites in the problem is now satisfied and using $Bin(p \lambda/N,N)\approx Po(p\lambda)$. letting $N \to \infty$ should indicate the answer.


Xamarin.Forms Prism app not showing Master-Detail navigation bar

Question: I am trying to get Master-Detail navigation configured in my Xamarin.Forms app with my UWP target running on Windows 10.
When I run the sample Master-Detail app provided by Xamarin (following https://developer.xamarin.com/guides/xamarin-forms/user-interface/navigation/master-detail-page/), and change the MasterBehavior to Popover, I see the following behavior:
Startup:

Select the hamburger icon:

Make a selection:

In my prism app, I navigate to MainPage/View1:
protected override void OnInitialized()
{
    InitializeComponent();
    var task = NavigationService.NavigateAsync("MainPage/View1");
    ...
}

MainPage is my MasterDetailPage with the MasterBehavior set to Popover, and View1 is a ContentPage.
MainPage:
<MasterDetailPage xmlns="http://xamarin.com/schemas/2014/forms"
                  xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                  xmlns:views="clr-namespace:My.Mobile.Application.Views;assembly=My.Mobile.Application"
                  x:Class="My.Mobile.Application.Frame.MainPage"
                  MasterBehavior="Popover">
  <MasterDetailPage.Master>
    <views:MasterPage x:Name="masterPage" />
  </MasterDetailPage.Master>
  <MasterDetailPage.Detail>
    <NavigationPage>
      <x:Arguments>
        <views:View1 />
      </x:Arguments>
    </NavigationPage>
  </MasterDetailPage.Detail>
</MasterDetailPage>

View1:
public View1()
{
  NavigationPage.SetHasNavigationBar(this,false);
  InitializeComponent();
}

On startup, I do not see any navigation bar, just the contents of View1 (currently just a red screen):

If I change the MasterBehavior of MainPage.xaml to Default instead of Popover, and remove the SetHasNavigationBar in View1, I see the side menu when the app launches:
MainPage:
<MasterDetailPage xmlns="http://xamarin.com/schemas/2014/forms"
                  xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                  xmlns:views="clr-namespace:My.Mobile.Application.Views;assembly=My.Mobile.Application"
                  x:Class="My.Mobile.Application.Frame.MainPage"
                  MasterBehavior="Default">
  <MasterDetailPage.Master>
    <views:MasterPage x:Name="masterPage" />
  </MasterDetailPage.Master>
  <MasterDetailPage.Detail>
    <NavigationPage>
      <x:Arguments>
        <views:View1 />
      </x:Arguments>
    </NavigationPage>
  </MasterDetailPage.Detail>
</MasterDetailPage>

View1:
public View1()
{
  //NavigationPage.SetHasNavigationBar(this,false);
  InitializeComponent();
}

When I make a selection after startup with MasterBehavior set to Default, I now see the hamburger menu.

Is there anything that I can add or verify in my solution to mimic the Xamarin sample behavior with the MasterBehavior set to Popup?
Answer: The problem is here: var task = NavigationService.NavigateAsync("MainPage/View1");

Since you want to show the hamburger menu, you need to wrap your Detail in a NavigationPage.  So first register a NavigationPage for navigation
Container.RegisterTypeForNavigation<NavigationPage>();
Then add it to your navigation path:
var task = NavigationService.NavigateAsync("MainPage/NavigationPage/View1");
Also, you can remove a the detail markup in your MasterPage XAML because the navigation service will build it up for you.
Answer: Try to do something like this:
public partial class ShellView : MasterDetailPage, IMasterDetailPageOptions
{
    public ShellView()
    {
        InitializeComponent();
    }

    public bool IsPresentedAfterNavigation
    {
        get { return Device.Idiom != TargetIdiom.Phone; }
    }
}


Quorum Vs Versioning, when should i use what?

Question:
A quorum is the majority number of servers that have to agree on a certain operation in order to move forward.
Versioning is a counter for each record.

In a database, if latest version will always give me the latest and correct record.
When and why should i use Quorum for distributed systems.
Answer: Quorum is required in a distributed environment where you are running a cluster of machines and anyone of these machines can accept a write/modify request and update the data.  Under such scenarios Quorum is used to identify the leader that will accept the writes or determine which node can accept write/modify requests for a given range of keys.
Let's consider a scenario where you have 3 master server accepting writes, in that case if you want to update the data, can we just match the version on one of the masters and assume it is safe to update?
No, because at the same moment some other write request to other master server  can also assume the same and hence you will end up with different state of data in different machines.
In this scenario, you need quorum to identify the leader that will accept writes for given range of data and then you can use versioning (optimistic locking) to ensure data is consistent across all machines and serialized.
Versioning, however is helpful when you have one master accepting the writes and multiple users might want try to update the data, using versioning here can help you to achieve Optimistic Locking. This is generally helpful when chances of locking are low.
Comment: Thanks, i thought we only have vector clocks and replicas syncing for brain-split problem.


How can I programmatically delete a user?

Question: I'm new to Drupal development and am way over my head on this one. My company runs a subscription-based site offering market research to corporations. A company pays for a subscription and is granted a certain number of users. The person designated as primary user has the ability to add the remaining users themselves. We now need to add a function to allow them to delete a user who is no longer with their company. In doing so, we need the following to happen:

Delete the record from "users" database table
Change the author on any node created by the deleted user to "Anonymous"
Send an email to our internal support address letting them know that the user should be removed from other non-connected systems

The previous developer created a custom module for account management that allows adding users under several different circumstances. For example the user is completely new to the company adding it, which means they need to be added to our other unconnected systems as well, as opposed to providing a Drupal account to a user who is already in our other systems.
Currently a lot of stuff is being done with JavaScript using Drupal.parseJson to process the request based on the segments of the URL clicked. This was done for the sole reason of being able to update the page with the user list without a complete refresh. I personally don't care if this new function works that way, or if it needs to hit the server and refresh the page. I just need to find a way to do everything in the above list with a single click.
I've looked at the API and found user_delete, but it requires two params - $edit and $uid. The uid is no problem, but all I can find about $edit is that it's "an array of submitted form values." We're not using a form, though; our user lists are static text, and the actions all occur onclick of an href (at this point); so there's nothing being submitted. Is there any way I can fake the values of $edit? Or is there another way to do this? I'm reading about hook_user() and thinking that I'd call user_delete() somewhere to do the actual delete, and then my hook_user() implementation would handle the rest with the $op = delete param. But before I worry about how to get the other stuff happening, I need some guidance about how to call user_delete().
Is it even worth it to use user_delete()? Would it be less trouble to just write my own queries to delete the user record and change any content records to "Anonymous"?
Answer: This is not that hard, for D6 it would look like this:

Delete record from Drupal database users table;
user_delete(array(), $uid);

Change author on any content created by deleted user to Anonymous;
handled by the node module.
Send an email to our internal support address letting them know that the user should be removed from other non-connected systems
drupal_mail(...);

See hook_mail for details.
Comment: The Node module in core will already set the posts to Anonymous, so that part you can skip.
Comment: @googletorp, so I don't actually need to pass any values in for the first param of user_delete()? That's what I was so hung up on and couldn't find any documentation for.
Comment: @Chaulky - so just calling user_delete will force the Node module to set the posts to Anon.? I don't have to do anything else?
Comment: Yup: http://api.drupal.org/api/drupal/modules--node--node.module/function/node_user/6
Comment: @EmmyS no you don't need to pass any value - an empty array will do. The user module use it internally when forms are submitted.
Answer:
Is it even worth it to use user_delete()? Would it be less trouble to just write my own queries to delete the user record and change any content records to "Anonymous"?

To delete a user account, and assign all the nodes the user authored to the anonymous user, you simply need to call user_delete(array(), $account->uid), or user_delete(array(), $uid), depending if you have an user object, or a user ID.
As for assigning the nodes created with the user account being deleted, user_delete() invokes all the implementations of hook_user() passing "delete" as value for $op. The Node module implements the hook using the following code:
function node_user($op, &$edit, &$user) {
  if ($op == 'delete') {
    db_query('UPDATE {node} SET uid = 0 WHERE uid = %d', $user->uid);
    db_query('UPDATE {node_revisions} SET uid = 0 WHERE uid = %d', $user->uid);
  }
}

As you see, the function already updates the nodes authored by the user account being deleted, and any node revisions where associated with that user account.
The first parameter required from user_delete() is normally not used from the implementations of hook_user(), when the $op parameter is set to "delete." In most of the cases, the modules just use $account->uid to identify the user data they wrote in their own database tables. Even supposing the modules saved the data using another value to identify the user account, it is a value contained in the user object.
As per writing your own queries to delete the user account, I would not suggest doing it, as there could be modules that need to be informed when a user account is delete, usually to delete the data the module associated to that account. Rewriting code when there is already a function for this specific purpose could mean also to update the code when passing to a new Drupal version. The code would not be as generic as the code already used by Drupal.
Answer: Non-Coding method:
Modules needed:
Triggers (part of core)
Step 1:  Enable trigger module
Step 2:  Create the send email action

goto admin/settings/actions
create 'Send email...' action
fill out the form

Step 3:  Create the trigger

goto admin/build/trigger/user
under Trigger: After a user has been deleted choose the action you just created

And your done! By default, when you delete a user, all of their post turns to anonymous.
Revised:
You now have a choice of where you want to delete users now.

You can bulk delete users by going to /admin/user/user
Go to the user profile page and delete
Create your own custom module and function that calls user_delete(array(), $uid)

Everyone of these ways will automatically sent an email out for every deleted user.  I believe this way is more flexible as you can change the email body and recipient without editing any code.
Comment: This doesn't actually delete the user though and the OP isn't using the typical "edit user" form to delete it.
Comment: I picture them getting a list of users to delete, going to /admin/user/user and bulk deleting them
Comment: @iStryker, Chaulky is right - we are not doing it that way. This is custom all the way, not accessing user/ at all.
Comment: Actually now that I think of it,  calling user_delete() should email users with this trigger.  Also just realized if you delete 10 people, it will send 10 emails.  Good luck with your custom coding.
Comment: Yes, we're aware of the individual emails; that's what we want. And I inherited this; it wasn't my choice to deviate from default functionality.


Replicating beanstalkd for High Availability

Question: Title says it all.
Does anyone know of a way to replicate beanstalkd such that if a beanstalk server went down, others slaves could take over?
Here's one approach I thought of:
I could make beanstalk write its binlog (with the -b) to a shared location, and then somehow have a secondary/backup server start beanstalkd if the primary fails.
There must be a better way though.
Answer: Since it is writing to disk via binlog, I'd think you could do something similar to what MySQL admins typically do: heartbeat w/ DRBD (example here).
The last time I tried to use heartbeat though, it didn't support non-multicast checking between nodes, meaning that it was more or less impossible to run on cloud/VPS infrastructure (AWS, Linode, Slicehost, etc). In fact, most clustering services use multicast. This may no longer be the case, but it's something to be aware of. You may be able to use keepalived to provide ip-based failover, which also only supports multicast BUT has a patch available via Willy Tarreau (author of HAProxy) to add unicast support. I have personally tested this on a pair of Linode VPS servers and keepalived is able to failover a shared IP address in the event of the master server failing.
One thing you can do which is probably less optimal is to write jobs to a number of beanstalkd servers (aka partitioning). If one of them goes down, have your app detect this and write to the other instance(s) instead. Your workers will have to intelligently poll each of the beanstalkd instances and be able to ignore dead instances. Since you are binlogging, bringing an instance back up should be as easy as restarting it and the app/workers will detect this and continue as usual (and begin processing the jobs in the newly-started instance). I'm obviously simplifying the process, but that's one other way to handle it.
Comment: Corosync supports unicast and is the default clustering tool in Redhat-based distros.
Comment: Thanks, didn't know about Corosync. Will keep it in mind for future projects.


Google Kubernetes Engine to Cloud SQL

Question: I am currently trying to learn to use Google Kubernetes Engine and Google Cloud SQL. In doing so i have created a AspnetCore 3.1 Web Api project in my visual studio 2019, to use as a training project.
At the moments i am currently able to do the following.

Deploy the Web Api to GKE, using Google Cloud Tools for Visual Studio
Connect to Cloud SQL from own PC, using SSMS and Cloud SQL Proxy

What i want to be able to do is as follows.

Deploy the Web Api to GKE, using Google Cloud Tools for Visual Studio, with a sidecar, containing Cloud SQL Proxy

From my understanding of Cloud SQL, it is best to always access it via the proxy, as it is more secure, which is why i want the sidecar. To get the proxy to work, i however need the credential file saved in my secrets in GKE. I also have some database related variables that need to be passed in as environment variables, again from secrets in GKE.
At the moment in my solution, beside my api project file, i have a Dockerfile, that looks as follows.
FROM gcr.io/google-appengine/aspnetcore:3.1
COPY . /app
WORKDIR /app
ENTRYPOINT ["dotnet", "HelloCloud.Api.dll"]

#FROM gcr.io/cloudsql-docker/gce-proxy
#COPY . /app
#WORKDIR /app
#CMD ["/cloud_sql_proxy -instances=noble-cubist-294511:europe-west2:helloclouddb=tcp:1433 -credential_file=/app/secrets/cloudsql/key.json"]

The second section of the Dockerfile is commented out, as you can see. This is done because it crashes the pods on GKE, as it is missing the credential file, that needs to be mounted from the secrets.
Beside the Dockerfile, also lies a file called deployment.yaml, which content is as follows.
apiVersion: apps/v1
kind: Deployment
metadata:
  name: hellocloud
spec:
  selector:
    matchLabels:
      app: hellocloud
  template:
    metadata:
      labels:
        app: hellocloud
    spec:
      containers:
      - name: hellocloud
        image: gcr.io/noble-cubist-294511/hello-cloud-api
        env:
            - name: DB_USER
              valueFrom:
                secretKeyRef:
                  name: helloclouddb-db-credentials
                  key: username
            - name: DB_PASS
              valueFrom:
                secretKeyRef:
                  name: helloclouddb-db-credentials
                  key: password
            - name: DB_NAME
              valueFrom:
                secretKeyRef:
                  name: helloclouddb-db-credentials
                  key: database
        resources:
          limits:
            memory: "128Mi"
            cpu: "500m"
        ports:
        - containerPort: 80

      - name: cloudsql-proxy
        image: gcr.io/cloudsql-docker/gce-proxy
        command: ["/cloud_sql_proxy",
                    "-instances=noble-cubist-294511:europe-west2:helloclouddb=tcp:1433",
                    "-credential_file=/secrets/cloudsql/key.json"]
        resources:
            limits:
              memory: "128Mi"
              cpu: "500m"
        volumeMounts:
            - name: credentials-volumn
              mountPath: /secrets/cloudsql
              readOnly: true

    volumes:
        - name: credentials-volumn
          secret:
            secretName: helloclouddb-instance-credentials

I have created the above deployment.yaml, by following the guide on this site: Connecting Cloud SQL
From working on this, i have found out that Google Cloud Tools for Visual Studio reacts to the Dockerfile, which is also why i tried the section that is commented out. I have been trying to figure out if i can instruct GKE, via the Dockerfile, to use the deployment.yaml file, because from my understanding that should do the trick.
I like the development concept DRY (Don't Repeat Yourself) which is another reason it want to do be able to do it via Google Cloud Tools for Visual Studio. I have tried to create a deployment directly on GKE, which took me around 10 minutes to do, and ended up not even working. Ofcourse if i get more used to creating deployment on GKE, it is gonna reduce the time, and eventually also work, but it will be a WET (Write Every Time) way of doing it.
After two days of banging my head against the table i have gotten no closer, which is why i am writing this Stackoverflow questing, in the hopes that someone more experienced with Docker, GKE and Cloud SQL, can give me some pointers.
Fell free to ask for more detail, if i maybe have missed something crucial.
[Edit 1]
As a workaround, i am trying to have the file(s) on my drive, where the copy in the Dockerfile is gonna take it from, atleast from my understanding. Below an image of my project in Visual Studio can be seen, followed my by my updated Dockerfile.

FROM gcr.io/google-appengine/aspnetcore:3.1
COPY . /app
WORKDIR /app
ENTRYPOINT ["dotnet", "HelloCloud.Api.dll"]

FROM gcr.io/cloudsql-docker/gce-proxy
COPY . /app
WORKDIR /app/Secrets/CloudSQL
CMD ["/cloud_sql_proxy -instances=noble-cubist-294511:europe-west2:helloclouddb=tcp:1433 -credential_file=key.json"]

Building the Dockerfile on my computer and looking at the content of the image using Dive command, it contains the "key.json" at the specified location. Even then, when deploying to GKE, Cloud Build, builds it just fine, but when starting a pod, it throws a RunContainerError, complaining about "no such file or directory". Image of the full error can be seen below.
Comment: Created a Api method, that when called simply tells me if the database.json and key.json file exists, which it says they do. So why does GKE throw that error...
Comment: I can see in your deployment file you are using absolute path, but the error shows `--credential_file` with relative path. Also, the path in your deployment file is in lowercases, and in your Dockerfile/project it is CamelCase... have you tried to keep it the same for all? I'm asking because for linux it is completely different if you say `cd Secrets/CloudSQL` and `cd /secret/cloudsql`
Comment: From deploying my project from Visual Studio, i do net see any suggestion that the deployment.yaml file does anything. What does effect the deployment is the Dockerfile. I have matched up the paths in both file, just in case, they now both say: "app/Secrets/CloudSQL/key.json". Deploying with them matched still caused the error. I also considered that it was the cloud_sql_proxy file that it was missing, so the lates Dockerfile has the command prior to CMD set to "WORKDIR ." From looking at the images with Dive, that is where the cloud_sql_proxy is located.
Comment: Have you managed the issue? The missing cloud_sql_file solved the problem?
Comment: @KoopaKiller Look at my answer down below.
Answer: I managed to get it to work by creating my own class in my project, that given the path to the proxy file would run it with the required arguments, which i also feed to it via my class. To get the proxy file together with my own code i used the following Dockerfile to build my images.
FROM gcr.io/cloudsql-docker/gce-proxy as proxy
COPY . /app

FROM gcr.io/google-appengine/aspnetcore:3.1
Copy --from=proxy . /app
WORKDIR /app/app
ENTRYPOINT ["dotnet", "HelloCloud.Api.dll"]

Given the path to the proxy file, along with Credentials and Database file, my 'CloudSQLInitializer' class, starts the proxy.
public Startup(IConfiguration configuration)
        {
            ...
            try
            {
                CloudSQLInitializer cloud = null;

                // Currently running the proxy from either a bat or windows service.
                // As such will not have it start the proxy
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                    cloud = new CloudSQLInitializer($"Secrets/CloudSQL/database.json");
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                    cloud = new CloudSQLInitializer($"../cloud_sql_proxy", $"Secrets/CloudSQL/database.json", $"Secrets/CloudSQL/key.json");

                ...
            }
            catch (Exception e)
            {
                ...
            }
        }

public class CloudSQLInitializer
    {
        public string ConnectionString { get; private set; }

        ...
        public CloudSQLInitializer(string databaseInformationFilePath)
        {
            ...

            var information =
                JsonConvert.DeserializeObject<CloudDatabase>(File.ReadAllText(databaseInformationFilePath));

            ConstructConnectionString(information);
        }

        ...
        public CloudSQLInitializer(string cloudSQLProxyFilePath, string databaseInformationFilePath, string cloudCredentialsFilePath)
        {
            ...

            var information =
                JsonConvert.DeserializeObject<CloudDatabase>(File.ReadAllText(databaseInformationFilePath));

            ...

            ConstructConnectionString(information);
            RunCloudSQLProxy(information, cloudSQLProxyFilePath, cloudCredentialsFilePath);
        }

        private void ConstructConnectionString(CloudDatabase information)
        {
            var cs = new StringBuilder();

            cs.Append($"Data Source=127.0.0.1;");
            cs.Append($"Initial Catalog={information.Database};");
            cs.Append($"Persist Security Info=True;");
            cs.Append($"User ID={information.Username};");
            cs.Append($"Password={information.Password}");

            ConnectionString = cs.ToString();
        }

        private void RunCloudSQLProxy(CloudDatabase information, string cloudSQLProxyFilePath, string cloudCredentialsFilePath)
        {
            var cmd = new StringBuilder();

            cmd.Append($" -instances={information.InstancesToOneString()}");
            cmd.Append($" -credential_file={cloudCredentialsFilePath}");

            var proxy = new ProcessStartInfo {FileName = cloudSQLProxyFilePath, Arguments = cmd.ToString()};
            Process.Start(proxy);
        }
    }

public class CloudDatabase
    {
        [JsonProperty("database")]
        public string Database { get; set; }

        [JsonProperty("username")]
        public string Username { get; set; }

        [JsonProperty("password")]
        public string Password { get; set; }

        [JsonProperty("instances")]
        public List<string> Instances { get; set; }

        ...
    }

In the above code snippets i have cut away summeries for the methods, along with code that check to ensure the files exists and likewise checks. Also cut away much of the code that was otherwise irrlevant to this case.
Hope this is of use to somebody at some point, in the future.

Google Kubernetes Engine to Cloud SQL


Print is invalid Syntax? [Python 3]

Question: I'm trying to write a program that will do some simple math for a video game, however I am encountering multiple errors.
the string after Print IS in brackets, because of Python 3.
I also get "Calculation error" if I try to enter 1.5 or a value similar for 'FCS'
import decimal
print("ARMORED CORE V - FCS SIMULATION")
print("This program will calculate lock times for weapons combined with their FCS in           Armored Core V")
print("----------------------------------------------------------------------------")

#Base Weapon Lock/FCS Lock Percentage (150=1.5)/60
#Seidenbaum at 421 Base Lock
#421/1.5/60 is lock time (4.67 seconds)
#Subcomputer: Base Weapon Lock/FCS Lock Percentage/Subcomp Lock Percentage  (320=3.02)/Second Subcomp/60
#Subcomps: 421/1.5/3.02/60 (1.54 Seconds)
#Dual Subcomps: 421/1.5/3.02/3.02/60 (0.5 Seconds)

while (1 == 1):
    command = input("\nTo begin, type 'compute'\nThen enter your weapon's Base Lock Time\nThen your FCS' Lock Computation\nAnd then how many Subcomputers you have\nyou can also type help [ compute // help ]")
    if command == "help":
        print("\nFollow the instuctions as prompted\n\nI will also display the Lock Times and Subcomp Acceleration for FCSes and Subcomputers")
        print("--FCSes--\nUFC-11 GLANCE - 1.7 Lock Computation\nFCS-09 YASAKANI - 1.05 Lock Computation\nKV-1T2/OTKRYT - 0.75 Lock Computation\nFCS-07/Lr UZUME - 1.8 Lock Computation\nSEHER FCS199 - 1 Lock Computation\nPREDIRE FCS190 - 1.5 Lock Computation\n--SUBCOMPUTERS--\nSUBCOMPUTER USC-1 DHANBAD - 3.02 Lock Improvment\nSUBCOMPUTER SBC-9 TSUKUYOMI - 3.06 Missile Lock Improvement [Enter Normally]")
    if command == "compute":
        baselock = input("\n\nEnter your weapon's Base Lock Time >> ")
        fcs = input("\nEnter your FCS' Lock Computation as a Percentage >> ")
        subcompone = input("\nEnter your first Subcomputer's lock improvment\n Enter '1' if you don't have any subcomps >> ")
        subcomptwo = input("\nEnter your second Subcomputer's lock improvment\n Enter '1' if you don't have a second subcomputer >> ")
        try:
locktime = float(int(baselock)//int(decimal.decimal(fcs)//int(decimal.decimal(subcompone)//int(decimal.decimal(subcomptwo)//60)
                return(locktime)
                print("Seconds")
        except ValueError:
            print("error in calculation")

Comment: We have no clue what the traceback looks like. And neither do you, by the looks of it.
Comment: Crazily, Google finds an old version of your code [here](http://ideone.com/Y8Cqvn) (I was curious which video game you were referring to).
Answer: You forgot a closing parantheses on the line
locktime = float(int(baselock)//int(decimal.decimal('fcs')//int(subcompone)//int(subcomptwo)//60))

Also, I'm assuming this is in the function and that return is needed, but print('seconds') won't be executed if the return is hit. It is unreachable.
Comment: Yep. I said it in the last statement. Should make it more profound. Thanks. :)

Print is invalid Syntax? [Python 3]


Laravel problem with cache file when deploy to heroku

Question: My application is using laravel 8. I deploy it from github to heroku and I want to run the command below:
php artisan optimize

But I don't know how to run the command in heroku and if the command creates cache files in my app then heroku will delete them after specific time because they are not permanently files deployed from github. Anyone know how to deal with this pls tell me what to do. Thank you!
P/s: i tried to do like the link below but it didn't create any cache file in my app. https://dev.to/autoidle/laravel-deployment-optimization-on-heroku-1hkc
[new update] Problem solved. Just follow the link above and my answer below.
Comment: Why did you remove the previous question and repost it?
Comment: If the post is closed because it was not clear, you should NOT just repost it. At least change it to make it clear.
Comment: @GertB. sorry for the inconvenient but my thread was closed because it was not clear( idk why) and i can not reopen it to receive the answer although i tried to edit the post. That was the first time i ask in stackoverflow.
Comment: you can run commands on Heroku this way: `heroku run /app/php/bin/php /app/www/artisan optimize`
Comment: @GertB. i did edit the thread to make it more clear, like the new thread. But it still tell me that the thread was closed after more than 30 minutes. Because it will not receive the answer but only the comment. Can you tell me how long the thread will reopen if i edit the question so next time i dont have to repost. Sorry again ;(
Comment: it said bash: /app/php/bin/php: No such file or directory.
Comment: i run the command you said in the "run console" of my app
Comment: `heroku run php ... ` looks like the path is not needed anymore. It's been a while since i've used Heroku
Comment: go to APP or (https://dashboard.heroku.com/apps/app-name)-> click on more -> select run console -> add php artisan command name
Comment: @svikramjeet  i tried it before and it didnt create any cache file in my app
Comment: [new update] the way to cache config follow the link above does create cache file. The only thing i care right now is will heroku remove those cache files after a specific time or not. i will wait and update info later (or anyone know the answer pls tell me) Thank you!
Comment: I thought you have read about Heroku, but you are 100% right about Heroku deleting files that are pushed after creating slug
Comment: @svikramjeet i did read herroku document, that 's why i afraid herroku will remove the cache files in no time. But i still hope there is an exception or somthing about this situation. Because if 's not, how devloper will deploy laravel application to herroku and run it without any cache config? :(.
Comment: https://devcenter.heroku.com/articles/dynos#ephemeral-filesystem
Comment: @svikramjeet Gert B. Thank you both for helping me. I think i got my answer by my self, will update the thread soon
Comment: Please provide enough code so others can better understand or reproduce the problem.
Answer: Heroku uses an ephemeral filesystem, that means that any changes to the filesystem whilst the dyno is running only last until that dyno is shut down or restarted. Each dyno boots with a clean copy of the filesystem from the most recent deploy. This is similar to how many container-based systems, such as Docker, operate.
The solution to your problem is to use Redis as cache (and also for session, queue, ...)

Add to your Heroku environments:
CACHE_DRIVER=redis

composer require ext-json

Install Redis as add-on for example: https://elements.heroku.com/addons/heroku-redis
Comment: Thank you. This will help me a lot in the future. But in this thread i found an easier way to solve the problem.  I edited the answer few secs ago.
Answer: [new update] You can follow the link below and do exactly the same but you need to fix the part of Procfile from composer warmup to composer run-script warmup. That will solve the problem in this thread.
https://dev.to/autoidle/laravel-deployment-optimization-on-heroku-1hkc
composer.json:
    "scripts": {
       ...
       "warmup": [
           "@php artisan config:cache",
           "@php artisan route:cache",
           "@php artisan view:cache"
    ]
},

Procfile:
web: composer run-script warmup && heroku-php-apache2

enter image description here
Comment: Please provide additional details in your answer. As it's currently written, it's hard to understand your solution.


Loadstring, como usar?

Question: Estou usando a função loadstring, mas não sei se essa é a maneira correta:
a= "st = {b=1, c=2}"
st = {}
b = loadstring(a)
b()
print(st.b)

Há algum modo mais simples?
Comment: Em exemplos artificiais assim, é complicado dizer o que pode ser menos poluído. Por exemplo `print(1)` produz o mesmo resultado neste caso e é menos poluído. Dá para fazer coisas intermediárias mas aí é questão de gosto já que este não é um problema real.
Comment: Depende do que você chama de mais simples. Se eu entendi, não existe. Por que existiria?
Comment: Com mais simples eu quis dizer menos poluido.
Fiz assim:
st = "{b=1, c=2}"
st = "st="..st
st loadstring(st)
print(st.b)
Comment: Sim, mas a forma mais prática de usar o LoadString, qual é?
Answer: Se você não precisar criar a variável global st, use
b = loadstring("return {b=1, c=2}")()

Se você quiser fazer isso muitas vezes, considere algo como
function eval(x)
  return loadstring("return "..x)()
end

Comment: Ah, a grande magica é o return. Obrigado!

Loadstring, como usar?


Critical points of $f(x)=|x^4 -16|+4x-2$, $x\geq -1$

Question: As the title says, I found two critical points 1 and 2 with its derivatives, but I don't know how to find the last critical point $x=-1$, since $f(x)$ is defined when $x=-1$. I would really appreciate it if someone can explain this to me. Thank you so much!
Comment: Your question is unclear. Are you asking *whether* $x=-1$ is a critical point, or are you asking *why* $x=-1$ is a critical point?
Comment: Hi Gonçalo, I would like to know both if possible. Thank you very much.
Comment: Best way to deal with absolute values is to consider the function as a piecewise function
Comment: Yes. I have done that, so I found two critical points. But I wonder why x=-1 is also a critical point.
Comment: For a continuous function on an interval, the extreme value theorem says that extrema can occur where the derivative is 0 or doesn't exist, or at the endpoints of the interval. -1 is the endpoint of the function's domain, so a maximum or minimum can occur there.
Answer: According to the definition of "critical point", $x$ is a critical point of a function $f$ if the derivative of $f$ at $x$ is $0$ or undefined.
Thus, for the function
$$f(x)=\mid x^4−16 \mid +4x−2, x \geq -1$$
$x =-1$ is a critical point, because the derivative of $f$ at $x = -1$ is undefined. It is undefined, because: The derivative of $f$ at some $x = x_0$ exists iff the left derivative and right derivative both exist and are equal. And here clearly for $x = -1$, we only have right derivative but not left derivative, because $f$ is undefined  when $x<-1$.
Hope this can help you.
Comment: This is very clear and detailed. Thank you so much! Wish you have a good day.
Comment: You are welcome.


AspCore T4 Generation Adding Reference To System.Runtime.DLL

Question: I'm writing a project that generates code.  I need to load System.Runtime.Dll into the T4 Generator as it does not seem to be apart of System.Core.Dll anymore
In previous version of the code this template header would of sufficed
<#@ assembly name="System.Core" #>

However, everything seems to be apart of the Nuget Packages now.  I would like a way to reference the System.Runtime.Dll v 18.104.22.168 universally so that it.
Answer: After referencing the package via nuget you can do one of the following, if you are using asp.net core you can reference the package in your user folder (where all packages for all solutions are kept):
example:
<#@ assembly name="$(UserProfile)\.nuget\packages\Humanizer.Core\2.1.0\lib\netstandard1.0\Humanizer.dll" #>

or for pre .net core, reference the package form your solution folder:
example:
<#@ assembly name="$(SolutionDir)\packages\Humanizer.1.37.7\lib\portable-win+net40+sl50+wp8+wpa81+MonoAndroid10+MonoTouch10+Xamarin.iOS10\Humanizer.dll" #>

Comment: Yeah, but none of the plugins work with vs 2017, have you heard of [scripty](https://channel9.msdn.com/coding4fun/blog/Scripty-a-C-T4-Alternative)?
Comment: Thanks, I'll check this out when I get home, I'm trying to make a shippable ASP.Net core code generator for Crud API's.  I'm just wondering if that definition will work with all computers
Comment: T4 templates only work with Visual Studio, which is usually windows, so this  should work. I don't think T4 templating is available in the Code IDE. Your project sounds interesting, we do something similar for our own projects.
Comment: Oh, I didn't know the tool didn't work on other platforms, I guess for now generation can only happen on windows,  The ASP.Net Core is frusterating with the runtime, because it keeps getting Runtime mismatches, but I really need this tool becuase when you're making enterprise architecture a lot of it is just fluff, so I figured I'd save myself hours and have it generate all the basic classes for me and I can override anything more complicated
Comment: Yep, I have some other posts about more cross platform code generation, but haven't found a better solution. pure cross platform and no dependency on the full framework is pretty hard right now anyway.
We build CRUD for EF7, looking at the Entity classes, saves heaps of time.
Comment: Yeah I was just debating on writing a the code generation as a core dll and just say screw t4. It's so outdated and doesn't have intellisense. Im barely even using the tt. I'm using the entities to generate, dtos, contracts, adapters and services. That way I have syntax highlighting and direct referencing back to the original entity. So I don't have to look though a messy tt file
Comment: We use the plugin from Tangible which helps with intellisense etc but unfortunately there is no replacement for T4 or anything else that can do the same job.