问:
since redis is single-threaded, then our concurrent requests become serialized requests when accessing redis. What is the significance of using redis?
We usually use redis for caching in the Spring‘s project. My problem is that since redis is single-threaded, then our concurrent requests become serialized requests when accessing redis. then,what is the significance of using redis?

Is it only because of "It's not very frequent that CPU becomes your bottleneck with Redis, as usually Redis is either memory or network bound.
......
using pipelining Redis running on an average Linux system can deliver even 1 million requests per second......
"?

I am learning redis， Redis document FAQ

答:
You've basically asked two questions in one question:

What is the significance of using Redis.

Well, Redis is known to be fast because it keeps the data in memory. If you ask whether being a single-threaded application is very restrictive - well, its a product, that works like this by design, maybe it could be even more performant if it was multithreaded, it depends on actual implementation under the hood after all.

In any case, it offers much more than just a "get data in memory":
 - Many primitives to work with
 - Configurable persistence
 - Replication of data
And much more

If the question is whether the in-memory cache will be faster (you've mentioned Spring framework, so you're at Java Land) - then yes.

In fact, Spring Cache support Guava Cache (spring 5/spring boot 2 use Caffeine for the same purpose instead) - and yes it will be faster in a head-to-head comparison with Redis. But what if you have a distributed application with many instances and one instance calculated something and put it to cache, how do you get the same information from another instance without distributing the information between the instances. Well, there are tools like Hazelcast but it's out of scope for this question, the point is that when the application is beyond basic, the tasks like cache synchronization /keeping it up-to-date becomes much less obvious.

If you can deliver 1 million operations per second.

Now this question is too vague to answer:

What is the hardware that runs Redis?

What are the network configurations? (after all Redis calls are done over the network)

How often do you persist on disk (Redis has configurations for that)

Do you use replication and split the load between many Redis servers reaching an overall much faster throughput?

What commands exactly are being running under that hood?

In any case, when it comes to benchmarking you can set up your system in the option way and use the tool offered by Redis itself:

Redis Benchmarking Chapter in Redis tutorial

The tool is called redis-benchmark you can run it with various parameters and see how fast redis really is:

Here is an example (I encourage you to read the full article in the link):

```<code>$ redis-benchmark -t set,lpush -n 100000 -q
  SET: 74239.05 requests per second
  LPUSH: 79239.30 requests per second
</code>```

This says: Connect to redis server available on localhost, run (-n) 100000 requests in a quiet mode (-q parameter) and run only tests specific for two commands: set and lpush

Body:
You've basically asked two questions in one question:

What is the significance of using Redis.

Well, Redis is known to be fast because it keeps the data in memory. If you ask whether being a single-threaded application is very restrictive - well, its a product, that works like this by design, maybe it could be even more performant if it was multithreaded, it depends on actual implementation under the hood after all.

In any case, it offers much more than just a "get data in memory":
 - Many primitives to work with
 - Configurable persistence
 - Replication of data
And much more

If the question is whether the in-memory cache will be faster (you've mentioned Spring framework, so you're at Java Land) - then yes.

In fact, Spring Cache support Guava Cache (spring 5/spring boot 2 use Caffeine for the same purpose instead) - and yes it will be faster in a head-to-head comparison with Redis. But what if you have a distributed application with many instances and one instance calculated something and put it to cache, how do you get the same information from another instance without distributing the information between the instances. Well, there are tools like Hazelcast but it's out of scope for this question, the point is that when the application is beyond basic, the tasks like cache synchronization /keeping it up-to-date becomes much less obvious.

If you can deliver 1 million operations per second.

Now this question is too vague to answer:

What is the hardware that runs Redis?

What are the network configurations? (after all Redis calls are done over the network)

How often do you persist on disk (Redis has configurations for that)

Do you use replication and split the load between many Redis servers reaching an overall much faster throughput?

What commands exactly are being running under that hood?

In any case, when it comes to benchmarking you can set up your system in the option way and use the tool offered by Redis itself:

Redis Benchmarking Chapter in Redis tutorial

The tool is called redis-benchmark you can run it with various parameters and see how fast redis really is:

Here is an example (I encourage you to read the full article in the link):

$ redis-benchmark -t set,lpush -n 100000 -q
  SET: 74239.05 requests per second
  LPUSH: 79239.30 requests per second

This says: Connect to redis server available on localhost, run (-n) 100000 requests in a quiet mode (-q parameter) and run only tests specific for two commands: set and lpush


来源: stackexchange

问:
Using turtle's onclick in a loop
I'm trying to create a simple interface from a dict of strings inside a function. Each string is used to display text, and a clickable turtle (using onclick() to make the turtle clickable). This is so I can click on the turtle, and input some values.

But, if I understand it right, when the function finishes running the loop through the dictionary, all the varibles that the loop was supposed to define are redefined as the last one that passed trough the loop, the last element of the dictionary. So the onclick() function returns me only the last element of the dictionary.

Is there a way I could make one onclick() function react/correspond diferently to each element of the dictionary?  I really don't want to write a bunch of onclick() functions for every element of the dictionary.  I'm trying to learn a better way.

```<code>list_alunos={'joao': ['5', 'm'],'maria': ['5', 'm'],'lobo': ['5', 'm'],'mau': ['5', 'm']}
def caca(dictx,file):
    import turtle
    mes=file
    vert=350
    hor=-600

    def got(t,x,y,d) :
        t.penup()
        t.goto(x,y)
        t.pendown()
        t.seth(d)

    def text(t,text, size, color, pos1, pos2):
        t.penup()
        t.goto(pos1, pos2)
        t.color(color)
        t.begin_fill()
        t.write(text, font=('Arial', size, 'normal'))
        t.end_fill()

    new_vert = vert
    for key in dictx:
        nome = key
        if vert == -340:
            new_vert = 350
            new_hor = hor + 250
        if vert!= -340:
            new_vert= new_vert-30
            new_hor = hor
            txt_vert = new_vert - 15
            txt_hor = new_hor + 20

        screen = turtle.Screen()

        width = 1200
        height = 1500
        turtle.screensize(width, height)

        tnome = turtle.Turtle(shape='turtle')
        tnome.color('pink')
        textnome = turtle
        tnome.speed('fastest')
        textnome.speed('fastest')

        text(textnome, '%s' %(nome), '20', 'pink', txt_hor,txt_vert)

        got(tnome,new_hor,new_vert,0)
        def tnome_handler(x, y):

            pos = list(dictx.keys()).index(nome)
            listt = list(dictx)

            pnt = screen.textinput(' pontuação', '%s:  '%(listt[pos]))
            pnt = [int(x) for x in pnt.split()]
            if len(pnt) == 5 :
                with open('%s.py' %(mes), 'a') as fd:
                    fd.write('\n%s.pontuacao(%i,%i,%i,%i,%i)' % (nome,pnt[0],pnt[1],pnt[2],pnt[3],pnt[4]))
                tnome.color('blue')
        tnome.onclick(tnome_handler)

caca(list_alunos,'mm')
</code>```

答:
I belive the following rework of your code does what you desire.  It effectively generates a custom handler for each turtle/button that responds uniquely to it:

```<code>from turtle import Screen, Turtle

WIDTH, HEIGHT = 1200, 1500

dict_alunos = {'joao': ['5', 'm'], 'maria': ['5', 'm'], 'lobo': ['5', 'm'], 'mau': ['5', 'm']}

def text(t, text, size, color, x, y):
    t.penup()
    t.goto(x + size, y - size/2)
    t.color(color)
    t.write(text, align='left', font=('Arial', str(size), 'normal'))
    t.goto(x, y)

def caca(dictionary, mes):

    def tnome_handler(nome, turtle, x, y):

        pnt = screen.textinput('pontuação', '%s:  ' % (nome))
        pnt = [int(x) for x in pnt.split()]

        if len(pnt) == 5:
            with open('%s.py' % (mes), 'a') as fd:
                fd.write('s.pontuacao(%i, %i, %i, %i, %i)\n' % (nome, pnt[0], pnt[1], pnt[2], pnt[3], pnt[4]))

        turtle.color('blue')

    vert = 350
    hor = -600

    new_vert = vert

    for nome in dictionary:

        if vert == -340:
            new_vert = 350
            new_hor = hor + 250

        if vert != -340:
            new_vert = new_vert - 30
            new_hor = hor
            txt_vert = new_vert - 15
            txt_hor = new_hor + 20

        turtle = Turtle(shape='turtle')
        turtle.color('pink')
        turtle.speed('fastest')
        turtle.setheading(0)

        text(turtle, '%s' % (nome), 20, 'pink', txt_hor, txt_vert)

        turtle.onclick(lambda x, y, n=nome, t=turtle: tnome_handler(n, t, x, y))

screen = Screen()
screen.setup(WIDTH, HEIGHT)

caca(dict_alunos, 'mm')

screen.mainloop()
</code>```

I've also reworked the code to fit a more common programming design.

ContentLicense: CC BY-SA 4.0

Title: Using turtle's onclick in a loop

