text:
Q: Sending a request through Ajax to a servlet (non spring) I have a CRUD table that lists a bunch of products, what I need is that when I click on a button, Ajax automatically sends a request to the servlet telling it that I want to change the state (instead of deleting the product) in the database, then after that is done it should reload the table.
I already have most of the code done, here is the AJAX that I had (Which I suppose is the part that is wrong), I was working on it trying to get it to work when I clicked on a row so ignore that part, there's a delete button per row).

And here is the servlet code:
 protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            int id = Integer.parseInt(request.getParameter("id"));
            ProductDAO productBD = new ProductDAO();
            Product products = productBD.selectById(id);
            if(products.getState() == "Active"){
                    Product product = new Product(id,"Not Active");
                    productBD.update(product);
                    ArrayList<Product> productList = new ArrayList<>();
                    productList = productBD.selectAll();
                    request.getSession().setAttribute("productList", productList);
                    request.getRequestDispatcher("/wproduct/listing.jsp").forward(request, response);
                }else if(products.getState() == "Not Active"){
                    Product product = new Product(id,"Active");
                    productBD.update(product);
                    ArrayList<Product> productList = new ArrayList<>();
                    productList = productBD.selectAll();
                    request.getSession().setAttribute("productList", productList);
                    request.getRequestDispatcher("/wproduct/listing.jsp").forward(request, response);
                }

}

I tried looking it up but only found how to do this with Spring
(Here is the full servlet code, it has Spanish names on it which is why I translated it for the original post):
package controladores;

import daos.ClienteDAO;
import dtos.Cliente;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author lycan
 */
@WebServlet(name = "ControladorEstado", urlPatterns = {"/controladorestado.do"})
public class ControladorEstado extends HttpServlet {

/**
 * Processes requests for both HTTP GET and POST
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            int id = Integer.parseInt(request.getParameter("id"));
            ClienteDAO clientebd = new ClienteDAO();
            Cliente clientes = clientebd.selectById(id);
            if(clientes.getEstado() == "Activo"){
                    Cliente cliente = new Cliente(id,"No Activo");
                    clientebd.update(cliente);
                    ArrayList<Cliente> lista = new ArrayList<>();
                        lista = clientebd.selectAll();
                        request.getSession().setAttribute("lista", lista);
                        request.getRequestDispatcher("/wcliente/listar.jsp").forward(request, response);
                }else if(clientes.getEstado() == "No Activo"){
                    Cliente cliente = new Cliente(id,"Activo");
                    clientebd.update(cliente);
                    ArrayList<Cliente> lista = new ArrayList<>();
                        lista = clientebd.selectAll();
                        request.getSession().setAttribute("lista", lista);
                        request.getRequestDispatcher("/wcliente/listar.jsp").forward(request, response);
                }

}

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
 * Handles the HTTP GET method.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);
}

/**
 * Handles the HTTP POST method.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);
}

/**
 * Returns a short description of the servlet.
 *
 * @return a String containing servlet description
 */
@Override
public String getServletInfo() {
    return "Short description";
}// </editor-fold>

}

And here is the listing code:
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%--
    Document   : listar
    Created on : 19-oct-2018, 11:00:29
    Author     : lycan
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <%@include  file="../WEB-INF/jspf/estilos.jspf"%>
        <title>Sistema Ventas</title>

            <%@include  file="../WEB-INF/jspf/header.jspf"%>
            <%@include  file="../WEB-INF/jspf/nav.jspf"%>

                            ID
                            Nombre
                            Descripcion
                            Categoria
                            Estado

                    <c:forEach var="clientes" items="${sessionScope.lista}">

                            ${clientes.id}
                            ${clientes.nombre}
                            ${clientes.descripcion}
                            ${clientes.categoria}
                            ${clientes.estado}
                            <a href="<%=request.getContextPath()%>/controladorcliente.do?operacion=detalle&id=${clientes.id}" class="btn btn-primary btn-lg " role="button" >Detalle
                            <a href="<%=request.getContextPath()%>/controladorcliente.do?operacion=actualizar&id=${clientes.id}" class="btn btn-primary btn-lg " role="button" >Actualizar
                            <a href="<%=request.getContextPath()%>/controladorcliente.do?operacion=eliminar&id=${clientes.id}" class="btn btn-primary btn-lg eliminar" role="button" >Eliminar

                    </c:forEach>

            <a href="<%=request.getContextPath()%>/controladorcliente.do?operacion=crear" class="btn btn-primary btn-lg " role="button">Registrar
            <a href="<%=request.getContextPath()%>/controladorcliente.do?operacion=buscar" class="btn btn-primary btn-lg " role="button">Buscar

            <%@include  file="../WEB-INF/jspf/footer.jspf"%>

        <%@include  file="../WEB-INF/jspf/js.jspf"%>

