text:
Q: blogdown serve_site() fails to render any function from keras package As soon as I include any code from the keras package in my content/*.Rmd, I get the following error when trying to serve the site (any other code builds normally):
Rendering content/post/keras.Rmd
Error in render_page(f) :
  Failed to render 'content/post/keras.Rmd'

This is an example but it happens with any keras function, like image_data_generator() (running it in my R console or from the Rmd codechunk works as expected:
library(keras)
is_keras_available()

Here is a link to my Github repo and the Rmd file in question
Further info can also be found in the blogdown issue I posted, that couldn't be fixed.
> xfun::session_info('blogdown')
R version 4.0.2 (2020-06-22)
Platform: x86_64-apple-darwin17.0 (64-bit)
Running under: macOS Catalina 10.15.6, RStudio 1.3.1073

Locale: en_US.UTF-8 / en_US.UTF-8 / en_US.UTF-8 / C / en_US.UTF-8 / en_US.UTF-8

Package version:
  base64enc_0.1.3 BH_1.72.0.3     blogdown_0.20.1 bookdown_0.20   digest_0.6.25   evaluate_0.14   glue_1.4.2      graphics_4.0.2  grDevices_4.0.2
  highr_0.8       htmltools_0.5.0 httpuv_1.5.4    jsonlite_1.7.1  knitr_1.29      later_1.1.0.1   magrittr_1.5    markdown_1.1    methods_4.0.2
  mime_0.9        promises_1.1.1  R6_2.4.1        Rcpp_1.0.5      rlang_0.4.7     rmarkdown_2.3   servr_0.18.1    stats_4.0.2     stringi_1.5.3
  stringr_1.4.0   tinytex_0.25    tools_4.0.2     utils_4.0.2     xfun_0.17       yaml_2.2.1

> devtools::session_info()
─ Session info ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
 setting  value
 version  R version 4.0.2 (2020-06-22)
 os       macOS Catalina 10.15.6
 system   x86_64, darwin17.0
 ui       RStudio
 language (EN)
 collate  en_US.UTF-8
 ctype    en_US.UTF-8
 tz       Europe/Berlin
 date     2020-09-09
─ Packages ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
 package     * version date       lib source
 assertthat    0.2.1   2019-03-21 [1] CRAN (R 4.0.0)
 backports     1.1.9   2020-08-24 [1] CRAN (R 4.0.2)
 base64enc     0.1-3   2015-07-28 [1] CRAN (R 4.0.0)
 blob          1.2.1   2020-01-20 [1] CRAN (R 4.0.2)
 blogdown      0.20.1  2020-09-09 [1] Github (rstudio/blogdown@d96fe78)
 bookdown      0.20    2020-06-23 [1] CRAN (R 4.0.2)
 callr         3.4.4   2020-09-07 [1] CRAN (R 4.0.2)
 cli           2.0.2   2020-02-28 [1] CRAN (R 4.0.0)
 crayon        1.3.4   2017-09-16 [1] CRAN (R 4.0.0)
 curl          4.3     2019-12-02 [1] CRAN (R 4.0.0)
 DBI           1.1.0   2019-12-15 [1] CRAN (R 4.0.0)
 dbplyr        1.4.4   2020-05-27 [1] CRAN (R 4.0.2)
 desc          1.2.0   2018-05-01 [1] CRAN (R 4.0.0)
 devtools      2.3.1   2020-07-21 [1] CRAN (R 4.0.2)
 digest        0.6.25  2020-02-23 [1] CRAN (R 4.0.0)
 dplyr         1.0.2   2020-08-18 [1] CRAN (R 4.0.2)
 ellipsis      0.3.1   2020-05-15 [1] CRAN (R 4.0.0)
 evaluate      0.14    2019-05-28 [1] CRAN (R 4.0.1)
 fansi         0.4.1   2020-01-08 [1] CRAN (R 4.0.0)
 fs            1.5.0   2020-07-31 [1] CRAN (R 4.0.2)
 generics      0.0.2   2018-11-29 [1] CRAN (R 4.0.0)
 glue          1.4.2   2020-08-27 [1] CRAN (R 4.0.2)
 htmltools     0.5.0   2020-06-16 [1] CRAN (R 4.0.2)
 jsonlite      1.7.1   2020-09-07 [1] CRAN (R 4.0.2)
 keras       * 2.3.0.0 2020-05-19 [1] CRAN (R 4.0.2)
 knitr         1.29    2020-06-23 [1] CRAN (R 4.0.2)
 lattice       0.20-41 2020-04-02 [1] CRAN (R 4.0.2)
 lifecycle     0.2.0   2020-03-06 [1] CRAN (R 4.0.0)
 magrittr      1.5     2014-11-22 [1] CRAN (R 4.0.0)
 Matrix        1.2-18  2019-11-27 [1] CRAN (R 4.0.2)
 memoise       1.1.0   2017-04-21 [1] CRAN (R 4.0.0)
 pillar        1.4.6   2020-07-10 [1] CRAN (R 4.0.2)
 pkgbuild      1.1.0   2020-07-13 [1] CRAN (R 4.0.2)
 pkgconfig     2.0.3   2019-09-22 [1] CRAN (R 4.0.0)
 pkgload       1.1.0   2020-05-29 [1] CRAN (R 4.0.2)
 prettyunits   1.1.1   2020-01-24 [1] CRAN (R 4.0.0)
 processx      3.4.4   2020-09-03 [1] CRAN (R 4.0.2)
 ps            1.3.4   2020-08-11 [1] CRAN (R 4.0.2)
 purrr         0.3.4   2020-04-17 [1] CRAN (R 4.0.0)
R6            2.4.1   2019-11-12 [1] CRAN (R 4.0.0)
 Rcpp          1.0.5   2020-07-06 [1] CRAN (R 4.0.2)
 remotes       2.2.0   2020-07-21 [1] CRAN (R 4.0.2)
 reticulate    1.16    2020-05-27 [1] CRAN (R 4.0.2)
 rlang         0.4.7   2020-07-09 [1] CRAN (R 4.0.2)
 rmarkdown     2.3     2020-06-18 [1] CRAN (R 4.0.2)
 rprojroot     1.3-2   2018-01-03 [1] CRAN (R 4.0.0)
 rstudioapi    0.11    2020-02-07 [1] CRAN (R 4.0.0)
 sessioninfo   1.1.1   2018-11-05 [1] CRAN (R 4.0.0)
 tensorflow    2.2.0   2020-05-11 [1] CRAN (R 4.0.0)
 testthat      2.3.2   2020-03-02 [1] CRAN (R 4.0.0)
 tfruns        1.4     2018-08-25 [1] CRAN (R 4.0.0)
 tibble        3.0.3   2020-07-10 [1] CRAN (R 4.0.2)
 tidyselect    1.1.0   2020-05-11 [1] CRAN (R 4.0.0)
 usethis       1.6.1   2020-04-29 [1] CRAN (R 4.0.0)
 vctrs         0.3.4   2020-08-29 [1] CRAN (R 4.0.2)
 whisker       0.4     2019-08-28 [1] CRAN (R 4.0.0)
 withr         2.2.0   2020-04-20 [1] CRAN (R 4.0.0)
 xfun          0.17    2020-09-09 [1] CRAN (R 4.0.2)
 yaml          2.2.1   2020-02-01 [1] CRAN (R 4.0.0)
 zeallot       0.1.0   2018-01-28 [1] CRAN (R 4.0.0)

[1] /Library/Frameworks/R.framework/Versions/4.0/Resources/library
>


text:
Q: How to animate this optimization model correctly I have implemented a simple randomized, population-based optimization method - Grey Wolf optimizer. I am having some trouble with properly capturing the Matplotlib plots at each iteration using the camera package.
I am running GWO for the objective function f(x,y) = x^2 + y^2. I can only see the candidate solutions converging to the minima, but the contour plot doesn't show up.
Do you have any suggestions, how can I display the contour plot in the background?

GWO Algorithm implementation
%matplotlib notebook
import matplotlib.pyplot as plt
import numpy as np
from celluloid import Camera
import ffmpeg
import pillow

# X : Position vector of the initial population
# n : Initial population size

def gwo(f,max_iterations,LB,UB):

    fig = plt.figure()
    camera = Camera(fig)

    def random_population_uniform(m,a,b):
        dims = len(a)
        x = [list(a + np.multiply(np.random.rand(dims),b - a)) for i in range(m)]
        return np.array(x)

    def search_agent_fitness(fitness):
        alpha = 0
        if fitness[1] < fitness[alpha]:
            alpha, beta = 1, alpha
        else:
            beta = 1

        if fitness[2] > fitness[alpha] and fitness[2] < fitness[beta]:
            beta, delta = 2, beta
        elif fitness[2] < fitness[alpha]:
            alpha,beta,delta = 2,alpha,beta
        else:
            delta = 2

        for i in range(3,len(fitness)):
            if fitness[i] <= fitness[alpha]:
                alpha, beta,delta = i, alpha, beta
            elif fitness[i] > fitness[alpha] and fitness[i]<= fitness[beta]:
                beta,delta = i,beta
            elif fitness[i] > fitness[beta] and fitness[i]<= fitness[delta]:
                delta = i

        return alpha, beta, delta

    def plot_search_agent_positions(f,X,alpha,beta,delta,a,b):

        # Plot the positions of search agents

        x = X[:,0]
        y = X[:,1]

        s = plt.scatter(x,y,c='gray',zorder=1)
        s = plt.scatter(x[alpha],y[alpha],c='red',zorder=1)
        s = plt.scatter(x[beta],y[beta],c='blue',zorder=1)
        s = plt.scatter(x[delta],y[delta],c='green',zorder=1)

        camera.snap()

    # Initialize the position of the search agents
    X = random_population_uniform(50,np.array(LB),np.array(UB))

    n = len(X)

    l = 1

    # Plot the first image on screen
    x = np.linspace(LB[0],LB[1],1000)
    y = np.linspace(LB[0],UB[1],1000)

    X1,X2 = np.meshgrid(x,y)

    Z = f(X1,X2)
    cont = plt.contour(X1,X2,Z,20,linewidths=0.75)

    while (l < max_iterations):
            # Take the x,y coordinates of the initial population
            x = X[:,0]
            y = X[:,1]

            # Calculate the objective function for each search agent
            fitness = list(map(f,x,y))

            # Update alpha, beta and delta
            alpha,beta,delta = search_agent_fitness(fitness)

            # Plot search agent positions
            plot_search_agent_positions(f,X,alpha,beta,delta,LB,UB)

            # a decreases linearly from 2 to 0
            a = 2 - l *(2 / max_iterations)

            # Update the position of search agents including the Omegas
            for i in range(n):
                x_prey = X[alpha]

                r1 = np.random.rand(2) #r1 is a random vector in [0,1] x [0,1]
                r2 = np.random.rand(2) #r2 is a random vector in [0,1] x [0,1]
                A1 = 2*a*r1 - a
                C1 = 2*r2

                D_alpha = np.abs(C1 * x_prey - X[i])
                X_1 = x_prey - A1*D_alpha

                x_prey = X[beta]
                r1 = np.random.rand(2)
                r2 = np.random.rand(2)
                A2 = 2*a*r1 - a
                C2 = 2*r2

                D_beta = np.abs(C2 * x_prey - X[i])
                X_2 = x_prey - A2*D_beta

                x_prey = X[delta]
                r1 = np.random.rand(2)
                r2 = np.random.rand(2)
                A3 = 2*a*r1 - a
                C3 = 2*r2

                D_delta = np.abs(C3 * x_prey - X[i])
                X_3 = x_prey - A3*D_delta

                X[i] = (X_1 + X_2 + X_3)/3

            l = l + 1

    return X[alpha],camera

Function call
# define the objective function
def f(x,y):
    return x**2 + y**2

minimizer,camera = gwo(f,7,[-10,-10],[10,10])

animation = camera.animate(interval = 1000, repeat = True,
                           repeat_delay = 500)

A: Is it possible that the line  x = np.linspace(LB[0],LB[1],1000) should be x = np.linspace(LB[0],UB[1],1000) instead? With your current definition of x, x is an array only filled with the value -10 which means that you are unlikely to find a contour.
Another thing that you might want to do is to move the  cont = plt.contour(X1,X2,Z,20,linewidths=0.75) line inside of your plot_search_agent_positions function to ensure that the contour is plotted at each iteration of the animation.
Once you make those changes, the code looks like that:
import matplotlib.pyplot as plt
import numpy as np
from celluloid import Camera
import ffmpeg
import PIL
from matplotlib import animation, rc
from IPython.display import HTML, Image # For GIF
from scipy.interpolate import griddata

rc('animation', html='html5')

# X : Position vector of the initial population
# n : Initial population size

def gwo(f,max_iterations,LB,UB):

    fig = plt.figure()
    fig.gca(aspect='equal')
    camera = Camera(fig)

    def random_population_uniform(m,a,b):
        dims = len(a)
        x = [list(a + np.multiply(np.random.rand(dims),b - a)) for i in range(m)]
        return np.array(x)

    def search_agent_fitness(fitness):
        alpha = 0
        if fitness[1] < fitness[alpha]:
            alpha, beta = 1, alpha
        else:
            beta = 1

        if fitness[2] > fitness[alpha] and fitness[2] < fitness[beta]:
            beta, delta = 2, beta
        elif fitness[2] < fitness[alpha]:
            alpha,beta,delta = 2,alpha,beta
        else:
            delta = 2

        for i in range(3,len(fitness)):
            if fitness[i] <= fitness[alpha]:
                alpha, beta,delta = i, alpha, beta
            elif fitness[i] > fitness[alpha] and fitness[i]<= fitness[beta]:
                beta,delta = i,beta
            elif fitness[i] > fitness[beta] and fitness[i]<= fitness[delta]:
                delta = i

        return alpha, beta, delta

    def plot_search_agent_positions(f,X,alpha,beta,delta,a,b,X1,X2,Z):

        # Plot the positions of search agents

        x = X[:,0]
        y = X[:,1]

        s = plt.scatter(x,y,c='gray',zorder=1)
        s = plt.scatter(x[alpha],y[alpha],c='red',zorder=1)
        s = plt.scatter(x[beta],y[beta],c='blue',zorder=1)
        s = plt.scatter(x[delta],y[delta],c='green',zorder=1)
        Z=f(X1,X2)
        cont=plt.contour(X1,X2,Z,levels=20,colors='k',norm=True)
        plt.clabel(cont, cont.levels, inline=True, fontsize=10)
        camera.snap()

    # Initialize the position of the search agents
    X = random_population_uniform(50,np.array(LB),np.array(UB))

    n = len(X)

    l = 1

    # Plot the first image on screen
    x = np.linspace(LB[0],UB[1],1000)
    y = np.linspace(LB[0],UB[1],1000)

    X1,X2 = np.meshgrid(x,y)
    Z=f(X1,X2)

    while (l < max_iterations):
            # Take the x,y coordinates of the initial population
            x = X[:,0]
            y = X[:,1]

            # Calculate the objective function for each search agent
            fitness = list(map(f,x,y))

            # Update alpha, beta and delta
            alpha,beta,delta = search_agent_fitness(fitness)

            # Plot search agent positions
            plot_search_agent_positions(f,X,alpha,beta,delta,LB,UB,X1,X2,Z)

            # a decreases linearly from 2 to 0
            a = 2 - l *(2 / max_iterations)

            # Update the position of search agents including the Omegas
            for i in range(n):
                x_prey = X[alpha]

                r1 = np.random.rand(2) #r1 is a random vector in [0,1] x [0,1]
                r2 = np.random.rand(2) #r2 is a random vector in [0,1] x [0,1]
                A1 = 2*a*r1 - a
                C1 = 2*r2

                D_alpha = np.abs(C1 * x_prey - X[i])
                X_1 = x_prey - A1*D_alpha

                x_prey = X[beta]
                r1 = np.random.rand(2)
                r2 = np.random.rand(2)
                A2 = 2*a*r1 - a
                C2 = 2*r2

                D_beta = np.abs(C2 * x_prey - X[i])
                X_2 = x_prey - A2*D_beta

                x_prey = X[delta]
                r1 = np.random.rand(2)
                r2 = np.random.rand(2)
                A3 = 2*a*r1 - a
                C3 = 2*r2

                D_delta = np.abs(C3 * x_prey - X[i])
                X_3 = x_prey - A3*D_delta

                X[i] = (X_1 + X_2 + X_3)/3

            l = l + 1

    return X[alpha],camera
    # define the objective function
def f(x,y):
    return x**2 + y**2

minimizer,camera = gwo(f,7,[-10,-10],[10,10])

animation = camera.animate(interval = 1000, repeat = True,repeat_delay = 500)

And the output gives:

redpajama_set_name: RedPajamaStackExchange


text:
Q: C++ directory_iterator memory usage keeps increasing I wrote a simple directory_iterator method in C++ to list the number of files in a given directory and noticed that when running the application the windows task manager memory usage for the application keeps increasing. I am not using any pointers so there is no free or delete[] statement in the below code.
This code snippet is part of a c++ webserver which keeps running and i noticed this issue of memory usage increase every time a directory_iterator is called. So i tried it on a stand alone application and noticed the same.
Sample code below. Visual Studio 16.9.3, C++ 17, (windows 7 pro)
#include <iostream>
#include <filesystem>
#include <conio.h>
#include <windows.h>
#include <codecvt>

std::string ws2s(const std::wstring& wstr)
{
    //std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> cvt;
    //return cvt.to_bytes(wstr);

    if (wstr.empty()) return std::string();
    int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), NULL, 0, NULL, NULL);
    std::string strTo(size_needed, 0);
    WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), &strTo[0], size_needed, NULL, NULL);
    return strTo;
}

int main()
{
    int counter = 0;

    while (!_kbhit())
    {
        Sleep(1000);
        for (const auto& entry : std::filesystem::directory_iterator("c:\\test"))
        {
            std::string fileName("");
            std::string pathName("");

            fileName = ws2s(entry.path().filename().wstring());
            std::cout << fileName << std::endl;
        }
        counter++;
        std::cout << counter << std::endl;
    }

    system("pause");
}


text:
Q: Python - Execute Java - Could not find or load main class I followed the SO Answer to execute a java program from python
import os.path, subprocess
from subprocess import STDOUT, PIPE

def compile_java(java_file):
    subprocess.check_call(['javac', java_file])

def execute_java(java_file, stdin):
    java_class, ext = os.path.splitext(java_file)
    cmd = ['java', java_class]
    process = subprocess.Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=STDOUT, universal_newlines=True)
    stdout, stderr = process.communicate(stdin)
    print(stdout)

compile_java(os.path.join('model', 'classification', 'Model.java'))
execute_java('Model', '5 6 7 8')

The python code compiles the /model/classification/Model.java without problems. But when the python code executes the java program, Java can not find or load the main class Model. Executing java Model in the command line in the same directory (with the compiled version, which was triggered by the python snippet above) works.

A: The problem seems to be, that you have to add the directory of your *.class file to the classpath! You compiled the class in the directory model/classification so the path of your *.class file is model/classification/Model.class. For executing this bytecode you need to add the directory to classpath by writing java -cp model/classification Model...
This python code works for me:
import os.path,subprocess
from subprocess import STDOUT,PIPE

def compile_java(java_file):
    subprocess.check_call(['javac', java_file])

def execute_java(java_file, stdin):
    java_class,ext = os.path.splitext(java_file)

    // I changed the following line by adding the directory to the classpath
    cmd = ['java', '-cp', 'model/classification', java_class]

    proc = subprocess.Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=STDOUT)
    stdout,stderr = proc.communicate(stdin)
    print ('This was "' + stdout + '"')

compile_java(os.path.join('model', 'classification', 'Model.java'))
execute_java('Model.java', '5 6 7 8')

In this case, the directory path is relative to the execution directory of your python script!


text:
Q: How can I split a string by white spaces that are not precedent by a certain character? I want to split a string only at white spaces that does not have a certain delimiter (: in my case) before it. E.g.:
$string = "Time: 10:40 Request: page.php Action: whatever this is Refer: Facebook";

Then from something like this I want to achieve an array such that:
$array = ["Time: 10:40", "Request: page.php", "Action: whatever this is", "Refer: Facebook"];

I've tried the following so far:
$split = preg_split('/(:){0}\s/', $visit);

But this is still splitting at every occurence of a white space.
Edit: I think I asked the wrong question, however "whatever this is" should stay as a single string
Edit 2: The bits before the colons are known and stay the same, maybe incorporating those somehow makes the task easier (of not splitting at whitespace characters in strings that should stay together)?

A: You can use a lookahead in your split regex:
/\h+(?=[A-Z][a-z]*: )/

RegEx Demo
Regex \h+(?=[A-Z][a-z]*: ) matches 1+ whitespaces that is followed by a word starting with upper case letter and a colon and space.

A: you can do it
$string = "Time: 10:40 Request: page.php Action: whatever this is Refer: Facebook";

$split = preg_split('/\h+(?=[A-Z][a-z]*:)/', $string);

dd($split);

A: Another option could be to match what is before the colon and then match upon the next part that starts with a space, non whitespace chars and colon:
\S+:\h+.*?(?=\h+\S+:)\K\h+

*

*\S+: Match 1+ times a non whitespace char

*\h+ Match 1+ times a horizontal whitespace char

*.*? Match any char except a newline non greedy

*(?=\h+\S+:) Positive lookahead, assert what is on the right is 1+ horizontal whitespace chars, 1+ non whitespace chars and a colon

*\K\h+ Forget what was matched using \K and match 1+ horizontal whitespace chars

Regex demo | php demo


text:
Q: Twitter Bootstrap Modal being affected by opacity CSS rule I have a problem with the twitter bootstrap modal setting the backdrop over the top of the modal IF an 'opacity' (less than 1) is set on the main  that the modal's html resides in.
Html Layout:

  ...some html

      <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Some Title

         ...some content

      <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>

CSS
.content-area {
 opacity:0.9;
}

Therefore, the result is when the Modal is called:
$("#someModelId").modal();
The background that the modal specifies sits in front of the modal and clicking on the modal acts as if you clicked outside the modal context and caused it to close.

A: This turned out to require moving the affected dialog html, outside of the area that was applying the opacity rule via css.


text:
Q: vue karma, how to write unit test Is there any example how to write test case in vue? The click event not working.
The template in App.vue
<template>

<textarea v-model="input" id="input" rows="3" placeholder="Please entry colors, eg: '#000','#fff' or ['#000', '#fff']"></textarea>
<button type="button" class="btn btn-primary parse" @click="parse">Go!</button>

      {{color}}

karma test
describe('App.vue', () => {
it('should render correct color', () => {
const vm = new Vue({
  template: "
<app></app>
",
  components: {
    App
  }
}).$mount()
console.log(vm.$el)
vm.input = '#333, #444'
vm.$el.querySelector('.btn').click()
expect(vm.$el.querySelector('ul li:eq(0) span').style.background).toBe('#333')
 })
})

And I have output the vm.$el, it shows like below, missing the v-model and @click

A: Does it give you any error? Are you using PhantomJS as browser?
I don't think click is supported on PhantomJS
See here PhantomJS; click an element


text:
Q: Webpack Module Parse Error with React when I try and run my Webpack config it fails with the following errors:
$ webpack
Hash: 826e21c818de1882d366
Version: webpack 1.13.1
Time: 53ms
   [0] ./public/js/react/swap-shop.js 0 bytes [built] [failed]

ERROR in ./public/js/react/swap-shop.js
Module parse failed: /Users/work/Development/group-2/public/js/react/swap-shop.js Unexpected token (23:6)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (23:6)
    at Parser.pp.raise (/Users/work/Development/group-2/node_modules/webpack/node_modules/acorn/dist/acorn.js:923:13)
    at Parser.pp.unexpected (/Users/work/Development/group-2/node_modules/webpack/node_modules/acorn/dist/acorn.js:1490:8)
    at Parser.pp.parseExprAtom (/Users/work/Development/group-2/node_modules/webpack/node_modules/acorn/dist/acorn.js:333:12)
    at Parser.pp.parseExprSubscripts (/Users/work/Development/group-2/node_modules/webpack/node_modules/acorn/dist/acorn.js:228:19)
    at Parser.pp.parseMaybeUnary (/Users/work/Development/group-2/node_modules/webpack/node_modules/acorn/dist/acorn.js:207:17)
    at Parser.pp.parseExprOps (/Users/work/Development/group-2/node_modules/webpack/node_modules/acorn/dist/acorn.js:154:19)
    at Parser.pp.parseMaybeConditional (/Users/work/Development/group-2/node_modules/webpack/node_modules/acorn/dist/acorn.js:136:19)
    at Parser.pp.parseMaybeAssign (/Users/work/Development/group-2/node_modules/webpack/node_modules/acorn/dist/acorn.js:112:19)
    at Parser.pp.parseParenAndDistinguishExpression (/Users/work/Development/group-2/node_modules/webpack/node_modules/acorn/dist/acorn.js:376:28)
    at Parser.pp.parseExprAtom (/Users/work/Development/group-2/node_modules/webpack/node_modules/acorn/dist/acorn.js:307:19)
    at Parser.pp.parseExprSubscripts (/Users/work/Development/group-2/node_modules/webpack/node_modules/acorn/dist/acorn.js:228:19)
    at Parser.pp.parseMaybeUnary (/Users/work/Development/group-2/node_modules/webpack/node_modules/acorn/dist/acorn.js:207:17)
    at Parser.pp.parseExprOps (/Users/work/Development/group-2/node_modules/webpack/node_modules/acorn/dist/acorn.js:154:19)
    at Parser.pp.parseMaybeConditional (/Users/work/Development/group-2/node_modules/webpack/node_modules/acorn/dist/acorn.js:136:19)
    at Parser.pp.parseMaybeAssign (/Users/work/Development/group-2/node_modules/webpack/node_modules/acorn/dist/acorn.js:112:19)
    at Parser.pp.parseExpression (/Users/work/Development/group-2/node_modules/webpack/node_modules/acorn/dist/acorn.js:88:19)
    at Parser.pp.parseReturnStatement (/Users/work/Development/group-2/node_modules/webpack/node_modules/acorn/dist/acorn.js:1872:26)
    at Parser.pp.parseStatement (/Users/work/Development/group-2/node_modules/webpack/node_modules/acorn/dist/acorn.js:1737:19)
    at Parser.pp.parseBlock (/Users/work/Development/group-2/node_modules/webpack/node_modules/acorn/dist/acorn.js:2009:21)
    at Parser.pp.parseFunctionBody (/Users/work/Development/group-2/node_modules/webpack/node_modules/acorn/dist/acorn.js:610:22)
    at Parser.pp.parseMethod (/Users/work/Development/group-2/node_modules/webpack/node_modules/acorn/dist/acorn.js:579:8)
    at Parser.pp.parseClassMethod (/Users/work/Development/group-2/node_modules/webpack/node_modules/acorn/dist/acorn.js:2155:23)
    at Parser.pp.parseClass (/Users/work/Development/group-2/node_modules/webpack/node_modules/acorn/dist/acorn.js:2140:10)
    at Parser.pp.parseStatement (/Users/work/Development/group-2/node_modules/webpack/node_modules/acorn/dist/acorn.js:1733:19)
    at Parser.pp.parseTopLevel (/Users/work/Development/group-2/node_modules/webpack/node_modules/acorn/dist/acorn.js:1666:21)
    at Parser.parse (/Users/work/Development/group-2/node_modules/webpack/node_modules/acorn/dist/acorn.js:1632:17)
    at Object.parse (/Users/work/Development/group-2/node_modules/webpack/node_modules/acorn/dist/acorn.js:885:44)
    at Parser.parse (/Users/work/Development/group-2/node_modules/webpack/lib/Parser.js:902:15)
    at DependenciesBlock.<anonymous> (/Users/work/Development/group-2/node_modules/webpack/lib/NormalModule.js:104:16)
    at DependenciesBlock.onModuleBuild (/Users/work/Development/group-2/node_modules/webpack/node_modules/webpack-core/lib/NormalModuleMixin.js:310:10)

I'm unsure why this might be happening, here is my config:
var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');

module.exports = {
  context: __dirname,
  devtool: debug ? "inline-sourcemap" : null,
  entry: "./public/js/react/swap-shop.js",
  output: {
    path: __dirname + "/dist",
    filename: "scripts.min.js"
  },
  plugins: debug ? [] : [
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
  ],
};

Then I have my React components that I am actually trying to bundle, here is the swap-shop.js file
import VehicleList from './components/vehicle-list.js';

class VehicleContainer extends React.Component {

  constructor(props) {
    super(props);

    this.state = { vehicles: [] };

  }

  componentWillMount() {

    // Make a request for vehicle data

    axios.get('/api/models')
    .then(response => this.setState({ vehicles: response.data }))
    .catch(error => console.log(error));
  }
  render() {
                console.log(this.state.vehicles);
    return (
      <VehicleList vehicles={this.state.vehicles}/>
    )
  }
};

ReactDOM.render(
  <VehicleContainer />,
  document.getElementById('swap-shop-range').getElementsByClassName('react-target')[0]
);

Then I have my VehicleList component:
// Vehicle List Componen
import VehicleDetail from './vehicle-detail';
// Create our component
let VEHICLES = [
  {make: 'Volkswagen', model: 'Golf', image: 'https://s3-eu-west-1.amazonaws.com/pulman-vw-images/uploads/images/thumbnails/a4a40021d1661b474e42ad3aa0419d940601b27f.png'}
];
const VehicleList = (props) => {
  // Just add props.vehicle to access API data instead of static
  const RenderedVehicles = VEHICLES.map(vehicle =>
    <VehicleDetail key={vehicle.make} vehicle={vehicle} />
  );

  return (

      {RenderedVehicles}

  );
};

// Export our component
export default VehicleList;

And finally my VehicleDetail component:
// Vehicle Description Component

const VehicleDetail = (props) => {
  return (

          {props.vehicle.make}
          {props.vehicle.model}

            Learn More

            Test Drive

  );
};

// Export our component
export default VehicleDetail;

My React component hierarchy:
public/js/react/

  swap-shop.js

  components/

    vehicle-detail.js
    vehicle-list.js

Then I simply include React, ReactDOM and Babel into my page just above the script tag that includes my React code. When I paste all of the components into my actual html page with one inline script tag they seem to work however when I try to bundle them with webpack I get this error for some reason. Any idea why this might be happening?

A: You may need babel-loader, babel-preset-es2015 and babel-preset-react
module.exports = {
  context: __dirname,
  devtool: debug ? "inline-sourcemap" : null,
  entry: "./public/js/react/swap-shop.js",
  output: {
    path: __dirname + "/dist",
    filename: "scripts.min.js"
  },
  module: {
    loaders: [
        {
            test: /\.js$/,
            exclude: /(node_modules|bower_components)/,
            loader: 'babel-loader',
            query: {
               presets: ['es2015']
            }
        }
   ]},
  plugins: debug ? [] : [
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false      })]};

Read more https://www.twilio.com/blog/2015/08/setting-up-react-for-es6-with-webpack-and-babel-2.html


text:
Q: Python strange list behavior i'm trying to update a csv file using the csv module but i've found some strange behaviour:
consider this code to read a csv
import csv
reader = csv.reader(open('/Users/r2-d2/Desktop/output.csv', 'rb'), delimiter = '\t')

And printing this way
for row in reader:
    print row

This code totally works and i get multiple lists one of each represents a row of my cvs
Now consider this code:
for row in reader:
    print row[0]

This code does not work for reasons unknown to me. (IndexError: list index out of range) EDIT: row[0] is empty but any other index gives error even if non empty
This code however
for row in reader:
    print row[:3]

Works as expected and i get the first 3 entries for each row as a list.
I am definitely missing something.

A: Some of your rows must be empty.
my_list[0]

throws and IndexError when my_list is empty
my_list[:3] will never break, as it will try to give you the slice of data you want, but would return less if my_list is shorter than the last index requested.
try:
for row in reader:
    if row:  # identical to if(len(row))
        print row[0]

EDIT:
I think that you should try to open your file in standard mode, not in binary mode:
reader = csv.reader(open('/Users/r2-d2/Desktop/output.csv', 'r'), delimiter = '\t')


text:
Q: How to give link from button in twitter bootstrap I have created a button using
<button type="button" class="btn btn-success btn-lg ">Register</button>

How could I give a link to another page when the button is pressed?

A: Use a anchor instead, and you can still style it as a button..
Register

Bootply: http://www.bootply.com/99320


text:
Q: Transferring Excel data into SQL table with different columns I want user to transfer data from Excel files into SQL using a C# WinForms application one file at a time. The Excel files consist of similar columns, and so there might be some new columns or columns absent. Row data will vary.
For example:
Excel file 1: Name, City State
Excel file 2: Name, City, Zip
Excel file 3: Name, City, County
In my existing SQL table I have columns: Name, City, Population, Schools
How do I insert the new Excel files with similar column names into an existing SQL database?
My thought so far is to copy the new Excel file data into temporary tables, and then insert that into the existing SQL table. The problem is, I don't know how to write C# code (or a SQL query) that would insert new Excel data with more or less columns than the existing SQL table.

A: You need No-SQL for this purpose, if you need to enter columns that are not already part of the table then sql is not a good option if you use c# to alter table  then be careful to the consequences. If you are sure about all possible column names in front then try altering your table before you start insert

A: This should't be too hard.  Export your data from Excel to a staging table table in SQL Server.  The C# code may look something like this.
public void importdatafromexcel(string excelfilepath)
{
    //declare variables - edit these based on your particular situation
    string ssqltable = "tdatamigrationtable";
    // make sure your sheet name is correct, here sheet name is sheet1, so you can change your sheet name if have
    different
    string myexceldataquery = "select student,rollno,course from [sheet1$]";
    try
    {
        //create our connection strings
        string sexcelconnectionstring = @"provider=microsoft.jet.oledb.4.0;data source=" + excelfilepath +
        ";extended properties=" + "\"excel 8.0;hdr=yes;\"";
        string ssqlconnectionstring = "server=mydatabaseservername;user
        id=dbuserid;password=dbuserpassword;database=databasename;connection reset=false";
        //execute a query to erase any previous data from our destination table
        string sclearsql = "delete from " + ssqltable;
        sqlconnection sqlconn = new sqlconnection(ssqlconnectionstring);
        sqlcommand sqlcmd = new sqlcommand(sclearsql, sqlconn);
        sqlconn.open();
        sqlcmd.executenonquery();
        sqlconn.close();
        //series of commands to bulk copy data from the excel file into our sql table
        oledbconnection oledbconn = new oledbconnection(sexcelconnectionstring);
        oledbcommand oledbcmd = new oledbcommand(myexceldataquery, oledbconn);
        oledbconn.open();
        oledbdatareader dr = oledbcmd.executereader();
        sqlbulkcopy bulkcopy = new sqlbulkcopy(ssqlconnectionstring);
        bulkcopy.destinationtablename = ssqltable;
        while (dr.read())
        {
            bulkcopy.writetoserver(dr);
        }

        oledbconn.close();
    }
    catch (exception ex)
    {
        //handle exception
    }
}

Then, in SQL Server, move the data from the staging table to your final production table.  Your SQL may look something like this.
insert into production
select ...
from staging
where not exists
(
    select 1 from staging
    where staging.key = production.key
)

That's my .02.  I think you will have a lot more control over the whole process that way.

A: If you are reading this question then my answer to this other question may be helpful for you (just create a Class to handle each row information, process the excel file and perform a bulk insert like explained there):
Bulk insert is not working properly in Azure SQL Server
I hope it helps.


text:
Q: Getting stickynotes to stay always on top? (just documenting this - self-answer to follow)
I am using the stickynotes applet in Ubuntu Natty for notes. I would occasionally like these notes to stay "always on top", but I cannot find a setting for anything like that (pic from here):

Is it at all possible to somehow force a stickynotes note to stay always on top?

A: Yup, it is possible - got the answer thanks to this post: Application started in shell automatically "always on top" / Desktop / Xfce Forums; one can use wmctrl for that.
First, in terminal, use wmctrl to obtain a listing of currently active windows:
$ wmctrl -l
0x01a00003 -1 mypc Bottom Expanded Edge Panel
0x01a00036 -1 mypc Top Expanded Edge Panel
0x01200023 -1 mypc x-nautilus-desktop
0x042000e1  1 mypc Mozilla Firefox
0x03400024  0 mypc Terminal
0x032000f2 -1 mypc 2013-03-29

The "2013-03-29" is the title of my stickynotes note window; then one can just run this command, in order to force that particular note window to stay on top:
wmctrl -i -r 0x032000f2 -b toggle,above

Note the use of -i switch, to "Interpret window arguments (<WIN>) as a numeric value rather than a string name for the window.". Also, this toggles the "always on top" property for the window; so if you'd like to turn the "always on top" off - simply run the same above command again.
Note that if stickynotes is set up to "Put notes on all workspaces"; then the "always on top" setting will be valid for all workspaces (although you may have to click through other windows at first, to have the window "understand" it should be "always on top").


text:
Q: Is $a\in[a,a)$? The title is my question, no more things.

A: $[a,b)$ is defined as $\{x:\ a\leq x < b\}$. If $a=b$ then the inequality $a\leq x < a$ is never satisfied. Therefore the set is empty.

A: No, as $[a,a)$ means $a \le a $ and $a<a$ according to Baby Rudin.  The second inequality is clearly false, so the set $[a,a)=\varnothing$.


text:
Q: Fast integration of a posterior distribution I wish to infer the posterior distribution on the probability of success $\theta$ in some binomial process, the twist being that I know that $\theta$ lies in the interval [0.5, 1].
The trouble is that a Beta distribution that is supported on [0.5, 1] is no longer conjugate. In particular, the prior looks like this ($p$ is the pdf):
$p(\theta) \propto {(\theta-0.5)}^{\alpha-1} {(1-\theta)}^{\beta-1}$
The likelihood, given $x$ successes in $n$ trials, is the usual binomial likelihood:
$p(n,x | \theta) \propto \theta^x {(1-\theta)}^{n-x}$
The posterior, as it stands, looks like this:
$p( \theta | n, x) \propto \theta^x {(\theta-0.5)}^{\alpha-1} {(1-\theta)}^{n-x+\beta-1}$
I would like to be able to make CDF calculations (i.e. compute integrals) of the posterior efficiently. (numerical integration, e.g., may be too slow for my purposes). I am unable to figure out how to do this.
Much appreciate any help the forum can provide.

A: How accurate does your posterior cdf need to be? You might consider replacing the continuous prior with a discrete approximation:
$p^*(\theta) \propto p(\theta) 1(\theta\in t_1, \dots, t_k)$
where $p(\theta)$ is your original continuous prior.
Then to compute the posterior you just calculate likelihood x prior
$p(\theta|x) \propto p^*(\theta)p(x|\theta)$
over the support of the prior $t_1, \dots, t_k$ and renormalize.
This is called "griddy Gibbs" by some. It can be quite effective if you have an informative prior in which case you can choose the grid points non-uniformly (and, of course, if you can live with a discrete approximation coarse enough to be computationally feasible).

A: There may be a simpler approach, simply by applying the usual Beta conjugate to the binomial, and then requiring $\theta \in [\frac12,1]$. You can do this with an indicator function, for example as in
$$p(\theta) \propto \theta^{\alpha-1} {(1-\theta)}^{\beta-1} \mathbb{1}[{\tfrac12 \le \theta \le 1}]$$
Now apply your $p(n,x | \theta) \propto \theta^x {(1-\theta)}^{n-x}$ to get the posterior density
$$p(\theta|x) \propto \theta^{\alpha+x-1} {(1-\theta)}^{\beta+n-x-1} \mathbb{1}[{\tfrac12 \le \theta \le 1}].$$
The posterior cumulative distribution function for $\theta \in [\frac12,1]$ is then $\dfrac{I_\theta(\alpha+x, \beta+n-x)-I_{\frac12}(\alpha+x, \beta+n-x)}{1-I_{\frac12}(\alpha+x, \beta+n-x)}$ with $I$ representing a regularised incomplete beta function or the cumulative distribution function of a Beta distribution, which any decent statistical program will calculate quickly, such as R's pbeta function.

A: You can always use Monte Carlo Integration or the Midpoint method. With Monte Carlo, you simply generate a bunch of points in your parameter space and see if they are in the area or volume or hyper-dimensional space you are trying to integrate.
From:
http://farside.ph.utexas.edu/teaching/329/lectures/node109.html
"Let us now consider the so-called Monte-Carlo method for evaluating multi-dimensional integrals. Consider, for example, the evaluation of the area, , enclosed by a curve, . Suppose that the curve lies wholly within some simple domain of area , as illustrated in Fig. 97. Let us generate  points which are randomly distributed throughout . Suppose that  of these points lie within curve . Our estimate for the area enclosed by the curve is simply" the ratio of random points in the space times the size of the space. The link has a nice picture and a description of the inferior midpoint method that I would suggest skipping.


text:
Q: ImportError: No module named 'Crypto.HASH' but pycryto installed I am trying to load pycrypto module. When I do
import Crypto

I get no error but when I do from Crypto.HASH import SHA256 , I am getting ImportError
>>> import Crypto
>>> hash = SHA256.new()
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    hash = SHA256.new()
NameError: name 'SHA256' is not defined
>>> from Crypto.HASH import SHA256
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    from Crypto.HASH import SHA256
ImportError: No module named 'Crypto.HASH'
>>>

OS : Windows 8
Python : 3.5 32 Bit
Thank you.

A: You are misspelling it, the correct module name is Crypto.Hash:
>>> from Crypto.Hash import SHA256
>>> h=SHA256.new()
>>> h.update(b"Hello")
>>> h.hexdigest()
'185f8db32271fe25f561a6fc938b2e264306ec304eda518007d1764826381969'


text:
Q: Выделение поддомена Привет всем!
Нужно выделить поддомен из URL - кто знает как?
Приму как PHP версию, так и htaccess
Есть несколько поддоменов, на них должна стоять одна и таже CMS'ка блога (работающая на xml файлах). Все данные она хранить в папке "content".
Задача: Если домен "1.domain.ru" тогда запрос к данным через /1/content
А если домен "2.domain.ru" тогда запрос к данным через /2/content
Ну это что бы не устанавливать CMS'ку десять раз))
A: $str = $_SERVER['HTTP_HOST'];

$array = explode('.', $str);

$array = array_slice ($array, 0, -2);

$array = array_reverse($array);

var_dump($array);

Дальше парсите адрес.


text:
Q: Login from a site A to a site B? There's one news-portal and its huge (site A). During production backwards, it has been even powered with some sort of a social networking stuff - not yet started, but about to start (soon site B).
Packed together looks great, but in some future there might be a lot of problems with maintaining the database, servers and stuff so I've been asked to separate it as I did. Site A goes on its own domain, site B also - databases are separated.
Now, I need to do the following: when user logs into site B (social site) and arrives to site A (portal) they should be instantly logged in there too (on a site A).
Any ideas how to do this - without duplicating entries to user tables?
EDIT:
Any other ideas instead of auth services? OpenId will just give us one user with 10 accounts, fakes and so on. How about cookie stuff or multi-database queries?
EDIT 2:
Well this is something hot.. unless its not April 1st joke and worth a try:
http://www.shawnhogan.com/2005/12/cross-database-join-with-mysql.html

A: You can use OpenID.
OpenID is an open standard that describes how users can be authenticated in a decentralized manner, eliminating the need for services to provide their own ad hoc systems and allowing users to consolidate their digital identities.
If you want to share some profile information (e.g. posts or photos) without giving access to your login and password you can use OAuth.

A: See if my answer here is of any use.
It's pretty simple, and only requires user information to be kept on one side. Where you need some information on the non-database side, you can just pass that information there using values in a query string, alongside the encrypted string.

A: Can you believe this?
$DB->query("SELECT * FROM table..."); // works of course...

$DB->query("SELECT * FROM another_database.table..."); // WORKS ALSO!

This guy is a miracle:
http://www.shawnhogan.com/2005/12/cross-database-join-with-mysql.html
I don't believe it, so simple at the end!


text:
Q: XMPPHP sends message but won't receive <?php
include("XMPP.php");

$conn = new XMPPHP_XMPP('server.com', 5222, 'user', 'pass', 'home');
$conn->useEncryption(true);
$conn->connect();
$conn->processUntil('session_start');
$conn->message('person@server.com', mktime());
$payloads = $conn->processUntil('message');
$conn->message('person@server.com', mktime());
$conn->disconnect();
?>

Right... so it connects - it starts the session and sends the first timestamp which is received on the jabber client I'm using.
Then its supposed to "processUntil" a message is received (afaik) and if a message is received send another timestamp. Well, this bit is the bit that doesn't work.
I have no prior knowledge of XMPP servers or XMPPHP, so all help, however basic, wouldn't go unappreciated! :)
Thanks.

A: I fought with this for a while. Turns out that you have to announce your presence when you connect. I extracted this from the cli_longrun_example.php and put it after my $conn->connect() and $conn->processUntil('session_start') calls:
$conn->presence($status='Controller available.');

A: you can recive first message in your jabber client.  with
$conn->message('person@server.com', mktime());

but then you are recive message from server with
   $payloads = $conn->processUntil('message');

but you cant recive message with that.
and scrpit cant load haead so you cant receive another message. i have a same problem. you can use jaxl for that.


text:
Q: Play Store: App has been removed for violating Location permission policy Our app has been removed from the play store due to the violation of the location permission policy. According to their rejection mail, we have been using the user's background location but actually, in our app, we only use the user's location only while using the app. We have added these two API permissions(access_coarse_location,access_fine_location) explicitly in our manifest file which is used only for foreground location access. So we have re-submit the app again and again but the app got rejected for the same reason.
Also, we have declared in the location permission policy form that we don't access user location in the background and attached a demo video link as well.
We also made an appeal a few days back but did not get any information on that so far. Our business has been impacted a lot because of this inconvenience.
Details:
Ti SDK: 9.0.3.GA
<uses-sdk android:minSdkVersion="19" android:targetSdkVersion="30"/>

App Manifest:
<uses-permission
    android:name="android.permission.ACCESS_FINE_LOCATION" />

<uses-permission
    android:name="android.permission.INTERNET" />

<uses-permission
    android:name="android.permission.ACCESS_WIFI_STATE" />

<uses-permission
    android:name="android.permission.ACCESS_NETWORK_STATE" />

<uses-permission
    android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<uses-permission
    android:name="android.permission.ACCESS_COARSE_LOCATION" />

Your help will be appreciated!!! Thanks in advance.

A: This kind of issue coming because you are getting user location in background task like async task, handler and others sources. Please get location in foreground. After that resubmit the in play store.


text:
Q: Errors related to discord.embed When I run the .py file, the window turns off immediately.
The error code did not appear at this time.
If I delete the code related to Embed, it will run normally.
I'm not sure what the problem is...
import discord, asyncio, os
from discord.ext import commands

token = "########"

game = discord.Game("&help")
bot =  commands.Bot(command_prefix = '&', status = discord.Status.online, activity = game)

@bot.event
async def on_ready():
    print("hi")

@bot.command()
async def help(ctx):
    embed=discord.Embed(title = "기억력이 나쁜 당신에게,,," , description=f"사용 방법을 알려드립니다.", color = 0x00ff56)
    embed.add_field(name="참가", value="&참가", inline=True)
    embed.add_field(name="멤버 제외", value="&제외", inline=True)
    embed.add_field(name="멤버 추가", value="&추가", inline=True)
    embed.add_field(name="참가자 명단", value="&명단", inline=True)
    embed.add_field(name="명단 초기화", value="&초기화", inline=True)
    embed.add_field(name="인원수 설정", value="&인원.", inline=True)
    embed.add_field(name="팀 생성", value="&생성", inline=True)
    embed.add_field(name="보이스 체널 이동", value="&보이스", inline=True)
    await ctx.send(embed=embed)

bot.run(token)

A: Just try another language than the Korean words, it may be the problem. try the english and see if this is the problem.

A: I solved it like this.
title = ""   ----->   title = f""
value = ""   ----->   value = f""
.
.

but I don't know why this works. :(
If anyone knows why, please let me know


text:
Q: Split By Attributes creates no Shapefiles? I want to create for each polygon of a shapefile a separate shapefile with the Split By Attributes tool.
Input is a polygon shapefile and as split field I choose the ID.
This tool works fine but in the results I cant find any shapefile, only .dbf , .dbf.xml and .cpg.
But why is there no .shp?
As output I tried a workspace and a geodatabase, both didn't worked.

A: Your target workspace appears to be a file geodatabase, which means your output will be feature classes. Open the Target GDB in Catalog/ArcMap and you will see the split attributes as single Feature Classes.
The documentation for the tool states the outputs are either feature classes or tables

http://desktop.arcgis.com/en/arcmap/latest/tools/analysis-toolbox/split-by-attributes.htm
Should you really desire to output Shapefiles, you can add the Feature Class To Shapefile (Conversion) tool to your model.

A: Your problem is that you use a Shapefile as an input.
Although this is a type of feature class, the Split by Attributes tool will treat this as a table. To fix this you will need to make sure that your input is in a geodatabase, either by:

*

*Changing the target destination of the Raster to Polygon tool to a geodatabase

*Adding the Feature Class to Geodatabase tool to your model


text:
Q: What does char '|' mean in Linux command In example:
lsof -i -P -n | grep LISTEN
How do I "read" that command? I have tried to search anywhere, and found nothing explained those.

A: This PIPE operator is very useful where the output of the first command acts as an input to the second command. For example, pipeline the output of ls -l to 'less' and see the output of the command.


text:
Q: c# set focus on multiple child forms I have a main form and then open one childdialog (nr 1) and on that I open an other childdialog (nr 2).
When I then open up that main form from another application the focus is set on the last child (nr 2), when I press enter the focus is set on the main form, I want the focus to go on child nr 1.
To open up the main form I use Activate();
Then in OwnedForms I have an array of children.
Activate();

if(OwnedForms.Any())
{
   OwnedForms.Last().Focus();
}

When I choose to close that form that has focus, the focus will go to the main form instead of the next child (last -1) in the OwnedForms array.
Tried bringtofront and sendtoback without any success.

A: Make sure that the form's parent is set.
OwnedForms.Last().Parent =  this;

Also you may want to look into .Show()  vs .ShowDialog() on the forms.
It seems like you might prefer .ShowDialog() in your case if you are not already doing so.


text:
Q: Find text between 2 strings globally in a file Unix I have multiple .sql files containing DDLs and DMLs.
1) In one set of files there is a DDL (create table ...) followed by a DML(Merge into ....) and then again a DDL (drop table...) as below:
    CREATE TABLE T1 (col1 ...);
    Merge into T2 using T1.....;
    Drop table T1;

2) In the second set, there multiple repitions of the above pattern as:
    CREATE TABLE T1 (col1 ...);
    Merge into T2 using T1.....;
    CREATE TABLE T3 (col1 ...);
    Merge into T4 using T1 and T3.....;
    Drop table T1;
    Drop table T3;

I need to create 2 files from each source file: one with all DDLs and the other with all DMLs. I have tried sed to first search between CREATE and semicolon and direct to a DDL file, then search between Merge and semicolon and direct to DML file and finally search between Drop and semicolon and append to above DDL file.
    sed -n '/CREATE/,/;/p' $SRCFILE > $TGTDDLFILE
    sed -n '/Merge/,/;/p' $SRCFILE > $TGTDMLFILE
    sed -n '/Drop/,/;/p' $SRCFILE >> $TGTDDLFILE

It works for Set 1 but not for set 2. Is there a way I can scale it to apply to every occurence so that it covers Set 2 as well.
If not is there any other way?
Appreciate your help. Thanks

A: You may use something like
    sed -n '/CREATE/p' $SRCFILE > $TGTDDLFILE
    sed -n '/Merge/p' $SRCFILE > $TGTDMLFILE
    sed -n '/Drop/p' $SRCFILE >> $TGTDDLFILE

This will do what you are looking for provided that the files you are referring to have one SQL statement on one line. It will fail both in case of multiple SQL statements on one line and one SQL statement on multiple lines.
If this be the case, you may also use grep.
    cat $SRCFILE | grep 'CREATE' > $TGTDDLFILE
    cat $SRCFILE | grep 'Merge' > $TGTDMLFILE
    cat $SRCFILE | grep 'Drop' >> $TGTDDLFILE

A: One problem in your original sed script is that you told sed to look for a range of lines beginning with, for example, CREATE and ending with ';' - sed doesn't consider a single line a range when you ask it to match, so it doesn't see the ';' when it is on the same line as CREATE.
Try this version and see it works better:
sed -ne 'H;/CREATE/h;/;/{s/.*//;x;/^CREATE/p;}' $SRCFILE > $TGTDDLFILE

