text:
Q: Browser crashing after adding asynchronous functions to Javascript file. How to fix? I have built a simple online shop application, using ES6 classes vanilla javascript. The shop item objects are stored in a JSON file. I used the file to load the items to the UI.
To create the functions "addToCart:, "quantityChange", and "DeleteFromCart" I intend to use an async callback function "find()" I created, which takes in an Id name, looks for it in the JSON file, and returns the object:

find(x, itemFunction, target) {
        //x is the item id to search for
        //itemFunction, function to use the item found
    const xhr = new XMLHttpRequest();
    xhr.open('GET', 'shop.json', true);

        xhr.onload = function(){
            if(this.status === 200){
                const itemsArray = JSON.parse(this.responseText);
                for(let i = 0; i < itemsArray.length;  i++){
                    if(itemsArray[i].id == x){
                        itemFunction(itemsArray[i], target)
                    }
                }
            }
        }
        xhr.send();
    }

"AddToCart" function works fine, but when I created the "DeleteFromCart" function -in a similar manner- my browser, then my computer kept on crashing. None of the functions work. Even the UI generated from the JSON doesn't load.

 deleteItem(target) {
        if (target.classList.contains('delete')){

            target.parentElement.parentElement.remove();

            let id = target.classList[1];

            this.find(id, this.deleteTheItem, target)
        }
    }

 deleteTheItem(item, target){
        Store.remove(item)
        //delete from localStorage
   }

Perhaps the bug is elsewhere? NB: I don't know Jquery.
Thank you in advance!! :)
I am still new to all this. Perhaps this could help clarify, here is a link to my repo;
https://github.com/HafseeMan/online-shop/tree/master/js

A: let's see if i can clarify this.
if (target.classList.contains('delete'))

That will always be true, because nothing is changing it (nothing in the code above suggest it, so i assume nothing changes that class).
So it will always pass, and run what's inside.
EDIT: try to improve above code like this:
let item = itemsArray.find((el) => el.id === x);
if(item) itemFunction(item, target);

And then in https://github.com/HafseeMan/online-shop/blob/master/js/store.js edit removeItem and change that foreach into this:
store_items = store_items.filter((el) => el.id !== id);

One extra suggestion is that since removeItem is actually only using the itemId, you may pass just that to removeItem method, so what i wrote above would best change into this:
let item = itemsArray.find((el) => el.id === x);
if(item) itemFunction(item.id, target);

And your removeItem like this:
static removeItem(itemId){

    const store_items = Store.getItems();
    store_items = store_items.filter((item) => item.id === itemId);

    localStorage.setItem('store_items', JSON.stringify(store_items));
}

Notice that i removed the target parameter since is doing nothing. So you may also remove it from the followings:
//from this
this.find(id, this.deleteTheItem);
//and this
find(x, itemFunction) {...
//aaand this
itemFunction(item.id, target);
//and also this
deleteTheItem(item, target);

Try that out, update and tell me if it gets better :)
I hope this clarifies the problem. Let me know, if not also tell me to reply your doubt.


text:
Q: Correct pattern to extract #define names by sed Can't define working pattern for sed. The main idea is to extract only #define's with values, not with macroses from line like one -
#define CPU_SUBTYPE_MASK        0xff000000.

Sample in shell script:
pattern="#define (${toRemove})([a-zA-Z0-9_]+)[^\(\)]+\s.*"
sed -n -E "s/$pattern/\t\tINSERT_ELEMENT(${enumName}::_\2, \2);/p" $*

Problem is sed ignores following lines:
#define CPU_SUBTYPE_VAX_ALL     ((cpu_subtype_t) 0)
#define CPU_SUBTYPE_VAX780      ((cpu_subtype_t) 1)
#define CPU_SUBTYPE_VAX785      ((cpu_subtype_t) 2)

...
But I expect it will ignore other lines:
#define CPU_SUBTYPE_INTEL(f, m) ((cpu_subtype_t) (f) + ((m) << 4))

So I can't figure out what is wrong

A: I noticed that \s is not working in sed(potentially, \s is for other regex syntax) but [ ]+ works! Tried another pattern to match, without negating:
pattern="#define (${toRemove})([a-zA-Z0-9_])[ ]+."
Finally, it works!

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to find where is memory leak in QThreads program through Valgrind? Header:
#ifndef CONTROLLER_THREAD
#define CONTROLLER_THREAD

#include <QThread>
#include <QTimer>

class Worker : public QObject
{
    Q_OBJECT
public:
    QTimer timer;

    Worker();
    ~Worker();

private slots:
    void calculateImage();

signals:
    void imageReady();
};

class Controller: public QObject
{
    Q_OBJECT
public:
    QThread objQThread;

    Controller();
    ~Controller();

public slots:
    void receiveImage();
};

#endif // CONTROLLER_THREAD

Source:
#include <controller_thread.h>
#include <iostream>
using namespace std;

Worker::Worker()
{
    connect( &timer, SIGNAL(timeout()), this, SLOT(calculateImage()) );
    timer.start(1000);
}

Worker::~Worker() {}

void Worker::calculateImage()
{
}

Controller::Controller()
{
    Worker *objWorker = new Worker();
    objWorker->moveToThread( &objQThread );

    connect( &objQThread, &QThread::finished, objWorker, &QObject::deleteLater );
    connect( objWorker, &Worker::imageReady, this, &Controller::receiveImage );

    objQThread.start();
}

Controller::~Controller()
{
    objQThread.quit();
    objQThread.wait();
}

void Controller::receiveImage()
{

}

main.cpp
#include "mainwindow.h"
#include <QApplication>
#include "controller_thread.h"
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    Controller f;

    MainWindow w;
    w.show();

    return a.exec();
}

MainWindow class is empty currently:
Header:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = 0);
    ~MainWindow();
};

#endif // MAINWINDOW_H

Source:
#include "mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
}

MainWindow::~MainWindow()
{
}

Valgrind says:
$ valgrind ./qmultithreading_paint
==17570== Memcheck, a memory error detector
==17570== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==17570== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==17570== Command: ./qmultithreading_paint
==17570==
QObject::killTimer: Timers cannot be stopped from another thread
QObject::~QObject: Timers cannot be stopped from another thread
==17570==
==17570== HEAP SUMMARY:
==17570==     in use at exit: 1,333,179 bytes in 14,454 blocks
==17570==   total heap usage: 106,397 allocs, 91,943 frees, 8,932,264 bytes allocated
==17570==
==17570== LEAK SUMMARY:
==17570==    definitely lost: 156 bytes in 2 blocks
==17570==    indirectly lost: 58 bytes in 1 blocks
==17570==      possibly lost: 16,177 bytes in 217 blocks
==17570==    still reachable: 1,234,172 bytes in 13,558 blocks
==17570==                       of which reachable via heuristic:
==17570==                         length64           : 5,336 bytes in 89 blocks
==17570==                         newarray           : 2,160 bytes in 55 blocks
==17570==         suppressed: 0 bytes in 0 blocks
==17570== Rerun with --leak-check=full to see details of leaked memory
==17570==
==17570== For counts of detected and suppressed errors, rerun with: -v
==17570== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
$

Heading
What is valgrind talking about here? How can I fix it?

definitely lost: 156 bytes in 2 blocks
      ==17570==    indirectly lost: 58 bytes in 1 blocks

A: The leak seems to be in the library (Qt) code and is largely inconsequential. If you really want to have a shot at fixing it, you must first get rid of the Timers cannot be stopped from another thread error. See e.g. this answer.
I'm almost certain that the timer list leaks: see _q_reregisterTimers handler - it's not called if the object is in the wrong thread, and thus the list isn't deleted.


text:
Q: Which polytopes are $01$-polytopes? Are there some basic criteria by which to check whether a polytope $P\subset\Bbb R^n$ is a $01$-polytope, that is, can be rotated and scaled to have vertices in $\{0,1\}^n$, maybe even by using higher-dimensional space? I am especially interested in necessary conditions.
In particuar, which of the regular or uniform polytopes is a $01$-polytopes?  Here are some examples for which I know that they are:

*

*simplices (and also hyper-simplices) .

*$n$-cubes (and also demi-cubes).

*$n$-crosspolytopes.

*cartesian products of $01$-polytopes (e.g. certain prisms, duo-prisms, ...).

I know that polytopes with a 5-fold rotational symmetry are not $01$-polytopes, e.g. the regular dodecahedron or 600-cell, since they do not have an embedding with purely rational vertex-coordinates. I also read that the cuboctahedron is not a $01$-polytope, but I have no argument for that. What about the 24-cell?

A: One necessary condition is that the set of distances between vertices (in particular, edge lengths) must scale to a subset of
$$
\{ 1, \sqrt{2}, \ldots  \}
$$
since those are the distances between vertices of the unit cube.

A: When the 24-cell would be a 01-polytope, then its equatorial section, the cuboctahedron, would be too. And, iterating that argument, when the cuboctahedron would be a 01-polytope, then its equatorial section, the regular hexagon, would be too. Sure, the hexagon well can be inscribed into a cube by means of a single cut, but then it would intersect it mid-edge wise. Thus it isn't a 01-polytope. And therefore those other 2 neither.
--- rk

A: I found two further criteria that helped me to eliminate a lot of candidates from my list of symmetric polytopes.

*