A: okay i see what you are doing now, thanks for including more information. The reason why nothing happens is because in your servlet you are trying to return the same page you are making the ajax call from. (and you're not even handling the response)
From the looks of it, you want to return a table through the ajax method, but in order to do that you need to create a separate jsp that you will return.. For example:
create a new jsp called user-table inside /wcliente/
user-table.jsp
<?xml version="1.0" encoding="UTF-8"?>
<%@page contentType="application/xml" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<data>

                        ID
                        Nombre
                        Descripcion
                        Categoria
                        Estado

                <c:forEach var="clientes" items="${lista}">

                        ${clientes.id}
                        ${clientes.nombre}
                        ${clientes.descripcion}
                        ${clientes.categoria}
                        ${clientes.estado}
                        <a href="<%=request.getContextPath()%>/controladorcliente.do?operacion=detalle&id=${clientes.id}" class="btn btn-primary btn-lg " role="button" >Detalle
                        <a href="<%=request.getContextPath()%>/controladorcliente.do?operacion=actualizar&id=${clientes.id}" class="btn btn-primary btn-lg " role="button" >Actualizar
                        <a href="<%=request.getContextPath()%>/controladorcliente.do?operacion=eliminar&id=${clientes.id}" class="btn btn-primary btn-lg eliminar" role="button" >Eliminar

                </c:forEach>

</data>

Now in your servlet, instead of this:
request.getRequestDispatcher("/wcliente/listar.jsp").forward(request, response);

do this:
request.getRequestDispatcher("/wcliente/user-table.jsp").forward(request, response);

For the ajax in your listar.jsp do this instead:

Reference:
How to use Servlets and Ajax?


text:
Q: How to back up OS and application preferences on Mac OS X Lion for reinstalling? The title pretty much says it all. I'm happy to copy folders, or use a utility. I know a lot of preferences are kept in ~/user/Library/Application Support.

A: Backup your system using Time Machine.
Then you can erase the entire disk, install Lion cleanly, and just restore e.g. user accounts, but not applications.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why GridSearchCV has higher score with a subset of parameters? Below is my code, I run it twice. The first one with "criterion": ['gini', 'entropy'] and the second one with just 'entropy' ('gini' was removed), nothing else changed. I expected with less number of combinations, the score must be equal or lower, but it was higher - How is it possible?? No randomness and those numbers repeated all the times.

*

*Using "criterion": ['gini', 'entropy'] got score of 0.850

*Using "criterion": ['entropy'] got score of 0.871 (higher)

    X_train, X_test, y_train, y_test = train_test_split(dataX, dataY, test_size=0.2, random_state=10, stratify=dataY)
    gs_params = {
        "criterion": ['gini', 'entropy'],
        "max_depth": [3, 4, 5, 6, 8, 10, 12, 15],
        "min_samples_split": range(2, 9, 2),
        "min_samples_leaf": range(1, 5)
    }

    gs = GridSearchCV(model, param_grid=gs_params, n_jobs=-1, verbose=1,
                      cv=5, scoring='f1_weighted', refit=True)

    clf = Pipeline([
        ('scaler', StandardScaler()),
        ('features1', SelectFromModel(RandomForestClassifier(random_state=80), threshold='median')),
        ('features2', SelectFromModel(RandomForestClassifier(random_state=81), threshold='median')),
        ('features3', SelectFromModel(RandomForestClassifier(random_state=82), threshold='median')),
        ('gs', gs)
    ])

    clf.fit(X_train.values, y_train.values)
    test_score_opt = clf.score(X_test.values, y_test.values)


text:
Q: C# program Time synchronization between Windows and linux I want to add a function in my C# program that can synchronize the time between linux and windows, is there any way to do this?

A: One solution is to run an ntp server on the Linux server (many distributions either include one or make it easy to install), then use some sort of NTP client from within your program.  One approach to the .NET side is here, but instead of using a public time server, you would want to use the address of the Linux server.


text:
Q: Why is integral of product of a test function and derivative of Dirac-delta function seems to diverge? Suppose,we have to evaluate the integral $\int_{-\infty}^{\infty}f(x)\delta'(x)dx$
Traditionally to solve this,we integrate by parts so that the integral is equal to$-f'(0)$,which is finite if $0$ is not a pole of the function $f(x)$.But if the following is done the integral diverges---
Differentiating both sides of the well known identity, $x\delta(x)=0 $ we get,
$1.\delta(x)+x\delta'(x)=0\implies \delta'(x)=-\frac{\delta(x)}{x}$.
Putting this in the integral to be evaluated, we have,
$\int_{-\infty}^{\infty}\frac{f(x)}{x}\delta(x)dx=\frac{f(0)}{0}$,which is undefined for any function $f(x)$.Where did this procedure go wrong?Is it related to the fact that delta function is a distribution?If so,How?

A: When we say that the delta function is a distribution, we mean that it only has meaning inside of an integral of the form $$ \int_a^b dx f(x) \delta(x)   $$ where $f(x)$ is a smooth test function which vanishes outside of the interval $[a,b]$. Your function $f(x)/x$ is not a smooth test function (it is undefined at $x=0$), so your argument does not apply.
Likewise your "well known identity" $x\delta(x)=0$ only makes sense inside an integral, and is not otherwise an identity at all. It means $$ \int_a^b dx x \delta(x)  = 0. $$ Differentiate $0$ and you get $0$.
Similarly, $\delta'(x)$ only has meaning inside an integral, and is only defined by integration by parts for a valid test function. You cannot use the product rule on a delta function, because it is not a differentiable function.

A: Since, you don't want a highly rigorous answer (per your comment). I would then simply point out that this integration can't be done as the integrand is singular and integral diverges. You may want to look at Singular Integral.
One way to do the integral is using contour integration in complex analysis. For example you may look at Type 4 Integrals.
Revert back if you have further doubts.


text:
Q: Hide Navigation Links From Non-Members I have an include file that stores the navigation links for my website. I just built a members-only section and I would like to make it so that some of the links in the navigation bar are visible only if someone is logged in. What are some good ways of going about doing this?

A: It's all depending on how you check whether the user is logged in or a visitor, if you have a variable that tracks so
eg. $isLoggedIn to track whether the user is logged in, you can do something like the below
Home |
<?php if ($isLoggedIn) { ?>
Member Area |
<?php } ?>
About Us

as for the different set of users, you might have a field called member_group in database, which member_group is in number. you can then have
<?php include "nav_group_{$memberGroup}.php" ?>

To include appropriate links
Do remember to do additional checking of $isLoggedIn inside member.php as well!

A: Since you say that you have built a members-only section, I guess you're already using sessions to track if a user is logged in or not. In the include file, check if the user's session exists and display the appropriate links.
As a more robust solution, if you wanted to show different sets of links to different logged in users, you would set up a DB table with flags for each user or groups of users indicating what links should be displayed for them. In the include file, you would check the user's permissions and display the appropriate links.

A: If you have the html source in DB, you can use a preg_replace:
$html = preg_replace('#]*>.*?]*>#is','Only members...',$html);

If you have a bbcode:
$html = preg_replace('#\[url[^\]]*].*?\[/url[^\]]*\]#is','Only members...',$html);

Too, if you want ban a some url:
$html = preg_replace('#http[s]?://(.*?)+[\b]#is','Only members...',$html);

A: check if username/ userid exists in session and based on that display/hide the navigation block..


text:
Q: How can I speed up aplication start time? such as vlc or firefox Why when I click to open application,firefox or vlc for example,it starts about 5 or 10 seconds after? Can I speed up start times? is it usual to wait 10 seconds to open a browser or any other application like software center? From what it depends? I have celeron dual core cpu 1007u and ivy bridge graphics.. i think it's decent for normal use such as surfing or watching a movies. Thanks in advance.

A: This Answer is rather a Wiki that Is meant to be read and understood first before attempting to use either Preload or Prelink.
We need to first understand how Applications launch under Linux, I will not comment on Windows. Linux is secure by design, So what do we really mean by that?
Application launch Process
Linux programs typically consist of a binary executable file that refers to multiple shared libraries. These libraries are loaded into memory once and shared by multiple executables. In order to make that happen, the dynamic linker (i.e. ld.so) needs to change the binary in memory such that any addresses of library objects point to the right place in memory. For applications with many shared libraries—GUI programs for example—that process can take some time. For most small programs this dynamic linking is very quick. But when bigger programs are launched it could take time. I mean considerable time.
Linux uses ASLR to randomize the addresses in memory. One of the ideas behind address space layout randomization (ASLR) is to randomize these locations each time a program is run—or library loaded—so that malicious programs cannot easily and reproducibly predict addresses
Let us understand With Context what preloading is and what prelinknig is and how they help reduce application launch times.
First lets take a look at Preloading.
Preloading is the action of putting and keeping target files into the RAM. The benefit is that preloaded applications start more quickly because reading from the RAM is always quicker than from the hard drive. However, part of your RAM will be dedicated to this task, but no more than if you kept the application open. Therefore preloading is best used with large and often-used applications like Firefox and LibreOffice.
Preload is an adaptive, pre-read demon. It observes the applications Starts over a period of time. Understands the application launch behaviour. It collects the information and based on the information starts to preload the libraries required by the programs into the device RAM. Hence over a period of time the Application launch times reduce considerably and applications launch faster.
Since Preload requires memory to store the program code, the system should in any case have more than 1GB of memory.
The increase in speed can be up to 55%. However, this is not detected right after installation. Preload requires a few days or a week or two until a reliable statistic is created. This statistic uses Preload to load the code of the corresponding programs in the memory.
Now Lets look at Prelinking
On most systems, libraries are not changed very often and when a program is run, the operations taken to link the program are the same every time. Prelink takes advantage of this by carrying out the linking and storing it in the executable, in effect prelinking it.
Idealy it nullifies the Randomization of the Addreses which means it is easy to predcit where the libraries are stored hence it results in quick access to the libraries. This in turn reduces the launch time considerably.
The idea behind pre-linking is fairly simple: reduce the amount of time the dynamic linker needs to spend doing these address relocations by doing it in advance and storing the results. The prelink program processes ELF binaries and shared libraries in much the same way that ld.so would, and then adds special ELF sections to the files describing the relocations. When ld.so loads a pre-linked binary or library, it checks these sections and, if the libraries are loaded at the expected location and the library hasn't changed, it can do its job much more quickly.
Which means that on a System which does not change much. Libraries stay the same for a long time, something like an Ubuntu LTS/RHEL/CentOS/Debian basically fixed release distros, Prelink will run better and provide great results.
There is only One Caviat.
Prelinking needs to be Scheduled, It needs to run after the Libraries/programs have been upgraded since the libraries are changing. One could achieve that using a simple Cron job or could run it manually once in a while.
So We could techinically combine Preload and Prelink. However prelink is still like a Hack but your mileage may vary. I would give it a shot anyways. If I was on something like Debian or CentOS I would definitely use Preload and Prelink Both.
References for more Information.
http://sysmagazine.com/posts/108454/
https://wiki.archlinux.org/index.php/Preload
https://wiki.archlinux.org/index.php/Prelink
http://lwn.net/Articles/341244/
https://wiki.gentoo.org/wiki/Prelink

A: One simple advice is to disable less important add-ons. It worked for me.


text:
Q: How change texts in the Login and register pages I am using Magento 2 and the Mr Bara template, I have managed to change the home and product view, but I can not find where to change the login and registration texts, I want to add an image as well and that should be done in the template . Has anyone managed to do it? Thanks

A: Check if the below files are already present in your theme:

/vendor/magento/module-customer/view/frontend/templates/form/login.phtml

and

/vendor/magento/module-customer/view/frontend/templates/form/register.phtml

Your template location will be like below:

app/design/frontend/[Vendor]/[theme]/Magento_Customer/templates/form/login.phtml

and

app/design/frontend/[Vendor]/[theme]/Magento_Customer/templates/form/register.phtml

If these files are not present then copy those from vendor location to your theme location as above and do the customisation.
Flush the cache and check if it works for you.

A: By default, Magento Login page and Register Page are displaying by below files

magento/vendor/magento/module-customer/view/frontend/templates/form/login.phtml
magento/vendor/magento/module-customer/view/frontend/templates/form/register.phtml

But you shouldn't directly change in these files. For this, you've to override these template files in your theme
For login template copy login.phtml file to below path

magento/app/design/frontend/Vendor/Theme/Magento_Customer/templates/form/login.phtml

For register template copy register.phtml file to below path

magento/app/design/frontend/Vendor/Theme/Magento_Customer/templates/form/register.phtml

A: Please check these two phtml files
vendor/magento/module-customer/view/frontend/templates/form/login.phtml
vendor/magento/module-customer/view/frontend/templates/form/register.phtml

A: Hello @EvinceDevelopment,
Can Anyone help me step by step to do this? I am looking for the same thing but Not sure what others files and folders are required to do this.
Thank you,


text:
Q: How to Check RAM Size without Looking at Motherboard As far as I am aware, one can view the RAM Size in System Properties:

From the above screenshot it seems that My RAM is 3.5 GB, but as far as I can tell I actually inserted 2 two GB RAM into my motherboard.
Is it that my memory is faulty, or that the information displayed in System Properties is faulty?

A: Because you are running 32Bit Windows 3.5GB is the maximum amount of RAM you can support.
A 64bit Operating system is required to use any more RAM. So currently you are wasting 512MB of RAM.

A: It's because your OS is 32-bit.  Check out Dude, Where's My 4 Gigabytes of RAM?

A: http://www.cpuid.com/cpuz.php
This will tell you everything about the memory installed in your machine along with the cpu. It will show which slots contain what size sticks and what speed they are running at.
The link JP posted from coding horror explains exactly why you only see 3.5gb out of the 4 you have installed is because of a 32bit OS.

A: Check memory with memtest86

*

*web site
Or use Everest or other hardware recognition software

*

*Everest web site
UPDATE:
Your question is wrong. Better is "Why my XP see only 3.5GB RAM?"
Answer from JP is right

A: 4GB Ram is the maximum allowed in 32bit operating systems.
I suspect that because your Video Card uses 1/2GB, that leaves 3.5 GB left.

A: Or try the Crucial system scanner.

A: the reason is not the operating system (which supports 4 GB), it is the 32-bit hardware architecture.
and while we're recommending software, here's another goodie:
SIW - System Information for Windows

A: Another way to check the memory size is:

*

*Click the Start Menu and choose Run.

*Type msinfo32.exe and press return.

A: Download CPU-Z... Will detect whatever is in your slot... ;)


text:
Q: How to change an empty star glyphicon button to star glyphicon button onclick with JS? This seems to change the glyphicon only when I click glyphicon itself. I want it to change when I click the button.

<button class="btn btn-default">

  </button>

A: You can use this jQuery code.
$(document).ready( function() {
    $('.btn').click(function(){
        $(this).find('.glyphicon').toggleClass('glyphicon-star-empty glyphicon-star');
    });
})

You have to bind the event on the button, not only the icon, else it will be triggered only clicking the star.


text:
Q: error on changing to device mode, Already have a Dart type associated I have a dart-polymer project working just fine in dartium. When changing to device mode/responsive design mode it throws multiple errors of the first type, I have removed some of them:
Already have a Dart type associated with paper-material interop_support.js:72 registerDartTypeUpgrader
interop_support.js:72 Already have a Dart type associated with paper-ripple
...
interop_support.js:72 Already have a Dart type associated with iron-request
...
interop_support.js:72 Already have a Dart type associated with neon-animatable
...
interop_support.js:72 Already have a Dart type associated with slide-from-right-animation
...
interop_support.js:72 Already have a Dart type associated with google-map
interop_support.js:72 Already have a Dart type associated with array-selector
interop_support.js:72 Already have a Dart type associated with dom-bind
...
undefined:1 Exception: Uncaught Error: NotSupportedError: Failed to execute 'registerElement' on 'Document': Registration failed for type 'resultat-element'. A type with that name is already registered.
Stack Trace:
#0      JsObject._callMethod (dart:js:235)
#1      JsObject.callMethod (dart:js:225)
#2      PolymerRegister.initialize (package:polymer/src/common/polymer_register.dart:19:23)
#3      loadInitializers.<anonymous closure>.<anonymous closure> (package:initialize/src/static_loader.dart:46:42)
#4      _runInitQueue (package:initialize/initialize.dart:35:24)
#5      _runInitQueue.<anonymous closure> (package:initialize/initialize.dart:38:39)
#6      _RootZone.runUnary (dart:async/zone.dart:1155)
#7      _Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:484)
#8      _Future._propagateToListeners (dart:async/future_impl.dart:567)
#9      _Future._completeWithValue (dart:async/future_impl.dart:358)
#10     _Future._asyncComplete.<anonymous closure> (dart:async/future_impl.dart:412)
#11     _asyncRunCallbackLoop (dart:async/schedule_microtask.dart:41)
#12     _asyncRunCallback (dart:async/schedule_microtask.dart:48)
#13     _handleMutation (dart:html:42316)

I can see one other also had a problem in an earlier version of polymer-dart here.
My .yaml file is looking like this
environment:
  sdk: '>=1.0.0 <2.0.0'

dependencies:
  web_components: '>=0.11.3 <0.13.0'
  route_hierarchical: any
  reflectable: ^0.3.1
  sqljocky: any

