## unit testing – Is inversion of control the opposite of “tell, don’t ask” principle?

First, let me explain what I mean by inversion of control and tell, don’t ask in this context. I have 3 objects ClassA, ClassB and ClassC. ClassA is a consumer of target object ClassB.

Inversion of control here means two things:

• passing in required arguments into each method on the target object ClassB
• assumes that target objects are made up of atomic methods to be controlled by either ClassA the consumer or public methods on ClassB

Tell, don’t ask here the following scenario:

• we have target task ClassC::d() and can either fetch arguments ClassB::E and ClassB::F on classA, then inject them into ClassC::d(). Or, the alternative that is instantiate ClassB inside ClassC. Then on ClassC::D(), we pull and modify the encapsulated ClassB instance and use it however we deem fit, be it by calling other local methods or what not ( utilize other classes), as opposed to returning a value after d’s atomic operation for it

Are these terms mutually exclusive? I got here by comparing both patterns. In pattern 1 which I appreciate atomic methods for their testability. I don’t have to bother about complex dependency chains.
However, in pattern 2, TDA ( given this understanding of it) is obviously cleaner and the consumer only ever worries about ClassC. This reveals pattern 1 equally creates a kind of dependency problem as regards testing. At what point is acceptable for an action in a class to be responsible for deciding what parameters it runs with.

One of my primary motives in all this is creation of an enabling environment for unit tests and a clear API (non-cluttered) for consumers

## autofocus – confusion about the principle of on-sensor PDAF technique

There are a lot of pictures over the internet illustrating the principle of phase detection autofocus, such as this one

What is PDAF and how does it work? Phase Detection Autofocus explained

The simplest way to understand how PDAF works is to start by thinking about light passing the camera lens at the very extreme edges. When in perfect focus, light from even these extremes of the lens will refract back to meet at an exact point on the camera sensor.

How Phase Detection Autofocus Works

When the light reaches these two sensors, if an object is in focus, light rays from the extreme sides of the lens converge right in the center of each sensor (like they would on an image sensor). Both sensors would have identical images on them, indicating that the object is indeed in perfect focus.

For on-sensor PDAF technique, there are many special pixels with an opaque mask over one half.
It may be look like this:

https://www.imaging-resource.com/PRODS/olympus-e-m1/ZTECH_PDAF_PIXELS.gif

How can the left image with left-mask pixels and the right image with right-mask pixels be identical when the object is in focus? From the first figure, the object points should be imaged into one pixel location when the object is in focus.

## brauer groups – A local-to global principle for splitting of Azumaya algebras

Let $$S$$ be a finitely generated domain with the field of fractions $$F.$$ Let X be a smooth,
geometrically connected affine variety over $$S.$$ Let $$A$$ be an Azumaya algebra over $$X.$$
Assume that for all large enough primes $$p,$$ $$A_p$$ splits over $$X_p$$-the reduction modulo $$p$$ of $$X.$$ Does this assumption imply that $$A_{overline{F}}$$ splits over $$X_{overline{F}}?$$ My naive guess is that the answer should be “yes”. Any suggestions or references would be
greatly appreciated.

## probability – Understanding the principle of deferred decisions; how are these events independent?

I am trying to wrap my head around the proof of the following theorem on the probabilistic verification of matrix multiplication in $$theta(n^2)$$ time in Mitzenmacher and Upfal’s Probability and Computing: Randomized Algorithms and Probabilistic Analysis. The proof is used to illustrate a broader technique used in the analysis of randomized algorithms called the principle of deferred decisions.

The proof in the text starts by defining $$D = AB – C$$. Then $$ABbar{r} = Cbar{r}$$ iff $$Dbar{r} = 0$$. Since $$D neq 0$$, $$D$$ has some nonzero entry $$d_{11}$$ without loss of generality. For $$Dbar{r} = 0$$, we must have $$sum_{j=1}^n d_{1j} r_j = 0$$. Rearranging gives

$$r_1 = -frac{sum_{j=2}^n d_{1j} r_j}{d_{11}}$$

It then follows from the law of total probability that

I understand that the $${r_i : i in (n)}$$ are independent, and thus $$r_1$$ and $$(r_2, … r_n)$$ are independent. But how could the events $$r_1 = -frac{sum_{j=2}^n d_{1j} r_j}{d_{11}}$$ and $$(r_2,…,r_n) = (x_2,…,x_n)$$ possibly be independent when the value of the right hand side of the former depends clearly on the latter?

## Generalised method for solving pigeon hole principle questions

