text:
Q: Converting a PDE into the heat equation I am looking at a PDE ${v_t}\left( {t,y} \right) = 4y{v_{yy}}\left( {t,y} \right) + 2{v_y}\left( {t,y} \right)$ defined for $\left( {t,y} \right) \in (\pi ,\infty ) \times (0,\infty )$. I think I should be able to transform this into the heat equation, but I am unable to think up of a transformation that would let me get rid of the y in $4y{v_{yy}}\left( {t,y} \right)$, without introducing more variables in the coefficients. The $\pi$ in the domain suggests that the transformation for the first variable at least would involve sin. Any suggestions for what kind of transformation I should perhaps try? Grateful for a nudge in any direction actually, I am stuck

A: There are two things in this equation that separate it from a heat equation:

*

*The coefficient in front of $v_{yy}$ depending on $y$. The usual heat equation has constant coefficients.

*The term $v_y$. The heat equation does not have any first order spatial derivatives.

We can deal with each thing separately.
To deal with the coefficient: changing coefficients in differential equations can usually be done by rescaling. We will define a new function $w$ such that
$$w(t,y)=v(\lambda t, \mu y),$$
for $\lambda$ and $\mu$ to be determined. First we compute the relevant time and space derivatives for this new function:

*

*$w_t=\lambda v_t$.

*$w_y=\mu v_y$.

*$w_{yy}=\mu v_{yy}$.

Now we plug these into your equation to obtain
$$w_{t} = \frac{\lambda}{\mu^2}4yw_{yy} + \frac{\lambda}{\mu}2w_{y},$$
so we can choose $\mu=\lambda=4y$, and the equation becomes
$$w_{t} = w_{yy} + 2w_{y}.$$ Much nicer!
To deal with the first spatial derivative: The equation we just arrived can be written as
$$w_{t} - 2w_{y} = w_{yy}.$$
You might have seen this type of equation before, it's a transport equation with diffusion. The left hand side is often called a transport operator, which causes the solution to travel in time. If the equation were just $$w_{t} - 2w_{y} = 0,$$ then the solution would simply transport the initial data $w(0,y)$ horizontally.
This suggests a way to deal with the extra term: we can change the spatial coordinates again to make the solution move in time, and this should counteract the transport term. I.e. let's define
$$u(t,y) = w(t, y+ct)$$
and choose $c$ later. We compute derivatives again:

*

*$u_{t} = w_t + cw_y$.

*$u_{y} = w_y$.

*$u_{yy} = w_{yy}$.

If we pick $c=-2$ and plug these into the equation, we get
$$u_{t} = u_{yy},$$
our beloved heat equation.
I hope this helps!


text:
Q: Почему эта строчка является вирусом для Касперского? Код из листинга (Delphi):
SendMessage(WindowFromPoint(Mouse.CursorPos),EM_SETPASSWORDCHAR,0,0);
Касперский сразу визжит и пишет:

Что в этом коде не так? Почему он считается вирусом?

A: Данное сообщение позволяет сделать из поля ввода со звездочками обычное поле ввода, таким образом узнав введенный пароль. Этим пользуется ряд программ.
Поэтому Касперский и ругается.

redpajama_set_name: RedPajamaStackExchange


text:
Q: wordpress unregister parent theme sidebar in child theme not working I see very plainly how the parent theme is registering the widget area (in parent theme's functions.php file):
add_action( 'widgets_init', 'theme_widgets_init' );
function theme_widgets_init(){
    register_sidebar( array (
        'name' => __( 'Sidebar Widget Area', 'text-domain' ),
        'id' => 'primary-widget-area',
        'before_widget' => '
',
        'after_widget' => "
",
        'before_title' => '
',
        'after_title' => '
',
    ) );
}

In simple theory, I don't know why this code (in the child theme folder's functions.php file) is not killing the sidebar widget area from displaying in the backend in Appearance > Widgets:
add_action( 'widgets_init', 'unregister_parent_sidebar' );
function unregister_parent_sidebar(){
    unregister_sidebar( 'primary-widget-area' );
}

A: You need to give higher weight to un-register sidebars. See 3rd argument in add_action function.
    function unregister_widgets_area(){

        // Unregister some of the sidebars
        unregister_sidebar( 'first-widget-area' );
        unregister_sidebar( 'second-widget-area' );
        unregister_sidebar( 'third-widget-area' );
    }

    add_action( 'widgets_init', 'unregister_widgets_area', 11 );


text:
Q: Multiple Booting I have Dell Inspiron shipped with Win 10 Home Edition and MS Office. 1 TB of HDD with partition of C: 416 GB; E and F each having 249 GB. I want to Boot Ubuntu LTS, Kali Linux, Arch Linux and Fedora. Later on maybe Gentoo and Slackware also.

*

*Will this Multiple booting cause any problem to Win 10 and purchased applications from MS Store?

*How do I partition 249 GB of F Drive for each of these OS? (when I shrink Volume in Disk Management Utility, it all goes into one Unallocated space. Or shall I Make New Volumes to Boot Different OS)

Any recommendation on multiple Booting will be of great help. Consider Me taking 1st Dive into Ocean of Linux

A: It is quite difficult to install so many operating systems on just one or two drives. I would suggest to use VMs in that case.

A: I don't think multi booting will mess with Win10 or purchased applications normally.
Since you have unallocated space, you can install a distro right on the unallocated space, as most linux distros will have options to help with creating a new volume and partitioning. I don't think you need to create a new volume first on windows. I know this to be true for all debian based operating systems.


text:
Q: VMWare workstation freezes, lags and khugepaged consumes 100% CPU in Ubuntu host Sometimes VMWare workstation lags (stuttering) or even freezes and often even freezes my host operating system. Usually this happens when under high load of the CPU or the GPU. In many cases typing text in the guest OS can trigger stuttering behaviour.
When freezing, the processes vmware-vmx and khugepaged get 100% cpu time for a couple of seconds.