dependency_overrides:
  polymer:
    git:
      url: https://github.com/dart-lang/polymer-dart.git
      ref: 1.0.0-rc.2
  polymer_interop:
    git:
      url: https://github.com/dart-lang/polymer_interop.git
      ref: 1.0.0-rc.1
  polymer_elements:
    git:
      url: https://github.com/dart-lang/polymer_elements.git
      ref: update

transformers:
- web_components:
    entry_points:
      - web/index.html
- reflectable:
    entry_points:
      - web/index.dart

I have tried looking at the different git issiues polymer_interop, polymer_elements and polymer-dart. But cant figure out what the problem can be and hot to fix it. Maybe it is a bug in one of the early releases I am using.


text:
Q: facebook api test submit for review I have an app that is using publish_actions in order to post images from within the game to our app's facebook page.
I am using the iOS social framework (SLRequest and SLServiceTypeFacebook) to get permissions and to actually post the image.
All this works and is verified when I use a test facebook account.
However, I am trying to submit this for review to facebook so I can enable it for the rest of my users. but I am unable to submit because it thinks I am not making the actual API call.

It looks like you haven't made any API requests to publish content
  with the publish_actions permission in the last 30 days. You need to
  test this permission in your app with any account listed in Roles
  before you can submit for review. It looks like you haven't tested
  this permission because no API request has been made against
  publish_actions in the last 30 days.

http://cl.ly/image/3g3Q1p13113F
I have tested and confirmed that I can successfully use the publish_actions API to post from the app to the app's facebook page. How can I get facebook to allow me to actually submit this permission for review?

A: Are you making a direct API call to any of the APIs that need publish_actions permission? There are some instances where you do not need this permission, namely, if you are using a share dialog. An example of an API that needs publish_actions permission is a POST request to /{user-id}/feed. Also if you are making a post as a page, you might need publish_pages permission instead. e.g. Making a call to {page-id}/feed Depending on your use case, try and make a POST request to any endpoint that makes use of these permissions. That should help get rid of the error.


text:
Q: mutate_all using map and case_when / ifelse on lists in r My data looks something similar to the following:
$`2013 Jul`
# A tibble: 2 x 12
      AAPL     AMD      ADI    ABBV        A      APD       AA       CF     NVDA      HOG      WMT     AMZN
     <dbl>   <dbl>    <dbl>   <dbl>    <dbl>    <dbl>    <dbl>    <dbl>    <dbl>    <dbl>    <dbl>    <dbl>
1 -0.00252 0.00385 0.000314 0.00148 0.000231 0.000644 -0.00107 -0.00137 0.000886 0.000806 0.000689 0.000615
2  1       5       2        5       2        3         1        1       4        4        3        3

$`2013 Aug`
# A tibble: 2 x 12
       AAPL     AMD     ADI    ABBV         A     APD        AA       CF    NVDA      HOG      WMT    AMZN
      <dbl>   <dbl>   <dbl>   <dbl>     <dbl>   <dbl>     <dbl>    <dbl>   <dbl>    <dbl>    <dbl>   <dbl>
1 0.0000471 0.00297 0.00111 0.00187 0.0000542 0.00186 -0.000795 -0.00109 0.00140 0.000700 0.000965 0.00101
2 1         5       3       5       2         4        1         1       4       2        3        3

I am trying to use case_when in a dplyr, mutate and map function over a list of tibbles. Where I replace all lists which contain a 5 or a 1 with a 0.5 and all else with a 0.
I am trying a variation of mutate_all but do not know how to use case_when with mutate_all. I am open to other suggestions on how to solve this also.
x[1] %>%
  mutate_all(case_when(... = 5 ~ 0.5))

Data
list(`2013 Jul` = structure(list(AAPL = c(-0.00252413896048252,
1), AMD = c(0.00385385230384388, 5), ADI = c(0.000313658814841043,
2), ABBV = c(0.00148473194650269, 5), A = c(0.000231372267065186,
2), APD = c(0.000644411609229898, 3), AA = c(-0.00106999405402468,
1), CF = c(-0.00136811540143579, 1), NVDA = c(0.000886436095375894,
4), HOG = c(0.000806051331850114, 4), WMT = c(0.000689490484865284,
3), AMZN = c(0.000614708184565435, 3)), row.names = c(NA, -2L
), class = c("tbl_df", "tbl", "data.frame")), `2013 Aug` = structure(list(
    AAPL = c(0.0000471064768722691, 1), AMD = c(0.00297250845145986,
    5), ADI = c(0.00110927645875706, 3), ABBV = c(0.00186505842086247,
    5), A = c(0.0000542259939665846, 2), APD = c(0.00186178155179209,
    4), AA = c(-0.000794925865044543, 1), CF = c(-0.00109320436559941,
    1), NVDA = c(0.00139874293303574, 4), HOG = c(0.000699507074667968,
    2), WMT = c(0.000964557826996342, 3), AMZN = c(0.00100980845937234,
    3)), row.names = c(NA, -2L), class = c("tbl_df", "tbl", "data.frame"
)), `2013 Sep` = structure(list(AAPL = c(0.000874550640770086,
3), AMD = c(0.00212896308150426, 5), ADI = c(0.000297401899798995,
1), ABBV = c(0.00126327568847214, 4), A = c(0.00097767693668047,
3), APD = c(0.00143416399096666, 5), AA = c(-0.000734440361937234,
1), CF = c(-0.000254998800234454, 1), NVDA = c(0.00127259109916125,
4), HOG = c(0.00105093597431519, 3), WMT = c(0.00038339075327491,
2), AMZN = c(0.000479002073488143, 2)), row.names = c(NA, -2L
), class = c("tbl_df", "tbl", "data.frame")), `2013 Oct` = structure(list(
    AAPL = c(0.000682565466572836, 2), AMD = c(0.00313699867162714,
    5), ADI = c(0.000209923665516306, 1), ABBV = c(0.000865756791407934,
    2), A = c(0.00161631482825611, 4), APD = c(0.00168294315897343,
    5), AA = c(-0.000319519044240903, 1), CF = c(0.00096163857613333,
    3), NVDA = c(0.00158604314072248, 4), HOG = c(0.00151424115101764,
    3), WMT = c(0.00000265229900199134, 1), AMZN = c(0.00124777917896926,
    3)), row.names = c(NA, -2L), class = c("tbl_df", "tbl", "data.frame"
)), `2013 Nov` = structure(list(AAPL = c(0.00138847413611967,
4), AMD = c(0.00131189086851618, 3), ADI = c(0.000998905149605624,
2), ABBV = c(0.00053428429850944, 1), A = c(0.0016278252466143,
4), APD = c(0.0018596391559994, 5), AA = c(0.000727945791304539,
1), CF = c(0.00128641077503917, 3), NVDA = c(0.000839077531026809,
2), HOG = c(0.00128443125529569, 3), WMT = c(-0.00000406995915300601,
1), AMZN = c(0.00279573900270221, 5)), row.names = c(NA, -2L), class = c("tbl_df",
"tbl", "data.frame")), `2013 Dec` = structure(list(AAPL = c(0.00176889092052374,
5), AMD = c(-0.000742603775364103, 1), ADI = c(0.00044132637464973,
1), ABBV = c(0.00113925715965696, 3), A = c(0.00135042334177499,
4), APD = c(0.00122867453428789, 3), AA = c(0.00102055404174894,
2), CF = c(0.00128611035428346, 3), NVDA = c(0.000674203471055744,
2), HOG = c(0.00164877495332821, 4), WMT = c(0.000671450466059644,
1), AMZN = c(0.00299158521138261, 5)), row.names = c(NA, -2L), class = c("tbl_df",
"tbl", "data.frame")))

EDIT:
Is it possible to make sure the numbers sum to 1? For example, currently we have:
$`2017 Aug`
# A tibble: 2 x 12
   AAPL   AMD   ADI  ABBV     A   APD    AA    CF  NVDA   HOG   WMT  AMZN
  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1     0   0       0     0     0     0   0     0     0     0       0     0
2     0   0.5     0     0     0     0   0.5   0.5   0.5   0.5     0

Which is correct. However I now see that there are four 0-5's. Is it possible to get the output as:
 $`2017 Aug`
    # A tibble: 2 x 12
       AAPL   AMD   ADI  ABBV     A   APD    AA    CF  NVDA   HOG   WMT  AMZN
      <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
    1     0   0       0     0     0     0   0     0     0     0       0     0
    2     0   0.20     0     0     0     0   0.20   0.20   0.20   0.20     0     0

A: As it is a list, we can loop through the list
map(lst1, ~ .x %>%
                mutate_all(~ case_when(. %in% c(5, 1) ~ .5,
                                        TRUE ~ 0)) )

Also, in this case, we can do this without case_when as well
map(lst1, ~ .x %>%
               mutate_all( ~ c(0, .5)[(. %in% c(5, 1)) + 1]))

If we need to make the columns sum to 1, one option is to subtract the first number from 1 for those cases which doesn't sum to 1 (as there are only two rows)
map(lst1, ~ .x %>%
            mutate_all(~ case_when(. %in% c(5, 1) ~ .5,
                                    TRUE ~ 0) ) %>%
            mutate_all(~ if(sum(.) != 1) replace(., 1, 1 - sum(.)) else .)  )

Or if we need to normalize the rows
map(lst1, ~ .x %>%
            mutate_all(~ case_when(. %in% c(5, 1) ~ .5,
                                    TRUE ~ 0) ) %>%
         pmap_dfr(., ~
                  {v1 <- c(...)
                   v2 <- if(sum(v1) > 1) replace(v1, v1 != 0, 1/sum(v1!=0)) else v1
                   as.list(v2)}))
#$`2013 Jul`
# A tibble: 2 x 12
#   AAPL   AMD   ADI  ABBV     A   APD    AA    CF  NVDA   HOG   WMT  AMZN
#  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#1   0     0       0   0       0     0   0     0       0     0     0     0
#2   0.2   0.2     0   0.2     0     0   0.2   0.2     0     0     0     0

#$`2013 Aug`
# A tibble: 2 x 12
#   AAPL   AMD   ADI  ABBV     A   APD    AA    CF  NVDA   HOG   WMT  AMZN
#  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#1   0     0       0   0       0     0   0     0       0     0     0     0
#2   0.2   0.2     0   0.2     0     0   0.2   0.2     0     0     0     0

#$`2013 Sep`
# A tibble: 2 x 12
#   AAPL   AMD   ADI  ABBV     A   APD    AA    CF  NVDA   HOG   WMT  AMZN
#  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#1     0   0     0       0     0   0     0     0       0     0     0     0
#2     0   0.2   0.2     0     0   0.2   0.2   0.2     0     0     0     0

#$`2013 Oct`
# A tibble: 2 x 12
#   AAPL   AMD   ADI  ABBV     A   APD    AA    CF  NVDA   HOG   WMT  AMZN
#  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#1     0   0     0       0     0   0     0       0     0     0   0       0
#2     0   0.2   0.2     0     0   0.2   0.2     0     0     0   0.2     0

