text:
Q: VUE JS in SHOPIFY: Cart properties are not updating after add to cart product How to update cart properties like cart_count, total_price, and so on in VUE JS after someone adds a product to the cart. What I am doing wrong? I have attached the code for adding products to the cart and updating minicart based on the quantity it is working fine but it is not updating other properties such as total price, total count, subtotal, and so on.
VUE CODE:
if (document.querySelector('.product-form')) {
  let productForm = new Vue({
    el:'.product-form',

    data(){
      return{
        form:{
          id: document.getElementById('getVariantDetails').value,
          quantity: 1
        }

      }
    },
    methods:{
      addToCart(){
        axios.post('/cart/add.js', this.form )
        .then( (response) => {

          // add data to mini cart object
          // check if product already exist
          let found = store.state.cartData[0].items.find(product => product.variant_id == response.data.variant_id);
          if(found){
            found.quantity += parseInt(this.form.quantity);
            // you can reset the quanity back to 1 if you want
            // this.form.quantity = 1;
          }else{
            // add item at the start of array
            store.state.cartData[0].items.unshift(response.data);
          }
          this.openMiniCart();

        })
        .catch( (error) =>  {
          console.log(error);
        });
      },

      openMiniCart(){
          // open mini cart
          $('#minicart-modal').addClass('active');
      }
    }
  });
}
if (document.querySelector('.minicart-app')) {
  let MiniCart = new Vue({
    el:'.minicart-app',
    delimiters: ['${', '}'],

    data(){
      return{
        cartData: store.state.cartData
      }
    },
    computed: {
      cart(){
        return this.cartData[0];
      }
    },
    created(){
      // mini cart is on every page, that's why, we cal it once here
      store.getCart();
    },
    methods:{
      // Remove item from cart
      remove(item){
        let found = this.cart.items.find(product => product.variant_id == item.variant_id);
        if(found){
          this.$delete(this.cart.items, this.cart.items.indexOf(found));
          axios.post('/cart/update.js', 'updates['+item.id+']=0');
        }
      },
      // Increment item by 1
      increment(item){
        let found = this.cart.items.find(product => product.variant_id == item.variant_id);
        if (found) {
          this.updateCart(found, 1);
        }
      },
      // Decrement item by 1
      decrement(item){
        let found = this.cart.items.find(product => product.variant_id == item.variant_id);
        if (found) {

          if (item.quantity > 0) {
            this.updateCart(found, -1 );
          }
        }
      },
      updateCart(item, quantity){
        let q = quantity + item.quantity;

        let data = {
          quantity: q,
          id: item.key
        }

        if (q < 1) {
          this.remove(item);
        }

        axios.post('/cart/change.js', data )
        .then( (response) => {

          // Find the current item and new item to compare the quanity
          let currentItem = this.cartData[0].items.find(product => product.variant_id == item.variant_id);
          let newItem = response.data.items.find(product => product.variant_id == item.variant_id);

          // If item exist
          if (currentItem) {
            // check if item quantity changed. Only change.js can detect this on response
            if(quantity > 0 && currentItem.quantity == newItem.quantity){

            }else{
              // add one to current item
              currentItem.quantity += quantity;
            }
          }
        })
        .catch(function (error) {
          console.log(error);
        });
      }
    },
  });
}

Template file: (header.liquid)
    <template v-if="cart">

        <template v-if="cart.item_count">${ cart.item_count }</template>

      {% include 'links-hover' %}
    </template>

Click to see the image (Quantity is not updating reactivity on runtime)


text:
Q: How can I get the number of hits of a query in a search engine in Java/JavaScript? I need to find the number of hits that query gets in a web search engine (such as Google) in a specific domain. For instance, if the user searches '"dry martini recipe" site:.uk', Google shows "About 15,800 results". I need to get that number (15,800).
The Google API used to be able to do this, but now is deprecated. I have considered web scraping, but since it is not allowed, I would rather not go this way. Using Google is in no way a must, I have considered engines like Duck Duck Go, but the web results do not seem to include the total count of this of a query.

redpajama_set_name: RedPajamaStackExchange


text:
Q: android view momentarily shows at final position before animation I'm animating a view to slide upwards to its final position as we enter the activity. My problem is that the view momentarily appears at final position  at the beginning, then jumps to initial position and then the animation begins. How can I prevent this?
Code
protected void onResume() {
    mImageView.setVisibility(View.INVISIBLE);
    super.onResume();
    Animator animator = new ObjectAnimator();
    animator = AnimatorInflater.loadAnimator(this,R.animator.slide_up_lock_icon);
    //animator.setStartDelay(500);
    animator.setTarget(mImageView);
    animator.setInterpolator(new AccelerateDecelerateInterpolator());
    mImageView.setVisibility(View.VISIBLE);
    animator.start();

Animator XML:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<objectAnimator
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="1000"
    android:propertyName="translationY"
    android:valueFrom="500"
    android:valueTo="0"
    android:valueType="floatType"
    android:startOffset="500"
    />

setting and resetting visibility helps somewhat, but the animation does'nt work as expected always

A: You have to move the mImageView to position from where it will start animating.
One way is to do  mImageView.setTranslationY(500) before animation starts..
Like this :
 mImageView.setVisibility(View.INVISIBLE);
 mImageView.setTranslationY(500);

 Animator animator = new ObjectAnimator();
 animator = AnimatorInflater.loadAnimator(this,R.animator.slide_up_lock_icon);
 //animator.setStartDelay(500);
 animator.setTarget(mImageView);
 animator.setInterpolator(new AccelerateDecelerateInterpolator());
 mImageView.setVisibility(View.VISIBLE);
 animator.start();

Hope it helps..!

A: maybe this could solve your problem.
Activity
protected void onResume() {
    super.onResume();
    //Here tv is your view
    tv.setVisibility(View.GONE);
    //Create an animation
    Animation animation = AnimationUtils.loadAnimation(this, R.anim.slide_up_lock_icon);
    //Set your view's visibility to Visible
    tv.setVisibility(View.VISIBLE);
    //Start animation on tv
    tv.startAnimation(animation);
}

Res anim
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >
  <translate
      android:duration="1000"
      android:fromYDelta="yourValueHere%"
      android:toYDelta="otherValueHere" />
</set>


text:
Q: Hawking radiation question A stationary observer near the black hole horizon will detect Hawking radiation proportional to their local acceleration.
If we call $\alpha=\frac{GM}{r^{2}}\frac{1}{\sqrt{1-\frac{2GM}{r}}}$ the proper acceleration then the temperature measured is: $T=\alpha/(2\pi)$. In order to find the temperature measured at infinity we need to account for a redshift factor $\sqrt{1-\frac{2M}{r}}$ and set $r=2M$.
I have two questions:

*

*Why is the temperature zero if we take a stationary observer at infinity $\alpha(r\rightarrow\infty)=0$? Shouldn't we be able to obtain the result also this way?

*When including the redshift factor we then set $r=2M$. Why is this necessary? In other words, I don't understand why we must propagate the temperature observed near the horizon and not in any arbitrary distance from it?


text:
Q: ReactJS: DOM property not recognized I am creating a ReactJS component with a search field described like this:
SearchNotes.js
<label for='search_notes'>Search</label>
<input id='search_notes' type='text' onKeyPress={this.handleKeyPressed}></input>

Everything is working fine, but I am getting this error here:

This property for clearly exists in label tags. What am I missing here?

A: The error is occurring because for is not an attribute on React elements. Use htmlFor instead, as the error suggests. React doesn't use any JavaScript keywords as attribute names like class (which is className) or for (which is htmlFor).


text:
Q: Editing already open website Selenium I want to mimic mouse clicks on buttons etc. on a website which is already open in a browser(e.g. Chrome). Do you guys know if I can do this with Selenium? Or do you guys know how I can do this in general?

A: No, you have to launch the browser with selenium by initializing the driver.  Selenium is proxying the browser so that your code can control it.
http://selenium-python.readthedocs.io/getting-started.html


text:
Q: How to avoid loosing complex query in a view? In a custom list definition bound to a custom content type, I attached the out of the box AssignedTo field.
In the schema, I defined a view with this query :
    <Query>
      <OrderBy>
        <FieldRef Name="Modified"
                  Ascending="FALSE"></FieldRef>
      </OrderBy>
      <Where>
        <Or>
          <Membership Type="CurrentUserGroups">
            <FieldRef Name="AssignedTo"/>
          </Membership>
          <Eq>
            <FieldRef Name="AssignedTo" />
            <Value Type="Integer">
              <UserID />
            </Value>
          </Eq>
        </Or>
      </Where>
    </Query>

The idea of this view is to display items either if the current user is specified in the AssignedTo field, or if the user is member of the group specified in the field.
This is working as expected. However, as soon as I change something in the view settings with the browser, the query is broken. It seems that the web UI does not know how to interpret my custom query, and override it when I save.
How can I avoid this settings page to break my query? is there a better way to display direct assignation or indirect assignation in the same view ?


text:
Q: Setting colors in theme.json changes default font size and family in backend I have a basic theme.json with an array or colors that creates a working colour palette.
The text in the backend page I am editing is set to 'default' but when I use the theme.json it goes from sans to a serif font.
I have tried adding fontfamiles to theme.json but nothing seems to effect the default backend text rendering.


text:
Q: Show that $\overline{z_1}dz_1+\overline{z_2}dz_2$ is invariant under right translations. I want to show that $(R_{e^{i\theta}})^*(\overline{z_1}dz_1+\overline{z_2}dz_2)=\overline{z_1}dz_1+\overline{z_2}dz_2$.
We are working with the principal $U(1)$ bundle $p:S^{2n+1}\rightarrow \mathbb CP^n$. And using $x^k,y^k$ as coordinates. I am trying to keep things simple and work with $n=1$ for the start.
I have found the following in the book Analysis and algebra on Manifolds. But I do not understand:

*

*how they go from $dx$ and $dy$ to $d(\arctan(y/x))$

*how they go from $R_{e^{i\theta}}^*d(\arctan(y/x))$ to $d(\arctan(y/x)+\theta)$. As far as I understand $R_{e^{i\theta}}^*d(\arctan(y/x))=d(dR_{e^{i\theta}}\arctan(y/x))$. Then $dR_{e^{i\theta}}=R_{e^{i\theta}}$ so we get $d(e^{i\theta}\arctan(y/x))$ not $d(\arctan(y/x)+\theta)$

A: I'll be changing the proof because working with arctangents lets one wonder about vanishing points for the coordinates, branches, and so on.
So instead, notice that the $1$-form $\omega:=\overline{z_1}dz_1+\overline{z_2}dz_2$ is well-defined over $\mathbb{R}^4$, and that $R=R_{e^{i\theta}}$ is as-well defined over $\mathbb{R}^4$.
It is thus enough to find the relation between $R^*\omega$ and $\omega$ in $\mathbb{R}^4$. If we find that they are equal at each point of $S^3$ (on the full four-dimensional tangent space to $\mathbb{R}^4$), we can then pull-back by the inclusion $i: S^3 \rightarrow \mathbb{R}^4$ and we are good.
So: in $\mathbb{R}^4$, $$R^*\omega=R^*\overline{z_1}d(R^*z_1)+R^*\overline{z_2}d(R^*z_2)=\overline{z_1} \circ R d(z_1 \circ R) + \overline{z_2} \circ R d(z_2 \circ R)=\overline{e^{i\theta}z_1}d(e^{i\theta}z_1)+\overline{e^{i\theta}z_2}d(e^{i\theta}z_2)=\omega$$ as $e^{i\theta}$ is a constant.
The derivation actually answers your question 2: for any $p$-form $\omega$ on $N$ and any smooth $f:M \rightarrow N$, $f^*\omega$ is a $p$-form on $M$ and $d(f^*\omega)=f^*(d\omega)$.
If $\omega$ is a $0$-form, corresponding to a smooth function $g: N \rightarrow \mathbb{R}$ then $f^*\omega$ is the $0$-form on $M$ corresponding to $g \circ f$.
For your question $1$, recall that for a smooth function $f$, $df=\sum_k{\frac{\partial f}{\partial u_k}}$ where the $u_k$ is a coordinate system.
In particular, $d(arctan{y/x})=\frac{\partial arctan(y/x)}{\partial x}dx+\frac{\partial arctan(y/x)}{\partial y}dy=\frac{-y}{x^2}\frac{1}{1+(y/x)^2}dx+\frac{1}{x}\frac{1}{1+(y/x)^2}dy=\frac{-ydx}{x^2+y^2}+\frac{xdy}{x^2+y^2}=\frac{ydx-xdy}{x^2+y^2}$.


text:
Q: Gerenciamento de estado com Flutter Boa tarde, Estou com um problema, estou com meu código abaixo, e nele faço o seguinte, quando abre a tela pela primeira vez ele busca dados de uma api e salva no banco. Logo o usuário pode fechar o app e abri-lo novamente, quando ele abre a tela e já tem os dados ele pesquisa direto no banco de dados e preenche o PaginatedDatatable, acalma a segunda opção funciona corretamente, os dados do banco estão bem, o problema esta quando executo a api, dentro da api já tem o processo de salvar no banco, salva certo sem problemas, mas espera lá e não preenche meu PaginatedDatatable, segue o código abaixo de tudo, obrigado pela ajuda.
import 'package:animated_text_kit/animated_text_kit.dart';
import 'package:....../conexao/endpoints_api.dart';
import 'package:....../api/produtos/produto.dart';
import 'package:balanco_app/helpers/database_helper.dart';
import 'package:balanco_app/models/dados_acesso.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class ListaDeProdutos extends StatefulWidget {
  @override
  _ListaDeProdutosState createState() => _ListaDeProdutosState();
}