Body:
I'm trying to create a simple interface from a dict of strings inside a function. Each string is used to display text, and a clickable turtle (using onclick() to make the turtle clickable). This is so I can click on the turtle, and input some values.

But, if I understand it right, when the function finishes running the loop through the dictionary, all the varibles that the loop was supposed to define are redefined as the last one that passed trough the loop, the last element of the dictionary. So the onclick() function returns me only the last element of the dictionary.

Is there a way I could make one onclick() function react/correspond diferently to each element of the dictionary?  I really don't want to write a bunch of onclick() functions for every element of the dictionary.  I'm trying to learn a better way.

list_alunos={'joao': ['5', 'm'],'maria': ['5', 'm'],'lobo': ['5', 'm'],'mau': ['5', 'm']}
def caca(dictx,file):
    import turtle
    mes=file
    vert=350
    hor=-600

    def got(t,x,y,d) :
        t.penup()
        t.goto(x,y)
        t.pendown()
        t.seth(d)

    def text(t,text, size, color, pos1, pos2):
        t.penup()
        t.goto(pos1, pos2)
        t.color(color)
        t.begin_fill()
        t.write(text, font=('Arial', size, 'normal'))
        t.end_fill()

    new_vert = vert
    for key in dictx:
        nome = key
        if vert == -340:
            new_vert = 350
            new_hor = hor + 250
        if vert!= -340:
            new_vert= new_vert-30
            new_hor = hor
            txt_vert = new_vert - 15
            txt_hor = new_hor + 20

        screen = turtle.Screen()

        width = 1200
        height = 1500
        turtle.screensize(width, height)

        tnome = turtle.Turtle(shape='turtle')
        tnome.color('pink')
        textnome = turtle
        tnome.speed('fastest')
        textnome.speed('fastest')

        text(textnome, '%s' %(nome), '20', 'pink', txt_hor,txt_vert)

        got(tnome,new_hor,new_vert,0)
        def tnome_handler(x, y):

            pos = list(dictx.keys()).index(nome)
            listt = list(dictx)

            pnt = screen.textinput(' pontuação', '%s:  '%(listt[pos]))
            pnt = [int(x) for x in pnt.split()]
            if len(pnt) == 5 :
                with open('%s.py' %(mes), 'a') as fd:
                    fd.write('\n%s.pontuacao(%i,%i,%i,%i,%i)' % (nome,pnt[0],pnt[1],pnt[2],pnt[3],pnt[4]))
                tnome.color('blue')
        tnome.onclick(tnome_handler)

caca(list_alunos,'mm')

Body:
I belive the following rework of your code does what you desire.  It effectively generates a custom handler for each turtle/button that responds uniquely to it:

from turtle import Screen, Turtle

WIDTH, HEIGHT = 1200, 1500

dict_alunos = {'joao': ['5', 'm'], 'maria': ['5', 'm'], 'lobo': ['5', 'm'], 'mau': ['5', 'm']}

def text(t, text, size, color, x, y):
    t.penup()
    t.goto(x + size, y - size/2)
    t.color(color)
    t.write(text, align='left', font=('Arial', str(size), 'normal'))
    t.goto(x, y)

def caca(dictionary, mes):

    def tnome_handler(nome, turtle, x, y):

        pnt = screen.textinput('pontuação', '%s:  ' % (nome))
        pnt = [int(x) for x in pnt.split()]

        if len(pnt) == 5:
            with open('%s.py' % (mes), 'a') as fd:
                fd.write('s.pontuacao(%i, %i, %i, %i, %i)\n' % (nome, pnt[0], pnt[1], pnt[2], pnt[3], pnt[4]))

        turtle.color('blue')

    vert = 350
    hor = -600

    new_vert = vert

    for nome in dictionary:

        if vert == -340:
            new_vert = 350
            new_hor = hor + 250

        if vert != -340:
            new_vert = new_vert - 30
            new_hor = hor
            txt_vert = new_vert - 15
            txt_hor = new_hor + 20

        turtle = Turtle(shape='turtle')
        turtle.color('pink')
        turtle.speed('fastest')
        turtle.setheading(0)

        text(turtle, '%s' % (nome), 20, 'pink', txt_hor, txt_vert)

        turtle.onclick(lambda x, y, n=nome, t=turtle: tnome_handler(n, t, x, y))

screen = Screen()
screen.setup(WIDTH, HEIGHT)

caca(dict_alunos, 'mm')

screen.mainloop()

I've also reworked the code to fit a more common programming design.


问:
dotnet core-Logging in class library
is it possible to use Microsoft.Extensions.Logging like use logging in controllers(put in constructor and framework handle it with DI), in class library which my ASP.NET Core web application use that library? and how instantiate class and use method?</p>

```<code>public class MyMathCalculator
{
    private readonly ILogger<MyMathCalculator> logger;

    public MyMathCalculator(ILogger<MyMathCalculator> logger)
    {
        this.logger = logger;
    }

    public int Fact(int n)
    {
        //logger.LogInformation($"Fact({n}) called.");
        if (n == 0)
        {
            return 1;
        }
        return Fact(n - 1) * n;
    }
}
</code>```

答:
Taked from a previous answer:

...That is the magic of dependency injection, just let the system create the object for you, you just have to ask for the type.

This is also a big topic, ... basically, all you have to do is to define classes as dependencies, so, when you ask for one, the system itself check the dependencies, and the dependencies of that objects, until resolves all the tree of dependencies.

With this, if you need one more dependency latter in your class, you can add directly but you do not need to modify all the classes that uses that class.

To use this in the controller, please check the official docs, you just have to add you dependencies to the constructor, and win!, basically two parts:

Add in your Startup.class

```<code>public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddTransient<MySpecialClassWithDependencies>();
    ...
}
</code>```

Then in your controller:

```<code>public class HomeController : Controller
{
    private readonly MySpecialClassWithDependencies _mySpecialClassWithDependencies;

    public HomeController(MySpecialClassWithDependencies mySpecialClassWithDependencies)
    {
        _mySpecialClassWithDependencies = mySpecialClassWithDependencies;
    }

    public IActionResult Index()
    {
        // Now i can use my object here, the framework already initialized for me!
        return View();
    }
</code>```

This sould be no different if you library class is in other project, at the end of the day you will be adding the class to the startup, that is how asp net knows what to load.

If you want your code clean, you can use an Extension method to group all your declarations and the just calling services.AddMyAwesomeLibrary(), for example:

In your awesomeLibraryProject:

```<code>public static class MyAwesomeLibraryExtensions
{
    public static void AddMyAwesomeLibrary(this IServiceCollection services)
    {
        services.AddSingleton<SomeSingleton>();
        services.AddTransient<SomeTransientService>();
    }
}
</code>```

And in your Startup

```<code>    public void ConfigureServices(IServiceCollection services)
    {
        ...
        services.AddMyAwesomeLibrary();
    }
</code>```

Title: dotnet core-Logging in class library

Body:
is it possible to use Microsoft.Extensions.Logging like use logging in controllers(put in constructor and framework handle it with DI), in class library which my ASP.NET Core web application use that library? and how instantiate class and use method?

public class MyMathCalculator
{
    private readonly ILogger<MyMathCalculator> logger;

    public MyMathCalculator(ILogger<MyMathCalculator> logger)
    {
        this.logger = logger;
    }

    public int Fact(int n)
    {
        //logger.LogInformation($"Fact({n}) called.");
        if (n == 0)
        {
            return 1;
        }
        return Fact(n - 1) * n;
    }
}

Body:
Taked from a previous answer:

...That is the magic of dependency injection, just let the system create the object for you, you just have to ask for the type.

This is also a big topic, ... basically, all you have to do is to define classes as dependencies, so, when you ask for one, the system itself check the dependencies, and the dependencies of that objects, until resolves all the tree of dependencies.

With this, if you need one more dependency latter in your class, you can add directly but you do not need to modify all the classes that uses that class.

To use this in the controller, please check the official docs, you just have to add you dependencies to the constructor, and win!, basically two parts:

Add in your Startup.class

public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddTransient<MySpecialClassWithDependencies>();
    ...
}

Then in your controller:

public class HomeController : Controller
{
    private readonly MySpecialClassWithDependencies _mySpecialClassWithDependencies;

    public HomeController(MySpecialClassWithDependencies mySpecialClassWithDependencies)
    {
        _mySpecialClassWithDependencies = mySpecialClassWithDependencies;
    }

    public IActionResult Index()
    {
        // Now i can use my object here, the framework already initialized for me!
        return View();
    }

This sould be no different if you library class is in other project, at the end of the day you will be adding the class to the startup, that is how asp net knows what to load.

If you want your code clean, you can use an Extension method to group all your declarations and the just calling services.AddMyAwesomeLibrary(), for example:

In your awesomeLibraryProject:

public static class MyAwesomeLibraryExtensions
{
    public static void AddMyAwesomeLibrary(this IServiceCollection services)
    {
        services.AddSingleton<SomeSingleton>();
        services.AddTransient<SomeTransientService>();
    }
}

And in your Startup

