text:
Q: Can't install wine from winehq.org on Ubuntu (actually Lubuntu) 18.04 LTS I have followed all the instructions on the winehq page.  In particular, I have run the following commands:
sudo dpkg --add-architecture i386
wget -nc https://dl.winehq.org/wine-builds/winehq.key
sudo apt-key add winehq.key
sudo apt-add-repository 'deb https://dl.winehq.org/wine-builds/ubuntu/ bionic main'

The first three of the above seemed to work fine.  However, the last command gives me the following error:
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 winehq-stable : Depends: wine-stable (= 5.0.0~bionic)
E: Unable to correct problems, you have held broken packages.

I'm running Lubuntu 18.04.3 on a USB live stick.  (However, if I remember correctly, a couple days ago I got the exact same error on a normal hard disk Lubuntu 18.04.3 installation.)
I've read that a lot of people get similar errors.  Unfortunately I haven't found any solutions online that worked.
Any help would be much appreciated.  Thanks!
EDIT:  Thanks for the comments and suggestions everyone.  I'll try them out later today.
In the mean time, here's something I don't understand.  Ubuntu 18.04 has been around for almost two years now.  In all that time, surely somebody has successfully installed wine, right?  What did they do to get it working?

A: Analysis
The WineHQ repository misses the dependencies for wine-stable package.
I have reported a bug 48513 to WineHQ bugzilla.
The main problem here is bad documentation, which is written in non-reproducible way.
The Rosanne DiMesio's main idea is "People who don't bother to read the directions are always going to have problems.".
So we need to write our own documentation until WineHQ-officials become smarter.
The problem with dependencies was caused by the FAudio dependency, which is not contained in Debian/Ubuntu and WineHQ repositories. We can determine the exact package name by using command below and analyzing of their output:
$ sudo apt-get install wine-stable-amd64
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 wine-stable-amd64 : Depends: libfaudio0 but it is not installable
                     Recommends: libcapi20-3 but it is not going to be installed
                     Recommends: libodbc1 but it is not going to be installed
                     Recommends: libosmesa6 but it is not going to be installed
                     Recommends: libsdl2-2.0-0 but it is not going to be installed
E: Unable to correct problems, you have held broken packages.

The aforementioned libfaudio0 package is available only for Ubuntu 19.10 and upcoming 20.04 LTS.

Solution
We need to follow official WineHQ guide for Ubuntu partially:
sudo dpkg --add-architecture i386
sudo apt update

Note: if you have WineHQ repository added - remove it with
sudo apt-add-repository -r 'deb https://dl.winehq.org/wine-builds/ubuntu/ bionic main'

to prevent the mess of repositories and then proceed.
Then we need to add other repository from OpenSuse Build Service to get libfaudio0 installed:
wget -q https://download.opensuse.org/repositories/Emulators:/Wine:/Debian/xUbuntu_18.04/Release.key -O Release.key -O- | sudo apt-key add -
sudo apt-add-repository 'deb https://download.opensuse.org/repositories/Emulators:/Wine:/Debian/xUbuntu_18.04/ ./'
sudo apt-get update

and only after this install one of WineHQ packages:
# Stable branch
sudo apt install --install-recommends winehq-stable

#Development branch
#sudo apt install --install-recommends winehq-devel

#Staging branch
#sudo apt install --install-recommends winehq-staging

A: Just an FYI, the Wine team have no intention of updating their misleading documentation, so this will continue to be problem on any distro based on 18.04 LTS:

The problem is with your system, not the packages.
You are probably missing FAudio, which is now a dependency for
  wine-stable, as stated clearly at the top of
  https://wiki.winehq.org/Ubuntu. The wiki also directs users to
  https://forum.winehq.org/viewtopic.php?f=8&t=32192 for instructions on
  how to install FAudio for bionic. Apparently you overlooked that part.
If that doesn't fix it, follow the instructions in
  https://wiki.winehq.org/FAQ#How_do_I_solve_dependency_errors_when_trying_to_install_Wine.3F
  to figure out exactly what dependencies you are missing. If you need
  further help, ask for it on the forum. Bugzilla is not for user
  support.

Friendly.

A: As another temporary solution, you may install previous version with command
apt-get install -y --install-recommends winehq-stable=4.0.3~bionic \
wine-stable=4.0.3~bionic wine-stable-amd64=4.0.3~bionic wine-stable-i386=4.0.3~bionic

It can be upgraded after maintainers fix their repository.

A: If the installation of winehq-stable gives the same error even after following all the steps in @N0rbert's answer.
Execute this command given in this link
sudo apt-get install libgnutls30:i386 libldap-2.4-2:i386 libgpg-error0:i386 libxml2:i386 libasound2-plugins:i386 libsdl2-2.0-0:i386 libfreetype6:i386 libdbus-1-3:i386 libsqlite3-0:i386

I had the same problem and this worked for me.


text:
Q: SignalR + token authorization via a remote service I'm making a SignalR-based service with a token-based authorization. The token is validated by an external API, which returns the user's ID. Then, notifications are sent to users with specific IDs.
The trouble that I can't get around is that SignalR's client code apparently sends 2 requests: one without a token (authentication fails) and the other with a token (authentication succeeds). For some reason, the first result gets cached and the user does not receive any notifications.
If I comment the checks and always return the correct ID, even if there's no token specified, the code suddenly starts working.
HubTOkenAuthenticationHandler.cs:
public class HubTokenAuthenticationHandler : AuthenticationHandler<HubTokenAuthenticationOptions>
{
    public HubTokenAuthenticationHandler(
        IOptionsMonitor<HubTokenAuthenticationOptions> options,
        ILoggerFactory logFactory,
        UrlEncoder encoder,
        ISystemClock clock,
        IAuthApiClient api
    )
        : base(options, logFactory, encoder, clock)
    {
        _api = api;
    }

    private readonly IAuthApiClient _api;

    protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        try
        {
            // uncommenting this line makes everything suddenly work
            // return SuccessResult(1);

            var token = GetToken();
            if (string.IsNullOrEmpty(token))
                return AuthenticateResult.NoResult();

            var userId = await _api.GetUserIdAsync(token); // always returns 1
            return SuccessResult(userId);
        }
        catch (Exception ex)
        {
            return AuthenticateResult.Fail(ex);
        }
    }

    ///
    /// Returns an identity with the specified user id.
    ///
    private AuthenticateResult SuccessResult(int userId)
    {
        var identity = new ClaimsIdentity(
            new[]
            {
                new Claim(ClaimTypes.Name, userId.ToString())
            }
        );
        var principal = new ClaimsPrincipal(identity);
        var ticket = new AuthenticationTicket(principal, Scheme.Name);
        return AuthenticateResult.Success(ticket);
    }

    ///
    /// Checks if there is a token specified.
    ///
    private string GetToken()
    {
        const string Scheme = "Bearer ";

        var auth = Context.Request.Headers["Authorization"].ToString() ?? "";
        return auth.StartsWith(Scheme)
            ? auth.Substring(Scheme.Length)
            : "";
    }
}

Startup.cs:
public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddHostedService<FakeNotificationService>();
        services.AddSingleton<IAuthApiClient, FakeAuthApiClient>();

        services.AddSingleton<IUserIdProvider, NameUserIdProvider>();

        services.AddAuthentication(opts =>
                {
                    opts.DefaultAuthenticateScheme = HubTokenAuthenticationDefaults.AuthenticationScheme;
                    opts.DefaultChallengeScheme = HubTokenAuthenticationDefaults.AuthenticationScheme;
                })
                .AddHubTokenAuthenticationScheme();

        services.AddRouting(opts =>
        {
            opts.AppendTrailingSlash = false;
            opts.LowercaseUrls = false;
        });

        services.AddSignalR(opts => opts.EnableDetailedErrors = true);
        services.AddControllers();
        services.AddMvc();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseDeveloperExceptionPage();

        app.UseRouting();

        app.UseAuthentication();

        app.UseEndpoints(x =>
        {
            x.MapHub<InfoHub>("/signalr/info");
            x.MapControllers();
        });
    }
}

FakeNotificationsService.cs (Sends a notification to user "1" every 2 seconds):
public class FakeNotificationService: IHostedService
{
    public FakeNotificationService(IHubContext<InfoHub> hubContext, ILogger<FakeNotificationService> logger)
    {
        _hubContext = hubContext;
        _logger = logger;
        _cts = new CancellationTokenSource();
    }

    private readonly IHubContext<InfoHub> _hubContext;
    private readonly ILogger _logger;
    private readonly CancellationTokenSource _cts;

    public Task StartAsync(CancellationToken cancellationToken)
    {
        // run in the background
        Task.Run(async () =>
        {
            var id = 1;
            while (!_cts.Token.IsCancellationRequested)
            {
                await Task.Delay(2000);
                await _hubContext.Clients.Users(new[] {"1"})
                                 .SendAsync("NewNotification", new {Id = id, Date = DateTime.Now});

                _logger.LogInformation("Sent notification " + id);

                id++;
            }
        });

        return Task.CompletedTask;
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        _cts.Cancel();
        return Task.CompletedTask;
    }
}

Debug.cshtml (client code):

    <title>SignalRPipe Debug Page</title>

Notifications log

    <textarea id="log" cols="180" rows="40"></textarea>

Minimal repro as a runnable project:
https://github.com/impworks/signalr-auth-problem
I tried the following, to no success:

*

*Adding a fake authorization handler which just allows everything

*Extracting the debug view to a separate project (express.js-based server)

What is that I'm missing here?

A: It doesn't look like you're handling the auth token coming from the query string which is required in certain cases such as a WebSocket connection from the browser.
See https://learn.microsoft.com/aspnet/core/signalr/authn-and-authz?view=aspnetcore-5.0#built-in-jwt-authentication for some info on how bearer auth should be handled.

A: Issue solved. As @Brennan correctly guessed, WebSockets do not support headers, so the token is passed via query string instead. We just need a little code to get the token from either source:
private string GetHeaderToken()
{
    const string Scheme = "Bearer ";

    var auth = Context.Request.Headers["Authorization"].ToString() ?? "";
    return auth.StartsWith(Scheme)
        ? auth.Substring(Scheme.Length)
        : null;
}

private string GetQueryToken()
{
    return Context.Request.Query["access_token"];
}

And then, in HandleAuthenticateAsync:
var token = GetHeaderToken() ?? GetQueryToken();

redpajama_set_name: RedPajamaStackExchange


text:
Q: multiple usage of require() in Node.js return undefined results I've got really strange behavior of require() in node.js.
I have simple common.js:
module.exports = common = {
    config: require('./config/config'),
    errorCodes: require('./config/errorCodes'),
    server: require('./server/server').server,
    dbManager: require('./db/dbManager').dbManager,
    idGenerator: require('./utils/idGenerator').idGenerator
};

my server.js:
var http = require('http'),
    url = require("url"),
    common = require('../common');

var server = (function ()
{
    var server = http.createServer(function (request, response)
    {

    });

    // running server
    function startServer()
    {
        server.listen(common.config.port);
        console.log('Tracking server running at :' + common.config.port);
    }

    return {
        startServer: startServer
    };
})();

