text:
Q: OSX - signed installer rejected I'm using following to sign my installer :
productsign --sign "Developer ID Installer: ACME, Inc (ABCDE12345)" "my-package-unsigned.pkg" "my-package-signed.pkg"

Output is following:
productsign: using timestamp authority for signature
productsign: signing product with identity "Developer ID Installer: ACME, Inc (ABCDE12345)" from keychain /Users/johnd/Library/Keychains/login.keychain
productsign: Wrote signed product archive to my-package-signed.pkg

Later, I check my installer and obtain following :
spctl -a -vvvv --type install my-package-signed.pkg

my-package-signed.pkg: rejected
origin=Developer ID Installer: ACME, Inc (ABCDE12345)

Any clue ?

A: Waited a few days and installer reported 'accepted' status again. Not sure what fixed it. Maybe a computer restart or an Apple update.


text:
Q: Determine homogeneous transformation matrix for reflection about the line $y = mx + b$, or specifically $y = 2x - 6$
Determine the homogeneous transformation matrix for reflection about the line
$y = mx + b$,  or specifically $ y = 2x - 6$.

I use  $mx - y +b =0$:  $\text{slope} = m$,  $\tan(\theta)= m$
intersection with the axes:
$x =0$  is $y = -b$   and  $y =0$ is  $x = \dfrac{b}{m}$
My question is, what  can I do next?

A: Write down the transform in vector form and you can derive it from scratch. The line can be written as $mx-y=-b$. The normal to the line is $\vec{n}=(m,-1)$. Let's also introduce some initial point on the line -- let's say $\vec{r}_0=(x,y)=(0,b)$. How do you reflect about a line through the center? Easy - subtract twice the projection to the normal. How about if it's not through the center? Move to the center, transform, and move back. The transform is:
$$\vec{r} \mapsto (\vec{r}-\vec{r}_0)-2\hat{n}( \hat{n}\cdot(\vec{r}-\vec{r}_0))+\vec{r}_0$$
I normalized the normal, $\hat{n}=\frac{\vec{n}}{|n|}=\frac{(m,-1)}{\sqrt{m^2+1}}$.
This can be simplified to:
$$\vec{r}-2\hat{n}( \hat{n}\cdot\vec{r})-2\hat{n}( \hat{n}\cdot\vec{r}_0)$$
The first two terms are the standard reflection matrix in 2D and represents the 2×2 block of your homogeneous 3×3 matrix. The last term is the offset that contributes to both components of the result, and is in the homogeneous coordinates obtained from the last column (which multiplies the constant third coordinate).
Observe that because $\vec{r}_0$ is on the line, it satisfies the original equation $\vec{n}\cdot\vec{r}_0=-b$, so our choice of the origin point is irrelevant.
Now, you can simply write the matrix out:
$$\begin{bmatrix}x'\\y'\\1\end{bmatrix}=\begin{bmatrix}1-2n_x^2/|n|^2 & -2n_xn_y/|n|^2 & 2n_xb/|n|^2 \\ -2n_xn_y/|n|^2 & 1-2n_y^2/|n|^2 & 2n_yb/|n|^2 \\0 & 0& 1\end{bmatrix}\begin{bmatrix}x\\y\\1\end{bmatrix}$$
In our specific case:
$$\begin{bmatrix}1-2m^2/(m^2+1) & 2m/(m^2+1) & 2mb/(m^2+1) \\ 2m/(m^2+1) & 1-2/(m^2+1) & -2b/(m^2+1) \\0 & 0& 1\end{bmatrix}$$

You can see it's way easier, if you use the canonical implicit form for the line. If you have
$$ax+by=c$$
where $a^2+b^2=1$, then the matrix simplifies to
$$\begin{bmatrix}1-2a^2 & -2ab & -2ac \\ -2ab & 1-2b^2 & -2bc \\0 & 0& 1\end{bmatrix}$$
or, if you want, $I-2(a,b,0)^T(a,b,c)$.

A: Note that any matrix $\mathbf A\cdot \vec{0}=\vec{0}$, so there is no matrix that can flip over $y=2x-6$ as it must map $\vec 0 \to (4 \frac{4}{5},-2\frac{2}{5})$.  You might want to do something about that.

redpajama_set_name: RedPajamaStackExchange


text:
Q: TF-IDF vectorizer with python I have a problem with the TfidfVectorizer function in python.
For example if I have a string like this one:
'xxx//xx. aaa.bb.ccc.d'
will be extracted these words as the key of the dictionary:
'xxx', 'xx', 'aaa', 'bb', 'ccc', 'd'
instead, I want to create these new features:
'xxx//xx.' , 'aaa.bb.ccc.d'
How can I ask to TfidfVectorizer function to select words separated by the space (' ')?

A: Have a look at:
https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfVectorizer.html
There is a parameter called token-pattern.

A: token-pattern parameter in TfidfVectorizer  used to specify custom split pattern
from sklearn.feature_extraction.text import TfidfVectorizer
a = ['xxx//xx. aaa.bb.ccc.d']
t = TfidfVectorizer(token_pattern=r"([a-z]*//[a-z]*)|([a-z.]*)")

Ouputs
[('', ''), ('', '.'), ('', 'aaa.bb.ccc.d'), ('xxx//xx', '')]

Some post cleaning is required in this case.


text:
Q: How to create a .bz2 file from a directory without using tar? I've been searching on the internet and used Archiver to make .bz2 files. My archiving tool only makes tar.bz2 and my game host doesn't read that. It reads .bz2 files only. Is there a way to make a DIRECTORY into a .bz2 file?
I've tried sudo bzip2 but it doesn't accept directories.

A: No; bzip2 and the other compression utilities only compress a single file, so if you want to archive multiple files you need another tool like tar first, then compress the archive.


text:
Q: Web worker imports are failing on the deployed React 18 / CRA I use a web worker to encrypt large files in my create-react-app.
In my encryption.worker.js file i import CryptoJS like so..
import * as CryptoJS from "crypto-js";

// eslint-disable-next-line no-restricted-globals
self.onmessage = async function (e) {
    const workerResult = await encryptFile(e.data.file, e.data.key);
    self.postMessage({result: workerResult, keyName: e.data.keyName}); // eslint-disable-line no-restricted-globals
}; ...

Then in my React component, I import and use this webworker like this:
const webworker = React.useMemo(() => new Worker(new URL('../WebWorkers/encryption.worker.js', import.meta.url)), []);

This works when run my app in development, however when the app is deployed, I get such errors:

Specifically:
Refused to execute script from 'https://DOMAIN+OF+THE+APP/publisher/static/js/static/js/541.fda53aa0.chunk.js' because its MIME type ('text/html') is not executable.

Source map from Chrome in case its helpful:

Is there something I'm doing wrong? Please advise..
--- UPDATE ---
The problem is that the url formed by
new URL('../WebWorkers/encryption.worker.js', import.meta.url)

is
https://DOMAIN+OF+THE+APP/publisher/static/js/static/js/541.fda53aa0.chunk.js
The problem is here .../static/js/static/js/.... However, I don't know how to fix this still.

A: Don't look at a source map when source fails to load. Don't forget it's just a map. This error makes the issue very clear:
because its MIME type ('text/html') is not executable
The URL is wrong. Since the import is done by webpack, I think it happens because your paths inside your project do not patch the path structure as seen from the server.
Since you're using webpack anyway, why don't you pack the crypto directly in the worker code? Is that to save resources and allow shared caching of that component?


text:
Q: Finding the differences in 2 Textboxes Interop C# I have 2 PowerPoint presentations one original and one edited and in each of them I have a TextBox.
The idea of this is to find any text that doesn't match. When I find text that doesn't match in the 2 TextBoxes I find the position of the edited word in the TextBoxin the edited presentation and add that word to the original presentation's textbox
e.g In My original presentation has a TextBox that contains "This is New" and in my edited presentation I have "Thisssss is Blaaa". When I run my code I get the following "This Thisssss is New Blaaa". This all works fine however when I have a TextBox in my original PowerPoint with the string "This This" and an edited TextBox saying "Thissss Blaa" I should get "This Thissss This Blaa" however I get "This Thissss Blaa" instead. It doesn't get the second "This" from the original TextBox for some reason. Any ideas how I could fix this?
var q = from original in originalList
        join editedTmp in editList on original.Id equals editedTmp.Id into g
        from edited in g.DefaultIfEmpty()
        select new
        {
            original,
            edited
        };

foreach (var item in q)
{
    var originalString = item.original.TextFrame.TextRange.Text;
    var editString = item.edited.TextFrame.TextRange.Text;
    var firstStringList = originalString.Split(delimiter).ToList();
    var secondStringList = editString.Split(delimiter).ToList();

    foreach (var word in firstStringList)
    {
        if (secondStringList.IndexOf(word) == -1)
        {
            var indexOfWord = firstStringList.IndexOf(word); //gets the position of the edited word eg. 3.
            // using indexOfWord+indexOfWord as I need do this if more than one word is added.
            secondStringList.Insert(indexOfWord + indexOfWord, word);
            // Insert the word that was not found at position 3 inside secondStringList
            one.Add(word);
        }
    }
    // Join the secondStringList to make 1 string separated by the space character
    item.edited.TextFrame.TextRange.Text = string.Join(" ", secondStringList);
}

A: Instead of getting the 'current' index inside firstStringList via IndexOf, you can declare indexOfWord outside of the foreach loop and count up yourself so the variable holds the current index.
Otherwise firstStringList.IndexOf() will return the first occurence of the current string.
Furthermore, you can pass that index as second parameter to secondStringList.IndexOf() to ensure that you don't get the index of an already inserted string.
int indexOfWord=0;
foreach (var word in firstStringList)
{
    if (secondStringList.IndexOf(word,indexOfWord) == -1)
    {
        // using indexOfWord+indexOfWord as I need do this if more than one word is added.
        secondStringList.Insert(indexOfWord + indexOfWord, word);
        // Insert the word that was not found at position 3 inside secondStringList
        one.Add(word);
    }
    indexOfWord++;
}

Not sure if that works in all cases but with the given example it worked fine for me.


text:
Q: How to update my user account data on ASP.net MVC 5 application I am new to the asp.net MVC 5 identity framework andI am try to do update my details directly.
Straight forward, What I want to do is to update my user information to the database.
Previously, I changed my user details by using Migrations and I use entity framework in order to generate my controller, view and model it self.
However,  How do I update my user details. I have seen role methods..but I never understand, How can I do? without using role..Because,
I want to update all of user information that I needed to do it in UserManageController...
Is it possible? in a different controller and getting values directly on generated user account? How to retrieve then?
Here is my Identity Models
// You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
    public class ApplicationUser : IdentityUser
    {
        public string userFname { get; set; }
        public string userLname { get; set; }
        public string address { get; set; }
        public string userContactNo { get; set; }
        public string commercialName { get; set; }
        public string commercialAddress { get; set; }
        public string commercialEmail { get; set; }
        public string userType { get; set; }

        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }
    }

Here is my Registeration model
public class RegisterViewModel
{
    [Required]
    [Display(Name = "User First Name")]
    public string userFname { get; set; }

    [Required]
    [Display(Name = "User Last Name")]
    public string userLname { get; set; }

    [Required]
    [Display(Name = "User Address")]
    public string address { get; set; }

