问:
Breaking tokens into subtokens with Lucene TokenFilter
My program needs to index with Lucene (4.10) unstructured documents which contents can be anything. So my custom Analyzer is making use of the ClassicTokenizer to first tokenize the documents.

Yet it does not completely fit my needs because for example I want to be able to search for parts of an email address or part of a serial number (can also be a telephone number or anything containing numbers) that can be written as 1234.5678.9012 or 1234-5678-9012 depending on who wrote the document being indexed.

Since this ClassicTokenizer recognizes email and treats points followed by numbers as a whole token, it ends up that the generated index includes email addresses as a whole and serial numbers as a whole too whereas I would also like to break those tokens into pieces to enable the user to later search for those pieces.

Let me give a concrete example : if the input document features xyz@gmail.com, the ClassicTokenizer recognizes it as an email and consequently tokenizes it as xyz@gmail.com. If the user searches for xyz they will find nothing whereas a search for xyz@gmail.com will yield the expected result.

After reading lots of blog postings or SO question I to the conclusion that one solution could be to use a TokenFilter that would split the email into its pieces (on each side of @ sign). Please not that I don't want to create my own tokenizer with JFlex and co.

Dealing with email I wrote the following code inspired from Lucene in action 2nd Edition's Synonymfilter :

```<code>public class SymbolSplitterFilter extends TokenFilter {

private final CharTermAttribute termAtt;
private final PositionIncrementAttribute posIncAtt;
private final Stack<String> termStack;
private AttributeSource.State current;

public SymbolSplitterFilter(TokenStream in) {
    super(in);
    termStack = new Stack<>();
    termAtt = addAttribute(CharTermAttribute.class);
    posIncAtt = addAttribute(PositionIncrementAttribute.class);
}

@Override
public boolean incrementToken() throws IOException {
    if (!input.incrementToken()) {
        return false;
    }

    final String currentTerm = termAtt.toString();

    System.err.println("The original word was " + termAtt.toString());
    final int bufferLength = termAtt.length();

    if (bufferLength > 1 && currentTerm.indexOf("@") > 0) { // There must be sth more than just @
        // If this is the first pass we fill in the stack with the terms
        if (termStack.isEmpty()) {
            // We split the token abc@cd.com into abc and cd.com
            termStack.addAll(Arrays.asList(currentTerm.split("@")));
            // Now we have the constituting terms of the email in the stack
            System.err.println("The terms on the stacks are ");
            for (int i = 0; i < termStack.size(); i++) {
                System.err.println(termStack.get(i));
                /** The terms on the stacks are
                * xyz
                * gmail.com
                */

            }

            // I am not sure it is the right place for this.
             current = captureState();

        } else {
            // This part seems to never be reached!
            // We add the constituents terms as tokens.
            String part = termStack.pop();
            System.err.println("Current part is " + part);
            restoreState(current);
            termAtt.setEmpty().append(part);
            posIncAtt.setPositionIncrement(0);
        }
    }

    System.err.println("In the end we have " + termAtt.toString());
    // In the end we have xyz@gmail.com
    return true;

}
</code>```

}

Please note : I just started with the email that's why I only showed that part of code but I'll have to enhance my code to also manage serial numbers (as explained earlier)

However the stack is never processed. Indeed I can't figure out how the incrementToken method works although I read this SO question and when it processes the given token from the TokenStream.

Finally the goal I want to achieve is : for xyz@gmail.com as input text, I want to generate the following subtokens :
xyz@gmail.com
xyz
gmail.com

Any help appreciated,

答:
Your Problem is, that the input TokenStream is already exhausted when your Stack is filled the first time. So input.incrementToken() returns false.
You should check whether the stack is filled first before incrementing the input. Like so:

```<code>public final class SymbolSplitterFilter extends TokenFilter {

private final CharTermAttribute termAtt;
private final PositionIncrementAttribute posIncAtt;
private final Stack<String> termStack;
private AttributeSource.State current;
private final TypeAttribute typeAtt;

public SymbolSplitterFilter(TokenStream in)
{
    super(in);
    termStack = new Stack<>();
    termAtt = addAttribute(CharTermAttribute.class);
    posIncAtt = addAttribute(PositionIncrementAttribute.class);
    typeAtt = addAttribute(TypeAttribute.class);
}

@Override
public boolean incrementToken() throws IOException
{
    if (!this.termStack.isEmpty()) {
        String part = termStack.pop();
        restoreState(current);
        termAtt.setEmpty().append(part);
        posIncAtt.setPositionIncrement(0);
        return true;
    } else if (!input.incrementToken()) {
        return false;
    } else {
        final String currentTerm = termAtt.toString();
        final int bufferLength = termAtt.length();

        if (bufferLength > 1 && currentTerm.indexOf("@") > 0) { // There must be sth more than just @
            if (termStack.isEmpty()) {
                termStack.addAll(Arrays.asList(currentTerm.split("@")));
                current = captureState();
            }
        }
        return true;

    }

}
}
</code>```

Note, that you might possibly want to correct your offsets as well and change the order of your tokens as the test shows your resulting tokens:

```<code> public class SymbolSplitterFilterTest extends BaseTokenStreamTestCase {

@Test
public void testSomeMethod() throws IOException
{
    Analyzer analyzer = this.getAnalyzer();
    assertAnalyzesTo(analyzer, "hey xyz@example.com",
        new String[]{"hey", "xyz@example.com", "example.com", "xyz"},
        new int[]{0, 4, 4, 4},
        new int[]{3, 19, 19, 19},
        new String[]{"word", "word", "word", "word"},
        new int[]{1, 1, 0, 0}
        );
}

 private Analyzer getAnalyzer()
{
    return new Analyzer()
    {
        @Override
        protected Analyzer.TokenStreamComponents createComponents(String fieldName)
        {
            Tokenizer tokenizer = new MockTokenizer(MockTokenizer.WHITESPACE, false);
            SymbolSplitterFilter testFilter = new SymbolSplitterFilter(tokenizer);
            return new Analyzer.TokenStreamComponents(tokenizer, testFilter);
        }
    };
}

}
</code>```

Body:
My program needs to index with Lucene (4.10) unstructured documents which contents can be anything. So my custom Analyzer is making use of the ClassicTokenizer to first tokenize the documents.

Yet it does not completely fit my needs because for example I want to be able to search for parts of an email address or part of a serial number (can also be a telephone number or anything containing numbers) that can be written as 1234.5678.9012 or 1234-5678-9012 depending on who wrote the document being indexed.

Since this ClassicTokenizer recognizes email and treats points followed by numbers as a whole token, it ends up that the generated index includes email addresses as a whole and serial numbers as a whole too whereas I would also like to break those tokens into pieces to enable the user to later search for those pieces.

Let me give a concrete example : if the input document features xyz@gmail.com, the ClassicTokenizer recognizes it as an email and consequently tokenizes it as xyz@gmail.com. If the user searches for xyz they will find nothing whereas a search for xyz@gmail.com will yield the expected result.

After reading lots of blog postings or SO question I to the conclusion that one solution could be to use a TokenFilter that would split the email into its pieces (on each side of @ sign). Please not that I don't want to create my own tokenizer with JFlex and co.

Dealing with email I wrote the following code inspired from Lucene in action 2nd Edition's Synonymfilter :

public class SymbolSplitterFilter extends TokenFilter {

private final CharTermAttribute termAtt;
private final PositionIncrementAttribute posIncAtt;
private final Stack<String> termStack;
private AttributeSource.State current;

public SymbolSplitterFilter(TokenStream in) {
    super(in);
    termStack = new Stack<>();
    termAtt = addAttribute(CharTermAttribute.class);
    posIncAtt = addAttribute(PositionIncrementAttribute.class);
}

@Override
public boolean incrementToken() throws IOException {
    if (!input.incrementToken()) {
        return false;
    }

    final String currentTerm = termAtt.toString();

    System.err.println("The original word was " + termAtt.toString());
    final int bufferLength = termAtt.length();

    if (bufferLength > 1 && currentTerm.indexOf("@") > 0) { // There must be sth more than just @
        // If this is the first pass we fill in the stack with the terms
        if (termStack.isEmpty()) {
            // We split the token abc@cd.com into abc and cd.com
            termStack.addAll(Arrays.asList(currentTerm.split("@")));
            // Now we have the constituting terms of the email in the stack
            System.err.println("The terms on the stacks are ");
            for (int i = 0; i < termStack.size(); i++) {
                System.err.println(termStack.get(i));
                /** The terms on the stacks are
                * xyz
                * gmail.com
                */

            }

            // I am not sure it is the right place for this.
             current = captureState();

        } else {
            // This part seems to never be reached!
            // We add the constituents terms as tokens.
            String part = termStack.pop();
            System.err.println("Current part is " + part);
            restoreState(current);
            termAtt.setEmpty().append(part);
            posIncAtt.setPositionIncrement(0);
        }
    }

    System.err.println("In the end we have " + termAtt.toString());
    // In the end we have xyz@gmail.com
    return true;

}

}

Please note : I just started with the email that's why I only showed that part of code but I'll have to enhance my code to also manage serial numbers (as explained earlier)

However the stack is never processed. Indeed I can't figure out how the incrementToken method works although I read this SO question and when it processes the given token from the TokenStream.

Finally the goal I want to achieve is : for xyz@gmail.com as input text, I want to generate the following subtokens :
xyz@gmail.com
xyz
gmail.com

Any help appreciated,

Body:
Your Problem is, that the input TokenStream is already exhausted when your Stack is filled the first time. So input.incrementToken() returns false.
You should check whether the stack is filled first before incrementing the input. Like so:

public final class SymbolSplitterFilter extends TokenFilter {

private final CharTermAttribute termAtt;
private final PositionIncrementAttribute posIncAtt;
private final Stack<String> termStack;
private AttributeSource.State current;
private final TypeAttribute typeAtt;

public SymbolSplitterFilter(TokenStream in)
{
    super(in);
    termStack = new Stack<>();
    termAtt = addAttribute(CharTermAttribute.class);
    posIncAtt = addAttribute(PositionIncrementAttribute.class);
    typeAtt = addAttribute(TypeAttribute.class);
}

@Override
public boolean incrementToken() throws IOException
{
    if (!this.termStack.isEmpty()) {
        String part = termStack.pop();
        restoreState(current);
        termAtt.setEmpty().append(part);
        posIncAtt.setPositionIncrement(0);
        return true;
    } else if (!input.incrementToken()) {
        return false;
    } else {
        final String currentTerm = termAtt.toString();
        final int bufferLength = termAtt.length();

        if (bufferLength > 1 && currentTerm.indexOf("@") > 0) { // There must be sth more than just @
            if (termStack.isEmpty()) {
                termStack.addAll(Arrays.asList(currentTerm.split("@")));
                current = captureState();
            }
        }
        return true;

    }

}
}