$`2013 Nov`
# A tibble: 2 x 12
   AAPL   AMD   ADI  ABBV     A   APD    AA    CF  NVDA   HOG   WMT  AMZN
  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1     0     0     0   0       0   0     0       0     0     0   0     0
2     0     0     0   0.2     0   0.2   0.2     0     0     0   0.2   0.2

$`2013 Dec`
# A tibble: 2 x 12
   AAPL   AMD   ADI  ABBV     A   APD    AA    CF  NVDA   HOG   WMT  AMZN
  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1   0     0     0       0     0     0     0     0     0     0   0     0
2   0.2   0.2   0.2     0     0     0     0     0     0     0   0.2   0.2


text:
Q: ASP.NET MVC Form Validation using JavaScript >" %>

    Index

    Todays Cases

    <%= Html.Encode(ViewData["message"]) %>

<form action="/TodaysCases/Index" method="post" id="rxForm">

    <% foreach (var item in Model)
       { %>

            <%= Html.Encode(item.LastName+", "+item.FirstName) %>

            <%= Html.Encode(item.Age) %>

            <input type="checkbox" name="NoComments" id="<%= item.CaseNumber%>" />

            <input type="text" name="Comments" id="comment_<%= item.CaseNumber%>" />

                Yes

            <input name="CaseNumber" type="hidden" value="<%=item.CaseNumber %>" />

    <% } %>

<input type="submit" value="Sign" />
</form>

In my model depending on how many cases are scheduled for today I may have one and upto 15 cases. So the page when displayed will have upto 15 rows. Each row will have a check box and a comment field. What I want to achieve with Java Script is the client side validation. Of course I will do the server side validation as well.  If the box is checked, then it means no comments, so I want to clear the corresponding comment field. if the box is unchecked, I want to force the user to have put some comment before submission of the form. Basically if there is some comment the user puts some comments. If no comments he check the box, ie, take some action. How do I go about doing this in Javascript? I learnt jQuery thinking I could do it there but I could not figure it out. Any help is appreciated.

A: If you are using ASP.NET MVC 2.0 Beta, you can take advantage of the built-in, client-side validation that it provides.
http://haacked.com/archive/2009/11/19/aspnetmvc2-custom-validation.aspx


text:
Q: Transformation of dataframe applied on 3 variables I wrote several commands to transform a dataframe but i would like to simplify the code that I wrote in four parts. Part 1,2 and 3 are to make calculation of column 1, 2 and 3 (count the number of time a value is repeated for each column and complete for missing number comprised between 0 and the max of value of the three column). The fourth part is to join the previous output.
I would like to simplify it in order to make the transformation of the 3 column in one block of code instead of 4. Is it possible to do it without using function ?
Thank you in advance.
set.seed(1234)

# Data

A=sample(0:10, 20, replace = TRUE)
B=sample(0:10, 20, replace = TRUE)
C=sample(0:10, 20, replace = TRUE)

df=data.frame(A,B,C)

  A  B  C
1  9  2  0
2  5  3  5
3  4  9  7
4  8  4  2
5  4  1  5
6  5  7  0
7  3 10  0
8  1  3  8
9  6  2  7
10 5  6  9
11 9  8  0
12 5  2 10
13 3  5  7
14 7  3  9
15 3  7  5
16 3  9  2
17 4 10  8
18 7  1  2
19 3  4  5
20 7  5  8

# Count for A
df2=data.frame(A=0:max(max(df$A),max(df$B),max(df$C)))

df3_A= df %>%
  select(A) %>%
  group_by(A) %>%
  mutate(A_number= n()) %>%
  distinct(A_number, .keep_all = TRUE) %>%
  ungroup() %>%
  complete (df2)

df3_A$A_number[is.na(df3_A$A_number)]=0

# Count for B

df2=data.frame(B=0:max(max(df$A),max(df$B),max(df$C)))

df3_B= df %>%
  select(B) %>%
  group_by(B) %>%
  mutate(B_number= n()) %>%
  distinct(B_number, .keep_all = TRUE) %>%
  ungroup() %>%
  complete (df2)

df3_B$B_number[is.na(df3_B$B_number)]=0

# Count for C

df2=data.frame(C=0:max(max(df$A),max(df$B),max(df$C)))

df3_C= df %>%
  select(C) %>%
  group_by(C) %>%
  mutate(C_number= n()) %>%
  distinct(C_number, .keep_all = TRUE) %>%
  ungroup() %>%
  complete (df2)

df3_C$C_number[is.na(df3_C$C_number)]=0

# Join

df3= df3_A %>%
  left_join(df3_B, by=c("A"="B")) %>%
  left_join(df3_C, by=c("A"="C"))

A A_number B_number C_number
   <int>    <dbl>    <dbl>    <dbl>
 1     0        0        0        4
 2     1        1        2        0
 3     2        0        3        3
 4     3        5        3        0
 5     4        3        2        0
 6     5        4        2        4
 7     6        1        1        0
 8     7        3        2        3
 9     8        1        1        3
10     9        2        2        2
11    10        0        2        1

A: Using base: stack and table:
as.data.frame.matrix(table(stack(df)))
#    A B C
# 0  0 0 4
# 1  1 2 0
# 2  0 3 3
# 3  5 3 0
# 4  3 2 0
# 5  4 2 4
# 6  1 1 0
# 7  3 2 3
# 8  1 1 3
# 9  2 2 2
# 10 0 2 1

A: You can reshape to long, count the values by variables, then reshape back to wide filling missings with zero:
library(dplyr)
library(tidyr)

df %>%
  pivot_longer(cols = everything()) %>%
  count(name, value) %>%
  pivot_wider(values_from = n, values_fill = 0) %>%
  arrange(value)

# A tibble: 11 × 4
   value     A     B     C
   <int> <int> <int> <int>
 1     0     0     0     4
 2     1     1     2     0
 3     2     0     3     3
 4     3     5     3     0
 5     4     3     2     0
 6     5     4     2     4
 7     6     1     1     0
 8     7     3     2     3
 9     8     1     1     3
10     9     2     2     2
11    10     0     2     1

A: You can use vctrs::vec_count over the columns and then merge the data.frames altogether:
library(dplyr)
library(purrr)
df %>%
  mutate(across(A:C, factor, levels = 0:10, ordered = TRUE)) %>%
  map(vctrs::vec_count) %>%
  imap(~ {name <- paste0("count", .y) %>%
  rename_with(.x, ~ name, count)}) %>%
  reduce(full_join, by = "key") %>%
  replace(is.na(.), 0) %>%
  arrange(key)

output
   key countA countB countC
1    0      0      0      4
2    1      1      2      0
3    2      0      3      3
4    3      5      3      0
5    4      3      2      0
6    5      4      2      4
7    6      1      1      0
8    7      3      2      3
9    8      1      1      3
10   9      2      2      2
11  10      0      2      1


text:
Q: setting scroll position to a particular row of primefaces datatable with performance I have a data table with thousands of data. i have a search functionality. if I search a term, the row which contains the term has to be highlighted and scroll position should be on the row. it is working fine. but it takes too much of time to position the scrollbar. this leads to performance issue. can anyone help to fix this.
currently i have set style class to the match row. searching for the style class and calculating the position and setting it with jQuery.

var trElement = $("tr.found").first();
            var trParentElement = trElement.parent();
            var childTop = trElement.offset().top;
            var parentTop = trParentElement.offset().top;
            var scrollPos = childTop - parentTop;
            $('#table').scrollTop(scrollPos);

is there any other way?
thanks in advance.


text:
Q: One image moves when I center the other image
I'm new to coding and I'm trying to make a simple page consisting of a title, a map picture, a picture of a pin that will overlay the map picture on a certain spot (I'm doing it this way instead of just making a jpeg with the pin because it'll be moving around later), and some info text under it. For some reason, when I center the map image, the pin image starts moving around horizontally when I resize the window. Id really appreciate some help with this!
<!DOCTYPE html>

<title>CampusSpots York University</title>

 York University

Important Numbers
York Security (General):416-650-8000
York Security (Urgent): 416-736-5333
York goSAFE: 416-736-5454
Emergency: 911
For General Inquiries: 416-736-2100

A: You've change how you're centering the contents, so I will answer according to your new code. A couple of things:

*

*You're trying to center the first image by defining auto margins. That only works on block elements, but the img element is an inline element, so you have to make it block display: block. By the way, you can simply make all margins auto margin: auto since you don't really specify top and bottom margins, but your way is fine so I left it as is.

*Your second image must be position: absolute in order for it to overlap the first image. Now, if you want to center it, then use left: 50% and then give it a negative left margin equals to half of its width margin-left: -10px. This will make it exactly centered like the first image and they both will move together when resizing the window. If the second image should not be exactly in the center and it needs to be off the center to overlap some spot of the first image, then change the value of the left margin until you get the result you want (or you can do it scientifically by measuring how much off-center the spot on the first image is, then subtract half of the width of the second image and change the result to negative then assign that value to the left margin).
Here is a working example:

 York University

Important Numbers
York Security (General):416-650-8000
York Security (Urgent): 416-736-5333
York goSAFE: 416-736-5454
Emergency: 911
For General Inquiries: 416-736-2100


text:
Q: How to convert a list of Numpy arrays to a Pandas DataFrame I have a list of Numpy arrays that looks like this:
[400.31865662]
[401.18514808]
[404.84015554]
[405.14682194]
[405.67735105]
[273.90969447]
[274.0894528]

When I try to convert it to a Pandas Dataframe with the following code
y = pd.DataFrame(data)
print(y)

I get the following output when printing it. Why do I get all those zeros?
            0
0  400.318657
            0
0  401.185148
            0
0  404.840156
            0
0  405.146822
            0
0  405.677351
            0
0  273.909694
            0
0  274.089453

I would like to get a single column dataframe which looks like that:
400.31865662
401.18514808
404.84015554
405.14682194
405.67735105
273.90969447
274.0894528

A: I just figured out my mistake. (data) was a list of arrays:
[array([400.0290173]), array([400.02253235]), array([404.00252113]), array([403.99466754]), array([403.98681395]), array([271.97896036]), array([271.97110677])]

So I used np.vstack(data) to concatenate it
conc = np.vstack(data)

[[400.0290173 ]
 [400.02253235]
 [404.00252113]
 [403.99466754]
 [403.98681395]
 [271.97896036]
 [271.97110677]]

Then I convert the concatened array into a Pandas Dataframe by using the
newdf = pd.DataFrame(conc)

    0
0  400.029017
1  400.022532
2  404.002521
3  403.994668
4  403.986814
5  271.978960
6  271.971107

Et voilà!

A: There is another way, which isn't mentioned in the other answers. If you have a NumPy array which is essentially a row vector (or column vector) i.e. shape like (n, ) , then you could do the following :
# sample array
x = np.zeros((20))
# empty dataframe
df = pd.DataFrame()
# add the array to df as a column
df['column_name'] = x

This way you can add multiple arrays as separate columns.

A: You could flatten the numpy array:
import numpy as np
import pandas as pd

data = [[400.31865662],
        [401.18514808],
        [404.84015554],
        [405.14682194],
        [405.67735105],
        [273.90969447],
        [274.0894528]]