    [Required]
    [Display(Name = "User Contact Number")]
    public string userContactNo { get; set; }

    [Display(Name = "Commercial Name")]
    public string commercialName { get; set; }

    [Display(Name = "Commercial Address")]
    public string commercialAddress { get; set; }

    [EmailAddress]
    [Display(Name = "Commercial Email")]
    public string commercialEmail { get; set; }

    [Key]
    [Required]
    [EmailAddress]
    [Display(Name = "Email")]
    public string Email { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }

    [Required]
    public string userType { get; set; }

}

A: How I do this,
UPDATED: As he commented in my answer bellow, he want to update a list of users in the same method. So this will work.
[HttpPost]
public async Task<ActionResult> UpdateUserInfo(List<RegisterViewModel> model)
{
  if (!ModelState.IsValid)
    {
        return View(model);
    }

    var userStore = new UserStore<ApplicationUser>(new
                                  ApplicationDbContext());
    var appManager = new UserManager<ApplicationUser>(userStore);

    // here you can do a foreach loop and get the email and assign new datas
    foreach(var i in model)
     {
       var currentUser = appManager.FindByEmail(i.Email);

       // here you can assign the updated values
       currentUser.userFname = i.userFname;
       // and rest fields are goes here
       await appManager.UpdateAsync(currentUser);
     }
    var ctx = userStore.Context;
    ctx.SaveChanges();
    // now you can redirect to some other method or-else you can return
    // to this view itself by returning the data

    return RedirectToAction("SomeActionMethod");
}

And yes, you should have the fields in your view and there will be a @Html.BeginForm and a submit button to post your data. Or-else you can post by ajax method
Hope it helps.

A: Assuming that your ApplicationUser class is part of your Entity Framework DBContext, you can retrieve and update a user like so, using Entity Framework;
var userId = "user id here"; // Set a user ID that you would like to retrieve

var dbContext = new YourDbContext(); // Your entity framework DbContext

// Retrieve a user from the database
var user = dbContext.Set<ApplicationUser>().Find(userId);

// Update a property on your user
user.address = "New value";

// Save the new value to the database
dbContext.SaveChanges();

If you need the userId of the current logged in user, use:
var userId = this.User.Identity.GetUserId();

Multiple users can be retrieved and updated like this:
var dbContext = new YourDbContext();

// Get all users
var users = dbContext.Set<ApplicationUser>().ToList();

foreach (var user in users)
{
   user.address = "New value";
}

// Save the new value to the database
dbContext.SaveChanges();

Entity framework will automatically track the changes to each for when you save.


text:
Q: How do I segue from a nested collectionView cell? I have a collectionView used for scrolling between pages, inside of one of these full page cells I have another collectionView with cells. How do I perform a segue when one of the cells inside of the inner most collectionView is tapped.

A: You will need a delegate on the cells with collection view, that will need to be notified when a particular cell is selected:
protocol CollectionCellDelegate: class {
    func selectedItem()
}

class CollectionCell: UITableViewCell {

    weak var delegate: CollectionCellDelegate?

    // ...

    func collectionView(_ collectionView: UICollectionView,
                    didSelectItemAt indexPath: IndexPath) {
        self.delegate?.selectedItem()
    }
}

And in the TableViewController you will have to implement that delegate to perform segue from it (you have to perform segue from UIViewController subclass, but the UITableViewCell is not subclassing it, that's why you need the delegate pattern).
class TableViewController: UITableViewController, CollectionCellDelegate {

    // ...

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CollectionCell", for: indexPath) as! CollectionCell
        // set its delegate to self
        cell.delegate = self
        return cell
    }

    func selectedItem() {
        // here you can perform segue
        performSegue(withIdentifier: "mySegue", sender: self)
    }

}

I haven't passed any argument to the delegate, but you can of course use arguments to pass any information that you need for the segue (e.g., the id of the collection cell that was selected, etc.).

A: When you tap on an item in collectionView, the following delegate method will be called (if you wired up everything properly) func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)... notice that the first param is collectionView itself.
Depending on how you set it up...
if you have two collectionViews within one UIViewController then you can do..
func collectionView(_ collectionView: UICollectionView,
             didSelectItemAt indexPath: IndexPath) {
  if collectionView == self.innerCollectionView {
     // performSegue...
  }
}

if you have two view controllers, one for outer and another for inner.. then you can create use delegate pattern to let the outer know which item got selected, and segue using that info.


text:
Q: optical mark reader (omr) in php I am working on a project (OMR) in PHP. i have google it but did not find any solution.
now my question is that what is the best way of comparing two images to get the result.

A: I am developing a PHP package that uses ImageMagick to read markup on images.
Maybe that can help you https://github.com/jansenfelipe/omr


text:
Q: Why don't my array values reflect what I see on the screen? I'm working on a snake game. When my snake "eats" a piece of blue food, I add another piece to its tail. However, when I console.log the snake array, I don't see the individual data attributes for each snake piece. I only see the position of the snake's head duplicated based on the snake's current length.
Is this happening because the setInterval that makes the snake move is too short of an interval? Is the snake moving so quickly that when console.log happens every piece is currently passing through where the head moves? Or is there some delay with what I'm seeing on the screen and where the snake array is? How can I fix my code so that I get the accurate values of each piece in the snake array? I want the array to reflect what I see on the screen.
If you press the shift key the snake will pause, but console.log still doesn't display the correct values. The arrow keys control the snake's movements. Click on the grid first to start playing.

//In the moveSnake function I had to use code from the below link in order to ignore multiple keydown events.
//https://stackoverflow.com/questions/9098901/how-to-disable-repetitive-keydown-in-jquery

$(document).ready(function() {
  makebox();
  addSnake();
  moveSnake();
  addFood();
  killSnake();
  addToSnake();
  });

function makebox() {

  var size = 24;  //24
  var boxSize = 12; //12
  for (i=1;i<=size*size;i++) {
    $("#container").append("

");
  };
  $("#container").width(size*boxSize + "px");
  $(".box").width(boxSize + "");
  $(".box").height(boxSize + "px");
  $(".box").each( function(i) {
    $(this).attr('data', (i+1));
  });
  };

function addSnake () {

var rightTime, leftTime, downTime, upTime, right, left, up, lildown;

moveRight = function() {
console.log(snake);
  right = true;
  left= false;
  up = false;
  lildown = false;
  down = {}
  rightTime = setInterval(function(){
  for (var i=0;i<snake.length;i++) {
    snake[i]++
$('*[data="' + snake[i] + '"]').addClass("hover")
$('*[data="' + (snake[snake.length-1]-snake.length) + '"]').removeClass("hover");

} }, 150)

};

moveLeft = function() {
  console.log(snake);
  right = false;
  left= true;
  up = false;
  lildown = false;
  down = {}
  leftTime = setInterval(function(){ //snake -= 1
    for (var i = 0; i <snake.length;i++){
        snake[i] -= 1
  $('*[data="' + snake[i] + '"]').addClass("hover");
  $('*[data="' + (snake[snake.length-1]+snake.length ) + '"]').removeClass("hover");
} }, 150)

};

moveDown = function() {
console.log(snake);
  right = false;
  left= false;
  up = false;
  lildown = true;
  down = {}
  downTime = setInterval(function(){ //snake += 25
    for (var i = 0; i <snake.length;i++){
        snake[i] += 18
  $('*[data="' + snake[i] + '"]').addClass("hover");
  $('*[data="' + (snake[snake.length-1] - 18 * snake.length) + '"]').removeClass("hover");

} }, 150)

};

moveUp = function() {
console.log(snake);
  right = false;
  left= false;
  up = true;
  lildown = false;
  down = {}
  upTime = setInterval(function(){ //snake -= 25
for (var i = 0; i <snake.length;i++){
        snake[i] -= 18
  $('*[data="' + snake[i] + '"]').addClass("hover");
  $('*[data="' + (snake[snake.length-1] + 18 * snake.length) + '"]').removeClass("hover");
} }, 150)

};

addTail = function() {
    snake.push(snake[snake.length - 1])
console.log(snake)
  }

var snake = [42]

$('*[data="' + snake[0] + '"]').addClass("hover");

var down = {};

removeExtra = function(){

var array = [];

  $(".hover").each(function() {
      array.push($(this).attr("data"));
  });

var len = array.length
var len2 = snake.length - 1
var combo = len-len2

  //for (var i=0;i<len2;i++){
    //array.splice(0,i)
    //$('*[data="' + (array[i]) + '"]').removeClass("hover");}

 }

  moveSnake = function() {

    $(document).keydown(function(event){

   var keycode = (event.keyCode ? event.keyCode : event.which);

   if(keycode == '39'){
        if (down['39'] == null) {
          window.clearInterval(leftTime);
          window.clearInterval(downTime);
          window.clearInterval(upTime);
          moveRight();
          removeExtra();
          down['39'] = true;

                             }
   }

  else if(keycode == '37'){
        if (down['37'] == null) {
          window.clearInterval(rightTime);
          window.clearInterval(downTime);
          window.clearInterval(upTime);
          moveLeft();
        removeExtra();
          down['37'] = true;
                    }
   }

   else if(keycode == '40'){
         if (down['40'] == null) {
           window.clearInterval(leftTime);
           window.clearInterval(rightTime);
           window.clearInterval(upTime);
           moveDown();
        removeExtra();
           down['40'] = true;
                     }
    }

    else if(keycode == '38'){
          if (down['38'] == null) {
            window.clearInterval(leftTime);
            window.clearInterval(rightTime);
            window.clearInterval(downTime);
            moveUp();
        removeExtra();
            down['38'] = true;
                      }
     }

          else if(keycode == '16'){

            window.clearInterval(upTime);
            window.clearInterval(leftTime);
            window.clearInterval(rightTime);
            window.clearInterval(downTime);
            console.log(snake)
          }

 });

 addToSnake = function(){
   var count = 0;

     var config = { attributes: true, childList: true, characterData: true };

     $(".box, .food").each(function () {
       var target = this;
       var observer = new MutationObserver(function(mutations) {
         mutations.forEach(function(mutation) {
          if ($(".food").hasClass("hover") == true){
            $(".box").removeClass("food")
            addTail();
            addFood();
                      }
                    });
                  });

      observer.observe(target, config);

   });

           }

  killSnake = function() {
    var config = { attributes: true, childList: true, characterData: true, subtree:true };

    $(".right-border, .left-border, .top-border, .bottom-border").each(function () {
      var target = this;
      var observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
          console.log("Game over!")
        });
      });

    observer.observe(target, config);
  });
          }
}

addFood = function(){
  var random = Math.floor(Math.random() * (500 - 1 + 1)) + 1;
  $('*[data="' + random + '"]').addClass("food")

};

};
.box {
  display: inline-block;
  border: 2px grey solid;

}

#container {
  display: block;
  border: 2px black solid;
  border-radius: 5px;
  font-size: 0;
  margin: 10px auto;
}
.hover {
  background-color: black;
}

.food {
  background-color: blue;
}

.white {
  background-color: white;
}

.right-border, .left-border, .top-border, .bottom-border {
  background: red;
  border: 2px red solid;

}
<!DOCTYPE html>

  <title>Snake</title>

  <meta charset="utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

  <link rel="stylesheet" href="style.css">

Snake

A: Wellll.. I've managed to fix this game somehow, mainly by doing 2 things:

*