A: This is not my solution (I don't know what the consequences of disabling khugepaged are) but it worked for me:

The khugepaged is the process that configures the transparent hugepages. When i disable the transparent hugepages windows guest run without freezes again. To disable it on every operating system start up i put in /etc/rc.local

if test -f /sys/kernel/mm/transparent_hugepage/enabled; then
    echo never > /sys/kernel/mm/transparent_hugepage/enabled
fi
if test -f /sys/kernel/mm/transparent_hugepage/defrag; then
    echo never > /sys/kernel/mm/transparent_hugepage/defrag
fi

Source: http://unversioned.blogspot.be/2015/10/vmware-workstation-11-ubuntu-high-cpu-utilization.html
EDIT: in hindsight this only seems to reduce the amount of freezes, but they still do occur. Especially when closing and then re-opening the VM, and strangely also especially when running simultaneously having Firefox open ...


text:
Q: JavaScript SyntaxError: Unexpected identifier when setting Grunt tasks I'm trying to set up a couple of tasks for Grunt but there seems to be an error that I can't find. JSlint points out to the watch section with the following error:

Unexpected token, expected ,

While in the terminal I get:

SyntaxError: Unexpected identifier Warning: Task "default" not found. Use --force to continue.

module.exports = function(grunt) {
  grunt.initConfig({

    pkg: grunt.file.readJSON('package.json'),

    sass: {
      dev: {
        options: {
          style: 'expanded',
          sourcemap: 'none'
        },
        files: {
          'compiled/style.css':'sass/style.scss'
        }
      },
      dist: {
        options: {
          style: 'compressed',
          sourcemap: 'none'
        },
        files: {
          'compiled/style-min.css': 'sass/style.scss'
        }
      }
    }

     watch: {
       css: {
         files: '**/*.scss',
         tasks: ['sass']
       }
     }

  });

  grunt.loadNpmTasks('grunt-contrib-sass');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.registerTask('default',['watch']);
}

A: I believe you are missing a comma before Watch.
module.exports = function(grunt) {
  grunt.initConfig({

    pkg: grunt.file.readJSON('package.json'),

    sass: {
      dev: {
        options: {
          style: 'expanded',
          sourcemap: 'none'
        },
        files: {
          'compiled/style.css':'sass/style.scss'
        }
      },
      dist: {
        options: {
          style: 'compressed',
          sourcemap: 'none'
        },
        files: {
          'compiled/style-min.css': 'sass/style.scss'
        }
      }
    },

     watch: {
       css: {
         files: '**/*.scss',
         tasks: ['sass']
       }
     }

  });

  grunt.loadNpmTasks('grunt-contrib-sass');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.registerTask('default',['watch']);
}

Hope this helps


text:
Q: How does IIS Know how to start .NET Web Application I'm trying to understand how IIS knows how to start my ASP.Net Web Application My understanding so far is that, when creating a web application we create a Web.Config which defines how IIS will start it's process
So We have a Web Config
<system.webServer>
  <modules runAllManagedModulesForAllRequests="true">
    <add name="LogRequests" type="BDBPayroll.Apps.API.Web.Shared.HttpModules.LogRequestsHttpModule, BDBPayroll.Apps.API.Web.Shared" />
    <add name="MiniProfiler" type="BDBPayroll.Apps.API.Web.Shared.HttpModules.MiniProfilerHttpModule, BDBPayroll.Apps.API.Web.Shared" />
  </modules>
  <handlers>
    <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
    <remove name="OPTIONSVerbHandler" />
    <remove name="TRACEVerbHandler" />
    <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
  </handlers>
</system.webServer>

And The Global Asax:
public class WebApiApplication : WebApiHttpApplication<WebModule>
{
    protected override void Configure(HttpConfiguration config)
    {
        config.Filters.Add(new Filters.ContextResolverFilter());
        config.Filters.Add(new ValidateModelAttribute());
        config.Filters.Add(new PaginationFilter());

        GlobalContext<JsonFormatterRule>.Instance.SetDefaultJsonFormatter(config);

    }
    //...
}

Since IIS can run multiple applications e.g php, .net etc, How does IIS Know from the Web Config To run the Global Asax.
My guess is that it looks up the application type from the web config, and then searches for WebApiHttpApplication, Does anybody have any more information on this process?

A:
Since IIS can run multiple applications e.g php, .net etc, How does IIS Know from the Web Config To run the Global Asax.
My guess is that it looks up the application type from the web config, and then searches for WebApiHttpApplication, Does anybody have any more information on this process?

As far as I know, if use send the request to the IIS.
After handling the http request by http.sys, IIS will move this request to the w3wp.exe to handle it.
Since IIS could only handle htm or html static page, IIS will use ISAPI to handle the page which IIS couldn't handle.
ISAPI is a kind of extention handler to handle different kinds of pages like php, aspx, cshtml or something else.
You could find it from IIS manager console handler mapping icon.
Image as below:

The IIS will send the request to right http hanlder according to its extension. The handler moudule(e.g asp.net isapi) will load the CLR and web application(include the globalasax) to handle the request.


text:
Q: How to prevent ToString("0,0") to return 00 I have a bunch of integers that I have to display in one of my views.
I display them this way:
int myVariable = 12500;
myVariable.ToString("0,0", System.Globalization.CultureInfo.InvariantCulture).Replace(",", " ")

If myVariable contains 12500, it will display: 12 500. This is exactly what I want.
However, if myVariable contains 0, it will display: 00. Instead of 00, I want 0 to be displayed.
I've looked on MSDN about Custom number formats and I haven't found anything that could help me. If it's possible, I would like to not be able to do some more string management (replace, etc). Just switching the format from 0,0 to something that would work for me.

A: I suspect you want:
myVariable.ToString("#,0", ...)

Although I'd be surprised if one of the standard string formats didn't handle this. For example, you could use:
myVariable.ToString("N0", ...)

Also note that instead of using the invariant culture and then replacing comma with space, you could create your own culture (based on the invariant culture, potentially) with a NumberGroupSeparator of " ".
Sample code:
// You don't need to create this every time. Create it once and put it in a static variable.
var culture = (CultureInfo) CultureInfo.InvariantCulture.Clone();
culture.NumberFormat.NumberGroupSeparator = " ";

Console.WriteLine(12345.ToString("N0", culture)); // 12 345


text:
Q: waf will not find correct python version I've been trying to build pycairo on my machine, which ships with waf. Upon running ./waf configure, I get the following result:
Checking for program python              : /usr/bin/python
Checking for python version              : (2, 7, 6, 'final', 0)
The python version is too old, expecting (3, 1, 0)
(complete log in /Users/USER/Downloads/pycairo-1.10.0/build_directory/config.log)

I have python 3 installed to /usr/local/bin/python3, but I don't know after reading waf's documentation how to override this. I am on OS X Yosemite 10.10.4.

A: How about running /usr/local/bin/python3 ./waf configure? This should force waf to use the correct python version.
EDIT: Try the following --
export PYTHON=/usr/local/bin/python3
./waf configure


text:
Q: Node.js, vs. Electron:: Run external command and show the stdout on interface I'm new to node.js and Electron and trying to run an external command in Electron and show the result with HTML.
I made an HTTP server-client version with node.js, which works fine.
But failed to make it to work with the Electron, even after following many answers here, such as

*

*Node.js spawn child process and get terminal output live

*Piping data from child to parent in nodejs
None of them worked for me for Electron.
Node.js version works.
I'm showing my working node.js code as follows. This code, after running node index.js, and open localhost:8888/start in the browser, will show the output of ls -al on the webpage:

// index.js

var server = require("./server");
var router = require("./router");
var requestHandlers = require("./requestHandlers");

var handle = {};
handle["/"] = requestHandlers.start;
handle["/start"] = requestHandlers.start;
handle["/upload"] = requestHandlers.upload;

server.start(router.route, handle);

The HTTP server:
// server.js

var http = require("http");
var url = require("url");

function start(route, handle) {
    http.createServer(function(request, response) {
        var pathname = url.parse(request.url).pathname;
        console.log("Request for " + pathname + " received.");

        route(handle, pathname, response);
}).listen(8888);

    console.log("Server has started.");
}

exports.start = start;

The router that handles two requests, i.e., start/upload, differently:
//router.js

function route(handle, pathname, response) {
    console.log("About to route a request for " + pathname);
    if (typeof handle[pathname] == 'function') {
        handle[pathname](response);
    } else {
        console.log("No request handler found for " + pathname);

        // send an HTTP status and content-type in the HTTP response *header*
        // back to the browser that requested your server).
        response.writeHead(404, {"Content-Type": "text/plain"});
        // send text in the HTTP response *body*.
        response.write("404 Not found");
        // finish the response.
        response.end();
    }
}

exports.route=route;

The actual request handlers:

// requestHandlers.js

var exec = require("child_process").exec;

function start(response) {
    console.log("Request handler 'start' was called.");
    var content = "empty";

    exec("ls -al",
        {timeout: 10000, maxBuffer: 20000*1024},
        function(error, stdout, stderr) {
            // send an HTTP status 200 and content-type in the HTTP response *header*
            // back to the browser that requested your server).
            response.writeHead(200, {"Content-Type": "text/plain"});

            // send text in the HTTP response *body*.
            response.write(stdout);

            // finish the response.
            response.end();
        });
}

function upload(response) {
    console.log("Request handler 'upload' was called.");
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.write("You've uploaded data");
    response.end();
}

exports.start = start;
exports.upload = upload;

The above code worked for me in Safari.
Electron version fails
Now I wanted to do the similar thing with Electron: Enter a command in an Entry box, run it through a submit button, and show the result on the same page below the controls. Here is my main process:

// main.js

const {app, BrowserWindow} = require('electron');

let mainWindow = null;

app.on('ready', () => {
    console.log('Hello from Electron');
    mainWindow = new BrowserWindow({
        webPreferences: {
            nodeIntegration: true
        }
    });

    mainWindow.webContents.openDevTools()

    mainWindow.webContents.loadFile('./app/index.html');

    // mainWindow events, within app lifecycle
    mainWindow.webContents.on('did-fail-load', function() {
        console.log("Failed to load index.html");
    })

})

Now the renderer process:

// renderer.js

const { shell } = require('electron');

const parser = new DOMParser();

const resultSection = document.querySelector('.results');
const errorMessage = document.querySelector('.error-message');
const newCmdForm = document.querySelector('.new-cmd-form');
const newCmd = document.querySelector('.new-external-cmd');
const newCmdSubmit = document.querySelector('.new-cmd-run');
const clearStorageButton = document.querySelector('.clear-results');

newLinkForm.addEventListener('submit', (event) => {
    const cmd = newCmd.value;
    processCmd(cmd);
});

const processCmd = (cmd) => {
    var exec = require('child_process').exec;

    exec("ls -al", {timeout: 10000, maxBuffer: 20000*1024},
        function(error, stdout, stderr) {
            var out = stdout.toString();
            var result =
                '<div class="text"' +
                `<h3>${out}</h3>` +
                '
';
            resultSection.innerHTML = result;
            console.log(result)
        });
}

const renderResults = () => {
    resultSection.innerHTML = '';
};

renderResults();

Here is the page:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="Content-Security-Policy" content="
        default-src 'self';
        script-src 'self' 'unsafe-inline';
        connect-src *">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Cmdlet</title>
    <link rel="stylesheet" href="style.css" type="text/css">

Cmdlet

    <form class="new-cmd-form">
        <input type="text" class="new-external-cmd" placeholder="default command" size="100" required>
        <input type="submit" class="new-cmd-run" value="Run">
    </form>

    <button class="clear-results">Clear</button>

Knowing that the calling of external command is async, I put the renderer update code in the callback. However, this code shows [object Object] in the target area, instead of the output of ls -al.
Where was I wrong?

A: // renderer.js

const { shell } = require('electron');

const parser = new DOMParser();

const resultSection = document.querySelector('.results');
const errorMessage = document.querySelector('.error-message');
const newCmdForm = document.querySelector('.new-cmd-form');
const newCmd = document.querySelector('.new-external-cmd');
const newCmdSubmit = document.querySelector('.new-cmd-run');
const newLinkForm = document.querySelector('.new-cmd-form');
const clearStorageButton = document.querySelector('.clear-results');

newLinkForm.addEventListener('submit', (event) => {
    event.preventDefault()
    const cmd = newCmd.value;
    console.log(event)
    processCmd('cmd');
});

const processCmd = (cmd) => {
    var exec = require('child_process').exec;

    exec("ls -al", {timeout: 10000, maxBuffer: 20000*1024},
        function(error, stdout, stderr) {
            var out = stdout.toString();
            const outArray = out.split('\n');

            let result = '
 {
                result += `<h3>${e}</h3>`
            });
            result += '
';
            resultSection.innerHTML = result;
            console.log(result)
        });
}

const renderResults = () => {
    resultSection.innerHTML = '';
};

renderResults();

Try to use this. I added some changes at your renderer.js
This will be working well.
But I'd like to recommend to do these kind of operation at main process.
You know we can use IPC api to communicate between Renderer and Main process.
Have a look at this
https://www.christianengvall.se/main-and-renderer-process-in-electron/
But personally, I don't usually run exec at Renderer process. For this operation, I rather to use this such exec or spawn at main process.
We can use IPC to communicate between Main and Renderer process.
IPCMain is used for listening the events from the Renderer and it's available at only Main process. And IPCRenderer is used for sending the events from Renderer to Main process. So that.
Using IPCRenderer, You can send the event like this at Renderer process.
const { ipcRenderer } = require('electron');

async function runCommand(cmd) {
  const res = await ipcRenderer.sendSync('runCommand', cmd);
  return res;
}

Then at Main process. (main.js)
// Listen runCommand event from the Renderer
// And return the result to Renderer.
ipcMain.on('runCommand', async (event, arg) => {
  event.returnValue = await runCommand(arg);
});

(you can declare the runCommand(arg) function yourself as your needs)
Feel free to use whatever you'd like.

A: *

*Use the node approach

*Use IPCRenderer and IPCMain to poll/respond as to whether the command has completed

*When IPCRenderer is told the content is ready, trigger an AJAX exchange to populate the renderer/website

PS: The documentation on how to use IPC in Electron seemed unclear to me -- and some of it seems not to work correctly! -- so if you need a simple & working example, here's my app's startup splash and here's the app code that responds (see, mainly, lines 96-109 of the latter link).


text:
Q: List all application URLs on iphone/ipad Is there a way to list all the application url schemes registered on a device?
(also on a jailbroken device)

A: Take a look to the list here. I don't know haw you can list all the url schemes for the app on the device.


text:
Q: Contar el número total de archivos en subcarpetas contenidas en varias carpetas con Python Estoy empezando a programar en Python, pero aún soy muy novato. Tengo un directorio (Dataset) con la siguiente estructura de carpetas y subcarpetas:

*

*fold_0:

*

*A

*

*Class_1

*

*files...

*Class_2

*

*files...

*B

*

*Class_1

*

*files...

*Class_2

*

*files...

*C

*

*Class_1

*

*files...

*Class_2

*

*files...

*fold_1

*

*A

*

*Class_1

*

*files...

*Class_2

*

*files...

*B

*

*Class_1

*

*files...

*Class_2

*

*files...

*C

*

*Class_1

*

*files...

*Class_2

*

*files...

*...

*...

*fold_10