The first command (H) puts the current line into the hold space whether we need it or not (this handles lines between CREATE and ';'). If the line contains CREATE, we overwrite the hold space with it so the line there starts with CREATE. Now if the line contains ';' we wipe out the current line and swap it with the hold space. If the hold space contents began with CREATE we print it. There's redundancy that could be cleaned up here, but at the cost of adding more to the script so I didn't bother. Unless you have have huge files it won't matter.


text:
Q: Value of state within React context not updating when used in another component I'm trying to use context in conjunction with state to do role-based routing with React router. Upon clicking sign in, the user data is fetched from the backend API and set as state within the context provider.
The issue is that when I then attempt to use that state in my authorization component that I wrap around my route, the state isn't updated (I presume). What am I missing here?
Codesandbox
The context:
const CurrentUserContext = createContext({});

export const CurrentUserProvider = ({children}) => {
    const [currentUser, setCurrentUser] = useState(null)
    const [currentUserRole, setCurrentUserRole] = useState(null)
    const requestOption = {
        method: 'GET',
        headers: {
            'Accept': 'application/json, text/plain, */*',
            'Content-Type': 'application/json',
            'Authorization': `Token ${localStorage.getItem('token')}`
        }
    }
    const fetchCurrentUser = () => {
        fetch('http://127.0.0.1:8000/api/users-current/', requestOption)
            .then(response => response.json())
            .then(data => {
                console.log('called')
                setCurrentUser(data['user'])
                setCurrentUserRole(data['role'])
            })
            .catch(error => console.log(error))
    }

    return (
        <CurrentUserContext.Provider value={{
            setCurrentUser,
            setCurrentUserRole,
            currentUser,
            currentUserRole,
            fetchCurrentUser
        }}>
            {children}
        </CurrentUserContext.Provider>
    )
}