Note, that you might possibly want to correct your offsets as well and change the order of your tokens as the test shows your resulting tokens:

 public class SymbolSplitterFilterTest extends BaseTokenStreamTestCase {

@Test
public void testSomeMethod() throws IOException
{
    Analyzer analyzer = this.getAnalyzer();
    assertAnalyzesTo(analyzer, "hey xyz@example.com",
        new String[]{"hey", "xyz@example.com", "example.com", "xyz"},
        new int[]{0, 4, 4, 4},
        new int[]{3, 19, 19, 19},
        new String[]{"word", "word", "word", "word"},
        new int[]{1, 1, 0, 0}
        );
}

 private Analyzer getAnalyzer()
{
    return new Analyzer()
    {
        @Override
        protected Analyzer.TokenStreamComponents createComponents(String fieldName)
        {
            Tokenizer tokenizer = new MockTokenizer(MockTokenizer.WHITESPACE, false);
            SymbolSplitterFilter testFilter = new SymbolSplitterFilter(tokenizer);
            return new Analyzer.TokenStreamComponents(tokenizer, testFilter);
        }
    };
}

}


来源: stackexchange

问:
Preserving the 'this' context when using JS Proxy objects
I'm trying to create a proxy to the global browser window object. The idea is simple - if the caller uses an existing method or property just return that, otherwise use the fake object. Here's the code:

```<code>var handler = {
  get: function(target, name) {
    return name in window ?
      window[name] :
      target[name];
  },
  set: function(obj, prop, value) {
    if (prop in window) {
      window[prop] = value
    } else {
      obj[prop] = value
    };
  },
};

var fakeWindow = new Proxy(function() {}, handler);
fakeWindow.foo = 'bar';
console.log(fakeWindow.foo); // outputs 'bar'
fakeWindow.alert('hello'); // error - the alert method is called without the correct this value
</code>```

Problem is, when invoking a method on the proxy object (such as alert in example above), the 'this' value is that of the proxy, not the window.
Is there any way to get this to work?

答:
Solution based on comment from Jonas w:</p>

```<code>var handler = {
  get: function(target, name) {
    return name in window ?
      (typeof window[name] == 'function' ? window[name].bind(window) : window[name]) :
      target[name];
  },
  set: function(obj, prop, value) {
    if (prop in window) {
      window[prop] = value
    } else {
      obj[prop] = value
    };
  },
};
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to create a proxy to the global browser window object. The idea is simple - if the caller uses an existing method or property just return that, otherwise use the fake object. Here's the code:

var handler = {
  get: function(target, name) {
    return name in window ?
      window[name] :
      target[name];
  },
  set: function(obj, prop, value) {
    if (prop in window) {
      window[prop] = value
    } else {
      obj[prop] = value
    };
  },
};

var fakeWindow = new Proxy(function() {}, handler);
fakeWindow.foo = 'bar';
console.log(fakeWindow.foo); // outputs 'bar'
fakeWindow.alert('hello'); // error - the alert method is called without the correct this value

Problem is, when invoking a method on the proxy object (such as alert in example above), the 'this' value is that of the proxy, not the window.
Is there any way to get this to work?

Body:
Solution based on comment from Jonas w:

var handler = {
  get: function(target, name) {
    return name in window ?
      (typeof window[name] == 'function' ? window[name].bind(window) : window[name]) :
      target[name];
  },
  set: function(obj, prop, value) {
    if (prop in window) {
      window[prop] = value
    } else {
      obj[prop] = value
    };
  },
};


问:
Google Sign In - prevent automatic load
I've been stuck on this for hours. I've tried google searching for answers but I don't understand any of them and have to assume it's out of date code.

I'm trying to add a 'sign in with google' to my site but I want it only to redirect to the login-check IF the user hits the button, not as soon as it detects I'm already logged in.

The button:

```<code><div class="g-signin2" data-onsuccess="onSignIn"></div>
</code>```

Script:

```<code><script>
function onSignIn(googleUser) {
    var profile = googleUser.getBasicProfile();
    console.log('ID: ' + profile.getId());
    console.log('Name: ' + profile.getName());
    var id_token = googleUser.getAuthResponse().id_token;
    window.location.replace("googleLogin.phptoken="+ id_token);
    }
</script>
</code>```

Anyone conquered this issue?

答:
I cant really remember what I did to fix this issue but i had the same one ended up making a new script here is a link to a js fiddle you will have to plug in your own client id and it doesn't have an image so you will just see a broken picture for the google login button.

```<code>var googleUser = {};
 var startApp = function() {
gapi.load('auth2', function(){
  // Retrieve the singleton for the GoogleAuth library and set up the client.
  auth2 = gapi.auth2.init({
    client_id: '83******98-pe4uneu******sj.apps.googleusercontent.com',
    cookiepolicy: 'single_host_origin',
    // Request scopes in addition to 'profile' and 'email'
    //scope: 'additional_scope'
  });
  attachSignin(document.getElementById('customBtn'));
});
};

function attachSignin(element) {
console.log(element.id);
auth2.attachClickHandler(element, {},
    function(googleUser) {
   first_name =  googleUser.getBasicProfile().getGivenName();
         last_name =  googleUser.getBasicProfile().getFamilyName();
         email =  googleUser.getBasicProfile().getEmail();
        console.log(googleUser.getBasicProfile().getGivenName());
        console.log(googleUser.getBasicProfile().getFamilyName());
        console.log(googleUser.getBasicProfile().getEmail());
        window.location = "/profile"
    }, function(error) {
      alert(JSON.stringify(error, undefined, 2));
    });

 }

 startApp();
</code>```

https://jsfiddle.net/josephmckenzie/9pxc41kx/

All the code you should need is in the js fiddle

Title: Google Sign In - prevent automatic load

Body:
I've been stuck on this for hours. I've tried google searching for answers but I don't understand any of them and have to assume it's out of date code.

I'm trying to add a 'sign in with google' to my site but I want it only to redirect to the login-check IF the user hits the button, not as soon as it detects I'm already logged in.

The button:

Script:

Anyone conquered this issue?

Body:
I cant really remember what I did to fix this issue but i had the same one ended up making a new script here is a link to a js fiddle you will have to plug in your own client id and it doesn't have an image so you will just see a broken picture for the google login button.

var googleUser = {};
 var startApp = function() {
gapi.load('auth2', function(){
  // Retrieve the singleton for the GoogleAuth library and set up the client.
  auth2 = gapi.auth2.init({
    client_id: '83******98-pe4uneu******sj.apps.googleusercontent.com',
    cookiepolicy: 'single_host_origin',
    // Request scopes in addition to 'profile' and 'email'
    //scope: 'additional_scope'
  });
  attachSignin(document.getElementById('customBtn'));
});
};

function attachSignin(element) {
console.log(element.id);
auth2.attachClickHandler(element, {},
    function(googleUser) {
   first_name =  googleUser.getBasicProfile().getGivenName();
         last_name =  googleUser.getBasicProfile().getFamilyName();
         email =  googleUser.getBasicProfile().getEmail();
        console.log(googleUser.getBasicProfile().getGivenName());
        console.log(googleUser.getBasicProfile().getFamilyName());
        console.log(googleUser.getBasicProfile().getEmail());
        window.location = "/profile"
    }, function(error) {
      alert(JSON.stringify(error, undefined, 2));
    });

 }

 startApp();

https://jsfiddle.net/josephmckenzie/9pxc41kx/

All the code you should need is in the js fiddle


问:
javascript dragging the div code will froze the input text
I use this code for dragging a DIV, which is a small information box.
Within, I have some simple HTML including a input text or similar. When enabling the drag (see code) all inputs are frozen.

```<code>var selected = null, // Object of the element to be moved
    x_pos = 0, y_pos = 0, // Stores x & y coordinates of the mouse pointer
    x_elem = 0, y_elem = 0; // Stores top, left values (edge) of the element

// Will be called when user starts dragging an element
function _drag_init(elem) {
    // Store the object of the element which needs to be moved
    selected = elem;
    x_elem = x_pos - selected.offsetLeft;
    y_elem = y_pos - selected.offsetTop;
}

// Will be called when user dragging an element
function _move_elem(e) {
    x_pos = document.all ? window.event.clientX : e.pageX;
    y_pos = document.all ? window.event.clientY : e.pageY;
    if (selected !== null) {
        selected.style.left = (x_pos - x_elem) + 'px';
        selected.style.top = (y_pos - y_elem) + 'px';
    }
}

// Destroy the object when we are done
function _destroy() {
    selected = null;
}

document.onmousemove = _move_elem;
document.onmouseup = _destroy;
</code>```

There is a bigger code here, so I will simplify:

```<code>div = document.getElementById("mydiv");

    div.onmousedown = function () {
        _drag_init(this);
        return false;
    };
</code>```

Now when I display the DIV, the drag works smoothly (FF 53) but any input elements within are frozen :)

The content of my infobox (the DIV) is simple

```<code><input id="input_text" type="text" name="product" list="productName"/>
<datalist id="productName">
    <option value="Pen">Pen</option>
    <option value="Pencil">Pencil</option>
    <option value="Paper">Paper</option>
</datalist><br> <button id="myNiceButton" action="input_text">OK</button>
</code>```

I already tried bunch of solutions from StackOverflow without success, including eg. this one

Prevent drag event to interfere with input elements in Firefox using HTML5 drag/drop

```<code><div draggable="true" id="draggableDiv">
    <textarea onfocus="onFocus();" onblur="onBlur();">Inside draggable (FIXED)</textarea>
</div>
</code>```

But seems that those events are not triggered at all. Also tried draggable="false" but the same story, not working.

What will be the problem?

答:
Actually the drag code is fine.

```<code>div.onmousedown = function () {
    _drag_init(this);
    return false; // <-- remove this
};
</code>```

Or play with preventdefault() which one suits best.

event.preventDefault() vs. return false

return false here will prevent any mouse "down" so I guess it's impossible to click in input text with the mouse, acting like "disabled".

Body:
I use this code for dragging a DIV, which is a small information box.
Within, I have some simple HTML including a input text or similar. When enabling the drag (see code) all inputs are frozen.

var selected = null, // Object of the element to be moved
    x_pos = 0, y_pos = 0, // Stores x & y coordinates of the mouse pointer
    x_elem = 0, y_elem = 0; // Stores top, left values (edge) of the element

// Will be called when user starts dragging an element
function _drag_init(elem) {
    // Store the object of the element which needs to be moved
    selected = elem;
    x_elem = x_pos - selected.offsetLeft;
    y_elem = y_pos - selected.offsetTop;
}

// Will be called when user dragging an element
function _move_elem(e) {
    x_pos = document.all ? window.event.clientX : e.pageX;
    y_pos = document.all ? window.event.clientY : e.pageY;
    if (selected !== null) {
        selected.style.left = (x_pos - x_elem) + 'px';
        selected.style.top = (y_pos - y_elem) + 'px';
    }
}

// Destroy the object when we are done
function _destroy() {
    selected = null;
}

document.onmousemove = _move_elem;
document.onmouseup = _destroy;

There is a bigger code here, so I will simplify:

div = document.getElementById("mydiv");

    div.onmousedown = function () {
        _drag_init(this);
        return false;
    };

Now when I display the DIV, the drag works smoothly (FF 53) but any input elements within are frozen :)

The content of my infobox (the DIV) is simple

<input id="input_text" type="text" name="product" list="productName"/>
<datalist id="productName">
    <option value="Pen">Pen</option>
    <option value="Pencil">Pencil</option>
    <option value="Paper">Paper</option>
</datalist>
 <button id="myNiceButton" action="input_text">OK</button>

I already tried bunch of solutions from StackOverflow without success, including eg. this one

Prevent drag event to interfere with input elements in Firefox using HTML5 drag/drop

    <textarea onfocus="onFocus();" onblur="onBlur();">Inside draggable (FIXED)</textarea>

But seems that those events are not triggered at all. Also tried draggable="false" but the same story, not working.

What will be the problem?

Body:
Actually the drag code is fine.

div.onmousedown = function () {
    _drag_init(this);
    return false; // <-- remove this
};

Or play with preventdefault() which one suits best.

event.preventDefault() vs. return false

return false here will prevent any mouse "down" so I guess it's impossible to click in input text with the mouse, acting like "disabled".


问:
Javascript String Company Issue
i return from php page an echo for test:

```<code>$('#form').on('submit', function (e) {

          e.preventDefault();

          $.ajax({
            type: 'POST',
            url: 'https://capelladb.000webhostapp.com/textExample.php',
            data: $('#form').serialize(),
            success: function (data) {
                  var compare = data.localeCompare('testest');
                  console.log(data);
                  console.log(compare);
                  }
          });

        });
    });