    public void ConfigureServices(IServiceCollection services)
    {
        ...
        services.AddMyAwesomeLibrary();
    }


问:
Ansible: Build Command with variables
I would like to build an ansible playbook and at this point I need some help.

I have my defaults:

```<code>variables:
  module1: true
  module2: false
  module3: true
  module4: true
</code>```

I need now to find out which module key has a true-value and put the key name in my command

```<code>- name: Install Packages
  command: {{ item }}
  with_items:
   - ./configure
</code>```

The output should be something like this:

```<code>- name: Install Packages
  command: {{ item }}
  with_items:
   - ./configure --module1 **--no**-module2 --module3 --module4
</code>```

How can I get all this modules and build my configure command?

Thanks!

答:
The play below

```<code>- hosts: localhost
  gather_facts: no
  vars:
    command: ""
    my_variables:
      module1: true
      module2: false
      module3: true
      module4: true
  tasks:
    - set_fact:
        command: "{{ command ~ item.value|ternary(' --' ~ item.key,
                                                  ' **--no**-' ~ item.key) }}"
      loop: "{{ my_variables|dict2items }}"
    - debug:
        var: command
</code>```

gives (abridged):

```<code>"command": " --module4 --module3 **--no**-module2 --module1"
</code>```

Notes:

dict2items works with ansible version >= 2.6

Title: Ansible: Build Command with variables

Body:
I would like to build an ansible playbook and at this point I need some help.

I have my defaults:

variables:
  module1: true
  module2: false
  module3: true
  module4: true

I need now to find out which module key has a true-value and put the key name in my command

- name: Install Packages
  command: {{ item }}
  with_items:
   - ./configure

The output should be something like this:

- name: Install Packages
  command: {{ item }}
  with_items:
   - ./configure --module1 **--no**-module2 --module3 --module4

How can I get all this modules and build my configure command?

Thanks!

Body:
The play below

- hosts: localhost
  gather_facts: no
  vars:
    command: ""
    my_variables:
      module1: true
      module2: false
      module3: true
      module4: true
  tasks:
    - set_fact:
        command: "{{ command ~ item.value|ternary(' --' ~ item.key,
                                                  ' **--no**-' ~ item.key) }}"
      loop: "{{ my_variables|dict2items }}"
    - debug:
        var: command

gives (abridged):

"command": " --module4 --module3 **--no**-module2 --module1"

Notes:

dict2items works with ansible version >= 2.6


问:
How to do a linear regression for each three rows in Python?
I want to make a linear regression for each three rows using for-loop and count, but I couldn't make it because I am confused with the input (x & y) for linear regression.

Here it is the code:

```<code>from sklearn.metrics import mean_squared_error, r2_score
import statsmodels.api as sm
import numpy as np

year=data_['Year']
value=data_['Value']
count=0
for a,b in zip(year,value):
    print(a,b)
    count = count+1[input][1]
    window_type='rolling'

    if count%3 == 0 :
        x=data_.loc[0:3,['Year']]
        y=data_.loc[0:3,['Value']]

        reg=linear_model.LinearRegression()
        x_train,x_test,y_train,y_test=train_test_split(x,y,test_size = 0.2 ,random_state=3)
        reg.fit(x,y)

        y4=4*reg.coef_ + reg.intercept_

        print("Equation : 4 *", reg.coef_, "+", reg.intercept_)
        print("Y4 : ", y4)
        print("====")
</code>```

Actual result:

```<code>1 6.262008
2 5.795994
3 5.082562
Equation : 4 * [[-76.71615936]] + [209.89679764]
Y4 :  [[-96.96783982]]
====
1 285.433511
2 260.43560099999996
3 238.71312400000002
Equation : 4 * [[-76.71615936]] + [209.89679764]
Y4 :  [[-96.96783982]]
====
1 2.595145
2 2.508278
3 2.67997
Equation : 4 * [[-76.71615936]] + [209.89679764]
Y4 :  [[-96.96783982]]
====
</code>```

The output I desire is:
every three rows result a different Y4

Please help me fixing this problem.

答:
If I understand your question correctly, you can first consult the official document of 'sklearn.linear_model.LinearRegression.fit'

Make sure your input reg.fit(X, y) is of numpy.ndarray type. To be clear, in your case,

```<code>X = np.array([1, 2, 3]).reshape(3,1)
y = np.array([6.262008, 5.795994, 5.082562])
reg=linear_model.LinearRegression()
reg.fit(X,y)
y4=4*reg.coef_ + reg.intercept_
print(np.squeeze(y4))
</code>```

That should return,

4.534075333333335

Body:
I want to make a linear regression for each three rows using for-loop and count, but I couldn't make it because I am confused with the input (x & y) for linear regression.

Here it is the code:

from sklearn.metrics import mean_squared_error, r2_score
import statsmodels.api as sm
import numpy as np

year=data_['Year']
value=data_['Value']
count=0
for a,b in zip(year,value):
    print(a,b)
    count = count+1[input][1]
    window_type='rolling'

    if count%3 == 0 :
        x=data_.loc[0:3,['Year']]
        y=data_.loc[0:3,['Value']]

        reg=linear_model.LinearRegression()
        x_train,x_test,y_train,y_test=train_test_split(x,y,test_size = 0.2 ,random_state=3)
        reg.fit(x,y)

        y4=4*reg.coef_ + reg.intercept_

        print("Equation : 4 *", reg.coef_, "+", reg.intercept_)
        print("Y4 : ", y4)
        print("====")

Actual result:

1 6.262008
2 5.795994
3 5.082562
Equation : 4 * [[-76.71615936]] + [209.89679764]
Y4 :  [[-96.96783982]]
====
1 285.433511
2 260.43560099999996
3 238.71312400000002
Equation : 4 * [[-76.71615936]] + [209.89679764]
Y4 :  [[-96.96783982]]
====
1 2.595145
2 2.508278
3 2.67997
Equation : 4 * [[-76.71615936]] + [209.89679764]
Y4 :  [[-96.96783982]]
====

The output I desire is:
every three rows result a different Y4

Please help me fixing this problem.

Body:
If I understand your question correctly, you can first consult the official document of 'sklearn.linear_model.LinearRegression.fit'

Make sure your input reg.fit(X, y) is of numpy.ndarray type. To be clear, in your case,

X = np.array([1, 2, 3]).reshape(3,1)
y = np.array([6.262008, 5.795994, 5.082562])
reg=linear_model.LinearRegression()
reg.fit(X,y)
y4=4*reg.coef_ + reg.intercept_
print(np.squeeze(y4))

That should return,

4.534075333333335


问:
In React, how do I detect if my component is rendering from the client or the server?
I'm building a isomorphic application, but I'm using a third-party component that only renders on the client. So, particularly for this component, I need to only render it when I'm rendering in the client.

How do I detect if I'm at the client or at the server? I'm looking for something like isClient() or isServer().

答:
You could also just use the use-ssr React hook

```<code>import useSSR from 'use-ssr'

const App = () => {
  var { isBrowser, isServer } = useSSR()

  // Want array destructuring? You can do that too!
  var [isBrowser, isServer] = useSSR()

  /*
   * In your browser's chrome devtools console you should see
   * > IS BROWSER:
   * > IS SERVER:
   *
   * AND, in your terminal where your server is running you should see
   * > IS BROWSER:
   * > IS SERVER:
   */
  console.log('IS BROWSER: ', isBrowser ? '' : '')
  console.log('IS SERVER: ', isServer ? '' : '')
  return (
    <>
      Is in browser? {isBrowser ? '' : ''}
      <br />
      Is on server? {isServer ? '' : ''}
    </>
  )
}
</code>```

Example

ContentLicense: CC BY-SA 3.0

Body:
You could also just use the use-ssr React hook

import useSSR from 'use-ssr'

const App = () => {
  var { isBrowser, isServer } = useSSR()

  // Want array destructuring? You can do that too!
  var [isBrowser, isServer] = useSSR()

  /*
   * In your browser's chrome devtools console you should see
   * > IS BROWSER:
   * > IS SERVER:
   *
   * AND, in your terminal where your server is running you should see
   * > IS BROWSER:
   * > IS SERVER:
   */
  console.log('IS BROWSER: ', isBrowser ? '' : '')
  console.log('IS SERVER: ', isServer ? '' : '')
  return (
    <>
      Is in browser? {isBrowser ? '' : ''}
      <br />
      Is on server? {isServer ? '' : ''}
    </>
  )
}

Example


问:
How to map silk 4j script to the test case in Silk Central
Please suggest on how to map/link silk 4j script to the manual test case written in Silk Central.

Like for 4Test script we select .t file and then the testcase under silk test classic properties in silk central for each test case.

答:
The test type can be changed in the Tests unit from the context menu of a node. Use the action "Automate with ...". Choose the appropriate type, e.g. "Silk Test Classic Test" for .t-files or "JUnit Test" if you use silk4j.

Regards,
Hubert