export const useAuth = () => useContext(CurrentUserContext)

The sign in component where I run fetchCurrentUser on sign in to set the state etc:
export default function SignIn() {

    const { fetchCurrentUser } = useAuth()
    const handleSubmit = (event) => {
        event.preventDefault();
        const data = new FormData(event.currentTarget);
        const credentials = btoa(`${data.get('username')}:${data.get('password')}`);

        const requestOptions = {
            method: "POST",
            credentials: 'include',
            headers: {
                'Accept': 'application/json, text/plain, */*',
                'Content-Type': 'application/json',
                "Authorization": `Basic ${credentials}`
            },
            body: JSON.stringify({})

        }
        fetch('http://127.0.0.1:8000/api/login/', requestOptions)
            .then(response => response.json())
            .then(data => {
                localStorage.setItem('token', data['token'])
                localStorage.setItem('role', data['role'])
            })
            .then(fetchCurrentUser())
            .catch(error => console.log(error))

    }

The component where I'm trying to access the currentUser state:
import { useLocation, Navigate, Outlet } from "react-router";
import { useAuth } from "./CurrentUserContext"

const RequireAuth = () => {

    const { currentUser } = useAuth()
    const location = useLocation()

    return (
        currentUser
        ? <Outlet />
        : <Navigate
                to="/"
                state={{ from: location }}
                replace
            />
    )
}

export default RequireAuth;

And finally my routes:
export default function App() {
    return (
        <CurrentUserProvider>
        <DialogProvider>
            <Router>
                <Routes>
                    <Route element={<RequireAuth/>}>
                        <Route path="roles" element={<DashboardContent role={true}/>}/>
                    </Route>
                    <Route path="/" element={<SignIn/>}/>
                </Routes>
            </Router>
        </DialogProvider>
        </CurrentUserProvider>

If I navigate to roles after signing in I'm just redirected to the sign in page again since currentUser is null.

A: I think this may be a stale enclosure over the requestOption object in the CurrentUser component. The SignIn component only updates the localStorage in the handleSubmit handler before calling fetchCurrentUser which uses the closed over requestOption object that hasn't pulled in the updated token value from localStorage.
Move the options into the fetchCurrentUser callback so they are computed on-demand from the current localStorage value.
export const CurrentUserProvider = ({ children }) => {
  const [currentUser, setCurrentUser] = useState(null);
  const [currentUserRole, setCurrentUserRole] = useState(null);

  const fetchCurrentUser = () => {
    const requestOption = {
      method: 'GET',
      headers: {
        'Accept': 'application/json, text/plain, */*',
        'Content-Type': 'application/json',
        'Authorization': `Token ${localStorage.getItem('token')}`
      }
    };

    fetch('http://127.0.0.1:8000/api/users-current/', requestOption)
      .then(response => response.json())
      .then(data => {
        console.log('called');
        setCurrentUser(data.user);
        setCurrentUserRole(data.role);
      })
      .catch(console.log);
  };

  return (
    <CurrentUserContext.Provider
      value={{
        setCurrentUser,
        setCurrentUserRole,
        currentUser,
        currentUserRole,
        fetchCurrentUser
      }}
    >
      {children}
    </CurrentUserContext.Provider>
  );
};

...
export default function SignIn() {
  const { fetchCurrentUser } = useAuth();

  const handleSubmit = (event) => {
    event.preventDefault();
    const data = new FormData(event.currentTarget);
    const credentials = btoa(`${data.get('username')}:${data.get('password')}`);

    const requestOptions = {
      method: "POST",
      credentials: 'include',
      headers: {
        'Accept': 'application/json, text/plain, */*',
        'Content-Type': 'application/json',
        "Authorization": `Basic ${credentials}`
      },
      body: JSON.stringify({})
    };

    fetch('http://127.0.0.1:8000/api/login/', requestOptions)
      .then(response => response.json())
      .then(data => {
        localStorage.setItem('token', data['token'])
        localStorage.setItem('role', data['role'])
      })
      .then(fetchCurrentUser) // <-- don't immediately invoke!
      .catch(error => console.log(error));
  };

  ...


text:
Q: Can't seem to make a functional THREE.js collada loader I'm having issues getting a custom made collada object with no built in camera or lighting to render. I more or less copied what I had seen in a few collada examples to create my own loader, which looks like this:
var loader = new THREE.ColladaLoader();
var room, scene, stats;
loader.load('../Models/Rooms/boot.dae', function colladaReady( collada ){
    collada.scene.getChildByName('Cube',true).doubleSided = true;
    room = collada.scene;
    room.scale.x = room.scale.y = room.scale.z = 1;
    room.updateMatrix();
    init();
});

The init function is fairly basic and looks like this
scene = new THREE.Scene();
scene.add( room );
scene.add( camera );
renderer.render(scene, camera);

Here is the actual object I'm trying to render. I have also tried it out with the monster.dae file that is in the examples folder without success. The Chrome javascript console isn't showing any errors, so I'm not quite sure where to look in my code. It all resembles functional examples, so I'm not sure why it's not functional. Is there something I'm unaware of that is relevant to collada loading?

A: RESOLVED: The item was rendering, but had no skin or texture associated with it.  So it was rendering at the same colour as the background, which understandably appears to not be rendering at all.  Discovered by adding a grid to the ground just to check.


text:
Q: Matrices help/double checking (with working).
Is my working correct? Do I need to change anything?
a)
r2-r1: 0 -1 0 | 0
2r1+r3 : 0 1 0 | k+2
r2+r3 : 0 0 0 | k+2 so echelon form is
1 0 1 | 1
0 -1 0 | 0
0 0 0 |k+2
b) any value of k ╪ -2, say k=1
c)
k=-2.
The equations reduce to y=0 and x+z=1 which are geometrically
two planes which intersect in a line, so there is a line of solutions.

A: I'd polish it up a bit, but otherwise it looks pretty good.
The matrix is
$$\left[\begin{array}{ccc|c}
1 & 0 & 1 & 1 \\
1 & -1 & 1 & 1 \\
-2 & 1 & -2 & k \\
\end{array}\right]$$
and you've reduced it to row echelon form via:
\begin{align*}
& \rightarrow_{R_2 \gets R_2-R_1}
\left[\begin{array}{ccc|c}
1 & 0 & 1 & 1 \\
0 & -1 & 0 & 0 \\
-2 & 1 & -2 & k
\end{array}\right] \\
& \rightarrow_{R_3 \gets R_3+2R_1}
\left[\begin{array}{ccc|c}
1 & 0 & 1 & 1 \\
0 & -1 & 0 & 0 \\
0 & 1 & 0 & k+2
\end{array}\right] \\
& \rightarrow_{R_3 \gets R_3+R_2}
\left[\begin{array}{ccc|c}
1 & 0 & 1 & 1 \\
0 & -1 & 0 & 0 \\
0 & 0 & 0 & k+2
\end{array}\right]
\end{align*}
This is indeed in row echelon form.
For the latter parts, I'd say something along the lines:

*

*If e.g. $k=1$, then the third equation implies $0=3$, which is inconsistent.  In this case, there are no solutions.

*If $k=-2$, then the corresponding system of equations to the row echelon form is
\begin{align*}
x+z &=1 \\
-y &=0 \\
0 &=0.
\end{align*}
We have a free variable, so we set $z=t$ for some real number $t$.  By back substitution, we find that $y=0$ and $x=-t+1$, and so there is an infinite number of solutions given by $(x,y,z)=(-t+1,0,t)$.


text:
Q: R Shiny observeEvent triggered multiple times I'm trying to implement a Shiny text prediction function based on what user has currently input.  The ideal scenario is suggested words are displayed as buttons and use can click on one of them and the word will appear on the text input area.  However, currently the program seems double triggering the first button so that each time user selects a word, another one (the 1st one) will also pop into the text input area.
library(shiny)

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      textAreaInput("typingArea", NULL)
    ),
    mainPanel(
      uiOutput("UI")
    )
  )
)