*Splitting the removal of the last tile & adding the first tile from updating snake indexes(values in the array). You got bugs in your code other that array values, and they are fixed this way.

*adding the variable that remembers the last field where the snake has been and using that variable to add tile when a snake eats something. this is the main fix to your issue, as previously, you were basically copying values in an array, and it worked only by mistake (bad loop).

So, now it should work as expected, buuuut..

*

*It's blasphemy against God to use jquery in a game, it has terrible performance comparing to vanilla, and won't help you in any possible way.

*Movement & updating should occur inside 1 interval/frame loop, not inside 4 loops, it's serious crime against DRY rule.

*It'll be probably easier to use 2-dimensional array.

*And several others

//In the moveSnake function I had to use code from the below link in order to ignore multiple keydown events.
//https://stackoverflow.com/questions/9098901/how-to-disable-repetitive-keydown-in-jquery

$(document).ready(function() {
  makebox();
  addSnake();
  moveSnake();
  addFood();
  killSnake();
  addToSnake();
  });

  var previousSnake = null;

function makebox() {

  var size = 24;  //24
  var boxSize = 12; //12
  for (i=1;i<=size*size;i++) {
    $("#container").append("

");
  };
  $("#container").width(size*boxSize + "px");
  $(".box").width(boxSize + "");
  $(".box").height(boxSize + "px");
  $(".box").each( function(i) {
    $(this).attr('data', (i+1));
  });
  };

function addSnake () {

var rightTime, leftTime, downTime, upTime, right, left, up, lildown;

moveRight = function() {
console.log(snake);
  right = true;
  left= false;
  up = false;
  lildown = false;
  down = {}
  rightTime = setInterval(function(){

$('*[data="' + (snake[0]+1) + '"]').addClass("hover")
$('*[data="' + snake[snake.length-1] + '"]').removeClass("hover");
previousSnake = snake[snake.length-1]
updateSnakeNumbers(snake[0]+1)
 }, 150)

};

moveLeft = function() {
  console.log(snake);
  right = false;
  left= true;
  up = false;
  lildown = false;
  down = {}
  leftTime = setInterval(function(){ //snake -= 1
  console.log('llll',JSON.stringify(snake))
  $('*[data="' + (snake[0]-1) + '"]').addClass("hover");
  $('*[data="' + snake[snake.length-1]  + '"]').removeClass("hover");
  previousSnake = snake[snake.length-1]
  console.log('llll',JSON.stringify(snake))
  updateSnakeNumbers(snake[0]-1)
  console.log('llll',JSON.stringify(snake))
 }, 150)

};

moveDown = function() {
console.log(snake);
  right = false;
  left= false;
  up = false;
  lildown = true;
  down = {}
  downTime = setInterval(function(){ //snake += 25
  $('*[data="' + (snake[0]+18) + '"]').addClass("hover");
  $('*[data="' + snake[snake.length-1] + '"]').removeClass("hover");
  previousSnake = snake[snake.length-1]
updateSnakeNumbers(snake[0]+18)

}, 150)

};

moveUp = function() {
console.log(JSON.stringify(snake));
  right = false;
  left= false;
  up = true;
  lildown = false;
  down = {}
  upTime = setInterval(function(){ //snake -= 25
  $('*[data="' + (snake[0]-18) + '"]').addClass("hover");
  $('*[data="' + snake[snake.length-1]  + '"]').removeClass("hover");
  previousSnake = snake[snake.length-1]
  updateSnakeNumbers(snake[0]-18)
 }, 150)

};

addTail = function() {
  console.log(JSON.stringify(snake),previousSnake)
    snake.push(previousSnake)
console.log(JSON.stringify(snake),previousSnake)
  }

var snake = [42]

function updateSnakeNumbers(head){
  var prevNum = head
  snake = snake.map(n=>{
    var tmpPrev = prevNum;
    prevNum = n;
    return tmpPrev
  })
}

$('*[data="' + snake[0] + '"]').addClass("hover");

var down = {};

removeExtra = function(){

var array = [];

  $(".hover").each(function() {
      array.push($(this).attr("data"));
  });

var len = array.length
var len2 = snake.length - 1
var combo = len-len2

  //for (var i=0;i<len2;i++){
    //array.splice(0,i)
    //$('*[data="' + (array[i]) + '"]').removeClass("hover");}

 }

  moveSnake = function() {

    $(document).keydown(function(event){

   var keycode = (event.keyCode ? event.keyCode : event.which);

   if(keycode == '39'){
        if (down['39'] == null) {
          window.clearInterval(leftTime);
          window.clearInterval(downTime);
          window.clearInterval(upTime);
          moveRight();
          removeExtra();
          down['39'] = true;

                             }
   }

  else if(keycode == '37'){
        if (down['37'] == null) {
          window.clearInterval(rightTime);
          window.clearInterval(downTime);
          window.clearInterval(upTime);
          moveLeft();
        removeExtra();
          down['37'] = true;
                    }
   }

   else if(keycode == '40'){
         if (down['40'] == null) {
           window.clearInterval(leftTime);
           window.clearInterval(rightTime);
           window.clearInterval(upTime);
           moveDown();
        removeExtra();
           down['40'] = true;
                     }
    }

    else if(keycode == '38'){
          if (down['38'] == null) {
            window.clearInterval(leftTime);
            window.clearInterval(rightTime);
            window.clearInterval(downTime);
            moveUp();
        removeExtra();
            down['38'] = true;
                      }
     }

          else if(keycode == '16'){

            window.clearInterval(upTime);
            window.clearInterval(leftTime);
            window.clearInterval(rightTime);
            window.clearInterval(downTime);
            console.log(snake)
          }

 });

 addToSnake = function(){
   var count = 0;

     var config = { attributes: true, childList: true, characterData: true };

     $(".box, .food").each(function () {
       var target = this;
       var observer = new MutationObserver(function(mutations) {
         mutations.forEach(function(mutation) {
          if ($(".food").hasClass("hover") == true){
            $(".box").removeClass("food")
            addTail();
            addFood();
                      }
                    });
                  });

      observer.observe(target, config);

   });

           }

  killSnake = function() {
    var config = { attributes: true, childList: true, characterData: true, subtree:true };

    $(".right-border, .left-border, .top-border, .bottom-border").each(function () {
      var target = this;
      var observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
          console.log("Game over!")
        });
      });

    observer.observe(target, config);
  });
          }
}

addFood = function(){
  var random = Math.floor(Math.random() * (500 - 1 + 1)) + 1;
  $('*[data="' + random + '"]').addClass("food")

};

};
.box {
  display: inline-block;
  border: 2px grey solid;

}

#container {
  display: block;
  border: 2px black solid;
  border-radius: 5px;
  font-size: 0;
  margin: 10px auto;
}
.hover {
  background-color: black;
}

.food {
  background-color: blue;
}

.white {
  background-color: white;
}

.right-border, .left-border, .top-border, .bottom-border {
  background: red;
  border: 2px red solid;

}
<!DOCTYPE html>

  <title>Snake</title>

  <meta charset="utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

  <link rel="stylesheet" href="style.css">

Snake


text:
Q: Postgres: how does a default value get populated? To be clear, I want to know what is the mechanism that is used to populate the default value not the SQL syntax needed to create the default value constraint on the table.
Does Postgres use some kind of trigger that updates the default value if it is missing or something else?. I couldn't find an explanation on the official website.

