问:
How to prevent img src invalid and if it's invalid preserve previous image
I am trying to stream live image to my webpage. When the image content is being  updated at backend, sometimes the path may return invalid content. How do I detect the URL contains invalid content, and thus do not refresh my image ?

My current implementation of image update:

```<code>function update(){

 $("#live").prop("src", "/HTTPGetImage?ImageIndex=0?"+ +new Date());

 setTimeout(update, 3000);

}
</code>```

I've tried to use .get() to check if return data is valid.

```<code>$.get('/HTTPGetImage?ImageIndex=0?').done(function(data)
{
  if(data!="")
   $("#live").prop("src", "/HTTPGetImage?ImageIndex=0?"+ +new Date());
})
</code>```

But this approach doesn't work. I think the updating is very frequent at backend, so between my first and second request to server, image at back-end might already been updated.  What should I do to avoid getting invalid content, and if I get invalid content, how do I preserve current img src  ?

答:
You can create a pseudo image with jquery that you will not attach to DOM, and hook into it's load and error events. My example shows how this can be achieved - just implement your logic into onerror and onload handlers - if it loads, you can set your image, if error is triggered, show previous.

$(document).ready(function(){
  var last_image = 0
  var sample_images = ["https://via.placeholder.com/100",
                       "https://via.placeholder.com/101/000/fff",
                       "https://via.placeholder.com/error",
                       "https://via.placeholder.com/103/880000/fff"]

  function loadImage(){

     var next_image = (last_image == sample_images.length-1)?0:last_image+1
     setTimeout(function(){

        var pseudoImg = $("");
        pseudoImg.attr("src",sample_images[next_image])
        pseudoImg.on("load",function(){
          $("#img").attr("src",sample_images[next_image])
          $("#url").html(sample_images[next_image])
          last_image=next_image
          loadImage()
        });
        pseudoImg.on("error",function(){
          // not changing previous image
          $("#url").html("ERROR LOADING "+sample_images[next_image]+"
 displaying previous: "+sample_images[last_image])
          last_image=next_image
          loadImage()
        })

     },2000)
  }

  loadImage()
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="https://via.placeholder.com/100" id="img">
<div id="url">https://via.placeholder.com/100</div></code>```

For your example the code would be something like this:

```<code>function update(){
   setTimeout(function(){
     var timestamp = new Date()
     var url = "/HTTPGetImage?ImageIndex=0?"+timestamp
     var pseudoImg = $("<img>");
     pseudoImg.attr("src",url)
     pseudoImg.on("load",function(){
       $("#live").attr("src",url)
       update()
     });
     pseudoImg.on("error",function(){
       // don't do nothing, just call next update
       update()
     })
  },3000);
}
</code>```

Body:
I am trying to stream live image to my webpage. When the image content is being  updated at backend, sometimes the path may return invalid content. How do I detect the URL contains invalid content, and thus do not refresh my image ?

My current implementation of image update:

function update(){

 $("#live").prop("src", "/HTTPGetImage?ImageIndex=0?"+ +new Date());

 setTimeout(update, 3000);

}

I've tried to use .get() to check if return data is valid.

$.get('/HTTPGetImage?ImageIndex=0?').done(function(data)
{
  if(data!="")
   $("#live").prop("src", "/HTTPGetImage?ImageIndex=0?"+ +new Date());
})

But this approach doesn't work. I think the updating is very frequent at backend, so between my first and second request to server, image at back-end might already been updated.  What should I do to avoid getting invalid content, and if I get invalid content, how do I preserve current img src  ?

Body:
You can create a pseudo image with jquery that you will not attach to DOM, and hook into it's load and error events. My example shows how this can be achieved - just implement your logic into onerror and onload handlers - if it loads, you can set your image, if error is triggered, show previous.

$(document).ready(function(){
  var last_image = 0
  var sample_images = ["https://via.placeholder.com/100",
                       "https://via.placeholder.com/101/000/fff",
                       "https://via.placeholder.com/error",
                       "https://via.placeholder.com/103/880000/fff"]

  function loadImage(){

     var next_image = (last_image == sample_images.length-1)?0:last_image+1
     setTimeout(function(){

        var pseudoImg = $("<img>");
        pseudoImg.attr("src",sample_images[next_image])
        pseudoImg.on("load",function(){
          $("#img").attr("src",sample_images[next_image])
          $("#url").html(sample_images[next_image])
          last_image=next_image
          loadImage()
        });
        pseudoImg.on("error",function(){
          // not changing previous image
          $("#url").html("ERROR LOADING "+sample_images[next_image]+"<br> displaying previous: "+sample_images[last_image])
          last_image=next_image
          loadImage()
        })

     },2000)
  }

  loadImage()
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="https://via.placeholder.com/100" id="img">
<div id="url">https://via.placeholder.com/100</div>

For your example the code would be something like this:

function update(){
   setTimeout(function(){
     var timestamp = new Date()
     var url = "/HTTPGetImage?ImageIndex=0?"+timestamp
     var pseudoImg = $("<img>");
     pseudoImg.attr("src",url)
     pseudoImg.on("load",function(){
       $("#live").attr("src",url)
       update()
     });
     pseudoImg.on("error",function(){
       // don't do nothing, just call next update
       update()
     })
  },3000);
}


来源: stackexchange

问:
How to calculate length of string in a tuple in scala
Given a list of tuples, where the 1st element of the tuple is an integer and the second element is a string,

```<code>scala> val tuple2 : List[(Int,String)] = List((1,"apple"),(2,"ball"),(3,"cat"),(4,"doll"),(5,"eggs"))
tuple2: List[(Int, String)] = List((1,apple), (2,ball), (3,cat), (4,doll), (5,eggs))
</code>```

I want to print the numbers where the corresponding string length is 4.

Can this be done in one line ?

答:
you need .collect which is filter+map

given your input,

```<code>scala> val input : List[(Int,String)] = List((1,"apple"),(2,"ball"),(3,"cat"),(4,"doll"),(5,"eggs"))
input: List[(Int, String)] = List((1,apple), (2,ball), (3,cat), (4,doll), (5,eggs))
</code>```

filter those of length 4,

```<code>scala> input.collect { case(number, string) if string.length == 4 => number}
res2: List[Int] = List(2, 4, 5)
</code>```

alternative solution using filter + map,

```<code>scala> input.filter { case(number, string) => string.length == 4 }
            .map { case (number, string) => number}
res4: List[Int] = List(2, 4, 5)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Given a list of tuples, where the 1st element of the tuple is an integer and the second element is a string,

scala> val tuple2 : List[(Int,String)] = List((1,"apple"),(2,"ball"),(3,"cat"),(4,"doll"),(5,"eggs"))
tuple2: List[(Int, String)] = List((1,apple), (2,ball), (3,cat), (4,doll), (5,eggs))

I want to print the numbers where the corresponding string length is 4.

Can this be done in one line ?

Body:
you need .collect which is filter+map

given your input,

scala> val input : List[(Int,String)] = List((1,"apple"),(2,"ball"),(3,"cat"),(4,"doll"),(5,"eggs"))
input: List[(Int, String)] = List((1,apple), (2,ball), (3,cat), (4,doll), (5,eggs))

filter those of length 4,

scala> input.collect { case(number, string) if string.length == 4 => number}
res2: List[Int] = List(2, 4, 5)

alternative solution using filter + map,

scala> input.filter { case(number, string) => string.length == 4 }
            .map { case (number, string) => number}
res4: List[Int] = List(2, 4, 5)


问:
sikuli, how to capture screen where the script did not run well
Sikuli, how to capture screen where the script did not run well where I got an error from the script execution in Sikuli, I'm doing the Eclipse script.</p>

答:
You can use something like this to capture a screenshot:

```<code>def takeScreenShot(application):
 img = capture(SCREEN) # img is an image file .png in temp folder now
 ts = time.time()
 st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d_%H-%M-%S')
 if not os.path.exists('PATH'):
  os.makedirs('')
 shutil.move(img, 'PATH\\%(appName)s\\%(timeStamp)s.png' %{"appName": application, "timeStamp": st})
</code>```

You can call this method as a part of a try catch block.

Body:
You can use something like this to capture a screenshot:

def takeScreenShot(application):
 img = capture(SCREEN) # img is an image file .png in temp folder now
 ts = time.time()
 st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d_%H-%M-%S')
 if not os.path.exists('PATH'):
  os.makedirs('')
 shutil.move(img, 'PATH\\%(appName)s\\%(timeStamp)s.png' %{"appName": application, "timeStamp": st})

You can call this method as a part of a try catch block.


问:
Managing channels using a HTTP request context
I have a basic HTTP server that accepts a request and returns data from a data store.

Each HTTP request does the following things:

Create a context with timeout

Create a read request (custom type)

Push read request onto channel

Wait for response and serve data

Here's the basic pseudo code:

```<code>package main

import (
    "context"
    "net/http"
    "time"
)

type dataRequest struct {
    data chan string
    ctx  context.Context
}

func handler(reqStream chan dataRequest) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
        defer cancel()

        req := dataRequest{
            data: make(chan string),
            ctx:  ctx,
        }

        select {
        case reqStream <- req:
            // request pushed to que
        case <-ctx.Done():
            // don't push onto reqStream if ctx done
        }

        select {
        case <-ctx.Done():
            // don't try and serve content if ctx done
        case data := <-req.data:
            // return data to client
        }

    }
}

func main() {
    dataReqs := make(chan dataRequest)
    go func() {
        for {
            select {
            case req := <-dataReqs:
                select {
                case <-req.ctx.Done():
                    // don't push onto data channel if ctx done
                case req.data <- "some data":
                    // get data from store
                }
            }
        }
    }()
    http.HandleFunc("/", handler(dataReqs))
    http.ListenAndServe(":8080", nil)
}
</code>```

My question is, because the context could finish at any time due to the deadline being exceeded or the client cancelling the request, is my current approach correct for handling this in multiple places or is there a more elegant solution?

答:
seems to me that it'll work.
few comments -

you can return in the first case of <- ctx.Done()

you're already waiting for req.ctx.Done() in the data store handler so you can completely remove the first select {} statement and just publish to the data requests channel. not sure about performance hits for the rare cases when the context is done so early before the request is even published...

Body:
I have a basic HTTP server that accepts a request and returns data from a data store.

Each HTTP request does the following things:

Create a context with timeout

Create a read request (custom type)

Push read request onto channel

Wait for response and serve data

Here's the basic pseudo code:

package main

import (
    "context"
    "net/http"
    "time"
)

type dataRequest struct {
    data chan string
    ctx  context.Context
}

func handler(reqStream chan dataRequest) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
        defer cancel()

        req := dataRequest{
            data: make(chan string),
            ctx:  ctx,
        }

        select {
        case reqStream <- req:
            // request pushed to que
        case <-ctx.Done():
            // don't push onto reqStream if ctx done
        }

        select {
        case <-ctx.Done():
            // don't try and serve content if ctx done
        case data := <-req.data:
            // return data to client
        }

    }
}

func main() {
    dataReqs := make(chan dataRequest)
    go func() {
        for {
            select {
            case req := <-dataReqs:
                select {
                case <-req.ctx.Done():
                    // don't push onto data channel if ctx done
                case req.data <- "some data":
                    // get data from store
                }
            }
        }
    }()
    http.HandleFunc("/", handler(dataReqs))
    http.ListenAndServe(":8080", nil)
}

My question is, because the context could finish at any time due to the deadline being exceeded or the client cancelling the request, is my current approach correct for handling this in multiple places or is there a more elegant solution?


问:
Generic and non-generic interfaces and inheritance - ambiguity while accessing
I have the following setup

Base class

```<code>public class Fruit
{

}
</code>```

Inherited class

```<code>public class Apple : Fruit
{

}
</code>```

Generic Base interface

```<code>public interface IFruitsBase<T> where T : Fruit
{
    T GetItem();
    void ProcessItem(T fruit);
    void Check();
}
</code>```

Non generic Interface that inheritates from generic interface with the base class as the generic

```<code>public interface IFruits : IFruitsBase<Fruit>
{

}
</code>```

Specific interface of the correspoing class

```<code>public interface IApples : IFruitsBase<Apple>, IFruits
{
    void MakeAppleJuice(IEnumerable<Apple> apples);
}
</code>```

Base implementation class

```<code>public class Fruits<T> : IFruitsBase<T>, IFruits where T : Fruit
{
    public T GetItem()
    {
        return null;
    }
    public void ProcessItem(T fruit)
    {

    }
    public void Check()
    {

    }

    Fruit IFruitsBase<Fruit>.GetItem()
    {
        return this.GetItem();
    }
    void IFruitsBase<Fruit>.ProcessItem(Fruit fruit)
    {
        ProcessItem((T)fruit);
    }
}
</code>```

Specific implementation

```<code>public class Apples : Fruits<Apple>, IApples
{
    public void MakeAppleJuice(IEnumerable<Apple> apples)
    {

    }
}
</code>```

The problem I am facing, is at that part:

```<code>public interface IApples : IFruitsBase<Apple>, IFruits
{
    void MakeAppleJuice(IEnumerable<Apple> apples);
}
</code>```

Here I am getting the message:

Possible ambiguity while accessing by this Interface Apple IFruitsBase<Apple> Get() Fruit IFruitsBase<Fruit>.Get()

To fix the problem I could remove the interface IFruits from IApples, but this gives other errors as in:

```<code>public class Context
{
    public IApples Apples { get; set; }

    public Context()
    {
        this.Apples = new Apples();
    }

    public IFruits GetFruits(Type type)
    {
        return this.Apples; //simplified the code here, it should actually get the member of this that fits the type
    }
}

public class Foo
{
    public void Main()
    {
        var context = new Context();
        Check(new IFruits[] { context.Apples }); //can't do that since context.Apples doesnt inherit from IFruits, to fix the above ambiguity
    }

    public void Check(IEnumerable<IFruits> fruits)
    {
        foreach (var fruit in fruits)
            fruit.Check();
    }
}
</code>```

My goal is if someone accesses the objects with:

```<code>var context = new Context();
context.Apples.[only apple relevant methods should be accessable]
</code>```

if someone access it with:

```<code>var context = new Context();
context.GetFruits(item.GetType()).[only fruit relevant methods should be accessable]
</code>```

and no matter if one got it with method a or b, all should be passable to methods with a signature of

```<code>void Foo(IFruits fruits);
</code>```

答:
You need to construct a covariant interface in order to accomplish this. Have you heard of the variance in C# and variant interfaces in particular? You need to re-define IFruitsBase<T> to be covariant. I.e., use the out keyword on the generic parameter and constraint it to be an IFruit, like this IFruitsBase<out T> where T : IFruit

Start off by defining interfaces for the Fruit and Apple classes and implement them in your actual classes:

```<code>public interface IFruit
{
}

public interface IApple : IFruit
{
}

public class Fruit : IFruit
{
}

public class Fruit : IFruit
{

}

public class Apple : Fruit, IApple
{

}
</code>```

Then go with the plurals (I hope this is just for the example, right?). IMHO you can get rid of the non-generic interface IFruits and rename the generic IFruitsBase<T> as IFruits<T>. As a coding standard, you apply the Base suffix to classes meant to be inherited.

```<code>public interface IFruits<out T> where T : IFruit
{
    T GetItem();
    void ProcessItem(IFruit fruit);
    void Check();

}

public interface IApples : IFruits<IApple>
{
    void MakeAppleJuice(IEnumerable<IApple> apples);
}

public class Fruits<T> : IFruits<T> where T : IFruit
{
    public void Check()
    {
        throw new NotImplementedException();
    }

    public T GetItem()
    {
        throw new NotImplementedException();
    }

    public void ProcessItem(IFruit fruit)
    {
        if (fruit is T)
        {

        }
        else
        {
            throw new NotSupportedException();
        }
    }
}

public class Apples : Fruits<IApple>, IApples
{
    public void MakeAppleJuice(IEnumerable<IApple> apples)
    {
        // Do the juice
    }
}
</code>```

Then modify the Context class a bit:

```<code>public class Context
{
    public IApples Apples { get; set; }

    public IBananas Bananas { get; set; }

    public Context()
    {
        Apples = new Apples();
    }

    public IFruits<T> GetFruits<T>() where T : IFruit
    {
        return new Fruits<T>();
    }
}
</code>```

Now the MakeAppleJuice() method is available ONLY when you access context.Apples.

Body:
I have the following setup

Base class

public class Fruit
{

}

Inherited class

public class Apple : Fruit
{

}

Generic Base interface

public interface IFruitsBase<T> where T : Fruit
{
    T GetItem();
    void ProcessItem(T fruit);
    void Check();
}

Non generic Interface that inheritates from generic interface with the base class as the generic

public interface IFruits : IFruitsBase<Fruit>
{

}

Specific interface of the correspoing class

public interface IApples : IFruitsBase<Apple>, IFruits
{
    void MakeAppleJuice(IEnumerable<Apple> apples);
}

Base implementation class

public class Fruits<T> : IFruitsBase<T>, IFruits where T : Fruit
{
    public T GetItem()
    {
        return null;
    }
    public void ProcessItem(T fruit)
    {

    }
    public void Check()
    {

    }

    Fruit IFruitsBase<Fruit>.GetItem()
    {
        return this.GetItem();
    }
    void IFruitsBase<Fruit>.ProcessItem(Fruit fruit)
    {
        ProcessItem((T)fruit);
    }
}

Specific implementation

public class Apples : Fruits<Apple>, IApples
{
    public void MakeAppleJuice(IEnumerable<Apple> apples)
    {

    }
}

The problem I am facing, is at that part:

public interface IApples : IFruitsBase<Apple>, IFruits
{
    void MakeAppleJuice(IEnumerable<Apple> apples);
}

Here I am getting the message:

Possible ambiguity while accessing by this Interface Apple IFruitsBase<Apple> Get() Fruit IFruitsBase<Fruit>.Get()

To fix the problem I could remove the interface IFruits from IApples, but this gives other errors as in:

public class Context
{
    public IApples Apples { get; set; }

    public Context()
    {
        this.Apples = new Apples();
    }

    public IFruits GetFruits(Type type)
    {
        return this.Apples; //simplified the code here, it should actually get the member of this that fits the type
    }
}

public class Foo
{
    public void Main()
    {
        var context = new Context();
        Check(new IFruits[] { context.Apples }); //can't do that since context.Apples doesnt inherit from IFruits, to fix the above ambiguity
    }

    public void Check(IEnumerable<IFruits> fruits)
    {
        foreach (var fruit in fruits)
            fruit.Check();
    }
}

My goal is if someone accesses the objects with:

var context = new Context();
context.Apples.[only apple relevant methods should be accessable]

if someone access it with:

var context = new Context();
context.GetFruits(item.GetType()).[only fruit relevant methods should be accessable]

and no matter if one got it with method a or b, all should be passable to methods with a signature of

void Foo(IFruits fruits);

Body:
You need to construct a covariant interface in order to accomplish this. Have you heard of the variance in C# and variant interfaces in particular? You need to re-define IFruitsBase<T> to be covariant. I.e., use the out keyword on the generic parameter and constraint it to be an IFruit, like this IFruitsBase<out T> where T : IFruit

Start off by defining interfaces for the Fruit and Apple classes and implement them in your actual classes:

public interface IFruit
{
}

public interface IApple : IFruit
{
}

public class Fruit : IFruit
{
}

public class Fruit : IFruit
{

}

public class Apple : Fruit, IApple
{

}

Then go with the plurals (I hope this is just for the example, right?). IMHO you can get rid of the non-generic interface IFruits and rename the generic IFruitsBase<T> as IFruits<T>. As a coding standard, you apply the Base suffix to classes meant to be inherited.

public interface IFruits<out T> where T : IFruit
{
    T GetItem();
    void ProcessItem(IFruit fruit);
    void Check();

}

public interface IApples : IFruits<IApple>
{
    void MakeAppleJuice(IEnumerable<IApple> apples);
}

public class Fruits<T> : IFruits<T> where T : IFruit
{
    public void Check()
    {
        throw new NotImplementedException();
    }

    public T GetItem()
    {
        throw new NotImplementedException();
    }

    public void ProcessItem(IFruit fruit)
    {
        if (fruit is T)
        {

        }
        else
        {
            throw new NotSupportedException();
        }
    }
}

public class Apples : Fruits<IApple>, IApples
{
    public void MakeAppleJuice(IEnumerable<IApple> apples)
    {
        // Do the juice
    }
}

Then modify the Context class a bit:

public class Context
{
    public IApples Apples { get; set; }

    public IBananas Bananas { get; set; }

    public Context()
    {
        Apples = new Apples();
    }

    public IFruits<T> GetFruits<T>() where T : IFruit
    {
        return new Fruits<T>();
    }
}

Now the MakeAppleJuice() method is available ONLY when you access context.Apples.


问:
Delivering data between two classes
I'm trying search a beacon device and get the Majoy & Minor, then send the data to request, but I got the problems is I don't know how to send the data between the two part ..

I want to put the beacon.getMajor()
to jsonObject.put("uuid", a)

Thank you !

Here is my code.

```<code>private List<String> placesNearBeacon(Beacon beacon) {
    int a = beacon.getMajor();
    final String b = String.valueOf(beacon.getMajor());
    Log.v("show", String.valueOf(a));

    Intent intent = new Intent(this,AsyncLogin.class);
    intent.putExtra("MAJOR",a);

    startActivity(intent);
    if (a == 258){
        new AsyncLogin().execute(String.valueOf(a));
    }
    String beaconKey = String.format("%d:%d", beacon.getMajor(), beacon.getMinor());
    return Collections.emptyList();
}

enter code here

private class AsyncLogin extends AsyncTask<String, String, String>
{
    HttpURLConnection conn;
    URL url = null;

    Uri a = new Intent().getData();

    @Override
    protected String doInBackground(String... params) {

        try {

            // Enter URL address where your php file resides
            url = new URL("http://etriplay.com/app/beacon_GetInform.php");

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "exception";
        }
        try {
            // Setup HttpURLConnection class to send and receive data from php and mysql
            conn = (HttpURLConnection)url.openConnection();
            conn.setReadTimeout(READ_TIMEOUT);
            conn.setConnectTimeout(CONNECTION_TIMEOUT);
            conn.setRequestMethod("POST");

            // setDoInput and setDoOutput method depict handling of both send and receive
            conn.setDoInput(true);
            conn.setDoOutput(true);
            // JSON

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("userid", "membe00001");
            jsonObject.put("mail", "test@mail.com");
            jsonObject.put("uuid", a);

            Log.v("v", String.valueOf(jsonObject));

            // Open connection for sending data
            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(String.valueOf(jsonObject));
            writer.flush();
            writer.close();
            os.close();
            conn.connect();
</code>```

答:
In this case If you want object or something to put in json you can do ie by-:

```<code>try
{
      jsonObject.put("value",chatMessage.getDate());
}
catch (JSONException e)
{
       e.printStackTrace();
}
</code>```

as in jsonobject.put("key",value);

You can assign the int value,string value,boolean value or whatever you want

Title: Delivering data between two classes

Body:
I'm trying search a beacon device and get the Majoy & Minor, then send the data to request, but I got the problems is I don't know how to send the data between the two part ..

I want to put the beacon.getMajor()
to jsonObject.put("uuid", a)

Thank you !

Here is my code.

private List<String> placesNearBeacon(Beacon beacon) {
    int a = beacon.getMajor();
    final String b = String.valueOf(beacon.getMajor());
    Log.v("show", String.valueOf(a));

    Intent intent = new Intent(this,AsyncLogin.class);
    intent.putExtra("MAJOR",a);

    startActivity(intent);
    if (a == 258){
        new AsyncLogin().execute(String.valueOf(a));
    }
    String beaconKey = String.format("%d:%d", beacon.getMajor(), beacon.getMinor());
    return Collections.emptyList();
}

enter code here

private class AsyncLogin extends AsyncTask<String, String, String>
{
    HttpURLConnection conn;
    URL url = null;

    Uri a = new Intent().getData();

    @Override
    protected String doInBackground(String... params) {

        try {

            // Enter URL address where your php file resides
            url = new URL("http://etriplay.com/app/beacon_GetInform.php");

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "exception";
        }
        try {
            // Setup HttpURLConnection class to send and receive data from php and mysql
            conn = (HttpURLConnection)url.openConnection();
            conn.setReadTimeout(READ_TIMEOUT);
            conn.setConnectTimeout(CONNECTION_TIMEOUT);
            conn.setRequestMethod("POST");

            // setDoInput and setDoOutput method depict handling of both send and receive
            conn.setDoInput(true);
            conn.setDoOutput(true);
            // JSON

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("userid", "membe00001");
            jsonObject.put("mail", "test@mail.com");
            jsonObject.put("uuid", a);

            Log.v("v", String.valueOf(jsonObject));

            // Open connection for sending data
            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(String.valueOf(jsonObject));
            writer.flush();
            writer.close();
            os.close();
            conn.connect();

Body:
In this case If you want object or something to put in json you can do ie by-:

try
{
      jsonObject.put("value",chatMessage.getDate());
}
catch (JSONException e)
{
       e.printStackTrace();
}

as in jsonobject.put("key",value);

You can assign the int value,string value,boolean value or whatever you want


问:
Extracting values from a cell in a table using BeautifulSoup
I'm super new to Python and everything and I'm trying to get BeautifulSoup to return a number value from one specific cell from this one table from this page
(or any other similar page in the same wiki)

For now all that I have is:

```<code>url = ('http://unisonleague.wikia.com/wiki/Brynhildr,_Dual_Lancer_(Gear)')
r = requests.get(url)
data = r.text
soup = BeautifulSoup (data , 'html.parser')
table = soup.find (id='mw-content-text')
rows = table.find ('tr')
cells = rows.findAll('td')
</code>```

The value that I want is from the cell next to "Max Unison Chance", so "10004" in this case.

```<code><td colspan="2" style="background-color:#5B4F3D; color:#ffffff;"> 10004 </td>
</code>```

I tried

```<code> soup.findAll('td colspan="2"')
</code>```

and

```<code>soup.find('td colspan')
</code>```

but it just returned nothing or an empty list.

I'm not quite sure where to go from here, I thought about/tried indexing by number of rows (I believe this is row [14]) and maybe the cell but I couldn't seem to get the code right?

答:
Instead of doing a top down approach like you are doing use the tree structure of the html to your advantage. I assume you wanted to generalize this to other similarly formatted pages so what you can do is you can treat the cell with "Max Unison Chance" in it as an anchor point where you will then traverse the parse tree that Beautiful Soup creates to get to the cell that you're looking for. Here is the html that contains both the description cell and the cell you're looking for/

```<code><td style="height: 29px; background-color:#3F2D18; color:#ffffff; font-size:7pt;"> <b><span style="cursor:help;" title="Maximum stats used during a Unison Chance. It is the total of both stats with +198.">Max Unison Chance</span>:</b>
</td><td colspan="2" style="background-color:#5B4F3D; color:#ffffff;"> 10004
</td>
</code>```

Here you can directly get the html tag that contains "Max Unison Chance" by calling:

```<code>element = soup.find(text='Max Unison Chance')
</code>```

This will get you the element that has the text "Max Unison Chance" in it.
If you then look at where the tag that contains the number that you are looking for is relative to the element that you now have. You can see that you need to go up three nodes to get to the element that is next to the cell with 10004 in it.

To navigate to this cell we can use the parent attribute of the element we have and use attribute chaining:

great_grandparent = element.parent.parent.parent

We now need to get the next_sibling of our great_grandparent by:

```<code>target_cell = great_grandparent.next_sibling
</code>```

And lastly grabbing the element's text value and cleaning it up:

```<code>result = target_cell.text.strip()
</code>```

Then putting it all together:

```<code>from bs4 import BeautifulSoup
import requests
url = ('http://unisonleague.wikia.com/wiki/Brynhildr,_Dual_Lancer_(Gear)')
r = requests.get(url)
data = r.text
soup = BeautifulSoup (data , 'html.parser')
element= soup.find(text='Max Unison Chance')
result = element.parent.parent.parent.next_sibling.text.strip()
</code>```

An alternative way to do this is do use the parse order instead of the tree order so you could replace result with:

```<code>result = cell.next.next.next.strip()
</code>```

Since the next attribute refers to the next element based on how the parser that you are using works

Body:
I'm super new to Python and everything and I'm trying to get BeautifulSoup to return a number value from one specific cell from this one table from this page
(or any other similar page in the same wiki)

For now all that I have is:

url = ('http://unisonleague.wikia.com/wiki/Brynhildr,_Dual_Lancer_(Gear)')
r = requests.get(url)
data = r.text
soup = BeautifulSoup (data , 'html.parser')
table = soup.find (id='mw-content-text')
rows = table.find ('tr')
cells = rows.findAll('td')

The value that I want is from the cell next to "Max Unison Chance", so "10004" in this case.

 10004

I tried

 soup.findAll('td colspan="2"')

and

soup.find('td colspan')

but it just returned nothing or an empty list.

I'm not quite sure where to go from here, I thought about/tried indexing by number of rows (I believe this is row [14]) and maybe the cell but I couldn't seem to get the code right?

Body:
Instead of doing a top down approach like you are doing use the tree structure of the html to your advantage. I assume you wanted to generalize this to other similarly formatted pages so what you can do is you can treat the cell with "Max Unison Chance" in it as an anchor point where you will then traverse the parse tree that Beautiful Soup creates to get to the cell that you're looking for. Here is the html that contains both the description cell and the cell you're looking for/

<td style="height: 29px; background-color:#3F2D18; color:#ffffff; font-size:7pt;"> <b><span style="cursor:help;" title="Maximum stats used during a Unison Chance. It is the total of both stats with +198.">Max Unison Chance</span>:</b>
</td><td colspan="2" style="background-color:#5B4F3D; color:#ffffff;"> 10004
</td>

Here you can directly get the html tag that contains "Max Unison Chance" by calling:

element = soup.find(text='Max Unison Chance')

This will get you the element that has the text "Max Unison Chance" in it.
If you then look at where the tag that contains the number that you are looking for is relative to the element that you now have. You can see that you need to go up three nodes to get to the element that is next to the cell with 10004 in it.

To navigate to this cell we can use the parent attribute of the element we have and use attribute chaining:

great_grandparent = element.parent.parent.parent

We now need to get the next_sibling of our great_grandparent by:

target_cell = great_grandparent.next_sibling

And lastly grabbing the element's text value and cleaning it up:

result = target_cell.text.strip()

Then putting it all together:

from bs4 import BeautifulSoup
import requests
url = ('http://unisonleague.wikia.com/wiki/Brynhildr,_Dual_Lancer_(Gear)')
r = requests.get(url)
data = r.text
soup = BeautifulSoup (data , 'html.parser')
element= soup.find(text='Max Unison Chance')
result = element.parent.parent.parent.next_sibling.text.strip()

An alternative way to do this is do use the parse order instead of the tree order so you could replace result with:

result = cell.next.next.next.strip()

Since the next attribute refers to the next element based on how the parser that you are using works


问:
What am I doing wrong with realloc() in c?
I would like to ask, what am I doing wrong with memory management. I just want to read some int array from stdin and then print it. Starting from 2 elements, then allocating by 2 to amount I will be satisfied with.</p>

```<code>#include <stdio.h>
#include <stdlib.h>

void read (int * array, int * n, int * l) {
    int * tmp;
    printf("Enter values:\n");
    for (*l = 0; *l < *n; (*l)++) {
        if (*l == *n - 1) {
            (*n) *= 2;
            tmp = (int*) realloc (array, sizeof(int) * (*n));
            if (tmp != NULL) {
                array = tmp;
                free(tmp);
            }
            else {
                printf("Error!\n");
                free(tmp);
        }
        if (scanf("%d", &array[*l]) != 1) break;
    }
}

void print (int * array, int length) {
    int i;
    printf("Your values:\n");
    for (i = 0; i < length; i++) printf("%d ", array[i]);
}

int main (void) {
    int n = 2; /* number of array elements */
    int length = 0;
    int * array = (int *) malloc(sizeof(int) * n);

    read(array, &n, &length);
    print(array, length);
    free(array);
    return 0;
}
</code>```

答:
regarding: free(tmp);

This statement should not be anywhere in the posted code.

It frees the memory just allocated

====
the pointer 'n' better be pointing to an array, in the caller, that was allocated and not to some fixed array

====
When passing a pointer where the called function is going to change where that pointer points,  It must be passed (in the current scenario) as int **n.   This also means the calling function must pass the address of the pointer, not the contents of the pointer

====
variable (and parameter) names should indicate usage or content (or better, both)  the parameter names 'n' and 'l' are meaningless even in the current context

Body:
I would like to ask, what am I doing wrong with memory management. I just want to read some int array from stdin and then print it. Starting from 2 elements, then allocating by 2 to amount I will be satisfied with.

#include <stdio.h>
#include <stdlib.h>

void read (int * array, int * n, int * l) {
    int * tmp;
    printf("Enter values:\n");
    for (*l = 0; *l < *n; (*l)++) {
        if (*l == *n - 1) {
            (*n) *= 2;
            tmp = (int*) realloc (array, sizeof(int) * (*n));
            if (tmp != NULL) {
                array = tmp;
                free(tmp);
            }
            else {
                printf("Error!\n");
                free(tmp);
        }
        if (scanf("%d", &array[*l]) != 1) break;
    }
}

void print (int * array, int length) {
    int i;
    printf("Your values:\n");
    for (i = 0; i < length; i++) printf("%d ", array[i]);
}

int main (void) {
    int n = 2; /* number of array elements */
    int length = 0;
    int * array = (int *) malloc(sizeof(int) * n);

    read(array, &n, &length);
    print(array, length);
    free(array);
    return 0;
}


问:
Setting maximum number of characters of `UITextView ` and `UITextField `
I'd like to set a maximum number of characters allowed to be typed both in a UITextView and a UITextField. This number will be then shown in a little label (for user's reference, Twitter Style.)

答:
Swift 4 , Xcode 9.1 GM</p>

```<code>func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    return textView.text.count + (text.count - range.length) <= 200
}
</code>```

Body:
Swift 4 , Xcode 9.1 GM

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    return textView.text.count + (text.count - range.length) <= 200
}

ContentLicense: CC BY-SA 4.0


问:
How a multidimensional array value assignation works in this case?
Why this function does not return an string with the first letter of each word on upper case?</p>

```<code>function titleCase(str) {
     str = str.split(' ');
     for (var i = 0; i < str.length; i++) {
         str[i][0] = str[i][0].toUpperCase();
         console.log(str);
     }
     return str;
}
</code>```

答:
Ty this:

```<code>function titleCase(str) {
     str = str.split(' ');
     for (var i = 0; i < str.length; i++) {
         str[i] = str[i].charAt(0).toUpperCase() + str[i].slice(1);
         console.log(str[i], 'i');
     }
     return str;
}
</code>```

to explain further:

Get the First letter and convert it to uppercase

```<code>str[i].charAt(0).toUpperCase()
</code>```

This is the rest of the word without the first letter.

```<code>str[i].slice(1);
</code>```

Body:
Why this function does not return an string with the first letter of each word on upper case?

function titleCase(str) {
     str = str.split(' ');
     for (var i = 0; i < str.length; i++) {
         str[i][0] = str[i][0].toUpperCase();
         console.log(str);
     }
     return str;
}

Body:
Ty this:

function titleCase(str) {
     str = str.split(' ');
     for (var i = 0; i < str.length; i++) {
         str[i] = str[i].charAt(0).toUpperCase() + str[i].slice(1);
         console.log(str[i], 'i');
     }
     return str;
}

to explain further:

Get the First letter and convert it to uppercase

str[i].charAt(0).toUpperCase()

This is the rest of the word without the first letter.

str[i].slice(1);


问:
make textbox accept only English numbers or ascii numbers in asp.net C#
How can I make textbox accept just English or ASCII numbers? not Arabic numbers.

I'm working on asp.net C#.

答:
You can use on keypress and check for input value.</p>

```<code>function isCharacterKeyPress(evt) {
            if ((event.charCode >= 48 && event.charCode <= 57) || (event.charCode >= 65 && event.charCode <= 90) || (event.charCode >= 97 && event.charCode <= 122))
                return true;
            return false;
        }

<asp:TextBox runat="server" onkeypress="return isCharacterKeyPress(event)" ID="txtAbcd" />
</code>```

Body:
You can use on keypress and check for input value.

function isCharacterKeyPress(evt) {
            if ((event.charCode >= 48 && event.charCode <= 57) || (event.charCode >= 65 && event.charCode <= 90) || (event.charCode >= 97 && event.charCode <= 122))
                return true;
            return false;
        }

<asp:TextBox runat="server" onkeypress="return isCharacterKeyPress(event)" ID="txtAbcd" />


答:
you filter and print as below

```<code>tuple2.filter(_._2.length == 4).foreach(x => println(x._1))
</code>```

You should have output as

```<code>2
4
5
</code>```

Title: How to calculate length of string in a tuple in scala

Body:
you filter and print as below

tuple2.filter(_._2.length == 4).foreach(x => println(x._1))

You should have output as

2
4
5


问:
Is project-tango still usable for ar development?
I I am doing a small demo project on indoor navigation recently. I have chosen project tango whit Unity and I just bought the lenovo Phab 2 Pro. However I just found that tango has been abandoned by google...

So I want to know should I countinue to use tango if I just want to develope a AR indoor navigation project,not considering business?

答: I'm in your situation too. Just bought ZenFone AR. I'm going to learn AR using this device and project tango. Hoping the depth cameras will rule the AR/MR world again :)))</p>


问:
"_version_ field must exist in schema", but it already does
I've taken over an abandoned project that is supposed to use Solr for searching and indexing, but Solr isn't working properly. There appear to be 3 cores, none of which had a conf directory or schema.xml files, so I wrote the schema below and pasted it onto the 3 cores' conf

```<code><?xml version="1.0" encoding="UTF-8" ?>
<schema name="mwplus_schema" version="1.6">

  <field name="_version_" type="long" indexed="true" stored="false" />
  <field name="pid" type="string" indexed="true" stored="true" required="true" multiValued="false"/>
  <field name="text" type="text" indexed="true" stored="true" multiValued="true"/>

  <uniqueKey>pid</uniqueKey>
  <defaultSearchField>text</defaultSearchField>
  <solrQueryParser defaultOperator="OR"/>

</schema>
</code>```

As you can see, the _version_ field exists, however when I do bin/solr start -f -p <port>, none of the 3 cores that are using this schema are able to be created because of this error:

Error creating core [xmeld_shard1_replica1]: Unable to use updateLog: _version_ field must exist in schema, using indexed="true" or docValues="true", stored="true" and multiValued="false" (_version_ does not exist)

I'm sorry I can't post more details, I'm not too familiar with Solr or with the project itself. Any suggestions or ideas on why this is happening and how to fix it?

EDIT: I changed schema.xml based on the answer to another question in SO, but the problem persists. Above is the updated version.

答:
You should make the stored="true" in  your schema against the _version_ field type, it will definitely start

e.g.

```<code><field name="_version_" type="long" indexed="true" stored="true" />
</code>```

Body:
I've taken over an abandoned project that is supposed to use Solr for searching and indexing, but Solr isn't working properly. There appear to be 3 cores, none of which had a conf directory or schema.xml files, so I wrote the schema below and pasted it onto the 3 cores' conf

<?xml version="1.0" encoding="UTF-8" ?>
<schema name="mwplus_schema" version="1.6">

  <field name="_version_" type="long" indexed="true" stored="false" />
  <field name="pid" type="string" indexed="true" stored="true" required="true" multiValued="false"/>
  <field name="text" type="text" indexed="true" stored="true" multiValued="true"/>

  <uniqueKey>pid</uniqueKey>
  <defaultSearchField>text</defaultSearchField>
  <solrQueryParser defaultOperator="OR"/>

</schema>

As you can see, the _version_ field exists, however when I do bin/solr start -f -p <port>, none of the 3 cores that are using this schema are able to be created because of this error:

Error creating core [xmeld_shard1_replica1]: Unable to use updateLog: _version_ field must exist in schema, using indexed="true" or docValues="true", stored="true" and multiValued="false" (_version_ does not exist)

I'm sorry I can't post more details, I'm not too familiar with Solr or with the project itself. Any suggestions or ideas on why this is happening and how to fix it?

EDIT: I changed schema.xml based on the answer to another question in SO, but the problem persists. Above is the updated version.

Body:
You should make the stored="true" in  your schema against the _version_ field type, it will definitely start

e.g.

<field name="_version_" type="long" indexed="true" stored="true" />


问:
PDF compressor for DELPHI 2007
Need a PDF compressor that I can use from DELPHI 2007.

What is the best one out there?

UPDATE ---

By PDF compressor I mean some way to compress an existing PDF. I don’t need to create new PDF files.

The usage that I’ll do with it, simple, I have in my applications the possibility to associate a file to a product, an entity, equipment whatever, and if the file is a PDF I want to be able reduce its size.

There some tools that can do this with no need to actually zip the file, what would mean that to see it you would have to decompress(unzip), this tools jut reduce the size.

So a PDF compressor, or call it what you will, is just this.

答:
There is an on-line PDF compressor that I heard is giving good results.

It should not be too hard to wrap that in Delphi for occasional use.

ContentLicense: CC BY-SA 2.5

Title: PDF compressor for DELPHI 2007


问:
MySQL JOIN the most recent row only?
I have a table customer that stores a customer_id, email and reference. There is an additional table customer_data that stores a historical record of the changes made to the customer, i.e. when there's a change made a new row is inserted.

In order to display the customer information in a table, the two tables need to be joined, however only the most recent row from customer_data should be joined to the customer table.

It gets a little more complicated in that the query is paginated, so has a limit and an offset.

How can I do this with MySQL? I think I'm wanting to put a DISTINCT in there somewhere...

The query at the minute is like this-

```<code>SELECT *, CONCAT(title,' ',forename,' ',surname) AS name
FROM customer c
INNER JOIN customer_data d on c.customer_id=d.customer_id
WHERE name LIKE '%Smith%' LIMIT 10, 20
</code>```

Additionaly, am I right in thinking I can use CONCAT with LIKE in this way?

(I appreciate that INNER JOIN might be the wrong type of JOIN to use. I actually have no clue what the difference is between the different JOINs. I'm going to look into that now!)

答:
You can also do this</p>

```<code>SELECT    CONCAT(title, ' ', forename, ' ', surname) AS name
FROM      customer c
LEFT JOIN  (
              SELECT * FROM  customer_data ORDER BY id DESC
          ) customer_data ON (customer_data.customer_id = c.customer_id)
GROUP BY  c.customer_id
WHERE     CONCAT(title, ' ', forename, ' ', surname) LIKE '%Smith%'
LIMIT     10, 20;
</code>```

Title: MySQL JOIN the most recent row only?

Body:
I have a table customer that stores a customer_id, email and reference. There is an additional table customer_data that stores a historical record of the changes made to the customer, i.e. when there's a change made a new row is inserted.

In order to display the customer information in a table, the two tables need to be joined, however only the most recent row from customer_data should be joined to the customer table.

It gets a little more complicated in that the query is paginated, so has a limit and an offset.

How can I do this with MySQL? I think I'm wanting to put a DISTINCT in there somewhere...

The query at the minute is like this-

SELECT *, CONCAT(title,' ',forename,' ',surname) AS name
FROM customer c
INNER JOIN customer_data d on c.customer_id=d.customer_id
WHERE name LIKE '%Smith%' LIMIT 10, 20

Additionaly, am I right in thinking I can use CONCAT with LIKE in this way?

(I appreciate that INNER JOIN might be the wrong type of JOIN to use. I actually have no clue what the difference is between the different JOINs. I'm going to look into that now!)

Body:
You can also do this

SELECT    CONCAT(title, ' ', forename, ' ', surname) AS name
FROM      customer c
LEFT JOIN  (
              SELECT * FROM  customer_data ORDER BY id DESC
          ) customer_data ON (customer_data.customer_id = c.customer_id)
GROUP BY  c.customer_id
WHERE     CONCAT(title, ' ', forename, ' ', surname) LIKE '%Smith%'
LIMIT     10, 20;


问:
Deleting duplicate edges from edge table
I have thought of following query but it seems syntactically wrong.

```<code> delete from table where geom_line in(select distinct(a.geom_line) from table
 a ,table b where a.source=b.target and b.source=a.target);
</code>```

my idea is to delete on of the edges of there exists edges where same source to target is target to source in another edge that is two edges for nodes 1 and 2, from 1->2 and 2->1 and i will delete one of them.

When running only the subquery i get distinct edges with there "geom_lines" as 2000 rows while when i run the whole query 4000 rows are deleted what could be wrong here?

答:
That should be as simple as</p>

```<code>DELETE FROM "table" a
USING "table" b
WHERE a.source = b.target
  AND a.target = b.source
  AND a.source > a.target;
</code>```

Body:
I have thought of following query but it seems syntactically wrong.

 delete from table where geom_line in(select distinct(a.geom_line) from table
 a ,table b where a.source=b.target and b.source=a.target);

my idea is to delete on of the edges of there exists edges where same source to target is target to source in another edge that is two edges for nodes 1 and 2, from 1->2 and 2->1 and i will delete one of them.

When running only the subquery i get distinct edges with there "geom_lines" as 2000 rows while when i run the whole query 4000 rows are deleted what could be wrong here?

Body:
That should be as simple as

DELETE FROM "table" a
USING "table" b
WHERE a.source = b.target
  AND a.target = b.source
  AND a.source > a.target;


问:
How can I split and insert a string into a SQL Server table?
I need to insert these IMS080','IMS108','IMS218 values into temptable in separate rows, like this:

```<code>row 1: IMS080
row 2: IMS108
row 3: IMS218
</code>```

Query :

```<code>INSERT INTO #TableName
    SELECT UserID
    FROM ('IMS080', 'IMS108', 'IMS218')
</code>```

Thanks in advance

答:
```<code>    CREATE TABLE #TableName(ID int identity(1,1),userid varchar(50));
    INSERT INTO #TableName
        SELECT value as UserID FROM  STRING_SPLIT('IMS080,IMS108,IMS218',',') ORDER BY value

    SELECT * FROM #TableName

------------
ID  userid
----------
1   IMS080
2   IMS108
3   IMS218
</code>```

Body:
I need to insert these IMS080','IMS108','IMS218 values into temptable in separate rows, like this:

row 1: IMS080
row 2: IMS108
row 3: IMS218

Query :

INSERT INTO #TableName
    SELECT UserID
    FROM ('IMS080', 'IMS108', 'IMS218')

Thanks in advance


问:
JavaScript customize text from dynamically created table
I was having some problem when trying to dynamically add a table to HTML using JavaScript.

I got an array and my sample data is [0,0,5,2,7,5,4,5,0]

My HTML:

```<code><div id="ftw" style="min-width:80px; overflow:auto; overflow-x:hidden; overflow-y:hidden; display:none;">
    <table id="ft" class="table" style="font-size:13.5px">

    </table>
</div>
</code>```

My JavaScript:

```<code>document.getElementById('ftw').style.display = 'block';
        var table = document.getElementById("ft");

        // helper function
        function addCell(tr, text) {
            var td = tr.insertCell();
            td.textContent = text;
            return td;
        }
</code>```

I wanted to do something like when the item == 0, then I set the font to red color. If item > 0, I wanted to bold the item.

Any ideas how can I achieve this?

答:
Here the JsFiddle..

I change td.textContent to td.innerHTML and add row.style.color="red"; addCell(row, 'Every ' + item + ' day(s)');

```<code> function addCell(tr, text) {
            var td = tr.insertCell();
            td.innerHTML = text;
            return td;
        }

dataset.forEach(function (item) {
            var row = table.insertRow();
            if(item == 0){
            row.style.color="red";
                addCell(row, 'No record');
            }else{
                addCell(row, 'Every <b>' + item + '</b> day(s)');

            }
        });
</code>```

Body:
I was having some problem when trying to dynamically add a table to HTML using JavaScript.

I got an array and my sample data is [0,0,5,2,7,5,4,5,0]

My HTML:

My JavaScript:

document.getElementById('ftw').style.display = 'block';
        var table = document.getElementById("ft");

        // helper function
        function addCell(tr, text) {
            var td = tr.insertCell();
            td.textContent = text;
            return td;
        }

I wanted to do something like when the item == 0, then I set the font to red color. If item > 0, I wanted to bold the item.

Any ideas how can I achieve this?

Body:
Here the JsFiddle..

I change td.textContent to td.innerHTML and add row.style.color="red"; addCell(row, 'Every <b>' + item + '</b> day(s)');

 function addCell(tr, text) {
            var td = tr.insertCell();
            td.innerHTML = text;
            return td;
        }

dataset.forEach(function (item) {
            var row = table.insertRow();
            if(item == 0){
            row.style.color="red";
                addCell(row, 'No record');
            }else{
                addCell(row, 'Every <b>' + item + '</b> day(s)');

            }
        });


问:
creating a drawable from sd card to set as a background in android
I am trying to use an image from the sd card and set it as the background for a relativelayout.  I have tried other solutions that i have found here and elsewhere but they havent seemed to work for me.  here is my code.  I have commented out other ways that i have tried and didnt work.  the only thing that worked for me was using setBackgroudnResource and using a resource from the app, but this was just to test to make sure mRoot was set up correctly.  when I have tried all the other ways, it just doesn't set anything.  Anyone know what I am doing wrong, or if there is a better way to do this?</p>

```<code>        //one way i tired...
//String extDir = Environment.getExternalStorageDirectory().toString();
//Drawable d = Drawable.createFromPath(extDir + "/pic.png");
//mRoot.setBackgroundDrawable(d);

//another way tried..
//Drawable d = Drawable.createFromPath("/sdcard/pic.png");
//mRoot.setBackgroundDrawable(d);

//last way i tried...
mRoot.setBackgroundDrawable(Drawable.createFromPath(new File(Environment.getExternalStorageDirectory(), "pic.png").getAbsolutePath()));

//worked, only to verify mRoot was setup correctly and it could be changed
//mRoot.setBackgroundResource(R.drawable.bkg);
</code>```

答:
I suggest checking that the drawable is being loaded correctly.  Some things to try:

Try using a different image on the sd card

Put pic.png in R.drawable and make sure mRoot.setBackgroundResource() does what you expect

After loading the drawable, check d.getBounds() to make sure it is what you expect

Body:
I am trying to use an image from the sd card and set it as the background for a relativelayout.  I have tried other solutions that i have found here and elsewhere but they havent seemed to work for me.  here is my code.  I have commented out other ways that i have tried and didnt work.  the only thing that worked for me was using setBackgroudnResource and using a resource from the app, but this was just to test to make sure mRoot was set up correctly.  when I have tried all the other ways, it just doesn't set anything.  Anyone know what I am doing wrong, or if there is a better way to do this?

        //one way i tired...
//String extDir = Environment.getExternalStorageDirectory().toString();
//Drawable d = Drawable.createFromPath(extDir + "/pic.png");
//mRoot.setBackgroundDrawable(d);

//another way tried..
//Drawable d = Drawable.createFromPath("/sdcard/pic.png");
//mRoot.setBackgroundDrawable(d);

//last way i tried...
mRoot.setBackgroundDrawable(Drawable.createFromPath(new File(Environment.getExternalStorageDirectory(), "pic.png").getAbsolutePath()));

//worked, only to verify mRoot was setup correctly and it could be changed
//mRoot.setBackgroundResource(R.drawable.bkg);


问:
Why feature scaling in SVM?
I found that scaling in SVM (Support Vector Machine) problems really improve its performance.
I have read this explanation:

The main advantage of scaling is to avoid attributes in greater numeric ranges dominating those in smaller numeric ranges.

Unfortunately this didn't help me. Can somebody provide a better explanation?

答:
Yes if normalisation is not there then contour will be skinny thus with normalisation:

Values be within the range

Speeds up the calculation of theta because number of calculations require will be less

Title: Why feature scaling in SVM?


问:
How do I keep running a Java Selenium script every five minutes when the system is shutdown and add the results onto a Google Spreadsheet?
I've written a Program in Eclipse using Java and Selenium Webdriver to

Go to a website and check the value of a number on the website (say stock prices)

If the value of the number is different from the last time the script was run, the script runs, else it terminates. (if the current stock price is different from when the script was run last time, the script runs. If the value is the same as last time, then the script terminates)

How do I

Automatically run it every 5 minutes

Keep running it even when my system is turned off?

Transfer all data onto a Google Sheet as and when the script is run?

答:
As per your question as want to loop and repeat the Test Execution at pre-defined interval and other conditions, there can be a couple of options available as follows :

Automatic Loops :

You can use the ScheduledExecutorService Interface from java.util.concurrent

Use a Continous Integration tool like Jenkins to support building, deploying and automating any project.

You can use the functionalities extended by Windows Scheduler to start your Test Execution.

Configure a Cron Job to execute your Test Suite at pre-defined intervals.

Execution when system is turned off :

Use BrowserStack

Use SauceLabs

Transfer all data into Cloud

Use G Suite


问:
what is wrong with this code of login validate form using php
In this code login page is going to validate form and if password is correct then its working correct but if not then its not working else code why?
Here is code

```<code><?php
    if(isset($_POST['submit']))
    {
        $user=$_POST['user'];
        $password=$_POST['password'];
        $query="select * from users where user='$user' and password='$password'";
        $run=mysqli_query($con,$query);
        if(mysqli_num_rows($run)>0){
            $row=mysqli_fetch_array($run);
            $u_name=$row['user'];
            $u_password=$row['password'];
            if($user==$u_name && $password==$u_password){
                if(isset($_POST['remember'])){
                    setcookie('user',$user,time()+60*60*7);
                    setcookie('password',$password,time()+60*60*7);
                }
                session_start();
                $_SESSION['user']=$user;
                echo "<script> window.location.assign('../index.php'); </script>";
                exit();
            }
            else{
                echo "<script> alert('incorrect user name or password')</script>";
                echo "<script> window.location.assign('login.php'); </script>";
            }
        }
    }
?>
</code>```

if condition  part is working correctly but not else condition  part .help me please.

答:
Your else is in your first if(mysqli_num_rows($run)>0) condition.

That's why this is not working

correct code is

```<code><?php
    if(isset($_POST['submit']))
    {
        $user=$_POST['user'];
        $password=$_POST['password'];
        $query="select * from users where user='$user' and password='$password'";
        $run=mysqli_query($con,$query);
        if(mysqli_num_rows($run)>0){
            $row=mysqli_fetch_array($run);
            $u_name=$row['user'];
            $u_password=$row['password'];
            if($user==$u_name && $password==$u_password){
                if(isset($_POST['remember'])){
                    setcookie('user',$user,time()+60*60*7);
                    setcookie('password',$password,time()+60*60*7);
                }
                session_start();
                $_SESSION['user']=$user;
                echo "<script> window.location.assign('../index.php'); </script>";
                exit();
            }
        }
        else{
            echo "<script> alert('incorrect user name or password')</script>";
            echo "<script> window.location.assign('login.php'); </script>";
        }
    }
?>
</code>```

Body:
In this code login page is going to validate form and if password is correct then its working correct but if not then its not working else code why?
Here is code

<?php
    if(isset($_POST['submit']))
    {
        $user=$_POST['user'];
        $password=$_POST['password'];
        $query="select * from users where user='$user' and password='$password'";
        $run=mysqli_query($con,$query);
        if(mysqli_num_rows($run)>0){
            $row=mysqli_fetch_array($run);
            $u_name=$row['user'];
            $u_password=$row['password'];
            if($user==$u_name && $password==$u_password){
                if(isset($_POST['remember'])){
                    setcookie('user',$user,time()+60*60*7);
                    setcookie('password',$password,time()+60*60*7);
                }
                session_start();
                $_SESSION['user']=$user;
                echo "";
                exit();
            }
            else{
                echo "";
                echo "";
            }
        }
    }
?>

if condition  part is working correctly but not else condition  part .help me please.

Body:
Your else is in your first if(mysqli_num_rows($run)>0) condition.

That's why this is not working

correct code is

<?php
    if(isset($_POST['submit']))
    {
        $user=$_POST['user'];
        $password=$_POST['password'];
        $query="select * from users where user='$user' and password='$password'";
        $run=mysqli_query($con,$query);
        if(mysqli_num_rows($run)>0){
            $row=mysqli_fetch_array($run);
            $u_name=$row['user'];
            $u_password=$row['password'];
            if($user==$u_name && $password==$u_password){
                if(isset($_POST['remember'])){
                    setcookie('user',$user,time()+60*60*7);
                    setcookie('password',$password,time()+60*60*7);
                }
                session_start();
                $_SESSION['user']=$user;
                echo "<script> window.location.assign('../index.php'); </script>";
                exit();
            }
        }
        else{
            echo "<script> alert('incorrect user name or password')</script>";
            echo "<script> window.location.assign('login.php'); </script>";
        }
    }
?>


问:
Using Dialogflow Inline Editor
I am a beginning user of Dialogflow and have two questions about
the use of the Inline Editor:

1 - Where are the files shown by the Inline Editor stored?  I assume they are stored within the Firebase database but not certain.

2 - Is any explicit "save" action required when using the Inline
Editor?

Thanks for any help.
Jim

答:
The inline editor directly uploads it content to your firebase functions on the Google project you are using for your DialogFlow agent from which you are uploading. This code in turn gets saved in the Google cloud function as firebase is built on Google cloud. You can find the code only over there. you can even edit directly in your Google cloud functions.
Hope this helps</p>

Title: Using Dialogflow Inline Editor


问:
Jmeter-Ant xslt-report: BUILD FAILED Test.jtl does not exist error although i have Test.jtl
I am trying to run my Test.jmx file through below ant cmd:
C:\apache-ant-1.10.1-bin\bin>ant

I got the following error:

C:\apache-ant-1.10.1-bin\bin>ant
Buildfile: C:\apache-ant-1.10.1-bin\bin\build.xml

run:
     [echo] funcMode = false
   [jmeter] Executing test plan: C:\apache-ant-1.10.1-bin\bin\Test.jmx ==> C:\apache-ant-1.10.1-bin\bin\Test.jtl

_message_xalan:

xslt-report:

BUILD FAILED
C:\apache-ant-1.10.1-bin\bin\build.xml:124: input file C:\apache-ant-1.10.1-bin\bin\Test.jtl does not exist

Total time: 4 seconds

C:\apache-ant-1.10.1-bin\bin>
```

<p>I fixed this issue by creating a new Test.jtl file.</p>

<p>Now I am getting this error:</p>

<pre class="lang-html prettyprint-override"><code>C:\apache-ant-1.10.1-bin\bin>ant -Dtestpath=C:\apache-ant-1.10.1-bin\bin\ -Dtest=Test
Buildfile: C:\apache-ant-1.10.1-bin\bin\build.xml

run:
     [echo] funcMode = false
   [jmeter] Executing test plan: C:\apache-ant-1.10.1-bin\bin\Test.jmx ==> C:\apache-ant-1.10.1-bin\bin\Test.jtl

_message_xalan:

xslt-report:
     [xslt] Processing C:\apache-ant-1.10.1-bin\bin\Test.jtl to C:\apache-ant-1.10.1-bin\bin\Test.html
     [xslt] Loading stylesheet C:\apache-ant-1.10.1-bin\bin\jmeter-results-report_21.xsl
     [xslt] C:\apache-ant-1.10.1-bin\bin\Test.jtl:1:1: Fatal Error! Premature end of file.
     [xslt] Failed to process C:\apache-ant-1.10.1-bin\bin\Test.jtl

BUILD FAILED
C:\apache-ant-1.10.1-bin\bin\build.xml:124: Fatal error during transformation using C:\apache-ant-1.10.1-bin\bin\jmeter-results-report_21.xsl: Premature end of file.; SystemID: file:/C:/apache-ant-1.10.1-bin/bin/Test.jtl; Line#: 1; Column#: 1

Total time: 3 seconds
</code>```

答:
use "resultlogdir" instead of "resultlog"
so change the build.xml  like this:

```<code><jmeter
jmeterhome="${jmeter.home}"
testplan ="${testpath}/${test}.jmx"
resultlogdir="${testpath}/log">
</code>```

and also the "in" property in  :
   in="${testpath}/log/${test}.jtl"

I have no idea how to explain why, but it worked in my computer

Body:
I am trying to run my Test.jmx file through below ant cmd:
C:\apache-ant-1.10.1-bin\bin>ant

I got the following error:

C:\apache-ant-1.10.1-bin\bin>ant
Buildfile: C:\apache-ant-1.10.1-bin\bin\build.xml

run:
     [echo] funcMode = false
   [jmeter] Executing test plan: C:\apache-ant-1.10.1-bin\bin\Test.jmx ==> C:\apache-ant-1.10.1-bin\bin\Test.jtl

_message_xalan:

xslt-report:

BUILD FAILED
C:\apache-ant-1.10.1-bin\bin\build.xml:124: input file C:\apache-ant-1.10.1-bin\bin\Test.jtl does not exist

Total time: 4 seconds

C:\apache-ant-1.10.1-bin\bin>

I fixed this issue by creating a new Test.jtl file.

Now I am getting this error:

C:\apache-ant-1.10.1-bin\bin>ant -Dtestpath=C:\apache-ant-1.10.1-bin\bin\ -Dtest=Test
Buildfile: C:\apache-ant-1.10.1-bin\bin\build.xml

run:
     [echo] funcMode = false
   [jmeter] Executing test plan: C:\apache-ant-1.10.1-bin\bin\Test.jmx ==> C:\apache-ant-1.10.1-bin\bin\Test.jtl

_message_xalan:

xslt-report:
     [xslt] Processing C:\apache-ant-1.10.1-bin\bin\Test.jtl to C:\apache-ant-1.10.1-bin\bin\Test.html
     [xslt] Loading stylesheet C:\apache-ant-1.10.1-bin\bin\jmeter-results-report_21.xsl
     [xslt] C:\apache-ant-1.10.1-bin\bin\Test.jtl:1:1: Fatal Error! Premature end of file.
     [xslt] Failed to process C:\apache-ant-1.10.1-bin\bin\Test.jtl

BUILD FAILED
C:\apache-ant-1.10.1-bin\bin\build.xml:124: Fatal error during transformation using C:\apache-ant-1.10.1-bin\bin\jmeter-results-report_21.xsl: Premature end of file.; SystemID: file:/C:/apache-ant-1.10.1-bin/bin/Test.jtl; Line#: 1; Column#: 1

Total time: 3 seconds

Body:
use "resultlogdir" instead of "resultlog"
so change the build.xml  like this:

<jmeter
jmeterhome="${jmeter.home}"
testplan ="${testpath}/${test}.jmx"
resultlogdir="${testpath}/log">

and also the "in" property in  :
   in="${testpath}/log/${test}.jtl"

I have no idea how to explain why, but it worked in my computer


问:
How to make commands using str array in for loop by Python
I want to do something like this

```<code>CMD_LIST = ['ls -l', 'echo Mama Mia', 'echo bla bla bla']
for i in range(len(CMD_LIST)):
    subprocess.call(CMD_LIST[1])
</code>```

How can i do list of commands in for loop?

答:
Python lets you loop directly over iterables like your command list

```<code>for cmd in CMD_LIST:
    subprocess.call(cmd)
</code>```

This is much more readable and avoids errors in indexed looping.

Body:
I want to do something like this

CMD_LIST = ['ls -l', 'echo Mama Mia', 'echo bla bla bla']
for i in range(len(CMD_LIST)):
    subprocess.call(CMD_LIST[1])

How can i do list of commands in for loop?

Body:
Python lets you loop directly over iterables like your command list

for cmd in CMD_LIST:
    subprocess.call(cmd)

This is much more readable and avoids errors in indexed looping.


问:
Delete Oracle Change Notifications
I'm trying to deregister change notifications in Oracle 12c by executing:

```<code>DBMS_CQ_NOTIFICATION.DEREGISTER(24906);
</code>```

But this gives an error:

ORA-29970: Specified registration id does not exist

Although when I query the USER_CHANGE_NOTIFICATION_REGS view it does clearly state the correct regid.

Any one encountered this problem?

答:
Solution according to the MOS-Note:

Use patched Oracle version (bug fix included in 12.1 or later and the 11.2.0.4 Database and Client patchset)

enable following event to consume the fix: event "10865 trace name context forever, level 1".

Title: Delete Oracle Change Notifications

Body:
I'm trying to deregister change notifications in Oracle 12c by executing:

DBMS_CQ_NOTIFICATION.DEREGISTER(24906);

But this gives an error:

ORA-29970: Specified registration id does not exist

Although when I query the USER_CHANGE_NOTIFICATION_REGS view it does clearly state the correct regid.

Any one encountered this problem?


问:
Call FFmpeg via JavaCPP：Caused by: java.lang.NoClassDefFoundError: Could not initialize class org.bytedeco.javacpp.avformat$AVFormatContext
In CentOS, use javacpp call FFmpeg to do video cropping a frame, in my own development machine using this code is no problem, but in centos6 reported NoClassDefFound: Could not initialize class org.bytedeco.javacpp.avutil

```<code>Caused by: java.lang.NoClassDefFoundError: Could not initialize class org.bytedeco.javacpp.avformat$AVFormatContext
    at org.bytedeco.javacv.FFmpegFrameGrabber.startUnsafe(FFmpegFrameGrabber.java:383) ~[javacv-1.0.jar:1.0]
    at org.bytedeco.javacv.FFmpegFrameGrabber.start(FFmpegFrameGrabber.java:377) ~[javacv-1.0.jar:1.0]
    at cn.xxtui.support.upload.BasicUpload.convertImage(BasicUpload.java:211) ~[classes/:?]
    at cn.xxtui.support.upload.BasicUpload.upload(BasicUpload.java:197) ~[classes/:?]
    at cn.com.ql.wiseBeijing.upload.UploadImage.upload(UploadImage.java:144) ~[classes/:?]
    at cn.com.ql.wiseBeijing.upload.UploadImage.imageCategory(UploadImage.java:51) ~[classes/:?]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.7.0_25]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[?:1.7.0_25]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.7.0_25]
    at java.lang.reflect.Method.invoke(Method.java:606) ~[?:1.7.0_25]
    at org.apache.cxf.service.invoker.AbstractInvoker.performInvocation(AbstractInvoker.java:180) ~[cxf-core-3.1.12.jar:3.1.12]
    at org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:96) ~[cxf-core-3.1.12.jar:3.1.12]
    ... 37 more
</code>```

This is my pom configuration：

```<code><dependency>
    <groupId>org.bytedeco</groupId>
    <artifactId>javacv</artifactId>
    <version>1.0</version>
</dependency>
<dependency>
    <groupId>org.bytedeco</groupId>
    <artifactId>javacpp</artifactId>
    <version>1.0</version>
</dependency>
<dependency>
    <groupId>com.github.hoary.ffmpeg</groupId>
    <artifactId>FFmpeg-linux-x86_64</artifactId>
    <version>2.0.1.1
    </version>
</dependency>
<dependency>
    <groupId>org.bytedeco.javacpp-presets</groupId>
    <artifactId>ffmpeg</artifactId>
    <version>2.7.1-1.0</version>
</dependency>
</code>```

This is my code：

```<code>public String convertImage(String filePath, String imagePath) throws IOException, FrameGrabber.Exception {
    FFmpegFrameGrabber g = new FFmpegFrameGrabber(filePath);
    g.start();
    Java2DFrameConverter java2DFrameConverter = new Java2DFrameConverter();
    BufferedImage bufferedImage = java2DFrameConverter.convert(g.grabImage());
    String path = imagePath + System.currentTimeMillis() + ".png";
    ImageIO.write(bufferedImage, "png", new File(path));
    g.stop();
    return path;
}
</code>```

答:
Make sure you have all libraries installed on your computer that are needed.
In this case, "javacv-platform".

This is what gives the hint to think in that direction:

```<code>java.lang.NoClassDefFoundError: Could not initialize class org.bytedeco.javacpp.avformat$AVFormatContext
</code>```

"NoClassDefFound" almost always means that something required is missing.

Body:
In CentOS, use javacpp call FFmpeg to do video cropping a frame, in my own development machine using this code is no problem, but in centos6 reported NoClassDefFound: Could not initialize class org.bytedeco.javacpp.avutil

Caused by: java.lang.NoClassDefFoundError: Could not initialize class org.bytedeco.javacpp.avformat$AVFormatContext
    at org.bytedeco.javacv.FFmpegFrameGrabber.startUnsafe(FFmpegFrameGrabber.java:383) ~[javacv-1.0.jar:1.0]
    at org.bytedeco.javacv.FFmpegFrameGrabber.start(FFmpegFrameGrabber.java:377) ~[javacv-1.0.jar:1.0]
    at cn.xxtui.support.upload.BasicUpload.convertImage(BasicUpload.java:211) ~[classes/:?]
    at cn.xxtui.support.upload.BasicUpload.upload(BasicUpload.java:197) ~[classes/:?]
    at cn.com.ql.wiseBeijing.upload.UploadImage.upload(UploadImage.java:144) ~[classes/:?]
    at cn.com.ql.wiseBeijing.upload.UploadImage.imageCategory(UploadImage.java:51) ~[classes/:?]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.7.0_25]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[?:1.7.0_25]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.7.0_25]
    at java.lang.reflect.Method.invoke(Method.java:606) ~[?:1.7.0_25]
    at org.apache.cxf.service.invoker.AbstractInvoker.performInvocation(AbstractInvoker.java:180) ~[cxf-core-3.1.12.jar:3.1.12]
    at org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:96) ~[cxf-core-3.1.12.jar:3.1.12]
    ... 37 more

This is my pom configuration：

<dependency>
    <groupId>org.bytedeco</groupId>
    <artifactId>javacv</artifactId>
    <version>1.0</version>
</dependency>
<dependency>
    <groupId>org.bytedeco</groupId>
    <artifactId>javacpp</artifactId>
    <version>1.0</version>
</dependency>
<dependency>
    <groupId>com.github.hoary.ffmpeg</groupId>
    <artifactId>FFmpeg-linux-x86_64</artifactId>
    <version>2.0.1.1
    </version>
</dependency>
<dependency>
    <groupId>org.bytedeco.javacpp-presets</groupId>
    <artifactId>ffmpeg</artifactId>
    <version>2.7.1-1.0</version>
</dependency>

This is my code：

public String convertImage(String filePath, String imagePath) throws IOException, FrameGrabber.Exception {
    FFmpegFrameGrabber g = new FFmpegFrameGrabber(filePath);
    g.start();
    Java2DFrameConverter java2DFrameConverter = new Java2DFrameConverter();
    BufferedImage bufferedImage = java2DFrameConverter.convert(g.grabImage());
    String path = imagePath + System.currentTimeMillis() + ".png";
    ImageIO.write(bufferedImage, "png", new File(path));
    g.stop();
    return path;
}

Body:
Make sure you have all libraries installed on your computer that are needed.
In this case, "javacv-platform".

This is what gives the hint to think in that direction:

java.lang.NoClassDefFoundError: Could not initialize class org.bytedeco.javacpp.avformat$AVFormatContext

"NoClassDefFound" almost always means that something required is missing.


问:
Freemarker template to check the constant value
Here is my piece of code

```<code><#if (miscValue_index > 0)><#break></#if>
<td valign=""top"">${miscValue.propertyName!}</td>
<td width=""10px"">   </td>
<td valign=""top"">${miscValue.propertyValue!}</td>
<td width=""10px"">   </td>
<td valign=""top"">${miscValue.newPropertyValue!}</td>
<td width=""10px"">   </td>
</code>```

i want to check if "miscValue.propertyValue" value is UNDEFINED or valid string

miscValue.propertyValue will return a valid string or UNDEFINED.
If the value returned is "UNDEFINED",i need to update "empty string" else the "orginal value" using freemarker language.Could anyone please help on this.
Thanks in advance

答:
I think you are looking for something as below,

```<code><#if value?? >
$value
<#if/>

<#if value?? >
$value
<#else>

<#if/>
</code>```

Here value can be a token that you want to verify. You can add <#else> tag if you want to print something else like blank space in case value is not valid as mentioned in second example.

Body:
Here is my piece of code

<#if (miscValue_index > 0)><#break></#if>
${miscValue.propertyName!}

${miscValue.propertyValue!}

${miscValue.newPropertyValue!}

i want to check if "miscValue.propertyValue" value is UNDEFINED or valid string

miscValue.propertyValue will return a valid string or UNDEFINED.
If the value returned is "UNDEFINED",i need to update "empty string" else the "orginal value" using freemarker language.Could anyone please help on this.
Thanks in advance

Body:
I think you are looking for something as below,

<#if value?? >
$value
<#if/>

<#if value?? >
$value
<#else>

<#if/>

Here value can be a token that you want to verify. You can add <#else> tag if you want to print something else like blank space in case value is not valid as mentioned in second example.


问:
How to wake up device when it sleeps
I've already read a lot about this topic on SO.
I'm trying to write SIP Client, which of course should accept incoming calls when the device is sleeping.
The first thing I've tried was to use these flags in my onCreate method:

```<code>Window window = this.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
</code>```

And my devices (different models of phones and different API Levels) woke up only when they were plugged in to PC with USB cable or were in charging process.
 When phones were unplugged there were no impact of flags. Then I found that one guy has already asked a similar question on SO: Android - Wake Up and Unlock Device Nobody replied to him and after some time he had found answer on his question and posted it. The answer was to use PowerManager class. His answer helped me a lot, but documentation of PowerManager says "Device battery life will be significantly affected by the use of this API". I felt it on myself. My application began to use too much energy of battery. I compared my app with WhatsApp and saw gigantic difference in battery energy using.

So, is there any other way to wake up device when it sleeps or

does anybody know how this process works in WhatsApp, Skype and other apps which receives incoming calls and saves battery life?

答:
You can use-

```<code>android:showOnLockScreen="true"
</code>```

in your manifest file and in your activity which you want that should appear on screen lock.

Title: How to wake up device when it sleeps

Body:
I've already read a lot about this topic on SO.
I'm trying to write SIP Client, which of course should accept incoming calls when the device is sleeping.
The first thing I've tried was to use these flags in my onCreate method:

Window window = this.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

And my devices (different models of phones and different API Levels) woke up only when they were plugged in to PC with USB cable or were in charging process.
 When phones were unplugged there were no impact of flags. Then I found that one guy has already asked a similar question on SO: Android - Wake Up and Unlock Device Nobody replied to him and after some time he had found answer on his question and posted it. The answer was to use PowerManager class. His answer helped me a lot, but documentation of PowerManager says "Device battery life will be significantly affected by the use of this API". I felt it on myself. My application began to use too much energy of battery. I compared my app with WhatsApp and saw gigantic difference in battery energy using.

So, is there any other way to wake up device when it sleeps or

does anybody know how this process works in WhatsApp, Skype and other apps which receives incoming calls and saves battery life?

Body:
You can use-

android:showOnLockScreen="true"

in your manifest file and in your activity which you want that should appear on screen lock.


问:
CSS How to put 4 divs on each side of a parent div
I wish to include 4 divs inside a parent div in the following manner:

I could use fixed position and set right/left/top/bottom = 0 accordingly for each child div if they were not inside in a div, but right now, I can't figure out how to do this.

答:
It will be helpful to you

.parent{
  position: relative;
  width: 100%;
  height: 100vh;
  border: 1px solid black;
}
.parent>div{
  position:absolute;
  text-align:center;
}
.one{
  background-color: green;
  bottom: 0;
  right: 0;
  width: 80%;
  height: 20%;
}
.two{
  background-color: blue;
  top: 0;
  right: 0;
  width: 20%;
  height: 80%;
}
.three{
  background-color: red;
  top: 0;
  left: 0;
  width: 80%;
  height: 20%;
}
.four{
  background-color: brown;
  bottom: 0;
  left: 0;
  width: 20%;
  height: 80%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="one"> Div1</div>
  <div class="two">Div2</div>
  <div class="three">Div3</div>
  <div class="four">Div4</div>
</div></code>```

Body:
It will be helpful to you

.parent{
  position: relative;
  width: 100%;
  height: 100vh;
  border: 1px solid black;
}
.parent>div{
  position:absolute;
  text-align:center;
}
.one{
  background-color: green;
  bottom: 0;
  right: 0;
  width: 80%;
  height: 20%;
}
.two{
  background-color: blue;
  top: 0;
  right: 0;
  width: 20%;
  height: 80%;
}
.three{
  background-color: red;
  top: 0;
  left: 0;
  width: 80%;
  height: 20%;
}
.four{
  background-color: brown;
  bottom: 0;
  left: 0;
  width: 20%;
  height: 80%;
}

<div class="parent">
  <div class="one"> Div1</div>
  <div class="two">Div2</div>
  <div class="three">Div3</div>
  <div class="four">Div4</div>
</div>


问:
Accessing HTML via AIR's HTML Component
I can't seem to find anything in Adobe's documentation about accessing the HTML of a web page through the HTML component in AIR.

I've looked into "domWindow", but that seems to only return Javascript.

Is there a property I can access that has the whole of the HTML in string format or do I need to use URLLoader or something like that?

答: htmlText  ? </p>

Title: Accessing HTML via AIR's HTML Component

Body: htmlText  ?


问:
Aspose not detecting digits
I cannot for the life of me get aspose to detect any digits, I've tried many different solutions but none seem to work.

Here is an example

As you can see it doesnt look anything remotely right.

I've now got the code (which is on a timer, so that the feed is live):

```<code> private void timer1_Tick(object sender, EventArgs e)
        {

            Image img = Clipboard.GetImage();

            pictureBox1.Image = img;
            ocr.Config.ProcessColoredBackground = true;

            if (img != null)
            {
                var ms = new MemoryStream();

                img.Save(ms, ImageFormat.Bmp); // put here the image format
                ms.Position = 0;

                ocr.Image = ImageStream.FromStream(ms, ImageStreamFormat.Bmp);
                ocr.Config.RemoveNonText = true;
                ocr.Config.Whitelist = new char[] { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '.' };

                    if (ocr.Process()) // Start processing it
                {
                    toolStripStatusLabel1.Text = "Text: " + ocr.Text;
                }
            }
        }
</code>```

答:
The main problem, as it was mentioned, is white text on black background.
To be correctly recognized, such images must be inverted.
The problem will be resolved in future Aspose.OCR releases.</p>

Title: Aspose not detecting digits

Body:
I cannot for the life of me get aspose to detect any digits, I've tried many different solutions but none seem to work.

Here is an example

As you can see it doesnt look anything remotely right.

I've now got the code (which is on a timer, so that the feed is live):

 private void timer1_Tick(object sender, EventArgs e)
        {

            Image img = Clipboard.GetImage();

            pictureBox1.Image = img;
            ocr.Config.ProcessColoredBackground = true;

            if (img != null)
            {
                var ms = new MemoryStream();

                img.Save(ms, ImageFormat.Bmp); // put here the image format
                ms.Position = 0;

                ocr.Image = ImageStream.FromStream(ms, ImageStreamFormat.Bmp);
                ocr.Config.RemoveNonText = true;
                ocr.Config.Whitelist = new char[] { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '.' };

                    if (ocr.Process()) // Start processing it
                {
                    toolStripStatusLabel1.Text = "Text: " + ocr.Text;
                }
            }
        }


问:
Is there a way for a lambda function to execute it's custom error prompt for AWS Lex bot?
I want to handle error messages dynamically and not rely on what we declared in the Lex dashboard. However when I tried to type a wrong message it will immediately trigger the default error message. When I check the lambda logs using Serverless the lambda function was not executed.

See logs:

There was no new entry when I typed in "can you do this". I was expecting that the lambda function would execute since I added some console.log to check out the event data.

Is it even possible?

答:
You can handle these dynamically but for that you need to setup an API Gateway and Lambda function in between your chat-client and the lex.

Your chat-client will send request to API Gateway, then to Lambda function and then to Lex (Lex will have one more lambda function). While returning the response from Lex, you can check in the Lambda function if it's an error message and trigger some action.

In the Lambda function we can use something like this:

```<code>import logging
import boto3

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)

client_run = boto3.client('lex-runtime')
client_model = boto3.client('lex-models')

def lambda_handler(event, context):
    response = client_run.post_text(
        botName='name_of_your_bot',
        botAlias='alias_of_your_bot',
        userId='some_id',
        sessionAttributes={
            'key1': 'value1'
        },
        inputText=event['user_query']
    )
    bot_details = client_model.get_bot(
    name='name_of_your_bot',
    versionOrAlias='$LATEST'
    )
    for content in bot_details['clarificationPrompt']['messages']:
        if response["message"] == content['content']:
            return error_handling_method(event)
    for content in bot_details['abortStatement']['messages']:
        if response["message"] == content['content']:
            return error_handling_method(event)
    return response["message"]
</code>```

Hope it helps.

Body:
You can handle these dynamically but for that you need to setup an API Gateway and Lambda function in between your chat-client and the lex.

Your chat-client will send request to API Gateway, then to Lambda function and then to Lex (Lex will have one more lambda function). While returning the response from Lex, you can check in the Lambda function if it's an error message and trigger some action.

In the Lambda function we can use something like this:

import logging
import boto3

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)

client_run = boto3.client('lex-runtime')
client_model = boto3.client('lex-models')

def lambda_handler(event, context):
    response = client_run.post_text(
        botName='name_of_your_bot',
        botAlias='alias_of_your_bot',
        userId='some_id',
        sessionAttributes={
            'key1': 'value1'
        },
        inputText=event['user_query']
    )
    bot_details = client_model.get_bot(
    name='name_of_your_bot',
    versionOrAlias='$LATEST'
    )
    for content in bot_details['clarificationPrompt']['messages']:
        if response["message"] == content['content']:
            return error_handling_method(event)
    for content in bot_details['abortStatement']['messages']:
        if response["message"] == content['content']:
            return error_handling_method(event)
    return response["message"]

Hope it helps.


问:
I want to make vhdl divider
i'm now using FPGA spartan3,

i want to calculate 'result' which is represented below formula.
and the 'result' should be returned as integer type. So i set up all the variables with integer type but it doesn't work.

```<code>    result <=((a*b*7894*7)/(w*temp_constant));
</code>```

i've set a,b,c,w,temp_constant as variables

```<code>    variable a : integer range 0 to 99;
    variable b : integer range 0 to 9999;
    variable w : integer range 0 to 200;
    variable temp_constant : integer range 0 to 99;
</code>```

but the operator '/' doesn't work at this synthesis. the error msg was
'Operator '/' must have constant operands or first operand must be power of 2"'

答:
The error message is almost (see the note below) 100% clear: divisions are not supported by your synthesis tool, except with constant operands (the result is computed by the synthesizer in the constant propagation phase) or with divisors that are powers of 2 (the division is a simple right shift).

One possible reason for this limitation of your synthesis tool is that there are many of ways to compute integer divisions in hardware and typing just / in a VHDL code is not enough to chose among them. There may be other reasons.

In your case where operands are not constants, and the divisor is not a power of 2, you must design this divider yourself at a lower level. If you have no idea about hardware implementations of integer dividers you will have to search a bit. This is a very classical topic, it should be easy to find good resources. Just a hint: pre-computing all inverses in fixed point representation, storing them in a read-only memory and using multiplications instead of divisions is an option.

Note: I find the error message you got (first operand must be power of 2) a bit surprising. Unless the term first operand is supposed to designate the divisor, which is not that common, it is probably a bug and the correct error message should be: second operand must be power of 2. Or, even better: divisor must be power of 2.

Title: I want to make vhdl divider

Body:
i'm now using FPGA spartan3,

i want to calculate 'result' which is represented below formula.
and the 'result' should be returned as integer type. So i set up all the variables with integer type but it doesn't work.

    result <=((a*b*7894*7)/(w*temp_constant));

i've set a,b,c,w,temp_constant as variables

    variable a : integer range 0 to 99;
    variable b : integer range 0 to 9999;
    variable w : integer range 0 to 200;
    variable temp_constant : integer range 0 to 99;

but the operator '/' doesn't work at this synthesis. the error msg was
'Operator '/' must have constant operands or first operand must be power of 2"'


问:
AWK Command print size in mb,kb or gb by finding a file using ls -l
I want to get a file size using find command along with size in kb, mb or gb with decimal point of two only.

Desired output:

```<code>15.04 MB
10MB
10GB
</code>```

I have tried below command but getting error:

```<code>find /orabackup/EXPDP/ATRUS001 -name "expdp_ATRUS001_04122017_0500.dmp" -exec ls -ltr  {} \;  | awk ' {s+=$5}' '{ split( "B KB MB GB TB PB" , v ); s=1; while( $1>1024 ){ $1/=1024; s++ } printf "%.2f %s", $1, v[s] }'
</code>```

Output:

```<code>awk: cmd. line:1: fatal: cannot open file `{ split( "B KB MB GB TB PB" , v ); s=1; while( $1>1024 ){ $1/=1024; s++ } printf "%.2f %s", $1, v[s] }' for reading (No such file or directory
</code>```

even though file is present in directory giving me above error. Thank you for your help.

答:
```<code>awk ' {s+=$5}' '{ split( "B... ?
</code>```

Why have you split the awk program into two arguments? This is almost certainly what's causing your problem.

It treats the first argument as the awk program and the second as the input file. This is supported by your error message, stating "cannot open file '{ split ...". What you need to do is to provide the awk program as a single argument.

As an aside (though I'm not sure about Solaris), many of the GNU utilities sport a -h option to produce human-readable sizes. Have you tried ls -h at all?

According to the Oracle docs, Solaris supports this, though it may not give you the two decimal places you desire.

As another aside, I cannot understand why you're trying to add the file size to s for each line if you're interested in individual sizes. I also can't understand why you're using $1 for the divisions when this would be the drwxr-xr-x part of the ls output.

Perhaps you would be better off specifying in more detail what you want to achieve.

The best I can do for now is to provide this as an example:

```<code>pax> find . -name '[a-z]*' -exec ls -ltr {} ';' | awk 'BEGIN{split("B KB MB GB TB PB EB ZB YB",v)} {s=1;while($5>1024&&s<9){$5/=1024;s++}printf "%6.2f %-2s %s\n",$5,v[s],$9}'
154.00 B  ./etc_ntp.conf
150.00 B  ./input.txt
  1.85 KB ./qq.sh
200.00 B  ./tmp00
</code>```

That seems to be basically what you're trying to do though you'll need to modify the find arguments for your specific case (I just grabbed all files starting with a lower-case letter).

It also limits s so that you don't run off the end of the array if you have Exabyte-sized files :-)

Breaking it down for readability:

```<code>BEGIN {
    # Only need do this once, allow for bigger files.
    split("B KB MB GB TB PB EB ZB YB", v)
}
{
    # Select B suffix.
    s=1

    # Need higher suffix, but stop at YB.
    while ($5 > 1024 && s < 9)
    {
        # Divide by 1K, go to next suffix.
        $5 /= 1024
        s++
    }

    # Pretty-print the line.
    printf "%6.2f %-2s %s\n", $5, v[s], $9
}
</code>```

Body:
I want to get a file size using find command along with size in kb, mb or gb with decimal point of two only.

Desired output:

15.04 MB
10MB
10GB

I have tried below command but getting error:

find /orabackup/EXPDP/ATRUS001 -name "expdp_ATRUS001_04122017_0500.dmp" -exec ls -ltr  {} \;  | awk ' {s+=$5}' '{ split( "B KB MB GB TB PB" , v ); s=1; while( $1>1024 ){ $1/=1024; s++ } printf "%.2f %s", $1, v[s] }'

Output:

awk: cmd. line:1: fatal: cannot open file `{ split( "B KB MB GB TB PB" , v ); s=1; while( $1>1024 ){ $1/=1024; s++ } printf "%.2f %s", $1, v[s] }' for reading (No such file or directory

even though file is present in directory giving me above error. Thank you for your help.

Body:
awk ' {s+=$5}' '{ split( "B... ?

Why have you split the awk program into two arguments? This is almost certainly what's causing your problem.

It treats the first argument as the awk program and the second as the input file. This is supported by your error message, stating "cannot open file '{ split ...". What you need to do is to provide the awk program as a single argument.

As an aside (though I'm not sure about Solaris), many of the GNU utilities sport a -h option to produce human-readable sizes. Have you tried ls -h at all?

According to the Oracle docs, Solaris supports this, though it may not give you the two decimal places you desire.

As another aside, I cannot understand why you're trying to add the file size to s for each line if you're interested in individual sizes. I also can't understand why you're using $1 for the divisions when this would be the drwxr-xr-x part of the ls output.

Perhaps you would be better off specifying in more detail what you want to achieve.

The best I can do for now is to provide this as an example:

pax> find . -name '[a-z]*' -exec ls -ltr {} ';' | awk 'BEGIN{split("B KB MB GB TB PB EB ZB YB",v)} {s=1;while($5>1024&&s<9){$5/=1024;s++}printf "%6.2f %-2s %s\n",$5,v[s],$9}'
154.00 B  ./etc_ntp.conf
150.00 B  ./input.txt
  1.85 KB ./qq.sh
200.00 B  ./tmp00

That seems to be basically what you're trying to do though you'll need to modify the find arguments for your specific case (I just grabbed all files starting with a lower-case letter).

It also limits s so that you don't run off the end of the array if you have Exabyte-sized files :-)

Breaking it down for readability:

BEGIN {
    # Only need do this once, allow for bigger files.
    split("B KB MB GB TB PB EB ZB YB", v)
}
{
    # Select B suffix.
    s=1

    # Need higher suffix, but stop at YB.
    while ($5 > 1024 && s < 9)
    {
        # Divide by 1K, go to next suffix.
        $5 /= 1024
        s++
    }

    # Pretty-print the line.
    printf "%6.2f %-2s %s\n", $5, v[s], $9
}