I am looking for a generalized method to solve simple to advanced pigeonhole principle questions (that are PURELY pigeon-hole ie not in combination with any other topics like probability)

The definition:

Suppose that $$n$$ pigeons fly into $$d$$ pigeonholes. Performing the division, let $$n = qd + r$$, where the remainder is $$r = 0, 1, 2, . . . , d − 1.$$

If $$r = 0$$, there must be at least one pigeonhole with $$q$$ pigeons.

If $$r > 0$$, there must be at least one pigeonhole with $$q + 1$$ pigeons.

The least number of pigeons that will guarantee that there is at least one pigeonhole with at least
$$q + 1$$ pigeons is $$qd + 1$$

Normally I don’t use the above definition because I dont really understand it but I can solve wuestion anyway by intuition. So I am asking: If $$r=0$$, why is $$n = q$$ and not $$qp$$? If $$r > 0$$, why is the remainder $$q+1$$? Since the remainder can be up to $$d-1$$, I don’t understand where the $$q+1$$ comes from. And From the third statement, I have realised that I am probably interpreting the law incorrectly: it seems that I should be ignoring $$d$$ for some reason or maybe I am just supposed to set it equal to $$1$$?

My second question is: will considering the “worst case scenario” work for every question? This method has not failed me yet but if I search online, there is hardly any information on it (and on the PHP in general).

Typical questions involve something along the lines of “how many socks/ties/hats would I have to pick to ensure two of the same color” and I just consider the worst case scenario where I delay the desired outcome until the very end. Then I just add one to force the ceiling function to go to the next positive integer, which basically ensures the “same color” pair. HOWEVER, when the “worst case scenario” gets more abstract eg $$text{Prove there are two powers of 2 that differ by a multiple of 8479}$$

I cannot identify the worst case scenario. Basically,should I be able to use it in all PHP questions?

I have a statement which I think is what I need to prove:

RTP $$2^a – 2^b = 8479k$$, where $$a,b,k$$ are integers.

But I’m not sure how to proceed from here

## c# – Dependency Inversion Principle with connection to a SQL Server

First, this is my first post on this stack exchange site. So please be patient with me. If there is something wrong or you miss something, please let me know. I will add it asap.

I am currently working with the SOLID principles and trying to achieve a practical implementation.
I have seen Tim Corey’s practical videos on YouTube, which explain the principles well.
Now I have a project where I would like to implement this and I am struggling a bit with the implementation of the dependency inversion principle in the context of SQL queries to a SQL server. Here, several instances of different classes are often needed, e.g. `SqlConnection`, `SqlDataAdapter` or `DataSet`.
Perhaps in advance. I know that Dependency Injection could make things easier. But first I wanted to understand the principle of dependency inversion.