A: This happens in the rewriteTargetListIU function in src/backend/rewrite/rewriteHandler.c. The comment says it all:
/*
 * rewriteTargetListIU - rewrite INSERT/UPDATE targetlist into standard form
 *
 * This has the following responsibilities:
 *
 * 1. For an INSERT, add tlist entries to compute default values for any
 * attributes that have defaults and are not assigned to in the given tlist.
 * (We do not insert anything for default-less attributes, however.  The
 * planner will later insert NULLs for them, but there's no reason to slow
 * down rewriter processing with extra tlist nodes.)  Also, for both INSERT
 * and UPDATE, replace explicit DEFAULT specifications with column default
 * expressions.

So this happens during query rewrite, which is the step between parsing the SQL string and optimizing it.


text:
Q: Customer Status is undefined I have a typescript code with simple if else logic
endDate: String = '';
customerStatus: String;
this.endDate = this.sampleData.customerStartDate;
if (this.endDate == null) {
this.customerStatus = 'Active';
} else {
this.customerStatus = 'In Active';
}

HTML Code:

{{customerStatus}}

    Customer Status

If I debug the code then in endDate I can see the value but in CustomerStatus I am getting Undefined and as a result, nothing is being displayed on HTML.
The logic is if the customer has end date then the customer is In-Active or else the customer is Active
What am I doing wrong?

A: You did not check null for sampleData object before using customerStartDate property.
Because line of code this.sampleData.customerStartDate throw exception, the next line of code cant executed.
Edit this line of code, it worked.
this.endDate = this.sampleData != null ? this.sampleData.customerStartDate : null;

https://stackblitz.com/edit/angular-wefvju


text:
Q: How can I open a web api URL from within Visual Studio I have a feeling this is off topic as it's not about code but, it is something any one working in MVC and Visual Studio is likely going to find useful.
Is it possible to open a browser at the URL of the route I am working on within MVC or Web Api?
For example, if my Web Api looked like
[Route("api/[controller]")]
[ApiController]
public class MyApi : ControllerBase
{
    [HttpGet]
    [Route("GetItAll")]
    public JsonResult Get()
    {
        return GetData();
    }
}

I'd like to be able to, for example, right click in the Get function, and choose 'launch in browser'.
Then, Visual Studio would generate the URL (in this case .../api/MyApi/GetItAll), start debugging and navigate to this URL in the browser


text:
Q: core.autocrlf true is not applied to a changed text file While having read a lot of documentation on EoL on different OS I am failing to understand why my yml file EoLs are not converted to LF automatically.
I made a mistake by creating a yml file in Notepad++ on Windows. However, I have core.autocrlf set to true. That's why I expect git to perform EoL convertion automatically. But no matter what I tried(editting the file again, replacing EoL in my IDE, etc.), I still see ^M instead of proper line ending when I push my file into github.
For some reason setting a global property is not enough.
What helped me in the end is adding a .gitattributes file to a repo, as explained here.
So, despite the fact that I found a solution that I really like and, to my mind, is preferable because the configurations are stored along with the code, I want to understnad why git config --global core.autocrlf true didn't work for me when multiple sources state something akin to:

core.autocrlf true: Git will process all text files and make sure that CRLF is replaced with LF when writing that file to the object database and turn all LF back into CRLF when writing out into the working directory.


text:
Q: TSQL Fill gaps in months and repeat values in column Started with TSQL last Wednesday...
I have the following data in tblStage1:
PROJECT    USERNAME           DATE          PERCENTAGE
---------  -----------------  ------------  ----------------------
Project 1  DOMAIN\Chris.User  03/01/2013    0.25
Project 1  DOMAIN\Chris.User  05/01/2013    0.75
Project 1  DOMAIN\Chris.User  07/01/2013    1
Project 1  DOMAIN\John.User   02/01/2013    1
Project 1  DOMAIN\John.User   06/01/2013    0.5

I have the following data in tblRawData
PROJECT    START_DATE   END_DATE
---------- -----------  ----------
Project 1  01/01/2013   09/01/2013

I would like to get the following data out into tblStage2 (data points are bound by START_DATE and END_DATE):
PROJECT    USERNAME           DATE          PERCENTAGE
---------  -----------------  ------------  ----------------------
Project 1  DOMAIN\Chris.User  01/01/2013    0
Project 1  DOMAIN\Chris.User  02/01/2013    0
Project 1  DOMAIN\Chris.User  03/01/2013    0.25
Project 1  DOMAIN\Chris.User  04/01/2013    0.25
Project 1  DOMAIN\Chris.User  05/01/2013    0.75
Project 1  DOMAIN\Chris.User  06/01/2013    0.75
Project 1  DOMAIN\Chris.User  07/01/2013    1
Project 1  DOMAIN\Chris.User  08/01/2013    1
Project 1  DOMAIN\Chris.User  09/01/2013    1
Project 1  DOMAIN\John.User   01/01/2013    0
Project 1  DOMAIN\John.User   02/01/2013    1
Project 1  DOMAIN\John.User   03/01/2013    1
Project 1  DOMAIN\John.User   04/01/2013    1
Project 1  DOMAIN\John.User   05/01/2013    1
Project 1  DOMAIN\John.User   06/01/2013    0.5
Project 1  DOMAIN\John.User   07/01/2013    0.5
Project 1  DOMAIN\John.User   08/01/2013    0.5
Project 1  DOMAIN\John.User   09/01/2013    0.5

I realize that there are a number of topics that relate to this subject such as this. I my case, I don't have any particular restrictions and I am looking for a clean routine that is relatively easy to understand.
I know there is a DateAdd function, but I haven't seen any INSERT INTO commands in the example statements. I am confused as to how one would iterate through the data set and create the interpolated values. I am still too green to understand the full context of the other examples and would greatly appreciate any help or clarification.
Edit Added additional information to the sample data for a better indication of my final goal. I will have multiple users in this data set. The USERNAME column is placed into the data set by the original source (a people picker on an InfoPath form). All "Percentages" are "0" until the first value is assigned then they retain that value until it is changed or the project reaches its end date. I hope this helps clarify!

A: It's not clear how USERNAME populated. I assume you have same USERNAME on project here.  CTE below just build a DATE table, if you have your own date table, you can skip this part.
SQL Fiddle
DECLARE @ENDDate DATETIME

SELECT @ENDDate =  MAX(END_DATE) FROM tblRawData

;WITH tblDate AS
( SELECT CAST(MIN(START_DATE) AS DATE) AS [date]
  FROM tblRawData
  UNION ALL
  SELECT DATEADD(month,1,[DATE])
  FROM tblDate
  WHERE [DATE] < @ENDDate
 )
SELECT
  d.[date]
  ,r.[Project]
  ,UserName =   (SELECT MAX(USERNAME) FROM tblStage1 ts WHERE r.PROJECT = ts.PROJECT)
  ,Percentage = (SELECT ISNULL(MAX(Percentage),0) FROM tblStage1 ts WHERE r.PROJECT = ts.PROJECT AND ts.[date] <= d.[date])
FROM tblDate d
INNER JOIN tblRawData r
  ON d.[date] between r.[START_DATE] AND r.[END_DATE]
ORDER BY 2,1
OPTION (Maxrecursion 0)

EDIT:  Just found out the date is increased by month. I update the CTE query. However, you need make sure you have all project start and end date at first day of the month.

EDIT
Base on your new sample date. the query became a little ugly now, however, it works. I can not think better solution right now.
New SQL Fiddler
DECLARE @ENDDate DATETIME

SELECT @ENDDate =  MAX(END_DATE) FROM tblRawData

;WITH tblDate AS
( SELECT CAST(MIN(START_DATE) AS DATE) AS [date]
  FROM tblRawData
  UNION ALL
  SELECT DATEADD(month,1,[DATE])
  FROM tblDate
  WHERE [DATE] < @ENDDate
 )
,ProjectList AS (
 SELECT Project,UserName
 FROM tblStage1
 GROUP BY Project,UserName
)
,cte AS (
SELECT
  d.[date]
  ,r.[Project]
  ,UserName = pl.Username
  ,CloseDate = (SELECT MAX(ts.[date]) FROM tblStage1 ts WHERE r.PROJECT = ts.PROJECT AND ts.UserName = pl.UserName AND ts.[date] <= d.[date])
FROM tblDate d
INNER JOIN tblRawData r
  ON d.[date] between r.[START_DATE] AND r.[END_DATE]
CROSS APPLY ProjectList pl
)
SELECT cte.[date],cte.project,cte.UserName,ISNULL(t.[PERCENTAGE],0) AS PERCENTAGE
FROM cte
LEFT JOIN tblStage1 t
 ON cte.PROJECT = t.PROJECT
  AND cte.UserName = t.UserName
  AND cte.CloseDate = t.[Date]
ORDER BY 2,3,1

A: You could do this with the APPLY operator as well...
WITH DateList (Project, MonthStart) AS
    (
        SELECT
            project
            , Start_Date
        FROM
            tblRawData
        UNION ALL
        SELECT
            dl.Project
            , DATEADD(MONTH, 1, dl.MonthStart)
        FROM
            DateList dl
        JOIN
            tblRawData r
            ON
                r.Project = dl.Project
                AND
                dl.MonthStart < r.End_Date
    )
SELECT
    dl.Project
    , lastUser.UserName
    , dl.monthstart [Date]
    , ISNULL(pct.Percentage, 0) Percentage
FROM
    DateList dl
CROSS APPLY
    (
        SELECT
            TOP 1
            USERNAME
        FROM
            tblStage1 t1
        WHERE
            t1.Project = dl.Project
        ORDER BY
            t1.Date DESC
    ) lastUser
OUTER APPLY
    (
        SELECT
            TOP 1
            Percentage
        FROM
            tblStage1 t2
        WHERE
            t2.Project = dl.Project
            AND
            t2.Date <= dl.MonthStart
        ORDER BY
            t2.Date DESC
    ) pct

A: A really easy way would be to create a temp table with the month values of each month you need then doing a left join on that table.
Out of curiosity - why is August 1 instead of 0?


text:
Q: Python (Fibo series): trying to understand what is the difference between a, b = b, a + b OR a = b & a = a + b I am not sure what would be an appropriate heading for this question and this can be a repeated question as well. So please guide accordingly.
I am new to python programming. I have this simple code to generate Fibonacci series.
1: def fibo(n):
2:    a = 0
3:    b = 1
4:    for x in range(n):
5:        print (a, end=' ')
6:        #a, b = b, a+b
7:        a = b
8:        b = a+b
9:    print()
10: num = int(input("enter n value: "))
11: print(fibo(num))

If I execute the above code as-is the result I get is as follows
enter n value: 10
0 1 2 4 8 16 32 64 128 256

If uncomment #6 and comment lines #7 and #8 the result I get is the actual fibo series.
enter n value: 10
0 1 1 2 3 5 8 13 21 34

I would like to know what is the difference between
a, b = b, a + b

and
a = b
b = a + b

Programming IDE used: PyCharm Community 2017.3

A: a = b
b = a + b

is actually:
a = b
b = b + b

what you want is:
a = b
b = old_value_of_a + b

When you do
a, b = b, a + b
it really is doing:
tmp_a = b
tmp_b = a + b
a = tmp_a
b = tmp_b

which is what you want

A: In line 7, you've already assigned the value in b to a, so in line 8, new value for b is actually double the old b's value.
While in line 6, the values on the right side of = will be using the old values, that's why you could get Fibo series.

A: Assignment Statements assigns reference of source variable to target variable. Let walk through an example to understand more
>>> a = 5
>>> b = 6
>>> a = b

In this example b is source variable and a is the target variable. Now memory address for both of these variables are same. We can confirm this as well
>>> hex(id(a)), hex(id(b))
>>> ('0x1002739e0', '0x1002739e0')

Another test to confirm this is to use is operator
>>> a is b
>>> True

Now coming back to your example. First statement
>>> a, b = b, a + b

Assignes b to a and (a+b) to b. This happens as a single operation so both variables are different. We can apply above tests to confirm this
>>> a is b
>>> False

>>> hex(id(a)), hex(id(b))
>>> ('0x1002739e0', '0x2008739t0')

The second statement
 >>> a = b
 >>> b = a + b

Assignes b to a and then (a+b) to b. These are two different statements, so at first step a and b are already identical. Thus the second statement is equivalent to b = b + b.

A: Thought make it simple so anyone can understand it
if you use this kind of syntax
a = 10
b = 20

a = b
b = a+b

print (a)
print (b)

after initially assigning a = 10 it will be assigning a = 20 since python is dynamically typed language it will change the value of variable a from 10 to 20
so the result will be like
a=20
b=40

but if we use
a = 10
b = 20

a,b = b,a+b

print (a)
print (b)

this will be assigning the values in a single line so the values of a and b will be exactly used from what it is initialised above it and the result will be like
which is the correct solution
a=20
b=30

A: I think the # line is pythonic solution. But if you got confused,you can you use a variable which is temporary. you can assign the value temp before, then you can change the values


text:
Q: Deletion of bulk records using spring jdbc I have two tables table1 and table2 and joining them using inner join on one column.
There is a possibility that child table can have more than 50 million recorrds.
It took 30 mins to delete 17 million records using spring jdbc update().
is there a optimized way  to reduce deletion time.

A: Use batchUpdate with some copeable batch size, eg. 5000.
EDIT: The problem is probably not in Spring jdbc but in your query.
Would this work for you?
DELETE
    res
FROM
    RESULT res
INNER JOIN
    POSITION pos
    ON res.POSITION_ID = pos.POSITION_ID
WHERE
    pos.AS_OF_DATE = '2012-11-29 11:11:11'

This removes entries from RESULT table. Simplified SQL fiddle demo: http://www.sqlfiddle.com/#!3/4a71e/15


text:
Q: how to grep for "/local" in all perl files in current directory I am using the following command to grep for string "/local" in all .pl files,can anyone point what is wrong here?
find . *.pl| xargs grep '/local' -sl

A: Pass -name argument, and quote *.pl:
find . -name "*.pl" | xargs grep '/local' -sl

A: Why is everyone suggesting "find"? The shell can work out your ".pl" files for you:
grep  "/local"  *.pl

A: You could just as easily
find . -type f -name '*.pl' -exec grep '/local/' {} \;

Or a more optimal form if your find supports it, this passes multiple files to grep at a time
find . -type f -name '*.pl' -exec grep '/local/' {} +

A: -exec tends to be slow.
I'm partial to:
find . -name "*.pl" -print0 | xargs -0 grep -sl '/local'

...because it isn't confused by filenames with newlines in them.
Note however that some versions of GNU grep appear to have a memory leak that is triggered by grep commands with a very long list of filenames to search.  Under such circumstances, -exec is more reliable.


text:
Q: Convert struct to slice of strings? I'm trying to write a CSV file using the package encoding/csv. All data I want to write per line is saved in a struct like this:
type record struct {
    Field0 string
    Field1 string
    Field2 string
    Field3 string
}

The csv package has a method called Write that requires a slice of strings.
Is it possible to convert a struct to a slice of strings?

A: For example,
package main

import (
    "fmt"
)

type record struct {
    Field0 string
    Field1 string
    Field2 string
    Field3 string
}

func main() {
    r := record{"f0", "f1", "f2", "f3"}
    fmt.Printf("%q\n", r)
    s := []string{
        r.Field0,
        r.Field1,
        r.Field2,
        r.Field3,
    }
    fmt.Printf("%q\n", s)
}

Output:
{"f0" "f1" "f2" "f3"}
["f0" "f1" "f2" "f3"]

A: I find the https://github.com/fatih/structs package to be quite useful...
package main

import (
    "fmt"
    "github.com/fatih/structs"
)

type record struct {
    Field0 string
    Field1 string
    Field2 string
    Field3 string
}

func main() {
    r := record{"f0", "f1", "f2", "f3"}
    fmt.Printf("%q\n", r)
    vals := structs.Values(r)
    fmt.Printf("%q\n", vals)
}
Output:

{"f0" "f1" "f2" "f3"}
["f0" "f1" "f2" "f3"]


text:
Q: Would an Option or Optional type (Option) make sense in TypeScript? Languages like Haskell, Rust, among others, offer a Maybe or Option type. Even in Java, there is a Optional type nowadays.
For simplicity, I will call this type an 'Option type' in the remaining question. 'Optional type' is apparently often used to describe situations where providing type annotations is optional.
I am curious about the following: does an Option type make sense in a language like TypeScript? The advantages of the Option type are quite convincing in other languages and I find myself missing the type when programming in TypeScript.
Basically, the type system forces you to explicitly unwrap any value that may be inside an Option value. Yes, TypeScript's strict null-checking can also accomplish that, however, working with the Option type offers you an (in my opinion) much nicer way to handle potential None values by providing map(f: T -> U): Option<U> and mapOr(f: T -> U, or: U): Option<U> methods, etc.
For instance, I would like something like the following code to work:
interface Foo {
    member: Option<string>
}
const opt: Option<Foo> = // ... some initialization
const memberLength: number = opt
    .map(x => x.member) // None if x is None, else Some(...)
    .map(x => x.length) // None if x.member is None, else Some(x.length)
    .unwrapOrElse(() => 0);

This is, of course a very simple example, where using an Option type is a bit over-engineered. It should give a basic idea, though.
I currently don't see a reason why this would be a bad idea, but no one seems to have implemented it, as far as I can tell. Would this have a serious performance impact? Or are there any other issues I can't see that make this non-viable?
Note: I am not (mainly) asking for how to implement this (although that is also an interesting topic -- but I have ideas for that). My main concern is finding out why no one seems to be using something like this yet.

A: EDIT 2019
Check fp-ts
Original Answer
I was missing it coming from Scala (and some Haskell) so I made my own lib for it (and a couple others): MM (MIT license)
Feel free to hack, fork etc...; it is MIT licensed

A: sniptt/monads is a simple library that adds rust-style Option and Result types to typescript. I've tried out a lot of these and this was the simplest to use.


text:
Q: CVPixelBuffer to RGBA Buffer in iOS/Swift? I am working with ARKit and I get the ARFrame - capturedImage is of CVPixelBuffer - Currently I convert this into a CVPixelBuffer->CIImage->UIImage-> JPEG
I want to know how to get the raw buffer from CVPixelBuffer - I know that ARFrame is of YUV format and I want the image buffer in RGBA format to set as a texture in my graphics application.
I feel that CVPixelBuffer->CIImage->UImage-> JPEG is too many conversion and again decoding from JPEG->Buffer at my application is too much wasteful processing.
So the question is how do I get RGBA image buffer from CVPixelBuffer. I am using Swift
Thanks


text:
Q: How do I make a large but unknown number of REST http calls in nodejs? I have an orientdb database. I want to use nodejs with RESTfull calls to create a large number of records.  I need to get the @rid of each for some later processing.
My psuedo code is:
for each record
  write.to.db(record)
  when the async of write.to.db() finishes
     process based on @rid
carryon()

I have landed in serious callback hell from this.  The version that was closest used a tail recursion in the .then function to write the next record to the db.  However, I couldn't carry on with the rest of the processing.
A final constraint is that I am behind a corporate proxy and cannot use any other packages without going through the network administrator, so using the native nodejs packages is essential.
Any suggestions?

A: With a completion callback, the general design pattern for this type of problem makes use of a local function for doing each write:
var records = ....;    // array of records to write
var index = 0;

function writeNext(r) {
    write.to.db(r, function(err) {
       if (err) {
          // error handling
       } else {
          ++index;
          if (index < records.length) {
             writeOne(records[index]);
          }
       }
    });
}

writeNext(records[0]);

The key here is that you can't use synchronous iterators like .forEach() because they won't iterate one at a time and wait for completion.  Instead, you do your own iteration.

If your write function returns a promise, you can use the .reduce() pattern that is common for iterating an array.
var records = ...;    // some array of records to write

records.reduce(function(p, r) {
    return p.then(function() {
       return write.to.db(r);
    });
}, Promsise.resolve()).then(function() {
   // all done here
}, function(err) {
   // error here
});

This solution chains promises together, waiting for each one to resolve before executing the next save.

A: It's kinda hard to tell which function would be best for your scenario w/o more detail, but I almost always use asyncjs for this kind of thing.
From what you say, one way to do it would be with async.map:
var recordsToCreate = [...];

function functionThatCallsTheApi(record, cb){
   // do the api call, then call cb(null, rid)
}

async.map(recordsToCreate, functionThatCallsTheApi, function(err, results){
   // here, err will be if anything failed in any function
   // results will be an array of the rids
});

You can also check out other ones to enable throttling, which is probablya  good idea.


text:
Q: Creating file and writing to it in one single command right now, I'm doing the following operation, which takes me two iterations of typing into my ubuntu terminal.
$ touch someFile
$ ls > SomeFile

Using ls here is just an example of some program that outputs some text.
It seems a bit tedious that I need to first create the file, and then write to it, is there any way I can do this in one go, something along these lines (which does not work):
$ ls > touch ff

Thanks a lot for any tips

A: You do not have to create the file first before writing to it.
Just simply:
$ ls
$ echo "asdf" > myFile
$ ls
myFile
$ cat myFile
asdf

Here is a reference that explains this in more detail


text:
Q: Find $x$ when $x^2\equiv y\bmod p$ Given $p$ is prime and $y$ is a constant. What's the fastest possible way to find $x$ where $x^2\equiv y\bmod p$?
Example: $x^2\equiv97\bmod101$ would give us $x=81$ as one of the solutions. What's the fastest way to compute any one of the solutions of $x$?
Constraints:

*

*$0\le p\le10^9$

*$0\le y\le p$

*$0\le x<p$

A: The standard approach to compute square roots modulo primes is the Tonelli–Shanks algorithm.


text:
Q: Get data from JSON file to populate dropdown and display other data on select dropdown I have a .json file with some info and wht I want to do is to populate my dropdown with some of the info and when I select an option from the dropdown, I want to display more info from the .json file.
So far, I have this:
[{
  "options": "Option 1 on dropdown",
  "result1": "Text to populate div1",
  "result2": "Text to populate div2"
},
 {
  "options": "Option 2 on dropdown",
  "result1": "Text to populate div1",
  "result2": "Text to populate div2"
},
{
  "options": "Option 3 on dropdown",
  "result1": "Text to populate div1",
  "result2": "Text to populate div2"
},
}]

CSS:

   <option value="">Select option</option>
</select>

JS:

So, when the user select an option, I want to display some data from the .json file according to the selection.
At the moment, I can just make the value to populate the div, but I want to use data from the .json file.
Is that possible?

A: If you get the json with a http request, you should pass it to the global variable
var url = "devices.json";
let data;
$.getJSON(url, function (_data) {
    data = _data;
/* no other change */