arr = np.array(data)

df = pd.DataFrame(data=arr.flatten())

print(df)

Output
            0
0  400.318657
1  401.185148
2  404.840156
3  405.146822
4  405.677351
5  273.909694
6  274.089453

A: Since I assume the many visitors of this post aren't here for OP's specific and un-reproducible issue, here's a general answer:
df = pd.DataFrame(array)

The strength of pandas is to be nice for the eye (like Excel), so it's important to use column names.
import numpy as np
import pandas as pd

array = np.random.rand(5, 5)

array([[0.723, 0.177, 0.659, 0.573, 0.476],
       [0.77 , 0.311, 0.533, 0.415, 0.552],
       [0.349, 0.768, 0.859, 0.273, 0.425],
       [0.367, 0.601, 0.875, 0.109, 0.398],
       [0.452, 0.836, 0.31 , 0.727, 0.303]])

columns = [f'col_{num}' for num in range(5)]
index = [f'index_{num}' for num in range(5)]

Here's where the magic happens:
df = pd.DataFrame(array, columns=columns, index=index)

            col_0     col_1     col_2     col_3     col_4
index_0  0.722791  0.177427  0.659204  0.572826  0.476485
index_1  0.770118  0.311444  0.532899  0.415371  0.551828
index_2  0.348923  0.768362  0.858841  0.273221  0.424684
index_3  0.366940  0.600784  0.875214  0.108818  0.397671
index_4  0.451682  0.836315  0.310480  0.727409  0.302597


text:
Q: Capture ESC in textbox I want to have the Esc key undo any changes to a textbox since it got focus.
I have the text, but can't seem to figure out how to capture the Esc key. Both KeyUp and KeyPressed don't seem to get it.

A: is this what you're looking for?
    string origStr = String.Empty;
    private void txtOrig_Enter(object sender, EventArgs e)
    {
        origStr = txtOrig.Text;
    }

    private void txtOrig_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == Convert.ToChar(Keys.Escape))
        {
            txtOrig.Text = origStr;
        }
    }

A: This should work. How are you handling the event?
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Escape)
    {
       MessageBox.Show("Escape Pressed");
    }
 }

Edit in reply to comment - Try overriding ProcessCmdKey instead:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
     if (keyData == Keys.Escape && myTextBox.Focused)
     {
         MessageBox.Show("Escape Pressed");
     }

     return base.ProcessCmdKey(ref msg, keyData);
}

A: Supposedly some keys are not considered "input keys" and so are not listened to by default. You need to handle PreviewKeyDown first to enable it.
myTextBox.PreviewKeyDown += (s, e) => {
   if (e.KeyCode == Keys.Escape) {
      e.IsInputKey = true;
      Debug.Print("ESC should get handled now.");
   }
};

However, results from testing say otherwise, so it may depend on framework version. For me, whether I do that or not, KeyDown does not get called for ESC, and whether I do that or not, KeyPress DOES get called for ESC. This is while a TextBox has focus, so it may also depend on the control.


text:
Q: Can't use PrimeFaces with Maven I added PrimeFaces to my pom.xml dependencies and in my project there is the jar file primefaces-4.0.jar.
Then I created a simple xhtml file with the following content:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:p="http://primefaces.org/ui">
<head>
</head>

<body>
    <p:spinner />
</body>

</html>

After deploying and calling the jsf file in my browser, I just get an simple input field, that has nothing to do with PrimeFaces. There are no error messages in my Eclipse console.
Can somebody help me? What could be the problem?

A: Try replacing <body> with <h:body>. Also, <h:head> should be used instead of <head>.
Refer to PrimeFaces Getting Started page.

A: For maven configure:
<dependency>
    <groupId>org.primefaces</groupId>
    <artifactId>primefaces</artifactId>
    <version>5.1</version>
</dependency>