</code>```

Just for test, the data returns in the success method is typeof "string" with "testest", but when im comapre to 'testest', is return -1 into "compare" variable. why it happen ?

Console.log photo: http://imgur.com/a/h7wWh

the PHP:

```<code><?php
    header("Access-Control-Allow-Origin: *");

    $servername = "localhost";
    $username = "id1635462_capellam";
    $password = "capella2017";
    $dbname = "id1635462_capella";

    $userInput = $_POST['username'];
    $passwordInput = $_POST['password'];

    echo $userInput . $passwordInput;
?>
</code>```

答:
Your data has empty spaces within.

You need to trim it, using .trim().

See the code below:

```<code>$('#form').on('submit', function (e) {
      e.preventDefault();

      $.ajax({
        type: 'POST',
        url: 'https://capelladb.000webhostapp.com/textExample.php',
        data: $('#form').serialize(),
        success: function (data) {
            var compare = data.trim().localeCompare('testest');
            console.log(data);
            console.log(compare);
        }
      });
    });
});
</code>```

Working example:

window.onload = function() {
  var data = 'testest      ';
  var test = data.localeCompare('testest');
  console.log('Not trimmed: ' + test);
  var test = data.trim().localeCompare('testest');
  console.log('Trimmed: ' + test);
};```

Title: Javascript String Company Issue

Body:
i return from php page an echo for test:

$('#form').on('submit', function (e) {

          e.preventDefault();

          $.ajax({
            type: 'POST',
            url: 'https://capelladb.000webhostapp.com/textExample.php',
            data: $('#form').serialize(),
            success: function (data) {
                  var compare = data.localeCompare('testest');
                  console.log(data);
                  console.log(compare);
                  }
          });

        });
    });

Just for test, the data returns in the success method is typeof "string" with "testest", but when im comapre to 'testest', is return -1 into "compare" variable. why it happen ?

Console.log photo: http://imgur.com/a/h7wWh

the PHP:

<?php
    header("Access-Control-Allow-Origin: *");

    $servername = "localhost";
    $username = "id1635462_capellam";
    $password = "capella2017";
    $dbname = "id1635462_capella";

    $userInput = $_POST['username'];
    $passwordInput = $_POST['password'];

    echo $userInput . $passwordInput;
?>

Body:
Your data has empty spaces within.

You need to trim it, using .trim().

See the code below:

$('#form').on('submit', function (e) {
      e.preventDefault();

      $.ajax({
        type: 'POST',
        url: 'https://capelladb.000webhostapp.com/textExample.php',
        data: $('#form').serialize(),
        success: function (data) {
            var compare = data.trim().localeCompare('testest');
            console.log(data);
            console.log(compare);
        }
      });
    });
});

Working example:

window.onload = function() {
  var data = 'testest      ';
  var test = data.localeCompare('testest');
  console.log('Not trimmed: ' + test);
  var test = data.trim().localeCompare('testest');
  console.log('Trimmed: ' + test);
};


问:
control servo using android
Asked question master, how to coding in arduino for controlling servo using android via bluetooth? Code below does not work, servo only runs between 48 - 56.</p>

```<code>#include <SoftwareSerial.h> #include <SoftwareSerial.h> #include <Servo.h> Servo servo; int bluetoothTx = 10; int bluetoothRx = 11; SoftwareSerial bluetooth(bluetoothTx, bluetoothRx); void setup() {   servo.attach(9);
 Serial.begin(9600); bluetooth.begin(9600);} void loop() {
//read from bluetooth and wrtite to usb serial
if(bluetooth.available()> 0 ){    int servopos = bluetooth.read();
Serial.println(servopos);
servo.write(servopos);}}
</code>```

答: What you are reading from the bluetooth is coming in as individual bytes of ascii code.  The ascii codes for digits run from 48 to 57.  So if you send for example "10" then it sends a 49 and then a 48.  You are just reading the values directly.  Instead you need to accumulate the characters you read into a buffer until you have them all and then use atoi to convert to a real number you can use.  </p>

Title: control servo using android

Body:
Asked question master, how to coding in arduino for controlling servo using android via bluetooth? Code below does not work, servo only runs between 48 - 56.

#include <SoftwareSerial.h> #include <SoftwareSerial.h> #include <Servo.h> Servo servo; int bluetoothTx = 10; int bluetoothRx = 11; SoftwareSerial bluetooth(bluetoothTx, bluetoothRx); void setup() {   servo.attach(9);
 Serial.begin(9600); bluetooth.begin(9600);} void loop() {
//read from bluetooth and wrtite to usb serial
if(bluetooth.available()> 0 ){    int servopos = bluetooth.read();
Serial.println(servopos);
servo.write(servopos);}}


问:
recvfrom for storing in 2D Char array
trying to collect 1261 UDP packet in 2D Char array using recvfrom function

```<code>define RxBuffSize   1514
define TotalPacket  1261

char    RxBuff[RxBuffSize]      =   {0};
</code>```

and the code i am trying to use is:

```<code>for (Count =0; Count <= TotalPacket; Count++)
{
    recvfrom(sock, RxBuff[Count],RxBuffSize,0,(struct sockaddr *)&Sender_addr, &Sender_addrlen);
}
</code>```

or no idea how to start just wanted to store all 1261 packets into RxBuff so that I can access packet data by its packet number for getting the data from packet by its packet number.

```<code>printf("%x ",Payload[packetno][data]);
</code>```

答:
You'll need enough space to store all of the packets contiguously. You can either statically allocate a 2D array

```<code>char RxBuff [RxBuffSize][1261];
</code>```

or use calloc

```<code>char *RxBuff = calloc(RxBuffSize, 1261);
</code>```

Then loop over recvfrom 1261 times just like in your question:

```<code>for (Count = 0; Count <= TotalPacket; Count++)
{
    recvfrom(sock, RxBuff[Count],RxBuffSize,0,(struct sockaddr *)&Sender_addr, &Sender_addrlen);
}
</code>```

Title: recvfrom for storing in 2D Char array

Body:
trying to collect 1261 UDP packet in 2D Char array using recvfrom function

define RxBuffSize   1514
define TotalPacket  1261

char    RxBuff[RxBuffSize]      =   {0};

and the code i am trying to use is:

for (Count =0; Count <= TotalPacket; Count++)
{
    recvfrom(sock, RxBuff[Count],RxBuffSize,0,(struct sockaddr *)&Sender_addr, &Sender_addrlen);
}

or no idea how to start just wanted to store all 1261 packets into RxBuff so that I can access packet data by its packet number for getting the data from packet by its packet number.

printf("%x ",Payload[packetno][data]);

Body:
You'll need enough space to store all of the packets contiguously. You can either statically allocate a 2D array

char RxBuff [RxBuffSize][1261];

or use calloc

char *RxBuff = calloc(RxBuffSize, 1261);

Then loop over recvfrom 1261 times just like in your question:

for (Count = 0; Count <= TotalPacket; Count++)
{
    recvfrom(sock, RxBuff[Count],RxBuffSize,0,(struct sockaddr *)&Sender_addr, &Sender_addrlen);
}


问:
Align text underneath images in css
I'd like to make some sort of a program page for a festival. I want to create a list of images with little text underneath. I don't succeed in placing the text underneath (it always ends up next to the images instead of underneath). Can somebody help?

It should look like this:

[img1] [img2] [img3]

[text1] [text2] [text3]

[img4] [img5]

[text4] [text5]

... and so on

The size of the images is fixed, so that the rows with only 2 images are the same size as those who have 3.

This is my code in CSS thus far:

For the texts (small and big):

```<code>.prog_big{width:321px; height:434px; margin-left:30px; font-family: Lucida Sans,Calibri; font-size:16px; float:left; text-align:center}

.prog_small{width:207px; height:283px; margin-left:30px; font-family: Lucida Sans,Calibri; font-size:16px; float:left;text-align:center}
</code>```

For the images (small and big):

```<code>.poster_big{width:321px; height:434px; margin-left:30px; float:left}

.poster_small{width:207px; height:283px; margin-left:30px; float:left}
</code>```

答:
Division and image tags are not inline element. Because of this reason they will create a new line in the screen for each of them.

Make them inline, using the css "display:inline-block". They will stand side by side.

div.first-row div, div.second-row div {
  display:inline-block;
  float:left;
  width:100%;
}

div.first-row div {
  width: 33.3%;
}

div.second-row div {
  width: 50%;
}

div img {
  width:100%;
  height:auto;
}

