Erro ao acessar campos inputs com cucumber + capybara

Question: Estava escrevendo minhas steps para meus testes com o Cucumber e os mesmos não estão encontrando os ids, labels ou names dos formulários.
Já olhei vários tutorias na internet e realmente meu problema é muito estranho, pois em todos sempre o problema é a referência, e neste caso, a minha está correta.
Steps (O primeiro passo funciona corretamente)
Dado(/^que eu esteja na página de criação de eventos$/) do
   visit "/events/new"
end

Quando(/^eu prencho os dados do evento corretamente$/) do
  fill_in "event_name", :with => "Nome do Evento"
end

Parte do formulário que contém o input

  <%= f.label :Evento %>

  <%= f.text_field :name, :class => "form-control", :required => true  %>

  <%= f.label :Data_Evento %>

  <%= f.date_select :date_event, :class => "form-control", :required => true  %>

  <%= f.label :Destacar_Evento? %>

  <%= f.check_box :detach, {}, "1", "2" %>

Answer: Criei um ambiente para simular o seu código aqui funcionou perfeitamente, veja abaixo a estrutura do projeto:
    #./projeto/app.rb
    #encoding: utf-8
    require 'sinatra'

    get '/' do
      "home"
    end

    get '/events/new' do
      erb :index
    end

__END__
@@index
<!doctype html>

      <form>

          Event Name
          <input name="event_name" id="event_name" type="text"/>

     </form>

#./projeto/features/teste.feature
#language: pt
Funcionalidade: Preencher formulario
Dado que o quadro abaixo

    Cenário:Preenchendo trecho de código
    Dado que eu esteja na página de criação de eventos
    Quando eu prencho os dados do evento corretamente

#./projeto/features/support/env.rb
#encoding: utf-8
require_relative '../../app'
require "capybara/cucumber"

Capybara.app = Sinatra::Application

#./projeto/features/step_definitions/teste_step.rb
#language: pt
Dado(/^que eu esteja na página de criação de eventos$/) do
    visit "/events/new"
end

Quando(/^eu prencho os dados do evento corretamente$/) do
  fill_in "event_name", :with => "Nome do Evento"
end

Os meus testes muitas das vezes, estavam quebrando porque não havia uma rota que funcionasse outra vezes porque o render ( tanto do rails quanto do sinatra ) não encontrava as variaveis não eram localizadas nas tag <%=f.algumacoisa%>, logo não era possivel encontrar os campos ( uma vez que a página não passa pelo processo de renderização ). Derrepente você pode verificar a exitencia de algum dos elementos que você julga essenciais para sua view. Você pode usar query:
page.has_xpath?('//table/tr')

se o problema persistir, mande os códigos de seu arquivo: env.rb, da views e da feature, ..., etc
Abrasss


vector by reference in a struct?