*Assuming a sufficiently symmetric polytope $P$ with barycenter in the origin, we can ask for the cosines $\cos\sphericalangle(v,w)$ of the angles between vectors $v$ and $w$ that belong to vertices of $P$ (in a sense, these are just the distances from Ethan's answer, but normalized in a sense). I also was able to derive a formula that gives these cosines in a $01$-polytopes in $\{0,1\}^n$, in which any two vertices have exactly $k$ one-entries. It is
$$\frac{n i-k^2}{n k-k^2},$$
where $i$ is the number of ones the two vectors have in common. So if you let $i$ run in $\{0,...,\max(2k-n,0)\}$ you can find all the cosines such a configuration allows. E.g., the list for the cuboctahedron and 24-cell coincide and are $\{-1,-1/2,0,1/2,1\}$. This list occures first time for $n=8,k=4$. Still, as Dr. Klitzing explained, they are no $01$-polytopes.

*If we look at $01$-polytopes $P$ in which all edges have the same length (e.g. uniform polytopes), then I was able to prove, that if you have to vertices $v$ and $w$ of $P$, their graph theoretical distance in the edge graph determines their Euclidean distance in the polytope and vice versa. This then gives an alternative proof that cuboctahedron and 24-cell are not $01$-polytopes: both have two distinct pairs of vertices at graph theoretical distance two, some belongs to the cosine $0$, and some to the cosine $-1/2$.


text:
Q: ASP.NET MVC4 only showing @RenderBody content on IIS7 ASP.NET MVC4 only showing @RenderBody content on IIS7
Setup: I've got a VM running Windows 7 upon which I've installed IIS7, MVC3 & MVC4 with Web Platform Installer. I've added a new website in IIS using a .NET 4.0 application pool, and then used the Visual Studio 2012 publish option to publish an MVC4 web app to the website's root directory.
The problem is that the only output I am getting is whatever is in the individual views. There is no layout, nothing other than the @RenderBody content.
It works fine when I preview it with Visual Studio.
This is my _Layout.cshtml:
    <!DOCTYPE html>

        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width" />
        <title>@ViewBag.Title</title>
        <link rel="shortcut icon" type="image/x-icon" href="~/favicon.ico">

        @Styles.Render("~/Content/css")
        @Scripts.Render("~/bundles/modernizr")

                @Html.Partial("_TopNavigationPartial")

        @RenderBody()

© 2013 snip.

                            @Html.Partial("_BottomNavigationPartial")

        @Scripts.Render("~/bundles/jquery")
        @RenderSection("scripts", required: false)

All that will be output though is what is in the view, e.g:

Home

You are here: Home/Index

Anyone have any idea why this might be so?
It's probably just that I haven't set up IIS7 right.
Edit: I just uploaded the Internet application and it has done the exact same thing. Only the view content is being output. So it's definitely something in IIS.
Edit 2: I have set up an Internet application as an application in IIS but still it returns the view content only. Weird.
Edit 3: Got it working, not sure how. http://i.imgur.com/ZpKb4P5.gif

A: Managed to fix this. Not sure exactly what was the problem, but I was making a new website and then dragging the published files into it, which wasn't working.
I then added an application to the default website, which worked, but then I found this post which explained that the default website itself is an application.
So in the end I just copied the published files into the default root directory and it worked.


text:
Q: How can I change the Axios responseURL when connecting a Vue.js frontend with a Node.js backend? I am trying to connect a Vue.js frontend to a Node.js backend using Axios. I followed tutorials online and have the following code snippets:
In backend, I have the following Node.js code snippet to post to localhost:5000/signup :
app.post("/signup", (req, res) =>{ // receive form data from signup
  console.log("Hello");
})

I am listening to port 5000:
const PORT = process.env.PORT || 5000;
const server = app.listen(PORT, () => {
  console.log("Server is running on port", server.address().port);
});

Frontend code snippets look something like this:
  methods: {
    submit() {
      this.$v.$touch();
      axios.post("/api/signup", {
        fname: this.fname,
        lname: this.lname,
        email: this.email,
        password: this.password,
        gender: 'Male',
        dob: this.dob,
      }).then((res) => {
        if(res.data.msg === "Email exists"){
          console.log("Email exists")
        }
        else{
          this.$router.push({ path: './browsing' });
        }
      })
      // .catch(()=>{
      //   alert("Something Went Wrong");
      // })

    },
    clear() {
      this.$v.$reset()
      this.name = ''
      this.email = ''
      this.select = null
      this.checkbox = false
    },
  }

I expected the Axios responseURL in the console to send me to localhost:5000/signup and print "Hello" but I have the following error message:
responseURL
:
"http://localhost:8081/api/signup"

It sends me to localhost:8081 which is the default port for Vue and DOESN'T PRINT ANYTHING. What could be the reason for this? And how can I make my responseURL localhost:5000/signup?

A: After playing around, I found that the problem was me not requiring "cors" in the backend file.
All I added was:
var cors = require('cors')
var app = express()
app.use(cors())


text:
Q: Correct spot to assign @@RowCount in SQL stored procedure I am looking for the correct spot to set my @RecordCount = @@ROWCOUNT;
Is it possible to just set it once or is it necessary to set it after each query?
My stored procedure is as follows:
BEGIN
SET NOCOUNT ON;

SELECT *
FROM Table1
WHERE Status = 'A'
AND college = @icollege
AND DeptCode = @idept
AND MajorCode = @imajr;

IF @@ROWCOUNT = 0
BEGIN
    SELECT *
    FROM Table1
    WHERE Status = 'A'
    AND college = @icollege
    AND DeptCode = @idept
    AND MajorCode = '****';

    IF @@ROWCOUNT = 0
    BEGIN
        SELECT *
        FROM Table1
        WHERE Status = 'A'
        AND college = @icollege
        AND DeptCode = '****'
        AND MajorCode = '****';

        SET @RecordCount = @@ROWCOUNT;
    END

    SET @RecordCount = @@ROWCOUNT;
END

SET @RecordCount = @@ROWCOUNT;
END

A: Every statement1 causes @@ROWCOUNT to be set. This means that if you want to do multiple things with the value set by one statement, you need to capture the value immediately into another variable.
So, I'd do something like:
BEGIN
SET NOCOUNT ON;

SELECT *
FROM Table1
WHERE Status = 'A'
AND college = @icollege
AND DeptCode = @idept
AND MajorCode = @imajr;

SET @RecordCount = @@ROWCOUNT;
IF @RecordCount > 0 RETURN

SELECT *
FROM Table1
WHERE Status = 'A'
AND college = @icollege
AND DeptCode = @idept
AND MajorCode = '****';

SET @RecordCount = @@ROWCOUNT;
IF @RecordCount > 0 RETURN

SELECT *
FROM Table1
WHERE Status = 'A'
AND college = @icollege
AND DeptCode = '****'
AND MajorCode = '****';

SET @RecordCount = @@ROWCOUNT;

END

I would, though, also note that this stored procedure may produce up to 3 result sets (with the first 1 or 2 being empty). If your calling code doesn't want to deal with that then we may need to come up with a single query that applies all of the criteria, and selects for the best matches.

1I'm probably wrong here and there's some obscure statement or set of statements that do not. But as a general rule and for most common statements, DML, control flow, SET, etc, it's true.


text:
Q: How do I configure Spring STS to run Selenium test classes? I'm using Spring STS (3.7) to develop an MVC application. I'm attempting to run a simple Selenium test using an example I've read in a book. I'm receiving a 'ClassNotFoundException' when I run the JUnit test. What's odd is that class that's not found is the test class itself: 'UIHomeTest'. I've verified that I have JUnit, Hamcrest and Selenium on the classpath. I've tried adding the JUnit library to the run configuration. Here is the code for the test class:
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverBackedSelenium;
import org.openqa.selenium.firefox.FirefoxDriver;

import static org.junit.Assert.assertEquals;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.thoughtworks.selenium.SeleneseTestBase;

public class UIHomeTest {
private WebDriver browser;

private static final String HOME_URL = "http://localhost:8080/";

@Before
public void setUp() throws Exception {

    WebDriver driver = new FirefoxDriver();

}

@Test
public void testHomePage()
{

    browser.get(HOME_URL);

    assertEquals("Home", browser.findElement(By.id("title")).getAttribute("value"));
}

@After
public void tearDown() throws Exception
{
    browser.close();
}

}

Here is the error:
Class not found org.test.ui.UIHomeTest
java.lang.ClassNotFoundException: org.test.ui.UIHomeTest
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.loadClass(RemoteTestRunner.java:685)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.loadClasses(RemoteTestRunner.java:421)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:444)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

I've been able to run a non-Selenium JUnit test class inside of Spring STS before. Can anyone help me properly configure Spring STS to run Selenium test classes? Thanks.

A: On observing the imports and selenium code i found there are few not required imports used like import org.openqa.selenium.WebDriverBackedSelenium; import com.thoughtworks.selenium.SeleneseTestBase; and also not used or initiated driver object. below is the complete code which works fine for me.
com.tesngtraining; is my package. If you are downloaded java specific selenium jars then please include all jars which are in different folders in build path or download standalone selenium jar file and give it in build path.
 package com.tesngtraining;

import static org.junit.Assert.*;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class TestingJunit {

private WebDriver browser;

private static final String HOME_URL = "http://localhost:8080/";

@Before
public void setUp() throws Exception {

    browser = new FirefoxDriver();

}

@Test
public void testHomePage()
{

    browser.get(HOME_URL);

    assertEquals("Home", browser.findElement(By.id("title")).getAttribute("value"));
}

@After
public void tearDown() throws Exception
{
    browser.close();
}

}

Thank you,
Murali


text:
Q: Can I make a visual block the current search term? Lets say there is some block of text that I want to search for in the file. Is there a way to make a visual-block selection of that text and then make it the current search term? That way I'd be able to do s//replacementText/g without typing the whole thing on the left side of the substitute command.

A: Make a visual block and yank it to the unnamed register "": with a visual block selected, type y to yank. Begin the search with / - or :s/ and type Ctrl-r then " to insert the contents of the unnamed register as the search term.
This won't make the block the current search, but it's nearly as easy.
Ctrl-r can be used anywhere in the command-line, so you can also use this e.g. to fill in the substitution or replacement text, or in insert mode.