class _ListaDeProdutosState extends State<ListaDeProdutos> {

  DatabaseHelper db = DatabaseHelper();
  Endpoints endpoints = Endpoints();
  bool sort;
  Color primaryColor;
  int _rowPerPage = PaginatedDataTable.defaultRowsPerPage;
  String sCnpj;
  String sUser;
  String sChave;

  @override
  void initState() {
    super.initState();

    resgataDados();
    sCnpj = context.read<DadosAcesso>().cnpjInicial;
    sUser = context.read<DadosAcesso>().usuario;
    sChave = context.read<DadosAcesso>().codAcesso;
  }

  @override
  Widget build(BuildContext context) {
    primaryColor = Theme.of(context).primaryColor;
    DTS dts = DTS(context.read<DadosAcesso>().listProd);

    setState(() {
      dados();
    });

    return FutureBuilder(
      future: db.getAllProdutos(),
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        if (snapshot.hasData) {
          return Container(
            child: ListView(
              children: [
                PaginatedDataTable(
                  sortColumnIndex: 1,
                  columnSpacing: 3,
                  dataRowHeight: 55,
                  horizontalMargin: 3,
                  headingRowHeight: 30,
                  header: Text('Lista de Produtos'),
                  columns: [
                    DataColumn(
                      label: Text(
                        'Cód.',
                        style: TextStyle(
                            fontStyle: FontStyle.normal,
                            fontWeight: FontWeight.bold,
                            fontSize: 15),
                      ),
                    ),
                    DataColumn(
                      label: Text(
                        'Descrição',
                        style: TextStyle(
                            fontStyle: FontStyle.normal,
                            fontWeight: FontWeight.bold,
                            fontSize: 18),
                      ),
                    ),
                    DataColumn(
                      label: Text(
                        'QTDE',
                        style: TextStyle(
                            fontStyle: FontStyle.normal,
                            fontWeight: FontWeight.bold,
                            fontSize: 16),
                      ),
                    ),
                  ],

                  source: dts,
                  onRowsPerPageChanged: (r) {
                    setState(() {
                      _rowPerPage = r;
                    });
                  },
                  rowsPerPage: _rowPerPage,
                ),
              ],
            ),
          );
        } else {
          return circularProgressGP();
        }
      },
    );
  }

  resgataDados() async {
    List linhas = await db.getDsDados();
    for (var linha in linhas) {
      sCnpj = linha['cnpjInicial'].toString();
      sUser = linha['usuario'].toString();
      sChave = linha['codAcesso'].toString();
    }
  }

  dados() async {

      await db.getAllProdutos().then((value) async{
        value.forEach((element) {
          context.read<DadosAcesso>().listProd.add(Produto(
              codbarras: element['codbarras'],
              desproduto: element["desproduto"]));
        });

        print('Lista length: ${context.read<DadosAcesso>().listProd.length}');

    if(context.read<DadosAcesso>().listProd.length == 0){
      await endpoints.resgata_produtos(sUser, sCnpj, sChave);

      context.read<DadosAcesso>().listProd.clear();

      await db.getAllProdutos().then((value) {
        value.forEach((element) {
          context.read<DadosAcesso>().listProd.add(Produto(
              codbarras: element['codbarras'],
              desproduto: element["desproduto"]));
        });
      }).catchError((error) {
        print(error);
      });
    }
      }).catchError((error) {
        print(error);
      });
    }

}

circularProgressGP() {
  return Container(
    color: Colors.white,
    child: Center(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            SizedBox(
              height: 100,
            ),
            SizedBox(
              height: 90,
              width: 90,
              child: CircularProgressIndicator(backgroundColor: Colors.white),
            ),
            SizedBox(
              height: 40,
            ),
            RotateAnimatedTextKit(
                duration: const Duration(milliseconds: 2000) ,
                onTap: () {},
                text: ["Conectando...", "Buscando Dados...", "Aguarde..."],
                textStyle: TextStyle(fontSize: 30, color: Colors.black),
                textAlign: TextAlign.start
            ),

          ],
        )
    ),
  );
}

class DTS extends DataTableSource{
  DTS(this.listProd);

  DatabaseHelper db = DatabaseHelper();
  Material material = Material();
  final List<Produto> listProd;

  @override
  DataRow getRow(int index) {

    assert(index >= 0);

    if (index >= listProd.length) return null;
    final row = listProd[index];

    print('Index: $index');

    return DataRow.byIndex(
        index: index,
        color: MaterialStateProperty.resolveWith<Color>(
                (Set<MaterialState> states) {
              if (states.contains(MaterialState.selected))
                return material.color.withOpacity(0.08);
              if (index % 2 == 0) return Colors.grey.withOpacity(0.3);
              return null;
            }),
        cells: [
          DataCell(
            Container(
              constraints: BoxConstraints(maxWidth: 150),
              child: Text(row.codbarras),
            ),
          ),
          DataCell(
            Container(
              constraints: BoxConstraints(maxWidth: 150),
              child: Text(
                row.desproduto,
                style: TextStyle(fontSize: 15),
              ),
            ),
          ),
          DataCell(
            Center(
              child: Container(
                constraints: BoxConstraints(maxWidth: 110),
                child: TextField(
                  keyboardType: TextInputType.number,
                  //controller: qtde_controller,
                  onChanged: (text) {
                    print("Texto digitado:  $text");
                  },
                  onTap: (){

                  },
                ),
              ),
            ),
          ),
        ]);
  }

  @override
  bool get isRowCountApproximate => true;

  @override
  int get rowCount => 10;

  @override
  int get selectedRowCount => 0;
}

O que estou fazendo de errado, pois sempre que a api roda e puxa os dados e salva no banco, mas não apresenta para mim em tela, a api esta certa, acredito que deve ser algo do PaginatedDataTable, agradeço a ajuda.

A: Você se perdeu em meio aos métodos assíncronos await e then()...
Existem duas formas de se fazer o que quer, mas irei focar na questão do FutureBuilder.
Primeiramente vamos modificar seu método Dados() da seguinte forma:
List<Produtos> dados() async {

    List<Produtos> produtos = [];

    produtos = await db.getAllProdutos();

    if(produtos.isEmpty()){
      await endpoints.resgata_produtos(sUser, sCnpj, sChave);

      context.read<DadosAcesso>().listProd.clear();

      produtos = await dados();
    } else {
        produtos.forEach((element) {
          context.read<DadosAcesso>().listProd.add(Produto(
              codbarras: element['codbarras'],
              desproduto: element["desproduto"]));
        });
    }

    return produtos;
}

Dessa forma, utilizando apenas o await, seu método irá aguardar cada chamada para depois retornar para o seu FutureBuilder todos os dados disponíveis.
Agora é necessário ajustar seu FutureBuilder, vamos fazer da seguinte forma:
FutureBuilder(
      future: dados(),
      builder: (BuildContext context, AsyncSnapshot<List<Map<String, dynamic>>> snapshot) {
        if (snapshot.hasData) {
          DTS dts = DTS(snapshot.data);

          return Container(
            child: ListView(
              children: [
                PaginatedDataTable(
                  sortColumnIndex: 1,
                  columnSpacing: 3,
                  dataRowHeight: 55,
                  horizontalMargin: 3,
                  headingRowHeight: 30,
                  header: Text('Lista de Produtos'),
                  columns: [
                    DataColumn(
                      label: Text(
                        'Cód.',
                        style: TextStyle(
                            fontStyle: FontStyle.normal,
                            fontWeight: FontWeight.bold,
                            fontSize: 15),
                      ),
                    ),
                    DataColumn(
                      label: Text(
                        'Descrição',
                        style: TextStyle(
                            fontStyle: FontStyle.normal,
                            fontWeight: FontWeight.bold,
                            fontSize: 18),
                      ),
                    ),
                    DataColumn(
                      label: Text(
                        'QTDE',
                        style: TextStyle(
                            fontStyle: FontStyle.normal,
                            fontWeight: FontWeight.bold,
                            fontSize: 16),
                      ),
                    ),
                  ],

                  source: dts,
                  onRowsPerPageChanged: (r) {
                    setState(() {
                      _rowPerPage = r;
                    });
                  },
                  rowsPerPage: _rowPerPage,
                ),
              ],
            ),
          );
        } else {
          return circularProgressGP();
        }
      },
    );

