text:
Q: How to avoid overlapping label's on the Bar in google bar charts? I'm creating a stacked bar graph and need to show the label inside the stack. But Few of the label's are getting overlapped. for reference image
Can you please help me how to avoid overlapping using google charts ?

Regards,
Srikanth

A: first, it appears you have an extra annotation column in your data,
that doesn't appear to belong to a specific column
copied from question above...
var data = new google.visualization.arrayToDataTable([
  [
    'Time Period',
    'XYZ',
    {role: 'annotation'},
    'ABC',
    {role: 'annotation'},
    {role: 'annotation'},  // <-- extra annotation?
    'Average'
  ],
  [
    'Aug',
    3754,
    '3754',
    2089,
    '2089',
    '5,843',  // <-- extra annotation?
    4000
  ],
  ...
]);

this could be part of the reason it's so cluttered
regardless, use the annotations configuration option for adjustments
the config option can be used for the entire chart, or just for a specific series
var options = {
  // entire chart
  annotations: {
    textStyle: {
      fontSize: 10
    }
  },
  series: {
    0: {
      // series 0
      annotations: {
        stem: {
          length: 0
        },
      },
    },
    1: {
      // series 1
      annotations: {
        stem: {
          length: 16
        }
      },
    },
  }
  ...
};

specifically, you can use a combination of annotations.textStyle.fontSize and annotations.stem.length to prevent overlapping
see following working snippet...
annotations.textStyle.fontSize is reduced for the entire chart
this allows the first annotation on the second column to fit within the bar
annotations.stem.length is set to zero (0) on the first series,
and 16 on the second...
(the extra annotation from the question has been removed)

google.charts.load('current', {
  callback: drawStacked,
  packages: ['corechart']
});

function drawStacked() {
  var data = new google.visualization.arrayToDataTable([
    ['Time Period', 'XYZ', {role: 'annotation'}, 'ABC', {role: 'annotation'}, 'Average'],
    ['Aug', 3754, '3754', 2089, '2089', 4000],
    ['Sept', 900, '900', 200, '200', 4000],
    ['Oct', 2000, '2000', 4900, '4900', 4000],
    ['Nov', 1700, '1700', 2200, '2200', 4000],
    ['Dec', 2400, '2400', 2089, '2200', 4000]
  ]);

  var options = {
    annotations: {
      textStyle: {
        fontSize: 10
      }
    },
    series: {
      0: {
        annotations: {
          stem: {
            length: 0
          },
        },
      },
      1: {
        annotations: {
          stem: {
            length: 16
          }
        },
      },
      2: {
        type: 'line'
      }
    },
    hAxis: {
      title: 'Time Period'
    },
    isStacked: true,
    seriesType: 'bars',
    title: 'Overview of the Tickets',
    vAxis: {
      title: 'Number of Tickets'
    }
  };

  var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
  chart.draw(data, options);
}

EDIT
since the third annotation is needed as the total of the other two stacks,
recommend adding the series value for the total, in addition to the annotation column
and setting the total series type to 'line'
this will place the total annotation above the rest, for sure
so long as there is enough room on the chart to display the annotation above the bars
to ensure enough room above bars, find the max vAxis value, and add a value that will create enough room for the annotation
then set that value as vAxis.viewWindow.max
you can turn off the line and point, and hide the total series from the legend if needed
in my experience, it takes quite a bit of manipulation to get a complex google chart to display nicely
see the following working snippet, which incorporates the third, 'total', annotation...

google.charts.load('current', {
  callback: drawStacked,
  packages: ['corechart']
});

function drawStacked() {
  var data = new google.visualization.arrayToDataTable([
    ['Time Period', 'XYZ', {role: 'annotation'}, 'ABC', {role: 'annotation'}, 'TOTAL', {role: 'annotation'}, 'Average'],
    ['Aug', 3754, '3,754', 2089, '2,089', 5843, '5,843', 4000],
    ['Sept', 900, '900', 200, '200', 1100, '1,100',  4000],
    ['Oct', 2000, '2,000', 4900, '4,900', 6900, '6,900',  4000],
    ['Nov', 1700, '1,700', 2200, '2,200', 3900, '3,900',  4000],
    ['Dec', 2400, '2,400', 2089, '2,089', 4489, '4,489',  4000]
  ]);

  // find max for all columns to set top vAxis number
  var maxVaxis = 0;
  for (var i = 1; i < data.getNumberOfColumns(); i++) {
    if (data.getColumnType(i) === 'number') {
      maxVaxis = Math.max(maxVaxis, data.getColumnRange(i).max);
    }
  }

  var options = {
    annotations: {
      textStyle: {
        fontSize: 10
      }
    },
    series: {
      0: {
        annotations: {
          stem: {
            length: 0
          },
        }
      },
      1: {
        annotations: {
          stem: {
            length: 2
          }
        }
      },
      2: {
        annotations: {
          stem: {
            color: 'transparent',
            length: 16
          }
        },
        color: 'black',
        lineWidth: 0,
        pointShape: 'square',
        pointSize: 0,
        type: 'line',
        visibleInLegend: false
      },
      3: {
        type: 'line'
      }
    },
    hAxis: {
      title: 'Time Period'
    },
    isStacked: true,
    seriesType: 'bars',
    title: 'Overview of the Tickets',
    vAxis: {
      title: 'Number of Tickets',
      viewWindow: {
        max: maxVaxis + 2000
      }
    }
  };

  var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
  chart.draw(data, options);
}

A: I think it happens because there's not enough vertical space for the labels.
Try this:

*