A: You'll have to forgive me, I can't remember where I found this, but it works wonders. Just add to your .vimrc. Use your typical * and # after visually selecting:
" Search for selected text, forwards or backwards.
vnoremap <silent> * :<C-U>
  \let old_reg=getreg('"')<Bar>let old_regtype=getregtype('"')<CR>
  \gvy/<C-R><C-R>=substitute(
  \escape(@", '/\.*$^~['), '\_s\+', '\\_s\\+', 'g')<CR><CR>
  \gV:call setreg('"', old_reg, old_regtype)<CR>
vnoremap <silent> # :<C-U>
  \let old_reg=getreg('"')<Bar>let old_regtype=getregtype('"')<CR>
  \gvy?<C-R><C-R>=substitute(
  \escape(@", '?\.*$^~['), '\_s\+', '\\_s\\+', 'g')<CR><CR>
  \gV:call setreg('"', old_reg, old_regtype)<CR>

The real advantage here is that this escapes any special chars, versus just pasting into search command. It's also less keystrokes, which maximizes the vimness of your task.


text:
Q: How to "fix ENOSPC: no space left on device, write" on Mac I've been using create-react-app to create all my react applications. Eventually, I ran into this issue, where when I run npm start, I get this error:
Failed to compile

    ./src/App.js
    Error: ENOSPC: no space left on device, write

I've done lots of research and still can't find out how to resolve the issue. I know it has to do how many "watches" the system is set to and I've reached that limit, but I don't know how to change the limit or delete my previous watches.

A: I bumped into the same issue today. I think you're out of space on your laptop.

A: I just encountered with the same problem but by running npm start command on your terminal it works.


text:
Q: Changing the color scheme of a wordpress theme I am decent with coding in html and css, but php is very new to me. I am looking to change the color scheme of this theme: http://bwthemes.com/themes/?theme=wellness. I have searched the css files endlessly looking for where the colors are for the nav menu bg, the body, and the wrapper, but have found nothing... I am really confused at this point and am thinking that the color schemes are saved externally on a website or in a folder, but I can't find this. If you look at the page source you can see the colors, but on the actual style sheet I can't find it.
By posting this Im hoping someone has created a theme like this here and can help me out. Any thoughts/guidance helps and I appreciate it! Thanks a lot in advance.

A: Just to be clear the "Theme" is called "Wellness" and it has multiple "skins". You don't want to create a new theme you want to create a new skin. That being said it looks like you can toggle through various skins the current one that is displaying in the link above is the skin1 located at this path.
wp-content > themes > wellness > skins > skin1.css
If you go into that directory you should be able to see all of the available skins. And simply add a another stylesheet and use the same naming convention. So if the last one is skin3.css then your custom sheet should be skin4.css.
This assumes that the developer of the theme didn't hard code the skins into the theme, and in that case you will have to hack the php...which is a different engagement and w/o access to your server side code I/we can't really give you much more guidance.

A: it looks like the css file is called superfish.css?ver=3.4.1
if youre using firefox.. firebug is a great tool for exploring css on a page.  you could download the extension for free.
then right click on anything in the page and click 'inspect element'   on the right side of the page you should see all the css properties

A: Use Google Chrome's Inspect Element feature or Firebug. Both are excellent resources for web development.
For example, in Chrome's developer tools, you'll be able to see something like this when you right click on the navigation and choose Inspect Element.
You can change the styles here and see changes real-time. Also, as you can see in the screenshot below, there is a link to the stylesheet. It's skin1.css.
Of course, there are other stylesheets too. You can see them with View Source option.

I hope that answers your question!


text:
Q: How do I properly set up a single-table inheritance structure using Ember's Active Model Adapter and Rails' Active Model Serializer? I'm creating a board game with a human player vs. a bot player, both types stored on a players table with a type column. Each player has their own board.
I have a Rails API using the active model serializer gem.
My ember app connects to it using active model adapter.
Here are my serializers:
class GameSerializer < ActiveModel::Serializer
    attributes :id, :winner_id, :created_at, :updated_at
    has_many :players, polymorphic: true, serializer: PlayerSerializer
end

class PlayerSerializer < ActiveModel::Serializer
    ### Players can be type Human or Bot
    attributes :id, :name, :game_id, :type, :created_at, :updated_at
    has_one :board
end

class BoardSerializer < ActiveModel::Serializer
    attributes :id, :player_id, :created_at, :updated_at
    has_one :player, polymorphic: true
    has_many :pieces
end

And here are my Ember models:
// game.js
import DS from 'ember-data';

export default DS.Model.extend({
    players: DS.hasMany('players', {async: true, polymorphic: true}),
    human: DS.belongsTo('human', {async: true}),
    bot: DS.belongsTo('bot', {async: true})
});

// player.js
import DS from 'ember-data';

export default DS.Model.extend({
    game_id: DS.attr(),
    name: DS.attr(),
    game: DS.belongsTo('game', {async: true }),
    board: DS.belongsTo('board', {async: true})
});

// human.js
import DS from 'ember-data';
import Player from './player';

export default Player.extend({
    type: DS.attr('string', {defaultValue: 'Human'})
});

// bot.js
import DS from 'ember-data';
import Player from './player';

export default Player.extend({
    type: DS.attr('string', {defaultValue: 'Bot'})
});

// board.js
import DS from 'ember-data'
export default DS.Model.extend({
    player_id: DS.attr(),
    player: DS.belongsTo('player', { async: true, polymorphic: true }),
    pieces: DS.hasMany('pieces', { async: true })
})

On the games.show route, I want to be able to call something like game.get('human.board.pieces') and game.get('bot.board.pieces') but no matter what I try, game.get('human.board.id') always returns undefined. I've also tried retrieving the board separately from the store, but the player_id is on the board, not the other way around.
Can anyone can help me figure out how to configure my AMS serializers and Ember Models correctly?

A: I ended up treating humans and bots as their own models since I would never really call game.get('players') this in the Ember app and it worked. Didn't have to touch the player, human, bot, or board models.
// game.js
export default DS.Model.extend({
    human: DS.belongsTo('human', {async: true}),
    bot: DS.belongsTo('bot', {async: true})
});


text:
Q: understanding TDictionary on IntegerList can I create a TDictionary directly on a TList class ? It looks a bit double work if I create my TDictionary Class with key and values are always the same data  like BlackList.Add(1, 1);
var
  BlackList: TDictionary<Integer, Integer>;
  ResultList: TDictionary<Integer, Integer>;
  TestListA: TLIst<Integer>;
  TestListB: TLIst<Integer>;
  i: Integer;
begin
  BlackList.Add(1, 1);
  BlackList.Add(2, 2);

  for i := 0 to TestListA.Count - 1 do
  begin
    if BlackList.ContainsValue(TestListA[i]) then
    begin
      // no action ...
    end
    else
    begin
      ResultList.Add(i, TestListA[i]);
    end;
  end;

  for i := 0 to TestListB.Count - 1 do
  begin
    if BlackList.ContainsValue(TestListB[i]) then
    begin
      // no action ...
    end
    else
    begin
      if not(ResultList.ContainsValue(TestListB[i])) then
        ResultList.Add(i, TestListB[i]);

    end;
  end;
end;

The purpose of this algorithm is to compare 2 Integer list's , find all doubles but exclude numbers from a blacklist. The first q is here Find common elements in two Integer List.

A: The whole purpose, in this particular code, of using TDictionary is to take advantage of O(1) lookup. With TList, which is an array, you do not have that property. Lookup is O(n) in general, O(log n) if sorted. So you cannot extract the O(1) lookup performance from a TList by any means, hence the use of TDictionary.
So it is the performance motivation that is driving the use of TDictionary. As I said in your previous question, the overhead of setting up dictionaries is only worthwhile if the lists are large. You would need to do some benchmarking to quantify what large means in this context.
As for your dictionary, it does not matter what values you use since only the keys are significant. So use zero always. Ideally what you want is a hash set type based on the same algorithm as the dictionary. But I don't believe there is such a thing in the stock RTL. I expect that libraries like Spring4D offer that functionality.


text:
Q: Automatically graph data in ggplot2: Date vs Data (with constraints) I am looking to automatically create and regularly update roughly 56 graphs from a large, regularly updated dataset. I am looking to graph specific columns, y1-y7, with specific sub-locations, 1-6, based on the selected column, at locations A, B, C, D. I have worked out how to manually create the graphs that I would like with the multiple functions, similar to the following code and with resulting graph:
graph <- function(A, B, C, D = "2020-04-20", E = "NA"){
    print(
        ggplot()+
            geom_line(data=A,
                      aes(x=DATE, y = y1, group = interaction(Location,SubLocation),
                          linetype = SubLocation, color = Location), size =1)+
            geom_point(data=A,
                       aes(x=DATE, y = y1, group = interaction(Location,SubLocation),
                           shape = SubLocation, color = Location), size =2)+
            scale_color_manual(values = c(B))+
            ggtitle(C)+
            xlab("Date")+
            ylab(y1)+
            theme_bw()+
            geom_vline(xintercept = as.numeric(xInt), color = "Red")+
            geom_rect(data = xRect, aes(xmin = Start, xmax = End, ymin = -Inf, ymax = Inf, alpha = 0.5))+
            coord_cartesian(xlim = c(as.Date(D), E), ylim = c(0,40))
    )
    ggsave("y1.jpeg", last_plot(), width=12, height=6, dpi=300)
}

I don't want to manually go through and create these 56 graphs with 12 separate functions and I can't figure out the syntax - with filtering in tidyverse or creating a list. I would like to select the following data, graph it, and save it as it's own output:

Do you have any thoughts on how to create a list, similar to the spreadsheet that I inserted where I can then loop the code to create and save the desired graphs, similar to this source?
Thank you so much.


text:
Q: Import outlook addin manifest from excel web (insert -> office addin), it says "Addin manifest not valid" I'm working on a outlook web-addin. The addin works when in run it on local host, can see the addin in outlook.
When the manifest file is validated with "npm run validate", it looks fine. But when I try to import the manifest file using Excel Web -> Insert -> Office Add-ins, I get "Your Addin manifest is not valid" error. could some on please guide how to identify the issue.
I'm planning to host the web UI in azure and install the manifest file on my team mate's machine to run some tests.

A: If it is a outlook addin, you should import it using outlook not Excel.

A: You need to use the target host application for sideloading the web add-in. In your case this is Outlook. Also you may consider deploying centralized, see Deploy add-ins in the Microsoft 365 admin center for more information.
You may also find the Deploy and install Outlook add-ins for testing article helpful.


text:
Q: Browser Neutral Way to add options to a select element in javascript I just learned something interesting. The add method for the javascript select object in IE 6 takes only one parameter. It throws an error when you pass it two parameters which I believe is the standard, even as documented on the MSDN site.
My question is this. What is your best-practice recommendation for programmatically adding option elements to a select element in javascript?

*

*Call the add method differently based on the value of the user agent?

*Wrap the select object in a class that provides the proper method signature?

*Use a javascript library which does this for you (specify which library)?

A: You can use a try-catch block for doing this :
              try
    {
        //Standards compliant
        list.add(optionTag, null);
    }
    catch (err)
    {
        //IE
        list.add(optionTag);
    }

A: $("#selectID").addOption(value, text);

using the addOption function from the jQuery selectboxes plugin

A: I would suggest using DOM-methods instead.
document.createElement('option')
selectEl.appendChild()

Never had issues with that.

A: You shouldn't be using the Select.add method, as it's broken in IE, and there are better ways to add options dynamically (see http://msdn.microsoft.com/en-us/library/ms535921(VS.85).aspx)
I have had the same problem, and have found that the best way is to use the Node.insertBefore method. This has the advantage of working in all browsers, and making sorting of the elements easy, because you don't have to add the element as the last element of the select list in IE. For example, adding an option from one select list to another, so that the options in the target list are sorted alphabetically, can be done like this:
/*
adds an option to select element, alphabetically sorted according to the lower case value of the display element (option.text)
*/

function insertOptionToList(optionToInsert, targetSelectElement){

    for (var i=0;i<targetSelectElement.options.length;i++){
        var tempOptionText = targetSelectElement.options[i].text;
        if(tempOptionText.length>0 && optionToInsert.text.toLowerCase()<tempOptionText.toLowerCase()){
            targetSelectElement.insertBefore(optionToInsert,targetSelectElement[i]);
            return true;
        }
    }
    targetSelectElement.options[targetSelectElement.options.length] = optionToInsert;
    return true;
}

A: Adding a new Option type works at least IE6 and up
function addOption(selectID, display, value)
{
  var obj = document.getElementById(selectID);
  obj.options[obj.options.length] = new Option(display, value);
}

Additionally tested in Firefox 2, 3, Opera 8, 9.5, and Safari 4 successfully.  IE4 failed :(

A: This worked for me
$(selectID).append($('<option>'+display+'</option>').attr('value', value));

A: I did some research myself using all permutations and combinations of creating an option object and I hope this is the best possible way by which we can add options to select in a browser neutral way:
function populateSelectField()
{

    document.frmMain.fldSelect.options.length = 0;
    document.frmMain.fldSelect.options[document.frmMain.fldSelect.options.length]=new Option("Your Value 1");
    document.frmMain.fldSelect.options[document.frmMain.fldSelect.options.length]=new Option("Your Value 2");
    document.frmMain.fldSelect.options[document.frmMain.fldSelect.options.length]=new Option("Your Value 3");
    document.frmMain.fldSelect.options[document.frmMain.fldSelect.options.length]=new Option("Your Value 4");
}

Since the select field object is accessed and manipulated by accessing it's parent object, which is "frmMain" (form) in this code, it doesn't create any problem for any browser to run the code.
This is supported by all browsers including IE.

A: If you want to add an option to the start of the dropdown, the following variation should do it:
    try{
        list.add(optionTag, 0);
    } catch (err) {
        // Firefox is dumb for once: http://www.quirksmode.org/dom/w3c_html.html#selects
        list.add(optionTag, list.options[0]);
    }

A: (edit: this doesn't work in IE, so it's not recommended.)
I do it by changing the innerHTML:
<select id="selectItem"></select>

var s=document.getElementById("selectItem");
s.innerHTML+="<option>apples</option>";
s.innerHTML+="<option>bananas</option>"; //(...etc)

Or put it in a loop if you are using an array to populate your dropdown list.

A: As I remember, IE4 accepts creation of an option element and appending it, but perhaps I don't recall it coorrectly !-)


text:
Q: Cannot create Windows shortcuts in PowerShell on Linux I want to use scripts to create shortcuts under the Windows operating system (.lnk).
In the Windows environment, I chose PowerShell, wrote the script, successfully created .lnk.
$shell = New-Object -ComObject WScript.Shell
$desktop = [System.Environment]::GetFolderPath('Desktop')
$shortcut = $shell.CreateShortcut("$desktop\clickme.lnk")
$shortcut.TargetPath = "C:\Users\scc\Desktop\linkfolder"
$shortcut.IconLocation = "shell32.dll,004"
$shortcut.Save()

But my online running environment is Linux.
Fortunately, I found that PowerShell in 2016 on a multi-platform transplant, yes, it can support Linux. I found it, downloaded, and installed. Under Linux, in the PowerShell command window I can run some basic commands.
There was a run-time error!
When I run the first line of code:
$shell = New-Object -ComObject WScript.Shell

The error message is:

New-Object : Unable to load DLL 'api-ms-win-core-com-l1-1-0.dll': The specified
module or one of its dependencies could not be found.
(Exception from HRESULT: 0x8007007E)
At line:1 char:10
+ $shell = New-Object -ComObject WScript.Shell
+          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [New-Object], DllNotFoundException
    + FullyQualifiedErrorId : System.DllNotFoundException,Microsoft.PowerShell.Commands.NewObjectCommand

According to the prompt, it seems that the lack of WScript-related modules. Missing DLL file.
My requirement is to run Java programs under Linux to create shortcuts in Windows format. (Stored in the network disk, the file system for the btrfs, and can provide SMB \ AFP \ NFS \ FTP these file services)
Yes, this demand seems to be strange, if you have a new solution ideas and ideas, please tell me or discuss with me.
I have a bold idea: can I use the SMB protocol to create an .lnk file?

A: You can use the below to create Windows Shortcuts in Linux:
MSLink
It is having both bash version and C source.
Refer this also:
Produce-lnk-file-on-gnu-linux-to-transfer-to-windows


text:
Q: Selenium python slider bouton Element Not Visible Exception I'm trying to write to a parser to click a button on a website and I can not click two of the buttons.
I would like to click on "Elija el imports a financiar" and "Elija la mensualidad"
Here's the html: https://www.cofidis.es/es/creditos-prestamos/prestamo-personal.html
python code:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
chrome_options.add_argument('--start-maximized')
webdriver = webdriver.Chrome('chromedriver',chrome_options=chrome_options)
url = "https://www.cofidis.es/es/creditos-prestamos/prestamo-personal.html"

webdriver.get(url)
targetSliderStep = 6.000
targetSliderStep = round(targetSliderStep  * 2) / 2  # to ensure is units covered by clicking
print('target: ' + "{0:.3f}".format(targetSliderStep))
webdriver.find_element_by_xpath('//*[@id="btncerrar"]').click()
actualSliderStep = float(webdriver.find_element_by_id('I2:simuPanel.O').text.replace(' €',''))
print(actualSliderStep)
webdriver.find_element_by_xpath('//*[@id="I2:simuPanel.mensMoreId"]').click()
webdriver.find_element_by_xpath('//*[@id="I2:simuPanel.mensLessId"]').click()
print(actualSliderStep)

webdriver.find_element_by_xpath('//*[@id="I2:simuPanel.mensMoreId"]').click()
webdriver.find_element_by_xpath('//*[@id="I2:simuPanel.mensLessId"]').click()

print(webdriver.find_element_by_id('I2:simuPanel.O7').text)
webdriver.find_element_by_xpath('//*[@id="I2:simuPanel.durMoreId"]').click()
webdriver.find_element_by_xpath('//*[@id="I2:simuPanel.durLessId"]').click()
print(webdriver.find_element_by_id('I2:simuPanel.O7').text)

I am getting this error.
ElementNotVisibleException: Message: element not interactable

A: I can see your Xpath is correct.But it is not interact able.
Please try the actionchain it should work. The code will work with headless when you add this below chrome options as well.
chrome_options.add_argument('window-size=2560x1440')

Instead of this
webdriver.find_element_by_xpath('//*[@id="I2:simuPanel.mensMoreId"]').click()

Please Try
 el=webdriver.find_element_by_xpath('//*[@id="I2:simuPanel.amountMoreId"]')
   ActionChains(webdriver).move_to_element(el).click(el).perform()

In that way change all 4 slide button click option.Let me know if that works.


text:
Q: OpenMPI Reduce using MINLOC I'm currently working on some MPI code for a graph theory problem in which a number of nodes can each contain an answer and the length of that answer.  To get everything back to the master node I'm doing an MPI_Gather for the answers and am attempting to do an MPI_Reduce using the MPI_MINLOC operation to figure out who had the shortest solution.  Right now my datatype that stores the length and node ID is defined as (per examples shown on numerous sites like http://www.open-mpi.org/doc/v1.4/man3/MPI_Reduce.3.php):
struct minType
{
    float len;
    int index;
};

On each node I'm initializing the local copies of this struct in the following manner:
int commRank;
MPI_Comm_rank (MPI_COMM_WORLD, &commRank);
minType solutionLen;
solutionLen.len = 1e37;
solutionLen.index = commRank;

At the end of the execution I have an MPI_Gather call that successfully pulls down all of the solutions (I've printed them out from in memory to verify them), and the call:
MPI_Reduce (&solutionLen, &solutionLen, 1, MPI_FLOAT_INT, MPI_MINLOC, 0, MPI_COMM_WORLD);

It's my understanding that the arguments are supposed to be:

*

*The data source

*is the target for the result (only significant on the designated root node)

*The number of items sent by each node

*The datatype (MPI_FLOAT_INT appears to be defined based on the above link)

*The operation (MPI_MINLOC appears to be defined as well)

*The root node's ID in the specified comm group

*The communications group to wait on.

When my code makes it to the reduce operation I get this error:
[compute-2-19.local:9754] *** An error occurred in MPI_Reduce
[compute-2-19.local:9754] *** on communicator MPI_COMM_WORLD
[compute-2-19.local:9754] *** MPI_ERR_ARG: invalid argument of some other kind
[compute-2-19.local:9754] *** MPI_ERRORS_ARE_FATAL (your MPI job will now abort)
--------------------------------------------------------------------------
mpirun has exited due to process rank 0 with PID 9754 on
node compute-2-19.local exiting improperly. There are two reasons this could occur:

1. this process did not call "init" before exiting, but others in
the job did. This can cause a job to hang indefinitely while it waits
for all processes to call "init". By rule, if one process calls "init",
then ALL processes must call "init" prior to termination.

2. this process called "init", but exited without calling "finalize".
By rule, all processes that call "init" MUST call "finalize" prior to
exiting or it will be considered an "abnormal termination"

This may have caused other processes in the application to be
terminated by signals sent by mpirun (as reported here).
--------------------------------------------------------------------------

I'll admit to being completely stumped on this.  In case it matters I'm compiling using OpenMPI 1.5.3 (built using gcc 4.4) on a Rocks cluster based on CentOS 5.5.

A: I think you are not allowed to use the same buffer for input and output (first two arguments). The man page says:

When the communicator is an intracommunicator, you can perform a
  reduce operation in-place (the output buffer is used as the input
  buffer). Use the variable MPI_IN_PLACE as the value of the root
  process sendbuf. In this case, the input data is taken at the root
  from the receive buffer, where it will be replaced by the output data.


text:
Q: Imagem em e-mail HTML no PHPMailer Estou fazendo um template para envio de e-mail marketing, que contém uma imagem:

Mas a imagem não vai para o e-mail (claro, está com endereço local).
Pelo PHPMailer, existe uma forma de "anexar" a imagem junto para usá-la ou terei que fazer o upload em um serviço de imagens ?
O problema no caso de servidor de imagens, seria esse link sair fora do ar um dia, e assim perder todos os e-mails anteriores, correto !?

A: Utilizando o método $mail->AddEmbeddedImage:
$mail->AddEmbeddedImage('img/logo.jpg', 'logo_ref');
Na tag  insere: src='cid:logo_ref'.
Dessa forma, a imagem ficará embutida no e-mail.


text:
Q: what is the real difference between ng test and ng e2e I am afraid someone close my question but I couldn't find a satisfying question (maybe because I am very limited in Angular 2+ world and I understood something wrong).
As far as I could understand after few Hello World done and few YouTube demo watched:
ng test:

*

*you write your test using Jasmine language

*you test your test with many Browsers available using Karma

*you execute either unit or integrated testing

*all xxx.compnent.spec.ts run and a final report similar to JUnit is showed in browser

ng e2e:

*

*you write your test using Jasmine language

*you test your test with many Browsers available using Karma

*you write your tests with nesting user event in mind
eg. page.navigateTo();
page.getParagraphText()
  .then(msg => expect(msg).toEqual('Welcome to app!!'))
  .then(msg => expect(msg).toEqual('xxx'))
  .then(done, done.fail);

*you execute End to End test using protractor mainly after deployed the application a kind of pre-production environment

*the tests under e2e folder are triggered and the result is printed in command line console

Theoracly saying, the second is specific for end to end where the focus is to simulate a entire flow done by an end user.
Hopefully, until here is correct, I am wondering what is happening behind the scene that really make them different. I don't want to compare which is better but certainly I am missing some point somehow because I created few tests using exact same idea done by end user and I triggered it by ng test.
For instance:
...

it('should display the modal when `create Paste` is clicked', () => {

    let createPasteButton = fixture.debugElement.query(By.css("button"));
    //create a spy on the createPaste  method
    spyOn(component,"createPaste").and.callThrough();

    //triggerEventHandler simulates a click event on the button object
    createPasteButton.triggerEventHandler('click',null);

    //spy checks whether the method was called
    expect(component.createPaste).toHaveBeenCalled();
    fixture.detectChanges();
    expect(component.showModal).toBeTruthy("showModal should now be true");
    expect(element.innerHTML).toContain("source-modal");
});

...

I remenbered I read something like "protractor offer a waiting/sleeping behaviour during tests execution" but I can't see where this aggregate value when I see the tests done without protractor been able to simulate a final user as well. As long as you code your tests to do exact same flow done by an end user it will be same e2e test propose under e2e folder created by Angular Cli.
If my study drove me to correctly understanding as posted above then, the only real difference is the way I, as developer, is organizing my tests. There is nothing really different happening behind the scene.
Again, I would appreciate see this as clarifing question for didatic purpose: there is no intention to compare frameworks here at all.

A: You are on the good road to understand all of it.

*

*Ng test (Jasmine + Angular Testing Utilities tests launched through Karma):
You are using the jasmine framework to write your tests and define them as suites and expect results that you can test, but the main thing is that you are actually using the karma launcher to execute tests directly on the browser. This is normaly configured in the angular app.
This means there is one server running the tests and that's it. You test with your own values and check that your components are working correctly.
The aim is to check for single components (unit test) or several modules / components (integration tests) that a single function / small workflow is working correctly as intended without side effects.

*

*Ng E2E (Jasmine + Protractor) :

Protractor is an end-to-end test framework for Angular and AngularJS
  applications. Protractor runs tests against your application running
  in a real browser, interacting with it as a user would.

Here, the tests you have written will act as a user. This means there is your application running in your browser, and another program will run the tests against your application, simulating a user interaction.
This is very important, because that means two things :

*

*Unit tests and Integration tests are using static, mock data to run the tests.

*Protractor tests are using real data, and doing the HTTP (or whatever you are using) calls to fetch the data and consume/test it.

The aim with protractor is to validate a full operationnal workflow in your application. For example, I'll write my unit test for my login component, write an unit test for my login service, write an integration test for my whole module and whatever behavior I need to test that depends on several components / services. Once this is done, I'll write later a full end-to-end test that will validate my whole authentication process in my application.
Bear in mind, there is a ratio that is important about testing which is very logical :

*

*Unit tests should represent 70% of your tests.

*Integration tests should represent 20% of your tests.

*E2E tests should represent 10% of your tests.

Why is that ? Because if you did unit test correctly a lot of your components, you won't need to test that again in your End-to-End tests.

Conclusion :

*

*They operate differently and their aim is to test different things (unit function / full workflow).

*They are complementary, which means that if you only realize Unit / Integration tests, you will never have the guarantee that a workflow will work from A to Z; as well as if you only write E2E tests you will never be able to confirm that there are no side-effects in your workflow.

N.B. : Be also aware of those points :

*

*Jasmine, Karma, and Protractor can be customized at will, so you can make them output in an XML file that could be processed by a Jenkins job instead of a command line which is not practical.

*Yes, you can write the same code for both and effectively test the same thing, but bear in mind that what you want is to be efficient and write maintanable test code. The ratios I talked about are very important.

Hope this helps.


text:
Q: firebase + next dont save data in realtime database Hello i have big problem, the firebase realtime database dont save data
for example
const createUserProfile = (email,user,username) => {
    console.log(email);
    console.log(user)
    const db = getDatabase();
    console.log(db)
    const dbRef = ref(db, 'users/' + user.uid);
    set(dbRef, {
      username,
      email,
      createDate: getDate()
    });
  };

In realtime conf i have write true and read true
what i can do? its next js
all data is okay,
console.log(db) response is

and realtime database dont update

A: This is probably because you don't pass the Firebase app instance to the getDatabase() method.
See here in the doc that you need to do
import { initializeApp } from 'firebase/app';
import { getDatabase } from "firebase/database";

// TODO: Replace with your app's Firebase project configuration
const firebaseConfig = {
  apiKey: "API_KEY",
  authDomain: "PROJECT_ID.firebaseapp.com",
  // The value of `databaseURL` depends on the location of the database
  databaseURL: "https://DATABASE_NAME.firebaseio.com",
  // ...
};

const app = initializeApp(firebaseConfig);

// Get a reference to the database service
const db = getDatabase(app);  // <= See how we pass the app object


text:
Q: Permanently continue work from previous commit I checked out a previous commit, using git checkout , I made changes, and committed them. However, when I do git status, it says HEAD detached from . How can I make commit that I've checked out the commit I want to keep going forward?

A: Let's look at the situation step by step. Initially you were at the head of a branch, let's say it was master:
--A--B--C
        ^ master
       HEAD

I checked out a previous commit, using git checkout

git checkout HEAD~

Now you're here:
--A--B--C
     ^  ^ master
   HEAD

This situation is called "detached HEAD" because HEAD (the current pointer) is not at the head of any branch.

I made changes, and committed them.

Now you're here:
       --D < HEAD
      /
--A--B--C
        ^ master

What do you want to do now? Do you want to drop the commit C at the head of master and move master to where your HEAD is (to D)? Or do you want to move the commit D to master (preserving C)?
The first task can be solved with the following commands:
git branch tmp-master # create a new branch

       tmp-master
         v
       --D < HEAD
      /
--A--B--C
        ^ master

git checkout master

       tmp-master
         v
       --D
      /
--A--B--C < HEAD
        ^ master

git reset --hard tmp-master # move the branch
git branch -D tmp-master # remove the temporary branch

       master
         v HEAD
       --D
      /
--A--B--C

Or, to streamline the new master branch:
--A--B--D
      \
       C

The commit C becomes a dangling commit and sooner or later will be removed by garbage collector.
But if you want to do the second task (preserve both C and D) the steps are a bit different:
git branch tmp-master # create a new branch

       tmp-master
         v
       --D < HEAD
      /
--A--B--C
        ^ master

git checkout master

       tmp-master
         v
       --D
      /
--A--B--C < HEAD
        ^ master

git cherry-pick tmp-master
git branch -D tmp-master # remove the temporary branch

--A--B--C--D' < HEAD
           ^ master

A: Just reset to that commit.
git reset --hard <commit_id>

A: Push it to the remote with -f so that it erases history.
If your branch is called b1:
git push -f origin b1

Then delete the local branch and checkout the remote branch again. You're all set.


text:
Q: Can't extract PostHistory from stack overflow data dumps I downloaded the stackoverflow.com-PostHistory.7z file from here and I can't extract the 7z file. I tried 7-zip software and WinRAR. I also tried extracting from 2 different hard drives. Both failed.
I got the following error in 7-zip when I tried to extract:

Data error (cyclic redundancy check).

The error appeared after about 50% of extraction like in this picture:

A: Sometimes downloaded files are "blocked" by the OS as a security measure. Right click the file you have downloaded and choose "Properties", you might see this:

If that's the case, tick the "Unblock" checkbox, confirm, and it should work as expected.

A: ok i found a solution to my problem.
i downloaded again the file, this time from this link:
https://ia800107.us.archive.org/27/items/stackexchange/
and i just managed to extract the file.


text:
Q: What cause segmentation fault error when using tbb::parallel_invoke? I tried using both openmp and intel tbb on ubuntu 18.04 with gcc and g++ version 6 for optimizing my code. I use openmp to optimize for loops and tbb::parallel_invoke to run 1 function with 4 different input.
I tried using lambda expression to pass some argument by reference, but I am not sure whether I wrote that right or not. However, I keep getting "segmentation fault (core dumped)" error when using parallel_invoke.
int shrink = 6;
cv::Mat mat1, mat2;
tbb::parallel_invoke([&]
        {mat1 = myfunction(image1, arg1, arg2) * shrink;}, [&]
        {mat2 = myfunction(image2, arg1, arg2) * shrink;});

image1, image2, and arg1 are opencv matrix while arg2 is my own defined class.
When I run the program without parallelization
mat1 = myfunction(image1, arg1, arg2) * shrink;
mat2 = myfunction(image2, arg1, arg2) * shrink;

There are no problem and the program run just fine. I use parallel_invoke because I expect those two can be run simultaneously. Is it not working because both arg1 and arg2 are used simultaneously?
I don't know what to do because Segmentation fault (core dumped) was all that is shown in the terminal.
Edit:
This is what Myfunction() looks like:
Mat edgebox_main(Mat E0, Mat O0, _para o) {
    // check and get inputs
    arrayf E;
    arrayf O;
    int h = E0.rows;
    O._h = E._h = h;
    int w = E0.cols;
    O._w = E._w = w;
    E._x = new float[h * w];
    O._x = new float[h * w];
    getadd(E0, E._x);
    getadd(O0, O._x);

    //optionally create memory for visualization
    arrayf V;

    // setup and run EdgeBoxGenerator
    EdgeBoxGenerator edgeBoxGen;
    Boxes boxes;
    edgeBoxGen._alpha = o.alpha;
    edgeBoxGen._beta = o.beta;
    edgeBoxGen._eta = o.eta;
    edgeBoxGen._minScore = o.minScore;
    edgeBoxGen._maxBoxes = o.maxBoxes;
    edgeBoxGen._edgeMinMag = o.edgeMinMag;
    edgeBoxGen._edgeMergeThr = o.edgeMinMag;
    edgeBoxGen._clusterMinMag = o.clusterMinMag;
    edgeBoxGen._maxAspectRatio = o.maxAspectRatio;
    edgeBoxGen._minBoxArea = o.minBoxArea;
    edgeBoxGen._maxBoxLength = std::min(std::min((int)o.maxBoxLength,h),w);
    edgeBoxGen._gamma = o.gamma;
    edgeBoxGen._kappa = o.kappa;
    edgeBoxGen.generate(boxes, E, O, V);
    boxesNms(boxes,edgeBoxGen._beta,edgeBoxGen._eta,edgeBoxGen._maxBoxes);

    // create output bbs and output to Matlab
    int n = (int) boxes.size();
    float *bbs = new float[n * 5];
    for (int i = 0; i < n; i++) {
        bbs[i + 0 * n] = (float) boxes[i].c + 1;
        bbs[i + 1 * n] = (float) boxes[i].r + 1;
        bbs[i + 2 * n] = (float) boxes[i].w;
        bbs[i + 3 * n] = (float) boxes[i].h;
        bbs[i + 4 * n] = boxes[i].s;
    }

    Mat bbs_mat(n, 5, CV_32FC1);
    fillmat(bbs, bbs_mat);
    return bbs_mat;
}

The code calls several other class and function which I think would be too long if I write all of them here. Also I am not very experienced with debugging in Linux. I usually use Microsoft Visual Studio for debugging C++, so I don't really know how to generate additional debugging information in the terminal, do you have any suggestion about what debugger to use or is g++ alone is enough?

A: After I use stacktrace and check the core dump as written in this post. I got additional error messages which says SIGSEGV error. That error basically tells that I tried to access an element that wasn't available in the array.


text:
Q: ¿Cómo acceder a relación 1:m en Ruby on Rails? estoy haciendo una API en Ruby on Rails, soy nuevo en este lenguaje y tengo problemas para acceder a las relaciones que tengo, tengo 'comidas' que se relacionan con una categoría, lo que busco hacer es que la API regrese toda la comida que esta registrada con sus respectivas categorías, quiero que se mande como se muestra continuación:
Salida
{
    "status": "Success",

    "message": "All foods DESC",
    "data": [
        {
            "id": 2,
            "name": "Una",
            "size": 12,
            "portion": "Vasos",
            "category": "Frutas",
            "updated_at": "2018-09-28T18:50:01.137Z"
        },
    {
        "id": 3,
        "name": "Otra",
        "size": 4,
        "portion": "cucharadas",
        "category": "Frutas",
        "updated_at": "2018-09-28T18:50:01.137Z"
    },
    {
        "id": 4,
        "name": "Otraxs",
        "size": 4,
        "portion": "cucharadas",
        "category": "Leguminosas",
        "updated_at": "2018-09-28T18:50:01.137Z"
    }
    ]
}

Modelos
Categoria
class Category < ApplicationRecord
    # Asociación con modelos.
    has_many :foods, dependent: :destroy
end

Comida
class Food < ApplicationRecord
    belongs_to :category
end

Controlador
def index
    food = Food.order('created_at DESC')
    foods = []
    food.each { |f| foods <<
        {  :id => f.id,
            :name => f.name,
            :size => f.size,
            :portion => f.portion,
            :category => f.category.name,
            :updated_at => f.updated_at
        }
    }
    render json: {status: 'Success', message: 'All foods DESC', data: foods}, status: :ok
end

Así como se muestra la salida, es la forma en que lo quiero, donde me muestre cual es el nombre de la categoría a la que pertenece, esto ya lo logré como se muestra en el controlador, sin embargo pienso que no es la forma correcta y quiero algo de asesoramiento

A: Puedes utilizar la gema Active Record Serializers https://github.com/rails-api/active_model_serializers
Para que de esa manera puedas crear un serializer para tu modelo y al ser enviado como json automaticamente tenga la estructura que tu definas.
En este ejemplo se incluyen los atributos de Food que quieres para tu json y además incluye un JSON Object con los atributos de la categoría a la que pertenece:
class FoodSerializer < ActiveModel::Serializer
  attributes :id, :name, :size, :portion, :updated_at
  belongs_to :category
end

Quedando así:
{
        "id": 2,
        "name": "Una",
        "size": 12,
        "portion": "Vasos",
        "category": {
          # Atributos de Category
        },
        "updated_at": "2018-09-28T18:50:01.137Z"
    }

O puedes hacerlo de la siguiente manera para que en lugar de incluir un JSON Object para category, agregue solo el campo que tu quieres:
class FoodSerializer < ActiveModel::Serializer
  attributes :id, :name, :size, :portion, :updated_at, :category

  def category
    object.category.name
  end

end

Queda así:
{
  "id": 2,
  "name": "Una",
  "size": 12,
  "portion": "Vasos",
  "category": "Frutas",
  "updated_at": "2018-09-28T18:50:01.137Z"
}

EDIT:
Tu acción en el controlador quedaría de esta forma
def index
    foods = Food.order('created_at DESC')
    foods_json = ActiveModelSerializers::SerializableResource.new(foods, adapter: :json).as_json
    render json: {status: 'Success', message: 'All foods DESC', data: foods_json}, status: :ok
end


text:
Q: Unable to dynamically increment a property of an object I'm trying to create a dynamic canvas animation using javascript. The intent is to increment the x property of many image objects and then draw them in the x position of the updated x property each time a draw() function runs. I'm not able to successfully increment this x property though - for some reason it always resets to 0.
I defined this global array to contain all the objects I will draw:
window.character = [];

I have this object constructor to create new image objects:
function Character(name, x, y){
    //define the image object within the Character
    this.imageObject = new Image();
    this.imageObject.src = name+'iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAW0lEQVR42mL8//8/AzpgZGTcC6KBcs5wMRwK/0MVMsLEmLAoEmXAApiwiKUhaRJCltgLsQVsWwIQ/wTx0fBeRigD7B6Y24i1mj4Kn4KI7Uie2Y7FI8+B2AMgwABjRynfWgpcxQAAAABJRU5ErkJggg==';

    window.character.push(this);
    window.characterPosition = window.character.indexOf(this);

    //set natural width and natural height once the image is loaded
    if (this.imageObject.addEventListener){
        this.imageObject.addEventListener('load', function(){
            window.imgWidth = this.naturalWidth/2;
            window.imgHeight = this.naturalHeight/2;

            //set natural width and natural height to object
            window.character[characterPosition]['imageObject']['w'] = window.character[characterPosition]['imageObject']['w0'] = window.imgWidth;
            window.character[characterPosition]['imageObject']['h'] = window.character[characterPosition]['imageObject']['h0'] = window.imgHeight;

            //set initial x and y position
            console.log(x);
            window.character[characterPosition]['imageObject']['x'] = x;
            window.character[characterPosition]['imageObject']['y'] = y;
            console.log(window.character[characterPosition]['imageObject']['x']);
            //set loaded property for the object once loading is done
            window.character[characterPosition]['imageObject']['loaded'] = true;

            function imageLoaded(element, index, array){
                return element['imageObject']['loaded'] == true;
            }

            //test whether every object in array has the image loaded
            if(character.every(imageLoaded)){
                $('button#play').show();
            };
        });
} //end object constructor

Inside that constructor function, there is some weird behavior. I created a new object using:
var sun0 = new Character('data:text/javascript;base64,', 12, 12);

Then here's what I see from the console.log messages inside the object constructor:
console.log(x); //returns 12, as expected
window.character[characterPosition]['imageObject']['x'] = x;
window.character[characterPosition]['imageObject']['y'] = y;
console.log(window.character[characterPosition]['imageObject']['x']); //returns 0. Thought it would be 12

Ultimately, here's how I intend to animate the object across the screen. This draw() function runs on an interval every 10ms.
function draw(){
    clear();

    //draw characters
    drawCharacter(window.character[0]['imageObject'],window.character[0]['imageObject']['x'],window.character[0]['imageObject']['y'],window.character[0]['imageObject']['w'],window.character[0]['imageObject']['h']);
    window.character[0]['imageObject']['x'] += 10;
    console.log(window.character[0]['imageObject']['x']); //returning 0 every time, not incrementing the way I expected it to.
}

How can I get this 'x' property to increment?
here's the JS Fiddle

A: Pointy answered your question in the comments, but to expand on this... you're trying to set x on an Image which can't be set. For instance, try this in your browser's console:
var img = new Image();
img.x = 1;
console.log(img.x); // this will be zero

That's effectively what you're doing. Additionally, in your code try changing ['x'] to ['myX'] and then it will work as expected.


text:
Q: How to split pyspark dataframe into segments of equal sized rows I'm trying to create a new column that puts rows in my pyspark dataframe into groups based on observed rank values. For example, I'd like the first 100,000 ranks to be group 1, the next 100,000 to be group 2, and so on, up to an arbitrary number of ranks (it needs this flexibility as the size of my data, and number of overall ranks is likely to change)
Does anyone know how to achieve this? This is what my intended output looks like
--------------------------------------
| id.       |     rank   | segment   |
--------------------------------------
| 100       |   1        |     1     |
| 200       |   100,002  |     2     |
| 300       |   900,007  |     9     |
--------------------------------------

The only help I can find from browsing is for splitting the ranks into some kind of quantile, but I need guarantees that my segments are of size 100,000.
Does anyone have any tips as to how to achieve this outcome?
Some sample code here if it helps
import pandas as pd

spark.createDataFrame(pd.DataFrame({
  "id": [100,200,300], "rank": [1, 100002, 900007]
}))

A: You can use the ceil function.
import pyspark.sql.functions as F

......
step = 100000
df = df.withColumn('segment', F.expr(f'ceil(rank / {step})'))
df.show(truncate=False)


text:
Q: oracle weblogic OAM servlet proxy - how to propagate OAMAuthnCookie I am trying to wrestle with SSO in weblogic version is 12.2.1.3. We have integrated it with OAM/OID, within a larger application comprising of Oracle Forms & Reports. In addition to Forms, we have various custom servlet-based applications that need to be called from Forms.
This is fine.
Because authentication happens within the Oracle world, through OAM login screen, up to now I didn't have to mess with the Access Management within my Java custom code, apart from getting the username from HTTP headers.
The bad thing is that sometimes we need our servlets to act as middle-man between Forms and Reports. E.g. I need to call various stuff with Reports (on server), transform them and send them back to the client. I know that this doesn't sound right design-wise. But still it's legacy code and we need to make this work - at least need to try..
Previously we used to get away with it passing cookies between requests. But in 11/12g OAM, I am gathering from here that the cookie needed for successful session validation (OAMAuthnCookie) is stripped from the request before reaching my servlet. This seems to happen indeed, basing on the header dumps i am doing, and tracing calls using F12 Developer Tools on the browser.
So.. I have gathered that I need to generate a new OAMAuthnCookie, or something that would create it and attach it to the new http call.. I just would like an expert or somebody who has dealt with this to verify that the following assumption is right - the only way to do this is using OAM SDK (a bit non-intuitive imho).
Another thing - many of the examples that I find about OAM SDK deal with login forms. I don't need to do user authentication, nor do I need to talk with OAM myself to verify if the resource is protected or not. I am dealing with an already authenticated request - need to just somehow get UserSession and user token from HttpServletRequest, in order to generate new OAMAuthnCookie so that my next request (using e.g. apache client) succeeds.. I used to assume that this wouldn't be hard to do, but am a bit stumped now.
Thank you for your attention.

A: Working with OAM SDK, as far as I cursively saw (at the time of writing this, we were using Weblogic 12c with Access Manager that behaves exactly as described in the documents that talk about OAM 11g - therefore I assume that's the version we are using too), involves

*

*generating ObAccessClient.xml from OAM Console, to establish contact between the code you are working on (which will be called Access Client), and OAM

*including JARs from the downloadable OAM SDK with your application

*writing code in your application (e.g. in authentication filter, or servlet) to establish communication with OAM via its SDK to finally authenticate/authorize etc.

There is a good guide about how to write the code in Oracle documentation here.
I found also these articles very informative:

*

*Oracle Access Management blog

*Oracle A-team Best Practices blog
The code that I had in mind would ultimately generate a new authentication cookie that I would pass to the reports servlet for further authorization (since this cookie is stripped indeed from the request before reaching my application). The only way I found to generate such a cookie would involve changing a setting in OAM console to include another cookie (OAM_IDENTITY_ASSERTION) in the requests, according to another Oracle A-Team article.
In the process of the above investigation, I finally stumbled on this magic reply to a question in Oracle forums. According to it, there is a user setting in OAM console, that allows to switch off the default filtering of OAMAuthnCookie.
filterOAMAuthnCookie=false

In our case, this perfectly suited me. Indeed after the change, the cookie in question was finally reaching my application, with the result of me being able to pass it to subsequent requests to Oracle Reports, without using OAM SDK.


text:
Q: What is the first proof that you've done using induction? Right now in class I'm learning induction and I'm having a hard time to grasp the concepts of it, especially strong induction which confuses me even further.
But out of curiosity, what is the first proof that you guys have done using mathematical induction?

A: One consequence of mathematical induction is the Well-ordering principle:

Every non-empty set of positive integers contains a least element.

In fact, it is possible that you must have internalized it long before even formally seeing the process of mathematical induction. So in a weird sense it could be the "first application" of it.


text:
Q: More efficient algorithm to randomly select raffle winners in Python I'm trying to find a code to select a random winner from all generated raffles and is there a faster way Python can generate more raffles quicker and generate millions if so how. Here's my code so far.
import random

def genNumber(n = 4):
    return "".join([str(random.randint(0,9)) for i in range(n)])

for i in range(12365):
    word = random.choice(['blue', 'aqua', 'jade','plum', 'gold', 'navy', 'pink', 'grey', 'ruby', 'rose', 'teal',"lime",])
    print("{} {} {}".format(word.title(), genNumber(4), genNumber(4)))
random.choice(word)

A: Your current raffle ticket generation algorithm has a problem: it may produce the same ticket more than once. A simple way to prevent that is to just generate the tickets in order. If you want to generate the tickets randomly, that's possible too, but you'll need to keep track of all the tickets generated to prevent duplicates.
The code below creates a list of all valid ticket numbers, shuffles that list, and then converts each number to a color + number string. My code only generates simple number strings, but that can be easily fixed to create numbers of the form xxxx xxxx if you want.
First, I'll illustrate the function that does the conversion.
    colors = ['Blue', 'Aqua', 'Jade',]
    num_colors = len(colors)

    def num_to_ticket(n):
        return '{0} {1}'.format(colors[n % num_colors], n // num_colors)

    num_tickets = 15
    for n in range(num_tickets):
        print(num_to_ticket(n))

output
Blue 0
Aqua 0
Jade 0
Blue 1
Aqua 1
Jade 1
Blue 2
Aqua 2
Jade 2
Blue 3
Aqua 3
Jade 3
Blue 4
Aqua 4
Jade 4

Now here's the code that shuffles the tickets and selects one at random. This code uses the random.seed function so that the results are reproducible. If you don't call random.seed, or if you call it with an argument of None (i.e. random.seed(None)), then the pseudo-random sequence will be seeded with a random number provided by the OS, so the results will vary each time you run the program.
From the random module docs:

random.seed(a=None, version=2)
Initialize the random number generator.
If a is omitted or None, the current system time is used. If
  randomness sources are provided by the operating system, they are used
  instead of the system time (see the os.urandom() function for
  details on availability).

from random import seed, randrange, shuffle

colors = [
    'Blue', 'Aqua', 'Jade',
    #'Plum', 'Gold', 'Navy',
    #'Pink', 'Grey', 'Ruby',
    #'Rose', 'Teal', 'Lime',
]
num_colors = len(colors)

def num_to_ticket(n):
    return '{0} {1}'.format(colors[n % num_colors], n // num_colors)

seed(1234)

num_tickets = 15

tickets = range(num_tickets)
shuffle(tickets)
for n in tickets:
    print(num_to_ticket(n))

winner = randrange(num_tickets)
print('\nWinner:', num_to_ticket(winner))

output
Aqua 1
Jade 0
Jade 2
Blue 1
Aqua 2
Aqua 0
Blue 3
Blue 4
Aqua 4
Jade 1
Jade 3
Aqua 3
Blue 0
Blue 2
Jade 4

Winner: Blue 3

If you're using Python 3 you need to change this line:
tickets = range(num_tickets)

to this:
tickets = list(range(num_tickets))

On my old 2 GHz machine with 2GB of RAM I can shuffle 10000000 tickets in about 30 seconds.

Here's a modified version that prints the tickets in the form Jade 0038 0763. It also allows you to specify the number of winners to generate. If you want the numbers to be different each time simply supply a new argument to seed each time, or just delete the seed call altogether.
from __future__ import print_function
from random import seed, randrange, shuffle, sample

colors = [
    'Blue', 'Aqua', 'Jade',
    #'Plum', 'Gold', 'Navy',
    #'Pink', 'Grey', 'Ruby',
    #'Rose', 'Teal', 'Lime',
]
num_colors = len(colors)

def num_to_ticket(n):
    color = colors[n % num_colors]
    num = str(n // num_colors).zfill(8)
    return '{0} {1} {2}'.format(color, num[:4], num[4:])

seed(1234)

num_tickets = 15
num_winners = 4

tickets = range(num_tickets)
shuffle(tickets)
for n in tickets:
    print(num_to_ticket(n))

#Select winners
winners = sample(tickets, num_winners)
for i, num in enumerate(winners):
    print('Winner #{0}: {1}'.format(i, num_to_ticket(num)))

output
Aqua 0000 0001
Jade 0000 0000
Jade 0000 0002
Blue 0000 0001
Aqua 0000 0002
Aqua 0000 0000
Blue 0000 0003
Blue 0000 0004
Aqua 0000 0004
Jade 0000 0001
Jade 0000 0003
Aqua 0000 0003
Blue 0000 0000
Blue 0000 0002
Jade 0000 0004
Winner #0: Jade 0000 0001
Winner #1: Jade 0000 0002
Winner #2: Blue 0000 0002
Winner #3: Jade 0000 0000

And here's the output of the "winners" section of the code when I change  num_tickets to 1500000
Winner #0: Jade 0038 0763
Winner #1: Jade 0033 4760
Winner #2: Aqua 0034 9232
Winner #3: Jade 0046 6305

That takes around 5 seconds on my machine.

Here's yet another version that should be more to your liking... However, it does run slower: generating 1,500,000 tickets (without printing them) takes around 12 seconds on my machine.
''' Generate random raffle tickets, and select winners

    See http://stackoverflow.com/q/35113113/4014959

    Written by PM 2Ring 2016.02.01
'''

from __future__ import print_function
from random import seed, randrange, shuffle, sample

colors = [
    'Blue', 'Aqua', 'Jade',
    'Plum', 'Gold', 'Navy',
    'Pink', 'Grey', 'Ruby',
    'Rose', 'Teal', 'Lime',
]
num_colors = len(colors)

def num_to_ticket(n):
    color = colors[n % num_colors]
    num = str(n // num_colors).zfill(8)
    return '{0} {1} {2}'.format(color, num[:4], num[4:])

seed(1234)

num_tickets = 15
num_winners = 4

tickets = set()
while len(tickets) < num_tickets:
    ticket = randrange(1200000000)
    tickets.add(ticket)

for n in tickets:
    print(num_to_ticket(n))

#Select winners
winners = sample(tickets, num_winners)
for i, num in enumerate(winners, 1):
    print('Winner #{0}: {1}'.format(i, num_to_ticket(num)))

output
Pink 6158 1569
Blue 0074 9147
Pink 3460 8896
Pink 6232 8147
Ruby 9392 6899
Jade 9109 7596
Lime 4407 3259
Ruby 0839 3822
Aqua 6715 6348
Pink 9664 5353
Pink 2368 0977
Jade 0308 1402
Plum 7664 8093
Ruby 7887 7271
Plum 5822 2757
Winner #1: Pink 3460 8896
Winner #2: Plum 5822 2757
Winner #3: Blue 0074 9147
Winner #4: Pink 6158 1569


text:
Q: viewdidappear not called on 2nd go round I have view1 that when shaken will load view2 and in view2 a button is pressed loading view3, in view3 button is pressed loading view1. When view1 is loaded from view3 the shake gesture in view1 does not respond to shake any longer.
- (BOOL)canBecomeFirstResponder {
    return YES; // making view the first responder for shake event
}

- (void)viewDidAppear:(BOOL)animated {
    [self becomeFirstResponder]; //for the shake event
    [super viewDidAppear:animated];
}

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {

 if (motion==UIEventSubtypeMotionShake) {
  //adding AskAsh2VC START
  AskAsh2VC *second = [[AskAsh2VC alloc] initWithNibName:nil bundle:nil];
  //this will set the animation style to CROSSDISSOLVE!
  second.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
  [self presentModalViewController:second animated:YES];
  [second release];
  //adding AskAsh2VC END
 }
}

- (IBAction)goToAskAsh2VC: (id) sender {
 // NSLog(@"Button WORKS!!!!");
 //adding AskAsh2VC START
 AskAsh2VC *second = [[AskAsh2VC alloc] initWithNibName:nil bundle:nil];

 //this will set the animation style to CROSSDISSOLVE!
 second.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
 [self presentModalViewController:second animated:YES];
 [second release];
}

A: why don't u call view did appear on vc once you have presented it
[self presentModalViewController:second animated:YES];
[second viewDidAppear:YES];

A: From what you are saying, your view1 presents view2 modally... which means view1 never left, it is just obscured by view2 and all the subsequent views. And you are pushing multiple modal views which is generally frowned upon. It sounds like you would be better suited loading a navigationController and push each view onto the stack. When you want to reset back to view1, you can just popToRootViewController and kill everything off except for your first view.
The reason your shakes aren't being registered is because they are being captured by your hidden view controller.


text:
Q: Regex not getting characters I have this regex
\.*?\{\{([\w\s]+)\|([\w\s]+)\}\}

and it captures the word like this correctly:
{{58afc8ed3688d3001cb8b043_1487915885599|data}}

But if I put a word like this
{{58afc8ed3688d3001cb8b043_1487915885599|data?}}

it fails capturing it.
How am I supposed to capture the later?

A: You can try the following regex :
.*?\{\{([\w\s]+)\|(.*?)\}\}

see demo

A: The only difference between your two examples is that you have an extra '?' character in (or after) the second group.
siam's answer is correct, but will result in a very broad match which might not be what you want. After all, in the extreme case you could replace the whole regex with \{\{(.*)\|(.*)\}\} if you wanted.
Assuming it's only a question mark you're concerned with, you could:

*

*add that to your acceptable characters anywhere in your group by
extending ([\w\s]+) to ([\w\s?]+)

*add it explicitly to the end of
your group, replacing ([\w\s]+) with ([\w\s]+\?*) (which will
allow zero or any number of trailing question marks)

*add it after the
group if you don't care about capturing it with ([\w\s]+)\?*
Of course, if you mean to accept special characters other than just the question mark you can simply keep adding them in the same way.

A: \.*?\{\{([\w\s]+)\|([\w\s?]+)\}\} should do the trick. \w\s won't catch a question mark.


text:
Q: Executing a stored procedure fails when placed in transaction I have a query that I want to execute via a linked server. The query looks like this:
USE db1;

SET xact_abort ON;

DECLARE @statement NVARCHAR(max);
SET @statement = 'EXECUTE (''INSERT INTO T1(V1, V2) VALUES (1, 2)'') AT LS1';

BEGIN try
    BEGIN TRANSACTION

    EXEC Sp_executesql @statement

    COMMIT TRANSACTION
END try

BEGIN catch
    IF ( Xact_state() ) = -1
      BEGIN
          PRINT Error_message()

          ROLLBACK TRANSACTION
      END

    IF ( Xact_state() ) = 1
      BEGIN
          PRINT 'COMMIT OPEN TRANSACTION'

          COMMIT TRANSACTION
      END

    INSERT INTO tblerrmsg (errornumber, errorseverity, errorstate, errorline, errormessage) EXECUTE Usp_geterrorinfo;
END catch

This fails with an entry in my TblErrMsg table.

ErrorNumber = 8501, ErrorSeverity = 16, ErrorState = 3, ErrorLine = 1, ErrorMessage = MSDTC on server 'XXX' is unavailable.

So I researched for the specific error message and checked if the Distributed Transaction Coordinator Service was running on the server, but this was already the case. Even a restart of the service did not bring any change. Next I tried to remove the transaction and execute the following procedure:
USE db1;

DECLARE @statement NVARCHAR(max);
SET @statement = 'EXECUTE (''INSERT INTO T1(V1, V2) VALUES (1, 2)'') AT LS1';

BEGIN try
    EXEC Sp_executesql @statement
END try

BEGIN catch
    PRINT Error_message()
END catch

And this time it worked. There were no errors and the INSERT also worked. So I'm wondering what really the problem is. Apparently there seems to be no problem with the execution of the procedure nor with the Linked Server connection.
Has anyone ever had a similar problem, or has an explanation for this behavior?

A: It's possible you're missing the key word DISTRIBUTED when specifying the explicit transaction.
Instead of
BEGIN TRANSACTION

Try
BEGIN DISTRIBUTED TRANSACTION

According to the Docs this is the way to specify "... the start of a Transact-SQL distributed transaction managed by Microsoft Distributed Transaction Coordinator (MS DTC)"
Without the explicit transaction the default behavior afaik is the transaction across linked server is not guaranteed to be atomic and cannot be rolled back.  This why it works when no explicit transaction is specified.
When BEGIN TRANSACTION is specified without 'DISTRIBUTED' the statement is asking something that's not possible when the procedure contains a linked server reference.


text:
Q: Computer randomly freezes, mostly on ubuntu I have a random freeze issue since I built my computer and never figured out what was wrong. I worked with it and restarted my computer every time I had the issue. I recently changed my motherboard & replaced my cpu fan with a watercooling, I hoped changing the motherboard would help, but it is now worse.
Before, my computer was freezing randomly 1 or 2 times a week, most of the time when I was working on Ubuntu, but I also had the issue on Winwows (I have the two installed on 2 different SSD, I switch at boot : Ubuntu for work and Windows to play games).
Now, I cannot even use Ubuntu, it just freezes almost every time I try to use it. Sometimes I can do some things before, sometimes just starting firefox make it freeze. I didn't had the issue on windows since I changed the motherboard, I do use it less than Ubuntu but still.
Here are some details about the freeze:

*

*keyword/mouse not responding, keyword leds (caps lock, num lock) frozen too. Can't open a console with Ctrl+Alt+F3 either.

*No error led on the motherboard, no error sound either.

*sometimes the music freezes too (loop of less than a sec, sometimes bigger loop). Sometimes music is shutdown.

*Screens are frozen too of course.

*Only solution: hard reset of the computer.

The hardware:

*

*CPU: AMD Ryzen 7 3700X

*Motherboard: MSI MAG X570 TOMAHAWK WIFI, previously (same bug but less often) B450 AORUS PRO

*CPU FAN: MSI CORELIQUID 240R

*RAM: Corsair Vengeance LPX Series Low Profile 32 Go (2 x 16 Go) DDR4 3600 MHz CL18

*GPU: EVGA GeForce RTX 3080 XC3 ULTRA GAMING

*SSD/HD: Samsung 860 EVO 500GB (Ubuntu), Samsung 860 PRO 256GB (Windows), other for data: WD20EZRX 2To, SanDisk 960GB, Samsung 970 Evo Plus 1TB (Nvme).

*Power: Corsair AX850 80PLUS Titanium

What I tried:

*

*CPU benchmark with hardinfo (all of them): no freeze.

*Removing 1 RAM and test with the other: freeze with either of them.

*Removing the Windows SSD: freeze.

*Wiping out the entier Ubuntu drive and reinstalling it from latest image (USB EFI): freeze, even had a freeze once from the usb itself when installing.

*Boot ubuntu with options: "noacpi" or "processor.max_cstate=5 rcu_nocbs=0-11": freeze.

*Reset motherboard settings to default: freeze.

I'm about to go crazy so if anyone has a lead I can work on, I would really appreciate it. My guess would be an issue in the CPU (since I changed the motherboard and the issue persist with either of the 2 ram), but I would like any other opinion on that and a way to be sure it's the source of the issue, because I can't just return it to my seller if it works fine...
Thanks.

A: This looks similar to something I'm seeing with a Ryzen 3700X on a Gigabyte B550 Motherboard. I'm using 5.12 and 5.13.x kernels, which has improved the support for the Radeon RX 5500M graphics card... My system usually freezes as you describe, often in a video conference with BigBlueButton - computer appears to be running, but accepts no input (keyboard or mouse) and the camera (USB) stop accepting images and dies. I suspect that part of the problem in my case is a motherboard issue with the USB hardware. The only vaguely relevant kernel messages related to the crash seem to be "usb1-3.1: Failed to query" messages around the time of the crash.

A: I have the same problem using the same mainboard / cpu combination (Ryzen 7 3700X on MSI MAG X570 TOMAHAWK WIFI).
The solution that works for me is to increase CPU voltage by 0.025 volts in the BIOS:

*

*set "CPU Core Voltage" to "offset mode"

*set "CPU Offset Voltage" to 0.025V

I have absolutely no freezes any more with this setting. As soon as this setting is removed (e.g. after BIOS update and resetting to default BIOS settings) the freezes are there again.
Hope this may help you.


text:
Q: Store objects that maintain their own internal immutable state, inside an array of stores Before I begin, please let me say that I have no intentions of implementing the following inside a React/Redux application. This question is hypothetical only.
The following code uses Redux to generate an array of Redux store objects inside an array. Each store has the ability to maintain it's own internal state object as this is what Redux does.
My question, albeit a simple one, is, is an array of store objects, which are capable of maintaining their own internal state, immutability?
Could this array be passed throughout an application and the states within the stores updated by dispatching actions to the appropriate store via the stores array index without mutating? i.e. stores[0].dispatch({ type: 'VALUE1' })
If the array needed to ever have a store removed, I'd imagine you could use array.filter to return a new array of store objects? Thank you
import { createStore } from 'redux'

const fake = function fakeReducerFunction(state, action) {
  switch (action.type) {
    case 'VALUE1':
      // Return new state object
      return
    case 'VALUE2':
      // Return new state object
      return
    default:
      return
  }
}

const numStores = 10
const create = function createArrayOfStores(counter = 0, array = []) {
  const store = createStore(fake)
  if (counter === numStores) return array
  return create(counter + 1, [...array, store])
}

const stores = create()
stores[0].dispatch({ type: 'VALUE1' })


text:
Q: Unable to send email to the same domain from which it's sent via SendGrid My setup is as follows:

*

*VPS running on DigitalOcean

*DNS running on DigitalOcean (managing the domain XYZ.com which directs to the VPS)

*day-to-day business email running in a 3rd party provider service (with addresses like name@XYZ.com)

*transactional email API (SendGrid) using the same domain as the VPS and business email (XYZ.com)

My problem is, whenever I try to send some transactional email via SendGrid to one of my business addresses I get the messages blocked with the following notification from SendGrid:

error dialing remote address: dial tcp <SOME_IP_HERE>:0-><ANOTHER_IP_HERE>:25:
i/o timeout

I reckon the issue might me sending and receiving the email from the same domain, however, I have no idea how to tackle this. What should I do?

A: It turns out it was an issue with anty-spoof filter on my business email. I turned it off and it all works now.

A: Check sendgrid

`
Suppressions -> (Bounces, Blocks)

`
option. some times sendgrid block the mail


text:
Q: How Initializing Direct to object works in C++? I really don't know what question/title can explain my problem.
I'm just going to show you example.
How this works? Does compiler automatically call parameter constructor with initializer list?
#include <iostream>
class A {
    public:
        int k;
};
int main(){
    A obj={2};
    std::cout << obj.k; // output 2;
}

I was confused that compiler automatically call parameterized constructor. Then I tried to test.
#include <iostream>
class A {
    public:
        int k;
        A(int a){
            std::cout << "Para A" << std::endl;
        }
};

int main(){
    A obj={2}; // error in C++98 but works in C++11 and call Para A.
    std::cout << obj.k; // Garbage value why?
}

After that I think, when we didn't define constructor explicitly, then Compiler automatically assume that A obj={firstField,SecondField,....}; mean call default constructor and then initlize fields with given values in {....} So, question is that is I'm Right with this logic if not then how this works? A obj={2};
IN C++11
if parameterized constructor defined, then you can call that constructor by this  A obj={values};

A: This is called aggregate initialization.

when we didn't define constructor explicitly, then Compiler automatically assume that A obj={firstField,SecondField,....}; mean call default constructor and then initlize fields with given values in {....}

Correct.
But when you define a constructor and do A obj = {...} that's copy-list-initialization.


text:
Q: How to use uproot to load referenced values (TRefArray) I am trying to use uproot to do some basic selection from a Delphes .root output file. Delphes's c++ code examples are looping over events and accessing reconstructed BranchElements,  which have methods to access the branch elements belonging to various classes.
e.g. The root file contains a <TBranchElement b'Jet' at 0x7fb36526b3c8> that (in c++) Delphes example code can use to get object=jet->Constituents.At(i) in a "for" loop and then if this object is a object->IsA() == Tower::Class then one calls object->P4() to get the 4momentum.
So, whereas using uproot one could only separately get the two values, in Delphes examples one uses the Jet class to get access to the Tower class (from which the Jet was reconstructed) using a method.
The information I see is:
    Jet_size                   (no streamer)              asdtype('>i4')
    Jet                        TStreamerInfo              asdtype('>i4')
    Jet.fUniqueID              TStreamerBasicType         asjagged(asdtype('>u4'))
.
.
.
    Jet.Constituents           TStreamerInfo              asgenobj(SimpleArray(TRefArray))

<TBranchElement b'Jet' at 0x7fb3657825f8>

<TBranchElement b'Jet.Constituents' at 0x7fb47840cba8>

For uproot, if one loads the TBranchElement as an array, then there's only access to the array elements in Jet.Constituents[i], which are lists of numbers.
How would I be able to load Jet.Constituents in a way that refers to the Tower.PT (or eta,phi etc.) values that it contains?

A: If you have an array of TRefs, you can use them directly as an integer index on the other collection. (See this tutorial, starting on In[29], for a general introduction to indexing by integer arrays, both in Numpy and Awkward Array.)
That is, if you have an array of TRef, as in this example,
import uproot
t = uproot.open("issue324.root")["Delphes"]
refs = t["Track.Particle"].array()
refs.id
# <JaggedArray [
#      [752 766 780 ... 1813 1367 1666]
#      ...
#      [745 762 783 ... 1863 1713 1717]]>

gives you the indexes and
pt = t["Particle.PT"].array()

the array you want to reference, so
pt[refs.id - 1]
# <JaggedArray [
#      [0.7637838 1.1044897 5.463864 ... 4.252923 1.9702696 9.213475]
#      ...
#      [1.2523094 0.37887865 0.7390242 ... 1.0288503 3.4785874 1.804613]]>

selects the pt values of interest (correcting for the fact that these indexes start with 1 and Python indexes start with 0).
If you have an array of TRefArray as in this example,
t["Tower.Particles"].array()
# <ObjectArray [[[1414, 1418, 1471, 1571], [1447], [1572],
#               ...,
#               [864, 1325], [992, 1437], [1262, 1501]]]>

it's actually an ObjectArray that generates sub-arrays from the data on demand (because ROOT doesn't store doubly jagged data natively). You can convert them to native JaggedArrays by calling awkward.fromiter on them:
import awkward
a = awkward.fromiter(t["Tower.Particles"].array())
# <JaggedArray [[[1414 1418 1471 1571] [1447] [1572]
#                ...
#                [864 1325] [992 1437] [1262 1501]]]>

and then use these doubly jagged indexes in any doubly jagged collection (in which all the numbers of elements line up, as they would for the collection you're referencing).