p {
  text-align:center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='first-row'>
  <div>
    <img src='http://via.placeholder.com/140?text=image'>
    <p>Some Text Here</p>
  </div>
  <div>
    <img src='http://via.placeholder.com/140?text=image'>
    <p>Some Text Here</p>
  </div>
  <div>
    <img src='http://via.placeholder.com/140?text=image'>
    <p>Some Text Here</p>
  </div>
</div>

<div class='second-row'>
  <div>
    <img src='http://via.placeholder.com/140?text=image'>
    <p>Some Text Here</p>
  </div>
  <div>
    <img src='http://via.placeholder.com/140?text=image'>
    <p>Some Text Here</p>
  </div>
</div></code>```

Title: Align text underneath images in css

Body:
I'd like to make some sort of a program page for a festival. I want to create a list of images with little text underneath. I don't succeed in placing the text underneath (it always ends up next to the images instead of underneath). Can somebody help?

It should look like this:

[img1] [img2] [img3]

[text1] [text2] [text3]

[img4] [img5]

[text4] [text5]

... and so on

The size of the images is fixed, so that the rows with only 2 images are the same size as those who have 3.

This is my code in CSS thus far:

For the texts (small and big):

.prog_big{width:321px; height:434px; margin-left:30px; font-family: Lucida Sans,Calibri; font-size:16px; float:left; text-align:center}

.prog_small{width:207px; height:283px; margin-left:30px; font-family: Lucida Sans,Calibri; font-size:16px; float:left;text-align:center}

For the images (small and big):

.poster_big{width:321px; height:434px; margin-left:30px; float:left}

.poster_small{width:207px; height:283px; margin-left:30px; float:left}

Body:
Division and image tags are not inline element. Because of this reason they will create a new line in the screen for each of them.

Make them inline, using the css "display:inline-block". They will stand side by side.

div.first-row div, div.second-row div {
  display:inline-block;
  float:left;
  width:100%;
}

div.first-row div {
  width: 33.3%;
}

div.second-row div {
  width: 50%;
}

div img {
  width:100%;
  height:auto;
}

p {
  text-align:center;
}

<div class='first-row'>
  <div>
    <img src='http://via.placeholder.com/140?text=image'>
    <p>Some Text Here</p>
  </div>
  <div>
    <img src='http://via.placeholder.com/140?text=image'>
    <p>Some Text Here</p>
  </div>
  <div>
    <img src='http://via.placeholder.com/140?text=image'>
    <p>Some Text Here</p>
  </div>
</div>

<div class='second-row'>
  <div>
    <img src='http://via.placeholder.com/140?text=image'>
    <p>Some Text Here</p>
  </div>
  <div>
    <img src='http://via.placeholder.com/140?text=image'>
    <p>Some Text Here</p>
  </div>
</div>


问:
Radio button adding class element
I need to create 2 radio buttons.

When a users is on the page, the radio buttons are unchecked.

Inside radio button content is the CTA button which will be greyed

The CTA button will change the color only when the user selects the radio.

I have created style for the button which I want to use rather switch back and forth when the radio button is selected.

Here's an example.

Can someone guide me on how to add and remove classes so the colors switch within jQuery?

https://codepen.io/Ambuja/pen/BZNzRx

$('input').prop('checked', false);
$('span a').css('background-color','grey')
$('input').on('change', function () {
    if ($(this).is(':checked')) {
        var dt = $(this).data('title')
        $('span a').css('background-color','grey')
        $('#' + dt).css('background-color','orange')
        console.log(dt)
    }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>label {
    font-family: $verdana;
    font-size:12px;
    margin-left:13px;
    font-weight: normal;
}

}
input[type="radio"]:checked + label:before {

    text-align: center;
}
.high {
    color:yellow;
}
 </code>```

    <input type="radio" name="form-radio" id="workshops" value="high" data-title="workshopcl" checked="">
    Workshops

This is random text

    WorkShops

    <input type="radio" name="form-radio" id="courses" data-title="cou" value="option2">
    Courses

This is a random text

    Courses

```

答:
Simply use the jQuery methods removeClass() and addClass().

Often when you want to remove an active class from a group of elements and apply the active class to a new one you remove the active class from all elements in the group first, then add the class to selected element. Though we'll do it a little different this time because there's additional markup complexity and a data- attribute we can hook into.

With this solution I took advantage of the fact that your data-title attribute contained the ID value of the associated anchor. On each change on an input we remove the active class from the stored anchor in $active, then use the value of data-title to select the associated anchor and apply the active class.

**Note: Made some improvements to your markup (HTML).

var $active;

$( 'input' ).on( 'change', function ( e ) {

  var $this = $( this ),
      ctaID = $this.data( 'title' );

  if ( $active ) $active.removeClass( 'active' );

  $active = $( '#' + ctaID ).addClass( 'active' );

} );```
<pre class="snippet-code-css lang-css prettyprint-override"><code>label {
  font-family: Verdana, sans-serif;
  font-size: 12px;
  margin-left: 13px;
  font-weight: normal;
}

.cta {
  background-color: gray;
}
.active {
  background-color: orange;
}</code>```

      <input id="workshops" class="radio" type="radio" name="form-radio" value="high" data-title="workshopcl">
      Workshops

This is random text

    WorkShops

      <input id="courses" class="radio" type="radio" name="form-radio" data-title="cou" value="option2">
      Courses

This is a random text

    Courses

```

Title: Radio button adding class element

Body:
I need to create 2 radio buttons.

When a users is on the page, the radio buttons are unchecked.

Inside radio button content is the CTA button which will be greyed

The CTA button will change the color only when the user selects the radio.

I have created style for the button which I want to use rather switch back and forth when the radio button is selected.

Here's an example.

Can someone guide me on how to add and remove classes so the colors switch within jQuery?

https://codepen.io/Ambuja/pen/BZNzRx

$('input').prop('checked', false);
$('span a').css('background-color','grey')
$('input').on('change', function () {
    if ($(this).is(':checked')) {
        var dt = $(this).data('title')
        $('span a').css('background-color','grey')
        $('#' + dt).css('background-color','orange')
        console.log(dt)
    }
})

label {
    font-family: $verdana;
    font-size:12px;
    margin-left:13px;
    font-weight: normal;
}

}
input[type="radio"]:checked + label:before {

    text-align: center;
}
.high {
    color:yellow;
}

    <input type="radio" name="form-radio" id="workshops" value="high" data-title="workshopcl" checked="">
    Workshops

This is random text

    WorkShops

    <input type="radio" name="form-radio" id="courses" data-title="cou" value="option2">
    Courses

This is a random text

    Courses

Body:
Simply use the jQuery methods removeClass() and addClass().

Often when you want to remove an active class from a group of elements and apply the active class to a new one you remove the active class from all elements in the group first, then add the class to selected element. Though we'll do it a little different this time because there's additional markup complexity and a data- attribute we can hook into.

With this solution I took advantage of the fact that your data-title attribute contained the ID value of the associated anchor. On each change on an input we remove the active class from the stored anchor in $active, then use the value of data-title to select the associated anchor and apply the active class.

**Note: Made some improvements to your markup (HTML).

var $active;

$( 'input' ).on( 'change', function ( e ) {

  var $this = $( this ),
      ctaID = $this.data( 'title' );

  if ( $active ) $active.removeClass( 'active' );

  $active = $( '#' + ctaID ).addClass( 'active' );

} );

label {
  font-family: Verdana, sans-serif;
  font-size: 12px;
  margin-left: 13px;
  font-weight: normal;
}