Tengo que contar el número de archivos para cada clase (subcarpetas Class_1 y Class_2), distinguiendo por subcarpetas A, B y C, y distinguiendo por carpetas desde fold_0 hasta fold_10.
La salida que espero sería (los números son solo como ejemplo):

*

*fold_0:

*A: 8

*

*Class_1: 5

*Class_2: 3

*B: 5

*

*Class_1: 2

*Class_2: 3

*C: 10

*

*Class_1: 4

*Class_2: 6

*fold_1:

*A: 6

*

*Class_1: 3

*Class_2: 3

*B: 7

*

*Class_1: 2

*Class_2: 5

*C: 11

*

*Class_1: 5

*Class_2: 6

*...

*...
Y así para cada carpeta desde fold_0 hasta fold_10. Finalmente, tengo que sumar todas las cantidades agrupando todas las carpetas desde fold_0 hasta fold_10. El resultado sería:

*

*Total A: A(de fold_0) + A(de fold_1) + ... + A(de fold_10) = 8 + 6 + ...

*Total B: B(de fold_0) + B(de fold_1) + ... + B(de fold_10) = 5 + 7 + ...

*Total C: C(de fold_0) + C(de fold_1) + ... + C(de fold_10) = 10 + 11 + ...

*Total Class_1: total Class_1(de fold_0) + total Class_1(de fold_1) + ... + total Class_1(de fold_10) = (5 + 2 + 4) + (3 + 2 + 5) +  ...

*Total Class_2: total Class_2(de fold_0) + total Class_2(de fold_1) + ... + total Class_2(de fold_10) = (3 + 3 + 6) + (3 + 5 + 6) + ...

Con el siguiente código puedo contar los archivos, pero no es la salida que espero:
import os
path = 'Dataset'
for dir,subdir,files in os.walk(path):
    print(dir,' ', str(len(files)))

La salida que obtengo es:
Dataset/Fold0   0
Dataset/Fold0/A    0
Dataset/Fold0/A/Class_1   83
Dataset/Fold0/A/Class_2   93
Dataset/Fold0/B   0
Dataset/Fold0/B/Class_1   71
Dataset/Fold0/B/Class_2   84
Dataset/Fold0/C   0
Dataset/Fold0/C/Class_1   626
Dataset/Fold0/C/Class_2   755
...
...

¿Podría alguien ayudarme?


text:
Q: RoR - password protected model I want to create password protected model. For example Post on the blog. I want to store this password in the database. And if user wants to see password protected post he needs to write this password. If there is no password in database everyone can see this post, each post can have its own pass. How can I create something like this in RoR? I
I only have found basic HTTP auth:
before_filter :authenticate

#protected

def authenticate
  authenticate_or_request_with_http_basic do |username, password|
    username == "foo" && password == "bar"
  end
end

but probably there is better solution for this? Do you have any ideas?

A: Something like this ?
def show
  @post = Post.find(...)

  if params[:post][:password].nil?
    # Show a form with a password asked
  elsif params[:post][:password] == @post.password
    # Show post
  else
    flash[:error] = "Bad password"
    # Render password form
  end
end


text:
Q: How to perform conditional back navigation using Navigation Components? I have a destination fragment called "C" that can be navigated to by using one of 3 different flows.
E.g.
Flow 1: A -> C
Flow 2: A -> B -> C
Flow 3: A -> X -> Y -> C
I'm using global actions to navigate to C because it allows me to use the same action for navigation regardless of if I'm in Flow 1, 2 or 3. That all seems to work fine, but I'm having trouble with navigating back from C now.
For Flows 1 and 2 I want to go from C back to A. I've been doing this by calling .popBackStack(R.id.A, false) which was worked well. Now we've added Flow 3 to our app. In Flow 3,  when I navigate back from C I want to go to X, not A. So my previous solution of using .popBackStack(R.id.A, false) does not work here since this will always bring me back to A.
Is there a recommended way of providing back navigation that is conditional upon how the user got to the destination they're currently at?
I could see examining the existing back stack and if I see X or Y, then I'd know to use .popBackStack(R.id.x, false). or .popBackStack(R.id.a, false).
I could pass in a "back ID" as an argument when launching C which I could then use in .popBackStack(backId, false)
Am I missing something obvious here?


text:
Q: How to parse this json data in Delphi 10 Seattle? I am having trouble parsing this JSON data in Delphi 10 Seattle. I want to get the values from the JSON and show them in TLabel components one by one. I am new to JSON and REST, it would be nice if you provide a working example.
{
  "countrydata":[
    {
      "info":{
        "ourid":119,
        "title":"Pakistan",
        "code":"PK",
        "source":"https://thevirustracker.com/pakistan-coronavirus-information-pk"
      },
      "total_cases":5038,
      "total_recovered":1026,
      "total_unresolved":0,
      "total_deaths":86,
      "total_new_cases_today":27,
      "total_new_deaths_today":0,
      "total_active_cases":3926,
      "total_serious_cases":37,
      "total_danger_rank":33
    }
  ],
  "stat":"ok"
}

EDIT
So far, I have this code but it gives access violation error and no output is given. What am I doing wrong.
procedure TForm1.Button2Click(Sender: TObject);
 var
  jsonRoot: TJSONObject;
  tokenRequest: TRESTRequest;
  tokenResponse: TRESTResponse;
  tokenClient: TRESTClient;
begin
  tokenClient := TRESTClient.Create(nil);
  tokenRequest := TRESTRequest.Create(nil);
  tokenResponse := TRESTResponse.Create(nil);
  try
    tokenRequest.Client := tokenClient;
    tokenRequest.Response := tokenResponse;
    tokenClient.BaseURL := 'https://api.thevirustracker.com/free-api?countryTotal=PK';
    tokenRequest.Execute;
    jsonRoot:= TJSONObject.ParseJSONValue(tokenResponse.JSONText) as TJSONObject;
    Memo1.Lines.Add('TotalCases => ' + jsonRoot.GetValue('total_cases').Value);
    Memo1.Lines.Add('TotalRecovered=> ' + jsonRoot.GetValue('total_recovered').Value);
    Memo1.Lines.Add('TotalDeaths=> ' + jsonRoot.GetValue('total_deaths').Value);
    Memo1.Lines.Add('TotoalNewCases=> ' + jsonRoot.GetValue('total_new_cases_today').Value);
  finally
    tokenResponse.Free;
    tokenRequest.Free;
    tokenClient.Free;
  end;
end;

A: You are getting an Access Violation because you are using TJSONObject incorrectly.
All of the JSON values you are trying to read are not immediate children of the top level object of the JSON hierarchy, where you are expecting, so GetValue() returns a nil pointer, and then your code crashes when it tries to read the Value property using that nil pointer.
The values you want are several levels deeper in the JSON hierarchy. The top level object contains a child named countrydata, which is an array of objects. The values you want are children of the 1st object in that array.
Try this instead:
procedure TForm1.Button2Click(Sender: TObject);
var
  jsonRoot: TJSONValue;
  jsonObj: TJSONObject;
  jsonArr: TJSONArray;
  tokenRequest: TRESTRequest;
  tokenResponse: TRESTResponse;
  tokenClient: TRESTClient;
begin
  tokenClient := TRESTClient.Create(nil);
  try
    tokenClient.BaseURL := 'https://api.thevirustracker.com/free-api?countryTotal=PK';

    tokenRequest := TRESTRequest.Create(tokenClient);
    tokenRequest.Client := tokenClient;

    tokenResponse := TRESTResponse.Create(tokenClient);
    tokenRequest.Response := tokenResponse;

    tokenRequest.Execute;

    jsonRoot := TJSONObject.ParseJSONValue(tokenResponse.JSONText);
    try
      jsonObj := jsonRoot as TJSONObject;
      jsonArr := jsonObj.GetValue('countrydata') as TJSONArray;
      jsonObj := jsonArr.Items[0] as TJSONObject;
      Memo1.Lines.Add('TotalCases => ' + jsonObj.GetValue('total_cases').Value);
      Memo1.Lines.Add('TotalRecovered=> ' + jsonObj.GetValue('total_recovered').Value);
      Memo1.Lines.Add('TotalDeaths=> ' + jsonObj.GetValue('total_deaths').Value);
      Memo1.Lines.Add('TotoalNewCases=> ' + jsonObj.GetValue('total_new_cases_today').Value);
    finally
      jsonRoot.Free;
    end;
  finally
    tokenClient.Free;
  end;
end;

Alternatively, you can use the TRESTResponse.RootElement and TRESTResponse.JSONValue properties instead of calling TJSONObject.ParseJSONValue() manually:
procedure TForm1.Button2Click(Sender: TObject);
var
  jsonObj: TJSONObject;
  jsonArr: TJSONArray;
  tokenRequest: TRESTRequest;
  tokenResponse: TRESTResponse;
  tokenClient: TRESTClient;
begin
  tokenClient := TRESTClient.Create(nil);
  try
    tokenClient.BaseURL := 'https://api.thevirustracker.com/free-api?countryTotal=PK';

    tokenRequest := TRESTRequest.Create(tokenClient);
    tokenRequest.Client := tokenClient;

    tokenResponse := TRESTResponse.Create(tokenClient);
    tokenRequest.Response := tokenResponse;
    tokenResponse.RootElement := 'countrydata';

    tokenRequest.Execute;

    jsonArr := tokenResponse.JSONValue as TJSONArray;
    jsonObj := jsonArr.Items[0] as TJSONObject;
    Memo1.Lines.Add('TotalCases => ' + jsonObj.GetValue('total_cases').Value);
    Memo1.Lines.Add('TotalRecovered=> ' + jsonObj.GetValue('total_recovered').Value);
    Memo1.Lines.Add('TotalDeaths=> ' + jsonObj.GetValue('total_deaths').Value);
    Memo1.Lines.Add('TotoalNewCases=> ' + jsonObj.GetValue('total_new_cases_today').Value);
  finally
    tokenClient.Free;
  end;
end;


text:
Q: NuGet update fails, does not seem to pick up VisualStudioVersion properly? Windows 2012 R2 build server, TeamCity 8.1.2, nuget.exe 2.8.1
After enabling and testing a build configuration that involved a regular full build clean followed by a NuGet restore, we enabled incremental VCS updates and have enabled NuGet update on our build configuration. The build configuration now fails with this error during NuGet update:
[Step 1/4] update: Updating NuGet packages for OurSolutionName.sln
[22:20:10]NuGet command: D:\TeamCity\buildAgent\tools\NuGet.CommandLine.DEFAULT.nupkg\tools\NuGet.exe update D:\TeamCity\buildAgent\work\52034b1c4c1ab5f5\OurSolutionName.sln -Verbose -RepositoryPath D:\TeamCity\buildAgent\work\52034b1c4c1ab5f5\packages
[22:20:10]Starting: D:\TeamCity\buildAgent\temp\agentTmp\custom_script9174264003705363137.cmd
[22:20:10]in directory: D:\TeamCity\buildAgent\work\52034b1c4c1ab5f5
[22:20:10]Scanning for projects...
[22:20:10]The imported project "C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\TypeScript\Microsoft.TypeScript.targets" was not found. Confirm that the path in the <Import> declaration is correct, and that the file exists on disk.  D:\TeamCity\buildAgent\work\52034b1c4c1ab5f5\proofs\MvcRouting\MvcRouting\MvcRouting.csproj
[22:20:11]Process exited with code 1
[22:20:11][Step 1/4] Step Update nuGet packages (NuGet Installer) failed