module.exports.server = server;

So, Case 1, - I'm reqiuring common only in server.js, it works:
start.js:
//var common = require('./common');
var server = require('./server/server').server;

// initialize whole server
var init = function ()
{
//    common.dbManager.init();
    server.startServer();
};

init();

And, Case 2, I'm requiring common in both modules - doesn't work:
start.js
var common = require('./common');
var server = require('./server/server').server;

// initialize whole server
var init = function ()
{
    common.dbManager.init();
    server.startServer();
};

init();

The error is that in the second case certain properies common.config and common.dbManager are undefined. Does anybody have an idea why?
Thanks in advance.
Update
Thanks guys, the following solution works:

Your 'common' model is not needed: just require modules you need
  explicitly

A: You have a cycle: server -> common -> server.
Node.js require() returns undefined (by design) when module that is being loaded is required again, in cycle.
Solve your cycle.


text:
Q: Spring Web MVC 404 error – deployed as root on a webhost Tomcat server This is driving me crazy. Please help.
I am new to Spring and I developed my first spring mvc web app using sts/eclipse. It runs perfect inside eclipse's tomcat server.
The application context is /realtyguide and I run it in eclipse at http://localhost:8080/realtyguide/
Here is my web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
           http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">

  <display-name>Realty Guide</display-name>

      <!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
      <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/root-context.xml</param-value>
      </context-param>

      <!-- Creates the Spring Container shared by all Servlets and Filters -->
      <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
      </listener>

      <!-- Handles Spring requests -->
      <servlet>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>
                org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
      </servlet>
      <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>/</url-pattern>
      </servlet-mapping>

</web-app>

Here is my root-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

  <!-- Root Context: defines shared resources visible to all other web components -->

</beans>

Here is my Spring application servlet configuration:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:lang="http://www.springframework.org/schema/lang"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
        http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">

    <context:annotation-config />

    <!-- Scans within the base package of the application for @Components to configure as beans -->
    <context:component-scan base-package="com.springproject.realtyguide" />

    <!-- Enables the Spring MVC @Controller programming model -->
    <mvc:annotation-driven />

    <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources -->
    <mvc:resources mapping="/resources/**" location="/resources/"/>

    <!-- Allows for mapping the DispatcherServlet to "/" by forwarding static resource requests to the container's default Servlet -->
    <mvc:default-servlet-handler/>

    <!-- Bean to provide Internationalization  -->
    <bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="WEB-INF/i18n/messages" />
        <property name="defaultEncoding" value="UTF-8" />
    </bean>

    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
        p:location="classpath:META-INF/spring/database.properties" />

    <bean id="dataSource"
        class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
        p:driverClassName="${jdbc.driverClassName}"
        p:url="${jdbc.databaseurl}" p:username="${jdbc.username}"
        p:password="${jdbc.password}" />

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation">
            <value>classpath:META-INF/hibernate.cfg.xml</value>
        </property>
        <property name="configurationClass">
            <value>org.hibernate.cfg.AnnotationConfiguration</value>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${jdbc.dialect}</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>

    <!-- Enable the configuration of transactional behavior based on annotations -->
    <tx:annotation-driven />

    <bean id="transactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <!-- __________ BEAN ENTRIES FOR TILES 2 -->

    <bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
        <property name="definitions">
            <list>
                <value>/WEB-INF/layouts/tiles.xml</value>
            </list>
        </property>
    </bean>

    <bean id="tilesViewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver" >
        <property name="order" value="0"/>
        <property name="viewClass">
            <value>org.springframework.web.servlet.view.tiles2.TilesView </value>
        </property>
        <property name="requestContextAttribute" value="requestContext"/>
        <property name="viewNames" value="*.tiledef"/>
    </bean>

    <bean id="jstlViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="order" value="1"/>
        <property name="viewClass">
            <value>org.springframework.web.servlet.view.JstlView</value>
        </property>
        <property name="prefix" value="/WEB-INF/views/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <!-- __________ END OF BEAN ENTRIES FOR TILES 2 -->

    <!-- Resolves localized <theme_name>.properties files in the classpath to allow for theme support -->
    <bean id="themeSource" class="org.springframework.ui.context.support.ResourceBundleThemeSource">
        <property name="basenamePrefix" value="theme-" />
    </bean>

    <bean id="themeResolver" class="org.springframework.web.servlet.theme.CookieThemeResolver">
        <property name="defaultThemeName" value="standard" />
    </bean>

</beans>

Here is my controler's handler method for the root
@RequestMapping(value = "/", method=RequestMethod.GET)
public String setupForm(
        @ModelAttribute("searchFormBean") SearchFormBean searchFormBean,
        Model model) {
    model.addAttribute("searchFormBean", searchFormBean);
    // 'index' is a Tile definition in tiles.xml
    return "index.tiledef";
}

This is my webhosts tomcat/conf/server.xml
I deleted most of the 'commented out' stuff to make it shorter.
                <?xml version="1.0" encoding="UTF-8"?>

                <Server port="9200" shutdown="SHUTDOWN">

                  <!-- Comment these entries out to disable JMX MBeans support used for the
                       administration web application -->
                  <Listener className="org.apache.catalina.core.AprLifecycleListener" />
                  <Listener className="org.apache.catalina.mbeans.ServerLifecycleListener" />
                  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
                  <Listener className="org.apache.catalina.storeconfig.StoreConfigLifecycleListener"/>

                  <!-- Global JNDI resources -->
                  <GlobalNamingResources>

                    <!-- Test entry for demonstration purposes -->
                    <Environment name="simpleValue" type="java.lang.Integer" value="30"/>

                    <!-- Editable user database that can also be used by
                         UserDatabaseRealm to authenticate users -->
                    <Resource name="UserDatabase" auth="Container"
                              type="org.apache.catalina.UserDatabase"
                       description="User database that can be updated and saved"
                           factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
                          pathname="conf/tomcat-users.xml" readonly="true" />

                  </GlobalNamingResources>

                  <!-- Define the Tomcat Stand-Alone Service -->
                  <Service name="Catalina">

                    <!-- Define a non-SSL HTTP/1.1 Connector on port 8080 -->
                    <Connector port="9201" maxHttpHeaderSize="8192"
                               maxThreads="10" minSpareThreads="5" maxSpareThreads="75"
                               enableLookups="false" redirectPort="8443" acceptCount="100"
                               connectionTimeout="20000" disableUploadTimeout="true" />

                    <!-- Define an AJP 1.3 Connector on port 8009 -->
                    <Connector port="9203"
                               enableLookups="false" redirectPort="8443" protocol="AJP/1.3" />

                    <!-- Define the top level container in our container hierarchy -->
                    <Engine name="Catalina" defaultHost="localhost">

                      <!-- This Realm uses the UserDatabase configured in the global JNDI
                           resources under the key "UserDatabase".  Any edits
                           that are performed against this UserDatabase are immediately
                           available for use by the Realm.  -->
                      <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
                             resourceName="UserDatabase"/>

                      <!-- Define the default virtual host
                           Note: XML Schema validation will not work with Xerces 2.2.
                       -->
                      <Host name="localhost" appBase="webapps"
                       unpackWARs="true" autoDeploy="true"
                       xmlValidation="false" xmlNamespaceAware="false">

                       </Host>

                    </Engine>

                  </Service>

                </Server>

My Goal
Bring up the index page of the site at example.com, without the extra /.../ after the domain name.
What I Did
Deployed as Root of Virtual Host on a Shared  Webhost:
I read on stackoverflow that I need to deploy as root so...
I packaged it in STS/Eclipse by: right click on project "realtyguide" > Run as > Maven package
Webhost server is  a private Tomcat 5.5. I deployed the war file (unzipped it) on my webhost as default application of virtual host (with Context path = "" in server.xml) so I can access the website as example.com and not example.com/realtyguide.
Success. Or so I thought. I am able to bring up the index page at http://example.com/
Problem
Access to the other web pages referenced from the index page return a 404 error:

The requested URL /realtyguide/page-name was not found on this server

Even though the browser address bar show the context path with a complete URL of http://www.example.com/realtyguide/page-name
I think the app is bypassing the spring dispatcher servlet, hence  not recognizing the context path, 'realtyguide', in the request URL  - resulting in a 404 error.
I am so lost on how to deal with this.
Questions:

*

*What can I do to bring up the index page of the website at example.com instead of example.com/realtyguide/ without breaking the app? I've tried a index.jsp file (in WEB-INF) forwarding to the index of the context path but it doesn't solve the problem. Maybe I was doing it wrong.

*Is there some forwarding mechanism that I can use so that a site visitor enters example.com and is immediately forwarded to the index page at example.com/realtyguide/ so that all URLs shall be handled by the app?
Am I thinking about the problem the right way? Any solutions you've used before?
I'd greatly appreciate your help. Thanks for your time.

A: You need to make your web application the default web application for Tomcat.  Instructions are here:
http://wiki.apache.org/tomcat/HowTo#How_do_I_make_my_web_application_be_the_Tomcat_default_application.3F
Once that's done, it's easiest to use the index.jsp to forward to your Spring application's index.
An index.jsp file in the WAR root containing the following should do it:
<jsp:forward page="/realtyguide/" />


text:
Q: Chain rule for multivariable gradients - a matrix of gradients In my coursebook, there was a function to be differentiated.
Its definition was: $$\varphi(x,y) = f(u(x,y), v(x,y)) $$ where $$f(u(x,y), v(x,y)) \in \mathbb R$$
This function is clearly a composition:
$$(x,y) \mapsto_{g} (u(x,y), v(x,y)) \mapsto_f \varphi $$
Therefore, to calculate its derivative we need to apply the chain rule. On the one hand, the derivative is:
$$\nabla \varphi = \left(\frac {\partial \varphi}{\partial x}, \frac{\partial \varphi}{\partial y} \right)$$
On the other hand, the derivative of $\varphi$ is:
$$f' \cdot g' = \nabla f \cdot \nabla g$$
Now, here comes the part which I do not understand. I know that the derivative of a multivaiable function is a vector, therefore, I expect $\nabla g$ to be a vector looking something like this:
$$\nabla g = \left(\frac{\partial g}{\partial u}, \frac{\partial g}{\partial v}
 \right)$$
However, the textbook presentes $\nabla g$ as a matrix looking exactly like this:
$$ \nabla g = \begin{bmatrix}\nabla u \\ \nabla v \end{bmatrix} $$
I do not understand why it is possible to present one gradient as a matrix of other gradients. Could you, please, clarify a little bit what is going on here?

