text:
Q: What is the best way to create AngularJS ACL? I want to share with you (community) my problem.
I use MEAN stack, so I use Node.js with Express and AngularJS and I have singe app application.
I use passport as an authentication strategy in Node \ Express \ Jade code.
I want to create admin section on my page to manage users and others stuff.
I want also protect this AngularJS sites loaded asynchronously by adding some access control to my $routeProvider like:
$routeProvider.when('/admin/users', {
    templateUrl: '/views/admin/users.html',
    auth: {
        required: true,
        roles: ['admin']
    }
})

This is only pseudocode which I want to achive in my real solution.
If user is not logged in, should be redirect to /signin page, and if user is logged in and does not have proper role to view this page, should be redirect to appropiate view with custom information.

A: I prefer to handle access control on the server side, and just not serve anything up to the user if s/he shouldn't be able to access it. Then I field and interpret the response from the server to do things like rerouting to a sign-in form.
This allows for really flexible security mechanisms. For example, I can configure my backend security with a firewall for something like you've described (where a route "/admin" and all of its descendants should be protected). I can use ACLs to secure individual objects, or a SecurityManager that allows for more complex analyses of the user making the request.
Maybe this isn't a direct answer to your question, but instead encouragement to approach the problem differently. Still I think it's a better approach than anything that I've seen in terms of pure JS access control.

A: Have a look at UI-Router: https://github.com/angular-ui/ui-router
It is pretty cool and you can intercept state changes based on whatever security scheme you want.
We are using it with a permission/role/group based security scheme and it works awesome.


text:
Q: Max(x,y) and argmax(x,y) I am writing my report and I got confused on this simple maths concept.
What I need is: I have 2 values i.e x and y and I want to use the maximum of either x or y as my length. So which statement is correct in maths terms.

*

*Max(x,y)

*argmax(x,y)

A: Yes, $\max(x,y)$ is the maximum of $x$ and $y$, whereas argmax$_{x,y} f(x,y)$ are the values of $x,y$ that maximize the function $f$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to capture the Refresh event of OWA In my project, I've implemented a WOPI server. Sometimes, oos prompt the message 'Sorry, your changes weren't saved. To continue editing this document, please copy your changes and refresh the page', But if I click the Refresh button, there is nothing happened.
My question is how to capture this refreshing event in my WOPI server?


text:
Q: async/await troubles in a recursive Redis function Ima rookie using async/await but must now to use Redis-om. NN_walkd walks through a Redis database looking for loop-chains and does this by recursion. So the 2 questions I have is:

*

*Am I calling the inner recursive NN_walkd calls correctly via async/await?

*At runtime, the compSearchM proc is called first and seems to work (it gets 5 entries so it has to call NN_walkd 5 times). A NN_walkd is then recursively called, and then when it loops the 1st time it then calls compSearchK where the problems are. It seems to sit on the first Redis call in compSearchK (.search). Yet the code for compSearchK and compSearchM look basically identical.

main call
NN_walk = async function(req, db, cnode, pnode, chain, cb) {
  var vegas, sneaker;

  req.session.walk = [];
  await NN_walkd(req, cnode, pnode, [], 1);
  req.session.walk = null;
  console.log('~~~~~~~~~~~~ Out of Walk ~~~~~~~~~~~~~~~');
  cb();
};

redis.mjs
export class RedisDB {
  constructor() {
    ...
    this._companyRepo = ...
  }
  compSearchK(ckey) {   // doesn't matter if I have a async or not here
    return new Promise(async (resolve) => {
      const sckey = await this._companyRepo.search()
        .where('COMPANYKEY').equals(ckey)
        .return.all();
      if (sckey.length) {
        const ttrr = await this._companyRepo.fetch(sckey[0].entityId);
        resolve(ttrr.toJSON());
      } else
        resolve(null);
    });
  }

  compSearchM(mkey) {
    var tArr=[];
    return new Promise(async (resolve) => {
      const smkey = await this._companyRepo.search()
        .where('MASTERKEY').equals(mkey)
        .and('TBLNUM').equals(10)
        .return.all();
      if (smkey.length) {
        for (var spot in smkey) {
          const ttrr = await this._companyRepo.fetch(smkey[spot].entityId);
          tArr.push(ttrr.toJSON());
        }
        resolve(tArr);
      } else {
        resolve(null);
      }
    });
  }

walk.js
NN_walkd = async function(req, cnode, pnode, chain, lvl) {
  ...
  if (cnode[1]) {
    const sObj = await req.app.get('redis').compSearchK(cnode[1]);
    if (sObj) {
      int1 = (sObj.TBLNUM==1) ? null : sObj.CLIENTKEY;
      (async () => await NN_walkd(req, [sObj.COMPANYKEY,int1], cnode, Array.from(chain), tlvl))()
    }
  } else {
    const sArr = await req.app.get('redis').compSearchM(cnode[0]);
    if (sArr.length) {
      for (sneaker in sArr) {
        (async () => await NN_walkd(req, [sArr[sneaker].COMPANYKEY,sArr[sneaker].CLIENTKEY], cnode, Array.from(chain), tlvl))()
      }
    } else {
      console.log('no more links on this chain: ',cnode);
    }
  }
}

A: "doesn't matter if i have async or not here"
  compSearchK(ckey) {   // doesn't matter if I have a async or not here
    return new Promise(async (resolve) => {
      const sckey = await this._companyRepo.search()
        .where('COMPANYKEY').equals(ckey)
        .return.all();
      if (sckey.length) {
        const ttrr = await this._companyRepo.fetch(sckey[0].entityId);
        resolve(ttrr.toJSON());
      } else
        resolve(null);
    });
  }

Of course it doesn't matter, because you're not using await inside of compSearchK!
You are using the explicit promise contructor anti-pattern. You should avoid it as it demonstrates lack of understanding. Here is compSearchK rewritten without the anti-pattern -
  async compSearchK(ckey) {
    // await key
    const sckey =
      await this._companyRepo.search()
        .where('COMPANYKEY').equals(ckey)
        .return.all();

    // return null if key is not found
    if (sckey.length == 0) return null;

    // otherwise get ttrr
    const ttrr = await this._companyRepo.fetch(sckey[0].entityId);

    // return ttrr as json
    return ttrr.toJSON();
  }


text:
Q: Advanced search in ADO. Net Windows form application I have the below ADO.Net code written in c# to get the detail of the student from the student table when the user puts either the roll number or the student name. The problem is that, it was all fine when the search was being performed using only one column but I want to use either condition on columns. Does anybody have any idea if this thing is possible in the below code.The below code is throwing me an error saying:

incorrect syntax near OR.

comm = new SqlCommand("select * from student_detail where (roll_no = '%" + txtRollNumber.Text + "%') OR (s_name = '"+ txtStudentName.Text +"')", conn);

A: You have a % in your sql query which is a special wildcard character that is only use in LIKE clauses.
Try this:
comm = new SqlCommand("select * from student_detail
                       where (roll_no = '" + txtRollNumber.Text + "')
                       OR (s_name = '" + txtStudentName.Text + "')"
                       ,conn);

A: Just be aware, that you're not sanitising your inputs in your example. So, if someone puts a backtick in txtStudentName they can effectively run commands on your database. It's called SQL Injection.
I suggest you look into how you can use Parameterized Queries in ADO.NET (it's really very, very easy) - this will make your code (well actually your database) much safer.


text:
Q: Pause/Resume/Seek mp4 on FFMPEG while transmitting to RTMP I'm currently streaming an mp4 to an RTMP server just fine. I'm trying to figure out if I can pause the MP4 and Resume while staying connected to the RTMP server the entire time.
I'm streaming with the following command:
ffmpeg -re -i myfile.mp4 -acodec copy -vcodec copy -preset:v ultrafast -f flv rtmp://myrtmp.server

The idea is that we are showing everyone a video that is in sync for everyone on our platform. If someone has a question, I would like to be able to pause the mp4. Once the question is answered, tell FFmpeg to resume playing the mp4
I'm currently using PHP, SOCKET, and obviously FFmpeg


text:
Q: Passing Variable from Until Loop into If statement I have the following until script with an embedded if statement. The embedded if statement uses a new_variable as defined by the parameters of the until loop.
The new_variable is not passing into the command when I put the commands in the background, but the loop does work if I don't put the commands in background. How do I define a new variable in the until/if loop? Any tips would be most appreciated!
counter=1
stop=10

until [ $counter -gt $stop ]; do
    if [ ... ]

        (new_variable=$(awk 'NR=='$counter'{print $2}' file )
          command1;
          command2;
          command3) &

        let counter+=1

    fi
done


text:
Q: CloudFormation Inside VPC? I get that I can create resources using CloudFormation, and that I can also create a VPC using CloudFormation, along with the resources inside it.
Can I create a stack, using a CloudFormation template, inside a pre-existing VPC? For example, let's say that I have a VPC for my company, and there is a Services segment, some production segments (private and public), and maybe some Development segments.
I want to define each set of services - Services, production environment, Development environments - with its own CloudFormation template inside the VPC.
Can I do that?

A: Since this isn't documented very well, and all the examples I've seen (including Julio's) just use a string field prompting for manual entry of the VPC ID, here is the best way.
You can have your template prompt you with a drop-down showing all existing VPCs, allowing you to select one.
Use the AWS::EC2::VPC::Id property in your template:
{
  "Parameters" : {
    "VpcId" : {
      "Type" : "AWS::EC2::VPC::Id",
      "Description" : "VpcId of your existing Virtual Private Cloud (VPC)"
    }
  }
}

http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html

A: Yes, you can. You can either pass the subnet id as a parameter and create resources inside those subnets or pass the vpc id as a parameter and create the subnets and resources inside it.
For example, this template will create an RDS database inside an existing VPC:
https://s3.amazonaws.com/cloudformation-templates-us-east-1/RDS_VPC.template

A: Interesting I was about to point out it should be List<> but I tested both and your approach works as well.
"VpcId" : {
  "Type" : "List<AWS::EC2::VPC::Id>",
  "Description" : "VpcId Ids"
}

A: Yes you can. The stack defined in another file is for the master JSON a resource of type stack.
Of course you must tell where to retrieve the other JSON/YML file.
Cloudformation is not easy so I would suggest try with an existing architecture and modify step by step.
This example should help you.


text:
Q: Changing the default listener of JQuery dialog buttons I display a dialog, with a single button, I was surprised that there's an "on key press" listener by default on that button..
I don't mind the default focus, but I NEED to use key up instead of key press.. because otherwise it messes with other listeners that I already have in the page
This means I need to disable the default key press that comes with the dialog's button.. or replace it by the key up I defined
$("#some-dialog").dialog({
    autoOpen: false,
    modal: true,
    buttons: {
        "Okay": function() {
            $(this).dialog( "close" );
    }
    },
    close: function() {
        doStuff();
    },
    width: 480});

var ENTER_KEY = 13;
var ESCAPE_KEY = 27;

$(".ui-dialog").live("keyup", function(e) {
    if ($(this).is(':visible') && (e.which == ENTER_KEY || e.which == ESCAPE_KEY)) {
        $(this).dialog("close");
    }
});


text:
Q: QGIS - plot points on a map proportionally to column values I have a .csv file like as follow:
latitude | longitude | norm_imp
-22.13   |  -43.18   |  0.017
-22.19   | -43.29    |  0.038
-22.33   |  -43.08   |  0.117
-22.19   | -43.29    |  0.2038

I plot the latitude and longitude points on a layer, but I need these points to be proportional to those in the norm_imp column. Is it possible to do this in QGIS? If so, how?

A: Just use the "data defined override" for the size, see pictures below:

then you can use your field directly or use the asistent to make a proper size function:


text:
Q: Open browser print window without using a package ReactJS I want to print my whole page on react js without using a package. Is there any way to do this, i found Window.print() which does not seem to work.
Just want to open the browser print window. The shortcut for that is Ctrl+P on chrome so there could be a possibe way to press ctrl+p onClick of a button maybe.

 Hello World

<button onClick = {DoPrint}></button>

Edit : Code to do this would be
Should work on all browsers except for  Firefox For Android
<button className="DoTest" onClick={window.print}></button>

Thanks

A: You could declare your page with an iframe:

And then print it with something like this:
var myPrint = document.getElementById("idofyourpage").contentWindow;
myPrint.focus();
myPrint.print();

Also remember that you might need to open the document and write some content to it depending of your functionality. However, I remember having used window.print() successfully, so you would also like to make sure you used it correctly, since it's an easier and cleaner way to get your page printed in a component.


text:
Q: Можно ли как-то отображать динамически изменяющуюся раскладку на Java? Добрый день, я хочу сделать отображение активного языка раскладки клавиатуры в своём приложении, просто потому что в полноэкранном режиме не удобно её контролить каждый раз выходя из него. Если знаете хорошее решение поделитесь пожалуйста)

A: Отловить событие переключения раскладки в системе не используя нативных библиотек не получится. Однако можно получать Locale из InputContext нужного вам компонента или окна. Периодически опрашивая контекст вы можете обновлять отображения внутри вашего приложения.
Пример на swing:
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Main {
    private static void createAndShowGUI() {
        final JFrame frame = new JFrame("");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final JLabel label = new JLabel(frame.getInputContext().getLocale().toString());
        frame.getContentPane().add(label);
        Timer timer = new Timer(2000, new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            label.setText(frame.getInputContext().getLocale().toString());
            }
        });

        timer.start();
        frame.pack();
        frame.setVisible(true);
   }