*Save the highest value of the graph (let's call it maxNumber)

*In the "options" set vAxis maxValue to be maxNumber plus a little more.
I have 4 horizontal lines in my graph so I wrote:
var options = {
                title: chartTitle,
                ....... //Your options
                vAxis: {
                    //Add more space in order to make sure the annotations are not overlapping
                    maxValue: maxNumber + maxNumber/4,
                },


text:
Q: The doctor prescribed that the child must take/should take/take the medicine every 8 hours Non-native here. The reason why this question confuses me is that this should be "took" based on what I have learnt in grammar classes. But that doesn't sound right. I am confused between take or must take. I feel it should be must since prescribed denotes authority. My friends are split between should take and take.

A: This is not the wording that is typically used in the UK.  Normally you would say that "the doctor prescribed  the medicine <as the object of 'prescribed' and then the dosage <in the form 'to be taken n times a day'>."  So, for example:-

The doctor prescribed an antibiotic to be taken three times daily.

Given the particular phrasing one which you are working, the correct standard tense depends on the context to which the sentence applies.
Thus it might be that the the patient has just come out of the surgery with the prescription and is saying to the chemist (so before even starting the course of treatment)

The doctor prescribed that I must take the antibiotic three times a day.

Or it might be that something went wrong with the prescription and the patient go so ill that s/he is suing the doctor for damages.  Both the medicine and the taking of the doses are fully in the past.  Then you would expect:-

The doctor prescribed that I should take the antibiotic three times a day

A: "The doctor prescribed that the child must take the medicine every 8 hours"
This is a little more emphatic and implies either that the reason the child is taking the medicine is very serious or that the doctor has some extra level of authority.
"The doctor prescribed that the child should take the medicine every 8 hours"
""The doctor prescribed that the child take the medicine every 8 hours"
These two have pretty much the exact same meaning.  Any difference between them would be pedantic or quibbling at best

redpajama_set_name: RedPajamaStackExchange


text:
Q: Error Parsing /page.xhtml: Error Traced[line: 45] The entity "laquo" was referenced, but not declared #{'«'.concat(text)}

It's ok. But
#{'«'.concat(text)}

Exception:
javax.faces.view.facelets.FaceletException: Error Parsing /page.xhtml: Error Traced[line: 45] The entity "laquo" was referenced, but not declared.

A: If you use facelets then this is the expected behaviour.
You should use the hexadecimal notation or declare the entity you wish to use in the doctype.Have a look at these websites for more details.
http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references#Predefined_entities_in_XML
Error Parsing /page.xhtml: Error Traced[line: 42] The entity "nbsp" was referenced, but not declared


text:
Q: How to restart Windows service programmatically? Used ServiceController to start my Windows service from a Windows Form application. But this is not working.
ServiceController service = new ServiceController(serviceName);

This statement not working.
Is there any other way to start Windows service from my application.
Service Display Name: Duress Alert Service
Service Name: Service1

How I can restart my service in C#?
Edit 1
According to MSDN from below answer:
ServiceController sc  = new ServiceController();
sc.ServiceName = "Service1";

It shows red line under ServiceName and error:

ServiceController does not contains the definition of ServiceName. No extension method 'ServiceName' no accepting a first argument of type controller could not be found (are you missing a using directive or an assembly reference?)

While I have added the reference of service process:
using System.ServiceProcess;

But it still showing the error.

A: You will need to use the Start and Stop methods.  See https://msdn.microsoft.com/en-us/library/yb9w7ytd%28v=vs.110%29.aspx for an example.


text:
Q: Trying to simulate 2 dice to know the percentage of same outcome So, i think they is a logical  error somewhere in the code.
The output keeps running 0% no matter any number i insert in the output terminal
#dice - count doubles in user - defined number of rounds.. repeated
import random

#simulate rolling a six sided die and return its value.
def rollOneDie():
    #generate random numbers from 1 to 6
    thisFace = random.randrange(1,7)
    return thisFace

while True:
    nDoubles = 0
    maxRounds = input(
        "how many rounds do you want to roll?(or ENTER to quit):")
    if maxRounds == '':
        break
    try:
        maxRounds = int(maxRounds)
    except:
        print("please an integer number")
        continue

    for roundNumbers in range(0, maxRounds):
        die1 = rollOneDie()
        die2 = rollOneDie()

    if die1 == die2:
        nDoubles = nDoubles + 1

    percent = (nDoubles * 100.0) / maxRounds
    print('out of ', maxRounds,  'you rolled',
      nDoubles, 'doubles or ', percent, '%')
print('ok byeee')

A: The reason it prints 0% is that the if statement which checks if the dice are the same is outside the for loop that "rolls" the dice, so the nDoubles increases by 1 only if the dice are the same the last time you "roll" them.
The correct way is:
for roundNumbers in range(0, maxRounds):
    die1 = rollOneDie()
    die2 = rollOneDie()

    if die1 == die2:
        nDoubles = nDoubles + 1

Also, you can write:
nDoubles += 1

instead of
nDoubles = nDoubles + 1


text:
Q: How can i bind multiple javascript object instance to elements I'm trying to create a JavaScript player, but not sure how can i have multiple instance of it in the same page such that each have its on functionality

$(function() {
  var player = function(obj) {
    player.item = obj;
    player.audio = player.item.attr('data-player-src');
    player.audioElement = document.createElement('audio');
    player.audioElement.setAttribute('src', player.audio);
    player.audioElement.addEventListener('canplay', function() {
      player.item.find('.length').text('duration : ' + player.audioElement.duration + ' seconds');
    });
    player.audioElement.addEventListener('timeupdate', function() {
      player.item.find('.duration').text('current seconds : ' + player.audioElement.currentTime);
    });
    player.item.find('.play').on('click', function() {
      player.play();
    });
    player.item.find('.pause').on('click', function() {
      player.pause();
    });
    player.play = function() {
      player.audioElement.play();
    }
    player.pause = function() {
      player.audioElement.pause();
    }
    return player;
  }

  $.fn.player = function(options) {
    return player($(this));
  }

  var playerone = $("#player1").player();
  var playerone = $("#player2").player();
});
.player {
  border: 1px solid red;
  height: 60px;
  width: 200px;
  margin: 8px;
  padding: 8px;
}

Length

  <input type="button" class="play" value="Play" />
  <input type="button" class="pause" value="Pause" />

Length

  <input type="button" class="play" value="Play" />
  <input type="button" class="pause" value="Pause" />

Currently the button clicks on player1 will trigger player2 or vice versa.
How can i make each player independent on each other in the same page

A: You just need to add
$(function() {
  var player = function(obj) {
    var player={};//this line

into the first line of your function to make it reusable. To make it usable through jquery you can do:
$.fn.player=function(options){
  return player($(this));
}

Usecase
var playerone= $("#el").player();


text:
Q: C++ STL:map search by iterator to another map I'm trying to jump through some hoops to organize data in a special way. I'm including a simplified piece of code that demonstrates my pain.
I can't use boost.
I'm using the latest version of g++ in cygwin.
#include <iostream>
#include <map>

using namespace std;

int main () {

    map< int,int > genmap;
    map< int,int >::iterator genmapit;
    map< map<int,int>::iterator,int > itermap;

    // insert something into genmap
    genmap.insert (make_pair(1,500) );

    // find and return iterator.
    genmapit=genmap.find(1);

    // insert the iterator/int into itermap. Dies on each of the following 3 versions of this line.
    //itermap[genmapit] = 600; // crash
    //itermap.insert ( pair< map<int,int>::iterator,int >(genmapit,600) ); // crash
    itermap.insert ( make_pair(genmapit,600) ); // crash

    return 0;
}

So as you can see, I have 1 simple map, an iterator to that map and another map that has the first argument as an iterator to the first map.
It's clear from this:
Why can't I put an iterator in map?
That I can have an iterator as the second argument. However, the way shown above provides this:
$ make
g++    -c -o main.o main.cpp
/usr/lib/gcc/i686-pc-cygwin/3.4.4/include/c++/bits/stl_function.h: In member fun
ction `bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp =
 std::_Rb_tree_iterator<std::pair<const int, int> >]':
/usr/lib/gcc/i686-pc-cygwin/3.4.4/include/c++/bits/stl_tree.h:871:   instantiate
d from `std::pair<typename std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _All
oc>::iterator, bool> std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::i
nsert_unique(const _Val&) [with _Key = std::_Rb_tree_iterator<std::pair<const in
t, int> >, _Val = std::pair<const std::_Rb_tree_iterator<std::pair<const int, in
t> >, int>, _KeyOfValue = std::_Select1st<std::pair<const std::_Rb_tree_iterator
<std::pair<const int, int> >, int> >, _Compare = std::less<std::_Rb_tree_iterato
r<std::pair<const int, int> > >, _Alloc = std::allocator<std::pair<const std::_R
b_tree_iterator<std::pair<const int, int> >, int> >]'
/usr/lib/gcc/i686-pc-cygwin/3.4.4/include/c++/bits/stl_map.h:360:   instantiated
 from `std::pair<typename std::_Rb_tree<_Key, std::pair<const _Key, _Tp>, std::_
Select1st<std::pair<const _Key, _Tp> >, _Compare, _Alloc>::iterator, bool> std::
map<_Key, _Tp, _Compare, _Alloc>::insert(const std::pair<const _Key, _Tp>&) [wit
h _Key = std::_Rb_tree_iterator<std::pair<const int, int> >, _Tp = int, _Compare
 = std::less<std::_Rb_tree_iterator<std::pair<const int, int> > >, _Alloc = std:
:allocator<std::pair<const std::_Rb_tree_iterator<std::pair<const int, int> >, i
nt> >]'
main.cpp:23:   instantiated from here
/usr/lib/gcc/i686-pc-cygwin/3.4.4/include/c++/bits/stl_function.h:227: error: no
 match for 'operator<' in '__x < __y'
make: *** [main.o] Error 1

"instantiated from here" tells me nothing and a web search gives me no info on this.
Does STL:map simply not allow for this? I can recode my app to work around this but it will be very inefficient and I would like to get this working. Is there another kind of pointer I can make for a map element I could use?
Thanks for your time.

A: You can't do this because std::map iterators are not random access iterators so aren't comparable with <.
Instead, you could use pointers to the value_type in the first map as a map key.

A: You have to learn to read the error messages. In particular look at the message that comes after the long-winded description where the error happened:

/usr/lib/gcc/i686-pc-cygwin/3.4.4/include/c++/bits/stl_function.h:227: error: no
   match for 'operator<' in '__x < __y'

Map iterators are not comparable with less-than operator which the map uses by default.
I suppose you can provide a comparison function that compares the pairs pointed to by the iterator, since the iterators themselves cannot be easily compared in a meaningful way.
struct CompareIterator
{
     template <class FirstIter, class SecondIter>
     bool operator()(FirstIter lhv, SecondIter rhv) const
     {
         return *lhv < *rhv;
     }
};

//usage with map:
map< map<int,int>::iterator,int, CompareIterator > itermap;

std::pair defines operator<. I also used two iterator types, since it might be possible the types are different (iterator and const_iterator)

A: map<Key, Value>

The map iterator as key element into another map is not possible because map expects operator < to be defined by default to the key. If the Key (in this case map iterator) is not defined then you need to pass a functor as a predicate function that provides the comparison of Key (map iterator).


text:
Q: Statsmodels - 'corrected predictors' on log-linear models? I'm currently working through an econometrics book , and in the section about log linear models it is stated that predictions
made with exp(b1 + b2x + σ2 / 2) are preferable to exp(b1 + b2x)
The software that I am using is the statsmodels python package. And the .predict function on my regression model seems to be using the 'wrong' predictor.
I've been unable to find any kwargs / alternative functions that provide 'corrected' predictions.
Does the statsmodels package not provide this functionality? And if so, is it because the authors disagree with the 'corrected predictor' or am I missing something really obvious here?

A: Log linear model: $log(Y)\sim N(X\beta,\sigma^2)$. Following log-normal distribution, we have $E(Y)=exp(X\beta+\frac 12 \sigma^2)$. But $\bar Y(X) = exp(X\hat\beta+\frac 12 \hat\sigma^2)$ is biased estimate of $E(Y|X)$ even $\hat \beta$ and $\hat \sigma^2$ are the unbiased estimates of $\beta$ and $\sigma^2$, because the non-linearity. But it is asymptotic unbiased estimate.
It is possible to using Taylor formula to decrease the bias duo to non-linearity. There is no other alternative functions.
Check the manual of statsmodels to see if it provide the correct function. Currently, the incorrect (free) things on the internet/website are very common.


text:
Q: angularjs constants is a function instead of string I'm trying to use the constant methods for setting environment variables.
When I want to access the constant it gives a Method instead of a String as I would expect.
I'm using a config.js:
angular.module("config", [])

.constant("endPoint", "http://localhost:8080");

Then I'm injecting it in my App.js:
angular.module('jbehaveWebApp', ['ngRoute', 'mgcrea.ngStrap', 'ui.bootstrap','config']).config(function($routeProvider)

After which I'm getting it as a parameter in my controller:
angular.module('jbehaveWebApp').controller('StoryCtrl', ['$scope', '$http', 'filterFilter','endPoint',
function StoryCtrl($scope, $http, endPoint)

When I'm logging the endpoint var the browser sends the following string:
function (array, expression, comparator) {
    if (!isArray(array)) return array;

    var comparatorType = typeof(comparator),
        predicates = [];

    predicates.check = function(value) {
      for (var j = 0; j < predicates.length; j++) {
        if(!predicates[j](value)) {
          return false;
        }
      }
      return true;
    };

    if (comparatorType !== 'function') {
      if (comparatorType === 'boolean' && comparator) {
        comparator = function(obj, text) {
          return angular.equals(obj, text);
        };
      } else {
        comparator = function(obj, text) {
          if (obj && text && typeof obj === 'object' && typeof text === 'object') {
            for (var objKey in obj) {
              if (objKey.charAt(0) !== '$' && hasOwnProperty.call(obj, objKey) &&
                  comparator(obj[objKey], text[objKey])) {
                return true;
              }
            }
            return false;
          }
          text = (''+text).toLowerCase();
          return (''+obj).toLowerCase().indexOf(text) > -1;
        };
      }
    }

    var search = function(obj, text){
      if (typeof text == 'string' && text.charAt(0) === '!') {
        return !search(obj, text.substr(1));
      }
      switch (typeof obj) {
        case "boolean":
        case "number":
        case "string":
          return comparator(obj, text);
        case "object":
          switch (typeof text) {
            case "object":
              return comparator(obj, text);
            default:
              for ( var objKey in obj) {
                if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) {
                  return true;
                }
              }
              break;
          }
          return false;
        case "array":
          for ( var i = 0; i < obj.length; i++) {
            if (search(obj[i], text)) {
              return true;
            }
          }
          return false;
        default:
          return false;
      }
    };
    switch (typeof expression) {
      case "boolean":
      case "number":
      case "string":
        // Set up expression object and fall through
        expression = {$:expression};
        // jshint -W086
      case "object":
        // jshint +W086
        for (var key in expression) {
          (function(path) {
            if (typeof expression[path] == 'undefined') return;
            predicates.push(function(value) {
              return search(path == '$' ? value : (value && value[path]), expression[path]);
            });
          })(key);
        }
        break;
      case 'function':
        predicates.push(expression);
        break;
      default:
        return array;
    }
    var filtered = [];
    for ( var j = 0; j < array.length; j++) {
      var value = array[j];
      if (predicates.check(value)) {
        filtered.push(value);
      }
    }
    return filtered;
}

Can someone tell my what I'm doing wrong?

A: This:
function StoryCtrl($scope, $http, endPoint)

Should be:
function StoryCtrl($scope, $http, filterFilter, endPoint)


text:
Q: Android ScrollTo View I have a Layout where there is a EditText at 75% position from top of the view and when it gets focused the keyboard is shown and the EditText automatically moves up. I want to ask what this behaviour is called and how can I reproduce this by code even without it's focused? Is there a way to do that without using ScrollView?
UPDATED
What I want is to show name suggestions as user types in EditText. As this is EditText, the keyboard would be shown and EditText has to be at x=0 and y=0 to have enough space for suggestions ListView so user can pick one.

A: public void scrollTo (int x, int y)
also see smoothscroll


text:
Q: add AlternateKey to model in asp.net i have one table like this

id
version
secondId

1
1
1000

1
2
1000

1
3
1000

2
1
1001

2
2
1001

2
3
1001

verion and id are composite key . i want to add auto increment secondId . for all id , secondId is same but version is diffrent. i dont konw how to handle this in code first EF .
i write blow code in dbcontext file
modelBuilder.Entity<user>().HasKey(e => new { e.Id, e.Version });
        modelBuilder.Entity<user>().HasAlternateKey(q => new { q.Version, q.SecondId });
        modelBuilder.Entity<user>().Property(q => q.SecondId).UseIdentityAlwaysColumn();
        modelBuilder.Entity<user>().Property(q => q.SecondId).HasIdentityOptions(1000);


text:
Q: Guardar Spinner dentro de una base de datos SQLite y mostrarlo después? Tengo una base de datos ya creada y la cual se muestra en un Recyclerview con valores como Id, Nombre y Telefono y quiero colocar un spinner el cual me deje colocar una serie de valores, como puedo hacer para que cuando le de click en un valor del spinner se guarde dicho valor en SQLite y despues cuando vuelva a entrar a la actividad me muestre el valor guardado, agradezco toda la ayuda que me puedas brindar. Gracias.
Este es mi Maganer:
public class DataBaseManager {

    public static final String TABLA_PEDIDO = "pedido";
    public static final String CREAR_TABLA_PEDIDO = "CREATE TABLE " + TABLA_PEDIDO + " (" +
            "Id integer," +
            "cantidad text," + //Este es espacio para asignarle el valor del spinner
            "Nombre text," +
            "Descripcion text," +
            "precio integer)";

    private DbHelper helper;
    private SQLiteDatabase db;

    public DataBaseManager(Context context) {
        helper = new DbHelper(context);
        db = helper.getWritableDatabase();
        db = helper.getReadableDatabase();
    }

    public void cerrar() {
        if (db.isOpen())
            db.close();
    }

    private ContentValues generarContentValues (int Id, String cantidad, String Nombre, String Descripcion, int Precio)
    {
        ContentValues cv = new ContentValues();
        cv.put("Id", Id);
        cv.put("cantidad", cantidad);
        cv.put("Nombre", Nombre);
        cv.put("Descripcion", Descripcion);
        cv.put("Precio", Precio);
        return cv;
    }

    public void insertar(int Id, String cantidad, String Nombre, String Descripcion, int Precio) {
        db.insert(TABLA_PEDIDO, null, generarContentValues(Id, cantidad, Nombre, Descripcion, Precio));
    }

    public void modificarValor (int Id, String nuevacantidad, String Nombre, String Descripcion, int Precio){

   SQLiteDatabase db = helper.getWritableDatabase();

   if (db != null){

   db.update(TABLA_PEDIDO, generarContentValues(Id, nuevacantidad, Nombre, Descripcion, Precio), "pysId=?", new String[]{String.valueOf(pysId)});
            db.close();
        }
    }

public List<Producto> getPedidoList() {

  List<Producto> pedido = new ArrayList<Producto>();
  String seleccion = "SELECT * FROM " + TABLA_PEDIDO;
  SQLiteDatabase db = helper.getReadableDatabase();
  Cursor cursor = db.rawQuery(seleccion, null);

  if (cursor.moveToFirst()){
            do {
                pedido.add(new Producto(cursor.getInt(0),cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getInt(4)));
            }while (cursor.moveToNext());
        }
        cursor.close();
        db.close();

        return pedido;
    }

    public void openDB (){
        try {
            db = helper.getWritableDatabase();
            db = helper.getReadableDatabase();
        }catch (SQLException e){
            e.printStackTrace();
        }
    }
}

Este es mi Helper:

public class DbHelper extends SQLiteOpenHelper {

    private static final String DB_NOMBRE = "juan.sqlite";
    private static final int VERSION = 1;

    public DbHelper(Context context) {
        super(context, DB_NOMBRE, null, VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        //crear tabla pedido
        try {
            db.execSQL(DataBaseManager.CREAR_TABLA_PEDIDO);

        }catch (SQLException e)
        {e.getMessage();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        db.execSQL("DROP TABLE IF EXISTS" + DataBaseManager.TABLA_PEDIDO);
        onCreate(db);
    }
}

Y este es mi adaptador:

public class ProductoAdapter extends RecyclerView.Adapter<ProductoAdapter.ProductoViewHolder> {
    //Cargando la imagen y el contexto
    Context mainContext;
    DataBaseManager db;

    int Id, Precio;
    String Cantidades, nuevaCantidad, Nombre, Descripcion;

    //Para almacenar una lista de todos los Clientes
    List<Producto> items;
    int selectedPos;

    public ProductoAdapter(List<Producto> items, Context contexto) {
        super();
        this.items = items;
        this.mainContext = contexto;
    }

    @Override
    public ProductoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.mostrar_pedido, parent, false);
        ProductoViewHolder pHolder = new ProductoViewHolder(v);
        return pHolder;
    }

    @Override
    public void onBindViewHolder(final ProductoViewHolder viewHolder, int position) {
        Producto item = items.get(position);
   viewHolder.txtpysId.setText(String.valueOf(item.getId()));
   viewHolder.txtnombre.setText(item.getNombre());
   viewHolder.txtdescrip.setText(item.getDescripcion());
   viewHolder.txtprecio.setText(String.valueOf(item.getPrecio()));
   viewHolder.txtcant.setAdapter(a());

   viewHolder.txtcant.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                nuevaCantidad = parent.getItemAtPosition(position).toString();

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

private SpinnerAdapter a() {

        String[] pedido = new String[]{"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};

        ArrayAdapter<String> adapter = new ArrayAdapter<>(mainContext,android.R.layout.simple_spinner_item, pedido);

        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        return adapter;
}

public void modificarValor (int Id, String nuevaCantidad, String Nombre, String Descripcion, int Precio){
        DataBaseManager dbManager = new DataBaseManager(mainContext);
        dbManager.modificarValor(Id, nuevaCantidad, Nombre, Descripcion, Precion);
}

@Override
public int getItemCount() {
        return items.size();
}

class ProductoViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        // Campos respectivos de un item
        public TextView txtId;
        public TextView txtnombre;
        public TextView txtdescrip;
        public TextView txtprecio;
        Spinner txtcant;

        public ProductoViewHolder(View v) {
            super(v);
            txtId = (TextView) v.findViewById(R.id.Id);
            txtnombre = (TextView) v.findViewById(R.id.txtNombre);
            txtdescrip = (TextView) v.findViewById(R.id.txtVDescripcion);
            txtprecio = (TextView) v.findViewById(R.id.precio);
            txtcant = (Spinner) v.findViewById(R.id.cantidad);

        }
    }
}

Esta es la actividad.

public class Pedidos extends AppCompatActivity implements OnItemSelectedListener {

    Spinner spinner;

    Context mainContext;
    private DataBaseManager managerPedidos;
    private RecyclerView recycler;
    private RecyclerView.LayoutManager lManager;
    private List<Producto> listaItemsCursos;
    private int id_pedido;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pedidos);
        MultiDex.install(this);

        managerPedidos = new DataBaseManager(this);
        listaItemsCursos = managerPedidos.getPedidoList();

        // Obtener el Recycler
        recycler = (RecyclerView) findViewById(R.id.pedidos);
        recycler.setHasFixedSize(true);

        // Usar un administrador para LinearLayout
        lManager = new LinearLayoutManager(this);
        recycler.setLayoutManager(lManager);

        // Crear un nuevo adaptador
        ProductoAdapter adapter = new ProductoAdapter(listaItemsCursos, this);
        recycler.setAdapter(adapter);

        recycler.addOnScrollListener(rVOnScrollListener);
        recycler.setItemAnimator(new DefaultItemAnimator());
    }
}

No se como guardar el spinner en el SQLite y que despues cuando vuelva a ingresar a esa actividad me muestre el spinner seleccionado, actualmente me sigue mostrando el primero por defecto.
Agradezco todos los que me puedan ayudar. Gracias.

A: Para poder hacer lo que necesitas, una vez que guardes los valores en la base de datos y vuelvas a entrar a la activity. Haz un select de esos valores guardados por ejemplo mi spinner tiene :
Chile
Peru
Mexico

Y en mi base de datos guardo mi valor Chile, entonces quiero que cuando vuelva a cargar la vista este valor se marque por defecto.
//Este valor debería saber el que guardaste en la base de datos.

String valorSeleccionado = "Chile";
ArrayAdapter myAdaptador = (ArrayAdapter) miSpinner.getAdapter();

//obtenemos la posición

int spinnerPosition = myAdaptador.getPosition(valorSeleccionado);

//y damos finalmente la posicion que queremos dejar seleccionada

miSpinner.setSelection(spinnerPosition);

A: La manera más directa sería utilizar Shared Preferences para guardar la posición cada vez que se selecciona un valor en el spinner. Entonces cuando vuelves a iniciar la actividad simplemente seteas esa posicion usando setSelection(posicion).


text:
Q: Split one background image into two divs Hello stackoweflow community, I need help, I'am creating website and I need split image in the half, but they must be divs.. Is it possible to split background-image into the half to be two divs? Hese is jsfiddle: http://jsfiddle.net/hLt5rguq/6/
Here is the html code how I need it to look like:

A: Yes it is, you just have to cut it into 2 elements and position the background. I've used .wallpaper to show the previous image

* {
  box-sizing: border-box;
}
.wallpaper {
  background: transparent url("http://intrawallpaper.com/wp-content/uploads/awesome-rain-wallpaper_0.jpg") no-repeat scroll 0% 0%;
  width: 500px;
  height: 200px;
  float: left;
  margin-top: 10px; //spacing
}
.left-side {
  float: left;
  background: transparent url("http://intrawallpaper.com/wp-content/uploads/awesome-rain-wallpaper_0.jpg") no-repeat scroll 0 top;
  width: 250px;
  height: 200px;
  margin-right: 10px; //show cutting edge
}
.right-side {
  float: left;
  background: transparent url("http://intrawallpaper.com/wp-content/uploads/awesome-rain-wallpaper_0.jpg") no-repeat scroll -250px top;
  width: 250px;
  height: 200px;
}

JSFiddle

A: Try this CSS out which should fix your problem
.left-side, .right-side {
    width: 50%;
    float: left;
    display: inline-block;
    height: inherit;
    background-color: transparent;
}

A: Yes we can do it using css, here is the example using one image spilt into two divs using below code
* { box-sizing: border-box; }
.wallpaper {
    width:1024px;
    height:683px;
    display:block;
}
.left-side{
     background: transparent url("http://intrawallpaper.com/wp-content/uploads/awesome-rain-wallpaper_0.jpg") no-repeat left top;
    width:50%;
    display:inline-block;
    height:100%;
    float:left;
}
.right-side{
     background: transparent url("http://intrawallpaper.com/wp-content/uploads/awesome-rain-wallpaper_0.jpg") no-repeat right top;
    width:50%;
    display:inline-block;
    height:100%;
}


text:
Q: display json data into another page in data table codeigniter Hi I have a problem reagrding my json , how can I view the json data like
{"0":["24","wings","1","₱7","₱7"]} into the datatable?
I have a view here, and it can save to database what I want is when user click process the {"0":["24","wings","1","₱7","₱7"]} will be displayed inside the table like the pos page/first page.
my view (pos_view.php)
<!DOCTYPE html>

    <link rel="stylesheet" type="text/css" href="<?php echo base_url('assets/bootstrap/css/bootstrap.css'); ?>">
    <link rel="stylesheet" type="text/css" href="<?php echo base_url('assets/pos_style.css') ?>">

<a href="<?php echo base_url('inventory') ?>"><button style="float: right; margin-top: 6px; margin-right: 20px;" class="btn btn-primary btn-lg" >Sign Out</button>

Customer Cart

                    Item ID
                    Item Name
                    Quantity
                    Price
                    Sub Total

            <form method="POST">

                    Item Name
                    <input id="item" type="text" name="item_name" placeholder="Enter Item Name" class="form-control">

                    Quantity
                    <input id="quantity" type="text" name="quantity" placeholder="Enter Quantity" class="form-control">

                    <input style="width: 100%; margin-bottom: 5px;" id="add" type="button" name="enter" class=" btn btn-info input-lg" value="ADD TO CART">
                    <input style="width: 100%;" id="process" type="button" name="process" class=" btn btn-success input-lg" value="PROCESS">

            </form>

            Item Name:

            Price:

            Description:

        <?php $total_amount = ""; ?>

Total Amount Due

next/ when clicking process (billing_view)
<!DOCTYPE html>

    <title>POS</title>
    <link rel="stylesheet" type="text/css" href="<?php echo base_url('assets/bootstrap/css/bootstrap.css'); ?>">
    <link rel="stylesheet" type="text/css" href="<?php echo base_url('assets/pos_style.css') ?>">

<?php echo $this->session->flashdata('errorMessage'); ?>
<?php echo form_open('billing/complete'); ?>
<?php echo form_fieldset('
Payment
'); ?>

    Total Amount:

    <input id="amount_due" type="text" name="" disabled="" class="form-control input-lg">

    Payment:

    <input type="text" id="payment" name="payment" placeholder="Enter Payment" class="form-control input-lg">

    Change:

    <input id="change" type="text" name="" disabled="" class="form-control input-lg">

<input type="text" name="cart" id="cart">
<input type="hidden" name="change" id="c">
<input type="hidden" name="total" id="t">

    <input type="submit" name="submit" class="form-control btn btn-success input-lg">

<?php echo form_close(); ?>

Controllers ; get.php (where the controller
  <?php
class Get extends CI_Controller {
    public function __construct() {
        parent::__construct();
        if (!$this->session->userdata('log_in')) {
            $this->session->set_flashdata('errorMessage','
Login Is Required
');
            redirect(base_url('login'));
        }
    }
    public function item_info() {
        $name = "";
        $price = "";
        $description = "";
        $item_name = $this->input->post('item_name');
        $this->load->model('ajax_model');
        if ($item_info = $this->ajax_model->item_info($item_name)) {
            $name = $item_info->name;
            $price = $item_info->price;
            $description = $item_info->description;
            ?>

            Item Name : <?php echo $name ?>

                Price : ₱<?php echo $price ?>

                Description : <?php echo $description ?>

            <?php
        }else {
            ?>

            No Item Found

            <?php
        }

    }

    public function cart() {
        $item_name = $this->input->post('item_name');
        $price = $this->input->post('price');
        $quantity = $this->input->post('quantity');
        $total = $this->input->post('total');
        $this->load->model('ajax_model');

        if ($item_info = $this->ajax_model->item_info($item_name)) {
            $id = $item_info->id;
        $sub_total = (int)substr($price,00) * (int)$quantity;
        $amount_due = (int)$total + $sub_total;
        $cart = [$id,$item_name,$quantity,$price,$sub_total];
        $json = json_encode($cart);
        echo "

            $id
            $item_name
            $quantity
            ₱$price
            ₱$sub_total

        ";
        echo "";
        }else {
            echo "

            ";

        }

    }

}

?>

and my billing controller
    public function index() {

    $this->load->view('billing_view');

}

public function complete() {
    $cart = $this->input->post('cart');
    $total = $this->input->post('total');
    $payment = $this->input->post('payment');
    $change = $this->input->post('change');
    $this->form_validation->set_rules('payment','Payment','required');
    if($this->form_validation->run() == FALSE) {
        $this->session->set_flashdata('errorMessage','
' . validation_errors() . '
');
        redirect(base_url('billing'));
    }else {

        $data['payment'] = $payment;
        $data['total'] = $total;
        $data['change'] = $change;
        $this->load->model('sales_model');
        $insert_sales = $this->sales_model->insert_sales($cart);

        if ($insert_sales) {
            $this->sales_model->updateStocks($cart);
            $this->load->view('complete',$data);
        }
    }

}


text:
Q: why mock data while testing? I'm trying to learn some testing, and stumbled upon mocking and stubbing. I actually think I can get the difference here, point I can't think of any reason i should use mocking in the first place.
Lets look at the example code from Mocha gem documentation:
require 'test/unit'
require 'mocha/test_unit'

class MiscExampleTest < Test::Unit::TestCase
   test "mocking_an_instance_method_on_a_real_object" do
      person = Person.new
      person.expects(:save).returns(true)
      assert person.save

   end

I dont understand the reason behind this line:
person.expects(:save).returns(true)

Whether I use it or not, the output is completely the same: the test passes. I can feel that it has something to do with telling the object/class how to behave, but how is that testing if we first tell the object to return true and then check if it returns true? It always will, we told it to. Isn't it pointless?

A: The example you posted indeed doesn't seem to make much sense:
test "mocking_an_instance_method_on_a_real_object" do
  person = Person.new
  person.expects(:save).returns(true)
  assert person.save
end

In fact the test doesn't test Person at all, it just tests that the mock works.
But mocking or stubbing can makes a lot of sense: It allows you to bypass parts you are not interested in (that are out of scope), to speed up you test suite by not loading data from your database or to not call external services.
Imagine the following example: You have a method that calls an external payment provider and may return an error:
def make_payment(user, amount)
  payment = ExternalPaymentGateway.transfer(company_account, user.account, amount)
  raise 'payment error' if payment.error?
end

To test this method you do not want to make real payments and you do not want to call the external service at all (because unnecessary API request slow down your test suite a lot). Instead you want to stub this service completely:
ExternalPaymentGateway.expects(:transfer).returns(true)
assert_nothing_raised make_payment(user, '$100000')

ExternalPaymentGateway.expects(:transfer).returns(false)
assert_raised 'payment_error' do
  make_payment(user, '$100000')
end

A: No it won't always return true.
Testing is to make sure every inch of your code will run as expected after you've made a change to the code or a change to its environment.
If you recently installed a new database, changed host or modified database.yaml then this "save" test will return false.
This should then raise flags in your head to not push to master until you've sorted out that database connection bug.


text:
Q: segmentation faults in MPI-2 any idea why the following would give me a segfault?
buf_int = new int[12];
buf_int[0] = stx1.min;
buf_int[1] = stx1.max;
buf_int[2] = stx2.min;
buf_int[3] = stx2.max;
buf_int[4] = sty1.min;
buf_int[6] = sty2.max;

MPI_Bcast(&buf_int, 12, MPI_INT, 0, MPI_COMM_WORLD);

stx1.min = buf_int[0];

if i comment out the final line, i do not get a segfault, but if i leave it in, i get the
=====================================================================================
=   BAD TERMINATION OF ONE OF YOUR APPLICATION PROCESSES
=   EXIT CODE: 11
=   CLEANING UP REMAINING PROCESSES
=   YOU CAN IGNORE THE BELOW CLEANUP MESSAGES
=====================================================================================

error which turns out is a segmentation fault. if the error cannot be deduced from the code given, i can include more.
buf_int is declared as
int* buf_int;

A: Since the signature of MPI_Bcast is this:
int MPI_Bcast(
  void *buffer,
  int count,
  MPI_Datatype datatype,
  int root,
  MPI_Comm comm
);

as taken from it's documentation, you should call the function as:
MPI_Bcast(buf_int, 12, MPI_INT, 0, MPI_COMM_WORLD);

That is, pass buf_int as first argument, instead of &bug_int.
You can see the example-code by scrolling down the page, and compare the usage.


text:
Q: How do I create a data table in code in R I have a data table as a CSV file that I use to create metrics for a dashboard.  The data table includes Metric IDs and associates these with field names.  This table--this definition of metrics--is largely static, and I'd like to include it within R code rather than, for example, importing a CSV file containing these headings.
The table looks something like this:

Metric_ID
Metric_Name
Numerator
Denominator

AB0001
Number_of_Customers
No_of_Customers

AB0002
Percent_New_Customers
No_of_New_Customers
No_of_Customers

This has about 40 rows of data, and I'd like to set this table up in code so that it is created at the time the R query is run.  I'll then use it to associate metric IDs with measures I retrive through SQL queries.  Sometimes this table may change -- for example, new metrics might be added or existing metrics modified.  This would need some modificatoin in the code to incorporate these metrics.
The closet way I could find was to create a data table, along the lines described in the query below.
dt<-data.table(x=c(1,2,3),y=c(2,3,4),z=c(3,4,5))
dt

   x y z
1: 1 2 3
2: 2 3 4
3: 3 4 5

cbind with data table and data frame
This works for a table with a few rows or columns, but will be unwieldy for tables with 40+ rows.  For example, if I wanted to modify a metric 20 rows down, I'd have to go 20 rows down in each column, and then test the table to ensure I switched the metric at the right place in each column -- especially where some metrics have empty cells.  for example, I may correct the metric ID in row 20, but accidentally put the definition (a separate column) in row 19.
Is there a more straightforward way of, in essence, creating a table in code?
(I appreciate the most straightforward way would be to keep a CSV file accessible and use read_csv to import it into R.  However, this doesn't work so well if colleagues are running this query on their machine and have a different file path to the CSV -- it also raises the risk of them running the query with an out-of-date metrics table, as they may not have the latest version in their files).
Thanks in advance for any guidance you might have!
Tony

A: Here are two options (examples taken from respective help pages):
data.table::fread()
fread("A,B
1,2
3,4
")
#>        A     B
#>    <int> <int>
#> 1:     1     2
#> 2:     3     4

https://rdatatable.gitlab.io/data.table/reference/fread.html
tibble::tribble()
tribble(
  ~colA, ~colB,
  "a",   1,
  "b",   2,
  "c",   3
)
#> # A tibble: 3 × 2
#>   colA   colB
#>   <chr> <dbl>
#> 1 a         1
#> 2 b         2
#> 3 c         3

https://tibble.tidyverse.org/reference/tribble.html
Other options:

*

*If you already have the data.frame from somewhere, you can also use dput() to get a structure() code you can paste into the files you are distributing.

*use the reprex package https://reprex.tidyverse.org/


text:
Q: How does Python solve 6/-132? In Python, 6/-132 gets an answer of -1, but should that be a 0?
What's the rules behind it?

A: Python floors the result, which means that 1/2 floors to zero, but 1/-2 floors to -1. This is different than C, which 'truncates toward 0'. AFAIK, most languages follow C. Python uses different rules to keep division 'in sync' with modulo. This article does a good job of explaining.
http://python-history.blogspot.com/2010/08/why-pythons-integer-division-floors.html


text:
Q: Typescript: type that is union of object keys can't be use as a key for this object I have a function that is called with one parameter. This parameter is object. This function is returning another object, which one property is value of passed to function object. I have problem when I'm trying to retrieve value of object, using obj[key] notation.
I do understand, that key has to be proper type to be used like this. I can't use simple key as string, if in interface I don't have [key: string]: any. But that's not the issue. My key is union of strings that were keys in passed object: 'user' | 'name' etc.
interface Twitter<T> {
  name: T;
  user: T;
  sex: T extends string ? boolean : string;
}
interface Facebook<T> {
  appName: T;
  whatever: T;
  imjustanexapmle: T;
}

type TwFbObjKeys = keyof Twitter<string> | keyof Facebook<string>

My function looks like this:
public static getArrayOfObjects(
        queryParameters: Twitter<string> | Facebook<string>,
    ) {
        const keys = Object.keys(queryParameters) as TwFbObjKeys[];
        return keys.map((paramId) => ({
            paramId,
            value: queryParameters[paramId],
        }));
    }

I would expect, that using paramId which is type: 'name' | 'sex' | 'appName' | ... as a key for object, that has this keys, wouldn't throw an error. But unfortunately I have error:
TS7053: Element implicitly has an 'any' type because expression of type 'name' | 'sex' | 'appName' | ... can't be used to index type Twitter | Facebook.
Property 'name' does not exists on type Twitter | Facebook
I'm fighting with it for few hours now. Any idea how I can solve it?

A: Better define the function parameter queryParameters as generic type T with constraint <T extends Twitter<string> | Facebook<string>> instead of an union type Twitter<string> | Facebook<string>:
function getArrayOfObjects<T extends Twitter<string> | Facebook<string>>(
    queryParameters: T
) {
    const keys = Object.keys(queryParameters) as (keyof T)[];
    return keys.map((paramId) => ({
        paramId,
        value: queryParameters[paramId],
    }));
}

Playground
Explanations
By using generics you keep the type of the passed in argument for queryParameters and just ensure that it will be a sub type of Twitter<string> | Facebook<string>. paramId with type keyof T now can access queryParameters properties.
With a union type Twitter<string> | Facebook<string>, queryParameters would remain undetermined and could be still Twitter<string> or Facebook<string> in the function body. That causes problems with keyof operator and property access in your case, as you can only access common property keys of all constituents given the union type. And there are no common properties for Twitter<string> and Facebook<string>.
To illustrate the issue a bit more, you probably meant to define TwFbObjKeys to be
// "name" | "user" | "sex" | "appName" | "whatever" | "imjustanexapmle"
type TwFbObjKeys = keyof Twitter<string> | keyof Facebook<string>

// not this: keyof only applies to Twitter<string> here: "name" | "user" | "sex" | Facebook<string>
type TwFbObjKeys_not = keyof Twitter<string> | Facebook<string>

But that would not solve the issue alone. Example:
declare const queryParameters: Twitter<string> | Facebook<string>

// type keysOfQueryParameters = never
type keysOfQueryParameters = keyof typeof queryParameters

// ok, let's try to define all union keys manually
type TwFbObjKeys = "name" | "user" | "sex" | "appName" | "whatever" | "imjustanexapmle"
declare const unionKeys: TwFbObjKeys

// error: doesn't work either
queryParameters[unionKeys]

// this would work, if both Twitter and Facebook have "common" prop
queryParameters["common"]

Playground
With help of a generic type, we can use keyof T to safely access the passed in queryParameters keys.

A: I think your problem is coming from that line
type TwFbObjKeys = keyof Twitter<string> | Facebook<string>
// is of type type TwFbObjKeys = "name" | "user" | "sex" | Facebook<string>

you probably want
type TwFbObjKeys = keyof Twitter<string> | keyof Facebook<string>
// of type type TwFbObjKeys = "name" | "user" | "sex" | "appName" | "whatever" | "imjustanexapmle"

A: (Assuming you means type TwFbObjKeys = keyof Twitter<string> | keyof Facebook<string>)
Typescript raise an error because paramId has the type which contains all the keys of both interfaces:
'name' | 'user'| 'sex' | 'appName' | 'whatever' | 'imjustanexapmle'
but queryParameters can only be a type of either one interface:
'name' | 'user'| 'sex'
or
'appName' | 'whatever' | 'imjustanexapmle'
To solve the problem, you should separate both types:
interface Twitter<T> {
  name: T;
  user: T;
  sex: T extends string ? boolean : string;
}
interface Facebook<T> {
  appName: T;
  whatever: T;
  imjustanexapmle: T;
}

function isTwitter<T>(val: Twitter<T> | Facebook<T>): val is Twitter<T> {
  return (
    'name' in (val as Twitter<T>) &&
    'user' in (val as Twitter<T>) &&
    'sex' in (val as Twitter<T>)
  )
}

function isFacebook<T>(val: Twitter<T> | Facebook<T>): val is Facebook<T> {
  return (
    'appName' in (val as Twitter<T>) &&
    'whatever' in (val as Twitter<T>) &&
    'imjustanexapmle' in (val as Twitter<T>)
  )
}

function getValue<T, K extends keyof T>(obj: T, key: K) {
  return obj[key];
}

function getArrayOfObjects(
    queryParameters: Twitter<string> | Facebook<string>,
) {
  if (isTwitter(queryParameters)) { // if queryParameters is of type Twitter<string>
    const keys = Object.keys(queryParameters);
    return keys.map((paramId) => ({
      paramId,
      value: getValue(queryParameters, paramId as keyof Twitter<string>)
    }));
  } else if (isFacebook(queryParameters)) { // if queryParameters is of type Facebook<string>
    const keys = Object.keys(queryParameters);
    return keys.map((paramId) => ({
      paramId,
      value: getValue(queryParameters, paramId as keyof Facebook<string>)
    }));
  } else {  // if queryParameters is invalid
    throw new Error("invalid queryParameters!")
  }
}


text:
Q: Python: My server mail is sent to spam I'm trying to send email verification emails from an app I'm writing. I'm running on Linode using server = smtplib.SMTP() and server.sendmail(). For some reason, gmail is marking these messages as spam.
My mail template is:
{% if define('From', 'CQ <Invite@campusquery.com>') or define('Reply-To', 'noreply@campusquery.com') or define('Subject', "CQ: You've been invited to our beta!") %}{{fail()}}{% end %}

msg goes here

It also worked before when I made CQ  be invite@campusquery.com instead. However, when this way does not allow me to define a sender.
How do I fix this?
Thanks.

A: What server are you sending from? There are tons of other factors involved like IP blacklists, rate of messages, whether users have marked you as spam, DNS/reverse DNS, SPF records.
You might consider signing up for an account with litmus.com to test your emails and see how you're performing on spam lists, and what you can do to improve it.

A: I would think that the "From" address would need to be a valid email address--e.g., have <some name>, an @ and a valid host like in bob@example.com--in order for GMail to not consider it spam.


text:
Q: How to check the type of file to be downloaded from a link I was trying to download a file from a link using the following line of code:
urllib.request.urlretrieve('http://ipfs.io/ipfs/QmcgBRy',f'{UNKNOWN_FACES_DIR}\\sample2.mp4')

But the thing is I don't know what type of file is stored in the link and hence cant give an appropriate file extension before downloading it.
Is there any way to get to know the type of file i.e. .jpg, .jpeg, .mp4 etc. before downloading it?

A: Using pure urllib, you can get the content type from the following:
import urllib
url = 'https://i.imgur.com/Woi6pwf.jpg'
urllib.request.urlopen(url).info()['content-type']

which returns:
'image/jpeg'

A: You can use the Python-Magic to find the MIME-type of the file. I guess this is the best library to be used for this purpose. You can do like this
import magic
magic.from_file("testdata/test.pdf")

# OUTPUT
# >>> 'PDF document, version 1.2'

Recommended Version
import magic
magic.from_buffer(open("testdata/test.pdf").read(2048))

# OUTPUT
# >>> 'PDF document, version 1.2'


text:
Q: Execute Statement using one value of query array I am attempting to execute a query using a prepared array. The array has two elements but this query uses only one of them. I am using node-postgres.
Array:
var g=[];
g.push(email,password);

Query:
getter.query('SELECT EXISTS (SELECT 1 FROM users WHERE email_address = $1)',g,
    function(err, result){
        if (err) console.log(err);
            //do stuff including another query
});

This is the error I get:
ERROR: bind message supplies 2 parameters, but prepared statement "" requires 1`
STATEMENT: SELECT EXISTS (SELECT 1 FROM users WHERE email_address = $1)

How do I Execute Statement using only one value of query array? Is there a way to get prepared query statements to accept only one or some elements of an array?


text:
Q: ObvservableCollection Adding Column I Didn't Ask For I have a WPF application that needs customer information retrieved from a database and displayed in a data grid.
Everything is working fine in the background, but when I add the customers to the ObservableCollection object, it is adding a variable to the table that I don't want.
This is where I use it:
private void button_DisplayInfo(object sender, RoutedEventArgs e)
{
    // A collection of customer information
    ObservableCollection<Customer> customerCollection = new ObservableCollection<Customer>();

    // Cycle through each customer in the customer list inside customerManager
    foreach (Customer eachCustomer in customerManager.CustomerList)
    {
        customerCollection.Add(new Customer
        {
            Name = eachCustomer.Name,
            CustomerID = eachCustomer.CustomerID,
            DateJoined = eachCustomer.DateJoined
        });
    }
    dataGrid_Main.ItemsSource = customerCollection;
}

The problem is that in the data grid, I am also getting a column that is a public bool property in the class that I did not specify to read at all, and it is putting a little checkbox instead of a value for it in the grid. Is there any way to prevent this, so that I can read (or at least output) only those three values from my Customer objects and not also the property?
Thanks!
P.S. The bool property is set in my constructor, if that means anything in regard to this.

A: Don't have the DataGrid autogenerate columns (set AutoGenerateColumns to false), and specify the columns manually.  This will give you complete control over which properties are displayed, and how they get displayed.

A: In the XAML, use the attribute AutoGenerateColumns="False" and list out the columns in DataGrid.Columns and specificy what they are bound do.


text:
Q: Easy way to encrypt a text file I'm working on a text based adventure game in C++ and I would like to store quests in a text file,but I don't want the player to read it.
Is there an easy way to encrypt it?

A: Another way to "hide" content of your file to player is to encrypt the file.
You can use openssl for instance.
In this thread you can have an idea on the usage.

A: Velthune's OpenSSL suggestion is fine but it is arguably overkill. I would try something simple like XOR encryption instead.
Of course XOR encryption is not secure, but neither is the OpenSSL approach, since your program must store the encryption key somewhere in the executable file in order to be able to do the decryption.
There is no way to truly secure the file's contents against a determined user and still have it be accessible to a program that runs on the user's machine.
So, I'd suggest XOR encryption as a simple form of obfuscation that will deter someone from changing the file casually, yet won't make your program dependent on an external library.


text:
Q: How does one find the reduced Singular Value Decomposition of a row or column vector? If we treat a column vector $a$ as an $n \times 1$ matrix, or a row vector $a^T$ as a $1 \times n$ matrix, how would one write out the reduced singular value decomposition of $a$?

A: $$a=(a/\| a \|) \begin{bmatrix} \| a \| \end{bmatrix} \begin{bmatrix} 1 \end{bmatrix}.$$
This pretty much follows by knowing the shape of a reduced SVD: if $A \in \mathbb{C}^{m \times n}$ then $U \in \mathbb{C}^{m \times r}, \Sigma \in \mathbb{R}^{r \times r}, V^* \in \mathbb{C}^{r \times n}$, where $r=\text{rank}(A)$. Now take $m=k,r=1,n=1$ (where $a$ is $k \times 1$).

A: I know this is not an answer, but it might be instructive to write out the full SVD:
For a row $a^T$, let $U =1$, $\Sigma =\begin{bmatrix} \|a\| & 0 & \cdots & 0 \end{bmatrix}$,
$V = \begin{bmatrix} {1 \over \|a\|} a^T \\ v_2^T \\ \vdots \\ v_n^T \end{bmatrix}$,
where ${1 \over \|a\|} a^T, v_2, \cdots,\ v_n$ form an orthonormal basis.
For a column $a$, replace $U,\Sigma, V$ by $V^T, \Sigma^T, U^T$ respectively.

A: The truncated SVD of $\mathbf{a} \in \mathbb{R}^{n \times 1}$ would be
$$
\mathbf{a}
=
\mathbf{U}\mathbf{\Sigma}\mathbf{V}^{T},
$$
where $\mathbf{U} = \mathbf{a} / \|\mathbf{a}\|\in \mathbb{R}^{n \times 1}$, $\mathbf{\Sigma} = [\|\mathbf{a}\|] \in \mathbb{R}^{1 \times 1}$ and $\mathbf{V} =[1] \in \mathbb{R}^{1 \times 1}$.
Essentially, the only non-trivial thing in this decomposition is to normalize the length of $\mathbf{a}$ to obtain $\mathbf{U}$, because the decomposition (at least to the best of my knowledge) requires that $\mathbf{U}$ (and $\mathbf{V}$) have orthonormal columns.
The full SVD could be obtained by setting
$\mathbf{U} = \left[ \frac{1}{\|\mathbf{a}\|}\mathbf{a} \;\; \mathbf{U}^{\prime}\right]\in \mathbb{R}^{n \times n}$, with $\mathbf{U}^{\prime}$ being any $n \times (n-1)$ matrix with orthonormal columns that are also orthogonal to $\mathbf{a}$,
 $\mathbf{\Sigma} = [\|\mathbf{a}\| \; 0\; 0 \; \dots \; 0]^{T} \in \mathbb{R}^{n \times 1}$ and $\mathbf{V} =[1] \in \mathbb{R}^{1 \times 1}$.


text:
Q: Azure DataSync with SQL Azure databases across subscriptions I am trying to synchronise databases in two different subscriptions using Azure datasync on the new portal
https://learn.microsoft.com/en-us/azure/sql-database/sql-database-get-started-sql-data-sync
On the portal, I do not get the ability to choose subscription or connection string to connect to a Azure database on a different subscription (this is not on premise)
The options presented are either
a) Database from existing subscription + database server
b) on-premise database- with a sync agent to be downloaded
Can linking to another database via connection string be implemented via API's or is there any restriction or feature limitation around this?

A: Based on your comment, your issue is due to you having different logins for each subscription. In order to achieve what you want to do, you will need to cross add the various users to the subscriptions.
First, log into your Azure portal. Navigate to the subscription you are the admin for. Click on Access control (IAM) to manage the permissions for it.

Click the Add button which will bring up a dialog to add permissions. Simply select the role you wish to grant (I believe you will need contributor for this) and enter the email address of the user that you want to grant permissions to.


text:
Q: Bootstrap Tags Input - how to prefill object values I'm using Bootstrap Tags Input in my form, initalized with following code:
$('#looking_for_job_titles').tagsinput({
    itemValue: 'id',
    itemText: 'name'
});

// TypeAhead.js
var job_scopes = new Bloodhound({
    datumTokenizer: function(d) {
        return Bloodhound.tokenizers.whitespace(d.value);
    },queryTokenizer: Bloodhound.tokenizers.whitespace,
    limit: 100,
    remote: {
        url: 'http://www.domain.com/json.php?action=job_title&q=%QUERY'
    }
});

job_scopes.initialize();

$('#looking_for_job_titles').tagsinput('input').typeahead({
        itemValue: 'name'
    },
    {
        name: 'job_scope',
        displayKey: 'name',
        source: job_scopes.ttAdapter(),
        templates: {
            empty: [
                '
',
                'no results found',
                '
'
            ].join('\n'),
            suggestion: function(data){
                return '
'+ data.industry +'> ' + data.name + '
';
            }
        },
        engine: Hogan
    }).bind('typeahead:selected', $.proxy(function (obj, datum) {
        this.tagsinput('add', datum);
    }, $('#looking_for_job_titles')));

This works fine, and returns comma separated list of ids, which I save into db.
My problem is how to prefill the object values back into the input field on page refresh? The object looks like:
[{"id":"80001","name":"Account Manager"},{"id":"80251","name":"Projektant"}]

A: For anyone needing this:
$.each(obj, function(index, value) {
    $('#looking_for_job_titles').tagsinput('add', value);
    console.log(value);
});

A: Check the document on Method here.
You can use:
$('input').tagsinput('add', 'some tag');

and
$('input').tagsinput('refresh');

A: it should be simple, fill value="" attribute of that input, but without javascript.
If you do this in the correct format value="1,2,3" it will work

A: so it will be
value=" [{"id":"80001","name":"Account Manager"},{"id":"80251","name":"Projektant"}]"


text:
Q: Do 'configuration environments' exist in Play 2.x? In Play 1.x, you could define a different configuration for production and development enviornment:
# These are applied in the default 'dev' enviornment.
db=mem
mail.smtp=mock

# The following are only relevant if 'play id' = prod
%prod.db=mysql://prod@db.us.com/
%prod.mail.smtp.host=in.mailjet.com
%prod.mail.smtp.user=mailuser
%prod.mail.smtp.pass=pass
%prod.mail.smtp.channel=ssl

Does Play 2 have something similar?

A: It doesn't exist but instead you can tell play to use a specific configuration file (you can have a "prod" file that can include a base configuration file and override only the needed properties for example).
See the section "Specifying alternative configuration file" in this documentation page : http://www.playframework.com/documentation/2.1.1/ProductionConfiguration


text:
Q: Cannot generate default assignment operator when a class member is a reference?(in C++) Here is my code:
class NO {
  public:
    NO(std::string& name):nameValue(name){};

  private:
    std::string& nameValue;           // this is now a reference

};

int main(){

  int b=10,c=20;
  int& d=b;
  d=c;

  std::string p="alpha", q="beta";

  NO x(p), y(q);
  x=y;

  return 0;

}

I get the error:
"non-static reference member 'std::string& NO::nameValue', can't use default assignment operator"

Why can't I re-assign the object with a reference member when I can do the same with a built-in type?
thanks

A: A reference can be initialized, but not assigned to. Once the reference is initialized, it will continue to refer to the same object for as long as it exists. If you don't define an assignment operator, the compiler will synthesize one that does member-wise assignment, but in this case that's impossible, so the compiler can't/won't synthesize one at all.
You can define an assignment operator yourself. It's up to you to decide exactly how to deal with a member that's a reference. Most of the time, you just define your object to not contain any references though.
When you get down to it, the primary use for references is almost certainly as parameters. As members of a class, they don't make sense very often, and in the rare case that they do make sense, the objects of that class probably shouldn't support assignment.


text:
Q: In jQuery how do I do something after an event has completed Use case:
I have a table that users enter order lines into. The table is a list of products, they can page up and down in the table. If they've entered a quantity into one product and then page down they need to be focused on the input field in the same column they started from, but at the new row, the page down has moved to.
Problem:
The page down changes the hover location. So I can get which row has the hover state and change focus to the correct column in that row.  I need code to execute after the page down has completed and a new row has: hover.
But because page down is async, getting the row with the hover state in my event handler returns the current row, not the one that will have: hover when the page down completes. How do I write a page down event handler so that code is executed after the page down has completed?
Attaching a promise to the table with code that executes after the 'keydown' type event is complete doesn't work. It runs before the new row has: hover state.

A: You can use document.activeElement to get the element that has focus, get the column from that and set the focus using $(columnSelector).focus() to newly populated records column.
Another way is to have focus event handler and maintain the last focused column name in a variable.


text:
Q: How to create a custom theme for SXA using SXA CLI (Sitecore 9.3)? I've been trying to install SXA CLI for Sitecore 9.3 nd I keep getting the following error when I run the gulp command:
Requiring external module @babel/register
ReferenceError: primordials is not defined
at fs.js:27:26
Bsed on a few articles, I have created the file npm-shrinkwrap.json at the same level as the package.json file and I ran the npm install command. Per the article, npm install should make changes to the file. However, that does not happen. I keep getting the above error.
I have delegted the node_modules folder and run npm install with the same results
Gulp version is:
CLI version: 2.3.0
Local version: 4.0.2
Node version is:
v12.13.0
How do I fix this?

A: The solution is:

*

*Add a file npm-shrinkwrap.json with the following contents at the location where package.json is located
 `{
   "dependencies": {
     "graceful-fs": {
       "version": "4.2.2"
     }
   }
}`

*Delete old node_module folder after adding the file.

*Now run npm-install then.


text:
Q: Debugging why git (svn) rebase does not detect patch (noop)? I have a git-svn repository (Unexpected merge error in a git svn system?); it has a remote called origingit referring to another git repo, in addition to git-svn which refers to an SVN repo.
$ git branch -a
* master
  remotes/git-svn
$ git remote show
origingit
$ tree .git/refs/{heads,remotes}
.git/refs/heads
└── master
.git/refs/remotes
├── git-svn
└── origingit

Here is the problem: when I do
git pull --rebase origingit master

... git splits the tree, so that all commits from origingit that have not been part of the original git svn clone lose their git-svn-id (are "local", see git-svn-id is missing from some commits); in this case, the relevant commits look like this (they all have "null edit" in the name):
$ git log --graph --decorate --pretty=oneline --abbrev-commit --all --date-order | grep 'null edit'
* cae158d (git-svn) : null edit A06
* 8f79edf : null edit A05
* 0c7373e : null edit A04
* b4bf336 : null edit A03
* e05cfc6 : null edit A02
| * e0c6823 (HEAD, master) : null edit A07
| * 03ed433 : null edit A06
| * de3bd53 : null edit A05
| * 65bf738 : null edit A04
| * 62ab3f6 : null edit A03
* | 964b300 : null edit A01
| * 14f5aba : null edit A02
| * f0ef194 : null edit A01

Note that master has picked up the latest "null edit A07", which came in from origingit.
When I do
git svn rebase

... all those commits present in the SVN repository should get a git-svn-id, and those not yet comitted to SVN don't - but are listed after (in time, or first in order) the git-svn-id ones in git log; so on the next git svn dcommit, those local would be comitted to SVN. However, in this particular case, I get the log --graph as:
* cae158d (HEAD, git-svn, master) : null edit A06
* 8f79edf : null edit A05
* 0c7373e : null edit A04
* b4bf336 : null edit A03
* e05cfc6 : null edit A02
* 964b300 : null edit A01

In fact, here git svn rebase outputs to stdout just "First, rewinding head to replay your work on top of it..." and exits; otherwise, it usually says "Applying: ..." which apparently refers to patches (and ... is the commit message for those local), and in that case, the expected log would be:
* xxxxxxx (HEAD, master) : null edit A07
* cae158d (git-svn) : null edit A06
* 8f79edf : null edit A05
* 0c7373e : null edit A04
* b4bf336 : null edit A03
* e05cfc6 : null edit A02
* 964b300 : null edit A01

So - even if null edit A07 is clearly a valid commit in the origingit repo, and comes after null edit A06 one (which is also present in SVN), git svn rebase fails to apply this patch. Why - and how is it even possible?
In any case, from this point, I can do git pull --rebase ... and get to the previous state shown.
Here it would be very nice if there was some debugging facility, which could tell you how git rebase goes through each commit and decides what to do - but unfortunately, --verbose just dumps a list of files changed between the last git-svn-id commit and the latest HEAD, so it doesn't help much.
Adding some printouts to /usr/lib/git-core/git-svn, I could see that git svn rebase ultimately calls git rebase refs/remotes/git-svn; so I tried to add interactive to it:
$ git pull --rebase origingit master
...
$ git rebase --interactive  refs/remotes/git-svn

... and it shows:
noop

# Rebase cae158d..e0c6823 onto cae158d
#
# Commands: [...]

So, applying patches doesn't happen during rebase, because it doesn't find that any patches should be made. But how is that possible - noting that  cae158d is the SHA of "null edit A06" within git-svn (and is present both on SVN and in origingit), while e0c6823 is the SHA of "null edit A07" which came in from origingit - where it stands unequivocally and without a problem as a commit (meaning, there must be an actual change from previous revision) after the "null edit A06"??
So, how can I inspect why this happens - and ultimately, how can I force git to recognize during git svn rebase that there is indeed a patch there?


text:
Q: ADO Update Or Insert is missing Output Inserted Value for second Execute Branch I am using a TADOQuery with SQL Server 2019 and Delphi 10.4 Update 2. I am trying to solve a update or insert operation in one SQL statement.
I have defined the column IndexField as an auto-incrementing column.
This is my (simplified) SQL Server table:
CREATE TABLE [dbo].[Artikel]
(
    [SuchBeg] [varchar](25) NULL,
    [ArtNr] [varchar](25) NULL,
    [IndexField] [bigint] IDENTITY(1,1) NOT NULL,
    PRIMARY KEY CLUSTERED ([IndexField] ASC)
                WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
                      IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
                      ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]

Simplified SQL statement:
UPDATE Artikel
SET [SuchBeg] = 'TEST',
    [ArtNr] = '19904.S'
OUTPUT INSERTED.[IndexField]
WHERE [ArtNr] = '19904.S'

IF @@ROWCOUNT = 0
INSERT INTO Artikel ([SuchBeg], [ArtNr])
    OUTPUT Inserted.[IndexField]
    VALUES ('TEST', '19904.S');

Delphi source:
Query := TADOQuery.Create(nil);
Query.Connection := ADOConnection;
try
  Query.SQL.Text := sSqlText;
  Query.Open; // not ExecSQL; if Results are expected: Open does the Trick.
  Memo1.Lines.Add('Ado Result: '+ Query.RecordCount.ToString + ' ~ ' +  Query.Fields[0].AsString);
finally
  Query.Free;
end;

if i hit the "Update Part" in my SQL i can read a 1 Row 1 Field Recordset from the Query. BUT if the Second "Insert Part" is executetd i dont get a Result (0 Row, 1 Field (Bigint) with 0).
If i execute either "Update" or "Insert" without the "if Rowcount" it works.
if the Statement is Executet in SQL Server Management Studio it Works, and shows 2 Result Windows. First 0 Rows Affected and Second with the desired Value and 1 Row affected.

Is it possible to do this in one go?
Alternative Upsert Ways are here ... but i did not want to be a SQL Server superhero.

A: Try storing the output to a table variable and then return the variable.
DECLARE @Output TABLE (IndexField BIGINT);

UPDATE Artikel SET [SuchBeg] = 'TEST', [ArtNr] = '19904.S' OUTPUT INSERTED.[IndexField] INTO @Output WHERE [ArtNr] = '19904.S'
if @@ROWCOUNT = 0
INSERT INTO Artikel ([SuchBeg], [ArtNr]) Output Inserted.[IndexField] INTO @Output VALUES ('TEST', '19904.S');

SELECT * FROM @Output;

A: If you are only updating one row you can use an OUTPUT parameter. I'm not sure the Delphi side, but the SQL would look like this
Declare @IndexField Bigint;
UPDATE Artikel
SET [SuchBeg] = 'TEST',
    @IndexField = [IndexField]
WHERE [ArtNr] = '19904.5'

IF @@ROWCOUNT = 0
BEGIN
    INSERT INTO Artikel ([SuchBeg], [ArtNr])
    VALUES ('TEST', '19904.5');

    SET @IndexField = SCOPE_IDENTITY();
END;

SELECT @IndexField;

I must say, I didn't see the point in updating the ArtNr column to the same value

Note that if you want to make this ACID-transaction compliant, you would use the following hints
SET XACT_ABORT ON;  -- ensures rollback

BEGIN TRAN;

UPDATE Artikel WITH (UPDLOCK, HOLDLOCK)
SET [SuchBeg] = 'TEST',
    @IndexField = [IndexField]
WHERE [ArtNr] = '19904.S'

IF @@ROWCOUNT = 0
BEGIN
    INSERT INTO Artikel ([SuchBeg], [ArtNr])
    VALUES ('TEST', '19904.S');

    SET @IndexField = SCOPE_IDENTITY();
END;

COMMIT;

SELECT @IndexField;


text:
Q: How to create new columns from subcategories in pandas? I'm trying to take subcategories and place them into columns so I can compute values for each column.
For example, what I have now is:
   c1   c2     c3
0  123  Orange 12
1  123  Car    15
2  123  Blue   14
3  123  Bike   13
4  234  Red    09
5  234  Bus    04
6  234  Train  19
7  234  Purple 17

What I want instead is:
   c1   c3 (colour)  c3 (transport)
0  123  26           28
1  234  26           23

Obviously with about ~20,000 rows and 50 columns.
I've tried using groupby and some other functions but my brain's a bit frazzled and I'm struggling to figure out how to get it to work in the way I want to.
Right now I'm using something to the effect of:
for x in df.c1.unique:
    df['c3 (colour)'] = df[(df[c1] == x) & (df[c2] == colour)].sum()

I'm aware that's a horrendously inefficient way to do it, but right now it's the only way I'm getting the table format that I want. I'm still trying to work out how to use pandas correctly so I'm a little unfamiliar with certain commands that could make it work quicker.

A: Something like this will do the trick for you:
First if you need breakdown per Colour/Transport - you need to classify it accordingly, so:
>>> df
    c1      c2  c3         c4
0  123  Orange  12     Colour
1  123     Car  15  Transport
2  123    Blue  14     Colour
3  123    Bike  13  Transport
4  234     Red   9     Colour
5  234     Bus   4  Transport
6  234   Train  19  Transport
7  234  Purple  17     Colour

Then in order to get exactly what you want (so kind of aggregation with "sumif"):
>>> df.assign(c3_Colour=df["c3"][df["c4"]=="Colour"], c3_Transport=df["c3"][df["c4"]=="Transport"]).fillna(0).groupby(c1).agg({"c3_Colour":sum, "c3_Transport": sum})
     c3_Colour  c3_Transport
123       26.0          28.0
234       26.0          23.0


text:
Q: Macro ending early - not running up till last cell in the column Currently, I have the following set of codes which is to help me run Macro1 for every cell in Column D, so long each cell is not blank/empty. However, with the codes below, it is not calling Macro1 at the last not empty/blank cell of the column. Any idea why is it so?
An update: I found that the loop ended early at Next R. It didn't proceed on. Any idea why so?
Sub testing()

    Dim Rl As Long                      ' last row
    Dim Tmp As Variant
    Dim CellValue As Range
    Dim R As Long                       ' row counter

    With ThisWorkbook.ActiveSheet

        'To find out how many rows in D, counting from the last cell (Not blank)
        Rl = .Cells(.Rows.Count, "D").End(xlUp).Row

        ' work on column D
        For R = 1 To Rl  ' start the loop in row 1
            Tmp = .Cells(R, "D").Value
            If Len(Tmp) Then
                Cells(R, "D").Select
                Call Macro1
            End If
            Rl = .Cells(.Rows.Count, "D").End(xlUp).Row
        Next R
    End With
End Sub

Macro1:
    Dim str As String
    Dim ArrStr() As String
    Dim i As Long
    Dim y As Long
    Dim RowsAdded As Boolean

    RowsAdded = False
    'Fill variables: str is the value of the active cell, ArrStr splits this value at the comma
    str = ActiveCell.Value
    ArrStr = Split(str, ", ")

    'Loop through each ArrStr to populate each cell below the activecell

    For i = 0 To UBound(ArrStr)
        ActiveCell.Offset(i, 0).Value = ArrStr(i)
        If RowsAdded = False Then
            For y = 1 To UBound(ArrStr)
                ActiveCell.Offset(1, 0).EntireRow.Insert xlDown
            Next y
            RowsAdded = True
        End If
    Next i

End Sub

A: Try the following code.  You had most of it in your original post above but I think were a bit fixated on the for loop and the number of cells in column D whilst missing that you already had set the exit criteria..
Sub testing()

    Dim myRow As Long: myRow = 1
    With ThisWorkbook.ActiveSheet

        'Exit when first non empty cell is encountered
        Do While Len(.Cells(myRow, "D").Value)
            Cells(myRow, "D").Select
            Call macro
            myRow = myRow + 1
        Loop

    End With
End Sub

A: Just putting out there in case anybody like to see how I did it. But its built upon @freeflow's answer:
Sub testing()

    Dim myRow As Long: myRow = 1
    With ThisWorkbook.ActiveSheet

        'Exit when first non empty cell is encountered
        Do While Len(.Cells(myRow, "D").Value) Or Len(.Cells(myRow, "D").Value) = 0
            lastRow = Range("D65000").End(xlUp).Row

            Cells(myRow, "D").Select
            Call Macro1
            myRow = myRow + 1

            If myRow = finalRow Then
                Cells(finalRow, "D").Select
                Call Macro1
                Exit Do
            End If

        Loop

    End With
End Sub


text:
Q: Dropdown menu with parent linked issue on tablet I have a menu with parent items all linked and also child and sub-child items that work on :hover to open the dropdown sub-items.
Every item (parents and childs) are also linked. Everything works fine on desktop because on mouse over the parent item the dropdown is opened and I can choose to click on the parent item link or on one of the dropdown that appeared with the mouseover.
The issue is on tablet device. In this case if I tap on the parent item then it just redirects me to the link of this menu item instead of opening the dropdown with child items.
So for tablet I would have a double tap for parent (and also sub-parents): first tap on the parent item open the dropdown, second tap always on the parent item fires it's link.
Thanks in advance.

A: hover function will work only on desktop. For tabs and mobiles you have to use click function by using jQuery / Javascript
Example :

        Home

Home1

Home2

Home3

        About

About1

About2

About3


text:
Q: selenium: Get the URL of the page you are on while flipping pages I'm wrtting script to get the URL of the page while fillipng pages.
I wrote script but nothing happend.
Dose anybody know why?
E.G) starts below page
https://www.jtb.co.jp/kokunai-hotel/list/kyoto/feature/couple_yado/
URL I want to get as below 4pages)
1.https://www.jtb.co.jp/kokunai-hotel/list/kyoto/feature/couple_yado/
2.https://www.jtb.co.jp/kokunai-hotel/list/kyoto/feature/couple_yado/?multiarea=26&dateunspecified=1&page=2
3.https://www.jtb.co.jp/kokunai-hotel/list/kyoto/feature/couple_yado/?multiarea=26&dateunspecified=1&page=3
4.https://www.jtb.co.jp/kokunai-hotel/list/kyoto/feature/couple_yado/?multiarea=26&dateunspecified=1&page=4
Script(Google colab)
!pip install selenium
import requests
!apt-get update
!apt install chromium-chromedriver
!cp /usr/lib/chromium-browser/chromedriver /usr/bin
from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
browser = webdriver.Chrome('chromedriver',options=options)
from time import sleep

pageURL = 'https://www.jtb.co.jp/kokunai-hotel/list/kyoto/feature/couple_yado/'
browser.get(pageURL)
sleep(3)

while True:
  try:
    currentpage = browser.current_url
    print(currentpage)
    next = browser.find_element_by_css_selector(".f-list-paging__arrow .f-list-paging__next a")
    next.click()
  except:
    break


text:
Q: Determine a diagonalizable linear map $g:\mathbb{R^4} \to \mathbb{R^4}$ knowing an eigenspace and the Kernel Determine a diagonalizable linear map $g:\mathbb{R^4} \to \mathbb{R^4}$ such that $\ker(g)=\langle(1,-\frac1{2},-\frac1{2},0)\rangle$ and $V_{-2}=\langle (0, 1, 0, 1),(0, 0, −1, 2) \rangle$.
I know there is an eigenspace missing, because the sum of the dimension of those two eigenspace equals $1$.
I would have written down my attempt if I had done something useful, thanks in advance
Update (thanks to amd's comment)
I found $e_1=(1,0,0,0)$ to be an eigenvector, given that is linearly independent to the other three eigenvector.
Then I can write a basis of eigenvectors: $$B=\left\{(1,0,0,0),\left(1,-\frac1{2},-\frac1{2},0\right),(0, 1, 0, 1),(0, 0, −1, 2)\right\}$$
Now I can define $M_{BB}(g)$ as the matrix with the eigenvalues in the diagonal, but I don't know the eigenvalue related to $e_1$, shall I put a parameter $k$ and see where $g(e_1)=ke_1$?


text:
Q: audio mixing two pcm streams I am using the windows mmSystem.h to generate a few pcm files. Well they are not files yet, really byte arrays. what I want to do is merge or mux these two streams so the sounds overlap before I export them to a wav file. searching stackoverflow everyone has mentioned using ffmpeg but no one has any example code, they just use the fmpeg.exe with a few flags. I'd prefer a solution that does point me to use any other third party library or sdk other than whats available in windows and ffmpeg.
Thanks for any help

A: If you have byte arrays, you must first convert those byte arrays to the correct sample format, such as 16-bit integer (short). Once you've done that, you have a few options, including:

*

*Average the data, sample-by-sample.

*Sum the data, sample-by-sample, and then "clip" any samples that are out of range.
The first option is the only correct way to do it without distorting your signal.
Finally, you may need to convert back to bytes to save to a file.
For more details, including code, you may want to see something more like a tutorial.

A: Assuming the two streams have the same sample rate and bits/sample you can just add the samples:
merged[n] = streama[n] + streamb[n];


text:
Q: Bound on spectral radius I've been struggling with a question. It goes as follows:
Given a matrix $A$ $$ \text{s.t. } \rho(A^TA)=1.$$ Prove: $$\rho((I-A^TA)(A^TA)^v)\le \frac{v^v}{(v+1)^{v+1}}$$
I've started thinking on a direction, but haven't been successful:
$A^TA$ is symmetric and PSD, all eigenvalues are real. The eigenvalues in question are all of the form $$ (1-\lambda_i)\lambda_i^v$$ where $\lambda_i$ is an eigenvalue of $A^TA$.
One of these values is zero, due to the known spectral radius, but how can I move towards that bound?

A: Presumably $v>0$. The condition $\rho(A^TA)=1$ and the fact that $A^TA\succeq0$ together imply that $0\le\lambda\le1$ for every eigenvalue $\lambda$ of $A^TA$. Now, let $f(\lambda)=(1-\lambda)\lambda^v=\lambda^v-\lambda^{v+1}$. Then $f'(\lambda)=v\lambda^{v-1}-(v+1)\lambda^v$. Therefore, when $f'(\lambda)=0$ only if $\lambda=0$ or $\lambda=\frac{v}{v+1}$. Since $f(0)=0<\frac{v^v}{(v+1)^{v+1}}=f(\frac{v}{v+1})$, the result follows.


text:
Q: integrate $\int \frac{dx}{1+cos^2x}$
$$\int \frac{dx}{1+\cos^2x}$$

I used $\cos x=\frac{1-v^2}{1+v^2}$ and $dx=\frac{2dv}{1+v^2}$
and got $$2\int \frac{dv}{v^4-v^2+1}=2\int \frac{dv}{(v^2-\frac{1}{2})^2+(\frac{\sqrt{3}}{2})^2}=\frac{4}{\sqrt{3}}arctan(\frac{2v^2-1}{\sqrt{3}})+c$$
How to continue?

A: An alternative method:
Multiplying through by $sec^2(x)$:
$$\int \frac{dx}{1+\cos^2x} = \int \frac{sec^2x}{1+sec^2x}dx$$
Defining $u = tanx$, $du = sec^2x$ $dx$, and using the identity $1+tan^2x = sec^2x$:
$$\int \frac{sec^2x}{1+sec^2x}dx = \int \frac{1}{u^2+2}du$$
The integral is now of the form of a very well-known $\arctan$ integral

A: Note that $\cos^2(x)=\frac{1+\cos(2x)}{2}$.  Then,
$$\int \frac{1}{1+\cos^2(x)}\,dx=\int \frac{2}{3+\cos(2x)}\,dx$$
Enforcing the substitution $x=u/2$ yields
$$ \int \frac{2}{3+\cos(2x)}\,dx=\int \frac{1}{3+\cos(u)}\,du \tag 1$$
Now, making the Weierstrass Substitution in $(1)$, as in the OP, we find
$$\int \frac{1}{1+\cos^2(x)}\,dx=\frac{1}{\sqrt 2}\arctan\left(\frac{\tan(u/2)}{\sqrt 2}\right)+C=\frac{1}{\sqrt 2}\arctan\left(\frac{\tan(x)}{\sqrt 2}\right)+C$$


text:
Q: Turtle Library in Python I am having a huge issue using the turtle library. I have to write my initials AR for an assignment. Can anyone help?
import turtle

turtlescreen

turtle.pos(400,400)
turtle.forward()

Here is the code I am trying to use. I am trying to right my initial "AR" with it.

A: You've managed to cram three errors into four lines of code.  First, you don't need this and it's an error:
turtlescreen

so toss it.  Second, the pos() function returns the current turtle postion, not set it.  So instead of:
 turtle.pos(400,400)

You want:
turtle.setpos(400, 400)

and finally, as @Jamie notes, you need to pass a distance (in pixels) to forward().  So instead of:
 turtle.forward()

Something like he suggests:
turtle.forward(15)

Complete code:
import turtle

turtle.setpos(400, 400)
turtle.forward(15)

turtle.done()

A: Your turtle.forward() requires an input variable in pixels. See the documentation for turtle.forward:

Move the turtle forward by the specified distance, in the direction the turtle is headed.

Try changing:
turtle.forward()
to something like:
turtle.forward(15)

A: There's a few mistakes I can see. Firstly, there is no command called turtlescreen so you can remove that. Next, instead of tom.pos try using tom.setpos(x, y) or tom.goto (x, y). Lastly, you should put a value in tom.forward (length). I also recommend going through the Python Turtle documentation, https://docs.python.org/3.3/library/turtle.html?highlight=turtle


text:
Q: Values initialized and set outside interrupt are zero within interrupt C++ on Xilinx Zynq I am experiencing a rather odd issue with my code where I have a value that I initialize in the main. Once I try to call that variable inside an interrupt it is 0. What am I missing here? Do different variables live within an interrupt?
I would like to note that this is a more theoretical question about interrupts and whether I can not share values between idle and interrupts.
Supervisor supervisor;
XScuTimer TimerInstance;
XScuGic IntcInstance;
uint32_t offset;

void interruptRoutine(void *CallBackRef) {

    // Define pointer to timer
    XScuTimer *TimerInstancePtr = (XScuTimer *) CallBackRef;

    // If timer is expired, clear interrupt status
    if (XScuTimer_IsExpired(TimerInstancePtr)) {
        XScuTimer_ClearInterruptStatus(TimerInstancePtr);

        // Why is offset 0 within the interrupt routine?
        xil_printf("Interrupt: %u\n", offset);

    }

}

//.. I omitted the interrupt init method ..//

int main() {

    while (true) {
        // Get all sensor data
        offset = 1;

    }

}


text:
Q: Use class constant as Ruby hash key I know I can use class as Hash key, but is it a good practice? Is there any drawbacks in terms of performance or testing?
{
  SomeClassA: 'hash value',
  AnotherClass: 'hash value'
}

A: {
  SomeClassA: 'hash value',
  AnotherClass: 'hash value'
}

Is actually equivalent to:
{
  :SomeClassA => 'hash value',
  :AnotherClass => 'hash value'
}

The keys are symbols. In the "new" literal hash syntax keys are just treated as literals which are cast into symbols (provided they are valid syntax).
To use constants, ranges or any other type of object you can dream up as keys you need to use hashrockets:
{
  SomeClassA => 'hash value',
  AnotherClass => 'hash value'
}

Is it a good practice?

Its a technique that could be used in few limited cases. For example to replace a series of if statements.
def foo(bar)
  if bar.is_a? SomeClassA
    'hash value'
  end
  if bar.is_a? AnotherClass
    'another value'
  end
end

def foo(bar)
  {
    SomeClassA => 'hash value',
    AnotherClass => 'another value'
  }[bar]
end

But I would rather use a case statement there anyways as its clearer in intent and more flexible.

Are there any drawbacks in terms of performance or testing?

Each hash you create would have keys that point to the exact same objects in memory just like if you where using symbols.
One big gotcha is that Rails monkey-patches const_missing to autoload files - when you reference a class name rails will load the file from the file system into memory. This is why you declare associations with:
class Foo < ApplicationRecord
  belongs_to :bar, class_name: "Baz"
end

It lets Rails instead lazy load Baz when needed. You would do the same with the example above by:
def foo(bar)
  {
    'SomeClassA' => 'hash value',
    'AnotherClass' => 'another value'
  }[bar.name]
end

A: That hash is using symbols, not classes, as keys, but you can use a Class by doing
hash = { SomeClassA => "some value" }

I can't think of why it would be worse than using any other object because

Classes in Ruby are first-class objects---each is an instance of class Class

So
{ SomeClassA => "some value" }

is functionally equivalent to
{ "Some String" => "some value" }

A: What you have there are not class keys but symbols.
Try
class A
end

class B
end

hash = {A: "Some", B: "Code"}
hash.keys[0].class
=> Symbol

But still A.class => Class
In case of symbol performance this POST is great
Also you can check ruby documentation about user-defined class as hash keys

A: While you can do it, I can't think of a reason for using it. Using a symbol or string as the key is much more efficient as the program does not have to load the whole class. (a side note, as pointed by others, your example in fact is using a symbol key, and you'll need to use a hash rocket to use a class name as the key)


text:
Q: Google Places API query 'opennow=true' returns 0 results (Node.js) I am querying the Google Places API with the following set-up:

*

*Backend: Radar Search Request via post-route (using Express and 'request'-module in Node.js)

*Frontend: Display results on map, querying Place Detail request after clicking on marker icon (example from API documentation as reference)
All works fine, except that my search request doesn't seem to pass on my restriction of 'only places currently open' via 'opennow=true' within search request. There are surely restaurants open in Amsterdam at the time I send this request, I manually checked it on GoogleMaps. I've been trying all different ways of spelling and searched for similar solutions, but can't find the problem. Any help very much appreciated, thank you.
Code for reference:

app.post('/results', function(req,res){

 //PARAMETERS FOR SEARCH QUERY FOR RESTAURANTS, OPEN NOW
 const baseurl = 'https://maps.googleapis.com/maps/api/place/radarsearch/json?';
 const location = 'location=52.370216,4.895168';
 const radius = 'radius=5000';
 const type = 'type=food';
 const key = 'key='+process.env.googleapikey;

 // const opennow = 'openNow=true'; //doesn't narrow down results, doesn't seem to get applied
 // const opennow2 = 'open_now=true'; //doesn't narrow down results, doesn't seem to get applied
 const opennow3 = 'opennow=true'; //0 search results returned, doesn't seem to work

 const queryurl = `${baseurl}${location}&${radius}&${type}&${key}&${opennow3}`;

 //SEARCH QUERY TO GOOGLE PLACES API, USING REQUEST MODULE
 request({
  uri: queryurl,
  method: "GET",
  timeout: 10000,
  followRedirect: true,
  maxRedireccts: 10
  }, function(err, response, body) {

   var allresults = [];

   if(err){
    console.log(err);
   } else {

    var responseparsed = JSON.parse(body);
    var results = responseparsed.results;

    for (var i = 0; i < results.length; i++) {
     allresults.push(results[i]);
    }
    console.log('Maps found >'+results.length+'< results');
   }
   res.render("results", {allresults: allresults, mapsjsapikey: mapsjsapikey});
  }
 )
});


text:
Q: If loop execution In the code below,
#include<stdio.h>
int main()
{
    int k,sum;
    for(k=7;k>=0;sum=k--)
        printf("%d \n",sum);

    return 0;
}

The output is:
0
7
6
5
4
3
2
1

I want to know how this loop executes and why isn't printing 0 in the last?

A: On first iteration sum is uninitialized. It has indeterminate value.
C11: 6.7.9 Initialization:

If an object that has automatic storage duration is not initialized explicitly, its value is
indeterminate.

Section 6.3.2.1 says that the behavior is undefined in this case.

A: In short, the sum variable is updated to be the same as k. After that update, k is decremented by 1 and then the loop runs
What that means is...
First loop, sum is uninitialised (hence the first 0)
the last time the loop runs, sum is set to k (1), k is decremented to 0. The loop runs. The condition is tested so the loop exits.
It all comes down the this: sum=k--. If you were to do sum=--k, k would be decremented before its value is assigned to sum.

A: Your program has undefined behaviour, since it is reading from an uninitialized variable in the first round of the loop (cf. C11 6.3.2.1/2).

A: Following code :
for(k =7; k >= 0; sum = k--)
   //your code here printf("%d \n",sum);

can be expanded as:
k=7;
for(; k >= 0; ){
   //your code here printf("%d \n",sum);
   sum = k--;
}

In first run sum is uninitialized so your program have undefined behavior.

A: Try this
 #include<stdio.h>
     int main()
      {
     int k=7,sum;
      for(sum=k=7;k>=0;sum=--k)

       printf("%d \n",sum);
      return 0;
       }

The loop starts by taking the initial value of the sum which in this case is by default equal to zero as a result the first iteration displays 0 however on the second iteration init of sum takes place and it starts from 7 to onward 0

A: When k=1 then value of k is assigned to sum and it gets decremented to 0 . Thus sum = 1 and k = 0.
Now k=0 and as per the loop condition k>=0 is true. So it enters into loop body and prints value of sum as 1 . Now value of k is get assigned to sum and k decrements . Thus sum = 0 and  k = -1 . But -1>=0 is false and loop execution stops .
Hence program is not printing 0 in the last.