A: You're getting tripped up by a misconception that Git Gud pointed out in a comment: that the derivative of a multivariable function is always a vector. Although this is true when the function's codomain is one-dimensional, which might be all that you've been exposed to until now, it's not generally true for vector-valued functions.
Assuming the "bulk" form of the chain rule that you've cited, we have, as you say, $\nabla\phi = \nabla f\nabla g$. Looking at this in purely algebraic terms, $\nabla\phi$ is a $1\times2$ matrix (a vector) as is $\nabla f$, so there are only two possibilities for $\nabla g$: it's either a scalar or a $2\times2$ matrix. Multiplication by a scalar is the same as multiplication by a multiple of the identity matrix, so both of these cases can be combined into one.
What does this $2\times2$ matrix look like? Expanding the components of $\nabla\phi$ we have $$\begin{align}\nabla\phi = \begin{pmatrix}{\partial\phi\over\partial x} & {\partial\phi\over\partial y} \end{pmatrix} &= \begin{pmatrix} {\partial f\over\partial u}{\partial u\over\partial x}+{\partial f\over\partial v}{\partial v\over\partial x} & {\partial f\over\partial u}{\partial u\over\partial y}+{\partial f\over\partial v}{\partial v\over\partial y} \end{pmatrix} \\
&= \begin{pmatrix}{\partial f\over\partial u} & {\partial f\over\partial v} \end{pmatrix} \begin{pmatrix} {\partial u\over\partial x} & {\partial u\over\partial y} \\ {\partial v\over\partial x} & {\partial v\over\partial y} \end{pmatrix}.\end{align}\tag{*}$$ Comparing this to the product $\nabla\phi = \nabla f\nabla g$ we can see that $\nabla g$ must be the $2\times2$ matrix of partial derivatives in the last line above. This matrix of partial derivatives is known as the Jacobian matrix of $g$ and one can think of the gradient of a scalar-valued function as a special case of this.
The first row of the above matrix is $\nabla u$ and the second row $\nabla v$, so we can write $$\nabla g = \begin{pmatrix}\nabla u\\\nabla v\end{pmatrix}.$$ This point of view in which the rows or columns of a matrix are treated as individual row/column vectors is quite common, for instance when we talk about the row and column spaces of a matrix or describe the columns of a transformation matrix as the images of the basis vectors. The product of a row vector and matrix, such as we have in (*) can be viewed as a linear combination of the rows of the matrix with coefficients given by the vector, i.e., $$\nabla\phi = \nabla f\nabla g = {\partial f\over\partial u}\nabla u+{\partial f\over\partial v}\nabla v.$$
Another way to see why $\nabla g$ is a matrix is to go back to the definition of the differential of a function as the linear map that best approximates the change in the function's value near a point: $$f(\mathbf v+\mathbf h)-f(\mathbf v) = \operatorname{d}f_{\mathbf v}[\mathbf h]+o(\mathbf h).$$ From this definition, we see that if, say, $f:\mathbb R^n\to\mathbb R^m$, then $\operatorname{d}f_{\mathbf v}:\mathbb R^n\to\mathbb R^m$, too. (Technically, the domain of $\operatorname{d}f_{\mathbf v}$ is the tangent space at $\mathbf v$, but we can gloss over that when working in $\mathbb R^n$.) This means that $\operatorname{d}f_{\mathbf v}$, when expressed in coordinates, is an $m\times n$ matrix, the Jacobian matrix of $f$, in fact. Now, strictly speaking $\operatorname{d}f_{\mathbf v}$ and the derivative of $f$ aren't quite the same thing—for $f:\mathbb R^n\to\mathbb R$, for instance, $\operatorname{d}f_{\mathbf v}$ is a linear functional that lives in the dual space $\mathbb (R^n)^*$ while $\nabla f(\mathbf v)$ is a vector in $\mathbb R^n$—but with a suitable choice of coordinate systems we can blithely ignore this distinction, identify them and say that $\nabla g$ is also $2\times2$ matrix.


text:
Q: Apply function over data frame rows I'm trying to apply a function over the rows of a data frame and return a value based on the value of each element in a column. I'd prefer to pass the whole dataframe instead of naming each variable as the actual code has many variables - this is a simple example.
I've tried purrr map_dbl and rowwise but can't get either to work. Any suggestions please?
#sample df
df <- data.frame(Y=c("A","B","B","A","B"),
                  X=c(1,5,8,23,31))

#required result
Res <- data.frame(Y=c("A","B","B","A","B"),
                  X=c(1,5,8,23,31),
                  NewVal=c(10,500,800,230,3100)
                  )

#use mutate and map or rowwise etc
Res <- df %>%
  mutate(NewVal=map_dbl(.x=.,.f=FnAdd(.)))

Res <- df %>%
  rowwise() %>%
  mutate(NewVal=FnAdd(.))

#sample fn
FnAdd <- function(Data){

  if(Data$Y=="A"){
    X=Data$X*10
  }

  if(Data$Y=="B"){
    X=Data$X*100
  }
  return(X)
}

A: If there are multiple values, it is better to have a key/val dataset, join and then do the mulitiplication
keyVal <- data.frame(Y = c("A", "B"), NewVal = c(10, 100))
df %>%
   left_join(keyVal) %>%
   mutate(NewVal = X*NewVal)
#  Y  X NewVal
#1 A  1     10
#2 B  5    500
#3 B  8    800
#4 A 23    230
#5 B 31   3100

It is not clear how many unique values are there in the actual dataset 'Y' column.  If we have only a few values, then case_when can be used
FnAdd <- function(Data){
   Data %>%
      mutate(NewVal = case_when(Y == "A" ~ X * 10,
                                Y == "B" ~ X *100,
                                TRUE ~ X))
}

FnAdd(df)
#   Y  X NewVal
#1 A  1     10
#2 B  5    500
#3 B  8    800
#4 A 23    230
#5 B 31   3100

A: You were originally looking for a solution using dplyr's rowwise() function, so here is that solution.  The nice thing about this approach is that you don't need to create a separate function.
Here's the version using if()
   df %>%
   rowwise() %>%
   mutate(NewVal = ifelse(Y == "A", X * 10,
                          ifelse(Y == "B", X * 100)))

and here's the version using case_when:
df %>%
   rowwise() %>%
   mutate(NewVal = case_when(Y == "A" ~ X * 10,
                             Y == "B" ~ X * 100))


text:
Q: facebook c# sdk getting started I would like to write a console application that automatically posts information to my wall once every morning.
I have signed up for facebook developer and have a AppID and App Secret
I have been trying to play with the C# facebook SDK and looked through several examples.
Seems like the examples get a user token - but have to use a browser that is in windows forms.  This is an automated process - so I dont want to have a user present.
Ive also created some examples using the application token - but it does not seem to be able to write to the wall.
I wrote the Twitter equivalent very quickly.  I must be missing something here ???
What is the proper way to proceed?
It seems that all I should need to is:
FaceBookClient(appID, appSecret)
and then just
FaceBookClient.Put(message)
???
clarification added:
Playing with the C# facebook sdk winform application
I had to change their FacebookLoginDialog.cs to use the folling URL:
https://graph.facebook.com/oauth/access_token?grant_type=client_credentials&client_id=APPID&client_secret=APPSECRET&scope=user_about_me,publish_stream,offline_access
which returns an accesskey in WebBrowser.DocumentText
If I then call:
            var fb = new FacebookClient(_accessToken);
            dynamic parameters = new ExpandoObject();
            parameters.message = "Hello World!";
            dynamic result = fb.Post("me/feed", parameters);

I get the exception:
(OAuthException) An active access token must be used to query information about the current user.
If I change the code above to NOT use that access token - but use the appID and Appsecret:
           FacebookClient myFacebookClient = new FacebookClient("APPID", "APPSECRET");
            dynamic parameters = new ExpandoObject();
            parameters.message = "Hello World!";
            dynamic result = myFacebookClient.Post("me/feed", parameters);

Then I get the exception:
(OAuthException) An active access token must be used to query information about the current user.
I guess it is the same exception

A: Here is what I found.
Download the facebook C# sdk source code and samples from http://facebooksdk.codeplex.com/
Unzip the code and load into Visual Studio the Facebook C# SDK sample called CS-WinForms.
At the top of Form1.cs - enter your application ID
Run the application.
Form1.cs pops up with a button "Login to Facebook".  Click the button.
FacebookLoginDialog.cs pops up with a browser window in it displaying facebook asking for permissions.
FacebookLoginDialog.cs creates a browser window that will go to your user on facebook and request permissions.  By default those permissions are: user_about_me,publish_stream,offline_access.
Offline_access means the AccessToken you get - never expires
Click "OK" in Facebook to allow the application to access your facebook data.
FacebookLoginDialog.cs should find that you logged in and get the access token that never expires.
The access token is a string.
Insert a break point so that you can copy this access token.  Save this access token as you can use it from now on to access to Facebook.
Facebook developers website has some tools that you can use to check the access token
https://developers.facebook.com/tools/debug/access_token
You can enter your access token and click "Debug" and it should list your applicationID, UserID, and for "expires" it should say "never".
Once you have this access token - then you can simply write code like:
                        var fb = new FacebookClient(AccessToken);
                        dynamic parameters = new ExpandoObject();
                        parameters.message = FacebookString;
                        dynamic result = fb.Post("me/feed", parameters);
                        var id = result.id;

to post message to Facebook!

A: You should request offline_access in addition to publish_stream.  Once you have the never-expiring token, store that in your app.


text:
Q: 3D graphics: Normal mapping vs Bump mapping? I know that normal mapping describes the process of adding detail to meshes without increasing the polygon count, and that this is achieved by using specific normal textures for manipulating the way light is applied to the object. Okay.

*

*But what is bump mapping then? Is it just another term for normal mapping?

*How do the visual results compare? Can both techniques be combined?

A: Bump Mapping describes a general technique for simulating bumps and wrinkles on the surface of an object.  This is normally accomplished by manipulating surface normals when doing lighting calculations.
Normal Mapping is a variation of Bump Mapping in which the surface normals are provided via a texture, with normals embedded into the RGB channels of the image.
Other techniques, such as Parallax Mapping, are also Bump Mapping techniques because they distort the surface normals.
To answer the second part of the question, they could fairly easily be combined.  The base surface normals could be determined from a normal mapping and then modified via another bump mapping technique.

A: Bump mapping was originally suggested by Jim Blinn back in 1978.  His system basically works by perturbing the normal on a surface by using the height of that texel and the height of the surrounding texels.
This is quite similar to DUDV bumpmapping (You may recall the original environment mapped bump mapping as introduced in DX6 which was DUDV). This works by pre-calculating the derivatives from above so that you can miss out the first stage of the calculation (as it does not change each frame).
Normal mapping is a very similar technique that works by, simply, replacing the normal at each texel position.  Conceptually its much simpler.
There is another technique that produces "similar" results.  It is called emboss bump mapping.  This method works by using multipass rendering.  Basically you end up subtracting a gray scale heightmap from the last pass but offsetting it a small amount based on the light direction.
There are other ways of emulating surface topology as well.
Elevation mapping uses the height map as an alpha texture and then renders multiple slices through that texture with a different alpha value to simulate the change in height.  If not performed correctly, however, the slices can be very visible.
Displacement mapping works by generating a 3D mesh that uses the texture as its basis.  This, obviously, massively increase your vertex count.
Steep parallax, relief mapping, etc are the newest techniques.  They work by casting a ray through the heightmap until it intersects.  This has the big advantage that if a lump should block out the texture behing it now does as the ray doesn't hit the heightmap behind where it initially hits so always displays the "closest" texel.


