问:
Can I access local system env. variables when using vue-cli?
I'm using Vue-cli V3, In my UI I need to pass an environment variable that states if I'm in test mode or not.

I know I can use .env files to define variables, but I have a problem (that is related to our Jenkins build process) that prevents me from using it.

Is there a way to access system env variables?

答:
Yes, you access them the same way that you would inside any normal JS file.</p>

```<code>// server.js
const port = process.env.PORT;
console.log(`Your port is ${port}`);
</code>```

Body:
Yes, you access them the same way that you would inside any normal JS file.

// server.js
const port = process.env.PORT;
console.log(`Your port is ${port}`);


来源: stackexchange

问:
Order of channel blocking
I am trying to understand how channels work in golang. The code I have is very simple but the output is surprising.

As the documentation states: reading and writing from/to a channel is blocking the current goroutine, so I thought writing to a channel would block the channel until the main routine yields.

```<code>package main

func rtn(messages chan<- string) {
    defer close(messages)

    println("p1")
    messages <- "ping1"

    //for i := 0; i < 10000000; i++ { }

    println("p2")
    messages <- "ping2"
}

func main() {
    messages := make(chan string)
    go rtn(messages)

    for msg := range messages {
        println(msg)
    }
}
</code>```

I thought it would print

```<code>p1
ping1
p2
ping2
</code>```

but it actually prints

```<code>p1
p2
ping1
ping2
</code>```

答:
You are using an unbuffered channels, that works as a point of synchronization between the main and second goroutines.

In this case, you only know that when the second goroutine is here messages <- "ping1" the main one is at the line for msg := range messages. Thus, there is no guarantee that main loop reaches println(msg) immediately. I.e., in the meantime the second goroutine could have moved on and reached lines println("p2") and messages <- "ping2".

As a counterexample, I am adding a channel just to enforce the complete synchronization between prints.

```<code>package main

func rtn(messages chan<- string, syncChan chan struct{}) {
    defer close(messages)

    println("p1")
    messages <- "ping1"

    //Wait for main goroutine to print its message
    <-syncChan

    //for i := 0; i < 10000000; i++ { }

    println("p2")
    messages <- "ping2"

    //Wait for main goroutine to print its message
    <-syncChan
}

func main() {
    messages := make(chan string)
    syncChan := make(chan struct{})
    go rtn(messages, syncChan)

    for msg := range messages {
        println(msg)
        //Notify the second goroutine that is free to go
        syncChan <- struct{}{}
    }
}
</code>```

Which prints the output you expected:

```<code>p1
ping1
p2
ping2
</code>```

Here is another example that produce the output you are looking for. In this case the main goroutine is forcefully blocked by the time.Sleep(). This will make the second goroutine be ready to send before the receiver is ready to receive. Therefore, the sender will actually block on the send operation.

```<code>package main

import (
    "time"
)

func rtn(messages chan<- string) {
    defer close(messages)

    println("p1")
    messages <- "ping1"

    //for i := 0; i < 10000000; i++ { }

    println("p2")
    messages <- "ping2"
}

func main() {
    messages := make(chan string)
    go rtn(messages)

    //Put main goroutine to sleep. This will make the
    //sender goroutine ready before the receiver.
    //Therefore it will have to actually block!
    time.Sleep(time.Millisecond * 500)

    for msg := range messages {
        println(msg)
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Order of channel blocking

Body:
I am trying to understand how channels work in golang. The code I have is very simple but the output is surprising.

As the documentation states: reading and writing from/to a channel is blocking the current goroutine, so I thought writing to a channel would block the channel until the main routine yields.

package main

func rtn(messages chan<- string) {
    defer close(messages)

    println("p1")
    messages <- "ping1"

    //for i := 0; i < 10000000; i++ { }

    println("p2")
    messages <- "ping2"
}

func main() {
    messages := make(chan string)
    go rtn(messages)

    for msg := range messages {
        println(msg)
    }
}

I thought it would print

p1
ping1
p2
ping2

but it actually prints

p1
p2
ping1
ping2

Body:
You are using an unbuffered channels, that works as a point of synchronization between the main and second goroutines.

In this case, you only know that when the second goroutine is here messages <- "ping1" the main one is at the line for msg := range messages. Thus, there is no guarantee that main loop reaches println(msg) immediately. I.e., in the meantime the second goroutine could have moved on and reached lines println("p2") and messages <- "ping2".

As a counterexample, I am adding a channel just to enforce the complete synchronization between prints.

package main

func rtn(messages chan<- string, syncChan chan struct{}) {
    defer close(messages)

    println("p1")
    messages <- "ping1"

    //Wait for main goroutine to print its message
    <-syncChan

    //for i := 0; i < 10000000; i++ { }

    println("p2")
    messages <- "ping2"

    //Wait for main goroutine to print its message
    <-syncChan
}

func main() {
    messages := make(chan string)
    syncChan := make(chan struct{})
    go rtn(messages, syncChan)

    for msg := range messages {
        println(msg)
        //Notify the second goroutine that is free to go
        syncChan <- struct{}{}
    }
}

Which prints the output you expected:

p1
ping1
p2
ping2

Here is another example that produce the output you are looking for. In this case the main goroutine is forcefully blocked by the time.Sleep(). This will make the second goroutine be ready to send before the receiver is ready to receive. Therefore, the sender will actually block on the send operation.

package main

import (
    "time"
)

func rtn(messages chan<- string) {
    defer close(messages)

    println("p1")
    messages <- "ping1"

    //for i := 0; i < 10000000; i++ { }

    println("p2")
    messages <- "ping2"
}

func main() {
    messages := make(chan string)
    go rtn(messages)

    //Put main goroutine to sleep. This will make the
    //sender goroutine ready before the receiver.
    //Therefore it will have to actually block!
    time.Sleep(time.Millisecond * 500)

    for msg := range messages {
        println(msg)
    }
}


问:
How many times functions can be deployed per project?
visit resource limits - https://cloud.google.com/functions/quotas

Number of functions : The total number of functions that can be deployed per project- 1000 limit.

its means 1000 separated functions can deployed or each function deployed 1000 versions?

答:
There can be no more than 1,000 active exported Cloud Functions per project.

The number of deployments is not relevant to this limit. But if you ever have more than 1,000 active, exported functions in a single deployment, that deployment will fail.


问:
Anti-Forgery Token was meant for a different claims-based user
I am working on a logout feature in the application we are using ASP.NET Identity login. I can login successfully but when I logout and then try to login again I get the following message:

```<code>The provided anti-forgery token was meant for a different claims-based user than the current user.
</code>```

Here is my logout code:

```<code> public ActionResult Logout()
        {
            SignInManager.Logout();
            return View("Index");
        }

**SignInManager.cs**
 public void Logout()
        {
            AuthenticationManager.SignOut();
        }
</code>```

After the user press the logout button he is taken to the login screen. The url still says "http://localhost:8544/Login/Logout". Since we are on the login screen maybe it should just say "http://localhost:8544/Login".

答:
I didn't have the AuthenticationManager.SignOut command as Sean mentioned in my Login method. I was able to reproduce by clicking on the login button more than once before hte next View loads. I disabled the Login button after the first click to prevent the error.</p>

```<code><button type="submit" onclick="this.disabled=true;this.form.submit();"/>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am working on a logout feature in the application we are using ASP.NET Identity login. I can login successfully but when I logout and then try to login again I get the following message:

The provided anti-forgery token was meant for a different claims-based user than the current user.

Here is my logout code:

 public ActionResult Logout()
        {
            SignInManager.Logout();
            return View("Index");
        }

**SignInManager.cs**
 public void Logout()
        {
            AuthenticationManager.SignOut();
        }

After the user press the logout button he is taken to the login screen. The url still says "http://localhost:8544/Login/Logout". Since we are on the login screen maybe it should just say "http://localhost:8544/Login".

Body:
I didn't have the AuthenticationManager.SignOut command as Sean mentioned in my Login method. I was able to reproduce by clicking on the login button more than once before hte next View loads. I disabled the Login button after the first click to prevent the error.

<button type="submit" onclick="this.disabled=true;this.form.submit();"/>


问:
OData server API and expression syntax, literals, and members
I wish to translate an OData query into a MongoDB query.  I have the olingo-odata4 code and have isolated the calls necessary to take an input string e.g.

```<code>Name eq 'Buzz' and (amount gt 1.99 or size lt 10)
</code>```

and run it through ExpressionParser with my own ExpressionVisitor implementation to intercept the various parse states like visitLiteral and visitBinaryOperator, etc.   From there it is trivial to construct the equivalent MongoDB query.  My main is essentially a trimmed down copy of the odata test drivers, including the mocking of the Edm class for startup:

```<code>ExpressionParser ep = new ExpressionParser(mock(Edm.class), odata);
</code>```

My challenge is that I cannot seem to set up the environment properly for the parser to recognize fields, e.g. members.   I would have hoped that Name eq 'Buzz' would cause the visitMember method to be called for Name but it does not; instead, I get a parse fail with the message: Property paths must follow a structured type.

So my overall question becomes:   If the $filter argument to OData shows the expression syntax as Name eq 'Buzz' then what has to happen in the server implementation to recognize Name as a member?

答:
The parser is unfortunately too closely coupled to the data model, IMHO.   The test drivers I looked at were mostly {5 eq 5} and things like that so I was led astray.  The property path test driver, however, cannot mock the EDM; it must construct a model in order to declare the type (string, etc.) of the fields.   This is why visitMember Member class has the getType() method.   But this means you cannot use the parser to just crack the syntax and dynamically perform actions on the results.

I ended up just creating a very small grammar in ANTLR to parse the OData query expressions and it was easy to convert to MongoDB query language.

Body:
I wish to translate an OData query into a MongoDB query.  I have the olingo-odata4 code and have isolated the calls necessary to take an input string e.g.

Name eq 'Buzz' and (amount gt 1.99 or size lt 10)

and run it through ExpressionParser with my own ExpressionVisitor implementation to intercept the various parse states like visitLiteral and visitBinaryOperator, etc.   From there it is trivial to construct the equivalent MongoDB query.  My main is essentially a trimmed down copy of the odata test drivers, including the mocking of the Edm class for startup:

ExpressionParser ep = new ExpressionParser(mock(Edm.class), odata);

My challenge is that I cannot seem to set up the environment properly for the parser to recognize fields, e.g. members.   I would have hoped that Name eq 'Buzz' would cause the visitMember method to be called for Name but it does not; instead, I get a parse fail with the message: Property paths must follow a structured type.

So my overall question becomes:   If the $filter argument to OData shows the expression syntax as Name eq 'Buzz' then what has to happen in the server implementation to recognize Name as a member?