I’ve created now a (mini) project, where my approach becomes clear (the project with the complete code is also available on Github https://github.com/dnsnx/Dependency_Inversion_SQL).

I first created an interface `IDatabase`:

``````using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Dependency_Inversion_SQL.Interfaces
{
public interface IDatabase
{
void AddParameters((string name, object value)() parameters);

System.Data.DataSet GetData(string commandText, System.Data.CommandType commandType = System.Data.CommandType.Text, string sourceTable = null);
}
}
``````

For simplicity, I just want to read data at the moment – no updates yet.
So I defined a method for setting parameters (`AddParameters`) and one method for reading the data (`GetData`).
First difficulty here:
Keep the interface non-specific, i.e. not directly designed for SQL Server. In the future, the DB system could be changed!
Then I created a class `SQLDatabase` which implements this interface:

``````using Dependency_Inversion_SQL.Interfaces;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;

namespace Dependency_Inversion_SQL.Classes
{
public class SQLDatabase : IDatabase
{
#region Variables
private readonly string _SqlServer = "Integrated Security=true;Initial Catalog=Test;Server=localhost\localhost;";
private SqlConnection _SqlConnection;
private SqlCommand _SqlCommand;
private DataSet _DataSet;
#endregion

#region Properties
public string SqlServer
{
get
{
return _SqlServer;
}
}
#endregion

#region Constructors
{
_SqlConnection = sqlConnection;
_SqlConnection.ConnectionString = _SqlServer;
_SqlCommand = _SqlConnection.CreateCommand();
_DataSet = dataSet;
}
#endregion

#region Methods
public void AddParameters((string name, object value)() parameters)
{
for (var i = 0; i < parameters.Length; i++)
{
}
}

public System.Data.DataSet GetData(string commandText, System.Data.CommandType commandType = System.Data.CommandType.Text, string sourceTable = null)
{
if (sourceTable == null)
{
sourceTable = "someName";
}
_DataSet.Clear();
_SqlCommand.CommandText = commandText;
_SqlCommand.CommandType = commandType;
_SqlCommand.Parameters.Clear();
_SqlCommand.CommandText = string.Empty;
return _DataSet;
}
#endregion
}
}
``````

Now, to implement dependency inversion, we need a `factory` class that defines which instances are created:

`Factory`:

``````using Dependency_Inversion_SQL.Classes;
using Dependency_Inversion_SQL.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Dependency_Inversion_SQL
{
public static class Factory
{
public static ICar CreateCar()
{
return new Car(CreateDatabase());
}

public static IDatabase CreateDatabase()
{
}

public static System.Data.SqlClient.SqlConnection CreateDatabaseConnection()
{
return new System.Data.SqlClient.SqlConnection();
}

{
}

public static System.Data.DataSet CreateDatabaseDataSet()
{
return new System.Data.DataSet();
}
}
}
``````

Then I needed a class, which queries SQL data. I created a simple class `Car`, which “reads” a car name.

``````using Dependency_Inversion_SQL.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Dependency_Inversion_SQL.Classes
{
class Car : ICar
{
IDatabase _Database;

public Car(IDatabase database)
{
_Database = database;
}

public string GetCarName()
{
var result = _Database.GetData("SELECT 'Audi R8' as CarName");
return result.Tables(0).Rows(0).ItemArray(0).ToString();
}
}
}
``````

Now my console application:

``````using Dependency_Inversion_SQL.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Dependency_Inversion_SQL
{
class Program
{
static void Main(string() args)
{
ICar car = Factory.CreateCar();
Console.WriteLine(\$"My dream car is an { car.GetCarName() }");
}
}
}
``````

As I wrote above, I was wondering, if there would be a more easy way to implement the `SQLDatabase` class.
It needs all the stuff in the constructor (`SqlConnection`, `SqlDataAdapter`, `DataSet`) and so on.
What I also don’t know, if it is correct, how I implemented the generation of these classes in the `Factory` class.

``````public static System.Data.SqlClient.SqlConnection CreateDatabaseConnection()
{
return new System.Data.SqlClient.SqlConnection();
}

{
}

public static System.Data.DataSet CreateDatabaseDataSet()
{
return new System.Data.DataSet();
}
``````

What I understood is, that the return type, should be a interface as best. This is in my eyes not possible with the SQL classes.

If this question is too large or I misunderstood the stack exchange site, please let me know. I will delete the question then.
Many thanks in advance for any comment on this.

## probability – Weak large deviation principle with non-unique rate function

In the book Large deviations techniques and applications by Dembo and Zeitouni, page 118, it is stated that

if $$X$$ is a locally compact space, the rate function is unique as soon as a weak LDP holds. As shown in Exercise 4.1.30, if X is a Polish space, then also the rate function is unique as soon as a weak LDP holds.

We recall that, by definition, the weak LDP holds if the lower LDP bound holds for all sets (as in the standard LDP) and the upper LDP bound holds for compact sets (page 7 of the book).

Ma question is: is there an example of a weak LDP on a regular Hausdorff topological space which admits several (lower semicontinuous) rate functions? Such example would necessarily involve a family of measures that is not exponentially tight, since exponential tightness combined with the weak LDP implies the full LDP (Lemma 4.1.4 in the book), for which the rate function is always unique.

## java – DRY principle vs decoupling (business from GUI)

Say I have a business model called `Vehicle`. `Vehicle` has many fields but to keep it simple say it looks like:

``````public class Vehicle {
String ownerName;
String brand;
FuelType fuelType;

}
public enum FuelType{
GAS,ELECTRIC,PETROL
}
``````

Now, this model has its own semantics in the domain. For example, this model is an entity meaning it gets persisted in a “something the GUI should not know about” (database). So there is a `VehicleService` that manages things like this. There are also things like `VehicleExportService` that exports a `business.Vehicle`(s), say to PDF files.

Now, the GUI (which is desktop) needs to show vehicles. If I use this model to show and let user edit vehicles, many parts of my GUI (ToolTipCreators, Controllers, Widgets) depend on this class (has import `business.Vehicle`) hence I consider this as “coupling” (please, give me a clarification if its not). Plus, during “store vehicle edits by user” phase or during “export” phase, parts of the application (mostly controllers) must depend on `VehicleService` and `VehicleExportService`. Changing things in domain, things in GUI must change too. Also, during GUI tests I will have to mock `VehicleService`. If one day I delete `VehicleService`, GUI tests will break.

So, in order to decouple and increase modularity, I introduce a `gui.VehicleModel` (MVC/MVP/Whatever). This allows me to add a `save()` or `export()` method. It is also an interface to let me test, without creating `business.Vehicle` objects during GUI testing or need to mock `VehicleService`.

Now, these 2 meet at `gui.adapt.VehicleAdapter` class that implements `gui.VehicleModel`. It takes in constructor a `business.Vehicle`, a `VehicleService` and a `VehicleExport` service and long story short, it just delegates the calls to business. For example, it looks like this:

``````public class VehicleAdapter implements VehicleModel {
public VehicleAdapter(Vehicle origin, VehicleService service, VehicleExportService exportService) {
...
}
//getters and setters for all Vehicle fields
@Override
public void save() {
service.save(origin);
}

@Override
public void export() {
exportService.export(origin);
}
}
``````

Now, the whole GUI works with VehicleModel. Changing `business.Vehicle` or say business splits VehicleService to `VehicleSaveService` and `VehicleDeleteService` will only require to change the adapter.

After all that are done, I think decoupling is achieved. I use this approach for other models (say VehicleOwner, or Brand or whatever) too. I have a `gui.adapt` package that is the only package accessing `business` package. However, what I find suspicious is the duplication between the 2 models. Between the MVC model (for GUI) and the business model. Vehicle has 30 fields (give or take). So, the interface has 30 getters and setters. The business model has 30 getters and setters and the MVC model has 30 getters and setters as well.

Am I overengineering? Should I use business models in the GUI? Do I have wrong impression of what “decoupling” means? Do I have wrong impression of what DRY stands for?

## mathematical optimization – Minimization problem in proving Fermat’s principle

I am trying to prove the Fermat’s Principle of least distance, the problem statement goes:

`Minimize[{n1* d1 * Sec[theta1] + n2 * d2 * Sec[theta2], d1 * Tan[theta1]+d2*Tan[theta2]==d},theta1]`

I can’t get a solution to this. The good solution should satisfy`n1*Sin[theta1]=n2*Sin[theta2]`

Can anyone help?

## php – Router and solid principle

I would like to know if my Routing system respects the solid principle ?

The system is simple, Router class contains the routes and returns the correct route and Route class represents a route, contains a path and an action to call. Router takes the Request class as a parameter in its constructor to try to respect the solid principle.

I would like to know what’s good and what isn’t.

``````class Router
{
private \$request;
private \$routes = ();

public function __construct(Request \$request)
{
\$this->request = \$request;
}

public function get(string \$path, string \$action)
{
}

private function addRoute(string \$path, string \$action, string \$method)
{
\$route = new Route(\$path, \$action);
\$this->routes(\$method)() = \$route;
return \$route;
}

public function run()
{
if(!isset(\$this->routes(\$this->request->getMETHOD()))) {
throw new RouterException('REQUEST_METHOD does not exist');
}
foreach (\$this->routes(\$this->request->getMETHOD()) as \$route) {
if (\$route->match(\$this->request->getUri())) {
return \$route->call();
}
}
throw new RouterException("La page demandée est introuvable.");
}
}
``````
``````class Route
{
private \$path;
private \$action;
private \$matches;
private \$parameters = ();

public function __construct(string \$path, string \$action)
{
\$this->path = trim(\$path, '/');
\$this->action = \$action;
}

public function where(string \$param, string \$regex)
{
\$this->parameters(\$param) = str_replace('(', '(?:', \$regex);
return \$this;
}

public function match(string \$requestUri)
{
\$requestUri = trim(\$requestUri, '/');
\$path = preg_replace_callback('#:((w)+)#', (\$this, 'paramMatch'), \$this->path);
\$regex = "#^\$path\$#";
if (preg_match(\$regex, \$requestUri, \$matches)) {
array_shift(\$matches);
\$this->matches = \$matches;
return true;
} else {
return false;
}
}

private function paramMatch(array \$match)
{
if (isset(\$this->parameters(\$match(1)))) {
return '(' . \$this->parameters(\$match(1)) . ')';
}
return '((^/)+)';
}

public function call()
{
\$parameters = explode('@', \$this->action);
\$controller = "Src\Controller\" . \$parameters(0);
\$controller = new \$controller();
\$method = \$parameters(1);
return call_user_func_array((\$controller, \$method), \$this->matches);
}
}
``````