问:
material-ui TextField disable Browser autoComplete
I use material ui v0.20.0 and I have to prohibit saving the password for a user with TextField. I added props to TextField autocomplete='nope' cause not all the browsers understand autocomplete='off'. It seems that the last version of Chrome 63 does not accept it. Sometimes it does not work and sometimes it does. I can not get why it works so hectic. When chrome asks to save password and I save it, and after that I want to edit input I still have this :

```<code>  <TextField
         name='userName'
         floatingLabelText={<FormattedMessage id='users.username' />}
         value={name || ''}
         onChange={(e, name) => this.changeUser({name})}
         // autoComplete='new-password'

    />

    <TextField
        name='password'
        floatingLabelText={<FormattedMessage id='users.passwords.new' />}
        type='password'
        value={password || ''}
        onChange={(e, password) => this.changeUser({password})}
        autoComplete='new-password'
   />
</code>```

Looks like it works in Firefox(v57.0.4)

By default TextField does not have autoComplete='off'

答:
To Disable auto Complete in material-ui TextField.
its works for me

```<code><TextField
  name='password'
  autoComplete='off'
  type='text'
  ...
/>
</code>```

should be autoComplete='off'

```<code>autoComplete='off'
</code>```

Body:
I use material ui v0.20.0 and I have to prohibit saving the password for a user with TextField. I added props to TextField autocomplete='nope' cause not all the browsers understand autocomplete='off'. It seems that the last version of Chrome 63 does not accept it. Sometimes it does not work and sometimes it does. I can not get why it works so hectic. When chrome asks to save password and I save it, and after that I want to edit input I still have this :

  <TextField
         name='userName'
         floatingLabelText={<FormattedMessage id='users.username' />}
         value={name || ''}
         onChange={(e, name) => this.changeUser({name})}
         // autoComplete='new-password'

    />

    <TextField
        name='password'
        floatingLabelText={<FormattedMessage id='users.passwords.new' />}
        type='password'
        value={password || ''}
        onChange={(e, password) => this.changeUser({password})}
        autoComplete='new-password'
   />

Looks like it works in Firefox(v57.0.4)

By default TextField does not have autoComplete='off'

Body:
To Disable auto Complete in material-ui TextField.
its works for me

<TextField
  name='password'
  autoComplete='off'
  type='text'
  ...
/>

should be autoComplete='off'

autoComplete='off'


问:
Minimizing ViewState size in ASP.Net, is there a difference between initializing control values in the constructor versus OnInit?
Ok I'm trying to understand how best to handle ViewState, for the programmatic setting of default values using C#. I understand that the construction of the ViewState hidden field is based on every value that is set after the OnInit event is triggered. What I'm not clear about is if there is a difference between using the control's constructor or the OnInit event to set default values.

```<code>public MyControl(){
    this.Text = "SomeDefaultValue";
}
</code>```

versus

```<code>protected override void OnInit(EventArgs e){
    this.Text = "SomeDefaultValue";
}
</code>```

I've seen some places that suggest testing the ViewState value for null in the get of the given property, like so:

```<code>public string Text {
    get {
        return this.ViewState["Text"] == null ?
            "SomeDefaultValue" :
            this.ViewState["Text"] as string;
    }
    set { this.ViewState["Text"] = value; }
}
</code>```

I don't like that because it makes clearing the value confusing.

So, Is there any functional difference between using the constructor vs OnInit to set default ViewState values?

答:
In terms of minimizing ViewState, there is no difference, as ViewState starts tracking after the OnInit method is run.

There are some functional differences, however: until the control is initialized, you cannot access other properties like the Page. For this reason, I usually prefer to use either OnInit or some handler tied to the Init event.

Also, be careful about overriding OnInit: you should call base.OnInit() to make sure that other event handlers for the Init event still get called.

I highly recommend that you read this excellent article on the topic: http://weblogs.asp.net/infinitiesloop/archive/2006/08/03/Truly-Understanding-Viewstate.aspx

Edit

To clarify, the ViewState starts tracking for a given control after the OnInit method is run for that control. So in the given example, you are safe to override OnInit like this:

```<code>protected override void OnInit(EventArgs e){
    this.Text = "SomeDefaultValue"; // Make sure this happens before base.OnInit
    base.OnInit();
}
</code>```

This works because the Text property is saving the value to the ViewState of this control. However, let's say you have another child control (I'll use a Label as an example). That Label's OnInit will already have been run by the time your control's OnInit method is called. So if you want to change the Label's Text value, you'll need to do it during that label's OnInit phase (or sooner).

You could do it in the constructor of the current control:

```<code>public MyControl(){
    this.Label.Text = "SomeDefaultValue";
}
</code>```

... but as mentioned earlier you won't have access to the external control structure, which may be necessary in some cases. A good alternative in these cases is to use an Init event handler on the label itself. You can hook up the event handler itself in your constructor:

```<code>public MyControl(){
    this.Label.Init +=
        (sender, e) => this.Label.Text =
             ((TextBox)Page.FindControl("SomeControl")).Text;
}
</code>```

... but this will only work if the control is declared directly as a member of your class. If the label is inside a template (like in a Repeater), you'll need to use markup to hook it up:

```<code><asp:Label runat="server" OnInit="Label_Init" />
</code>```

with the code-behind:

```<code>public void Label_Init(object sender, EventArgs e)
{
    var label = (Label)sender;
    label.Text = ((TextBox)Page.FindControl("SomeControl")).Text;
}
</code>```

This latter example has the advantage of working in just about every circumstance I can think of, but it requires more boilerplate code, as well as a change in markup. So pick your poison based on your specific situation.

Body:
Ok I'm trying to understand how best to handle ViewState, for the programmatic setting of default values using C#. I understand that the construction of the ViewState hidden field is based on every value that is set after the OnInit event is triggered. What I'm not clear about is if there is a difference between using the control's constructor or the OnInit event to set default values.

public MyControl(){
    this.Text = "SomeDefaultValue";
}

versus

protected override void OnInit(EventArgs e){
    this.Text = "SomeDefaultValue";
}

I've seen some places that suggest testing the ViewState value for null in the get of the given property, like so:

public string Text {
    get {
        return this.ViewState["Text"] == null ?
            "SomeDefaultValue" :
            this.ViewState["Text"] as string;
    }
    set { this.ViewState["Text"] = value; }
}

I don't like that because it makes clearing the value confusing.

So, Is there any functional difference between using the constructor vs OnInit to set default ViewState values?

Body:
In terms of minimizing ViewState, there is no difference, as ViewState starts tracking after the OnInit method is run.

There are some functional differences, however: until the control is initialized, you cannot access other properties like the Page. For this reason, I usually prefer to use either OnInit or some handler tied to the Init event.

Also, be careful about overriding OnInit: you should call base.OnInit() to make sure that other event handlers for the Init event still get called.

I highly recommend that you read this excellent article on the topic: http://weblogs.asp.net/infinitiesloop/archive/2006/08/03/Truly-Understanding-Viewstate.aspx

Edit

To clarify, the ViewState starts tracking for a given control after the OnInit method is run for that control. So in the given example, you are safe to override OnInit like this:

protected override void OnInit(EventArgs e){
    this.Text = "SomeDefaultValue"; // Make sure this happens before base.OnInit
    base.OnInit();
}

This works because the Text property is saving the value to the ViewState of this control. However, let's say you have another child control (I'll use a Label as an example). That Label's OnInit will already have been run by the time your control's OnInit method is called. So if you want to change the Label's Text value, you'll need to do it during that label's OnInit phase (or sooner).

You could do it in the constructor of the current control:

public MyControl(){
    this.Label.Text = "SomeDefaultValue";
}

... but as mentioned earlier you won't have access to the external control structure, which may be necessary in some cases. A good alternative in these cases is to use an Init event handler on the label itself. You can hook up the event handler itself in your constructor:

public MyControl(){
    this.Label.Init +=
        (sender, e) => this.Label.Text =
             ((TextBox)Page.FindControl("SomeControl")).Text;
}

... but this will only work if the control is declared directly as a member of your class. If the label is inside a template (like in a Repeater), you'll need to use markup to hook it up:

<asp:Label runat="server" OnInit="Label_Init" />

with the code-behind:

public void Label_Init(object sender, EventArgs e)
{
    var label = (Label)sender;
    label.Text = ((TextBox)Page.FindControl("SomeControl")).Text;
}

This latter example has the advantage of working in just about every circumstance I can think of, but it requires more boilerplate code, as well as a change in markup. So pick your poison based on your specific situation.


问:
Angular tree structure with 2 different list populating from nested rxjs subscription
In Angular 7 I have two observable which is getting data from the server; Observables gives the following lists:

```<code>    productgroup = [{"id":"1","groupname":"gr1"},{"id":"2","groupname":"gr2"}];
    products = [{"id":"1","productname":"COMPUTER","productgroup":"gr2",....},{"id":"2","productname":"ACCESSORIES","productgroup":"gr1",....}]
</code>```

I have to make a tree data structure to create a menu with an angular material tree like the following:

```<code>    [
        {
            "id":1,
            "name": "gr1",
            "children": [
                {"id":"1","productname":"COMPUTER","productgroup":"gr2",....},
                {"id":"2","productname":"ACCESSORIES","productgroup":"gr1",....}
            ]
        }
        {
        }
    ]
</code>```

The code i have tried is as following --

```<code> this.productGroupService.getAll().pipe(switchMap((allgroup: any) => {
          var flag = 0;
          this.groups = []; // array to hold group or parent data
          allgroup.map(element => {
            this.finalarr = []; // fial array
            console.log(element.id);

            this.productService.getbygroup(element.id)// for each group getting product data list
            .pipe(map((data) => {
              this.productInGroup[flag] = []; // array to hold children data
              this.groups.push(element);
              data.map((dval)=>{
                this.productInGroup[flag].push({productname: dval["productname"], id: String(dval["id"])});
              })
              flag++;

            })
            ).subscribe((data) => {
              if(allgroup.length == flag){
                //console.log(this.groups);
                var flag2 = 0;
                this.groups.map(()=>{
                  var obj = {groupname: this.groups[flag2].groupname,id:this.groups[flag2].id,
                    products:this.productInGroup[flag2]}; // joining child and parent data into single object
                  this.finalarr.push(obj);
                  flag2++;
                  if(flag2 == this.groups.length){
                    this.datasource = this.finalarr;
                    console.log(this.datasource);
                  }
                })
              }
            })
          });
      })).subscribe()
</code>```

At first I am looping over productgroup list and creating a parent array.
Then for each group, I am getting data from the server by subscription and creating a child array. Then making an object with that array and pushing it to the final array.

The code is working for small dataset. But I am not happy with this solution
as it iterates through all products for all groups nxm times.

I know it would have been much easier if the table in the database were associated via foreign key and a flat list but I don't have control over that.

Any help or suggestion is appriciated. Thanks!

答:
By introducing state your solution has become very complex.

Try this

```<code>  const productGroup$ = this.productGroupService.getAll();

  productGroup$.pipe(
  mergeMap((productGroupArray) => from(productGroupArray)),
  concatMap(
    (productGroupItem) => this.productService.getbygroup(productGroupItem.id).pipe(
    map((product) => {
      let json = {};
      json['id'] = productGroupItem.id;
      json['name'] = productGroupItem.groupname;
      json['children'] = product;
      return json;
    })
  )),
  toArray()
).subscribe((val) => console.log(val));
</code>```

Inside subscribe you will get the array directly.

Body:
In Angular 7 I have two observable which is getting data from the server; Observables gives the following lists:

    productgroup = [{"id":"1","groupname":"gr1"},{"id":"2","groupname":"gr2"}];
    products = [{"id":"1","productname":"COMPUTER","productgroup":"gr2",....},{"id":"2","productname":"ACCESSORIES","productgroup":"gr1",....}]

I have to make a tree data structure to create a menu with an angular material tree like the following:

    [
        {
            "id":1,
            "name": "gr1",
            "children": [
                {"id":"1","productname":"COMPUTER","productgroup":"gr2",....},
                {"id":"2","productname":"ACCESSORIES","productgroup":"gr1",....}
            ]
        }
        {
        }
    ]

The code i have tried is as following --

 this.productGroupService.getAll().pipe(switchMap((allgroup: any) => {
          var flag = 0;
          this.groups = []; // array to hold group or parent data
          allgroup.map(element => {
            this.finalarr = []; // fial array
            console.log(element.id);

            this.productService.getbygroup(element.id)// for each group getting product data list
            .pipe(map((data) => {
              this.productInGroup[flag] = []; // array to hold children data
              this.groups.push(element);
              data.map((dval)=>{
                this.productInGroup[flag].push({productname: dval["productname"], id: String(dval["id"])});
              })
              flag++;

            })
            ).subscribe((data) => {
              if(allgroup.length == flag){
                //console.log(this.groups);
                var flag2 = 0;
                this.groups.map(()=>{
                  var obj = {groupname: this.groups[flag2].groupname,id:this.groups[flag2].id,
                    products:this.productInGroup[flag2]}; // joining child and parent data into single object
                  this.finalarr.push(obj);
                  flag2++;
                  if(flag2 == this.groups.length){
                    this.datasource = this.finalarr;
                    console.log(this.datasource);
                  }
                })
              }
            })
          });
      })).subscribe()

At first I am looping over productgroup list and creating a parent array.
Then for each group, I am getting data from the server by subscription and creating a child array. Then making an object with that array and pushing it to the final array.

The code is working for small dataset. But I am not happy with this solution
as it iterates through all products for all groups nxm times.

I know it would have been much easier if the table in the database were associated via foreign key and a flat list but I don't have control over that.

Any help or suggestion is appriciated. Thanks!

Body:
By introducing state your solution has become very complex.

Try this

  const productGroup$ = this.productGroupService.getAll();

  productGroup$.pipe(
  mergeMap((productGroupArray) => from(productGroupArray)),
  concatMap(
    (productGroupItem) => this.productService.getbygroup(productGroupItem.id).pipe(
    map((product) => {
      let json = {};
      json['id'] = productGroupItem.id;
      json['name'] = productGroupItem.groupname;
      json['children'] = product;
      return json;
    })
  )),
  toArray()
).subscribe((val) => console.log(val));

Inside subscribe you will get the array directly.


问:
Remove backslashes from response entity Json in Java
I am testing my Rest controller and when i print the results in java they seem to be okay but on swagger or postman it return slashes. How do i remove these.

In Java i print the object with a log and the result is as below:

ReturnObject

```<code>    {
      create=Create{
        create={
          "Apartment": "Flat",
          "Drink": {
            "Alchol": {
              "Beer": {
                "Dutch": "Groeshe",
                "Zimbo": "Zambezi"
              },
              "Wine": "pocupine"
            },
            "NonAlcoholic": {
              "fizzy": "Coke",
              "juice": "liquifruit"
            }
          },
          "fruit": "Apple",
          "size": "Large",
          "color": "Red",
          "Proffesion": [
            "Java",
            "Lawyer"
          ],
          "cars": {
            "type": "BMW",
            "Color": "Brown"
          }
        }
      },
      update=null,
      delete=null
    }
</code>```

I googled and nothing in java seems to solve this problem. Please assist

```<code>    @RestController
    public class ProcessController<T extends Serializable> {

    @Autowired
    private EngineImpl engine;

    @RequestMapping(value = "/api/processEngine", method = RequestMethod.POST, produces = "application/json")
    public ResponseEntity<ReturnObject<T>> processEngine(@RequestBody final Request request) throws Exception {

        ReturnObject<T> response = engine.calculate((T) request.getA(), (T) request.getB());

        LOG.info("ReturnObject engine response parameters: " + response);
        //Prints: ReturnObject{create=Create{create={"Apartment":"Flat","Drink":{"Alchol":{"Beer":{"Dutch":"Groeshe","Zimbo":"Zambezi"},"Wine":"pocupine"},"NonAlcoholic":{"fizzy":"Coke","juice":"liquifruit"}},"fruit":"Apple","size":"Large","color":"Red","Proffesion":["Java","Lawyer"],"cars":{"type":"BMW","Color":"Brown"}}}, update=null, delete=null}
        return new ResponseEntity<>(response, HttpStatus.OK);
    }
}
</code>```

Expected:

```<code>    {
      "create": {
        "create": {
            "Apartment": "Flat",
            "Drink": {
                "Alchol": {
                    "Beer": {
                        "Dutch": "Groeshe",
                        "Zimbo": "Zambezi"

                    },
                    "Wine": "pocupine"

                },
                "NonAlcoholic": {
                    "fizzy": "Coke",
                    "juice": "liquifruit"
                }
            },
            "fruit": "Apple",
            "size": "Large",
            "color": "Red",
            "Proffesion": ["Java", "Lawyer"],
            "cars": {
                "type": "BMW",
                "Color": "Brown"
            }
        },
        "update": null,
        "delete": null
    }
}
</code>```

Actual:

```<code>    {
      "create": {
        "create": "{\"Apartment\":\"Flat\",\"Drink\":{\"Alchol\":{\"Beer\":{\"Dutch\":\"Groeshe\",\"Zimbo\":\"Zambezi\"},\"Wine\":\"pocupine\"},\"NonAlcoholic\":{\"fizzy\":\"Coke\",\"juice\":\"liquifruit\"}},\"fruit\":\"Apple\",\"size\":\"Large\",\"color\":\"Red\",\"Proffesion\":[\"Java\",\"Lawyer\"],\"cars\":{\"type\":\"BMW\",\"Color\":\"Brown\"}}"
      },
      "update": null,
      "delete": null
    }
</code>```

答:
After Second "create" it is Basically converting your value to String.
please implement this annotation
    @PostMapping("/api/processEngine")
please Try this and Let Me know immediately</p>

Body:
I am testing my Rest controller and when i print the results in java they seem to be okay but on swagger or postman it return slashes. How do i remove these.

In Java i print the object with a log and the result is as below:

ReturnObject

    {
      create=Create{
        create={
          "Apartment": "Flat",
          "Drink": {
            "Alchol": {
              "Beer": {
                "Dutch": "Groeshe",
                "Zimbo": "Zambezi"
              },
              "Wine": "pocupine"
            },
            "NonAlcoholic": {
              "fizzy": "Coke",
              "juice": "liquifruit"
            }
          },
          "fruit": "Apple",
          "size": "Large",
          "color": "Red",
          "Proffesion": [
            "Java",
            "Lawyer"
          ],
          "cars": {
            "type": "BMW",
            "Color": "Brown"
          }
        }
      },
      update=null,
      delete=null
    }

I googled and nothing in java seems to solve this problem. Please assist

    @RestController
    public class ProcessController<T extends Serializable> {

    @Autowired
    private EngineImpl engine;

    @RequestMapping(value = "/api/processEngine", method = RequestMethod.POST, produces = "application/json")
    public ResponseEntity<ReturnObject<T>> processEngine(@RequestBody final Request request) throws Exception {

        ReturnObject<T> response = engine.calculate((T) request.getA(), (T) request.getB());

        LOG.info("ReturnObject engine response parameters: " + response);
        //Prints: ReturnObject{create=Create{create={"Apartment":"Flat","Drink":{"Alchol":{"Beer":{"Dutch":"Groeshe","Zimbo":"Zambezi"},"Wine":"pocupine"},"NonAlcoholic":{"fizzy":"Coke","juice":"liquifruit"}},"fruit":"Apple","size":"Large","color":"Red","Proffesion":["Java","Lawyer"],"cars":{"type":"BMW","Color":"Brown"}}}, update=null, delete=null}
        return new ResponseEntity<>(response, HttpStatus.OK);
    }
}

Expected:

    {
      "create": {
        "create": {
            "Apartment": "Flat",
            "Drink": {
                "Alchol": {
                    "Beer": {
                        "Dutch": "Groeshe",
                        "Zimbo": "Zambezi"

                    },
                    "Wine": "pocupine"

                },
                "NonAlcoholic": {
                    "fizzy": "Coke",
                    "juice": "liquifruit"
                }
            },
            "fruit": "Apple",
            "size": "Large",
            "color": "Red",
            "Proffesion": ["Java", "Lawyer"],
            "cars": {
                "type": "BMW",
                "Color": "Brown"
            }
        },
        "update": null,
        "delete": null
    }
}

Actual:

    {
      "create": {
        "create": "{\"Apartment\":\"Flat\",\"Drink\":{\"Alchol\":{\"Beer\":{\"Dutch\":\"Groeshe\",\"Zimbo\":\"Zambezi\"},\"Wine\":\"pocupine\"},\"NonAlcoholic\":{\"fizzy\":\"Coke\",\"juice\":\"liquifruit\"}},\"fruit\":\"Apple\",\"size\":\"Large\",\"color\":\"Red\",\"Proffesion\":[\"Java\",\"Lawyer\"],\"cars\":{\"type\":\"BMW\",\"Color\":\"Brown\"}}"
      },
      "update": null,
      "delete": null
    }


问:
The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. on deploying to tomcat
I have built an application using Spring with Eclipse IDE. When I launch the project from Eclipse IDE everything is fine but when I package the maven project as a war file and deployed to separate tomcat I have this issue

```<code>The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
</code>```

This is a configuration snippet from my xml file

```<code><!-- View Resolver -->
    <beans:bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/pages/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>
</code>```

I am trying to access this controller

```<code>@RequestMapping(value = {"/welcome", "/"})
    public String defaultPage() {
            return "Web Service data successfuly consumed";

    }
</code>```

anyone with an idea why this is failing on deployed to tomcat?

答:
This issue can even occur when you try to run your project from controller page.
Run your project from the jsp page.
Go to your jsp page; right-click->Run As->Run on Server.
I faced the same issue.I was running my project from the controller page.
Run your project from jsp page.</p>

Body:
I have built an application using Spring with Eclipse IDE. When I launch the project from Eclipse IDE everything is fine but when I package the maven project as a war file and deployed to separate tomcat I have this issue

The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.

This is a configuration snippet from my xml file

    <beans:bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/pages/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>

I am trying to access this controller

@RequestMapping(value = {"/welcome", "/"})
    public String defaultPage() {
            return "Web Service data successfuly consumed";

    }

anyone with an idea why this is failing on deployed to tomcat?


问:
Error in betadisper(dissimilarity_matrix ~ Group) : distances 'd' must be a 'dist' object
I get the error as in the title, when I try to do betadisper on my dissimilarity matrix. When looking at my environment it clearly says 'dist'.

as.dist() doesn't help

```<code>#fhf is a phyloseq object

veganotu = function(physeq) {
    require("vegan")
    OTU = otu_table(physeq)
    if (taxa_are_rows(OTU)) {
        OTU = t(OTU)
    }
    return(as(OTU, "matrix"))
}

Group <- sample_names(fhf)
dissimilarity_matrix <- vegdist(veganotu(fhf), method="bray")
homogen <- betadisper(dissimilarity_matrix ~ Group)
anova(homogen)
</code>```

I expect a result similar to this, but with other values:

Analysis of Variance Table

Response: Distances
          Df   Sum Sq   Mean Sq F value Pr(>F)
Groups     5 0.021037 0.0042074  1.5524  0.252
Residuals 11 0.029813 0.0027103

Error message:

Error in betadisper(dissimilarity_matrix ~ Group) :
  distances 'd' must be a 'dist' object

答: betadisper does not accept formula. You must write betadisper(dissimilarity_matrix, Group).

Body:
I get the error as in the title, when I try to do betadisper on my dissimilarity matrix. When looking at my environment it clearly says 'dist'.

as.dist() doesn't help

#fhf is a phyloseq object

veganotu = function(physeq) {
    require("vegan")
    OTU = otu_table(physeq)
    if (taxa_are_rows(OTU)) {
        OTU = t(OTU)
    }
    return(as(OTU, "matrix"))
}

Group <- sample_names(fhf)
dissimilarity_matrix <- vegdist(veganotu(fhf), method="bray")
homogen <- betadisper(dissimilarity_matrix ~ Group)
anova(homogen)

I expect a result similar to this, but with other values:

Analysis of Variance Table

Response: Distances
          Df   Sum Sq   Mean Sq F value Pr(>F)
Groups     5 0.021037 0.0042074  1.5524  0.252
Residuals 11 0.029813 0.0027103

Error message:

Error in betadisper(dissimilarity_matrix ~ Group) :
  distances 'd' must be a 'dist' object


问:
Is OSBA the only way to connect Azure CosmosDB within AKS pod
I have a Java pod application which connect to CosmosDB using the default connection string. The pod runs perfectly on my local minikube. But it has connection exception when I deploy it to my AKS.

The pod keep crashing with this MongoDB error.

Timed out after 30000 ms while waiting for server that matches...
  Client view of cluster state is ... xxx.documents.azure.com:10255

Looks like it cannot reach the CosmosDB. At first I think it is because the default Network security rules block the outgoing port 10255. Then I add a NSG to that resource group. Add the outgoing rule on port 10255. It does not solve the problem.

Then I stumble upon this article. CosmosDB on AKS using OSBA
Is it the only way? do I have to use OSBA to access a public CosmosDB?

Connection string copy from Azure portal

mongodb://mycompany:some_base64_encrypted_stuff@mycompany.documents.azure.com:10255/?ssl=true&replicaSet=globaldb

error log of my pod

UPDATE:

turns out the spring-boot-starter 2.1.0 is using mongodb-driver 3.8.2.
the mongodb-driver appends :27017 to my connection string. I have updated it to 3.10.2. Now that the connection string is correct. My program running in Kubernetes is giving me UnknownHostException mydoc.documents.azure.com.
I am guessing there could be a problem caused by build docker image in windows and then run it on alpine.

UPDATE:

I think I am getting very close to the answer. The problem is from the kubernetes cluster. My cluster contains two nodes. I create another cluster with single node. Deploy my program to it and it connects to CosmosDB without error.
But I do not know how to debug kubernetes cluster.

答:
if you are using network policies, you can use the sample network policy to allow all egress traffic:

```<code>apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-all
spec:
  podSelector: {}
  egress:
  - {}
  policyTypes:
  - Egress
</code>```

If you are not using Network policies, connection should just work, you dont need OSBA. You can fine tune the network policy later to make it more restrictive.

https://kubernetes.io/docs/concepts/services-networking/network-policies/

ps. if you are using istio with certain settings your outbound requests will be also blocker, you'd need to account for that as well

Body:
if you are using network policies, you can use the sample network policy to allow all egress traffic:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-all
spec:
  podSelector: {}
  egress:
  - {}
  policyTypes:
  - Egress

If you are not using Network policies, connection should just work, you dont need OSBA. You can fine tune the network policy later to make it more restrictive.

https://kubernetes.io/docs/concepts/services-networking/network-policies/