问:
how to set the size of the element same as that of browser in asp.net
I am making a website and in that i have a master page. I have set the width and height of elements in the master page to suit Firefox browser so it is working fine when i open my page in it but as soon as i shift to Chrome or opera or IE, the page doesn't fit the entire browser area. The page is either smaller (showing white spaces) or larger (getting scroll bar) than the viewing area of the browser and the functioning is obvious because I have hard-coded the width and height to suit Firefox. I also know that when i open the same page in Firefox but in someone else's computer there will be at least some distortion (due to different resolution).

Does anybody has a javascript/c# code which i can use to dynamically set the size of an element as per browser in which it is opening? The following is the html of my Master page. I have highlighted the code in bold which i have set for Firefox.

```
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Untitled Page</title>
    <asp:ContentPlaceHolder id="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <table <b>width="1330"</b> cellspacing="1" cellpadding="1" border="0" align="left">
    <tr>
        <td width="5" rowspan=2> </td>
        <td width="95"> </td>
        <td align="center" width="1230"><img src="Images/dset01titleds.gif" width=392 height=63 border=0 alt="Blank Title w/ Drop Shadow"></td>
    </tr>
    <tr>
        <td align="center" valign="top" width="100">
            <a href="http://"><img src="Images/dset01b01.gif" width=114 height=30 border=0 alt="Home"></a><br>
            <a href="http://"><img src="Images/dset01b02.gif" width=114 height=30 border=0 alt="About Us"></a><br>
            <a href="http://"><img src="Images/dset01b03.gif" width=114 height=30 border=0 alt="Products"></a><br>
            <a href="http://"><img src="Images/dset01b04.gif" width=114 height=30 border=0 alt="Services"></a><br>
            <a href="http://"><img src="Images/dset01b05.gif" width=114 height=30 border=0 alt="Order"></a><br>
            <a href="http://"><img src="Images/dset01b06.gif" width=114 height=30 border=0 alt="Contact"></a><br>
            <a href="http://"><img src="Images/dset01b07blank.gif" width=114 height=30 border=0 alt="Blank"></a><br>
        </td>
        <td valign="top" <b>width="1230px" style="height:440px"</b>>
            <asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
            </asp:ContentPlaceHolder>
        </td>
    </tr>
    <tr style="height:10px"><td colspan=3 align=center>bottom of the screen</td></tr>
    </table>
    </div>
    </form>
</body>
</html>```

答:
You can just use css, with like this:

```<code>width: 100vw; // 100% of viewport width
width: 100vh: // 100% of viewport height
</code>```

This should work because viewport refers to current device

Body:
I am making a website and in that i have a master page. I have set the width and height of elements in the master page to suit Firefox browser so it is working fine when i open my page in it but as soon as i shift to Chrome or opera or IE, the page doesn't fit the entire browser area. The page is either smaller (showing white spaces) or larger (getting scroll bar) than the viewing area of the browser and the functioning is obvious because I have hard-coded the width and height to suit Firefox. I also know that when i open the same page in Firefox but in someone else's computer there will be at least some distortion (due to different resolution).

Does anybody has a javascript/c# code which i can use to dynamically set the size of an element as per browser in which it is opening? The following is the html of my Master page. I have highlighted the code in bold which i have set for Firefox.

<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>Untitled Page</title>
    <asp:ContentPlaceHolder id="head" runat="server">
    </asp:ContentPlaceHolder>

    <form id="form1" runat="server">

    <table width="1330" cellspacing="1" cellpadding="1" border="0" align="left">

        <td valign="top" width="1230px" style="height:440px">
            <asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
            </asp:ContentPlaceHolder>

bottom of the screen

    </form>

Body:
You can just use css, with like this:

width: 100vw; // 100% of viewport width
width: 100vh: // 100% of viewport height

This should work because viewport refers to current device


问:
Why is wire variable causing illegal left-hand side in continuous assignment?
I have read through all similar posts, but none address the issue I'm having, namely that line 41 assign Y[b]=~Y[b]; causes error "Illegal left-hand side in continuous assignment."

I haven't assigned any regs so I don't see what the issue is. If I replace b with an actual number (say, 3) it works fine. But I need b as a variable here.

```<code>// Hamming code 1-bit error correction
module HCG(I,e,O);
  input [4:1] I;   // input BCD
  input [7:1] e;   // noise simulation
  wire [7:1] X;    // Hamming code
  wire [7:1] Y;     // Hamming code after addition of noise
  wire [3:1] P;     // Parity at start
  wire [3:1] S;    // Parity at end
  wire b;        // the error bit
  output [4:1] O;  // corrected output

  assign X[1]=I[1]^I[2]^I[4];   // Hamming code generator
  assign X[2]=I[1]^I[3]^I[4];
  assign X[3]=I[1];
  assign X[4]=I[2]^I[3]^I[4];
  assign X[5]=I[2];
  assign X[6]=I[3];
  assign X[7]=I[4];

  assign P[1]=X[1]; // Parity at start
  assign P[2]=X[2];
  assign P[3]=X[4];

  assign Y[1]=e[1]^X[1]; // noise added
  assign Y[2]=e[2]^X[2];
  assign Y[3]=e[3]^X[3];
  assign Y[4]=e[4]^X[4];
  assign Y[5]=e[5]^X[5];
  assign Y[6]=e[6]^X[6];
  assign Y[7]=e[7]^X[7];

  assign S[1]=Y[3]^Y[5]^Y[7]; // Parity at end
  assign S[2]=Y[3]^Y[6]^Y[7];
  assign S[3]=Y[5]^Y[6]^Y[7];

  assign b=(S[1]!=P[1])? b:b+1; // if parity of 2^0 not the same, add 1 to b
  assign b=(S[2]!=P[2])? b:b+2; // if parity of 2^1 not the same, add 2 to b
  assign b=(S[3]!=P[3])? b:b+4; // if parity of 2^2 not the same, add 4 to b

  assign Y[b]=~Y[b]; // correct the incorrect bit
  assign O[1]=Y[3]; // assigning outputs
  assign O[2]=Y[5];
  assign O[3]=Y[6];
  assign O[4]=Y[7];

endmodule
</code>```

答:
The problem is the continuous assignment you are doing. To quote from the IEEE Std 1800-2012. (Section 10.3) on continuous assignments:

Continuous assignments shall drive values onto nets or variables, both vector (packed) and scalar. This assignment shall occur whenever the value of the right-hand side changes. Continuous assignments provide a way to model combinational logic without specifying an interconnection of gates.

When you do assign Y[b]=~Y[b], the assignment itself automatically causes the right-hand side to change again, which triggers the assignment again.

Body:
I have read through all similar posts, but none address the issue I'm having, namely that line 41 assign Y[b]=~Y[b]; causes error "Illegal left-hand side in continuous assignment."

I haven't assigned any regs so I don't see what the issue is. If I replace b with an actual number (say, 3) it works fine. But I need b as a variable here.

// Hamming code 1-bit error correction
module HCG(I,e,O);
  input [4:1] I;   // input BCD
  input [7:1] e;   // noise simulation
  wire [7:1] X;    // Hamming code
  wire [7:1] Y;     // Hamming code after addition of noise
  wire [3:1] P;     // Parity at start
  wire [3:1] S;    // Parity at end
  wire b;        // the error bit
  output [4:1] O;  // corrected output

  assign X[1]=I[1]^I[2]^I[4];   // Hamming code generator
  assign X[2]=I[1]^I[3]^I[4];
  assign X[3]=I[1];
  assign X[4]=I[2]^I[3]^I[4];
  assign X[5]=I[2];
  assign X[6]=I[3];
  assign X[7]=I[4];

  assign P[1]=X[1]; // Parity at start
  assign P[2]=X[2];
  assign P[3]=X[4];

  assign Y[1]=e[1]^X[1]; // noise added
  assign Y[2]=e[2]^X[2];
  assign Y[3]=e[3]^X[3];
  assign Y[4]=e[4]^X[4];
  assign Y[5]=e[5]^X[5];
  assign Y[6]=e[6]^X[6];
  assign Y[7]=e[7]^X[7];

  assign S[1]=Y[3]^Y[5]^Y[7]; // Parity at end
  assign S[2]=Y[3]^Y[6]^Y[7];
  assign S[3]=Y[5]^Y[6]^Y[7];

  assign b=(S[1]!=P[1])? b:b+1; // if parity of 2^0 not the same, add 1 to b
  assign b=(S[2]!=P[2])? b:b+2; // if parity of 2^1 not the same, add 2 to b
  assign b=(S[3]!=P[3])? b:b+4; // if parity of 2^2 not the same, add 4 to b

  assign Y[b]=~Y[b]; // correct the incorrect bit
  assign O[1]=Y[3]; // assigning outputs
  assign O[2]=Y[5];
  assign O[3]=Y[6];
  assign O[4]=Y[7];

endmodule


问:
Push ViewController in UITabBarController
I have a general question: I have set up a TabBar in my app. When I click on item 1, the TabBar shows a ViewController (VC 1) embedded in a NavigationController. This VC is supposed to push another VC (VC 2) when the user logs out (using firebase   and addStateDidChangeListener). It works great : When I log out the VC1 push VC 2. However when I click again on the item 1 on the tab bar. Guess what? I can see VC 1 while there is no user. I think I have to dismiss VC 1 somehow but I do not know how to implement this function. Can you help me?

答:
Changing view controllers in the navigation controller

When logout button is tapped remove the VC1 from navigation controller and add VC2

```<code>if var viewControllers = self.navigationController?.viewControllers {
    viewControllers.removeLast()
    viewControllers.append(VC2())
    self.navigationController?.setViewControllers(viewControllers, animated: true)
}
</code>```

When logging in again in VC2 again change view controllers

```<code>self.navigationController?.setViewControllers([VC1()], animated: true)
</code>```

Changing view controllers in tab bar controller

Logout

```<code>if var viewControllers = self.tabBarController?.viewControllers {
    let newVC = UINavigationController(rootViewController: VC2())
    newVC.tabBarItem = UITabBarItem(title: "Log In", image: nil, tag: 0)
    viewControllers.removeFirst()
    viewControllers.insert(newVC, at: 0)
    self.tabBarController?.viewControllers = viewControllers
}
</code>```

Login

```<code>if var viewControllers = self.tabBarController?.viewControllers {
    let newVC = UINavigationController(rootViewController: VC1())
    newVC.tabBarItem = UITabBarItem(title: "Home", image: nil, tag: 0)
    viewControllers.removeFirst()
    viewControllers.insert(newVC, at: 0)
    self.tabBarController?.viewControllers = viewControllers
}
</code>```

Body:
Changing view controllers in the navigation controller

When logout button is tapped remove the VC1 from navigation controller and add VC2

if var viewControllers = self.navigationController?.viewControllers {
    viewControllers.removeLast()
    viewControllers.append(VC2())
    self.navigationController?.setViewControllers(viewControllers, animated: true)
}