text:
Q: Using scons to generate latex source files and compile pdf I am working on a book. The chapters are stored in markdown
files. I use pandoc to generate the LaTeX-Files of the chapters.
Here is the structure of the project:

*

*Book/Manuscript: contains the markdown files

*Book/Editions/PDF/tex: contains the generated LaTeX files

*Book/Editions/PDF/Layout_1/: first layout of the book

*Book/Editions/PDF/Layout_2/: second layout of the book

I would like to use scons to generate the latex files and to
call LaTeX to compile the PDFs.
scons set up
Book/SConstruct:
The SConstruct script defines only where subsequent
scripts may find the chapters of the book:
manuscript = Environment()
Manuscript.Replace(MARKDOWN_FILES = Glob('Manuscript/*.md'))

SConscript('Editions/PDF/SConscript', exports='manuscript')

Book/Editions/PDF/SConscript:
This script defines the LaTeX environment:
Import('manuscript')

PDF = Environment()

PDF.Replace(PDFLATEX='lualatex')

Export('PDF')

SConscript('tex/SConscript')

SConscript('Layout_1/SConscript')

SConscript('Layout_2/SConscript')

Book/Editions/PDF/tex/SConscript
This script uses a generator function to create the LaTeX
files:
import os

Import('Manuskript')

# write LaTeX file to Editions/PDF/tex
pandoc_action = 'pandoc -f markdown -o Editions/PDF/tex/{} {}'

def generate_pandoc_action(source, target, env, for_signature):
  # get the name of the target file
    tex_file = target[0].rstr().split(sep='/')[-1]
    return pandoc_action.format(tex_file, source[0])

env = Environment(ENV = os.environ)

markdownToLaTeX = Builder(generator = generate_pandoc_action,
                          suffix='.tex',
                          src_suffix='.md')

env['BUILDERS']['Pandoc'] = markdownToLaTeX

for input in Manuskript['MARKDOWN_FILES']:
    env.Pandoc(input)

I tried several other ways to call pandoc like a custom
builder. In any case, the LaTeX files were alway created in
directory Book/Manuscript and I had to move or copy them
to Editions/PDF/tex.
Book/Editions/PDF/Layout_1/SConscript
This script calls lualatex to generate the PDF of the first
layout. The script for the second layout looks accordingly.
Import('PDF')
basename = 'layout_'
pdf = PDF.PDF(basename + '.tex')
PDF.Clean(pdf, basename + '.synctex.gz')
Default(pdf)

Problems
First problem
Book/Editions/PDF/tex/SConscript always processes all
markdown files in Book/Manuscript even if none of those
changed. I tried to use VariantDir to tell the script that
it should look for the targets in Book/Editions/PDF/tex/
but whenever I run scons --debug=explain it says:
scons: building `Manuscript/some_chapter.tex' because it doesn't exist

How do I tell scons to generate the targets in
Book/Editions/PDF/tex/ and look for them in that directory
when it checks whether a target has to be created?
Second problem
Book/Editions/PDF/SConscript does not work as I
expected. My expectation was the scons would

*

*enter directory Book/Editions/PDF/tex to generate the LaTeX
files from all changed Markdown files

*enter directory Book/Editions/PDF/Layout_1 to generate
 the PDF for the first layout

*enter directory Book/Editions/PDF/Layout_2 to generate
 the PDF for the second layout

But scons only performs the second and the third step and
seems to either ignore the first step completely or to decide
that it does not have to perform it. Here is the output of
scons --debug=explain:
scons: Reading SConscript files ...
scons: done reading SConscript files.
scons: Building targets ...
scons: `Editions/PDF/Layout_1/book.pdf' is up to date.
scons: `Editions/PDF/Layout_2/book.pdf' is up to date.
scons: done building targets.

scons only calls the
Pandoc builder if I delete or uncomment the subsequent lines
in Book/Editions/PDF/SConscript. For example like this:
SConscript('tex/SConscript')

# SConscript('Layout_1/SConscript')

# SConscript('Layout_2/SConscript')

I do not understand why scons ignores tex/SConscript
when the other two scripts are active? What is the problem?
Thanks in advance
Maral

A: You need to specify a target for builders (or have your emitter do it)..
Also all files when represented as strings
Try this and see if that helps.
Book/Editions/PDF/tex/SConscript
import os

Import('Manuskript')

env = Environment(ENV = os.environ)

markdownToLaTeX = Builder('pandoc -f markdown -o $TARGET $SOURCE',
                          suffix='.tex',
                          src_suffix='.md')

env['BUILDERS']['Pandoc'] = markdownToLaTeX

for input in Manuskript['MARKDOWN_FILES']:
    # write LaTeX file to Editions/PDF/tex
    target = '#Editions/PDF/tex/'+File(input).file
    env.Pandoc(target, '#Book/'+input)


text:
Q: Disable tabbing between links but inputs I am trying to disable tabbing between links with pure Javascript or with a simple css class that will affect the entire website:
Here is what i try to do
document.getElementsByTagName("a")[0].setAttribute("tabindex", "-1");

This is how it can be achieved with jquery:
$('a').attr('tabindex', '-1');

A: jQuery's $('a').attr:

sets one or more attributes for every matched element.

If you do
document.getElementsByTagName("a")[0].setAttribute

As you can see by the [0] there, you're only setting the attribute of one element. You need to loop through all elements instead:

document.querySelectorAll('a').forEach(
  a => a.setAttribute('tabindex', '-1')
);
<input placeholder="click on me, then press tab">
link
link
link

(Compare to, with no Javascript at all:)

<input placeholder="click on me, then press tab">
link
link
link

For old browsers that don't support NodeList.forEach, use the polyfill, or call the forEach like this instead:
Array.prototype.forEach.call(
  document.querySelectorAll('a'),
  function(a){ a.setAttribute('tabindex', '-1'); }
);


text:
Q: why am i getting sql error 0 with mysql 8? i can't seem to figure it out why i'm getting this error i am using percona server for mysql 8 with sql mode set to sql_mode = "NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION"
this is the error i am getting whats sql error 0 ?
 MySQL: Invalid Query:
            SELECT
              Rank,
              SpecialRank,
              TotalRank,
              DonationTime,
              RankExpirationTime + INTERVAL 766 HOUR
            FROM users_donor_ranks
            WHERE UserID = '1' SQL error: 0 ()

the sql table that i am using
CREATE TABLE `users_donor_ranks` (
  `UserID` int(10) NOT NULL DEFAULT '0',
  `Rank` tinyint(2) NOT NULL DEFAULT '0',
  `DonationTime` datetime DEFAULT NULL,
  `Hidden` tinyint(2) NOT NULL DEFAULT '0',
  `TotalRank` int(10) NOT NULL DEFAULT '0',
  `SpecialRank` tinyint(2) DEFAULT '0',
  `InvitesRecievedRank` tinyint(4) DEFAULT '0',
  `RankExpirationTime` datetime DEFAULT NULL,
  PRIMARY KEY (`UserID`),
  KEY `DonationTime` (`DonationTime`),
  KEY `SpecialRank` (`SpecialRank`),
  KEY `Rank` (`Rank`),
  KEY `TotalRank` (`TotalRank`)
) ENGINE=InnoDB CHARSET=utf8mb4;

the query i am making
G::$DB->query("
        SELECT
          Rank,
          SpecialRank,
          TotalRank,
          DonationTime,
          RankExpirationTime + INTERVAL 766 HOUR
        FROM users_donor_ranks
        WHERE UserID = '$UserID'");

A: RANK is a reserved word in MySQL starting version 8.0.2.
You would need to quote this identifier, using backticks:
SELECT
    `Rank`,
    SpecialRank,
    TotalRank,
    DonationTime,
    RankExpirationTime + INTERVAL 766 HOUR
FROM users_donor_ranks
WHERE UserID = ?


text:
Q: group chat in flutter using firebase with a twist Disclaimer: I have never worked with firebase or any other DB so my idea is pretty rough and I will be glad if u correct me in some of my assumptions. Also this is my first question on StackOverflow so I hope it will be detailed enough.
I am currently working on my project which is basically a group chat in flutter using firebase, where I should be able to create a new group chat(create a new DB in firestore) trough the app, let other ppl join(assign them to the new group chat DB).
The twist: If I send a message to the group chat I want other ppl to see a pop-up saying: "do you accept this message", no=> doesn't show / yes=> Shows the message but deletes it for others.
This app is nothing but my idea of how to confirm my theory and also learn a little bit more about both flutter and firebase, so please do not mind if it's useful or not.
Assumption: Each groupchat has it's own DB (Can I create a DB in firestore trough app / send request to?)
Question: Can I assign a specific ID to each message and choose and further edit who is going to be able to see the message trough the app(app_instance_1"I accepted the message so only I and sender can see it")?

A: Here's a great article for making a Flutter chat app: https://medium.com/flutter-community/building-chat-app-in-flutter-with-firebase-888b6222fe20. If you need more detail or help just write a comment.
About your assumption. Each app usually is connected to one database, and within the database, you can have separate documents to hold each group chat. You can also set up documents for each individual user to save the chats that only they can see. Within documents, you add collections that hold your data.


text:
Q: Как посчитать разницу значений колонок? Вопрос вроде не сложный, но не могу решить.
Есть таблица из двух колонок и индексного столбца дат. Надо создать третью колонку, и поместить в неё разницу между значениями первой колонки сего дня и второй колонки предыдущего дня.
df = pd.DataFrame({'col01': np.random.rand(100),
              'col02' : np.random.rand(100)},
              index = pd.date_range('1/1/2000', periods=100, freq='B'))
df

Получится следующая таблица:

Значение третьей колонки должно выглядеть:
    df['col03'] = 0
    df.loc['2000-01-03', 'col03'] = df.loc['2000-01-03', 'col02'] - df.loc['2000-01-04', 'col01']

Но только для всего столбца.

A: Вы не поверите:
df = pd.DataFrame({'col01': np.random.rand(100),
              'col02' : np.random.rand(100)},
              index = pd.date_range('1/1/2000', periods=100, freq='B'))

df['col03'] = df['col02']-df['col01'].shift(1)

ваш df (разумеется, числа у нас будут разные):
               col01     col02     col03
2000-01-03  0.049760  0.292412       NaN
2000-01-04  0.792802  0.022108 -0.027652
2000-01-05  0.411132  0.252973 -0.539829
2000-01-06  0.231647  0.300546 -0.110586
2000-01-07  0.680433  0.676711  0.445064
...              ...       ...       ...
2000-05-15  0.733525  0.412041 -0.083264
2000-05-16  0.401303  0.803666  0.070141
2000-05-17  0.496733  0.047584 -0.353719
2000-05-18  0.237565  0.980574  0.483840
2000-05-19  0.539980  0.143298 -0.094267


text:
Q: How to add the help text of a custom module in a separate template file in Drupal 8? Following this documentation https://www.drupal.org/docs/8/creating-custom-modules/basic-structure, the help text can be added inside the hook_help() function in my_custom_module.module file when creating a custom module in Drupal 8.
I would like to put the help text in a separate template file and inside the hook_help() function I point to that template file. How can I do that?

A: hook_help() returns a renderable array, so you can use custom theme and template for this:
function help_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    case 'your.custom.route':
      return ['#theme' => 'my_custom_theme'];
  }
}

Don't forget to use t function in your twig templates to support translation:
{{ "My string"|t }}


text:
Q: Setting up CNAME at DirectNIC.com caused gmail in Google Apps for Businesses to stop working I am helping a friend set up a website at Drupal Gardens. The domain is www.fromtheheartyoga.com. Previously the site was hosted at Modwest. While at Modwest I set them up with gmail/Google Apps for business (free version), so they could use the @fromtheheartyoga.com emails with gmail.
A few days ago I moved hosting from Modwest to Drupal Gardens. In order to get the domain working correctly I had to set up a CNAME record at DirectNIC (the domain provider) to point the domain "www.fromtheheartyoga.com" at the Drupal Garden site "fthy.drupalgardens.com". In order to do this I had to upgrade the DirectNIC account to a hosted account.
When I created the CNAME record, email stopped working. I later went in and updated the MX records at DirectNIC with all of the relevant Google Mail MX information. Email still didn't work. DirectNIC sait it could take as long as 48 hour for these changes to propagate. Thing is, when I updated the CNAME record, the domain began pointing to the new hosting environment almost immediately. Not so with the email.
That was Friday. As of today, none of the email addresses using the @fromtheheartyoga.com (gmail) have received any email. Every email I send from another account disappears into the internet. For the emails I send from my personal gmail account, I occasionally get a transfer update which includes, among other things the note that "The recipient server did not accept our requests to connect".
I can still send from the @fromtheheartyoga gmail account. Replies to emails sent from there also disappear.
I have had no luck with Google searches, unless the answer is right in front of me and I simply don't know enough about the issue to recognize it. Likewise here at StackOverflow. Any insights would be greatly appreciated
-John Winkelman

A: For compatibility reasons, you can't put a CNAME in the root domain; doing so will break email.
Use an A record instead.

A: Just make an A record for fromtheheartofyoga.com. The old BIND4 CNAME for a domain directive really wasn't right even back then. It's just more records to edit should you move again, who cares.
Edit to add: I don't know whether you get a definite IP address with your hosting service, you would have to know that for this to work.
Regards,
Brian in CA


text:
Q: How to keep custom object sequence property in model when there are multiple lists of that type used in application I have a wpf application with MVVM pattern. There is a view which displays the warnings (text) on screen, which are of type WarningModel.cs
In my ViewModel I have 3 properties of type ObservableCollection<WarningModel>(), these are bound to 3 different grids (telerik for wpf grids). Three grids because there are 3 types of warnings.
My requirement is when user adds new warning (new object of type WarningModel) into the grid, that object should be assigned an order sequence starting with 1 followed by 2 and so on for next object.
What I tried is added a static field in Warning.cs which will be auto incremented each time the constructor is called. Now the problem is since there are 3 ObservableCollection each time the object is instantiated from any of the collection, sequence gets incremented but all the three collection should maintain their own sequence.
What else can be employed here to achieve the desired output.
Here are my classes
 public class Warning
    {
        public string MESSAGE { get; set; }

        private int _type;
        public int TYPE
        {
            get { return _type; }

            set
            {
                if (value != _type)
                    _type = value;
            }
        }
        public int SORT_ORDER { get; set; }
        public static int SORT_SEQUENCE = 0;
        public Warning()
        {
            SORT_ORDER = Interlocked.Increment(ref SORT_SEQUENCE);
        }
    }

   public class WarningsViewModel
        {
            public ObservableCollection<WarningModel> WarningBP { get; set; }
            public ObservableCollection<WarningModel> WarningPP { get; set; }
            public ObservableCollection<WarningModel> WarningPB { get; set; }

            public VoyageInfoViewModel()
            {
                WarningBP = new ObservableCollection<WarningModel>();
                WarningPP = new ObservableCollection<WarningModel>();
                Warning PB = new ObservableCollection<WarningModel>();
            }
        }

A: You can attach handler for CollectionChanged of ObservableCollection and assign ID as index of inserted item.
public VoyageInfoViewModel()
{
    WarningBP = new ObservableCollection<WarningModel>();
    WarningBP.CollectionChanged += WarningCollectionChanged;
    ...
}
private void WarningCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
   if (e.Action == NotifyCollectionChangedAction.Add)
      for (var i = 0; i < e.NewItems.Count; i++)
         ((Warning)e.NewItems[i]).SORT_ORDER = e.NewStartingIndex + i + 1;
}

If you allow user also to delete warnings and want SORT_ORDER be recalculated on deletion you can write handler as:
private void WarningCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
   for (var i = 0; i < ((ICollection)sender).Count; i++)
      ((Warning)((IList)sender)[i]).SORT_ORDER = i + 1;
}

A: You could for example create a custom ObservableCollection<T> that sets the sequence number of added items. Something like this:
public class SequencedObservableCollection : ObservableCollection<WarningModel>
{
    private int _sequenceCounter = 0;

    protected override void InsertItem(int index, WarningModel item)
    {
        item.SORT_ORDER = ++_sequenceCounter;

        base.InsertItem(index, item);
    }
}

public abstract class WarningModel
{
    public int SORT_ORDER { get; set; }
}

Don't forget to change the type of your source properties in the view model:
public SequencedObservableCollection  WarningBP { get; set; }
public SequencedObservableCollection  WarningPP { get; set; }
public SequencedObservableCollection  WarningPB { get; set; }


text:
Q: Logcat don`t log system apps in latest android 4.3 In android 4.1.2 I'm using logcat to log system apps (example Update Firmware)
After update to 4.3 logcat stopped writing any logs of system applications
But in the applications themselves as before there Log(tag, '...');
I do not create an application that reads the logs. I use logcat via USB (usb debug is ON)
Question: How to get a log of system applications for android 4.3?