   public static void main(String[] args) {
      javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowGUI();
        }
    });
  }
}


text:
Q: ERROR: Cannot find module '../node-v11-darwin-x64/node_sqlite3.node' There is a production version of Ghost blogging platform with content and style changes on our server. I downloaded the blog's app folder to my local machine. The instructions seem straight forward.

Quickstart:

*

*npm install -g grunt-cli

*npm install

*grunt init (and grunt prod if you want to run Ghost in production mode)

*npm start
But when I run grunt init I get the following:
Running "shell:bower" (shell) task

module.js:340
    throw err;
      ^
Error: Cannot find module 'q'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (/Users/steelcollar/workspace/blog/node_modules/.bin/bower:6:9)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
Warning: Command failed:
module.js:340
    throw err;
      ^
Error: Cannot find module 'q'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (/Users/steelcollar/workspace/blog/node_modules/.bin/bower:6:9)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
Use --force to continue.

Eventually, running npm start leads to:
ERROR: Cannot find module '../node_modules/sqlite3/lib/binding/node-v11-darwin-x64/node_sqlite3.node'
I have bower and grunt installed. I haven't changed the code at all. Where could the problem be?
Update:
According to the folder structure I downloaded, the path is ../node-v11-linux-x64/node_sqlite3.node' instead of ../node-v11-darwin-x64/node_sqlite3.node'.
I am receiving this error if I change the folder name from darwin to linux though:
ERROR: dlopen(../node_modules/sqlite3/lib/binding/node-v11-darwin-x64/node_sqlite3.node, 1): no suitable image found.  Did find:
../node_modules/sqlite3/lib/binding/node-v11-darwin-x64/node_sqlite3.node: unknown file type, first eight bytes: 0x7F 0x45 0x4C 0x46 0x02 0x01 0x01 0x00

A: Hi I had the same situation and this is how I solved it:
On the local computer, simply npm uninstall sqlite3 and npm install sqlite3 --save, and it should work normally now.
I'm not sure why it's like this. But I think it's because the versions of sqlite3 each OS requires are different, simply downloading the app directory from server to local computer will result in incompatibility issue, so just let npm decide which version of sqlite3 to install.

A: I got the same error. This didn't work:
yarn remove sqlite3 && yarn add sqlite3

Then I tried this, which did:
npm uninstall sqlite3 && npm install sqlite3

A: The correct answer to this would be to run npm rebuild. This will rebuild all the bindings relevant to the current project, especially after updates.


text:
Q: How to upsert in mySQL so it will work with sqlite3? I need to test a python flask app that uses mySQL to run its' queries using sqlalchemy, with sqlite3.
I've encountered an exception when trying to test an upsert function using an ON DUPLICATE clause:
(sqlite3.OperationalError) near "DUPLICATE": syntax error

After a brief search for a solution, I've found that the correct syntax for sqlite to execute upsert queries is ON CONFLICT(id) DO UPDATE SET ..., I've tried it but mySQL doesn't recognize this syntax.
What can I do? How can I do an upsert query so sqlite3 and mySQL will both execute it properly?
Example:
employees table:

id
name

1
Jeff Bezos

2
Bill Gates

INSERT INTO employees(id,name)
VALUES(1, 'Donald Trump')
ON DUPLICATE KEY UPDATE name = VALUES(name);

Should update the table to be:

id
name

1
Donald Trump

2
Bill Gates

Thanks in advance!

A:
How can I do an upsert query so sqlite3 and mySQL will both execute it properly?

You can achieve the same result by attempting an UPDATE, and if no match is found then do an INSERT. The following code uses SQLAlchemy Core constructs, which provide further protection from the subtle differences between MySQL and SQLite . For example, if your table had a column named "order" then SQLAlchemy would emit this DDL for MySQL …
CREATE TABLE employees (
    id INTEGER NOT NULL,
    name VARCHAR(50),
    `order` INTEGER,
    PRIMARY KEY (id)
)

… and this DDL for SQLite
CREATE TABLE employees (
    id INTEGER NOT NULL,
    name VARCHAR(50),
    "order" INTEGER,
    PRIMARY KEY (id)
)

import logging

import sqlalchemy as sa

# pick one
connection_url = "mysql+mysqldb://scott:tiger@localhost:3307/mydb"
# connection_url = "sqlite://"

engine = sa.create_engine(connection_url)

def _dump_table():
    with engine.begin() as conn:
        print(conn.exec_driver_sql("SELECT * FROM employees").all())

def _setup_example():
    employees = sa.Table(
        "employees",
        sa.MetaData(),
        sa.Column("id", sa.Integer, primary_key=True, autoincrement=False),
        sa.Column("name", sa.String(50)),
    )
    employees.drop(engine, checkfirst=True)
    employees.create(engine)

    # create initial example data
    with engine.begin() as conn:
        conn.execute(
            employees.insert(),
            [{"id": 1, "name": "Jeff Bezos"}, {"id": 2, "name": "Bill Gates"}],
        )

def upsert_employee(id_, name):
    employees = sa.Table("employees", sa.MetaData(), autoload_with=engine)
    with engine.begin() as conn:
        result = conn.execute(
            employees.update().where(employees.c.id == id_), {"name": name}
        )
        logging.debug(f" {result.rowcount} row(s) updated.")
        if result.rowcount == 0:
            result = conn.execute(
                employees.insert(), {"id": id_, "name": name}
            )
            logging.debug(f" {result.rowcount} row(s) inserted.")

if __name__ == "__main__":
    logging.basicConfig(level=logging.DEBUG)
    _setup_example()
    _dump_table()
    """
    [(1, 'Jeff Bezos'), (2, 'Bill Gates')]
    """
    upsert_employee(3, "Donald Trump")
    """
    DEBUG:root: 0 row(s) updated.
    DEBUG:root: 1 row(s) inserted.
    """
    _dump_table()
    """
    [(1, 'Jeff Bezos'), (2, 'Bill Gates'), (3, 'Donald Trump')]
    """
    upsert_employee(1, "Elon Musk")
    """
    DEBUG:root: 1 row(s) updated.
    """
    _dump_table()
    """
    [(1, 'Elon Musk'), (2, 'Bill Gates'), (3, 'Donald Trump')]
    """