When logging in again in VC2 again change view controllers

self.navigationController?.setViewControllers([VC1()], animated: true)

Changing view controllers in tab bar controller

Logout

if var viewControllers = self.tabBarController?.viewControllers {
    let newVC = UINavigationController(rootViewController: VC2())
    newVC.tabBarItem = UITabBarItem(title: "Log In", image: nil, tag: 0)
    viewControllers.removeFirst()
    viewControllers.insert(newVC, at: 0)
    self.tabBarController?.viewControllers = viewControllers
}

Login

if var viewControllers = self.tabBarController?.viewControllers {
    let newVC = UINavigationController(rootViewController: VC1())
    newVC.tabBarItem = UITabBarItem(title: "Home", image: nil, tag: 0)
    viewControllers.removeFirst()
    viewControllers.insert(newVC, at: 0)
    self.tabBarController?.viewControllers = viewControllers
}


问:
How many wiki instances to install?
I've been asked to install Mediawiki to house documentation for a company intranet. Furthermore, I've been asked to install several instances - one per contributing group: non-technical users get one, developers one, management one, etc. The idea is to provide separate web spaces for each group. Is there a way to achieve separation within one instance?

答: If you do end up going with one wiki, with multiple namespaces, make sure to include the $wgNamespacesToBeSearchedDefault in your local settings, so that when a new user account is created it is set to automatically search the new namespaces by default.</p>

ContentLicense: CC BY-SA 2.5

Title: How many wiki instances to install?

LastEditorDisplayName: nzpcmad

OwnerDisplayName: Adrian Archer


问:
How to create mock/ dummy Initial context for Junit tests out of container
I am facing big problem instantiating weblogic Initial context while running jUnit tests.
Application uses Spring / hibernate / weblogic.
In application code,  methods  uses JMS proxy to send messages to JMS, Queues are setup on weblogic.

My problem is while JUnit tests currently I need to keep weblogic server running  on local machine just to initialize WeblogicInitialContext  which is  used in JMS proxies. My junit test don't need to send anything to server, NO JMS , NO datasources. All are handeled by spring unit test framework.
I want to decouple/ get rid of Weblogic for my junit tests.  Please suggest.
Here is my code:

This is my test application context XML:

```<code><beans xmlns="http://www.springframework.org/schema/beans"
...
>

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

<util:properties id="webLogicInitialContext">
    <prop key="java.naming.factory.initial">weblogic.jndi.WLInitialContextFactory</prop>
    <prop key="java.naming.provider.url">t3://localhost:7001</prop>
    <prop key="java.naming.security.principal">admin</prop>
    <prop key="java.naming.security.credentials">password</prop>
</util:properties>

<jee:jndi-lookup id="responseProxyConnectionFactory"
    jndi-name="jms/ConnectionFactory" environment-ref="webLogicInitialContext"/>

<bean id="responseProxyJmsTemplate" class="org.springframework.jms.core.JmsTemplate">
    <property name="connectionFactory"
        ref="responseProxyConnectionFactory" />
</bean>
</beans>
</code>```

This is One  Java class methods :

```<code>public class Order {
    public void addOrder(OrderRequest addOrderRequest) {
        PurchaseOrder newOrder = orderHelper.createOrder(addOrderRequest);
        orderDaoHibernate.addOrder(newOrder);
        responseProxy.send(newOrder);

    }
}
</code>```

My Test :

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners( {TransactionalTestExecutionListener.class, DependencyInjectionTestExecutionListener.class,DirtiesContextTestExecutionListener.class })
@ContextConfiguration(locations={"/test-application-context.xml"})
@TransactionConfiguration(defaultRollback=true)

public class TestOrder {

    @Test
    @Transactional
    public void testMyOrder(){
        Order ord = new Order();
        OrderRequest req = new OrderRequest();
        ....
        ord.addOrder(req);
    }

}
</code>```

If I run this test the Spring framework try to load the WeblogicInitialContext , and if local weblogic not running it throws exceptions.

I don't want to send any JMS message when I call this method from Junit.
How can I create dummy WeblogicInitialContext.

Please help.

Some part of Exception;

```<code>Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean     with name 'responseProxyConnectionFactory': Invocation of init method failed; nested exception is javax.naming.CommunicationException [Root exception is java.net.ConnectException: t3://localhost:7001: Destination unreachable; nested exception is:
</code>```

答:
If this were a common context that you're sharing with your production application, I would say that can avoid instantiating the database and JMS stuff by moving the JMS related beans into a different context that is loaded only by your main application and not test code.

But since this is a dedicated test context, you can probably simply remove those beans that are not needed, such as the weblogic config and the jndi context lookup bean. If you still need a jms queue to test again, you can use a mock, as described in this SO question.

Body:
I am facing big problem instantiating weblogic Initial context while running jUnit tests.
Application uses Spring / hibernate / weblogic.
In application code,  methods  uses JMS proxy to send messages to JMS, Queues are setup on weblogic.

My problem is while JUnit tests currently I need to keep weblogic server running  on local machine just to initialize WeblogicInitialContext  which is  used in JMS proxies. My junit test don't need to send anything to server, NO JMS , NO datasources. All are handeled by spring unit test framework.
I want to decouple/ get rid of Weblogic for my junit tests.  Please suggest.
Here is my code:

This is my test application context XML:

<beans xmlns="http://www.springframework.org/schema/beans"
...
>

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

<util:properties id="webLogicInitialContext">
    <prop key="java.naming.factory.initial">weblogic.jndi.WLInitialContextFactory</prop>
    <prop key="java.naming.provider.url">t3://localhost:7001</prop>
    <prop key="java.naming.security.principal">admin</prop>
    <prop key="java.naming.security.credentials">password</prop>
</util:properties>

<jee:jndi-lookup id="responseProxyConnectionFactory"
    jndi-name="jms/ConnectionFactory" environment-ref="webLogicInitialContext"/>

<bean id="responseProxyJmsTemplate" class="org.springframework.jms.core.JmsTemplate">
    <property name="connectionFactory"
        ref="responseProxyConnectionFactory" />
</bean>
</beans>

This is One  Java class methods :

public class Order {
    public void addOrder(OrderRequest addOrderRequest) {
        PurchaseOrder newOrder = orderHelper.createOrder(addOrderRequest);
        orderDaoHibernate.addOrder(newOrder);
        responseProxy.send(newOrder);

    }
}

My Test :

@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners( {TransactionalTestExecutionListener.class, DependencyInjectionTestExecutionListener.class,DirtiesContextTestExecutionListener.class })
@ContextConfiguration(locations={"/test-application-context.xml"})
@TransactionConfiguration(defaultRollback=true)

public class TestOrder {

    @Test
    @Transactional
    public void testMyOrder(){
        Order ord = new Order();
        OrderRequest req = new OrderRequest();
        ....
        ord.addOrder(req);
    }

}

If I run this test the Spring framework try to load the WeblogicInitialContext , and if local weblogic not running it throws exceptions.

I don't want to send any JMS message when I call this method from Junit.
How can I create dummy WeblogicInitialContext.

Please help.

Some part of Exception;

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean     with name 'responseProxyConnectionFactory': Invocation of init method failed; nested exception is javax.naming.CommunicationException [Root exception is java.net.ConnectException: t3://localhost:7001: Destination unreachable; nested exception is:


问:
Which is more performant? Custom SQL or PowerBI joins/manipulation
I'm in the process of starting to build a new dashboarding project, and wanted some guidance with respect to some best processes regarding data ingestion into PowerBI. My company uses MySQL for data.

Most common dashboarding software (Tableau and PowerBI, not sure of others) has features to use a GUI to do the equivalent of SQL commands. They also have the option to just do straight custom SQL to get data as well.

Is there a performance advantage to using custom SQL vs the GUI? Does the GUI take advantage of indexing?

答:
I don't know as much about Tableau, but with Power BI, most of the GUI transformations are converted to SQL as the "native query" that gets sent back to the server. You can read more about this here:

http://blog.pragmaticworks.com/power-bi-checking-query-folding-with-view-native-query

Basically, using the Power BI GUI is just as efficient as custom SQL unless it's folding inefficiently or you are doing transformations that can't automatically be folded.


问:
accessibility support in jquery blockUI plugin
I just wanted to know if blockUI provide any support for differently-abled / blind users ?
For example, when loading spinner is visible on screen, an announcement should be made for screen reader users eg. 'alert loading content' or something similar.

Please let me if same is already implemented or not?

```<code><span aria-live="assertive" id="" class="sr-only" role="alert" style="display:none;">something is loading</span>
</code>```

this span should be shown if loading spinner is visible

答:
Just using a demo, the plugin is not completely accessible. It would require extra work since the modal dialog does not properly handle all keyboard interaction at all. A user should be able to close the dialog with the Escape key. As well, clicking on the 'shade' area should close the dialog, and there's no close button for the pop-up. The user is forced into a choice.

Speaking to the animation specifically, I would suggest following the guidelines for timed media specific to video-only since there's an animation, and provide a clear explanation of the loader, but I would avoid using this method if at all possible. There are much clearer and cleaner methods for modals that are WCAG Compliant and still actively supported.

Time-Based Media: https://www.w3.org/TR/WCAG21/#time-based-media

Body:
I just wanted to know if blockUI provide any support for differently-abled / blind users ?
For example, when loading spinner is visible on screen, an announcement should be made for screen reader users eg. 'alert loading content' or something similar.

Please let me if same is already implemented or not?

something is loading

this span should be shown if loading spinner is visible


问:
how can i change the hint_text of TextInput box which is in .kv file , from .py file
i want to change the hint_text of textbox which is in .kv on the calling function which is define inside the .py file

I know the label text can be changed like this
  self.root.ids.tm.text = '[color=#FF0000]Time over[/color]'
but same does not work in case of textbox ex
  self.root.ids.some_id.hint_text:"some special text "

答:
Changing from within App class

Use self.root.ids.text_input_id.hint_text = "Something special"

Changing from within root class

Use self.ids.text_input_id.hint_text = "Something special"

Example

main.py

```<code>from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder

Builder.load_string("""
<HintTextDemo>:
    orientation: 'vertical'
    TextInput:
        id: text_input
        hint_text: 'Write here'
    Button:
        text: 'Change hint text'
        on_release: app.change_hint_text()
""")

class HintTextDemo(BoxLayout):
    pass

class TestApp(App):

    def build(self):
        return HintTextDemo()

    def change_hint_text(self):
        self.root.ids.text_input.hint_text = 'Type something here'

if __name__ == "__main__":
    TestApp().run()
</code>```

Output

Body:
Changing from within App class

Use self.root.ids.text_input_id.hint_text = "Something special"

Changing from within root class

Use self.ids.text_input_id.hint_text = "Something special"

Example

main.py

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder

Builder.load_string("""
<HintTextDemo>:
    orientation: 'vertical'
    TextInput:
        id: text_input
        hint_text: 'Write here'
    Button:
        text: 'Change hint text'
        on_release: app.change_hint_text()
""")

class HintTextDemo(BoxLayout):
    pass

class TestApp(App):

    def build(self):
        return HintTextDemo()

    def change_hint_text(self):
        self.root.ids.text_input.hint_text = 'Type something here'

if __name__ == "__main__":
    TestApp().run()

Output


问:
external IP not being generated for elastic
I followed the commands mentioned on this page...

https://www.elastic.co/guide/en/cloud-on-k8s/current/index.html

elastic service is stared successfully. But I do not see external-ip

```<code>#  /usr/local/bin/kubectl --kubeconfig="wzone2.yaml" get service
NAME                      TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)    AGE
kubernetes                ClusterIP   10.245.0.1      <none>        443/TCP    10m
quickstart-es             ClusterIP   10.245.97.209   <none>        9200/TCP   3m11s
quickstart-es-discovery   ClusterIP   None            <none>        9300/TCP   3m11s
</code>```

I tried port forwarding command but that did not help.

kubectl port-forward service/quickstart-es 9200

How do I connect to this elastic server?

答: ClusterIP services are only available from inside the cluster. To make it visible from the outside you would need to change it to LoadBalancer type, and have an implementation of that available (read: be running on a cloud provider or use MetalLB).</p>

Body:
I followed the commands mentioned on this page...

https://www.elastic.co/guide/en/cloud-on-k8s/current/index.html

elastic service is stared successfully. But I do not see external-ip

#  /usr/local/bin/kubectl --kubeconfig="wzone2.yaml" get service
NAME                      TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)    AGE
kubernetes                ClusterIP   10.245.0.1      <none>        443/TCP    10m
quickstart-es             ClusterIP   10.245.97.209   <none>        9200/TCP   3m11s
quickstart-es-discovery   ClusterIP   None            <none>        9300/TCP   3m11s

I tried port forwarding command but that did not help.

kubectl port-forward service/quickstart-es 9200

How do I connect to this elastic server?


问:
How to resolve: The provided anti-forgery token was meant for a different claims-based user than the current user
I am getting this error:

```<code>The provided anti-forgery token was meant for a different claims-based user than the current user.
</code>```

and I am not sure how to correct this..

I have a MVC5 site and in this site I have a login page.

This is the scenario that it occurs on.

User AAA logs in. (No issues)

I attempt to access a view where the user does not have access.

I have the class decorated with an Authorize(Roles="aa")

The view then logs the user off and puts them back to the login page.

User AAA logs in. (This time I get the error mentioned above)

To note:

I am using customErrors and this is where I see the error message.

When I log the user out I am running this method:

```<code>[HttpGet]
public void SignOut()
{
    IAuthenticationManager authenticationManager = HttpContext.GetOwinContext().Authentication;
    authenticationManager.SignOut(MyAuthentication.ApplicationCookie);
}
</code>```

Could I possibly be missing something on the SignOut?

UPDATE:

This only occurs because of step #2 listed above.

If I log in, then log out (calling same code) then log back in, then I do not have this issue.

答:
I was able to reproduce by clicking on the login button more than once before the next View loads. I disabled the Login button after the first click to prevent the error.</p>

```<code><button type="submit" onclick="this.disabled=true;this.form.submit();"/>
</code>```

Body:
I am getting this error:

The provided anti-forgery token was meant for a different claims-based user than the current user.

and I am not sure how to correct this..

I have a MVC5 site and in this site I have a login page.

This is the scenario that it occurs on.

User AAA logs in. (No issues)

I attempt to access a view where the user does not have access.

I have the class decorated with an Authorize(Roles="aa")

The view then logs the user off and puts them back to the login page.

User AAA logs in. (This time I get the error mentioned above)

To note:

I am using customErrors and this is where I see the error message.

When I log the user out I am running this method:

[HttpGet]
public void SignOut()
{
    IAuthenticationManager authenticationManager = HttpContext.GetOwinContext().Authentication;
    authenticationManager.SignOut(MyAuthentication.ApplicationCookie);
}

Could I possibly be missing something on the SignOut?

UPDATE:

This only occurs because of step #2 listed above.

If I log in, then log out (calling same code) then log back in, then I do not have this issue.

Body:
I was able to reproduce by clicking on the login button more than once before the next View loads. I disabled the Login button after the first click to prevent the error.

<button type="submit" onclick="this.disabled=true;this.form.submit();"/>


问:
php script is executed multiple times per browser request
I have a virtual host in apache. I am on ubuntu 10.04 using LAMP.

```<code><VirtualHost *:80>
DocumentRoot /home/username/websites/site_folder
ServerName www.site_folder.com
ServerAlias site_folder.com
    <Directory /home/username/websites/site_folder/>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Order allow,deny
        allow from all
    </Directory>