server = function(input, output, session){
  wordlist <- data.frame("word"=sample(LETTERS, 5), stringsAsFactors = F)

  Gibberish <- reactive({
    input$typingArea
    return(sample(letters, 5))
  })

  output$UI = renderUI({
    res <- Gibberish()
    obsList <- list()
    lapply(
      1:5,
      function(i) {
        btnID <- paste0("btn", i)
        if (is.null(obsList[[btnID]])) {
          obsList[[btnID]] <<- observeEvent(input[[btnID]], {
            mytext <- paste0(input$typingArea, res[i], " ")
            updateTextAreaInput(session, "typingArea", value=mytext)
          })
        }
        fluidRow(
          actionButton(btnID, res[i]), br(), br()
        )
      }
    )
  })
}

shinyApp(ui,server)

I suspect that is because of the input$typingArea has been called within two different reactive functions.  But I have no idea how to fix this problem.  Appreciate for any suggestion.

A: With the great cost of using globals and repeat code, you can do this way:
library(shiny)
res <<-(sample(letters, 5))
mytext <<- NULL
ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      textAreaInput("typingArea", NULL)
    ),
    mainPanel(

      fluidRow(
        actionButton("btn1", res[1]),
      actionButton("btn2", res[2]),
    actionButton("btn3", res[3]),
  actionButton("btn4", res[4]),
actionButton("btn5", res[5])
      )
    )
  )
)