text:
Q: How do I create a Sector in Stellaris? I'm playing Stellaris. The tutorial AI has been repeatedly (literally non stop) telling me to create sectors.
There is a Planets & Sectors menu as part of the main menu bar (it's even mapped to F4). It does not contain a "create sector" or "split into setors" or any such sort of UI element.

I've looked long and hard through the UI, and nothing solves this issue
I've tried clicking on outside the menu onto solar systems while the Planets & Sectors menu is open, and I've tried unfolding the only sector I have and clicking everywhere within that.
I get taken to different other parts of the game. This planet, that leader, my empire tab, etc. etc. etc... nothing is meant as a create sector button.
I've also dug up old screenshots in this thread:
https://steamcommunity.com/app/281990/discussions/0/357286119102514045/

In which you can see a "Create new Sector" button, but the interface has clearly changed since then.

A: As shown in this dev diary, starting in version 2.3 the option to form a sector is located in the planet window. The button has the "three hexes" sector icon and a plus sign, like so:

This will create a new sector centered on the chosen system that includes all other systems within four jumps. Your capital starts out as the center of the core sector, and any colonies you found within four systems will join that sector automatically.
Note that the option to create a sector only shows up if the selected planet is not already part of a sector. For non-core sector worlds that button disbands the sector, for core sector worlds it allows you to move your capital, and for your capital it does nothing.


text:
Q: Energy of not absorbed photon If a photon was incident towards an atom colliding with its electron without being absorbed by it because it has less or more energy from the required, then what will happen to the Photon next? Will it reserve its energy or lose some of its energy or lose it all? If so then where that energy is gone? Is it absorbed by the  electron or something else? Please explain this point and try to be simple as much as you can thank you.

A: This is a good question. The photon can scatter inelastically in a process called Rayleigh scattering. Or it can scatter elastically in a process called Compton scattering.


text:
Q: partial specialization variadic template typename as void I have a function,in a library, that is a variadic template, and is used by a other programme.
1
A.hpp
class A {
    template<typename Ret,typename ... Args>
    static Ret f(int id,Args&& ... args);
};
#include "A.tpl"

A.tpl
template<typename Ret,typename ... Args>
Ret A::f(int id,Args&& ... args)
{
    //do somthing with args and id
    Ret ret;
    /// do somthing with ret
    return ret;
}

My problem is this one:
If Ret is void, the code is not correct.
So i try to build a specialization of f:
2
A.tpl
template<typename ... Args>
void A::f<void,Args ...>(int id,Args&& ... args)
{
    //do somthing with args and id
    return;
}

template<typename Ret,typename ... Args>
Ret A::f(int id,Args&& ... args)
{
    //do somthing with args and id
    Ret ret;
    /// do somthing with ret
    return ret;
}

But this code is not correct.

so I try to split the code:
3
A.hpp
class A {
    template<typename Ret,typename ... Args>
    static Ret f(int id,Args&& ... args);

   template<typname Ret>
   static Ret f2();
}
#include "A.tpl"

A.tpl
template<typename Ret,typename ... Args>
Ret A::f(int id,Args&& ... args)
{
    //do somthing with args and id
    return f2<Ret>();
}

template<typename Ret>
Ret A::f2()
{
    Ret ret;
    /// do somthing with ret
    return ret;
}

A.cpp
template<>
void A::f2<void>()
{
     return;
}

Now the code is ok, and my lib compile fine in a .so/dll.
But when I use f(...), only f2 from "A.tpl" is find by the compiler, and not f2 in the .so/dll (from the .cpp). So the code is not valid (again), because of ret declared as void.
So, if anyone have any idea to deal with this ...

Edit
Solution:
Do the 3 solution, and add in A.tpl
template<>
void A::f2<void>();

A: You can't partial specialize a function/method...
You may use a helper class which can be partial specialized.
template<typename Ret, typename ... Args> struct helper;

template<typename ... Args>
struct helper<void, Args...>
{
    void operator() (int id, Args&& ... args) const { /* Implementation for void */ }
};

template<typename Ret, typename ... Args>
struct helper<Ret, Args...>
{
    Ret operator() (int id, Args&& ... args) const { /* Implementation for non void case */ }
};

class A {
    template<typename Ret,typename ... Args>
    static Ret f(int id, Args&& ... args)
    {
        return helper<Ret, Args...>()(id, std::forward<Args>(args)...);
    }
};

A: Partial specialization of a helper class is probably the most elegant the way to go, you can do what is in Jarod42's answer. As to why your solution didn't work. It's because you need a declaration of the specialization in your header file so that the compiler will know not to instantiate with the generic template.
template <>
void A::f2<void>();

A: I think SFINAE could fix your problem, then you could just disable the function for when the type is void and enable a separate function for when it is.
Use std::enable_if in your return type like this:
template<typename Ret, typename ... Args>
typename std::enable_if<!std::is_void<Ret>::value, Ret>::type
f(int id,Args&& ... args);

this is admittidly hard to read so you could make it less verbose like this:
template<bool Enable, class T = void>
using enable_if_t = typename std::enable_if<Enable, T>::type

template<typename Ret, typename ... Args>
enable_if_t<!std::is_void<Ret>::value, Ret> f(int id, Args&& ... args);

enable_if_t will be pre-defined if you're using C++14, btw.
You should be able to do the same for when Ret = void:
template<tpyename Ret, typename ... Args>
enable_if_t<std::is_void<Ret>::value> f(int id, Args&& ... args);

Define both in you class like this:
class A{
    public:
        template<typename Ret, typename ... Args>
        static enable_if_t<!std::is_void<Ret>::value, Ret> f(int id, Args&& ... args);

        template<typename Ret, typename ... Args>
        static enable_if_t<std::is_void<Ret>::value> f(int id, Args&& ... args);
};

Then implement them with the same return type.
You can see it in action here: http://ideone.com/Wdmn5q

A: Tag dispatching is clean and simple here
class A {
private:
  template<typename Ret,typename ... Args>
  static void f_impl(std::true_type /* Ret_is_void */, int id,Args&& ... args);
  template<typename Ret,typename ... Args>
  static Ret f_impl(std::false_type /* Ret_is_void */, int id,Args&& ... args);
public:
  // forward to one of the two _impl versions above.
  // based on if ret is void or not.  While this seems to return void_expression
  // such is valid in certain cases involving template code, including this one!
  template<typename Ret,typename ... Args>
  static Ret f(int id,Args&& ... args) {
    return f_impl<Ret>( std::is_same<Ret,void>{}, id, std::forward<Args>(args)... );
  }
};

template<typename Ret,typename ... Args>
Ret A::f_impl(std::false_type /* Ret_is_void */ int id,Args&& ... args)
{
  static_assert( !std::is_same<Ret,void>::value, "this version is only valid with Ret as non-void");
  //do somthing with args and id
  Ret ret;
  // do somthing with ret
  return ret;
}
template<typename Ret,typename ... Args>
void A::f_impl(std::true_type /* Ret_is_void */ int id,Args&& ... args)
{
  static_assert( std::is_same<Ret,void>::value, "this version is only valid with Ret as void");
  // whatever you do when Ret is non-void
}


text:
Q: How to install objax with GPU support? I have followed the objax documentation to install the library with GPU support: https://objax.readthedocs.io/en/stable/installation_setup.html
i.e.
pip install --upgrade objax
CUDA_VERSION=11.6
pip install -f https://storage.googleapis.com/jax-releases/jax_releases.html jaxlib==`python3 -c 'import jaxlib; print(jaxlib.__version__)'`+cuda`echo $CUDA_VERSION | sed s:\\\.::g`
However the last step doesn't work. I get the following error message:

ERROR: Could not find a version that satisfies the requirement jaxlib==0.3.15+cuda116 (from versions: 0.1.32, 0.1.40, 0.1.41, 0.1.42, 0.1.43, 0.1.44, 0.1.46, 0.1.50, 0.1.51, 0.1.52, 0.1.55, 0.1.56, 0.1.57, 0.1.58, 0.1.59, 0.1.60, 0.1.61, 0.1.62, 0.1.63, 0.1.64, 0.1.65, 0.1.66, 0.1.67, 0.1.68, 0.1.69, 0.1.70, 0.1.71, 0.1.72, 0.1.73, 0.1.74, 0.1.75, 0.1.76, 0.3.0, 0.3.2, 0.3.5, 0.3.7, 0.3.8, 0.3.10, 0.3.14, 0.3.15)
ERROR: No matching distribution found for jaxlib==0.3.15+cuda116

I have tried with multiple versions of python/CUDA, but I always get this error.
Executing pip install --upgrade pip at the begining does not help.
System description:

*

*Operating system: Ubuntu 20.04.4 LTS

*CUDA Version: 11.6

*Python version: 3.8.13

A: JAX recently updated its GPU installation instructions, which you can find here: https://github.com/google/jax#pip-installation-gpu-cuda
In particular, the CUDA wheels are now located at https://storage.googleapis.com/jax-releases/jax_cuda_releases.html
So, for example, you can install JAX with
$ pip install "jax[cuda11_cudnn805]" -f https://storage.googleapis.com/jax-releases/jax_cuda_releases.html

and replace cuda11 and cudnn805 respectively with the appropriate CUDA and CUDNN version for your system, ensuring that they match the versions listed in the index at the above URL.
I've sent a pull request to the objax repository to update the instructions you were following: https://github.com/google/objax/pull/246

A: The doc page was last updated 2 year ago. It's outdated and due to this it currently  lies. Take a close look at https://storage.googleapis.com/jax-releases/jax_releases.html — there're currently no releases with CUDA.
As for no-CUDA versions you can install them directly from PyPI:
pip install jaxlib

For CUDA version — try to compile from sources. Or use conda: https://anaconda.org/search?q=jaxlib


text:
Q: Receiving TPE error 1105 when attempting to transmit to irs a2a system I am receiving the TPE 1105 whenever I try to submit to the IRS through A2A. I have been over the soap examples as well as dug into the wsd's multiple times and have been unable to figure out what might be causing this issue.
If you have any insight I would be so eternally grateful to finally put the 1105 to bed.
    POST [AATS_URL] HTTP/1.1
    Content-Encoding: gzip
    Accept-Encoding: gzip,deflate
    Content-Type: multipart/related; type="application/xop+xml"; start="<root_part>"; boundary="--=_part_85c4167d-966b-4dfd-b6f9-c7a5aa410517"; start-info="text/xml"
    SOAPAction: "BulkRequestTransmitter"
    MIME-Version: 1.0
    Accept: text/xml,multipart/related
    Expect: 100-continue
    Cache-Control: no-cache
    Pragma: no-cache
    User-Agent: Java/1.8.0_111
    Host: la.www4.irs.gov
    Connection: keep-alive
    Content-Length: 16299

    ----=_part_85c4167d-966b-4dfd-b6f9-c7a5aa410517
    Content-Type: application/xop+xml; charset=UTF-8; type="text/xml"
    Content-Transfer-Encoding: 8bit
    Content-Id: <root_part>

    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <soapenv:Envelope xmlns:air="urn:us:gov:treasury:irs:ext:aca:air:ty18" xmlns:com="urn:us:gov:treasury:irs:common" xmlns:hdr="urn:us:gov:treasury:irs:msg:acabusinessheader" xmlns:oas1="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:req="urn:us:gov:treasury:irs:msg:irsacabulkrequesttransmitter" xmlns:sec="urn:us:gov:treasury:irs:msg:acasecurityheader" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
        <soapenv:Header xmlns:wsa="http://www.w3.org/2005/08/addressing">
            <wse:Security xmlns:wse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" Id="SH-3f88e9e4-c4ea-4473-ad04-0b567e2a4bf7">
                <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#" Id="SIG-3f88e9e4-c4ea-4473-ad04-0b567e2a4bf7">
                    <ds:SignedInfo>
                        <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#WithComments"/>
                        <ds:SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"/>
                        <ds:Reference URI="#TS-3f88e9e4-c4ea-4473-ad04-0b567e2a4bf7">
                            <ds:Transforms>
                                <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#WithComments">
                                    <ds:InclusiveNamespaces xmlns:ds="http://www.w3.org/2001/10/xml-exc-c14n#" PrefixList="wse wsa osa1 soapenv air com hdr sec req"/>
                                </ds:Transform>
                            </ds:Transforms>
                        <ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/>
                        <ds:DigestValue>FqYS/pHdN05mKKccxqM4jmEwJNRR+ikRPB7HuyvbGQY=</ds:DigestValue>
                        </ds:Reference>
                        <ds:Reference URI="#MH-3f88e9e4-c4ea-4473-ad04-0b567e2a4bf7">
                            <ds:Transforms>
                                <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#">
                                    <ds:InclusiveNamespaces xmlns:ds="http://www.w3.org/2001/10/xml-exc-c14n#" PrefixList="wse wsa osa1 soapenv com hdr sec req"/>
                                </ds:Transform>
                            </ds:Transforms>
                        <ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/>
                        <ds:DigestValue>qlWuAbD2PwDmvK7/KzU56ZWsKhBH2PYW/v2eW/30/4E=</ds:DigestValue>
                        </ds:Reference>
                        <ds:Reference URI="#BH-3f88e9e4-c4ea-4473-ad04-0b567e2a4bf7">
                            <ds:Transforms>
                                <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#">
                                    <ds:InclusiveNamespaces xmlns:ds="http://www.w3.org/2001/10/xml-exc-c14n#" PrefixList="wse wsa osa1 soapenv air com sec req"/>
                                </ds:Transform>
                            </ds:Transforms>
                            <ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/>
                            <ds:DigestValue>E2cw4uavSk8RGQeewG04q3tcBRwM6dnMQmSctdJl4k8=</ds:DigestValue>
                        </ds:Reference>
                    </ds:SignedInfo>
                    <ds:SignatureValue>[SIGNATURE_VALUE]</ds:SignatureValue>
                    <ds:KeyInfo Id="KI-3f88e9e4-c4ea-4473-ad04-0b567e2a4bf7">
                        <wse:SecurityTokenReference wsu:Id="STR-3f88e9e4-c4ea-4473-ad04-0b567e2a4bf7">
                            <wse:KeyIdentifier EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary" ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3">[CERT_VALUE]</wse:KeyIdentifier>
                        </wse:SecurityTokenReference>
                    </ds:KeyInfo>
                </ds:Signature>
                <wsu:Timestamp wsu:Id="TS-3f88e9e4-c4ea-4473-ad04-0b567e2a4bf7">
                    <wsu:Created>2019-02-15T15:41:01Z</wsu:Created>
                    <wsu:Expires>2019-02-15T15:51:01Z</wsu:Expires>
                </wsu:Timestamp>
            </wse:Security>
            <air:ACATransmitterManifestReqDtl xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="MH-3f88e9e4-c4ea-4473-ad04-0b567e2a4bf7">
                <air:PaymentYr>2018</air:PaymentYr>
                <air:PriorYearDataInd>0</air:PriorYearDataInd>
                <com:EIN>[REDACTED]</com:EIN>
                <air:TransmissionTypeCd>O</air:TransmissionTypeCd>
                <air:TestFileCd>T</air:TestFileCd>
                <air:TransmitterForeignEntityInd>0</air:TransmitterForeignEntityInd>
                <air:TransmitterNameGrp>
                    <air:BusinessNameLine1Txt>[REDACTED]</air:BusinessNameLine1Txt>
                </air:TransmitterNameGrp>
                <air:CompanyInformationGrp>
                    <air:CompanyNm>[REDACTED]</air:CompanyNm>
                    <air:MailingAddressGrp>
                        <air:USAddressGrp>
                            <air:AddressLine1Txt>[REDACTED]</air:AddressLine1Txt>
                            <com:CityNm>[REDACTED]</com:CityNm>
                            <air:USStateCd>[REDACTED]</air:USStateCd>
                            <com:USZIPCd>[REDACTED]</com:USZIPCd>
                        </air:USAddressGrp>
                    </air:MailingAddressGrp>
                    <air:ContactNameGrp>
                        <air:PersonFirstNm>[REDACTED]</air:PersonFirstNm>
                        <air:PersonMiddleNm>[REDACTED]</air:PersonMiddleNm>
                        <air:PersonLastNm>[REDACTED]</air:PersonLastNm>
                    </air:ContactNameGrp>
                    <air:ContactPhoneNum>[REDACTED]</air:ContactPhoneNum>
                </air:CompanyInformationGrp>
                <air:VendorInformationGrp>
                    <air:VendorCd>I</air:VendorCd>
                    <air:ContactNameGrp>
                        <air:PersonFirstNm>[REDACTED]</air:PersonFirstNm>
                        <air:PersonMiddleNm>[REDACTED]</air:PersonMiddleNm>
                        <air:PersonLastNm>[REDACTED]</air:PersonLastNm>
                    </air:ContactNameGrp>
                    <air:ContactPhoneNum>[REDACTED]</air:ContactPhoneNum>
                </air:VendorInformationGrp>
                <air:TotalPayeeRecordCnt>2</air:TotalPayeeRecordCnt>
                <air:TotalPayerRecordCnt>1</air:TotalPayerRecordCnt>
                <air:SoftwareId>[REDACTED]</air:SoftwareId>
                <air:FormTypeCd>1094/1095B</air:FormTypeCd>
                <com:BinaryFormatCd>application/xml</com:BinaryFormatCd>
                <com:ChecksumAugmentationNum>25fbebd1143d8aa935a445db998eb374761113af8b17d67b3a95af9ad73e17bc</com:ChecksumAugmentationNum>
                <com:AttachmentByteSizeNum>7245</com:AttachmentByteSizeNum>
                <air:DocumentSystemFileNm>1094B_Request_[TCC]_20190215T154101026Z.xml</air:DocumentSystemFileNm>
            </air:ACATransmitterManifestReqDtl>
            <hdr:ACABusinessHeader xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="BH-3f88e9e4-c4ea-4473-ad04-0b567e2a4bf7">
            <air:UniqueTransmissionId>3f88e9e4-c4ea-4473-ad04-0b567e2a4bf7:SYS12:[TCC]::T</air:UniqueTransmissionId>
            <com:Timestamp>2019-02-15T15:41:01Z</com:Timestamp>
            </hdr:ACABusinessHeader>
            <sec:ACASecurityHeader>
            <hdr:UserId>[REDACTED]</hdr:UserId>
            </sec:ACASecurityHeader>
            <wsa:Action>BulkRequestTransmitterService</wsa:Action>
        </soapenv:Header>
        <soapenv:Body>
            <req:ACABulkRequestTransmitter version="1.0">
                <com:BulkExchangeFile>
                    <xop:Include xmlns:xop="http://www.w3.org/2004/08/xop/include" href="cid:1094B_Request_[TCC]_20190215T154101026Z.xml"/>
                </com:BulkExchangeFile>
            </req:ACABulkRequestTransmitter>
        </soapenv:Body>
    </soapenv:Envelope>

    ----=_part_85c4167d-966b-4dfd-b6f9-c7a5aa410517
    Content-Type: application/xml
    Content-Transfer-Encoding: 7bit
    Content-Id: <1094B_Request_[TCC]_20190215T154101026Z.xml>
    Content-Disposition: attachment; filename="1094B_Request_[TCC]_20190215T154101026Z.xml"

    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <msg:Form109495BTransmittalUpstream xmlns:air="urn:us:gov:treasury:irs:ext:aca:air:ty18" xmlns:com="urn:us:gov:treasury:irs:common" xmlns:msg="urn:us:gov:treasury:irs:msg:form1094-1095Btransmitterupstreammessage" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:us:gov:treasury:irs:msg:form1094-1095Btransmitterupstreammessage ../MSG/IRS-Form1094-1095BTransmitterUpstreamMessage.xsd">
    [REMOVED TO SAVE SPACE]
    </msg:Form109495BTransmittalUpstream>

    ----=_part_85c4167d-966b-4dfd-b6f9-c7a5aa410517--

We are generating these soap envelopes manually using the core org.w3c.dom Document library in Java in conjunction with the java xml dsig library for signing and validating.
EDIT-- I've managed to pass the 1105 and am now hitting the 1122 'WS Security Header Error'. I've read over the docs many times, tried to verify everything I can, but am still hitting it. There are a few unknowns for me-

*

*What exactly is expected inside the KeyIdentifier element? I've tried the base64 encoded bytes of the cert, and the public key but the docs from oasis for the x509v3 token aren't exactly very descriptive or maybe I've just misread them.

*Is there a way to verify my references are correct? I see them, so that would mean they are being created correctly, no?

*If you happen to see anything out of the ordinary with the security header, please please let me know. This Transmission code is identical currently to what is passing the 1105 and failing the 1122, minus formatting.

I'm using the java dsig library to create my Signature elements in the below code.

A: The first thing that sticks out to me is the namespace for UserId is different than what I currently am using. It looks like you are using the namespace for acabusinessheader when it should be the common namespace, changing it to what I've changed below will at least have that tag using the right namespace.
<sec:ACASecurityHeader>
   <com:UserId>[REDACTED]</com:UserId>
</sec:ACASecurityHeader>

A: Ok, so this is a bit of a lack of understanding of the technology on my part and the vagueness of the IRS docs as well. The issue with my failed transmission receiving the TPE 1105 was caused because I was 'indenting' my xml with my transformer in Java when writing our data to the connection. This caused the soap message to become unrecognizable as a MIME type message. Hope this can help someone.
EDIT-- So my second problem, encountering the 1122, was caused by the org.w3.dom Document being a level 1 document vs. a level 2 in Java. This in conjunction with the java dsig library was not properly signing ( I believe ) the xml. Once I upgraded the code to use a level 2 document, everything is working fine. Hopefully someone will find this useful as it would have saved me loads of time.


text:
Q: Mule ESB - How to use WS Consumer Response as input for WS Consumer 2 - Error coercing number to string I am struggling to use the output from WS Consumer A as input for WS Consumer B using a transformer component.
The error I am getting is "Cannot coerce null to string".
The IDNumber from WS Consumer A output is of type number which I am trying to convert to a string as input of WS Consumer B
    %dw 1.0
%output application/xml
%namespace ns0 http://www.iLov2kodez.com/fakeNamespace0
%namespace ns1 http://www.iLov2kodez.com/fakeNamespace1
%namespace ns2 http://www.iLov2kodez.com/fakeNamespace2

---
{
    ns0#SearchCustomerDetails: {
        ns0#IDnumber: payload.ns0#Response.ns0#Result.ns1#IDnumber as :string
    }
}