.cta {
  background-color: gray;
}
.active {
  background-color: orange;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<div class="row">

  <div class="medium-6 large-6 columns">

    <label id="workshoping" for="workshops">
      <input id="workshops" class="radio" type="radio" name="form-radio" value="high" data-title="workshopcl">
      Workshops
    </label>
    <p>This is random text</p>
    <a href="#" id="workshopcl" class="cta">WorkShops</a>

  </div>

  <div class="medium-6 large-6 columns">

    <label for="courses">
      <input id="courses" class="radio" type="radio" name="form-radio" data-title="cou" value="option2">
      Courses
    </label>
    <p>This is a random text</p>
    <a href="#" id="cou" class="cta">Courses</a>

  </div>

</div>


问:
Google SignIn CocoaPods deprecated
How to implement Google SignIn in iOS app as now Google pod is deprecated?

Using the deprecated pod is giving
: Framework not found GoogleAppUtilities

答:
New pod location is:-</p>

```<code> pod 'GoogleSignIn'
</code>```

Title: Google SignIn CocoaPods deprecated

Body:
New pod location is:-

 pod 'GoogleSignIn'


问:
How to calculate time difference between typing the URL and opening of that URL?
I want to calculate the time difference between the user typing the URL and opening up the website or else refreshing the current page. Is there any way to do this using Javascript ?</p>

答:
Short answer: no. There's no way to tell how long it takes someone to type your URL, you simply aren't in the scope of your website and there's no way to tell how long it actually takes. But the next best thing is the load time, here's an example of how to do that:</p>

```<code><html>
    <head>
        <script type="text/javascript">
            var timerStart = Date.now();
        </script>
        <!-- do all the stuff you need to do -->
    </head>
    <body>
        <!-- put everything you need in here -->

        <script type="text/javascript">
             $(document).ready(function() {
                 console.log("Time until DOMready: ", Date.now()-timerStart);
             });
             $(window).load(function() {
                 console.log("Time until everything loaded: ", Date.now()-timerStart);
             });
        </script>
    </body>
</code>```

Body:
Short answer: no. There's no way to tell how long it takes someone to type your URL, you simply aren't in the scope of your website and there's no way to tell how long it actually takes. But the next best thing is the load time, here's an example of how to do that:

<html>
    <head>
        <script type="text/javascript">
            var timerStart = Date.now();
        </script>
        <!-- do all the stuff you need to do -->
    </head>
    <body>
        <!-- put everything you need in here -->

        <script type="text/javascript">
             $(document).ready(function() {
                 console.log("Time until DOMready: ", Date.now()-timerStart);
             });
             $(window).load(function() {
                 console.log("Time until everything loaded: ", Date.now()-timerStart);
             });
        </script>
    </body>


问:
Cannot load System.Net.Http.Primitives in Xamarin iOS
I have an older Xamarin forms project that I've updated, that uses Microsoft Azure's Mobile App Services (previously used Azure Mobile Services).

Was working fine, but after a clean and rebuild I now get this error whenever attempting to run it (I'm using Xamarin Studio)

```<code>Could not load file or assembly 'System.Net.Http.Primitives, Version=1.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies.
</code>```

Microsoft.Azure.Mobile.Client and SQLiteStore are at version 2.0.1.  I've tried removing and readding the assembly via NuGet, without any luck.

Has anyone seen this issue or resolved it?

答:
I faced a similar error in my solution with Xamarin.iOS native project which is using ModernHttpHandler.

Try adding a reference to standard Mono System.Net.Http in csproj file:

```<code><Reference Include="System.Net.Http" />
</code>```

For more details take a look at this blog post.

Body:
I have an older Xamarin forms project that I've updated, that uses Microsoft Azure's Mobile App Services (previously used Azure Mobile Services).

Was working fine, but after a clean and rebuild I now get this error whenever attempting to run it (I'm using Xamarin Studio)

Could not load file or assembly 'System.Net.Http.Primitives, Version=1.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies.

Microsoft.Azure.Mobile.Client and SQLiteStore are at version 2.0.1.  I've tried removing and readding the assembly via NuGet, without any luck.

Has anyone seen this issue or resolved it?

Body:
I faced a similar error in my solution with Xamarin.iOS native project which is using ModernHttpHandler.

Try adding a reference to standard Mono System.Net.Http in csproj file:

<Reference Include="System.Net.Http" />

For more details take a look at this blog post.


问:
fancybox - resizing image inside the iframe
I am using fancybox version 2.1.5
What I am trying to do is display large images in the fancybox iframe of about width 900 and height 500. Of course right now images render huge and don't fit into that iframe.
I am having a hard time capturing the right class or a way to navigate to the image to resize it. What I tried is using beforeShow function and do this:

```<code>                 $(".fancybox").fancybox({
                    type: 'iframe',
                    href: source,
                    title: title,
                    width: 900,
                    height: 500,
                    closeBtn: false,
                    nextSpeed: 0, //important
                    prevSpeed: 0, //important
                    beforeShow: function() {
                        alert('its working!');
                        $(".fancybox-iframe img").css("width","900px");
                        $(".fancybox-iframe img").css("height","auto");
                        $(".fancybox-iframe img").addClass("imageResize");
                    }
                });
</code>```

However, neither $(".fancybox-iframe img") nor $(".fancybox-inner img") are correct ways to trigger the img.
How can I use beforeShow function to properly resize my images inside the fancybox iframe.
Thanks!

答:
I figured it out</p>

```<code>                    beforeShow: function () {
                        var newWidth = 900; // set new image display width
                        $('.fancybox-iframe').contents().find('img').css({
                            width  : newWidth,
                            height : "auto"
                        }); // apply new size to img
                    }
</code>```

Body:
I am using fancybox version 2.1.5
What I am trying to do is display large images in the fancybox iframe of about width 900 and height 500. Of course right now images render huge and don't fit into that iframe.
I am having a hard time capturing the right class or a way to navigate to the image to resize it. What I tried is using beforeShow function and do this:

                 $(".fancybox").fancybox({
                    type: 'iframe',
                    href: source,
                    title: title,
                    width: 900,
                    height: 500,
                    closeBtn: false,
                    nextSpeed: 0, //important
                    prevSpeed: 0, //important
                    beforeShow: function() {
                        alert('its working!');
                        $(".fancybox-iframe img").css("width","900px");
                        $(".fancybox-iframe img").css("height","auto");
                        $(".fancybox-iframe img").addClass("imageResize");
                    }
                });

However, neither $(".fancybox-iframe img") nor $(".fancybox-inner img") are correct ways to trigger the img.
How can I use beforeShow function to properly resize my images inside the fancybox iframe.
Thanks!

Body:
I figured it out

                    beforeShow: function () {
                        var newWidth = 900; // set new image display width
                        $('.fancybox-iframe').contents().find('img').css({
                            width  : newWidth,
                            height : "auto"
                        }); // apply new size to img
                    }


问:
Android layout overlay tobe uses instead of Toast
I managed to have a relative layout with an image in the middle over a constraint layout - this image should be shown instead of a Toast-Message (fade in => fade out)

When the app starts - just to prove that it works - it shows that image from the XML settings (thumb up / visibility).

Now I want to use the following function to change the image:

```<code>  public void showThumbs(Integer like){
    if (like > 0){
        overlayout.bringToFront();
        overlay.setImageResource(R.drawable.like);
        overlay.bringToFront();
        overlay.animate().alpha(1.0f).setDuration(800);
        overlay.animate().alpha(0.0f).setDuration(800);
    }
    if (like < 0){
        overlayout.bringToFront();
        overlay.setImageResource(R.drawable.dislike);
        overlay.bringToFront();
        overlay.animate().alpha(1.0f).setDuration(800);
        overlay.animate().alpha(0.0f).setDuration(800);
    }
}
</code>```

I tried to work with visibility which did not work and now I tried the animation fader.

What happens is this:

At the beginning it shows the thumb up as set in the XML-layout itself - OK

When I set like to a negative value it changes the image and fades it out

When I set like to a positive value it uses the thumbs up and fades it out

But it only works fades the image the first time and only the fade out part.
As soon as it is gone I can call this function again an again and it will not show any picture anymore.

Any idea where my mistake is?

It should work like a Toast-Message (Fade in => Fade out).

答:
First of all there should be else between if statements. So you should have if( ){ } else { } instead of if( ) { } if( ) { }

Secondly, this line makes your image invisible permanently:

overlay.animate().alpha(0.0f).setDuration(800);

To make it work you should "chain" you animations. First option is:

```<code>if (isLiked) {
    overlay.setImageResource(R.drawable.like);
    // overlay is invisible by default
    overlay.animate()
        .alpha(1.0f)
        .setListener(new AnimatorListenerAdapter() {
          @Override
          public void onAnimationEnd(Animator animation) {
            super.onAnimationEnd(animation);
            overlay.animate().alpha(0.0f).setDuration(800);
          }
        }).setDuration(800);
} else {
    //...
}
</code>```

Another option is using AnimatorSet.

```<code>ObjectAnimator fadeOut = ObjectAnimator.ofFloat(overlay, "alpha",  1f, 0f);
fadeOut.setDuration(800);
ObjectAnimator fadeIn = ObjectAnimator.ofFloat(overlay, "alpha", 0f, 1f);
fadeIn.setDuration(800);

final AnimatorSet mAnimationSet = new AnimatorSet();

mAnimationSet.play(fadeOut).after(fadeIn);
mAnimationSet.start();
</code>```

Body:
I managed to have a relative layout with an image in the middle over a constraint layout - this image should be shown instead of a Toast-Message (fade in => fade out)

When the app starts - just to prove that it works - it shows that image from the XML settings (thumb up / visibility).

Now I want to use the following function to change the image:

  public void showThumbs(Integer like){
    if (like > 0){
        overlayout.bringToFront();
        overlay.setImageResource(R.drawable.like);
        overlay.bringToFront();
        overlay.animate().alpha(1.0f).setDuration(800);
        overlay.animate().alpha(0.0f).setDuration(800);
    }
    if (like < 0){
        overlayout.bringToFront();
        overlay.setImageResource(R.drawable.dislike);
        overlay.bringToFront();
        overlay.animate().alpha(1.0f).setDuration(800);
        overlay.animate().alpha(0.0f).setDuration(800);
    }
}

I tried to work with visibility which did not work and now I tried the animation fader.

What happens is this:

At the beginning it shows the thumb up as set in the XML-layout itself - OK

When I set like to a negative value it changes the image and fades it out

When I set like to a positive value it uses the thumbs up and fades it out

But it only works fades the image the first time and only the fade out part.
As soon as it is gone I can call this function again an again and it will not show any picture anymore.

Any idea where my mistake is?

It should work like a Toast-Message (Fade in => Fade out).

Body:
First of all there should be else between if statements. So you should have if( ){ } else { } instead of if( ) { } if( ) { }

Secondly, this line makes your image invisible permanently:

overlay.animate().alpha(0.0f).setDuration(800);

To make it work you should "chain" you animations. First option is:

if (isLiked) {
    overlay.setImageResource(R.drawable.like);
    // overlay is invisible by default
    overlay.animate()
        .alpha(1.0f)
        .setListener(new AnimatorListenerAdapter() {
          @Override
          public void onAnimationEnd(Animator animation) {
            super.onAnimationEnd(animation);
            overlay.animate().alpha(0.0f).setDuration(800);
          }
        }).setDuration(800);
} else {
    //...
}

Another option is using AnimatorSet.

ObjectAnimator fadeOut = ObjectAnimator.ofFloat(overlay, "alpha",  1f, 0f);
fadeOut.setDuration(800);
ObjectAnimator fadeIn = ObjectAnimator.ofFloat(overlay, "alpha", 0f, 1f);
fadeIn.setDuration(800);

final AnimatorSet mAnimationSet = new AnimatorSet();

mAnimationSet.play(fadeOut).after(fadeIn);
mAnimationSet.start();


问:
how to set variable/custom id value to Html.TextBoxFor - MVC, C#, Razor
How does one give a TextBoxFor a variable ID value?

Example Attempt:

```<code> @var variable = model.codeOne;

<div>
@Html.TextBoxFor(item => item.OperationNo, new { id = "@("materialCostInput"+
variable)" })
</div>
</code>```

I have looked around the forum for an answer to this question, but have yet to find a similar question.

答:
You can do like this</p>

```<code>@{
    var variable = "123";
 }
@Html.TextBoxFor(item => item.OperationNo, new { id = "materialCostInput" + variable })
</code>```

Body:
How does one give a TextBoxFor a variable ID value?

Example Attempt:

 @var variable = model.codeOne;

@Html.TextBoxFor(item => item.OperationNo, new { id = "@("materialCostInput"+
variable)" })

I have looked around the forum for an answer to this question, but have yet to find a similar question.

Body:
You can do like this

@{
    var variable = "123";
 }
@Html.TextBoxFor(item => item.OperationNo, new { id = "materialCostInput" + variable })


问:
Angular table filter on inner array of an object

I am new the angular, what I am trying to do is applying filter on inner array of an object from table row, filter is working but works only for that td, not for the entire row, why is this happening, is there anything missing here? Any help is much appreciated.

plunker here:  http://plnkr.co/edit/lXxTS1A3zRCk6mdtw2JP?p=preview

答:
You should apply the filter to the correct field where is associated your ng-model.
So instead of:

```<code><tr ng-repeat="item in tableObject | filter:search">
</code>```

It should be for example:

```<code><tr ng-repeat="item in tableObject | filter:search.title">
</code>```

Body:
You should apply the filter to the correct field where is associated your ng-model.
So instead of:

<tr ng-repeat="item in tableObject | filter:search">

It should be for example:

<tr ng-repeat="item in tableObject | filter:search.title">


问:
Play video and sound in python, with RAM cache
I am writing a python application. This application should play a sound or a video when the user press a button.

This are always the same sounds and videos which are played. Each video and each sound may be played several times.

This application will work on a raspberry Pi.

Here is what i have done:

for audio:

```<code>pygame.mixer.init()
pygame.init()
pygame.mixer.music.load("myfile.mp3")
pygame.mixer.music.play()
</code>```

for video:

```<code>p = Popen(['omxplayer', 'myvideo.mp4'])
</code>```

It works great but the video is not immediatly displayed. This is normal, because the system should load mp4 file on disk and launch external player.

What i want to do is to load all my audio and video files into ram memory and play it immediatly when the user press the button.

I only have 5 videos or audio files, but the users will tap 100 times on the button. As you can understand, i cannot load files on disk each time.

So my question is: how can i load, play and display files from ram memory in python ?

Thanks

答:
Comment: ... there missing a "global media" in playmedia function

There is no global required, as there is first a read media and therfore Binds to the Local Namespace of def. But does not harm.

```<code>    if not filename in media:
</code>```

Comment: i cannot do twice the section with pygame.mixer ...

Try adding a seek.

```<code>    media[filename].seek(0)
    pygame.mixer.music.load(...
</code>```

The buffer is discarded when music calls the close() method.
  Then, check if music can be forced NOT TO CLOSE the Filehandle.

This example plays the two Media Files 3 Times, but load File once in Memory:

```<code>import io, subprocess, time
media = {}
def playMedia(filename):
    if not filename in media:
        with open(filename, 'rb') as in_file:
            media[filename] = io.BytesIO(in_file.read())

    p = subprocess.Popen(['./mplayer', '-cache 8192'], stdin=subprocess.PIPE )
    p.stdin.write(media[filename].getbuffer())
    p.stdin.close()

    time.sleep(5)
    p.terminate()

if __name__ == '__main__':
    for n in range(3):
        for m in ["mp.mp3", 'mp.mp4']:
            playMedia(m)
</code>```

Body:
I am writing a python application. This application should play a sound or a video when the user press a button.

This are always the same sounds and videos which are played. Each video and each sound may be played several times.

This application will work on a raspberry Pi.

Here is what i have done:

for audio:

pygame.mixer.init()
pygame.init()
pygame.mixer.music.load("myfile.mp3")
pygame.mixer.music.play()

for video:

p = Popen(['omxplayer', 'myvideo.mp4'])

It works great but the video is not immediatly displayed. This is normal, because the system should load mp4 file on disk and launch external player.

What i want to do is to load all my audio and video files into ram memory and play it immediatly when the user press the button.

I only have 5 videos or audio files, but the users will tap 100 times on the button. As you can understand, i cannot load files on disk each time.

So my question is: how can i load, play and display files from ram memory in python ?

Thanks

Body:
Comment: ... there missing a "global media" in playmedia function

There is no global required, as there is first a read media and therfore Binds to the Local Namespace of def. But does not harm.

    if not filename in media:

Comment: i cannot do twice the section with pygame.mixer ...

Try adding a seek.

    media[filename].seek(0)
    pygame.mixer.music.load(...

The buffer is discarded when music calls the close() method.
  Then, check if music can be forced NOT TO CLOSE the Filehandle.

This example plays the two Media Files 3 Times, but load File once in Memory:

import io, subprocess, time
media = {}
def playMedia(filename):
    if not filename in media:
        with open(filename, 'rb') as in_file:
            media[filename] = io.BytesIO(in_file.read())

    p = subprocess.Popen(['./mplayer', '-cache 8192'], stdin=subprocess.PIPE )
    p.stdin.write(media[filename].getbuffer())
    p.stdin.close()

    time.sleep(5)
    p.terminate()

if __name__ == '__main__':
    for n in range(3):
        for m in ["mp.mp3", 'mp.mp4']:
            playMedia(m)


问:
Ionic GUI freezes with click event
I'm having som issues with a button in my Ionic app. My button have a click event "loginEvent()" that performs a login for the user. I have two span tags that is supposed to display a loading symbol while the login is performed.

The problem is that the button is not updated with the loading symbol until the loginEvent() returns. The click animation on the button does also not run until the loginEvent() returns.

When the button is clicked both "login" and "/login" is printed before the button updates to a spinner, giving the impression that the GUI freezes. The desired behaviour is that the login-button get the spinner while the login call is being performed.

Any idea why my button behaves like this?

Login button

<button ion-button block (click)="loginEvent();">
    Logga in
    <ion-spinner></ion-spinner>
</button>
```

<p><strong>loginEvent()</strong></p>

<pre class="lang-js prettyprint-override"><code>loginEvent() {
    console.log("login");
    this.isLoading = true;
    this.userHandler.login(this.username, this.password, this); //Performa authentication to Amazon Cognito and returns the result via callback function
    console.log("/login");
}
</code>```

EDIT

Adding the code for my UserHandler and AuthenticationService.

UserHandler.ts

@Injectable()
export class UserHandler {

    constructor(public authenticationService: AuthenticationService) {
        this.observers = new Array<Observer>();
    }

    public login(username: string, password: string, callback: any) {
        this.authenticationService.performLogin(username, password, callback);
    }
}
```

<p><strong>AuthenticationService.ts</strong></p>

<pre class="lang-js prettyprint-override"><code>public performLogin(username: string, password: string, callback: CognitoCallback) {

    username = username .toLowerCase();

    var authenticationData = {
        Username: username,
        Password: password,
    };
    var authenticationDetails = new AWSCognito.AuthenticationDetails(authenticationData);

    var userData = {
        Username: username,
        Pool: this.getUserPool()
    };

    let cognitoUser = new AWSCognito.CognitoUser(userData);
    cognitoUser.authenticateUser(authenticationDetails, {

        onSuccess: function (result: any) {
            var loginKey = 'cognito-idp.' + environment.region + '.amazonaws.com/' + environment.userPoolId;

            var loginProvider = {};
            loginProvider[loginKey] = result.getIdToken().getJwtToken();

            var credentials = new AWS.CognitoIdentityCredentials({
                IdentityPoolId: environment.identityPoolId,
                Logins: loginProvider
            });

            credentials.refresh((error: any) => {
                if (error) {
                    console.error(error);
                }
            });

            credentials.get(function (err: any) {
                if (!err) {
                    callback.cognitoCallback(null, result, "FAILED");
                } else {
                    callback.cognitoCallback(err.message, null, "SUCCESS");
                }
            });
        },

        onFailure: function (err: any) {
            callback.cognitoCallback(err.message, null, "FAILURE");
        },
        newPasswordRequired: function (userAttributes: any, requiredAttributes: any) {
            callback.cognitoCallback("Please set a new password", null, "newPasswordRequired");
        }
    });
}
</code>```

答:
I guess 'userHandler.login' is used to call the API for user authentication. As the HTTP requests are asynchronous it returns promise immediately you call them.

Instead of the spinner, you can use ionic loading component, where you can show the loader until the API returns the response.
Please share your userHandler code.

Title: Ionic GUI freezes with click event

Body:
I'm having som issues with a button in my Ionic app. My button have a click event "loginEvent()" that performs a login for the user. I have two span tags that is supposed to display a loading symbol while the login is performed.

The problem is that the button is not updated with the loading symbol until the loginEvent() returns. The click animation on the button does also not run until the loginEvent() returns.

When the button is clicked both "login" and "/login" is printed before the button updates to a spinner, giving the impression that the GUI freezes. The desired behaviour is that the login-button get the spinner while the login call is being performed.

Any idea why my button behaves like this?

Login button

<button ion-button block (click)="loginEvent();">
    Logga in
    <ion-spinner></ion-spinner>
</button>

loginEvent()

loginEvent() {
    console.log("login");
    this.isLoading = true;
    this.userHandler.login(this.username, this.password, this); //Performa authentication to Amazon Cognito and returns the result via callback function
    console.log("/login");
}

EDIT

Adding the code for my UserHandler and AuthenticationService.

UserHandler.ts

@Injectable()
export class UserHandler {

    constructor(public authenticationService: AuthenticationService) {
        this.observers = new Array<Observer>();
    }

    public login(username: string, password: string, callback: any) {
        this.authenticationService.performLogin(username, password, callback);
    }
}

AuthenticationService.ts

public performLogin(username: string, password: string, callback: CognitoCallback) {

    username = username .toLowerCase();

    var authenticationData = {
        Username: username,
        Password: password,
    };
    var authenticationDetails = new AWSCognito.AuthenticationDetails(authenticationData);

    var userData = {
        Username: username,
        Pool: this.getUserPool()
    };

    let cognitoUser = new AWSCognito.CognitoUser(userData);
    cognitoUser.authenticateUser(authenticationDetails, {

        onSuccess: function (result: any) {
            var loginKey = 'cognito-idp.' + environment.region + '.amazonaws.com/' + environment.userPoolId;

            var loginProvider = {};
            loginProvider[loginKey] = result.getIdToken().getJwtToken();

            var credentials = new AWS.CognitoIdentityCredentials({
                IdentityPoolId: environment.identityPoolId,
                Logins: loginProvider
            });

            credentials.refresh((error: any) => {
                if (error) {
                    console.error(error);
                }
            });

            credentials.get(function (err: any) {
                if (!err) {
                    callback.cognitoCallback(null, result, "FAILED");
                } else {
                    callback.cognitoCallback(err.message, null, "SUCCESS");
                }
            });
        },

        onFailure: function (err: any) {
            callback.cognitoCallback(err.message, null, "FAILURE");
        },
        newPasswordRequired: function (userAttributes: any, requiredAttributes: any) {
            callback.cognitoCallback("Please set a new password", null, "newPasswordRequired");
        }
    });
}


问:
pseudo selector for uppercase chars/words?
Is there a CSS pseudoselector for uppercase characters/letters/words? I want all my capitals to be a pt smaller and all the other characters the same size. A capital is not neccesarily the first character of a sentence (or word) nor the other way around.

Or maybe there's another way to find these characters in CSS? With a trick? I like tricks.

答:
This is not possible using CSS.

You could use Javascript to check all characters in your text for uppercase (e.g. by using if (yourtext == yourtext.toUpperCase())) and then wrap a  around them containing your CSS to style these.

Or something around these lines:

```<code>function wrapCaps() {
    var text = document.getElementById("my_text").value;
    for(i=0; i < text.length; i++) {
        if(text[i].charCodeAt(text[i]) >= 65 && text[i].charCodeAt(text[i]) <= 90)
        wrapNode(text[i], 'span');
    }
}
</code>```

I didn't try it out (maybe somebody has the time to create a jsfiddle with this?), you might need to use replaceNode or something like that. The charCodeAt method just looks for uppercase letters, please note that no unicode characters like special greek uppercase letters will be included.

You now only need to style your span with something like:

```<code>#my_text span {
    font-size: 10px;
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
This is not possible using CSS.

You could use Javascript to check all characters in your text for uppercase (e.g. by using if (yourtext == yourtext.toUpperCase())) and then wrap a <span> around them containing your CSS to style these.

Or something around these lines:

function wrapCaps() {
    var text = document.getElementById("my_text").value;
    for(i=0; i < text.length; i++) {
        if(text[i].charCodeAt(text[i]) >= 65 && text[i].charCodeAt(text[i]) <= 90)
        wrapNode(text[i], 'span');
    }
}

I didn't try it out (maybe somebody has the time to create a jsfiddle with this?), you might need to use replaceNode or something like that. The charCodeAt method just looks for uppercase letters, please note that no unicode characters like special greek uppercase letters will be included.

You now only need to style your span with something like:

#my_text span {
    font-size: 10px;
}


问:
How to test an ES6 class that needs jquery?
I have an ES6 module that needs jquery.

```<code>import $ from 'jquery';

export class Weather {
    /**
     * Constructor for Weather class
     *
     * @param latitude
     * @param longitude
     */
    constructor(latitude, longitude) {
        this.latitude  = latitude;
        this.longitude = longitude;
    }

    /**
     * Fetches the weather using API
     */
    getWeather() {
        return $.ajax({
            url: 'http://localhost:8080/weather?lat=' + this.latitude + '&lon=' + this.longitude,
            method: "GET",
        }).promise();
    }
}
</code>```

Module works fine when use it in my main module but the issue is with the test that I am writing for it.

Here's the test:

```<code>import {Weather} from '../js/weather';
import chai from 'chai';
import sinon from 'sinon';

chai.should();

describe('weatherbot', function() {
    beforeEach(function() {
        this.xhr = sinon.useFakeXMLHttpRequest();

        this.requests = [];
        this.xhr.onCreate = function(xhr) {
            this.requests.push(xhr);
        }.bind(this);
    });

    afterEach(function() {
        this.xhr.restore();
    });

    it('should return a resolved promise if call is successful', (done) => {
        let weather = new Weather(43.65967339999999, -79.72506369999999);

        let data = '{"coord":{"lon":-79.73,"lat":43.66},"weather":[{"id":521,"main":"Rain","description":"shower rain","icon":"09d"}],"base":"stations","main":{"temp":15.28,"pressure":1009,"humidity":82,"temp_min":13,"temp_max":17},"visibility":24140,"wind":{"speed":7.2,"deg":30},"clouds":{"all":90},"dt":1496770020,"sys":{"type":1,"id":3722,"message":0.0047,"country":"CA","sunrise":1496741873,"sunset":1496797083},"id":5907364,"name":"Brampton","cod":200}';

        weather.getWeather().then((data) => {
            expect(data.main.temp).to.equal(15.28);
            done();
        });

        this.requests[0].respond("GET", "/weather?lat=43.659673399999996&lon=-79.72506369999999", [
            200, {"Content-Type":"application/json"}, JSON.stringify(data)
        ]);
    });
});
</code>```

And here's my package.json:

```<code>{
  "devDependencies": {
    "babel-core": "^6.24.1",
    "babel-loader": "^6.1.0",
    "babel-polyfill": "^6.3.14",
    "babel-preset-es2015": "^6.1.18",
    "chai": "^3.5.0",
    "copy-webpack-plugin": "^0.2.0",
    "css-loader": "^0.28.0",
    "extract-text-webpack-plugin": "^2.1.0",
    "file-loader": "^0.11.1",
    "mocha": "^3.4.1",
    "mocha-webpack": "^1.0.0-beta.1",
    "qunitjs": "^2.3.2",
    "sinon": "^2.2.0",
    "style-loader": "^0.16.1",
    "svg-inline-loader": "^0.7.1",
    "webpack": "*",
    "webpack-dev-server": "^1.12.1",
    "webpack-node-externals": "^1.6.0"
  },
  "scripts": {
    "build": "webpack",
    "watch": "webpack --watch --display-error-details",
    "start": "webpack-dev-server --hot --inline --port 8383",
    "test": "mocha --compilers js:babel-core/register ./test/*.js",
    "test:watch": "npm run test -- --watch"
  },
  "babel": {
    "presets": [
      "es2015"
    ]
  },
  "dependencies": {
    "bootstrap": "^3.3.7",
    "jquery": "^3.2.1",
    "webpack": "*"
  }
}
</code>```

As you can see I only have to do npm test to run the test.

When do npm test, I get this error:

```<code>TypeError: _jquery2.default.ajax is not a function
      at Weather.getWeather (js/weather.js:19:18)
      at Context.<anonymous> (test/index.js:26:17)
</code>```

But I am importing the jquery in the module, why it might be happening?

答:
In my project, I stub all the jQuery methods I use, so, I would stub $.ajax since all you need to test are the returned promises.

Something like this in another file:

```<code>module.exports = {
  ajax: sinon.stub(global.$, 'ajax')
}
</code>```

Then, in your test

```<code>import { ajax } from 'stubs'
</code>```

This way, the ajax method is stubbed and you can define what it should return on a per test basis:

```<code>ajax.returns({
  done: (callback) => { callback(someParam) },
  fail: () => {},
  always: (callback) => { callback() }
});
</code>```

Body:
I have an ES6 module that needs jquery.

import $ from 'jquery';

export class Weather {
    /**
     * Constructor for Weather class
     *
     * @param latitude
     * @param longitude
     */
    constructor(latitude, longitude) {
        this.latitude  = latitude;
        this.longitude = longitude;
    }

    /**
     * Fetches the weather using API
     */
    getWeather() {
        return $.ajax({
            url: 'http://localhost:8080/weather?lat=' + this.latitude + '&lon=' + this.longitude,
            method: "GET",
        }).promise();
    }
}

Module works fine when use it in my main module but the issue is with the test that I am writing for it.

Here's the test:

import {Weather} from '../js/weather';
import chai from 'chai';
import sinon from 'sinon';

chai.should();

describe('weatherbot', function() {
    beforeEach(function() {
        this.xhr = sinon.useFakeXMLHttpRequest();

        this.requests = [];
        this.xhr.onCreate = function(xhr) {
            this.requests.push(xhr);
        }.bind(this);
    });

    afterEach(function() {
        this.xhr.restore();
    });

    it('should return a resolved promise if call is successful', (done) => {
        let weather = new Weather(43.65967339999999, -79.72506369999999);

        let data = '{"coord":{"lon":-79.73,"lat":43.66},"weather":[{"id":521,"main":"Rain","description":"shower rain","icon":"09d"}],"base":"stations","main":{"temp":15.28,"pressure":1009,"humidity":82,"temp_min":13,"temp_max":17},"visibility":24140,"wind":{"speed":7.2,"deg":30},"clouds":{"all":90},"dt":1496770020,"sys":{"type":1,"id":3722,"message":0.0047,"country":"CA","sunrise":1496741873,"sunset":1496797083},"id":5907364,"name":"Brampton","cod":200}';

        weather.getWeather().then((data) => {
            expect(data.main.temp).to.equal(15.28);
            done();
        });

        this.requests[0].respond("GET", "/weather?lat=43.659673399999996&lon=-79.72506369999999", [
            200, {"Content-Type":"application/json"}, JSON.stringify(data)
        ]);
    });
});

And here's my package.json:

{
  "devDependencies": {
    "babel-core": "^6.24.1",
    "babel-loader": "^6.1.0",
    "babel-polyfill": "^6.3.14",
    "babel-preset-es2015": "^6.1.18",
    "chai": "^3.5.0",
    "copy-webpack-plugin": "^0.2.0",
    "css-loader": "^0.28.0",
    "extract-text-webpack-plugin": "^2.1.0",
    "file-loader": "^0.11.1",
    "mocha": "^3.4.1",
    "mocha-webpack": "^1.0.0-beta.1",
    "qunitjs": "^2.3.2",
    "sinon": "^2.2.0",
    "style-loader": "^0.16.1",
    "svg-inline-loader": "^0.7.1",
    "webpack": "*",
    "webpack-dev-server": "^1.12.1",
    "webpack-node-externals": "^1.6.0"
  },
  "scripts": {
    "build": "webpack",
    "watch": "webpack --watch --display-error-details",
    "start": "webpack-dev-server --hot --inline --port 8383",
    "test": "mocha --compilers js:babel-core/register ./test/*.js",
    "test:watch": "npm run test -- --watch"
  },
  "babel": {
    "presets": [
      "es2015"
    ]
  },
  "dependencies": {
    "bootstrap": "^3.3.7",
    "jquery": "^3.2.1",
    "webpack": "*"
  }
}

As you can see I only have to do npm test to run the test.

When do npm test, I get this error:

TypeError: _jquery2.default.ajax is not a function
      at Weather.getWeather (js/weather.js:19:18)
      at Context.<anonymous> (test/index.js:26:17)

But I am importing the jquery in the module, why it might be happening?

Body:
In my project, I stub all the jQuery methods I use, so, I would stub $.ajax since all you need to test are the returned promises.

Something like this in another file:

module.exports = {
  ajax: sinon.stub(global.$, 'ajax')
}

Then, in your test

import { ajax } from 'stubs'

This way, the ajax method is stubbed and you can define what it should return on a per test basis:

ajax.returns({
  done: (callback) => { callback(someParam) },
  fail: () => {},
  always: (callback) => { callback() }
});


问:
what method is created for this? perl
I need an explanation of this one liner. Is this only calling the set() method? Or something else?

Thanks for the help!

has 'shape' =>
( is => 'rw' );

The object is using MooseX::FollowPBP.

答:
This is basic Moose syntax. has is a Moose keyword that defines an attribute in your class. The attributes name is shape, and it is read-write.

It's documented in multiple places.

has $name|@$names => %options

This will install an attribute of a given $name into the current class. If the first parameter is an array reference, it will create an attribute for every $name in the list. The %options will be passed to the constructor for Moose::Meta::Attribute (which inherits from Class::MOP::Attribute), so the full documentation for the valid options can be found there.

The MooseX::FollowPBP has nothing to do with it directly. It just changes the behavior of Moose, to turn the default accessor $obj->shape into $obj->get_shape and $obj->set_shape, following the suggestion of Damian Conway in his book Perl Best Practices.

Title: what method is created for this? perl


问:
LS and ES monitorign
i am using EL and LS of the same version 5.4.0 and filbeat version 5.4.1.there is the configuration.
--------------elasticsearch.yml

```<code>cluster.name: elasticsearch
node.name: node1
node.attr.rack: r1
path.data: /path/to/data
path.logs: /path/to/logs
bootstrap.memory_lock: true
network.host: 0.0.0.0
http.port: 9200
discovery.zen.ping.unicast.hosts: ["127.0.0.1:9200", "127.0.0.1:9200"]
discovery.zen.minimum_master_nodes: 3
gateway.recover_after_nodes: 3
action.destructive_requires_name: true
</code>```

----------filebeat.yml

```<code>filebeat.prospectors:
input_type: log
paths:
- c:\logstash-tutorial.log
output.logstash:
hosts: ["localhost:5044"]
</code>```

--------------pipeline.conf-----

```<code>input {
beats {
port => "5044"
}
}
filter {
grok {
match => { "message" => "%{COMBINEDAPACHELOG}"}
}
geoip {
source => "clientip"
}
}
output {
elasticsearch {
hosts =>"localhost:9200"
}
stdout { codec => rubydebug }
}
</code>```

Note:the LS and ES are runing at the port 6900 and 9200 well.but i get those errors:
for filebeat: ERR Connecting error publishing events (retrying): dial tcp 127.0.0.1:5044: connectex: Aucune connexion n’a pu être établie car l’ordinateur cible l’a expressément refusée.
for logstash:error=>"Got response code '503' contacting Elasticsearch at URL 'http://localhost:9200/
Please how can i solve this probleme?

答:
Try to bind to 127.0.0.1:9200 instead of localhost, maybe:

```<code>output {
elasticsearch {
    hosts =>"127.0.0.1:9200"
}
    stdout { codec => rubydebug }
}
</code>```

Title: LS and ES monitorign

Body:
i am using EL and LS of the same version 5.4.0 and filbeat version 5.4.1.there is the configuration.
--------------elasticsearch.yml

cluster.name: elasticsearch
node.name: node1
node.attr.rack: r1
path.data: /path/to/data
path.logs: /path/to/logs
bootstrap.memory_lock: true
network.host: 0.0.0.0
http.port: 9200
discovery.zen.ping.unicast.hosts: ["127.0.0.1:9200", "127.0.0.1:9200"]
discovery.zen.minimum_master_nodes: 3
gateway.recover_after_nodes: 3
action.destructive_requires_name: true

----------filebeat.yml

filebeat.prospectors:
input_type: log
paths:
- c:\logstash-tutorial.log
output.logstash:
hosts: ["localhost:5044"]

--------------pipeline.conf-----

input {
beats {
port => "5044"
}
}
filter {
grok {
match => { "message" => "%{COMBINEDAPACHELOG}"}
}
geoip {
source => "clientip"
}
}
output {
elasticsearch {
hosts =>"localhost:9200"
}
stdout { codec => rubydebug }
}

Note:the LS and ES are runing at the port 6900 and 9200 well.but i get those errors:
for filebeat: ERR Connecting error publishing events (retrying): dial tcp 127.0.0.1:5044: connectex: Aucune connexion n’a pu être établie car l’ordinateur cible l’a expressément refusée.
for logstash:error=>"Got response code '503' contacting Elasticsearch at URL 'http://localhost:9200/
Please how can i solve this probleme?

Body:
Try to bind to 127.0.0.1:9200 instead of localhost, maybe:

output {
elasticsearch {
    hosts =>"127.0.0.1:9200"
}
    stdout { codec => rubydebug }
}


问:
Pandas df to database using flask-sqlalchemy
I'm trying to insert a pandas dataframe into a mysql database. I am using flask-sqlalchemy.

I have created this table:

```<code>class Client_Details(db.Model):
    __tablename__ = "client_history"

    client_id = db.Column(db.Integer, primary_key=True)
    client_name = db.Column(db.VARCHAR(50))
    shack= db.Column(db.VARCHAR(50))
</code>```

and I would like to insert the data from this df into it:

```<code>index   name     shack
0        jay       H9
1        ray       I8
2        t-bop     I6
3        jay-k     F89
4        phil      D89
</code>```

This doesn't seem to work:

```<code>for index, row in df.iterrows():
    client_add = client_history(client_name = row[1], shack =row[2])
    db.session.add(client_add)
    db.session.commit()
</code>```

Is there a better way to do this, using to_sql, perhaps?

答:
Kyle's answer was close - the flask-sqlalchemy engine IS created behind the scenes with some magic, but the correct way to access it is with db.engine. Here's what you're looking for:

```<code>df.to_sql(name='client_history', con=db.engine, index=False)
</code>```

I also agree with VinceP's assessment that to_sql can be slow for larger tables, so keep that in mind.

For what it's worth, you can also access the session with Flask-SQLAlchemy as db.session.

Body:
I'm trying to insert a pandas dataframe into a mysql database. I am using flask-sqlalchemy.

I have created this table:

class Client_Details(db.Model):
    __tablename__ = "client_history"

    client_id = db.Column(db.Integer, primary_key=True)
    client_name = db.Column(db.VARCHAR(50))
    shack= db.Column(db.VARCHAR(50))

and I would like to insert the data from this df into it:

index   name     shack
0        jay       H9
1        ray       I8
2        t-bop     I6
3        jay-k     F89
4        phil      D89

This doesn't seem to work:

for index, row in df.iterrows():
    client_add = client_history(client_name = row[1], shack =row[2])
    db.session.add(client_add)
    db.session.commit()

Is there a better way to do this, using to_sql, perhaps?

Body:
Kyle's answer was close - the flask-sqlalchemy engine IS created behind the scenes with some magic, but the correct way to access it is with db.engine. Here's what you're looking for:

df.to_sql(name='client_history', con=db.engine, index=False)

I also agree with VinceP's assessment that to_sql can be slow for larger tables, so keep that in mind.

For what it's worth, you can also access the session with Flask-SQLAlchemy as db.session.


问:
What is the IntentFilter that do my app be recognized like having audio to share?
What is the IntentFilter that I have to use in order to my app be recognized as like having audio to share? WhatsApp do not list my app anyway...

Like this:

I already tried:

```<code><intent-filter>
                <action android:name="android.intent.action.SEND" />
                <data android:mimeType="audio/*" />
</intent-filter>

<intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <data android:mimeType="audio/*" />
</intent-filter>
</code>```

and too

```<code><activity
        android:name=".activities.MyActivity"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
    <intent-filter>
        <action android:name="android.intent.action.PICK" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:mimeType="audio/*" />
    </intent-filter>
    <intent-filter>
        <action android:name="android.intent.action.GET_CONTENT" />
        <category android:name="android.intent.category.OPENABLE" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:mimeType="audio/*" />
    </intent-filter>
</activity>
</code>```

But nothing seems to work...

Anyone knows?

Thx

答:
I don't know if you are looking for this, but try to use the mimeType audio:

```<code><intent-filter>
    <action android:name="android.intent.action.SEND" />
    <category android:name="android.intent.category.DEFAULT"/>
    <data android:mimeType="audio/*" />
</intent-filter>
</code>```

For more info visit Android Intent-Filter Doc

Body:
What is the IntentFilter that I have to use in order to my app be recognized as like having audio to share? WhatsApp do not list my app anyway...

Like this:

I already tried:

<intent-filter>
                <action android:name="android.intent.action.SEND" />
                <data android:mimeType="audio/*" />
</intent-filter>

<intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <data android:mimeType="audio/*" />
</intent-filter>

and too

<activity
        android:name=".activities.MyActivity"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
    <intent-filter>
        <action android:name="android.intent.action.PICK" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:mimeType="audio/*" />
    </intent-filter>
    <intent-filter>
        <action android:name="android.intent.action.GET_CONTENT" />
        <category android:name="android.intent.category.OPENABLE" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:mimeType="audio/*" />
    </intent-filter>
</activity>

But nothing seems to work...

Anyone knows?

Thx

Body:
I don't know if you are looking for this, but try to use the mimeType audio:

<intent-filter>
    <action android:name="android.intent.action.SEND" />
    <category android:name="android.intent.category.DEFAULT"/>
    <data android:mimeType="audio/*" />
</intent-filter>

For more info visit Android Intent-Filter Doc


问:
Removing shortcut arrow from icon
I'm writing a little program (in C#) that allows me to make a list of games and sort these by specific categories, but because of the way Steam adds shortcuts to your games (via a .url file that redirects to a steam link) I have to extract them using the code found on this microsoft support page:

https://support.microsoft.com/en-us/help/319350/how-to-use-the-shgetfileinfo-function-to-get-the-icons-that-are-associated-with-files-in-visual-c-.net

However, with this code, I run into the issue that the little shortcut arrow is put upon the icon, which I'd rather avoid for aesthetic reasons. I've Googled the issue plenty, but the only results that came up were ways to remove all shortcut arrows from my computer via registry changes, which I'm not interested in. I'd be very grateful if someone had a solution to this issue.

答: I tried to remove the short-cut icon it's not possible unless you edit the registry. i tried to copy the application to different folder but the application doesn't work has it doesn't have any reference. I tried to create a icon using Photoshop and tried to change the icon it still adds the short cut icon to it. There are "Ultimate windows tweaker" which removes the shortcut on all the icons. I would say it's not possible to remove on single application and if you check the properties of the shorcut icon you would see the "start in" linking to main application. </p>

Title: Removing shortcut arrow from icon


问:
Matlab - Creating two arrays that consider all possible values for two objects
I have two physical "objects." I am representing their positions with two different arrays.

• Object 1 moves in the xy-plane only

• Object 2 moves in all three physical dimensions

Objective: Vectorize the four for loops without distorting the data. Also, the intent is to perform this operation for all possible values of object 1 to be compared with object 2.

Here is the code snippet:

```<code>Npos = 21;
Nsam = 200;

% dummy initialisation
AX = rand(1, Npos);
AY = zeros(1, Npos);
AZ = rand(1, Npos);
Bx = rand(Nsam);
By = rand(Nsam);
Bz = rand(Nsam);

for qx = 1 : Npos
    for yx = 1 : Npos
        for zx = 1 : Nsam
            for cx = 1 : Nsam
                Tx2Array( qx, yx, zx, cx ) = sqrt( ( AX( qx ) - Bx( zx, cx ) ).^2 + ( AY( yx ) - By( zx, cx ) ).^2 + ( AZ( yx ) - Bz( zx, cx ) ).^2 );
            end
        end
    end
end
% Result is a 21 x 21 x 200 x 200 matrix filled with all real numbers
</code>```

Legend

AX, AY, AZ are 1 x 21 arrays and represent the (x,y=0,z) of Object 1

AY is all zeros, but for readability is still included (hence no fifth loop!)

Bx, By, Bz are all 200 x 200 arrays and represent the (x,y,z) of Object 2

Npos = 21; Nsam = 200;

The formula used above is:

```<code>sqrt( (a1-b1)^2 + (a2-b2)^2 + (a3-b3)^2 )
</code>```

答:
If you have the Statistics Toolbox available, you can use pdist2 to calculate the distance between each coordinate for Object 1 and each coordinate for Object 2:

```<code>[X1, Z1] = ndgrid(AX(:), AZ(:));   % X1 and Z1 will be 21x21
D = pdist2([X1(:), zeros(size(X1(:))), Z1(:)], [Bx(:), By(:), Bz(:)]);
</code>```

The output in this case will be a 441 x 40,000 array where D(i, j) gives you the distance between point i of Object 1 and point j of Object 2, both using linear indexing.

Body:
I have two physical "objects." I am representing their positions with two different arrays.

• Object 1 moves in the xy-plane only

• Object 2 moves in all three physical dimensions

Objective: Vectorize the four for loops without distorting the data. Also, the intent is to perform this operation for all possible values of object 1 to be compared with object 2.

Here is the code snippet:

Npos = 21;
Nsam = 200;

% dummy initialisation
AX = rand(1, Npos);
AY = zeros(1, Npos);
AZ = rand(1, Npos);
Bx = rand(Nsam);
By = rand(Nsam);
Bz = rand(Nsam);

for qx = 1 : Npos
    for yx = 1 : Npos
        for zx = 1 : Nsam
            for cx = 1 : Nsam
                Tx2Array( qx, yx, zx, cx ) = sqrt( ( AX( qx ) - Bx( zx, cx ) ).^2 + ( AY( yx ) - By( zx, cx ) ).^2 + ( AZ( yx ) - Bz( zx, cx ) ).^2 );
            end
        end
    end
end
% Result is a 21 x 21 x 200 x 200 matrix filled with all real numbers

Legend

AX, AY, AZ are 1 x 21 arrays and represent the (x,y=0,z) of Object 1

AY is all zeros, but for readability is still included (hence no fifth loop!)

Bx, By, Bz are all 200 x 200 arrays and represent the (x,y,z) of Object 2

Npos = 21; Nsam = 200;

The formula used above is:

sqrt( (a1-b1)^2 + (a2-b2)^2 + (a3-b3)^2 )

Body:
If you have the Statistics Toolbox available, you can use pdist2 to calculate the distance between each coordinate for Object 1 and each coordinate for Object 2:

[X1, Z1] = ndgrid(AX(:), AZ(:));   % X1 and Z1 will be 21x21
D = pdist2([X1(:), zeros(size(X1(:))), Z1(:)], [Bx(:), By(:), Bz(:)]);

The output in this case will be a 441 x 40,000 array where D(i, j) gives you the distance between point i of Object 1 and point j of Object 2, both using linear indexing.