$(document).ready(function(){
var url = "devices.json";

const data = [{
  "options": "Option 1 on dropdown",
  "result1": "Text to populate div1 - 1",
  "result2": "Text to populate div2 - 1"
},
 {
  "options": "Option 2 on dropdown",
  "result1": "Text to populate div1 - 2",
  "result2": "Text to populate div2 - 2"
},
{
  "options": "Option 3 on dropdown",
  "result1": "Text to populate div1 - 3",
  "result2": "Text to populate div2 - 3"
}]
//$.getJSON(url, function (data) {
    $.each(data, function (index, value) {
        $('#sel').append('<option value="' + index + '">' + value.options +
'</option>');

  });
//    });

$("select").change(function(){
        $(this).find("option:selected").each(function(){
            var optionValue = $(this).attr("value");

            if(optionValue){
                $("#sol").text(data[optionValue].options);
                $("#div1").text(data[optionValue].result1);
                $("#div2").text(data[optionValue].result2);
                $(".box").show();
                /*
                $(".box").not("." + optionValue).hide();
                $("#sol").text(optionValue);
                $("." + optionValue).show();
                */
            } else{
                $(".box").hide();
            }
        });
    }).change();
});
.box{
        color: #fff;
        padding: 20px;
        display: none;
        margin-top: 20px;
    }

body {
  background: #000;
}

<select id="sel">
   <option value="">Select option</option>
</select>


text:
Q: Being certain $G$ semigroup, is it group? I'm starting a course on algebraic structures in university, and this is one of the first problems. I want to know if my solution is valid. The question goes like this:

Being $G$ non-empty semigroup (set with associative binary product).
We know that $G$ verifies that:

*

*$\exists e\in G:ex=x \forall x\in G$ ("left" neutral element).

*$\forall x \in G, \exists y\in G : yx=e$ ("left" inverse element).

Prove that $G$ is group.

My solution goes like this:
$$e=ee=(g^{-1}g)e=g^{-1}(ge)$$
Then necessarily $ge=g$, because $g^{-1}(ge)$ must be equal to $e$. So that proves that $e$ is in fact left and right neutral element of $G$.
Now, we see that:
$$g=ge=g(g^{-1}g)=(gg^{-1})g$$
and we conclude that $gg^{-1}=e$ because $(gg^{-1})g$ must be equal to $g$, so we conclude that $g^{-1}$ is left and right inverse element of $g$.
Given this, I conclude that $G$ is in fact group.
Is my reasoning correct? I'll thank any help.


text:
Q: STM32F407VG SDIO read and write speed I am writing the on board accelerometer data to my SD card. I am using a STM32F407VG board. The data is being written and read. How can I measure or test the speed of reading and writing data to the SD card through STM32F407VG board?

A: Count the number of written blocks per second.
You can probably hook into the SDIO interrupts or driver to get an integer increment somewhere. Or it might already have this, check the documentation.
Then in the systick for example, see every 1 second how many blocks were written. And reset the integer.
Or use the producing data thread, and increment an integer each byte you write to the file stream. Then see how big this number is every 1 second, and clear it.
For example, printf and related functions often return the number of written bytes.


text:
Q: May I bind Mission Control's next and previous space to ctrl+mousewheel? May I bind Mission Control's next and previous space to ctrl+mousewheelup and ctrl+mousewheeldown?
Using the system settings apparently I can't, so I'm wondering if there's another non-invasive way? (such as manually editing a config file, for instance)
OSX 10.8, in case this matters.

A: Check out BetterTouchTool. It's a free app that allows you to bind a large number of system actions to the controls on your mouse, including Mission Control and changing spaces. I have a Magic Mouse, so I'm not 100% sure that it will work with a normal mouse scroll wheel, but I'm fairly certain that it will.


