text:
Q: Visualize manifold from the metric and extrinsic curvature? Is there some software or technique that would allow me to visualize a (2 dimensional) Riemannian manifold given its metric tensor and second fundamental form?
For instance, given
$$ g =d\theta^2 +\sin(\theta)^2 d\varphi^2$$
and
$$ K_{ab} \sim \begin{pmatrix}
a^2 & 0 \\
0 & \sin(\theta)^2
\end{pmatrix}$$
it would plot some oblong $\mathbb{S}^2$ type object.

A: Yes There is.
Please visit
Reconstructing a Surface from its Fundamental Form Coefficients.
Just note that the result comes by numerically solving differential equations and the file comes in Maple software format.


text:
Q: Small UIImage view in custom UICollectionViewCell I have UICollectionViewCell
#import "DBPhotoCollectionViewCell.h"
#define IMAGEVIEW_BORDER_LENGTH 5
    @implementation DBPhotoCollectionViewCell
    - (id)initWithFrame:(CGRect)frame
    {
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        [self setup];
    }
    return self;
}

/* Need to implement the initWithCoder method since this class will be created from the storyboard */
-(id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];

    if (self){
        [self setup];
    }
    return self;
}

/* Create the UIImageView and add it to the cell's contentView in code. */
-(void)setup
{
    self.imageView = [[UIImageView alloc] initWithFrame:CGRectInset(self.bounds, IMAGEVIEW_BORDER_LENGTH, IMAGEVIEW_BORDER_LENGTH)];
    [self.contentView addSubview:self.imageView];
}

@end

And call this Cell from CollectionViewController class
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Photo Cell";

    DBPhotoCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
    cell.imageView.image = [UIImage imageNamed:@"Astronaut.jpg"];
    // Configure the cell

    return cell;
}

But I have one problem when I start my application my picture is showed with small size. What I missed?
http://screencast.com/t/ia8tE05P6yc
http://screencast.com/t/33N4AhT7

A: cell.imageView, imageView object is not same as which you have added on cell of Interface Builder. UICollectionViewCell has default size UIImageView which are accessing, you can access your customView imageView in cellForIndexPath method of collectionView by linking imageView of subClass DBPhotoCollectionViewCell in interface builder you don't need to add  [self.contentView addSubview:self.imageView]; in setup method.
Second approach would be assign tag value to imageView when you adding to cell contentView
/* Create the UIImageView and add it to the cell's contentView in code. */
-(void)setup
{
    self.imageView = [[UIImageView alloc] initWithFrame:CGRectInset(self.bounds, IMAGEVIEW_BORDER_LENGTH, IMAGEVIEW_BORDER_LENGTH)];
self.imageView.tag=1;
    [self.contentView addSubview:self.imageView];
}

//And access imagView in cellForIndexPath

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Photo Cell";

    DBPhotoCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
   UIImageView *imageView=[cell.contentView viewWithTag:1];
    imageView.image = [UIImage imageNamed:@"Astronaut.jpg"];
    // Configure the cell

    return cell;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: pushing data inside an existing empty array Basically I have an main object dataToMovie, I have empty arrays. I want to display the content of the arr variable into mov[] and the content of the arr2 into ser[]. I have attempted to do something as you can see. I am looking to do this seperately for each array as I will have multiple data in the future
const dataToMovie = {
  createMovie,
  links: {
    mov: [],
    ser: [],
    rev: [],
    ext: [],
  },
};

const dataToInsert1 = {
  'model-10389': 164703,
  'model-10388': 164704,
  'model-10387': 164705,
};

const dataToInsert2 = {
  'model-10389': [1656, 1234, 1245],
  'model-10384': [1656, 1234, 1245],
  'model-10383': [1656, 1234, 1245],
};

const arr = Object.entries(dataToInsert1).map((entry) => ({
  id: entry[0].substring(6, entry[0].length),
  value: entry[1],
}));

//dataToMovie.links.mov[arr]

const arr2 = Object.entries(dataToInsert2).map(([key, value]) => ({
  modelId: key.substring(6),
  ids: value,
}));

//dataToMovie.links.ser[arr2]

A: concat is a good candidate for this operation. it returns a merged array.
dataToMovie.links.mov = dataToMovie.links.mov.concat( arr )
dataToMovie.links.ser = dataToMovie.links.set.concat( arr2 )

A: You are close. if the arrays are empty you can just do:
dataToMovie.links.mov = arr
dataToMovie.links.ser= arr2

If the arrays have items in them and you just want to add to them, you can use the spread operator
dataToMovie.links.mov = [...dataToMovie.links.mov, ...arr]
dataToMovie.links.ser = [...dataToMovie.links.ser, ...arr2]


text:
Q: Why is changing protected access in a base class to public access in a derived class allowed? In TypeScript this is legal code:
class Animal {
    name: string;

    constructor(theName: string) {
         this.name = theName;
    }

    protected move(distanceInMeters: number = 0) {
        console.log(`${this.name} moved ${distanceInMeters}m.`);
    }
}

class Snake extends Animal {
    constructor(name: string) {
         super(name);
    }

    move(distanceInMeters = 5) {
        console.log("Slithering...");
        super.move(distanceInMeters);
    }
}

class Horse extends Animal {
    constructor(name: string) {
         super(name);
    }

    move(distanceInMeters = 45) {
        console.log("Galloping...");
        super.move(distanceInMeters);
    }
}

However this would be illegal in C#, for example. Going from public to protected is not allowed in TypeScript, however.
What is the rationale for allowing a protected function to be exposed as a public function in a derived class? Coming from C# and Java, it doesn't make sense to me to allow the access level of a member to be changed at all.

A:
What is the rationale for allowing a protected function to be exposed as a public function in a derived class

It is allowed because its not disallowed. You are simply getting what you write (and since you didn't write the child became public as that is the default).
More
Language Design https://blogs.msdn.microsoft.com/ericgu/2004/01/12/minus-100-points/

Going from public to protected is not allowed in TypeScript, however.

For good reason. Consider the following
class Animal {
    name: string;

    constructor(theName: string) {
         this.name = theName;
    }

    move(distanceInMeters: number = 0) {
        console.log(`${this.name} moved ${distanceInMeters}m.`);
    }
}

class Snake extends Animal {
    constructor(name: string) {
         super(name);
    }

    protected move(distanceInMeters = 5) { // If allowed
        console.log("Slithering...");
        super.move(distanceInMeters);
    }
}

let snake = new Snake('slitherin');
snake.move(); // ERROR
let foo: Animal = snake;
foo.move(); // HAHA made my way around the error!


text:
Q: metastore_db created wherever I run Hive Folder metastore_db is created in any directory where I run Hive query. Is there any way to have only one metastore_db in a defined location and stop it from being created all over the places? Does it have anything to do with hive.metastore.local?

A: Since you use Embedded derby mode. To use single metastore_db location. you need to change following properties.
<property>
  <name>javax.jdo.option.ConnectionURL</name>
  <value>jdbc:derby:;databaseName=/<file-location>/metastore_db;create=true</value>
  <description>JDBC connect string for a JDBC metastore</description>
</property>

I hope this will help you. For more details click here

A: The property of interest here is javax.jdo.option.ConnectionURL. The default value of this property is jdbc:derby:;databaseName=metastore_db;create=true. This value specifies that you will be using embedded derby as your Hive metastore and the location of the metastore is metastore_db. Also the metastore will be created if it doesn't already exist.
Note that the location of the metastore (metastore_db) is a relative path. Therefore, it gets created where you launch Hive from. If you update this property (in your hive-site.xml) to be, say an absolute path to a location, the metastore will be used from that location.
I must warn you though that embedded derby metastore can only be accessed by one user at a time. Hive uses embedded derby by default to allow an out of the box experience and for ease of testing. For any practical system, I would recommend moving to standalone "real" database like MySQL or PostgreSQL. Instructions on how to do that are available here.


text:
Q: Invoke POST operation in different parts of app, by utilising factory generated functions from a service I'm setting up something to persist data on individual events that occur within a user 'transaction' (session) within an application.
I'm creating something that allows a different POST operation for each event, with a generic method of posting, that uses different payloads for each event. I want to be able to record events in different parts of the application by importing a collection of operations from a service, then invoking different operations within the collection.
I'm posting what I've done so far. transactionEvents is created using a factory pattern, through calling the function makeTransactionEvents.
How can I can call the userPressedButton POST operation in myRoute.svelte?
service.js
/**
 * Performs the equivalent of Array.prototype.map() on an object.
 *
 * @param {object} obj - The object to map.
 * @param {Function} func - The function to execute on each item in the object.
 * @returns {object} The new object resulting from the map.
 */
function objectMap(obj, func) {
  return Object.fromEntries(
    Object.entries(obj).map(([key, value], index) => [
      key,
      func(value, key, index),
    ])
  );
}

const eventPayloads = {

  userPressedButton() {
    return {
      eventType: TRANSACTION_EVENT_TYPES.UserAction,
      eventSubType: TRANSACTION_EVENT_SUBTYPES.PressedButton
    }
  },

  userDidSomethingElse() {
    return {
      eventType: TRANSACTION_EVENT_TYPES.UserAction,
      eventSubType: TRANSACTION_EVENT_SUBTYPES.DidSomethingElse
    }
  }
};

/**
 * Create a 'transactionEvent' service call function.
 *
 * Sends the request.
 *
 * @param {Function} payloadFunc - Function for creating the payload.
 * @returns {Function} - Initialises creation of TransactionEvent.
 */
function makeTransactionEvent(payloadFunc) {
  return (...args) => {
    initialiseTransactionEvent(payloadFunc(...args));
  };
}

/**
 * Creates functions for each of the reporting transactionEvent payloads.
 */
function makeTransactionEvents() {
  return objectMap(eventPayloads, (payloadFunc) => makeTransactionEvent(payloadFunc));
}

function initialiseTransactionEvent(body) {
  logger.info(`Recording transaction event.`);
  fetch(myUri, {
    method: 'POST',
    .... other http stuff
    body: JSON.stringify(body),
  })
}

const transactionEvents = makeTransactionEvents();

export default {
  ...transactionEvents,
}

myRoute.svelte
import { transactionEvents } from 'service.js';

** How do I call userPressedButton() by referencing its key within transactionEvents ? **

A: I realised that the spread transactionEvents is being exported as a constant which represents the default. With name independence of namespacing for an import, I can reference the constant in myRoute.svelte like this:
import dataPersister from 'service.js';

Then simply call userPressedButton() with:
dataPersister.userPressedButton()


text:
Q: Real world uses or interesting facts about/for Associahedron or Permutohedron I'm doing a small research project into these but their Wiki page and other pages I've looked at just detail what they are, and their properties.
Does anyone know of any real world applications or some interesting facts besides their properties?

A: For some interesting connections of the combinatoric relations underlying the structure of these polytopes to other areas of mathematics, see
1) Why is there a connection between enumerative geometry and nonlinear waves?
2) Relating face polytopes of permutohedra to integer partitions
3) Why do polytopes pop up in Lagrange inversion?
4) Guises of the Stasheff polytopes, associahedra ...
5) Important formulas in combinatorics
6) What is Lagrange inversion good for?
For me, the most interesting connections follow from the relations to multiplicative and compositional inversion.