Error:
Cannot coerce a :null to a :string
Type                  : com.mulesoft.weave.mule.exception.WeaveExecutionException
Code                  : MULE_ERROR--2

A: are you sure your getting response from WSConsumer1. You can try thing using mule break point or using logger. Try to post your piece of xml code to better understand the issue.


text:
Q: Get first day of yyyyMM format I wish to get the first and the last day of the month with
select CONVERT(varchar,dateadd(d,-1,dateadd(m,1,cast(cast('201812' as varchar(6))+'01' as date))),112)

Actually I can get the last day of month but I don't know how can I get the first day of month.

A: If you are starting with '201801asyyyymm`, then use:
select convert(date, yyyymm + '01') as first_day_of_month,
       eomonth(convert(date, yyyymm + '01')) as last_day_of_month


text:
Q: Is it possible to move .mx file from one server to other? I have mathematica file in one server along with .mx file. Is there any way to move the .mx file from one server to other such that the values can be regained in other server?
Is an .mx file exported on one computer readable on other computers?

A: Starting with Mathematica 10, .mx files are only restricted by 'bitness', i.e. an .mx file generated on a 64 bit machine should be interchangeable between all 64 bit platforms (Windows-x86-64, OSX-x86-64, Linux-x86-64). Similarly, MX files generated on 32 bit platforms should be compatible with Windows-x86 and Linux-x86.


text:
Q: If $\triangle ABC \cong \triangle XYZ$, is it "illegal" to say $\overline{AB}\cong\overline{YX}$ (instead of $\overline{XY}$)? Question about corresponding sides of congruent triangles.
I know that if triangle $ABC$ is congruent to triangle $XYZ$ that side $AB$ is congruent to side $XY$; side $BC$ is congruent to side $YZ$; etc.  But is it "illegal" to say $AB$ is congruent to $YX$?  If so, why?  Isn't that statement still true?


text:
Q: Clicking on the options of an active filter does not work I am trying to create a filter like the one here.
I have written some code in an HTML file and the aspect is identical, but the JavaScript does not work, meaning that if I click on a different option that the one active by default then nothing happens.

$(document).ready(function() {

  $("#filter-bar li").click(function() {
    $("#filter-bar li").removeClass("active");
    $(this).addClass("active");
    $("#filter-bar").removeClass().addClass($(this).attr("data-target"));
  });

})
body {
  background-color: #eee;
  margin: 0;
  padding: 0;
  font-family: Tahoma;
}

h2 {
  text-align: center;
}

#filter-bar {
  width: 100%;
  margin: 0;
  padding: 0;
  height: 36px;
  display: inline-flex;
}

#wrapper-filter {
  background-color: #fff;
  width: 570px;
  height: auto;
  margin: 30px auto;
  border-radius: 30px;
  box-sizing: border-box;
}

#filter-bar li {
  width: 190px;
  background-color: transparent;
  text-align: center;
  list-style-type: none;
  z-index: 10;
  cursor: pointer;
  font-family: Open Sans, sans-serif;
  font-weight: 100;
  font-size: 15px;
  line-height: 36px;
}

.pill {
  position: absolute;
  width: 190px;
  height: 38px;
  background-color: #39c;
  border-radius: 30px;
  color: #444;
  z-index: 10;
  border: 5px solid #eee;
  box-sizing: border-box;
}

.filter-option {
  transition: color 500ms;
}

#filter-bar.option-1 .pill {
  margin-left: 0px;
  transition: margin-left 200ms ease;
}

#filter-bar.option-2 .pill {
  margin-left: 187px;
  transition: margin-left 200ms ease;
}

#filter-bar.option-3 .pill {
  margin-left: 380px;
  transition: margin-left 200ms ease;
}

.option-1.active,
.option-2.active,
.option-3.active {
  color: #fff;
  transition: color 200ms;
}

Animated filter selector

Books

Shoes

Toys

So, what I think is that the Javascript script is not visible at all, so what it should do, does not happen at all.
Did I place it wrongly? I am a front-end beginner, so I am not sure what is wrong.
Can anyone help me?