text:
Q: How do I trigger the admin_consent flow using IdentityServer 4 for a multi-tenant app? I'm building a POC multi-tenant app using IdentityServer 4 on asp.net core as the middleman between my client app and Azure Active Directory using openIdConnect. Is there a way to trigger the admin_consent flow when a user logs in from a new AAD tenant which is not yet authorized to use the app?
This Azure sample shows how to perform a manual consent using a controller on the client site which builds the AAD Uri from scratch, but I'm shooting for an experience where a user from a new directory hits my site, gets kicked to AAD common endpoint, logs in, and is presented with a UI to authorize the app in their directory.

Now that I type that, I'm thinking the problem is that AAD may not
  have a way to be told to skip the 'not registered with your directory'
  error screen, so an AAD admin from the new tenant would need to
  execute the admin_consent workflow on their own ahead of time anyway.

I'm still interested to know if IdentityServer can kick off that process (i.e - can the openIdConnect Uri be manipulated), because I'd like to run all identity workflows through IdentityServer, including my admin consent workflow.

A: For a multi-tenant application, the initial registration for the application lives in the Azure AD tenant used by the developer. When a user from a different tenant signs in to the application for the first time, Azure AD asks them to consent to the permissions requested by the application.
This consent experience is affected by the permissions requested by the application. Azure AD supports two kinds of permissions, app-only and delegated.
App-only permissions always require a tenant administrator's consent. If your application requests an app-only permission and a normal user tries to sign in to the application, your application will get an error message saying the user isn't able to consent, like :This application requires application permissions to another application. Consent for application permissions can only be performed by an administrator.
If your application uses permissions that require admin consent, you need to have a gesture in your application such as a button or link where the admin can initiate the action. The request your application sends for this action is a usual OAuth2/OpenID Connect authorization request, but that also includes the prompt=admin_consent query string parameter .eg:

https://login.microsoftonline.com/common/oauth2/authorize?client_id=&response_type=code&redirect_uri=&scope=openid&prompt=admin_consent

With this query string , admin consent is needed , if you use a normal user(not admin),you will get the error like:This operation can only be performed by an administrator You could check whether add the query string according to your requirement . In your scenario, you could click here for code sample about how to configure Identity Server4 with Azure AD external login . If you want to force the admin consent flow , you could handle the OnRedirectToIdentityProvider event when configuring the OpenIdConnectOptions, and add the prompt query string parameters by calling the ProtocolMessage.SetParameter method on the supplied RedirectContext :
        app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
        {
            AuthenticationScheme = schemeName,
            DisplayName = "AzureAD",
            SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme,
            ClientId = clientId,
            Authority = $"https://login.microsoftonline.com/{tenantId}",
            ResponseType = OpenIdConnectResponseType.IdToken,
            StateDataFormat = dataFormat,
            Events = new OpenIdConnectEvents
            {
                OnRedirectToIdentityProvider = context =>
                {
                    context.ProtocolMessage.SetParameter("prompt", "admin_consent");

                    return Task.FromResult(0);
                }
            }

        });


text:
Q: Combining Enum Value using Bitmask I understand it's possible to use bitmasks in enum values, but I don't know how to create it.
I have a simple enum :
enum State
{
    minimizing = 0,
    maximizing,

    minimized,
    maximized
};

A state is always State.minimized or State.maximized, and can have additional state on resize. So something can be Maximized and minimizing

A: I just tried this in VS2012, the optimizer seems to correctly combine bits without any need for assistance if you're using bitfields.
struct BITS { int x: 1; int y:1; };

then
BITS b;
b.x = b.y = 1;

Sets both bits with one instruction.

A: I am going to assume that myState has the type of your enum State.
The traditional use of enum is to create the constant values that a variable of this type can take. You wish to set you variable myState to a combination of the values defined in the enum.
The enum defines 1, 2, 4, and 8 as valid values, yet you want to be able to set the variable to 4 | 2 = 6. While C uses your implementation-defined int type for all enum, it is not the case in C++. myState = 6 is not valid in C++. Actually, myState = 4 is not either valid in C++, you need to cast explicitly or use one of the constant names of the enum.
Although possible in C, it is not good practice to set myState to a value that is not defined by its type (for example to 6).
In your case, a solution that seems consequent would be:
typedef enum {
    OTHER,
    MINIMIZED,
    MAXIMIZED
} win_size_t;

typedef struct {
    win_size_t current;
    win_size_t next;
} state_t;

state_t myState;

That way, you can write to the fields current and next undependently.
If you still want to have bit fields, you can set the size of the elements of your struct in bits. It is kind of dangerous though, the implementation of bit fields depend on your compiler. I am not even sure if compilers would accept to have an enum type in a bit field (should be ok in C, since enums are int).
typedef struct {
    win_size_t current : 2;  // not tested
    win_size_t next : 2;
} state_t;

The previous given solutions are valid of course. My point is that if your variable myState has your enum State as type, it should only use the members of the enum for its values, not a combination.
Maybe myState has another type, what do I know.

If myState is not of the enum State type, then you may use the constants defined in your enum in combination.
enum State {
    MINIMIZING = (1u << 0),
    MAXIMIZING = (1u << 1),
    MINIMIZED  = (1u << 2),
    MAXIMIZED  = (1u << 3),
};

unsigned int myState = 0;

myState |= MAXIMIZED;  // sets that bit
myState &= ~MAXIMIZED; // resets that bit

This allows you to do two things in one assignment:
myState = MAXIMIZED | MINIMIZING;

But also things you are not likely to want:
myState = MAXIMIZED | MINIMIZED;  // does that make sense?

A: You can get this effect by specifying all fields in the enum and increased in powers of two to get the bitmask effect.  For example, in your case:
enum State
{
    minimizing = 1,
    maximizing = 2,

    minimized = 4,
    maximized = 8
};

So you can then have your combinations of (State.maximized | State.minimizing).  However this won't apply the restriction of only being State.maximized or State.minimized.  If you want to do that you could convert them to a single bit, but I imagine in this example you would want to be able to have a case where it is neither maximized nor minimized.

A: Use a different bit for every value in your enumeration, such as:
enum State
{
  minimizing = 0x01, // 00000001
  maximizing = 0x02, // 00000010
  minimized  = 0x04, // 00000100
  maximized  = 0x08  // 00001000
}:

Then, you can combine multiple values with bitwise or (minimizing | maximized) and test for values with bitwise and (bool is_minimized = (flags & minimized);).


text:
Q: Difference between using a TNS name and a service name in a JDBC connection I have a java based server (Tomcat) that connects to an Oracle database using a JDBC connection. There are multiple ways to connect to the database: SID, TNS name, Service name.
I would like to understand what is the difference between each of these connections and what would be the recommended connection (SID, TNS, or service) if connecting to a clustered database. Here is the TNS name we have for the database:
MY_NICE_TNS_NAME.MY_COMPANY.COM =

(DESCRIPTION =

  (ADDRESS = (PROTOCOL = TCP)(HOST = myhostname)(PORT = 1521))

  (LOAD_BALANCE = YES)

  (CONNECT_DATA =

   (SERVER = DEDICATED)

   (SERVICE_NAME = MY_NICE_SERVICE_NAME.MY_COMPANY.COM)

   (FAILOVER_MODE =

   (TYPE = SELECT)(METHOD = BASIC)(RETRIES = 180)(DELAY = 5)

   )

  )

)

Thanks!

A: SERVICE_NAME is a alias to a database instance (or many instances). The main purpose of this is if you are running a cluster. Using this we can connect specific database within a cluster. And other way, using SID (System IDentifier) we can connect to a database instance, which is a unique name for an Oracle database instance.
In short, SID = the unique name of your DB, SERVICE_NAME = the alias used when connecting.
There are several ways to provide database information like Directly Specified, tnsnames.ora (i.e. TNS name), LDAP Directory, Network Information Services.
A TNS (Transparent Network Substrate) name is the name of the entry in tnsnames.ora file which is kept in $ORACLE_HOME/network/admin
This file contains the information which is used by the system to connect to oracle database. Using this a client can fetch server associated information transparently.  It contains the  following information
PROTOCOL
HOST IP ADDRESS
PORTNO
SID  or SERVICE_NAME

E.g
 mydb =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = 10.35.15.1)(PORT = 1521))
    (CONNECT_DATA = (SID = mydb))

JDBC drivers connect with a connection string using TNS as follows
System.setProperty("oracle.net.tns_admin", PATH_TO_TNSNAMES.ORA);
Class.forName ("oracle.jdbc.OracleDriver");
dbUrl = "jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST="+IPHOST+")(PORT="+PORT+"))(CONNECT_DATA=(SERVER = DEDICATED)(SERVICE_NAME="+DBNAME+")))"

conn = DriverManager.getConnection(dbUrl, USERNAME, PASSWORD);

A: Oracle SID is the unique name that uniquely identifies your instance/database where as Service name is the TNS alias that you give when you remotely connect to your database and this Service name is recorded in Tnsnames.ora file on your clients and it can be the same as SID and you can also give it any other name you want.
SERVICE_NAME is the new feature from oracle 8i onwards in which database can register itself with listener. If database is registered with listener in this way then you can use SERVICE_NAME parameter in tnsnames.ora otherwise - use SID in tnsnames.ora.
Also if you have OPS (RAC) you will have different SERVICE_NAME for each instance.
SERVICE_NAMES specifies one or more names for the database service to which this instance connects. You can specify multiple services names in order to distinguish among different uses of the same database. For example:
SERVICE_NAMES = sales.acme.com, widgetsales.acme.com
You can also use service names to identify a single service that is available from two different databases through the use of replication.
In an Oracle Parallel Server environment, you must set this parameter for every instance.
The TNS is the sql*net configuration file that defines datbases address for establishing connection to them.


text:
Q: for cookie poisoning demo, write and read cookies in vb.net I would like to test cookie poisoning so I want to edit one of my projects. There, I would like to write cookies which will contain subtotal of products and the checkout page will use it again to show the subtotal. I am not sure whether my thinking is correct or not and also my cookies are not working.
First, I put these codes under addcart button method:
Dim aCookie As New HttpCookie("SubTotal")
aCookie.Value = objShopCart.ComputeSubTotal().ToString()
aCookie.Expires = DateTime.Now.AddDays(1)
HttpContext.Current.Response.Cookies.Add(aCookie)

And in the checkout page;
If (Request.Cookies("aCookie") IsNot Nothing) Then
    Dim subTotal As String
    If (Request.Cookies("aCookie")("SubTotal") IsNot Nothing) Then
        subTotal = Request.Cookies("aCookie")("SubTotal")
        lblSubTotal.Text = subTotal
    End If
End If

According to the above codes, I cannot read the cookies. The Request.Cookies("aCookie") is always nothing I don't know why. And for the cookie poisoning demo is I intend to intercept the cookie of when I put things into the shopcart and edit it so when I got to checkout page, its shown with wrong info of subtotal etc. Appreciate to any help.

A: You need to retrieve the cookie value by the same name you saved it. For example,
If (Request.Cookies("SubTotal") IsNot Nothing) Then
   Dim subTotal As String
   subTotal = Request.Cookies("SubTotal").Value
End If

Just FYI, you do not want to save the subtotal in cookie, because it can be manipulated easily at client side. Save it in session state or recalculate it in check out page again.