</VirtualHost>
</code>```

I added in /etc/hosts the line:

```<code>127.0.0.1 site_folder.com
</code>```

Inside the folder of the vhost I added a php script named one.php, having the code:

```<code><?php
$today = getdate();
$handle = fopen("logs/logs.txt", "a");
fwrite($handle, $today['mday'].'/'.$today['mon'].'/'.$today['year']." this is a log post"." \n");
fclose($handle);
?>
</code>```

when I run the script from the browser, http://localhost/one.php or site_folder.com/one.php, the logs.txt has logged the same message 3 times:

```<code>12/4/2011 this is a log post
12/4/2011 this is a log post
12/4/2011 this is a log post
</code>```

Using netbeans debugger I saw that that the script is actually repeated 3 times (after reaching the end of the script it continues from the start of the same script->one.php)
No .htaccess exists inside the folder.

What I have noticed is that the $_SERVER['REQUEST_URI'] changes a bit each execution/repetition:

```<code>1)$_SERVER['REQUEST_URI'] => /one.php?XDEBUG_SESSION_START=netbeans-xdebug
2)$_SERVER['REQUEST_URI'] => /one.php
3)$_SERVER['REQUEST_URI'] => /one.php
</code>```

I need to log my message only once.

I added the uncommented directives from apache2.conf :

```<code>ServerRoot "/etc/apache2"
LockFile /var/lock/apache2/accept.lock
PidFile ${APACHE_PID_FILE}
Timeout 300
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 15
<IfModule mpm_prefork_module>
    StartServers          5
    MinSpareServers       5
    MaxSpareServers      10
    MaxClients          150
    MaxRequestsPerChild   0
</IfModule>
<IfModule mpm_worker_module>
    StartServers          2
    MinSpareThreads      25
    MaxSpareThreads      75
    ThreadLimit          64
    ThreadsPerChild      25
    MaxClients          150
    MaxRequestsPerChild   0
</IfModule>
<IfModule mpm_event_module>
    StartServers          2
    MaxClients          150
    MinSpareThreads      25
    MaxSpareThreads      75
    ThreadLimit          64
    ThreadsPerChild      25
    MaxRequestsPerChild   0
</IfModule>
User ${APACHE_RUN_USER}
Group ${APACHE_RUN_GROUP}
AccessFileName .htaccess
<Files ~ "^\.ht">
    Order allow,deny
    Deny from all
    Satisfy all