server = function(input, output, session){
  wordlist <- data.frame("word"=sample(LETTERS, 5), stringsAsFactors = F)

  Gibberish <- reactive({
  input$typingArea
  mytext <<- paste0(mytext,input$typingArea, " ")
  return(sample(letters, 5))

  })
  observeEvent(input$btn1, {
    mytext<<-paste0(mytext,res[1], " ")
    updateTextAreaInput(session, "typingArea", value=mytext)
    res <<-  sample(letters, 5)
    print(res)
  })
  observeEvent(input$btn2, {
       mytext<<-paste0(mytext,res[2], " ")
       updateTextAreaInput(session, "typingArea", value=mytext)
       res<<-  sample(letters, 5)
  })
  observeEvent(input$btn3, {
    mytext<<-paste0(mytext,res[3], " ")
    updateTextAreaInput(session, "typingArea", value=mytext)
    res <<-  sample(letters, 5)
  })
  observeEvent(input$btn4, {
    mytext<<-paste0(mytext,res[4], " ")
    updateTextAreaInput(session, "typingArea", value=mytext)
    res <<-  sample(letters, 5)
  })
  observeEvent(input$btn5, {
    mytext<<-paste0(mytext,res[5], " ")
    updateTextAreaInput(session, "typingArea", value=mytext)
    res <<-  sample(letters, 5)
  })
  observeEvent({input$btn1 },{
  updateActionButton(session,"btn1", res[1])
    updateActionButton(session,"btn2", res[2])
    updateActionButton(session,"btn3", res[3])
    updateActionButton(session,"btn4", res[4])
    updateActionButton(session,"btn5", res[5])

    })
  observeEvent({input$btn2 },{
    updateActionButton(session,"btn1", res[1])
    updateActionButton(session,"btn2", res[2])
    updateActionButton(session,"btn3", res[3])
    updateActionButton(session,"btn4", res[4])
    updateActionButton(session,"btn5", res[5])

  })
  observeEvent({input$btn3 },{
    updateActionButton(session,"btn1", res[1])
    updateActionButton(session,"btn2", res[2])
    updateActionButton(session,"btn3", res[3])
    updateActionButton(session,"btn4", res[4])
    updateActionButton(session,"btn5", res[5])

  })
  observeEvent({input$btn4 },{
    updateActionButton(session,"btn1", res[1])
    updateActionButton(session,"btn2", res[2])
    updateActionButton(session,"btn3", res[3])
    updateActionButton(session,"btn4", res[4])
    updateActionButton(session,"btn5", res[5])

  })
  observeEvent({input$btn5 },{
    updateActionButton(session,"btn1", res[1])
    updateActionButton(session,"btn2", res[2])
    updateActionButton(session,"btn3", res[3])
    updateActionButton(session,"btn4", res[4])
    updateActionButton(session,"btn5", res[5])

  })
}