text:
Q: Rails: Writing a function for a div Hey I am quite new to Rails and I got a bit stuck So I have this div in rails that I am using over and over again to show icons. I want to write a function since there are about 20 images and 3 different states (inactive/active/completed)
My View

   <%= link_to "course_6" do %>
   <%= image_tag '/icons/course_6_active.png', width: 150, height: 150, alt: ''%>
   <%end%>

Controller
def iconloader(number,state)

 <%= link_to "course_#{number}" do %>
 <%= image_tag '/icons/course_#{number}_#{state}.png', width: 150, height: 150, alt: ''%>
 <%end%>
end

I can't seem to figure out how to write a function for a div.(I know it should be really easy but I have been stuck for 2 days now) I am a bit lost. Also where do I put the function? In the controller or the view?
to rephrase my question a bit clearer: how would I use less code to achieve the same in my view using rails? It is a bit of a mess now.

A: I think what you're looking for is a view helper
http://www.rails-dev.com/custom-view-helpers-in-rails-4

A: First, if you want a function which will render simple HTML in your views, use a helper function. These are in app/helpers. Putting a method in application_helper.rb will be callable anywhere within your views.
As for rendering HTML in Ruby, you can use the following syntax:
In application.rb:
def iconloader(number, state)
  content_tag(:div, class: "position6") do
    link_to "course_6" do
      image_tag '/icons/course_6_active.png', width: 150, height: 150, alt: ''
    end
  end
end

Then, simply call the icon loader in your view:
<%= iconloader(number, state) %>

Also, I'd consider using a partial instead of a function to render HTML when possible. It's often easier to express HTML in HTML itself rather than Ruby, especially for more complex HTML.


text:
Q: Get enum parameter value I wrote this enum with parameter is a string
public enum ButtonType {
    case number(value: String)
    case clear(value: String)
    case backspace(value: String)

    static func generateNumpad() -> [ButtonType] {
        return [
            .number(value: "1"),
            .number(value: "2"),
            .number(value: "3"),
            .number(value: "4"),
            .number(value: "5"),
            .number(value: "6"),
            .number(value: "7"),
            .number(value: "8"),
            .number(value: "9"),
            .clear(value: "Clear"),
            .number(value: "0"),
            .backspace(value: "Del"),
        ]
    }
}

In view controller I assign all button type to an array
let buttons = ButtonType.generateNumpad()

How can I get the parameter value?
example: buttons[0].value
Please help!

A: Inside ButtonType enum, declare property like this:
enum ButtonType {
    ...
    var value: String {
        switch self {
        case .number(let number): return number
        case .clear(let clearValue): return clearValue
        case .backspace(let backSpaceValue): return backSpaceValue
        }
    }
}


text:
Q: Recomeçar a contagem se exceder as opções Esta pergunta provavelmente será respondida em menos de 5 minutos de tão fácil, mas eu estou quebrando a cabeça...
Vou simplificar muito aqui, mas acho que dá pra entender:
Crio elementos pelo javascript, cada um tem sua cor de fundo, são 8 cores que estão em classes. (.fundo1, .fundo2...).
Mas são apenas 8 cores, como faço para se criar mais do que 8 elementos a contagem volte a 0?
OBS: Sei que da pra fazer isso apenas de uma forma simples sem usar variáveis... Mas hoje não ta sendo meu dia nem aqui nem no tio google.
Código exemplo:

$(function(){
  $("#adicionar").on("click",function(e){
    $("#teste").append("

");
    e.preventDefault();
  });
});
#teste div{
  float:left;
  clear: left;
  width:40px;
  height: 40px;
  margin: 2px;
}
.fundo1{
  background-color: #000;
}
.fundo2{
  background-color: #00F;
}
.fundo3{
  background-color: #0FF;
}
.fundo4{
  background-color: #F00;
}
.fundo5{
  background-color: #FF0;
}
.fundo6{
  background-color: #FA0;
}
.fundo7{
  background-color: #0F0;
}
.fundo8{
  background-color: #F0F;
}

Adicionar

A: Se você não quiser as cores exatamente nessa ordem, pode gerar um valor aleatório entre 1 e 8:

$(function(){
  $("#adicionar").on("click",function(e){
  var num = Math.floor((Math.random() * 8) + 1);
    $("#teste").append("

");
    e.preventDefault();
  });
});
#teste div{
  float:left;
  clear: left;
  width:40px;
  height: 40px;
  margin: 2px;
}
.fundo1{
  background-color: #000;
}
.fundo2{
  background-color: #00F;
}
.fundo3{
  background-color: #0FF;
}
.fundo4{
  background-color: #F00;
}
.fundo5{
  background-color: #FF0;
}
.fundo6{
  background-color: #FA0;
}
.fundo7{
  background-color: #0F0;
}
.fundo8{
  background-color: #F0F;
}

Adicionar