Question: I want to create a struct containing a double and a vector of strings. I tried this
int main ()
{
  struct List
  {
      double price;
      vector<string> items;
  };

  List list;

  ifstream infile ("Aap.txt");

  double p;
  infile>>p;
  list.price=p;
  cout<<list.price<<endl;

  int i=0;
  string name;
  getline(infile,name);

  while(infile)
  {
      list.items.push_back(name);
      cout<<list.items[i]<<endl;
      i++;
      getline(infile,name);
  }
  infile.close();

  if (!infile)
  {
      cout<<"File closed."<<endl;
  }

return 0;

This is not filling my vector, because it is not by reference in the struct I suppose?
But when I define the vector in the struct as:
vector<string>& items;

I get an error saying:
error: structure `list' with uninitialized reference members.
How can I fix this?
Thank you for helping!
Comment: What does "not filling my vector" mean? Your code looks fine as far as that `vector` is concerned. No need for any references.
Comment: It means that the code 'couts' the double from the file, but not the list of items...
Comment: I just tried your code with a quick artificial input file and it works fine. What does your input file look like? Does it read and print the price value in your experiments?
Comment: Are you sure you don't have a `using namespace std;` somewhere? A variable named list could easily conflict with the list type that is declared in the standard namespace.
Comment: Oh my... I changed somethings to make the code clearer for posting... copy-paste in code blocks.. it now runs fine :-)
Answer: Your code works perfectly fine.
There's a little issue of the first read: if you have a newline character in your input file after the price value, that newline character will remain unread. In this situation the first call to getline will read an empty string, meaning that the first name in your items array will end up empty.

vector by reference in a struct?


Gitlab Sonar Qube Redirect Url

Question: I have a problem with authorization in Sonar Qube with Gitlab. The error is "The redirect URI included is not valid. ".My Sonar Qube is hosted on Azure VM Ubuntu. When I open the network in the browser I see that the redirect URL is "redirect_uri: http://localhost:9000/oauth2/callback/gitlab".Why in Gitlab Applications I put http://mysonarcubeIP/oauth2/callback/gitlab.Sonar Qube is community and Gitlab also.
Comment: In `sonar.properties` file, please add your domain name or ip in the property `http.nonProxyHosts`. Ex: **http.nonProxyHosts=mysonarcube.com|184.108.40.206**
Comment: I've exactly the same problem. I've put my sonarqube domain name but my redirect_uri is localhost:9000... It's maybe a problem with the sonarqube configuration because its default listen port is 9000 (for me, sonarqube run in a container and i've bind  0.0.0.0:57563 with 9000/tcp).
Comment: Did either of you have any success? I'm having the same issue
Comment: Try  Sourav Alta comment
Answer: In version 8.7 (the version we have), the redirect URL is controlled by the Server Base URL, key sonar.core.serverBaseURL.  The description of the field mentions being used in the construction of emails, but it is also used as the callback.
You can find it in the "General" tab of the settings.
Comment: Thanks a lot, it did work after configuring this attribute.

Gitlab Sonar Qube Redirect Url


Problem with the final result of the inequality

Question: I am trying to solve the inequality:
$$\frac{\log(1+x^3)}{2x-\sqrt{4x+3}} \geq 0$$
I tried to find the domain for $x$:
$$4x+3 \geq 0 \Rightarrow x \geq \frac{-3}{4}$$
$$1+x^3 > 0 \Rightarrow x > -1$$
$$2x - \sqrt{4x+3} \neq 0 \Rightarrow x \neq \frac{3}{2} \land x \neq \frac{-1}{2}$$
I did the intersection of the entire domain and I get
$$x \in [0,  \frac{3}{2}) \cup (\frac{3}{2},+ \infty) $$
After this I solved $\log(1+x^3) \geq 0 \Rightarrow x \geq 0$ and after i solved 2x - sqrt(4x+3) > 0 with the system 1) 4x + 3 >= 0 , 2) 2x > 0 , 3) 4x+3 < 4x^2

=> x >= -3/4
=> x > 0
=> (-∞, -1/2) U (3/2, +∞)

I did the intersection of this system and the result is x ∈ (3/2, +∞)
After verifying the domain, my solution is  x ∈ (3/2, +∞).
I saw on wolfram alpha if my solution was correct but its not.
It should be x ∈ [-3/4,0] U (3/2 , +∞).
Comment: Here's a tutorial: https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference
Comment: That's not an inequality! It's just an expression.
Comment: It seems like you are trying to find the domain of your expression. That does require solving some inequalities, but you should say you seek the domain, rather than "solve inequality" because the whole thing is not an inequality.
Comment: OP: Are you trying to establish that the left-hand expression is non-negative whenever it is defined (i.e., when $4x+3 \geq 0$)? Or just, as others have mentioned, to identify the values of $x$ for which it is non-negative? If neither, can you clarify?
Comment: Make a sign table...
Answer: $$\begin{array}{|r|r|r|r|r|}
\hline
&&-1&&-\frac34&&-\frac12&&0&&\frac32&\\\hline
\log(1+x^3)&X&X&-&-&-&-&-&0&+&+&+\\\hline
2x-\sqrt{4x+3}&X&X&X&-&-&-&-&-&-&0&+\\\hline
f(x)&X&X&X&+&+&+&+&0&-&X&+\\\hline
\end{array}$$
From the sign table above the domain of $\sqrt{f(x)}=\sqrt{\frac{\log(1+x^3)}{2x-\sqrt{4x+3}}}$ is
$$D=[-\tfrac34,0]\cup(\tfrac32,\infty)$$


SNMP port forwarding one way

Question: I would like to forward snmp from one LAN to another LAN. I believe I got one way working (from outside to inside), but sadly the box1 cannot seem to reply. (inside to outside)
The setup I would like to make :
  box1                  box2             box3
[10.1.255.245] -------------------------- [public_ip]
    |               eth0-|-eth1               |
    |-----------3161---------------- 3161 ----|

These are the iptables rules which are relevant of BOX 2,
-A PREROUTING -i eth1 -p udp -m udp --dport 3161 -j DNAT --to-destination 10.1.255.244:3161
-A FORWARD -d 10.1.255.244/32 -p udp -m udp --dport 3161 -m state --state NEW,RELATED,ESTABLISHED -j ACCEPT

Now I validated that packages coming from box3 are received in box1.
tcpdump 'port 3161'
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on eth0, link-type EN10MB (Ethernet), capture size 65535 bytes
13:46:03.887718 IP x-20150810-092601.x.be.53329 > compute-0-2.local.doc1lm: UDP, length 48
13:46:04.888851 IP x-20150810-092601.x.be.53329 > compute-0-2.local.doc1lm: UDP, length 48
13:46:05.889977 IP x-20150810-092601.x.be.53329 > compute-0-2.local.doc1lm: UDP, length 48
13:46:06.891108 IP x-20150810-092601.x.be.53329 > compute-0-2.local.doc1lm: UDP, length 48

So I assume the snmp process cannot respond to the location cause it does not know how to find this out-of-lan ip... how can I add this ?
this is route on box1 :
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
255.255.255.255 *               255.255.255.255 UH    0      0        0 eth0
box2 box2     255.255.255.255 UGH   0      0        0 eth0
22.214.171.124       *               255.255.255.0   U     0      0        0 eth0
10.1.0.0        *               255.255.0.0     U     0      0        0 eth0
link-local      *               255.255.0.0     U     1002   0        0 eth0
link-local      *               255.255.0.0     U     1003   0        0 eth1
192.168.0.0     *               255.255.0.0     U     0      0        0 eth1
default         storage          0.0.0.0         UG    0      0        0 eth1

Or am I missing something else obvious ?
Answer: SNMP working trough UDP, so there is no sessions, like in TCP. So you should add additional NAT entry on box2 to allow packets from box1 to box3.
Something like this:
-A PREROUTING -i eth0 -p udp -m udp --dport 3161 -j DNAT --to-destination <RealIP>:3161
-A FORWARD -d <RealIP>/32 -p udp -m udp --dport 3161 -m state --state NEW,RELATED,ESTABLISHED -j ACCEPT

Comment: I tried this, but sadly no packets are going, box1 does not know where that IP is located (and has no internet) would that routing table try box2 for that adress ?
Comment: @SvennD yes, with this configuration you should use box2 address.
Comment: That was the issue, the gateway was wrong :) but also these 2 rules where missing.

SNMP port forwarding one way


Selecting Box-Cox parameter in TBATS function in R

Question: I am struggling to manually select the Box-Cox transformation in my TBATS function. I have a time series with multiple seasonality called belpex.
I have tried the following pieces of code:
belpex_Model <-  tbats(belpex,use.box.cox=TRUE,bc.lower=0,bc.upper=0.2)

As well as this:
belpex_Model <-  tbats(belpex,use.box.cox=TRUE,lambda=0)

However, in both cases, the output of the model is as follows:
TBATS(1, {2,2}, 0.838, {<24,11>, <168,6>})

From the documentation of tbats, the first output of TBATS is the parameter of the Box-Cox transformation.
As a result, the model that I obtain has no Box-Cox transformation despite I explicitly say so.
Another thing that I have noticed is that, despite:
belpex_Model <-  tbats(belpex,use.box.cox=TRUE,lambda=0)

returns that no Box-Cox transformation is used, the output model is quite different that the instruction:
belpex_Model <-  tbats(belpex)

Can it be that when using lambda=0 TBATS does use the proper Box-Cox transformation but that is not really reflected in the TBATS function?
Any other idea/suggestions of what I might be doing wrong?
Answer: Omega equals 1, this could imply that no Box-Cox transformation is necessary (see De Livera et al. 2010, S. 25-27 in footnote *).
An additional note:
Also consider the source code of the TBATS function by typing 'tbats' to the R console and hitting enter. Since I can't reproduce your problem, I just can guess, that your data set may contain negative values which Box-Cox transformation can't handle. Then the use.box.cox argument will be set to FALSE (see line 58-61).
Both interval limits for the Box-Cox parameter will only by used, if any transformation will be executed.
See my examples:
set.seed(123)

numbers <- sample(rnorm(200), 200, replace = F, prob = NULL)
numbers_abs <- abs(sample(rnorm(200), 200, replace = F, prob = NULL))

my_msts <- msts(numbers, seasonal.periods = c(7, 14.25))
my_msts_abs <- msts(numbers_abs, seasonal.periods = c(7, 14.25))

tbats_abs <- tbats(my_msts_abs)
tbats_abs

tbats_abs_false <- tbats(my_msts_abs, use.box.cox = F)
tbats_abs_false

tbats_negative <- tbats(my_msts, use.box.cox = T)
tbats_negative

tbats_negative_false <- tbats(my_msts, use.box.cox = F)
tbats_negative_false

tbats_abs_interval <- tbats(my_msts_abs, use.box.cox = T, bc.lower = 0.2, bc.upper = 0.3)
tbats_abs_interval

tbats_interval <- tbats(my_msts, use.box.cox = T, bc.lower = 0.2, bc.upper = 0.3)
tbats_interval

*De Livera, Hyndman, Snyder (2010): Forecasting time series with complex seasonal patterns using exponential smoothing.


resolv.conf search suffix limited to six domains and 256 characters

Question: Is there a way to increase the resolv.conf search suffix limitation beyond six domains and 256 characters? This is an issue for an environment that has well over six domains to consider.
I realize that having more suffixes will delay resolution in many cases, but there are "timeout" and "attempts" parameters that could deal with this, I assume.
Comment: Are those domains disjunctive? Usually one would make one domain the master of the others, and have that delegate sub-queries appropriately.
Comment: For the most part yes. This is on a global network.
Answer: libc must be recompiled after redefining MAXDNSRCH and defdname in resolv.h in the package, and then re-packaged. Do not modify /usr/include/resolv.h, but rather resolv.h in the package which delivers it.
For example, if one is on an RPM-based operating system, one would download the .srpm, install it locally, modify the source code, re-archive it and rebuild the .srpm and .rpm packages, upload the .rpm into the Yellowdog Update Manager ("YUM") repository and mass-upgrade the libc package on all affected systems. The .srpm would, after regression testing, be committed into one's local source code repository and the changes documented in the commit log as well as the build release document. Although this example used RPM, this applies to all operating systems which support packages.
Anything less than this, and one is looking at a hack instead of doing clean system engineering.
Answer: Looking in to /usr/include/resolv.h, you will see the value is hardcoded:
# define MAXDNSRCH 6 /* max # domains in search path */

and
char defdname[256]; /* default domain (deprecated) */

So if you want to modify, you must re-complie resolv.h to make it changes, but I think it's not a good ideal.
Comment: Actually: you don't recompile headers; that header is part of libc. So they'd recompile their ** GNU C Library** - which, I agree, is not a good idea.
Comment: Sorry for my poor English, but I think it's is the same. Could you recompile `GNU C Lib` without the header?
Comment: Thanks for the replies. Why would this be a bad idea?
Comment: There are a couple suggestions here: http://flyingtux.blogspot.com/2009/07/maxns.html

I think a named server for my use will be fine. This is for a management server that I run scripts from. It will speed up the queries tremendously in general, I think.
Comment: @Gnouc: by your logic one could say one is driving fuel because a car won't run w/o it? :)
Comment: If `defdname` is used to define the maximum length of `domain`, then changing that is a really bad idea. If a DNS query exceeds 255 characters (256 for the null terminating byte in memory), it violates RFC.


Tem alguma forma de exibir um componente apenas se houver dados no arquivo json para populá-lo?

Question: Eu estou fazendo um app de quiz e acontece que algumas questões têm 5 e outras têm apenas 4 alternativas.
No tutorial que eu segui ele cria 4 choicebutton. Eu, muito inocente que sou, adicionei um quinto, que fica vazio quando não existe a quinta alternativa. Ainda quero aprender a fazer uma tela mais dinâmica, mas por enquanto queria apenas ocultar a quinta opção caso não haja dados pra ela.
Não reparem na bagunça do código, eu ainda vou arrumar
import 'dart:async';
import 'package:firebase_admob/firebase_admob.dart';
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:flutter/services.dart';
import 'package:queazybymtvr/resultpage.dart';
import 'ad_manager.dart';
import 'home.dart';
import 'package:shared_preferences/shared_preferences.dart';

class getjson extends StatelessWidget {

  String mat;
  getjson(this.mat);
  String assettoload;

  setasset() {
    if (mat == "lp") {
      assettoload = "assets/lp.json";
      debugPrint(assettoload);
    }else{
      debugPrint("não clicou em língua portuguesa");
    }
  }

  @override
  Widget build(BuildContext context) {
    setasset();
    return FutureBuilder(
      future:
      DefaultAssetBundle.of(context).loadString(assettoload, cache: false),
      builder: (context, snapshot){
        var mydata = json.decode(snapshot.data.toString());
        if(mydata == null){
          return Scaffold(
            body: Center(
              child: Text(
                "Loading",
              ),
            ),
          );
        }else{
          return quizpage(mydata : mydata);
        }
      },
    );
  }
}

class quizpage extends StatefulWidget {

  var mydata;

  quizpage({Key key, @required this.mydata}) : super(key : key);

  @override
  _quizpageState createState() => _quizpageState(mydata);
}

class _quizpageState extends State<quizpage> {

  bool _isRewardedAdReady;

  void _loadRewardedAd() {
    RewardedVideoAd.instance.load(
      targetingInfo: MobileAdTargetingInfo(),
      adUnitId: AdManager.rewardedAdUnitId,
    );
  }

  void _onRewardedAdEvent(RewardedVideoAdEvent event,
      {String rewardType, int rewardAmount}) {
    switch (event) {
      case RewardedVideoAdEvent.loaded:
        setState(() {
          _isRewardedAdReady = true;
        });
        break;
      case RewardedVideoAdEvent.closed:
        setState(() {
          _isRewardedAdReady = false;
        });
        _loadRewardedAd();
        break;
      case RewardedVideoAdEvent.failedToLoad:
        setState(() {
          _isRewardedAdReady = false;
        });
        print('Failed to load a rewarded ad');
        break;
      case RewardedVideoAdEvent.rewarded:
        setState(() {
          //TODO: passar para a próxima questão
          i++;
          ultimaQuestao(i);
        });

        break;
      default:
      // do nothing
    }
  }

  SharedPreferences _preferences;

  String _ultimaQuestao = 'ultimaQuestao';
  String _marks = 'marks';

  Future ultimaQuestao(int q) async {
    final _preferences = await SharedPreferences.getInstance();
    setState(() {
      _preferences.setInt(_ultimaQuestao, q);
      _preferences.setInt(_marks, marks);
    });
  }

  Future setMarks(int marks) async {
    final _preferences = await SharedPreferences.getInstance();
    setState(() {
      _preferences.setInt(_marks, marks);
    });
  }

  getUltimaQuestao() async {
    SharedPreferences _preferences = await SharedPreferences.getInstance();
    setState(() {
      if(_preferences.getInt(_ultimaQuestao) != null){
        i = _preferences.getInt(_ultimaQuestao);
        debugPrint("i.toString() = " + i.toString());
      }else{
        i =  1;
      }
    });

  }

  InterstitialAd _interstitialAd;
  BannerAd _bannerAd;
  bool _isInterstitialAdReady;

  Future<void> _initAdMob() {

    return FirebaseAdMob.instance.initialize(appId: AdManager.appId);
  }

  void _loadBannerAd() {
    _bannerAd
      ..load()
      ..show(
        anchorOffset: 0.0,
        horizontalCenterOffset: 0.0,
        anchorType: AnchorType.bottom
      );
  }

  void _loadInterstitialAd() {
    _interstitialAd.load();
  }

  @override
  void dispose() {

    RewardedVideoAd.instance.listener = null;

    _bannerAd?.dispose();

    _interstitialAd?.dispose();

    super.dispose();
  }

  var mydata;

  _quizpageState(this.mydata);

  Color colortoshow = Colors.indigoAccent;
  Color right = Colors.green;
  Color wrong = Colors.red;
  int marks = 0;
  Future<int> uq;
  int i = 1;
  //int timer = 30;
  //String showtimer = "30";
  //int interstitial_timer = 10;

  Map<String, Color> btncolor = {
    "a" : Colors.indigoAccent,
    "b" : Colors.indigoAccent,
    "c" : Colors.indigoAccent,
    "d" : Colors.indigoAccent,
    "e" : Colors.indigoAccent
  };

  bool canceltimer = false;

  @override
  void initState(){

    _bannerAd = BannerAd(
      adUnitId: AdManager.bannerAdUnitId,
      size: AdSize.banner,
    );

    _loadBannerAd();

    _isInterstitialAdReady = false;

    _interstitialAd = InterstitialAd(
      adUnitId: AdManager.interstitialAdUnitId,
      listener: _onInterstitialAdEvent,
    );

    //show_interstitial_ad();

    getUltimaQuestao();

    _isRewardedAdReady = false;

    RewardedVideoAd.instance.listener = _onRewardedAdEvent;

    _loadRewardedAd();

    //starttimer();

    super.initState();
  }

  void _onInterstitialAdEvent(MobileAdEvent event) {
    switch (event) {
      case MobileAdEvent.loaded:
        _isInterstitialAdReady = true;
        break;
      case MobileAdEvent.failedToLoad:
        _isInterstitialAdReady = false;
        print('Failed to load an interstitial ad');
        break;
      case MobileAdEvent.closed:

        break;
      default:
      // do nothing
    }
  }

  /*void starttimer() async{

    const onesec = Duration(seconds: 1);
    Timer.periodic(onesec, (Timer t) {
      setState(() {
        if(timer < 1) {
          t.cancel();
          nextquestion();
        }else if(canceltimer == true){
          t.cancel();
        }else{
          timer = timer - 1;

        }
        showtimer = timer.toString();
      });
    });
  }*/

  void show_interstitial_ad(){
    InterstitialAd interstitialAd = new InterstitialAd(
        adUnitId: InterstitialAd.testAdUnitId,
        listener: (MobileAdEvent e) {
          print("Mobile ad event => $e");
        });
    interstitialAd.load().then((val) {
      interstitialAd.show();
    });
  }

  void nextquestion(){

    _loadInterstitialAd();
    //canceltimer = false;
    //timer = 30;
    setState(() {
      if(i < 10){
        if(i % 5 == 0) {
          showDialog(
              context: context,
              builder: (context) =>
                  AlertDialog(
                    title: Text("Queazer by MTVR"),
                    content: Text(
                        "Assita uma propaganda para acessar mais 10 questões."),
                    actions: <Widget>[
                      FlatButton(
                        child: Text("Cancelar"),
                        onPressed: () {
                          Navigator.pop(context);
                        },
                      ),
                      FlatButton(
                        child: Text("OK"),
                        onPressed: () {
                          Navigator.pop(context);

                          RewardedVideoAd.instance.show();

                        },
                      )
                    ],
                  )
          );
        }else{
          i++;
          ultimaQuestao(i);

        }
        //show_interstitial_ad();
      }else{
        ultimaQuestao(1);
        Navigator.of(context).pushReplacement(MaterialPageRoute(
          builder: (context) => resultpage(marks : marks)
        ));
      }
      btncolor["a"] = Colors.indigoAccent;
      btncolor["b"] = Colors.indigoAccent;
      btncolor["c"] = Colors.indigoAccent;
      btncolor["d"] = Colors.indigoAccent;
      btncolor["e"] = Colors.indigoAccent;

    });
    //starttimer();

  }

  void checkanswer(String k){
    //if(mydata[2][i.toString()] == mydata[1][i.toString()][k]){
    if(k == mydata[2][i.toString()]){
      //marks = marks +5;
      colortoshow= right;
      //setMarks(marks);
    }else{
      colortoshow = wrong;
    }
    setState(() {
      btncolor[k] = colortoshow;
      canceltimer = true;
    });

    Timer(Duration(seconds: 1), nextquestion);
  }

  Widget choicebutton(String k){
    return Padding(
      padding: EdgeInsets.zero,
      child: MaterialButton(
        onPressed: (){
          checkanswer(k);
          debugPrint("k = " + k + " e i.toString() = " + i.toString());
          debugPrint("mydata[2][i.toString()] = " + mydata[2][i.toString()] + ", mydata[1][i.toString()][k] = " + mydata[1][i.toString()][k]);
        },
        child: Text(
          mydata[1][i.toString()][k],

          style: TextStyle(
            fontSize: 16.0,
            fontFamily: "Alike-Regular",
            color: Colors.white
          ),
          //maxLines: 1,
        ),
        color: btncolor[k],
        splashColor: Colors.indigo[700],
        highlightColor: Colors.indigo[700],
        minWidth: 200.0,
        height: 45.0,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5.0))
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitDown,
      DeviceOrientation.portraitUp
    ]);
    return WillPopScope(
      onWillPop: (){
        return showDialog(
          context: context,
          builder: (context) => AlertDialog(
            title: Text(
              "Queazy by MTVR",
            ),
            content: Text(
              "Deseja realmente sair?"
            ),
            actions: <Widget>[
              FlatButton(
                onPressed: (){
                  Navigator.of(context).pop();
                },
                child: Text("Cancelar"),
              ),
              FlatButton(
                onPressed: (){
                  Navigator.of(context).pushReplacement(MaterialPageRoute(
                      builder: (context) => homepage()));
                  //TODO: sair e destruir a tela

                },
                child: Text("Sair"),
              )
            ],
          )
        );
        //TODO: destruir a página

      },
        child: Scaffold(
          appBar: AppBar(
            title: Text("Língua Portuguesa"),
            centerTitle: true,
          ),
        body: ListView(
          children: <Widget>[
            Expanded(
              flex: 2,
              child: Container(
                padding: EdgeInsets.all(15.0),
                alignment: Alignment.bottomLeft,

                child: Text(
                  i.toString() + " - " + mydata[0][i.toString()],
                  style: TextStyle(
                      fontSize: 16.0,
                      fontFamily: "Quando"
                  ),
                ),
              ),
            ),
            Expanded(
              flex: 7,
              child: Container(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    choicebutton('a'),
                    choicebutton('b'),
                    choicebutton('c'),
                    choicebutton('d'),
                    choicebutton('e'),
                  ],
                ),
              ),
            ),
            Expanded(
              flex: 1,
              child: Padding(
                padding: EdgeInsets.only(bottom: 60.0),
                child: Container(
                  alignment: Alignment.topCenter,
                  child: Center(
                    child: Container(
                      ),
                    ),
                  ),
                ),
              ),
          ],
        ),
      )
    );
  }
}

Answer: Seu código pode ser melhorado e refatorado em alguns pontos, porém, me atendo ao foco da pergunta:
Você pode utilizar o operador ternário que Dart disponibiliza. Caso a verificação seja falsa, coloque para receber valor nulo. Da seguinte forma:
[...]
children: <Widget>[
                    choicebutton('a'),
                    choicebutton('b'),
                    choicebutton('c'),
                    choicebutton('d'),
                    TemDados() ? choicebutton('e') : null,
                  ],
[...]

Pelo seu código, não dá para saber exatamente como é o formato da variável mydata, mas acredito que sua verificação teria que ser algo do tipo:
mydata[1][i.toString()].containsKey("e")

containsKey() é um método que retorna verdadeiro se a key está presente no dicionário.
Porém, a titulo de curiosidade, após o Dart 2.3, você também pode usar um if dentro de uma coleção. Acredito ser mais legível, e mais elegante. No seu caso ficaria:
children: <Widget>[
                    choicebutton('a'),
                    choicebutton('b'),
                    choicebutton('c'),
                    choicebutton('d'),
                    if (TemDados()) choicebutton('e'),
                  ],
[...]

Comment: nossa, cara! muito obrigado.vc me deu uma baita de uma aula. e o meu código tá precisando melhorar sim. vou trabalhar nisso depois de fazer o básico funcionar. A propósito, esse mydata recupera dados de um arquivo json que foi o que eu aprendi no tutorial mas, na próxima versão do app eu pretendo usar firebase pq no caso do app (questões de concurso) compensa.


jCarousel and image zoom

Question: I'm using the module image zoom to enlarge an image with the mouse over, also I use jCarousel to get a carousels in different pages.
In the image zoom module you have the option to get the thumbnail of the not selected images.
example :you have a node with 6 images, one will be big and the other will be thumbnails and when you click on one of them automatically it the big image will be swapped with the clicked one.
Now automatically those thumbnail are styled with the jquery carousel, I don't mind but the problem is that I cannot change the configuration of it! I cannot change horizanotal to vertical or other settings.
How do I fix it? Should I create the jcarousel by my self and uninstall the modules or is there a solution somewhere?
Thanks in advance.
Answer: As described on the jCarousel module page:

Note that you will almost certainly need to do custom CSS in your
  theme in order to use this module.

Use Chrome Inspect, Right Click > Inspect aka Chrome Developers Tools or Even use Firebug on Firefox to inspect the applied css properties and override them in your .css file in your theme folder "sites/all/themes/themename"
A basic CSS Knowledge is what you really need.
To Change the Settings of jCarousel, Go to your views and find the "Format" Area. Make sure that the "Format" is set to jCarousel and click on "Settings" beside it. A new pop-up will open. Inside, You will find all the setting related to your jCarousel initiator.
To change from Horizontal to Vertical scrolling, Click on the Advanced, Scroll down then Check the "Vertical" checkbox. See Screenshot
This is the most easy way to do it. If I understod your question rightly.
Comment: That way you should create the jCarousel yourself, All you need is to include the jCarousel .js and .css files in your template directory and add them to template.php using drupal_add_js and drupal_add_css.

You can also use the same plugin and use the API, Read more in the API Usage in the Readme file on the Module Project Page.
Comment: It's not a css issue, i cannot change the setting of the jcarousel. I need to change it. The default setting is "horizontal, 3items scroll" i need to have it vertical with 1 item scroll. I cannot do it with the css.
Comment: Syd, I added a part in the answer, On how to change the jCarousel Settings. Sorry for misunderstanding. Check the Bold Line and paragraph above.
Comment: Hi Jonathan, you got that option if you create a view. It's not a view, it's a node. I don't have the option to change the jcarousel. The system automatically create that carousel. It would be fine as long as i can change the setting. I cannot change it from "manage display" i cannot change in view because it's not a view. Try it, install image zoom and jcarousel, test it and you will see what happens.
Comment: Thanks Jonathan, I always do it manually but it was more easier with the module. Thanks for you help. I give you one vote up now and I will flag it as answer if nobody comes with the solution within one week.

jCarousel and image zoom


Formalization of a simple statement regarding intervals

Question: I have the following statement:
"The open interval (0,1) contains no 'largest' number"
Which I am asked to "formalize" (I hope I am using the correct mathematical jargon here).
I think the most correct way to formalize it is:
$$\forall a (((a>0) \wedge (a<1)) \rightarrow \exists b ((a<b) \wedge (b<1)))$$
I would like to hear your opinion about it.
But is the following also correct? If not, why?
$$\forall a \exists b((a>0) \wedge (a<1) \wedge (a<b) \wedge (b<1))$$
Comment: It depends on the domain you are quantifying over when you write "for all $a$". For all $a$ where?
Comment: It doesn't specify in the question. The question just gives different formalizations of the statement I have given, and I am asked to mark which ones are correct. @MichalAdamaszek
Answer: If you translate this to human language the first expression says:

"for all $a$ in $(0,1)$ there exists a $b$ between $a$ and one" (perfect).

The second expression sounds odd:

"for all $a$ [which ones?] there exists a $b$ such that $a$ is in $(0,1)$ and $b$ is between $a$ and one."

It is certainly not true that any $a$ is in $(0,1)$.
Comment: But is it even correct to say "For all a, if a is in (0,1) ...... " because then it's not for all a. It's like saying "For every colour, if it is white ......" . It's not for every colour in that case. It sounds a bit stupid to say.
Comment: You are right. "For all $a$, if a is in $(0,1)$ ... " is another human language version of your *first* logical statement. The second one is bogus.
Comment: **Second** (borrowing the legend in my Answer) *is* syntactically correct and semantically meaningful, and in fact, the form $∀x{\in}(2,3)\;P(x)$ that you're used to is actually an [abbreviation](https://math.stackexchange.com/a/4232992/21813) of $∀x\;\big(x{\in}(2,3){\implies}P(x)\big).$ This statement asserts that $P(2.7)$ is true while making no claim about the truth value of $P(4.5).$ [Here](https://math.stackexchange.com/a/4272817/21813) is a longer explanation. @MCFromScratch
Comment: @ryang . Thanks for pointing this out. If I now understand correctly : $\forall x \exists y\;(((x>0) \wedge (x<1)) \color{green}{\to} ((x0) \wedge(x<1)) \color{red}{\wedge}  ((x<y) \wedge (y<1)))$ is the wrong second statement. The difference lies in $\color{green}{\to}$ versus $\color{red}{\wedge} $.
Answer:
$$\forall a\;(((a>0) \wedge (a<1)) \rightarrow \exists b\;((a<b) \wedge (b<1)))$$ $$\forall a \exists b\:\:((a>0) \wedge (a<1) \wedge (a<b) \wedge (b<1))$$

Let's call the two statements First and Second. Their domain of discourse is $\mathbb R.$

First accurately formalises the given verbal statement, and is a true statement.
Second claims that whatever $a$ is, we can find some $b$ such that $a∈(0,1)$ and $a<b<1;$ the counterexample $a=100$ clearly shows
that Second is a false statement.
First is logically equivalent to $\forall x \exists y\;(((x>0) \wedge (x<1)) \to ((x<y) \wedge (y<1))).$
(Why?)
Second logically implies First (why?), but not vice versa (why?); that is, Second is a stronger statement than First.
Comment: P.S. [This previous answer](https://math.stackexchange.com/q/4293729/21813) may also be relevant.


Already using utf8mb4 but getting 1366: Incorrect string value: '\xF0\x9F\x98\x81\xF0\x9F...'

Question: All answers to the issue "Incorrect string value" point to using utf8mb4. However, I'm still using that I still get that error.
Running
SELECT CCSA.character_set_name, collation_name FROM information_schema.`TABLES` T,
       information_schema.`COLLATION_CHARACTER_SET_APPLICABILITY` CCSA
WHERE CCSA.collation_name = T.table_collation
  AND T.table_schema = "test"
  AND T.table_name = "products";

produces
character_set_name  collation_name
utf8mb4             utf8mb4_unicode_ci

And running
SELECT character_set_name, collation_name FROM information_schema.`COLUMNS`
WHERE table_schema = "test"
  AND table_name = "products"
  AND column_name = "description";

produces the same result. Then, when I try to update the column description:
UPDATE test.products SET description='Esperienza molto negativa... SCONSIGLIATISSIMO' WHERE id='50'
I get the abovementioned error
1366: Incorrect string value: '\xF0\x9F\x98\x81\xF0\x9F...' for column 'description' at row 1

I've tried this update both through a jdbc connection jdbc:mysql://localhost:3306/test?useUnicode=yes;characterEncoding=utf8; and directly through MySQLWorkbench. I don't know what else to try of look for. What am I missing?
EDIT
Output of SHOW CREATE TABLE
CREATE TABLE `products` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `manufacturerId_fk` int(11) NOT NULL,
  `type_fk` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'TEST',
  `ownerId_fk` int(11) DEFAULT NULL,
  `rating_fk` int(11) NOT NULL,
  `description` varchar(2000) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `authorName` varchar(75) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `authorUrl` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `manufacturer_authorUrl_UNIQUE` (`manufacturerId_fk`,`authorUrl`),
  KEY `fk_products_manufacturers_idx` (`manufacturerId_fk`),
  KEY `fk_products_users_idx` (`ownerId_fk`),
  KEY `fk_products_validRatings_idx` (`rating_fk`),
  KEY `fk_products_productTypes` (`type_fk`),
  CONSTRAINT `fk_products_productTypes` FOREIGN KEY (`type_fk`) REFERENCES `productTypes` (`type`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `fk_products_manufacturers` FOREIGN KEY (`manufacturerId_fk`) REFERENCES `manufacturers` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `fk_products_validRatings` FOREIGN KEY (`rating_fk`) REFERENCES `validRatings` (`value`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=418 DEFAULT CHARSET=utf8mb4

Comment: Please provide `SHOW CREATE TABLE` for the table in question.  And provide the JDBC connection string.
Comment: @RickJames Added `SHOW CREATE TABLE`. The JDBC connection string is right above it
Comment: This is because of character set mismatch for sure, as a try you can recreate the table and insert some sample data and then try to update again.
Comment: @AdarshGangadharan I've just tried dropping and recreating the table, then inserting a row and updating it. Same result
Comment: what is the full hex sequence? it seams there is an error in it...
Comment: @PavelGatnar I don't think there is anything wrong with the hex sequence. It's just for times the hex for GRINNING FACE WITH SMILING EYES, \xF0\x9F\x98\x81
Comment: Do you have any trigger on it? Please provide the show create table results.
Answer: A similar question occurred to me with a text field.
(MySQL 1366 error incorrect string value)
I confirmed the database, table, column character set were all utf8mb4.
The problem was solved by changing the field type to longtext.
Hope this could help someone.
Answer: it is necessary to check up what type costs for the table and for a concrete field. As I understand it, if the configuration is applied after the table has been created, then changing the character type of the database does not affect the table and field settings. I changed the settings for the database type, the table and the specific field where I wrote the value from utf-8.
queries will look like this:
ALTER TABLE `dbName`.`TableName`
CHARACTER SET = utf8mb4 ;

it was for the table. For field:
ALTER TABLE `TableName`
CHANGE COLUMN `columname` `columname` type CHARACTER SET 'utf8mb4' NOT NULL ;

also a Collation related error may occur when using functions and possibly in other cases. To fix, change the table field Collation to one that is compatible. Error example:

Error Code: 1267. Illegal mix of collations (utf8mb4_0900_ai_ci,IMPLICIT) and (utf8mb4_general_ci,IMPLICIT) for operation '='


Cassandra query returns empty array on first query but non-empty array on subsequent queries

Question: I am trying to do a simple query against a Cassandra cluster using the Node.js Cassandra driver. I am following the examples, but it seems like my callback functions are getting called even if there are no results in the returned set.
var q = function (param) {
    var query = 'SELECT * FROM my_table WHERE my_col=?';
    var params = [param];

    console.log("Cassandra query is being called with parameters " + params);

    client.execute(query, params, function (err, result) {
        console.log("Cassandra callback is being called. Row count is " + result.rows.length);

        if (err != null) {
            console.log("Got error");
        }

        if (result.rows.length <= 0) {
            console.log("Sending empty response.");
        }
        else {
            console.log("Sending non-empty response.");
        }
    });
};

q('value');
q('value');

Outputs
Cassandra query is being called with parameters value
Cassandra query is being called with parameters value
Cassandra callback is being called. Row count is 0
Sending empty response.
Cassandra callback is being called. Row count is 1
Sending non-empty response.

This is happening fairly consistently, but sometimes both calls will come up empty, and sometime both calls will return values.
I guess I'm doing something wrong with the async calls here, but I'm not really sure what it is.
Answer: I think this was due to a bad node in my cluster. One of the nodes was missing a bunch of data, and so one third of the time I would get back no results.
Answer: When you open the connection do you send down a consistency command?
I had this issue as well, when I open a connection call execute and send use <keyspace>; followed by consistency local_quorum;. This tells Cassandra to look a little harder for the answer and agree with other nodes that you are getting the latest version.
Note: I keep my connections around for a while, so this doesn't add any meaningful overhead (for me).
Note2: The above doesn't seem to work from my python app anymore (using Cassandra 3.5). However, using SimpleStatement and setting the consistency before calling execute does: https://datastax.github.io/python-driver/getting_started.html#setting-a-consistency-level
I hope this helps.


dhcrelay append option 66 and 67

Question: I'm running a PXE Linux server in a VLAN.
How is it possible to use [dhcrelay][1] to forward the DHCP requests to the main DHCP server and add the options for PXE with dhcrelay?
I've tried something like that:
dhcrelay -d -i eth0 10.0.0.42 -a -m append option 66 10.0.0.23

Assuming 10.0.0.42 is the DHCP and 10.0.0.23 is the PXE server. But I get these results:
Adding 9-byte relay agent option
Forwarded BOOTREQUEST for 00:23:23:23:23:23 to 10.0.0.42
send_packet: Invalid argument

Any Ideas about that?
Answer: The DHCP relay does not add the PXE options, the PXE Server does it.
Answer: The solution was to use dnsmasq in proxyDHCP mode.
This helped me a lot:
https://wiki.fogproject.org/wiki/index.php?title=ProxyDHCP_with_dnsmasq

dhcrelay append option 66 and 67


Implementing geocoder service for OpenLayers map in Angular project

Question: I am working on an Angular project, part of which involves displaying a map with a marker on the given address. I wanted to use the geocoding (and reverse) service from Here, and I followed all the instructions from here:
https://developer.here.com/blog/using-the-here-geocoder-api-for-javascript-in-an-angular-application
The problem is that this request requires an "app id" and an "app code" for authentication. I found on Here's website that "app code" is no longer given out for authentication, and only API key and OAuth token are (which I have), for better security. On using the apikey in place of "app code", it responds with an error "credentials invalid for app-id", understandably. I am having trouble finding the documentation for this service platform object where I can find a way to use the API key instead. Any suggestions? If I resolve the authentication issue, I am pretty sure this will work just fine.
For more context on the project, I do have a restriction on the map service to use (OpenLayers), but not on the third-party geocoder service. There are a few geocoding libraries available on npm but they're all either outdated or don't work. My only last resort is to make my own Http request-response service for another external geocoding API (for which I have proper credentials) - I am currently working on that as well but it is taking time, given I am new to Angular. I just want to make sure I have tried everything else wrt already available services before I set this up from scratch. Please help!
Answer: I think that with just a couple of changes you are ready to go.

Update the version of the API to 3.1, you can do that just by modifying the library url in index.html.

from

to

Update the platform initialization parameters, you can do that by modifying HereService constructor.

from
this.platform = new H.service.Platform({
    "app_id": "APP-ID-HERE",
    "app_code": "APP-CODE-HERE"
});

to
this.platform = new H.service.Platform({
  'apikey': '{YOUR_API_KEY}'
});

That should works.
Comment: Glad it help you!


Executar função PHP com onclick()

Question: Olá, tenho uma função que deveria ser executada somente ao clicar no botão filtrar, mas a página já abre com a pesquisa, com a função executada. O onclick já está no botão de filtro.
Aqui está a função:
function LoadFiltro(buscanova){

    var nr_cliente              = $('select[name=nr_cliente]').val();
    var nr_gc1                  = $('select[name=nr_gc1]').val();
    var nr_status               = $('select[name=nr_status]').val();
    var nr_empresa              = $("select[name='nr_empresa']").val();
    var nr_potencial_fechamento = $("select[name='nr_potencial_fechamento']").val();
    var dt_previsao_fechamento1 = $("input[name='dt_fechamento_ini']").val();
    var dt_previsao_fechamento2 = $("input[name='dt_fechamento_fim']").val();

   $.post('../App_Cad/ControlPreVendas.php',
        {action: 'load',
        type: 'filtro_controle',
        nr_cliente: nr_cliente,
        nr_gc1: nr_gc1,
        nr_status: nr_status,
        nr_empresa: nr_empresa,
        nr_potencial_fechamento: nr_potencial_fechamento,
        dt_previsao_fechamento1: dt_previsao_fechamento1,
        dt_previsao_fechamento2: dt_previsao_fechamento2,
        buscanova: buscanova},
            function(data){
                $('#resp_filtro').html(data);
            }
   );

E aqui o botão:
<input type="button" value="Filtrar" class="botao" onClick="LoadFiltro(true);"/>
Estou abrindo o body assim:

Answer: Boa tarde Felipe!
Talvez eu não seja a pessoa mais recomendada para responder sua pergunta, mas creio que seja impossível fazer javascript executar função em php diretamente... espero que alguém consiga dizer se estou errado ou certo.
Tente passar uma variável como submit/post para a mesma pagina.
Exemplo:
index.php
<?
$execute = $_POST["execute"];

function teste() {
  ...
}

if (!empty($execute)) {
  teste();
}

<form method="POST" action="index.php">
  <input hidden type="text" name="execute" value="1">
  <input type="submit" value="Testar">
</form>

?>

Answer: Consegui resolver e obter o resultado que eu queria.
O que foi feito para dar certo foi: Retirei o atributo onLoad="LoadFiltro(false); do body e deu certo.
Muito obrigado.

Executar função PHP com onclick()


Unable to do forwarding in BIND DNS?

Question: I have BIND working on Windows Server 2003. I want to forward my queries to another server. Recursion is working but forwarding is not working. Can you guide me to set it up? I have given the following in the options:
options {
       directory "c:\named\zones";
       allow-transfer { none; };
       forward only;
       forwarders { 22.214.171.124 ; };
       recursion no;
};

Is the format for forwarding correct in the above.
If not what is the format. Am i to give any port number in the forwarders line? Does forwarding have any particular port number?
Thank You in advance....
Comment: That configuration should work. Do you get any errors in the log files?
Answer: Recursion should not be working, as you have "recursion no;".
options {
  recursion yes;
  allow-recursion { localhost; };
  forward only;
  forwarders { 126.96.36.199; 22.214.171.124; };
};

Unable to do forwarding in BIND DNS?


how to display large amounts of data while keeping the app responsive

Question: In my Android app, I've got a background thread that downloads a lot of data from the network. The thread then parses the data into a form ready for display. Eventually, the thread needs to display this data - i.e. modify a lot of UI elements. The displaying can be only done from the UI thread. If I try to display everything in one go, on my phone it takes about 3 seconds, during which the app appears frozen.
So I've split the displaying into several chunks and wait in between like so:
void backroudThreadDownloadData()
  {
  downloadDataFromInternet();
  parseData();
  int N = splitIntoChunksForDisplaying();

  for(int chunk=0; chunk<N; chunk++)
    {
    final int CHUNK = chunk;

    mActivity.runOnUiThread(new Runnable()
      {
      public void run()
        {
        displayChunk(CHUNK);
        }
      });

    try
      {
      Thread.sleep(200);
      }
    catch( InterruptedException ie)
      { }
    }
  }

This more or less works; the data gets displayed and the app remains mostly responsive during that time. However, it still feels like a hack - especially since I don't really know how long to sleep between the next invocations of the 'displayChunk()' thing.
Any better suggestions how to display large amounts of data while keeping the app responsive?
Answer: For displaying large amounts of data you should consider using PagedList and displaying it in a RecyclerView using a PagedListAdapter.
You can only be pointed in the right direction as it won't be possible to create the whole implementation of this solution right here.
Following are some useful links in this regard:
Paging Library Overview
PagedList
PagedListAdapter
Answer: what you have to do is Tiled Rendering.
basically display what you are capable to compute. then change it at users will.
think that as displaying huge image files (50kx50k jpeg file).
are start you get relatively low res thumbnail of image beacuse phone image cant show that big file (2kx1k image)
then you will get details at zoom.
to fully implement this process you would be needing a manager(viewer) and a renderer(adapter).
another example is viewing infinite lists with recycle view
as a manager recycleview is a good example. we use that with writing a renderer(adapter) class


Join lines with similar first column

Question: File:
A    20
A    35
B    13
C    14
C    49
C    58

Expected output:
A    20,35
B    13
C    14,49,58

I have a tab separated file as above. I want to combine lines with a comma that have the same first column. I know how to combine the lines to give me a tab separated second column, but I'd like the combined values in column 2 to be separated with a comma instead. This is the command I was using:
LC_ALL='C' awk -F'\t' -v OFS='\t' '{x=$1;$1="";a[x]=a[x]$0}END{for(x in a)print x,a[x]}' input.txt > output.txt

I tried to change -F'\t' to -F',', but that didn't seem to work.
Answer: awk '{ A[$1] = A[$1] d[$1] $2; d[$1] = ","}
END {for (i in A) print i, A[i]}' input.txt > output.txt

Explanation :
A[$1] = A[$1] d[$1] $2; - will set an associated array with index $1 and value A[$1] d[$1] $2. Initially it will be equal to $2 because A[$1] and d[$1] are not defined. d[$1] stores output delimiter "," .
END block prints the array index(unique 1st column ) and elements("," separated string)  in a loop.
Comment: This worked wonderfully. Would you mind explaining what you've done though? In the end, I ended up using  `awk 'BEGIN {OFS = "\t"} { A[$1] = A[$1] d[$1] $2; d[$1] = ","} END {for (i in A) print i, A[i]}'` to preserve the first tab
Comment: `for (i in A)` won't guarantee that the output will be printed in the order OP has posted.
Comment: Yes. but then `| sort -k ...` could be used
Answer: $ cat infile
A    20
A    35
B    13
C    14
C    49
C    58

$ awk '{a[$1]=($1 in a ? a[$1] ",":"") $2}END{for(i in a)print i,a[i]}' infile
A 20,35
B 13
C 14,49,58

Explanation:

a[$1] a is array, $1 is first field, used as array key/index
$1 in a if array (a) has index, which is $1 then we get boolean true state
a[$1] "," if previous step state is true, then content of array a for such index will be concatenated with 2nd field, otherwise :"" just second field, that when array has no such index.
for(i in a)print i, a[i] Loop through array a, and variable i as key,
print array key, and value.

a[$1]=($1 in a ? a[$1] ",":"") $2 Can be written as follows for better reading/understanding for beginners.
# if array a seen index $1 before then
if($1 in a){

   # append with existing data
   a[$1] = a[$1] "," $2

# else
}else{

   # did not see before, lets just set new data
   a[$1] = $2

}

Answer: here is another one, takes a grouped input file
$ awk -v OFS=, 'function pr() {if(p2) print p2; p1=$1; p2=$0}
                              {if($1==p1) p2=p2 OFS $2; else pr()}
                END           {pr()}' file

A       20,35
B       13
C       14,49,58

Answer: The problem is its multiple space  and not tab
awk -F'[[:space:]][[:space:]]+' -v OFS=' ' '{if(a[$1])a[$1]=a[$1]","$2; else a[$1]=$2;}END{for (i in a)print i, a[i];}' input.txt > output.txt

Answer: Simply do.
awk '{(a[$1])?a[$1]=a[$1]","$2:a[$1]=$2} END{for (i in a) print i"\t"a[i]}' infile

Join lines with similar first column


Cisco 4400 Series Initializing Hardware loop

Question: I am experiencing an issue with our Cisco 4400 router. Upon booting it gives a flashing STAT light along with a green PWR, TEMP, FAN, PSU0. It then restarts and the fan comes on briefly, and the router outputs "Initializing Hardware . . ." This process repeats over and over. No other errors are displayed. Any insight to this issue would be very helpful.
Thanks in advance,
James
Comment: Had you recently performed an update? I'd [call TAC](http://www.cisco.com/c/en/us/support/web/tsd-cisco-worldwide-contacts.html).
Comment: Had you added or removed a card from your router ?
Comment: No updates have been performed. No cards have been tocuhed. This system was online roughly 2 months agoand worked fine, this is the first time it has come back online since.
Answer: You appear to have a hardware problem.  If you have a maintenance contract with Cisco, you should give them a call.  If you don't, now would be the time to get one.
Comment: Note that if the router is still under warranty, you can also call them without having a support contract. (Warranty FAQ: http://www.cisco.com/c/en/us/products/warranty_qa_guest.html). Also, support contracts have a 1 month lead time, so if you buy one now you may have to wait to get a replacement unit (although if you are lucky you might get one sooner).


Drupal View for the 10 Most Recent Items Sorted by Date ASC

Question: Is it possible to construct a view of the 10 most recent nodes sorted by date in ascending order?
This sounds simple, but it seems as if it's more complicated than I'd imagined.
I think to do this in SQL you'd need a subquery, and I can't see that views is capable of that...
...or is it possible to reverse the order of the rows in the view after they're brought back from the database?
Answer: It seems like a problem with sorting and offset.
To get the 10 most recent nodes sorted by date descending is easy and will return the correct result. You are however sorting for the 10 most recent by date ascending and will just get the 10 oldest nodes.
Ideally you need to get the count of all nodes as by your criteria, then subtract 10 from that to use as the offset.
The easiest is to just reverse the order before rendering. Construct your view to sort by date descending, then add this to your theme's template.php file:
function THEME_views_pre_render(&$view) {
  if ($view->name == "VIEWNAME" && $view->current_display == "DISPLAYNAME") {
    $view->result = array_reverse($view->result);
  }
}

After you add this code you need to clear your cache.
You get the view machine name and display name like this:

Hover mouse on View tab, then look at link below: here most_recent is the view machine name and page is the display name.
Comment: I managed to create a custom module which creates a custom views display extender that puts in an option called "Reverse Results" under the "Advanced->Other" section in the Views UI. I implemented hook_views_post_execute so that any views format should get the results in reverse. Thanks for your help!


How to calculate the inverse matrix?

Question: It is given that, $A$ is $3 \times 3$ matrix and that
$$A\begin{pmatrix} x\\y\\z\\\end{pmatrix}= 5\begin{pmatrix} p\\q\\r\\\end{pmatrix}$$
and that
$$x= 3p+2q-4r \\
y=p+5q-2r \\
z=7p-6q+3r \\$$
then how can I find $A^\text{-1}$ ?
Comment: solve it for $p,q,r$
Comment: multiply both sides of equation by $A^{-1}/5$, and fill in the standard basis vectors for $(p,q,r)$. This will give the columns of $A^{-1}$. Note the inverse exist, since $A$ is surjective by the equation.
Answer: Hint: $$\begin{bmatrix}x\\y\\z\end{bmatrix} = 5A^{-1}\begin{bmatrix}p\\q\\r\end{bmatrix}.$$
The first row of $5 A^{-1} = \begin{bmatrix}3 & 2 & -4\end{bmatrix}.$
Comment: please give me more hints...
Comment: @MubtasimFuad I gave you the first row of $5A^{-1}$. Compare it with the first equation $x = 3 p + 2q - 4r$. Can you figure out how I got $[3~2~-4]$ from the equation? For the second row, use the second equation. Likewise, the third row can be obtained from the third equation.
Comment: Thank you, I think I got it.
so $$A^{-1}=\begin{pmatrix}
    3/5 & 2/5 & -4/5\\ 1/5 & 1 & -2/5\\ 7/5 & -6/5 & 3/5\\ \end{pmatrix}$$ ?
Comment: I'm glad that you have obtained the correct value of $A^{-1}$.

How to calculate the inverse matrix?


Determine the value of a second determinant based on the first

Question: I know the theory of determinants, but I have no idea how to apply it to this problem.
Suppose $$\det\begin{bmatrix}a&b&c\\ d&e&f\\ g&h&i \end{bmatrix} = 6$$
What is the value of
$$\det\begin{bmatrix}g - 2a&h - 2b&i - 2c\\ 3a&3b&3c\\2d&2e&2f \end{bmatrix}$$
The options for the answers are:

4
36
24
-24
Comment: Elementary transformation on matrix do not change the determinant.
Comment: Ah, thanks  I remember reading that. What i did not add onto this question though is the fact that this is a multiple choice question. I will edit the question with the options. Of course, the options could be wrong.
Answer: Also, for the fast way not the theoretical approach, you can set $a=2,e=3,i=1$ and other arrays to be zero and just examine the value of determinant you're asked. So, it gives you $36$.
Comment: This method is usefull to verify a long calculus (+1).
Comment: Nice work, @Babak!
Answer: $$\det\begin{bmatrix}g - 2a&h - 2b&i - 2c\\ 3a&3b&3c\\2d&2e&2f \end{bmatrix}$$
$$=\det\begin{bmatrix}g&h&i\\ 3a&3b&3c\\2d&2e&2f \end{bmatrix}$$ (Applying $R_1'=R_1+\frac23 R_2$)
$$=3\cdot2\cdot \det\begin{bmatrix}g&h&i\\ a&b&c\\d&e&f \end{bmatrix}$$ (Taking out $3,2$ as common factors from the $R_2,R_3$ respectively)
$$=(-1)3\cdot2\cdot \det\begin{bmatrix}a&b&c\\ g&h&i\\d&e&f \end{bmatrix}$$ (Exchanging $R_1,R_2$ resulting '-' sign )
$$=(-1)(-1)3\cdot2\cdot \det\begin{bmatrix}a&b&c\\d&e&f\\ g&h&i \end{bmatrix}$$
(Exchanging $R_2,R_3$ resulting '-' sign  again)
Answer: We switch the first and the second row and the second and third row so
$$\det\begin{bmatrix}g - 2a&h - 2b&i - 2c\\ 3a&3b&3c\\2d&2e&2f \end{bmatrix}=3\times 2\times \det\begin{bmatrix}a&b&c\\ d&e&f\\ g - 2a&h - 2b&i - 2c\end{bmatrix}$$
and we add $2\times$ the first row to the third row we find
$$\det\begin{bmatrix}g - 2a&h - 2b&i - 2c\\ 3a&3b&3c\\2d&2e&2f \end{bmatrix}=3\times 2\times \det\begin{bmatrix}a&b&c\\ d&e&f\\ g &h &i \end{bmatrix}=6\times 6=36$$
Answer: det$\begin{bmatrix}g - 2a&h - 2b&i - 2c\\ 3a&3b&3c\\2d&2e&2f \end{bmatrix}$ =3$\times 2\times \det\begin{bmatrix}g - 2a&h - 2b&i - 2c\\ a&b&c\\d&e&f \end{bmatrix}$  =6$\times -1\times \det\begin{bmatrix}a&b&c\\g - 2a&h - 2b&i - 2c \\d&e&f \end{bmatrix}$R1 ->R2, R2 ->R1 = 6$\times -1\times -1\times\det\begin{bmatrix}a&b&c\\d&e&f \\g - 2a&h - 2b&i - 2c \end{bmatrix}$R2 ->R3, R3 ->R2 = 6$\times\det\begin{bmatrix}a&b&c\\d&e&f \\g - 2a&h - 2b&i - 2c \end{bmatrix}$ = 6$\times\det\begin{bmatrix}a&b&c\\d&e&f \\g&h&i\end{bmatrix}$ R3 -> 2R1+R3 As, $\det\begin{bmatrix}a&b&c\\d&e&f \\g&h&i\end{bmatrix}$=6
 = 6$\times6=36$
Answer: determined of square matrix is the multiplication of all term present on diagonal. so you can set $a,e,i$ such that is gives $6$ and all other terms $0$. Now put all values in second matrix and evaluate the result it is $36$.
let $a=1, e=1,i=6$
$$\det\begin{bmatrix} -2&0&6\\ 3&0&0\\0&2&0\end{bmatrix}$$
it gives $36$


How to test a function that's using a Client API function imported from another module?

Question: I've been trying to figure out a way to test the following piece of code (in Elixir):
 defmacro __using__(_) do
      quote do
        # API functions will be used from this client
        import Client.API

        def list_storages do
          case list_buckets do
            {:ok, res} ->
              case res.status_code do
                200 ->
                  res.body
                  |> Friendly.find("name")
                  |> Enum.map(fn bucket -> bucket.text end)
                _   ->
                  res |> show_error_message_and_code
              end
            {:error, reason} ->
              parse_http_error reason
          end
        end
  ...

The problem is the list_buckets function is being import from the Client.API module (that's already being tested in another project which I can't really change anything there). My idea was to stub/mock/dummy the API functions so that they return just a dummy reply. I've tried using defoverridable to override the list_buckets function but that doesn't work since the function definition is happening in another module.
I've read the following post by José Valim and that has helped test the Client.API module but I don't find a way to apply those concepts to this particular problem.
My only (and stupid) idea so far is to just reimplement every function inside the macro in a test file and use a dummy API function defined there but that feels very wrong and not helpful if there are code changes in the non-testing code.
Basically I want to test if the three possible cases are correct:

Receiving {:ok, res} and code 200 -> Outputs the correct data
Receiving {:ok, res} and another code -> Output the error message and code
Receiving {:error, reason} -> parses the HTTP error and outputs the reason for failure

Can anyone help me with this?
Answer: You can still use the principles from that blog post. Instead of importing Client.Api pass it as a last variable to list_storages.
def list_storages(api \\ Client.Api) do
  case api.list_buckets do

This way you don't need to change anything in your application code and you can pass dummy mock when testing the function.


Does Unity compile scripts to c++?

Question: Does Unity compile C# scripts to C++?
And generally how does running games in Unity work?
Comment: @nada You can just write in C++ from the beginning. But you lose vast amounts of development iteration speed. The unity burst compiler offers "performance by default", with a nice job system. You can write something faster, but there's not many widely available engines that can compete with Unity's extensive tools library and Cpu performance combined right now, even engines that encourage writing native C++ for gamecode.
Comment: @VTT probably because of IL2CPP and Burst.
Comment: No. It would probably have decent performance, if it did.
Comment: @VTT Because it does if you use IL2CPP... See their [blog](https://blogs.unity3d.com/2015/05/06/an-introduction-to-ilcpp-internals/)
Comment: @nada You can use IL2CPP... it will convert C# to C++....
Comment: No it doesn't. Unity executes on C# virtual machine.
Comment: @LudovicFeltz Ooooorrrr I just write my code in C++ from the beginning.
Comment: @George I'd love to discuss this further, but in practise you are proven correct by the vast amount of games that pop up which are made with unity.
Answer: I see a lot of comment here that are totally WRONG. The answer is YES, you can convert C# code to C++ as an alternative to Mono if you are using IL2CPP. (if you choose to in player params)

When building a project using IL2CPP, Unity converts IL code from
  scripts  and assemblies to C++, before creating a native binary file
  (.exe, apk, .xap, for example) for your chosen platform. Some of the
  uses for IL2CPP include increasing the performance, security, and
  platform compatibility of your Unity projects.

You can see this blog post on the Unity website about how it works.
Or the documentation for more informations on the subject
Comment: @nada Do you have any background for the statements you are making? It appears to me that you are throwing around unfounded (and incorrect) guesses as facts. Please write an answer if you are sure of what you are saying and have sources to back you up.
Comment: @nada The Sub-question *And generally how does running games in Unity works?* looks a little to broad to answer here... I just answer to *how does it convert C# to C++* would be more correct i think
Comment: Just a reminder: You haven't actually answered OP's embedded question _And generally how does running games in Unity works?_
Comment: Sorry for the *link only* answer but i will not copy paste the content here
Comment: @nada I bet too :) but that's another subject ;)
Comment: @MaxLanghof Just a rule of thumb: _Additional layers of complexity add potential for additional problems_ (... and this sounds to me like it has huge complexity, just have a quick glimpse at the linked docs)
Comment: Unity also offers the [Burst compiler](https://firstname.lastname@example.com/manual/index.html#overview), I haven't used it extensively for any sort of long term project. But I have used it for a few smaller projects aswell as jams and it has worked great so far. Obviously it compiles straight to assembly so you do lose C++ symbols, not sure if that's really a problem though.
Comment: IL2CPP, just like Burst, is a form of AOT compilation, and regardless of method used the final output will still be a managed code using the same mono runtime. Also use of IL2CPP *reduces* security and platform compatibility.
Comment: @VTT for the security/compatibility part, i just quoted their documentation. And for the managed part it looks like it compile the generated C++ to native code dependent on the target platform see: the [documentation](https://docs.unity3d.com/Manual/IL2CPP-HowItWorks.html)

Does Unity compile scripts to c++?


calling javascript function from PHP - quotes issue

Question: I'm trying to call javascript function from PHP. the idea is to create each parameter from file as link that when clicked inputs it's value into text box.
$lines = file('http://localhost/repositories.txt');
foreach ($lines as $line_num => $line) {
    echo  "".htmlspecialchars($line) . "
";
}

when clicking the created links I'm getting (for example):
ReferenceError: test2 is not defined

I think there should be quotation marks around the parameter, but I can't add them. I tried to use ' \" ' without success.
any ideas?
Comment: Can you tell us something about test2?
Answer: You need to quote and properly escape the JavaScript string that you're assigning to the input value property. You can use json_encode for that:
echo "".htmlspecialchars($line) . "
";

Demo

The main cause of the issue is that your code was missing the quotes around the string value, so JavaScript was interpreting it as an identifier (variable name).
json_encode adds quotes around the value and, more importantly, escapes the value to make sure it is a valid JSON string (it escapes line feeds, carriage returns and quotes which could easily result in a syntax error otherwise).
JSON is a subset of the JavaScript syntax, so any valid JSON is valid JavaScript. (provided it is used in a suitable context)
Finally, as the value is inside an HTML attribute, htmlspecialchars is still applied to escape the value. It escapes quotes to make sure the variable value does not break out of the attribute value and also escapes characters such as & to not be interpreted as the beginning of an HTML entity sequence.

Finally, I would recommend against echo in this case, as to reduce the number of quotes and make interpolation easier to read:
$lines = file('http://localhost/repositories.txt');
foreach ($lines as $line_num => $line) { ?>
    <a onclick='document.folderForm.folderLocation.value=<?= htmlspecialchars(json_encode($line)) ?>;' href='#'><?= htmlspecialchars($line) ?>

<?php } ?>

Demo
Note: PHP short echo tags are available everywhere independent of configuration as of PHP 5.4. Switch <?= to <?php echo if you need to support PHP < 5.4.
Comment: No problem. I've just added some more in-depth explanation as well.


Drawing on Classical Guitar with Open Pore Finish

Question: this might be a somewhat naive question, but I am curious if using some type of permanent marker to draw on a classical guitar with an open pore finish will cause any issues? I'd like to give it a go, but I am somewhat concerned that it may affect the tone of the guitar. I mean to illustrate pretty much the entire body and possibly neck, but I just don't know if that would potentially ruin it. Searching online I am only finding things for electric and steel with glossy finish.
Which makes me also wonder, if it is possible, are there specific types of markers I should use for an open pore? And, would I have to put a glossy finish on it? I don't think I would want to do that if possible.
Answer: I'm skeptical that it would affect the sound, but it would almost certainly affect the value. (And if it has a tone worth worrying about, then perhaps its value is enough that it's a bad idea to ruin it!) If you do an extraordinarily good job of decoration (or become famous) it might increase the value, but otherwise it would probably drastically reduce it. Of course, if the guitar doesn't have much value to lose... why not. To anyone who wants to get verklempt about "defacing" an instrument by decorating it, I'd point to the long tradition of decorating the Norwegian "hardanger" fiddle with pen-and-ink patterns. And of course Woodie Guthrie famously personalized his guitar, and it's certainly worth something today.
Comment: Thank you! Much appreciated! And, totally agree with the value, in my case it is a cheap $500 classical. Good tone, but not anything to be concerned about.
Comment: @RobProctor If it were me, I'd definitely want to practice on some pieces of scrap wood first! Also, https://www.rickertmusicalinstruments.com/2011/03/tattooed-fiddles-by-don-rickert-design.html suggests that sometimes people use transfers or stencils. Though it also talks about putting a clear coat over the top, and that definitely might affect tone.


UIScrollView as image viewer

Question: I have to use UIScrollView as image viewer like Photo app. The UIScrollView is supposed to show photos with swiping, zooming and rotating with interface rotation.i have to load minimum 20 images.is it possible? which is the best way? plz post some sample codes.
Comment: This is a _very_ general question - you're dealing with multiple concepts (swiping, zooming, interface rotation) and haven't provided sample code of what you've tried or a place to get started. Try to focus in on one area, or take a stab at it (using Apple-provided sample code (the Scrolling project would be a good start)) and then refine your question.
Answer: I've written a simple and easy to use photo browser called MWPhotoBrowser which you should be able to look at and dissect.
It is an implementation of a photo viewer that I wrote allowing the user to view one or more images in a similar way to the native Photos app. It can display one or more images by providing either UIImage objects, file paths to images on the device, or URLs images online. Photos can also be zoomed, panned, and navigated with previous/next buttons.
View MWPhotoBrowser on GitHub
Hope this helps!
Answer: Refer to the sample application page control here https://developer.apple.com/iphone/library/samplecode/PageControl/ , it should help you get started, they have a scroll view that you can use to scroll through a bunch of pages, you can modify this to do pictures.  It doesnt do zooming o rotationg but its a good place to start

UIScrollView as image viewer


Complex/real base vectors

Question: If I have a subspace of $\mathbb C^n$ which is spanned by $N$ complex basis vectors. Could I span the same space with $N$ basis vectors that each have real components? (but, of course, using complex coefficients)?
Comment: It is not clear what you mean. Is your space supposed to be a subspace of $\mathbb C^k$ for some $k$?
Answer: Consider the vector space $\mathbb{C}^{2}$ over the field $\mathbb{C}$.
Now consider the subspace spanned by $\left[\begin{array}{c}
1\\
i
\end{array}\right]$. That is, $$\text{span}\left(\left[\begin{array}{c}
1\\
i
\end{array}\right]\right)=\left\{ \left(z\left[\begin{array}{c}
1\\
i
\end{array}\right]\right)\in\mathbb{C}^{2}\mid z\in\mathbb{C}\right\}. $$ Clearly $\left[\begin{array}{c}
1\\
i
\end{array}\right]$ is in this space. Can you find a vector $v\in\mathbb{R}^{2}$ s.t.
$zv=\left[\begin{array}{c}
1\\
i
\end{array}\right]$ for some $z\in\mathbb{C}$? Try
and convince yourself that you cannot.
Comment: Thank you... My doubt was resolved.

Complex/real base vectors


How can I see the source code for the Python library "keyboard"?

Question: Let's say that I wanted to create my own library to be used in Python. How would I code a key press? How do I establish that without referencing the Python library of "keyboard"? I would love to be able to view the "keyboard" library that I import, in order to see how that library was created.
Thanks!
Comment: Do `import keyboard; print(keyboard.__file__)`, then open that file in the text editor of your choice. Alternatively, find the code on github.
Comment: https://github.com/boppreh/keyboard? I just looked it up on https://pypi.org/ and followed the links to the source code.
Comment: @Aran-Fey, in place of `_file_`, am I putting something like `_init_ or _main_`, or do you literally mean `_file_`? Because when I run that, I am getting:

`AttributeError: module 'keyboard' has no attribute '_file_'`
Comment: @jonrsharpe Thank you for the link. That was what I was looking for, I think. I'm still new to all of this so that's a lot of source code to look through.
Comment: I mean `__file__` with 2 underscores on each side.
Answer: You can check out the inspect module.
Also possibly duplicate of this: How can I get the source code of a Python function?


get error after add routing to my anglularjs application

Question: I'm new in angularjs and I want to load new content from another html file I use this below codes but I don't know why I get this errors
Error: [$injector:modulerr] http://errors.angularjs.org/1.2.25/$injector......

app.js
var app = angular.module("boors", ['ngRoute']);
app.config(boorsRouter);
function boorsRouter($routeProvider){
 $routeProvider
             .when('#/', {templateUrl: 'partials/news.html',
              controller: function  ($scope) {
                 $scope.setActive('news');
              }})
 ;
}

I add this script in html file

where I go wrong?
Comment: What does error message complain about?
Comment: I don't know exactly what does it about I don't know why i get that error
Comment: It's hard to say. There is some error. I think in the code you didn't include here.
Comment: when i remove the rout the error disapear
Comment: What is `$scope.setActive`?
Comment: you can include not minified `angular.js` and `angular-route.js` - it can help you get more readable error. can you provide full error text?
Answer: Remove # in the when method.
$routeProvider
    .when('/', {templateUrl: 'partials/news.html',
        controller: function  ($scope) {
            $scope.setActive('news');
        }
    });

Comment: i remove all of the content of function but anything doesnt change
Comment: what is $scope.setActive()?
Comment: it is a function for display a content , I REMOVE ALL THE CONTENT OF FUNCTION


How does centering make a difference in PCA (for SVD and eigen decomposition)?

Question: What difference does centering (or de-meaning) your data make for PCA? I've heard that it makes the maths easier or that it prevents the first PC from being dominated by the variables' means, but I feel like I haven't been able to firmly grasp the concept yet.
For example, the top answer here How does centering the data get rid of the intercept in regression and PCA? describes how not centering would pull the first PCA through the origin, rather than the main axis of the point cloud. Based on my understanding of how the PC's are obtained from the covariance matrix's eigenvectors, I can't understand why this would happen.
Moreover, my own calculations with and without centering seem to make little sense.
Consider the setosa flowers in the iris dataset in R. I calculated the eigenvectors and eigenvalues of the sample covariance matrix as follows.
data(iris)
df <- iris[iris$Species=='setosa',1:4]
e <- eigen(cov(df))
> e
$values
[1] 0.236455690 0.036918732 0.026796399 0.009033261

$vectors
            [,1]       [,2]       [,3]        [,4]
[1,] -0.66907840  0.5978840  0.4399628 -0.03607712
[2,] -0.73414783 -0.6206734 -0.2746075 -0.01955027
[3,] -0.09654390  0.4900556 -0.8324495 -0.23990129
[4,] -0.06356359  0.1309379 -0.1950675  0.96992969

If I center the dataset first, I get exactly the same results. This seems quite obvious, since centering does not change the covariance matrix at all.
df.centered <- scale(df,scale=F,center=T)
e.centered<- eigen(cov(df.centered))
e.centered

The prcomp function results in exactly this eigenvalue-eigenvector combination as well, for both the centered and uncentered dataset.
p<-prcomp(df)
p.centered <- prcomp(df.centered)
Standard deviations:
[1] 0.48626710 0.19214248 0.16369606 0.09504347

Rotation:
                     PC1        PC2        PC3         PC4
Sepal.Length -0.66907840  0.5978840  0.4399628 -0.03607712
Sepal.Width  -0.73414783 -0.6206734 -0.2746075 -0.01955027
Petal.Length -0.09654390  0.4900556 -0.8324495 -0.23990129
Petal.Width  -0.06356359  0.1309379 -0.1950675  0.96992969

However, the prcomp function has the default option center = TRUE. Disabling this option results in the following PC's for the uncentered data (p.centered remains the same when center is set to false):
p.uncentered <- prcomp(df,center=F)
> p.uncentered
Standard deviations:
[1] 6.32674700 0.22455945 0.16369617 0.09766703

Rotation:
                    PC1         PC2        PC3         PC4
Sepal.Length -0.8010073  0.40303704  0.4410167  0.03811461
Sepal.Width  -0.5498408 -0.78739486 -0.2753323 -0.04331888
Petal.Length -0.2334487  0.46456598 -0.8317440 -0.19463332
Petal.Width  -0.0395488  0.04182015 -0.1946750  0.97917752

Why is this different from my own eigenvector calculations on the covariance matrix of the uncentered data? Does it have to do with the calculation? I've seen mentioned that prcomp uses something called the SVD method rather than the eigenvalue decomposition to calculate the PC's. The function princomp uses the latter, but its results are identical to prcomp. Does my issue relate to the answer I described at the top of this post?
EDIT: Issue was cleared up by the helpful @ttnphns. See his comment below, on this question: What does it mean to compute eigenvectors of a covariance matrix if the data were not centered first? and in this answer: https://stats.stackexchange.com/a/22520/3277. In short: a covariance matrix implicitly involves centering of the data already. PCA uses either SVD or eigendecomposition of the centered data $\bf X$, and the covariance matrix is then equal to ${\bf X'X}/(n-1)$.
Comment: `Based on my understanding of how the PC's are obtained from the covariance matrix's eigenvectors...` Please read comments in the answer you link to. Covariances imply centering of data, PCA "on covariances" = PCA on centered data. If you don't center the original variables `X`, PCA based on such data will be = PCA on `X'X/n [or n-1]` matrix. See also important overview: http://stats.stackexchange.com/a/22520/3277.
Comment: `through the origin, rather than the main axis of the point cloud`. PCA always pierces the origin. If data were centered, origin = the centroid.
Comment: Many sources emphasise the importance of centering your data and then go on to explain how the eigenvectors of the covariance matrix are of interest, seemingly ignoring the fact that $\bf S$ is implicitly centered already. The PCA entry on wikipedia does not make this distinction either: *To find the axes of the ellipse, we must first subtract the mean of each variable from the dataset to center the data around the origin. Then, we compute the covariance matrix of the data, and calculate the eigenvalues and corresponding eigenvectors of this covariance matrix.*
Comment: See [Principal component analysis: a review and recent developments](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4792409/) for a discussion of centered vs. un-centered PCA (which are generally not the same).
Comment: Thank you, the overview especially helped clear things up for me. So it is simply an issue of naming conventions? I assumed PCA was a calculation based around the covariance matrix, whereas it is generally defined as a calculation performed on a centered dataset (where $\bf X'X$ is the covariance matrix). This seems like a confusing convention though. cont.
Answer: As you remarked yourself and as explained by @ttnphns in the comments, computing covariance matrix implicitly performs centering: variance, by definition, is the average squared deviation from the mean. Centered and non-centered data will have identical covariance matrices. So if by PCA we understand the following procedure: $$\mathrm{Data}\to\text{Covariance matrix}\to\text{Eigen-decomposition},$$ then centering does not make any difference.

[Wikipedia:] To find the axes of the ellipse, we must first subtract the mean of each variable from the dataset to center the data around the origin. Then, we compute the covariance matrix of the data...

And so you are right to observe that this is not a very accurate formulation.
When people talk about "PCA on non-centered data", they mean that instead of covariance matrix the eigen-decomposition is performed on the $\mathbf X^\top \mathbf X/(n-1)$ matrix. If $\mathbf X$ is centered then this will
be exactly the covariance matrix. If not then not. So if by PCA we understand the following procedure:
$$\text{Data } \mathbf X\to\text{Matrix } \mathbf X^\top \mathbf X/(n-1)\to\text{Eigen-decomposition},$$
then centering matters a lot and has the effect described and illustrated by @ttnphns in How does centering the data get rid of the intercept in regression and PCA?
It might seem weird to even mention this "strange" procedure, however consider that PCA can be very conveniently performed via singular value decomposition (SVD) of the data matrix $\mathbf X$ itself. I describe this in detail here: Relationship between SVD and PCA. How to use SVD to perform PCA? In this case the procedure is as follows:
$$\text{Data } \mathbf X \to \text{Singular value decomposition}.$$
If $\mathbf X$ is centered then this is equivalent to standard PCA done via covariance matrix. But if not, then it's equivalent to the "non-centered" PCA as described above. Since SVD is a very common and very convenient way to perform PCA, in practice it can be quite important to remember to center the data before calling svd function. I certainly had my share of bugs because of forgetting to do it.
Comment: I've got an advice for your answer to make a cleaner logic. Since in your two first (eigen) examples you are speaking of the decomposition MSCP matrix `X'X/(n-1)` and not of SSCP matrix `X'X` - it would be in the svd example, showing the equivalence, to decompose `X/sqrt(n-1)` instead of `X` (as you currently speak of). [Of course the difference is only in the scale part (eigenvalues) not eigenvectors, but it is better didactically, I would think.] My second point would be to remind that as soon as centering of `X` takes no place the Bessel correction `n-1` becomes unnecessary, `n` is welcome.
Comment: Both good points, @ttnphns. I will think about how I can incorporate them into my answer: I wanted this answer to be understandable by a broader audience and so tried to avoid going into unnecessary mathematical details.
Answer: I'll try to provide a mathematical justification.
By centering, I assume you mean applying eigendecomposition on $XX^T$ instead of $(X-\mu)(X-\mu)^T$
Here $\mu$ denotes the sample mean and not the true mean, thus $\mu = \sum_i x_i / n$
Let $B = \sum_i x_ix_i^T$
Let $A = \sum_i (x_i - \mu)(x_i - \mu)^T$
$A= \sum_i (x_ix_i^T -\mu x_i^T - x_i \mu^T + \mu\mu^T) = B + \sum_i (-\mu x_i^T - x_i \mu^T + \mu\mu^T)$
$A = B - \mu(\sum_i x_i)^T - (\sum_i x_i)\mu^T + \sum_i \mu\mu^T$
$A = B - \mu(n\mu)^T - (n\mu)\mu^T + n\mu\mu^T$
$A = B - n\mu\mu^T - n\mu\mu^T + n\mu\mu^T$
$A = B - n\mu\mu^T$
Usually, we take the eigendecomposition of $C = A/(n-1)$ (This is definition of the sample covariance matrix)
Here, say if you take the eigendecomposition of $D = B/(n-1)$, thus,
$$\boxed{D = C + \frac{n\mu\mu^T}{n-1}}$$
Then it is clear that the eigenvalues and eigenvectors corresponding to $D$ won't be the same as those for $C$ (unless $\mu$ = 0)
Thus, you would obtain wrong principal components (The correct principal components correspond to the eigendecompostion of $C$).
Answer: Carefully read through this thread which helps me greatly on understanding the whole PCA process, here is my summary (not sure if I get the true idea or not):
PCA <-> Eigen-decomposition on cov matrix -> it will find axis on whose direction the data has max spread. it doesn't matter whether we center the data data before hand, the cov matrix is the same and thus we will always get axis maximize the data spread.
I saw some text book when introducing PCA, they assume that the data matrix is centered. I think this is the reason that triggers my confusion, it induced me that the data needs to be centered before doing PCA analysis. Now my feeling is that I need to look these in a revers way: centering the data helps to justify that eigen vectors of covariance matrix is the right axis that we are looking for.
Comment: I think you missed the main point: PCA can be conducted on the sum-of-squares-and-products matrix.  This is not the covariance matrix at all.  It matters *hugely* whether the data are centered.


How to restrict previous date display in custom forms?

Question: I created a custom module for a form which accepts from date and to date as user input. I would like to restrict the user from selecting a date prior to current date.
Code snippet of my code
<code>$form['oneway']['from_date'] = array (
  '#type' => 'date',
  '#title' => t('From Date'),
  '#date_year_range' => '-80:0',
  '#required' => TRUE,
);
</code>
Can someone please help me out?
Comment: what does your from date look like? `d/m/Y 18/01/2016` ? OR ???
Answer: Approach to get today's date as Minimum date
Pass the JS options in '<code>#datepicker_options</code>'
<code>$form['oneway']['from_date'] = array(
  '#title' => t('From Date'),
  '#type' => 'date_popup',
  '#date_format' => 'Y-m-d',
  '#date_year_range' => '-80:0',
  '#required' => TRUE,
  '#datepicker_options' => array(
    'minDate' => 0,
  ),
);
</code>

minDate => 0 (Sets the min date to today's date)
minDate => -1 (Sets the min date to yesterday's date)

More info: http://api.jqueryui.com/datepicker/#option-minDate
Comment: HI Gaurav, Thanks for your replay i have deployed the code in my form,but the date picker in my form is not visible. I am using drupal 8, are there any changes to be made in drupal 8
Comment: date_popup is not working in drupal 8 ???
Answer: <code>    $form['oneway']['from_date'] = array(
      '#title' => t('From Date'),
      '#type' => 'datetime',
      '#date_format' => 'Y-m-d',
      '#date_year_range' => '-80:0',
      '#required' => TRUE,
      '#attributes' => [
        'min' =>  \Drupal::service('date.formatter')->format(REQUEST_TIME, 'custom', 'Y-m-d'),
    ],
    );
</code>
date_popup is not going to work in drupal 8.x, use datetime


How to determine influence of two time series with feedback?

Question: Say you have two time series, A & B. Each have a mutual effect on the other. To give a real-world example, say that time series A measures an artist's CD sales per month, and time series B is some measure of the artist's "Q" rating. Clearly, increase in A will drive an increase in B, but at the same time, an increase in the Q rating could drive sales higher (or vice-versa). Is there a statistical approach to tackle this problem, or is this more the realm of control systems?
Answer: A more general but less tractable approach is referred to as Vector Arima (VARIMA) which doesn't place restrictions on the model form as Vector Autoregression does (VAR). In both cases , one needs to incorporate exogenous variables and be aware that Pulses, Seasonal Pulses, Local Level Shifts and Local Time trends need to be dealt with via Intervention Detection. As usual with time series care has to be taken to test constany of parameters and error variance over time.
Answer: I think you are looking for Vector Autoregression.


Xamarin iOS HttpClient Timeout doesn't work

Question: At some point we found all the requests in our app have timeout of 60 seconds on iOS though we set the default value for the HTTP framework we use as 3 minutes. I tried the following piece of code to figure out if it's the library who has an issue:
try
{
    using (var http = new HttpClient())
    {
        http.Timeout = TimeSpan.FromMinutes(1.5);
        await http.GetAsync("https://httpstat.us/200?sleep=70000");
    }
}
catch (Exception ex)
{
}

This code fails with the timeout exception though the timeout is set as 90 sec and the request goes for 70 sec. Turns out it doesn't override the default timeout of 60 sec. The same code works well on the fresh project.
In the project file we have <MtouchHttpClientHandler>NSUrlSessionHandler</MtouchHttpClientHandler>
Answer: Xamarin's NSUrlSessionHandler uses the default NSUrlSessionConfiguration if you are not creating your own instance of the NSUrlSessionHandler and providing a custom NSUrlSessionConfiguration in its .ctor.
The default NSUrlSessionConfiguration timeouts are set to 60 seconds in iOS.
So in your Xamarin.iOS application project, open the AppDelegate.cs and set the default session timeout parameters within the FinishedLaunching override.
NSUrlSessionConfiguration.DefaultSessionConfiguration.TimeoutIntervalForRequest = 90.0;
NSUrlSessionConfiguration.DefaultSessionConfiguration.TimeoutIntervalForResource = 90.0;

timeoutIntervalForRequest
The timeout interval to use when waiting for additional data.

timeoutIntervalForResource
The maximum amount of time that a resource request should be allowed to take.

re: https://developer.apple.com/documentation/foundation/nsurlsessionconfiguration#//apple_ref/occ/instp/NSURLSessionConfiguration/timeoutIntervalForRequest
Comment: I'll try, thanks. Though it doesn't explain why the same works for the fresh project.
Comment: Are you assigning that the HttpClient use NSUrlSessionHandler in that new iOS project? You can look at Xamarin's `NSUrlSessionHandler` code, they do not alter the default NSUrlSessionConfiguration parameters and HttpClient options are not "passed through" as changing the *default* parameters would not be very "polite".
Comment: Sure. Both use it.
Comment: As the value may be set globally, I'm thinking if one of our other 3rd party dependencies could reset it...
Comment: @SergeyMetlov That is possible, you can always provide your own `NSUrlSessionConfiguration` in the .ator to `NSUrlSessionHandler`.
Comment: The documentation of `NSUrlSessionConfiguration.DefaultSessionConfiguration` in Visual Studio  is "A copy of the default session configuration" meaning (to me) that everything you do to this instance (even if its properties had `set;`) will change nothing;
Comment: @Marc_Alx See "Types of Session Configurations" : https://developer.apple.com/documentation/foundation/nsurlsessionconfiguration


Multi-variable logistic regression for paired data in SPSS?

Question: I was hoping for some assistance regarding performing a multi-variable logistic regression for a matched data set. I am not formally trained as a statistician (biology trained with basic stats/SPSS training), so am struggling a little bit.
I have a data set with ~300 propensity score matched pairs. I am interested in outcome "X", and seeing if any of my variables were independent predictors of outcome X.
In the unmatched data set (prior to propensity matching) I performed a multivariable logistic regression, and was interested in doing the same for my matched model.
I am currently using SPSS for my data analysis.
Comment: Outcome X is yes/no. I used propensity matching as I am trying to compare two similar (but quite different) technical methods that can be performed to fix for a certain problem. Propensity matching was used to try and account (as much as possible) for any bias that may be present in choosing one method over another
Comment: @Joe_74 conditional logistic regression is better. Using subjid as a *fixed effect* do you mean *random effect*?
Comment: @sunny_aus the point of propensity matching is reducing the influence of confounders and precision variables. Are you proposing to continue to adjust for those effects even though they have an expected odds ratio of association of 1?
Comment: What do you mean by "multivariable" logistic regression? i) Multivariate (2+ conceptually independent response variables), ii) repeated measures (2+ related, paired response variables), or iii) multiple predictor variables?
Comment: @AdamO Yes, you are right
Comment: You just need to run a mixed model using subject ID as fixed effect and logit link...
Comment: Do you have time-to-outcome data, or just yes/no for outcome? What are you trying to accomplish with the propensity matching? Often you lose information by throwing away cases. What did you match on?
Answer: Although you could use a common ID for each matched pair, as suggested in a comment on the question, I would recommend that you use (inverse) propensity-score weighting rather than propensity-score matching to deal any bias resulting from how the method was chosen in each case.
When you match you are necessarily throwing away all the information included in the discarded cases and decreasing the number of degrees of freedom for your ultimate statistical tests. If your original logistic multiple regression model was well specified,  close to the "true" model, then you wouldn't need to correct at all. The propensity adjustment provides an additional control in case your model wasn't actually well specified.
You can correct for the bias that you fear by including all cases but weighting each case inversely to its propensity score. Also, for generating the propensity score, it can be best to use a rich modeling approach that allows for nonlinearities and for interactions among covariates, like gradient boosting, as provided by the twang package in R. (I don't know what the equivalent is in SPSS.) That can provide superior performance to, say, determining propensity scores via a logistic regression without interactions. The threads listed as "Related" on this page and links from them provide further guidance. I've found answers from @Noah particularly helpful on issues regarding propensity scores.
Answer: Propensity matching is designed to reduce the influence of variables you would normally adjust for. Propensity matching will "balance" variables exactly that were used for matching. Propensity matching will also approximately "balance" variables that were not matched for depending on how well they're predicted by the matching. Basically, there should be very little reason to perform further adjustment...
Regardless, conditional logistic regression is a standard way of analyzing such data. Input the matched pair ID as a cluster variable and calculate the conditional OR of association for the appropriate exposure.
You can further adjust for covariates if there's residual confounding to account for, but the tendency of the conditional logistic regression to behave erratically in finely stratified data is more nefarious than in standard logistic regression.