shinyApp(ui,server)

I agree, it is totally unelegant and dirty, but it is the best thing i have been able to come with.
I hope it helps you!


text:
Q: PHP Uploading Files I'm having a problem uploading files in PHP.  When I submit, $_FILES[] is empty.  I feel like this is such a n00b question :/
My form:
<form method="post" action="uploadfile.php">
<input type="hidden" name="MAX_FILE_SIZE" value="300000" />
Image: <input name="ImageFile" type="file" />

<input type="submit" value="Add Image" />

</form>

Relevant php.ini:

;;;;;;;;;;;;;;;;
; File Uploads ;
;;;;;;;;;;;;;;;;

; Whether to allow HTTP file uploads.
file_uploads = On

; Temporary directory for HTTP uploaded files (will use system default if not
; specified).
upload_tmp_dir = "c:\php5\upload\"

; Maximum allowed size for uploaded files.
upload_max_filesize = 300M

c:\php5\upload\ is writable by IUSR_HOSTNAME
Any thoughts on what else I should check?

A: Make sure your form tag has this attribute: enctype="multipart/form-data"
Without it the files will not get uploaded.


text:
Q: Encountering lag when updating a CardView item in a RecycleView i'm having an issue working with CardViews . I`ve created a CardView containing 1 TextView and 2 ImageViews , which gets displayed in an RecycleView . When i try to update the contents of one of the CardViews (created 5 cards for testing) the interface starts to lag when scrolling over the updated card, but goes back to normal when i pass the item. It only happens when ImageViews are present , when substituting the ImageViews for say, TextViews with some random text in them, it works normally.
Now, here's my code , after that i'll add some more information that could be causing it.
First , the Adapter class, which also contains the items class and List :
public class MovieDetailsAdapter extends RecyclerView.Adapter<MovieDetailsAdapter.MovieViewHolder> {

public List<MovieDetails> movieList;
private static final String TAG = "MyAdapter";

public MovieDetailsAdapter() {

    movieList = new ArrayList< MovieDetails>();
}

public void setItemCount(int count ,String title, Bitmap poster,Bitmap fanart ) {
    movieList.clear();
    movieList.addAll(generateDummyData(count, title, poster , fanart));

    notifyDataSetChanged();
}

@Override
public int getItemCount() {

    return movieList.size();
}

public void addItem(int position,String title, Bitmap poster, Bitmap fanart) {
   if (position > movieList.size()) return;

    movieList.add(position, generateDummyItem(title, poster, fanart));
   // notifyDataSetChanged();
    notifyItemInserted(position);
}

public void updateItem(int position, String title, Bitmap poster, Bitmap fanart) {
    if (position > movieList.size()) return;

    movieList.add(position, generateDummyItem(title, poster, fanart));
     notifyItemChanged(position);
  //  notifyDataSetChanged();
}

@Override
public MovieViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    View itemView = LayoutInflater.
            from(viewGroup.getContext()).
            inflate(R.layout.card_layout_movies, viewGroup, false);
    Log.d(TAG, "create header view holder");
    return new MovieViewHolder(itemView);
}