text:
Q: FLRW metric for flat universe To derive the FLRW metric, we first make the assumption of isotropy and homogeneity of the universe. This enables us to write our general metric tensor in the following form:
$$ds^2 = c^2g_{00}(t)dt^2-dl^2$$
where $dl$ is the line element for a spacial surface. I am interested here in the case of a flat universe. As far as I understand, this means $dl^2 = dx^2+dy^2+dz^2$. Defining $t'$ such that $dt' = \sqrt{g_{00}}dt$, we get
$$ds^2 = c^2dt'^2-(dx^2+dy^2+dz^2)$$
which is clearly wrong since it is Minkowskian, and according to the internet the solution should be $ds^2 = c^2dt^2 - a^2(t)(dx^2+dy^2+dz^2)$ for the FLRW metric in the flat universe case. I have clearly a misunderstanding of either $dl^2$ or the validity of my change of variables; I suspect the latter. Where did I go wrong?
Everywhere I look for a detailed derivation of the FLRW metric, they do it for the case of a spherical universe, and then take some kind of limit for the radius $R$ which does not help me very much.


text:
Q: Django: Call function once on login I implemented Segment.io in my Django application. Once the user logs in I have to call analytics.identify once.
Currently, I call it every time on every page load as long {% if user.is_authenticated %} is the case. Do you have any idea how I can only call it once after the user logged in?
<script type="text/javascript">
  {% if user.is_authenticated %}
    analytics.identify('{{ user.email }}', {
      'first_name': user.first_name,
      'last_name': user.last_name,
    });
  {% endif %}
</script>

A: The way I would implement this is:

*

*Change your 'login' view (the one that calls authenticate and login) to return a page, rather than a redirect.

*This page would have the script tag you've mentioned above, as well as a meta refresh redirect to the main page (or wherever you want the user to go)

A: You can set a cookie in your response object so that in the next page load you can avoid rendering the call to analytics.identify if that cookie is set:
def view(request):
    template = loader.get_template('polls/index.html')
    context = {'user_unidentified': 'user_identified' not in request.COOKIES}
    response = HttpResponse(template.render(context, request))
    if 'user_identified' not in request.COOKIES:
        response.set_cookie('user_identified', '1')
    return response

Then in your template:
<script type="text/javascript">
  {% if user_unidentified %}
    analytics.identify('{{ user.email }}', {
      'first_name': user.first_name,
      'last_name': user.last_name,
    });
  {% endif %}
</script>

A: You can use django signals for this. Put this code in your models.
from django.contrib.auth.signals import user_logged_in

def do_stuff(sender, user, request, **kwargs):
    whatever...

user_logged_in.connect(do_stuff)

for more information, check out
https://docs.djangoproject.com/en/dev/ref/contrib/auth/#module-django.contrib.auth.signals and http://docs.djangoproject.com/en/dev/topics/signals/
Original Answer: https://stackoverflow.com/a/6109366/4349666


text:
Q: Connection string not found with ASP.net I'm trying to get my local SQL database connecting to my ASP.Net project and nothing I try is working.
The database is named cinemaDatabase and its using windows authentication.
In web.config I have
   <connectionStrings>
    <add name="myDatabase" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=cinemaDatabase;Integrated Security=True;" providerName="System.Data.SqlClient" />
  </connectionStrings>

Then in a cshtml page I have
@using WebMatrix.Data;

@{
    var db = Database.Open("myDatabase");
 }

I keep getting this error

InvalidOperationException: Connection string "myDatabase" was not
  found. OpenNamedConnection

What am I doing wrong here? Thanks in advance.
Edit -
Got it working, had to make a normal SQL server instead of the local MSSQLLocalDB one and change the data source in web.config to that.
Then used this code on my page and it connects now.
@using WebMatrix.Data;
@using System.Data.SqlClient;

@{

    var connectionString = "Data Source=DESKTOP-58NGNQP;Initial Catalog=webDev;Integrated Security=True";
    var providerName = "System.Data.SqlClient";
    var db = Database.OpenConnectionString(connectionString, providerName);
}

A: I believe the problem is with your connection string. Unfortunately, I don't have a running example right this moment with an attached .mdf file, but I believe something like this will do the job for you, I grabbed this string from MSDN's article on connection strings
<add name="ConnectionStringName"
providerName="System.Data.SqlClient"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFileName=|DataDirectory|\DatabaseFileName.mdf;InitialCatalog=DatabaseName;Integrated Security=True;MultipleActiveResultSets=True" />

Couple of important facts here:

*

*Data Source=(LocalDB)\v11.0 - This specifies the start-on-demand localdb instance to use. Note that the version, v11.0 in this string, varies from installation to installation, and you should find the correct version for your string. (You should be able to find it easier below)

*AttachDbFilename=|DataDirectory|\DatabaseFilename.mdf - this tells LocalDb to load that database file. Alternatively, localdb persists database files in your user home directory, or AppData directory somewhere.

*Integrated Security=true - A connection string needs an authentication scheme. Two possible options are Integrated Security, which uses your windows credentials to attempt access to your database, which works well with many things, LocalDb being one of them. Another option is to use sql authentication and a sql name and password to connect.


text:
Q: C# Unity - Assigning data to array containing classes - Thought I was doing it right I'm using Unity2D and coding in C#. I have a class 'TileInfoArray' which holds an array of 'TileInfo' classes. 'TileInfo' contains a bunch of data for the game's tilemap including what sprite should be shown, the movement cost, etc.
Sample of 'TileInfoArray':
   public class TileInfoArray {
         private TileInfo[] arr;
         . . .
        public void SetSprite(int index, Sprite sprite) {
            arr[index].sprite = sprite;
        }
    }

This code is called with a simple
'world.tileInfoArray.SetSprite(index, sprite_Cobblestone);', yet later when I call 'world.tileInfoArray[index].sprite' for that same index, I get the default sprite I used when I created the array.
tileInfoArray = new TileInfoArray(WorldSizeTiles);
tileInfoArray.Populate(new TileInfo());

If anyone was interested. 'Populate' just calls a for loop that adds starting data.
I'm confused as to why this is. I have verified that the indexes are always within range and mapped correctly, and the array starts with assigned default data. I'm aware that something like 'TileInfoArray array = world.tileInfoArray' would just copy the data, and trying 'array[index].sprite = newSprite' wouldn't affect the original 'world.tileInfoArray', but since I'm calling a method from the class that holds the array, shouldn't that then change its data?
Any help would be much appreciated. I will be out of town for the weekend, but I'll be back first thing Monday to answer any questions and hopefully just look like a big dummy for missing an obvious mistake.


text:
Q: Fit a curve with a SIR model and predict I have searched and referenced the code for solving the SIR model from others on this website, but the fitting effect is very poor. Is there something wrong with my data? Still what? How should I predict given new data for this SIR model?
    import numpy as np
    import matplotlib.pyplot as plt
    from scipy import integrate, optimize
    import pandas as pd

    y_total = [0.0, 0.0010131712259371835, 0.0035460992907801418, 0.00911854103343465,
        0.008611955420466059, 0.021783181357649443, 0.00911854103343465, 0.07852077001013172, 0.4397163120567376,
        0.21681864235055726, 0.232016210739615, 0.5278622087132725, 0.13576494427558258, 0.2988855116514691, 0.37436676798378926,
        0.4209726443768997, 0.544579533941236, 0.7254305977710233, 1.0, 0.7740628166160081, 0.43617021276595747, 0.48226950354609927]

    x_total = range(0,22)
    ydata = np.array(y_total, dtype=float)
    xdata = np.array(x_total, dtype=float)

    # IO + SO + R0 is always 1 regardless of "value"
    I0 = 0.3
    S0 = 1 - I0
    R0 = 0

    def sir_model(y, x, beta, gamma):
        S = -beta * y[0] * y[1] / N
        R = gamma * y[1]
        I = -(S + R)
        return S, I, R

    def fit_odeint(x, beta, gamma):
        return integrate.odeint(sir_model, (S0, I0, R0), x, args=(beta, gamma))[:,1]

    N = 1.0
    I0 = ydata[0]
    S0 = N - I0
    R0 = 0.0

    popt, pcov = optimize.curve_fit(fit_odeint, xdata, ydata)
    fitted = fit_odeint(xdata, *popt)

    plt.plot(xdata, ydata, 'o')
    plt.plot(xdata, fitted)
    plt.show()

A: Make the initial infected number also a variable, which is easily done by shift the computation of the initial state into the target function

    def sir_model(y, x, beta, gamma):
        N = sum(y)
        S = -beta * y[0] * y[1] / N
        R = gamma * y[1]
        I = -(S + R)
        return S, I, R

    def fit_odeint(x, beta, gamma, I0):
        # IO + SO + R0 is always 1 regardless of "value"
        S0 = 1 - I0
        R0 = 0
        return integrate.odeint(sir_model, (S0, I0, R0), x, args=(beta, gamma))[:,1]

    popt, pcov = optimize.curve_fit(fit_odeint, xdata, ydata,(1/5,1/8,0.1))

There were some other changes, especially adding an initial guess to curve_fit. Still this gets a warning on some difficulty in odeint. But a result is reached anyway, with popt = [0.36714402, 0.04176973, 0.01311579], 1/popt = [2.72372678, 23.94078424, 76.2439491]. Changing the initial guess to values close to this, (1/3, 1/24, 0.05), eliminates the warning.