</Files>
DefaultType text/plain
HostnameLookups Off
ErrorLog /var/log/apache2/error.log
LogLevel warn
Include /etc/apache2/mods-enabled/*.load
Include /etc/apache2/mods-enabled/*.conf
Include /etc/apache2/httpd.conf
Include /etc/apache2/ports.conf
LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined
LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %O" common
LogFormat "%{Referer}i -> %U" referer
LogFormat "%{User-agent}i" agent
CustomLog /var/log/apache2/other_vhosts_access.log vhost_combined
Include /etc/apache2/conf.d/
Include /etc/apache2/sites-enabled/
</code>```

答:
I suppose you tried it out, but..., have you tried to do it from a real server, instead a localhost one? I mean, the trouble maybe is in you Apache Server...

I don't know, just read it as a simple idea to test.

Body:
I have a virtual host in apache. I am on ubuntu 10.04 using LAMP.

<VirtualHost *:80>
DocumentRoot /home/username/websites/site_folder
ServerName www.site_folder.com
ServerAlias site_folder.com
    <Directory /home/username/websites/site_folder/>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Order allow,deny
        allow from all
    </Directory>
</VirtualHost>

I added in /etc/hosts the line:

127.0.0.1 site_folder.com

Inside the folder of the vhost I added a php script named one.php, having the code:

<?php
$today = getdate();
$handle = fopen("logs/logs.txt", "a");
fwrite($handle, $today['mday'].'/'.$today['mon'].'/'.$today['year']." this is a log post"." \n");
fclose($handle);
?>

when I run the script from the browser, http://localhost/one.php or site_folder.com/one.php, the logs.txt has logged the same message 3 times:

12/4/2011 this is a log post
12/4/2011 this is a log post
12/4/2011 this is a log post

Using netbeans debugger I saw that that the script is actually repeated 3 times (after reaching the end of the script it continues from the start of the same script->one.php)
No .htaccess exists inside the folder.

What I have noticed is that the $_SERVER['REQUEST_URI'] changes a bit each execution/repetition:

1)$_SERVER['REQUEST_URI'] => /one.php?XDEBUG_SESSION_START=netbeans-xdebug
2)$_SERVER['REQUEST_URI'] => /one.php
3)$_SERVER['REQUEST_URI'] => /one.php

I need to log my message only once.

I added the uncommented directives from apache2.conf :

ServerRoot "/etc/apache2"
LockFile /var/lock/apache2/accept.lock
PidFile ${APACHE_PID_FILE}
Timeout 300
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 15
<IfModule mpm_prefork_module>
    StartServers          5
    MinSpareServers       5
    MaxSpareServers      10
    MaxClients          150
    MaxRequestsPerChild   0
</IfModule>
<IfModule mpm_worker_module>
    StartServers          2
    MinSpareThreads      25
    MaxSpareThreads      75
    ThreadLimit          64
    ThreadsPerChild      25
    MaxClients          150
    MaxRequestsPerChild   0
</IfModule>
<IfModule mpm_event_module>
    StartServers          2
    MaxClients          150
    MinSpareThreads      25
    MaxSpareThreads      75
    ThreadLimit          64
    ThreadsPerChild      25
    MaxRequestsPerChild   0
</IfModule>
User ${APACHE_RUN_USER}
Group ${APACHE_RUN_GROUP}
AccessFileName .htaccess
<Files ~ "^\.ht">
    Order allow,deny
    Deny from all
    Satisfy all
</Files>
DefaultType text/plain
HostnameLookups Off
ErrorLog /var/log/apache2/error.log
LogLevel warn
Include /etc/apache2/mods-enabled/*.load
Include /etc/apache2/mods-enabled/*.conf
Include /etc/apache2/httpd.conf
Include /etc/apache2/ports.conf
LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined
LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %O" common
LogFormat "%{Referer}i -> %U" referer
LogFormat "%{User-agent}i" agent
CustomLog /var/log/apache2/other_vhosts_access.log vhost_combined
Include /etc/apache2/conf.d/
Include /etc/apache2/sites-enabled/


问:
Word frequency elegantly in Powershell
Donald Knuth once got the task to write a literate program computing the word frequency of a file.

Read a file of text, determine the n most frequently used words, and print out a sorted list of those words along with their frequencies.

Doug McIlroy famously rewrote the 10 pages of Pascal in a few lines of sh:

```<code>tr -cs A-Za-z '\n' |
tr A-Z a-z |
sort |
uniq -c |
sort -rn |
sed ${1}q
</code>```

As a little exercise, I converted this to Powershell:

```<code>(-split ((Get-Content -Raw test.txt).ToLower() -replace '[^a-zA-Z]',' ')) |
  Group-Object |
  Sort-Object -Property count -Descending |
  Select-Object -First $Args[0] |
  Format-Table count, name
</code>```

I like that Powershell combines sort | uniq -c into a single Group-Object.

The first line looks ugly, so I wonder if it can be written more elegantly? Maybe there is a way to load the file with a regex delimiter somehow?

One obvious way to shorten the code would be to uses the aliases, but that does not help readability.

答:
I would do it this way.

```<code>PS C:\users\me> Get-Content words.txt
One one
two
two
three,three.
two;two

PS C:\users\me> (Get-Content words.txt) -Split '\W' | Group-Object

Count Name                      Group
----- ----                      -----
    2 One                       {One, one}
    4 two                       {two, two, two, two}
    2 three                     {three, three}
    1                           {}
</code>```

EDIT:  Some code from Bruce Payette's Windows Powershell in Action

```<code># top 10 most frequent words, hash table
$s = gc songlist.txt
$s = [string]::join(" ", $s)
$words = $s.Split(" `t", [stringsplitoptions]::RemoveEmptyEntries)
$uniq = $words | sort -Unique
$words | % {$h=@{}} {$h[$_] += 1}
$frequency = $h.keys | sort {$h[$_]}
-1..-10 | %{ $frequency[$_]+" "+$h[$frequency[$_]]}

# or
$grouped = $words | group | sort count
$grouped[-1..-10]
</code>```

Title: Word frequency elegantly in Powershell

Body:
Donald Knuth once got the task to write a literate program computing the word frequency of a file.

Read a file of text, determine the n most frequently used words, and print out a sorted list of those words along with their frequencies.

Doug McIlroy famously rewrote the 10 pages of Pascal in a few lines of sh:

tr -cs A-Za-z '\n' |
tr A-Z a-z |
sort |
uniq -c |
sort -rn |
sed ${1}q

As a little exercise, I converted this to Powershell:

(-split ((Get-Content -Raw test.txt).ToLower() -replace '[^a-zA-Z]',' ')) |
  Group-Object |
  Sort-Object -Property count -Descending |
  Select-Object -First $Args[0] |
  Format-Table count, name

I like that Powershell combines sort | uniq -c into a single Group-Object.

The first line looks ugly, so I wonder if it can be written more elegantly? Maybe there is a way to load the file with a regex delimiter somehow?

One obvious way to shorten the code would be to uses the aliases, but that does not help readability.

Body:
I would do it this way.

PS C:\users\me> Get-Content words.txt
One one
two
two
three,three.
two;two

PS C:\users\me> (Get-Content words.txt) -Split '\W' | Group-Object

Count Name                      Group
----- ----                      -----
    2 One                       {One, one}
    4 two                       {two, two, two, two}
    2 three                     {three, three}
    1                           {}

EDIT:  Some code from Bruce Payette's Windows Powershell in Action

# top 10 most frequent words, hash table
$s = gc songlist.txt
$s = [string]::join(" ", $s)
$words = $s.Split(" `t", [stringsplitoptions]::RemoveEmptyEntries)
$uniq = $words | sort -Unique
$words | % {$h=@{}} {$h[$_] += 1}
$frequency = $h.keys | sort {$h[$_]}
-1..-10 | %{ $frequency[$_]+" "+$h[$frequency[$_]]}

# or
$grouped = $words | group | sort count
$grouped[-1..-10]


问:
the router-link config's target do not generate to html code
I config the Vue table header params like below:

```<code>render: (h, params) => {

      return h(
        'router-link',
        {
          props: {
            tag: 'a',
            target: '_blank',
            to: {
              name: 'physicalserverDetails',
              query: {id: params.row.id}
            },

          }
        },
        params.row.name
      )
    }
</code>```

but when I check the generated html code, there did not generate the target param:

```<code><a href="/physicalserverDetails?id=193" class="">CD-Z12</a>
</code>```

is there anything I config wrong?

答:
Normal HTML attributes such as target must be passed inside an attrs object as stated in the vue.js documentation. As target is passed as a prop in your snippet, it can't appear in the generated anchor tag.

Try the snippet below :

```<code>render: (h, params) => {
  return h(
    'router-link',
    {
      attrs: {
       target: '_blank'
      },
      props: {
        to: {
          name: 'physicalserverDetails',
          query: {id: params.row.id}
        }
      }
    },
    params.row.name
  )
}
</code>```

Body:
I config the Vue table header params like below:

render: (h, params) => {

      return h(
        'router-link',
        {
          props: {
            tag: 'a',
            target: '_blank',
            to: {
              name: 'physicalserverDetails',
              query: {id: params.row.id}
            },

          }
        },
        params.row.name
      )
    }

but when I check the generated html code, there did not generate the target param:

CD-Z12

is there anything I config wrong?

Body:
Normal HTML attributes such as target must be passed inside an attrs object as stated in the vue.js documentation. As target is passed as a prop in your snippet, it can't appear in the generated anchor tag.

Try the snippet below :

render: (h, params) => {
  return h(
    'router-link',
    {
      attrs: {
       target: '_blank'
      },
      props: {
        to: {
          name: 'physicalserverDetails',
          query: {id: params.row.id}
        }
      }
    },
    params.row.name
  )
}


问:
UWP TreeView ItemTempleteSelector is not executed
TreeView on which I'm working does not execute ItemTemplateSelector, no matter I had declared it in XAML and code behind.

Here is my Page resources in XAML:

```<code><DataTemplate x:Key="FolderTemplate" x:DataType="localdata:FolderInfo">
        <TreeViewItem ItemsSource="{x:Bind subFolders}">
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="#Folder#" />
                <Image Width="20" Source="Assets/img2.png"/>
                <TextBlock Text="{x:Bind  FolderName }" />
            </StackPanel>
        </TreeViewItem>
    </DataTemplate>

    <DataTemplate x:Key="FileTemplate" x:DataType="localdata:FolderInfo">
        <TreeViewItem>
            <StackPanel Orientation="Horizontal">
                <Image Width="20" Source="Assets/img3.png"/>
                <TextBlock Text="{x:Bind FolderName}"/>
            </StackPanel>
        </TreeViewItem>
    </DataTemplate>

    <localdata:ExplorerItemTemplateSelector
        x:Key="ExplorerItemTemplateSelector"
        FolderTemplate="{StaticResource FolderTemplate}"
        FileTemplate="{StaticResource FileTemplate}" />
</code>```

Here is the TreeView declaration, it does use Style but it is not of importance to this review:

```<code><TreeView
        x:Name="treeview" Grid.Row="2" ItemsSource="{Binding storageFolders,Mode=OneWay}"
        Style="{StaticResource TreeViewStyle1}"
        ItemTemplateSelector="{StaticResource ExpolrerItemTemplateSelector}"
        >
            <TreeView.ItemTemplate>
                <DataTemplate x:DataType="localdata:FolderInfo">
                    <TreeViewItem ItemsSource="{x:Bind subFolders}" Content="{x:Bind FolderName}"/>
                </DataTemplate>
            </TreeView.ItemTemplate>
        </TreeView>
</code>```

and in my code behind file:

```<code>public class ExplorerItemTemplateSelector : DataTemplateSelector
{
    public DataTemplate FolderTemplate { get; set; }
    public DataTemplate FileTemplate { get; set; }

    protected override DataTemplate SelectTemplateCore(object item, DependencyObject container)
    {
        var explorerItem = (FolderInfo)item;
        if (explorerItem.IsFolder == true) return FolderTemplate;

        return FileTemplate;
    }
}
</code>```

Bindings works fine. I had omitted VM from this review to remove clutter. What is also interesting is that if I remove ItemTemplateSelector="{StaticResource ExpolrerItemTemplateSelector}" from declaration of TreeView, it works without any change in visual or functional sense.

答:
The DataTemplateSelector type actually has two different SelectTemplateCore method overloads and TreeView uses the second one, with just one object parameter:

```<code>public class ExplorerItemTemplateSelector : DataTemplateSelector
{
    public DataTemplate FolderTemplate { get; set; }
    public DataTemplate FileTemplate { get; set; }

    protected override DataTemplate SelectTemplateCore(object item)
    {
        var explorerItem = (FolderInfo)item;
        if (explorerItem.IsFolder == true) return FolderTemplate;

        return FileTemplate;
    }
}
</code>```

In this form, the method should be called as expected.

Body:
TreeView on which I'm working does not execute ItemTemplateSelector, no matter I had declared it in XAML and code behind.

Here is my Page resources in XAML:

<DataTemplate x:Key="FolderTemplate" x:DataType="localdata:FolderInfo">
        <TreeViewItem ItemsSource="{x:Bind subFolders}">
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="#Folder#" />
                <Image Width="20" Source="Assets/img2.png"/>
                <TextBlock Text="{x:Bind  FolderName }" />
            </StackPanel>
        </TreeViewItem>
    </DataTemplate>

    <DataTemplate x:Key="FileTemplate" x:DataType="localdata:FolderInfo">
        <TreeViewItem>
            <StackPanel Orientation="Horizontal">
                <Image Width="20" Source="Assets/img3.png"/>
                <TextBlock Text="{x:Bind FolderName}"/>
            </StackPanel>
        </TreeViewItem>
    </DataTemplate>

    <localdata:ExplorerItemTemplateSelector
        x:Key="ExplorerItemTemplateSelector"
        FolderTemplate="{StaticResource FolderTemplate}"
        FileTemplate="{StaticResource FileTemplate}" />

Here is the TreeView declaration, it does use Style but it is not of importance to this review:

<TreeView
        x:Name="treeview" Grid.Row="2" ItemsSource="{Binding storageFolders,Mode=OneWay}"
        Style="{StaticResource TreeViewStyle1}"
        ItemTemplateSelector="{StaticResource ExpolrerItemTemplateSelector}"
        >
            <TreeView.ItemTemplate>
                <DataTemplate x:DataType="localdata:FolderInfo">
                    <TreeViewItem ItemsSource="{x:Bind subFolders}" Content="{x:Bind FolderName}"/>
                </DataTemplate>
            </TreeView.ItemTemplate>
        </TreeView>

and in my code behind file:

public class ExplorerItemTemplateSelector : DataTemplateSelector
{
    public DataTemplate FolderTemplate { get; set; }
    public DataTemplate FileTemplate { get; set; }

    protected override DataTemplate SelectTemplateCore(object item, DependencyObject container)
    {
        var explorerItem = (FolderInfo)item;
        if (explorerItem.IsFolder == true) return FolderTemplate;

        return FileTemplate;
    }
}

Bindings works fine. I had omitted VM from this review to remove clutter. What is also interesting is that if I remove ItemTemplateSelector="{StaticResource ExpolrerItemTemplateSelector}" from declaration of TreeView, it works without any change in visual or functional sense.

Body:
The DataTemplateSelector type actually has two different SelectTemplateCore method overloads and TreeView uses the second one, with just one object parameter:

public class ExplorerItemTemplateSelector : DataTemplateSelector
{
    public DataTemplate FolderTemplate { get; set; }
    public DataTemplate FileTemplate { get; set; }

    protected override DataTemplate SelectTemplateCore(object item)
    {
        var explorerItem = (FolderInfo)item;
        if (explorerItem.IsFolder == true) return FolderTemplate;

        return FileTemplate;
    }
}

In this form, the method should be called as expected.


问:
How to retrieve the value(s) of a parameter declared with vararg in an enum in Kotlin
I am new to Kotlin and I have an enum containing many values, those values refer to different states my application has.

Now I need to log something whenever the app enters a state but some state in the enum can log more than one thing (based on other parameters coming from outside the app) and some state does not need to log something.

Here is my enum:

```<code>enum class StateName(vararg log: String) {
    FIRST_CONNECTION(), // no parameter here
    AUTHORIZATION_CHECK("message 1", "message 2"),
    HANDSHAKE_SUCCESS("message")
    //...
}
</code>```

If had declared the enum with a single obligatory parameter StateName(var log: String) I could have used HANDSHAKE_SUCCESS.log to retrieve its value but with vararg the IDE (android studio) does not find log at all.

So how can I retrieve my string with something like log[0]?

Note:

My enum is already defined (without parameters) and in use in my application and I can't use a different method of changing the actual state/adding a logging functionality

I need to use Kotlin even if I just started learning as the project was written with this language so I just want to know if (and how) I can do that.

答:
You need to create a variable inside enum which will hold all the arguments like below:

```<code>  enum class StateName( vararg log: String) {
        FIRST_CONNECTION(), // no parameter here
        AUTHORIZATION_CHECK("message 1", "message 2"),
        HANDSHAKE_SUCCESS("message");

        public var logParams:Array<out String>

        init{
             logParams=log
        }

    }
</code>```

And to print the param corresponding to particular enum, you can iterate like below:

```<code> for (item in StateName.AUTHORIZATION_CHECK.logParams) {
           println("item = "+item)
 }
</code>```

Body:
I am new to Kotlin and I have an enum containing many values, those values refer to different states my application has.

Now I need to log something whenever the app enters a state but some state in the enum can log more than one thing (based on other parameters coming from outside the app) and some state does not need to log something.

Here is my enum:

enum class StateName(vararg log: String) {
    FIRST_CONNECTION(), // no parameter here
    AUTHORIZATION_CHECK("message 1", "message 2"),
    HANDSHAKE_SUCCESS("message")
    //...
}

If had declared the enum with a single obligatory parameter StateName(var log: String) I could have used HANDSHAKE_SUCCESS.log to retrieve its value but with vararg the IDE (android studio) does not find log at all.

So how can I retrieve my string with something like log[0]?

Note:

My enum is already defined (without parameters) and in use in my application and I can't use a different method of changing the actual state/adding a logging functionality

I need to use Kotlin even if I just started learning as the project was written with this language so I just want to know if (and how) I can do that.

Body:
You need to create a variable inside enum which will hold all the arguments like below:

  enum class StateName( vararg log: String) {
        FIRST_CONNECTION(), // no parameter here
        AUTHORIZATION_CHECK("message 1", "message 2"),
        HANDSHAKE_SUCCESS("message");

        public var logParams:Array<out String>

        init{
             logParams=log
        }

    }

And to print the param corresponding to particular enum, you can iterate like below:

 for (item in StateName.AUTHORIZATION_CHECK.logParams) {
           println("item = "+item)
 }


问:
How can i input some music in my html code?
Im new here and also i'm a student from university of Kavala. I was starting learning about codes such us html and css and i was wondering how can i input some music in my html code, so when i open my index it will show up my html site with some music.</p>

答:
audio tags are supported since HTML 4.0. Try this:</p>

```<code><audio controls autoplay>
  <source src="abc.ogg" type="audio/ogg">
  <source src="xyz.mp3" type="audio/mpeg">
  Your browser does not support audio.
</audio>
</code>```

Body:
audio tags are supported since HTML 4.0. Try this:

<audio controls autoplay>
  <source src="abc.ogg" type="audio/ogg">
  <source src="xyz.mp3" type="audio/mpeg">
  Your browser does not support audio.
</audio>


问:
Maven: how to place resource file together with jar?
I have \src\main\resources\logback.xml file. When I run mvn package it is placed into the jar by default. How do I make Maven place it next to jar, not inside?

So, well, I just want Maven to copy the resource to the same folder where jar will be.

答:
You can build a ZIP file containing both using the Maven Assembly plugin.

You can also use Maven Antrun plugin or similar to put whatever file you want but the idea of single artifact per project is built deep into Maven internals so there is a chance it will hunt you down elsewhere.


问:
Using inflection point as threshold for segmentation
Following this tutorial on image processing, I think the goal of the tutor is to achieve traditional threshold
segmentation in order to separate the background and foreground of an image,
by fitting a polynomial curve to the intensity distribution of the image and
finding an inflection point in the curve to use as a threshold.

Here is the code:

```<code>img = imread('rice.tif');
degree = 6;

%fitting intensity distribution
[frequency, intensity] = imhist(img);
[polynome, ~, mu] = polyfit(intensity, frequency, degree);
eval_fit = polyval(polynome, intensity, [], mu);
</code>```

However, in the next code block:

```<code>%locate inflection point
[values, indices] = sort(abs(diff(eval_fit)));
[m, i] = min(diff(values))

thresh = indices(i)/255;
img_seg = imbinarize(img, thresh);
</code>```

Specifically, the first two lines, I don't get, why use abs, sort if your going to derivate a second time?

Second, I searched on Google and I didn't find a similar approach, so I want ask is this approach good? Have you encountered it?

答:
I hadn’t seen this one before.

I cannot wrap my head around the method. It is not looking for the inflection point of the polynomial fit. I think it is looking for a point where the derivative is most frequent. The minimum of the derivative of the sorted derivative values is a derivative value that occurs at least twice (the sort is such that it’s derivative is always non-negative). What this point means I don’t know. It is likely one of the maxima or minima of the polynomial fit?

The person in the video claims this is their method, meaning they invented it. Their Google Scholar page doesn’t seem to list a paper about this method though.

In any case, since the person in the video claims that their method produces a similar result to Otsu, I see no point in using an unproven method when Otsu is so simple and well established.

I also recommend you learn image processing from a good book rather than random tutorials on YouTube. There is lots of crap on YouTube and it often is hard to tell good and bad apart. Production values do not necessarily correlate with correctness.

Body:
Following this tutorial on image processing, I think the goal of the tutor is to achieve traditional threshold
segmentation in order to separate the background and foreground of an image,
by fitting a polynomial curve to the intensity distribution of the image and
finding an inflection point in the curve to use as a threshold.

Here is the code:

img = imread('rice.tif');
degree = 6;

%fitting intensity distribution
[frequency, intensity] = imhist(img);
[polynome, ~, mu] = polyfit(intensity, frequency, degree);
eval_fit = polyval(polynome, intensity, [], mu);

However, in the next code block:

%locate inflection point
[values, indices] = sort(abs(diff(eval_fit)));
[m, i] = min(diff(values))

thresh = indices(i)/255;
img_seg = imbinarize(img, thresh);

Specifically, the first two lines, I don't get, why use abs, sort if your going to derivate a second time?

Second, I searched on Google and I didn't find a similar approach, so I want ask is this approach good? Have you encountered it?


问:
Query to subtract Now()-[Table].[Field]
I want to run a query that subtracts a certain amount of days from today and filters on that result. I'm working in Access 2007

This works but I need to read the 50 from a table named SetupExp.qryFilter

```<code>SELECT CustItemExp.LocationKey, CustItemExp.MarketBasket, CustItemExp.SaleDate
FROM CustItemExp
WHERE Now() -50;
</code>```

I've tried WHERE Now() -[SetupExp].[qryFilter]

No luck, it just prompts for a value.

I want to put the 50 in a table/field so the query can read it without user input.

答:
Fist of all Now() - 50 is not the correct way to subtract 50 days from today. The correct way is DateAdd('d', -50, Now()) or even better if you don't want to use time components and just use days DateAdd('d', -50, Date()).

You can use DLookup to look up a value from a table. If you are looking for a single fixed value (your table literally has a single record with that value) then you can use DLookUp('qryfilter', 'SetupExp'). If your table has multiple records and depending on how which record you want to use in relation to each CustItemExp you can either JOIN CustItemExp and qryfilter as part of your SQL statement or use the optional 3rd parameter of DLookup which acts as a WHERE type filter.

Title: Query to subtract Now()-[Table].[Field]

Body:
I want to run a query that subtracts a certain amount of days from today and filters on that result. I'm working in Access 2007

This works but I need to read the 50 from a table named SetupExp.qryFilter

SELECT CustItemExp.LocationKey, CustItemExp.MarketBasket, CustItemExp.SaleDate
FROM CustItemExp
WHERE Now() -50;

I've tried WHERE Now() -[SetupExp].[qryFilter]

No luck, it just prompts for a value.

I want to put the 50 in a table/field so the query can read it without user input.


问:
Why am I getting the count value as zero of the counting class I am expecting it to be 20?
I am expecting the output as 20 since there are two threads and the "counting" class method "counter" is also synchronized.

```<code> class Counting{
     public int count ;
     public synchronized void counter(){
        count = count + 1;
    }
}

class mulA implements Runnable{
    public void run() {
        Counting obj = new Counting();
        for(int i = 0;i<10;i++) {
            obj.counter();
        }
    }
}

class mulB implements Runnable{
    public void run() {
        Counting obj1 = new Counting();
        for(int i = 0;i<10;i++) {
            obj1.counter();
        }
    }
}

public class MulTi {

    public static void main(String[] args) throws Exception {

        mulA obj2 = new mulA();
        mulB obj3 = new mulB();

        Thread t1 = new Thread(obj2);
        Thread t2 = new Thread(obj3);

        t1.start();
        t2.start();
        t1.join();
        t2.join();
        Counting obj4 = new Counting();

        System.out.println(obj4.count);

    }

}
</code>```

How will i get the output as 20.Please tell me about my error.

答:
You can add a getCount() method to you Counting class to return the count.
And also add a getCount() method to you mulA and mulB classes to return the count from their respective Counting objects.

Then you get both counts with obj2.getCount() and obj3.getCount()

So your modified code would look like this:

```<code>class Counting {
    private int count ;
    public synchronized void counter() {
        count = count + 1;
    }

    public int getCount() {
        return count;
    }
}

class mulA implements Runnable {
    private Counting obj = new Counting();
    public void run() {
        for(int i = 0;i<10;i++) {
            obj.counter();
        }
    }

    public int getCount() {
        return obj.getCount();
    }

}

class mulB implements Runnable {
    private Counting obj = new Counting();
    public void run() {
        for(int i = 0;i<10;i++) {
            obj.counter();
        }
    }

    public int getCount() {
        return obj.getCount();
    }
}

public class MulTi {

    public static void main(String[] args) throws Exception {

        mulA obj2 = new mulA();
        mulB obj3 = new mulB();

        Thread t1 = new Thread(obj2);
        Thread t2 = new Thread(obj3);

        t1.start();
        t2.start();
        t1.join();
        t2.join();

        System.out.println("Total 1: " + obj2.getCount());
        System.out.println("Total 2: " + obj3.getCount());
        System.out.println("Grand total: " + (obj2.getCount() + obj3.getCount()));
    }
}
</code>```

NOTE: There is no shared resources as both your mul objects have their own Counting object. You do not need the synchronized keyword here.

It outputs

```<code>Total 1: 10
Total 2: 10
Grand total: 20
</code>```

Bonus:

Here is a version with only one Mul class that you can configure to count to as many as you want.

```<code>class Counter {
    private int count = 0;
    public void incrementCounter() {
        count = count + 1;
    }
    public int getCount() {
        return count;
    }
}

class Mul implements Runnable {
    private Counter obj = new Counter();
    private int countTo;

    public Mul(int countTo) {
        this.countTo = countTo;
    }

    public void run() {
        for(int i = 0;i<countTo;i++) {
            obj.incrementCounter();
        }
    }
    public int getCount() {
        return obj.getCount();
    }
}

public class MulTi {
    public static void main(String[] args) throws Exception {
        Mul mul1 = new Mul(10000);
        Mul mul2 = new Mul(50000);
        Thread t1 = new Thread(mul1);
        Thread t2 = new Thread(mul2);

        t1.start();
        t2.start();
        t1.join();
        t2.join();

        System.out.println("Total 1: " + mul1.getCount());
        System.out.println("Total 2: " + mul2.getCount());
        System.out.println("Grand total: " + (mul1.getCount() + mul2.getCount()));
    }
}
</code>```

Outputs:

```<code>Total 1: 10000
Total 2: 50000
Grand total: 60000
</code>```

And one more bonus if you really want to use shared resources
In this case all Threads will use the same counter, so you need the synchronized keyword

```<code>class Counter {
    private static int count = 0;
    public static synchronized void incrementCounter() {
        count = count + 1;
    }
    public static int getCount() {
        return count;
    }
}

class Mul implements Runnable {
    private int countTo;

    public Mul(int countTo) {
        this.countTo = countTo;
    }

    public void run() {
        for(int i = 0;i<countTo;i++) {
            Counter.incrementCounter();
        }
    }
}

public class MulTi {
    public static void main(String[] args) throws Exception {
        Mul mul1 = new Mul(100000);
        Mul mul2 = new Mul(500000);
        Thread t1 = new Thread(mul1);
        Thread t2 = new Thread(mul2);

        t1.start();
        t2.start();
        t1.join();
        t2.join();

        System.out.println("Grand total: " + Counter.getCount());
    }
}
</code>```

Outputs:

```<code>Grand total: 600000
</code>```

you will not get 600000 if it is not synchronized

Body:
I am expecting the output as 20 since there are two threads and the "counting" class method "counter" is also synchronized.

 class Counting{
     public int count ;
     public synchronized void counter(){
        count = count + 1;
    }
}

class mulA implements Runnable{
    public void run() {
        Counting obj = new Counting();
        for(int i = 0;i<10;i++) {
            obj.counter();
        }
    }
}

class mulB implements Runnable{
    public void run() {
        Counting obj1 = new Counting();
        for(int i = 0;i<10;i++) {
            obj1.counter();
        }
    }
}

public class MulTi {

    public static void main(String[] args) throws Exception {

        mulA obj2 = new mulA();
        mulB obj3 = new mulB();

        Thread t1 = new Thread(obj2);
        Thread t2 = new Thread(obj3);

        t1.start();
        t2.start();
        t1.join();
        t2.join();
        Counting obj4 = new Counting();

        System.out.println(obj4.count);

    }

}

How will i get the output as 20.Please tell me about my error.

Body:
You can add a getCount() method to you Counting class to return the count.
And also add a getCount() method to you mulA and mulB classes to return the count from their respective Counting objects.

Then you get both counts with obj2.getCount() and obj3.getCount()

So your modified code would look like this:

class Counting {
    private int count ;
    public synchronized void counter() {
        count = count + 1;
    }

    public int getCount() {
        return count;
    }
}

class mulA implements Runnable {
    private Counting obj = new Counting();
    public void run() {
        for(int i = 0;i<10;i++) {
            obj.counter();
        }
    }

    public int getCount() {
        return obj.getCount();
    }

}

class mulB implements Runnable {
    private Counting obj = new Counting();
    public void run() {
        for(int i = 0;i<10;i++) {
            obj.counter();
        }
    }

    public int getCount() {
        return obj.getCount();
    }
}

public class MulTi {

    public static void main(String[] args) throws Exception {

        mulA obj2 = new mulA();
        mulB obj3 = new mulB();

        Thread t1 = new Thread(obj2);
        Thread t2 = new Thread(obj3);

        t1.start();
        t2.start();
        t1.join();
        t2.join();

        System.out.println("Total 1: " + obj2.getCount());
        System.out.println("Total 2: " + obj3.getCount());
        System.out.println("Grand total: " + (obj2.getCount() + obj3.getCount()));
    }
}

NOTE: There is no shared resources as both your mul objects have their own Counting object. You do not need the synchronized keyword here.

It outputs

Total 1: 10
Total 2: 10
Grand total: 20

Bonus:

Here is a version with only one Mul class that you can configure to count to as many as you want.

class Counter {
    private int count = 0;
    public void incrementCounter() {
        count = count + 1;
    }
    public int getCount() {
        return count;
    }
}

class Mul implements Runnable {
    private Counter obj = new Counter();
    private int countTo;

    public Mul(int countTo) {
        this.countTo = countTo;
    }

    public void run() {
        for(int i = 0;i<countTo;i++) {
            obj.incrementCounter();
        }
    }
    public int getCount() {
        return obj.getCount();
    }
}

public class MulTi {
    public static void main(String[] args) throws Exception {
        Mul mul1 = new Mul(10000);
        Mul mul2 = new Mul(50000);
        Thread t1 = new Thread(mul1);
        Thread t2 = new Thread(mul2);

        t1.start();
        t2.start();
        t1.join();
        t2.join();

        System.out.println("Total 1: " + mul1.getCount());
        System.out.println("Total 2: " + mul2.getCount());
        System.out.println("Grand total: " + (mul1.getCount() + mul2.getCount()));
    }
}

Outputs:

Total 1: 10000
Total 2: 50000
Grand total: 60000

And one more bonus if you really want to use shared resources
In this case all Threads will use the same counter, so you need the synchronized keyword

class Counter {
    private static int count = 0;
    public static synchronized void incrementCounter() {
        count = count + 1;
    }
    public static int getCount() {
        return count;
    }
}

class Mul implements Runnable {
    private int countTo;

    public Mul(int countTo) {
        this.countTo = countTo;
    }

    public void run() {
        for(int i = 0;i<countTo;i++) {
            Counter.incrementCounter();
        }
    }
}

public class MulTi {
    public static void main(String[] args) throws Exception {
        Mul mul1 = new Mul(100000);
        Mul mul2 = new Mul(500000);
        Thread t1 = new Thread(mul1);
        Thread t2 = new Thread(mul2);

        t1.start();
        t2.start();
        t1.join();
        t2.join();

        System.out.println("Grand total: " + Counter.getCount());
    }
}

Outputs:

Grand total: 600000

you will not get 600000 if it is not synchronized


问:
Best way to handle background process
I got my first android phone since two week
And I'm starting my first real App.
My phone is a LG Optimus 2X and one of the missing thing is a
notification led for when there is a missed call, sms, email ect ...

So I'm wondering what's the best way to do this.

For know I've a broatcastreceiver for incoming sms, and the I call a
service that will light the phone buttons (don't bother about this
part, it's working).
But seems that this method will workin only for sms, phone calls, not
emails.

So know I'm thinking to used Listeners instead for everything, but
this mean having a service running  nonstop. Not sure it's the best
way ...

I hope I'm clear, and that my ennglish is not too bad.
Thx in advance

答:
I will be interested in knowing how you implement your listener framework for email notification. But I digress. If you want to have a background service, then the best way to do is polling. If you keep your service running in the background, the service becomes a prime candidate for android to kill, if it runs low on resource. But polling may not work for you, if you are trying to leverage existing email client in android. ( As I understand, you need to keep a listener running when the email message is received..)

So the best bet is to have a polling service using AlarmManager and writing your own custom email client code ( NO need for a UI). In periodic intervals you can poll your email server to check if there are new emails and then call the android inbuild email client as a pending Intent. I assume there could be some logistic problems in implementing this. ( For eg: You poll the email client, but when you notify user and the user responds to notification, you will open the android email client and that would still not have the new email, so it might confuse the users), but this is what I could think of.

Title: Best way to handle background process


问:
Replace value with the value of nearest neighbor in Pandas dataframe
I have a problem with getting nearest values for some rows in pandas dataframe and fill another column with values from those rows.

data sample I have:

```<code>id   su_id  r_value  match_v

A      A1      0        1
A      A2      0        1
A      A3      70       2
A      A4      120      100
A      A5      250      3
A      A6      250      100
B      B1      0        1
B      B2      30       2
</code>```

The thing is, wherever match_v is equal to 100, I need to replace that 100 with a value from the row where r_value is the closest to r_value from origin row(where match_v is equal to 100), but just withing group (grouped by id)

Expected output

```<code>id   su_id  r_value  match_v

A      A1      0        1
A      A2      0        1
A      A3      70       2
A      A4      120      2
A      A5      250      3
A      A6      250      3
B      B1      0        1
B      B2      30       2
</code>```

I have tried with creating lead and leg with shift and then finding differences. But doesn't work well and it somehow messed up already good values.
I haven't tried anything else cause I really don't have any idea.

Any help or hint is welcomed and I if you need any additional info, I'm here.

Thanks in advance.

答:
More like merge_asof

```<code>s=df.loc[df.match_v!=100]
s=pd.merge_asof(df.sort_values('r_value'),s.sort_values('r_value'),on='r_value',by='id',direction='nearest')
df['match_v']=df['su_id'].map(s.set_index('su_id_x')['match_v_y'])
df
Out[231]:
  id su_id  r_value  match_v
0  A    A1        0        1
1  A    A2        0        1
2  A    A3       70        2
3  A    A4      120        2
4  A    A5      250        3
5  A    A6      250        3
6  B    B1        0        1
7  B    B2       30        2
</code>```

Here is another way using numpy broadcast , build for speed up calculation

```<code>l=[]
for x , y in df.groupby('id'):
    s1=y.r_value.values
    s=abs((s1-s1[:,None])).astype(float)
    s[np.tril_indices(s.shape[0], 0)] = 999999
    s=s.argmin(0)
    s2=y.match_v.values
    l.append(s2[s][s2==100])
df.loc[df.match_v==100,'match_v']=np.concatenate(l)
df
Out[264]:
  id su_id  r_value  match_v
0  A    A1        0        1
1  A    A2        0        1
2  A    A3       70        2
3  A    A4      120        2
4  A    A5      250        3
5  A    A6      250        3
6  B    B1        0        1
7  B    B2       30        2
</code>```

Body:
I have a problem with getting nearest values for some rows in pandas dataframe and fill another column with values from those rows.

data sample I have:

id   su_id  r_value  match_v

A      A1      0        1
A      A2      0        1
A      A3      70       2
A      A4      120      100
A      A5      250      3
A      A6      250      100
B      B1      0        1
B      B2      30       2

The thing is, wherever match_v is equal to 100, I need to replace that 100 with a value from the row where r_value is the closest to r_value from origin row(where match_v is equal to 100), but just withing group (grouped by id)

Expected output

id   su_id  r_value  match_v

A      A1      0        1
A      A2      0        1
A      A3      70       2
A      A4      120      2
A      A5      250      3
A      A6      250      3
B      B1      0        1
B      B2      30       2

I have tried with creating lead and leg with shift and then finding differences. But doesn't work well and it somehow messed up already good values.
I haven't tried anything else cause I really don't have any idea.

Any help or hint is welcomed and I if you need any additional info, I'm here.

Thanks in advance.

Body:
More like merge_asof

s=df.loc[df.match_v!=100]
s=pd.merge_asof(df.sort_values('r_value'),s.sort_values('r_value'),on='r_value',by='id',direction='nearest')
df['match_v']=df['su_id'].map(s.set_index('su_id_x')['match_v_y'])
df
Out[231]:
  id su_id  r_value  match_v
0  A    A1        0        1
1  A    A2        0        1
2  A    A3       70        2
3  A    A4      120        2
4  A    A5      250        3
5  A    A6      250        3
6  B    B1        0        1
7  B    B2       30        2

Here is another way using numpy broadcast , build for speed up calculation

l=[]
for x , y in df.groupby('id'):
    s1=y.r_value.values
    s=abs((s1-s1[:,None])).astype(float)
    s[np.tril_indices(s.shape[0], 0)] = 999999
    s=s.argmin(0)
    s2=y.match_v.values
    l.append(s2[s][s2==100])
df.loc[df.match_v==100,'match_v']=np.concatenate(l)
df
Out[264]:
  id su_id  r_value  match_v
0  A    A1        0        1
1  A    A2        0        1
2  A    A3       70        2
3  A    A4      120        2
4  A    A5      250        3
5  A    A6      250        3
6  B    B1        0        1
7  B    B2       30        2


问:
Replace multiple (special) characters - most efficient way?
At the texts that I have, I want to replace the following special characters with a single space:

```<code>symbols = ["`", "~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "-", "+", "=", "{", "[", "]", "}", "|", "\\", ":", ";", "\"", "<", ",", ">", ".", "?", "/"]
</code>```

What is the most efficient way (in terms of time of code execution) to do this?

For example, I want this:

```<code>(Hello World)] *!
</code>```

to become this:

```<code>Hello World
</code>```

The candidate methods seem to be the following:

list comprehension

.replace()

.translate()

regular expressions

答:
str.translate() is indeed the fastest method.  Here's a concise way to build the translation table for exclusion of characters:

```<code>symbols = ["`", "~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "-", "+", "=", "{", "[", "]", "}", "|", "\\", ":", ";", "\"", "<", ",", ">", ".", "?", "/"]
removeSymbols = str.maketrans("","","".join(symbols))

cleanText = "[Hello World] *!".translate(removeSymbols)
print(cleanText) # "Hello World "
</code>```

The maketrans() functions can take 3 parameters,  the first one is a string with the characters to replace, the second one is their replacements and the third one is a list of characters that should be removed.   To bluntly remove all characters, we just need to supply the 3rd parameter with a string containing the symbols to remove.

The translation table removeSymbols then performs a complete removal of the characters in the symbols list.

To replace with spaces, build the translation table like this:

```<code>removeSymbols = str.maketrans("".join(symbols)," "*len(symbols))
</code>```

Body:
At the texts that I have, I want to replace the following special characters with a single space:

symbols = ["`", "~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "-", "+", "=", "{", "[", "]", "}", "|", "\\", ":", ";", "\"", "<", ",", ">", ".", "?", "/"]

What is the most efficient way (in terms of time of code execution) to do this?

For example, I want this:

(Hello World)] *!

to become this:

Hello World

The candidate methods seem to be the following:

list comprehension

.replace()

.translate()

regular expressions

Body:
str.translate() is indeed the fastest method.  Here's a concise way to build the translation table for exclusion of characters:

symbols = ["`", "~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "-", "+", "=", "{", "[", "]", "}", "|", "\\", ":", ";", "\"", "<", ",", ">", ".", "?", "/"]
removeSymbols = str.maketrans("","","".join(symbols))

cleanText = "[Hello World] *!".translate(removeSymbols)
print(cleanText) # "Hello World "

The maketrans() functions can take 3 parameters,  the first one is a string with the characters to replace, the second one is their replacements and the third one is a list of characters that should be removed.   To bluntly remove all characters, we just need to supply the 3rd parameter with a string containing the symbols to remove.

The translation table removeSymbols then performs a complete removal of the characters in the symbols list.

To replace with spaces, build the translation table like this:

removeSymbols = str.maketrans("".join(symbols)," "*len(symbols))


问:
Promise async call
I am new to node js and trying to understand how to make async calls.
I am trying to wrap a function into a promise in order to make it async. For simplicity, the function is just a loop that takes time :

```<code>var p = new Promise(resolve => {
    for (let i=0;i<999999999;i++){}
    resolve('foo')
});

p.then(function (value) { console.log(value);});
console.log('bar');
</code>```

I am expecting to see :

bar  // printed immediately

foo // printed after the loop finishes

Instead, they are both printed after the loop completion.
How to make the loop block run asynchronously?

Ps. Apologies for the indentation/formatting, I had to write this from a phone.

Thanks

答:
But there's nothing asynchronous about your promise. Creating a promise starts the execution of the function, and JS always runs to completion.

Typically, a promise is used to initiate something asynchronous, like an API call, or even a plain setTimeout, that runs outside JS's thread. Your code, however, will iterate through the empty loop bajillion times, and only after that any following lines will be run.

Replace the empty line with a timeout, and it will become async:

var p = new Promise(resolve => {
  setTimeout(() => resolve("foo"), 2000);
});

p.then(function(value) {
  console.log(value);
});
console.log('bar');```

Title: Promise async call

Body:
I am new to node js and trying to understand how to make async calls.
I am trying to wrap a function into a promise in order to make it async. For simplicity, the function is just a loop that takes time :

var p = new Promise(resolve => {
    for (let i=0;i<999999999;i++){}
    resolve('foo')
});

p.then(function (value) { console.log(value);});
console.log('bar');

I am expecting to see :

bar  // printed immediately

foo // printed after the loop finishes

Instead, they are both printed after the loop completion.
How to make the loop block run asynchronously?

Ps. Apologies for the indentation/formatting, I had to write this from a phone.

Thanks


答:
You seem to assume that "asynchronous code" involves concurrency, in the sense that code will run at the same time in another thread. That is not the case. Unless you start another thread by purpose, JS itself will run in a single thread. Therefore no matter what you do with promises: Either the loop runs first and then the logs run or the logs run first and then the loop runs.

You could also achieve concurrent execution through multitasking: If you stop the loop inbetween, other code can run in the meantime:

```<code> (async function() {
    while(true) {
       console.log("loop");
       await Promise.resolve();
    }
 })();

 console.log("in the meantime");
</code>```

Title: Promise async call

Body:
You seem to assume that "asynchronous code" involves concurrency, in the sense that code will run at the same time in another thread. That is not the case. Unless you start another thread by purpose, JS itself will run in a single thread. Therefore no matter what you do with promises: Either the loop runs first and then the logs run or the logs run first and then the loop runs.

You could also achieve concurrent execution through multitasking: If you stop the loop inbetween, other code can run in the meantime:

 (async function() {
    while(true) {
       console.log("loop");
       await Promise.resolve();
    }
 })();

 console.log("in the meantime");


问:
Validate array of strings with joi, must be strings
I need to validate an array to check if it's elements are strings using joi. It always sends the error of "Inavlid tag".</p>

```<code>// returned array from req.body
let tags = ["Vue", "React", "Angular"]

// joi shema
const schema = {
     tags: Joi.array().items(Joi.string()),
};

const { error, value } = Joi.validate(tags, schema);

if (error) {
     return res.status(400).send({ tagError: "Invalid tag" });
}
</code>```

答:
The issue is due to how you defined the schema, the right way to validate would be:

// returned array from req.body
let tags = ["Vue", "React", "Angular"]

const schema = Joi.array().items(Joi.string());

const { error, value } = Joi.validate(tags, schema);```

Body:
I need to validate an array to check if it's elements are strings using joi. It always sends the error of "Inavlid tag".

// returned array from req.body
let tags = ["Vue", "React", "Angular"]

// joi shema
const schema = {
     tags: Joi.array().items(Joi.string()),
};

const { error, value } = Joi.validate(tags, schema);

if (error) {
     return res.status(400).send({ tagError: "Invalid tag" });
}