ps. if you are using istio with certain settings your outbound requests will be also blocker, you'd need to account for that as well


问:
Even better support for HAML in Netbeans?
This plugin is pretty good, definitely better than plain-text.. but I'm longing for a little more. Code completion, the Netbeans code generator shortcuts, 'ri' integration for looking up documentation like the .erb files have..

Does anyone have some tricks, is there a different plugin for this type of functionality in Netbeans?

Definitely would like SASS support for Netbeans as well!

答: There's an haml plugin that needs some teaks in order to change the default colors: How to change color of HAML tags in NetBeans?</p>

ContentLicense: CC BY-SA 2.5


问:
ClassNotFoundException even after adding dependecy jars
I'm creating a simple REST web service using Jersey. And when I try to run it on the server(Tomcat 7) I'm getting the following exception. I can see in my Maven dependecy library that the class(com.sun.jersey.spi.container.servlet.ServletContainer) is already present.Need help.

```<code>Exception:
SEVERE: Servlet /SampleJersey threw load() exception
java.lang.ClassNotFoundException: com.sun.jersey.spi.container.servlet.ServletContainer
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1714)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559)
</code>```

1.I have added the extra maven dependency core and servlet and tried. But it did not work.

```<code><dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-core</artifactId>
    <version>1.17.1</version>
</dependency>
<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-servlet</artifactId>
    <version>1.17.1</version>
</dependency>
</code>```

I tried the following as well:
Right click on project --> Build Path --> Build Path --> Add Library --> Server Runtime --> Apache Tomcat v7.0

Here's my pom.xml:

```<code> <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
     <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-server</artifactId>
        <version>1.8</version>
    </dependency>
    <dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-json</artifactId>
    <version>1.19.4</version>
</dependency>
  </dependencies>
</code>```

And web.xml:

```<code><servlet>
 <servlet-name>Jersey Web Application</servlet-name>
 <servlet-class>
     com.sun.jersey.spi.container.servlet.ServletContainer
 </servlet-class>
        <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
 <servlet-name>Jersey Web Application</servlet-name>
     <url-pattern>/*</url-pattern>
</servlet-mapping>
</code>```

答:
Here you are running the project as dynamic web project on a server within eclipse, so you should open the project properties and send the maven dependencies to the server directory by adding the maven dependency to deployment assembly.

Right click on Project -> properties -> deployment assembly -> add -> java build path entries -> maven dependency

Body:
I'm creating a simple REST web service using Jersey. And when I try to run it on the server(Tomcat 7) I'm getting the following exception. I can see in my Maven dependecy library that the class(com.sun.jersey.spi.container.servlet.ServletContainer) is already present.Need help.

Exception:
SEVERE: Servlet /SampleJersey threw load() exception
java.lang.ClassNotFoundException: com.sun.jersey.spi.container.servlet.ServletContainer
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1714)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559)

1.I have added the extra maven dependency core and servlet and tried. But it did not work.

<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-core</artifactId>
    <version>1.17.1</version>
</dependency>
<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-servlet</artifactId>
    <version>1.17.1</version>
</dependency>

I tried the following as well:
Right click on project --> Build Path --> Build Path --> Add Library --> Server Runtime --> Apache Tomcat v7.0

Here's my pom.xml:

 <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
     <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-server</artifactId>
        <version>1.8</version>
    </dependency>
    <dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-json</artifactId>
    <version>1.19.4</version>
</dependency>
  </dependencies>

And web.xml:

<servlet>
 <servlet-name>Jersey Web Application</servlet-name>
 <servlet-class>
     com.sun.jersey.spi.container.servlet.ServletContainer
 </servlet-class>
        <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
 <servlet-name>Jersey Web Application</servlet-name>
     <url-pattern>/*</url-pattern>
</servlet-mapping>


问:
Angular Material Snackbar Change Color
I'm using Angular 7 with Material Snackbar. I want to changes the color of Snackbar to green.

In app.component.ts, I have:

```<code>this.snackBarRef = this.snackBar.open(result.localized_message, 'X', {
    duration: 4000,
    verticalPosition: 'top',
    panelClass: 'notif-success'
});

this.snackBarRef.onAction().subscribe(() => {
    this.snackBarRef.dismiss();
});
</code>```

In app.component.scss, I have:

```<code>.notif-success {
    color: #155724 !important; // green
    background-color: #d4edda !important;
    border-color: #c3e6cb !important;
    .mat-simple-snackbar-action {
        color: #155724 !important;
    }
}
</code>```

But the Snackbar is still shown in its default colors.

I can see that the notif-success class has been applied to the snackbar

```<code><snack-bar-container class="mat-snack-bar-container ng-tns-c18-84 ng-trigger ng-trigger-state notif-success mat-snack-bar-center mat-snack-bar-top ng-star-inserted" role="status" style="transform: scale(1); opacity: 1;">
</code>```

Why is the custom css not working?

答:
Instead of:

```<code>panelClass: 'notif-success'
</code>```

Try:

```<code>extraClasses: ['notif-success']
</code>```

I had the same issue and stumbled across this Stackblitz that had a working example.

Just realized extraClasses is deprecated, the accepted answer is probably better here.

Title: Angular Material Snackbar Change Color

Body:
I'm using Angular 7 with Material Snackbar. I want to changes the color of Snackbar to green.

In app.component.ts, I have:

this.snackBarRef = this.snackBar.open(result.localized_message, 'X', {
    duration: 4000,
    verticalPosition: 'top',
    panelClass: 'notif-success'
});

this.snackBarRef.onAction().subscribe(() => {
    this.snackBarRef.dismiss();
});

In app.component.scss, I have:

.notif-success {
    color: #155724 !important; // green
    background-color: #d4edda !important;
    border-color: #c3e6cb !important;
    .mat-simple-snackbar-action {
        color: #155724 !important;
    }
}

But the Snackbar is still shown in its default colors.

I can see that the notif-success class has been applied to the snackbar

<snack-bar-container class="mat-snack-bar-container ng-tns-c18-84 ng-trigger ng-trigger-state notif-success mat-snack-bar-center mat-snack-bar-top ng-star-inserted" role="status" style="transform: scale(1); opacity: 1;">

Why is the custom css not working?

Body:
Instead of:

panelClass: 'notif-success'

Try:

extraClasses: ['notif-success']

I had the same issue and stumbled across this Stackblitz that had a working example.

Just realized extraClasses is deprecated, the accepted answer is probably better here.


问:
FileNotFound exception error even thought the file exists in eclipse
While running my java file io program I'm getting FileNotFoundException

I tried changing the directory of the file and most of the other solution mentioned in SO, nothing works.

My code:

```<code>package com.HelloWorld;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class Test {
public static void main(String[] args) {
    FileWriter w=null;
    BufferedWriter bw=null;
    try {
        String s="welcome";
        String b="D:\\test.txt";
        w=new FileWriter(b);
        bw=new BufferedWriter(w);
        bw.write(s);
        bw.flush();
    }
    catch(IOException e)
    {
        System.out.println("exception caught"+e);
    }
    finally{
        try {
            if(bw!=null)
                bw.close();}
            catch(Exception e) {
                System.out.println("exception caught"+e);
            }
            try {
                if(w!=null)
                {
                    w.close();
                    System.out.println("success");
                }}
                catch(Exception e) {
                    System.out.println("exception caught"+e);
                }
            }

}
}
</code>```

答: I had already created the file in the D drive so the FileWriter overrides the already created file name because of which it did not write to the file</p>

Body:
While running my java file io program I'm getting FileNotFoundException

I tried changing the directory of the file and most of the other solution mentioned in SO, nothing works.

My code:

package com.HelloWorld;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class Test {
public static void main(String[] args) {
    FileWriter w=null;
    BufferedWriter bw=null;
    try {
        String s="welcome";
        String b="D:\\test.txt";
        w=new FileWriter(b);
        bw=new BufferedWriter(w);
        bw.write(s);
        bw.flush();
    }
    catch(IOException e)
    {
        System.out.println("exception caught"+e);
    }
    finally{
        try {
            if(bw!=null)
                bw.close();}
            catch(Exception e) {
                System.out.println("exception caught"+e);
            }
            try {
                if(w!=null)
                {
                    w.close();
                    System.out.println("success");
                }}
                catch(Exception e) {
                    System.out.println("exception caught"+e);
                }
            }

}
}


问:
Form button not being disabled
I have a form button that is not being disabled. I am doing a check to see if password match and meet a minimum length. Here is my code

```<code>  <div id="wrapper">
    <section>
      <div class="page-container">
        <p class="profile-details">
          Please enter a username and password to create your profile
        </p>
        <form [formGroup]="profileDetailsForm">
          <div>
            <label for="username">Username</label>
            <input id="username" type="text" formControlName="username" size="50" />
          </div>
          <div>
            <label for="password">Password</label>
            <input id="password" type="password" formControlName="password" />
          </div>
          <div>
            <label for="confirmPassword">Confirm Password</label>
            <input
              type="password"
              id="confirmPassword"
              (ngModelChange)="onCheckPasswordFields()"
              formControlName="confirmPassword"
            />
            <p *ngIf="isConfirmPasswordFails" class="error">
              * Password and Confirm Password do not match, please try again.
            </p>
          </div>
          <button (click)="onCreateProfile()" [disabled]="passwordsMatch == 'false'">CREATE PROFILE</button>
        </form>
      </div>
    </section>
  </div>

  onCheckPasswordFields() {
    const passwordField = this.profileDetailsForm.value.password;
    const confirmPasswordField = this.profileDetailsForm.value.confirmPassword;
    if ((passwordField === confirmPasswordField) && (confirmPasswordField.length > 7)) {
      this.passwordsMatch = true;
    } else {
      this.passwordsMatch = false;
    }
  }

  onCreateProfile() {
    this.profileDetails.username = this.profileDetailsForm.get('username').value;
    this.profileDetails.password = this.profileDetailsForm.get('password').value;
    this.profileDetails.confirmPassword = this.profileDetailsForm.get('confirmPassword').value;
    this.create.emit(this.profileDetails);
    localStorage.setItem('userName', this.profileDetails.username)
  }
</code>```

I am not sure what I a missing here. I thought it was because passwordsMatch was not instantiated but I am declaring it passwordsMatch: boolean = false;

Please assist.

答:
disabled attribute accepts a boolean value, I hope it will help you

```<code>  <button (click)="onCreateProfile()" [disabled]="passwordsMatch">CREATE PROFILE</button>
</code>```

Title: Form button not being disabled

Body:
I have a form button that is not being disabled. I am doing a check to see if password match and meet a minimum length. Here is my code

          Please enter a username and password to create your profile

        <form [formGroup]="profileDetailsForm">

            Username
            <input id="username" type="text" formControlName="username" size="50" />

            Password
            <input id="password" type="password" formControlName="password" />

            Confirm Password
            <input
              type="password"
              id="confirmPassword"
              (ngModelChange)="onCheckPasswordFields()"
              formControlName="confirmPassword"
            />

              * Password and Confirm Password do not match, please try again.

          <button (click)="onCreateProfile()" [disabled]="passwordsMatch == 'false'">CREATE PROFILE</button>
        </form>

  onCheckPasswordFields() {
    const passwordField = this.profileDetailsForm.value.password;
    const confirmPasswordField = this.profileDetailsForm.value.confirmPassword;
    if ((passwordField === confirmPasswordField) && (confirmPasswordField.length > 7)) {
      this.passwordsMatch = true;
    } else {
      this.passwordsMatch = false;
    }
  }

  onCreateProfile() {
    this.profileDetails.username = this.profileDetailsForm.get('username').value;
    this.profileDetails.password = this.profileDetailsForm.get('password').value;
    this.profileDetails.confirmPassword = this.profileDetailsForm.get('confirmPassword').value;
    this.create.emit(this.profileDetails);
    localStorage.setItem('userName', this.profileDetails.username)
  }

I am not sure what I a missing here. I thought it was because passwordsMatch was not instantiated but I am declaring it passwordsMatch: boolean = false;

Please assist.

Body:
disabled attribute accepts a boolean value, I hope it will help you

  <button (click)="onCreateProfile()" [disabled]="passwordsMatch">CREATE PROFILE</button>


问:
Entity Framework - Adding POCO with proxy object and then updating same object creates duplicate items in the database
I am using Entity Framework 4.0 with POCO entities using dynamic proxies for change tracking. I am trying to add an entity, call SaveChanges, and then update some other entities that need the IDENTITY value returned from the added object. Since the objects are not related in the edmx file, I cannot call SaveChanges at once and have EF manage it all. And then at the end I want to edit a few fields in the original object and then have SaveChanges update it. What is happening is the database is creating duplicate records for this original item. It is adding the first object, returning a new ID, but then when I call SaveChanges later after editing a couple of fields, it is adding the item to the table again. Any ideas?</p>

```<code>MyClass newItem = new MyClass();
newItem.field1 = 2;
newItem.field2 = false;
newItem.field3 = 44;

context.AddObject(newItem);
//force a save to get the identity of the added item so I can use it with another entity
context.SaveChanges();

//Setting the object state to unchanged (or not doing anything) will add a duplicate object
//If I set the object state to modified, it does not add a duplicate record, but it also does not save the updates
context.SetObjectState(newItem, ObjectStateEntry.Unchanged);

//do something else unrelated using the new ID returned from the IDENTITY field in the database

//update a couple of fields on the newly added item
newItem.field1 = 3;
newItem.field2 = true;
//save again
context.SaveChanges();
</code>```

答: This was a mistake on my part when calling SetObjectState. I had a wrapper that called this method, and the wrapper was passing in the wrong Enum value. Everything works okay now.</p>

Body:
I am using Entity Framework 4.0 with POCO entities using dynamic proxies for change tracking. I am trying to add an entity, call SaveChanges, and then update some other entities that need the IDENTITY value returned from the added object. Since the objects are not related in the edmx file, I cannot call SaveChanges at once and have EF manage it all. And then at the end I want to edit a few fields in the original object and then have SaveChanges update it. What is happening is the database is creating duplicate records for this original item. It is adding the first object, returning a new ID, but then when I call SaveChanges later after editing a couple of fields, it is adding the item to the table again. Any ideas?

MyClass newItem = new MyClass();
newItem.field1 = 2;
newItem.field2 = false;
newItem.field3 = 44;

context.AddObject(newItem);
//force a save to get the identity of the added item so I can use it with another entity
context.SaveChanges();

//Setting the object state to unchanged (or not doing anything) will add a duplicate object
//If I set the object state to modified, it does not add a duplicate record, but it also does not save the updates
context.SetObjectState(newItem, ObjectStateEntry.Unchanged);

//do something else unrelated using the new ID returned from the IDENTITY field in the database

//update a couple of fields on the newly added item
newItem.field1 = 3;
newItem.field2 = true;
//save again
context.SaveChanges();


问:
Tizen Web SDK: How to remotely debug (web inspector) web app running on watch (Galaxy)?
I'm wondering how (and if it's even possible) to remotely debug an app, written with the web SDK, running on the Samsung Galaxy Watch?

I'm able to:

connect to the watch with the Device Manager (logs show up, etc)

install and run the app on the watch

debug an app in the watch emulator (so I can confirm the Javascript debugger is working)

When I try to debug on the watch itself:

it correctly installs the app

sets up the port forwarding, eg build console has: Forwarded port: local(34473) -> remote(34473)

launches the Chrome Dev Tools, eg build console has: Opening the Web Inspector: http://127.0.0.1:34473/devtools/inspector.html?ws=127.0.0.1:34473/devtools/page/3c071e56-9c65-494f-a22a-0011ea747859

...but the Chrome page is blank. Reloading the page makes no difference, still stays blank.

Googling around I've found very little. This forum post (https://developer.tizen.org/forums/web-application-development/web-inspector-not-working-remote-device?langswitch=en) describes the same issue, but the answer is not useful: the provided link shows how to run the app (which works), not how to remotely debug.

Any help would be appreciated. At this point I'm not sure it's even possible.

Watch is running Tizen 4.0.0.1, and using Tizen Studio 3.0.

答: I had similar problem in the past. I noticed that Chrome since version 54 started block some process and console tab is blank. I found out that jakubkozlowsk@hotmail.com prepared extension Tizen Console Fix which fix this problem. I'm started using it and it helped me</p>


问:
Playing list of mp3 files one by one
I have list of mp3 files and I want them to play after the other.

I have attached my code.
In between I am getting error.

```<code>function playAudio(){
  var au = document.getElementById('saveAudio');
  if($scope.listOfMp3.length > 0){
     $scope.mp3 = $scope.listOfMp3[0];
     au.src = $scope.mp3;
     var promise = au.play();
     if (promise !== undefined) {
        promise.then(function () {
          console.log('Succesfully played');
        }).catch(error => {
          console.log('Problem in playing');
          $scope.listOfMp3.shift();
          playAudio();
        });
     }
     au.addEventListener('ended',function(){
        $scope.listOfMp3.shift();
        playAudio();
     });
  } else {
     au.pause();
  }
}
</code>```

答: To solve this problem, you should get the song end event of the song and on that event, you should pass the function to play the next song.</p>

Title: Playing list of mp3 files one by one

Body:
I have list of mp3 files and I want them to play after the other.

I have attached my code.
In between I am getting error.

function playAudio(){
  var au = document.getElementById('saveAudio');
  if($scope.listOfMp3.length > 0){
     $scope.mp3 = $scope.listOfMp3[0];
     au.src = $scope.mp3;
     var promise = au.play();
     if (promise !== undefined) {
        promise.then(function () {
          console.log('Succesfully played');
        }).catch(error => {
          console.log('Problem in playing');
          $scope.listOfMp3.shift();
          playAudio();
        });
     }
     au.addEventListener('ended',function(){
        $scope.listOfMp3.shift();
        playAudio();
     });
  } else {
     au.pause();
  }
}