A: $(function(){
  //cria uma variavel para saber qual a contagem
  var contador = 0;
  $("#adicionar").on("click",function(e){
    // alimenta + 1 na variável;
    contador ++;
    // se ela for mais que 8, volta a ter o valor 1
    if(contador > 8){
      contador = 1;
    }
    $("#teste").append("

");
    e.preventDefault();
  });
});

A: Então, acabei de lembrar como se faz, peço desculpas por tomar o tempo de vocês.
É só usar %, no caso:
var num=NUMERO_ATUAL % MÁXIMO;

Isso vai manter dentro do meu range máximo. Então seguindo meu exemplo:

$(function(){
  $("#adicionar").on("click",function(e){
    $("#teste").append("

");
    e.preventDefault();
  });
});
#teste div{
  float:left;
  clear: left;
  width:40px;
  height: 40px;
  margin: 2px;
}
.fundo1{
  background-color: #000;
}
.fundo2{
  background-color: #00F;
}
.fundo3{
  background-color: #0FF;
}
.fundo4{
  background-color: #F00;
}
.fundo5{
  background-color: #FF0;
}
.fundo6{
  background-color: #FA0;
}
.fundo7{
  background-color: #0F0;
}
.fundo8{
  background-color: #F0F;
}

Adicionar


text:
Q: Detect missing binary symbols in Linux repository Is there any tool that is able to validate that a linux repository contains all needed binary symbols? I need to verify completeness of the repository over binary symbols.
I.e. I need to know that for every executable file in the repository all its external symbols (as reported by nm -g) are provided by some shared library from this repository.
As for now my target repository is not restricted to rpm or deb, or any particular distribution at all, I just need to know is there any such tool at all?
I was unsuccessful googling for that, so I'll be grateful for at least key words for google.

A: ALT linux has implemented something called set:versions as
a type of dependency,
The set:versions is a compact symbol encoding that can do
subsetting efficiently. What that means is that an executable
which uses only some of the symbols in libraries has a set:version
that can detect if it is a proper subset, i.e. no missing symbols.
The set:version implementation was written by Alexey Tourbin.
Meanwhile, its not too hard to use nm(1) to generate lists of
all provided library symbols, and all needed executable symbols.
If you use a common file format for provided/required symbols, and
alphabetize and remove duplicates using "sort -u", then you can
simply diff the two files to ensure that there are no unresolved symbols.


text:
Q: How to apply conditional formatting in openpyxl? I am using openpyxl to manipulate a Microsoft Excel Worksheet.
What I want to do is to add a Conditional Formatting Rule that fills the rows with a given colour if the row number is even, leaves the row blank if not.
In Excel this can be done by selecting all the worksheet, creating a new formatting rule with the text =MOD(ROW();2)=0 or =EVEN(ROW()) = ROW().
I tried to implement this behaviour with the following lines of code (considering for example the first 10 rows):
redFill = PatternFill(start_color='EE1111', end_color='EE1111', fill_type='solid')
ws2.conditional_formatting.add('A1:A10', FormulaRule(formula=['MOD(ROW();2) = 0'], stopIfTrue=False, fill=redFill))

My program runs correctly but when I try to open the output Excel file, it tells me that the file contains unreadable content and it asks me if I want to recover the worksheet content. By clicking yes, the worksheet is what I expect but there is no formatting.
What is the correct way to apply such a formatting in openpyxl (possibly to the entire worksheet)?

A: Unfortunately, the way formulae are handled in conditional formatting is particularly opaque. The best thing to do is to create a file with the relevant conditional format and inspect the relevant file by unzipping it. The rules are stored in the relevant worksheet files and the formats in the styles file.
However, I suspect that the problem may simply because you are using ";" to separate parameters in the function: you must always use commas for this.
A sample formula from one of my projects:
green_text = Font(color="006100")
green_fill = PatternFill(bgColor="C6EFCE")
dxf2 = DifferentialStyle(font=green_text, fill=green_fill)
r3 = Rule(type="expression", dxf=dxf2)
r3.formula = ["AND(ISNUMBER(C2), C2>=400)"]


text:
Q: how to scan a windows registry's all user profiles and fetch the value of ProxyEnable and proxy server using REG query Please tell me how to search each profile of HKEY_USERS and find the value of ProxyEnable and proxy server.
I have a Nodejs binary(.exe) which basically runs in individual machines. I use Procrun(commons.apache.org/proper/commons-daemon/procrun.html) to run my Nodejs application as a service. and the Nodejs application tries to find the proxy config through child process which runs this reg query.
Due to some other limitation of application its always fetching the details from the default profile "Computer\HKEY_USERS\.DEFAULT\Software\Microsoft\Windows\CurrentVersion\Internet Settings" because it is running under the default profile(User). So the idea is just to scan all profiles(Users) under HKEY_USERS and fetch ProxyEnable and proxy server details. It would be great if you suggest a way to accomplish this.
I use the below script
FOR /F " skip=2 tokens=1-3" %%A IN ('reg query "HKEY_USERS" /v ProxyEnable 2^>nul') DO (
  @echo %KEY_NAME%\%VALUE_NAME% not found
    set ValueName=%%A
    set ValueType=%%B
    set ValueValue=%%C
)

It's not returning the values. My expectation is it should scan all folders under HKEY_USERS and get all the values of ProxyEnable key.

Thanks


text:
Q: Google drive .zip file set permission expiration Is it possible to set an expiration time for a permission on a non-google drive file? e.g. a zip file (not a google doc, spreadsheet, .etc.).
If so, how does one do it?
I am using the following function to generate a shareable link:
public function getShareableLink($file) {
    $tempPermission = new Google_Service_Drive_Permission([
        'type' => 'anyone',
        'role' => 'reader',
        'withLink' => true,
    ]);
    $this->service->permissions->create($file, $tempPermission);
    $fileMetadata = $this->service->files->get($file, array('fields' => 'webViewLink'));
    return $fileMetadata->getWebViewLink();
}

and it seems I can set an expiration via the permission class, however I can't find any information in the drive gui as to whether the link expires (or even to set an expiry time for that matter).

A: so far, the expiry option is open to permission type of 'user' only.


text:
Q: Closing sessions while pressing on a link I want to close my session while pressing on the text in the list. I don't really know how to do it. It is ASP.net and its need to be when I press the last link.

Home

Regels

Afspraken

Grenzen

Users

Uitloggen

A: The user would click on the AdminPage.aspx link and then you can clear the session in the Page_Load event.
protected void Page_Load(object sender, EventArgs e)
{
   // clear or abandon ...
}

It's not clear whether you want to use Session.Clear or Abandon. See the following SO answer on which one is suitable for your requirement.
In ASP.NET, when should I use Session.Clear() rather than Session.Abandon()?


text:
Q: How can I modify a value of a dictionary that inside another dictionary I have a variable "Persons" that contain the following dictionary,
persons = {
    'mohammed': {'age': 25, 'job': 'programmer', 'city': 'tripoli'}
}

what I want to do is to modify any valus of the 'mohammed' items which is the key of the persons dictionary.

A: try this :
persons["mohammad"]["job"] = "teacher"


text:
Q: One assert statement tests several conditions I found many information about bad practices to use several asserts in one method (one test condition). It's clear. Each method should test one and only one condition. So it should be one assert in most cases.
But I can't find any information about best practices to situation, if my one assert tests several conditions.
Example:
@Test
public void findAllPerformers_returnsPerformersInAlphabeticalOrder() {
    List<String> performers = reportRepository.findAllPerformers();
    assertThat("Should return performers in alphabetical order",
            performers, contains("Bart Simpson", "Homer Simpson",
                    "Ned Flanders", "Xena Warrior Princess"));
}

First, I had to have 2 more test methods (conditions): findAllPerformers_returnsAllUniquePerformers and findAllPerformers_returnsEachPerformerOnlyOnce. But then I realized that my first method tests this two conditions too!
So, what should I do?

*

*Leave all methods as is.

*Remove 2 other test methods and rename my findAllPerformers_returnsPerformersInAlphabeticalOrder method to very long name with all three conditions included (because it really tests all three conditions!)

*Just remove 2 other test methods.

*Leave all methods but invoke findAllPerformers_returnsPerformersInAlphabeticalOrder method from two other methods.

*Copy-paste findAllPerformers_returnsPerformersInAlphabeticalOrder method contents to two other methods.

*Anything else...

A: If this test fails then the person looking at the failed test would initially see findAllPerformers_returnsPerformersInAlphabeticalOrder().
Looking at that alone it appears that the method under test returned a list that wasn't in alphabetical order, not that the list didn't contain 'Bart Simpson'.
Avoid options 4 and 5, they don't really solve anything and will increase duplication/maintenance without any added value (since tests will fail for reasons not mentioned in the test name). Instead try to find a way to actually test what you want with the assert.


text:
Q: How to display 2 digits after dot in PostgreSQL? I have a table which their values are NUMERIC(16,4)
Example:
12.4568
13.2
14.05

I want to display the value with only 2 digits after dot without rounding.
Expected result is:
12.45
13.2
14.05

What I did is:
Select price::Numeric(16,2)
from prices

It works however I am not sure if this is the correct way to do it. I think it's better to use some kind of display edit rather then casting?

A: you can do this in following way:
select round(cast(your_float_column as decimal(10,2)), 2, 1)
from your_table

If you just want to skip round off then
select round(12333.347, 2, 1)

hope this will work for you

A: Did you try:
Select round(price,2)
from prices

A: try this
select price::decimal(16,2) from prices


text:
Q: How to display user inputted line breaks from a textarea value? I am creating a program with two pages: one for inputting text via textarea into a database as a form, and the other to fetch said data and display it on a textarea. However, submitting text that has indentation in it (as a product of the user hitting the enter button), the page to fetch and display info breaks, and I know why but not how to fix it.
Page to submit form:

      <form action="/spaceData" method="POST">

               <textarea value="" id="textbox" name="usertext" maxlength="100" placeholder="Write your fortune:" onchange="handleChange(this)"></textarea>

            <button type="submit" id="submit" onclick="return handleChange()">Contribute Wisdom</button>

      </form>

The page to display data is an ejs file which retrieves the text value of a submission as so:
let text = "<%= text %>";

But, for strings with indentation, the variable breaks. For example, say a user inputs the string:
hello
world
!

The ejs file would display the variable as:
let text = "hello
world
!";

This causes the program to break. How do I allow the text variable to detect line breaks?
I thought perhaps I could have the string be iterated over prior to submission and if an indentation is detected it can be replaced with a \n, but I'm unsure how to implement this or if it would even fix the problem.
Thanks for any advice.

A: this is cause html and js break lines are working different.
any the case. text area send this breaklines when you input them
and if you want you enable these linebreaks in you frontend just add this css in the area where you want to render these textarea info
for example: into a "p" tag
in < style> or .css file:
p {
  white-space: pre-wrap;
}

or in the html:

 {textarea}

textarea can register all these breaklines. but when it sendit to a database there is no form in js you can see that breaklines. idk how to explain it but are hidding these  lines


text:
Q: Movie ID: Alien lifeform runs rampant on ISS I saw this sci-fi movie a while ago. Anyways, the movie wasn't made more than 4 years ago, and it is about this single-cell alien lifeform that is found on Mars. It is sent to the ISS to be studied. The lifeform evolves very quickly and is intelligent. It quickly grows to a pretty big size and becomes hostile to the astronauts on the ISS.
At some point, NASA sends up a Soyuz capsule to push the ISS out of its Earth orbit to try and save the world from this thing. I can't remember if it does anything, but by then, the last two living astronauts decide that they have to do something.
They each board Soyuz capsules that are there to be lifeboats in case of an 'abandon ship' scenario. One of the astronauts decides to be a distraction to get the alien on board so that the capsule will take them both away from the Earth to a slow death. The other one tries to get back to Earth.
You'd think that the distraction guy would succeed, even with the alien inside the capsule with the astronaut, trying to get him to let go of the manual controls so that autopilot wouldn't kick in and pilot the capsule to Earth, but he fails. And of course, the other astronaut's autopilot fails and suffers a slow but inevitable demise in space. Sadly, the alien gets to Earth and probably destroys the world.

A: This would likely be Life, released just last year in 2017.
From the IMDB description:

A team of scientists aboard the International Space Station discover a rapidly evolving life form that caused extinction on Mars and now threatens all life on Earth.


text:
Q: How to visualize pyspark ml's LDA or other clustering Is there a simple way to visualize the pyspark's LDA (pyspark.ml.clustering.LDA)?
ldamodel.transform(result).show() generates
+--------------------+---+--------------------+--------------------+
|            filtered| id|            features|   topicDistribution|
+--------------------+---+--------------------+--------------------+
|    [problem, popul]|  0|(18054,[49,493],[...|[0.03282220322786...|
|[tyler, note, glo...|  1|(18054,[40,52,57,...|[0.00440868073429...|
|[mani, economist,...|  2|(18054,[12,17,25,...|[0.00404065731437...|
|[probabl, correct...|  3|(18054,[0,4,7,21,...|[0.00485107317270...|
|[even, popul, ass...|  4|(18054,[10,12,49,...|[0.00334279689625...|
|[sake, argument, ...|  5|(18054,[1,9,12,61...|[0.00285045818525...|
|[much, tougher, p...|  6|(18054,[27,32,49,...|[0.00485107690380...|

+--------------------+---+--------------------+--------------------

A: This notebook helped me to visualize pyspark LDA topics. It uses D3 bubble chart to visualize the clusters. You could also use pyLDAvis for an interactive topic model visualization.
Here is code with pyspark that shows transforming the topic distribution from .transform API on dataframe. I am using spark LDA example data set in SVM format
# Code to train LDA model using spark ml
from pyspark.ml.clustering import LDA
from pyspark.sql.types import DoubleType
from pyspark.sql import functions as F

# Loads data
dataset = spark.read.format("libsvm").load("file:///usr/sample_lda_libsvm_data.txt")
dataset.show(truncate=False)

Example data
dataset.show(truncate=False)
+-----+---------------------------------------------------------------+
|label|features                                                       |
+-----+---------------------------------------------------------------+
|0.0  |(11,[0,1,2,4,5,6,7,10],[1.0,2.0,6.0,2.0,3.0,1.0,1.0,3.0])      |
|1.0  |(11,[0,1,3,4,7,10],[1.0,3.0,1.0,3.0,2.0,1.0])                  |
|2.0  |(11,[0,1,2,5,6,8,9],[1.0,4.0,1.0,4.0,9.0,1.0,2.0])             |
|3.0  |(11,[0,1,3,6,8,9,10],[2.0,1.0,3.0,5.0,2.0,3.0,9.0])            |
|4.0  |(11,[0,1,2,3,4,6,9,10],[3.0,1.0,1.0,9.0,3.0,2.0,1.0,3.0])      |
|5.0  |(11,[0,1,3,4,5,6,7,8,9],[4.0,2.0,3.0,4.0,5.0,1.0,1.0,1.0,4.0]) |
|6.0  |(11,[0,1,3,6,8,9,10],[2.0,1.0,3.0,5.0,2.0,2.0,9.0])            |
|7.0  |(11,[0,1,2,3,4,5,6,9,10],[1.0,1.0,1.0,9.0,2.0,1.0,2.0,1.0,3.0])|
|8.0  |(11,[0,1,3,4,5,6,7],[4.0,4.0,3.0,4.0,2.0,1.0,3.0])             |
|9.0  |(11,[0,1,2,4,6,8,9,10],[2.0,8.0,2.0,3.0,2.0,2.0,7.0,2.0])      |
|10.0 |(11,[0,1,2,3,5,6,9,10],[1.0,1.0,1.0,9.0,2.0,2.0,3.0,3.0])      |
|11.0 |(11,[0,1,4,5,6,7,9],[4.0,1.0,4.0,5.0,1.0,3.0,1.0])             |
+-----+---------------------------------------------------------------+

Train a LDA model
# Trains a LDA model
lda = LDA(k=10, maxIter=10)
model = lda.fit(dataset)

# Describe topics.
topics = model.describeTopics(3)
print("The topics described by their top-weighted terms:")
topics.show(truncate=False)

The topics described by their top-weighted terms:
+-----+-----------+---------------------------------------------------------------+
|topic|termIndices|termWeights                                                    |
+-----+-----------+---------------------------------------------------------------+
|0    |[4, 7, 10] |[0.10782284792565977, 0.09748059037449146, 0.09623493647157101]|
|1    |[1, 6, 9]  |[0.16755678146051728, 0.14746675884135615, 0.12291623854765772]|
|2    |[3, 10, 6] |[0.2365737123772152, 0.10497827056720986, 0.0917840535687615]  |
|3    |[1, 3, 7]  |[0.1015758016249506, 0.09974496621850018, 0.09902599541011434] |
|4    |[9, 10, 3] |[0.10479879348457938, 0.10207370742688827, 0.09818478669740321]|
|5    |[8, 5, 7]  |[0.10843493028120557, 0.0970150424500599, 0.09334497822531877] |
|6    |[8, 5, 0]  |[0.09874156962344234, 0.09654280831555884, 0.09565956823827508]|
|7    |[9, 4, 7]  |[0.11252483000458603, 0.09755087587088286, 0.09643430900592685]|
|8    |[4, 1, 2]  |[0.10994283713713536, 0.09410686873447463, 0.0937471573628509] |
|9    |[5, 4, 0]  |[0.15265940066441183, 0.14015412109446546, 0.13878634876078264]|
+-----+-----------+---------------------------------------------------------------+

View topic distribution for every document
# view topic distribution for every document
transformed = model.transform(dataset)
transformed.show(truncate=False)

+-----+---------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|label|features                                                       |topicDistribution                                                                                |
+-----+---------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|0.0  |(11,[0,1,2,4,5,6,7,10],[1.0,2.0,6.0,2.0,3.0,1.0,1.0,3.0])      |[0.004830688509084788,0.9563375886321935,0.004924669693727129,0.004830693291141946,0.004830675601199576,0.004830690970098452,0.004830731737552684,0.004830674902568036,0.004830730786933749,0.004922855875500012]       |
|1.0  |(11,[0,1,3,4,7,10],[1.0,3.0,1.0,3.0,2.0,1.0])                  |[0.008057778755383592,0.3149188541525326,0.00821568856074705,0.008057899973735082,0.00805773202965193,0.00805773219443841,0.00805772753178338,0.008057790266770967,0.008057845264839285,0.6204609512701176]             |
|2.0  |(11,[0,1,2,5,6,8,9],[1.0,4.0,1.0,4.0,9.0,1.0,2.0])             |[0.004199741171245032,0.9620401773226402,0.004281469704273017,0.004199769097486346,0.004199807571784884,0.004199819505813106,0.004199835506062414,0.004199781772904878,0.004199800982100323,0.004279797365689855]       |
|3.0  |(11,[0,1,3,6,8,9,10],[2.0,1.0,3.0,5.0,2.0,3.0,9.0])            |[0.003714896800546591,0.5070516557688054,0.4631584573147577,0.003714914880264338,0.0037150085177011572,0.003714949896828997,0.0037149846555122436,0.003714886267751718,0.003714909060953893,0.003785336836878225]       |
|4.0  |(11,[0,1,2,3,4,6,9,10],[3.0,1.0,1.0,9.0,3.0,2.0,1.0,3.0])      |[0.004024716198633711,0.004348960756766257,0.9633765414688664,0.004024715826289515,0.0040247523412803785,0.004024714760590197,0.004024750967476446,0.004024750137766685,0.004024763598734582,0.004101333943595805]      |
|5.0  |(11,[0,1,3,4,5,6,7,8,9],[4.0,2.0,3.0,4.0,5.0,1.0,1.0,1.0,4.0]) |[0.003714916720108325,0.004014106400247752,0.0037876992243613913,0.0037149522531312196,0.0037149927030871474,0.0037149587146134535,0.0037149750439419123,0.0037150099006180567,0.003714963609773339,0.9661934254301174] |
|6.0  |(11,[0,1,3,6,8,9,10],[2.0,1.0,3.0,5.0,2.0,2.0,9.0])            |[0.003863637584067354,0.44120209378688086,0.5278152614977222,0.0038636593932357263,0.003863751204372584,0.0038636970054184935,0.003863731528120536,0.0038636169190041057,0.003863652151710295,0.003936898929468125]     |
|7.0  |(11,[0,1,2,3,4,5,6,9,10],[1.0,1.0,1.0,9.0,2.0,1.0,2.0,1.0,3.0])|[0.004390955723890411,0.004745014492795635,0.9600436030532219,0.004390986523517605,0.004391013571891052,0.004390968206875746,0.004391003804300225,0.004390998289212864,0.0043910030406065104,0.004474453293687847]      |
|8.0  |(11,[0,1,3,4,5,6,7],[4.0,4.0,3.0,4.0,2.0,1.0,3.0])             |[0.004391082468515706,0.004744799620819518,0.004477230286216996,0.004391179034422902,0.004391083385391976,0.0043911102087152145,0.004391108242443274,0.0043911476110250714,0.0043911508747108575,0.9600401082677386]    |
|9.0  |(11,[0,1,2,4,6,8,9,10],[2.0,8.0,2.0,3.0,2.0,2.0,7.0,2.0])      |[0.0033302167739046973,0.9698998050463385,0.0033949933226572675,0.0033302031974203014,0.0033302208173504686,0.003330228671311114,0.0033302277108795157,0.003330230056473623,0.0033302455331591036,0.0033936288705052665]|
|10.0 |(11,[0,1,2,3,5,6,9,10],[1.0,1.0,1.0,9.0,2.0,2.0,3.0,3.0])      |[0.0041998552715806015,0.004538086674649772,0.9617828003374762,0.0041998854155415434,0.004199964563679233,0.004199898040748559,0.004199948969028732,0.004199941207400563,0.004199894377993083,0.004279725141901989]     |
|11.0 |(11,[0,1,4,5,6,7,9],[4.0,1.0,4.0,5.0,1.0,3.0,1.0])             |[0.0048305604098789244,0.005219225001032762,0.004924487214200011,0.004830543265675906,0.00483056515654878,0.004830577688731923,0.004830590528195045,0.004830599936989683,0.004830615233900232,0.9560422355648467]       |
+-----+---------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+

Schema of transformed model
transformed.printSchema()
root
|-- label: double (nullable = true)
|-- features: vector (nullable = true)
|-- topicDistribution: vector (nullable = true)

As you notice topicDistribution is a vector. Below helper function helps parsing a vector.
def ith_(v, i):
    try:
        return float(v[i])
    except ValueError:
        return None

ith = F.udf(ith_, DoubleType())

Format to display each topic distribution for every document as separate column
df = transformed.select(["label"] + [ith("topicDistribution", F.lit(i)).alias('topic_'+str(i)) for i in range(10)] )
df.show(truncate=False)
+-----+---------------------+---------------------+---------------------+---------------------+---------------------+---------------------+---------------------+---------------------+---------------------+---------------------+
|label|topic_0              |topic_1              |topic_2              |topic_3              |topic_4              |topic_5              |topic_6              |topic_7              |topic_8              |topic_9              |
+-----+---------------------+---------------------+---------------------+---------------------+---------------------+---------------------+---------------------+---------------------+---------------------+---------------------+
|0.0  |0.004830687791450502 |0.9563377999372255   |0.004830652446299898 |0.004830693203685635 |0.004924680975321234 |0.004830690324650106 |0.004830724790894176 |0.004830674545741453 |0.004830728328369402 |0.00492266765636222  |
|1.0  |0.00805777782592821  |0.3150888304586096   |0.008057821375392899 |0.008057900091752447 |0.00821563090347786  |0.008057731378987427 |0.008057716226340182 |0.00805778996991863  |0.008057841440203276 |0.6202909603293896   |
|2.0  |0.004199740539975822 |0.9620403414727842   |0.004199830281319767 |0.004199769011855544 |0.004281446354869374 |0.004199818930938506 |0.004199829456280457 |0.004199781450899189 |0.004199798835689997 |0.00427964366538733  |
|3.0  |0.003714883352496639 |0.39438266523895776  |0.0037149161634889914|0.003714899290148889 |0.5758276298046127   |0.003714939245435922 |0.0037149657297638815|0.003714878209574761 |0.0037148981104253493|0.0037853248550950695|
|4.0  |0.00402472343811409  |0.0043486720544167945|0.0040247584323080295|0.004024726616022349 |0.9633767817635327   |0.004024722506471514 |0.004024749723387701 |0.004024759068339994 |0.00402477228684825  |0.0041013341105585275|
|5.0  |0.0037149161731463167|0.00401410657859215  |0.0037150318186438148|0.003714952190974752 |0.0037876713720541993|0.003714958223027372 |0.003714969707955506 |0.0037150096299263177|0.003714961725756829 |0.9661934225799228   |
|6.0  |0.0038636235465470963|0.32506932380193027  |0.0038636563625666425|0.003863644344443025 |0.6439482136665527   |0.0038636867164242353|0.003863712160357752 |0.003863609226073573 |0.003863641557265962 |0.00393688861783849  |
|7.0  |0.004390963901259502 |0.004744419369141901 |0.004391020228883301 |0.00439099927884862  |0.9600441405838983   |0.004390977425037901 |0.004391002809855065 |0.004391008592998927 |0.004391013090740394 |0.004474454719336111 |
|8.0  |0.004391081853379135 |0.004744865767572997 |0.004391206214702098 |0.004391178993516226 |0.004477132667794462 |0.0043911096593825015|0.0043911019675074445|0.004391147323286589 |0.0043911486798455125|0.960040026873013    |
|9.0  |0.003330216240957084 |0.9698999783457445   |0.00333023738785573  |0.0033302030986131904|0.003394973102900875 |0.0033302280874212362|0.0033302228867079335|0.0033302291785187624|0.0033302391644247616|0.003393472506855918 |
|10.0 |0.004199858865711682 |0.004538534384183169 |0.004199958349762097 |0.004199894260340701 |0.9617823390796781   |0.004199903494953782 |0.0041999446501473445|0.004199945557171458 |0.004199899755712464 |0.004279721602339041 |
|11.0 |0.00483055973980833  |0.005219211145215135 |0.004830592303351509 |0.004830543225945144 |0.004924458988916403 |0.004830577090650675 |0.004830583633398643 |0.004830599625982923 |0.004830612825588896 |0.9560422614211423   |
+-----+---------------------+---------------------+---------------------+---------------------+---------------------+---------------------+---------------------+---------------------+---------------------+---------------------+

You can use the results from here to visualize topic distribution for a document or topics with top-weighted terms.


text:
Q: React and Redux Architecture I have questions about React and Redux architecture.
Suppose you have normalized data
const user = [
  { userId: 1, name: 'Ian', groupId: 1 },
  { userId: 2, name: 'Tom', groupId: 2 }
]

const groups = [
  { groupId: 1, groupName: 'Facebook developers'},
  { groupId: 2, groupName: 'Google developers'}
]

const chat = {
  { userIdFrom: 1, message: 'Hello!', timestamp: 1324132332 },
}

What is the best practice to manipulate data such as .map, .filter, .reduce, .forEach, .sort, denormalization etc?
I create utils functions to handle huge data manipulation like Utils.getChatsFromUsers etc and invoked from render method on Component.
Is this my solution good practice to handle huge and many data manipulation in Component's render function?
Please give me your advise and insight.
Thanks!

A: It is not really a good practice to manipulate arrays inside the render method unless the array is the only thing being rendered, or if the array is the prop the will most likely change. You should manipulate them in the componentWillReceiveProps.
So, instead of having something like this:
render() {
    const { string1, string2, string3, array } = this.props;
    const mappedArray = array.map(element =>
{element}
);
    return (

{string1}

{string3}

{string3}

{mappedArray}

  );
}

you should do something like this:
componentWillReceiveProps(nextProps) {
  // R is from ramda, but you can compare the arrays any way you want
  // even just comparing the array references if that's good enough for you
  if (R.equals(nextProps.array, this.props.array)) {
    this.mappedArray = array.map(element =>
{element}
);
  }
}

render() {
    const { string1, string2, string3, array } = this.props;
    return (

{string1}

{string3}

{string3}

{this.mappedArray}

  );
}

This way you avoid having to recreate the mapped array every time the render method is called (which could happen from other props changing or the state being changed).
This topic is covered here.


text:
Q: How to Gather & Parse JSON Data in HTML I'm ultimately looking to create a HTML file that will accomplish the following tasks.  The point is, I need it to be all inclusive in an HTML snippet/file.

*

*Make a GET api call to a backend CMS (ie:  Drupal). This api call returns the following JSON data for a specific content item:

{
    "jsonapi": {
        "version": "1.0",
        "meta": {
            "links": {
                "self": {
                    "href": "http://jsonapi.org/format/1.0/"
                }
            }
        }
    },
    "data": {
        "type": "node--espot_html",
        "id": "fbaab7dd-09c2-4aa0-852d-4b9462074a45",
        "attributes": {
            "drupal_internal__nid": 1,
            "drupal_internal__vid": 11,
            "langcode": "en",
            "revision_timestamp": "2019-10-31T13:29:29+00:00",
            "revision_log": null,
            "status": true,
            "title": "Razor Hero Image",
            "created": "2019-10-28T16:24:20+00:00",
            "changed": "2019-10-31T13:29:29+00:00",
            "promote": true,
            "sticky": false,
            "default_langcode": true,
            "revision_translation_affected": true,
            "path": {
                "alias": "/razor-hero",
                "pid": 1,
                "langcode": "en"
            },
            "body": {
                "value": "
\r\n
\r\n
\r\n
\r\n
\r\n
Get a Much Better
\r\nShave
\r\n\r\n
Fewer things look and feel better than a clean shave!
\r\nSHOP NOW
\r\n
\r\n
\r\n
\r\n
\r\n",
                "format": "full_html",
                "processed": "

\n
\n
\n
\n
Get a Much Better
\nShave
\n\n
Fewer things look and feel better than a clean shave!
\nSHOP NOW
\n
\n
\n
\n
\n",
                "summary": ""
            }
        },
        "relationships": {
            "node_type": {
                "data": {
                    "type": "node_type--node_type",
                    "id": "837a5cbe-f8fe-4c03-a613-2092dff1168e"
                },
                "links": {
                    "self": {
                        "href": "http://localhost:4700/jsonapi/node/espot_html/fbaab7dd-09c2-4aa0-852d-4b9462074a45/relationships/node_type?resourceVersion=id%3A11"
                    },
                    "related": {
                        "href": "http://localhost:4700/jsonapi/node/espot_html/fbaab7dd-09c2-4aa0-852d-4b9462074a45/node_type?resourceVersion=id%3A11"
                    }
                }
            },
            "revision_uid": {
                "data": {
                    "type": "user--user",
                    "id": "c0d80edb-325a-4ad7-9be3-bc9dc32ed878"
                },
                "links": {
                    "self": {
                        "href": "http://localhost:4700/jsonapi/node/espot_html/fbaab7dd-09c2-4aa0-852d-4b9462074a45/relationships/revision_uid?resourceVersion=id%3A11"
                    },
                    "related": {
                        "href": "http://localhost:4700/jsonapi/node/espot_html/fbaab7dd-09c2-4aa0-852d-4b9462074a45/revision_uid?resourceVersion=id%3A11"
                    }
                }
            },
            "uid": {
                "data": {
                    "type": "user--user",
                    "id": "c0d80edb-325a-4ad7-9be3-bc9dc32ed878"
                },
                "links": {
                    "self": {
                        "href": "http://localhost:4700/jsonapi/node/espot_html/fbaab7dd-09c2-4aa0-852d-4b9462074a45/relationships/uid?resourceVersion=id%3A11"
                    },
                    "related": {
                        "href": "http://localhost:4700/jsonapi/node/espot_html/fbaab7dd-09c2-4aa0-852d-4b9462074a45/uid?resourceVersion=id%3A11"
                    }
                }
            }
        },
        "links": {
            "self": {
                "href": "http://localhost:4700/jsonapi/node/espot_html/fbaab7dd-09c2-4aa0-852d-4b9462074a45?resourceVersion=id%3A11"
            }
        }
    },
    "links": {
        "self": {
            "href": "http://localhost:4700/jsonapi/node/espot_html/fbaab7dd-09c2-4aa0-852d-4b9462074a45"
        }
    }
}

*I'm then looking for the JSON response to be parsed to extract the only the data under the "value": object.

*I need to have the escape characters removed

*The end result should be that the HTML (shown below) is rendered in the browser:

Get a Much Better
Shave

Fewer things look and feel better than a clean shave!
SHOP NOW

"

*If processed successfully, this is what should display on the webpage:
Screenshot if image rendered via HTML

*Here is the HTML I have tried.  My apologies for breaking etiquette, I was not aware this would be perceived as such.  In my browsers console it tells me the forEach is not a valid function or this response.

'<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <title>Ghibli App</title>

    <link href="https://fonts.googleapis.com/css?family=Dosis:400,700" rel="stylesheet" />

'

A: This ended up producing the end result that I was looking to produce:

<!DOCTYPE html>