问:
Cut a longer word/string in smaller chunks for fitting a field
I want to fill a field with a string of many words. When I have huge words I need a to split the word. If my word is longer than 10 letters I need a space at position 5 of this word.

How do I get the new "myString" with shorter words?

```<code>    static void Main(string[] args)
    {
        var myString = "This is my string with some loooooooooooooong words. Please devide meeeeeeeeeeeeeeeeeeeeeeeee";
        var myStringSplit = myString.Split();
        var query = myStringSplit.Where(x => x.Length > 10).ToList();
        foreach (var item in query)
        {
            item.Insert(5, " ");
        }
    }
</code>```

Edit: My expected result: myString = "This is my strin g with some loooo ooooo ooooo ng words. Pleas e devid e meeee eeeee eeeee eeeee eeeee e";

答:
Try this might be helpful

```<code>static void Main(string[] args)
        {
            var myString = "This is my string with some loooooooooooooong words. Please devide meeeeeeeeeeeeeeeeeeeeeeeee";
            var myStringSplit = myString.Split();
            var query = myStringSplit.Where(x => x.Length > 10).ToList();
            foreach (var item in query)
            {
                string outString = Regex.Replace(item, ".{5}", "$0 ");
            }
        }
</code>```

This will separates the string after each five words..

Edited

Body:
I want to fill a field with a string of many words. When I have huge words I need a to split the word. If my word is longer than 10 letters I need a space at position 5 of this word.

How do I get the new "myString" with shorter words?

    static void Main(string[] args)
    {
        var myString = "This is my string with some loooooooooooooong words. Please devide meeeeeeeeeeeeeeeeeeeeeeeee";
        var myStringSplit = myString.Split();
        var query = myStringSplit.Where(x => x.Length > 10).ToList();
        foreach (var item in query)
        {
            item.Insert(5, " ");
        }
    }

Edit: My expected result: myString = "This is my strin g with some loooo ooooo ooooo ng words. Pleas e devid e meeee eeeee eeeee eeeee eeeee e";

Body:
Try this might be helpful

static void Main(string[] args)
        {
            var myString = "This is my string with some loooooooooooooong words. Please devide meeeeeeeeeeeeeeeeeeeeeeeee";
            var myStringSplit = myString.Split();
            var query = myStringSplit.Where(x => x.Length > 10).ToList();
            foreach (var item in query)
            {
                string outString = Regex.Replace(item, ".{5}", "$0 ");
            }
        }

This will separates the string after each five words..

Edited


来源: stackexchange

问:
preventDefault() seems to disable entire form?
I have a very simple form:

```<code><form id="formRegister">
    ....
    <input autocomplete="off" class="form-control input-sm required " id="Code" maxlength="10" name="Code" placeholder="VIP Code" style="width:150px;" type="text" value="">
    ....
    <button id="btnVIPCodeLookup" type="submit" class="button-primary">Submit<i class="icon"></i></button>
</form>
</code>```

And here's the script behind it:

```<code>// Landing page form submit
$("#formRegister").submit(function (e) {
    e.preventDefault();
    var code = $('#Code').val();
    vipLookup(code);
});

function vipLookup(code) {
    showBusy();
    $.getJSON("/EventRegistration/EventRegistrationCodeLookUp", { code: code }, function (data) {
        hideBusy();
        if (data.Result == "true") {
            $('#CodeResultSpan').text('');
            $('#EncryptedCode').val(data.EncryptedVIPCode);
            ShowLegal();
        }
        else
        {
            if (data.Result == "false") {
                $('#CodeResultSpan').text('VIP Code not found. Please check the VIP Code you received and try again.');
            }
            if (data.Result == "used") {
                $('#CodeResultSpan').text('VIP Code has been used.');
            }
            if (data.Result == "error") {
                $('#CodeResultSpan').text('There was an error while looking up your VIP Code.  Please try again.');
            }
            if (data.Result == "canceled") {
                $('#CodeResultSpan').text('This VIP Code has been canceled.');
            }
            $('#Code').css('border-bottom', '1px solid #e03e3e');
        }
    });
}
</code>```

The weird thing that I am seeing in some browsers (especially any iOS device, or when emulating an iOS device in Chrome), is that after the button is clicked, the form becomes disabled.  I can't refocus into the textbox, and I can't click the button again.

If I remove e.preventDefault(); then the problem goes away, but this of course creates a new problem in that the page is refreshed, and the error messages vanishes.

You can see this in action here:

http://dev.walkup.audidriveusa.com/EventRegistration

Using Chrome, just type anything into the text box and click 'Submit'. You'll see the message.  Then (if you can) change the text, and try to click 'Submit' again.  It doesn't let you.

答:
If your goal with the form is not to submit it with a normal request, then you should not add a submit button. Add a button with type button instead:

```<code><button type="button" id="submitButton">some text</button>
</code>```

and

```<code>$('#submitButton').on('click', function (e) {
  var code = $('#Code').val();
  vipLookup(code);
});
</code>```

That will not trigger a submit of the form, then attach your eventhandler to that button instead.

If you want to handle hitting the enter key, add a handler for that.

```<code><div id="containerToWatchForEnter">
<form>
...
</form>
</div>
</code>```

and

```<code>$('#containerToWatchForEnter').on('keydown', function (e) {
  if(e.which == 13) {
    var code = $('#Code').val();
    vipLookup(code);
  }
});
</code>```

You might to only watch for hitting enter in input fields on that form - assuming you have only one form:

```<code>$('form:input').on('keydown', ...
</code>```

UPDATE:
You might want to watch for 'keypress' instead of 'keydown' when working with iOS.

ContentLicense: CC BY-SA 3.0

Body:
I have a very simple form:

<form id="formRegister">
    ....
    <input autocomplete="off" class="form-control input-sm required " id="Code" maxlength="10" name="Code" placeholder="VIP Code" style="width:150px;" type="text" value="">
    ....
    <button id="btnVIPCodeLookup" type="submit" class="button-primary">Submit</button>
</form>

And here's the script behind it:

// Landing page form submit
$("#formRegister").submit(function (e) {
    e.preventDefault();
    var code = $('#Code').val();
    vipLookup(code);
});

function vipLookup(code) {
    showBusy();
    $.getJSON("/EventRegistration/EventRegistrationCodeLookUp", { code: code }, function (data) {
        hideBusy();
        if (data.Result == "true") {
            $('#CodeResultSpan').text('');
            $('#EncryptedCode').val(data.EncryptedVIPCode);
            ShowLegal();
        }
        else
        {
            if (data.Result == "false") {
                $('#CodeResultSpan').text('VIP Code not found. Please check the VIP Code you received and try again.');
            }
            if (data.Result == "used") {
                $('#CodeResultSpan').text('VIP Code has been used.');
            }
            if (data.Result == "error") {
                $('#CodeResultSpan').text('There was an error while looking up your VIP Code.  Please try again.');
            }
            if (data.Result == "canceled") {
                $('#CodeResultSpan').text('This VIP Code has been canceled.');
            }
            $('#Code').css('border-bottom', '1px solid #e03e3e');
        }
    });
}

The weird thing that I am seeing in some browsers (especially any iOS device, or when emulating an iOS device in Chrome), is that after the button is clicked, the form becomes disabled.  I can't refocus into the textbox, and I can't click the button again.

If I remove e.preventDefault(); then the problem goes away, but this of course creates a new problem in that the page is refreshed, and the error messages vanishes.

You can see this in action here:

http://dev.walkup.audidriveusa.com/EventRegistration

Using Chrome, just type anything into the text box and click 'Submit'. You'll see the message.  Then (if you can) change the text, and try to click 'Submit' again.  It doesn't let you.

Body:
If your goal with the form is not to submit it with a normal request, then you should not add a submit button. Add a button with type button instead:

<button type="button" id="submitButton">some text</button>

and

$('#submitButton').on('click', function (e) {
  var code = $('#Code').val();
  vipLookup(code);
});

That will not trigger a submit of the form, then attach your eventhandler to that button instead.

If you want to handle hitting the enter key, add a handler for that.

<div id="containerToWatchForEnter">
<form>
...
</form>
</div>

and

$('#containerToWatchForEnter').on('keydown', function (e) {
  if(e.which == 13) {
    var code = $('#Code').val();
    vipLookup(code);
  }
});

You might to only watch for hitting enter in input fields on that form - assuming you have only one form:

