Q:

Automatic selectors for selectors which extend a named selector?

I am using Stylus to pre-process my CSS and have found that it would be extremely convenient if I could figure out a way to define stylesheets in the following way:
// This is a template for an element which can contain content.
$content-container
    font-family tahoma, arial, sans-serif
$content-container p
    blah
$content-container ul
    blah
$content-container li
    etc.

// Then I would like to promote specific elements into content containers:
.blog article
    @extend $content-container
.release-notes main
    @extend $content-container

So the idea is that above would yield something like the following:
.blog article,
.release-notes main {
    font-family: tahoma, arial, sans-serif;
}
.blog article p,
.release-notes main p {
    blah
}
.blog article ul,
.release-notes main ul {
    blah
}
.blog article li,
.release-notes main li {
    etc.
}

Is there a way to achieve this? it would certainly make things a lot easier!!

A:

Okay... it looks like this is the default behaviour after all.
It seems that using @extend within the template $content-container causes this to break:
$content-container
    p
        @extend $standard-paragraph

I worked around this issue by using a mixin instead:
$content-container
    p
        $standard-paragraph()

Whilst this solves my problem; I would be interested to know whether the behaviour of @extend is a bug or whether it is the intended behaviour.


Q:

Are there any advantages in using const parameters with an ordinal type?

I know marking string parameters as const can make a huge performance difference, but what about ordinal types? Do I gain anything by making them const?
I've always used const parameters when handling strings, but never for Integer, Pointer, class instances, etc.
When using const I often have to create additional temporary variables, which replace the now write-protected parameters, so I'm wondering: Do I gain anything from marking ordinal parameters as const?

A:

You need to understand the reason, to avoid "cargo-cult programming."  Marking strings as const makes a performance difference because you no longer need to use an interlocked increment and decrement of the refcount on the string, an operation that actually becomes more expensive, not less, as time goes by because more cores means more work that has to be done to keep atomic operations in sync.  This is safe to do since the compiler enforces the "this variable will not be changed" constraint.
For ordinals, which are usually 4 bytes or less, there's no performance gain to be had.  Using const as optimization only works when you're using value types that are larger than 4 bytes, such as arrays or records, or reference-counted types such as strings and interfaces.
However, there's another important advantage: code readability.  If you pass something as const and it makes no difference whatsoever to the compiler, it can still make a difference to you, since you can read the code and see that the intention of it was to have this not be modified.  That can be significant if you haven't seen the code before (someone else wrote it) or if you're coming back to it after a long time and don't remember exactly what you were thinking when you originally wrote it.

A:

You can't accidentally treat them like var parameters and have your code compile. So it makes your intentions clear.

A:

Declaring ordinal types const makes no difference because they are copied anyway (call-by-value), so any changes to the variable do not affect the original variable.
procedure Foo (Val : Integer)
begin
Val := 2;
end;
...
SomeVar := 3;
Foo (SomeVar);
Assert (SomeVar = 3);

IMHO declaring ordinal types const makes no sense and as you say requires you to introduce local variables often.


Q:

Why can't I assign List to IEnumerable in .NET 4.0

I try to do this:
IEnumerable<object> ids = new List<string>() { "0001", "0002", "0003" };

it works great!
But when I try to do this:
IEnumerable<object> intIds = new List<System.Int32>() { 1, 2, 3 };

Visual Studio tells me:
Cannot implicitly convert type 'System.Collections.Generic.List' to 'System.Collections.Generic.IEnumerable'. An explicit conversion exists (are you missing a cast?)
Why is that?

A:

Simply put: generic variance in .NET 4 doesn't support variance for type arguments which are value types.
The reason it can work for reference types is that once the CLR has decided it knows the generic conversion is safe, it can treat all reference values the same way - they have the same representation internally. No actual conversion is required to turn a string reference into an object reference, or vice versa if you know it's definitely a reference to a string - it's the same bits, basically. So the generated native code can just treat the references as references, happy in the knowledge that the rules around variance have guaranteed that nothing nasty will happen at the type safety level, and not performing any conversions on the values themselves.
That isn't true for value types, or for reference types where the conversion isn't a "reference conversion" (i.e. a representation-preserving one). That's why you can't write IEnumerable<XName> names = new List<string>(); by the way...

A:

int is a value type and can only be boxed to object - it doesn't inherit from object. Since you're using an IEnumerable<object> anyway, this should work:
IEnumerable intIds = new List<int>() { 1, 2, 3 };

A:

From MSDN Blogs > C# Frequently Asked Questions > Covariance and Contravariance FAQ:

Variance is supported only if a type parameter is a reference type. Variance is not supported for value types.
  The following doesn’t compile either:
// int is a value type, so the code doesn't compile.
IEnumerable<Object> objects = new List<int>(); // Compiler error here.


Q:

How can I get file path on raw resources in Android Studio?

I have been using this tutorial to make some face detections on picture. The problem is when I getting the file path that used on java
String xmlFile = "E:/OpenCV/facedetect/lbpcascade_frontalface.xml";
CascadeClassifier classifier = new CascadeClassifier(xmlFile);

How can I translate on android studio. I try put my lbpcascade_frontalface.xml on raw resources. CascadeClassifier is a class that opencv library provided. The only problem is they only loaded string path (on xmlfile).
this is my code.
String pathtoRes = getRawPathAtempt2(context);
CascadeClassifier cascadeClassifier = new CascadeClassifier();
cascadeClassifier.load(pathtoRes);

I translated to some method like this.
  public String getRawPathAtempt2(Context context) {
    return "android.resource://" + context.getPackageName() + "/raw/" + "lbpcascade_frontalface.xml";
}

I get the asertions error by opencv that tell me the file is null. Thats mean I had been wrong when I used file path on my method. how can I get file path on raw resources? help me please I have been stuck for several days now

A:

how can i get file path on raw resources?

You can't. There is no path. It is a file on your development machine. It is not a file on the device. Instead, it is an entry in the APK file that is your app on the device.
If your library supports an InputStream instead of a filesystem path, getResources().openRawResource() on a Context to get an InputStream on your raw resource.


Q:

Минусы хранения статей в файлах, а не в базе данных

Некоторые CMS используют для хранения статей не базу данных, а обычные текстовые файлы. Хотелось бы узнать, какие в этом случае могут возникнуть проблемы при большом количестве статей.
Пока единственное, что приходит на ум - это поиск, но при желании и его можно ускорить, если создавать индекс.
PS. Одним таким движком я давно уже пользуюсь и доволен, но статей на данный момент не очень много.

A:

Резервная копия. Придётся файлы копировать отдельно от базы. Если в
это время происходят транзакции, то файлы могут оказаться немного не
синхронизированными с базой.
Индексация. Многие базы поддерживают полнотекстовый поиск и
соответствующие индексы. По своим полям они точно ищут и
индексируют, а вот внешние файлы - кто знает?   Хотя конечно можно
сделать поля специально для хранения индекса (грубо говоря из текста
извлечь ключевые слова и поместить в это поле).
Переключение с одной методы получения/записи данных на другую.   Это
просто неудобство. В некоторых случаях оно так и так будет (если
пользоваться не привычным SELECT/INSERT, а каким-то более
эффективным на больших данных поточным интерфейсом базы данных)

В любом случае приходится предпринимать дополнительные усилия по синхронизации записей в БД и внешних файлов. Где это действительно важно, требуется задействовать базы данных и файловые системы с поддержкой распределённых транзакций, координировать транзакции бд и фс.


Q:

Does software based file recovey solutions have the same results on real physical device vs dd image file?

I have a flash drive and I want to recover some files from it. Can I take a dd image of the device and perform the recovery operation on dd image instead? Does it have the same results when performing recovery using software on physical flash drive?

A:

Yes!
It's standard forensic procedure to work from a "Physical Copy", which is what a dd bit-for-bit image is. It will have the same results as working from the drive. In fact the hash checks verify that they are the same.
This assumes of course that the dd image was done appropriately. An example of an inappropriate dd image would be one done against a multisession DVD as DVDs are not actually block devices and only the last session would be extracted.
A flash drive is a block device and would image as expected via a dd.
Wear leveling is a bugaboo that's often thrown around but it's not a factor here.
The one extremely unlikely difference with an SSD (Solid State Drive) is a massively delayed TRIM function. If the TRIM runs delayed by many minutes, a dd image may actually extract data before the TRIM runs quicker that performing the analysis directly against the SDD, in which case the image would be better but the hashes would not match causing problems. I've never seen this occur!


Q:

Why is the config server string order sensitive when launching mongos?

and thanks in advance for your time.
For a given sharded setup, mongos is launched while specifying the config server(s) to talk to. Say we start with the following mongos option:
--configdb=cf1,cf2,cf3

Everything is all fine and dandy. If you were to relaunch mongos (or launch a different mongos) with:
-- configdb=cf3,cf2,cf1

It results in the following error:
Tue Jul  9 23:32:41 uncaught exception: error: { "$err" : "could not initialize sharding on connection rs1/db1.me.net:27017,db2.me.net:27017,db3.me.net:27017, :: caused by :: mongos specified a different config database string : stored :cfg1:27017,cfg2:27017,cfg3:27017 vs given :cfg3:27017,cfg2:27017,cfg1:27017","code" : 15907}

My question is, what is the reasoning mongo sensitive to the order of the config server string? I would imagine at some point it parses the different servers hostnames/port, so why not just compare the set? I know you can see from the source code that its just a string comparison, but my question is the underlying reason for this.
Some context to this problem: I am using chef for my mongo deployments. We recently went through the exercise of migrating the config server with the same hostname. However, this still ended up being a disruptive process because the order the chef picked up the config servers had changed, thus changing order mongos starts its process with. I understand that this issue is directly because of chefs functionality, but I am curious as to why Mongo is not this flexible.
Thanks again for your time.

A:

When mongos process changes metadata for sharded cluster, it has to change it in all three config servers "simultaneously" (i.e. all three must agree in order to have a valid metadata change).
If the system were to go down in the middle of such a metadata change, if the config database order was not fixed, there would be a lot more possible permutations of incorrect states to unwind.  Requiring a fixed sequence of config dbs allows (a) simpler checking of whether all members of the cluster are viewing the same metadata (b) significant reduction of possible states when a system crashes or otherwise stops unexpectedly.
In addition it reduces chances for "race condition" sorts of bugs if different mongos' could initiate the same operations on different config servers.   Even as simple a change as mongos process taking a "virtual" distributed lock to see if a chance is necessary - how could you handle the case of different mongos' checking config servers in different order to check on (and take out) the lock?
As a summary, the three config servers are not a replica set, but one of them still has to be the one that always accepts the changes "first" - think of the order of configdbs to mongos as designation of such "first" status.


Q:

Adding to virtual function in derived class

I have a class pawn which inherits from piece: piece has a function moveTo declared as below:
public virtual void moveTo(Coord newLoc)
{
    Coord origLoc = location;
    Transform transform = gameObject.GetComponent<Transform>();
    Coord transCoord = newLoc - location;

    if (LogicMaster.currentBoard[newLoc].piece != null) {
        if (LogicMaster.currentBoard[transCoord].piece.targeted) {
            UnityEngine.Object.Destroy(LogicMaster.currentBoard[transCoord].actor);
            LogicMaster.currentBoard[transCoord].actor = null;
        }
    }

    if (LogicMaster.currentBoard[newLoc].actor == null)
    {
        Vector3 transVector = new Vector3();

        transVector.x = transform.position.x + transCoord.x * Constants.oneRight.x;
        transVector.z = transform.position.z + transCoord.y * Constants.oneForward.y;
        transVector.y = transform.position.y;
        transform.position =  transVector;

        LogicMaster.currentBoard[newLoc].actor = gameObject;
        LogicMaster.currentBoard[newLoc].piece = this;
        LogicMaster.currentBoard[newLoc].piece.location = newLoc;
        LogicMaster.currentBoard[this].actor = null;
        LogicMaster.currentBoard[this].piece = null;
        LogicMaster.selectedPiece = null;
        LogicMaster.pieceSelected = false;
        LogicMaster.currentBoard.resetColours();
        LogicMaster.currentBoard.hideMarkers();
        LogicMaster.whiteTurn = !LogicMaster.whiteTurn;
    }
}

Is it possible to implement an override within the pawn class that implements the code within moveTo but then adds some onto the end? Otherwise I assume it's simply a copy and paste job.
Thanks.

A:

As CodeCaster mentions you can override the method and call base.MoveTo(..) and afterwards add your own logic.
Example
The base class:
public class CodeFirstInstallationService : IInstallationService
{
    public virtual void InstallData(string defaultUserEmail,
        string defaultUserPassword, bool installSampleData = true)
    {
        // Doing basic logic
    }
}

The class deriving from the base:
public class MyInstallationService : CodeFirstInstallationService
{
    public override void InstallData(string defaultUserEmail,
        string defaultUserPassword, bool installSampleData = true)
    {
        // Let the base class do it´s install logic
        base.InstallData(defaultUserEmail, defaultUserPassword, installSampleData);

        // Do my own logic
        // Install flux capacitor etc
    }
}


Q:

How to download jar file from github source code?

I need to use a nxParser library to parse my NTriple files in eclipse.
Apparently, the only source that perfectly works is this github code but this is just the source code and I need a built-in jar library.
Could anyone help me how can I use a source code as a built-in jar file?

A:

If you need a jar file itself rather than adding pom.xml click on below link to download jar file http://central.maven.org/maven2/org/semanticweb/yars/nxparser-parsers/2.3.3/nxparser-parsers-2.3.3.jar
If you want to create jar file from github follow the below steps,
In Linux/Mac
1.Clone the repository
git clone https://github.com/nxparser/nxparser.git
cd nxparser

2.Build the project
./gradlew build

3.Find jar file
`nxparser-parsers/build/libs/nxparser-parsers-2.3.4-SNAPSHOT.jar`


Q:

Given the current hashing powers, what do pools actually do in practice?

Given the current hashing powers, what do pools actually do in practice to find a block?
Ok, so here is my thinking, please correct me if I'm wrong anywhere:

Here's the format of the block header, the thing which is actually hashed:

version(4b) + prevBlockHash(32b) + merkleHash(32b) + ctimestamp(4b) +
  ctarget(4b) + nonce(4b);

So, canonically, what miners do is going through all the possible values of the last NONCE(4 bytes).
If we treat that as unsigned int, the range would be 0-4294967295.
Right now you can buy a 2Ghs miner for < $100.
Given that you have something that can hash 2GHs(very cheap solution, I'm not even talking about THs systems that pools reportedly have), you could bruteforce through the range of 0:4294967295 in less than 3 seconds.

So, the question is, what keeps mining in that ~10min period?
My suspicion is that its not that much of a problem to find a nonce anymore, its more a problem to find the proper block that will actually have a nonce.
If that is true:
a) what do miners do in practice, play around with the timestamp, or generate some transactions to change the merkle root?
b) is there any mathematical proof that such a block will ever be found? I mean, bitcoin not getting stuck, because of some unfortunate block having such a bad coincidence of bits that will endup blocking the result from getting enough zeros in the end to fit the target(I'm asking about mathematical proof that it is impossible).

A:

For a given combination of
version(4b) + prevBlockHash(32b) + merkleHash(32b) + ctimestamp(4b) + ctarget(4b),
There is no guarantee that there will be a valid nonce. There usually isn't - the probability that there will be is 1 divided by the difficulty, which is currently 9 billion. So miners try different combinations, try the nonce range for each, until they find a valid solution.
a) The most general method is to change extraneous data in the generation transaction to change the Merkle root. Currently, to reduce communication overhead between the pool and miners, a method such as GBT is used, where the miner gets a block template and can fill in the generation transaction himself.
b) No; hashing, like much of the core cryptographic primitives, is kind of a "dark art" - there's little in the way of proof that it all works. Let's say you fix just the prevBlockHash, there is no proof that you can fill in the other details to obtain a valid hash. However, if hash functions behave more or less the way we think they do, it is extremely unlikely there will be no solution.


Q:

HTTP requests trace