A: Your code works fine, you just missed adding jQuery, add this to the head section in your html file
This will add the jQuery library to your project, jQuery will add a bunch of new features. Take a look at the docs here

$(document).ready(function() {
  $("#filter-bar li").click(function() {
    $("#filter-bar li").removeClass("active");
    $(this).addClass("active");
    $("#filter-bar").removeClass().addClass($(this).attr("data-target"));
  });
})
body {
  background-color: #eee;
  margin: 0;
  padding: 0;
  font-family: Tahoma;
}

h2 {
  text-align: center;
}

#filter-bar {
  width: 100%;
  margin: 0;
  padding: 0;
  height: 36px;
  display: inline-flex;
}

#wrapper-filter {
  background-color: #fff;
  width: 570px;
  height: auto;
  margin: 30px auto;
  border-radius: 30px;
  box-sizing: border-box;
}

#filter-bar li {
  width: 190px;
  background-color: transparent;
  text-align: center;
  list-style-type: none;
  z-index: 10;
  cursor: pointer;
  font-family: Open Sans, sans-serif;
  font-weight: 100;
  font-size: 15px;
  line-height: 36px;
}

.pill {
  position: absolute;
  width: 190px;
  height: 38px;
  background-color: #39c;
  border-radius: 30px;
  color: #444;
  z-index: 10;
  border: 5px solid #eee;
  box-sizing: border-box;
}

.filter-option {
  transition: color 500ms;
}

#filter-bar.option-1 .pill {
  margin-left: 0px;
  transition: margin-left 200ms ease;
}

#filter-bar.option-2 .pill {
  margin-left: 187px;
  transition: margin-left 200ms ease;
}

#filter-bar.option-3 .pill {
  margin-left: 380px;
  transition: margin-left 200ms ease;
}

.option-1.active,
.option-2.active,
.option-3.active {
  color: #fff;
  transition: color 200ms;
}

Animated filter selector

Books

Shoes

Toys


text:
Q: Unable to change text box value in React JS Hi I am working on React JS application. I have assigned default value to textbox on page load. User should be allowed to change this but user is not able to edit the value in textbox. Below is my code.
    const EditStyleFormComponent = ({
submitting,
invalid,
}) => (
  <form className={className} onSubmit={handleSubmit}>

LSPL (Low Stock Presentation Level)

    <Line />
    <InputGroup>
      <TextField value="Current" label="LSPL Manual" isEditable="true" />
    </InputGroup>
 </form>
);

Below is my TextField.js
const TextField = ({
  className,
  label,
  description,
  state,
  errorMessage,
  isEditable,
  spaceAtBottom, // Not used, but we don't want it in otherProps
  ...otherProps
}) => {
  const inputId = _.uniqueId();
  return (

      {label &&
        {label}
      }

        <input
          id={inputId}
          readOnly={!isEditable}
          {...otherProps}
        />
        {getStatusIcon(state)}
        {errorMessage &&
          <Error>{errorMessage}</Error>
        }
        {description &&
          <Description>{description}</Description>
        }

  );
};

Can someone help me to fix this issue? Any help would be appreciated. Thanks

A: Using Uncontrolled input, you may use defaultValue
const TextField = ({
  className,
  label,
  description,
  state,
  errorMessage,
  isEditable,
  spaceAtBottom, // Not used, but we don't want it in otherProps
  ...otherProps
}) => {
  const inputId = 1;
  return (

      {label &&
        {label}
      }

        <input
          id={inputId}
          readOnly={!isEditable}
          {...otherProps}
        />
        {errorMessage &&
          <Error>{errorMessage}</Error>
        }
        {description &&
          <Description>{description}</Description>
        }

  );
};

const EditStyleFormComponent = ({
submitting,
invalid,
}) => (
  <form>

LSPL (Low Stock Presentation Level)

      <TextField defaultValue="Current" label="LSPL Manual" isEditable="true" />
 </form>
);

class Hello extends React.Component {
  render() {
    return
<EditStyleFormComponent/>
;
  }
}

ReactDOM.render(
  <Hello name="World" />,
  document.getElementById('container')
);

See the fiddle here https://jsfiddle.net/0f6n85ym/
Alternatively you can also do it in controlled input.
const TextField = ({
  className,
  label,
  description,
  state,
  errorMessage,
  isEditable,
  spaceAtBottom, // Not used, but we don't want it in otherProps
  ...otherProps
}) => {
  const inputId = 1;
  return (

      {label &&
        {label}
      }

        <input
          id={inputId}
          readOnly={!isEditable}
          {...otherProps}
        />
        {errorMessage &&
          <Error>{errorMessage}</Error>
        }
        {description &&
          <Description>{description}</Description>
        }

  );
};

const EditStyleFormComponent = ({
submitting,
invalid,
value,
onChange
}) => (
  <form>

LSPL (Low Stock Presentation Level)

      <TextField value={value} onChange={onChange} label="LSPL Manual" isEditable="true" />
 </form>
);

class Hello extends React.Component {
constructor(props){
super(props);
   this.state = {
      name: 'Current'
   }
}

onChange = (e)=>{
this.setState({name: e.target.value});
}
  render() {
    return
<EditStyleFormComponent value={this.state.name} onChange={this.onChange}/>
;
  }
}

ReactDOM.render(
  <Hello name="World" />,
  document.getElementById('container')
);

See the fiddle here
https://jsfiddle.net/bshumpy0/

A: You can use logical OR operator to set defaultValue if value is not provided(if you use controlled input)
Like that:
class App extends Component {
  constructor() {
    super();
    this.state = {
      value: ''
    };
     this.handleChange = this.handleChange.bind(this)
  }

  handleChange(event) {
    this.setState({value: event.target.value});
  }

  render() {
    return (

        <TextField value={this.state.value} defaultValue='213' onChange={this.handleChange} />

    );
  }
}

And in TextField component:
<input type='text' value={value || defaultValue} onChange={onChange}/ >

Full example - https://stackblitz.com/edit/react-4daxck


text:
Q: Can I get columns of last inserted row? Hi I'm using Codeigniter and would love a solution in CI but can suffice with mysqli or PDO.
I was wondering if there is a way to get a column of the last inserted row in MySql 5.1.54
The reason is I'm inserting a null value which then a trigger changes that null into some calculated value and instead of getting the last inserted id and querying for that value.
Is there some way this can be done?
In case I wasn't clear : I know I can run a query on last inserted id, I mean can I get last inserted "column"?

A: You can get the last inserted id by
$this->db->insert_id();

and select the last row and use it normally
ref Query Helper

A: The PDO comes with lastInsertId method. You can then SELECT * FROM table WHERE id=return_of_this_function.

A: I Guess the answer @Eric is looking for is NO.


text:
Q: What is preventing my computer from going idle? When I first boot my Windows 7 computer, it will go idle if I stop using it - first the screensaver comes on, then the computer goes to sleep after a certain amount of time. This is the expected behavior.
However, after I've used the computer for awhile without rebooting (after about a day or so), I've noticed that it stops going idle - the screensaver won't come on, and the computer won't sleep, no matter how long it sits unused.
I've confirmed that the idle timer is increasing as expected via GetLastInputInfo. However, it looks like something is interfering with the results from CallNtPowerInformation. Every 14 or 16 seconds, the TimeRemaining value jumps back up to its maximum value when I query SystemPowerInformation.
I've used the SysInternals Process Monitor to detect any unusual events that might be happening to trigger this reset, but come up empty. Does anyone know exactly what are the possible causes of TimeRemaining resetting to its maximum value?
I'm fairly sure that it's not my mouse, keyboard, or network sending spurious events, because I've disabled each one and the problem continues to occur. This would also reset the GetLastInputInfo timer, which is not happening. I'm looking for something that affects SystemPowerInformation TimeRemaining, but does not affect GetLastInputInfo.
Thanks.

A: It's been some time since I last used this, but I do remember having similar issues fixed by using MCE Standby Tool on Windows 7, even though it does not officially support that version of Windows.


text:
Q: Relating classes to this program to help better understand how to program with classes I am new to python trying to get a handle on classes and OOP. I just can't seem to think of when I would use a class in a program, so I just decided to try and organize this code with classes before preforming some unit test practice on it. Not sure if adding classes to this would be useful at all but I think it would organize it at the least. Can someone help related Class and objects to this code pls.
def Max_Month(max):
    maxind = rainfalllist.index(max)
    maxmonth = months.pop(maxind)
    return maxmonth

def Min_Month(min):
    minind = rainfalllist.index(min)
    minmonth = months.pop(minind)
    return minmonth

def Rain_Fall_Math(rainfalllist):
    ave_rain = sum(rainfalllist) / len(rainfalllist)
    high_rain = max(rainfalllist)
    min_rain = min(rainfalllist)
    print(f"Total Rainfall:{rainfalllist}")
    print(f"The average monthly precipitation:{ave_rain}")
    print(f"The highest monthly precipitation: {high_rain}")
    print(f"The lowest monthly precipitation: {min_rain}")
    print(f"The month(s) with the highest precipitation:",Max_Month(high_rain))
    print(f"The month(s) with the lowest precipitation:",Min_Month(min_rain))

months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
rainfalllist = list()
for month in months:
    _ = float(input(f"What was the precipitation in {month}?"))
    rainfalllist.append(_)
Rain_Fall_Math(rainfalllist)

A: For what your code is trying to do I don't think OOP is the way to go. If you want examples of when to use classes and objects then a good tip is to use them if you want to make your own data structure (similar to struct in c and c++) or abstractify something.
Another thing to keep in mind is that just because you could use OOP doesn't mean its the only way to accomplish something.
You should also look at the 4 pillars of OOP, abstraction, inheritance, polymorphism, and encapsulation.
Say you wanted to represent a lot of people with their own attributes and apply functions to them.
You could do this OOP like this
class Human:
    humans = [] # array of all humans

    def __init__(self, name, age, hairclr, eyeclr, favfood, house, height):
        self.name = name
        self.age = age
        self.hairclr = hairclr
        self.eyeclr = eyeclr
        self.favfood = favfood
        self.house = house
        self.height = height

        Human.humans.append(self)

    def growOld(self, years):
        self.age += years
        self.height += years * .04

    def moveHouses(self, newhouse):
        self.house = newhouse

    def foo(self, a,b,c):
        pass

    def interact(self, anotherhuman):
        if self.name == anotherhuman:
            greet()
            talk()
            saygoodbye()
        if self.age < another.human.age:
            stuff()

    def __add__(self, anotherhuman):
        # DUNDER METHODS ARE SUPER COOL LOOK INTO THEM
        #they essentially act as if
        # h1 and h2 were human objects, this method is called if you try to do something like
        # h1 + h2

        self.height += anotherhuman.height

I don't think a single example could cover all possibilities of OOP and I think there are better ones where OOP is the way to go, but I think you can see kind of what OOP could be used for.
Another example from one of my projects goes along the lines of this which uses inheritance and polymorphism
from math import sqrt
class UIComponent:
    def __init__(self, x, y, state):
        self.x = x
        self.y = y
        self.state = state

    def getDist(self, x2, y2):
        return sqrt((x2 - self.x)**2 + (y2 - self.y)**2)

    def setGlobalCoords(self, c1, c2):
        self.c1 = c1
        self.c2 = c2
        update()

    def update():
        #stuff
        pass

class TextUiComponent(UIComponent):
    def __init__(self, x,y, state, text):
        super(self, TextUiComponent).__init__(x,y,state)
        self.text = text

    def updateText(self, newtext, newfont):
        self.text = newtext
        self.font = newfont

        self.update() #from earlier