The key is the \v10.0\ in the MSBuild path.  I looked at the csproj file mentioned in the error, and it uses the standard compatibility logic to determine the Visual Studio version and set the paths appropriately, only falling back to 10.0 if VisualStudioVersion is null.  I checked in the solution file and I have confirmed that the VisualStudioVersion is 12:
Microsoft Visual Studio Solution File, Format Version 12.00
Visual Studio 2013
VisualStudioVersion = 12.0.30110.0

Any ideas why NuGet update doesn't seem to be picking up the correct Visual Studio version?

A: The VisualStudioVersion will be defined when you build from within Visual Studio. On the build server it will not be defined by default.
You should be able to set it through an environment variable on the machine or in Team City. Or just update your project so it fallsback to version 12 instead.
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">12.0</VisualStudioVersion>

NuGet does not read anything from the solution itself. It just uses it as the base directory from which to find any packages.config files that exist in any subdirectory below the solution.


text:
Q: GBQ load job failed due to file not available The load job failed due to GCS file not found as below:

creationTime: 2015-03-26 02:40:55
startTime: 2015-03-26 02:46:47
endTime: 2015-03-26 02:46:47
job_duBpwC75IL6sPSttT3_e6NLMblE : DONE
[state] => DONE
    [errorResult] => Array
        (
            [reason] => notFound
            [message] => Not found: Google Storage File gs://vindico_impressions_out/2015_03_25/22/Campaign_021107_V3Impressions21_20150325_0059789468.csv
        )

But checking the the file on GCS it already existed there:
163.24 KB  2015-03-26T02:19:06Z  gs://vindico_impressions_out/2015_03_25/22/Campaign_021107_V3Impressions21_20150325_0059789468.csv#1427336346623000  metageneration=1
TOTAL: 1 objects, 167159 bytes (163.24 KB)

Is there any warm up period or any other parameters needs to be considered before the GCS object is available for GBQ to use?

A: Looking at the ingestion logs, there was an internal error reading that file; if you retry, does the error go away? I've filed an internal bug and we'll investigate more on the BigQuery / Google Cloud Storage side.


text:
Q: Pick up attachment from similarly named attachments I have an attachment list in column "I" with an entry "Portfolio Holdings Distribution - Fund MW".
There are other files in a folder with name
- "JUN2019_fund_MWMU" or
- "JUN2019_fund_MWMD"
I want to pick up "JUN2019_fund_MW"
I tried below code and get an error.
.Attachments.Add Pth & Dir(Pth & "*" & Replace(ws.Range("I" & i + 1).Value, "Portfolio Holdings Distribution - Fund ", "") & "*")

A: Try this
.Attachments.Add Pth & _
                 "JUN2019_fund_" & _
                 Replace(ws.Range("I" & i + 1).Value, "Portfolio Holdings Distribution - Fund ", "") & _
                 ".xls"

A better way to handle it would be
Dim Atthfile As String

Atthfile = pth & _
           "JUN2019_fund_" & _
           Replace(ws.Range("I" & i + 1).Value, "Portfolio Holdings Distribution - Fund ", "") & _
           ".xls"

'~~> If file is found, attach else continue without attaching
If Dir(Atthfile) <> "" Then .Attachments.Add Atthfile


text:
Q: Why does creating ImageViews with a loop from an ArrayList cause a memory error? I'm working on an Android app and I've come to a section of the app where I need to get an ArrayList and create an ImageView for each String in the ArrayList. These will be displayed along the bottom of the layout and scroll horizontally.
The code I've been using for this is:
ArrayList<String> selectedUser = userInformation.getUserArrayList();
LinearLayout holderGUI = findViewById(R.id.holder);
Integer i = 0;
ImageView newImg;
do {
    newImg = new ImageView(this);
    Integer id = getResources().getIdentifier(selectedUser.get(i),"drawable",getPackageName());
    newImg.setImageResource(id);
    newImg.setContentDescription(selectedUser.get(i));
    newImg.setAdjustViewBounds(true);
    newImg.setScaleType(ImageView.ScaleType.FIT_CENTER);
    holderGUI.addView(newImg);
    i++;
} while (i < selectedUser.size());

This code works fine because each image file on the app matches the possible strings in the ArrayList. However, this loop only iterates three times before the app crashes with a memory allocation error. I've tried taking the block of code in the loop and just pasting it in five times to ensure that there's no issue with the loop, but I get the same result.
Is there a more efficient way to do this or is there something that I'm going wrong? Any help would be appreciated.

A: While converting String to image if string size is big then it causes OutOfMemoryError and throws an Exception so you need to handle it.
android:largeHeap="true"
android:hardwareAccelerated="false"

Add above lines in Manifest Application tag.
boolean isOutOfMemory = false;

try{
    // Your Code here.
    }catch (OutOfMemoryError ex) {
        System.gc();                // clean up largeVar data
        isOutOfMemory = true;       // flag available for use
    }

Add your code in try catch block.
I Hope this will work for you.


text:
Q: Can Phoenix v4.4 utilize HBase namespaces? As we've been evaluating the use of Phoenix + HBase in HortonWorks 2.3, we came upon the conclusion that in the current bundled version of Phoenix, 4.4, that namespaces are not supported. The upstream JIRAs are confusing but it looks like Phoenix will not support namespaces + permissions until 4.7-4.8.
This is what we seen when enabling Phoenix on our system. The SYSTEM.* tables are Phoenix's. Ours are in the ns: namespace.
Version 1.1.2.2.3.6.0-3796, r2873b074585fce900c3f9592ae16fdd2d4d3a446, Thu Jun 23 16:29:31 UTC 2016

hbase(main):001:0> list
TABLE
SYSTEM.CATALOG
SYSTEM.FUNCTION
SYSTEM.SEQUENCE
SYSTEM.STATS
ambarismoketest
ns:contact
ns:counters
ns:counters-backup
ns:lists
ns:logins
ns:modelLogs
ns:models
ns:reportLogs
ns:users

Questions
Does this sound like a correct conclusion? If so what are my options in terms of Phoenix?

*

*upgrade it within HW 2.3 (assuming this is not an option)?

*work around it somehow?

*Move Phoenix tables manually out of default NS into our applications? How?

References

*

*HBase namespaces surfaced in phoenix

*Support HBase non-default Namespace

*Phoenix Schema should mapping to HBase Namespace