Are there any tools to trace the exact HTTP requests sent by a program?
I have an application which works as a client to a website and facilitates certain tasks (particularly it's a bot which makes automatic offers in a social lending webstite, based on some predefined criteria), and I'm interested in monitoring the actual HTTP requests which it makes.
Any tutorials on the topic?

A:

Some popular protocol/network sniffers are:

Wireshark (previous the famous Ethereal)
Nirsoft SmartSniff (using WinPcap)
Nirsoft SocketSniff (allows you to watch the WinSock activity of the selected process and watch the content of each send or receive call, in Ascii mode or as Hex Dump)
Microsoft's Network Monitor (and a list of video-tutorials here, note video 'Advanced Filtering 2 of 2' where they specifically filter on process)

Wikipedia article 'Comparison of packet analyzers' has a nice overview of some other tools to.
Alternatively you could also look into (man-in-the-middle) proxy tools like:

Fiddler
mitmproxy

Both of the above actually record/decrypt/modify/replay HTTPS to!! You'd need to point the application you are monitoring to this proxy. If nothing else uses that proxy the log would be application/process specific and another upside to this approach is that one could also run the monitor/logger on a different machine.
Once you choose a tool, you can easily google a tutorial to go along with it.
However the core idea is usually the same: basically one sets a filter (on capture itself or display of captured data) on things like protocol, network/mac address, portno, etc. Depending on the tool, some can also filter on local application.
Hope this helps!


Q:

Beyond Face Detection-OpenCV

I used the information provided in the OpenCV wiki to make a face detection program which identifies the presence of a face in the Camera feed. The source code that I used was provided in the link given below
http://docs.opencv.org/doc/tutorials/objdetect/cascade_classifier/cascade_classifier.html
Now I wanted to take it to another level so that it can actually identify the ears also. Thus I would want to place a mask on the users face which shows the presence of face and also the ears, something like
http://code.google.com/p/ehci/wiki/6dofhead
How to do this without using OpenGL, and using some kind of cascade classifier?

A:

There HaarCascades available for ears, eyes, nose, mouth, etc. You can use them in the same way as you used Face cascades to detect faces. The cascades are provided with the source.
OpenCV-version/data/haarcascades


Q:

Can phase transitions occur in open systems?

Is it possible that in open systems can occur phase transitions if the required conditions (i.e., temperature and pressure) are met? Are there examples?

A:

Yes.
Some examples are found, e.g., in the 1978 paper Experimental Studies of Some Phase Transitions in Nonequilibrium Open Systems (namely, "onset of self-sustained electric oscillation, evolution of vortex around a sink hole and successive transitions in liquid crystals due to an electric field").
And not only phase transitions can take place in open systems, also critical states can be sustained, e.g., in systems displaying Self-Organized Criticality, such as a sand pile over which grains fall randomly.


Q:

Proof that $ab/(a+c)$ is bounded for bounded $b$ and $c$

Is there a concise way to prove that $\frac{ab}{a+c} \in [0, 1]$ for all $a > 0$, $b \in [0, 1]$, and $c \in [0, 1]$?

A:

$$0\leq \frac{ab}{a+c}=\frac{b}{1+\frac{c}{a}}\leq b\leq 1$$


Q:

Angular add function reply comments

I have code which adds new comments, but the "reply to comment" feature isn't working properly. If I push form add comment when click reply() and add then inside/under existing comment only five times.
This is my code:
HTML:

            {{ comment.date | date: 'medium' }}

            Reply

{{ comment.text }}

    <form class="form" name="form" ng-submit="form.$valid && commCtrl.addComment()" novalidate>

        <textarea
                  class="input"
                  ng-model="commCtrl.comment.text"
                  placeholder="Add comment..."
                  required></textarea>

        <input type="submit" value="SEND">

    </form>

JavaScript:
(function(){
  'use strict';

 var myApp = angular.module('addCommentsApp', []);
    myApp.controller('AddCommentsController', AddCommentsController);

  // Inject $scope dependency.
  AddCommentsController.$inject = ['$scope', '$timeout'];

  // Declare AddCommentsController.
  function AddCommentsController($scope, $timeout) {
    var vm = this;

    // Current comment.
    vm.comment = {};

    // Array where comments will be.
    vm.comments = [];

    // Fires when form is submited.
    vm.addComment = function() {

      // Add current date to the comment.
      vm.comment.date = Date.now();

      vm.comments.push( vm.comment );
      vm.comment = {};

      // Reset clases of the form after submit.
      $scope.form.$setPristine();
    }
  }

})();

CSS:
.comment-form .form .input{
  background-color: #fcfcfc;
  border: none;
  border-radius: 4px;
  box-shadow: 0 1px 1px rgba(0, 0, 0, .15);
  color: #555f77;
  font-family: inherit;
  font-size: 14px;
  padding: 5px 10px;
  outline: none;
  width: 100%;
}

.comment-form .form textarea.input{
  height: 100px;
  padding: 15px;
}

.comment-form .form input[type=submit]{
  background-color: #555f77;
  border: none;
  border-radius: 4px;
  box-shadow: 0 1px 1px rgba(0, 0, 0, .15);
  color: #fff;
  cursor: pointer;
  display: block;
  margin-left: auto;
  outline: none;
  padding: 6px 15px;
}

.comment-form .form .input.disabled {
    background-color: #E8E8E8;
}

.comment-form,
.comment{
  margin-bottom: 20px;
  position: relative;
  z-index: 0;
}

.comment .comment-box{
  background-color: #fcfcfc;
  border-radius: 4px;
  box-shadow: 0 1px 1px rgba(0, 0, 0, .15);
  margin-left: 100px;
  min-height: 60px;
  position: relative;
  padding: 15px;
}

.comment .comment-box:before,
.comment .comment-box:after{
  border-width: 10px 10px 10px 0;
  border-style: solid;
  border-color: transparent #FCFCFC;
  content: "";
  left: -10px;
  position: absolute;
  top: 20px;
}

.comment .comment-box:before{
  border-color: transparent rgba(0, 0, 0, .05);
   top: 22px;
}

.comment .comment-footer:after{
  content: "";
  display: table;
  clear: both;
}

.comment .comment-footer a{
  color: #acb4c2;
  text-decoration: none;
}

.comment .comment-footer a:hover{
  color: #555f77;
  text-decoration: underline;
}

.comment .comment-info{
  float: left;
  width: 85%;
}

.comment .comment-date:before{
  content: "|";
  margin: 0 10px;
}

.comment-actions{
  float: left;
  text-align: right;
  width: 15%;
}

There is also a fiddle at https://jsfiddle.net/kurzalowski/eefyap1y/

A:

You can change addComment to:
vm.addComment = function(oldComment) {
  if (oldComment !== undefined) {

    oldComment.comment.date = Date.now();

    if (!oldComment.comments) {
      oldComment.comments = [];
    }

    oldComment.comments.push({
      text: oldComment.comment.text,
      date: oldComment.comment.date
    });
  } else {
    // Add current date to the comment.
    vm.comment.date = Date.now();
    vm.comments.push(vm.comment);
    vm.comment = {};
  }
// Reset clases of the form after submit.
    $scope.form.$setPristine();

So structure will be:
[
  {
    "text": "sdsd",
    "date": 1504440173932,
    "showReply": true,
    "comment": {
      "text": "aaaaa2",
      "date": 1504440258984
    },
    "comments": [
      {
        "text": "aaaaa",
        "date": 1504440176459
      },
      {
        "text": "aaaaa2",
        "date": 1504440258984
      }
    ]
  }
]

Demo Fiddle

Full HTML

            {{ comment.date | date: 'medium' }}

            Reply

{{subcomment.text}}

              <form class="form" name="form" ng-submit="form.$valid && commCtrl.addComment(comment)" novalidate>

                  <textarea class="input" ng-model="comment.comment.text" placeholder="Add comment..." required></textarea>

                  <input type="submit" value="SEND">

              </form>

{{ comment.text }}

      <form class="form" name="form" ng-submit="form.$valid && commCtrl.addComment()" novalidate>

          <textarea class="input" ng-model="commCtrl.comment.text" placeholder="Add comment..." required></textarea>

          <input type="submit" value="SEND">

      </form>


Q:

Tracing Batch Variable

I have this batch which executes on the server computer. There is a scheduled job which runs the batch. The Batch detects a particular file and then it executes an sqlcmd like below:
if not exist %TRIG_FILE% goto No_Triggers

sqlcmd
-S %WSL_SERVER%
-d %WSL_DATABASE%
-E
-Q "DECLARE @RES integer;DECLARE @RET varchar(1);DECLARE @MSG varchar(65);EXEC Ws_Job_Release 1,'Release Job Unlock Batch','All',0,0,'Unlock_Batch',@RET OUTPUT,@MSG OUTPUT,@RES OUTPUT"

My question is - how did the batch know what the %WSL_SERVER% variable is, because when I look at the script, there is nowhere in there which sets the %WSL_SERVER% variable.
This is the first time I'm reading a .bat script, I know a fair bit of programming, but I can't see how that variable was passed into this script so that it knows which server. There's no other batch calling this, it's from the batch run by the scheduler.
thanks
gemmo

A:

Most likely the WSL_SERVER and WSL_DATABASE are global environment variables initialised every time with your Windows session. That means they exist (are defined) in every CMD session and thus in every batch script. You can open a new Command Prompt window and issue this command
SET WSL

which will (try to) display all environment variables, whether global or local, whose names start with WSL. My guess is the output will show you at least the two WSL variables used in your script.
There is a number of global variables pre-defined and maintained by the OS. Yours, however, are probably user-defined (just my guess based on the fact that my system does not have them). User-defined variables can be created by third-party software or your own (maybe someone else's) batch scripts, as well as with a standalone invocation of the SETX command:
SETX VarName "Value"

You can use that command to change the value of any of your variables globally. Note that you can also change that value temporarily only, for the duration of the script, using the SET command as usual, if global change is undesirable:
SET "VarName=Value"


Q:

In Eclipse, how to add a folder of jars under WEB-INF/lib folder?

I am currently getting an error of
.jar will not be explored or published. Runtime ClassNotFoundExceptions may result.

The reason for that is I did not put my libraries under WEB-INF/lib folder directly. I put them in folders. Is there a way to store them rather in folders?
Structure:
WEB-INF
---lib
------folder1
---------<jars>
------folder2
---------<jars>

Those jars are not added to the classpath, even though I select them through Build Path -> Configure Build Path -> Libraries -> Add JARs...

A:

First You can create a User Library
Go to Window => Preferences=> Java => Build Path => User Libraries. => Then choose New, and give your library a name => Then add the JARs you want.
Once the Librray is created at them in class path of your project.To add
right-clicking on the project => Propertries=>Library Tab=>Add Libraries => User Libraries, and selecting your library name.


Q:

(Modernes) Buch über die Syntax des Deutschen

Ich bin auf der Suche nach einem Buch über die deutsche Syntax. Dank meiner universitären Studien kenne ich mich mit den Grundlagen der generativen Grammatik gut aus und hatte schon mit dependentiellen Theorien zu tun. Darum geht es aber erstmal nicht.
Wenige - denke ich - haben nie von der Idee gehört, dass L2-Lerner die deutsche Syntax als einen Behemoth-ähnlichen Haufen von grauenhaften Regeln wahrnehmen. Leider bin ich selbst L2-Lerner und muss sagen, dass ich nach fünf Jahren Deutschunterricht manchmal noch am Scheitern bin. In welche Reihenfolge stelle ich die Phrasen eines Satzes? Wie soll die Informationsstruktur in einem bestimmten Fall aussehen? Kann ich zehn Relativphrasen in einen Satz nacheinander einbetten, ohne dass derjenige, der meinen Aufsatz lesen wird, nach den ersten drei deswegen klagen wird?
Klar ist es, dass meine Bedenken nicht nur auf die Syntax bezogen sind. Trotzdem will ich euch fragen:
Gibt es ein Buch, das Antworten auf manche meiner Fragen geben könnte?

A:

Das Standardwerk zur Syntax der deutschen Sprache von Hans-Werner Eroms, das (oh Wunder!) "Syntax der deutschen Sprache" heißt, ist bei Google Books in Auszügen verfügbar. Es ist 2001 erschienen und deshalb ausgesprochen aktuell (zumindestens nach Maßstäben für wissenschaftliche Arbeiten). Vielleicht möchtest du mal reinschnuppern, ob das etwas nach deinem Geschmack ist.
Solche Bücher sind möglicherweise sehr gut, um zu verstehen, wieso eine Sprache so funktioniert, wie sie es eben tut. Ob sie allerdings zum Erlernen der Sprache geeignet sind, bezweifle ich - Das erworbene Regelwissen in einem normalen Gespräch anzuwenden, halte ich für unmöglich. Du würdest 10 Minuten brauchen, um einen einzelnen Satz zu formulieren. Sprache lernt man am besten, indem man die Regeln so oft wie möglich praktisch anwendet (und sie wahrscheinlich nicht einmal kennt) - nicht, indem man sie auswendig lernt.


Q:

How to convert json array to csv in spark sql

I have tried this query to get required experience from linkedin data.

 Dataset<Row> filteredData = spark
                    .sql("select full_name ,experience from (select *, explode(experience['title']) exp from tempTable )"
                            + "  a where lower(exp) like '%developer%'");

But I got this error:

and finally I tried  but I got more rows with the same name .
Dataset<Row> filteredData = spark
                    .sql("select full_name ,explode(experience) from (select *, explode(experience['title']) exp from tempTable )"
                            + "  a where lower(exp) like '%developer%'");

Please give me hint, how to convert array of string to comma separated string in the same column.

A:

You can apply UDF for making a comma separate string
Create UDF like this
def mkString(value: WrappedArray[String]): String = value.mkString(",")

Register UDF in sparkSQL context
sqlContext.udf.register("mkstring", mkString _)

Apply it on SparkSQL query
sqlContext.sql(select mkstring(columnName) from tableName)

it will return comma separate value of array


Q:

Subscribe multiple FormControl(s) only once

I have filtered out few FormControl(s) from a large FormGroup based on some logic now - I'd like to know how can I merge / combine those selected FormControls and have only one subscribe..
I looked into RxJS docs and marble diagrams but didn't understand it properly. It's very confusing to understand all of these and know which one to use for my case:
- forkJoin
- combineLatest
- merge
- join
- zip

Here's more detailed info about the question:
Let's say 2 FormControls (i.e., controlA, controlB). I want to execute my some handlerFunction whenever any of the FormControl value changes.
* It needs to execute my handlerFunction once whenever any control valueChanges (In my case any one control will be changed at one time)
Thanks.

A:

The best option for you is combineLatest that emits after all source Observables emitted at least one value and then on every emission from any source Observable:
Observable.combineLatest(controlA.valueChanges, controlB.valueChanges)
  .subscribe(...);

Eventually you can chain each source with startWith(null) to guarantee that every source will emit one item immediately and filter what you want in the subscriber.
Observable.combineLatest(
    controlA.valueChanges.startWith(null),
    controlB.valueChanges.startWith(null)
  )
  .subscribe(([val1, val2]) => ...);

Btw, about the other operators:

zip - emits only when all sources emitted the same number of items
forkJoin - emits when all sources emitted at least one item and completed (never happens with valueChanges)
merge - just merges Observables but you can't know which one emitted what value
join - I don't think that's part RxJS 5


Q:

What are the popular API to get current exchange rates for Ethereum to USD

Can you please list all the API providers for cryptocurrency to USD
Thanks in advance.

A:

I recommend CryptoCompare: https://www.cryptocompare.com/api/
Example:
GET https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=BTC,USD,EUR

{"BTC":0.1048,"USD":858.99,"EUR":662.93}


Q:

Word count in thesis (muthesis) - how to do?

Apologies if this is really simple but I cannot figure this out. I am using the muthesis template for my thesis. A requirement of the University is to include a word count at the end of the toc, lof and lot. Within this template there is already a line for the word count as
    \def\wordcount{}
I thought this would be a case of simply using the latex word count tool online http://app.uio.no/ifi/texcount/, input each of my chapters, add the numbers  up and put this into \def\wordcount{}, e.g. \def\wordcount{57103}. But when I do this, it still comes up with 'word count 999,999'.
What am I doing wrong?
Here is a MWE:
\documentclass[11pt,PhD,twoside]{muthesis}
\usepackage[T1]{fontenc}% recommended
\usepackage{textcomp}
\usepackage{todonotes}
\usepackage{amsmath}
\usepackage{amstext}

\usepackage{enumitem}
% tables
\usepackage{tabularx}
\usepackage{multirow}
\usepackage{booktabs}
% captions and floats
\usepackage[font=footnotesize,labelfont=bf]{caption}
\usepackage[aboveskip=2pt]{subcaption} % aboveskipchanges spacing     beten     caption and figure
\captionsetup[subfigure]   {justification=justified,singlelinecheck=false}     %%% alignment of  subfigure captions

\usepackage{stackengine}
% colour, graphics, diagrams
\PassOptionsToPackage{table}{xcolor}
\usepackage{graphicx}% don't load graphics as well - this covers it all     already
\usepackage{pgfplotstable}
\pgfplotstableset{col sep=comma}
\usepackage[UKenglish]{datetime}
\usepackage{parskip}
\usepackage[none]{hyphenat}
\usepackage{lscape}

% for references

\usepackage{natbib}
%\setlength{\bibhang}{5em}
\renewcommand{\bibfont}{\normalfont\small}

\usepackage{algorithm}
\usepackage{algorithmic}
\usepackage{listings}

\usepackage[]{titlesec}
\usepackage{fancyhdr}

% to sort out issues with urls
\usepackage[hyperindex,breaklinks]{hyperref}

\titleformat{\section}
{\normalfont\fontsize{13}{15}\bfseries}{\thesection}{1em}{}
\titleformat{\subsection}
{\normalfont\fontsize{13}{15}\bfseries}{\thesubsection}{1em}{}
\titleformat{\subsubsection}
{\normalfont\fontsize{13}{15}\bfseries}{\thesubsubsection}{1em}{}
\titleformat{\subsubsubsection}
{\normalfont\fontsize{13}{15}\bfseries}{\thesubsubsubsection}{1em}{}

\setcounter{tocdepth}{4}
\setcounter{secnumdepth}{4}

\def\afterpreface{\newpage
    \pagestyle{fancy}}
\pagestyle{fancy}
\fancyhf{}
\renewcommand*\headrulewidth{0pt}
\fancyhf[leh,roh]{\thepage}
\fancyhf[loh,reh]{\slshape\leftmark}

\begin{document}

\title{A thesis}
\author{AN Author}

\school{School of}
\faculty{Faculty}
\def\wordcount{57103} %%% Word count required at end of toc/lof and lot

\beforeabstract
\section*{Abstract}
\addcontentsline{toc}{chapter}{Abstract}

\begin{spacing}{1.0}
\fontsize{12}{12}\normalfont% faculty requirements for abstract
abstract   abstract   abstract   abstract   abstract   abstract            abstract   abstract   abstract   abstract   abstract   abstract   abstract   abstract   abstract   abstract   abstract   abstract   abstract   abstract   abstract   abstract   abstract   abstract   abstract   abstract   abstract   abstract   abstract   abstract   abstract   abstract   abstract   abstract   abstract
\end{spacing}

\afterabstract
\prefacesection{Acknowledgements}
I would like to thank......

\afterpreface

\chapter{Introduction}
\section{Background}
Background Background Background Background Background Background         Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background
\clearpage
\section{Background2}
Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background
\clearpage
\section{Background3}
Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background
\end{document}

A:

So the best I can come up with is to copy the \beforeabstract macro from muthesis.cls into your preamble and adjust the word count there:
\documentclass[11pt,PhD,twoside]{muthesis}

%Your preamble goes here

\def\beforeabstract{
        \pagenumbering{arabic}
        \pagestyle{plain}
        \titlep
        \ifsigpage\signaturepage\fi
        \tableofcontents
        ~\\
        ~\\
%Here the number can be adjusted
        Word Count: 57103
        % Download texcount.pl from  http://app.uio.no/ifi/texcount/ and
        % uncomment following lines to have word count handled automatically

        % Run texcount on report.tex and write results to word.count
        \immediate\write18{perl ./texcount.pl -1 -sum -relaxed -inc report.tex > word.count}
        % TC:ignore
        %Word Count: \input{word.count} % texcount ignore around this to stop error message (open recursion on file)
       % TC:endignore
        % note: if this causes an error (word.count missing, or a blank wordcount) you may need to add: " --enable-write18" (win) or "--shell-escape" (Linux) to arguments for LaTeX
        % see http://app.uio.no/ifi/texcount/faq.html for details of this and other possible errors
        ~\\
        \newpage
        \iftablespage
                \addvspace{10pt}
                \listoftables
                \newpage
        \fi
        \iffigurespage
                \addvspace{10pt}
                \listoffigures
                \newpage
        \fi}

\begin{document}

\title{A thesis}
\author{AN Author}

\school{School of}
\faculty{Faculty}

%You don't need that line
%\def\wordcount{57103} %%% Word count required at end of toc/lof and lot
\beforeabstract

\section*{Abstract}
\addcontentsline{toc}{chapter}{Abstract}

\begin{spacing}{1.0}
\fontsize{12}{12}\normalfont% faculty requirements for abstract
abstract   abstract   abstract   abstract   abstract   abstract            abstract   abstract   abstract   abstract   abstract   abstract   abstract   abstract   abstract   abstract   abstract   abstract   abstract   abstract   abstract   abstract   abstract   abstract   abstract   abstract   abstract   abstract   abstract   abstract   abstract   abstract   abstract   abstract   abstract
\end{spacing}

\afterabstract
\prefacesection{Acknowledgements}
I would like to thank......

\afterpreface

\chapter{Introduction}
\section{Background}
Background Background Background Background Background Background         Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background
\clearpage
\section{Background2}
Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background
\clearpage
\section{Background3}
Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background Background
\end{document}

In that way, you don't have to fiddle with the contents of muthesis, which you might want to keep as they are.
EDIT: After inspecting the commented lines in \beforeabstract I managed to do the word count automatically: For that, you need to run pdflatex --shell-escape report.tex and have the following code:
\def\beforeabstract{
        \pagenumbering{arabic}
        \pagestyle{plain}
        \titlep
        \ifsigpage\signaturepage\fi
        \tableofcontents
        ~\\
        ~\\
%        Word Count: 57103
        % Download texcount.pl from  http://app.uio.no/ifi/texcount/ and
        % uncomment following lines to have word count handled automatically

        % Run texcount on report.tex and write results to word.count
%Insert your file here instead of "filename.tex"
        \immediate\write18{perl ./texcount.pl -1 -sum -relaxed -inc filename.tex > word.count}
        % TC:ignore
        Word Count: \input{word.count} % texcount ignore around this to stop error message (open recursion on file)
       % TC:endignore
        % note: if this causes an error (word.count missing, or a blank wordcount) you may need to add: " --enable-write18" (win) or "--shell-escape" (Linux) to arguments for LaTeX
        % see http://app.uio.no/ifi/texcount/faq.html for details of this and other possible errors
        ~\\
        \newpage
        \iftablespage
                \addvspace{10pt}
                \listoftables
                \newpage
        \fi
        \iffigurespage
                \addvspace{10pt}
                \listoffigures
                \newpage
        \fi}

Further, you need a local copy of texcount.pl, refer to the links provided in the comments for help there.


Q:

R: how to get the definition of an overloaded generic function?

I tried to get definition of the function predict.fastLm, which is an overloaded generic function in RcppArmadillo, but the following code will fail:
library(RcppArmadillo)
getFunction('predict.fastLm')

On the other hand, it works for predict.lm:
getFunction('predict.lm')

Can anyone shed some lights on what's going on? Thanks!

A:

That function is not exported, so simply type the following instead:
> RcppArmadillo:::predict.fastLm
function (object, newdata = NULL, ...)
{
    if (is.null(newdata)) {
...

If you insist on using getFunction, specify the where argument:
getFunction('predict.fastLm', where = asNamespace('RcppArmadillo'))


Q:

What's the difference between an Application Service Provider and Cloud computing?

They seem similar and I found an article at attempted to explain the difference, but I don't understand.  They both use computers "in the cloud" or out on the Internet, so how are they different?
Thank you
EDIT:  Also, why is this different than simply getting a hosting service like "normal"?
EDIT:  I may have missed it but why is a hosting service different from a cloud service?

A:

First of all, Cloud Computing is a hot buzzword. There have been other terms for pretty much the same thing in the past. ASP is certainly one of those, as is SaaS.
I suppose the main two concepts of Cloud Computing are that

it removes the need to maintain physical hardware from the user, and
the ability to scale up and down very quickly, meaning that it is

technologically possible to use a much higher or lower amount of the service than usual at very short notice and
the contractual and billing arrangements are almost completely usage-driven (no fixed costs) and short-term (can sign-up, ramp-up, cancel at any time).

Many services offered on the Internet can fit under this fashionable umbrella.
Another interesting aspect (and this probably sets it apart from traditional ASP) is that in addition to the end-user using ASP/SaaS instead of his own hardware to run his software, the provider of that service also does not necessarily own any hardware, but can use storage, backup, computing, delivery providers himself. This makes it possible to start running an ASP with almost no initial cost. It also puts you at the mercy of a complex layer of service-level-agreements.


Q:

How to trigger a function of class via button in view

I'm setting up an application working with Django and Keras. It takes a lot of time to take my uploaded document, prepare, train and to show my results. That's why I'm trying to split my code into different phases. But I don't know how to trigger a function using my created object before. Do you know how to connect a button to trigger a process via using created object?
Thanks in advance!

A:

To trigger an action from a template view you need to set up an endpoint and use needed class/func there. You can call it with ajax if that's you want.
path('action/', app.views.action, 'action')
def action(request):
    my_util_class.my_function()
    return HttpResponse('')

Button


Q:

Basic Tic-Tac-Toe

I am starting a software engineering degree soon and have been practicing the last couple months. I have posted some code I wrote for a basic Tic Tac Toe game below (C++). I have read the worst thing to do is to get into bad habits early on, so please can you read over the code and tell me what I should be doing differently? Be as brutally honest as possible, I care more about my future than feelings. Bad practices, bad code, bad formatting, anything.
#include <iostream>
#include <string>

void playGame();
void printBoard(char board[3][3]);
int nextMove(char symbol, int plays, int playedMoves[9]);
bool checkWinner(char board[3][3], char symbol, int plays);

int main()
{
    using namespace std;

    cout << "Tic Tac Toe by Kevin\n"
        << "____________________\n\n";

    playGame();

    char yn = 'a';

    //Check if players want another game
    while (true)
    {
        while (tolower(yn) != 'y' && tolower(yn) != 'n')
        {
            cout << "Do you want to play again? (y/n): ";
            cin >> yn;

            //following 2 lines are to handle incorrect inputs
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
        }

        if (tolower(yn) == 'y')
            playGame();
        else
            break;
    }

    return 0;
}

//Where the game starts. Sets up board and runs 9 plays
void playGame()
{
    using namespace std;

    char board[3][3] =
    {
        { ' ', ' ', ' ', },
        { ' ', ' ', ' ', },
        { ' ', ' ', ' ' }
    };
    printBoard(board);

    char symbol = ' ';
    int move = 0;
    int playedMoves[9] = { 0 };

    for (int plays = 1; plays < 10; plays++)
    {
        if (!(plays % 2))
            symbol = 'O';
        else
            symbol = 'X';

        move = nextMove(symbol, plays, playedMoves);
        playedMoves[plays - 1] = move;

        int x = 0, y = 0;
        x = (move + 2) % 3;
        y = (move - 1) / 3; //math to convert 1-9 to [][]
        board[x][y] = symbol;

        printBoard(board);

        if (plays > 4)
            if (checkWinner(board, symbol, plays)) break;
    }
}

//Prints the board
void printBoard (char board[3][3])
{
    using namespace std;

    string sLine = "";

    cout << endl;

    for (int k = 0; k < 3; k++)
    {
        sLine = "";

        for (int l = 0; l < 3; l++)
        {
            sLine += board[l][k];
            if (l < 2) sLine += "|";
        }

        cout << sLine << endl;
        if (k < 2) cout << "-----" << endl;
    }

    cout << endl;
}

//Takes next move and checks for errors
int nextMove (char symbol, int plays, int playedMoves[9])
{
    using namespace std;

    bool validPlay = false;
    int move = 0;

    while (!validPlay)
    {
        while (move < 1 || move > 9)
        {
            cout << "Player " << symbol << " enter your move: ";
            cin >> move;

            if (!cin)
            {
                cin.clear();
                cin.ignore(numeric_limits<streamsize>::max(), '\n');
            }
        }

        validPlay = true;

        for (int k = 0; k < plays; k++)
        {
            if (move == playedMoves[k]) validPlay = false;
        }
    }

    return move;
}

//Check to see if a player has won or if there is a tie
bool checkWinner(char board[3][3], char symbol, int plays)
{
    using namespace std;

    bool winner = false;

    //Check vertical and horizontal
    for (int k = 0; k < 3; k++)
    {
        if (board[k][0] == symbol && board[k][1] == symbol && board[k][2] == symbol)
            winner = true;
        if (board[0][k] == symbol && board[1][k] == symbol && board[2][k] == symbol)
            winner = true;
    }

    //Check diagonal
    if (board[0][0] == symbol && board[1][1] == symbol && board[2][2] == symbol)
        winner = true;
    if (board[2][0] == symbol && board[1][1] == symbol && board[0][2] == symbol)
        winner = true;

    if (winner)
        cout << "Congratulations! The winner is " << symbol << "'s!\n\n";
    if (!(winner) && (plays == 9))
        cout << "Unfortunately it was a tie!\n\n";

    return winner;
}

A:

Here are some observations that may help you improve your code.
Use the appropriate #includes
This code uses numeric_limits which is actually defined in <limits>.  Even if your code compiles that way, it's probably only because one of the other files happened to include it.  You can't and shouldn't rely on that, though.
Use objects
You have a board structure and then separate functions printBoard and checkWinner that operate on board data. With only a slight syntax change, you would have a real object instead of C-style code written in C++.  You could declare a TicTacToe object and then play, print and checkWinner could all be member functions.
Separate I/O from program logic
Right now every individual function has both game logic and I/O.  It's often better design to separate the two so that the game logic is independent of the I/O with the user.
Use const where practical
I would not expect the checkWinner or printBoard routines to alter the underlying board on which they operate, and indeed they do not.  You should make this expectation explicit by using the const keyword:
void printBoard(const char board[3][3]);

This declares that the printBoard will not modify the passed board, making it clear to both the compiler and to the human reader of your code.
Create a function rather than repeating code
In several places in the code, a prompt is printed, then a answer read, then the input cleared.  Instead of repeating it, make it into a function.
Don't abuse using namespace std
Putting using namespace std at the top of every program is a bad habit that you'd do well to avoid.  Having it inside every function is only slightly better.  For instance, it's entirely superfluous in the playGame function and should be omitted.  For this program, I'd advocate removing it everywhere and using the std:: prefix where needed.
Think of the user
It's not intuitively obvious how to enter a move when the game first starts.  It would be better to consider the user and to offer a prompt (at least at the beginning) showing how the squares are numbered.
Fix the bug
If a player enters a square that is already filled, the program simply hangs. That's not good behavior and must be considered a bug.
Consider altering your algorithm
Right now, the checkWinner routine is only called if more than four moves have been made.  Since this code is not particularly performance sensitive, why not simply call it every time?  It would make the code a little simpler to read and the extra time taken will almost certainly never be noticed.
Declare the loop exit condition at the top
The for loop inside playGame currently says this:
for (int plays = 1; plays < 10; plays++)

Reading that line, we would conclude that the play continues until plays >= 10.  However, way down at the bottom of the loop is a break that occurs if one player has won.  Rather than forcing the reader of the code to examine every line, it's better if you simply declare loop exit conditions completely and honestly at the top.
Put conditional statements on a separate line
The code currently includes a number of places where something like this is done:
if (l < 2) sLine += "|";

It makes things a little bit harder to read than if you put them on separate lines like this:
if (l < 2) {
    sLine += "|";
}

Further, especially when you are beginning, it's useful to always put the curly braces there.  Doing so will make your intentions clear to both readers of the code and the compiler and can reduce the possibility for certain kinds of subtle bugs like this:
for (int i = 0; i < 3; ++i)
    f[k] = k*2;
    g[k] = f*7;

By the indentation, one would expect that both statements are executed every loop iteration, but the subtle lack of braces means that the compiler will do something else entirely.
Use meaningful variable names
Your function names are descriptive and good enough, but the variable names are not so good.  In particular the printBoard routine uses a loop counter named l which is a particularly bad choice of variable name.  It's too easily mistaken for the digit 1 or the letter i.
Eliminate "magic numbers"
This code has a number of "magic numbers," that is, unnamed constants such as 2, 9, 10, etc.  Generally it's better to avoid that and give such constants meaningful names.  That way, if anything ever needs to be changed, you won't have to go hunting through the code for all instances of "3" and then trying to determine if this particular 3 is relevant to the desired change or if it is some other constant that happens to have the same value.
Eliminate return 0 at the end of main
When a C++ program reaches the end of main the compiler will automatically generate code to return 0, so there is no reason to put return 0; explicitly at the end of main.

A:

This is very well-written "beginner" code.
To add to @Edward's already great answer, here are a few style considerations (i.e. opinions):
Prefer prefix increment
for (int plays = 1; plays < 10; plays++) // bad style
for (int plays = 1; plays < 10; ++plays) // good style

You'll often see people complain when you use i++ instead of ++i in for loops.
This is because these are two different operators with different semantics.
In the case of lightweight integers and pointers, there is no difference,
but there can actually be a performance penalty or even bugs due to using i++.
This is particularly true for pure input iterators, such as istream_iterator.
Avoid declaring multiple variables on the same line
int x = 0, y = 0;

Many people consider this bad style, because it gets very confusing for more complex types.
For example, with pointers:
int* x = NULL, y = NULL;

This code is incorrect, because x is a pointer, but y is a normal int. The corrected version is:
int *x = NULL, *y = NULL;

This is caused by C++'s weird inside-out type syntax.
The preferred style is usually:
int x = 0;
int y = 0;

Combine related if blocks
Inside your checkWinner function, there are a couple of instances of:
if (something)
    winner = true;
if (something_else)
    winner = true;

That can (and probably should) be transformed into:
if (something || something_else) {
    winner = true;
}

Also, at the end of your checkWinner function, we find this:
if (winner)
    cout << "Congratulations! The winner is " << symbol << "'s!\n\n";
if (!(winner) && (plays == 9))
    cout << "Unfortunately it was a tie!\n\n";

That can be transformed into this:
if (winner) {
    cout << "Congratulations! The winner is " << symbol << "'s!\n\n";
} else if (plays == 9) {
    cout << "Unfortunately it was a tie!\n\n";
}

Note: Please, please, please, put braces around your if blocks.
Regarding using namespace std;
Many people have a great distaste for using namespace.
It causes "namespace pollution", which can cause name conflicts later on.
Generally, using namespace is meant for sort of "inheriting" a namespace.
Your namespace is now a partial owner to everything in the namespace you pulled in.
Consider:
#include <string>

struct string
{
    char* data;
    int length;
};

int main()
{
    using namespace std;
    string str;
    // error: reference to 'string' is ambiguous
}

In general, a much better solution is to either prefix things with std:: or only pull in the things you need.
For example, your main:
int main()
{
    using std::cin;
    using std::cout;
    using std::tolower;
    using std::numeric_limits;
    using std::streamsize;

The advantage of this style is that you know exactly what each function depends on.
However, it can get very messy for functions that depend on a lot of things.
Another method that can be used for long or nested namespace names is namespace aliases:
#include <functional> // namespace std { namespace placeholders { struct {} _1; } }

void func(int);

int main()
{
    namespace ph = std::placeholders;
    std::bind(func, ph::_1)(7);
    // No need to understand this, the key is using `ph::_1` instead of `std::placeholders::_1`.
}

A:

I would change this:
playGame();

char yn = 'a';

//Check if players want another game
while (true)
{
    while (tolower(yn) != 'y' && tolower(yn) != 'n')
    {
        cout << "Do you want to play again? (y/n): ";
        cin >> yn;

        //following 2 lines are to handle incorrect inputs
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
    }

    if (tolower(yn) == 'y')
        playGame();
    else
        break;
}

to
char yn = 'y';
while (tolower(yn) == 'y')
{
    playGame();

    //Check if players want another game
    cout << "Do you want to play again? (y/n): ";
    cin >> yn;
    while (tolower(yn) != 'y' && tolower(yn) != 'n')
    {
        cout << "Do you want to play again? (y/n): ";
        cin >> yn;

        //following 2 lines are to handle incorrect inputs
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
    }
}


Q:

Restriction 10km of interpolation radius in QGIS

I am trying to use the Grid (Interpolation) tool from Analysis Menu in QGIS 2.18 for a small set of very few, sparsely ditributed points (they are centroids of municipalities and the quantity is population potential). But for the radius parameters of IDW method, I can't define values more than 10000m. I wonder, is it on purpose or is it a bag on the code?

A:

Strange, using QGIS 2.18.2 (Win7 64-bit), the radius limit for me is 65000. However, you could also try accessing the same tool from the Processing Toolbox and see if the radius limit there lets you go above 10000:


Q:

Can you retrieve the datagrid object with just a DataGridRow? WPF

I'm trying to retrieve the datagrid because I want to focus on a specific cell in a row. I have a DataGridRow based on the LoadingRow event that I use by doing this:
<i:EventTrigger EventName="LoadingRow">
   <utils:InteractiveCommand Command="{Binding RelativeSource = {RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.MainWindowViewModel.SDataGrid_LoadingRow}"/>
</i:EventTrigger>

But in the function receiving this, I only am able to get the DataGridRow.
    public void SDataGridLoadingRow(object param)
    {
        DataGridRowEventArgs e = param as DataGridRowEventArgs;
        e.Row.Tag = e.Row.GetIndex().ToString();
    }

I want to get a specific cell from the row and focus on it so the user can type. Is this possible?
I'm using MVVM
Also have this now
    public void SDataGridLoadingRow(object sender, DataGridRowEventArgs e)
    {
        e.Row.Tag = e.Row.GetIndex().ToString();

        DataGrid dataGrid = sender as DataGrid;
        dataGrid.Focus();

        // Cancel our focus from the current cell of the datagrid
        // if there is a current cell
        if (dataGrid.CurrentCell != null)
        {
            var cancelEdit = new System.Action(() =>
            {
                dataGrid.CancelEdit();
            });
            Application.Current.Dispatcher.BeginInvoke(cancelEdit,
                System.Windows.Threading.DispatcherPriority.ApplicationIdle, null);
        }

        dataGrid.CurrentCell = new DataGridCellInfo(
            dataGrid.Items[e.Row.GetIndex()], dataGrid.Columns[1]);

        var startEdit = new System.Action(() =>
        {
            dataGrid.BeginEdit();
        });
        Application.Current.Dispatcher.BeginInvoke(startEdit,
            System.Windows.Threading.DispatcherPriority.ApplicationIdle, null);
    }

And the previous row is still in edit mode... can't quite figure out how to get it out of edit mode...

A:

I am not sure why your LoadingRow event handler is in your ViewModel.
If you are using MVVM your viewModels shouldn't be manipulating visual element such as DataGrid and DataGridCell but only the underlying business data.
In your case you could subscribe to the LoadingRow event like this:
<DataGrid ItemsSource="{Binding BusinessObjectExemples}" LoadingRow="DataGrid_LoadingRow" />

and then in your code behind (xaml.cs file):
private void DataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
    {
        if (sender is DataGrid dataGrid && e.Row is DataGridRow row)
        {
            //You can now access your dataGrid and the row
            row.Tag = row.GetIndex().ToString();
            //The grid is still loading row so it is too early to set the current cell.
        }
    }

What you can do is subscribe to the loaded event of your grid and set the selectedCell there:
private void Grid_Loaded(object sender, RoutedEventArgs e)
    {
        //Adapt the logic for the cell you want to select
        var dataGridCellInfo = new DataGridCellInfo(this.Grid.Items[11], this.Grid.Columns[1]);
        //The grid must be focused in order to be directly editable once a cell is selected
        this.Grid.Focus();
        //Setting the SelectedCell might be neccessary to show the "Selected" visual
        this.Grid.SelectedCells.Clear();
        this.Grid.SelectedCells.Add(dataGridCellInfo);

        this.Grid.CurrentCell = dataGridCellInfo;
    }

You could also execute the same logic with a button.
Xaml:
<DataGrid x:Name="Grid" ItemsSource="{Binding BusinessObjectExemples}"
                  Loaded="Grid_Loaded" SelectionUnit="Cell" AutoGenerateColumns="False"
                  LoadingRow="DataGrid_LoadingRow">

And if some of the treatment is related to the business and needs to be in your viewModel. You can then invoke a command or run public methods from DataGrid_LoadingRow in your code behind.


Q:

How to get IMEI number for Google Nexus 7 TAB in android?

I used the below code to get IMEI number for Google Nexus 7 tab.
 I couldn't got. How can i get IMEI number for Google Nexus 7?
TelephonyManager telephonyManager = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        return telephonyManager.getDeviceId();

A:

If I am not wrong google nexus 7 doesn't have any sim. SO if there is no sim you cannot get the IMEI number of the device as the IMEI is the network dependant on gsm networks. So if the device is wifi only you cannot identify the device by IMEI. You can use MAC address instead.


Q:

Bootstrap 3 responsive table with first fixed column

I followed this and this post to lock width of first column. Table is responsive and I want to achieve fixed width of first column when I resize the table. I tried Guruprasad's post, but it doesn't work.
jsfiddle
html

                Number
                Table heading
                Table heading
                Table heading
                Table heading
                Table heading
                Table heading

                First
                Table cell
                Table cell
                Table cell
                Table cell
                Table cell
                Table cell

                Second
                Table cell
                Table cell
                Table cell
                Table cell
                Table cell
                Table cell

                Third
                Table cell
                Table cell
                Table cell
                Table cell
                Table cell
                Table cell

css
.table>thead:first-child>tr:first-child>th:first-child
{
    position: absolute;
    display: inline-block;
    height:100%;
}
.table> tbody > tr > td:first-child
{
    position: absolute;
    display: inline-block;
    height:100%;

}
.table>thead:first-child>tr:first-child>th:nth-child(2)
{
    padding-left:40px;
}
.table> tbody > tr > td:nth-child(2)
{
    padding-left:50px !important;

}

A:

I have edited your fiddle and did some changes like i removed display:inline-block and position and added fix width for that column so it will stay there.
.table>thead:first-child>tr:first-child>th:first-child
{
    height:auto;
    width:100px; /*change according to your need*/
}

For more details please check this  link .


Q:

node ssh2 shell unable to run apt-get install on remote machine

I'm doing a program in node.js to deploy my code from git to a server (Digital Ocean). I'm connecting to the server via ssh2 module and running commands via shell, like bellow:
var Client = require('ssh2').Client;

var conn = new Client();
conn.on('ready', function() {
  console.log('Client :: ready');
  conn.shell(function(err, stream) {

    if (err) throw err;

    stream.on('close', function() {

      console.log('Stream :: close');
      conn.end();

    }).on('data', function(data) {

      console.log('STDOUT: ' + data);

    }).stderr.on('data', function(data) {

      console.log('STDERR: ' + data);

    });

    stream.end('sudo apt-get update -y\nsudo apt-get install -y build-essential\nexit\n');
 });
}).connect({
  host: 'x.x.x.x',
  port: 22,
  username: 'yyy',
  privateKey: 'zzz'
});

The command "apt-get update" works fine, but the command "apt-get install build-essential" (I have tried to install other programs, like vim and curl) seems to freeze the stream on output's last line.
I think it can be caused by the prompt "Y/n" of the apt-get, but I couldn't find a workaround for it. Someone know how to deal with it?

A:

Try to change \nwith &&:
stream.end('sudo apt-get update -y && sudo apt-get install -y build-essential && exit');


Q:

Jacoco maven configuration for multi module project when some modules are present in sub directory

My Project contains following structure
pom.xml
|
|
-----sub module A pom.xml
|
|
-----sub module B pom.xml
|
|
-----sub module plugins/C pom.xml
|
|
-----sub module plugins/D pom.xml

I have configured Main pom like this
<modules>
    <module>A</module>
    <module>B</module>
    <module>plugins/C</module>
    <module>plugins/D</module>
</modules>
<plugin>
    <groupId>org.jacoco</groupId>
    <artifactId>jacoco-maven-plugin</artifactId>
    <version>0.7.7.201606060606</version>
    <executions>
        <execution>
            <goals>
                <goal>prepare-agent</goal>
            </goals>
        </execution>
        <execution>
            <id>report</id>
            <phase>prepare-package</phase>
            <goals>
                <goal>report</goal>
            </goals>
        </execution>
    </executions>
</plugin>

When I am running "mvn verify" jacoco reports are getting generated only for module A & B. For module plugin/C and plugin/D Jacoco is not executed hence no reports.

A:

This question is not about jacoco-maven-plugin, but about aggregation and inheritance in Maven.
Given example/pom.xml
<project>
  <modelVersion>4.0.0</modelVersion>

  <groupId>org.example</groupId>
  <artifactId>example</artifactId>
  <version>0.1-SNAPSHOT</version>
  <packaging>pom</packaging>

  <modules>
    <module>A</module>
    <module>plugins/C</module>
  </modules>

  <build>
    <plugins>
      <plugin>
        <groupId>org.jacoco</groupId>
        <artifactId>jacoco-maven-plugin</artifactId>
        <version>0.7.7.201606060606</version>
        <executions>
          <execution>
            <goals>
              <goal>prepare-agent</goal>
            </goals>
          </execution>
          <execution>
            <id>report</id>
            <phase>prepare-package</phase>
            <goals>
              <goal>report</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>

specifies that example/A and example/plugins/C should be built as part of build of example, but doesn't specify anything about inheritance of configuration of plugins, properties, etc.
For inheritance in example/plugins/C/pom.xml from example/pom.xml, the first one should declare the second one as parent:
<project>
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>org.example</groupId>
    <artifactId>example</artifactId>
    <version>0.1-SNAPSHOT</version>
    <relativePath>../..</relativePath>
  </parent>

  <groupId>org.example</groupId>
  <artifactId>C</artifactId>
  <version>0.1-SNAPSHOT</version>
</project>

In such case configuration of plugins will be inherited and they will be executed:
Apache Maven 3.5.0 (ff8f5e7444045639af65f6095c62210b5713f426; 2017-04-03T21:39:06+02:00)
...
[INFO] ------------------------------------------------------------------------
[INFO] Building C 0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- jacoco-maven-plugin:0.7.7.201606060606:prepare-agent (default) @ C ---
...

P.S. Latest as of today version of JaCoCo is 0.7.9.


Q:

Сбор статистической информации (DDD vs Transaction Script)

Есть список серверов. На каждом сервере свой список игроков. Периодически список игроков, как и данные сервера изменяются. По каждому игроку ведется отдельная статистика.
Для сбора информации о сервере и игроках создал отдельный контекст. Решил применить CQRS.
Для вывода статистической информации создал отдельную Read Model. Здесь все довольно просто - обычные операции чтения.
Возник вопрос относительно области записи информации.
Что лучше применить при получении обработке статистических данных:

Формировать полноценную доменную модель с набором агрегатов, событий и других тактических шаблонов
Использовать обычные сценарии транзакции (Transaction Script)

Я склоняюсь к использованию сценария транзакции:

Простота реализации
Разовое обновление большого количества данных

Использование в данном случае DDD меня смущает:

Не представляю использование подхода DDD при обработке статистической
информации - потенциально большое количество абстракций
Репозиторий предполагает редактирование одного агрегата за раз.
Допустим у меня игрок сервера является отдельным агрегатом с
соответствующей статистической информацией. При необходимости
обновления информации о большом количестве игроков будет большая
нагрузка на базу данных.

С другой стороны:

DDD позволит нормально инкапсулировать логику валидации данных.
Transaction Script со временем трудно поддерживать.

Очень нужен Ваш совет)

A:

Подход DDD хорош, когда у вас богатая предметная область: движение документов, регламенты, взаимодействие разных сущностей в рамках одного бизнес-сценария. Задачи обработки данных, тем более быстрой обработки данных, плохо ложатся на DDD, поскольку логика в них относительно простая, и для их решения достаточно SQL.
То есть, DDD слишком сложен для решения таких простых задач. Кроме того, DDD может оказаться не слишком производительным подходом, поскольку, например, предполагает загрузку агрегата целиком.
Это с одной стороны. С другой стороны, подход DDD это не набор жёстких правил, а набор принципов. Мы можем выделить под обработку данных ограниченный контекст (bounded context), где модели будут проще, чем в основном контексте.
Правила, что хранилище (repository) может обрабатывать только один агрегат за раз, в действительности не существует. Репозиторий — коллекция сверх-большого размера, и поэтому мы не можем работать со всеми её элементами непосредственно, только какими-то кусками небольшого размера. Так определяет репозитории Эванс.
Репозиторий может содержать методы групповой вставки, удаления и изменения данных, если это продиктовано предметной областью. Скорее, надо обратить внимание на то, чтобы каждый такой вызов выполнялся быстро, то есть нельзя создавать метод обновления всех записей в базе, которых может быть несколько миллионов. Вместо него нужен метод порционного (постраничного) обновления, при этом размер каждой порции может составлять 100 или 1000 записей.
Сущности для решения статистических задач не обладают поведением, поэтому в нашем ограниченном контексте мы используем паттерн анемичная модель (anemic domain model). Про него надо помнить, что его часто причисляют к анти-паттерном, и это вполне справедливо. Но в данном конкретном случае это правильное решение, поскольку, по сути, мы должны сделать срез данных в базе, и с помощью нескольких операций реляционной алгебры свести их к нескольким таблицам.
Второй подход я бы определил не просто как Transaction Script. В конечном итоге мы можем для подготовки отчётов использовать специализированное средство, которое будет иметь доступ к базе данных на чтение, какой-нибудь Microsoft Reporting Services. Возможно, нам придётся агрегировать промежуточные данные в соседней базе для того, чтобы позднее делать отчёты быстрее, и это мы сделаем на SQL.
В общем, мы не обязаны всё решение делать в рамках не только DDD, но и ООП. И даже не обязаны делать его на основном языке проекта Java/C#/Python. Здесь, скорее, определяющую роль играют навыки команды.
Единственное ограничение, которое я бы добавил к такой системе: статистическое приложение не должно менять данные в основной базе. Оно имеет доступ только для чтения, а если ему нужны собственные промежуточные данные, оно хранит их в отдельной схеме или отдельной базе. Это ограничение избавит вас от тонких ошибок.
Итого:

Если у вас вся команда пишет в основном на Java/C#/подставьте свой язык, то попробуйте ограниченный контекст с анемичными моделями и мощными репозиториями.
Если кто-то шарит в SQL/Reporting Services и так далее, можете сделать отдельное решение. Может оказаться быстрее и удобнее, чем делать то же самое на Java/C#.
Промежуточное решение: можно сделать выделенное решение на Java/C#, но с минимумом ООП. Можно использовать простые паттерны доступа к данным: row gateway, table gateway, transaction script и так далее.
Какой бы из вариантов вы ни выбрали, не пишите из второго решения в основную базу во избежание ошибок, которые трудно найти и исправить. Доступ к основной базе только для чтения, менять её может только основной контекст.


Q:

How can I avoid having too many arguments in Spring Java controllor

In my Spring web application:
    @RequestMapping(value = NEW)
public String addProduct(@RequestParam String name, @RequestParam(required = false) String description,
                         @RequestParam String price, @RequestParam String company, ModelMap model,
                         @RequestParam(required = false) String volume, @RequestParam(required = false) String weight) {
    try {
        productManagementService.addNewProduct(name, description, company, price, volume, weight);
        model.addAttribute("confirm", PRODUCT_ADDED);
        return FORM_PAGE;
    } catch (NumberFormatException e) {
        logger.log(Level.SEVERE, INVALID_VALUE);
        model.addAttribute("error", INVALID_VALUE);
        return FORM_PAGE;
    } catch (InvalidUserInputException e) {
        logger.log(Level.SEVERE, e.getMessage());
        model.addAttribute("error", e.getMessage());
        return FORM_PAGE;
    }
}

What are the possible ways to reduce/bind total number of arguments.

A:

create Form Class i.e
class MyForm{
String name;
String price;
String description;
...
 // Getters and setters included
}

and do like
@RequestMapping(value = NEW)
public String addProduct(@ModelAttribute MyForm myForm)

instantiation of MyForm and binding of request parameters to its properties and adding to ModelMap is done by spring behind the scenes.
Source: Spring Docs

An @ModelAttribute on a method argument indicates the argument should
  be retrieved from the model. If not present in the model, the argument
  should be instantiated first and then added to the model. Once present
  in the model, the argument's fields should be populated from all
  request parameters that have matching names. This is known as data
  binding in Spring MVC, a very useful mechanism that saves you from
  having to parse each form field individually.

A:

Create a class, encapsulate all the attributes in that class and then accept that class object as your @ModelAttribute. Something like:
public class MyData {

    private String name;

    private String description;

    private String price;

    private String company;

    private String volume;

    private String weight;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }

    public String getCompany() {
        return company;
    }

    public void setCompany(String company) {
        this.company = company;
    }

    public String getVolume() {
        return volume;
    }

    public void setVolume(String volume) {
        this.volume = volume;
    }

    public String getWeight() {
        return weight;
    }

    public void setWeight(String weight) {
        this.weight = weight;
    }

}

And then modifying your addProduct method like this:
public String addProduct(@ModelAttribute MyData myData, ModelMap model)


Q:

How do I go from $33/64 - 2x + x^2 \longrightarrow \bigg(x - \frac{2 + \sqrt{4 +33/16}}{2}\bigg)\bigg(x - \frac{2 - \sqrt{4 +33/16}}{2}\bigg)$?

How do I go from $\frac{33}{64} - 2x + x^2 \longrightarrow\bigg(x - \frac{2 + \sqrt{4 +33/16}}{2}\bigg)\bigg(x - \frac{2 - \sqrt{4 +33/16}}{2}\bigg)$ and then to $\big(x - 1-\frac{\sqrt{33}}{8}\big)\big(x - 1 + \frac{\sqrt{31}}{8}\big)?$

For the first, I know that it has something with the quadratic equation to do, but what is that? And how do I go from the second to the third?

A:

$$
\begin{align}
&\frac{33}{64} - 2x + x^2 \\
&= x^2 - 2x + \frac{33}{64} \\
&= x^2 - 2x + 1 - 1 + \frac{33}{64} \\
&= (x-1)^2 - 31/64 \\
&= (x-1)^2 - 31/64 \\
&= (x-1)^2 - 31/64 \\
&= \left( (x-1) - \sqrt{31}/8 \right)\cdot\left( (x-1) + \sqrt{31}/8 \right) \\
&= \color{red}{\left( x-1 - \sqrt{31}/8 \right)\cdot\left( x-1 + \sqrt{31}/8 \right)} \\
&= \left( x-\frac {2 + \sqrt{31}/4}2 \right)\cdot\left( x-\frac{2 - \sqrt{31}/4}{2} \right) \\
&= \left( x-\frac {2 + \sqrt{31/16}}2 \right)\cdot\left( x-\frac{2 - \sqrt{31/16}}{2} \right) \\
& = \left(x - \frac{2 + \sqrt{4 \color{red}-33/16}}{2}\right)\cdot\left(x - \frac{2 - \sqrt{4 \color{red}-33/16}}{2}\right)
\end{align}
$$
Please note the minus inside square roots!


Q:

Help with rubbery roti/chapatti

I have been trying to master the roti for about a year now, and I've only made perfectly soft roti a handful of times. Otherwise they come out rubbery.
The problem is NOT the dough.
I make the dough with atta, water and about a teaspoon of oil. But my mother-in-law uses the same dough and achieves perfectly soft roti every-time. She has watched me making roti and can not spot the problem.
After I roll out the roti (not too thick, not too thin, but not always in a perfect circle), I place it on a preheated tawa on high gas. I wait until bubbles come up on one side and then I flip it. Once brown spots start to appear, I flip it onto the gas. Usually they bloat, but even the bloated ones come out rubbery. I then place them in a box with paper to keep them warm.
Another thing is that these rubbery roti give stomach aches, which might mean they're undercooked. But when I cook them longer on the tawa, they get crispy and hard.
I've tried the style of dabbing the roti with a cloth (no significant change, only slightly softer), I've tried putting less flour when rolling (slightly softer but almost impossible to roll). I've tried making only small roti, and then making bigger roti. Nothing has worked.
Any feedback would be appreciated. I'm at my wits end trying to figure out what's wrong.
EDIT: My mother-in-law and I suspect it has to do with the cooking on the tawa, primarily because when I roll but she cooks it, it turns out fine. She can't tell what I'm doing wrong though then I'm flipping it.
My roti ends up slightly brownish, while hers are more white. I'm guessing that means its undercooked, but when I cook it longer it tends to get crunchy and hard.
Flips: 1st when there are bubbles and the sides start to turn up. 2nd when there are medium-brown dark spots on the roti. 3. I let it bloat for a few seconds both side on the open flame.

A:

If you are using the same dough then the issue lies in your preparation of the dough. There are too many variables to this, I would approach this systematically, eliminating variables as you go by watching your mother in law and measuring how she does things. Specifically I would look for:

Maybe your roti is too thick or too thin, measure the weight of the dough she uses for a single roti and how big she rolls it out, then replicate that yourself
under-cooking or over-cooking, see how hot she makes her pan and how long she cooks the roti
After cooking what do you do with the roti? Does your mother in law seal it in a container and keep the steam in?

I suspect your roti is too thick, and/or maybe you are cooking it too long at too low a temperature. If it's too thick it needs a longer cooking time and you either have one that's undercooked or one that's rubbery. If your pan is too cool then your roti won't cook quickly enough to trap the air in, letting it deflate and get rubbery. Try rolling them thinner and getting the pan hotter.

A:

I appreciate that this is a pretty old question now, but I have had a similar experience myself with hit and miss rotis in the past.  For me, the key has proved to be resting them before and after cooking.
I find that if I roll out the rotis and then leave them for 5-10 minutes before placing on the tawa then they bubble more readily and seem to cook more evenly than if I just add them to the tawa straight away after rolling.  I would guess this is probably because it allows the gluten in the atta to relax but I don't honestly know; I just know it helps.
Similarly, once cooked, I leave them to rest on a plate and put another plate on top.  This helps retain some of the moisture as the rotis cool and therefore retains their softness.  Doing this can even re-soften any rotis that may have overcooked and gone crusty.


Q:

Помощь с ботом ВК (php)

Использую CallBackAPI.
Не отправляется ответ на сообщение Привет.
Сервер подтвердил, токен подтверждения правильный.
Думаю не правильно функцию написал.
Без функции, все работает отлично.
<?php

if (!isset($_REQUEST)) {
return;
}
$confirmation_token = '2b9034db';
$token = 'тут мой токен сообщества';
function msgnew ($user_id, $text)
{
    $request_params = array(
    'message' => $text,
    'user_id' => $user_id,
    'access_token' => $token,
    'v' => '5.50'
    );
$get_params = http_build_query($request_params);
file_get_contents('https://api.vk.com/method/messages.send?'. $get_params);
}

$data = json_decode(file_get_contents('php://input'));

switch ($data->type) {
case 'confirmation':
    echo $confirmation_token;
break;

case 'message_new':
$bodycase = $data->object->body;
$user_id = $data->object->user_id;

    if ($bodycase == "Привет")
    {
        msgnew ($user_id, "Привет");
    }

echo 'ok';
break;

}
?>

UPD:
Использую php://input, чтобы декодировать входящий запрос JSON, в строку.
Дальше уже switch выбирает, тип входящего запроса.
Моя функция описывает только ответ на входящий запрос 'message_new'

A:

function msgnew ($user_id, $text, $token)

Решением оказалось добавление параметра $token в параметрах функции, т.к функция не имела $token описанный выше, соответственно не имела доступа к группе.


Q:

How to reuse a widget in flutter

I am learning flutter I want a particular widget to be reused with different images at run time.
How to attain this is giving me difficulties I would like to know how to get this.
I am writing the peice of code kindly suggest what is a correct way
       scaffold: CupertinoPageScaffold(
         navigationBar: CupertinoNavigationBar(
          trailing: Image.asset('assets/Menu_Button.png'),
          automaticallyImplyLeading: false,
          backgroundColor: Colors.blueAccent,
        ),
          child: SafeArea(
            child: Material(
              child: Container(
                child: Column(
                  children: [
                    Column(
                      children: <Widget>[
                       new Stack(children: <Widget>[
                       new Container(
                          child: background.Row1
                       ),
                      Container(
                          color: Colors.blueAccent,
                          child: Image.asset('assets/card_bg.png')
                      ),
                    ]
                    ),

                    Container(
                        color: Colors.blueAccent,
                     child: Row(
                     mainAxisAlignment: MainAxisAlignment.center,
                     children: <Widget>[
                     ShowingOptions('assets/image1.png').Options,//*****calling function with parameter so that it can put widget**********//
                     ShowingOptions('assets/image2.png').Options,
                     ShowingOptions('assets/image3.png').Options,
                     ShowingOptions('assets/image4.png').Options,

              ],
              ),

                  background.Row2,
                  background.Row3
                ],
              ),
            ),
          ))
            ),
      );
      }
     }

     /**********function defination starts *************/
    ShowingOptions(image) {

     Widget Options =  padding: EdgeInsets.only(bottom: 5, left: 7,
              right: 7, top: 5),
         child: Container(
         height: 55.0,
          width: 55.0,

            child: Padding(
             padding: EdgeInsets.all(1),
               child: CircleAvatar(
                backgroundColor: Colors.transparent,

                radius: 10,
                  child: new Image.asset(image, height: 150, width:
               150),
              )),
             decoration: new BoxDecoration(
           shape: BoxShape.circle,
           color: Colors.white,
           border: new Border.all(
             color: Colors.orange,
            width: 5.0,
           ),
        )
        ),

    );
  }
     }
               /**********function defination ends *************/

What Iam doing is making a funciton and when I am calling the function 'showOptions('assets/image1')' I am passing the image that I need to show.
Inside the function defination I am writing a widget that I wanted to be placed whenevr I call that funcition bys showing the image that I have passed
the way I implemented this whole is not working want a solution. I know this is not the proper way as I am new I would like to have some guidance.

A:

Create a Custom Widget,

Create a Stateless or Stateful Class
declare Required Vairables
return your Custom Widget

below is Example of CustomButton with onPressed event.
  //Create a Stateless or Stateful Class
  class CustomButton extends StatelessWidget {

  //declare Required Vairables
  final String buttonText;
  final VoidCallback onPressed;
  final bool loading;

  //constructor
  CustomButton({this.buttonText,this.onPressed,this.loading});

  @override
  Widget build(BuildContext context) {
    return Row(
      children: <Widget>[
        Expanded(
          child: Padding(
            padding: const EdgeInsets.only(left: 30,right: 30),
            child: Container(
              decoration: BoxDecoration(borderRadius: BorderRadius.all(Radius.circular(100)),
              color: Colors.red),
              child: Material(
                color: Colors.transparent,
                child: InkWell(
                  borderRadius: BorderRadius.all(Radius.circular(100)),
                  splashColor: Colors.green,
                  onTap: onPressed,
                  child: Padding(
                    padding: const EdgeInsets.all(15.0),
                    child: Center(child:
                    loading==true?
                        CircularProgressIndicator(backgroundColor: Colors.white,)
                        :
                    Text(buttonText,style: TextStyle(fontSize: 30,color: Colors.white),)),
                  ),
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }

}

Use :
CustomButtonSmall(buttonText: "Direction",onPressed: (){})