@Override
public void onBindViewHolder(MovieViewHolder movieViewHolder, int i) {

    Log.d(TAG, "bind header view holder");
    MovieDetails mdet = movieList.get(i);

    movieViewHolder.vTitle.setText(mdet.Title);
    movieViewHolder.vPoster.setImageBitmap(mdet.imageViewPoster);
    movieViewHolder.vFanart.setImageBitmap(mdet.imageViewFanart);

    Log.d(TAG, "position: " + i + " holder: " + movieViewHolder + " text: " + movieViewHolder.vTitle);

}

public static class MovieViewHolder extends RecyclerView.ViewHolder {

    protected TextView vTitle;
    protected ImageView vPoster;
    protected ImageView vFanart;

    public MovieViewHolder(View v)
    {
        super(v);
        vTitle  = (TextView)  v.findViewById(R.id.title);
        vPoster = (ImageView) v.findViewById(R.id.imageViewPoster);
        vFanart = (ImageView) v.findViewById(R.id.imageViewFanart);

    }

}

public static class MovieDetails {

    protected String title;
    protected Bitmap imageViewPoster;
    protected Bitmap imageViewFanart;

    public MovieDetails(String title, Bitmap imageViewPoster,Bitmap imageViewFanart )
    {
        this.title = title;
        this.imageViewPoster = imageViewPoster;
        this.imageViewFanart = imageViewFanart;
    }
}

public static MovieDetails generateDummyItem(String title, Bitmap poster, Bitmap fanart) {

    MovieDetails mov = new MovieDetails(title, poster, fanart);
    return  mov;
}

public static List< MovieDetailsAdapter.MovieDetails> generateDummyData(int count, String title , Bitmap imageViewPoster, Bitmap imageviewFanart) {

    ArrayList<MovieDetailsAdapter.MovieDetails> items = new ArrayList<MovieDetailsAdapter.MovieDetails>();

    for (int i=0; i < count; i++) {

        items.add(new MovieDetailsAdapter.MovieDetails(title, imageViewPoster, imageviewFanart));
    }

    return items;
}

}
Now, here is my main class , the activity class
public class MoviesListActivity extends AppCompatActivity {

public MovieDetailsAdapter ca = new MovieDetailsAdapter();
public RecyclerView recList;
private Button button;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_movies_list);
    RecyclerView recList = (RecyclerView) findViewById(R.id.cardList);

    LinearLayoutManager llm = new LinearLayoutManager(this);
    llm.setOrientation(LinearLayoutManager.VERTICAL);
    recList.setLayoutManager(llm);
    button = (Button) findViewById(R.id.button);
    MyOnClickListener Listener = new MyOnClickListener();
    button.setOnClickListener(Listener);

    recList.setItemAnimator(null);

    Bitmap bittest1 = decodeSampledBitmapFromResource(getResources(), R.drawable.poster_example, 640, 955);
    Bitmap bittest2 = decodeSampledBitmapFromResource(getResources(), R.drawable.fanart_example, 800, 450);

    ca.setItemCount(5, "TestingTitle", bittest1, bittest2);
    recList.setAdapter(ca);
}

public class MyOnClickListener implements View.OnClickListener {

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button:

                Bitmap bittest12 = decodeSampledBitmapFromResource(getResources(), R.drawable.poster2, 640, 955);
                Bitmap bittest22 = decodeSampledBitmapFromResource(getResources(), R.drawable.fanart2, 800, 450);

                Toast.makeText(getApplicationContext(), "msg msg", Toast.LENGTH_SHORT).show();

                ca.updateItem(1, "test", bittest12, bittest22);
               // ca.addItem(1,"test",bittest12,bittest22);
                break;
            default:
                break;
        }
    }
}

//------methods used for resizing the images down to smaller ones before loading into memory---//

public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
                                                        int reqWidth, int reqHeight) {

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(res, resId, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(res, resId, options);
}

public static int calculateInSampleSize(
        BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

        final int halfHeight = height / 2;
        final int halfWidth = width / 2;

        // Calculate the largest inSampleSize value that is a power of 2 and keeps both
        // height and width larger than the requested height and width.
        while ((halfHeight / inSampleSize) > reqHeight
                && (halfWidth / inSampleSize) > reqWidth) {
            inSampleSize *= 2;
        }
    }

    return inSampleSize;
  }

And finally, not that i probably matters, my CardView XML.
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/card_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
card_view:cardCornerRadius="4dp"
android:layout_margin="5dp">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/title"
        android:layout_width="match_parent"
        android:layout_height="20dp"
        android:background="@color/bkg_card"
        android:text="Movie Title"
        android:gravity="center_vertical"
        android:textColor="@android:color/white"
        android:textSize="14dp"/>

    <ImageView
        android:elevation="5dp"
        android:scaleType="fitCenter"
        android:layout_width="100dp"
        android:layout_height="150dp"
        android:id="@+id/imageViewPoster"
        android:text="Poster"
        android:gravity="center_vertical"
        android:layout_below="@id/title"
        android:layout_marginTop="10dp"
        android:layout_marginLeft="5dp"/>

    <ImageView
        android:id="@+id/imageViewFanart"
        android:scaleType="fitCenter"
        android:layout_alignBottom="@+id/imageViewPoster"
        android:layout_toEndOf="@+id/imageViewPoster"
        android:layout_width= "235dp"
        android:layout_height="122dp"
        android:layout_marginRight="5dp"/>

</RelativeLayout>

Now , somebody in another discussion showed me this as a possible cause : Why RecyclerView.notifyItemChanged() will create a new ViewHolder and use both the old ViewHolder and new one?
So i added the Log items inside the onBind and onCreate methods of the Adapter to see if that could be causing it, and indeed, it`s not just creatind one additional ViewHolders, but 3 of them, and each time i scroll over the newly updated card, it seems to be re-binding, the onBind method seems to be called each time.
Setting the animation to 'null' as per the solution in the thread doesn't seem to have any effect in my case, so maybe that`s not what is causing it.
Any ideas ?

A: Well, i solved it. It seems to happen only when i'm loading the images via the XML method, if i load them with a 3rd party library like Picasso, the lag seems to dissapear. Something like :
Picasso.with(context).load(MovieDetails.getPoster())
            .error(R.drawable.placeholder)
            .placeholder(R.drawable.placeholder)
            .into(movieViewHolder.imageViewPoster);

inside the onBindViewHolder
and instead of passing around bitmaps, just pass a String for the URL or location of the image. And pass the Context to the Adapter class.


text:
Q: Let m be any positive integer and let k be an even integer. Show that there exist a, b ∈ Z with k = a − b and gcd(a, m) = gcd(b, m) = 1. Let m be any positive integer and let k be an even integer. Show that there exist a, b ∈ Z with k = a − b and gcd(a, m) = gcd(b, m) = 1.
This problem seems simple but is quite difficult to approach. I tried the Chinese remainder theorem but failed. I want to ask for a proof for this question. Thanks!

A: Suppose the prime factorization of $m$ are $ \prod_{i=1}^u P_i^{m_{P_i}} \prod_{j=1}^v Q_j^{m_{Q_j}}$ and prime factorization of $k$ are $\prod_{i=1}^u P_i^{k_{P_i}} \prod_{j=1}^w R_j^{k_{R_j}}$. For each $j$, there exists $S_j$ such that $\prod_{i=1}^u P_i^{k_{P_i}} +S_j \not\equiv 0 (\bmod Q_j)$ and $S_j \not\equiv 0 (\bmod Q_j)$, since $Q_j \neq 2$. By Chinese remainder theorem, there exists $S \in \mathbb{Z}$ such that $\prod_{i=1}^u P_i^{k_{P_i}} +S \not\equiv 0 (\bmod Q_j)$ and $S \not\equiv 0 (\bmod Q_j)$. We can also assume $S$ relatively prime to all $P_i$, else we can replace $S$ by $S+ \prod Q_j$. Finally, we can pick $b=\prod_{j=1}^w R_j^{k_{R_j}}S$. Now, it is clear from the construction that $\gcd(b,m)$=1. It is also not hard to show that for $a=k+b$, we have $\gcd(a,m)=1$.
PS: Case $\prod_{j=1}^v Q_j^{m_{Q_j}}=1$ you can pick $b=1$.


text:
Q: drag and drop div onto div I am not sure how to ask this question, but I'll try my best.
I am coding a website, and I have a list of div's that are generated with php. There is another div on the side. The idea is, when you drag one of the divs in the list onto the other div, it will do something with the class of the div in the list.
The HTML code for one of the divs in the list:

[content]

The HTML code for the div you drop it into:

[content]

The idea is, when you drag "div1" into "dropzone", dropzone will run a javascript function with "div1" as a variable.
Is there a way to do this in javascript?
Thanks!

A: You can get idea from this site :

http://www.html5rocks.com/en/tutorials/dnd/basics/
http://www.w3schools.com/html/html5_draganddrop.asp