text:
Q: Matlab: create band matrix with repeating and alternating values Let us say that I have 7 values: a, b, c, d, e, f and g
I would like to construct an m by n matrix in this way:
[ a b c d 0 0 0 0 . . . .
[ b e f g 0 0 0 0 . . . .
[ c f a b c d 0 0 . . . .
[ d g b e f g 0 0 . . . .
[ 0 0 c f a b c d 0 0 . .
[ 0 0 d g b e f g 0 0 . .
[ . . 0 0 c f a b c d . .
[ . . 0 0 d g b e f g . .

And so forth...
Therefore, the desired matrix is symmetrical. Values a and e alternate on the main diagonal; values b and f alternate on the 1st upper diagonal; values c and g alternate on the 2nd upper diagonal; values d and 0 alternate on the 3rd upper diagonal. I would like to be able to specify the matrix size with m by n parameters.
I used to do this easily with the SparseArray and Band functions in Mathematica, but I cannot find equivalent functions in Matlab. Would there be an efficient way to construct this kind of matrix in Matlab?

A: You can use spdiags to specify the upper diagonals in a sparse matrix and then add the transpose of the strictly upper triangular part for exact symmetry:
>> n  = 6;
>> a = 1;b = 2;c = 3;d = 4;e = 5;f = 6;g = 7;
>> n  = 6;
>> A = spdiags(repmat([[a;e] , [f;b] , [c;g] , [0;d]],n/2,1),0:3,n,n);
>> A = A + triu(A,1).';
>> issymmetric(A)
ans =
     1
>> full(A)
ans =
     1     2     3     4     0     0
     2     5     6     7     0     0
     3     6     1     2     3     4
     4     7     2     5     6     7
     0     0     3     6     1     2
     0     0     4     7     2     5

You might notice I flipped b/f and 0/d to adjust for the filling behavior; there may be a better way to do this.

For non-square matrices with potentially odd dimension number, I would build the minimum-sized square sparse matrix that has the actual one as a sub-matrix and mask out the unneeded portion at the end:
>> m = 13;
>> n = 6;
>> p = max([m,n]);
>> p = p + mod(p,2); % added to make p even.
>> A = spdiags(repmat([[a;e] , [f;b] , [c;g] , [0;d]],p/2,1),0:3,p,p);
>> A = A + triu(A,1).';
>> A = A(1:m,1:n);
>> full(A)
ans =
     1     2     3     4     0     0
     2     5     6     7     0     0
     3     6     1     2     3     4
     4     7     2     5     6     7
     0     0     3     6     1     2
     0     0     4     7     2     5
     0     0     0     0     3     6
     0     0     0     0     4     7
     0     0     0     0     0     0
     0     0     0     0     0     0
     0     0     0     0     0     0
     0     0     0     0     0     0
     0     0     0     0     0     0

It's a tad inefficient to build, but easy and straight-forward.

A: You can use the spdiags function
Using numbers instead of letters (sparse does not support symbols) like this:
m = 10;
n = 10;
B = repmat([1:4;[5:7 0]],n/2,1);
B=[B(:,end:-1:2) B];
d=-3:3;
A = spdiags(B,d,m,n);
full(A)

which outputs:
 1     6     3     0     0     0     0     0     0     0
 2     5     2     7     4     0     0     0     0     0
 3     6     1     6     3     0     0     0     0     0
 4     7     2     5     2     7     4     0     0     0
 0     0     3     6     1     6     3     0     0     0
 0     0     4     7     2     5     2     7     4     0
 0     0     0     0     3     6     1     6     3     0
...

Explanation:
The B matrix contains the values needed on the diagonals in its columns. It is first constructed using B = repmat([1:4;[5:7 0]],n/2,1); which makes the first two rows repeat n/2 times. At that point it looks like:
 1     2     3     4
 5     6     7     0
 1     2     3     4
 5     6     7     0
 1     2     3     4
 5     6     7     0
 1     2     3     4
...

Then it is mirrored to give it the diagonals that are in the lower diagonal part using B=[B(:,end:-1:2) B]; which makes it look like:
 4     3     2     1     2     3     4
 0     7     6     5     6     7     0
 4     3     2     1     2     3     4
 0     7     6     5     6     7     0
 4     3     2     1     2     3     4
 0     7     6     5     6     7     0
 4     3     2     1     2     3     4
 ...

These are the diagonals passed to the spdiags function.
The end is a MATLAB keyword which refers to the last column or row. That indexing line says, in words: "Take all the rows of B, and the columns starting from the end, going back 1 step at a time until the second column, and place that submatrix before B." That is how the mirroring is accomplished.


text:
Q: Make list in decsending order of length of dataset I have 3 dataset namely pc_dat, rf_dat & co_dat:
pc_dat
User Val
A     21
B     22

rf_dat
User Val
A     41
B     52
C     45

co_dat
User Val
A     89

If I get following:
length(pc_dat)
[1] 2

length(rf_dat)
[1] 3

length(co_dat)
[1] 1

Then I want to create a list which will automatically takes datasets with descending order of lengths i.e. rf_dat will appear first, pc_dat second and co_dat third as shown below:
list_data = list(rf_dat, pc_dat, co_dat)

A: We place the datasets in a list using ls and mget, then order in descending by getting the number of rows in the list
list_data <- mget(ls(pattern ="_dat$"))
list_data[order(-sapply(list_data, nrow))]
#$rf_dat
#  User Val
#1    A  41
#2    B  52
#3    C  45

#$pc_dat
#  User Val
#1    A  21
#2    B  22

#$co_dat
#  User Val
#1    A  89

Just to be safe, order also have decreasing = TRUE argument


text:
Q: On what criterion compiler chooses one of the overloaded method What is the formal reason of prefering one to method to the other(by compiler)?
Why it chooses first one for bytes etc. I know that int can represent bytes, but float also. Why is it so formally?
public class MethodCurrier {

    public void setValue(int wrt){//naglowek
        System.out.println("Typ int "+ wrt);
    }
    public void setValue(float wrt){//naglowek
        System.out.println("Typ float "+ wrt);
    }
    public static void main(String[] args) {
        MethodCurrier currier = new MethodCurrier();
        currier.setValue(4);//int
        currier.setValue(2.3f);//float
        currier.setValue('c');//char
        currier.setValue((byte)4);

    }
}

A: The Java Language Specification defines this as follows:

If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.
The informal intuition is that one method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time type error.

In your case, the int method is more specific than the float method, because an int can be implictly converted to a float, but not vice versa.

A: Because the Java Language Specification says so.


text:
Q: Update python from 3.5 to 3.6 in conda I want to upgrade my python version from 3.5 to 3.6 to use the new features.
I first copy the base env as base3.6 using Clone base environment in anaconda,
then I want to upgrade the python3.5 to 3.6 using conda install python=3.6, but I have this error
(base3.6) D:\Desktop\GOC-VRPTW-master>conda install python=3.6
Solving environment: failed

UnsatisfiableError: The following specifications were found to be in conflict:
  - defaults/win-64::psutil==4.3.1=py35_0 -> python=3.5 -> python_abi=[build=*_cp35m] -> pypy[version='<0a0']
  - python=3.6
Use "conda info <package>" to see the dependencies for each package.

Similar problem, but different in details conda install python=3.6 UnsatisfiableError

A: I find that reinstalling a new environment is a better choice.


text:
Q: Power Series solution of $y''+x^3y'+3x^2y=0$. Power Series solution of the following differential equation:
$$y''+x^3y'+3x^2y=0$$
I started with $y = \sum_{n=0}^{\infty}a_nx^n$, then $y' = \sum_{n=1}^{\infty}na_nx^{n-1}$ and  $y'' = \sum_{n=2}^{\infty}n(n-1)a_nx^{n-2}$, then, $$y''+x^3y'+3x^2y= \sum_{n=2}^{\infty}n(n-1)a_nx^{n-2}+\sum_{n=1}^{\infty}na_nx^{n+2}+3\sum_{n=0}^{\infty}a_nx^{n+2}$$
but unable to proceed further held needed.
I have also observed that $y''+x^3y'+3x^2y= y''+(x^3y)'$.

A: Collect like terms
\begin{align}
y''+x^3y'+3x^2y&= \sum_{n=2}^{\infty}n(n-1)a_nx^{n-2}+\sum_{n=1}^{\infty}na_nx^{n+2}+3\sum_{n=0}^{\infty}a_nx^{n+2}
\\&=
\sum_{n=0}^{\infty}(n+2)(n+1)a_{n+2}x^{n}
+\sum_{n=3}^{\infty}(n-2)a_{n-2}x^{n}
+3\sum_{n=2}^{\infty}a_{n-2}x^{n}
\\ &=
\big[2a_2\big] + \big[6a_3\big]x + \big[12a_4+3a_0\big]x^2
+\sum_{n=3}^\infty \big[(n+2)(n+1)a_{n+2} +(n+1)a_{n-2}\big]x^n
\end{align}
So to get $0$ as the result, all coefficients must be zero:
\begin{align}
2a_2 &= 0
\\
6a_3 &= 0
\\
12a_4+3a_0 &= 0
\\
(n+2)(n+1)a_{n+2} +(n+1)a_{n-2} &= 0\quad\text{for }n\ge 3
\end{align}
So $a_0, a_1$ are arbitrary, $a_2 = a_3 = 0$, $a_4=-a_0/4$,
$$
a_k = -\frac{1}{k}a_{k-4}\quad\text{for }k \ge 5
$$

A: Another way to do it.
When I was a student, we were taught to never change the index. So, the way we did it :
$$y = \sum_{n=0}^{\infty}a_nx^n\qquad y' = \sum_{n=0}^{\infty}na_nx^{n-1}\qquad y'' = \sum_{n=0}^{\infty}n(n-1)a_nx^{n-2}$$
$$y''+x^3y'+3x^2y=\sum_{n=0}^{\infty}n(n-1)a_nx^{n-2}+\sum_{n=0}^{\infty}na_nx^{n+2}+3\sum_{n=0}^{\infty}a_nx^{n+2}$$ that is to say
$$y''+x^3y'+3x^2y=\sum_{n=0}^{\infty}n(n-1)a_nx^{n-2}+\sum_{n=0}^{\infty}(n+3)a_nx^{n+2}$$
Now, to have the coefficient for $x^m$, the first summation requires $n-2=m$ that is to say $n=m+2$ and the second summation requires $n+2=m$ that is to say $n=m-2$. So,
$$(m+2)(m+1)a_{m+2}+(m+1) a_{m-2}=0\implies a_{m+2}=-\frac {a_{m-2}} {m+2}$$
Now, make $m+2=k$ that is to say $m=k-2$ to get
$$a_k=-\frac {a_{k-4}} k$$
For sure, you need to identify the very first coefficients $a_0,a_1,a_2,a_3,a_4$ but this is simple as already shown in GEdgar's answer.


text:
Q: Left align a rotated text inside a flex I have a card like structure in a webpage. Each card is a graph. I need to display the y axis label for each graph for any aspect ratio of cards.
HTML

Test 1

test y lable

          <Graph class="graph">(This is the graph)</Graph>

test x lable

Test 2

test y lable

          <Graph class="graph">(This is the graph)</Graph>

test x lable

CSS
.graphAxisY{
  transform-origin: 0% 0%;
  transform: rotate(270deg) translate(-22%, 25%);
  background-color: transparent;
  z-index: 100;
}
.grid{
  display: grid;
  grid-template-columns: repeat(auto-fit,33%);
}
.chart{
  display: flex;
  flex-direction: column;
  padding-right: 0.8vw;
}

Result is fine when the aspect ratio of graphs is 4

Results is not fine when aspect ratio of a graph is 1

Notice the Y label text is not centered in vertical axis. How can I put the Y axis label for a flex box with a variable aspect ratio?

A: Could you change the chart display actually to "flow-root" instead, like so?:

.graphAxisY {
  transform-origin: 0% 0%;
  transform: rotate(270deg) translate(-33%, 0%);
  background-color: transparent;
  z-index: 100;
}

.graphAxisX {
  text-align: center;
}

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, 33%);
}

.chart {
  display: flow-root;
  flex-direction: column;
  padding-right: 0.8vw;
}

.graph {
  padding: 0% 15% 25% 15%;
  display: flex;
}

Test 1

test y label

    <Graph class="graph">(This is the graph)</Graph>

test x label

Test 2

test y label

    <Graph class="graph">(This is the graph)</Graph>

test x label


text:
Q: How to not lose line breaks when sending a text via post Hey I have the following problem: I want to send some text from a textarea per POST to a php script which writes it in a file and displays it on the website. But when I do this the line breaks disappear and the displayed text looks kind of ugly.
JS:
let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
    if (this.readyState === 4) {
        document.querySelector(".displayMessage").innerHTML = this.responseText;
    }
};

xhttp.open("POST", "submitMessage.php", true);
xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

let params = "message=" + document.querySelector("#nachricht").value;
xhttp.send(params);

php
<?php
if (isset($_POST['message']) && $_POST['message'] != "") {
   $write = fopen('counter/message.txt', 'w');
   fwrite($write, $_POST['message']);
}

echo $visitors = file_get_contents('counter/message.txt');

A: Try to apply the below css on the div or the element in which you show the text.
div {
    white-space: pre-wrap;
}

Example:

function display() {
 let elem = document.getElementById('content');
 document.getElementById('display').innerHTML = elem.innerHTML;
}
div {
        white-space: pre-wrap;
}
<textarea id="content">This is some text   with some extra spacing    and a
    few newlines along with some trailing spaces
         and five leading spaces thrown in
    for                                              good
    measure   </textarea>

  <button onclick="display()">Display</button>


text:
Q: magnetic effect in scrollView I am displaying a series of images in a (vertical) ScrollView. The idea is that it resembles some kind of thumbwheel.
I would like to have the scrollView "stop" or "click" at certain intervals, like it 'captures' the nearest position with a magnetic effect. You see this magnetic capture effect many times in image galleries.
Are there any specific attributes to this scrollview that enables this effect?
Probably not, because I searched this intensively. But ya never know...
If not, is it possible to implement this in Java code?
Or any other tips - perhaps not using ScrollView?

A: Check out RealViewSwitcher. It should work the way you want after a few modifications


text:
Q: Initializing a Module mixed in to a Model I have this:
class Bullet < ActiveRecord::Base
  include StagedVersionMethods
  ...
end

And this
module StagedVersionMethods
  def initialize
    puts self.bullet_id
  end
end

When I create an instance of Bullet, the modules initialize method fires, but I get an ActiveRecord error:
...activerecord-2.2.2/lib/active_record/attribute_methods.rb:268:in `read_attribute'
My intent is to initialize an instance variable for which I need the primary key value of the record I'm mixing into. Other methods in the module will then work with this instance variable.
The module included() callback does not fit the task either, because self, in that context, is the Module not the AR record.
How should this be approached?
Thanks

A: Overiding the initializer on ActiveRecord can have strange side effects that prove difficult to debug, so it's not recommended. The recommended approach would be to use the :after_initialize callback that ActiveRecord provides instead. You can still mix this behaviour in via a module...
module MyCleverMixin

  def after_initialize
    puts "I'm Initializing!"
  end

end

class MyModel < ActiveRecord

  include MyCleverMixin

end

A: If you define initialize like:
def initialize(*atts)
  super(*atts)
  puts self.bullet_id
end

then I think it will do what you want as it will set up the object correctly for you using the ActiveRecord initialization first. However, I'm not sure how robust that approach is for what you're trying to achieve. It might be more appropriate to create this instance variable when it is accessed rather than when the object is initialized.
It's kind of hard to say without knowing what you want the instance variable to do though.


text:
Q: Problem with CREATE SECURITY POLICY in SQL Server 2014 SP3 I'm trying to create a security policy with this query:
CREATE SECURITY POLICY Security.DegreeFilter
ADD FILTER PREDICATE Security.fn_securitypredicate(Degree) ON Students
WITH (STATE = ON);

But I get this error:

Msg 343, Level 15, State 1, Line 1
Unknown object type 'SECURITY' used in a CREATE, DROP, or ALTER statement.
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near 'FILTER'.

I'm using SQL Server 2014 SP3.
SELECT @@version returns Microsoft SQL Server 2014 (SP3).
compatibility_level for my database is 120.

A: According to the Documentation
CREATE SECURITY POLICY only applies to SQL Server 2016 (13.x) and later


text:
Q: pymongo with flask I am trying to return my posts, but instead I get

TypeError: 'Cursor' object is not callable.

How can I correct this? Here is my code:
from flask import Flask
from flask.ext.pymongo import PyMongo
app = Flask(__name__)
mongo = PyMongo(app)
from pymongo import Connection
connection = Connection()
db = connection.test_database
collection = db.test_collection

@app.route('/')
def home_page():
   post = {"author":"mike","text":"jiii"}
   posts = db.posts
   posts.insert(post)
   return posts.find()

if __name__=='__main__':
   app.run(debug=True)

A: When you return something from a Flask handler it must be one of the following types of things:

*

*A flask.Response object (or a werkzeug.wrappers.Response object). Using Flask's render_template will return a response object.

*A tuple in the form (content, status_code, headers)

*A WSGI callable (A function or callable object that takes two params and returns an iterable).

When you return the PyMongo Cursor object Flask sees that it is not an instance of flask.Response (actually, flask.Flask.response_class) and not a tuple so it assumes that it must be a WSGI object and attempts to call it (hence the error).
The best solution is to either use flask.jsonfiy to return a JSON response or to create a template to render the posts and use render_template to return the appropriate response.

A: find() returns a Cursor object that you must iterate over to access the documents returned by the query.  As in:
for post in posts.find():
    # do something with post

A: The answers above are both correct. Flask views are expected to return some kind of HTTP response. So you need to process the data and make a response, probably using Flask's utility functions. Also, the find() method returns a cursor, that you need to iterate over at some point.
You just need to change the last line of the view:
@app.route('/')
def home_page():
   post = {"author":"mike","text":"jiii"}
   posts = db.posts
   posts.insert(post)
   return render_template(posts.find(), "index.html")

And provide an index.html that contains something like:
{% for post in posts %}

Post by {{ post.author}}

{{ post.text }}

{% endfor %}

A: Use:
from flask_pymongo import Pymongo

instead of:
from flask.ext.pymongo import PyMongo


text:
Q: Same variable names in different JavaScript functions, considering one function calls the other I am doing a small work in JavaScript and I want to avoid problems, so I am asking beforehand.
Can I use two different variables and name them the same in different functions, given that one of these functions calls the other?
So, when I define the variable in the second function, will it interpret as two different variables, or will it rewrite the value of the original variable from the first function? (Or, will it throw an error due to the fact that a variable with that name already exists?)
Here is an example:
function first()
{
var a = somevalue;
second();
}

function second()
{
var a = differentvalue;
}

Thanks!

A: Variables declared inside a function are local to that function, and doesn't conflict with variables with the same name anywhere else.
You can even have a global variable with the same name, and the code inside the function will only see the local variable.
Example:
var a; // global variable

function first() {
  var a; // local variable in first
  second();
}

function second() {
  var a; // local variable in second
}

(Global variables should of course be used as little as possible, but it's good to know that you can have a local variable that is unaffected by any global variables that may exist.)
A local variable inside a function is not only local to the function, it's actually local to that execution of the function. If you call the function again, a new variable is created, and if the function calls itself (recursion), each level will have it's own variable.

A: Yes you can, as long as you don't forget the var keyword : the scope of a variable is either the function in which it is declared or the global scope. There is no way from outside the functions to gain access to the variables they declare.


text:
Q: issue while getting state of outgoing call in android? I am trying to come back to my activity once the outgoing call is ended.I found the similar questions and tried implementing the code but the problem is oncallstatechange() method,the state is 0 all the time,thus once the call is made it is getting disconnected as the code is directly getting into if loop where condition is state-idle and coming back to my app.though the problem is solved,I am getting into my activity back ,but the call is immediately getting hanged up.kindly help.thanks in advance.
//inside on create...
     callListener = new EndCallListener();
         mTM = (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);

//calling on item click
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3)
    {
        // TODO Auto-generated method stub

        LinearLayout ll = (LinearLayout) ((LinearLayout) v).getChildAt(0);
        LinearLayout lc = (LinearLayout) ll.getChildAt(0);

        TextView tv = (TextView) lc.getChildAt(3);

        String st = tv.getText().toString();//contains phone number

        mTM.listen(callListener, PhoneStateListener.LISTEN_CALL_STATE);

    Intent i=new Intent(android.content.Intent.ACTION_CALL,Uri.parse("tel:"+st));
        startActivity(i);

            //finish();
         }// onitemclick

//this is where I am calling my activity back..
class EndCallListener extends PhoneStateListener {

                         @Override
        state-->0        public void onCallStateChanged(int state, String incomingNumber) {
                         super.onCallStateChanged(state, incomingNumber);

                        if(TelephonyManager.CALL_STATE_RINGING == state) {

                        }
                        if(TelephonyManager.CALL_STATE_OFFHOOK == state) {
                            //wait for phone to go offhook (probably set a boolean flag) so you know your app initiated the call.

                        }
                        if(TelephonyManager.CALL_STATE_IDLE == state) {
                            //when this state occurs, and your flag is set, restart your app

                        startActivity(new Intent(recentcalling.this,recentcalling.class));

                        }
                    }
                }


text:
Q: Getting Exit Code (1) Error and Output in Error output using Process in Symfony I'm developing an application using Symfony 3.4 and I have to use some python scripts.
I used Symfony's Process Component to execute my python script and I got an Exit Code: 1 (General Error) that I don't understand.
Moreover, I saw that my expected output appears in the ErrorOutput, is that normal?
Here is my python script (index.py) :
import scipy.stats as stats
import sys

\#Kendall Coefficient

def kendallcoeff(x1,x2):
    tau, p_value = stats.kendalltau(x1,x2)
    return tau

sys.exit(float(kendallcoeff(sys.argv[1],sys.argv[2])))
\#sys.exit(sys.argv)

And in my php class, I have this code :
$process = new Process("python3 python/index.py",null,["arg1" => $timeArray,"arg2" => $speedArray]);
$process->run();

When I uncomment sys.exit(sys.argv), I get the error output :
"['python/index.py']"

Which shows that my arguments are not correctly passed to my script.
I always get :
The command "python3 python/index.py" failed.
Exit Code: 1(General error)
Can someone explain to me why I get this?

A: The Python function sys.exit() is only intended to pass Python process exit status, not application results between processes.  Call sys.exit(0) if the Python process terminated normally.  Call sys.exit(1) or sys.exit("error-message-string") if there was an error.  Your Python code passes a float to sys.exit() which evaluates to 1, causing Symfony Process to print the error message.
Instead, pass Python application results using print() to Symfony PHP.
(See https://symfony.com/doc/3.4/components/process.html for several ways of getting the output of the Python process.)
Since $timeArray and $speedArray are arrays, passing them on the command line to Python is problematic because they may be treated as more than two arguments.  So the below code passes the arrays as one JSON string.
Python script {symfony-base}/public/python/index.py) :
#!/usr/bin/python3

import json
import scipy.stats as stats
import sys

def kendallcoeff(x1,x2):
    tau, p_value = stats.kendalltau(x1,x2)
    return tau

print(sys.argv)
json_data = sys.argv[1]
python_obj = json.loads(json_data)
timeArray = python_obj[0]
speedArray = python_obj[1]

print(kendallcoeff(timeArray,speedArray))

sys.exit(0)

PHP Symfony class src/Controller/KendallCoefficientController.php should look something like this:
<?php

namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Process\Process;
use Symfony\Component\Routing\Annotation\Route;

class KendallCoefficientController extends AbstractController
{
    /**
     * @Route("/kendall", name="kendall")
     */
    public function index()
    {
        $timeArray = [1.0, 2.0, 3.0];
        $speedArray = [10.1, 20.2, 30.3];
        $arg = json_encode([$timeArray, $speedArray]);
        $process = new Process(['python3', 'python/index.py', $arg]);
        $process->run();

        // executes after the command finishes
        if (!$process->isSuccessful()) {
            throw new ProcessFailedException($process);
        }

        $pyoutput = $process->getOutput();

        $response = new Response($pyoutput, Response::HTTP_OK,
            ['content-type' => 'text/plain']);
        return $response;
    }
}


text:
Q: Apache rewrite to different places I have a site:
oldsub.oldsite.com that I now need to rewrite to newsub.newsite.com
So far I have this which seems to work for the site:
  <VirtualHost *:80>
    ServerName oldsub.oldsite.com
    Redirect 301 / http://newsub.newsite.com
  </VirtualHost>

BUT
There is one page that I need to redirect to a different location on the new site.
oldsub.oldsite.com/oldpage now needs to go to newsub.newsite.com/bla/bla/bla/newpage
How do I combine both of these things?
i.e. One specific page gets redirected to the new page on the new site and everything else just goes to the home page of the new site.

A: Just place an exception for the more specific URL before the more general "catch all" you already have:
<VirtualHost *:80>
    ServerName oldsub.oldsite.com

    RewriteEngine on
    RewriteRule ^/oldpage http://newsub.newsite.com/bla/newpage [L,R=301,QSA]

    Redirect 301 / http://newsub.newsite.com
</VirtualHost>

You obviously need the rewrite module inside your http server for that. But it should be available with a single click for all typical distributions.

A: Thanks @arkascha for the advice. Got me in the write direction. This is what worked:
<VirtualHost *:80>
ServerName oldsub.oldsite.com

RewriteEngine on
RedirectMatch 301 ^/oldpage http://newsub.newsite.com/bla/newpage

Redirect 301 / http://newsub.newsite.com
</VirtualHost>

Seems like the rewriterule and redirect don't work well together?


text:
Q: How to determine the tangential and radial component of the net forces on 2 particles connected by a rod? How to determine the tangential and radial component of the net force such as the one in the following situation?

Do the radial components always have to be in the direction of the rod? If so, why?
Is it that we first determine the radial components, then we rotate the vector by $90^\circ$ to find the tangential components?
I think I am in general having trouble to visualize the 2 particles' motion. Any explanations on that would be appreciated!

A: Radial component of the net force may be defined as the component of the net force along the radius while tangential component may be defined as the component of the net force along the tangent at any point in circular motion. In this question, as the two-mass system rotates about the z-axis in the x-y plane, we can say that the two masses $m_1$ and $m_2$ undergo circular motion with the origin as the centre.

Do the radial components always have to be in the direction of the rod? If so, why?

Now, in this question, since the rods lie along the radii (line joining center to the masses) of the circular paths traced by both the masses, the radial component of the net force will be in the direction of the rods in this case. But, this is specific to this particular question only; had the rods been not along the radii, the radial component of the net force would not have been in the direction of the rods. The radial component of the force must always be along the radius and it has nothing to do with the presence or absence of the rod along the radius.

Is it that we first determine the radial components, then we rotate the vector by $90^\circ$ to find the tangential components?

From plane geometry, it is known that the tangent to the circle is perpendicular to the radius at any point. Consequently, the tangential component of the force is also perpendicular to the radial component of the force at a given point. So yes, we can rotate the radial component by $90^\circ$ to get the tangential component but this will only give the direction of the tangential component of the force, not the magnitude as the two components may have entirely different magnitudes depending upon the context given.
Hope it answers your question.


text:
Q: How to consistently wipe H2 in Memory database when using JPA and JUnit Testing My set up is like this.
H2 in Memory database connected to using JPA the persistence context is configured  using Spring. The database set up script is run by Flyway to generate my tables and add in data.
Database URL: jdbc:h2:mem:test_data
In our JUnit tests we have setUp and tearDown Methods like this
@Override
protected void setUp() throws Exception {
    this.context = new ClassPathXmlApplicationContext("classpath:/DataContext.xml");
    this.data = this.context.getBean(DataProvider.class);
}

@Override
protected void  tearDown( ) throws Exception {
    this.context.close();
    this.context = null;
    this.data = null;
}

The intention here is for each JUnit test to get it's own data base, and this does seem to work sometimes, however there seem to be occasions when it appears like I am getting the same database as the previous test. An example is that I have 2 tests:
public void testGetFoos()
{
    Collection<Foo> foos= data.getFoos();
    assertEquals(NUMBER_OF_FOOS,foos.size());
}

public void testSaveFoos()
{
    Foo bar = makeDummyFoo();
    data.saveFoo(bar);
    Collection<Foo > foos = data.getFoos();

    assertEquals(NUMBER_OF_FOOS + 1,foos.size());
}

These methods should be able to run in any order and when running the maven build that appears to be the case, they are able to run independently without affecting each other, however occasionally when running the JUnit test class individually from eclipse the save method will run first, then the get method will run and get the wrong count because it seems to have gotten the same in mem database as the previous test method.
So my question is how to I kill my H2 in memory database between JUnit tests using my set up with Spring? or What could be causing it to not shut down properly, if the context.close() method is the correct way?

A: I believe using DbUnit would be a better approach; it is intended for exactly this purpose. Give it a look.
Good luck.

A: I suggest that you use :

*

*@Test annotations on test methods

*@Before on setup

*@After on teardown

You can put this code in @Before to ensure that all @Test methods will have fresh db
Connection connection = DriverManager.getConnection("jdbc:h2:~/test", "sa", "");
Statement stmt = connection .createStatement()
stmt.execute("DROP ALL OBJECTS");
connection.commit();
connection.close();

A: You could use Spring's @Sql annotation to setup and teardown the database after each test method on your junit test like this:
@SqlGroup({
    @Sql(executionPhase = ExecutionPhase.BEFORE_TEST_METHOD, scripts ="classpath:db/data.sql"),
    @Sql(executionPhase = ExecutionPhase.AFTER_TEST_METHOD, scripts = "classpath:db/clean.sql")
})
public void test(){
    //test logic
}


text:
Q: Previous and Next buttons(php and mysqli) keep getting 500 internal server error Here is my code:
                <?php
                    $sql = mysqli_query("SELECT thb_id FROM thumbnails LIMIT 10");
                    $result=mysqli_query($connection,$sql);
                    $count = mysqli_num_rows($sql);
                    if(isset($_GET['thb_id'])) {
                        $page = preg_replace('#[^0-9]#', '', $_GET['thb_id']);
                    } else {
                        $page = 1;
                    }
                    $lastPage = $count;
                    $total = 10;
                        if($page>1)
                        {
                            echo "PREVIOUS";
                        }
                        if($page!=$total)
                        {
                            echo "NEXT";
                        }
                    }
                ?>

My portfolio website is using PHP and MYSQL to call data from database,
each project has an assigned ID(thb_id), and i am showing 10 projects ($total = 10;). The code above is for my previous and next button, and they are on my "project.php" page. However, it has an internal server error, and i don't know how to fix it.
The updated version:
<?php
                    error_reporting(E_ALL);
                    ini_set('display_errors', true);
                    $sql = ("SELECT thb_id FROM thumbnails LIMIT 10");
                    $result=mysqli_query($connection,$sql);
                    $count = mysqli_num_rows($result);
                    if(isset($_GET['thb_id'])) {
                        $page = preg_replace('#[^0-9]#', '', $_GET['thb_id']);
                    } else {
                        $page = 1;
                    }
                    $lastPage = $count;
                    if($page < 1) {
                        $page = 1;
                    } else if($page > $lastPage) {
                        $page = 1;
                    }
                ?>

The new problem is: both prev and next buttons only take users to project 1(ID = 1).

A: Looks like you have an extra } at the end


text:
Q: Check full value of a long string in the VB6 IDE I have a string 'sSQL' that contains a very long tsql statement. I need to check what its value is while debugging. I usually just use ?sSQL in the immediate window but this is truncating the first half and only giving me the end half.
So is there an alternative way to see the full value using the vb6 sp5 dev environment?

A: While execution is paused on the breakpoint you could type in the immediate window:
Debug.Print(sSql)

;-)

A: One way is to use write the string out to a file. You can do this in a single line in the immediate window by using Line continuations, e.g.:
Open "C:\SQL.TXT" For Append As #1: Write #1,sSQL : Close #1

Note: You'll need to change C:\SQL.Txt to a path that you can write to depending on your OS.

A: If it's that long, save it to a text file. Have a debug method:
sub SaveStringToDebugFile(s as string)
  ...
end sub

and then call it from the immediate window:
SaveStringToDebugFile sSQL

A: Erm, the immediate window doesn't truncate (except at 200 lines of 1023 characters). Have you just tried pressing the home key or scrolling left?

A: For debugging, Clipboard.Clear: Clipboard.SetText ssql then paste into notepad.

A: Check the length of the "long" string using the Immediate:
?len(sSQL)
 4221

then knowing the size you can start getting chunks of string using Mid function:
?Mid(sSQL, 1, 500)

?Mid(sSQL, 500, 1000)

?Mid(sSQL, 1000, 1500)


text:
Q: How can i insert 2 for loops into print function in python im having problam to insert 2 for loops into my print function ,
im trying to print the following :
[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20],
[0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30],
[0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40],
[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50],
[0, 6, 12, 18, 24, 30, 36, 42, 48, 54, 60],
[0, 7, 14, 21, 28, 35, 42, 49, 56, 63, 70],
[0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80],
[0, 9, 18, 27, 36, 45, 54, 63, 72, 81, 90],
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]]

in 1 print line!
my try for this:
print ( for y in range(11)  [x*y for x in range(11)] )
please if someone can guide me it will help me alot

A: print([[x * y for x in range(11)] for y in range(11)])


text:
Q: Camera Preview does not fill screen This is how I am setting up the camera preview in landscape mode in my iPad3
- (void)viewDidAppear:(BOOL)animated

{
AVCaptureSession *session = [[AVCaptureSession alloc] init];
session.sessionPreset = AVCaptureSessionPreset640x480;

CALayer *viewLayer = self.vImagePreview.layer;

NSLog(@"viewLayer = %@", viewLayer);

AVCaptureVideoPreviewLayer *captureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];

captureVideoPreviewLayer.frame = self.vImagePreview.bounds;
[self.vImagePreview.layer addSublayer:captureVideoPreviewLayer];

AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

NSError *error = nil;
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
if (!input) {
    // Handle the error appropriately.
    NSLog(@"ERROR: trying to open camera: %@", error);
}
[session addInput:input];

stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
NSDictionary *outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys: AVVideoCodecJPEG, AVVideoCodecKey, nil];
[stillImageOutput setOutputSettings:outputSettings];

[session addOutput:stillImageOutput];

[session startRunning];

}
In the storyboard, I set the view to fill the entire screen, however it ends up looking like this:

And furthermore, the image is also rotated 90º degrees. How can I change this, so I can make the camera preview fill the entire screen?
Thanks.

A: Rotate your layer:
    switch (self.interfaceOrientation)
    {
     case UIInterfaceOrientationLandscapeRight:
       [captureVideoPreviewLayer setAffineTransform:CGAffineTransformMakeRotation(-M_PI / 2)];
       break;
     case UIInterfaceOrientationLandscapeLeft:
       [captureVideoPreviewLayer setAffineTransform:CGAffineTransformMakeRotation(M_PI / 2)];
       break;
    }

[self.vImagePreview.layer addSublayer:captureVideoPreviewLayer];


text:
Q: How to read attribute in an XML rootnode using classic ASP? I am attempting to read the "ts" attribute in the rootnode of this XML, using classic ASP, but I cannot seem to get the proper syntax.  I am able to read attributes in the various nodes and nested nodes below, but I need info from the rootnode.
Can anyone suggest a solution?
XML Code snippet:
<?xml version="1.0" encoding="utf-8"?>
<results ts="2012-04-24 17:10:45" nm="Test project" fin="0" bal="131494" vot="131494" tab="614" cltab="172" pol="1737" clpol="72" stpol="1735">
    <choices>
        <choice id="1" tot="1" vot="211" e="1" />
        <choice id="2" tot="1" vot="196" e="-1" />
    </choices>
    <area id="1" bal="131494" vot="131494" bal2="131494" vot2="131494" tab="614" cltab="172" pol="1737" clpol="72" stpol="1735">
        <tab>
            <cg cgId="1" tot="132" clos="131" />
            <cg cgId="2" tot="23" clos="23" />
            <cg cgId="3" tot="459" clos="18" />
        </tab>
    </area>
    </areas>
</results>

ASP Code Snippet to read a typical node that is working fine...
Dim objResultXML
Set objResultXML = Server.CreateObject("Microsoft.XMLDOM")
objResultXML.async = False
objResultXML.Load (Server.MapPath("FileToParse.xml"))

ReDim ResultArray(3,0)
Set NodeList = objResultXML.documentElement.selectNodes("choices/choice")
For Each Node In NodeList
    If CStr(ResultArray(0,0))<>"" Then  ''< Balance signs
        ReDim Preserve ResultArray(3,UBound(ResultArray,2)+1)
    End if
    ResultArray(0,UBound(ResultArray,2)) =CLng(Node.getAttribute("id"))
    ResultArray(1,UBound(ResultArray,2)) =CLng(Node.getAttribute("tot"))
    ResultArray(2,UBound(ResultArray,2)) =CLng(Node.getAttribute("vot"))
    ResultArray(3,UBound(ResultArray,2)) =CStr(Node.getAttribute("e"))

Next
Set NodeList=Nothing

A: .documentElement is results element.
All you need is just that : objResultXML.documentElement.getAttribute("ts")


text:
Q: Way to get Venue capacity from Google API Is there a Google API that provides a capacity of a particular place or venue.
Let's say Bank of America stadium.
If we do a search with the name on Google then at right hand side of the page, we see the detailed information which also contains the capacity of that particular place.
Is there any API to achieve this particular state.
Knowledge Search API of Google provides some of the details but not the capacity of that venue.


text:
Q: What condition should the image of a basis have so that the function is an algebra morphism? Say we have a morphism $f$ from some $\mathbb{k}$-algebra $A$ to $\mathbb{k}$, but we also know that $A$ is a vectorspace i.e. we can define a basis on $A$. Then clearly to look at the image of $A$ we can just look at what $f$ does to the basis of $A$. So say the basis elements of $A$ are written as $e_i$, so we look at $f(e_i) : = \lambda_i$, where each $\lambda_i \in \mathbb{k}$.
What can we say about the set of images of each basis element in $\mathbb{k}$, so that $f$ is an algebra morphism? Other than dimensions being equal, I can't think of any other specific properties.


text:
Q: How to trace resolving process of nuget package references I have a solution with multiple projects in it (~400). A lot of them are using newtonsoft.json library. Some of them are using different version of the library. In a host project for web app, there is no direct reference to newtonsoft.json. Also, I believe, there are dependencies to packages that depend on newtonsoft.json. However, in bin folder of that project I began getting newtonsoft.json 9.0 instead of newtonsoft.json 11.0 as it used to be. And it causes load exception in runtime due to invalid version. If I include direct reference to newtonsoft.json 11.0, it still puts version 9.0 in the bin folder even if I clear all bin,obj folders. I use PackageReference for managing dependencies, and everything is in .net 4.6.1; I use binding redirects to resolve issues with different versions of the same library.
My question is if there is a way to diagnose how particular dll of package ref appears in bin folder? I would like to see some sort of comprehensive trace of dependency resolution so that I can fix it without using "trial and error" approach.
Upd.
Actually, thanks guys for pointing to structured logging. You are the best! So the issue was that one of the project had <OutputPath> pointing to the bin folder of the host project. So when the project was built, it was overriding binaries in the host project. Apparently, build order has changed due to continuous reference shuffling and the project with wrong <OutputPath> started building last. To find this out 1) I Newtonsoft.Json was recorded in DoubleWrites section 2) analyzing location from double writes I found out in _CopyFilesMarkedLocal section
Copying file from "\VenomousProject\bin\Debug\Newtonsoft.Json.dll" to "HostProject\bin\Debug\Newtonsoft.Json.dll".

That was it.

A: You can try MSBuild Binary and Structured Log Viewer (https://msbuildlog.com/)

*

*build the project from command line with msbuild -bl - you will get msbuild.binlog

*open the binlog with the log viewer and use the dll name as a search term

*inspect all records related to the dll and backtrack a place (project and msbuild' target) where the wrong file version is taken.

A: With PackageReference, NuGet will write a file named project.assets.json in the project's obj folder. This file is used by the rest of the build to determine what files from packages should be included in the build, but it also contains a list of all the packages that were selected, what version was selected, and what dependencies each package has (package id and version). This is the closest thing to dependency resolving debugging that NuGet has.
In the file, search for "Newtonsoft.Json/, and you should find which version of Newtonsoft.Json that NuGet selected. Remove the / and replace it with ", and you can find all the packages that have dependencies on Newtonsoft.Josn. Search for newtonsoft.json.dll to find all the packages that ship that dll in its package (sometimes package authors perfer to ship multiple dlls in their package, rather than adding dependencies, which prevents NuGet from being able to version selection.
If there are multiple packages with which contain a dll with the same filename, NuGet will tell MSBuild about all of them, and it's up to MSBuild to select which one to use (pass to the compiler and copy to the bin/publish directory). As @Serg wrote in their answer, you can use binlogs (with the -bl argument on any MSBuild command, including dotnet restore or dotnet build). NuGet's inner workings are not output to MSBuild, so when your package graph has multiple packages that list Newtonsoft.Json as a dependency, it won't tell you why NuGet chose a specific version, but binlogs are very useful at debugging other build related issues.


text:
Q: delayed_job dies with out error - no attempt has been made I have a delayed job which is implemented as a model method (see below).  If I use delayed_job daemon it ran and died silently.  Not one job got complete and no logged message was found.  But if I use RAILS_ENV=production rake jobs:work everything works OK.
I don't know why, even if an exception is thrown it should appear in the log, but there is none.  And if there's something wrong with the logic then why the rake job succeeded?
def recalc(params)
    last_known = self
    t = nil # target(self)
    target_date = self.as_on.yesterday
    success = true
    saved = -1
    # cater for the first one
    TimeSlot.where(employee_id:self.employee_id).where('incurred_on >= ?', self.as_on).order('incurred_on ASC').each do |ts|
        # loop
        if (ts.incurred_on >= target_date) then
            if !t.nil? && target_date.day <=7 # roll over to a new month
                t.bal_sick += 4 # add 4 days
                if t.bal_sick > 40
                    overflow = t.bal_sick-40
                    t.bal_sick = 40
                    t.bal_sick2 += overflow
                    t.bal_sick2 = 120 if t.bal_sick2 > 120 # overflow again
                end
            end
            unless saved<0
                success = t.save
                last_known = t
            end
            if success
                saved += 1
                t = target(last_known)
                target_date = t.as_on
            else
                logger.warn("Recalc cannot saved a record for #{t.errors.first}")
                logger.warn(t.inspect)
                return
            end
        end
        if ts.types.include? 'overtime'
            t.bal_ot += ts.hours.to_i
            t.bal_ot = 100 if t.bal_ot >100
        elsif ts.types.include? 'toil'
            t.bal_ot -= ts.hours.to_i
        elsif ts.types.include? 'vacation'
            t.bal_vacation -= ts.hours
        elsif ts.types.include? 'sick1'
            t.bal_sick -= ts.hours
        end
    end
    logger.info("Recalc saved %d records"% saved)
end

A: After reading https://github.com/collectiveidea/delayed_job/wiki/Common-problems I found that I've missed out "specify your rails environment", i.e. RAILS_ENV=production bin/delayed_job start, the default environment appears to be development.
But why the default environment is development?  It should be production.  If I am in development I'd rather do rake jobs:work


text:
Q: how data binding works between ng-template and the context passed to the template using CreateEmbeddedView I have this template.
<ng-template #thumbnailTemplate let-context="thumbnailContext">

</ng-template>

The following code create a view using the above template
  thumbnailTemplateViewRef = this.thumbnailContainerRef.createEmbeddedView(this.thumbnailTemplateRef,
      {thumbnailContext: new ThumbnailContext(divId,
        imgId,
        closeId,
        imageString,this.thumbnailContainerRef.length,null)});

and when deleteThumbnail is called and the context is passed to it, I am accessing the index property as follows
let index = thumbnailContext.thumbnailContext.index;
  deleteThumbnail(thumbnailContext:any){
    console.log("delete thumbnail  clicked with context ",JSON.stringify(thumbnailContext));
    let index = thumbnailContext.thumbnailContext.index; //note that thumbnailContext.index is undefined
    console.log("deleting index ", index);
    let wasConfirmed = confirm("Are you sure you want to delete the attachment?");
    if(wasConfirmed) {

      this.thumbnailContainerRef.remove(index);

      return false;
    }
  }

ThumbnailContext is
export class ThumbnailContext{
  constructor(public divId:string,
              public imgId: string,
              public closeId:string,
              public imgSrc:string,
              public index:number,
              public viewRefId:EmbeddedViewRef<ThumbnailContext>){}
}

I am unable to understand what the type of context is let-context=thumbnailContext is in the ng-template
Is context it
{
thumbnailContext:{divId:.., imgId:..}
}

or is context
{
divId:.., imgId:..,
}

In the html it looks like it is the latter one because I am able to assign the values in the html as div id="{{context.divId}}but when then I unable to do context.index in deleteThumbnail? Why I had to do thumbnailContext.thumbnailContext.index?

A: This is my understanding but it could be wrong so I am happy to accept other answers.
In templates, context information could be passed as an object and the passed object's key(s) will be available for binding by the local template let declarations.
eg, if the template is
<ng-template #myTemplate let-col let-foo="bar">

{{col}}

{{foo}}

</ng-template>

and if the object passed is myContext = {$implicit: 'World', bar: 'Svet'}; then col will be assigned the value World because it is assigned the $implicit key's value and foo is assigned value of bar key i.e. Svet
In my example if I use let-context="thumbnailContext" in the html then I need thumbnailContext key in the context object.
 {thumbnailContext: new ThumbnailContext(divId, //storing information about this thumbnail in the context of teh embedded view
          imgId,
          closeId,
          imageString,this.thumbnailContainerRef.length,null)}

then context becomes {divId:..., imgId:...} and I can use it as context.divId
alternatively I could have used let-context only along with $implicit
 $implicit: new ThumbnailContext(...)

Now this is the part I am unsure of but the following is my understanding.Note that context variable in let-context is a key/value, not an object itself. In the example below
<ng-template #eng let-name>Hello {{name}}!</ng-template>, if the object passed is
   myContext = {$implicit: 'World', localSk: 'Svet'};
   then name is World (the value)
So when I pass context to deleteThumbnail, I am passing a key/value i.e. thumbnail:{divId:..., imgId:...). Javascript wraps this   inside an object i.e.
   {
   thumbnailContext:{divId:..., imgId:...}
   }

thus to access it inside deleteThumbnail, I'll have to do thumbnailContext.thumbnailContext.divId because the
   top level object (function argument) is called thumbnailContext


text:
Q: How to make scp go faster? I use the following command to transfer files across my home network (when I have to transfer a lot of files, I usually archive them with the tar utility):
scp -c blowfish [FILE] [USER]@[ADDRESS]:[PATH]

It takes about 25 minutes to send 500 Mb of data to another computer. The average speed is at about 600 KB/s. I think there absolutely must be a way to make the process go faster because I don't believe that I'm able to pull a 1 Gb file comfortably off the Web in less than 10 minutes, but I can't get a 500 Mb file sent across the network in less that time.

A: Two ideas:

*

*Experiment with a different cipher

*Use 'on the fly' compression

1. Experiment with a different cipher:
One idea is to test the various ciphers which are available through scp and try to determine which is the fastest for you. (The idea behind this is that it is the encryption of your data that is taking up the time.) Find the available ciphers by running the following:
andrew@athens:~$ ssh -Q cipher
3des-cbc
blowfish-cbc
cast128-cbc
arcfour
arcfour128
arcfour256
aes128-cbc
aes192-cbc
aes256-cbc
rijndael-cbc@lysator.liu.se
aes128-ctr
aes192-ctr
aes256-ctr
aes128-gcm@openssh.com
aes256-gcm@openssh.com
chacha20-poly1305@openssh.com
andrew@athens:~$

This shows available ciphers on a default Xenial Xerus installation and can be added in using the syntax you have already suggested:
scp -c <cipher> [FILE] [USER]@[ADDRESS]:[PATH]

This option is passed directly to ssh hence testing ssh itself for the available ciphers. Hopefully you can find a cipher that will allow an increase in your transfer speed, when you have found this cipher you can place it in ~/.ssh/config rather than typing it in each time...
2. Use 'on the fly' compression:
scp is able to compress your transfers 'on the fly' meaning that the compressions is only used during transfer and will not be seen at either the host or remote ends. Add this in using the -C option:
scp -c <cipher> -C [FILE] [USER]@[ADDRESS]:[PATH]

Here is an example on my own system:
debug1: compress outgoing: raw data 365865, compressed 150118, factor 0.41
debug1: compress incoming: raw data 150118, compressed 365865, factor 2.44

The compression level is the same as the one used for gzip and if you really wish to experiment you can use the 'CompressionLevel' option which varies from 1-9, 1 being the fastest compression, 9 being the slowest with best compression and 6 being the default. This can be set in ~/.ssh/configas follows:
Host *
Compression yes
CompressionLevel 9

Bear in mind that this sets high compression for all scp / ssh transfers, it can be set for individual hosts if you wish...
Use the -v option to investigate the effects of any changes you make. You will note with experimentation that different data will have different compression ratios.


text:
Q: How do you make a window full screen using the kivy design language? Can someone tell me how to set a kivy window to full screen mode using the design language?
The result I'm looking for is either bordered full screen/border-less full screen. If you run the following example you'll see exactly what I'm trying to achieve.
from kivy.core.window import Window
from kivy.uix.widget import Widget
from kivy.config import Config
from kivy.app import App

class ExampleClass(Widget):
    pass

class ExampleApp(App):
    def build(self):
       return ExampleClass()

Window.fullscreen = 'auto'
ExampleApp().run()

'''
   If you've never run it with that setting before. Be ready for borderless
   Full screen output.It can be scary the first time you see it lol :D
'''

An example of the code I'm working with is as follows.
from kivy.lang import Builder
from kivy.core.window import Window
from kivy.graphics import Canvas
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition
from kivy.config import Config

class StartScreen(Screen):

    def Mute_Audio(self):
        pass

    def new_g(self):
        pass

    def l_g(self):
        pass

    def Settings(self):
        pass

class SelectionScreen(Screen):
    pass

class MyScreenManager(ScreenManager):
    pass

root_widget = Builder.load_string('''
#:import FadeTransition kivy.uix.screenmanager.FadeTransition
MyScreenManager:
    transition: FadeTransition()
    StartScreen:
    SelectionScreen:

<StartScreen>:
    name: 'start_screen'
    canvas:
        Rectangle:
            pos: self.pos
            size: self.size

    Button:
        id: b_1
        pos: 330,350
        size_hint:  0.2, 0.1
        text: 'button 1'
        font_size: 18
        on_press: root.new_g()
        on_release: app.root.current = 'selection_screen'

    Button:
        id: b_2
        pos: 330, 280
        size_hint:  0.2, 0.1
        text: 'button_2'
        font_size: 18

    Button:
        id: settings
        pos: 330, 210
        size_hint: 0.2, 0.1
        text: 'Settings'
        font_size: 18

    Button:
        id: mute_button
        pos:658, 495
        size_hint: 0.2, 0.2

<SelectionScreen>:
    name: 'selection_screen'
    canvas:
        Rectangle:
            pos: self.pos

''')

class ExampleApp(App):
    def build(self):
        self.title = 'Save me Stack Overflow'
        return root_widget

ExampleApp().run()

to reiterate, I need help setting the window to full screen using the design language. I just have no idea how to set it to full screen with kv.
UPDATE:
To re-iterate. I don't care about the positioning of widgets or how the full screen looks. All I need to know is how to set a Window to full screen mode using the design language aka KV.
I showed two examples. The first example shows what I want to do. In that it shows a border-less full screen window. The second example illustrates an example of the design language. I need to achieve the same result produced in the first example in the second example but instead of doing it in straight python I need to do it in the design language.

A: It seems it is possible to do it from the KV file! (using setattr)
some kv file:
#:import Window kivy.core.window.Window

<RootWidget>:
     some_property: setattr(Window, 'fullscreen' , 'auto')  or 'real_value!'

It is hackish though...


text:
Q: Getting Unusual Error while using Selenium and PhantomJS in Python I'm trying to fill the forms of these page, I checked the HTML code and the forms that I'm looking for are there but when I run my code, I got an error that I never seen in selenium.
I'm using PhantomJS 2.1.1 in Python 3.6.1 with Selenium.
I Want to fill these form.
<input type="text" name="Dt_Ref" value="31/08/2017" maxlength="10" size="10" class="form_data" onBlur="formatCamp(this, 'date');javascript:if(REUNE.Dt_Ref.value!=REUNE.Dt_RefAnt.value){REUNE.target='_self';REUNE.action='reune.asp';REUNE.submit()};" onKeyPress="return(validaConteudo(event, this, 'date'))" onKeyUp="saltaCampo(event, this, 'date',8)" onFocus="removeCaracs(this, 'date')">  <a style="cursor:hand; cursor:pointer;" onclick="openCalendar(document.REUNE.elements['Dt_Ref']);return false;">

My Code is:
from selenium import webdriver

url = 'http://www.anbima.com.br/reune/reune.asp'
path_phantom = 'C:\\Users\\TBMEPYG\\AppData\\Local\\Continuum\\Anaconda3\\Lib\\site-packages\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe'

#Processing

driver = webdriver.PhantomJS(executable_path= path_phantom)
driver.get(url)
name = driver.find_element_by_name("Dt_Ref")
driver.quit()

And I got this error:
Traceback (most recent call last):
  File "C:\Users\TBMEPYG\Desktop\beta_anbima.py", line 11, in <module>
    name = driver.find_element_by_name("Dt_Ref")
  File "C:\Users\TBMEPYG\AppData\Local\Continuum\Anaconda3\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 426, in find_element_by_name
    return self.find_element(by=By.NAME, value=name)
  File "C:\Users\TBMEPYG\AppData\Local\Continuum\Anaconda3\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 832, in find_element
    'value': value})['value']
  File "C:\Users\TBMEPYG\AppData\Local\Continuum\Anaconda3\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 297, in execute
    self.error_handler.check_response(response)
  File "C:\Users\TBMEPYG\AppData\Local\Continuum\Anaconda3\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 194, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: {"request":{"headers":{"Accept":"application/json","Accept-Encoding":"identity","Connection":"close","Content-Length":"89","Content-Type":"application/json;charset=UTF-8","Host":"127.0.0.1:64945","User-Agent":"Python http auth"},"httpVersion":"1.1","method":"POST","post":"{\"using\": \"name\", \"value\": \"Dt_Ref\", \"sessionId\": \"cc170460-8e5e-11e7-ad22-8d3d940cf70e\"}","url":"/element","urlParsed":{"anchor":"","query":"","file":"element","directory":"/","path":"/element","relative":"/element","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/element","queryKey":{},"chunks":["element"]},"urlOriginal":"/session/cc170460-8e5e-11e7-ad22-8d3d940cf70e/element"}}
Screenshot: available via screen

This is the first step of my code. I'm under a bank proxy and this could be the problem. When I access from my Chrome, the page works fine.
When I try to use the same code (changing the url and the element name) in this site, it works fine.
Thank you all.

A: This is an issue/bug with PhantomJS.
I would suggest you use Chrome as such or docker image for selenium/standalone-chrome
If you look at https://github.com/ariya/phantomjs/issues there are 1923 open issues, which speaks for itself.
You can't even query
driver.find_elements_by_xpath("//*")

You will get the error
NoSuchElementException: Message: {"request":{"headers":{"Accept":"application/json","Accept-Encoding":"identity","Connection":"close","Content-Length":"87","Content-Type":"application/json;charset=UTF-8","Host":"127.0.0.1:53425","User-Agent":"Python http auth"},"httpVersion":"1.1","method":"POST","post":"{\"using\": \"xpath\", \"value\": \"//*\", \"sessionId\": \"eb09e680-8e72-11e7-8b72-d1137b47fa59\"}","url":"/elements","urlParsed":{"anchor":"","query":"","file":"elements","directory":"/","path":"/elements","relative":"/elements","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/elements","queryKey":{},"chunks":["elements"]},"urlOriginal":"/session/eb09e680-8e72-11e7-8b72-d1137b47fa59/elements"}}
Screenshot: available via screen

So open a bug and make the count 1924, but I really doubt you would get much help


text:
Q: eslint error cannot read property 'range' of null I have had the same eslint issue for days now.
Everyone on the team has the same eslintrc & installed version of eslint. Their eslint works fine, mine does not.
I have tried restarting my computer, deleting node_modules, deleting anything under my user (in home directory). Nothing works.
Issue:
./node_modules/.bin/eslint *.js*
                                                                          1 ↵  11504  10:19:47
Cannot read property 'range' of null
TypeError: Cannot read property 'range' of null
    at SourceCode.getTokenBefore (/Users/jhill/gitRepo/sponsoroo/node_modules/eslint/lib/token-store/index.js:303:18)
    at checkSpacingBefore (/Users/jhill/gitRepo/sponsoroo/node_modules/eslint/lib/rules/template-curly-spacing.js:52:42)
    at TemplateElement (/Users/jhill/gitRepo/sponsoroo/node_modules/eslint/lib/rules/template-curly-spacing.js:117:17)
    at listeners.(anonymous function).forEach.listener (/Users/jhill/gitRepo/sponsoroo/node_modules/eslint/lib/util/safe-emitter.js:47:58)
    at Array.forEach (<anonymous>)
    at Object.emit (/Users/jhill/gitRepo/sponsoroo/node_modules/eslint/lib/util/safe-emitter.js:47:38)
    at NodeEventGenerator.applySelector (/Users/jhill/gitRepo/sponsoroo/node_modules/eslint/lib/util/node-event-generator.js:251:26)
    at NodeEventGenerator.applySelectors (/Users/jhill/gitRepo/sponsoroo/node_modules/eslint/lib/util/node-event-generator.js:280:22)
    at NodeEventGenerator.enterNode (/Users/jhill/gitRepo/sponsoroo/node_modules/eslint/lib/util/node-event-generator.js:294:14)
    at CodePathAnalyzer.enterNode (/Users/jhill/gitRepo/sponsoroo/node_modules/eslint/lib/code-path-analysis/code-path-analyzer.js:608:23)

Details
Version:
./node_modules/.bin/eslint --version

v4.16.0

.eslintrc
{
  "extends": ["airbnb-base", "plugin:security/recommended"],
  "rules": {
      "import/prefer-default-export": "off",
      "no-console": "off",
      "class-methods-use-this": "off",
      "global-require": "off",
      "consistent-return": "off",
      "import/no-extraneous-dependencies": ["error", {"devDependencies": true}],

      /* JSX */
      "jsx-quotes": [2, "prefer-double"],

      /* React */
      "react/display-name": 1,
      "react/jsx-boolean-value": 1,
      "react/jsx-no-duplicate-props": 1,
      "react/jsx-no-undef": 1,
      "react/jsx-quotes": 0,
      "react/jsx-sort-props": 0,
      "react/jsx-uses-react": 1,
      "react/jsx-uses-vars": 1,
      "react/no-danger": 1,
      "react/no-did-mount-set-state": 1,
      "react/no-did-update-set-state": 1,
      "react/no-multi-comp": 1,
      "react/no-unknown-property": 1,
      "react/prop-types": 1,
      "react/react-in-jsx-scope": 1,
      "react/self-closing-comp": 1,
      "react/sort-comp": 1,
      "react/wrap-multilines": 0,

      /* Security */
      "security/detect-non-literal-fs-filename": 2,
      "security/detect-non-literal-regexp": 2,
      "security/detect-unsafe-regex": 2,
      "security/detect-buffer-noassert": 2,
      "security/detect-child-process": 2,
      "security/detect-disable-mustache-escape": 2,
      "security/detect-eval-with-expression": 2,
      "security/detect-no-csrf-before-method-override": 2,
      "security/detect-non-literal-require": 2,
      "security/detect-object-injection": 2,
      "security/detect-possible-timing-attacks": 1,
      "security/detect-pseudoRandomBytes": 2,
      "no-unsafe-innerhtml/no-unsafe-innerhtml": 2
  },
  "parser": "babel-eslint",
  "plugins": [
    "babel",
    "react",
    "security",
    "no-unsafe-innerhtml"
  ],
  "env": {
    "jest": true,
    "browser": true,
    "es6": true,
    "node": true
  },
  "settings": {
    "import/extensions": {
      "webpack": {
        "config": "./webpack.config.react.js"
      }
    }
  }
}

Also, if I delete "parser": "babel-eslint" from my .eslinrc, the problem/erorr goes away, but my eslint doesn't work. I am using ES6 syntax.
UPDATE:
My solution was to use yarn instead of npm. Has solved the problem for the time being.

A: These .eslintrc rules fixed the problem for me:
rules : {
  "template-curly-spacing" : "off",
  "indent": ["error", 2, {
    "ignoredNodes": ["TemplateLiteral"]
  }]
}

A: babel-eslint has been deprecated in favor of @babel/eslint-parser.
read here
Here are steps to upgrade from babel-eslint to @babel/eslint-parser:

*

*replace babel-eslint with @babel/eslint-parser:

npm
npm uninstall babel-eslint babel-eslint-plugin
npm install --save-dev @babel/eslint-parser @babel/eslint-plugin

Yarn
yarn remove babel-eslint babel-eslint-plugin
yarn add --dev @babel/eslint-parser @babel/eslint-plugin

*Upgrade .eslintrc.js:

module.exports = {
    ---  parser: "babel-eslint",
    +++  parser: "@babel/eslint-parser"
    plugins: [
        ---   "babel"
        +++   "@babel
    ]
};

A: I added only two rules in .eslintrc.js file and it resolved for me.
rules : {
    "template-curly-spacing" : "off",
    indent : "off"
  }

A: As @Vasan mentioned, specifically, on issue 530, this was the comment that helped me to solve the issue:
Most likely the issue is causing of wrong parsing.
import(`some_path/${variable}`) // issue exists

Fix
import("some_path" + variable) // issue fixed

A: Fix the version of babel-eslint to 7.2.3 or 8.0.1 by running:
npm install --save-dev babel-eslint@7.2.3

Or:
npm install --save-dev babel-eslint@8.0.1

A: Expanding off @SergeyP's answer above.
It's worth noting that you might need to set the requireConfigFile flag to false in your parserOptions if, like me, you get a Parsing error: No Babel config file detected error after following his instructions.
module.exports = {
  parser: '@babel/eslint',
  parserOptions: {
    requireConfigFile: false,
  },
  // ...snip...
}

There is further information here in regards to this issue expanding on this.
https://github.com/babel/ember-cli-babel/issues/366

A: This is caused most probably due to indentation in Template Literals ,so to fix it just add below in your .eslintrc

    "indent": ["error", 2, {
      "ignoredNodes": ["TemplateLiteral"]

}]

A: For me a warning was showing for each string literal (e.g some text ${someVariable}) and installing these two packages solved my problem:
npm i @babel/types @babel/traverse --save-dev


text:
Q: Makefile confusion phony hack Folder structure:

*

*Makefile

*rect_01.c

*rect_02.c

*square_01.c

Makefile (relevant parts):
%.c:
    echo 'Building $@ for $(PLATFORM)...'
    $(CC) $(CFLAGS) $@ -o '$(DESTDIR)/$*'

Command:
make rect_01.c PLATFORM=FOO

Problem - gave me the output:
'rect_01.c up already to date'

So I tried a hack and added a dependency which I added to .Phony,
so that %.c should be executed every time. But now it tries to compile my
makefile even it hasn't the extension .c.
I wrote  the following updated makefile (relevant parts):
.PHONY: phonyDummy

%.c: phonyDummy
    echo 'Building $@ for $(PLATFORM)...'
    $(CC) $(CFLAGS) $@ -o '$(DESTDIR)/$*'

Which gives me the following output:
make rect_01.c PLATFORM=LINUX_X86
echo 'Building Makefile.c for LINUX_X86...'
Building Makefile.c for LINUX_X86...
g++ -Wall -g Makefile.c -o '../Executables/Makefile'
Makefile: file not recognized: File format not recognized
Makefile:55: recipe for target 'Makefile.c' failed
make: *** [Makefile.c] Error 1

Can you explain this behaviour?

A: You should learn more about Makefile. You mix two important things: target and dependency.
The target is a file (in most cases) which should create with a rule. The dependency is the "source".
If you write:
%.c:
    echo 'Building $@ for $(PLATFORM)...'
    $(CC) $(CFLAGS) $@ -o '$(DESTDIR)/$*'

it means: "I want to create files with .c extension". You don't want to create .c files because you've many (three) .c files. The make checks the rect_01.c: it exists and it's up-to-date because it hasn't any dependency (after the : there isn't anything).
I think you want to build rect_01.so (or similar) - this is the target! So you want similar:
%.o: %.c
    echo 'Building $@ for $(PLATFORM)...'
    $(CC) $(CFLAGS) -o $@ $<

In this case if you want to build rect_01.o you should run make rect_01.o. The $(CC) will run if rect_01.o doesn't exist or older than rect_01.c (so the source rect_01.c is newer and doesn't rebuild yet).


text:
Q: How to test hoverover text in Cucumber I am using cucumber for testing the hover over text for the table Header text. since I am using a template I dont have identifiers for the table header so I am not sure how to target all the headers and compare it against the required value.

header1

header2

header3

A: The problem identified is: You need to validate your title attribute for each
Here is some pseudo-code on how to accomplish your task.  (in java)
WebElement elements = driver.findElements(By.cssSelector("th > a"));

for (WebElement element : elements)
  assertTrue(element.getAttribute("title").equals("Some title"));


text:
Q: Cant open location services screen please someone help me. How can I open Location Services from my app?  I tried this but it doesn't work
URL(string: "prefs:root=LOCATION_SERVICES")

A: Opening a specific sub-screen of Settings programatically no longer works, since iOS 11. Now all you can do is open main screen of Settings App, using url string App-Prefs


text:
Q: Passing values of latitude and longitude from ListViewActivity class to MyMapActivity class I am having list of hotels in listview and their latitude and longitude.
Now I want to pass all these values to MyMapActivity class to display places of all hotels in the map.
I had retrieved all the value of latitude and longitude, but these are not retrived in the MyMapActivity class.

A: You have to pass latitude and longitude to getFromLocation method in Geocoder class:
Take a look at:
http://developer.android.com/reference/android/location/Geocoder.html

A: Use this:
Geocoder geocoder = new Geocoder();
try {
    addresses = geocoder.getFromLocation(lat, lng, 1);
}
catch (IOException e) {
    e.printStackTrace();
}

if (addresses != null && addresses.size() > 0) {
    Address address = addresses.get(0);
    locale = address.getCountryName();
    localenane = locale.replaceAll(" ", "_");
}

A: send latitude and longitudes to MyMapActivity class using extras like below
Intent intent = new Intent(this, MyMapActivity class);
intent.putExtra("latitude",latitude);
intent.putExtra("longitude",longitude);
startActivity(intent);


text:
Q: .NET AWS Lambda with Mediator we want create new application with aws Lambda. We normally use Mediator, clean architecture and controllers. Is it ok use mediator with lambda? Because we have common logic like pipeline behaviours, validations etc. And i don't know if it's good plan. Because every lambda functions must build many dependencies. Is it ok or it's better create "normally" api?
Thank you


text:
Q: Insert picture in header with VBA from picture located in workbook Was using this but it became quickly apparent today that expecting the picture to be in the same directory all the time is not a good plan.
With ActiveSheet.PageSetup.LeftHeaderPicture
    .filename = ThisWorkbook.path + "\pic.jpg"
    .Height = 275.25
    .Width = 195
End With

While the picture never changes, the text in the header changes daily so this needs to be generated automatically hence the need for inserting it with VBA as I'm putting the picture in the header as well as other text every time the relevant data changes.

A: You already have code to import an external picture file and import it into a header.  Since you have an embedded picture, we can export it and then use the code you have.  Say we have:

This code will:

*

*create a Chart Object on the worksheet

*copy the picture to the chart

*export the chart to an external file

*delete the chart

The code:
Sub SaveTheBaby()
    Dim chrt As Chart, MyPic As Shape
    Set MyPic = ActiveSheet.Shapes(1)

    ActiveSheet.Shapes.AddChart
    Set chrt = ActiveSheet.ChartObjects(1).Chart

    MyPic.Select
    MyPic.Copy
    ActiveSheet.ChartObjects(1).Activate
    ActiveChart.Paste
    chrt.Export Filename:="baby.jpg"
    ActiveSheet.ChartObjects(1).Delete
End Sub