web.xml configure
<servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>/faces/*</url-pattern>
    </servlet-mapping>

A: i got the same error, only when i cutted off the dependency by maven and inserted the jar i could see the correct rendering of the primefaces tags.


text:
Q: How do you ignore the safe area in UIKit? I know you use ignoresSafeArea() in SwiftUI to make some UI-element-frame dismiss the safe area. However, when using UIKit I don't know how to do it. I want to place a UILabel right below the actual screen, but I cannot see it because it is hidden behind the safe area.
import UIKit

class SignInViewController: UIViewController {

    private let headline = UILabel()

    override func viewDidLoad() {
        super.viewDidLoad()

        addLabel()
        view.backgroundColor = .black

    }

    func addLabel() {

        headline.text = "SmashPass"
        headline.textColor = UIColor.red
        headline.frame = CGRect(x: 0 , y: 0 , width: 243, height: 29)
        headline.textAlignment = .center

        // alignment
        headline.center.x = view.center.x
        headline.center.y = view.frame.minY - 10

        view.addSubview(headline)

    }

}

A: Learn about how to use Auto-Layout...
Here is your code, with modifications to use Constraints and Auto-Layout to place the label at the bottom of the view:
class SignInViewController: UIViewController {

    private let headline = UILabel()

    override func viewDidLoad() {
        super.viewDidLoad()

        addLabel()

        view.backgroundColor = .black
    }

    func addLabel() {

        headline.text = "SmashPass"
        headline.textColor = UIColor.red
        headline.textAlignment = .center

        // -- use Auto-Layout!
        // alignment
        //headline.frame = CGRect(x: 0 , y: 0 , width: 243, height: 29)
        //headline.center.x = view.center.x
        //headline.center.y = view.frame.minY - 10

        view.addSubview(headline)

        headline.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            // label uses full-width
            headline.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            headline.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            // constrain the label bottom to the view bottom
            headline.bottomAnchor.constraint(equalTo: view.bottomAnchor),
            // label height is 29-points
            headline.heightAnchor.constraint(equalToConstant: 29.0),
        ])

    }

}

Note: in general, we want to constrain elements with awareness of the Safe-Area...
Using that code, we'll get this on an iPhone 12 Pro (for example):

and, if we set headline.backgroundColor = .yellow so we can see the label's frame:


text:
Q: Android record all events I would like record all users events for test my application.
For example I would the keyboard events, screen tap events etc..
I know Robotium Recorder but I would like understand how it works


text:
Q: Prove a claim on a commutative property of a diagonal matrix with identical diagonal entries I'm trying to show this statement:

For a matrix to commute with all the others you need the matrix to be
scalar, i.e. diagonal with entries on the diagonal which are all the
same.

Suppose $A,B,\Lambda$ are $n \times n$ matrices. Suppose $\Lambda = \lambda I$, where $\lambda$ is a real number. How can I show that I can move $\Lambda$ anywhere, i.e. $AB\Lambda = A\Lambda B = \Lambda AB$?
I thought about doing this, but I'm not sure if I'm right:
$$ A B \Lambda = A B \lambda I = \lambda A B I $$
Since $I$ is the identity matrix, it can go anywhere.
I'm doubtful about this, since $\lambda I$ means you multiply all elements in a matrix by $\lambda$. Can we move $\lambda$ around like this?

A: Let $A,B \Delta \in M_{n \times n}(\mathbb{R})$ such that $\Delta=\lambda I$.
We claim that for any real number $\lambda$ and any matrix $A$ ,$\lambda A$=$A \lambda$
Let $\lambda A=(\lambda a_{ij})$ where $0 \leq i \leq n$ and $0 \leq j \leq n$, since
$a_{ij}\in \mathbb{R}, \lambda$ and it is a field then $\lambda a_{ij}=a_{ij} \lambda$ but
$a_{ij} \lambda$ are the entries of the matrix $A \lambda$ and then $\lambda A$=$A \lambda$.
And therefore you approach is correct
$AB\Delta=AB \lambda I=A \lambda BI=A \lambda IB$
And too you can prove the other equations.


text:
Q: Migrate Users from keycloak to Firebase with Python We have switched from Keycloak authentication to Firebase authentication and I need to migrate the users from Keycloak to Firebase using Python.
These users were stored by Keycloak in a Postgres DB. I used the Admin SDK to get the users out of the Postgres DB and have already successfully saved them to Firebase, using the instructions from Firebase: https://firebase.google.com/docs/auth/admin/import-users. The users are also successfully created and displayed in Firebase. The users who logged in with the identity provider like Google Auth. can log in without problems. Only those users who log in with email and password get an error message INVALID_PASSWORD, CODE:400.
My guess then was that the salt and/or hash are not passed correctly or that they are stored wrong (keycloak hashing alg.:pbkdf2_sha256 and iterations: 27500 (default value)).
When passing in Python to the firebase attributes: password_hash and password_salt a byte array is expected, which I convert with bytes(user.password_hash/.password_salt, encoding='utf-8') to a byte
array. In some posts (like https://github.com/firebase/firebase-admin-python/issues/182) I saw that I should decode the hash in base64 and after that it should already work.
users = []
for user in list_users:
    record = auth.ImportUserRecord(
        uid=user.uid,
        email= user.email,
        display_name= user.display_name,
        email_verified= user.email_verified,
        password_hash= None if user.password_hash is None else ab64_decode(bytes(user.password_hash, encoding='utf-8')),
        password_salt= None if user.password_salt is None else bytes(user.password_salt, encoding='utf-8'),
        provider_data= None if user.providers == [] else getProviderRecords(user.providers),
    )
    users.append(record)

But what I know is that keycloak already stores hash and salt in format base 64 into the DB. The salt was also tested by me with an online tool (https://8gwifi.org/pbkdf.jsp) and it could validate. When saving in Firebase I don't get an exception and I also reconstructed the saving of the hash (https://github.com/firebase/firebase-admin-python/blob/master/firebase_admin/_user_import.py).
However, there could be something wrong with auth.UserImportHash, but I also got this code from the Firebase instructions.
iteraions_round=27500
hash_alg = auth.UserImportHash.pbkdf2_sha256(rounds=iteraions_round)
try:
    result = auth.import_users(users, hash_alg=hash_alg)
    print('Successfully imported {0} users. Failed to import {1} users.'.format(
        result.success_count, result.failure_count))
    for err in result.errors:
        print('Failed to import {0} due to {1}'.format(users[err.index].uid, err.reason))
except exceptions.FirebaseError:
    # Some unrecoverable error occurred that prevented the operation from running.
    pass

Also, I output the users again before saving, but password_hash and password_salt are also saved with b'hash/salt' as in the Firebas instructions.

A: "If the salt is stored as a base64 encoded string, you have to decode that before passing it to Firebase. The code above only seems to decode the password hash." hiranya911
following code worked as expected:
...
password_hash= None if user.password_hash is None else ab64_decode(bytes(user.password_hash, encoding='utf-8')),
password_salt= None if user.password_salt is None else ab64_decode(bytes(user.password_salt, encoding='utf-8')),
...


text:
Q: Compile-time performance of constexpr computation I have some non-trivial C++17 functions marked as constexpr. They are doing graph-related computation (depth-first traversal) and general algorithms (e.g., find, sort, unique...).
If I try to force evaluation at compile-time by putting the result in a constexpr global variable, 3 things can happen:

*

*For small-size computation (to give an idea, lets say graphs of ~100 nodes, nodes being more or less integers) the compilation is fine (takes ~2s)

*With ~500 nodes, the compilation takes ~1min and takes 30GB of memory (!).

*With ~1000 nodes, the compilation requires too much memory for me to let it finish.

If I remove the constexpr qualifiers and ask for a run-time computation, compilation and execution are very fast (less than 5s)
I used g++ 8.2 with -O3 -std=c++17.
Why is it taking so long ? Is g++ known for compile-time optimization problems of constexpr ?
What performance should I expect from constexpr functions during compilation? From what I understand, the compiler turns itself into an interpreter for constexpr computations. But I have absolutely no doubt that evaluating the same program in Python would be very fast, given the very small size of the data.
Edit: Such problems are mentionned here (Blog of a GCC developer)

A: g++ memoizes compile time structures.  What more, compile time structures may be created and inspected along both the branch you want to take, and the one you do not, unless you are careful.
Exponential blowup is quite possible, and may be what you are seeing.
There are strategies to reduce compile time complexity.  Avoid deep recursion.  Pay attention to accumulated symbol length.  Ensure that only the branches you want to take have to be examined.
I mean, examine a really simple:
std::conditional_t< (A<B), make_type_A<Ts...>, make_type_B<Ts...> >

The writer of this code probably intended to make only one type, but this code requires that both types be created.
This is unlikely to be your problem, but a similar problem could occur when running constexpr code.
For each call, work out the size of the state required.  Add up the total state needed.  Throw in a 10x overhead.
You can also analyze what the O-notation of your problem is by having more samples than 2 completed.  Check 100, 200, 300, 400, 500 size graphs.  Try linear graphs, trivial graphs, complete graphs, random graphs with constant or percentage connectivity.
The O-notation of the growth in compile time might help you narrow down where the problem is.  If it is linear, polynomial or exponential you are going to be looking at different kinds of problems.
Linear with a sharp inflection means you are hitting a resource bottleneck.  Maybe memory.  Start graphing other resource usage and see if you can find the bottleneck.
Exponential looks a lot like linear with a cliff if you don't log-graph it and zoom in on the "cliff".  There may be a narrow portion where the exponential part leaves the constant factor behind.
Polynomial gets interesting.  The order of the polynomial (log graph can help find that) can tell what kind of operation is screwing you over.  Much like knowing your conventional algorithm is O(n^3) means you are looking for a triple-loop.  An O(n^3) compile time means you are somehow instantiating the equivalent of a triple-loop.


text:
Q: What does "spun off" in "Presuppose that the little body of dissenters suddenly spun off no less than a majority" mean? "William F. Buckley—the movement's Max Eastman, its most brilliant pamphleteer—predicted Goldwater's landslide defeat. His candidacy, like the revolution of 1905, had come too soon, but it foretold the victory to come. At a Young Americans for Freedom convention, Buckley exhorted an audience of true-believing cadres to think beyond November: 'Presuppose that the fiery little body of dissenters, of which you are a shining meteor, suddenly spun off no less than a majority of all the American people, who suddenly overcome a generation's entrenched lassitude, suddenly penetrated to the true meaning of freedom in society where the truth is occluded by the verbose mystification of thousands of scholars, tens of thousands of books, a million miles of newsprint.' Then Goldwater's inevitable defeat would turn into 'the well planted seeds of hope, which will flower on a great November day in the future, if there is a future.'"
--the Atlantic


text:
Q: No \p{L} for JavaScript Regex ? Use Unicode in JS regex I nedd to add a-zA-ZáàâäãåçéèêëíìîïñóòôöõúùûüýÿæœÁÀÂÄÃÅÇÉÈÊËÍÌÎÏÑÓÒÔÖÕÚÙÛÜÝŸÆŒ x time but I find this very ugly. So I try \p{L} but it does not working in JavaScript.
Any Idea ?
my actual regex : [a-zA-ZáàâäãåçéèêëíìîïñóòôöõúùûüýÿæœÁÀÂÄÃÅÇÉÈÊËÍÌÎÏÑÓÒÔÖÕÚÙÛÜÝŸÆŒ][a-zA-ZáàâäãåçéèêëíìîïñóòôöõúùûüýÿæœÁÀÂÄÃÅÇÉÈÊËÍÌÎÏÑÓÒÔÖÕÚÙÛÜÝŸÆŒ' ,"-]*[a-zA-ZáàâäãåçéèêëíìîïñóòôöõúùûüýÿæœÁÀÂÄÃÅÇÉÈÊËÍÌÎÏÑÓÒÔÖÕÚÙÛÜÝŸÆŒ'",]+
I want to have a thing like that : [\p{L}][\p{L}' ,"-]*[\p{L}'",]+ (or smaller than the actual expression)

A: What you need to add is a subset of what you asked for. First you should define what set of characters you need. \pL means every letter from every language.
It's kind of ugly but doesn't affect performance and rather the best solution to get around such kind of problems in JS. ECMA2018 has a support for \pL but way far to be implemented by all major browsers.
If it's a personal taste, you could reduce this ugliness a bit:
var characterSet = 'a-zA-ZáàâäãåçéèêëíìîïñóòôöõúùûüýÿæœÁÀÂÄÃÅÇÉÈÊËÍÌÎÏÑÓÒÔÖÕÚÙÛÜÝŸÆŒ';
var re = new RegExp('[' + characterSet + ']' + '[' + characterSet + '\' ,"-]*' + '[' + characterSet + '\'",]+');

This update credits go to @Francesco:

var pCL = 'a-zA-ZáàâäãåçéèêëíìîïñóòôöõúùûüýÿæœÁÀÂÄÃÅÇÉÈÊËÍÌÎÏÑÓÒÔÖÕÚÙÛÜÝŸÆŒ';
var re = new RegExp(`[${pCL}][${pCL}' ,"-]*[${pCL}'",]+`);
console.log(re.source);

A: You have XRegExp addon to support unicode letter matcher:
var unicodeWord = XRegExp("^\\pL+$"); // L: Letter

Here you can see more example matching unicode in javascript
http://xregexp.com/plugins/


text:
Q: No implicit conversion of Symbol into Integer only happening sometimes Can someone explain what I'm doing wrong!?
   if response[:result]
      response[:credentials].each do |cred|

        AntHQ.logger.debug "==> #{cred}"
        c = app_instance.credentials.find_by(name: cred[:name])

        if c && cred[:value]
          c.value = cred[:value]
          c.expiry = cred[:expiry]
          c.save!
        end
      end
    end

Error
TypeError: no implicit conversion of Symbol into Integer

File "/usr/local/lib/ruby/gems/2.1.0/bundler/gems/ant_light_tasks-01095a3ea065/lib/ant_light_tasks/app/update_credentials.rb" line 16 in []

Line 16:
 c.value = cred[:value]

Example "response":
{:result=>true, :credentials=>[{:name=>"access_token", :value=>"...", :expiry=>"..."}]}

A: Hi guys I appreciate your answers.
The real cause was because our jenkins agent wasn't deploying the code to all our instances.


text:
Q: MVC.net Dynamic bootstrap Modal content call another cshtml file but the javascript in the partial view is not working I have page with table list of employee, when the user click one of the list, its trigger a function to create a modal and call a partial view from controller based on the item clicked and send the parameter,
im using @url.Action to send the parameter to the javascript to generate the modal and it shows correctly,
however all the javascript inside the partial view is not working.
How to enable all the script within the partialview cshtml file (ViewPMEmployee)?
Html

                @foreach (var item in Employee)
                {

                            <input type="checkbox" name="cb" value="@item.EmployeeCd" onclick="return EmployeeProperties('@item.EmployeeCd')" />

                            @*@item.EmployeeCd.ToString()*@
                            @item.EmployeeCd.ToString()

                            @item.EmployeeNm

                }

Javascript
$(function () {

    $('body').on('click', '.modal-link', function (e) {
        e.preventDefault();
        $("#myModal").remove();
        $(".modal-backdrop").remove();

        $.get($(this).data("targeturl"), function (data) {
            $('
' +
                '
' +
                '
' +
                '

Modal Heading
<button type="button" class="close" data-dismiss="modal">×</button>
' +
                '
' +
                data + '
' +
                '
<button type="button" class="btn btn-default" data-dismiss="modal"> Close</button >

').modal();
            $(".modal-backdrop").addClass("d-none");
                            });
                        });
});

A: You can simply place the partial view javascript code above the HTML section within the partial view. Or you can move the Code in a separate javascript file and include the script in partial view above the partial view HTML. hopefully, it works.


text:
Q: Reference to application users always returning null even though included My Club has many members so I have added the following virtual property Members my question is when I want to list the club members shouldn't adding just the virtual load this into lazy loading am using .net 5.0.1 at present.
var members =  _context.Clubs.Include(c=>c.Members).Where(w => w.ClubId == tennantId ).ToList();

When I look at var members even when the members have been included it is zero even though the teannatId matches.
public class MSFSAddonDBContext : IdentityDbContext<ApplicationUser>
{
    public MSFSAddonDBContext(DbContextOptions<MSFSAddonDBContext> options)
    : base(options)
    {
    }
     public DbSet<Club> Clubs { get; set; }
     public virtual List<ApplicationUser>? Members { get; set; }
    }

This is my controller method.
public void  IActionResult ClubMembers()
{
    var tennantId =  GetTennantId().Result;
    var members =  _context.Clubs.Include(c=>c.Members).Where(w => w.ClubId == tennantId ).ToList();
    return View(members);
}

There are two members references at top level and inside the clubs.
This is the club class
public  class Club
{
    public int Id { get; set; }
    public Guid? TeannatId { get; set; }
    public Guid? ClubId { get; set; }
    public Guid? UserId { get; set; }
    public string? Name { get; set; }
    public string? Description { get; set; }
    public string? Url { get; set; }
    public int? ClubLikes { get; set; }
    public int? ClubDislikes { get; set; }
    public int? MembersCount { get; set; }
    public string? Logo { get; set; }
    public List<Flight>? Flights { get; set; }
    public string? ThumbNail { get; set; }
    public DateTimeOffset? GpdrRemoveRequestDate { get; set; }
    public bool? isGpdrRemoveRequest { get; set; }
    public DateTimeOffset? BannedTime { get; set; }
    public TimeSpan? BanPeriod { get; set; }
    public bool? isBanned { get; set; }
    public bool? isActive { get; set; }
    public bool? isDeleted { get; set; }
    public DateTime? CreatedDate { get; set; }
    public string? CreatedBy { get; set; }
    public virtual List<ApplicationUser>? Members { get; set; }
}

Edit 2
This is the application user class.
public class ApplicationUser : IdentityUser
{
    public enum UserTypeEnum
    {
        Guest=0,
        User=1,
        Author=2,
        AddonOwner=3,
        GroupOwner=5,
        ClubMember=6,
        ClubAdmin=7,
        SuperAdmin=199,
        BandUser=999
    }
    public string? FirstName { get; set; }
    public string? LastName { get; set; }
    public string? GamerTag { get; set; }
    public bool? isOnline { get; set; }
    public int? UserType { get; set; }
    public Guid? TennantId { get; set; }
    public Guid? ClubId { get; set; }
    public List<Badges>? Badges { get; set; }
}

NB As always with ef the primary keys in all my tables are the Id column thanks


text:
Q: Can't run included js file I am running a project and need to allow the users change their own passwords. But I include the popup for my change password form at the very beginning of my php file. And include the other (.js) files at the bottom of my PHP file.
So, when i insert the js code for my change password AJAX just after the FORM i get "undefined $" error (which means i didnt include jquery). I include my .js file at the bottom but it doesnt detect my "click" on the specified button. What did i do wrong?
change_password.js file:
$('#change_password_submit').on('click',function() {

    alert('OK!');

    $('#change_password_form').removeClass("has-error");
    $('#change_password_confirm_form').removeClass("has-error");

    if($("#change_password").val()=="" || $("#change_password").val()==" ")
    {
        $.smallBox({
            title : "Failed",
            content : " Define a password.",
            color : "#C46A69",
            iconSmall : "fa fa-times fa-2x fadeInRight animated",
            timeout : 4000
        });
        $('#change_password_form').addClass("has-error");
        return false;
    }
    if($("#change_password_confirm").val()=="" || $("#change_password_confirm").val()==" ")
    {
        $.smallBox({
            title : "Failed",
            content : " Confirm your password.",
            color : "#C46A69",
            iconSmall : "fa fa-times fa-2x fadeInRight animated",
            timeout : 4000
        });
        $('#change_password_confirm_form').addClass("has-error");
        return false;
    }
    if($("#change_password_confirm").val() != $("#change_password").val())
    {
        $.smallBox({
            title : "Failed",
            content : " Passwords does not match.",
            color : "#C46A69",
            iconSmall : "fa fa-times fa-2x fadeInRight animated",
            timeout : 4000
        });
        $('#change_password_confirm_form').addClass("has-error");
        return false;
    }

    $.SmartMessageBox({
        title   : " Confirmation!",
        content : "Do you want to edit the user?",
        buttons : '[No][Yes]'
    },
    function(ButtonPressed)
    {
        if (ButtonPressed === "Yes")
        {
            $.ajax({
                type: 'POST',
                url: 'user_func.php',
                data :
                {
                    'password'                  : $('#change_password').val(),
                    'password_confirm'          : $('#change_password_confirm').val(),
                    'ajax_action'               : 'change_password'
                },
                success: function(msg)
                {
                    if (msg == "no_match") {
                        $.smallBox({
                            title : "Failed",
                            content : " Passwords does not match.",
                            color : "#C46A69",
                            iconSmall : "fa fa-times fa-2x fadeInRight animated",
                            timeout : 4000
                        });
                    } else {
                        $.smallBox({
                            title : "Success",
                            content : " Password changed successfully.",
                            color : "#659265",
                            iconSmall : "fa fa-check fa-2x fadeInRight animated",
                            timeout : 4000
                        });
                    }
                }
            });
        }
        if (ButtonPressed === "No")
        {
            $.smallBox({
                title : "Cancelled",
                content : " Change cancelled.",
                color : "#C46A69",
                iconSmall : "fa fa-times fa-2x fadeInRight animated",
                timeout : 4000
            });
        }
    });
});

my change password for at the top:

    <form action='noaction();' class='form-horizontal'>

                    <input type='password' id='change_password' name='change_password' placeholder='New Password' class='form-control'>

                    <input type='password' id='change_password_confirm' name='change_password_confirm' placeholder='Confirm Password' class='form-control'>

    </form>

            <button id='change_password_submit' class='btn btn-block btn-primary change_password_submit'>Submit</button>

and this is how i include my js file at the very bottom of the page:

A: If you wrap your script in a $(document).ready(function () {});?


text:
Q: recognize the sound that is playing on my computer I want to recognize the sound that is playing on my computer. What should I do?
import speech_recognition
import pyaudio
from speech_recognition import *
import os

r = Recognizer()
m = Microphone()

with m as source:
            print('start recognize')
            audio = r.listen(source)
            try:
                Text = r.recognize_google(audio)
                print(Text)
            except:
                print('error')


text:
Q: Resharper Shortcuts for Create Class and Move Class To New File What are the Resharper 4 shortcuts to

*

*Create a class from usage?  e.g. I type "var p = new Person();", and I want to now create the person class.

*Move this class to its own file?  When the Person class exists in the same file next to my Order class, what is the shortcut to move it.
I can't seem to find these shortcuts on the cheatsheet or the Internet.

A: Type the line out:
var p = new Person();

Person will be highlighted in red as an error by ReSharper.  Put the caret on it and press ALT+ENTER to invoke the quick-fix context menu.  Select Create class 'Person'.
The cursor will then be on the new class' name, so press ALT+ENTER again to invoke the context-sensitive quick-fix menu again and select Move to another file to match type name.
That's just two actions - really quick and easy.  After a while, it (like most R# commands) becomes muscle memory.  Like driving, walking or chewing gum.
FOR BONUS POINTS
The above is all you need to do what you wanted, but you can take it a step or two further:

*

*If you'd rather the class was moved to a different namespace, you can press SHIFT+CTRL+R and select Modify Namespace....

*If you'd rather the class was moved to a different project entirely, you can press SHIFT+CTRL+R and select Move to Folder....
The great thing is - ReSharper will make all necessary changes to namespaces to make sure things still compile.  With one gotcha - only if the project you move the classes to is referenced by the one you move them from.  You have two choices

*

*Go ahead with the refactoring and use ReSharper quick-fixes to both add the reference and import namespaces in one go (if it's a new class, I'd do this because it'll be the only usage).

*Add the reference manually before moving them and it'll do it all for you.


text:
Q: What does the phrase "by the time token" mean? I saw the sentence "by the time token" in a physics textbook. The original sentence is:

By the time token, if E < V(and V is constant), then Y is exponential.

In Cambridge Dictionary, "token" means "symbol", but obviously it doesn't suit the context here. Can anyone please explain what the phrase means?

A: I'm going to go with Cookie Monster on this one and suggest it's a misprint.  The common expression is "by the same token", meaning "in the same way".

If I leave my house at 5 in the morning, I can beat the traffic and get to work in half an hour.  By the same token if I leave work before 3, I can get home in the same amount of time.

It's possible that "time token" has a specific meaning in the textbook, which would have been earlier defined, but there isn't enough context in your example to be sure.


text:
Q: CSS change style base on valid input I'm new to CSS and I will appreciate any help.
I'm trying to style the asterisk * inside the span element of a required element based on the input:valid property.
<input value="someValue" id="firstnameId" required />

    First Name
    *

I tried to do :
input:valid .ddff {
    color: palegreen;
}

But it's not working.
I want to change the color of the * from red to green if the input is valid or keep it red otherwise.
How can I achieve it using CSS?
Thanks!

A: your css is inline, try with !important

input:valid + label .ddff {
      color: palegreen !important;
 }
<input value="someValue" id="firstnameId" required />
    First Name
    *

A: You can use :valid and :invalid selector for form elements with limitation such as required.
Try this:

input[required]:invalid + label:after{content:"*";color:red}
input[required]:valid + label:after{content:"*";color:green}
<input placeholder="Placeholder" required />
 First Name

A: it can works because .ddff is not an input child
<input value="someValue" id="firstnameId" required />
    First Name
    *

.ddff{
      color: red;
}
input:valid + label .ddff {
      color: green;
 }

input:invalid +label .ddff {
      color: red;
 }

A: Your CSS selector is not correct, you have to use the Adjacent sibling combinator:

input + label .ddff {
    color: red;
}

input:valid + label .ddff {
    color: palegreen;
}
<input value="someValue" id="firstnameId" required />

    First Name
    *

A: can you please try:
CSS:
input:valid + label span.ddff {
      color: palegreen !important;
 }

Note: You can use an inline CSS. please overwrite your CSS.


text:
Q: How to model relationships in scenario where every product can (don't have to) be associated to only one category This one still occupies my mind. How do you model 1:N relationships.
Consider having a category and product (typical e-commerce scenario).
Every product can (don't have to) be associated to only one category.
Should I model such relationship as: (pseudo-code)
Product
{
    Category category;
}

Category {}

or on Category's side:
Category
{
    Product[] products;
}

Product {}

Second way seems more logical (products are organized in categories) but brings other problems (imagine category with 10k products and every time you want to add product to collection, you must check whether it contains that product or not.
The first way makes it easier. There is always one Category and Product in memory, but Category entity without behavior seems awkward.
Any suggestions?


text:
Q: Using the denseness of trigonometric polynomials to prove the following $f:[0,2\pi] \to \mathbb R$ is a continuous function. For every trigonometric function $T(x)=\sum_{k=0}^n a_k\cos(kx)+b_k\sin(bx)$, we have $\int_0^{2\pi}f(x)T(x)dx=0$. We need to prove $f=0$(and I wonder whether it is just $f=0$ a.e.)
Anyways, my consideration is that since $T(x)$ is dense in $C([0,2\pi],\mathbb R)$ which is equipped with sup norm, we have some $T(x)$ that is "almost" $f(x)$. So we can have something looks like $\int_{0}^{2\pi}f^2=0$, which gives $f=0$ a.e. But it is not precise and I got stuck here. Can anyone help out with this?

A: Let $\epsilon > 0$. Choose a trigonometric polynomial $T$ such that $\|f - T\| < \epsilon$. Then
$$\int_0^{2\pi} f^2(x)\, dx = \int_0^{2\pi} f^2(x)\, dx - \int_0^{2\pi} f(x)T(x)\, dx = \int_0^{2\pi} f(x)(f(x) - T(x))\, dx,$$
and
$$\int_0^{2\pi} f(x)(f(x) - T(x))\, dx \le \int_0^{2\pi} |f(x)| |f(x) - T(x)|\, dx <\epsilon \int_0^{2\pi} |f(x)|\, dx.$$
Thus
$$\int_0^{2\pi}f^2(x)\, dx < \epsilon \int_0^{2\pi} |f(x)|\, dx.$$
Since the latter inequality holds for all $\epsilon > 0$, $\int_0^{2\pi} f^2(x)\, dx = 0$. As $f^2$ is nonnegative and continuous on $[0,2\pi]$, $f^2 \equiv 0$. Hence $f \equiv 0$.

A: You want too much.  Think of du Bois-Reymond's Lemma:
$$
\int f(x)\phi(x)d x=0\text{ for all smooth }\phi
\implies
f=0.
$$
(What's wrong with "density"?)


text:
Q: React Toggle Button color attribute I'm trying to change the color attribute for ToggleButton in React.
I'd like to to do something like
<ToggleButton color='primary' />
The ToggleButton API is not currently supporting this option. A workaround that I found was overriding the MuiToggleButton CSS class.
const theme = createMuiTheme({
    overrides: {
        MuiToggleButton: {
            root: {
                color: 'rgba(50, 72, 86, 0.38)',
                '&$selected': {
                    backgroundColor: 'rgba(50, 72, 86, 0.12)',
                    color: 'rgba(50, 72, 86, 1)',
                    '&:hover': {
                        backgroundColor: 'rgba(50, 72, 86, 0.15)',
                    },
                },
            },
        },
    },
}

This solution overrides all the ToggleButton so it might be problematic in some situations.

A: You can create a custom Toggle component and apply the corresponding color from the theme
import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import ToggleButton from "@material-ui/lab/ToggleButton";
import ToggleButtonGroup from "@material-ui/lab/ToggleButtonGroup";

const useStyles = makeStyles((theme) => ({
  root: (props) => {
    return {
      color: theme.palette[props.color].main
      // some other custom styles
    };
  }
}));

function MyToggleButton(props) {
  const { color, ...other } = props;
  const classes = useStyles({ color });
  return <ToggleButton classes={classes} {...other} />;
}

export default function CustomColorToggle() {
  const [color, setColor] = React.useState("primary");
  const handleColor = (e, value) => setColor(value);
  return (
    <ToggleButtonGroup
      onChange={handleColor}
      value={color}
      exclusive
      aria-label="text alignment"
    >
      <MyToggleButton color="primary" value="primary">
        Primary
      </MyToggleButton>
      <MyToggleButton color="secondary" value="secondary">
        Secondary
      </MyToggleButton>
    </ToggleButtonGroup>
  );
}

https://codesandbox.io/s/custom-color-toggle-7r0mf?file=/demo.js:0-1037


text:
Q: Multiple Key KeyStroke for Menu Shortcuts in Java I am working on a program that maintains data for multiple different purposes, such as loads, vehicle service, brokers, customers, fuel purchases, as well as other types of purchases.
To this end, I have used a JMenu to contain the menu items for creating these new data items. So, the user can press, for example, ALT+N, L to open the new load wizard. This is just simple menu navigation.
Is there also a way to create a keyboard shortcut, such as CTLR+N, L that would do basically the same thing, but without opening the menus?
What I mean is, the user presses CTLR+N and the system waits for another key, which would be L for new loads, B for new broker entry, etc. I was using some program (I can't remember which program off-hand) that had functionality like this. I don't know what language it was written in, but I remember thinking that it was cool that the developers had created multiple hot keys based off of standard keyboard shortcuts by simply waiting for a third key to be pressed separately from the CTRL+${KEY} combination.
I have been searching online for an idea of how to accomplish this feat, but am not seeing anything close to what I am looking for. Just to be clear about what I am trying to do, look at the following:

*

*I have a module for handling the load tracking data, which comes with a wizard for entering new loads. To launch this wizard, I would like the keyboard shortcut to be displayed on the New...Load Wizard menu item as CTRL+N, L. When the user presses CTRL+N the application waits to see what key is pressed next. If the next key pressed is N, then the New Load Wizard is launched.

*I have a module for handling the broker data, which has a data entry dialog for entering new brokers. To open this dialog, I would like the keyboard shortcut to be displayed on the New...Broker menu item as CTRL+N, B. When the user presses CTRL+N the application waits to see what key is pressed next. If the next key pressed is B, then the New Broker dialog is displayed.

*I have a module for handling vehicle services, maintenance, and repairs, which has a single dialog for entering the information regarding these purchases. I would like the keyboard shortcut to be displayed on the New...Service/Repair menu item as CTRL+N, S. When the user presses CTRL+N the application waits to see what key is pressed next. If the next key pressed is S, then the New Service/Repair dialog is opened.

*There will be a similar menu item under the New menu for the other modules in the application, which should function the same way.

*If the key pressed after the CTRL+N KeyStroke is not one of the available single shortcut keys displayed on the various New menu items, then it cancels the wait for the next key press. In other words, if the user presses CTRL+N, then presses, for example, Z (which has no menu item associated with it) the CTRL+N is simply discarded.

I am not sure if I have explained what I am trying to do clearly enough, so am more than willing to answer questions to allow for better understanding of my thoughts. Even so, any ideas or thoughts are greatly appreciated!
-SC

A: This is how I did it.
I set a flag after the user presses Ctrl+N and then if the user presses b, perform the appropriate action if the flag is set.
The below code is simply a proof of concept (POC).
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;

import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.BorderFactory;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.KeyStroke;

public class BindKeys {
    private boolean  flag;
    private JTextField  textField;

    private JPanel createButton() {
        JPanel panel = new JPanel();
        JButton button = new JButton("Exit");
        button.addActionListener(e -> System.exit(0));
        panel.add(button);
        return panel;
    }

    private JPanel createTextField() {
        JPanel panel = new JPanel();
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        textField = new JTextField(12);
        InputMap im = textField.getInputMap();
        KeyStroke ctrlN = KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_DOWN_MASK);
        im.put(ctrlN, "SET_FLAG");
        KeyStroke b = KeyStroke.getKeyStroke('b');
        im.put(b, "NEW_BROKER");
        ActionMap am = textField.getActionMap();
        am.put("SET_FLAG", new CtrlNAction());
        am.put("NEW_BROKER", new BAction());

        panel.add(textField);
        return panel;
    }

    private void showGui() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(createTextField(), BorderLayout.PAGE_START);
        frame.add(createButton(), BorderLayout.PAGE_END);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    private class BAction extends AbstractAction {
        public void actionPerformed(ActionEvent event) {
            if (flag) {
                textField.setText("New broker");
            }
            else {
                textField.setText(textField.getText() + "b");
            }
        }
    }

    private class CtrlNAction extends AbstractAction {
        public void actionPerformed(ActionEvent event) {
            flag = true;
        }
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> new BindKeys().showGui());
    }
}

Refer to How to Use Key Bindings


text:
Q: Add Email Functionality to Custom Component I'm creating a custom LWC component and would like to add email functionality similar to the native experience within Salesforce, for example on the Activity component within a contact.
For example, this is the email tab I'm referring to, which i can find on a contact within my Salesforce instance.

Is there a way to add the above Email tab component to my custom LWC component? Or, is it possible to add the entire Activity component (which houses the Email tab shown above) within my custom LWC?

A: You can search the component library for all the reusable components. These two are not part of that library
https://developer.salesforce.com/docs/component-library/overview/components
What you'll need to do is

*

*Query the Feed object and re-create the activity component

*Create a custom UI to send emails similar to Salesforce and use SingleEmail in Apex to send the emails


text:
Q: how to import LDAP user passwords into keycloak I'm having a problem with an integration of IDAP users to keycloak, it imports all users and their information, it just can't log in with users already registered in IDAP using the same password and user and in keycloak the information appears normally but the credentials are empty, can anyone help me?

A: LDAP's user password did not save into Keycloak. Keycloak ask to LDAP server when user Login even if all other information import into Keycloak.
This is source code for checking password in LDAP.
And here official documentation said in Lightweight Directory Access Protocol (LDAP) and Active Directory
An exception exists for synchronizing passwords. Keycloak never imports passwords. Password validation always occurs on the LDAP server.


text:
Q: Using -XGeneralizedNewtypeDeriving with -XMultiParamTypeClasses The following code results in an error:
{-# LANGUAGE GeneralizedNewtypeDeriving, MultiParamTypeClasses, StandaloneDeriving #-}

class Module a b where
    (*>) :: a -> b -> b

data D
newtype DWrapper = DW D
instance Module D D
deriving instance Module DWrapper DWrapper

The error:
No instance for (Module DWrapper D) arising from a use of 'Main.*>'
In the first argument of 'GHC.Prim.coerce', namely
  '(Main.*>) :: DWrapper -> D -> D'
In the expression:
    GHC.Prim.coerce ((Main.*>) :: DWrapper -> D -> D) ::
      DWrapper -> DWrapper -> DWrapper
In an equation for '*>':
    (*>)
      = GHC.Prim.coerce ((Main.*>) :: DWrapper -> D -> D) ::
          DWrapper -> DWrapper -> DWrapper
When typechecking the code for  'Main.*>'
  in a derived instance for 'Module DWrapper DWrapper':
  To see the code I am typechecking, use -ddump-deriv

So GHC is looking for a Module DWrapper D instance to derive the requested Module D D instance. This is reasonable I guess, but not what I intended. Is there a way to tell GHC which instance to derive from? How does GNTD work on MPTCs?

A: Unfortunately, GeneralizedNewtypeDeriving only works on the last parameter of a multi-parameter typeclass. Even with standalone deriving:

*

*The stand-alone syntax is generalised for newtypes in exactly the same way that ordinary deriving clauses are generalised (Section 7.5.5, "Generalised derived instances for newtypes"). For example:
newtype Foo a = MkFoo (State Int a)
deriving instance MonadState Int Foo

GHC always treats the last parameter of the instance (Foo in this example) as the type whose instance is being derived.

(BTW, I tried searching for any relevant GHC trac bug report or feature request, but couldn't find any.)


text:
Q: How do i preview a TextView? Good day,
I am trying to add a textview preview to my app. For example, i created a news app with card view and I want to have a few lines on the first screen and then it expands the full story in a new activity onclick.
I have already set up the new activity part but I just need the preview on the first screen

A: You should have all the News data available on your first Activity - NewsActivity.
In that case you just

*

*Limit number of lines of preview TextView with attribute android:maxLines="3"

*Then on click on TextView you would open another activity with an Intent and inside the Intent pass whole News object that corresponds to data displayed in preview TextView. Remember that News object should be implement Serializable or Parcelable interfaces to be passed with intent.

*Retrieve data from an Intent and display it in the second Activity - NewsDetailsActivity


text:
Q: Turn on a iOS hotspot without 3G connection Is it possible to turn on my hotspot on my iPhone 5s (running iOS 8) without wifi or 3G connection?
I would like people to connect to my network to play LAN games while overseas. However, I do not want to turn on my 3G so as to save money from the data charges. Is there any way to turn on your hotspot while your 3G/4G is off without jailbreaking?

A: In short, No.
The iPhone's hotspot only works with your carrier, 3G, 4G etc, it doesn't operate over Wifi.
I've never Jailbroken, so I don't know if that would help.


text:
Q: How Should I Find Statistically Significant Differences Between Two Markov Models? Suppose I have N Markov Models of M states representing the behaviour patterns of 2 different groups (note: fully observable models, no hidden states), and have stored each model as a matrix of transition probabilities for a particular test subject.
I would like to test whether the transition probability from any one state to any other is different in one group than the other.
My first thought was to treat each of the MxM transition probabilities as a random variable, and test each hypothesis (i.e. that the means of the RVs differed) independently. The variable is a probability akin to one of the parameters of a multinomial distribution, so a binomial proportion-based confidence interval seems applicable. A correction for testing MxM hypothesises simultaneously from the same data also seems necessary.
There are three questions that I'm left with now:

*

*Is this the right approach at all?

*Should I be using a different test?

*Should I be applying a correction to the CIs for multiple hypothesis testing as described?

I've read over this question already, but it's concerned with whether the matrices as a whole are identical, not whether any individual parameters differ. There doesn't seem to be much else available on SE for this topic.