A: You can upgrade Phoenix within HDP 2.3 by replacing the correct jar files in `/usr/hdp/......phoenix


text:
Q: Drupal Views exposed filter of Author name I have a view which I would like to add an exposed filter of the author name. So I can filter all the posts created by "John Smith" etc. I can't seem to see it listed under filter. Is this possible to do?

A: This is actually a little harder than it sounds. You need to create a "Relationship" to the "Node revision: User", and then under the filter section, choose the User category and pick User:uid, and choose "Use relationship..."

A: Under Build > Views (/admin/build/views)

*

*add a filter (from filter category user)

*click Expose in the filter configuration section (near to the right border).

A: For applying filter using views you can follow the following steps:-
=> Go to administer setting
=> site building
=> views
=> add view
=> edit the view name and its description also the tag
=> add a filter in right side
=> then select on which type of node or
whatever you choose and then apply the filter.
suppose if you choose the filter on node then you can select what condition either it is published, type, etc and after doing this you can choose your node type from option(is one of).
now you can apply filter on your desired type or node.


text:
Q: Filter method in a function to output an average I am trying to filter through a given array and only output the average of a new array's numbers. However, for some reason, the length of an array is based on the original array's length where other data types are located, although I specified the length to be based on a newArr array.
Could someone please help?

const bills = [[], 4, 42, 9, "error"];

const calcAverage = function (arr) {
    let sum = 0;
    let avg;
    for (let i = 0; i < arr.length; i++) {
        if (typeof arr[i] === "number") {
            sum = sum + arr[i];
            avg = sum / arr.length
        } else {
            const newArr = arr.filter(arr => typeof arr[i] === "number");

            for (let b = 0; b < newArr.length; b++) {
                sum = sum + newArr[b];
                avg = sum / newArr.length;
            }
        }
    }
    return avg;
}

console.log(calcAverage(bills));

A: You don't really need to use .filter with the for loop.
Instead you can keep a count of the amount of numbers encountered so far and use that to calculate your average. If you come across an item that isn't a number we can just skip it and move on.

const bills = [[], 4, 42, 9, 'error'];

const calcAverage = function (arr) {
  let sum = 0, avg = 0;

  for (let i = 0, count = 0; i < arr.length; i++) {
    if (typeof arr[i] === 'number') {
      count++;
      sum += arr[i];
      avg = sum / count;
    }
  }

  return avg;
};

console.log(calcAverage(bills));

A: revised:
const bills = [[], 4, 42, 9, "error"];
const calcAverageOLD = function(arr) {
  let sum = 0;
  let avg;
// filter Before loop for correct length
  const newArr = arr.filter(primitive => typeof(primitive) === "number");
  console.log(newArr)
  for (let i = 0; i < newArr.length; i++) {
      sum += newArr[i];
      avg = sum / newArr.length;
    }
      return avg;
  }
console.log('old', calcAverageOLD(bills))

A: Are you trying to calculate the average from the numbers in the array?
I am not sure if I understand your question but here is what I did:
First filter the numbers and then it's much easier to calculate the average
const bills = [[], 4, 42, 9, "error"];
const calcAvarage2 = function (arr){
    let newArr = arr.filter( item=>typeof(item)==="number")
    let sum = 0;
    for( number of newArr){
        sum += number;
    }
    let avg = sum/ newArr.length

    return avg
}

console.log(calcAvarage2(bills));


text:
Q: Caml to get today's birthdays I have a list with birthday field (DateTime).
How do I write caml query to retrieve only the records where birthday falls on today (i.e. only comparing day and month value of birthday column to today's day and month)

A: It turns out, there is no simple way to achieve this. However, I can suggest at least three quite acceptable approaches.
1 - "This Year Birthday" calculated column
You can consider creating "This Year Birthday" calculated field, use it in the CAML query and compare to <Today /> element:
<Eq><FieldRef Name='ThisYearBirthday' /><Value Type='DateTime'><Today /></Value></Eq>

But since calculated columns are updated only if the item is updated or if the field is updated, you should also create the corresponding timer job to update this field two times a year to get the calculated column refreshed with values for the next year.
This solution is not very elegant, I admit, but it is 100% workable (actually we're using it in our enterprise product).
2 - use Calendar lists
Another very promising option could be to leverage Calendar lists functionality. They have recurring events and you can create birthdays there and display them using "Current Events" standard view.
3 - use dynamic SPQuery (thanks Stuart Pegg for this idea!)
You can create the SPQuery programmatically on each page load. To avoid additional requests to database, you can consider the following scenario:
First, create two calculated columns:

*

*Birthday_Month: =MONTH([Birthday])

*Birthday_Day: =DAY([Birthday])
Then, use the following CAML query:
<Where>
  <And>
    <Eq>
      <FieldRef Name='Birthday_Month' />
      <Value Type='Number'>{0}</Value>
    </Eq>
    <Eq>
      <FieldRef Name='Birthday_Day' />
      <Value Type='Number'>{1}</Value>
    </Eq>
  </And>
</Where>

Replace {0} with the current month number (DateTime.Now.Month), and {1} with the current day number (DateTime.Now.Day).
Additionally, you can hide the calculated columns from DisplayForm page setting SPField.ShowInDisplayForm property to false.

A: Edit: Doesn't actually work; possibly due to issues between <In> and DateTimes.
Ready for some madness? This is an ungodly and unmaintainable solution, but it's worth it for the laugh:
<In>
    <FieldRef Name="Birthday" />
    <Values>
        <Value Type="DateTime" IncludeTimeValue="FALSE">
            <Today OffsetDays="-365" />
        </Value>
        <Value Type="DateTime" IncludeTimeValue="FALSE">
            <Today OffsetDays="-730" />
        </Value>
        <Value Type="DateTime" IncludeTimeValue="FALSE">
            <Today OffsetDays="-1095" />
        </Value>
        <Value Type="DateTime" IncludeTimeValue="FALSE">
            <Today OffsetDays="-1461" />
        </Value>
        ...
    </Values>
</In>

Note that this will need to take into account leap years; hence 1 will need to be subtracted from those numbers in 29 days time.

A: Try something like this:
<FieldRef Name='Birthday' /><Value Type='DateTime'><Today /></Value>

A: Constellation Solutions has a low-cost employee anniversary and birthday solution that can be added to an on-prem or Office 365 instance of SharePoint.  It uses the User Profile service to pull the current employees.  You can find out more information at Employee Birthdays and Anniversaries in SharePoint


text:
Q: React Native Draggable Flatlist with Swipeable Item not working I am new to React native. I am trying draggable Flatlist with Swipeable item which is not working. But when i tried with example it's working but not with real code.
https://snack.expo.dev/@computerjazz/swipeable-draggable-list -- Working
 //Here is my first component

This is my first component where i have added only draggable flatlist.But when i tried with example it's working but not with real code.
//Correct Draggable list
import React, {useState} from 'react';
import {StyleSheet, Text, TouchableOpacity, View, CheckBox} from 'react-native';
import DraggableFlatList from 'react-native-draggable-flatlist';
import LABEL from '../common/ContentTranslations';
import RowComponent from './RowComponent';

function DashboardSortableListComponent(props) {
  const [data, setData] = useState(props.data);
  const disableText = props.appLanguage
    ? LABEL[props.appLanguage].LABEL_DISABLE
    : '';

  const data_order = props.data;
  const order = Object.keys(data_order);
  const renderItem = ({item, index, drag, isActive}) => (
    <View style={styles.item}>
      <TouchableOpacity onLongPress={drag}>
        <RowComponent
          key={item.pid}
          rowData={item}
          index={index}
          totalRows={item.length}
          navigate={props.navigate}
          appLanguage={props.appLanguage}
          disableText={disableText}
          removeCurrencyPairFromList={props.removeCurrencyPairFromList}
        />
      </TouchableOpacity>
    </View>
  );

  return (
    <View style={styles.screen}>
      <View style={{flex: 1}}>
        <DraggableFlatList
          data={data}
          renderItem={renderItem}
          keyExtractor={(item, index) => index.toString()}
          onDragEnd={({data}) => setData(data)}
          updateOrder={props.onUpdateOrder}
          order={order}
          disableText={disableText}
          navigate={props.navigate}
          appLanguage={props.appLanguage}
          refreshCurrencyPairsList={props.refreshCurrencyPairsList}
          removeCurrencyPairFromList={props.removeCurrencyPairFromList}
        />
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  screen: {
    //marginTop: 24,
    flex: 1,
    //backgroundColor: '#212121',
  },
  item: {
    // flexDirection: 'row',
    // justifyContent: 'space-between',
  },
});

export default DashboardSortableListComponent;

   //Here is my second component where i have added Swipeable list in another component.

 import React from 'react';
import Swipeout from 'react-native-swipeout';
import {Text, View, Animated, TouchableOpacity} from 'react-native';
import {TouchableHighlight} from 'react-native-gesture-handler';
import HTMLText from 'react-native-html-to-text';
import {Helper} from '../common/helpers/Helper';
import Icon from 'react-native-vector-icons/Ionicons';
import Swipeable from 'react-native-gesture-handler/Swipeable';
import SwipeableItem, {
  useSwipeableItemParams,
} from 'react-native-swipeable-item';
import DraggableFlatList, {
  ScaleDecorator,
} from 'react-native-draggable-flatlist';
let createReactClass = require('create-react-class');
let styles = require('../assets/stylesheet/stylesheet');

const RowComponent = createReactClass({
  render: function () {
    let swipeoutBtns = [
      {
        text: this.props.disableText,
        backgroundColor: '#dfb665', //ff3333
        underlayColor: '#555d66',
        color: '#000000',
        onPress: () => {
          this.props.removeCurrencyPairFromList(this.props.rowData);
        },
      },
      ,
    ];
    const UnderlayRight = ({removeCurrencyPairFromList}) => (
      <Animated.Text
        style={{
          backgroundColor: '#dfb665',
          underlayColor: '#555d66',
          color: '#000000',
          flex: 1,
        }}>
        <TouchableOpacity
          onPress={() =>
            this.props.removeCurrencyPairFromList(this.props.rowData)
          }>
          <Text>{this.props.disableText}</Text>
        </TouchableOpacity>
      </Animated.Text>
    );

    return (
      <View
        style={
          this.props.index === this.props.totalRows - 1
            ? styles.cpLastRowStyle
            : styles.cpNormalRowStyle
        }>
        <ScaleDecorator>
          {/* <SwipeableItem
            key={this.props.rowData.pid}
            item={this.props.rowData}
            overSwipe={50}
            //swipeDamping={5}
            renderUnderlayRight={() => (
              <UnderlayRight
                removeCurrencyPairFromList={
                  this.props.removeCurrencyPairFromList
                }
              />
            )}
            snapPointsRight={[150]}> */}
             <Swipeout
          left={swipeoutBtns}
          style={{backgroundColor: '#414a53'}}
          autoClose={true}
          buttonWidth={100}
          sensitivity={10}>
            <View>
              {Helper.isChartsAvailable(
                this.props.rowData.currencyPair,
                this.props.rowData.graphCurrencyPair,
              ) ? (
                <TouchableHighlight
                  underlayColor={'#000000'}
                  delayLongPress={50}
                  style={{backgroundColor: '#333e48'}}
                  {...this.props.sortHandlers}
                  onPress={() =>
                    this.props.navigate('Charts', {
                      currencyPair: this.props.rowData.graphCurrencyPair,
                      bid: this.props.rowData.bid,
                      offer: this.props.rowData.offer,
                      graphCurrencyPair: this.props.rowData.graphCurrencyPair,
                      productName: Helper.selectProductNameBaseOnLang(
                        this.props.appLanguage,
                        this.props.rowData,
                      ),
                    })
                  }>
                  <View style={[styles.rowstyle]}>
                    <HTMLText
                      style={[
                        styles.width100,
                        styles.customFont,
                        styles.textGold,
                      ]}
                      html={Helper.selectProductNameBaseOnLang(
                        this.props.appLanguage,
                        this.props.rowData,
                      )}
                    />
                    <Text style={[styles.width60, styles.customFont]}>
                      {Helper.getDecimalPointsForCurrencyPairs(
                        this.props.rowData.currencyPair,
                      ) != -1
                        ? this.props.rowData.bid.toFixed(
                            Helper.getDecimalPointsForCurrencyPairs(
                              this.props.rowData.currencyPair,
                            ),
                          )
                        : this.props.rowData.bid}
                    </Text>
                    <Text style={[styles.width60, styles.customFont]}>
                      {Helper.getDecimalPointsForCurrencyPairs(
                        this.props.rowData.currencyPair,
                      ) != -1
                        ? this.props.rowData.offer.toFixed(
                            Helper.getDecimalPointsForCurrencyPairs(
                              this.props.rowData.currencyPair,
                            ),
                          )
                        : this.props.rowData.offer}
                    </Text>
                    <Icon
                      name="ios-stats-chart"
                      style={[styles.gridiconstyle, styles.width30]}
                    />
                  </View>
                </TouchableHighlight>
              ) : (
                <TouchableHighlight
                  underlayColor={'#000000'}
                  style={{backgroundColor: '#333e48'}}
                  delayLongPress={50}
                  {...this.props.sortHandlers}>
                  <View style={[styles.rowstyle]}>
                    <HTMLText
                      style={[
                        styles.width100,
                        styles.customFont,
                        styles.textGold,
                      ]}
                      html={Helper.selectProductNameBaseOnLang(
                        this.props.appLanguage,
                        this.props.rowData,
                      )}
                    />
                    <Text style={[styles.width60, styles.customFont]}>
                      {Helper.getDecimalPointsForCurrencyPairs(
                        this.props.rowData.currencyPair,
                      ) != -1
                        ? this.props.rowData.bid.toFixed(
                            Helper.getDecimalPointsForCurrencyPairs(
                              this.props.rowData.currencyPair,
                            ),
                          )
                        : this.props.rowData.bid}
                    </Text>
                    <Text style={[styles.width60, styles.customFont]}>
                      {Helper.getDecimalPointsForCurrencyPairs(
                        this.props.rowData.currencyPair,
                      ) != -1
                        ? this.props.rowData.offer.toFixed(
                            Helper.getDecimalPointsForCurrencyPairs(
                              this.props.rowData.currencyPair,
                            ),
                          )
                        : this.props.rowData.offer}
                    </Text>
                    <Icon
                      name="ios-stats-chart"
                      style={[
                        styles.gridiconstyle,
                        styles.width30,
                        styles.desabled,
                      ]}
                    />
                  </View>
                </TouchableHighlight>
              )}
            </View>
          {/* </SwipeableItem> */}
          </Swipeout>
        </ScaleDecorator>
      </View>
    );
  },
});

module.exports = RowComponent;


text:
Q: getOptionInstance()->getOptions() returning empty array I am trying to delete custom options in a data install script. I have a list of product IDs and I am looping through them like this:
foreach ($productIds as $productId) {
    $product = Mage::getModel('catalog/product')->load($productId);
    $oldOptions = $product->getOptionInstance()->getOptions();
    foreach ($oldOptions as $key => $option) {
        $oldOptions[$key]['is_delete'] = 1;
    }
    $product->getOptionInstance()->setOptions($oldOptions);
    $product->getOptionInstance()->saveOptions();
}

The problem is, $oldOptions is always an empty array. I know for a fact that the products in question have custom options set. When I run it through a debugger, I can see that the _options property on the product is populated correctly.
I have a query I can use to delete the options from the database, but that makes me a bit nervous since I'm not 100% clear on how that will affect the product (i.e., what type of lifecycle methods may not be skipped by doing a direct SQL delete).


text:
Q: PHP Form inputting same Value for 2 fields which are different So I have a table which I want to be able to choose the Restaurant ID & Name and insert it into the new table for the deal which is linked to that restaurant.
<?php
// First we start a session which allow for us to store information as SESSION variables.
session_start();
// "require" creates an error message and stops the script. "include" creates an error and continues the script.
require "config.php";

$sql = "SELECT * FROM Restaurants";
$result= mysqli_query($link, $sql) or die("Bad Query: $sql");
$row = mysqli_fetch_array($result);

if (isset($_GET['post'])) {
    $Restaurant_ID = mysqli_real_escape_string($link, $_GET['Restaurant_ID']);
    $Name = mysqli_real_escape_string($link, $_GET['Name']);
}

?>
<select name="Restaurant_ID">
    <?php
    foreach($result as $row)
    {
        $output .=  '<option value ="'. $row['Restaurant_ID'] .'">'. $row['Name'] .'</option>';
    }

echo $output;
?>
</select>
</div>
<select name="Name">
    <?php
    foreach($result1 as $row1)
    {
        $output .=  '<option '. $row1['Name'] .'>'. $row1['Name'] .'</option>';
    }
echo $output;
?>

</select>

when it puts them into the table it gives $Name & $Restaurant_ID the same name and inserts only $Restaurant_ID in both fields.
Site to see how it works http://thefoodieapp.co.uk/thefoodieappv1/deal_form.php?signup=success


text:
Q: What is the difference between asp and asp.net? I am developing web application using asp.net, but i want to work on asp i have to install asp or can we write  the code using asp.net, what is the main difference between these two asp,asp.net. Thank you

A: ASP is the legacy version of active server pages that was created before the .NET framework. It works on IIS and is written in VBScript or Javascript.
ASP.NET is the newer version built on top of the .NET framework and is written in VB.NET or C#
IMO, you should spend your time learning and using ASP.NET as classic ASP is rather ancient in terms of web technologies and will likely not be supported for much longer (merely guessing there..)
You may also want to consider looking at ASP.NET MVC as a possible solution as well.

A: You should be able to use classic ASP in a .NET environment running IIS. If that is what you're asking.


text:
Q: How do I use variable fonts with Google Fonts? Unlike traditional fonts that require a file for each weight (300, 400, 500, etc.), variable fonts allow you to access every combination of the font's weights and styles through a single (smaller) font file. This has obvious benefits for the web, and I'm trying to use the Inter font from Google Fonts, which both Google and the designer's website claim to be a variable font.
However when selecting the font in Google Fonts I'm still required to select the individual weights that I want to use, and the generated <link> tag also specifies individual weights, suggesting that it's downloading each of those files:
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@100;200;300;400;500;600&display=swap" rel="stylesheet">

I've also noticed that it doesn't seem to come with italics, and when I try to render italics it simulates them with faux italics, which I confirmed by adding the CSS rule font-synthesis:none:
font-style: italic;
font-synthesis: none ; /* Disables faux italics and other simulated styles:
                          if no italic style is installed, defaults to normal

Why is this, and how can I use the variable version of Inter via Google Fonts, including italics?

A: Google Fonts lets you choose a non-standard value in the Variable axes section, but you still need to input the value/s as google serves smaller and specific files to avoid large requests, it also approximates them.
For example by picking 401 and 410 you get the exact same file as a response (the only difference is the font-weight in the style).
Check them:

*

*https://fonts.googleapis.com/css2?family=Inter:wght@401&display=swap

*https://fonts.googleapis.com/css2?family=Inter:wght@410&display=swap
Inter seems not to be available in italics btw.

A: Google Fonts does allow you to load a variable font in your site, not specific weights. For more info, see:
https://fonts.google.com/knowledge/using_type/loading_variable_fonts_on_the_web


text:
Q: Is it beneficial to study past the basics of a core language when the primary goal is to rely on its framework? Please keep in mind this is not another 'How much [insert programming language here] should I know before moving onto [insert framework here]?' What I'd like to know is how beneficial is it to learn the those advanced concepts of a programming language when your intention is to heavily rely on its framework the majority of the time. So for example I've began to use jQuery and first took the time out to really grasp the core concepts of Javascript. Additionally I have a few beyond the basics books (Secrets of a Javascript Ninja for instance) on the shelf that really delve into the language. As I skim through the pages though I find that a fair bit of it doesn't carry over to jQuery being that my main intention is DOM manipulation.
The same can be said for Ruby and RoR. Will these books make me a better programmer overall? Probably. Can these topics help me become that much better with its framework? That's what I'm having a hard time understanding.

A: Of course. The question is "is that benefit worth the time investment?". I would argue that it always is, but it certainly depends on you and your environment since they will impact the benefit (how much your environment will gain from your knowledge) versus the cost (how long it takes you to learn, and how well you absorb knowledge).
Why would I argue it's beneficial? Because you won't always be in the framework. Even the most comprehensive framework is still a part of a larger ecosystem. You can't make jQuery calls alone. You need to know how to bind your script into the page, how it runs, how it interacts with the stuff you want to do. That may be "basics" in your book, but I've always found that deeper knowledge helped me make code quicker, and certainly debug problems faster. Framework or not.
Beyond that, the real world has a nasty habit of intruding on programmers. Sure, your task today may be to do some DOM manipulation, but tomorrow you might need to wire up some SWFObject. Having a good foundation will let you adjust more easily to changing environments.
And lastly, even though you may only want to do DOM manipulation, very few programmers work alone anymore. Your peers will likely do more advanced things with the programming language. You'll need to be able to read that code, or at the very least, not screw it up.

A: It's more important to study the language than it is to study the framework.  Learn the language well, and you'll use the framework well.
In order of importance (most important first):

*

*Fundamental programming principles - Algorithms, data structures, etc.

*Language paradigms - OOP, Functional, etc.

*Language features.

*Syntax and frameworks.

A: Probably need a little balance in the amount you should learn. It's not all or nothing, so put as much time in it as you can. You have to ask yourself what risks you are wiling to accept by relying on the framework.
It's great if all you need is to get some Minimum Viable Product up and running. There aren't going to be huge performance or complex requirement gotchas. This assumes you picked a framework that can handle what it is you're trying to build.
On the other side of the spectrum is if you are working on a fairly large/complex application and you find something that the framework handles poorly. No big deal, so you end up having to learn more JavaScript. You would have had to spend that time on it if you learned it from the beginning. But do you have the time? Will you be able to learn the fundamentals under the stress of not getting something done on time? No one can answer that.
Balancing it out is probably the best bet. Pace yourself. Learn some JavaScript if you can. You may not become an expert, but that is no reason to ignore it. Frameworks were created by people who needed to solve a problem similar to yours, but not exactly like yours.

A: A general area that suffers from delving in the framework(s) before knowing the core language well is performance. This is true for all languages/platforms (Hibernate n+1 selects etc). Here's a lot of JQuery tips and tricks which  rely (among other things) on good knowledge of the core language in relation to performance:

Use For Instead of Each Native functions are always faster than any
  helper counterparts. Whenever you're looping through an object
  received as JSON, you'd better rewrite your JSON and make it return an
  array through which you can loop easier.
Use IDs Instead of Classes It's much better to select objects by ID
  because of the library's behavior: jQuery uses the browser's native
  method, getElementByID(), to retrieve the object, resulting in a very
  fast query.

A: I think your question is based on a false premise. You start by saying that you're planning to rely on a framework, and then you ask if it's beneficial to learn beyond the framework. So of course you come to the conclusion it's not worth it. But that premise is flawed. You shouldn't focus on using a framework. You should focus on using the right tool for the right job. jQuery is really good at certain tasks, and so is Ruby on Rails or any other framework. But they aren't always the right tool for everything. Learning about the language beyond the framework, and even learning about other frameworks or microframeworks or other tools, helps you identify when your framework is getting in your way more than it's helping, and it gives you the ability to seek other, better solutions.
So my answer is: yes, it's absolutely worth it because the framework isn't the right tool for every job.


text:
Q: How To Add Retry Button in Custom error Page Of Android Webview? I have Created Android Webview For The website.
I have Created custom error page when internet is not connected.
The file is loading fine.
if internet is not connected error page is loading.
Is there any way to add retry button in custom error page so that once internet is connected and if user clicks the retry button and then load the webview again?
Now I have to exit app and then again i have to again open the app once internet is connected.
Rather than exiting app, once internet is connected i want have retry button on custom error page so that without exiting app webview will be loaded.
Or Is it possible to load webview automatically once internet is connected?
MainActivity.java is

package com.flyingcolorz.flyingcolorz;

import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.app.Activity;
import android.view.KeyEvent;
import android.content.DialogInterface;
import android.app.AlertDialog;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.graphics.Bitmap;
import android.view.View;
import android.widget.ProgressBar;
import android.webkit.WebResourceRequest;
import android.content.Intent;
import android.net.Uri;

public class MainActivity extends Activity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    String url = "https://google.com/";
    setContentView(R.layout.activity_main);
    final WebView myWebView = (WebView) findViewById(R.id.webview);
    WebSettings webSettings = myWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    myWebView.loadUrl(url);
    //myWebView.setWebViewClient(new WebViewClient());
    // Get Connectivity Manager class object from Systems Service
    //ConnectivityManager cm = (ConnectivityManager)  getSystemService(Context.CONNECTIVITY_SERVICE);
    // Get Network Info from connectivity Manager
    //NetworkInfo networkInfo = cm.getActiveNetworkInfo();
    // if no network is available networkInfo will be null
    // otherwise check if we are connected
    // if (networkInfo == null) {
    myWebView.setWebViewClient(new WebViewClient() {
      @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
        myWebView.loadUrl("file:///android_asset/error.html");
      }
    });
    // }
  }
  //goto previous page
  @Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {
    WebView myWebView = (WebView) findViewById(R.id.webview);
    if (event.getAction() == KeyEvent.ACTION_DOWN) {
      switch (keyCode) {
        case KeyEvent.KEYCODE_BACK:
          if (myWebView.canGoBack()) {
            myWebView.goBack();
          } else {
            //finish();
            new AlertDialog.Builder(this)
              .setIcon(android.R.drawable.ic_dialog_alert)
              .setTitle("Exit")
              .setMessage("Are you sure you want to exit?")
              .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                  finish();
                }

              })
              .setNegativeButton("No", null)
              .show();
          }
          return true;
      }
    }
    return super.onKeyDown(keyCode, event);
  }
}

A: You can do something like this for as a solution.
Add your webview with swiperefresh layout.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.vvhvb.hesselfeenstra.vvheerenveenseboys.MainActivity"
tools:showIn="@layout/activity_main">

<android.support.v4.widget.SwipeRefreshLayout
    android:id="@+id/swipeContainer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

<android.support.v4.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <WebView
        android:id="@+id/webView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true" />

</android.support.v4.widget.NestedScrollView>
</android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>

And show your error message as "Error Occoured! Swipe from top to retry."
Now when user refreshes load default url that you want into your webview.
mySwipeRefreshLayout.setOnRefreshListener(
    new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            webview.loadUrl(url);
        }
      }
    );

A: You might have to add some connectivity trigger that will reload to the original URL automatically once it detects that the connectivity is back. However, I don't know if it's even possible or how to do that.
I had the exact same issue. Here's how I tackled it (I didn't want Swipe to Refresh):
I created a seperate activity for the error page (say ErrorActivity) and loaded the error.html page like you'd load a normal webview.
So, I changed my onReceivedError to this:
    @Override
    public void onReceivedError(WebView webview, int i, String s, String s1)
    {
        WebView.setVisibility(View.GONE);
        Intent intent = new Intent(MainActivity.this, ErrorActivity.class);
        startActivity(intent);
        finish();
    }

Basically, this code is detecting that some error has been received, then it is hiding the original WebView and launching the ErrorActivity using an Intent, and finishing the MainActivity.
The ErrorActivity is then having my error.html page which tells users to reload the page from a menu button.
Now, to create the ErrorActivity we'll need to define it in AndroidManifest.xml, create a layout file for it and then load the WebView.
If you don't already have a menu, you'll have to create a menu folder inside res. An example menu.xml file for this case:
<?xml version="1.0" encoding="utf-8"?>

<menu xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">

            <item
                android:id="@+id/refresh"
                android:icon="@drawable/ic_refresh_black_24dp"
                android:orderInCategory="1"
                app:showAsAction="always"
                tools:ignore="AlwaysShowAction"
                android:title="@string/refresh"/>

</menu>

In ErrorActivity.java, outside your onCreate, add this:
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
    MenuInflater menuInflater = getMenuInflater();
    menuInflater.inflate(R.menu.menu, menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item)
{
    switch (item.getItemId())
    {
        case R.id.refresh:
            Intent intent = new Intent(ErrorActivity.this, MainActivity.class);
            startActivity(intent);
            finish();
            break;
    }
    return super.onOptionsItemSelected(item);
}

Basically, as soon as you press on Refresh, your app will try to load MainActivity. If there still are some internet connectivity issues, your MainActivity's WebView will again receive an error and that will again load ErrorActivity. So far, this has worked flawlessly for me.
This should do it.
Be sure to update the id, etc. if you're gonna change this code to match your needs.

A: A medical student is here, trying to solve your problem.
Just add a button in your error page (error.html).
<button>RETRY</button>

bye!
It's time to see a patient.


text:
Q: Поиск набора слов в строке Делаю фильтр сообщений в боте Телеграм. Столкнулся с такой проблемой.
У меня есть следующее:
слова_и_фразы = ["слово0 слово1", "слово2", ("слово3" || "слово4") && ("слово5" || "слово6" || "слово7")]
Мне нужно найти слово или слова в пришедшей строке.
Я делаю следующее:
написанная_фраза.ИндексОф(слова_и_фразы[цикл] != -1)
{console.log("Успешно")}
если я напишу боту - "слово0 слово1" - всё хорошо
если я напишу боту - "слово0 слово2" - всё хорошо
если я напишу боту - "слово3 слово6" или "слово6 слово3" - плохо
бот реагирует на слово3, при этом игнорирует условие
Я новичок, сильно не ругайте
Как сделать подскажите?

A: Проблему решил путём построением двойного массива (массив в под массиве). Где 0 это первые фразы, 1 это вторые фразы. Далее проверяем двумя циклами. Всем спасибо кто помогал)


text:
Q: Multiple plots using for loop I am trying to print out and save to ggplot2 object (with a proper name with may change for each element of p.vec) using for loops, any help will be appreciated, many thanks in advance.
 par(mfrow = c(2, 2))
    p.vec <- c("disp","mpg")
    for(i in p.vec){
    p <- ggplot(data = mtcars, aes(x = mpg, y= i)) +geom_jitter()
    print(p)
    #ggsave("plot.pdf")
    }

A: Try using lapply :
library(ggplot2)
p.vec <- c("disp","mpg")

lapply(p.vec, function(x) {
  p <- ggplot(data = mtcars, aes(x = mpg, y= .data[[x]])) +geom_jitter()
  ggsave(sprintf('plot_%s.jpg', x))
})

Instead of .data[[x]] you can also use any of the option from this answer.


text:
Q: Spring Cloud Stream Kafka Binder Configuration update at runtime I am using Spring cloud stream along with Kafka binders to connect to a Kafka cluster using SASL. The SASL config looks as follows:
spring.cloud.stream.kafka.binder.configuration.sasl.mechanism=SCRAM-SHA-512
spring.cloud.stream.kafka.binder.configuration.sasl.jaas.config= .... required username="..." password="..."
spring.cloud.stream.kafka.binder.configuration.security.protocol=SASL_SSL

I want to update the username and password programmatically/at runtime, how can I do that in Spring Cloud Stream using Spring Kafka binders?
Side note:
Using BinderFactory I can get reference to KafkaMessageChannelBinder which has KafkaBinderConfigurationProperties, in its configuration hashmap I can see those configurations but I want to know how can I update the configuration at runtime such that those changes are reflected in the connections as well?
@Autowired
BinderFactory binderFactory

....

public void foo()
{
    KafkaMessageChannelBinder k = (KafkaMessageChannelBinder)binderFactory.getBinder(null, MessageChannel.class);
    // Using debugger I inspected k.configurationProperties.configuration which has the SASL properties I need to update
}

A: jaas username and password can be provided using configuration, which also means that they can be overridden using the same properties at runtime.
Here is an example: https://github.com/spring-cloud/spring-cloud-stream-samples/blob/master/multi-binder-samples/kafka-multi-binder-jaas/src/main/resources/application.yml#L26
At runtime, you can override the values set in application.properties. For example, if you are running the app using java -jar, you could simply pass the property along with it: spring.cloud.stream.kafka.binder.jaas.options.username. Then this new value will take effect for the duration of the application run.

A: I came across this problem yesterday and spent about 3-4 hours in order to figure out how to programmatically update the username and password in Spring Cloud Stream using Spring Kafka binders as one cannot/should not store passwords inside Git.(Spring Boot Version 2.5.2)
Overriding the bean KafkaBinderConfigurationProperties works.
@Bean
@Primary
public KafkaBinderConfigurationProperties kafkaBinderConfigurationProperties(KafkaBinderConfigurationProperties properties) {
    String saslJaasConfigString = "org.apache.kafka.common.security.scram.ScramLoginModule required username=${USERNAME_FROM_EXTERNAL_SYSTEM_LIKE_VAULT} password=${PASSWORD_FROM_EXTERNAL_SYSTEM_LIKE_VAULT}"
    Map<String, String> configMap = properties.getConfiguration();
    configMap.put(SaslConfigs.SASL_JAAS_CONFIG, saslJaasConfigString);
    return properties;
}


text:
Q: axios: Cannot read property 'slice' of null Got this error while doing some react server side rendering with redux
Stack trace
 TypeError: Cannot read property 'slice' of null
    at dispatchHttpRequest (E:\Projects\real-estate\node_modules\axios\lib\adapters\http.js:84:37)
    at httpAdapter (E:\Projects\real-estate\node_modules\axios\lib\adapters\http.js:19:10)
    at dispatchRequest (E:\Projects\real-estate\node_modules\axios\lib\core\dispatchRequest.js:52:10)
    at process._tickCallback (internal/process/next_tick.js:103:7)

Action
import axios from 'axios';

export const FETCH_USER = 'FETCH_USER';
export const FETCH_POSTS = 'FETCH_POSTS';
const GET_POSTS_URI = '/api/posts';

export const fetchPosts = () => {
        let posts = axios.get(GET_POSTS_URI).catch(err => console.log(err));
        return {
            type: FETCH_POSTS,
            payload: posts
        }
}

API
app.get('/api/posts', function(req, res, next) {
    Post.model.find()
        .exec()
        .then(function(posts) {
            res.send(posts);
        }, function(err) {
            return next(err);
        });
})

I still got the JSON response in the network tab in dev tool, but I could not retrieve the JSON response in the reducers. I also didn't get this error when I used OpenWeatherAPI

A: You are missing redux-thunk because you need it in order to do side-effect(like api call). Check out this: redux-thunk and redux async actions.


text:
Q: What will a function return if there's no explicit 'return' I bumped into this problem when I forgot to write the return clause of a function, but there was no warning or error in gcc. I fixed it but started wondering why the function would return something meaningless without a return. Here are some examples I tried:
#include "stdio.h"
#include "stdlib.h"

int func1 () {
        int i;
        i = 2;
}

int func2 (int a) {
        int i = a+3;
}

int func3 () {
        int i;
        for (i = 0; i <= 1; i++);
}

int main(void) {
        int a = 0;
        int b = 0;
        int c = 0;
        a = func1();
        printf("a = %d \n", a);
        b = func2(a);
        printf("b = %d \n", b);
        c = func3();
        printf("c = %d \n", c);
}

And the results are:
a = 1
b = 4
c = 7

My questions:
1) why these results? Is there any general rule for this?
2) why keep this thing rather than report an error? Can it be somehow 'useful' somewhere?

A: It is undefined behaviour per section 6.9.1, paragraph 12 (of the N1570 draft of the C standard):

If the } that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined.

The behaviour is not undefined if the return value is not used by the caller.
There is no diagnostic message required for mere undefined behaviour, so the compiler is not obliged to warn. gcc will warn if you ask it to (-Wreturn-type, implied by -Wall), and clang warns by default.
For functions returning a type other than void, a return statement must include an expression whose value shall be returned, per 6.8.6.4, paragraph 1:

A return statement with an expression shall not appear in a function whose return type is void. A return statement without an expression shall only appear in a function whose return type is void.

A: This is undefined behavior and will depend on the calling convention being used. If the caller is expecting the result in a register then whatever value was last in the register will be used.
Edit
The draft C99 standard in section 6.9.1 Function definitions paragraph 12 says:

If the } that terminates a function is reached, and the value of the function call is used by
  the caller, the behavior is undefined.

clang will warn by default and gcc will warn with -Wall, in general you should enable warnings.

A: On my system (gcc 4.5.3, linux), compiling your code with no optimization, I get this:
main:
...
    call    func1
    movl    %eax, 28(%esp)
...

i.e. the return value of func1 is drawn from the eax register, but that register is never set within func1, so the return value is whatever happened to be in that register when the function was called.


text:
Q: One to one correspondance of entities when building a table If I have 2 items with 1-1 strong dependency then one is an attribute i.e. column in the other one's table.
E.g. if we have a movie database and each movie must have a review score (review score is a number that represents the average score from X number of viewers) and each review score belongs to a movie then the review score should be a column in the table Movie.
Now if the review score comes from X number of people that actually did the review then this should be part of the Movie database too as a column.
But seems weird to me because the number of people is an attribute of the review score not of the movie right?
Am I misunderstanding something in this database design approach/theory?

A: Plan A:  Have another table with (movie_id, user_id, score).  Then do
SELECT ROUND(AVG(score), 1)
    FROM tbl
    WHERE movie_id = $movie_id
PRIMARY KEY(movie_id, user_id)

Plan B:  Keep these two columns in the movie table, or in a table with 1:1 correspondence to the movie table:  (score_count, score_sum).  Then compute the avg thus:
SELECT ROUND(score_sum / score_count, 1)
    FROM ...
    WHERE movie_id = $movie_id

Recording a new score (if a separate table) would be
INSERT INTO movie_scores ( movie_id, score_count score_sum )
    VALUES ($movie_id, 1, $score)
    ON DUPLICATE KEY UPDATE
        score_count = score_count + 1,
        score_sum = score_sum + VALUES(score_sum);
PRIMARY KEY(movie_id)

If same table as other movie info:
Initialize the two columns to 0.
Deal with the case where the average is 0/0.
UPDATE movies SET
        score_count = score_count + 1,
        score_sum = score_sum + $score
    WHERE movie_id = $movie_id

I prefer to use a separate table for this (and view-counts, LIKEs, upvotes, etc), in spite of it being 1:1.  This because movie_scores will be updated frequently.  The traffic to that table and the traffic to movies are independent.  Keeping them separate cuts down on contention (in very busy systems).

A: You seem to use "review score" for two distinct notions: One is the average value of values that are "user scores" of a movie. The other is a thing with existence separate from such a value, where two movies with the same "review score" value could be associated with different "review score" things. There is a common everyday related thing: a user review of a movie, with an associated value we could call a user (review) score for a movie. Your review score as thing we might better call a "review averaging" of a movie, and your review score as value a "review averaging score". In your design there might be a need for review and/or review averaging things rather than just scores, eg if we associate them with other things/values like a (review's) comment or a (review averaging's) number of users. But the things are distinct from the values.
So your movies may be 1:1 with review score things. But even then different movies can have the same review score value. (And if there are movies unrated by users then a movie could have no review score value.) So we are not talking about a 1:1 correspondence between movies and review score values.
Phrases like "have a", "belongs to" "is an attribute (property) of", "associated" and "related"  are vague. Eg: You say that a review score "belongs to" a movie. But also a movie can "belong to" a review score.
These phrases beg the question. Instead, identify what (application) relationship, represented by a table (base, view or query), you are saying some things/values participate in. Eg: "SCORE is the review averaging score from the N user reviews of movie MOVIE", giving table (and shorthand) Movie(movie, score, n).
Only when you have identified a particular relationship that you are talking about do phrases like "have a" and "belongs to" or "cardinality of" even have a meaning. Eg: We can express Movie(movie, score, n) as "movie MOVIE has review score value SCORE from N user reviews" as long as we realize that that is a very specific use of "has" for just this table.
We have to decide on sufficient base relationships, each characterized by such a predicate (sentence template) and represented by a table, to fully describe any application situation that can arise. Eg: If a movie can have no reviews then we can use Movie for rows where "movie MOVIE has review score value SCORE from some user reviews" but not "movie MOVIE has review score value SCORE". So that would require an additional predicate/table. Whereas if a movie must have a review then those two predicates mean the same thing and we can just use Movie.
Many predicates of interest can be expressed in terms of some other, base, predicates, and their corresponding tables in terms of corresponding base tables and relation operators. These are views and queries. Eg: Consider HorrorFan(user, movie) "for some values for STARS, SCORE & N, user USER gave user score value STARS to movie MOVIE in genre 'Horror' with review score value SCORE and STARS > 2 * SCORE". It can be rephrased as "there EXISTS values for STARS, GENRE, SCORE & N, such that Review(USER, MOVIE, STARS) AND Genre(MOVIE, GENRE) AND Movie(MOVIE, SCORE, N) AND STARS > 2 * SCORE and GENRE = 'Horror'". The rows that satisfy it, ie that are in its value, are expressed by replacing table predicates by table names and certain logic operators by certain relational operators: SELECT user, movie FROM Review NATURAL JOIN Genre NATURAL JOIN Movie WHERE STARS > 2 * SCORE and GENRE = 'Horror'.
So stop using those vague words and start finding relevant predicates, each of which gets a table.

A: From an entity-relationship point of view, don't confuse attributes with 1:1 relationships. Attributes are distinct from relationships - attributes map to value sets while relationships map between entity sets. Entity sets are key values, while value sets are non-key values.
Attributes are 1:N relations, e.g. each movie is associated with one review score, but multiple movies might have the same review score. If you find 1:1 attributes, that might indicate a natural key that wasn't identified as such.
The number of people that reviewed a movie isn't an attribute of a review score. Given a score of 8, should you be able to tell me how many people reviewed the movie? I don't think so. Rather, both review score and number of people are measurements of a review pool that you're not recording. Given a 1-1 relationship between a movie and a review pool, attributes of the review pool apply transitively to the movie. Cutting out the review pool, you can just record those attributes directly on the movie.


text:
Q: "Please confirm immediately'' vs ''Please confirm at your earliest convenience'' I took a test about choosing the appropriate salutation in writing a business letter. The question tells:

"If you want someone to act immediately, you can write:..."?

I answered:

"Please confirm immediately"

but it turned out to be wrong.

"Please confirm at your earliest convenience"

was the correct choice. I'm confused why is it that even if I want someone to ACT IMMEDIATELY, I should still write: "at your earliest convenience"?

A: Your answer is fine if there is no other context missing. In that case, the person who designed the test has made the mistake.
This appears to be a case of bad test writing. It's a common problem we see on this site, where the person creating the test has one particular answer in mind, but phrases a question poorly, so that more than one correct answer is possible, and confused students come here asking for an explanation.
Now, if the wording included "polite" or "to a superior" or "using the business writing phrases we have learned this week", then your answer is wrong.
There are so many possible answers in that blank that it seems quite odd to put it in a test question.
"Please confirm..."

*

*immediately

*as soon as possible

*right away

*the moment you get this

*at your earliest convenience

All those are correct answers. In fact, the last one is the weakest, because it suggests the other person's convenience, depending on who is receiving the letter.


text:
Q: Netflix Conductor as a workflow engine solution Can someone share a tutorial on how to use Netflix Conductor? Is there like a code example on github or something? I've done a sample on Amazon SWF and understand how the whole thing works but need some pointers on getting started with Conductor.

A: The initial go-to resource is the official documentation of Netflix conductor. The other parts that might help anyone to come up to speed is the actual working of the conductor.
Conductor server mainly manages the lifecycle of the tasks.
Assume that the conductor server is running using default configuration. To execute a workflow, you will need to

*

*Create task definitions,

*Create workflow definition that uses the task definitions in step 1,

*Execute the workflow.

As part of the execution, conductor server schedules the next task in the workflow. It is the first task in the workflow if you have just executed. Conductor uses dyno-queues internally where the tasks are available for consumption by the clients (A client can be an internal task or can be an external worker application that interacts with conductor through REST API).
The main doubt I had initially was about how and where worker runs? The worker can run in the moon provided your worker can access the REST API exposed by the conductor and be able to update the status of the task back. i.e. you can run microservices anywhere it is needed.
A simple usecase could be the on-boarding employment verification. To verify the employee before on-boarding you may check criminal background, drug, education verification etc., If you are running conductor server on your premises and have workers placed in institutions that are responsible for above said areas, the workers would perform the checks and update the workflow accordingly.
Conductor is integrated with explicit components like elastic search, dynomite backed by redis for the data stores. You can have these provisioned over HA cluster.
Using contribs modules you can integrate external MQ brokers for the tasks and have your workflow updated with respective sink details so that the events are published to the configured sink.
You can also have other workflows that you can execute as sub workflow of the main workflow through event handlers in a loosely coupled manner. In the above said usecase this subworkflow could be the workflow for education verification, or a subworkflow for criminal background check etc.
Due to the stateless nature of the conductor, you can run multiple instances of the conductor through containerization.

A: Easiest way in my opinion is using docker.
Clone this repository:
https://github.com/Netflix/conductor
Go to, conductor/docker and run, docker-compose up
Now, open your browser on http://localhost:5000
On the left menu you will see the workflow def item, where you can see a workflow example.
To deploy your own workflow, copy the json from this site, change the name and deploy it using this software Postman.com.
Do a post to this endpoint to deploy: http://localhost:8080/api/metadata/workflow
Do a post to this endpoint to run your workflow: http://localhost:8080/api/workflow/

A: There are a number of sample applications and codelab walkthroughs for Netflix Conductor in the following repository: https://github.com/conductor-sdk/conductor-examples
There is also a free online playground to build/test and run your workflows at https://play.orkes.io

A: I have done small POC on Netflix conductor, you can get detailed description under the below link. Also click on code in below github link to get the code and execute the same.
https://github.com/manishkushwaha1412/conductor-poc/wiki