Explicação
O FutureBuilder irá chamar o método Dados(), que por sua vez irá buscar no banco de dados toda a informação necessária, caso não encontre vai tentar requisitar para a API.
Feito isso, irá retornar os dados disponíveis para o FutureBuilder que irá disponibilizar os valores dentro de snapshot.data que no seu caso é uma lista de Maps.
Dessa forma, tentro do FutureBuilder após tratado todas as requisições, você pode fazer a chamada da sua classe DTS, caso exista informações disponíveis.

Obs.: Como não nos informou o tipo da lista de produtos, joguei algo
genérico List<Produtos>, ai tu faz as modificações necessárias...


text:
Q: How to add parse dependency in android empty project? Hey I want to add parse as backend (https://aws.amazon.com/marketplace/pp/prodview-gu6judefvlbxg) in my android project dependencies, I had EC2 instance, parse server url , masterKey , ... (things which will require to connect with parse server as said in udemy course tutorial, which I am following.)
I checked many online tutorials and blogs but most of them are outdated, can anyone help to add parse dependencies to my project?


text:
Q: What are the Issues with a vector-of-vectors? I've read that a vector-of-vectors is bad given a fixed 2nd dimension, but I cannot find a clear explanation of the problems on http://www.stackoverflow.com.
Could someone give an explanation of why using 2D indexing on a single vector is preferable to using a vector-of-vectors for a fixed 2nd dimension?
Also, I'm assuming that a vector-of-vectors is the preferable data structure for a 2D array with a variable 2nd dimension? If there is any proof to the contrary I'd love to see that.

A: I shall answer with a simple analogy.
What is "better" in general out of the two things?

*

*A telephone book where each entry is a code referring to a different book that you have to find and read to discover someone's telephone number

*A telephone book that lists people's telephone numbers

Keeping all your data in a single big blob is more simple, more sensible, and easier on your computer's cache. A vector with N vectors inside it is much more operationally complex (remember, each of those requires a dynamic allocation and size management operations!); one vector is, well, one vector. You haven't multiplied the workload by N.
The only downside really is that to simulate 2D array access with a 1D underlying data store, you need to write a facade. Fortunately, this is very easy.
Now for the subjective part: on balance I'd say that it's worthwhile unless you're really in a rush and your code quality doesn't particularly matter.

A: Using a vector of vectors:

*

*Is inefficient in terms of memory allocation, due to multiple blocks being allocated.

*Models a jagged right hand edge, so bugs can creep in.

Using a single vector is, in general, better as the memory management is simpler. But you can encounter problems if your matrix is large as it can be difficult to acquire a large contiguous block.
If your array is resizeable, then I'd still stick to a single vector: the resize complexity can be isolated in a single function that you can optimise.
The best solution of all is, of course, to use something like the linear algebra library (BLAS), available in Boost. That also handles large sparse matrices beautifully.

A: For a std::vector the underlying array is dynamically allocated from the heap. If you have e.g. std::vector<std::vector<double>>, then your outer vector would look like
{v1, v2, v3, v4, ... vn}

This looks like each of the inner vectors will be in contiguous memory, and they will, but their underlying arrays will not be contiguous. See the diagram of the memory layout in this post. In other words the you cannot say that
&(v1.back()) + 1 == &(v2.front()) // not necessarily true!

Instead if you used a single vector with striding then you would gain data locality, and it would inherently be more cache friendly as all your data is contiguous.
For the sake of completeness, I would use neither of these methods if your matrix was sparse, as there are more elegant and efficient storage schemes than straight 1D or 2D arrays. Though since you mentioned you have a "fixed 2nd dimension" I will assume that is not the case here.


text:
Q: QWebView not resizing correctly I have a QMainWindow with a horizontal layout as central widget. The horizontal layout contains three widgets.
Here is the code:
this.navigationTree=new NavigationTree();
Browser browser = new Browser();
this.clusteringPlot=new ClusteringPlot();
QWidget centralWidget=new QWidget();
QHBoxLayout layout=new QHBoxLayout();
layout.addWidget(navigationTree);
layout.addWidget(clusteringPlot);
layout.addWidget(browser);
centralWidget.setLayout(layout);
this.setCentralWidget(centralWidget);`

where Browser is a QWebView.
Whenever I resize the main window Browser does not get resized while clusteringPlot(extends QWidget) and navigationTree(extends QTreeWidget) do.
How can I change my code so that also Browser get resized? I took a look at similar questions but I could not find a solution to my problem.
Thanks a lot in advance
Rossella

A: A layout queries the minimum size of its children when deciding how to assign space. Your first task therefore is to ensure that all of the widgets occupying your QHBoxLayout know what their minimum useful size is:

*

*Since NavigationTree inherits QTreeWidget, I'm assuming that it is already supplying a sensible minimum size (via the minimumSizeHint() inherited from QAbstractScrollArea)). If this needs altering, reimplement QWidget::minimumSizeHint() as below.

*If ClusteringPlot inherits directly from QWidget, it's probably not providing the layout with a sensible minimum size, so you need to provide one. You can either reimplement QWidget::minimumSizeHint() as a virtual function in ClusteringPlot (especially useful if you're able to calculate the size based on the state of the object) or call  clusteringPlot->setMinimumSize(...);.

*Since you are dictating the minimum size for your QWebView, call browser->setMinimumSize(1024, 768);.

Once enough space in has been assigned to satisfy each of its child widget's minimumSizeHint()s, a QBoxLayout starts assigning remaining space according to the stretchFactor of each widget. The easiest way to set stretch factors is when adding the widgets to the layout. Try changing your code to:
layout.addWidget(navigationTree, 1);
layout.addWidget(clusteringPlot, 1);
layout.addWidget(browser, 2);

This tells the layout that any spare space should be assigned in the ratio 1:1:2, i.e. if 40 extra pixels become available, 10 go to navigationTree, 10 to clusteringPlot and 20 to browser.


text:
Q: How to use Standard HTML to send values from view to controller I have this View Model:
public class MemberRegisterVM
{
    public Users User { get; set; }
    public Location Location { get; set; }
}

Which Consists from User and Location Models
User:
public partial class Users : Persons
{
    public Guid? UserRoleId { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
    public DateTime? RegisterDate { get; set; }
    public DateTime ExpireDate { get; set; }
    public bool IsLock { get; set; }
    public string DigitalSignture { get; set; }
    public Guid? BranchID { get; set; }
    public int PersonType { get; set; }
    public Guid Token { get; set; }
}

public partial class Users
{
    public string NewPassword { get; set; }
    public string ConfirmPassword { get; set; }
    public string ConfirmDigitalSignture { get; set; }

}

Location :
   public  class Location
    {
        public int ID { get; set; }
        public int ParentId { get; set; }
        public int TypeId { get; set; }
        public int Code { get; set; }
        public string Name { get; set; }
    }

For Single Model [for example: User Model] i know if I use a Standard html input like below it'll send my data to controller as the referenced Model based on Its Name attribute:
View:
@model User

<input name="UserName" Id="UserName" type="text" />

Controller:
public ActionResult Submit(User user)
{
      //user.UserName is filled here
}

Now my question is how to name my Standard HTML elements to send the data to controller as my view model (which consists several models)? using html.helper i will reference it as below for example:
@Html.TextBoxFor(x => x.User.UserName)

Will it be like below?
<input type="Text" name="User.UserName" id="User.UserName">

Or something else? because I've tried above but it still sends value as null on form submit.
Update:
I've excluded other fields on the form, they are based on html.helpers and pass the value correctly, however there are 2 fields that are not working right one would be Gender and second would be BirthDate, since User Model inherits from Person model i'll add it here as well:
Person Model:
public class Persons
{
    public bool Gender { get; set; }
    public Datetime BirthDate { get; set; }
}

Here is my View
@model Models.MemberRegisterVM

@{
    Layout = "~/Views/Shared/_SiteLayout.cshtml";
}
@using Entities.Texts;
@using (@Html.BeginForm("Register", "MembershipAuth", FormMethod.Post))
{

                        @Labels.Gender

                        <input name="User.Gender" type="radio" id="men_gender" value="0" />
                        @Labels.Male

                        <input name="User.Gender" type="radio" id="female_gender" value="1" />
                        @Labels.Female

                        @Labels.BirthDay

                        <input type="text" name="User.BirthDate" id="User_BirthDate" />

                <input type="submit" class="btn btn-primary" value="Sign Up" />

}

And This is my ActionResult on controller:
[HttpPost]
[AllowAnonymous]
public ActionResult Register(Models.MemberRegisterVM vm, FormCollection form)

{
   //vm.User.Gender is not filled here as well as vm.User.BirthDate
}

A: Your name attributes are correct, however your Gender property will not bind correctly (the value will always be false) because your generating radio buttons with values of 0 and 1. In order to bind to a bool, they need values of True and False, e.g.
<input name="User.Gender" type="radio" id="men_gender" value="True" />

although your property name/type does not really make sense for Gender (either making the type an enum with "Male" and "Female", or changing the name to bool IsMale would be more appropriate)
You have not given enough details about what value is being posted for the BirthDate property, but if its not binding, then this is most likely due to the format of the date not matching the culture of the server (for example if a value of 7/24/2017 was posted but the server has a culture that accepts dates in dd/MM/yyyy format).
Its not clear why you want to generate the html manually. Your losing 2-way model binding (for example if your editing existing data or need to return the view because ModelState is invalid, the control will not display the correct value), and your not getting any client side validation. At the very least you should be inspecting the value of ModelState in the POST method to see what validation errors have been added.
As a side note, there is no reason to include the FormCollection form parameter in your method since your binding to a model.

A: Look First of All I recommend you to:-

*

*Use @Html helpers whenever possible like this
@Html.TextBoxFor(x => x.User.UserName)

*View Models should be simple or complex objects but not derive from any class as it is just a data transfer object, this will help you make most benefit from MVC default model binder and model state provider, make your code more cleaner and help you write less code by avoiding coding against form collection or Request.Form have a look Here

*For date time you may use a string model property and do manual convert or override the default model binder behavior in the global.asax  for example
ModelBinders.Binders[typeof(DateTime)] =
   new DateAndTimeModelBinder() { CustomFormat = "yyyy-mm-dd" };

or whatever format according to the javascript picker
After these points we can say that:-
In MVC
@Html.TextBoxFor(x => x.User.UserName)

is equal to
<input type="Text" name="User.UserName" id="User_UserName">

or
<input type="Text" name="User.UserName" id="User.UserName">

the id doesn't matter the name matter, the point here is that the model binder will bind it by default only if this attribute is one of the simple or complex VM object attributes and not a derived one
I hope this is of any help.


text:
Q: Django fails to login user Authenticating a user using valid credentials passes on the login view. When request.user.is_authenticated is printed, it even outputs True. But after redirecting to LOGIN_REDIRECT_URL, the request is returned back to LOGIN_URL meaning the just authenticated user is no longer authenticated.
The project in concern is a mixed project i.e It uses core django builtin view, route and templating as well as djangorestframework.
djangorestframework TokenAuthentication has worked fine so far, but when i try logging in with core django view i get this weird situation.
I'm using a custom auth user model and two backend authentication ( which are all working fine on api authentication and authorization ). Every other aspect of the project works fine, the only issue is this authentication. I've tried several resource to fix this, but all lead to dead ends. I even used functional based view and django builtin LoginView (as an inherited class and on path route ), same occurence i got irrespective.
Tools

*

*Django 3.1.1

*Python 3.8.4

*Postgres

*Postgis

*django restframework 3.11.1
settings.py
INSTALLED_APPS = [
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.staticfiles',
    'django.contrib.gis',

     # installed apps and third party apps
]

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

AUTH_USER_MODEL = 'accounts.Account'
PASSWORDLESS_AUTH_BACKEND = 'accounts.auth_backends.PasswordLessAuthenticationBackend'
EMAIL_AUTHENTICATION_BACKEND = 'accounts.auth_backends.EmailAuthenticationBackend'

AUTHENTICATION_BACKENDS = (
    EMAIL_AUTHENTICATION_BACKEND, PASSWORDLESS_AUTH_BACKEND
)

LOGIN_URL = '/admin/'
LOGIN_REDIRECT_URL = '/admin/index'

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    )
}

SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timezone.timedelta(days=1),
    'REFRESH_TOKEN_LIFETIME': timezone.timedelta(days=2),
    'ROTATE_REFRESH_TOKENS': False,
    'BLACKLIST_AFTER_ROTATION': True,

    'SIGNING_KEY': os.getenv('PROJECT_SECRET_KEY'),
    'ALGORITHM': 'HS256',
    'VERIFYING_KEY': None,
    'AUDIENCE': None,
    'ISSUER': None,

    'AUTH_HEADER_TYPES': ('Bearer',),
    'USER_ID_FIELD': 'id',
    'USER_ID_CLAIM': 'user_id',

    'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),

    ...
}

views.py
class WebAdminLoginView(View):
    """Handles web admin login"""

    def post(self, request, *args, **kwargs):
        """logs in authenticated user account."""
        email, password = request.POST['email'], request.POST['password']
        account = authenticate(email=email, password=password)
        login(request, account, backend=settings.EMAIL_AUTHENTICATION_BACKEND)

        # The below code outputs True
        print(request.user.is_authenticated)            # printsTrue
        return HttpResponseRedirect(settings.LOGIN_REDIRECT_URL)

    def get(self, request, *args, **kwargs):
        return render(request, "admin_login.html")

class IndexListing(LoginRequiredMixin, ListView):
    """Returns a list of all verified partners"""
    model = User
    context_object_name = 'users'
    template_name = 'jadminapp/index/list_users.html'

urls.py
index_patterns= [
    path(...),
    ....
]

urlpatterns = [
    path(
        '',
        core_view.WebAdminLoginView.as_view(),
        name='web-admin-login'
    ),

    path(
        'index',
        include(
            (index_patterns, 'index'),
            namespace='index'
        )
    ),
]


text:
Q: MySQL change delimiter in PhpStorm data editor console window How to get PhpStorm data editor to recognize DELIMITER \\?
Scenario: I have a console open, and I want to create a function where I have ; defined in the function.
On execution, function create fails on the first line where ; exists.
The query is like so
DELIMITER //
create function blah (datablah varchar(200)) returns tinyint(1)
  BEGIN
   Return tinyintVar;
  END //
DELIMITER ;

This function works as intended too as it is in production and I want to copy it over into a dev DB. This is why I know the error is due to the delimiter.
But this is not the first time I've tried to do this in an open console with another function. When executing this SQL inline in the data editor console, it just doesn't detect or acknowledge the DELIMITER keyword. Even if I just run with Ctrl + Enter on the line with DELIMITER \\ I get the message "nothing to run".
Note: this will work if I have a .sql file and I just execute the file. But current workflow is to highlight the function from live DB, open editor to view the create function code and then Copy + Paste into the open console window I currently have open.
So, is the only way to get the DELIMIER recognized is to execute a .sql file?
PhpStorm 2018.2.2
The error is
[2018-09-05 12:07:33] [42000][1064] You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(19), endPeriod DATETIME(19)) returns tinyint(1)
[2018-09-05 12:07:33] BEGIN
[2018-09-05 12:07:33] DECLARE live BOOLEA' at line 1

screenshot

From the screenshot, you'll notice the execute group hasn't put the green box around the delimiter keywords. This is why I think it's not recognizing the keyword.

A: As there is a Feature request to have it implemented I will say it's not supported.
DBE-2968: Ability to configure SQL Statement delimiter/terminator


text:
Q: LEFT OUTER JOIN on CachedRowSet I would like to perform left join on two CachedRowSet. Seems like JoinRowSetImpl only supports INNER JOIN. What can I use to get left join working?
Thanks and regards.

A: Seem like rebuilding JoinRowSetImpl class in this way does the trick. initJOIN methot rebuild as follows (works for my purpose):
    /**
     * Internal initialization of JoinRowSet.
     */
    private void initJOIN(CachedRowSet rowset) throws SQLException {
        try {

            CachedRowSetImpl cRowset = (CachedRowSetImpl) rowset;
            // Create a new CachedRowSet object local to this function.
            CachedRowSetImpl crsTemp = new CachedRowSetImpl();
            RowSetMetaDataImpl rsmd = new RowSetMetaDataImpl();

            /*
             * The following 'if block' seems to be always going true. commenting this out
             * for present
             *
             * if (!supportedJOINs[1]) { throw new
             * SQLException(resBundle.handleGetObject("joinrowsetimpl.notsupported").
             * toString()); }
             *
             */

            if (vecRowSetsInJOIN.isEmpty()) {

                // implies first cRowset to be added to the Join
                // simply add this as a CachedRowSet.
                // Also add it to the class variable of type vector
                // do not need to check "type" of Join but it should be set.
                crsInternal = (CachedRowSetImpl) rowset.createCopy();
                crsInternal.setMetaData((RowSetMetaDataImpl) cRowset.getMetaData());
                // metadata will also set the MatchColumn.

                vecRowSetsInJOIN.add(cRowset);

            } else {
                // At this point we are ready to add another rowset to 'this' object
                // Check the size of vecJoinType and vecRowSetsInJoin

                // If nothing is being set, internally call setJoinType()
                // to set to JoinRowSet.INNER_JOIN.

                // For two rowsets one (valid) entry should be there in vecJoinType
                // For three rowsets two (valid) entries should be there in vecJoinType

                // Maintain vecRowSetsInJoin = vecJoinType + 1

                if ((vecRowSetsInJOIN.size() - vecJoinType.size()) == 2) {
                    // we are going to add next rowset and setJoinType has not been set
                    // recently, so set it to setJoinType() to JoinRowSet.INNER_JOIN.
                    // the default join type

                    setJoinType(JoinRowSet.INNER_JOIN);
                } else if ((vecRowSetsInJOIN.size() - vecJoinType.size()) == 1) {
                    // do nothing setjoinType() has been set by programmer
                }

                // Add the table names to the class variable of type vector.
                vecTableNames.add(crsInternal.getTableName());
                vecTableNames.add(cRowset.getTableName());
                // Now we have two rowsets crsInternal and cRowset which need
                // to be INNER JOIN'ED to form a new rowset
                // Compare table1.MatchColumn1.value1 == { table2.MatchColumn2.value1
                // ... upto table2.MatchColumn2.valueN }
                // ...
                // Compare table1.MatchColumn1.valueM == { table2.MatchColumn2.value1
                // ... upto table2.MatchColumn2.valueN }
                //
                // Assuming first rowset has M rows and second N rows.

                int rowCount2 = cRowset.size();
                int rowCount1 = crsInternal.size();

                // total columns in the new CachedRowSet will be sum of both -1
                // (common column)
                int matchColumnCount = 0;
                for (int i = 0; i < crsInternal.getMatchColumnIndexes().length; i++) {
                    if (crsInternal.getMatchColumnIndexes()[i] != -1)
                        ++matchColumnCount;
                    else
                        break;
                }

                rsmd.setColumnCount(crsInternal.getMetaData().getColumnCount() + cRowset.getMetaData().getColumnCount()
                        - matchColumnCount);
                crsTemp.setMetaData(rsmd);
                crsInternal.beforeFirst();
                cRowset.beforeFirst();
                for (int i = 1; i <= rowCount1; i++) {
                    if (crsInternal.isAfterLast()) {
                        break;
                    }
                    if (crsInternal.next()) {
                        cRowset.beforeFirst();
//
                            int p;
                            int colc = 0;
//  ****first with null***
                            crsTemp.moveToInsertRow();
                            boolean match = true;
                            // create a new rowset crsTemp with data from first rowset
                            for (p = 1; p <= crsInternal.getMetaData().getColumnCount(); p++) {

                                match = false;
                                for (int k = 0; k < matchColumnCount; k++) {
                                    if (p == crsInternal.getMatchColumnIndexes()[k]) {
                                        match = true;
                                        break;
                                    }
                                }
                                if (!match) {

                                    crsTemp.updateObject(++colc, crsInternal.getObject(p));
                                    // column type also needs to be passed.

                                    rsmd.setColumnName(colc, crsInternal.getMetaData().getColumnName(p));
                                    rsmd.setTableName(colc, crsInternal.getTableName());

                                    rsmd.setColumnType(p, crsInternal.getMetaData().getColumnType(p));
                                    rsmd.setAutoIncrement(p, crsInternal.getMetaData().isAutoIncrement(p));
                                    rsmd.setCaseSensitive(p, crsInternal.getMetaData().isCaseSensitive(p));
                                    rsmd.setCatalogName(p, crsInternal.getMetaData().getCatalogName(p));
                                    rsmd.setColumnDisplaySize(p,
                                            crsInternal.getMetaData().getColumnDisplaySize(p));
                                    rsmd.setColumnLabel(p, crsInternal.getMetaData().getColumnLabel(p));
                                    rsmd.setColumnType(p, crsInternal.getMetaData().getColumnType(p));
                                    rsmd.setColumnTypeName(p, crsInternal.getMetaData().getColumnTypeName(p));
                                    rsmd.setCurrency(p, crsInternal.getMetaData().isCurrency(p));
                                    rsmd.setNullable(p, crsInternal.getMetaData().isNullable(p));
                                    rsmd.setPrecision(p, crsInternal.getMetaData().getPrecision(p));
                                    rsmd.setScale(p, crsInternal.getMetaData().getScale(p));
                                    rsmd.setSchemaName(p, crsInternal.getMetaData().getSchemaName(p));
                                    rsmd.setSearchable(p, crsInternal.getMetaData().isSearchable(p));
                                    rsmd.setSigned(p, crsInternal.getMetaData().isSigned(p));

                                } else {
                                    // will happen only once, for that merged column pass
                                    // the types as OBJECT, if types not equal

                                    crsTemp.updateObject(++colc, crsInternal.getObject(p));

                                    rsmd.setColumnName(colc, crsInternal.getMetaData().getColumnName(p));
                                    rsmd.setTableName(colc,
                                            crsInternal.getTableName() + "#" + cRowset.getTableName());

                                    rsmd.setColumnType(p, crsInternal.getMetaData().getColumnType(p));
                                    rsmd.setAutoIncrement(p, crsInternal.getMetaData().isAutoIncrement(p));
                                    rsmd.setCaseSensitive(p, crsInternal.getMetaData().isCaseSensitive(p));
                                    rsmd.setCatalogName(p, crsInternal.getMetaData().getCatalogName(p));
                                    rsmd.setColumnDisplaySize(p,
                                            crsInternal.getMetaData().getColumnDisplaySize(p));
                                    rsmd.setColumnLabel(p, crsInternal.getMetaData().getColumnLabel(p));
                                    rsmd.setColumnType(p, crsInternal.getMetaData().getColumnType(p));
                                    rsmd.setColumnTypeName(p, crsInternal.getMetaData().getColumnTypeName(p));
                                    rsmd.setCurrency(p, crsInternal.getMetaData().isCurrency(p));
                                    rsmd.setNullable(p, crsInternal.getMetaData().isNullable(p));
                                    rsmd.setPrecision(p, crsInternal.getMetaData().getPrecision(p));
                                    rsmd.setScale(p, crsInternal.getMetaData().getScale(p));
                                    rsmd.setSchemaName(p, crsInternal.getMetaData().getSchemaName(p));
                                    rsmd.setSearchable(p, crsInternal.getMetaData().isSearchable(p));
                                    rsmd.setSigned(p, crsInternal.getMetaData().isSigned(p));

                                    // don't do ++colc in the above statement
                                } // end if
                            } // end for
//*********second**************

                            for (int q = 1; q <= cRowset.getMetaData().getColumnCount(); q++) {

                                match = false;
                                for (int k = 0; k < matchColumnCount; k++) {
                                    if (q == cRowset.getMatchColumnIndexes()[k]) {
                                        match = true;
                                        break;
                                    }
                                }
                                if (!match) {
                                    crsTemp.updateNull(++colc);
                                    rsmd.setColumnName(colc, cRowset.getMetaData().getColumnName(q));
                                    rsmd.setTableName(colc, cRowset.getTableName());

                                    /**
                                     * This will happen for a special case scenario. The value of 'p' will
                                     * always be one more than the number of columns in the first rowset in the
                                     * join. So, for a value of 'q' which is the number of columns in the second
                                     * rowset that participates in the join. So decrement value of 'p' by 1 else
                                     * `p+q-1` will be out of range.
                                     **/

                                    // if((p+q-1) > ((crsInternal.getMetaData().getColumnCount()) +
                                    // (cRowset.getMetaData().getColumnCount()) - 1)) {
                                    // --p;
                                    // }
                                    rsmd.setColumnType(p + q - 1, cRowset.getMetaData().getColumnType(q));
                                    rsmd.setAutoIncrement(p + q - 1, cRowset.getMetaData().isAutoIncrement(q));
                                    rsmd.setCaseSensitive(p + q - 1, cRowset.getMetaData().isCaseSensitive(q));
                                    rsmd.setCatalogName(p + q - 1, cRowset.getMetaData().getCatalogName(q));
                                    rsmd.setColumnDisplaySize(p + q - 1,
                                            cRowset.getMetaData().getColumnDisplaySize(q));
                                    rsmd.setColumnLabel(p + q - 1, cRowset.getMetaData().getColumnLabel(q));
                                    rsmd.setColumnType(p + q - 1, cRowset.getMetaData().getColumnType(q));
                                    rsmd.setColumnTypeName(p + q - 1,
                                            cRowset.getMetaData().getColumnTypeName(q));
                                    rsmd.setCurrency(p + q - 1, cRowset.getMetaData().isCurrency(q));
                                    rsmd.setNullable(p + q - 1, cRowset.getMetaData().isNullable(q));
                                    rsmd.setPrecision(p + q - 1, cRowset.getMetaData().getPrecision(q));
                                    rsmd.setScale(p + q - 1, cRowset.getMetaData().getScale(q));
                                    rsmd.setSchemaName(p + q - 1, cRowset.getMetaData().getSchemaName(q));
                                    rsmd.setSearchable(p + q - 1, cRowset.getMetaData().isSearchable(q));
                                    rsmd.setSigned(p + q - 1, cRowset.getMetaData().isSigned(q));
                                } else {
                                    --p;
                                }
                            }
//**********second updates if foud match**************

                            colc = 13;

                            for (int j = 1; j <= rowCount2; j++) {
                                if (cRowset.isAfterLast()) {
                                    break;
                                }

                                if(cRowset.next()) {
//                                  System.out.println(cRowset.getInt(1));
                                    match = true;

                                    for (int k = 0; k < matchColumnCount; k++) {
                                        if (!crsInternal.getObject(crsInternal.getMatchColumnIndexes()[k])
                                                .equals(cRowset.getObject(cRowset.getMatchColumnIndexes()[k]))) {
                                            match = false;
                                            break;
                                        }
                                    }
                                    if (match) {

                                        // append the rowset crsTemp, with data from second rowset
                                        for (int q = 1; q <= cRowset.getMetaData().getColumnCount(); q++) {

                                            match = false;
                                            for (int k = 0; k < matchColumnCount; k++) {
                                                if (q == cRowset.getMatchColumnIndexes()[k]) {
                                                    match = true;
                                                    break;
                                                }
                                            }
                                            if (!match) {

                                                crsTemp.updateObject(++colc, cRowset.getObject(q));

                                                rsmd.setColumnName(colc, cRowset.getMetaData().getColumnName(q));
                                                rsmd.setTableName(colc, cRowset.getTableName());

                                                /**
                                                 * This will happen for a special case scenario. The value of 'p' will
                                                 * always be one more than the number of columns in the first rowset in the
                                                 * join. So, for a value of 'q' which is the number of columns in the second
                                                 * rowset that participates in the join. So decrement value of 'p' by 1 else
                                                 * `p+q-1` will be out of range.
                                                 **/

                                                // if((p+q-1) > ((crsInternal.getMetaData().getColumnCount()) +
                                                // (cRowset.getMetaData().getColumnCount()) - 1)) {
                                                // --p;
                                                // }
                                                rsmd.setColumnType(p + q - 1, cRowset.getMetaData().getColumnType(q));
                                                rsmd.setAutoIncrement(p + q - 1, cRowset.getMetaData().isAutoIncrement(q));
                                                rsmd.setCaseSensitive(p + q - 1, cRowset.getMetaData().isCaseSensitive(q));
                                                rsmd.setCatalogName(p + q - 1, cRowset.getMetaData().getCatalogName(q));
                                                rsmd.setColumnDisplaySize(p + q - 1,
                                                        cRowset.getMetaData().getColumnDisplaySize(q));
                                                rsmd.setColumnLabel(p + q - 1, cRowset.getMetaData().getColumnLabel(q));
                                                rsmd.setColumnType(p + q - 1, cRowset.getMetaData().getColumnType(q));
                                                rsmd.setColumnTypeName(p + q - 1,
                                                        cRowset.getMetaData().getColumnTypeName(q));
                                                rsmd.setCurrency(p + q - 1, cRowset.getMetaData().isCurrency(q));
                                                rsmd.setNullable(p + q - 1, cRowset.getMetaData().isNullable(q));
                                                rsmd.setPrecision(p + q - 1, cRowset.getMetaData().getPrecision(q));
                                                rsmd.setScale(p + q - 1, cRowset.getMetaData().getScale(q));
                                                rsmd.setSchemaName(p + q - 1, cRowset.getMetaData().getSchemaName(q));
                                                rsmd.setSearchable(p + q - 1, cRowset.getMetaData().isSearchable(q));
                                                rsmd.setSigned(p + q - 1, cRowset.getMetaData().isSigned(q));
                                            } else {
                                                --p;
                                            }
                                        }
                                            cRowset.deleteRow();
                                            break;
                                    } else {

                                    }

                                }
                            }

                            crsTemp.insertRow();
                            crsTemp.moveToCurrentRow();

                    }

                } // end outer for
                crsTemp.setMetaData(rsmd);
                crsTemp.setOriginal();

                // Now the join is done.
                // Make crsInternal = crsTemp, to be ready for next merge, if at all.

                int[] pCol = new int[matchColumnCount];
                for (int i = 0; i < matchColumnCount; i++)
                    pCol[i] = crsInternal.getMatchColumnIndexes()[i];

                crsInternal = (CachedRowSetImpl) crsTemp.createCopy();

                // Because we add the first rowset as crsInternal to the
                // merged rowset, so pCol will point to the Match column.
                // until reset, am not sure we should set this or not(?)
                // if this is not set next inner join won't happen
                // if we explicitly do not set a set MatchColumn of
                // the new crsInternal.

                crsInternal.setMatchColumn(pCol);
                // Add the merged rowset to the class variable of type vector.
                crsInternal.setMetaData(rsmd);
                vecRowSetsInJOIN.add(cRowset);
            } // end if
        } catch (SQLException sqle) {
            // %%% Exception should not dump here:
            sqle.printStackTrace();
            throw new SQLException(resBundle.handleGetObject("joinrowsetimpl.initerror").toString() + sqle);
        } catch (Exception e) {
            e.printStackTrace();
            throw new SQLException(resBundle.handleGetObject("joinrowsetimpl.genericerr").toString() + e);
        }
    }


text:
Q: No such file or directory when 'cp' but not with 'ls' I am trying to copy the shared preferences folder of my app to the /sdcard partition from my PC using the following ADB command:

adb shell su -c "cp
  /data/data/com.anrapps.pixelbatterysaver/shared_prefs/
  /sdcard/appdata/"

But this returns cp: Skipped dir '/data/data/com.anrapps.pixelbatterysaver/shared_prefs': No such file or directory. However when executing the ls command, it says that folder is present:

adb shell su -c "ls /data/data/com.anrapps.pixelbatterysaver"
cache
  code_cache
  files
  shared_prefs

What is the problem? May be permission related?

A: If you're trying to copy a whole directory, you need to use cp -r to make it a recursive copy.


text:
Q: Notify ObservableCollection when property changes I have the following classes.
Class Contract
{
   public double Bid { get; set; }
   ...
}

Class Leg
{
   public Contract con {get; set; }
   ...
}

class Combo
{
   public Leg L1 { get; set;}
   public Leg L2 { get; set;}
   ....
}

ObservableCollection<Combo> listOfCombos = new ObservableCollection<Combo>();
Combo cmbo = new Combo();
listOfCombos.Add(cmbo);

//datagrid bound to ObservableCollection
<DataGrid x:Name="dgCombos" ItemsSource="{Binding listOfCombos,Mode=OneWay}"

How do I notify the listOfCombos when a Bid property of a Contract changes. I also want the change to propagate to the datagrid.
I know how to notify ObservableCollection when a property of T (the only class) changes.
Im confused on how to notify, when theres more than one Class. ie. Combo > Leg > Contract. - Thanks


text:
Q: preventing duplicate records when importing a delimited data file into salesforce I need to load hundreds of contacts into a salesforce database from a delimited file that only contains first name, last name, street address1, street address2, city, state, and zip.  My understanding is that you can only use name or email address to see if a conact already exists in a salesforce database.
I want to be able to match on name, street address1, and city so that I can limit the duplicate records in my database.
Is this possible in salesforce?

A: There are some options... I'll make it a community wiki post so anybody can chip in.
Checks before / during loading
There's a way to create a text field and mark it as unique or external id, then write a workflow rule that would populate it with {!Contact.Name} + ' ' + {!Contact.MailingStreet} + ' ' + {!Contact.MailingCity} when contact is inserted or any of these reference fields change. But then you'd have to somehow fill this in for all Contacts you already have (which is not totally impossible: export a report with all contacts, fill the field in, import it back with dupe checking set to contact's Id).
If it's one time action though, perhaps you'd be better not creating this field. Export data from SF report then make some matching in Excel etc and load back?
You could write a trigger for data deduplication but that's a bit nasty solution (by default whole load fails, it's more for flagging as error than somehow merging data). I don't think you want to go that way (can you use apex code or is your SF edition limited?)
Checks after loading
You could decide to load them all in and deal with duplicates later. Then run a report that groups contacts by these 3 fields and when a group contains more than 1 - you have a candidate to merge contacts (that's a button on Contact record).
You could also resort to AppExchange tools, there are tons of them!
Other random gibberish ;)
If they're people with whom you might do business but you're not sure yet, you might want to load them as Leads. Think of a Lead record like a business card you got on some trade expo. There might be an opportunity here or it might not work at all. So load them up, then you can click "Convert" button on the lead - this might create up to 3 records (Account, Contact, Opportunity) or merge into existing data which is also an option for you I think.


text:
Q: Data Annotations for Display Name are not rendering in Razor form I'm trying to assign a display name in my model class using data annotations, but the view is not displaying the name.  It's defaulting to the property name and ignoring the data annotation.
In my model:
public interface IFeedbackLogMetadata
{
        [Display(Name="Description")]
        string FeedbackDescription { get; set; }
}
public partial class FeedbackLog : PersistantEntity, IFeedbackLogMetadata
{
//..other stuff
}

I have also tried:
[DisplayName("Description")]
string FeedbackDescription { get; set; }

In my view, I have tried:
@Html.LabelFor(model => model.FeedbackDescription, htmlAttributes: new {@class = "control-label col-md-2"})
<label class="control-label col-md-2">@Html.DisplayNameFor(d => d.FeedbackDescription)</label>

The label displays "FeedbackDescription".  It should be "Description".  Why is the display name data annotation being ignored?

A: /Headsmack/
I needed to decorate the partial class with the MetadataType for the interface.  Without this, the view is pulling from the EF generated class, which doesn't have the data annotations.
[MetadataType(typeof(IFeedbackLogMetadata))]
public partial class FeedbackLog : PersistantEntity, IFeedbackLogMetadata
{
//...other stuff
}


text:
Q: Working with Aliased Columns in SQL Server 2012 Okay, so I know from this question why I cannot reference an aliased column from WHERE, GROUP BY, or HAVING statements.
My problem is that I have this query which is being moved from a Teradata database to SQL Server 2012.
In Teradata, referencing an aliased column in the where, group by, having, and even join statements is perfectly valid.
My question is, how can I perform this query, and others like it, in SQL Server, without having to resort to populating a temporary table to select from first. (This example is just a single part of a large tSQL script containing 10 separate transactions, many of which or more complex than the example provided)
SELECT
    MAX(CASE WHEN
            Field_Name = 'Parent Brand Cd' AND
            DATALENGTH(Field_Val)>1
        THEN SUBSTRING(Field_Val, 1, DATALENGTH(Field_Val) - 1)
        ELSE NULL
        END
        ) AS Parent_Brand_Cd,
    MAX(CASE WHEN
            Field_Name = 'Brand Id' AND
            DATALENGTH(Field_Val)>1
        THEN SUBSTRING(Field_Val, 1, DATALENGTH(Field_Val) - 1)
        ELSE NULL
        END
        ) AS Hotel_Cd,
    @src_sys_id AS Src_Sys_Id,
    MAX(CASE WHEN
            Field_Name = 'Brand' AND
            DATALENGTH(Field_Val)>1
        THEN SUBSTRING(Field_Val, 1, DATALENGTH(Field_Val) - 1)
        ELSE NULL
        END
        ) AS Temp1,
    CASE Temp1
        WHEN 'Company1'
            THEN 'c1'
        WHEN 'Company2'
            THEN 'c2'
        WHEN 'Company3'
            THEN 'c3'
        ELSE TEmp1
    END AS Brand_Cd,
    @process_id AS Insert_Process_Id
 FROM dbo.Company -- STAGING
 GROUP BY Parent_Brand_Cd
 HAVING
    Parent_Brand_Cd IS NOT NULL AND
    Hotel_Cd IS NOT NULL

The first issue with this query is that it is creating an aliased column Temp1 and then immediately attempting to perform a CASE statement against it. I can correct this by doing this:
MAX(CASE WHEN
            Field_Name = 'Brand' AND
            DATALENGTH(Field_Val)>1
        THEN SUBSTRING(Field_Val, 1, DATALENGTH(Field_Val) - 1)
        ELSE NULL
        END
        ) AS Temp1,
    MAX(CASE WHEN
            Field_Name = 'Brand' AND
            DATALENGTH(Field_Val)>1
        THEN
            CASE
                WHEN SUBSTRING(Field_Val, 1, DATALENGTH(Field_Val) - 1) = 'Company1' THEN 'c1'
                WHEN SUBSTRING(Field_Val, 1, DATALENGTH(Field_Val) - 1) = 'Company2' THEN 'c2'
                WHEN SUBSTRING(Field_Val, 1, DATALENGTH(Field_Val) - 1) = 'Company' THEN 'c3'
                ELSE SUBSTRING(Field_Val, 1, DATALENGTH(Field_Val) - 1)
            END
        ELSE NULL
        END
        ) AS Brand_Cd,

But this will not help on other parts of the script where the aliased columns are calculation that are then used in other calculations. Also, it does not solve the issue of the aliased columns in the Group By or Having statements.
Is there any way around the limitations of Aliased Columns in SQL Server, without having to create and populate temporary tables all over the place?
EDIT: Working Solution as Proposed by GarethD
SELECT
            Parent_Brand_Cd,
            Hotel_Cd,
            @src_sys_id AS Src_Sys_Id,
            CASE Temp1
                WHEN 'Company1' THEN 'C1'
                WHEN 'Company2' THEN 'C2'
                WHEN 'Company3' THEN 'C3'
                ELSE TEmp1
            END AS Brand_Cd,
            @process_id AS Insert_Process_Id,
            @process_id AS Update_Process_Id
        FROM
            (
                SELECT
                    MAX(CASE WHEN Field_Name = 'Parent Brand Cd' THEN FieldValue END) AS Parent_Brand_Cd,
                    MAX(CASE WHEN Field_Name = 'Brand Id' THEN FieldValue END) AS Hotel_Cd,
                    MAX(CASE WHEN Field_Name = 'Brand' THEN FieldValue END) AS Temp1
                FROM
                    (
                        SELECT
                            Field_Name,
                            FieldValue = CASE WHEN DATALENGTH(Field_Val) > 1 THEN SUBSTRING(Field_Val, 1, DATALENGTH(Field_Val) - 1) END
                        FROM    DEV_STG_TB.dbo.Company_Attributes_3 -- STAGING
                    ) AS c

            ) AS sub
        WHERE
            Parent_Brand_Cd IS NOT NULL AND
            Hotel_Cd IS NOT NULL
        GROUP BY
            Parent_Brand_Cd,
            Hotel_Cd,
            Temp1

A: You can move your query into a subquery, and the reference your aliases. SQL Server is smart enough to be able to optimise this in the same way as the having clause (in the tests I have done at least). Consider the following two queries:
SELECT  Name, [Count]
FROM    (   SELECT  name, [Count] = COUNT(*)
            FROM    sys.Columns
            GROUP BY name
        ) AS sub
WHERE   [Count] > 1;

SELECT  name, [Count] = COUNT(*)
FROM    sys.Columns
GROUP BY name
HAVING COUNT(*) > 1;

The execution plan for both queries is exactly the same:

So your query would end up as something like:
SELECT  Parent_Brand_Cd,
        Hotel_Cd,
        @src_sys_id AS Src_Sys_Id,
        Temp1
        CASE Temp1
            WHEN 'Company1' THEN 'c1'
            WHEN 'Company2' THEN 'c2'
            WHEN 'Company3' THEN 'c3'
            ELSE TEmp1
        END AS Brand_Cd,
        @process_id AS Insert_Process_Id
FROM    (   SELECT  MAX(CASE WHEN Field_Name = 'Parent Brand Cd' AND DATALENGTH(Field_Val) > 1 THEN SUBSTRING(Field_Val, 1, DATALENGTH(Field_Val) - 1) END) AS Parent_Brand_Cd,
                    MAX(CASE WHEN Field_Name = 'Brand Id' AND DATALENGTH(Field_Val) > 1 THEN SUBSTRING(Field_Val, 1, DATALENGTH(Field_Val) - 1) END) AS Hotel_Cd,
                    MAX(CASE WHEN Field_Name = 'Brand' AND DATALENGTH(Field_Val) > 1 THEN SUBSTRING(Field_Val, 1, DATALENGTH(Field_Val) - 1) END) AS Temp1
            FROM    dbo.Company -- STAGING
            GROUP BY Parent_Brand_Cd
        ) AS sub
WHERE   Parent_Brand_Cd IS NOT NULL
AND     Hotel_Cd IS NOT NULL;

You could even reduce the repeated expressions further by using another subquery:
SELECT  Parent_Brand_Cd,
        Hotel_Cd,
        @src_sys_id AS Src_Sys_Id,
        Temp1
        CASE Temp1
            WHEN 'Company1' THEN 'c1'
            WHEN 'Company2' THEN 'c2'
            WHEN 'Company3' THEN 'c3'
            ELSE TEmp1
        END AS Brand_Cd,
        @process_id AS Insert_Process_Id
FROM    (   SELECT  MAX(CASE WHEN Field_Name = 'Parent Brand Cd' THEN FieldValue END) AS Parent_Brand_Cd,
                    MAX(CASE WHEN Field_Name = 'Brand Id' THEN FieldValue END) AS Hotel_Cd,
                    MAX(CASE WHEN Field_Name = 'Brand' THEN FieldValue END) AS Temp1
            FROM    (   SELECT  Parent_Brand_Cd,
                                Field_Name,
                                FieldValue = CASE WHEN DATALENGTH(Field_Val) > 1 THEN SUBSTRING(Field_Val, 1, DATALENGTH(Field_Val) - 1) END
                        FROM    dbo.Company -- STAGING
                    ) AS c
            GROUP BY Parent_Brand_Cd
        ) AS sub
WHERE   Parent_Brand_Cd IS NOT NULL
AND     Hotel_Cd IS NOT NULL;

Note, I have removed ELSE NULL from the case expressions as this is redundant.
I am a big fan of using Common Table Expressions instead of subqueries to de-clutter my queries (this is entirely subjective), and also using PIVOT, so I would personally rewrite the above as:
WITH CompanyCTE AS
(   SELECT  Parent_Brand_Cd,
            Field_Name,
            FieldValue = CASE WHEN DATALENGTH(Field_Val) > 1
                            THEN SUBSTRING(Field_Val, 1, DATALENGTH(Field_Val) - 1)
                        END
    FROM    dbo.Company
)
SELECT  pvt.Parent_Brand_Cd
        Parent_Brand_Cd = pvt.[Parent Brand Cd],
        Hotel_Cd = pvt.[Brand Id],
        Temp1 = pvt.[Brand]
FROM    CompanyCTE AS c
        PIVOT
        (   MAX(FieldValue)
            FOR Field_Name IN ([Parent Brand Cd], [Brand Id], [Brand])
        ) AS pvt
WHERE   pvt.[Parent Brand Cd] IS NOT NULL
AND     pvt.[Brand Id] IS NOT NULL;

The other advantage is PIVOT gives you direct access to the aggregated columns.
Of course, your other option is to just repeat the aggregate function:
HAVING MAX(CASE WHEN
                Field_Name = 'Parent Brand Cd' AND
                DATALENGTH(Field_Val)>1
            THEN SUBSTRING(Field_Val, 1, DATALENGTH(Field_Val) - 1)
            ELSE NULL
            END
            ) IS NOT NULL
AND    MAX(CASE WHEN
                Field_Name = 'Parent Brand Cd' AND
                DATALENGTH(Field_Val)>1
            THEN SUBSTRING(Field_Val, 1, DATALENGTH(Field_Val) - 1)
            ELSE NULL
            END
            ) IS NOT NULL;

ADDENDUM
Having seen the working solution it appears you don't need any grouping at all, so I think the following will work for you:
SELECT  Parent_Brand_Cd,
        Hotel_Cd,
        @src_sys_id AS Src_Sys_Id,
        Temp1
        CASE Temp1
            WHEN 'Company1' THEN 'c1'
            WHEN 'Company2' THEN 'c2'
            WHEN 'Company3' THEN 'c3'
            ELSE TEmp1
        END AS Brand_Cd,
        @process_id AS Insert_Process_Id
FROM    (   SELECT  MAX(CASE WHEN Field_Name = 'Parent Brand Cd' THEN FieldValue END) AS Parent_Brand_Cd,
                    MAX(CASE WHEN Field_Name = 'Brand Id' THEN FieldValue END) AS Hotel_Cd,
                    MAX(CASE WHEN Field_Name = 'Brand' THEN FieldValue END) AS Temp1
            FROM    (   SELECT  Field_Name,
                                FieldValue = CASE WHEN DATALENGTH(Field_Val) > 1 THEN SUBSTRING(Field_Val, 1, DATALENGTH(Field_Val) - 1) END
                        FROM    dbo.Company -- STAGING
                    ) AS c
        ) AS sub
WHERE   Parent_Brand_Cd IS NOT NULL
AND     Hotel_Cd IS NOT NULL;

The reason being since parent_brand_cd is by definition unique, since it is derived from an aggregate with no grouping, any further grouping, although inconsequential, is redundant.
Or the PIVOT solution.
WITH CompanyCTE AS
(   SELECT  Field_Name,
            FieldValue = CASE WHEN DATALENGTH(Field_Val) > 1
                            THEN SUBSTRING(Field_Val, 1, DATALENGTH(Field_Val) - 1)
                        END
    FROM    dbo.Company
)
SELECT  Parent_Brand_Cd = pvt.[Parent Brand Cd],
        Hotel_Cd = pvt.[Brand Id],
        Src_Sys_Id = @src_sys_id,
        Temp1 = pvt.[Brand],
        Brand_Cd = CASE pvt.[Brand]
                        WHEN 'Company1' THEN 'c1'
                        WHEN 'Company2' THEN 'c2'
                        WHEN 'Company3' THEN 'c3'
                        ELSE TEmp1
                    END,
        Insert_Process_Id = @process_id
FROM    CompanyCTE AS c
        PIVOT
        (   MAX(FieldValue)
            FOR Field_Name IN ([Parent Brand Cd], [Brand Id], [Brand])
        ) AS pvt
WHERE   pvt.[Parent Brand Cd] IS NOT NULL
AND     pvt.[Brand Id] IS NOT NULL;


text:
Q: Data and Index size doubles after update to primary key in table with millions of rows Here's the situation:
Using SQL Server 2005, I've went through and updated the primary key (a char(16)) in several tables replacing a good chunk of the first six characters with others. (I'm doing this as part of a data scrubbing project at my job).
Most of these tables contain millions of rows and may have 1 or 2 non-clustered indexes as well.
After doing these updates the data pages used by the data and indexes seem to have doubled thus causing the MDF to double in size as well. I've went through checking several things against another copy of the original database like column data types, collation, used/reserved/unused space and have even created/updated the statistics for everything then ran a shrink on the data. Nothing has helped or hinted at a reason for the increase in size. By the way, the row counts are the same between the two databases so it's not duplicated rows or anything like that.
I have not executed a 'dbcc checkdb' or rebuilt the indexes - these are my last ditch ideas. Has anyone seen something similar to this?
TLDR - Database MDF doubles after updating primary keys of several tables with millions of rows. Have checked column data types, row counts, data/index size. Updated stats and tried shrinking. Nothing works. Halp!

A: You need to rebuild the indexes with your normal fill factor to determine if your page use has been disrupted.


text:
Q: How to create an 2D ArrayList in java? I want to create a 2D array that each cell is an ArrayList!
I consider this defintions, but I can not add anything to them
are these defintions true?!
ArrayList<ArrayList<String>> table = new ArrayList<ArrayList<String>>();

or
ArrayList[][] table = new ArrayList[10][10];

//table.add??????

Please help me

A: I want to create a 2D array that each cell is an ArrayList!
If you want to create a 2D array of ArrayList.Then you can do this :
ArrayList[][] table = new ArrayList[10][10];
table[0][0] = new ArrayList(); // add another ArrayList object to [0,0]
table[0][0].add(); // add object to that ArrayList

A: The best way is to use a List within a List:
List<List<String>> listOfLists = new ArrayList<List<String>>();

A: 1st of all, when you declare a variable in java, you should declare it using Interfaces even if you specify the implementation when instantiating it
ArrayList<ArrayList<String>> listOfLists = new ArrayList<ArrayList<String>>();

should be written
List<List<String>> listOfLists = new ArrayList<List<String>>(size);

Then you will have to instantiate all columns of your 2d array
    for(int i = 0; i < size; i++)  {
        listOfLists.add(new ArrayList<String>());
    }

And you will use it like this :
listOfLists.get(0).add("foobar");

But if you really want to "create a 2D array that each cell is an ArrayList!"
Then you must go the dijkstra way.

A: ArrayList<String>[][] list = new ArrayList[10][10];
list[0][0] = new ArrayList<>();
list[0][0].add("test");

A: This can be achieve by creating object of List data structure, as follows
List list = new ArrayList();
For more information refer this link
How to create a Multidimensional ArrayList in Java?


text:
Q: Can I perform sanity checking in the initializer list of a constructor? Using the initializer lists is encouraged in general. Now let's say I have the following code (trivial example just to make the question clearer):
class foo
{
  public:
    foo(ptr1* a, ptr2* b) : m_a(a), m_b(b), m_val(a->val) {}

  /* code and members here */
};

I would like to check that a is not NULL before it tries to dereference it to get val. Is there any way I can perform a sanity check there?

A: Use the ternary operator:
#include <cstdio>

class Test
{
    int x;

public:

    Test(int *px)
    : x (px ? *px : -1)
    {
        printf("%d\n", x);
    }
};

int main(int argc, char *argv[])
{
    Test(NULL);
    return 0;
}

The above sample outputs -1.

A: You can try:
foo(ptr1* a, ptr2* b) : m_a(a), m_b(b), m_val(a==nullptr ? 0 : a->val) {}

Alternatively, if a==nullptr is an error in programming logic, you can use an assert() to catch it while unit-testing your debug builds.


text:
Q: Can I use a value passed through ajax to make a database search using a prepared statement? Guys I been struggling with this issue quite a bit, I'm a novice in using ajax calls and jdbc related functions. Moving on to the point, I'm passing a datepicker value to the servlet side by using an ajax function, the function works right, I'm printing the value in a random div just to see if its working and it does work. Now how can I take that value and use it in a prepared statement to search on my database data depending on the date picked by the user, can this be done at all?
heres some code to add more context
$.ajax({
            type:'POST',
            data:{dateinput:dateinput},
            url:'/Rest/sales?action=param2',
            dataType: 'json',
            success:function(result){

                $('#altdate').html(result);
            },
            error: function (error) {
                console.log(error);
            }

        });

    });

I have a prepared statement with a static value just to see if it was working (it does) but here is where I can't make progress, how do I declare that value?
ConnectionPool pool = ConnectionPool.getInstance(DatosGeneral.DATABASE);
    Connection connection = pool.getConnection();
    PreparedStatement ps = null;
    ResultSet rs = null;

    String[] ids = null;
    double[] prices = null;

    try{
        String query = "SELECT * FROM [" + GeneralData.DATABASE + "].[dbo].[SalesDetails] "
                + "WHERE [Branch] = '" + GeneralData.bra + "' "
                + "AND [UpDate] = ?" ; //previous value 20190521
        System.out.println(query);
        ps = connection.prepareStatement(query,
                ResultSet.TYPE_SCROLL_INSENSITIVE,
                ResultSet.CONCUR_READ_ONLY);
        rs = ps.executeQuery();
        int rowcount = 0;

        if (rs.last()) {
            rowcount = rs.getRow();
            rs.beforeFirst();
        }

        ids = new String[rowcount];
        prices = new double[rowcount];

        for (int i = 0; rs.next(); i++) {
            if (rs.getString("Type").replaceAll("\\s+", "").equals("PROD")) {
                ids[i] = rs.getString("ProductCode").replaceAll("\\s+", "");
                prices[i] = rs.getDouble("Price");
            }
        }

Lastly my dopost function where I'm requesting the parameters
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String action= request.getParameter("action");
    if(action.equals("param1")){
        int i = Integer.parseInt(request.getParameter("branch"));
        GeneralData.bra = GeneralData.branches[i];
        GeneralData.braName = GeneralData.braNames[i];
        System.out.println(GeneralData.bra);

    }else if (action.equals("param2")){
        String altdate = request.getParameter("dateinput");
        PrintWriter out = response.getWriter();
        out.print(altdate);
    }

any help would be appreciate it

A: Well I solved it, the only thing I did was to declare a variable  where I could store the value passed through the ajax call(the value of the datepicker) and assign it with the doPost method. Something like this:
private String datePickerValue=null;

doPost method:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

      datePickerValue=altdate;
 }

and lastly in the query of the prepared statement  just specified that variable as the parameter used to get the data from the db:
try{
    String query = "SELECT * FROM [" + GeneralData.DATABASE + "].[dbo].[SalesDetails] "
            + "WHERE [Branch] = '" + GeneralData.bra + "' "
            + "AND [UpDate] = '" + datePickerValue +"'" ; //previous value 20190521


text:
Q: Service reference config I have standard class library infrastructure assembly which i reference in my main application.
The infrastructure assembly uses a webservice internally and exposes functionality to my main application.
To get it to work i need to add a reference in my main app to the webservice otherwise i get a Endpointexeption. If i add it everything works fine. It seems to me that the infrastructure dll reads information in the main applications app.config so the entry has to be there. But it seems strange that i cant expose the web service throug an external dll as the main application does not call the webservie directly. Whats even stranger is that the webservice ignores the main applications security mode and reads it from the external dll's app.config.
If im correct in my assumptions, how do i expose a webservice in an external dll withot the main app knowing about the webservice.

A: in your class library project when you add the service reference you have to make sure the generated proxy is Internal.
for more info:
C#, WCF, Hide web service through dll
This will hide the WCF interface to the client.
if you don't want that the client that uses your class library project needs to add the WCF configuration key in its app/web.config your library has to configure the EndPoint/address/binding in the code (hard coded)  but I won't recommend you to go down this road as if something changes on the WCF side your class library won't work anymore

A: You don't need to add the service reference to your main app, but you must copy the relevant configurations to the main app.config


text:
Q: Why Unbound Local error is showing up, where I expect NameError should be raised? When I delete the variable and access it inside function the unboundLocalError shows up where as if do the same thing outside the function NameError is raised.I am not able to understand why there is inconsistency in behaviour to access the deleted Variable?
def func():
    x=10
    del x
    print(x)
func() #this will cause UnboundLocal Error

#But if i copy the same code and execute it without using the function call then NameError shows up

x=10
del x
print(x) #this will raise NameError as x does not exist

According to me in both cases NameError should be raised as we are trying to access the variable after deleting the variable.

A:
Raised when a reference is made to a local variable in a function or method, but no value has been bound to that variable. This is a subclass of NameError.

https://docs.python.org/3/library/exceptions.html?highlight=unboundlocalerror
The difference seems to be one of purely location. UnboundLocalError extends the NameError and UnboundLocalError is chosen as the error when it occurs inside a method/function.
This might not settle a separate question: "Why did python dev's decide to do this this way" But it does explain why you're seeing it.


text:
Q: how to handle "Only the original thread that created a view hierarchy can touch its views."
Possible Duplicate:
Android : CalledFromWrongThreadException;: Only the original thread that created a view hierarchy can touch its views

Now I am working on an application.I want to show a progressbar until i get a true reply from called method.I used the following code.
 progressBar = new ProgressDialog(this);
      progressBar.setCancelable(true);
      progressBar.setMessage("Loading");
      progressBar.show();

new Thread(new Runnable() {

    @Override
    public void run() {
        // TODO Auto-generated method stub

        final boolean flag=  GetFixtureDetailsJsonFunction();

        if (flag==true) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            progressBar.dismiss();
        }

    }
}).start();

protected boolean GetFixtureDetailsJsonFunction()
{
  //some code
  return true;
}

But I am getting the exception
03-14 15:48:23.722: E/AndroidRuntime(910): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

Please help me friends

A: change the way you are dismissing progressBar as below:
new Thread(new Runnable() {
@Override
public void run() {
    // TODO Auto-generated method stub

    final boolean flag=  GetFixtureDetailsJsonFunction();

    if (flag==true) {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //dismissing prograssBar on UI thread
        Your_Activity_Class.this.runOnUiThread(new Runnable() {
           @Override
           public void run() {
              progressBar.dismiss();
           }
        });
    }

}
}).start();

actually you are dismissing prograssBar on a separate thread (non UI thread) which is wrong and thats why you are getting this exception. However, by using the code above, it dismisses the prograssBar on your UI thread.

A: your problem is that one of your thread is trying to access the data that belongs to another thread, you cannot do that because that can lead to serious data corruption.
follow the following article for solution to the problem.
http://www.tutorialforandroid.com/2009/01/using-handler-in-android.html


text:
Q: Compare dataframe values to aggregated dataframe I have a dataframe called allData which contains thousands of rows of trial info/data pertaining to thousands of files of x,y,z trajectory data.
Each row contains:

*

*obsScenario: 0, 1 or 2

*startPos: 1 or 2

*targetPos: 1, 2, or 3

*cumDist: float64 value of cumulative distance traveled for that trajectory

For each obsScenario, there are the 2 start positions and the 3 target positions, so each obstacle scenario has 6 trials (1 X 2 X 3).
allData looks like this:
    obsScenario  startPos  targetPos    cumDist
0            0         1          1  33.797209
1            2         1          1  34.941458
2            2         1          2  34.153108
3            2         2          1  37.489698
4            0         1          1  35.099954
5            0         1          3  37.368709
6            2         1          1  33.421624
7            0         1          2  32.491703
8            1         2          1  37.268338
9            2         2          2  34.414690
...

I created a second dataFrame, allData_avg to get the average cumulative distance, grouped by variables 1-3 (obsScenario, startPos, targetPos) using:
allData_avg = allData.groupby(['obsScenario', 'startPos', 'targetPos']).agg([np.average])

allData_avg looks like this:
                                  cumDist
                                  average
obsScenario startPos targetPos
0           1        1          34.236374
                     2          33.360685
                     3          40.131592
            2        1          39.493517
                     2          34.034068
                     3          34.835779
1           1        1          34.290811
                     2          34.100946
                     3          39.116431
            2        1          38.641681

I am now trying to use these averages to filter out trajectories from allData that have a cumulative distance 1.25x greater/larger than the average pertaining to that trial's specific combination of obsScenario, startPos, and targetPos values (this is to filter out participant trajectories that are weird/bad).
So for example, for index 5 of allData, the cumDist 37.37 needs to be < 1.25 * 40.13. If not, then that entire row of data should be deleted from the original dataframe allData.
I've been trying to do this for a while and am stumped. Any help is much appreciated.

A: import pandas as pd
import numpy as np

df=pd.read_excel(r"D:\Stack_overflow\test10.xlsx")

df['avg_cum']=df.groupby(['obsScenario', 'startPos', 'targetPos'])['cumDist'].transform('mean') #ADDING AVERAGE OF CUMDIST COLUMN BASED ON THE COMBINATION

df.loc[df['cumDist'] < df['avg_cum']*1.25] #FILTER BASED ON THE VALUE

This is how We can filter out the values based on cumulative columns which is being added newly.
I am not sure About the value 40.13 how have you achieved, probably it is the average of all data whereas i have performed actions on first 9-10 rows which has been listed in the question.
Hope that solves the problem.

A: This is not going to be the most optimised solution but it will give you an idea of how to go about it.
rows_to_be_deleted = []

for i, row in allData.iterrows():

    obsScenario = row['obsScenario']
    startPos = row['startPos']
    targetPos = row['targetPos']

    cumDistAvg = allData_avg.loc[obsScenario].loc[startPos].loc[targetPos]['cumDist'].loc['average']

    if row['cumDist'] >= (1.25 * cumDistAvg):
        rows_to_be_deleted.append(i)

allData_filtered = allData.drop(rows_to_be_deleted)


text:
Q: Can JavaScript post messages to Flash? I'm wondering if JavaScript can post JSON messages to Flash? and if so can you please provide an example or a link to one?

A: Use ExternalInterface class to add callback methods that Javascript can call.
for example:
import flash.external.ExternalInterface;
ExternalInterface.addCallback("callbackName", doMyCallback);

function doMyCallback(someParam:Strimg):void {
    // use the AS3CoreLib JSON decoder like mentioned by @ludesign to decode the JSON string.
}

Then in your javascript, you can call the callbackName method on the flash object.
AS3CoreLib
ExternalInterface

A: I am pretty sure that you can use FlashVars for this. Been a long time since I have done it so I wouldnt be able to provide code but a quick google found a couple of links:
http://kb2.adobe.com/cps/164/tn_16417.html
http://www.permadi.com/tutorial/flashVars/index.html
Hope it helps.


text:
Q: Searching for duplicates in rows with attached datasets from another table I need to delete duplicate records from the table. Syntax: T-SQL (MS SQL Server)
There are two difficulties with it:

*

*There are fields containing data that should not affect row comparison

*There is an additional table linked with the first with "one-to-many" relationships

Example:
Table A                 Table B
--------------          --------------
AId - int       <-\     BId - int
A1 - int           \->  AId - int
A2 - varchar            B6 - varchar
A3 - varchar            B7 - varchar
A4 - varchar            B8 - varchar
A5 - int                B9 - int

So, any record in Table A contains the fields AId, A1, A2, A3, A4 and A5, and the list of "sub-records": a list of records in Table B where B.AId matches A.AId. For instance, it can be list of purchasing transactions, where Table A contains properties of transaction, such as date/time or client ID, and Table B can represent a list of goods with their prices and amounts.
Once some of the records were duplicated. They have different AId, different BId, different A4, A5, B8 and B9. All other fields should match to make two records a duplicate.
Thus, two records X and Y from A are considered duplicate if:

*

*X.A1 == Y.A1

*X.A2 == Y.A2

*All the records from Table B with AId == X.AId completely match all the records from B with AID == Y.AId, but excluding (ignoring) B8 and B9 fields

I need to at least get AIDs of such duplicate records, at most to delete those duplicates but left only one copy of the record (doesn't matter which one).
Please tell me if the following clarification is needed. Thank you in advance.
upd: SQL Fiddle: http://sqlfiddle.com/#!3/898c8/1

A: Select a1, Count(CompareField) From (Select a.a1 as a1, a.a1 + a.a2 +  a.a3 + b.b6 + b.b7 as compareField from A inner join b on a.AID = b.AID) z Group by z.comparefield

This will get you a list of all the duplicates then you could use an outer query to delete the records Delete From a Where AID in (prevquery)
It probably doesn't need to be stated but, MAKE SURE YOU BACK UP THE DATA BASE BEFORE RUNNING YOUR DELETE QUERY. :)

A: The trick is to concat multiple rows from table B to a single string.
For SQL server you can abuse the XML features (can be problematic if there are special characters in the values - others have built-in functions like LIST() in Sybase, which returns a comma-separated list):
SELECT AID, A1, A2, A3, (
  SELECT B6, B7
  FROM B
  WHERE AID=A.AID
  ORDER BY B6, B7
  FOR XML RAW
) XML
FROM A

http://sqlfiddle.com/#!3/898c8/29/0
Now you have a flat table and it's easy to find and delete duplicates (which is left as an exercise for the reader)...