$('form:input').on('keydown', ...

UPDATE:
You might want to watch for 'keypress' instead of 'keydown' when working with iOS.


问:
websocket-rails Chat Rooms
I am trying to create sort of Whatsapp like messaging app server side in Rails, with private conversations. now, I am trying to implement the realtime part of the app - I am using websocket-rails - and I am not sure how to send a message only to the users in the private message - I saw a feature called private channels in websocket-rails - but after reading the documentation, I got under the impression that each private channel needs to be defined statically, and I cannot create channels realtime.
Do you know how can I implement private conversations in websocket-rails, like a guide or a direction? or any other websocket service I can use to implement it? </p>

答:
You can pass parameters from the client side to the server side when creating a subscription. For example:

```<code># app/channels/chat_channel.rb
class ChatChannel < ApplicationCable::Channel
  def subscribed
    stream_from "chat_#{params[:room]}"
  end
end
</code>```

An object passed as the first argument to subscriptions.create becomes the params hash in the cable channel. The keyword channel is required:

```<code># app/assets/javascripts/cable/subscriptions/chat.coffee
App.cable.subscriptions.create { channel: "ChatChannel", room: "Best Room" },
  received: (data) ->
    @appendLine(data)

  appendLine: (data) ->
    html = @createLine(data)
    $("[data-chat-room='Best Room']").append(html)

  createLine: (data) ->
    """
    <article class="chat-line">
      <span class="speaker">#{data["sent_by"]}</span>
      <span class="body">#{data["body"]}</span>
    </article>
    """
</code>```

Somewhere in your app this is called, perhaps

```<code>ActionCable.server.broadcast(
  "chat_#{room}",
  sent_by: 'Paul',
  body: 'This is a cool chat app.'
)
</code>```

Title: websocket-rails Chat Rooms

Body:
You can pass parameters from the client side to the server side when creating a subscription. For example:

# app/channels/chat_channel.rb
class ChatChannel < ApplicationCable::Channel
  def subscribed
    stream_from "chat_#{params[:room]}"
  end
end

An object passed as the first argument to subscriptions.create becomes the params hash in the cable channel. The keyword channel is required:

# app/assets/javascripts/cable/subscriptions/chat.coffee
App.cable.subscriptions.create { channel: "ChatChannel", room: "Best Room" },
  received: (data) ->
    @appendLine(data)

  appendLine: (data) ->
    html = @createLine(data)
    $("[data-chat-room='Best Room']").append(html)

  createLine: (data) ->
    """
    <article class="chat-line">
      <span class="speaker">#{data["sent_by"]}</span>
      <span class="body">#{data["body"]}</span>
    </article>
    """

Somewhere in your app this is called, perhaps

ActionCable.server.broadcast(
  "chat_#{room}",
  sent_by: 'Paul',
  body: 'This is a cool chat app.'
)


问:
How to use IF in SELECT statement as a filter
I have simalary (but not identical) report which share the same tables and filters. Instead of writing invidual stored procedures, I'd like to create one and switch between SELECT datasets with a parameter accompanied with a filter.

I've tried something like:

```<code>IF @UseDataGroup = 1 --from ssrs
    BEGIN
    SELECT
        IF transaction_type IN (10, 27)
        .....
    END
IF @UseDataGroup = 2
    BEGIN
    SELECT
        IF transaction_type IN (11)
        .....
    END

    FROM

    WHERE
</code>```

..with unfortunately returns an error  'multi-part identifier transaction_type could not be bound'
Any help would be aprreciated. Thanks.

答:
You can use the incoming filter from SSRS and the filter on transaction_type in the WHERE clause in your SELECT statement

```<code>SELECT YourFields
FROM YourTable
WHERE (@UseDataGroup = 1 AND transaction_type IN (10, 27))
  OR (@UseDataGroup = 2 AND transaction_type = 11)
  --add additional filters as needed
</code>```

Body:
I have simalary (but not identical) report which share the same tables and filters. Instead of writing invidual stored procedures, I'd like to create one and switch between SELECT datasets with a parameter accompanied with a filter.

I've tried something like:

IF @UseDataGroup = 1 --from ssrs
    BEGIN
    SELECT
        IF transaction_type IN (10, 27)
        .....
    END
IF @UseDataGroup = 2
    BEGIN
    SELECT
        IF transaction_type IN (11)
        .....
    END

    FROM

    WHERE

..with unfortunately returns an error  'multi-part identifier transaction_type could not be bound'
Any help would be aprreciated. Thanks.

Body:
You can use the incoming filter from SSRS and the filter on transaction_type in the WHERE clause in your SELECT statement

SELECT YourFields
FROM YourTable
WHERE (@UseDataGroup = 1 AND transaction_type IN (10, 27))
  OR (@UseDataGroup = 2 AND transaction_type = 11)
  --add additional filters as needed


问:
Copy string text, and paste it in 6 input text boxes, showing the full string on first box
I have a question regarding copy and pasting a string such as "123456", in 6 different input text fields. The input text fields have also have maxlength as 1, I first had to remove this attribute from the fields for it to paste the whole 6 characters in each input field. The solution I have right now works, but I am having a slight problem, because as soon as I paste the whole 6 number digit on the first box, it puts the whole string on the first box for a small amount of time, and then it puts the numbers on the other fields. The question is, how can I do to not see the whole number being pasted on the first box, and showing only one number? Here is a working example:

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
    <title>Heading Example</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

    <input type="text" name="numberInput" value="" tab-index="0" placeholder="#" maxlength="1">
    <input type="text" name="numberInput" value="" tab-index="1" placeholder="#" maxlength="1">
    <input type="text" name="numberInput" value="" tab-index="2" placeholder="#" maxlength="1">
    <input type="text" name="numberInput" value="" tab-index="3" placeholder="#" maxlength="1">
    <input type="text" name="numberInput" value="" tab-index="4" placeholder="#" maxlength="1">
    <input type="text" name="numberInput" value="" tab-index="5" placeholder="#" maxlength="1">

```

Many thanks.

答:
You can use the properties of the paste event to prevent the default action and get the intended paste text, and then do your logic, removing the setTimeout as well since you are not using the native paste event anymore.

Also, there is no need to remove and add the maxlength attribute that I can see- you are only inserting one character anyway, and since we are bypassing the native paste event, the full string never really hits any of the inputs.

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
    <title>Heading Example</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

    <input type="text" name="numberInput" value="" tab-index="0" placeholder="#" maxlength="1">
    <input type="text" name="numberInput" value="" tab-index="1" placeholder="#" maxlength="1">
    <input type="text" name="numberInput" value="" tab-index="2" placeholder="#" maxlength="1">
    <input type="text" name="numberInput" value="" tab-index="3" placeholder="#" maxlength="1">
    <input type="text" name="numberInput" value="" tab-index="4" placeholder="#" maxlength="1">
    <input type="text" name="numberInput" value="" tab-index="5" placeholder="#" maxlength="1">

```

Body:
I have a question regarding copy and pasting a string such as "123456", in 6 different input text fields. The input text fields have also have maxlength as 1, I first had to remove this attribute from the fields for it to paste the whole 6 characters in each input field. The solution I have right now works, but I am having a slight problem, because as soon as I paste the whole 6 number digit on the first box, it puts the whole string on the first box for a small amount of time, and then it puts the numbers on the other fields. The question is, how can I do to not see the whole number being pasted on the first box, and showing only one number? Here is a working example:

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
    <title>Heading Example</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

    <input type="text" name="numberInput" value="" tab-index="0" placeholder="#" maxlength="1">
    <input type="text" name="numberInput" value="" tab-index="1" placeholder="#" maxlength="1">
    <input type="text" name="numberInput" value="" tab-index="2" placeholder="#" maxlength="1">
    <input type="text" name="numberInput" value="" tab-index="3" placeholder="#" maxlength="1">
    <input type="text" name="numberInput" value="" tab-index="4" placeholder="#" maxlength="1">
    <input type="text" name="numberInput" value="" tab-index="5" placeholder="#" maxlength="1">

Many thanks.

Body:
You can use the properties of the paste event to prevent the default action and get the intended paste text, and then do your logic, removing the setTimeout as well since you are not using the native paste event anymore.

Also, there is no need to remove and add the maxlength attribute that I can see- you are only inserting one character anyway, and since we are bypassing the native paste event, the full string never really hits any of the inputs.

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
    <title>Heading Example</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  </head>
  <body>

    <input type="text" name="numberInput" value="" tab-index="0" placeholder="#" maxlength="1">
    <input type="text" name="numberInput" value="" tab-index="1" placeholder="#" maxlength="1">
    <input type="text" name="numberInput" value="" tab-index="2" placeholder="#" maxlength="1">
    <input type="text" name="numberInput" value="" tab-index="3" placeholder="#" maxlength="1">
    <input type="text" name="numberInput" value="" tab-index="4" placeholder="#" maxlength="1">
    <input type="text" name="numberInput" value="" tab-index="5" placeholder="#" maxlength="1">

    <script src="https://code.jquery.com/jquery-2.2.4.min.js" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <script>
      $(document).ready(function(){
        $('input[type="text"]').bind('paste', function(e) {
          e.preventDefault();
          var text = e.originalEvent.clipboardData.getData('text');
          var textArray = text.split('');

          $('input[type="text"]').each(function(index,element){
            $(element).val(textArray[index]);
          });
        });
      });
    </script>
  </body>
</html>


问:
Laravel Session expiration event
Is it possible to fire some event when user session is expired ?

As example (session expiration time 30 mins):

User logged into website;

Made several actions;

Session expired;

No More actions with website.

So User has to be log out from external discourse forum.

Any good ideas how to achieve this ?

答: Why don't you set the expiration time on the forum the same as the main site?</p>

Title: Laravel Session expiration event


问:
Factoring out skeleton processing (C#)
Is there a language construct in C# that allows the abstraction of loop (or other) "outer" processing?

I have a fairly straight forward nested structure (lists of lists of ints say) and the code to "spin" through each of the lowest level ints. The code isn't complicated (nor particularly long) but I have multiple functions thats need to "interact" with the lowest level independently and have been just copying the loop skeleton to do so. Seems like a waste to me.

```<code>foreach (list in outerlists)
    ... a few random lines of structure traversing
    foreach (int in list)
        do something simple to int
</code>```

This is obviously a scaled down example but my real world is similar - I end up copying the outer processing repeatedly to change out relatively few inner lines of work.

My tentative solution is to make a "processing" method that contains the loops and takes an enumeration (or something) parameter to tell it which inner function to call. Then put a switch statement at the "do something" level which calls the correct sub function.

Am I on the right track or is there an easier way? I could get rid of the switch statement with a concept of function pointers (just pass a function pointer into the processing loop and call it at the do something level) but don't know if that is possible in C#?

答:
(elaborating a bit on Oded's answer)

Assuming you always want to iterate the same way and that the only thing different between the copy-pasted foreach's is the innermost nested block then you could encapsulate all the looping into a method:

```<code>public void DoStuffOnInnerElements (Action<int> theStuffToDo)
{
    foreach (var subList in outerLists)
    {
        // a few random lines here...
        foreach (int item in subList)
        {
            theStuffToDo(item);
        }
    }
}
</code>```

The action can be any of the formats that C# accepts for delegates (a delegate is C#'s answer to C/C++ function pointers):

```<code>// Lambdas
DoStuffOnInnerElements((i) => Console.WriteLine(i));
// Methods
DoStuffOnInnerElements(My_Void_xxx_Int_Method);
DoStuffOnInnerElements(new Action<int>(Console.WriteLine));
// anonymous delegates
DoStuffOnInnerElements(delegate(int i) { Console.WriteLine(i); });
// etc.
</code>```

ContentLicense: CC BY-SA 2.5

Title: Factoring out skeleton processing (C#)

Body:
Is there a language construct in C# that allows the abstraction of loop (or other) "outer" processing?

I have a fairly straight forward nested structure (lists of lists of ints say) and the code to "spin" through each of the lowest level ints. The code isn't complicated (nor particularly long) but I have multiple functions thats need to "interact" with the lowest level independently and have been just copying the loop skeleton to do so. Seems like a waste to me.

foreach (list in outerlists)
    ... a few random lines of structure traversing
    foreach (int in list)
        do something simple to int

This is obviously a scaled down example but my real world is similar - I end up copying the outer processing repeatedly to change out relatively few inner lines of work.

My tentative solution is to make a "processing" method that contains the loops and takes an enumeration (or something) parameter to tell it which inner function to call. Then put a switch statement at the "do something" level which calls the correct sub function.

Am I on the right track or is there an easier way? I could get rid of the switch statement with a concept of function pointers (just pass a function pointer into the processing loop and call it at the do something level) but don't know if that is possible in C#?

Body:
(elaborating a bit on Oded's answer)

Assuming you always want to iterate the same way and that the only thing different between the copy-pasted foreach's is the innermost nested block then you could encapsulate all the looping into a method:

public void DoStuffOnInnerElements (Action<int> theStuffToDo)
{
    foreach (var subList in outerLists)
    {
        // a few random lines here...
        foreach (int item in subList)
        {
            theStuffToDo(item);
        }
    }
}

The action can be any of the formats that C# accepts for delegates (a delegate is C#'s answer to C/C++ function pointers):

// Lambdas
DoStuffOnInnerElements((i) => Console.WriteLine(i));
// Methods
DoStuffOnInnerElements(My_Void_xxx_Int_Method);
DoStuffOnInnerElements(new Action<int>(Console.WriteLine));
// anonymous delegates
DoStuffOnInnerElements(delegate(int i) { Console.WriteLine(i); });
// etc.


问:
Cannot filter by more than one field in SAP GatewayClient
This is the url I try to call:

```<code>/sap/opu/odata/sap/ZEITERFASSUNG_SRV/ArbeitszeitenSet?$filter=Pernr eq '00000141' and Datum='20120822'
</code>```

The fields exist, are filterable and written correctly. If I remove the Date part from the URL it is working. Response I am getting:

```<code><?xml version="1.0" encoding="utf-8"?>
<error xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
    <code>005056A509B11EE1B9A8FEC11C21178E</code>
    <message xml:lang="de">An Position 24 wurde ein ungültiger Token festgestellt</message>
    <innererror xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
        <transactionid>7D84538F491C0080E00591BF48EADF30</transactionid>
        <timestamp>20170607112124.9987340</timestamp>
        <Error_Resolution>
            <SAP_Transaction>Run transaction /IWFND/ERROR_LOG on SAP Gateway hub system (Sys
            <SAP_Note>See SAP Note 1797736 for error analysis (https://service.sap.com/sap/s
        </Error_Resolution>
    </innererror>
</error>
</code>```

It seems like I can't chain filters with and & or (both not working).

答:
I was able to solve the problem by casting the value to datetime in my url.

```<code>/sap/opu/odata/sap/ZEITERFASSUNG_SRV/ArbeitszeitenSet?$filter=Pernr eq '00000141' and Datum eq datetime'2012-08-22T15:15:15'&$format=json
</code>```

somehow the date part is not transmitted to the backend but thats okay since it's not needed.

Body:
This is the url I try to call:

/sap/opu/odata/sap/ZEITERFASSUNG_SRV/ArbeitszeitenSet?$filter=Pernr eq '00000141' and Datum='20120822'

The fields exist, are filterable and written correctly. If I remove the Date part from the URL it is working. Response I am getting:

<?xml version="1.0" encoding="utf-8"?>
<error xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
    005056A509B11EE1B9A8FEC11C21178E
    <message xml:lang="de">An Position 24 wurde ein ungültiger Token festgestellt</message>
    <innererror xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
        <transactionid>7D84538F491C0080E00591BF48EADF30</transactionid>
        <timestamp>20170607112124.9987340</timestamp>
        <Error_Resolution>
            <SAP_Transaction>Run transaction /IWFND/ERROR_LOG on SAP Gateway hub system (Sys
            <SAP_Note>See SAP Note 1797736 for error analysis (https://service.sap.com/sap/s
        </Error_Resolution>
    </innererror>
</error>

It seems like I can't chain filters with and & or (both not working).

Body:
I was able to solve the problem by casting the value to datetime in my url.

/sap/opu/odata/sap/ZEITERFASSUNG_SRV/ArbeitszeitenSet?$filter=Pernr eq '00000141' and Datum eq datetime'2012-08-22T15:15:15'&$format=json

somehow the date part is not transmitted to the backend but thats okay since it's not needed.


问:
Setting Color through Javascript based on condition
I am generating a html table through C# code in an MVC Application .

I want to color the value in table cell as red and condition for this is (if column-x value is greater than value of column-y than set color of column-x as red).

column-x and column-y have their on id,s

Below is generated HTML and javascript code which I am using

$('#body table').each(function () {
    $('#' + this.id + ' ' + 'tr').each(function () {
        var v1 = $('#TodayPDue').html();
        var v2 = $('#TodayIntDue').html();

        if (v1 > v2){
            $('#TodayPDue').css('color','red');
        }
     })
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id='CollectionRPT' class='table table-bordered table-hover'>
     <tbody>
         <tr>
            <td>1</td>
            <td>BIHAR</td>
            <td id='TodayPDue'>2220515</td>
            <td id='TodayIntDue'>457565</td>
            <td id='TodayPCollected'>0</td>
            <td id='TodayIntCollected'>0</td>
            <td id='MonthPDue'>10232468</td>
            <td id='MonthIntDue'>2058526</td>
            <td id='MonthPCollected'>5912869</td>
            <td id='MonthIntCollected'>1167760</td>
            <td id='YearPDue'>6432342</td>
            <td id='YearIntDue'>1303773</td>
            <td id='YearPCollected'>2111473</td>
            <td id='YearIntCollected'>413023</td>
         </tr>
     </tbody>
</table></code>```

Any idea why it is showing no effect ?

答:
1) Are you really have element with body id on your page. If you meat all tables on the page use ('body table') or just ('table').

2) I think you need classes instead of ids. Id should be unique in document context

3) I don't think you will get correct results here:

```<code> var v1 = $('#TodayPDue').html();
 var v2 = $('#TodayIntDue').html();
 if (v1 > v2)
</code>```

You trying to compare text not numbers, So 3 is greater then 20 in your case.
   I think you need parseInt or parseFloat

Body:
I am generating a html table through C# code in an MVC Application .

I want to color the value in table cell as red and condition for this is (if column-x value is greater than value of column-y than set color of column-x as red).

column-x and column-y have their on id,s

Below is generated HTML and javascript code which I am using

$('#body table').each(function () {
    $('#' + this.id + ' ' + 'tr').each(function () {
        var v1 = $('#TodayPDue').html();
        var v2 = $('#TodayIntDue').html();

        if (v1 > v2){
            $('#TodayPDue').css('color','red');
        }
     })
});

            1
            BIHAR
            2220515
            457565
            0
            0
            10232468
            2058526
            5912869
            1167760
            6432342
            1303773
            2111473
            413023

Any idea why it is showing no effect ?

Body:
1) Are you really have element with body id on your page. If you meat all tables on the page use ('body table') or just ('table').

2) I think you need classes instead of ids. Id should be unique in document context

3) I don't think you will get correct results here:

 var v1 = $('#TodayPDue').html();
 var v2 = $('#TodayIntDue').html();
 if (v1 > v2)

You trying to compare text not numbers, So 3 is greater then 20 in your case.
   I think you need parseInt or parseFloat


问:
How to "turn off" jQuery Mobile's styling of <select> drop downs?
I need to turn off jQuery Mobile's styling of <select> drop downs. Ultimately I'd like the device itself (iPhone, Android, Blackberry, etc.) to determine how the <select> drop down looks.

Currently my markup is (option quantity reduced for display purposes):

```<code><div data-role="fieldcontain">
    <label for="state">State:</label>
    <select name="state" id="state" data-role="none">
        <option value="MA">Massachusetts</option>
        <option value="MI">Michigan</option>
        <option value="MN" selected="selected">Minnesota</option>
        <option value="MS">Mississippi</option>
    </select>
</div>
</code>```

I tried using data-role="none" on the <select> but nothing changed.

Is there a way to "turn off" jQuery Mobile for just the select drop down?

答:
They're still working on it, works in latest git code but I wouldnt recommend it:
https://github.com/jquery/jquery-mobile/issuesearch?state=closed&q=select#issue/350</p>

Body:
I need to turn off jQuery Mobile's styling of <select> drop downs. Ultimately I'd like the device itself (iPhone, Android, Blackberry, etc.) to determine how the <select> drop down looks.

Currently my markup is (option quantity reduced for display purposes):

    State:
    <select name="state" id="state" data-role="none">
        <option value="MA">Massachusetts</option>
        <option value="MI">Michigan</option>
        <option value="MN" selected="selected">Minnesota</option>
        <option value="MS">Mississippi</option>
    </select>

I tried using data-role="none" on the <select> but nothing changed.

Is there a way to "turn off" jQuery Mobile for just the select drop down?


问:
Openstreetmap (osm), how to create map for my DB? Description inside
How is it possible to cut some area on the osm (display only city/country or smth similar)? And when user will be near to the ground, he will see more and more: streets, then maybe shops etc. Then I will put it in the DB, that I have, and user will get the map in the app from my DB. But question is: where (what program) can help me to cut the area and do everything, that i described; or how I can do it on the osm site?</p>

答:
You can try with the zoom event on your map. On different zoom level, you display/hide your (base)layers.

Have a look on this example : http://tombatossals.github.io/angular-leaflet-directive/examples/0000-viewer.html#/layers/overlays-hide-on-zoomout-example


问:
How to configure empty targetNamespace in the Web Service?
I'm trying to set up empty target namespace when creating the Web Service. Here is the example. My service looks like this:

```<code>package com.example;

import javax.jws.WebMethod;
import javax.jws.WebService;

@WebService
public class SampleService
{
    @WebMethod
    public void sampleMethod()
    {

    }
}
</code>```

Defined like that, it accepts requests that look like this (please note the exam namespace declaration):

```<code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:exam="http://example.com/">
   <soapenv:Header/>
   <soapenv:Body>
      <exam:sampleMethod/>
   </soapenv:Body>
</soapenv:Envelope>
</code>```

I would like to configure the web service to accept the requests that look like this (without the namespace):

```<code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
   <soapenv:Header/>
   <soapenv:Body>
      <sampleMethod/>
   </soapenv:Body>
</soapenv:Envelope>
</code>```

I tried to set up the targetNamespace to the empty string, but that didn't work - it just defaulted to the exam namespace.

@WebService(targetNamespace="")

I'm using Apache CXF (3.1.0) to expose the service:

```<code><bean id="sampleService" class="com.example.SampleService" />
<jaxws:endpoint id="sampleServiceWs" implementor="#sampleService"
    address="/SampleService" publish="true">
</jaxws:endpoint>
</code>```

答:
To answer my question - I didn't find a way to set the empty targetNamespace, but I managed to leave out the request validation on my service, so that it now accepts the request with the namespace also. To do that, I used the @EndpointProperty annotation on top of the service class:

```<code>package com.example;

import javax.jws.WebMethod;
import javax.jws.WebService;
import org.apache.cxf.annotations.EndpointProperty;

@WebService
@EndpointProperty(key = "soap.no.validate.parts", value = "true")
public class SampleService
{
    @WebMethod
    public void sampleMethod()
    {

    }
}
</code>```

Body:
I'm trying to set up empty target namespace when creating the Web Service. Here is the example. My service looks like this:

package com.example;

import javax.jws.WebMethod;
import javax.jws.WebService;

@WebService
public class SampleService
{
    @WebMethod
    public void sampleMethod()
    {

    }
}

Defined like that, it accepts requests that look like this (please note the exam namespace declaration):

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:exam="http://example.com/">
   <soapenv:Header/>
   <soapenv:Body>
      <exam:sampleMethod/>
   </soapenv:Body>
</soapenv:Envelope>

I would like to configure the web service to accept the requests that look like this (without the namespace):

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
   <soapenv:Header/>
   <soapenv:Body>
      <sampleMethod/>
   </soapenv:Body>
</soapenv:Envelope>

I tried to set up the targetNamespace to the empty string, but that didn't work - it just defaulted to the exam namespace.

@WebService(targetNamespace="")

I'm using Apache CXF (3.1.0) to expose the service:

<bean id="sampleService" class="com.example.SampleService" />
<jaxws:endpoint id="sampleServiceWs" implementor="#sampleService"
    address="/SampleService" publish="true">
</jaxws:endpoint>

Body:
To answer my question - I didn't find a way to set the empty targetNamespace, but I managed to leave out the request validation on my service, so that it now accepts the request with the namespace also. To do that, I used the @EndpointProperty annotation on top of the service class:

package com.example;

import javax.jws.WebMethod;
import javax.jws.WebService;
import org.apache.cxf.annotations.EndpointProperty;

@WebService
@EndpointProperty(key = "soap.no.validate.parts", value = "true")
public class SampleService
{
    @WebMethod
    public void sampleMethod()
    {

    }
}


问:
How to order by multiple timestamp fields and return them in chronological order?
I have a table of posts (news) but they can have different date attributes and some of them may be unset (0). I want to order DESC on all fields and then get a result where the chronological order is respected, rather than the order i gave in the query.

```<code>title | pubdate     | startdate  | enddate     | closedate  |
------------------------------------------------------------
exm1  | 1271887200  |          0 |          0  |          0 |
exm2  | 1291071600  |          0 |          0  |          0 |
exm3  |          0  | 1496102400 | 1496361600  |          0 |
exm4  | 1496620800  |          0 |          0  |          0 |
exm5  |          0  | 1501545600 | 1501891200  | 1496966400 |
exm6  |          0  | 1493856000 | 1496361600  |          0 |
</code>```

The relevant fields are "pubdate", "startdate" or "closedate". So what i did was simply putting them into my ORDER BY statement:

```<code>SELECT * FROM news ORDER BY closedate DESC, startdate DESC, pubdate DESC
</code>```

That works of course, but i noticed that this always puts rows with "closedate" to the front of the result, followed by "startdate" results, etc.. and the ordering only happens within those slices and not across all values. They are treated like a different set, stitched together.

The result is therefore: exm5, exm3, exm6, exm4, exm2, exm1

But i wanted the following: exm5, exm4, exm3, exm6, exm2, exm1

Reason:

```<code>- exm5 close is 06.09.2017 (and pub is 0)
- exm4 pub   is 06.05.2017 (and close is 0 and enddate is 0)
- exm3 start is 05.30.2017 (and close is 0 and pub is 0)
- exm6 start is 05.04.2017 (and close is 0 and pub is 0)
</code>```

I could apply this sorting by code but i want to use LIMIT and offsets with this query, maintaining the order for pagination.

I feel i somehow have to merge these values and sort on a single field, but i don't know how to do that or if its even possible with just MYSQL.

Any ideas? Thanks.

答:
Perhaps greatest() does what you want:

```<code>ORDER BY GREATEST(closedate, startdate, pubdate) DESC
</code>```

You seem to be using 0 for missing values.  If so, this is fine.  If you actually have NULLs, then the logic needs to handle them.

EDIT:

If you have a priority, then use:

```<code>ORDER BY (CASE WHEN closeddate > 0 THEN closeddate
               WHEN startdate > 0 THEN startdate
               ELSE pubdate
          END)
</code>```

This works for NULL values.

Body:
I have a table of posts (news) but they can have different date attributes and some of them may be unset (0). I want to order DESC on all fields and then get a result where the chronological order is respected, rather than the order i gave in the query.

title | pubdate     | startdate  | enddate     | closedate  |
------------------------------------------------------------
exm1  | 1271887200  |          0 |          0  |          0 |
exm2  | 1291071600  |          0 |          0  |          0 |
exm3  |          0  | 1496102400 | 1496361600  |          0 |
exm4  | 1496620800  |          0 |          0  |          0 |
exm5  |          0  | 1501545600 | 1501891200  | 1496966400 |
exm6  |          0  | 1493856000 | 1496361600  |          0 |

The relevant fields are "pubdate", "startdate" or "closedate". So what i did was simply putting them into my ORDER BY statement:

SELECT * FROM news ORDER BY closedate DESC, startdate DESC, pubdate DESC

That works of course, but i noticed that this always puts rows with "closedate" to the front of the result, followed by "startdate" results, etc.. and the ordering only happens within those slices and not across all values. They are treated like a different set, stitched together.

The result is therefore: exm5, exm3, exm6, exm4, exm2, exm1

But i wanted the following: exm5, exm4, exm3, exm6, exm2, exm1

Reason:

- exm5 close is 06.09.2017 (and pub is 0)
- exm4 pub   is 06.05.2017 (and close is 0 and enddate is 0)
- exm3 start is 05.30.2017 (and close is 0 and pub is 0)
- exm6 start is 05.04.2017 (and close is 0 and pub is 0)

I could apply this sorting by code but i want to use LIMIT and offsets with this query, maintaining the order for pagination.

I feel i somehow have to merge these values and sort on a single field, but i don't know how to do that or if its even possible with just MYSQL.

Any ideas? Thanks.

Body:
Perhaps greatest() does what you want:

ORDER BY GREATEST(closedate, startdate, pubdate) DESC

You seem to be using 0 for missing values.  If so, this is fine.  If you actually have NULLs, then the logic needs to handle them.

EDIT:

If you have a priority, then use:

ORDER BY (CASE WHEN closeddate > 0 THEN closeddate
               WHEN startdate > 0 THEN startdate
               ELSE pubdate
          END)

This works for NULL values.


问:
Why is Maven downloading from the wrong repository?
I'm a newbie to Maven. I'm trying to setup a local Archiva 1.3.6 server to act as a repository server for a project's internal artifact, as well as mirror to external repos. Things work fine except for snapshots. I'm using Maven version 3.0.5.

Here are the mirror settings in my settings.xml file

  <mirrors>
    <mirror>
        <id>internal</id>
        <mirrorOf>external:*</mirrorOf>
        <name>My Maven Repository</name>
        <url>http://my.repo.server:9000/archiva/repository/internal/</url>
    </mirror>
  </mirrors>
```

<p>During the build, Maven tries to download the snapshot artifact from the wrong repository. I have 2 repositories set in the parent's parent <code>pom.xml</code>: <code>internal</code> and <code>snapshots</code>.</p>

<pre class="lang-xml prettyprint-override"><code><repositories>
    <repository>
        <id>internal</id>
        <url>http://my.repo.server:9000/archiva/repository/internal/</url>
        <releases>
            <enabled>true</enabled>
        </releases>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
    <repository>
        <id>snapshots</id>
        <url>http://my.repo.server:9000/archiva/repository/snapshots/</url>
        <releases>
            <enabled>false</enabled>
        </releases>
        <snapshots>
            <enabled>true</enabled>
        </snapshots>
    </repository>
</repositories>
</code>```

In the project's pom.xml I have the following dependency:

<dependency>
    <groupId>com.mygroup</groupId>
    <artifactId>metadata-framework</artifactId>
    <version>1.0.3.SNAPSHOT</version>
</dependency>
```

<p>During the build Maven tries to do this:</p>

```Downloading:
.../archiva/repository/**snapshots**/com/mygroup/metadata-framework/1.0.3.SNAPSHOT/maven-metadata.xml

Downloaded:
.../archiva/repository/**snapshots**/com/mygroup/metadata-framework/1.0.3.SNAPSHOT/maven-metadata.xml (795 B at 16.9 KB/sec)

Downloading:
.../archiva/repository/**internal**/com/mygroup/metadata-framework/1.0.3.20130908.081541-1/cems-metadata-framework-1.0.3.20130908.081541-1.pom

[WARNING] The POM for com.myground:metadata-framework:jar:1.0.3.20130908.081541-1 is missing, no dependen
cy information available
```

I verified the files in snapshot repo is correct, that it has properly generated maven-metadata.xml and etc. it appears that Maven downloaded the metadata correctly from snapshot repo, determined the right timestamped version, but somehow it decided to download the actual file from internal repo instead of snapshots, which lead to 404 and failed build.

I have no idea how Maven works, please help.

答: I know this post is old by in order for maven to search in a snapshot repository the version should end with "-SNAPSHOT" (rather than ".SNAPSHOT")</p>

Body:
I'm a newbie to Maven. I'm trying to setup a local Archiva 1.3.6 server to act as a repository server for a project's internal artifact, as well as mirror to external repos. Things work fine except for snapshots. I'm using Maven version 3.0.5.

Here are the mirror settings in my settings.xml file

  <mirrors>
    <mirror>
        <id>internal</id>
        <mirrorOf>external:*</mirrorOf>
        <name>My Maven Repository</name>
        <url>http://my.repo.server:9000/archiva/repository/internal/</url>
    </mirror>
  </mirrors>

During the build, Maven tries to download the snapshot artifact from the wrong repository. I have 2 repositories set in the parent's parent pom.xml: internal and snapshots.

<repositories>
    <repository>
        <id>internal</id>
        <url>http://my.repo.server:9000/archiva/repository/internal/</url>
        <releases>
            <enabled>true</enabled>
        </releases>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
    <repository>
        <id>snapshots</id>
        <url>http://my.repo.server:9000/archiva/repository/snapshots/</url>
        <releases>
            <enabled>false</enabled>
        </releases>
        <snapshots>
            <enabled>true</enabled>
        </snapshots>
    </repository>
</repositories>

In the project's pom.xml I have the following dependency:

<dependency>
    <groupId>com.mygroup</groupId>
    <artifactId>metadata-framework</artifactId>
    <version>1.0.3.SNAPSHOT</version>
</dependency>

During the build Maven tries to do this:

Downloading:
.../archiva/repository/**snapshots**/com/mygroup/metadata-framework/1.0.3.SNAPSHOT/maven-metadata.xml

Downloaded:
.../archiva/repository/**snapshots**/com/mygroup/metadata-framework/1.0.3.SNAPSHOT/maven-metadata.xml (795 B at 16.9 KB/sec)

Downloading:
.../archiva/repository/**internal**/com/mygroup/metadata-framework/1.0.3.20130908.081541-1/cems-metadata-framework-1.0.3.20130908.081541-1.pom

[WARNING] The POM for com.myground:metadata-framework:jar:1.0.3.20130908.081541-1 is missing, no dependen
cy information available

I verified the files in snapshot repo is correct, that it has properly generated maven-metadata.xml and etc. it appears that Maven downloaded the metadata correctly from snapshot repo, determined the right timestamped version, but somehow it decided to download the actual file from internal repo instead of snapshots, which lead to 404 and failed build.

I have no idea how Maven works, please help.


问:
Replace words taken from the list in txt file in python
i have txt file with one word in each line (library.txt) like:

```<code>Word1
Word2
</code>```

Second txt file look like this:

```<code>I have got many words.
I know Word1 is very interesting.
ButWord2 is awful because its connected with another word.
I think there is no Word3 at all.
</code>```

i need to search for those words from library.txt in Second txt file and replace them so those will look like this:

```<code>I have got many words.
For example <font=yellow>Word1</font> is very interesting.
But<font=yellow>Word2</font> is awful because its connected with another word.
I think there is no Word3 at all.
</code>```

Ive got such code but it doesnt work:

```<code>rules =[]
with open(library, 'r') as libraryfile:
    for line in libraryfile:
        rules.append(line.rstrip())

with open(second', 'r') as secondfile:
    with open(third', 'w') as thirdfile:
        for line in secondfile:
            if all(rule in line for rule in rules):
                thirdfile.write(line.replace(rule, '<font color=yellow>'+rule+'</font>'))
            else:
                thirdfile.write(line)
</code>```

答: You want any instead of all, as it is enough for one of the words from rules to appear in a line.

Body:
i have txt file with one word in each line (library.txt) like:

Word1
Word2

Second txt file look like this:

I have got many words.
I know Word1 is very interesting.
ButWord2 is awful because its connected with another word.
I think there is no Word3 at all.

i need to search for those words from library.txt in Second txt file and replace them so those will look like this:

I have got many words.
For example Word1 is very interesting.
ButWord2 is awful because its connected with another word.
I think there is no Word3 at all.

Ive got such code but it doesnt work:

rules =[]
with open(library, 'r') as libraryfile:
    for line in libraryfile:
        rules.append(line.rstrip())

with open(second', 'r') as secondfile:
    with open(third', 'w') as thirdfile:
        for line in secondfile:
            if all(rule in line for rule in rules):
                thirdfile.write(line.replace(rule, ''+rule+''))
            else:
                thirdfile.write(line)


问:
Adding items from one list to another list in another form in c#
I have a Form1 which displays a list of students in a ListBox.

I use Form2 to populate this list of students, well I want to.

Form2 is meant to update the studentList_Form1 in Form1 every time a button is clicked in Form2.

what I'm trying to figure out is how to actually do this? Because I have tried this

Form1:

```<code>public List<Student> studentList_Form1;

public List<Student> StudentList_Form1
{
    get
    {
        return studentList_Form1;
    }
}
</code>```

Form2:

```<code>public List<Student> studentList = new List<Student>();

private void update_main_student_list()
{
    using (Form1 newForm = new Form1())
    {
        foreach(Student s in studentList)
        {
            newForm.StudentList_Form1.Add(s);
        }
    }
    //As well as the code to populate studentList
}
</code>```

But I keep getting an error saying I need to check if s if null before I use it.

Student is a class which is made up of a string name, string address, int id

答: Create an event in Form2 and subscribe this event in Form1. update the list in the event handler of Form1.</p>

Body:
I have a Form1 which displays a list of students in a ListBox.

I use Form2 to populate this list of students, well I want to.

Form2 is meant to update the studentList_Form1 in Form1 every time a button is clicked in Form2.

what I'm trying to figure out is how to actually do this? Because I have tried this

Form1:

public List<Student> studentList_Form1;

public List<Student> StudentList_Form1
{
    get
    {
        return studentList_Form1;
    }
}

Form2:

public List<Student> studentList = new List<Student>();

private void update_main_student_list()
{
    using (Form1 newForm = new Form1())
    {
        foreach(Student s in studentList)
        {
            newForm.StudentList_Form1.Add(s);
        }
    }
    //As well as the code to populate studentList
}

But I keep getting an error saying I need to check if s if null before I use it.

Student is a class which is made up of a string name, string address, int id


问:
THREE.Color: Unknown color #002dff (warning/error)
I need to update the color after receiving the value from dat.GUI .
But, this

```<code>var colored = new THREE.Color(value.replace("#","0x"));
</code>```

is throwing this warning "THREE.Color: Unknown color 0x002dff" and the 'colored' isn't updating.

value = #002dff (at that time, it keeps on changing, user input)

Edit: I know I can use this as "THREE.Color( #002dff )", but the color is changing at run time according to the user input from controls I've created using dat.GUI, so I won't be knowing the actual value that can be added to the code.

PS: It was replace() which was causing the problem. It's solved.

答:
You have to give a hexadecimal number, not a string to the Color constructor. Try to call the parseInt function:

```<code>var colorValue = parseInt ( value.replace("#","0x"), 16 );
var colored = new THREE.Color( colorValue );
</code>```

Body:
I need to update the color after receiving the value from dat.GUI .
But, this

var colored = new THREE.Color(value.replace("#","0x"));

is throwing this warning "THREE.Color: Unknown color 0x002dff" and the 'colored' isn't updating.

value = #002dff (at that time, it keeps on changing, user input)

Edit: I know I can use this as "THREE.Color( #002dff )", but the color is changing at run time according to the user input from controls I've created using dat.GUI, so I won't be knowing the actual value that can be added to the code.

PS: It was replace() which was causing the problem. It's solved.

Body:
You have to give a hexadecimal number, not a string to the Color constructor. Try to call the parseInt function:

var colorValue = parseInt ( value.replace("#","0x"), 16 );
var colored = new THREE.Color( colorValue );


问:
What's the best way to represent a tree with XML?
I'm implementing some classes to handle the common data structures (Tree, BinaryTree, Search Binary Tree, BTree, AVL, etc). I'd like a way to store tree information in a data source and parse it to one of those classes. The simplest way is to use XML (portability is very important). The thing is that the XML documents that i make are not easy to read. They're not enough "intuitive". For example, i was doing something like this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<tree>
    <root>100</root>
    <node>
        <tree>
            <root>50</root>
        </tree>
    </node>
    <node>
        <tree>
            <root>200</root>
        </tree>
    </node>
</tree>
</code>```

There, the tree would be something like this:

```<code>                    100
              50                200
</code>```

What do you say? Do you have any other recommendation?

答:
I don't see in your description any important structural difference between the root, leaves of the tree, and other nodes. So they could all have the same content model, as in this example:

```<code><tree>
    <value>100</value>
    <tree>
        <value>50</value>
    </tree>
    <tree>
        <value>200</value>
    </tree>
</tree>
</code>```

This structure is a bit less verbose, and the XML document tree is matching the tree you are trying to represent. If your values can be expressed as strings, you could even write it like that:

```<code><tree>
    100
    <tree>50</tree>
    <tree>200</tree>
</tree>
</code>```

Body:
I'm implementing some classes to handle the common data structures (Tree, BinaryTree, Search Binary Tree, BTree, AVL, etc). I'd like a way to store tree information in a data source and parse it to one of those classes. The simplest way is to use XML (portability is very important). The thing is that the XML documents that i make are not easy to read. They're not enough "intuitive". For example, i was doing something like this:

<?xml version="1.0" encoding="UTF-8"?>
<tree>
    <root>100</root>
    <node>
        <tree>
            <root>50</root>
        </tree>
    </node>
    <node>
        <tree>
            <root>200</root>
        </tree>
    </node>
</tree>

There, the tree would be something like this:

                    100
              50                200

What do you say? Do you have any other recommendation?

Body:
I don't see in your description any important structural difference between the root, leaves of the tree, and other nodes. So they could all have the same content model, as in this example:

<tree>
    <value>100</value>
    <tree>
        <value>50</value>
    </tree>
    <tree>
        <value>200</value>
    </tree>
</tree>

This structure is a bit less verbose, and the XML document tree is matching the tree you are trying to represent. If your values can be expressed as strings, you could even write it like that:

<tree>
    100
    <tree>50</tree>
    <tree>200</tree>
</tree>


问:
How to Map a Complex native Query Result Set to a Pojo Class in Spring Data JPA
My Repository

```<code> public interface ProductRepository extends JpaRepository<Product,Integer> {

           @Query(value = "select mp.*,u.name,p.name, p.ext_id from merchant_product mp join campaign c on c.product_id = mp.id and c.status in (4, 8)join product p on p.id = mp.product_id join user u on u.id = mp.user_id where mp.status = 4 and mp.availability = 'Y';", nativeQuery = true)

            List<Object> getAllProduct();

    }
</code>```

This is my Query in Spring Boot  i am using Spring data JPA . I need to map this to a Pojo class . So that i can use it for further processing .

can anyone help me with this.

My pojo

```<code>@Data
@AllArgsConstructor
public class Product {
    @Id
    //data of merchant product table
    //data of user table
    private int id;
    private String name;
    private String ext_id;

}
</code>```

答:
```<code>@Query(nativeQuery = true, name = "test", value = "select mp.* ...")
@SqlResultSetMapping(name="test", classes = {
        @ConstructorResult(targetClass = Product.class,
                columns = {@ColumnResult(name="name"), @ColumnResult(name="id")}, @ColumnResult(name="ext_id")})
})
</code>```

Add the SqlResultSetMapping to initialize mappings which columns from the query corresponding to the Pojo fields

Body:
My Repository

 public interface ProductRepository extends JpaRepository<Product,Integer> {

           @Query(value = "select mp.*,u.name,p.name, p.ext_id from merchant_product mp join campaign c on c.product_id = mp.id and c.status in (4, 8)join product p on p.id = mp.product_id join user u on u.id = mp.user_id where mp.status = 4 and mp.availability = 'Y';", nativeQuery = true)

            List<Object> getAllProduct();

    }

This is my Query in Spring Boot  i am using Spring data JPA . I need to map this to a Pojo class . So that i can use it for further processing .

can anyone help me with this.

My pojo

@Data
@AllArgsConstructor
public class Product {
    @Id
    //data of merchant product table
    //data of user table
    private int id;
    private String name;
    private String ext_id;

}

Body:
@Query(nativeQuery = true, name = "test", value = "select mp.* ...")
@SqlResultSetMapping(name="test", classes = {
        @ConstructorResult(targetClass = Product.class,
                columns = {@ColumnResult(name="name"), @ColumnResult(name="id")}, @ColumnResult(name="ext_id")})
})

Add the SqlResultSetMapping to initialize mappings which columns from the query corresponding to the Pojo fields


问:
Bottom Navigation View not responsive
I need that BottomNavigationView to be responsive. When I use a Nexus 4 it has the exact measurement, but with Nexus 6 it does not. Any idea?</p>

```<code><android.support.design.widget.BottomNavigationView
    android:id="@+id/navigation"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="bottom"
    app:itemIconTint="@drawable/selector"
    app:itemTextColor="@color/colorPrimary"
    android:background="?android:attr/windowBackground"
    app:menu="@menu/navigation"/>
</code>```

答:
Use BottomNavigationView height as android:layout_height="wrap_content" or
android:layout_height="56dp".

See documentation about height.

Title: Bottom Navigation View not responsive

Body:
I need that BottomNavigationView to be responsive. When I use a Nexus 4 it has the exact measurement, but with Nexus 6 it does not. Any idea?

<android.support.design.widget.BottomNavigationView
    android:id="@+id/navigation"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="bottom"
    app:itemIconTint="@drawable/selector"
    app:itemTextColor="@color/colorPrimary"
    android:background="?android:attr/windowBackground"
    app:menu="@menu/navigation"/>


问:
Currency symbol from ¥ to 円
There is a requirement to change the currency symbol for yen ¥ to  円
But Using Culture info if I use ja-JP as language code its resolves to ¥ only.

I have seen in some sites (Japanese) the hepburn symbol has been implemented.
Any idea how achieve the same.
¥500   to 500円

Position can changed through NumberFormat.CurrencyPositivePattern  but not sure about the symbol.

CultureInfo cs = new CultureInfo("ja-JP");
 cs.NumberFormat.CurrencyPositivePattern = 1;

答:
This is a related question: How to use cultureinfo to format depricated currencies

The answer is the same:

You can create a custom CultureInfo (by cloning one and modifying) which uses a different currency symbol/format (ie. set its NumberFormat to a different instance of NumberFormatInfo).

Then pass this CultureInfo to formatting functions as needed.

As the comment to the question notes, .NET (and Windows in general) doesn't provide historic data (similarly for time zones but there's a library for that). In the cases you need you'll need to hold enough data yourself.
Remember ISO-4217 currency codes are not reused under such a change, so holding that against amounts allows you to format correctly. Additionally just because a country formats their currency amounts one way doesn't mean everyone does. Eg. 25 French Francs was be "FF25.00" in the UK but "25FF00" or "FF25,00" in other locales. (EDIT: I note you covered this last paragraph in the question.)

Title: Currency symbol from ¥ to 円


问:
Random (bullet) images for List Items in a UL?
I have a ul li sidebar generated from wordpress posts. The client has used different images for the bullet for each LI. Rather then adding a separate bullet manually, is there a way to do it that it chooses from a set of say 10 options?

was thinking Jquery function? Anyone ever done this?

THanks

答:
Perhaps something like the following:

```<code><style type="text/css">
/* Add the styles here, incrementing the number of each one as you go (then change
   the 3 in the jQuery addClass method so it corresponds with the number of options
   available */
li.bullet-0 { list-style-type: circle; }
li.bullet-1 { list-style-type: disc; }
li.bullet-2 { list-style-type: square; }
</style>
<Script type="text/javascript">
$(document).ready(){
  $('ul > li').each(function(i,e){
    $(this).addClass('bullet-'+(i%3)); // change 3 to number of styles that are above.
  });
});
</script>
</code>```

jsFiddle link to show it being applied: http://www.jsfiddle.net/bradchristie/yxZ4m/

Body:
Perhaps something like the following:

<style type="text/css">
/* Add the styles here, incrementing the number of each one as you go (then change
   the 3 in the jQuery addClass method so it corresponds with the number of options
   available */
li.bullet-0 { list-style-type: circle; }
li.bullet-1 { list-style-type: disc; }
li.bullet-2 { list-style-type: square; }
</style>
<Script type="text/javascript">
$(document).ready(){
  $('ul > li').each(function(i,e){
    $(this).addClass('bullet-'+(i%3)); // change 3 to number of styles that are above.
  });
});
</script>

jsFiddle link to show it being applied: http://www.jsfiddle.net/bradchristie/yxZ4m/


问:
knitr::kable is there a way to reduce the font size?
I am using this code chunk

```<code>```{r, echo = FALSE}
  knitr::kable(df)
```
</code>```

However I would like to reduce the size of all font inside this table so that the output looks nicer. Is there a way to do that with kable or is there another package which supports it?

答: I use \tiny before the function and \normalsize after it, which works for .pdf using the formats latex and markdown.

Body:
I am using this code chunk

```{r, echo = FALSE}
  knitr::kable(df)
```

However I would like to reduce the size of all font inside this table so that the output looks nicer. Is there a way to do that with kable or is there another package which supports it?


问:
Check that the file is not binary in pre receive hook
In my git pre-recieve hook on server side I get a list of files in commit by using this command:

```<code>my @new_file_list =  `git diff --name-only $old..$new`;;
</code>```

I get a size of every file, by looping:

```<code>foreach $file (@new_file_list)
{
  $size = `git cat-file -s $new:$file`;
</code>```

By using what command can I get a boolean variable, that will define, if the file in the commit is binary?
So I have a filename in the input, and $old $new revisions, what command can define, if the file is binary?

Thanks in advance.

答:
It depends what you exactly want to achieve and by what cost. If you want to prevent accidentally commits of files being a result of compilation, just add a .gitignore file excluding them from being committed (btw, this is always a good idea, exclude also backup copies and editor temporary files) and in a hook check if extension of committed file is in allowed list.

The aforementioned     -T/-B check in Perl is nice, however, it's good to read proposed documentation. It's less efficient than checking the extension, but it gives the answer using the real content of the file.

If the -B/-T heuristic, as described in documentation, does not suit your needs, use file. In Perl you have few packages already available:

```<code>File::Type
File::LibMagic
File::MMagic
</code>```

You will receive the MIME type of the file and you need to write some logic to interpret the result.

Unless there are no specific requirements which we are not aware of, I personally would stuck to .gitignore and checking extensions. Optionally, you can consider some kind of stick (preferably virtual, as corporal punishment is generally frowned upon) for developers committing forbidden files into repository.

Body:
In my git pre-recieve hook on server side I get a list of files in commit by using this command:

my @new_file_list =  `git diff --name-only $old..$new`;;

I get a size of every file, by looping:

foreach $file (@new_file_list)
{
  $size = `git cat-file -s $new:$file`;

By using what command can I get a boolean variable, that will define, if the file in the commit is binary?
So I have a filename in the input, and $old $new revisions, what command can define, if the file is binary?

Thanks in advance.

Body:
It depends what you exactly want to achieve and by what cost. If you want to prevent accidentally commits of files being a result of compilation, just add a .gitignore file excluding them from being committed (btw, this is always a good idea, exclude also backup copies and editor temporary files) and in a hook check if extension of committed file is in allowed list.

The aforementioned     -T/-B check in Perl is nice, however, it's good to read proposed documentation. It's less efficient than checking the extension, but it gives the answer using the real content of the file.

If the -B/-T heuristic, as described in documentation, does not suit your needs, use file. In Perl you have few packages already available:

File::Type
File::LibMagic
File::MMagic

You will receive the MIME type of the file and you need to write some logic to interpret the result.

Unless there are no specific requirements which we are not aware of, I personally would stuck to .gitignore and checking extensions. Optionally, you can consider some kind of stick (preferably virtual, as corporal punishment is generally frowned upon) for developers committing forbidden files into repository.


问:
Read Named Range Names into VBA array
I'm trying to figure out how I can get the names of ranges in a given worksheet into an array. I've got as far as the listnames function but that seems to list them all in one go. Any ideas?</p>

答:
Something like:

```<code>Sub listum()
    Dim ary(1 To 3) As String
    With ActiveWorkbook
        If .Names.Count > 0 Then
            For i = 1 To .Names.Count
                MsgBox (i & "  " & .Names(i).Name & "  " & Range(.Names(i)).Address)
                ary(i) = .Names(i).Name
            Next
        End If
    End With
End Sub
</code>```

will display them and put them into an array.

Size the array to suit your needs.
Insure that there are no non-Range Names in the workbook.

ContentLicense: CC BY-SA 4.0

Title: Read Named Range Names into VBA array

Body:
Something like:

Sub listum()
    Dim ary(1 To 3) As String
    With ActiveWorkbook
        If .Names.Count > 0 Then
            For i = 1 To .Names.Count
                MsgBox (i & "  " & .Names(i).Name & "  " & Range(.Names(i)).Address)
                ary(i) = .Names(i).Name
            Next
        End If
    End With
End Sub

will display them and put them into an array.

Size the array to suit your needs.
Insure that there are no non-Range Names in the workbook.


问:
TYPO3 Extbase - Check if property in model x is set before adding it to container of model y
I have two models file and filecontainer.

Let's assume I have a checkbox in file called Allow to add.

And I should only be able to add the file to the container of filecontainer, if the property Allow to add is set in that file and if possible show an alert if someone tries to add it even though Allow to add is not set.

Filecontainer

Is this possible?

PS: I just ask this question for learning purposes to see what is possible and what not.

答: I assume you use the TCA type select. You can specify a foreign_table_where clause there to filter the records shown from the file table.


问:
It is possible to paste a whole Class on JShell?
I would like to know if using the new command jshell, it is possible to test a whole Java class.

Many thanks in advance.

Juan antonio

答:
Use /open command to let JShell read the Java class as a snippet.

/open C:\Test.java should add contents of Test.java as a snippet.

A question on similar lines is answered here


问:
How to move angular code from my local to github?
When i try to commit it displays the following,

On branch gh-pages
Untracked files:
        node_modules/max-buffer-exceeded-error/

nothing added to commit but untracked files present

答: You should never commit node_modules to your repo. Create, if you not already have, a .gitignore file in the root of your project, and add node_modules/


问:
Country name with zend locale
When I save countries into my database I use the international abbreviation.

How do I convert this abbreviation with zend_locale to the full country name?

答:
Here is the method. It tries to use the browser's locale and defaults to US English if that fails.</p>

```<code>try {
    $locale = new Zend_Locale(Zend_Locale::BROWSER);
    $countries = $locale->getTranslationList('Territory', Zend_Locale::BROWSER, 2);
} catch (exception $e) {
    $locale = new Zend_Locale('en_US');
    $countries = $locale->getTranslationList('Territory', 'en_US', 2);
}

asort($countries, SORT_LOCALE_STRING);

// Unset invalid countries
// SU = USSR
// ZZ = Unknown or Invalid Region
// VD = North Vietnam
// DD = East Germany
unset($countries['SU'], $countries['ZZ'], $countries['VD'], $countries['DD']);
</code>```

Title: Country name with zend locale

Body:
Here is the method. It tries to use the browser's locale and defaults to US English if that fails.

try {
    $locale = new Zend_Locale(Zend_Locale::BROWSER);
    $countries = $locale->getTranslationList('Territory', Zend_Locale::BROWSER, 2);
} catch (exception $e) {
    $locale = new Zend_Locale('en_US');
    $countries = $locale->getTranslationList('Territory', 'en_US', 2);
}

asort($countries, SORT_LOCALE_STRING);

// Unset invalid countries
// SU = USSR
// ZZ = Unknown or Invalid Region
// VD = North Vietnam
// DD = East Germany
unset($countries['SU'], $countries['ZZ'], $countries['VD'], $countries['DD']);


问:
input field edit not updating ng-model for date picker?
I have created a date picker in Angular

```<code>     <div class="datepicker-wrapper">
        <label for="license_expiry_date">Start Date (YYYY-MM-DD)</label>
        <input type="text" class="form-control" [ngModel]="fromDate | date: 'yyyy-MM-dd'" placeholder="Enter start date" (focus)="onPurchaseDateFocus('from')" name="start_date">
        <div [hidden]="!isFromDatepickerVisible" class="datepicker-container">
            <datepicker [(ngModel)]="fromDate" name="fromdatepicker" (selectionDone)="onDateSelectionDone('from')">
            </datepicker>
        </div>
    </div>
</code>```

I can select a date by using date picker which will update the ng-model, the input tag above the date picker is editable. but when I edit the date from the input field instead of date picker instead of selecting by date picker, ng-model is not getting updated.

Why is the value not updated when I edit the input field?

答:
Not sure what's going wrong but my first guess is the one-way data binding on the form control.

[ngModel]="fromDate | date: 'yyyy-MM-dd'"

try to change it to

[(ngModel)]="fromDate | date: 'yyyy-MM-dd'"

More on two-way data binding

https://angular.io/docs/ts/latest/guide/template-syntax.html#!#two-way

Body:
I have created a date picker in Angular

        Start Date (YYYY-MM-DD)
        <input type="text" class="form-control" [ngModel]="fromDate | date: 'yyyy-MM-dd'" placeholder="Enter start date" (focus)="onPurchaseDateFocus('from')" name="start_date">

            <datepicker [(ngModel)]="fromDate" name="fromdatepicker" (selectionDone)="onDateSelectionDone('from')">
            </datepicker>

I can select a date by using date picker which will update the ng-model, the input tag above the date picker is editable. but when I edit the date from the input field instead of date picker instead of selecting by date picker, ng-model is not getting updated.

Why is the value not updated when I edit the input field?


问:
How to Retrieve a Listing of Employee's Superiors in SQL
Essentially, I have a table that lists an employee's number and the employeeNumber of who they report to.

```<code> EmpNum | Name         | ReportsTo
 ---------------------------------
 1234   | John Smith   | 4523
 3245   | Annie Apples | 1234
 1532   | Bob Rogers   | 3245
 6574   | Dong Wong    | 1532
</code>```

Etc. Etc. So Dong Wong's hierarchy would be: He reports to -> 1532 which reports to -> 3245 which reports to -> 1234.

(I'm new to SQL, so clean and understandable solutions would be appreciated)

答:
You didn't specify your DBMS so this is standard ANSI SQL

```<code>with recursive report_tree as (
  select empnum, name, reportsto
  from employees
  where empnum = 6574
  union all
  select c.empnum, c.name, c.reportsto
  from employees c
    join report_tree p on p.reportsto = c.empnum
)
select *
from report_tree;
</code>```

If you want a "graphical" display, you can do something like this (still standard ANSI SQL):

```<code>with recursive report_tree as (
  select empnum, name, reportsto, name as report_path, 1 as level
  from employee
  where empnum = 6574
  union all
  select c.empnum, c.name, c.reportsto, p.report_path || ' -> ' || c.name, p.level + 1
  from employee c
    join report_tree p on p.reportsto = c.empnum
)
select *
from report_tree
order by level desc
fetch first 1 row only;
</code>```

Body:
Essentially, I have a table that lists an employee's number and the employeeNumber of who they report to.

 EmpNum | Name         | ReportsTo
 ---------------------------------
 1234   | John Smith   | 4523
 3245   | Annie Apples | 1234
 1532   | Bob Rogers   | 3245
 6574   | Dong Wong    | 1532

Etc. Etc. So Dong Wong's hierarchy would be: He reports to -> 1532 which reports to -> 3245 which reports to -> 1234.

(I'm new to SQL, so clean and understandable solutions would be appreciated)

Body:
You didn't specify your DBMS so this is standard ANSI SQL

with recursive report_tree as (
  select empnum, name, reportsto
  from employees
  where empnum = 6574
  union all
  select c.empnum, c.name, c.reportsto
  from employees c
    join report_tree p on p.reportsto = c.empnum
)
select *
from report_tree;

If you want a "graphical" display, you can do something like this (still standard ANSI SQL):

with recursive report_tree as (
  select empnum, name, reportsto, name as report_path, 1 as level
  from employee
  where empnum = 6574
  union all
  select c.empnum, c.name, c.reportsto, p.report_path || ' -> ' || c.name, p.level + 1
  from employee c
    join report_tree p on p.reportsto = c.empnum
)
select *
from report_tree
order by level desc
fetch first 1 row only;


问:
Visual Studio Code on Linux Xwindow forwarding
My configuration is as follows:

OS:

```<code>DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=14.04
DISTRIB_CODENAME=trusty
DISTRIB_DESCRIPTION="Ubuntu 14.04.4 LTS"
NAME="Ubuntu"
VERSION="14.04.4 LTS, Trusty Tahr"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 14.04.4 LTS"
VERSION_ID="14.04"
HOME_URL="http://www.ubuntu.com/"
SUPPORT_URL="http://help.ubuntu.com/"
BUG_REPORT_URL="http://bugs.launchpad.net/ubuntu/"
</code>```

Visual studio code
1.5.3

Xming 6.9.0.31

I had to jump quite a lot of hoops to get visual studio code installed. At the end, I managed to do that.
When I run

code or code .

It returns to the command line immediately with no error.

Then I ran

```<code>code --verbose
</code>```

I get the following messages.

```<code>OpenGL Warning:
XComposite not found or old version (0.0), no VisibilityTracking
{ [Error: ENOENT: no such file or directory, open '/home/vagrant/.config/Code/storage.json']
  errno: -2,
  code: 'ENOENT',
  syscall: 'open',
  path: '/home/vagrant/.config/Code/storage.json' }
(5:08:07 AM) ### VSCode main.js ###
(5:08:07 AM) /usr/share/code/resources/app { _: [],
  paths: [],
  performance: false,
  verbose: true,
  debugPluginHost: undefined,
  debugBrkPluginHost: undefined,
  logExtensionHostCommunication: false,
  'new-window': false,
  'reuse-window': false,
  goto: false,
  diff: false,
  extensionHomePath: undefined,
  extensionDevelopmentPath: undefined,
  extensionTestsPath: undefined,
  'disable-extensions': false,
  locale: undefined,
  wait: false }
</code>```

Also, installing node.js didnt help. Xwindow forwaring works fine for other programs, such as ImageMagick, QtCreator. etc.

答:
XMing works for me! All defaults nothing changed except enable X11 forwarding in PuTTy.

Note however to get recent versions of XMing you have to donate on the author's website which will email you credentials to access the 7.x installs.

Body:
My configuration is as follows:

OS:

DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=14.04
DISTRIB_CODENAME=trusty
DISTRIB_DESCRIPTION="Ubuntu 14.04.4 LTS"
NAME="Ubuntu"
VERSION="14.04.4 LTS, Trusty Tahr"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 14.04.4 LTS"
VERSION_ID="14.04"
HOME_URL="http://www.ubuntu.com/"
SUPPORT_URL="http://help.ubuntu.com/"
BUG_REPORT_URL="http://bugs.launchpad.net/ubuntu/"

Visual studio code
1.5.3

Xming 6.9.0.31

I had to jump quite a lot of hoops to get visual studio code installed. At the end, I managed to do that.
When I run

code or code .

It returns to the command line immediately with no error.

Then I ran

code --verbose

I get the following messages.

OpenGL Warning:
XComposite not found or old version (0.0), no VisibilityTracking
{ [Error: ENOENT: no such file or directory, open '/home/vagrant/.config/Code/storage.json']
  errno: -2,
  code: 'ENOENT',
  syscall: 'open',
  path: '/home/vagrant/.config/Code/storage.json' }
(5:08:07 AM) ### VSCode main.js ###
(5:08:07 AM) /usr/share/code/resources/app { _: [],
  paths: [],
  performance: false,
  verbose: true,
  debugPluginHost: undefined,
  debugBrkPluginHost: undefined,
  logExtensionHostCommunication: false,
  'new-window': false,
  'reuse-window': false,
  goto: false,
  diff: false,
  extensionHomePath: undefined,
  extensionDevelopmentPath: undefined,
  extensionTestsPath: undefined,
  'disable-extensions': false,
  locale: undefined,
  wait: false }

Also, installing node.js didnt help. Xwindow forwaring works fine for other programs, such as ImageMagick, QtCreator. etc.


问:
Cannot allow crossOrigin in spring security
i have a spring-rest application with oauth2 authentication. Everything works fine and i can receive a token and use it to authenticate and all that stuff. Now i am developing a frontend for the application with Angular2.

The main Problem here is: How can i allow CORS in my Oauth2 security configuration?
I have managed to allow it in my Controller classes with the @CrossOrigin annotation, but how does it work in the security configuration?

i have tried this:

```<code>@Configuration
@EnableWebSecurity
public class OAuth2SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http
        .csrf().disable()
        .anonymous().disable()
        .authorizeRequests()
        .antMatchers(HttpMethod.OPTIONS, "/oauth/token").permitAll()
        .and()
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("http://localhost:3000"));
        configuration.setAllowedMethods(Arrays.asList("GET","POST"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}
</code>```

But i still got the error:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 401.

答:
According to the Spring doc the CorsConfigurationSource is not used as a bean but in a CorsFilter, see https://docs.spring.io/spring/docs/current/spring-framework-reference/html/cors.html#_filter_based_cors_support

```<code>public class MyCorsFilter extends CorsFilter {

    public MyCorsFilter() {
        super(configurationSource());
    }

    private static UrlBasedCorsConfigurationSource configurationSource() {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("http://domain1.com");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return source;
    }
}
</code>```

Another way would be to provide a cors mapping in the WebMvcConfigurerAdapter, see https://docs.spring.io/spring/docs/current/spring-framework-reference/html/cors.html#_javaconfig

```<code>@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
            .allowedOrigins("http://domain2.com")
            .allowedMethods("PUT", "DELETE")
            .allowedHeaders("header1", "header2", "header3")
            .exposedHeaders("header1", "header2")
            .allowCredentials(false).maxAge(3600);
    }
}
</code>```

Body:
i have a spring-rest application with oauth2 authentication. Everything works fine and i can receive a token and use it to authenticate and all that stuff. Now i am developing a frontend for the application with Angular2.

The main Problem here is: How can i allow CORS in my Oauth2 security configuration?
I have managed to allow it in my Controller classes with the @CrossOrigin annotation, but how does it work in the security configuration?

i have tried this:

@Configuration
@EnableWebSecurity
public class OAuth2SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http
        .csrf().disable()
        .anonymous().disable()
        .authorizeRequests()
        .antMatchers(HttpMethod.OPTIONS, "/oauth/token").permitAll()
        .and()
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("http://localhost:3000"));
        configuration.setAllowedMethods(Arrays.asList("GET","POST"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}

But i still got the error:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 401.

Body:
According to the Spring doc the CorsConfigurationSource is not used as a bean but in a CorsFilter, see https://docs.spring.io/spring/docs/current/spring-framework-reference/html/cors.html#_filter_based_cors_support

public class MyCorsFilter extends CorsFilter {

    public MyCorsFilter() {
        super(configurationSource());
    }

    private static UrlBasedCorsConfigurationSource configurationSource() {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("http://domain1.com");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return source;
    }
}

Another way would be to provide a cors mapping in the WebMvcConfigurerAdapter, see https://docs.spring.io/spring/docs/current/spring-framework-reference/html/cors.html#_javaconfig

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
            .allowedOrigins("http://domain2.com")
            .allowedMethods("PUT", "DELETE")
            .allowedHeaders("header1", "header2", "header3")
            .exposedHeaders("header1", "header2")
            .allowCredentials(false).maxAge(3600);
    }
}


问:
Cut a longer word/string in smaller chunks for fitting a field
I want to fill a field with a string of many words. When I have huge words I need a to split the word. If my word is longer than 10 letters I need a space at position 5 of this word.

How do I get the new "myString" with shorter words?

```<code>    static void Main(string[] args)
    {
        var myString = "This is my string with some loooooooooooooong words. Please devide meeeeeeeeeeeeeeeeeeeeeeeee";
        var myStringSplit = myString.Split();
        var query = myStringSplit.Where(x => x.Length > 10).ToList();
        foreach (var item in query)
        {
            item.Insert(5, " ");
        }
    }
</code>```

Edit: My expected result: myString = "This is my strin g with some loooo ooooo ooooo ng words. Pleas e devid e meeee eeeee eeeee eeeee eeeee e";

答:
```<code>static void Main(string[] args)
{
    var myString = "This is my string with some loooooooooooooong words. Please devide meeeeeeeeeeeeeeeeeeeeeeeee";
    var newString = string.Empty;
    var myStringSplit = myString.Split();
    var query = myStringSplit.Where(x => x.Length > 10).ToList();
    foreach (var item in myStringSplit)
    {
        if(item.Length > 10)
        {
            var itemToSplit = item;
            itemToSplit.Insert(5, " ");
            newString += itemToSplit;
        }
        else
        {
           newString += item;
        }
    }
}
</code>```

It should be something like this. The reason your attempt is not working is because you are not allowed to edit the item in the foreach loop. More info on the foreach loop

Body:
I want to fill a field with a string of many words. When I have huge words I need a to split the word. If my word is longer than 10 letters I need a space at position 5 of this word.

How do I get the new "myString" with shorter words?

    static void Main(string[] args)
    {
        var myString = "This is my string with some loooooooooooooong words. Please devide meeeeeeeeeeeeeeeeeeeeeeeee";
        var myStringSplit = myString.Split();
        var query = myStringSplit.Where(x => x.Length > 10).ToList();
        foreach (var item in query)
        {
            item.Insert(5, " ");
        }
    }

Edit: My expected result: myString = "This is my strin g with some loooo ooooo ooooo ng words. Pleas e devid e meeee eeeee eeeee eeeee eeeee e";

Body:
static void Main(string[] args)
{
    var myString = "This is my string with some loooooooooooooong words. Please devide meeeeeeeeeeeeeeeeeeeeeeeee";
    var newString = string.Empty;
    var myStringSplit = myString.Split();
    var query = myStringSplit.Where(x => x.Length > 10).ToList();
    foreach (var item in myStringSplit)
    {
        if(item.Length > 10)
        {
            var itemToSplit = item;
            itemToSplit.Insert(5, " ");
            newString += itemToSplit;
        }
        else
        {
           newString += item;
        }
    }
}

It should be something like this. The reason your attempt is not working is because you are not allowed to edit the item in the foreach loop. More info on the foreach loop


问:
Using react-native-zip-archive, getting error, "Cannot read property 'unzip' of undefined"
I am using react-native-zip-archive for unzipping a zip file. While running on ios emulator, the project build fails stating "Cannot read property 'unzip' of undefined". I have performed all the required steps to add the library correctly.</p>

答:
According to the package's entry on NPM you need to do it like this: import { zip, unzip, unzipAssets, subscribe } from 'react-native-zip-archive'.

The latter three are optional; just make sure you use the braces.


问:
Adding ng-model directive to dynamically created input tag using AngularJs
I am trying that on a button click, a div and and input tag are created and the input tag contain ng-model and the div has binding with that input.
Kindly suggest some solution.</p>

答:
You should use $compile service to link scope and your template together:

angular.module('myApp', [])
.controller('MyCtrl', ['$scope', '$compile', '$document' , function MyCtrl($scope, $compile, $document) {
  var ctrl = this;

  var inputTemplate = '
--{{$ctrl.testModel}}<input type="text" name="testModel"/>
';

  ctrl.addControllDynamically = addControllDynamically;

  var id = 0;
  function addControllDynamically() {
    var name = "testModel_" + id;
    var cloned = angular.element(inputTemplate.replace(/testModel/g, name)).clone();
    cloned.find('input').attr("ng-model", "$ctrl." + name); //add ng-model attribute
    $document.find('[ng-app]').append($compile(cloned)($scope)); //compile and append
    id++;
  }

  return ctrl;
}]);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//code.angularjs.org/1.6.2/angular.js"></script>
<div ng-app="myApp">
  <div ng-controller="MyCtrl as $ctrl">
    <input type="button" value="Add control dynamically" ng-click="$ctrl.addControllDynamically()"/>
  </div>
</div></code>```

UPDATE: to add a new compiled template each time the button is clicked, we need to make a clone of the element.

UPDATE 2: The example above represents a dirty-way of manipulating the DOM from controller, which should be avoided. A better (angular-)way to solve the problem - is to create a directive with custom template and use it together with ng-repeat like this:

angular.module('myApp', [])
.controller('MyCtrl', ['$scope', function MyCtrl($scope) {
  var ctrl = this;

  ctrl.controls = [];
  ctrl.addControllDynamically = addControllDynamically;
  ctrl.removeControl = removeControl;

  function addControllDynamically() {
    //adding control to controls array
    ctrl.controls.push({ type: 'text' });
  }

  function removeControl(i) {
    //removing controls from array
    ctrl.controls.splice(i, 1);
  }

  return ctrl;
}])
.directive('controlTemplate', [function () {
        var controlTemplate = {
            restrict: 'E',
            scope: {
              type: '<',
              ngModel: '='
            },
            template: "
" +
              "
<input type='type' ng-model='ngModel'/>
" +
              "
"
        }
        return controlTemplate;
}]);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//code.angularjs.org/1.6.2/angular.js"></script>

<div ng-app="myApp">
  <div ng-controller="MyCtrl as $ctrl">
    <input type="button" value="Add control dynamically" ng-click="$ctrl.addControllDynamically()"/>

    <div ng-repeat="control in $ctrl.controls">
      <control-template type="control.type" ng-model="control.value"></control-template>
    </div>
  </div>
</div></code>```

Body:
You should use $compile service to link scope and your template together:

angular.module('myApp', [])
.controller('MyCtrl', ['$scope', '$compile', '$document' , function MyCtrl($scope, $compile, $document) {
  var ctrl = this;

  var inputTemplate = '<div><span ng-bind="$ctrl.testModel"></span>--<span>{{$ctrl.testModel}}</span><input type="text" name="testModel"/></div>';

  ctrl.addControllDynamically = addControllDynamically;

  var id = 0;
  function addControllDynamically() {
    var name = "testModel_" + id;
    var cloned = angular.element(inputTemplate.replace(/testModel/g, name)).clone();
    cloned.find('input').attr("ng-model", "$ctrl." + name); //add ng-model attribute
    $document.find('[ng-app]').append($compile(cloned)($scope)); //compile and append
    id++;
  }

  return ctrl;
}]);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//code.angularjs.org/1.6.2/angular.js"></script>
<div ng-app="myApp">
  <div ng-controller="MyCtrl as $ctrl">
    <input type="button" value="Add control dynamically" ng-click="$ctrl.addControllDynamically()"/>
  </div>
</div>

UPDATE: to add a new compiled template each time the button is clicked, we need to make a clone of the element.

UPDATE 2: The example above represents a dirty-way of manipulating the DOM from controller, which should be avoided. A better (angular-)way to solve the problem - is to create a directive with custom template and use it together with ng-repeat like this:

angular.module('myApp', [])
.controller('MyCtrl', ['$scope', function MyCtrl($scope) {
  var ctrl = this;

  ctrl.controls = [];
  ctrl.addControllDynamically = addControllDynamically;
  ctrl.removeControl = removeControl;

  function addControllDynamically() {
    //adding control to controls array
    ctrl.controls.push({ type: 'text' });
  }

  function removeControl(i) {
    //removing controls from array
    ctrl.controls.splice(i, 1);
  }

  return ctrl;
}])
.directive('controlTemplate', [function () {
        var controlTemplate = {
            restrict: 'E',
            scope: {
              type: '<',
              ngModel: '='
            },
            template: "<div>" +
              "<div><span ng-bind='ngModel'></span><input type='type' ng-model='ngModel'/></div>" +
              "</div>"
        }
        return controlTemplate;
}]);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//code.angularjs.org/1.6.2/angular.js"></script>

<div ng-app="myApp">
  <div ng-controller="MyCtrl as $ctrl">
    <input type="button" value="Add control dynamically" ng-click="$ctrl.addControllDynamically()"/>

    <div ng-repeat="control in $ctrl.controls">
      <control-template type="control.type" ng-model="control.value"></control-template>
    </div>
  </div>
</div>