class ImgUIComponent(UIComponent):
    def __init__(self, x,y, state, img):
        super(self, TextUiComponent).__init__(x,y,state)
        self.img = img

    def transfromImg(self, scale):
        transform(self.img, scale) # or self.img.transfrom(scale) this is all psuedocode
        #other stuff
        setGlobalCoords(scale, 1+scale)

If you want to create complex data structures with their own operations or abstract something along with many other cases then consider this paradigm.
There's a lot more to talk about in OOP which I couldn't possibly give a full rundown but this is the gist and I suggest you research more if you're confused, but OOP is a powerful tool.


text:
Q: Non-left recursive grammar for math equations I need some help with CS task.
I have to make a grammar (for LL() top-down parser) that will take math equation with all operators (+-/*^ and relation) without using left recursion and "erese production" (by this, I think he means epsilon). After hours of trying to find some help searching the web I cant come up with any solution to this problem.
Can you help me?


text:
Q: primes dividing binomial coefficients Dear All,
I am considering maximal subgroups of odd index in Alternating and Symmetric groups, and this leeds me to some questions on binomial coefficients that I presently do not know and that I need some hints and suggestions :

*

*Assume that $ab=2^t$ with $a>1, b>1,t\geq 3$. Which values of $a$ and $b$ such that
$$\frac{(2^t)!}{(a!)^b.b!}$$
is odd and smallest.

*Let $n\geq 9$ be an odd integer (not prime) and $p$ the largest prime less than $n$. Is there always an integer $r\geq 1$ such that $\binom{n}{r}$ is odd and divisible by $p$. Note that this is not true for the case $n=9$. Is it also true for $n$ even?
Thanks you very much in advance for comments and advice.

A: Hi! I have a proposed answer for 2).
You can construct an infinite series of counter examples. Erdos proved that there are primes between $n$ and $2n$. Now consider $2n=2^k$ for some $k>2$.
We can observe that the binomial number $\binom{2n+1}{r}, 1< r < n+1$ is always even.
The upper product have powers of 2 as the following sequence: $\lbrace k,1,2,1,3,\dots,s \rbrace$
while the bottom product have powers of 2 of the form: $\lbrace 1,2,1,3,\dots,s,k-1\rbrace$.
This can be reflected for cases $\binom {2n+1}{r}, n < r < 2n$.
The difference of the sum of these 2 sequences is at least 1.
As a result, the binomial number may be divisible by $p$ but it will not be even.
(Edit) Exception: When the binomial number is $\binom{2n+1}{1}$ or $\binom{2n+1}{2n}$ you have either no powers of 2 or same powers of 2. But in this case it will not be divisible by $p$.

A: About the question (1), I quoted here the result from this paper of Attila Maróti
First, We may assume that $a\geq b$ since if $b>a$ then
$$b!^{a-1}=a!^{a-1}(a+1)^{a-1}\cdots b^{a-1}>a!^{a-1}a^{(b-a)(a-1)}$$
In addition, we have that $a^{a-1}>1.2.\cdots.a=a!$ and so
$$b!^{a-1}>a!^{a-1}a!^{b-a}=a!^{b-1}$$
which implies that
$$b!^a.a!>a!^b.b!\Rightarrow \frac{m!}{a!^b.b!} > \frac{m!}{b!^a.a!}$$
Assume now that $m=a_1b_1=a_2b_2$ with $b_1\leq a_1, b_2\leq a_2$. If $b_1\leq b_2$ and $a_1\geq a_2$ then
$$a_1!^{b_1}.b_1! \geq  a_2!^{b_1}(a_2+1)^{b_1}\cdots a_1^{b_1}b_1! \geq  a_2!^{b_1}a_2^{(a_1-a_2)b_1}b_1! \quad (\rm{since  ~ a_1\geq a_2})$$
$$ =   a_2!^{b_1}b_1! (a_2^{a_2})^{\frac{b_1}{a_2}(a_1-a_2)} =  a_2!^{b_1}b_1! (a_2^{a_2-1}a_2)^{\frac{b_1}{a_2}(a_1-a_2)} $$
$$\geq   a_2!^{b_1}b_1! (a_2!b_2)^{\frac{b_1}{a_2}(a_1-a_2)} =  a_2!^{b_1}b_1! (a_2!b_2)^{b_2-b_1} \quad  (\rm{since ~ a_2\geq b_2 ~ and ~ a_1b_1=a_2b_2})$$
$$ \geq   a_2!^{b_2}b_1!(b_1+1)\cdots b_2 = a_2!^{b_2}b_2! \quad (\rm{since ~ b_2\geq b_1})$$
and hence
$$\frac{m!}{a_1!^{b_1}.b_1!}\leq \frac{m!}{a_2!^{b_2}.b_2!}$$

A: Your first problem has a simple solution.
Suppose $p$ is a prime and $(n!)_p$ is the $p$-part of $n!$. Dirichlet proved $(n!)_p=p^k$ where $k = (n-s_p(n))/(p-1)$ and $s_p(n)$ is the sum of the base-$p$ digits of $n$. Let $a=2^\alpha$ and $b=2^\beta$. Then $(a!)_2 = 2^{a-1}$, $(b!)_2 = 2^{b-1}$ and $((ab)!)_2 = 2^{ab-1}$. The index of the imprimitive group $S_a\wr S_b$ in $S_{ab}$ is $(ab)!/((a!)^b\,b!)$ and this odd for all $\alpha,\beta\geqslant0$.
Proof: $((a!)^b\,b!)_2 = (2^{a-1})^b\,2^{b-1}=2^{ab-1}=((ab)!)_2$. Thus a Sylow 2-subgroup of $S_a\wr S_b$ has order $2^{ab-1}$ as does a Sylow 2-subgroup of $S_{ab}$, and so $(ab)!/((a!)^b\,b!)$ is odd. QED


text:
Q: Generate a grid in Swift using Sprite Kit I have an app idea so mocked it up in C# because that's my most fluent language. I now want to port this over to Swift if possible, how hard will it be to generate a grid of 6x6 blocks, each block needs to be separate from each other as I need to change they're properties and detect touches on them. This is the grid I've currently got running on Windows.
Thanks for any help.

A: There are a lot of different ways to approach this problem, so you need to provide more details. You could do it with a single custom UIView, drawing the current representation of your model in the drawRect method and it would also be able to handle all of the touch events since you can just calculate where the user did the touch in the same way that you calculated drawing the grid and coloring the squares.
But if you want to use SpriteKit, then this tutorial will show you all the details of doing a 2D array, using sprites, tiles, etc.
http://www.raywenderlich.com/75270/make-game-like-candy-crush-with-swift-tutorial-part-1


text:
Q: MS Robotics Studio: "contract is different from that of the namespace" I'm trying to build a DSS service using MS Robotics Studio and VS 2008, but when I build, I get an error from dssproxy.exe saying:
    The class MyServiceName has a ContractAttribute but the contract is different from that of the namespace.

and the build fails because dssproxy returns code 10.  Does anyone know what this message means?
The Contract identifier is declared in the Types class file and used in the attribute declaration just the way the Add New Project > Dss Service wizard builds them.  My understanding is that the identifier is just a unique string.  Is this trying to tell me it must match my namespace somehow?
If I build again, the error goes away, but if I force a rebuild or clean before building, it comes back.
Thanks,
  Andy

A: I figured it out myself:  If the contract identifier contains capital letters, this error will occur, even in it matches the manifest exactly.  Both the identifier in the types and the manifest must be all lowercase.  Unfortunately, the Add New Project dialog doesn't prevent you from entering mixed-case for this. :(


text:
Q: Loading OpenStreetMap data in QGIS? In QGIS 1.8 I used the openstreetmap plugin to request data from the server, or open a .osm XML file, which produced 3 layers (polygons, polylines and points) in QGIS.
This was great (give or take the 64bit bug which highly affects the freshly mapped area I work on), but how do I do that in QGIS 2.x?
I can't find any updated documentation about it.
In the vector menu, I've tried importing from osm servers, I get a .osm file, but then I'm stuck. There's a menu option for loading an XML file, but it produces a spatialite db, which apparently only has non-geometry tables when I try to add it as a spatialite layer.
If I open the attribute table, I can see node ids, ways and so on, but I can't figure out how to actually make use of them.
I've also tried adding a vector layer from a .osm XML file. I get a gpsbabel window that shows nothing, then finally an invalid data source message in QGIS.

A: If you don't like the plugin, fetch the OSM data you need with Overpass API, and add the result to QGIS with Add Vector Layer (enabeling All files filter).
QGIS 2.0 uses GDAL 1.10's ogr2ogr OSM importer which does a good job.
Relation support seems to be better than the plugin does at the moment.
Just make sure you download ways and relations completely, that is all nodes of the ways, and all members of the relations, with all their nodes.

A: You know, you don't need to put the data into SpatialLite. You can just:

*

*Download the data (Vector > OpenStreetMap > Download Data, creates an .osm file)

*Load the data (.osm file) as a vector layer (Layer > Add Vector Layer). After you select the file, it'll ask you which layers you want to add (as GDAL makes separate files for each type: Point, Line, MultiLine, MultiPolygon, GeomCollection). Select what you want and load it up.

A: Update for QGIS 3.x: The old OSM importer from QGIS 2 was dropped in QGIS 3 due to lots of unresolved bugs. The QuickOSM plugin also enables to read osm raw files. You can use user Layer - Add Layer - Add Vector Layer instead. In that case, OSM data are opened with GDAL as documented by http://gdal.org/drv_osm.html

In QGIS 2.x, There are 3 steps involved

*

*Get an OSM File, you can get it using josm or overpass or any other source. It has to be a valid xml. You can also download it from qgis Vector > OpenStreetMap > Download OSM Data menu, but sometimes it does not give result. I would recommend using overpass turbo.

*Vector > OpenStreetMap > Import Topology from XML, this as you said will produce a spatialite database with non-geometry tables. This i think is the topology.

*Finally, you can get data by Vector > OpenStreetMap > Export Topology to Spatialite, here you need to give the db file made above and just like in qgis 1.8 you will have option to choose points, lines or polygons. Below that in exported tags section you can load all the tags contained in the file and select only those which you require. This is additional feature than in 1.8.

The layer gets added to map, if you want all nodes, ways you can repeat step 3 with other options.
http://wiki.openstreetmap.org/wiki/QGIS#QGIS2_OpenStreetMap_Vectors

A: I found downloading OSM data using the plugin and going through the import and export motions very tedious. That's why I wrote up a different solution: http://anitagraser.com/2014/05/31/a-guide-to-googlemaps-like-maps-with-osm-in-qgis/
Summary:
Raw OSM files can be quite huge. That's why it's definitely preferable to download the compressed binary .pbf format instead of the XML .osm format.
As a download source, I'd recommend Geofabrik.
For the first preprocessing step: extracting the area of interest, we can use Osmosis:
C:\Users\anita_000\Geodata\OSM_Noirmoutier>..\bin\osmosis.bat --read-pbf pays-de-la-loire-latest.osm.pbf --bounding-box left=-2.59 bottom=46.58 right=-1.44 top=47.07 --write-xml noirmoutier.osm
While QGIS can also load .osm files, I found that performance and access to attributes is much improved if the .osm file is converted to spatialite.
C:\Users\anita_000\Geodata\OSM_Noirmoutier>ogr2ogr -f "SQLite" -dsco SPATIALITE=YES noirmoutier.db noirmoutier.osm
In QGIS, we can load the points, lines, and multipolygons using Add SpatiaLite Layer.
When we load the spatialite tables, there are some issues:

*

*There is no land polygon. Instead, there are "coastline" line features.

*Most river polygons are missing. Instead there are "riverbank" line features.

Creating the missing river polygons is not a big deal:

*

*select all the lines where waterway=riverbank.

*use the Polygonize tool from the processing toolbox to automatically create polygons from the areas enclosed by the selected riverbank lines. (Note that Processing by default operates only on the selected features but this setting can be changed in the Processing settings.)

Creating the land polygon (or sea polygon if you prefer that for some reason) is a little more involved since most of the time the coastline will not be closed for the simple reason that we are often cutting a piece of land out of the main continent. Therefore, before we can use the Polygonize tools, we have to close the area. To do that, I suggest to first select the coastline using "other_tags" LIKE '%"natural"=>"coastline"%' and create a new layer from this selection (save selection as …) and edit it (don't forget to enable snapping!) to add lines to close the area. Then polygonize.


text:
Q: Абсолютная позиция и прозрачность элемента Есть поле ввода с подсказками (выпадающими вариантами) и кнопка. Работает это всё через чистый JS без jQuery.
По-началу оно работает корректно:

Но после нескольких нажатий, оно становится таким:

Я проверил все z-index и position параметры. Есть мысль, что все дело в opacity. Когда курсор на не элементе, элемент становится немного прозрачным.
Как можно исправить?

A: Исправил ситуацию. Вынес прозрачность в отдельный css класс. Если подсказки на экране, класс, отвечающий за прозрачность удаляется, иначе добавляется.


text:
Q: Hazelcast: how to ensure cluster startup is finished I have a cluster with 3 nodes (in different machines) and I have a "business logic" that use a distributed lock at startup.
Sometimes when there is more latency every node acquires the exclusive lock with success because the cluster isn't already "startup" so each node does not yet see the other.
Subsequently the nodes see each other and the cluster is correctly configured with 3 nodes. I know there is a "MemberShipListener" to capture the event "Member added" so I could execute again the "business logic", but I would to know if there is a method to ensure when the cluster startup is properly finished in order to wait to execute the "business logic" until the cluster is on.
I tried to use hazelcast.initial.wait.seconds but configure the right seconds isn't deterministic and I don't know if this also delay the member join operations.

A: Afaik, there is no such thing in Hazelcast. As the cluster is dynamic, a node can go and leave at any time, so the cluster is never "complete" or not.
You can, however :

*

*Configure an initial wait, like you described, in order to help with initial latencies

*use hazelcast.initial.min.cluster.size to define the minimum number of members hazelcast is waiting for at start

*Define a minimal quorum : the minimal number of nodes for the cluster to be considered as useable/healthy (see cluster quorum)

*Use the PartitionService to check is the cluster is safe, or if there are pending migrations


text:
Q: Switching  backgroundcolor and fontcolor at the same time I have a simple table here where I can switch the background color when clicked.
The below code switches the background color back and forth when clicked. I need also the font color to be switched in the same manner when clicked (in addition to background color switching). The default font color is white, when clicked, it would be black, and at second click, it would be white again.
The code is like this:

window.onload = function() {

  var all = document.getElementsByTagName("td");
  for (var i = 0; i < all.length; i++) {
    all[i].onclick = inputClickHandler;
  }
};

function inputClickHandler(e) {
  e = e || window.event;
  var tdElm = e.target || e.srcElement;
  if (tdElm.style.backgroundColor == 'rgb(154, 201, 157)') {
    tdElm.style.backgroundColor = '#fff';
  } else {
    tdElm.style.backgroundColor = '#9ac99d';
  }

}
.rep {
  border: 1px solid #CCC;
  font-family: Arial, Helvetica, sans-serif;
  font-size: 12px;
  color: whitesmoke;
  border-collapse: collapse;
  width: 10%;
  margin: 10px;
  float: left;
  margin-left: 45px;
}

.rep td {
  padding: 2px;
  margin: 2px;
  border: 1px solid #ccc;
  text-align: center;
  height: 17px;
  width: 17px;
}

    1
    2
    3

A: JavaScript:
if(variable) {
  element.style.backgroundColor = "firstBGColor";
  element.style.color = "firstFGColor";
} else {
  element.style.backgroundColor = "secondBGColor";
  element.style.color = "secondFGColor";
}
variable = !variable

jQuery:
$("body").css("background-color", "blue").css("color", "white") This jQuery code changes the background color and the color of the body "at the same time".
Prefered:
But I would suggest creating classes and settings and removing them. It makes the code way more maintainable.
if(variable) {
  element.className = "firstClass";
} else {
  element.className = "secondClass";
}
variable = !variable

**CSS**
.firstClass {
  background-color: firstBGColor;
  color: firstFGColor
}
.secondClass {
  background-color: secondBGColor;
  color: secondFGColor
}

A: try this code

$(function(){
  $("td").click(function(){
    if($(this).css('background-color') == 'rgb(154, 201, 157)'){
      $(this).css('background-color', '#fff')
      $(this).css('color', 'white')
    }else{
      $(this).css('background-color', 'rgb(154, 201, 157)')
      $(this).css('color', 'black')
    }
  });
});
.rep {
  border: 1px solid #CCC;
  font-family: Arial, Helvetica, sans-serif;
  font-size: 12px;
  color:whitesmoke;
  border-collapse:collapse;
  width: 10%;
  margin: 10px;
  float: left;
  margin-left:45px;
}
.rep td {
  padding: 2px;
  margin: 2px;
  border: 1px solid #ccc;
  text-align: center;
  height:17px;
  width:17px;
}

  1
  2
  3


text:
Q: Generate suggestion based on database (PHP and MySql) Can you give me some tips how can i generate a suggestion based on the word entered by the user? Its not a misspelling thing, i wan't when a user enter the word: "hello" if the database does not contain the word "hello" but the word "helo" or "helol" suggest that.
Thank you.

A: FYI
You should look into PHP's levenshtein function, this finds closest matching words based on a score, using a dictionary file... I know you said it's not mispelling, but the dictionary file can be anything and you can have more than one, depending on how you want to use it

A: It will be way too complex to do with MySQL alone. You need to index commonly used words using something like Sphinx Search (a stand-alone full text search engine) and then run the queries against Sphinx.
There is a pretty good thread about it at http://sphinxsearch.com/forum/view.html?id=5898

A: You can use the Soundex function and compare submitted string to a dictionnary database, i.e.:
soundex("Hellllo")       == soundex("Hello");

All you have to do, is storing your suggestions soundex in a table. Then when a user submit a word, you can search for his soundex hash in your table and return the words with the same / close pronounciation.
The soundex method is kind of fast, but your dictionnary table has to be indexed if you need performance.


text:
Q: How to put default_url_option for specific path only I am using defaul_url_option for putting lang params in my url e.g. home/?lang=en, However some of my ajax function is not working because of the parameter lang added to the url request, How to specify only in specific path or routes

A: Actually you should even not touch the lang param in any of your routes, unless you want to change your language.
Your app controller should have:
  def default_url_options(options={})
    logger.debug "default_url_options is passed options: #{options.inspect}\n"
    { lang: I18n.locale }
  end

and you routes.rb:
  scope "/(:lang)", :lang => /de|en/ do
    # resources definitions
  end

Now, in any of your route you do not need provide lang param (unless you want to switch language), it is generated out of the box.


text:
Q: C# form - controls losing dock state during threaded operation I have a form with a menu strip, a status strip, and a main split container (which itself contains other split containers, tree views, tab control, etc).  Occasionally (fairly frequently, actually), the application will stop resizing controls within the main form (usually during or right after a background thread operation to retrieve data).  The control itself still claims its DockStyle is Fill, but the control isn't resizing with the form.  I can't find any information on what might cause this issue, has anyone come across anything like this before?

A: Making sure you manipulate the UI from the proper thread is critical. I recommend using the following extension methdds
public delegate void EmptyHandler();
public delegate void ParamHandler(params object[] args);

public static void SafeCall(this Control control,
                      ParamHandler method, params object[] args)
{
    if (control.InvokeRequired)
    {
        control.Invoke(method, args);
    }
    else
    {
        method(args);
    }
}
public static void SafeCall(this Control control, EmptyHandler method)
{
    if (control.InvokeRequired)
    {
        control.Invoke(method);
    }
    else
    {
        method();
    }
}

then you can call the appropriate method from the incorrect thread like this
{  ... background thread

    void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        this.SafeCall(SetImage, e.Result);
    }

 }

which calls the method SetImage(Bitmap bitmap) with the proper thread.

A: Well, that was stupid.
Turns out I had a rogue SuspendLayout() call that didn't have a corresponding ResumeLayout() call.  This behaviour isn't what I would have expected.  Learn something new every day!  Thanks for looking!


text:
Q: C# - Why does a class, new() constraint use Activator.CreateInstance()? I just asked C# - How do generics with the new() constraint get machine code generated?
After thinking about this for a while, I'm wondering why the C# Compiler emitted IL like that.
Why couldn't it say some IL like: "Call T's default constructor"?

A: There is no such instruction in CIL (http://www.ecma-international.org/publications/standards/Ecma-335.htm).
Assuming we can add one, an another implementation of this could be that in the Type's VTable we make the default constructor be indexed at index 0, and then the JIT can assume this information and emit code that does a VTable lookup, pick index 0 and call the function located at address pointed by this entry 0 in the VTable.
As you can see this requires a change in CLR data structures, possibly each object's layout, and likely a different solution for value types (I'm ignoring that case, because you specifically say class and new().


text:
Q: Using the Google Analytics Export API to get a websites trend i am working on an application that uses the Google Analytics Export API and i am trying to get the "Trend" result that Google shows against each of your site accounts as a percentage
ie UP 35.04%  or DOWN 16.02%
How/where do they get this figure and is it available in the API somewhere.
i have tried comparing averages of last month to this month/first week of the period vs last week of the period etc, but i cannot seem to get the same numbers that Google provides.
any ideas?
thanks in advance
Doug

A: The formula is pretty simple (excluding today's data):

(Visits over the last 30 days - Visits
  between 31 and 60 days ago)  / (Visits
  between 31 and and 60 days ago).

You can see it in action in the interface if you go to the default dashboard, where it shows you the last 30 days, then on the calendar, click "Compare to past" and select the default amount. It'll show you the numbers used for each calculation and the calculations as they appears in that account list.
The API does not, however, expose pre-calculated numbers (for example, they don't compute bounce rate for you; they just give you the pieces for it.)
So, you'd need to do two API requests to get this data. One for ga:visits in the last 30 days, and then one for ga:visits in the 30 days prior.
Then, when you get it, just subtract, divide, and multiply by 100, and you'll have the percent you're looking for.
UPDATE: The striked out part of the answer was true, but is no longer. The newest version of the Google Analytics API does provide access to some pre-calculated values.


text:
Q: Lucene - Search for multiple associated values I would like to index and search pieces of data that are indexed using Lucene.
E.g. Items and their colour
Item 1 - Black
Item 2 - Yellow
Item 3 - Red

Search examples
Search word - Item
Item 1 - Black
Item 2 - Yellow
Item 3 - Red

Search word - Item 1
Item 1 - Black

Search word - Item 2 - Yellow
Item 2 - Yellow

Possible solution
From what I found on the answer to this apparently I can add these into a field using this format.
// {Item 1}|{Black}
document.add(new StringField("item", MessageFormat.format("'{'{0}'}'|'{'{1}'}'", itemName, itemColour, Field.Store.YES));

If I now do a search with the data in this format I get no results.
I'm using the StandardAnalyzer.
This is how I'm creating the query.
QueryParser queryParser = new QueryParser("item", analyzer);
queryParser.setAllowLeadingWildcard(true);
Query query = queryParser.parse(keyword);

I would like to search for:

*

*All items that have a matching name

*All items that match and also have a specific colour

What is the best method of solving this?

A: I would suggest a different structure for the documents in case if you wanna build other possible searches in the future. Here an abstract view
new StringField("number", number);
new StringField("item", item);
new StringField("color", color);

additional to this 3 fields you add a field for fulltext searches including all the informations of the three fields. This will be done by TextField See Lucene Field javadoc
new TextField("fulltext", item + " " + number + " " + "color");

With this you're able to apply your fulltext search to the "fulltext" field and may some other searches to the other fields directly.
One last thing:

queryParser.setAllowLeadingWildcard(true);

You really wanna allow this? this may has performance-impacts and may lead to unexpected search behavior.


text:
Q: Array.isDefinedAt for n-dimensional arrays in scala Is there an elegant way to express
val a = Array.fill(2,10) {1}
def do_to_elt(i:Int,j:Int) {
    if (a.isDefinedAt(i) && a(i).isDefinedAt(j)) f(a(i)(j))
}

in scala?

A: You just need to check the array at index i with isDefinedAt if it exists:
def do_to_elt(i:Int, j:Int): Unit =
  if (a.isDefinedAt(i) && a(i).isDefinedAt(j)) f(a(i)(j))

EDIT: Missed that part about the elegant solution as I focused on the error in the code before your edit.
Concerning elegance: no, per se there is no way to express it in a more elegant way. Some might tell you to use the pimp-my-library-Pattern to make it look more elegant but in fact it does not in this case.
If your only use case is to execute a function with an element of a multidimensional array when the indices are valid then this code does that and you should use it. You could generalize the method by changing the signature of to take the function to apply to the element and maybe a value if the indices are invalid like this:
def do_to_elt[A](i: Int, j: Int)(f: Int => A, g: => A = ()) =
  if (a.isDefinedAt(i) && a(i).isDefinedAt(j)) f(a(i)(j)) else g

but I would not change anything beyond this. This also does not look more elegant but widens your use case.
(Also: If you are working with arrays you mostly do that for performance reasons and in that case it might even be better to not use isDefinedAt but perform validity checks based on the length of the arrays.)

A: I recommend that you not use arrays of arrays for 2D arrays, for three main reasons.  First, it allows inconsistency: not all columns (or rows, take your pick) need to be the same size.  Second, it is inefficient--you have to follow two pointers instead of one.  Third, very few library functions exist that work transparently and usefully on arrays of arrays as 2D arrays.
Given these things, you should either use a library that supports 2D arrays, like scalala, or you should write your own.  If you do the latter, among other things, this problem magically goes away.
So in terms of elegance: no, there isn't a way.  But beyond that, the path you're starting on contains lots of inelegance; you would probably do best to step off of it quickly.


text:
Q: Searching for prototype inspirations to simulate Windows Azure scaling features I want to write an application in ASP.NET running in Windows Azure. I would then simulate a thousand users at the same time to show the behaviour of the application and the scaling features of Windows Azure. Would be great if this application would cause high cpu usage too.
Therefore I could use some good ideas which type of application would fit these requirements.
Thx to all for helping me out.
EDIT:
Thanks for your answers. The simulation tools are quite useful. But that is not my main problem to find an apropriate testing tool. I want write an asp.net application and need some ideas for this particularly application. For example a file conversion application was one idea of mine, because it needs a lot cpu and I could measure what goes on in the cloud. What I wanna know are some more ideas for a cool application prototype.
Thx again guys.

A: There are a number of tools and services that will allow you to simulate load on servers.  You don't need anything to be Azure specific:
https://stackoverflow.com/questions/532236/are-there-any-free-tools-to-help-me-simulate-load-on-a-server
What sort of scaling features of Azure are you looking to test?  Or do you just want to see how many users an Azure server can handle?  Azure does not automatically scale with demand, you'll want to use an autoscaling service like AzureWatch to help you scale with demand
HTH

A: As Igor said, AzureWatch is a great 3rd-party scaling and monitoring service.
Also, check out the new Cloud Ninja project on codeplex, developed by a few of my teammates. It demonstrates multi-tenancy, metering, and scaling concepts.
If you're looking for a very easy way to generate massive load, for scale testing, check out Loadstorm, a cloud-based load generation service. While not as sophisticated as, say, Microsoft's Visual Studio Test system or some of the enterprise tools like Loadrunner, it's very easy to use and easily handles most common load-testing scenarios. I've used Loadstorm for several load-testing engagements.


text:
Q: How do I get the divs to float next to, and below each other I have a lot of divs with text in it, and I want them to nicely align next to each other and below each other.
(I've read somehwere that I should make a parent div for these, and give the parent a relative position and the child a absolute position, but this didn't work for me)
But it won't work.
I found this lay-out with shows exactly what I want mine to do
HTML

Title

            Text

CSS
/*.blockboxgrid{
   position:relative; <<< I saw this example while googling, to make the area where the box is in relative, and the box itself absolute. But this didn't work for me either.
}*/

.blockbox {
    /*position:absolute;*/
    background-color:#fff;
    border-radius: 4px;
    border:8px solid #ff6b6b;
    display: block;
    float: left;
    margin: 10px;
    width: 330px;

    color:#000;
    transition: all 0.5s ease;
}

JSFiddle

A: The site your are referring to uses a JavaScript package called Masonry:
http://masonry.desandro.com/
This type of grid layout cannot be achieved by CSS alone, so you need the
Masonry package.

A: http://jsfiddle.net/zqrjLz9d/1/ Here you go.
.block {
    width:100%;
    height:auto;
    display: inline-block;
    float:left;
}


text:
Q: How to get Maximum Difference between Dates in a row using SQL

Date 1
Date 2
Date 3
Date 4
LineCount
Month_Gap

2020-01-01
2019-10-01
2019-09-06

1

2020-01-01
2019-10-01
2019-09-13
2019-09-06
2
0

2020-01-01
2019-10-01
2019-08-13
2019-09-06
2
1

If the LineCount is 1, then Month_Gap should be the maximum month difference between (Date1 & Date3) and (Date2 & Date3). Date3 will always be in between Date1 and Date2.
In this Case, the output should be the max month difference between (2020/01/01 - 2019/09/06) and (2019/10/01 - 2019/09/06), which is 3 months:

Date 1
Date 2
Date 3
Date 4
LineCount
Month_Gap

2020-01-01
2019-10-01
2019-09-06

1
3

2020-01-01
2019-10-01
2019-09-13
2019-09-06
2
0

2020-01-01
2019-10-01
2019-08-13
2019-09-06
2
1

I was trying something like this but not sure how to go about it -
CASE WHEN LineCount = 1 THEN MAX(DATE_DIFF(.....), which won't work I guess.

A: The pattern you should use is
SELECT TIMESTAMPDIFF("MONTH", LEAST(date1,date2,date3,date4), GREATEST(date1,date2,date3,date4)) as `maximum_difference`;

This will simply look through your columns, find the least and greatest, and return the result.

A:     SELECT
    CASE WHEN LineCount = 1 THEN GREATEST(DATE_DIFF('month', Date3, Date1),
    DATE_DIFF('month', Date3, Date2)) END AS Month_Gap


text:
Q: Import JSON data into a table using excel VSTO webaddin c# I want to get data from this api and import data into a excel sheet using c#
and also want to convert that jasonContent1 to csv format.
thank you..
private void button3_Click(object sender, RibbonControlEventArgs e)
{
    string url = String.Format("https://jsonplaceholder.typicode.com/users?id=1");
    WebRequest webRequest = WebRequest.Create(url);

    webRequest.Method = "GET";
    HttpWebResponse respObj = null;
    respObj = (HttpWebResponse)webRequest.GetResponse();

    string resultTest1 = null;
    using (Stream stream = respObj.GetResponseStream())
    {
        StreamReader reader = new StreamReader(stream);
        resultTest1 = reader.ReadToEnd();
        //string json = resultTest1.Trim();
        // DataSet jsonContent = JsonConvert.DeserializeObject<DataSet>(json);
        var jsonContent1 = JsonConvert.DeserializeObject(resultTest1);

        reader.Close();

    }
}


text:
Q: How to identify the primary key of a table in databricks using SparkSql or Pyspark? I tried using this as my code but was not able to get the output!
SHOW PRIMARY KEYS
[ IN { ACCOUNT | DATABASE [ <database_name> ] | SCHEMA [ <schema_name> ] | TABLE | [ TABLE ] <table_name> } ]

A: Technically speaking, Spark doesn't have built-in concept of the primary key that will be enforcing uniqueness. There is a concept of the partition key (you can use SHOW PARTITIONS), but it's a different thing used to separate data files by some specific key


text:
Q: Sync Framework: Oracle/SQLServer I want to setup a sync service using Microsoft Sync Framework.
The main objective is to sync some tables between an Oracle Database and a SQL Server Database.
How can I do it? There are any OracleSyncProvider?

A: if you go the Sync Framework way, there is a sample Oracle sync provider at: http://code.msdn.microsoft.com/Database-Sync-Oracle-and-037fb083

A: There are several forms of third party software which will automate this process for you, however if you would like to do it manually I would suggest the Oracle CREATE DATABASE LINK.
This approach allows you to access information (tables,views, etc) from another database using the Heterogeneous Services.
Once you have established a connection between the two databases you can create a trigger for the Oracle tables which in-turn fire on updates/inserts/deletes so that the same action gets invoked on the Microsoft database.
See the following link for additional details on Oracle's DATABASE LINK : http://docs.oracle.com/cd/B12037_01/server.101/b10759/statements_5005.htm
The same setup can be applied to the SQL server so that whenever an update/insert/delete is performed the correlating table in Oracle gets updated, "synced", as well. For the Microsoft approach to this see the following link, http://msdn.microsoft.com/en-us/library/ms188279.aspx .

A: To solve this problem I used a Linked Server to the Oracle DB Server and after that I created a SQL SERVER JOB that runs the Merge command.


text:
Q: @Query in JPA throwing null pointer exception I am getting nullPointerException from my custom jpa method findShiftNameById() in my shift planner project(github link below). I have used @Query annotation inside ShiftDetailsRepo Interface to implement the method. Please check and let me know what could be causing this. I tried by removing nativeQuery parameter but that gives shift_details not mapped error.I tried by changing datatypes between int and long and also by changing sd.shiftName to sd.shift_name(as per the column name that is available in my actual database) but still same nullPointerException error is coming.
Github link-https://github.com/Anupam5713/shiftPlannerAPI
The method is being called in the ShiftPlanService Class inside the service package
Is there something wrong in my query?
@Query(value = "select sd.shiftName from shift_details sd where sd.shiftId=:shiftId",nativeQuery=true)
    public String findShiftNameById(@Param("shiftId") int shiftId);

A: The following is the cause of NPE.  The call to sdr is done before the dependencies are wired.
@Service
public class ShiftPlanService {

    @Autowired
    ShiftDetailsRepo sdr;
    String S1 = sdr.findShiftNameById(1);
    String S2 = sdr.findShiftNameById(2);

Move these initializations to a @PostConstruct method.
Example
@PostConstruct
public void initDetails() {
    S1 = sdr.findShiftNameById(1);
    S2 = sdr.findShiftNameById(2);
}