text:
Q: Elastic collisions inside a moving fence A square, rigid fence of mass $M$ moves on a horizontal, frictionless plane. Inside it a point mass $m$ moves freely without friction. Assume the fence has initial velocity $0$ and that the particle has initial velocity $v_0$ forming an angle $\theta$ with one of the fence's sides. Determine the particle's trajectory if all collisions are perfectly elastic.
Notes: it is assumed that the fence cannot deform but can rotate.
There is no gravity.
It seems as if the solution involves writing down conservation of momentum on both axes, conservation of energy and conservation of angular momentum in the centre of mass frame, analysing the differences in the system's state before and after an individual collision, and remarking that the motion is periodical in the centre of mass frame. After trying this multiple times, most recently this morning, I have not one more clue about this problem than I had when starting.
Anything is appreciated.


text:
Q: reasons for laptop shutting down I have a laptop running Arch that I've been using for about 3 years now. Admittedly, I'm a bit sloppy on system updates, but it's in great shape aside from a few quirks with the graphics driver. This changed overnight yesterday.
Somehow, the laptop shuts down spontaneously in very short intervals, to the point where it's extremely hard to even diagnose what's going on (typically, after startup, I have 1-2 minutes to do something until it decides to shut down). The shutdown is "orderly" in the sense that it doesn't just turn black, but instead I see the shutdown log. Upon next boot, I see some checks being run because the file system was not unmounted properly, but other than that, I see no indication of anything being wrong - very similar to when the laptop shuts down because of critically low battery, only that here, it happens irrespective of whether it's on battery power or on AC.
I've asked friend google, and it seems that most of the time something like this happens, it's related to overheating. Hence, I've looked at the temperature sensors and found that immediately before the shutdown, none of the temperatures was even above 50C, which makes it seem very unlikely to me that this is the issue.
I'm at a loss - what are possible causes for this behavior, and how can I fix it?
There was nothing specifically I did with the system before it started, no full system update, installation of new hardware or physical accident. The most recent to changes I can remember performing was updating a few userspace apps (discord, skype, chrome) and swapping between the two batteries I have for this laptop a few times, but none of this should in any way be related to this behavior.
Usually, I would now start reading up on the internet, but since most of the search results are related to overheating (which doesn't seem to be the problem in my case) and I don't really have enough time with the machine running to sensibly debug and test hypotheses of my own, I'm coming here for guidance and suggestions on what to check.
Any ideas, suggestions and checks to run are highly appreciated.

A: Ultimately, I was able to find the reason. A single hair of mine made its way into the CPU fan. Removing it from there solved the issue once and for all.


text:
Q: How to get the data from a Mat angular dialog in other component? SO I have a component: DetailComponent:
export class DetailComponent implements OnInit  {

  @Input() participant: ParticipantInfoDTO;

  constructor(private dialog: MatDialog, route: ActivatedRoute) {
    this.participant = route.snapshot.data['participant'];
  }

  ngOnInit() {}

  openEcheqSelectorDialog() {
    this.dialog.open(EcheqSelectorComponent, {
      width: '600px',
      maxHeight: 'calc(100vh - 2em)',
      data: {
        participant: console.log('participantIDTest', this.participant)
      }
    });
  }
}

And the data from : this.participant is like this:
{participantId: "ac3d1836-2e36-4947-a62f-04cd00425bcc", email: "k@endrix.org", gender: "Male", fullName: "k kaas", firstName: "k", …}

So I get the correct data back.
But now I want also receive the same data in other component. The other component looks like this:

export class EcheqSelectorComponent implements OnInit, OnDestroy {
  private subscriptions = new Subscription();
  echeqs: EcheqFamilyInfo[] = [];
  allEcheqs: EcheqFamilyInfo[] = [];
  echeqFamily: EcheqFamilyInfo;
  searchInput = '';
  filtering = false;
  participantInfo: ParticipantInfoDTO;
  echeqsToSend: EcheqFamilyInfo[] = [];
  echeqSubmissionBatchDTO: EcheqSubmissionBatchDTO;
  participantIds$: Observable<string[]>;
  patientId: string;

  public participantIds: string[] = [];

  constructor(
    private apiService: EcheqDefinitionService,
    private dialog: MatDialogRef<EcheqSelectorComponent>,
    public selectedParticipantService: SelectedParticipantsService,
    private submissionService: EcheqSubmissionMedicalService,
    private snackBar: MatSnackBar,
    @Inject(MAT_DIALOG_DATA) data: any
  ) {

  }

  ngOnInit() {
    this.subscriptions.add(
      this.apiService.listEcheqFamilies().subscribe(families => {
        this.echeqs = families;
        this.allEcheqs = families;
      })
    );

    this.subscriptions.add(
      this.selectedParticipantService.getParticipantIds
        .pipe(tap(participantIds => console.log('Participants', participantIds)))
        .subscribe()
    );

      console.log('participantId',   this.participantInfo.participantId);
  }
}

But if I do this:
  console.log('participantId',   this.participantInfo.participantId);

Then I will receive this error:
EcheqSelectorComponent_Host.ngfactory.js? [sm]:1 ERROR TypeError: Cannot read property 'participantId' of undefined
    at EcheqSelectorComponent.push../src/app/participant/modules/echeq/components/echeq-selector/echeq-selector.component.ts.EcheqSelectorComponent.ngOnInit (echeq-selector.component.ts:62)
    at checkAndUpdateDirectiveInline (core.js:18620)
    at checkAndUpdateNodeInline (core.js:19884)
    at checkAndUpdateNode (core.js:19846)
    at debugCheckAndUpdateNode (core.js:20480)
    at debugCheckDirectivesFn (core.js:20440)
    at Object.eval [as updateDirectives] (EcheqSelectorComponent_Host.ngfactory.js? [sm]:1)
    at Object.debugUpdateDirectives [as updateDirectives] (core.js:20432)
    at checkAndUpdateView (core.js:19828)
    at callViewAction (core.js:20069)

So what I have to change to receive the correct data?
Thank you
If I do this:
 public participantIds: string[] = [];

  constructor(
    private apiService: EcheqDefinitionService,
    private dialog: MatDialogRef<EcheqSelectorComponent>,
    public selectedParticipantService: SelectedParticipantsService,
    private submissionService: EcheqSubmissionMedicalService,
    private snackBar: MatSnackBar,
    @Inject(MAT_DIALOG_DATA) public data: any, public dialogRef:MatDialogRef<EcheqSelectorComponent>
  )
  {
    this.participantInfo = data.participant;
  }

  ngOnInit() {
    this.subscriptions.add(
      this.apiService.listEcheqFamilies().subscribe(families => {
        this.echeqs = families;
        this.allEcheqs = families;
      })
    );

    this.subscriptions.add(
      this.selectedParticipantService.getParticipantIds
        .pipe(tap(participantIds => console.log(' selected Participants', participantIds)))
        .subscribe()
    );

      console.log('participantId', this.dialogRef.id);
  }

But how to get the
{participantId: "0bde3c11-50a2-4e4e-a9e3-08d6cccff86a"}

So the participantId?
Thank you

A: Here is an example of how you can receive data back from a dialog
async deleteRequest(id) {
const dialogRef = this.dialog.open(ConfirmationComponent, {
  width: '250px',
  data: 'Are you sure you want to delete this request?'
});
 dialogRef.afterClosed().subscribe(async result => {
  if (result == "yes") {
   console.log('yes');
  }
  else{
   console.llog('No');
  }
});

On your dialog
export class ConfirmationComponent implements OnInit {

constructor(@Inject(MAT_DIALOG_DATA) public data: any, public dialogRef:
MatDialogRef<ConfirmationComponent>) { }

onNoClick() {
this.dialogRef.close('no');
}

onYesClick() {
this.dialogRef.close('yes');
}

ngOnInit() {
}

}

you can return data as per your requirement and send it to other.


text:
Q: IE8 absolute positioned elements within button element are wrong Title says it all: absolute positioned children of a button element are wrong in IE8
Here's a fiddle
And here's the mandatory piece of code:
<button>

</button>

I've searched and tried everything I could think of. Maybe I should abandon using the button element :-/
What's going on here?

A: You need to add an overflow:visible to the button css.
Here is a fiddle https://jsfiddle.net/innerurge1/os2e9c2j/7/. Also you should swap out the divs with spans as this is more semantic. Divs are not "allowed" in buttons, because they are block elements and buttons are inline.
.parent{
    position: relative;
    width: 200px;
    height: 200px;
    border: 0;
    background: gray;
    text-align : left;
    overflow:visible;
}


text:
Q: Inserting 'Log a Call' task using REST API I am currently trying to insert a new 'Log a Call' task for accounts / contacts using the REST API.
I have the information I require from the calls in an SQL database table including the accountId/contactId.
There are approximately 100 calls per day which I need to add every 30 minutes (20 at a time max).
I would prefer to add these via the REST API for ease of use (it fits alongside a current REST API implementation).
If I iterate over the records, is it possible to do the insert in this fashion?

A: Yes, you can use the REST API to insert tasks for account.  The REST api only supports actions on individual records, if you want to use one call for multiple records you'll need to use the BULK API.  Whether being inefficient and doing one call per record matters has to do with how many API calls your organizations has available.  Large organizations with unlimited edition rarely have issues, but smaller organizations can hit the 1K/day/user limit (assuming enterprise license) much quicker.
As @theGreatDanton points out.  You also have the option of creating your own REST webservice which you can build out your logic to insert multiple records in one call.


text:
Q: PostgreSQL 9.5.2 - Building a JSON object/String - Multiple 1:many relationships I am playing with PostgreSQL building JSON objects/strings for a project.
I am new with the syntax and am looking for "best practices" in doing this.
Imagine the following tables (ignoring the design)
CREATE TABLE object (
    item_id INT
    ,name VARCHAR(64)
    ,category_id INT
)
CREATE TABLE object_features (
    item_id INT
    ,feature_1 VARCHAR(64)
    ,val_1 FLOAT
    ,feature_2 VARCHAR(64)
    ,val_2 FLOAT
    ,feature_3 VARCHAR(64)
    ,val_3 FLOAT
    ,feature_n VARCHAR(64)
    ,val_n FLOAT
)
CREATE TABLE category (
    id INT
    ,name VARCHAR(64)
)
CREATE TABLE comment (
    object_id  INT
    ,name VARCHAR(64)
    ,date DATETIME
    ,score INT
)

How would you create the following JSON (or at least as close as possible)?
[{
    "item_id": 1234,
    "category": "category 1",
    "name": "xyz",
    "features": [{
        "feature_1": "val_1",
        "highlight": "Y"
    }, {
        "feature_4": "val_2",
        "highlight": "Y"
    }, {
        "feature_3": "val_3",
        "highlight": "N"
    }, {
        "feature_n": "val_n",
        "highlight": "Y"
    }],
    "comments": [{
        "name": "larry",
        "date": "2016-04-01",
        "score": 1
    }, {
        "name": "harry",
        "date": "2016-03-01",
        "score": 5
    }]
}, {
    "item_id": 434,
    "category": "category 2",
    "name": "dda",
    "features": [{
        "feature_1": "val_1",
        "highlight": "N"
    }, {
        "feature_4": "val_2",
        "highlight": "N"
    }, {
        "feature_3": "val_3",
        "highlight": "N"
    }, {
        "feature_n": "val_n",
        "highlight": "N"
    }],
    "comments": [{
        "name": "merry",
        "date": "2016-04-01",
        "score": 1
    }]
}]

Regards,
G