text:
Q: How can I set up Vue.js in my Laravel Project ? I work with Laravel and I try to do something with Vue.js but I can't see it up.
First of all I install Node.js and npm.
Now I'm trying to user 'npm run watch'. To see if my js code runs on my laravel project.
But, when I type 'npm run watch' in my cmd. It's like this:

What should I do ?
Thanks !

A: It looks like your version of Laravel Mix is out-of-date; there was a bug fixed in March 2017 that addressed this issue on newer versions of webpack.
You can update your version of Laravel Mix by either doing this:
npm uninstall laravel-mix && npm install --save-dev laravel-mix

or updating your package.json file to change the version for laravel-mix
...
"devDependencies": {
    ...
    "laravel-mix": "^0.11.4",
    ...
}
...

After changing the version number, run npm update.


text:
Q: Export pb and pbtxt from python tensorflow to opencv with c++ Hello everybody i created my own model inside tensorflow 2.0 and i dont know how to export pb file and pbtxt to opencv can anyone tell me how
Thank you in advance


text:
Q: how to run multi threaded curl script from terminal? I have used a multi curl library for PHP that facilitates fetching multiple pages in parallel (basically an easy to use API).
My Scenario: Fetch user data from API , process it and store results. All those users whose data have to be fetched are place in queue. This whole fetching , processing & storing result will take almost 8 - 10 min. And its really costly if I process it synchronously. So I have used php curl library for multi-threading. Its works fine if I run it in browser but since its cron-job so I have to run same script using command line. When I do so ; it will not work. Can anybody help me? Thanks in advance.
Psuedo Code:
$query = " Fetch users based on certain criteria LIMIT 200" ;
$result = execute-query ;

$curl_handle = curl_multi_init();
$i = 0;
$curl = array();

while ($row = mysql_fetch_assoc($result)) {
    $curl[$i] = add_handle($curl_handle, API_CALL);
}

exec_handle($curl_handle);

for ($j = 0; $j < count($curl); $j++)//remove the handles
    curl_multi_remove_handle($curl_handle, $curl[$i]);

curl_multi_close($curl_handle);

// Reference url
http://codestips.com/php-multithreading-using-curl/


text: Q: XNA Loading models, not fbx I want to load models from a game called 'Half Life' so I downloaded some from here: http://hl2.gamebanana.com/skins/122283, and i got this files: metrocop_elite_normal.vtf, metrocop_sheet_normal.vtf, and some more .vtf and .vmt. Can I load other files than .fbx? and how?


text:
Q: How is debugger variable content displayed implemented I was wondering how to implement the debuggger mouse over display functionality, U know when u have set a breakpoint in a degugger, say in VS and you hover over a variable and the context is displayed.
I'm curious as to how that would be implemented?
Bob.

A: These are debugging visualizers and here is a link to MSDN for writing custom visualizer


text:
Q: Python panda dataframe string with prefix convert to float I have a dataframe of strings that I convert to float using df.astype('float', errors = 'ignore').
I used iloc and then have a loop to go through all columns.
The issue is that some values in some columns has a prefix, in a given column the numbers could be ['0.02u\n', '0.1\n', '2.02n\n' .... ]
The point is that u = 10^(-6) and n = 10^(-9). The question is how to convert this in an elegant way to a float.

A: Solution I used is to look in all cells and see if there i a 'n' or 'u' in the end of string. Remove letter, convert to float and then multiply.
no_col = len(df_T.columns)
no_row = len(df_T)
for i in range(0,no_col):
   for j in range(0,no_row):
        df_T.iloc[j,i] = df_T.iloc[j,i][:-1]
for i in range(0,no_col):
   for j in range(0,no_row):
     if df_T.iloc[j,i][-1] == 'u':
         df_T.iloc[j,i] = df_T.iloc[j,i][:-1]
         df_T.iloc[j,i] = float(df_T.iloc[j,i])
         df_T.iloc[j,i] = df_T.iloc[j,i]*10**-6
     elif df_T.iloc[j,i][-1] == 'n':
         df_T.iloc[j,i] = df_T.iloc[j,i][:-1]
         df_T.iloc[j,i] = float(df_T.iloc[j,i])
         df_T.iloc[j,i] = df_T.iloc[j,i]*10**-9
     else:
         df_T.iloc[j,i] = float(df_T.iloc[j,i])

A: Pandas can evaluate expression in columns using pd.eval(). So, if you have an expression in string format you can apply pd.eval() and it will be evaluated.
To use this, firstly you can remove the \n in your columns, for which I used .replace().
Next, to make the expression readable by pd.eval() - for example '3x' should be converted to '3*x', again used .replace with regex.
Finally apply pd.eval() and it will be evaluated.
import pandas as pd

df = pd.DataFrame({'col': ['0.02u\n', '0.1\n', '2.02n\n']})
u = 10^(-6)
n = 10^(-9)

# Remove the \n characters
df['col'] = df['col'].replace(to_replace="\n", value="", regex=True)
# Put '*' for multiplication --> '3x' will be converted to '3*x'
df['col'] = df['col'].replace(to_replace=r"((?:\d+)|(?:[a-zA-Z]\w*\(\w+\)))((?:[a-zA-Z]\w*)|\()",
                              value=r"\1*\2", regex=True)
df['val'] = pd.eval(df['col'])
print(df)

Result:
      col   val
0  0.02*u -0.32
1     0.1  0.10
2  2.02*n -6.06


text:
Q: test express / express-session with supertest I am trying to test an express api using supertest.
Problem arises when I am trying to persist a session cookie between test requests.
The stack I am using is express + express-session and supertest/jest for testing.
Using a simple logger for monitoring the sessionId.
Of course I am generating 2 different sessionId when testing using jest, since I am not saving any cookies. Getting the same sessionId when testing with curl.
How can I resend the cookie with jest/supertest?
Server implementation:
const express = require('express');
const session = require('express-session');
...

var simpleLogger = function (req, res, next) {
  console.log({sessionID:req.sessionID});
  next()
};

app.use(session({
  genid: () => {return uuidv4();},
  secret: 'XXXXXX',
  resave: false,
  saveUninitialized: true
}));

// login controller

const login = async (req, res) => {
  const {user_name, user_password} = req.body;
  const session_uuid = req.sessionID;
...

// login router
router.post('/login', loginController.login);

curl test implementation
curl -b cookie.txt -c cookie.txt -s -w " %{http_code}" -X POST http://localhost:3001/login/login -H "Content-Type: application/json" -d '{"user_name":"xxx","user_password":"xxx"}'
curl -b cookie.txt -c cookie.txt -s -w " %{http_code}" -X POST http://localhost:3001/login/login -H "Content-Type: application/json" -d '{"user_name":"xxx","user_password":"xxx"}'

curl test logging (same sessionID)
{ sessionID: 'fbc29360-1102-4d4a-81aa-961fa6810294' }
{ sessionID: 'fbc29360-1102-4d4a-81aa-961fa6810294' }

supertest implementation
describe('login endpoint tests', () => {
  it('ADMIN LOGIN', (done) => {
    request(app.app)
        .post('/login/login')
        .send({"user_name": "super", "user_password": "admin"})
        .expect(200).end(done);
  });
  it('ADMIN LOGIN', (done) => {
    request(app.app)
        .post('/login/login')
        .send({"user_name": "super", "user_password": "admin"})
        .expect(200).end(done);
  });
});

** supertest logging (different sessionID)**
{ sessionID: '0af83d6a-abaa-4fad-854f-1c3d627ab627' }
{ sessionID: '24d17bbc-1d6d-4192-9a7f-1b0b4a3fe5dd' }

Banging my head :(.
Any suggestion on how to persist the sessionID in the test?


text:
Q: Linux copying subdirectories with same name to a file Imagine a directory structure that looks like :
/a1/b1/c1/O

/a1/b2/c2/O

/a1/b3/c3/O

how do I copy all content of the "O" directory to one file?
I've tried cp -r /a1/*/O ~/O and it fails

A: One more glob pattern needed. Use:
cp -r /a1/*/O/* ~/O

OR to make this command work for any depth use find:
find /a1 -type d -name 'O' -print0 | xargs -0 -I % cp -r %/* ~/O


text:
Q: What is a binary loss, and should I use a binary loss or a softmax loss for classification? I was trying to understand the final section of the paper Revisiting Baselines for Visual Question Answering. The authors state that their model performs better with a binary loss in comparison to a softmax loss.
What is a binary loss (in this case)? Is the softmax loss a synonym for binary cross-entropy?  Should I use a binary loss or a softmax loss for classification?

A: There is a nice explanation here

Binary Cross-Entropy Loss is also called Sigmoid Cross-Entropy loss. It is a Sigmoid activation plus a Cross-Entropy loss. Unlike Softmax loss it is independent for each vector component (class), meaning that the loss computed for every vector component is not affected by other component values.

The term binary stands for number of classes = 2.

A: I think that binary loss is the one based Shannon on entropy $-\sum_ip_i\ln p_i$, while the softmax is based on Boltzmann distribution: $\frac{e^{z_i}}{\sum_j e^{z_i}}$
Softmax itself shouldn't be a loss function though. It's the probability like function that you use to pick the output of classificator. For instance, you could use it to calculate probabilities $\hat p_{ij}$ of classificator outcomes for categories $i$ for sample $j$.
Then you can use the entropy based loss function to evaluate the fit: $\sum_ip_{ij}\ln\hat p_{ij}$, where $p_{ij}$ is a binary outcome of a category $i$.


text:
Q: Persistant Taskbar in Android I want to have a persistant taskbar like the status bar of Android. I dont want  it to load with individual activity. i want that taskbar to remain persistant for all activities that too at the bottom of the screen.*(Not on top of screen where status bar is present.)
Thank you for your help.

A: That is not possible from the Android SDK. It should be possible by modifying the firmware.

A: Yes Rohan you need to modify the firmware....Also CommonsWare can you elaborate on your comment to modify the firmware.


text:
Q: SUM GROUP BY giving undesired result First 12 rows of Table T1:
Name    Status  Duration
Todd    Active  60
Todd    Active  60
Todd    Active  60
Todd    Schedu  60
Todd    Schedu  60
Todd    Schedu  120
Todd    Schedu  120
Bran    Active  30
Bran    Active  30
Bran    Active  60
Bran    No Show 120
Bran    No Show 120

If I run this query (or use a DISTINCT without the GROUP BY):
SELECT Name, Status, Duration
FROM Table T1
GROUP BY Name,Status,Duration

I get:
Name    Status  Duration
Todd    Active  60
Todd    Schedu  60
Todd    Schedu  120
Bran    Active  30
Bran    Active  60
Bran    No Show 120

From the above result, I want the desired result as SUM(Duration) GROUPED BY Name, Status:
Name    Status  Duration
Todd    Active  60
Todd    Schedu  180
Bran    Active  90
Bran    No Show 120

I'm trying this query to achieve the desired result:
SELECT Name, Status, SUM(Duration)
FROM Table T1
GROUP BY Name,Status

But I'm getting huge numbers for SUM(Duration) - It's probably adding all the durations and not the distinct durations for each group of Name and Status.

A: One method to get what you want uses a subquery:
SELECT Name, Status, SUM(Duration)
FROM (SELECT Name, Status, Duration
      FROM Table T1
      GROUP BY Name,Status,Duration
     ) NSD
GROUP BY Name, Status;

A: You can use Distinct inside SUM function. It will give you expected result.
SELECT Name, Status, SUM(DISTINCT Duration)
FROM T1
GROUP BY Name,Status

A: You could use CTE,
WITH C1 AS(
          SELECT Name, Status, Duration
          FROM Table T1
          GROUP BY Name,Status,Duration
        )
SELECT Name,Status,SUM(Duration) FROM C1 GROUP BY Name,Status

A: with temp_cte
as
(select Name, Status, Duration
FROM  dbo.test2
group by name,status,duration
)
select tc.name,tc.status,sum(tc.duration) from temp_cte as tc
group by tc.name,tc.status
order by name


text:
Q: Solar Distillation I have a rather large project on the northern beaches of Tanzania and am looking for the optimum off grid method to distill water. We have a salty well. I have seen many many diagrams on the web on the subject with some of them being very close to suiting my purpose. So far I have not seen anything produce more than 10 litres/square meter of glass coverage per day. If I could make a coverage of 10 sq mt and get 100 litres per day it may suffice.
My question is this. If I can continually boil water in a reservoir and distill the steam is it more efficient that merely heating from the sun. I would have thought so.
My thoughts are steering toward using the already discovered and mass produced solar hot water system that you see on many a suburban roof.
If I was to block the outlet and reduce the psi on pressure relief valve and tap the steam from that exit would it be more efficient than the standard sloping glass model we all know? If I was to add another row of evacuated tubes would it help? Has anyone come across any research on this subject? Cheers
Mike


text:
Q: In Cosmology, what does it mean to be 'local'? I'm trying to make a point that there is curvature of spacetime from the metric expansion that contributes to the dynamics of a galaxy.  This curvature would be in addition to the curvature caused by the visible mass/energy content of the galaxy.  I got back a note from an editor saying
"In the language of relativity physicists, "locally flat", also called "locally Lorentz", means flat at first order in separation from any chosen point.  Of course, at second order one sees the influence of the Riemann curvature tensor, i.e. of the curvature."
Can someone interpret this for me?  When a book says that the local geometry of spacetime is flat, how local is that?  Microscopically, the size of a football field, a solar system, a galaxy?  What's the cutoff for a 'local' geometry?

A: In coordinates that have the dimension of length, the dimensions of the Riemann curvature tensor are inverse length squared. Therefore at each point the components of this tensor establish length scales which you can loosely think of as radii of curvature. "Local" refers to a region whose length scales are small compared with any of these curvature-based length scales.
For example, near the horizon of a stellar-mass black hole, the radii of curvature are on the scale of kilometers. Therefore dynamics in a local region on the scale of, say, meters is barely affected by the curvature. The differences from the Minkowski metric within this local region are on the order of one part in a million.
For an even smaller region, the differences from Minkowskian are even more negligible. For a larger region, they are less negligible. There is no "cutoff", but just "smaller and more flat" or "bigger and less flat". Over a scale of kilometers the spacetime is not flat at all. Over no region is it perfectly flat.
To understand mathematically how spacetime is "flat at first order", but not second order, at every point, look at the metric tensor in Riemann normal coordinates:
$$g_{\mu\nu}=\eta_{\mu\nu}-\frac13R_{\mu\sigma\nu\tau}x^\sigma x^\tau+O(|x|^3).$$
If we write
$$R\sim\left(\frac{1}{L_\text{curvature}}\right)^2$$
then the deviations from the Minkowski metric over a region of linear scale $L_\text{region}$ are of order $$\left(\frac{L_\text{region}}{L_\text{curvature}}\right)^2.$$

A: What G. Smith said is correct, but I want to also point out that

there is curvature of spacetime from the metric expansion that contributes to the dynamics of a galaxy

is incorrect. There's no such effect.
There are various ways to see this. Here's one. FLRW spacetimes have no Weyl curvature, only Ricci curvature. Ricci curvature is nonpropagating: the field equation directly equates it to the stress-energy at the exact location of the curvature. Therefore all of the curvature of FLRW spacetimes comes from locally present stress-energy. The only significant contributors to the stress-energy tensor are ordinary matter, dark matter, and dark energy. Once you've accounted for those, you're done. There is no mechanism in GR by which any extra "metric expansion" effect could enter into the dynamics.
Note that, within galaxies, none of the major contributors to the stress-energy tensor has a net outward motion, nor a tendency to dilute with the scale factor. The only reason that ordinary and dark matter dilute by $1/a^3$ at larger scales is that the voids between superclusters increase in size and the average density including those voids therefore decreases. This has no effect on the dynamics of individual galaxies. There's no mechanism in GR by which it could have an effect.
The reason for this very common misconception seems to be that people think of FLRW spacetime as a background, i.e., as what you start with before adding the galaxies. It's actually the gravitational field of a uniform matter distribution, and that matter is the same matter that makes up the galaxies. If you put a galaxy on a FLRW background, you're double-counting the matter. To get the correct dynamics, you need to put the galaxy on a de Sitter background, because that's what's actually left behind when the ordinary and dark matter clump.


text:
Q: Prevent Iframe from Reloading the Parent I have a Page with standard iframe markup
Inside the frame is Linked to a Https URL
The iframe does some processing (payment info and such)
Then returns back a POST data When the processing fails most of the time it does not reload the parent(Return url, plus POST data to that URL, loads inside Iframe), and when the processing payment returns successful, most of the time it completely reloads the parent page (Returns url, plus POST data to the Successful URL, Reloads parent to that URL)
As this is code from the secure payment, there isn't alot of things I can show.
Is there any javascript or Html attr that will make this without randomness

A: End up using sandbox mode for iframe and forced stop the redirection atleast for modern browsers.
sandbox="" without allow-top-navigation will force prevent the reload
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe

A: If it only redirects on successful attempts and not every time, then it is most likely redirected from the server (e.g. using a redirect header, or a window.refresh) then you would have to fix your code there (if you have control over it).
If you don't have control over the server side code where the iframe is coming from, ask the owner of the API for help. If they refuse (which they will most likely do) to apply the changes you need, it will probably be due to security concerns (if the user's transaction is getting processed on another server, why is the page hosted in an iframe in your page? read about click jacking)
Either way, I would use fiddler, or any other tool you can think of to examin the contents of a successful response to verify whether the server side code is redirecting.


text:
Q: GetType When Type Is Provided As A String I understand that C# is a staticly typed language and I already read the answers to this SO posting:
initialize a class by string variable in c#?
My question is a bit different, however. I'm working with a T4 template that provides me with the name of a class as a string parameter. I would give the template code here but what's important is that the type is in a string, so it's the same as having this statement in any C# module:
string s = "MyNamespace.Customer.Model";

Using that string, I need to get the type into a Type variable. Normally, I would use this code when I have access to the actual type:
Type typeModel = typeof(MyNamespace.Customer.Model);

How would I be able to obtain the Type given a string? In other words, my code would ideally look something like this (I know this doesn't work because "s" is a string):
Type typeModel = typeof(s);

(I do know what assembly the type is in, by the way, so I can use that information; also, the assembly containing the Type in question is referenced by the template, for what that's worth...)
Note: I do not want to create an object instance of the Type so please don't suggest a solution that requires using Activator.CreateInstance unless that's the only solution...
Thank you for any ideas you can provide.

A: The method Type.GetType(string typeName) does what you want, but if you only provide the FullName (namespace and name) of the type, it will only resolve types from the current assembly or mscorlib.
You would need to supply an AssemblyQualifiedName if you want to resolve types outside the current assembly. The problem of course is that multiple assemblies can contain different types with the same name and namespace (thanks Steven Liekens):
string aqn = Assembly.CreateQualifiedName(assemblyName, namespaceAndNameOfType);
Type t = Type.GetType(aqn);

If you don't know the assembly beforehand, you could deal with this by:

*

*Loading all assemblies from the current AppDomain.BaseDirectory, or

*Using AppDomain.GetAssemblies() for the currently loaded assemblies

And then iterating over each assembly's GetTypes() method.


text:
Q: C - Ncurses window not displaying My cursor movements are working as expected, the only problem is my window is just not showing up. What i have written to appear in the window is not showing. I tried googling the solution but similar code does it the same way I have. I just don't see what is the issue here.
EDIT: I forgot to mention that, my actual intention for this window is to have an updating score for a game. The print that u see there is just an example.
#include <ncurses.h>
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int y = 0;
    int x = 0;
    int oldy = 0;
    int oldx = 0;
    char m = 'l';
    initscr();
    WINDOW* win;
    win = newwin(1, 40, 10 ,0);
    mvwprintw(win,0,0,"First line");
    wrefresh(win);

    while(m != 'q')
    {
            m=getch();
    if(m == 's')
        {
            move((y= oldy+1),x);
            refresh();
            oldy = y;
        }
    else if(m == 'd')
        {
            move(y,(x=oldx+1));
            refresh();
            oldx = x;
        }
    else if(m == 'a')
        {
            move(y,(x=oldx-1));
            refresh();
            oldx = x;
        }
    else if(m == 'w')
        {
            move((y= oldy-1),x);
            refresh();
            oldy = y;
        }
    else
        m = 'q';
    }

    delwin(win);
    endwin();

    return 0;
}

A: Do it like follows,
#include <ncurses.h>
#include <stdio.h>
#include <stdlib.h>

int main()
{
        int y = 0;
        int x = 0;
        int oldy = 0;
        int oldx = 0;
        char m = 'l';
        initscr();

        mvaddstr(0,0, "First line");

        while(m != 'q')
        {
                m=getch();
                if(m == 's')
                {
                        move((y= oldy+1),x);
                        refresh();
                        oldy = y;
                }
                ................
                ................


text:
Q: Statically typed definitions vs dynamic lookup On the book The Go Programming Language Phrasebook said:

If you require performance, then you can use statically
  typed definitions and avoid the dynamic lookup.
  If you require flexibility, then you can use the
  late binding mechanism of interfaces

Can someone explain me what "statically typed definitions" and "dynamic lookup" are for methods and functions in Go?

A: Imagine that we have the following code:
type A struct {}

func (a A) Foo() {
    fmt.Println("Foo called")
}

type I interface {
    Foo()
}

I can now create a variable of type A and call this method:
a := A{}
a.Foo()

The compiler knows the static type of the variable, so knows that the method call refers to the A.Foo method.  So it can compile the above code to use a direct call to A.Foo, which will be as fast as a normal function call.
If instead we use a variable of type I, things are different:
var i I = A{}
i.Foo()

The variable i can hold any type that has a Foo method. In this particular case it is holding an A value, but won't necessarily know this at compile time.  So instead the compiler generates code to check the dynamic type of i, look up the associated Foo method and finally call that method.  This form of dispatch is slower than the first, but has the benefit the code will work for any type implementing the interface.
This is similar to C++'s distinction between virtual and non-virtual methods, except rather than the type of dispatch being fixed for a method at its definition, it depends on the type of variable you use in Go.

A: What the book refers to when it says using static types is using non interface types:
func Foo(v int, s string) { ... }

The other option is using interface:
func Bar(a interface{}, b interface{}) { ... }

Because with the first option, Go will know at compile time what type of value the function will retrieve (int and string in this case), it will compile the code specifically for those types.
With the second option, you will have to use reflection at runtime in order to know the values contained in the interfaces. This is a bit of overhead, but it allows you to pass different types of values as parameters to the function, thus being more dynamic.
Further reading: Laws of Reflection in Go