问:
Character "d' " becoming " d' " when displayed
So I got this address 7 rue la Tour d'Auvergne from an API request in AJAX.

But when I feed it to an input in my view or even just display it like this

get_adress.js.erb

```<code>alert('<%= @sellsy_address.address %>')
$('#address').val('<%= @sellsy_address.address unless @sellsy_address.blank? %>');
</code>```

I got this 7 rue la Tour d'Auvergne

Any idea on how I can manage to keep the d' as it is ? I tried to encode or decode it in different ways but no results.

Thanks in advance

EDIT

If I use raw of html_safe, my js.erb just does not load at all anymore

答:
Try using html_safe along with escape_javascript (or j), like this:

```<code>alert('<%= j @sellsy_address.address.html_safe %>');
</code>```

Alternatively, you could skip j but change single quotes to double quotes, like this:

```<code>alert("<%= @sellsy_address.address.html_safe %>");
</code>```

If I use raw of html_safe, my js.erb just does not load at all anymore

That is because you get a syntax error due to the ' in 7 rue la Tour d'Auvergne being inside single quotes. Check the following examples;

Single quotes, without escape_javascript (or j)

```<code>alert('<%= @sellsy_address.address.html_safe %>');

//generated code:
alert('7 rue la Tour d'Auvergne');
</code>```

As you can see, the alert gets the string '7 rue la Tour d' and then expects a closing parenthesis ()), so you get an error an no alert is displayed.

Single quotes, with escape_javascript (or j)

```<code>alert('<%= j @sellsy_address.address.html_safe %>');

//generated code:
alert('7 rue la Tour d\'Auvergne');
</code>```

Now the ' has been escaped and is no longer a closing quote, so the alert is correctly displayed.

Double quotes, without escape_javascript (or j)

```<code>alert("<%= @sellsy_address.address.html_safe %>");

//generated code:
alert("7 rue la Tour d'Auvergne");
</code>```

This time ' needs no escaping since the string is enclosed between double quotes ('" "') which avoids any conflict with single quotes (').

Body:
So I got this address 7 rue la Tour d'Auvergne from an API request in AJAX.

But when I feed it to an input in my view or even just display it like this

get_adress.js.erb

alert('<%= @sellsy_address.address %>')
$('#address').val('<%= @sellsy_address.address unless @sellsy_address.blank? %>');

I got this 7 rue la Tour d'Auvergne

Any idea on how I can manage to keep the d' as it is ? I tried to encode or decode it in different ways but no results.

Thanks in advance

EDIT

If I use raw of html_safe, my js.erb just does not load at all anymore

Body:
Try using html_safe along with escape_javascript (or j), like this:

alert('<%= j @sellsy_address.address.html_safe %>');

Alternatively, you could skip j but change single quotes to double quotes, like this:

alert("<%= @sellsy_address.address.html_safe %>");

If I use raw of html_safe, my js.erb just does not load at all anymore

That is because you get a syntax error due to the ' in 7 rue la Tour d'Auvergne being inside single quotes. Check the following examples;

Single quotes, without escape_javascript (or j)

alert('<%= @sellsy_address.address.html_safe %>');

//generated code:
alert('7 rue la Tour d'Auvergne');

As you can see, the alert gets the string '7 rue la Tour d' and then expects a closing parenthesis ()), so you get an error an no alert is displayed.

Single quotes, with escape_javascript (or j)

alert('<%= j @sellsy_address.address.html_safe %>');

//generated code:
alert('7 rue la Tour d\'Auvergne');

Now the ' has been escaped and is no longer a closing quote, so the alert is correctly displayed.

Double quotes, without escape_javascript (or j)

alert("<%= @sellsy_address.address.html_safe %>");

//generated code:
alert("7 rue la Tour d'Auvergne");

This time ' needs no escaping since the string is enclosed between double quotes ('" "') which avoids any conflict with single quotes (').


来源: stackexchange

问:
Hide scrollbar when scrolling listview programmatically?
I made a chat application and have Chat Activity in it.
To display messages in dialog-like style I use ListView.

When I receive or send message to chat I need ListView to scroll down to it's end. Now I doing it with

```<code>chatView.smoothScrollToPosition(chatAdapter.getCount());
</code>```

But when listview scrolls down it shows an animated vertical scrollbar.
However. I want to display the vertical scrollbar when a user scrolls the list by himself (using finger) and NOT show the scrollbar when I do it programmatically.

How can I achieve that?

答:
Use android:scrollbars="none"in ListView

It will only hide the scrollbars keeping the horizontal or vertical scrolling as it is.

ContentLicense: CC BY-SA 3.0

Body:
I made a chat application and have Chat Activity in it.
To display messages in dialog-like style I use ListView.

When I receive or send message to chat I need ListView to scroll down to it's end. Now I doing it with

chatView.smoothScrollToPosition(chatAdapter.getCount());

But when listview scrolls down it shows an animated vertical scrollbar.
However. I want to display the vertical scrollbar when a user scrolls the list by himself (using finger) and NOT show the scrollbar when I do it programmatically.

How can I achieve that?


问:
Why do I need two return values within a function?
This question is very basic and very simple but I need to understand it.

I have this function in React:

```<code>renderPosts() {
  return _.map(this.props.posts, post => {
    return (
      <li className="list-group-item" key={post.id}>
        { post.title }
      </li>
    );
  });
}
</code>```

Why do I need the first return?

Basically, the second return will return me the li's. Why do I need to return (first return) them again? I need someone to help me explain this part. I am just confused.

答: I believe it is because you are in javascript. So the first return, is the return of the function (the prototype map of your object "_" ). And the second return is the return of your map function.</p>

Body:
This question is very basic and very simple but I need to understand it.

I have this function in React:

renderPosts() {
  return _.map(this.props.posts, post => {
    return (

        { post.title }

    );
  });
}

Why do I need the first return?

Basically, the second return will return me the li's. Why do I need to return (first return) them again? I need someone to help me explain this part. I am just confused.


问:
Inno Setup unable to find and execute ie4uinit.exe on x64
I am trying to refresh the Windows icon cache using the well known and documented method of calling ie4uinit.exe -ClearIconCache for anything below Window 10 and ie4uinit.exe -Show on Windows 10 and above:

```<code>[Run]
Filename: "{sys}\ie4uinit.exe"; Parameters: "-ClearIconCache"; StatusMsg: "Rebuilding Windows icon cache..."; Flags: runhidden; Check: not IsWindows10AndAbove
Filename: "{sys}\ie4uinit.exe"; Parameters: "-Show"; StatusMsg: "Rebuilding Windows icon cache..."; Flags: runhidden; Check: IsWindows10AndAbove
</code>```

Both commands work as expected when run in Explorer or at a command prompt. They also work correctly in Inno Setup when running on an x86 system. However, on an x64 system, the following error is produced:

The path to the file, using the {sys} constant, resolves correctly and the file exists and can be seen both in Explorer and in a directory listing at the command prompt:

The following variation of the above code, running through the command prompt, also fails in much the same way, although it is silent and only indicated by an exit code of 1 in the install log.

```<code>[Run]
Filename: "{cmd}"; Parameters: "/c {sys}\ie4uinit.exe -ClearIconCache"; StatusMsg: "Rebuilding Windows icon cache..."; Flags: runhidden; Check: not IsWindows10AndAbove
Filename: "{cmd}"; Parameters: "/c {sys}\ie4uinit.exe -Show"; StatusMsg: "Rebuilding Windows icon cache..."; Flags: runhidden; Check: IsWindows10AndAbove
</code>```

I have already read clear icon cache in win 7 programmatically - execute ie4uinit.exe-ClearIconCache using C# or Visual Basic, which also has mention of this being a problem in Inno Setup (towards the bottom) and tried the workaround to copy the file and run it from elsewhere. However, attempting to copy the file to another location, using the FileCopy function, also failed to find it in C:\Windows\System32. I also tried running the same command in the [Code] section using the Exec function, but this also fails to find it in C:\Windows\System32.

I considered making a copy of the file and installing it to the temp directory to run it from there, but this file is a different version on each Windows version, so this is not really a viable solution, especially as, being a system file, it may also change in the future.

The accepted answer in the above question seems to be to build the executable for 'Any CPU' rather than 'x86'. However, I am not sure if this can be done in Inno Setup and also if doing so would have any unforeseen side effects on the installers behaviour?

Is there any way to resolve or work around this in Inno Setup?

答:
I finally figured this out. Inno Setup cannot find the file as, rather confusingly, despite it displaying that it is looking in C:\Windows\System32, Windows file redirection is actually silently causing it to look in C:\Windows\SysWOW64, where ie4uinit.exe does not exist. The solution, therefore, is to temporarily disable file redirection in the [Code] section, using the [Run] section BeforeInstall and AfterInstall directives, followed by the EnableFsRedirection function, after which Inno Setup can now see and access the actual C:\Windows\System32 directory, copy the file to the temp directory and run it from there, before restoring file redirection to it's previous state:

```<code>[Run]
Filename: "{tmp}\Config Tools\ie4uinit.exe"; Parameters: "-ClearIconCache"; StatusMsg: "Refreshing Windows icon cache..."; Flags: runhidden; Check: not IsWindows10AndAbove; BeforeInstall: StartRefreshIconCache; AfterInstall: FinishRefreshIconCache
Filename: "{tmp}\Config Tools\ie4uinit.exe"; Parameters: "-Show"; StatusMsg: "Refreshing Windows icon cache..."; Flags: runhidden; Check: IsWindows10AndAbove; BeforeInstall: StartRefreshIconCache; AfterInstall: FinishRefreshIconCache

[Code]
//Start refresh or rebuild of the Windows icon cache
procedure StartRefreshIconCache();
var
  OriginalFileRedirectionState: Boolean;
begin
  if not IsWin64 then
    begin
      if FileCopy(ExpandConstant('{sys}\ie4uinit.exe'), ExpandConstant('{tmp}\Config Tools\ie4uinit.exe'), False) then
        begin
          Log(ExpandConstant('Copied {sys}\ie4uinit.exe to {tmp}\Config Tools\ie4uinit.exe'));
        end;
    end
  else if IsWin64 then
    begin
      //Store Windows file redirection's original state and temporarily disable to allow access to the System32 directory on x64 to allow copy of ie4uinit.exe
      OriginalFileRedirectionState := EnableFsRedirection(False);
      Log('File redirection temporarily disabled for x64 compatibility.');
      try
        if FileCopy(ExpandConstant('{sys}\ie4uinit.exe'), ExpandConstant('{tmp}\Config Tools\ie4uinit.exe'), False) then
          begin
            Log(ExpandConstant('Copied {sys}\ie4uinit.exe to {tmp}\Config Tools\ie4uinit.exe'));
          end;
      finally
        //Restore file redirection's original state
        EnableFsRedirection(OriginalFileRedirectionState);
        Log('File redirection restored to it''s original state.');
      end;
    end;
end;

//Finish refresh or rebuild of the Windows icon cache
procedure FinishRefreshIconCache();
begin
  if DeleteFile(ExpandConstant('{tmp}\Config Tools\ie4uinit.exe')) then
    begin
      Log(ExpandConstant('Deleted {tmp}\Config Tools\ie4uinit.exe'));
    end;
end;
</code>```

Body:
I am trying to refresh the Windows icon cache using the well known and documented method of calling ie4uinit.exe -ClearIconCache for anything below Window 10 and ie4uinit.exe -Show on Windows 10 and above:

[Run]
Filename: "{sys}\ie4uinit.exe"; Parameters: "-ClearIconCache"; StatusMsg: "Rebuilding Windows icon cache..."; Flags: runhidden; Check: not IsWindows10AndAbove
Filename: "{sys}\ie4uinit.exe"; Parameters: "-Show"; StatusMsg: "Rebuilding Windows icon cache..."; Flags: runhidden; Check: IsWindows10AndAbove

Both commands work as expected when run in Explorer or at a command prompt. They also work correctly in Inno Setup when running on an x86 system. However, on an x64 system, the following error is produced:

The path to the file, using the {sys} constant, resolves correctly and the file exists and can be seen both in Explorer and in a directory listing at the command prompt:

The following variation of the above code, running through the command prompt, also fails in much the same way, although it is silent and only indicated by an exit code of 1 in the install log.

[Run]
Filename: "{cmd}"; Parameters: "/c {sys}\ie4uinit.exe -ClearIconCache"; StatusMsg: "Rebuilding Windows icon cache..."; Flags: runhidden; Check: not IsWindows10AndAbove
Filename: "{cmd}"; Parameters: "/c {sys}\ie4uinit.exe -Show"; StatusMsg: "Rebuilding Windows icon cache..."; Flags: runhidden; Check: IsWindows10AndAbove

I have already read clear icon cache in win 7 programmatically - execute ie4uinit.exe-ClearIconCache using C# or Visual Basic, which also has mention of this being a problem in Inno Setup (towards the bottom) and tried the workaround to copy the file and run it from elsewhere. However, attempting to copy the file to another location, using the FileCopy function, also failed to find it in C:\Windows\System32. I also tried running the same command in the [Code] section using the Exec function, but this also fails to find it in C:\Windows\System32.

I considered making a copy of the file and installing it to the temp directory to run it from there, but this file is a different version on each Windows version, so this is not really a viable solution, especially as, being a system file, it may also change in the future.

The accepted answer in the above question seems to be to build the executable for 'Any CPU' rather than 'x86'. However, I am not sure if this can be done in Inno Setup and also if doing so would have any unforeseen side effects on the installers behaviour?

Is there any way to resolve or work around this in Inno Setup?

Body:
I finally figured this out. Inno Setup cannot find the file as, rather confusingly, despite it displaying that it is looking in C:\Windows\System32, Windows file redirection is actually silently causing it to look in C:\Windows\SysWOW64, where ie4uinit.exe does not exist. The solution, therefore, is to temporarily disable file redirection in the [Code] section, using the [Run] section BeforeInstall and AfterInstall directives, followed by the EnableFsRedirection function, after which Inno Setup can now see and access the actual C:\Windows\System32 directory, copy the file to the temp directory and run it from there, before restoring file redirection to it's previous state:

[Run]
Filename: "{tmp}\Config Tools\ie4uinit.exe"; Parameters: "-ClearIconCache"; StatusMsg: "Refreshing Windows icon cache..."; Flags: runhidden; Check: not IsWindows10AndAbove; BeforeInstall: StartRefreshIconCache; AfterInstall: FinishRefreshIconCache
Filename: "{tmp}\Config Tools\ie4uinit.exe"; Parameters: "-Show"; StatusMsg: "Refreshing Windows icon cache..."; Flags: runhidden; Check: IsWindows10AndAbove; BeforeInstall: StartRefreshIconCache; AfterInstall: FinishRefreshIconCache

[Code]
//Start refresh or rebuild of the Windows icon cache
procedure StartRefreshIconCache();
var
  OriginalFileRedirectionState: Boolean;
begin
  if not IsWin64 then
    begin
      if FileCopy(ExpandConstant('{sys}\ie4uinit.exe'), ExpandConstant('{tmp}\Config Tools\ie4uinit.exe'), False) then
        begin
          Log(ExpandConstant('Copied {sys}\ie4uinit.exe to {tmp}\Config Tools\ie4uinit.exe'));
        end;
    end
  else if IsWin64 then
    begin
      //Store Windows file redirection's original state and temporarily disable to allow access to the System32 directory on x64 to allow copy of ie4uinit.exe
      OriginalFileRedirectionState := EnableFsRedirection(False);
      Log('File redirection temporarily disabled for x64 compatibility.');
      try
        if FileCopy(ExpandConstant('{sys}\ie4uinit.exe'), ExpandConstant('{tmp}\Config Tools\ie4uinit.exe'), False) then
          begin
            Log(ExpandConstant('Copied {sys}\ie4uinit.exe to {tmp}\Config Tools\ie4uinit.exe'));
          end;
      finally
        //Restore file redirection's original state
        EnableFsRedirection(OriginalFileRedirectionState);
        Log('File redirection restored to it''s original state.');
      end;
    end;
end;

//Finish refresh or rebuild of the Windows icon cache
procedure FinishRefreshIconCache();
begin
  if DeleteFile(ExpandConstant('{tmp}\Config Tools\ie4uinit.exe')) then
    begin
      Log(ExpandConstant('Deleted {tmp}\Config Tools\ie4uinit.exe'));
    end;
end;


问:
Display selected values of multi-value parameter in tablix rows
I am designing a report for SSRS. I want the user requesting the report to be able to specify, when they generate the report, from a pre-defined selection some values which should be displayed in a tablix on the report.

I have therefore created a multi-value parameter and populated the Available Values with the options I want the user to be able to select from, and, as expected, when the report is generated the user is able to select one or more of these values.

However, what I now want to do is include a tablix in the report, and display a row for every value in the multi-value parameter that the user selected, with the value displayed in the first cell of the row.

If the values were coming from a data table this would obviously be easy. I've also found answers on how to show all of the selected parameter values in a single textbox using the JOIN function, but I don't want to do that.

The only solution I can think of is to replicate the list of available values in the multi-value parameter in a tablix manually, and link the visibility of each row of the tablix to the selected state of the corresponding value in the multi-value parameter, but that's not very elegant and increases the effort involved in maintaining the report definition.

Any ideas on how to do this? I know the selected values from the parameter simply form an array, but I can't see how to bind a tablix to any data that isn't in a dataset, or how to create a dataset from the parameter values.

答:
Considering that a tablix sources from a dataset, I did some experiments to see how to create a low maintenance solution for you.

Option 1: Create a data set with hard-coded options to match your multi-value parameter and select those options WHERE they exist in the parameter.

Example:

```<code> SELECT val
    FROM (
        SELECT 'opt1' as val
        UNION SELECT 'opt2'
        UNION SELECT 'opt3'
        UNION SELECT 'opt4') a
    WHERE val IN (@Param)
</code>```

Thoughts: easier to maintain than visibility on a table, but still two hard-coded places within the report.

Option 2: Create a dataset that selects the multi-value parameter and splits it by each value.  This was my first idea, but I ran into some issues with determining how to actually select the multi-value without a syntax error.  I came up with a method that creates a deliminated string in the report and than parsed that string back into rows in the dataset:

Step 1) Within the dataset properties, on the parameter tab, join the multiple values together with a JOIN expression

Step 2) Create a simple query which uses the new SQL Server 2016 function string_split.  Note that your database compatibility level MUST be 130 or higher to use this function (SQL 2016+).  If this isn't your scenario, there are many string split functions that you can find on Stack Overflow to achieve the same thing.

Fun problem!

Body:
Considering that a tablix sources from a dataset, I did some experiments to see how to create a low maintenance solution for you.

Option 1: Create a data set with hard-coded options to match your multi-value parameter and select those options WHERE they exist in the parameter.

Example:

 SELECT val
    FROM (
        SELECT 'opt1' as val
        UNION SELECT 'opt2'
        UNION SELECT 'opt3'
        UNION SELECT 'opt4') a
    WHERE val IN (@Param)

Thoughts: easier to maintain than visibility on a table, but still two hard-coded places within the report.

Option 2: Create a dataset that selects the multi-value parameter and splits it by each value.  This was my first idea, but I ran into some issues with determining how to actually select the multi-value without a syntax error.  I came up with a method that creates a deliminated string in the report and than parsed that string back into rows in the dataset:

Step 1) Within the dataset properties, on the parameter tab, join the multiple values together with a JOIN expression

Step 2) Create a simple query which uses the new SQL Server 2016 function string_split.  Note that your database compatibility level MUST be 130 or higher to use this function (SQL 2016+).  If this isn't your scenario, there are many string split functions that you can find on Stack Overflow to achieve the same thing.

Fun problem!


问:
Docker: How to install memcached in container
I am using php:5.6-apache docker image for local development. Now I am developing one portal using codeigniter3. I want to use memcached for caching purpose. But it was not found by default in php:5.6-apache image.

How can i install memcached in my container?

Right now I am trying to use memcached container for this purpose but don't get success yet. Any help will be appreciated.

答:
With something like this:

docker-compose.yml

```<code>version: "3"
services:
  php:
    build: .
  memcached:
    image: memcached
</code>```

You can point to memcached container from php container as this: memcached:11211

You will need to enable php-memcached mod in your current php Dockerfile.

Body:
With something like this:

docker-compose.yml

version: "3"
services:
  php:
    build: .
  memcached:
    image: memcached

You can point to memcached container from php container as this: memcached:11211

You will need to enable php-memcached mod in your current php Dockerfile.


问:
mark if combine of multiple textbox value match in while loop table
i need little help to solve my problem. i have a table with mysql/php while loop. and two textbox with query value like

```<code><tbody>
<?php while($row = mysqli_fetch_assoc($result)){ ?>
<tr>
<td><input name="telephone_number" type="text" value="<?php echo $row['telephone_number'];?>"/></td>
<td><input name="priority" type="text"  value="<?php echo $row['priority'];?>" /></td>
<td>.....</td>
<td>.....</td>
</tr>
<?php }  ?>
</tbody>
</code>```

Now lets say if telephone number val- 888 and priority val- 0 both altogether  match with other row then all matched row(tr) colored with class say class_matched.

so far i can do with one textbox with textbox background color with the help of stackoverflow. but cant figure out for both textbox and add class inside tr.

```<code>$('#table1').find("input[name='telephone_number']").each(function() {
if ($this.val().length > 1) {
$(this).addClass('class_matched');
}
});
</code>```

Thanks in advance for help. sincerely apologize if duplicate.

Edited: and also i want to implement on change event for both textbox.

答:
You need to two loops

Store outer loop val and then use second loop

Add class if matched with inner loop

$('#table1 tr').each(function(i, e) {
  var ot = $(this).find("input[name='telephone_number']").val();
  var op = $(this).find("input[name='priority']").val();
  var isMatched = false;
  $('#table1 tr').each(function(j, k) {
    if (j > i) {
      var it = $(this).find("input[name='telephone_number']").val();
      var ip = $(this).find("input[name='priority']").val();
      if (it == ot && ip == op) {
        $(this).addClass('class_matched');
        isMatched = true;
      }
    }
  });
  if (isMatched) {
    $(this).addClass('class_matched');
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.class_matched {
  background-color: red;
}</code>```

      <input name="telephone_number" type="text" value="888" />
      <input name="priority" type="text" value="0" />

      <input name="telephone_number" type="text" value="999" />
      <input name="priority" type="text" value="0" />

      <input name="telephone_number" type="text" value="888" />
      <input name="priority" type="text" value="0" />

```

Body:
i need little help to solve my problem. i have a table with mysql/php while loop. and two textbox with query value like

<?php while($row = mysqli_fetch_assoc($result)){ ?>

<input name="telephone_number" type="text" value="<?php echo $row['telephone_number'];?>"/>
<input name="priority" type="text"  value="<?php echo $row['priority'];?>" />
.....
.....

<?php }  ?>

Now lets say if telephone number val- 888 and priority val- 0 both altogether  match with other row then all matched row(tr) colored with class say class_matched.

so far i can do with one textbox with textbox background color with the help of stackoverflow. but cant figure out for both textbox and add class inside tr.

$('#table1').find("input[name='telephone_number']").each(function() {
if ($this.val().length > 1) {
$(this).addClass('class_matched');
}
});

Thanks in advance for help. sincerely apologize if duplicate.

Edited: and also i want to implement on change event for both textbox.

Body:
You need to two loops

Store outer loop val and then use second loop

Add class if matched with inner loop

$('#table1 tr').each(function(i, e) {
  var ot = $(this).find("input[name='telephone_number']").val();
  var op = $(this).find("input[name='priority']").val();
  var isMatched = false;
  $('#table1 tr').each(function(j, k) {
    if (j > i) {
      var it = $(this).find("input[name='telephone_number']").val();
      var ip = $(this).find("input[name='priority']").val();
      if (it == ot && ip == op) {
        $(this).addClass('class_matched');
        isMatched = true;
      }
    }
  });
  if (isMatched) {
    $(this).addClass('class_matched');
  }
});

.class_matched {
  background-color: red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table id="table1">
  <tbody>
    <tr>
      <td><input name="telephone_number" type="text" value="888" /></td>
      <td><input name="priority" type="text" value="0" /></td>
    </tr>
    <tr>
      <td><input name="telephone_number" type="text" value="999" /></td>
      <td><input name="priority" type="text" value="0" /></td>
    </tr>
    <tr>
      <td><input name="telephone_number" type="text" value="888" /></td>
      <td><input name="priority" type="text" value="0" /></td>
    </tr>
  </tbody>
</table>


问:
Copy to redshift fails with an error when using KMS Managed CMK
I am trying to write a java program which encrypts data using KMS key id. I am using the default java code for uploading an object to S3. I am changing the values to be uploaded to S3 to be a records so that I can use load it to redshift.

```<code>import java.io.ByteArrayInputStream;
import java.util.Arrays;

import junit.framework.Assert;

import org.apache.commons.io.IOUtils;

import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3EncryptionClient;
import com.amazonaws.services.s3.model.CryptoConfiguration;
import com.amazonaws.services.s3.model.KMSEncryptionMaterialsProvider;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.S3Object;

public class testKMSkeyUploadObject {

    private static AmazonS3EncryptionClient encryptionClient;

    public static void main(String[] args) throws Exception {
       String bucketName = "***bucket name***";
        String objectKey  = "ExampleKMSEncryptedObject";
        String kms_cmk_id = "***AWS KMS customer master key ID***";

        KMSEncryptionMaterialsProvider materialProvider = new KMSEncryptionMaterialsProvider(kms_cmk_id);

        encryptionClient = new AmazonS3EncryptionClient(new ProfileCredentialsProvider(), materialProvider,
                new CryptoConfiguration().withKmsRegion(Regions.US_EAST_1))
            .withRegion(Region.getRegion(Regions.US_EAST_1));

        // Upload object using the encryption client.
        byte[] plaintext = "xyz,abc,1"
                .getBytes();
        System.out.println("plaintext's length: " + plaintext.length);
        encryptionClient.putObject(new PutObjectRequest(bucketName, objectKey,
                new ByteArrayInputStream(plaintext), new ObjectMetadata()));

     // Download the object.
        S3Object downloadedObject = encryptionClient.getObject(bucketName,
                objectKey);
        byte[] decrypted = IOUtils.toByteArray(downloadedObject
                .getObjectContent());

        // Verify same data.
        Assert.assertTrue(Arrays.equals(plaintext, decrypted));
    }
}
</code>```

I am using Redhsift copy command with below syntax to copy the records to redshift.

```<code>copy table_name from 's3://bucket-name/KMSEncryptedObject' credentials as
'aws_access_key_id=<access-key-id>;aws_secret_access_key=<secret-access-key>;master_symmetric_key=<master-key>'
</code>```

When run above copy command I am encountering below error:

```<code>Query execution failed
Reason: SQL Error [500310] [XX000]: [Amazon](500310) Invalid operation: Failed writing body (0 != 16)
Cause: S3 object 'KMSEncyptedObjecr does not have 'x-amz-meta-x-amz-key metadata
Details:
----------------
error: Failed writing body (0 != 16) Cause: S3 object 'KMSEncyptedObjeci does not have 'x-amz-meta-x-amz-key metadata
</code>```

答:
AFAIK you don't have to specify the KMS key id when copying the data from S3. Simply, remove the master_symmetric_key argument from your credentials string.

Looking at http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingKMSEncryption.html you only need the KMS key ID to upload (and of course the IAM user / role needs to have access to this key).

Body:
I am trying to write a java program which encrypts data using KMS key id. I am using the default java code for uploading an object to S3. I am changing the values to be uploaded to S3 to be a records so that I can use load it to redshift.

import java.io.ByteArrayInputStream;
import java.util.Arrays;

import junit.framework.Assert;

import org.apache.commons.io.IOUtils;

import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3EncryptionClient;
import com.amazonaws.services.s3.model.CryptoConfiguration;
import com.amazonaws.services.s3.model.KMSEncryptionMaterialsProvider;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.S3Object;

public class testKMSkeyUploadObject {

    private static AmazonS3EncryptionClient encryptionClient;

    public static void main(String[] args) throws Exception {
       String bucketName = "***bucket name***";
        String objectKey  = "ExampleKMSEncryptedObject";
        String kms_cmk_id = "***AWS KMS customer master key ID***";

        KMSEncryptionMaterialsProvider materialProvider = new KMSEncryptionMaterialsProvider(kms_cmk_id);

        encryptionClient = new AmazonS3EncryptionClient(new ProfileCredentialsProvider(), materialProvider,
                new CryptoConfiguration().withKmsRegion(Regions.US_EAST_1))
            .withRegion(Region.getRegion(Regions.US_EAST_1));

        // Upload object using the encryption client.
        byte[] plaintext = "xyz,abc,1"
                .getBytes();
        System.out.println("plaintext's length: " + plaintext.length);
        encryptionClient.putObject(new PutObjectRequest(bucketName, objectKey,
                new ByteArrayInputStream(plaintext), new ObjectMetadata()));

     // Download the object.
        S3Object downloadedObject = encryptionClient.getObject(bucketName,
                objectKey);
        byte[] decrypted = IOUtils.toByteArray(downloadedObject
                .getObjectContent());

        // Verify same data.
        Assert.assertTrue(Arrays.equals(plaintext, decrypted));
    }
}

I am using Redhsift copy command with below syntax to copy the records to redshift.

copy table_name from 's3://bucket-name/KMSEncryptedObject' credentials as
'aws_access_key_id=<access-key-id>;aws_secret_access_key=<secret-access-key>;master_symmetric_key=<master-key>'

When run above copy command I am encountering below error:

Query execution failed
Reason: SQL Error [500310] [XX000]: [Amazon](500310) Invalid operation: Failed writing body (0 != 16)
Cause: S3 object 'KMSEncyptedObjecr does not have 'x-amz-meta-x-amz-key metadata
Details:
----------------
error: Failed writing body (0 != 16) Cause: S3 object 'KMSEncyptedObjeci does not have 'x-amz-meta-x-amz-key metadata


问:
Generating passwords for the Azure Api Management Git repository
Azure Api Management has an option to create time-bounded passwords for the integrated git repository.

As part of our VSTS release management, we want to push our changes automatically to this git repository. We don't want to create every month a new git password through the Azure portal.

The publisher portal provides credentials (identifier with primary and secondary key) to generate passwords.

But I can't find any references how to use this. Could somebody give me some insights?

答:
You can use the REST api to automate this process to get credentials.

Use REST API
Get Git UserId

Then Use REST API Generate Credentials For User to generate the credentials for the user.


问:
Dealing with polymorphic association: is there such a thing as "too many" LEFT JOIN?
I have ten tables (Product_A, Product_B, Product_C, etc.), each of them having a primary key pointing to a row in a the parent table Product.

Basically, I have applied the recommendations coming from the SQL antipattern book from Bill Karwin (this antipattern solution described here:
https://fr.slideshare.net/billkarwin/practical-object-oriented-models-in-sql/34-Polymorphic_Assocations_Exclusive_Arcs_Referential )

In order to load a child product, I use something like this:

```<code>SELECT * FROM Product
LEFT JOIN Product_A USING (product_id)
LEFT JOIN Product_B USING (product_id)
LEFT JOIN Product_C USING (product_id)
LEFT JOIN Product_D USING (product_id)
WHERE product_id = 1337
etc.
</code>```

I fear that the more types of child table products I get, the more JOIN clause I will have to add, causing the query to end up incredibly slow.

Is using LEFT JOIN in order to prevent polymorphic associations antipattern still a solution if we work on tens of sub child tables?

Should I start thinking of up using a query on parent table Product in order to grab a "product_type" and then execute another query on the appropriate child table depending on the value stored in the "product_type" column in the parent table?

Update: first replies on this topic state that this is bad design and that I should create a single table combining the colums from the child tables. But each product type has its own attributes. To say it otherwise: "A TV might have a pixel count, but that wouldn't make much sense for a blender." @TomH

Thank you

答:
What kind of data is going into these tables? Is it simply metadata about the products? If that's the case you could create a tall table that describes each product.

For example, a Product_Details table that has three columns: product_id, product_data_key, value. Where product_data_key is what used to be the columns in Product_A, Product_B, Product_C...

You could even have a separate table that better describes product_data_key so it's just a foreign key in Product_Details.

Body:
I have ten tables (Product_A, Product_B, Product_C, etc.), each of them having a primary key pointing to a row in a the parent table Product.

Basically, I have applied the recommendations coming from the SQL antipattern book from Bill Karwin (this antipattern solution described here:
https://fr.slideshare.net/billkarwin/practical-object-oriented-models-in-sql/34-Polymorphic_Assocations_Exclusive_Arcs_Referential )

In order to load a child product, I use something like this:

SELECT * FROM Product
LEFT JOIN Product_A USING (product_id)
LEFT JOIN Product_B USING (product_id)
LEFT JOIN Product_C USING (product_id)
LEFT JOIN Product_D USING (product_id)
WHERE product_id = 1337
etc.

I fear that the more types of child table products I get, the more JOIN clause I will have to add, causing the query to end up incredibly slow.

Is using LEFT JOIN in order to prevent polymorphic associations antipattern still a solution if we work on tens of sub child tables?

Should I start thinking of up using a query on parent table Product in order to grab a "product_type" and then execute another query on the appropriate child table depending on the value stored in the "product_type" column in the parent table?

Update: first replies on this topic state that this is bad design and that I should create a single table combining the colums from the child tables. But each product type has its own attributes. To say it otherwise: "A TV might have a pixel count, but that wouldn't make much sense for a blender." @TomH

Thank you


问:
XMLHttpRequest in google-chrome is not reporting progress events
Hi all I have this code:

```<code>function test()
{
    req = new XMLHttpRequest();
    req.upload.addEventListener("progress", updateProgress, false);
    req.addEventListener("readystatechange", updateProgress, false);
    req.addEventListener("error", uploadFailed, false);
    req.addEventListener("abort", uploadCanceled, false);

    var data = generateRandomData(currentPayloadId);
    totalSize = data.length;

    req.open("POST", "www.mydomain.com/upload.aspx");
    start = (new Date()).getTime();
    req.send(data);
}

function updateProgress(evt)
{
    if (evt.lengthComputable) {
        total = totalSize = evt.total;
        loaded = evt.loaded;
    }
    else {
        total = loaded = totalSize;
    }
}
</code>```

Also, my server responds to the initial OPTIONS request for upload.aspx with 200 and the Access-Control-Allow-Origin: *
and then the second request POST happens

Everything seems in place and it's working great on FireFox but on G Chrome the updateProgress handler is not getting called but only once and then the lengthComputable is false.

I needed the Access-Control-Allow-Origin: * because this is a cross-domain call, the script parent is a resource on a different server then the upload.aspx domain

Anyone can give me some clues, hints, help please? is this a known issue with G Chrome?

Thank you!
Ova

答:
I had this problem when the page your are loading doesn't contain a

```<code>  Content-Length: 12345
</code>```

in the header, where 12345 is the length of the response in bytes.  Without a length parameter, the progress function has nothing to work on.

Body:
Hi all I have this code:

function test()
{
    req = new XMLHttpRequest();
    req.upload.addEventListener("progress", updateProgress, false);
    req.addEventListener("readystatechange", updateProgress, false);
    req.addEventListener("error", uploadFailed, false);
    req.addEventListener("abort", uploadCanceled, false);

    var data = generateRandomData(currentPayloadId);
    totalSize = data.length;

    req.open("POST", "www.mydomain.com/upload.aspx");
    start = (new Date()).getTime();
    req.send(data);
}

function updateProgress(evt)
{
    if (evt.lengthComputable) {
        total = totalSize = evt.total;
        loaded = evt.loaded;
    }
    else {
        total = loaded = totalSize;
    }
}

Also, my server responds to the initial OPTIONS request for upload.aspx with 200 and the Access-Control-Allow-Origin: *
and then the second request POST happens

Everything seems in place and it's working great on FireFox but on G Chrome the updateProgress handler is not getting called but only once and then the lengthComputable is false.

I needed the Access-Control-Allow-Origin: * because this is a cross-domain call, the script parent is a resource on a different server then the upload.aspx domain

Anyone can give me some clues, hints, help please? is this a known issue with G Chrome?

Thank you!
Ova

Body:
I had this problem when the page your are loading doesn't contain a

  Content-Length: 12345

in the header, where 12345 is the length of the response in bytes.  Without a length parameter, the progress function has nothing to work on.


问:
Vuejs v-model special characters
Can you escape special characters with v-model? I am seeing an issue where I edit text that I receive from a data call. 'this' is showing as '&'#39;this'&#39' in the textarea when editing. I know of v-html, but can you use that with v-model? If not, what is another option?</p>

答:
v-model works like v-text and shows all characters while v-html let you show the html code.
If you see "this" in you source file/debugger/response the reason might be the encoding or that you try to display json-text.
Because ' is the NCR dez. for the character ' .

v-model gives automatic two way binding, if you do not need that you can use one of the other directives.

Title: Vuejs v-model special characters

Body:
v-model works like v-text and shows all characters while v-html let you show the html code.
If you see "this" in you source file/debugger/response the reason might be the encoding or that you try to display json-text.
Because &#39; is the NCR dez. for the character ' .

v-model gives automatic two way binding, if you do not need that you can use one of the other directives.


问:
This program requires version 3.2.0 of the Protocol Buffer runtime library, but the installed version is 2.6.1
I'm trying to train a Caffe model. My .prototxt file uses custom Python Data and Loss layers.

When I execute the training command in terminal, however, this error is raised:

```<code>[libprotobuf FATAL google/protobuf/stubs/common.cc:61] This program requires version 3.2.0 of the Protocol Buffer runtime library, but the installed version is 2.6.1.  Please update your library.  If you compiled the program yourself, make sure that your headers are from the same version of Protocol Buffers as your link-time library.  (Version verification failed in "google/protobuf/descriptor.pb.cc".)
terminate called after throwing an instance of 'google::protobuf::FatalException'
</code>```

My Python Package Manager (pip) has version 3.2.0 of protobuf installed, but the system version is at 2.6.1 for a package called libprotoc. I am not sure how to specify that the pip protobuf version is the one I want to use for caffe.

On another computer which has version 3.3.0 of protobuf installed on pip and 2.6.1 for the system version, I was thrown the same error, except that it said the program required version 3.3.0 rather than version 3.2.0.

Best.

答:
I ran into exactly the same issue today. The workaround that worked for me was to start the training from caffe's python interface as opposed to starting it directly from the shell. Example:

```<code>import caffe

weights = '../ilsvrc-nets/vgg16-fcn.caffemodel'
caffe.set_device(0)
caffe.set_mode_gpu()

solver = caffe.SGDSolver('solver.prototxt')
solver.net.copy_from(weights)

for _ in range(25):
    solver.step(4000)
</code>```

Off course the above is just an example/very barebones, you'll have to handle running against the validation set yourself but the pycaffe interface is quite flexible and allows you to do all that. You can find more details on how to use that here:

http://christopher5106.github.io/deep/learning/2015/09/04/Deep-learning-tutorial-on-Caffe-Technology.html

Body:
I'm trying to train a Caffe model. My .prototxt file uses custom Python Data and Loss layers.

When I execute the training command in terminal, however, this error is raised:

[libprotobuf FATAL google/protobuf/stubs/common.cc:61] This program requires version 3.2.0 of the Protocol Buffer runtime library, but the installed version is 2.6.1.  Please update your library.  If you compiled the program yourself, make sure that your headers are from the same version of Protocol Buffers as your link-time library.  (Version verification failed in "google/protobuf/descriptor.pb.cc".)
terminate called after throwing an instance of 'google::protobuf::FatalException'

My Python Package Manager (pip) has version 3.2.0 of protobuf installed, but the system version is at 2.6.1 for a package called libprotoc. I am not sure how to specify that the pip protobuf version is the one I want to use for caffe.

On another computer which has version 3.3.0 of protobuf installed on pip and 2.6.1 for the system version, I was thrown the same error, except that it said the program required version 3.3.0 rather than version 3.2.0.

Best.

Body:
I ran into exactly the same issue today. The workaround that worked for me was to start the training from caffe's python interface as opposed to starting it directly from the shell. Example:

import caffe

weights = '../ilsvrc-nets/vgg16-fcn.caffemodel'
caffe.set_device(0)
caffe.set_mode_gpu()

solver = caffe.SGDSolver('solver.prototxt')
solver.net.copy_from(weights)

for _ in range(25):
    solver.step(4000)

Off course the above is just an example/very barebones, you'll have to handle running against the validation set yourself but the pycaffe interface is quite flexible and allows you to do all that. You can find more details on how to use that here:

http://christopher5106.github.io/deep/learning/2015/09/04/Deep-learning-tutorial-on-Caffe-Technology.html


问:
How to package a Python Game made in Python using Pygame?
So recently I made a game in python pygame and when I want to try it on a different computer it cant work because I don't have pygame as a package there, so my question is what do I do when I want to give my game to a friend without him having to get all the packages/modules I used to code it?</p>

答: You'll want to compile it into an executable. You can use a popular program like py2exe to convert your project into an executable that can be used on any windows platform. Just make sure you are using the right version of python.</p>


问:
preg_replace - Replacing
 with nothing in
 tags
I have the following:

```<code>$newtext = preg_replace('@```.*
]*?>?```@si','',$text);
</code>```

and I want it to replace all
,
, or
 tags with nothing when between ``` tags, but it isn't working.  What's wrong with it?

答:
Your problem is that you're trying to use regular expressions to do a parser's job.  Even if you get it mostly working, you'll be finding edge cases where things break down the road.

See: RegEx match open tags except XHTML self-contained tags

ContentLicense: CC BY-SA 2.5

Title: preg_replace - Replacing <br> with nothing in <pre> tags

Body:
I have the following:

$newtext = preg_replace('@
.*
]*?>?
@si','',$text);

and I want it to replace all
,
, or
 tags with nothing when between
 tags, but it isn't working.  What's wrong with it?


问:
How to copy projects in Android Studio?
I tried copying my Android Studio project but every time I do that it gives me errors. I read other questions and answers on this topics but none of this helped me.

When I copy a project and try to run it on the emulator it gives the following error:

"Installation failed with message Invalid File:
  C:...\app\build\intermediates\split-apk\debug\slices\slice_9.apk. It
  is possible that this issue is resolved by uninstalling an existing
  version of the apk if it is present, and then re-installing."

According to answers on similar questions, it should help to perform a 'clean project'. When I do this, the emulator starts but stops starting the app with a runtime error:

"java.lang.RuntimeException: Unable to instantiate activity
  ComponentInfo{nl.assortimens.hardlooptrainingapp/nl.assortimens.hardlooptrainingapp.MainMenuActivity}:
  java.lang.ClassNotFoundException: Didn't find class
  "nl.assortimens.hardlooptrainingapp.MainMenuActivity" on path:
  DexPathList[[zip file
  "/data/app/nl.assortimens.hardlooptrainingapp-1/base.apk"],nativeLibraryDirectories=[/data/app/nl.assortimens.hardlooptrainingapp-1/lib/x86,
  /vendor/lib, /system/lib]]"

How can I copy projects without errors or what should I do to fix those errors?

答: go to run-> rebuild project  and should work correct </p>

Title: How to copy projects in Android Studio?


问:
Populating a list of lists with random items
I have a list of lists with a certain range:

```<code>l = [["this", "is", "a"], ["list", "of"], ["lists", "that", "i", "want"], ["to", "copy"]]
</code>```

And a list of words:

```<code>words = ["lorem", "ipsum", "dolor", "sit", "amet", "id", "sint", "risus", "per", "ut", "enim", "velit", "nunc", "ultricies"]
</code>```

I need to create an exact replica of the list of lists, but with random terms picked from the other list.

This was the first thing that came to mind, but no dice.

```<code>for random.choice in words:
  for x in list:
    for y in x:
      y = random.choice
</code>```

Any ideas? Thank you in advance!

答:
You can use list comprehensions for this:

```<code>import random
my_list = [[1, 2, 3], [5, 6]]
words = ['hello', 'Python']

new_list = [[random.choice(words) for y in x] for x in my_list]
print(new_list)
</code>```

Output:

```<code>[['Python', 'Python', 'hello'], ['Python', 'hello']]
</code>```

This is equivalent to:

```<code>new_list = []
for x in my_list:
    subl = []
    for y in x:
        subl.append(random.choice(words))
    new_list.append(subl)
</code>```

With your example data:

```<code>my_list = [['this', 'is', 'a'], ['list', 'of'],
           ['lists', 'that', 'i', 'want'], ['to', 'copy']]

words = ['lorem', 'ipsum', 'dolor', 'sit', 'amet', 'id', 'sint', 'risus',
         'per', 'ut', 'enim', 'velit', 'nunc', 'ultricies']
new_list = [[random.choice(words) for y in x] for x in my_list]
print(new_list)
</code>```

Output:

```<code>[['enim', 'risus', 'sint'], ['dolor', 'lorem'], ['sint', 'nunc', 'ut', 'lorem'], ['ipsum', 'amet']]
</code>```

Body:
I have a list of lists with a certain range:

l = [["this", "is", "a"], ["list", "of"], ["lists", "that", "i", "want"], ["to", "copy"]]

And a list of words:

words = ["lorem", "ipsum", "dolor", "sit", "amet", "id", "sint", "risus", "per", "ut", "enim", "velit", "nunc", "ultricies"]

I need to create an exact replica of the list of lists, but with random terms picked from the other list.

This was the first thing that came to mind, but no dice.

for random.choice in words:
  for x in list:
    for y in x:
      y = random.choice

Any ideas? Thank you in advance!

Body:
You can use list comprehensions for this:

import random
my_list = [[1, 2, 3], [5, 6]]
words = ['hello', 'Python']

new_list = [[random.choice(words) for y in x] for x in my_list]
print(new_list)

Output:

[['Python', 'Python', 'hello'], ['Python', 'hello']]

This is equivalent to:

new_list = []
for x in my_list:
    subl = []
    for y in x:
        subl.append(random.choice(words))
    new_list.append(subl)

With your example data:

my_list = [['this', 'is', 'a'], ['list', 'of'],
           ['lists', 'that', 'i', 'want'], ['to', 'copy']]

words = ['lorem', 'ipsum', 'dolor', 'sit', 'amet', 'id', 'sint', 'risus',
         'per', 'ut', 'enim', 'velit', 'nunc', 'ultricies']
new_list = [[random.choice(words) for y in x] for x in my_list]
print(new_list)

Output:

[['enim', 'risus', 'sint'], ['dolor', 'lorem'], ['sint', 'nunc', 'ut', 'lorem'], ['ipsum', 'amet']]


问:
Asp.Net 3.5 Routing to Webservice?
I was looking for a way to route http://www.example.com/WebService.asmx to http://www.example.com/service/ using only the ASP.NET 3.5 Routing framework without needing to configure the IIS server.

Until now I have done what most tutorials told me, added a reference to the routing assembly, configured stuff in the web.config, added this to the Global.asax:

```<code>protected void Application_Start(object sender, EventArgs e)
{
    RouteCollection routes = RouteTable.Routes;

    routes.Add(
        "WebService",
        new Route("service/{*Action}", new WebServiceRouteHandler())
    );
}
</code>```

...created this class:

```<code>public class WebServiceRouteHandler : IRouteHandler
{
    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        // What now?
    }
}
</code>```

...and the problem is right there, I don't know what to do. The tutorials and guides I've read use routing for pages, not webservices. Is this even possible?

Ps: The route handler is working, I can visit /service/ and it throws the NotImplementedException I left in the GetHttpHandler method.

答:
Just thought I would round off this question with a bit more of a detailed solution based on the answer given by Markives that worked for me.

Firstly here is the route handler class which takes the virtual directory to your WebService as its constructor param.

```<code>public class WebServiceRouteHandler : IRouteHandler
{
    private string _VirtualPath;

    public WebServiceRouteHandler(string virtualPath)
    {
        _VirtualPath = virtualPath;
    }

    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        return new WebServiceHandlerFactory().GetHandler(HttpContext.Current,
            "*",
            _VirtualPath,
            HttpContext.Current.Server.MapPath(_VirtualPath));
    }
}
</code>```

and the actual usage of this class within the routey bit of Global.asax

```<code>routes.Add("SOAP",
    new Route("soap", new WebServiceRouteHandler("~/Services/SoapQuery.asmx")));
</code>```

Title: Asp.Net 3.5 Routing to Webservice?

Body:
I was looking for a way to route http://www.example.com/WebService.asmx to http://www.example.com/service/ using only the ASP.NET 3.5 Routing framework without needing to configure the IIS server.

Until now I have done what most tutorials told me, added a reference to the routing assembly, configured stuff in the web.config, added this to the Global.asax:

protected void Application_Start(object sender, EventArgs e)
{
    RouteCollection routes = RouteTable.Routes;

    routes.Add(
        "WebService",
        new Route("service/{*Action}", new WebServiceRouteHandler())
    );
}

...created this class:

public class WebServiceRouteHandler : IRouteHandler
{
    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        // What now?
    }
}

...and the problem is right there, I don't know what to do. The tutorials and guides I've read use routing for pages, not webservices. Is this even possible?

Ps: The route handler is working, I can visit /service/ and it throws the NotImplementedException I left in the GetHttpHandler method.

Body:
Just thought I would round off this question with a bit more of a detailed solution based on the answer given by Markives that worked for me.

Firstly here is the route handler class which takes the virtual directory to your WebService as its constructor param.

public class WebServiceRouteHandler : IRouteHandler
{
    private string _VirtualPath;

    public WebServiceRouteHandler(string virtualPath)
    {
        _VirtualPath = virtualPath;
    }

    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        return new WebServiceHandlerFactory().GetHandler(HttpContext.Current,
            "*",
            _VirtualPath,
            HttpContext.Current.Server.MapPath(_VirtualPath));
    }
}

and the actual usage of this class within the routey bit of Global.asax

routes.Add("SOAP",
    new Route("soap", new WebServiceRouteHandler("~/Services/SoapQuery.asmx")));


问:
regexp to match sequence if not starting and ending with a specific character
When it comes to regexps, I'm not very good at finding one that works and suits my needs.I need to match a word say foo if it is not included between a character say [ and another character say ]

```<code> "[foo] foo" // I need to replace foo with bar
 // expected result : "[foo] bar" but not "[bar] bar"
</code>```

I know how to match it if it is not followed by ]

```<code> "foo] foo".replace(/foo(!?\])/g,"bar")
</code>```

And I also know how to match it if it is not preceded by [

```<code> " [foo foo".replace(/(\[)?foo/g,function(_0,_1) {
      return _1:_0?"bar"
 })
</code>```

But I don't know how to put them together.Thank you!

答:
Please, try this to match a word between [ and ]</p>

```<code>"[foo] foo".match(/\[.*?\]/g)
</code>```

Body:
When it comes to regexps, I'm not very good at finding one that works and suits my needs.I need to match a word say foo if it is not included between a character say [ and another character say ]

 "[foo] foo" // I need to replace foo with bar
 // expected result : "[foo] bar" but not "[bar] bar"

I know how to match it if it is not followed by ]

 "foo] foo".replace(/foo(!?\])/g,"bar")

And I also know how to match it if it is not preceded by [

 " [foo foo".replace(/(\[)?foo/g,function(_0,_1) {
      return _1:_0?"bar"
 })

But I don't know how to put them together.Thank you!

Body:
Please, try this to match a word between [ and ]

"[foo] foo".match(/\[.*?\]/g)


问:
How to install node-v6.11.0-linux-x86.tar.xz in Ubuntu
I'm a windows user and I'm having a difficulty installing the latest version of NodeJS.

I've tried sudo apt-get install -y nodejs and it installed  v0.10.25 version.

Can someone guide me how to install the tar.xz file properly.

答:
Use nvm

It'll take care of everything.

Body:
Use nvm

It'll take care of everything.


问:
Re-host a website in JavaScript?

This is a unusual question (keep that in mind)

1. The idea.

There is a computer that has a website hosted on the web browser via JavaScript and other computers can connect to that website and access it, once that computer has loaded the website on it's browser then other computers can access it from that computer, so as long as there is a active user on the website at the moment running the JavaScript that is hosting it then the website is online. Once there is no one on it it goes offline can can't get online again.

2. The purpose

The purpose of a non server based website is that it would, well not have a server which can therefore cannot be taken down no matter what as long as the users use it, it cannot be traced too since you connect to it via different public IP addresses. How do you know what address you should connect to? I don't know yet, maybe logging the computers that have accessed it on the website source code and then pining those to see if they are online, not sure myself. All this allows for complete anonymity and no trace ability, but finding a way to refresh all the sites without immense computational power to dispose is also still a mystery for me.

3. The question

How do i host a website on the JavaScript that is available to execute on web browser or is it even possible. If it is not then is there a possibility to create a library for the JavaScript and embed it in the source code of the site? If that does not work, what way is there to make a P2P based website that can refresh at a modest speed?

3.1 The question (Re-clarified because some ZGljaw0K thought so)

How do i host a website on the JavaScript that is run on a web browser?

答:
This is not only possible, it's commonly done!

There are some caveats though.  First, to make peer-to-peer (P2P) connections in-browser, you need to use WebRTC.  To make a WebRTC connection, the browsers first have to communicate over a signalling channel to negotiate protocol version, any media channels (if used), and what addresses to connect with.  That signalling channel generally requires a server.  (There are some neat WebRTC signalling methods that use QR Codes to send data visually... but those only work if the devices' cameras can see the other screen, such as in the same room.)

Because of this requirement, and the extra overhead of distribution, P2P web serving is usually reserved for bandwidth intensive requests, such as HD video segments.  There are commercial products for this:  https://www.peer5.com/

Also, check out WebTorrent.  https://webtorrent.io/  There are many projects built off of it around what you are asking.

Title: Re-host a website in JavaScript?


问:
Is the type of a function parameter deducible?
I have a class which uses return code:

```<code>class MyClass
{
    // ...

public:
    // ValueType get_value() const;               // usual code
    ErrorCode get_value(ValueType& value) const;  // uses error code

   // ...
};
</code>```

Thus, the second form of get_value() actually provides the value as function parameter, rather than as return value.

Is it possible to deduce the type of the function parameter of get_value(), maybe using  decltype?

```<code>int main()
{
    // ...

    MyClass my_class;
    // auto val = my_class.get_value();  // okay: value has correct type

    declytype( /* something here */ ) value;
    const auto error = my_class.get_value( value );

    // ...
}
</code>```

答:
A more compact solution that doesn't require to fully define a new type.

You can use a function declaration (no definition required) and decltype to do that.

It follows a minimal, working example:

```<code>#include<type_traits>

template<typename R, typename C, typename T>
constexpr T f(R(C::*)(T));

struct S {
    void f(int) {}
};

int main() {
    static_assert(std::is_same<int, decltype(f(&S::f))>::value, "!");
}
</code>```

You can also extend it to multiple parameters quite easily by using a tuple:

```<code>template<typename R, typename C, typename... T>
constexpr std::tuple<T...> f(R(C::*)(T...));
</code>```

In C++17 you can also get a more user-friendly type handler using auto template parameter:

```<code>template<auto M>
using Type = decltype(f(M));
</code>```

And use it as:

```<code>static_assert(std::is_same_v<int, Type<&S::f>>);
</code>```

Body:
I have a class which uses return code:

class MyClass
{
    // ...

public:
    // ValueType get_value() const;               // usual code
    ErrorCode get_value(ValueType& value) const;  // uses error code

   // ...
};

Thus, the second form of get_value() actually provides the value as function parameter, rather than as return value.

Is it possible to deduce the type of the function parameter of get_value(), maybe using  decltype?

int main()
{
    // ...

    MyClass my_class;
    // auto val = my_class.get_value();  // okay: value has correct type

    declytype( /* something here */ ) value;
    const auto error = my_class.get_value( value );

    // ...
}

Body:
A more compact solution that doesn't require to fully define a new type.

You can use a function declaration (no definition required) and decltype to do that.

It follows a minimal, working example:

#include<type_traits>

template<typename R, typename C, typename T>
constexpr T f(R(C::*)(T));

struct S {
    void f(int) {}
};

int main() {
    static_assert(std::is_same<int, decltype(f(&S::f))>::value, "!");
}

You can also extend it to multiple parameters quite easily by using a tuple:

template<typename R, typename C, typename... T>
constexpr std::tuple<T...> f(R(C::*)(T...));

In C++17 you can also get a more user-friendly type handler using auto template parameter:

template<auto M>
using Type = decltype(f(M));

And use it as:

static_assert(std::is_same_v<int, Type<&S::f>>);


问:
Programmatically generating BigQuery schema in Beam pipeline
I have a collection of homogeneous dicts, how do I write them to BigQuery without knowing the schema?

The BigQuerySink requires that I specify the schema when I construct it. But, I don't know the schema: it's defined by the keys of the dicts I'm trying to write.

Is there a way to have my pipeline infer the schema, and then provide it back (as a sideinput?) to the sink?

For example:

```<code># Create a PCollection of dicts, something like
# {'field1': 'myval', 'field2': 10}
data = (p | 'generate_data' >> beam.ParDo(CreateData())

# Infer the schema from the data
# Generates a string for each element (ok to assume all dict keys equal)
# "field1:STRING, field2:INTEGER"
schema = (data
  | 'infer_schema' >> beam.ParDo(InferSchema())
  | 'sample_one'   >> beam.combiners.Sample.FixedSizeGlobally(1))
</code>```

But then, how do I feed the schema as a parameter to the BigQuerySink, and use that in a beam.io.Write?

I know this isn't correct, but what I want to do is:

```<code>sink = BigQuerySink(tablename, dataset, project, schema=Materialize(schema))
p | 'write_bigquery' >> beam.io.Write(sink)
</code>```

tl;dr
Is there a way to create and write a bigquery table from apache beam programmatically inferring the schema from the data?

答:
Assuming that your schema can change frequently, it may work better for you to keep the data in a more generic form.

For example, your row may consist of a single repeated record (your dictionary entries).

The record schema looks like:
key (STRING) | optional string_val (STRING) | optional int_val (INTEGER) optional double_val (DOUBLE) | optional boolean_val (BOOLEAN) | ...

Then you can write queries that scan your records by type. This is somewhat less efficient (because you'll have to scan rows that you might otherwise be able to skip if they were in different columns), but entirely avoids specifying your schema up-front.

Body:
I have a collection of homogeneous dicts, how do I write them to BigQuery without knowing the schema?

The BigQuerySink requires that I specify the schema when I construct it. But, I don't know the schema: it's defined by the keys of the dicts I'm trying to write.

Is there a way to have my pipeline infer the schema, and then provide it back (as a sideinput?) to the sink?

For example:

# Create a PCollection of dicts, something like
# {'field1': 'myval', 'field2': 10}
data = (p | 'generate_data' >> beam.ParDo(CreateData())

# Infer the schema from the data
# Generates a string for each element (ok to assume all dict keys equal)
# "field1:STRING, field2:INTEGER"
schema = (data
  | 'infer_schema' >> beam.ParDo(InferSchema())
  | 'sample_one'   >> beam.combiners.Sample.FixedSizeGlobally(1))

But then, how do I feed the schema as a parameter to the BigQuerySink, and use that in a beam.io.Write?

I know this isn't correct, but what I want to do is:

sink = BigQuerySink(tablename, dataset, project, schema=Materialize(schema))
p | 'write_bigquery' >> beam.io.Write(sink)

tl;dr
Is there a way to create and write a bigquery table from apache beam programmatically inferring the schema from the data?


问:
Should consecutive whitespace in an XML file be ignored by an XML reader?
At my work we have our own XML classes which build a DOM, but I'm not sure how consecutive whitespace should be handled?

e.g.

```<code><some-text>
Hello     World
</some-text>
</code>```

When this is read into the DOM, should the text node include the consecutive whitespace inbetween Hello and World or just reduce it to one space?

Or should the XML source be written like this:

```
<some-text>
Hello     World
</some-text>
```

or if not   than perhaps   ?

OwnerDisplayName: Ben Daniel

Body:
At my work we have our own XML classes which build a DOM, but I'm not sure how consecutive whitespace should be handled?

e.g.

<some-text>
Hello     World
</some-text>

When this is read into the DOM, should the text node include the consecutive whitespace inbetween Hello and World or just reduce it to one space?

Or should the XML source be written like this:

<some-text>
Hello     World
</some-text>

or if not   than perhaps   ?

LastEditorDisplayName: Ben Daniel

Body:
&nbsp; is a HTML entity and nothing to do with XML itself.

To answer your question though, i would treat that as significant. Even the HTML DOM treats consecutive spaces as significant, it's just that it only visually renders one space. How it appears in the DOM and how it appears on your screen are two entirely different things.

OwnerDisplayName: nickf


问:
How to get the JSON with duplicate keys completely in javascript
I am trying to get JSON from the url, But in the response object duplicate keys are removed. Is there any way to fetch it completely without removing the duplicate keys? Here is my js Code

```<code>$('document').ready(function(){
    var s = $.getJSON("new.json");
    console.log(s);
});
</code>```

following is my new.json

```<code>{
"s": "wae",
"s": "asd"
}
</code>```

But in console i am getting the json Object as follows

```<code>responseJSON: Object
s: "asd"
</code>```

Thanks in advance

答:
This is not possible with JSON.parse(). I believe that the more modern ES spec states that subsequent keys override earlier ones.

However, the JSON spec does not disallow JSON like this. And there are alternative parsers and serializers which can produce and consume such JSON from within JavaScript. For example, you can use the SAX-style JSON parser clarinet:

```<code>const clarinet = require('clarinet');

const parser = clarinet.parser();
const result = [];
parser.onkey = parser.onopenobject = k => {
    result.push({key: k, value: null});
};
parser.onvalue = v => {
    result[result.length - 1].value = v;
};
parser.write('{"a": "1", "a": "2"}').close();

console.log(result);
// [ { key: 'a', value: '1' }, { key: 'a', value: '2' } ]
</code>```

If you are wondering about how to use require() from the browser, learn how to use webpack.

Body:
I am trying to get JSON from the url, But in the response object duplicate keys are removed. Is there any way to fetch it completely without removing the duplicate keys? Here is my js Code

$('document').ready(function(){
    var s = $.getJSON("new.json");
    console.log(s);
});

following is my new.json

{
"s": "wae",
"s": "asd"
}

But in console i am getting the json Object as follows

responseJSON: Object
s: "asd"

Thanks in advance

Body:
This is not possible with JSON.parse(). I believe that the more modern ES spec states that subsequent keys override earlier ones.

However, the JSON spec does not disallow JSON like this. And there are alternative parsers and serializers which can produce and consume such JSON from within JavaScript. For example, you can use the SAX-style JSON parser clarinet:

const clarinet = require('clarinet');

const parser = clarinet.parser();
const result = [];
parser.onkey = parser.onopenobject = k => {
    result.push({key: k, value: null});
};
parser.onvalue = v => {
    result[result.length - 1].value = v;
};
parser.write('{"a": "1", "a": "2"}').close();

console.log(result);
// [ { key: 'a', value: '1' }, { key: 'a', value: '2' } ]

If you are wondering about how to use require() from the browser, learn how to use webpack.


问:
Generic User Control designer error: a new guard page for the stack cannot be created
I have a Generic UserControl as blow:

```<code> public partial class TreeNodeView<C,T>: UserControl
    {
        public TreeNodeView(C foo, T foo1)
        {
            InitializeComponent();
        }
    }
</code>```

Either change the partial class as below:

```<code>partial class TreeNodeView<C, T>
</code>```

And because get this error in partial designer class:

Using the generic type 'TreeNodeView' requires 2 type arguments

in line :

```<code>System.ComponentModel.ComponentResourceManager resources =
new System.ComponentModel.ComponentResourceManager(typeof(TreeNodeView));
</code>```

change it to:

```<code>System.ComponentModel.ComponentResourceManager resources = new
System.ComponentModel.ComponentResourceManager(typeof(TreeNodeView<C,T>));
</code>```

The code compile successful but when want to see the designer i see ma messagebox:

a new guard page for the stack cannot be created

and when press OK visual studio close immediately. Anybody know whats my wrong?

答:
You can't design a control which is a generic type. This is not supported by the WinForms Designer. </p>

<p>Either change your control to a non-generic type and use generic methods instead, or try to design a derived type of which is not generic anymore. </p>

Body:
I have a Generic UserControl as blow:

 public partial class TreeNodeView<C,T>: UserControl
    {
        public TreeNodeView(C foo, T foo1)
        {
            InitializeComponent();
        }
    }

Either change the partial class as below:

partial class TreeNodeView<C, T>

And because get this error in partial designer class:

Using the generic type 'TreeNodeView' requires 2 type arguments

in line :

System.ComponentModel.ComponentResourceManager resources =
new System.ComponentModel.ComponentResourceManager(typeof(TreeNodeView));

change it to:

System.ComponentModel.ComponentResourceManager resources = new
System.ComponentModel.ComponentResourceManager(typeof(TreeNodeView<C,T>));

The code compile successful but when want to see the designer i see ma messagebox:

a new guard page for the stack cannot be created

and when press OK visual studio close immediately. Anybody know whats my wrong?

Body:
You can't design a control which is a generic type. This is not supported by the WinForms Designer.

Either change your control to a non-generic type and use generic methods instead, or try to design a derived type of which is not generic anymore.


问:
Swap bootstrap text class for a google material icons
OK to preface I am new to javascript so this may not be the optimal way of doing this...

I am trying to change the color of a material icon when it is clicked. basically I am trying to turn it on and off. The problem is my code while it does find the icon does not read the class...I have tried adding a class, using an id, even a name and it fails to read it. I have see other responses where images are swapped and have tried with the image swap but I just want the color to change.

JAVASCRIPT:

```<code>function updateFavorites()
{
if($(this).find($("#staricon")).hasClass('text-warning'))
{
 $(this).find($("#staricon")).addClass('text-warning');

}
else
{
$(this).find($("#staricon")).removeClass('text-warning');
}
}
</code>```

HTML:

```<code><a  class=" stats pull-right " href="javacript:void" ><span
onclick="updateFavorites()"><i id="staricon" class="text-warning material-
icons " title="Favorite" >star</i></span></a>
</code>```

答:
thank you all for the help...i got it to work using the following:

JAVASCRIPT

```<code>updateFavorites(id){
if($(this).find('#staricon'+id)){
    if($('#staricon'+id).hasClass('star-color')) {
        $('#staricon'+id).removeClass('star-color');
    }
    else {
        $('#staricon'+id).addClass('star-color');
    }
}
}
</code>```

HTML:

```<code><a  class=" stats pull-right " href="javacript:void" ><span id="staricon' . $story_id .'"   onclick="updateFavorites(' . $story_id . ')"><i  class=" material-icons " title="Favorite" >star</i></span></a>
</code>```

Body:
OK to preface I am new to javascript so this may not be the optimal way of doing this...

I am trying to change the color of a material icon when it is clicked. basically I am trying to turn it on and off. The problem is my code while it does find the icon does not read the class...I have tried adding a class, using an id, even a name and it fails to read it. I have see other responses where images are swapped and have tried with the image swap but I just want the color to change.

JAVASCRIPT:

function updateFavorites()
{
if($(this).find($("#staricon")).hasClass('text-warning'))
{
 $(this).find($("#staricon")).addClass('text-warning');

}
else
{
$(this).find($("#staricon")).removeClass('text-warning');
}
}

HTML:

star

Body:
thank you all for the help...i got it to work using the following:

JAVASCRIPT

updateFavorites(id){
if($(this).find('#staricon'+id)){
    if($('#staricon'+id).hasClass('star-color')) {
        $('#staricon'+id).removeClass('star-color');
    }
    else {
        $('#staricon'+id).addClass('star-color');
    }
}
}

HTML:

<a  class=" stats pull-right " href="javacript:void" ><span id="staricon' . $story_id .'"   onclick="updateFavorites(' . $story_id . ')"><i  class=" material-icons " title="Favorite" >star</i></span></a>


问:
Passing a PHP variable to JavaScript in a Blade template
is there any ways that JavaScript can get the variable from the controller in a Laravel Blade template?

Example:
I have the code below:

$langs = Language::all();
return View::make('NAATIMockTest.Admin.Language.index',compact('langs'));
```
<p>Can I get <code>$langs</code> and pass it to JavaScript? I already used PHP-Vars-To-Js-Transformer. But when I use <code>JavaScript::put()</code> for two functions in the controller. It didn't work. Any help?</p>
<p>This is my create function in the controller:</p>
<pre class="lang-php prettyprint-override"><code>public function create()
{
    $names = $this->initLang();
    Javascript::put([
        'langs' => $names
    ]);

    return View::make('NAATIMockTest.Admin.Language.create',compact('names'));
}
</code>```

this is my view:

@extends('AdLayout')
@section('content')

Create language

                    {!! Form::open() !!}

                            {!! Form::label('Name','Language: ') !!}
                            <input type="text" name="searchLanguage" ng-model="searchLanguage">

                        <select name="Name[]" multiple size="10" ng-model="lang" ng-click="show()">
                            <option value="@{{v}}" ng-repeat="(k,v) in languages | filter:searchLanguage">
                                @{{v}}
                            </option>
                        </select>

                            {!! Form::submit('Create',['class'=>'btn btn-primary']) !!}
                            {!!   Html::linkAction('NAATIMockTest\LanguageController@index', 'Back', null, array('class' => 'btn btn-primary')) !!}

                    {!! Form::close() !!}

@endsection
```
<p>my javascript.php in config folder:</p>
<pre class="lang-php prettyprint-override"><code><?php
return [
    'bind_js_vars_to_this_view' => 'footer',
    'bind_js_vars_to_this_view' => 'NAATIMockTest.Admin.Language.create',
    'bind_js_vars_to_this_view' => 'NAATIMockTest.Admin.Language.edit',

    'js_namespace' => 'window',
];
</code>```

The idea is:
I have a table language in MySQL. I want to show the dropdown list with multiple attributes to choose, and I also want to search with angularjs as well. That's why I want to pass the variable from the controller to JavaScript. Additionally, I have the function inside LanguageController called initLang to check if any language is exist inside the database, it isn't displayed inside the dropdown list in create the view.

答:
Standard PHP objects

The best way to provide PHP variables to JavaScript is json_encode. When using Blade you can do it like following:

```<code><script>
    var bool = {!! json_encode($bool) !!};
    var int = {!! json_encode($int) !!};
    /* ... */
    var array = {!! json_encode($array_without_keys) !!};
    var object = {!! json_encode($array_with_keys) !!};
    var object = {!! json_encode($stdClass) !!};
</script>
</code>```

Displaying unescaped data - Laravel docs

json_encode - PHP docs

There is also a Blade directive for decoding to JSON. I'm not sure since which version of Laravel but in 5.5 it is available. Use it like following:

```<code><script>
    var array = @json($array);
</script>
</code>```

Blade Templates - Laravel 5.5 docs

Jsonable's

When using Laravel objects e.g. Collection or Model you should use the ->toJson() method. All those classes that implements the \Illuminate\Contracts\Support\Jsonable interface supports this method call. The call returns automatically JSON.

```<code><script>
    var collection = {!! $collection->toJson() !!};
    var model = {!! $model->toJson() !!};
</script>
</code>```

When using Model class you can define the $hidden property inside the class and those will be filtered in JSON. The $hidden property, as its name describs, hides sensitive content. So this mechanism is the best for me. Do it like following:

```<code>class User extends Model
{
    /* ... */

    protected $hidden = [
        'password', 'ip_address' /* , ... */
    ];

    /* ... */
}
</code>```

And somewhere in your view

```<code><script>
    var user = {!! $user->toJson() !!};
</script>
</code>```

Serializing to JSON - Laravel docs

ContentLicense: CC BY-SA 4.0

Body:
is there any ways that JavaScript can get the variable from the controller in a Laravel Blade template?

Example:
I have the code below:

$langs = Language::all();
return View::make('NAATIMockTest.Admin.Language.index',compact('langs'));

Can I get $langs and pass it to JavaScript? I already used PHP-Vars-To-Js-Transformer. But when I use JavaScript::put() for two functions in the controller. It didn't work. Any help?

This is my create function in the controller:

public function create()
{
    $names = $this->initLang();
    Javascript::put([
        'langs' => $names
    ]);

    return View::make('NAATIMockTest.Admin.Language.create',compact('names'));
}

this is my view:

@extends('AdLayout')
@section('content')

Create language

                    {!! Form::open() !!}

                            {!! Form::label('Name','Language: ') !!}
                            <input type="text" name="searchLanguage" ng-model="searchLanguage">

                        <select name="Name[]" multiple size="10" ng-model="lang" ng-click="show()">
                            <option value="@{{v}}" ng-repeat="(k,v) in languages | filter:searchLanguage">
                                @{{v}}
                            </option>
                        </select>

                            {!! Form::submit('Create',['class'=>'btn btn-primary']) !!}
                            {!!   Html::linkAction('NAATIMockTest\LanguageController@index', 'Back', null, array('class' => 'btn btn-primary')) !!}

                    {!! Form::close() !!}

@endsection

my javascript.php in config folder:

<?php
return [
    'bind_js_vars_to_this_view' => 'footer',
    'bind_js_vars_to_this_view' => 'NAATIMockTest.Admin.Language.create',
    'bind_js_vars_to_this_view' => 'NAATIMockTest.Admin.Language.edit',

    'js_namespace' => 'window',
];

The idea is:
I have a table language in MySQL. I want to show the dropdown list with multiple attributes to choose, and I also want to search with angularjs as well. That's why I want to pass the variable from the controller to JavaScript. Additionally, I have the function inside LanguageController called initLang to check if any language is exist inside the database, it isn't displayed inside the dropdown list in create the view.

Body:
Standard PHP objects

The best way to provide PHP variables to JavaScript is json_encode. When using Blade you can do it like following:

<script>
    var bool = {!! json_encode($bool) !!};
    var int = {!! json_encode($int) !!};
    /* ... */
    var array = {!! json_encode($array_without_keys) !!};
    var object = {!! json_encode($array_with_keys) !!};
    var object = {!! json_encode($stdClass) !!};
</script>

Displaying unescaped data - Laravel docs

json_encode - PHP docs

There is also a Blade directive for decoding to JSON. I'm not sure since which version of Laravel but in 5.5 it is available. Use it like following:

<script>
    var array = @json($array);
</script>

Blade Templates - Laravel 5.5 docs

Jsonable's

When using Laravel objects e.g. Collection or Model you should use the ->toJson() method. All those classes that implements the \Illuminate\Contracts\Support\Jsonable interface supports this method call. The call returns automatically JSON.

<script>
    var collection = {!! $collection->toJson() !!};
    var model = {!! $model->toJson() !!};
</script>

When using Model class you can define the $hidden property inside the class and those will be filtered in JSON. The $hidden property, as its name describs, hides sensitive content. So this mechanism is the best for me. Do it like following:

class User extends Model
{
    /* ... */

    protected $hidden = [
        'password', 'ip_address' /* , ... */
    ];

    /* ... */
}

And somewhere in your view

<script>
    var user = {!! $user->toJson() !!};
</script>

Serializing to JSON - Laravel docs


问:
What is the right syntax for launching an executable in Appveyor?
I'm trying to start the Azure Storage Emulator in an AppVeyor instance but I can't find the right syntax. I've tried this:

```<code>- ps: "C:\Program Files (x86)\Microsoft SDKs\Azure\Storage Emulator\AzureStorageEmulator.exe" start
</code>```

and this:

```<code>- ps: & "C:\Program Files (x86)\Microsoft SDKs\Azure\Storage Emulator\AzureStorageEmulator.exe" start
</code>```

and this:

```<code>- "C:\Program Files (x86)\Microsoft SDKs\Azure\Storage Emulator\AzureStorageEmulator.exe" start
</code>```

All fail with various unhelpful YAML parsing errors.

答:
```<code>- cmd: '"C:\Program Files (x86)\Microsoft SDKs\Azure\Storage Emulator\AzureStorageEmulator.exe" start'
</code>```

or simple:

```<code>- '"C:\Program Files (x86)\Microsoft SDKs\Azure\Storage Emulator\AzureStorageEmulator.exe" start'
</code>```

or with PowerShell:

```<code>- ps: '& "C:\Program Files (x86)\Microsoft SDKs\Azure\Storage Emulator\AzureStorageEmulator.exe" start'
</code>```

Easiest way to avoid YAML parsing errors is to do initial configuration in UI and then press Export YAML. GitHub search for appveyor.yml <something> often brings useful results too.

Body:
I'm trying to start the Azure Storage Emulator in an AppVeyor instance but I can't find the right syntax. I've tried this:

- ps: "C:\Program Files (x86)\Microsoft SDKs\Azure\Storage Emulator\AzureStorageEmulator.exe" start

and this:

- ps: & "C:\Program Files (x86)\Microsoft SDKs\Azure\Storage Emulator\AzureStorageEmulator.exe" start

and this:

- "C:\Program Files (x86)\Microsoft SDKs\Azure\Storage Emulator\AzureStorageEmulator.exe" start

All fail with various unhelpful YAML parsing errors.

Body:
- cmd: '"C:\Program Files (x86)\Microsoft SDKs\Azure\Storage Emulator\AzureStorageEmulator.exe" start'

or simple:

- '"C:\Program Files (x86)\Microsoft SDKs\Azure\Storage Emulator\AzureStorageEmulator.exe" start'

or with PowerShell:

- ps: '& "C:\Program Files (x86)\Microsoft SDKs\Azure\Storage Emulator\AzureStorageEmulator.exe" start'

Easiest way to avoid YAML parsing errors is to do initial configuration in UI and then press Export YAML. GitHub search for appveyor.yml <something> often brings useful results too.


问:
NSString not showing all characters in NSLog
I converted a std::string to NSString* by :

```<code>NSString *BufferString = [[NSString alloc] initWithCString:allBufferString.c_str()
                                                    encoding:[NSString defaultCStringEncoding]];
</code>```

The code cout<<allBufferString; shows the whole string in Log.
But NSLog(@"%@ ",BufferString) doesn't show all the data instead ends with
0.061523 -0.03<...> in the log .

So two questions:

If I send the NSString as a JSON string. Will all data be there?

How can I print all the data in the NSLog ?

答:
It is Xcode bug (or feature). You can print logs as in this post</p>

```<code>#define NSLog(FORMAT, ...) printf("%s\n", [[NSString stringWithFormat:FORMAT, ##__VA_ARGS__] UTF8String]);
</code>```

Body:
I converted a std::string to NSString* by :

NSString *BufferString = [[NSString alloc] initWithCString:allBufferString.c_str()
                                                    encoding:[NSString defaultCStringEncoding]];

The code cout<<allBufferString; shows the whole string in Log.
But NSLog(@"%@ ",BufferString) doesn't show all the data instead ends with
0.061523 -0.03<...> in the log .

So two questions:

If I send the NSString as a JSON string. Will all data be there?

How can I print all the data in the NSLog ?

Body:
It is Xcode bug (or feature). You can print logs as in this post

#define NSLog(FORMAT, ...) printf("%s\n", [[NSString stringWithFormat:FORMAT, ##__VA_ARGS__] UTF8String]);


问:
How do I get and set an object in session scope in JSF?
I need to persist just one object in session scope of my JSF application. Where do I define a session variable, and how do I get and set it from either a view file or backing bean? </p>

答:
Two general ways:

Store it in ExternalContext#getSessionMap()

```<code>ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
Map<String, Object> sessionMap = externalContext.getSessionMap();
sessionMap.put("somekey", yourVariable);
</code>```

And then later:

```<code>SomeObject yourVariable = (SomeObject) sessionMap.get("somekey");
</code>```

Or, make it a property of a @SessionScoped bean which you inject in your @RequestScoped bean.

```<code>sessionBean.setSomeVariable(yourVariable);
</code>```

And then later:

```<code>SomeObject yourVariable = sessionBean.getSomeVariable();
</code>```

You can get a @Named @SessionScoped into a @Named @RequestScoped via @Inject.

```<code>@Inject
private SessionBean sessionBean;
</code>```

Or, if you're not using CDI yet, you can get a @ManagedBean @SessionScoped into a @ManagedBean @RequestScoped via @ManagedProperty.

```<code>@ManagedProperty("#{sessionBean}")
private SessionBean sessionBean; // +getter+setter
</code>```

Body:
Two general ways:

Store it in ExternalContext#getSessionMap()

ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
Map<String, Object> sessionMap = externalContext.getSessionMap();
sessionMap.put("somekey", yourVariable);

And then later:

SomeObject yourVariable = (SomeObject) sessionMap.get("somekey");

Or, make it a property of a @SessionScoped bean which you inject in your @RequestScoped bean.

sessionBean.setSomeVariable(yourVariable);

And then later:

SomeObject yourVariable = sessionBean.getSomeVariable();

You can get a @Named @SessionScoped into a @Named @RequestScoped via @Inject.

@Inject
private SessionBean sessionBean;

Or, if you're not using CDI yet, you can get a @ManagedBean @SessionScoped into a @ManagedBean @RequestScoped via @ManagedProperty.

@ManagedProperty("#{sessionBean}")
private SessionBean sessionBean; // +getter+setter


问:
VB.Net: Inserting Data Validation In Excel Cell
I'm trying to programmatically add a drop down box to a cell in an Excel Worksheet. For a very simple example I just want the drop down box to give the option of "Yes" or "No". After Googling, it sounds like I can do this rather easily by inserting data validation on the cell.

I'm running across the issue of finding an example on how to do this. All the examples I've found are outdated, too complex, or not in VB.Net. When I say too complex, I mean it's not a simple "Yes" "No" situation. They are using actual columns in a different worksheet.

答:
If you just want a simple in-cell yes/no dropdown, you just have to declare a range and add a validation rule to it. Microsoft has a bit of documentation on that here, but as with most interop docs it's a little sparse...so here's a snippet showing how a validation list can be added:</p>

```<code>    'Imports Microsoft.Office.Interop.Excel

    Dim xlApp As New Excel.Application
    xlApp.Visible = True
    Dim xlWorkbooks As Excel.Workbooks = xlApp.Workbooks
    Dim xlWorkbook As Excel.Workbook = xlWorkbooks.Add
    Dim xlWorksheet As Excel.Worksheet = CType(xlWorkbook.Worksheets(1), Excel.Worksheet)

    Dim xlRng As Excel.Range = xlWorksheet.Cells(1, 1)
    With xlRng.Validation
        .Add(Type:=Excel.XlDVType.xlValidateList, _
             AlertStyle:=Excel.XlDVAlertStyle.xlValidAlertStop, _
             Operator:=Excel.XlFormatConditionOperator.xlBetween, _
             Formula1:="Yes,No")
        .IgnoreBlank = True
        .InCellDropdown = True
    End With

    System.Runtime.InteropServices.Marshal.ReleaseComObject(xlRng)
    System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorksheet)
    System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkbook)
    System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkbooks)
    System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp)
</code>```

Body:
If you just want a simple in-cell yes/no dropdown, you just have to declare a range and add a validation rule to it. Microsoft has a bit of documentation on that here, but as with most interop docs it's a little sparse...so here's a snippet showing how a validation list can be added:

    'Imports Microsoft.Office.Interop.Excel

    Dim xlApp As New Excel.Application
    xlApp.Visible = True
    Dim xlWorkbooks As Excel.Workbooks = xlApp.Workbooks
    Dim xlWorkbook As Excel.Workbook = xlWorkbooks.Add
    Dim xlWorksheet As Excel.Worksheet = CType(xlWorkbook.Worksheets(1), Excel.Worksheet)

    Dim xlRng As Excel.Range = xlWorksheet.Cells(1, 1)
    With xlRng.Validation
        .Add(Type:=Excel.XlDVType.xlValidateList, _
             AlertStyle:=Excel.XlDVAlertStyle.xlValidAlertStop, _
             Operator:=Excel.XlFormatConditionOperator.xlBetween, _
             Formula1:="Yes,No")
        .IgnoreBlank = True
        .InCellDropdown = True
    End With

    System.Runtime.InteropServices.Marshal.ReleaseComObject(xlRng)
    System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorksheet)
    System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkbook)
    System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkbooks)
    System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp)


问:
Input not binding correctly with Vue.js
I'm still relatively new to Vue.js and am having an issue binding one of my inputs to my viewmodel.

Here is my JavaScript:

```<code>var viewModel = new Vue({
    el: "#InventoryContainer",
    data: {
        upcCode: "",
        component: {
            Name: ""
        }
    },
    methods: {
        upcEntered: function (e) {
            if (this.upcCode.length > 0){
                $.ajax({
                    url: "/Component/GetByUpc",
                    type: "GET",
                    data: {
                        upc: this.upcCode
                    }
                }).done(function (response) {
                    if (response.exists) {
                        $("#ComponentInformation").toggleClass("hidden");
                        this.component = response.component;
                    } else {
                        alert("No component found.");
                    }
                });
            }
        }
    }
});
</code>```

Here is my HTML:

```<code><div class="form-horizontal row">
    <div class="col-sm-12">
        <div class="form-group">
            <label class="control-label col-md-4">UPC Code</label>
            <div class="col-md-8">
                <input id="ComponentUPC" class="form-control" placeholder="Scan or enter UPC Code" v-on:blur="upcEntered" v-model="upcCode" />
            </div>
        </div>

        <div id="ComponentInformation" class="hidden">
            <input type="text" class="form-control" readonly v-model="component.Name" />
        </div>
    </div>
</div>
</code>```

Now the issue is that even when I enter a valid UPC code and I assign the component to my ViewModel, the input that is bound to component.Name does not update with the component name. And when I enter into the console viewModel.component.Name I can see that it returns "".

But if I put an alert in my ajax.done function after I've assigned the component and it looks like this alert(this.component.Name) it alerts the name of the component.

Any ideas of where I'm going wrong here?

答:
in order for vue to work you need to define the parent container with id InventoryContainer

```<code><div id="InventoryContainer" class="form-horizontal row">
    <div class="col-sm-12">
        <div class="form-group">
 ....
</code>```

here is the updated code: https://jsfiddle.net/hdqdmscv/
here is the updated fiddle based on your comment

https://jsfiddle.net/hdqdmscv/2/

(replace this with name of vue variable in ajax)

Title: Input not binding correctly with Vue.js

Body:
I'm still relatively new to Vue.js and am having an issue binding one of my inputs to my viewmodel.

Here is my JavaScript:

var viewModel = new Vue({
    el: "#InventoryContainer",
    data: {
        upcCode: "",
        component: {
            Name: ""
        }
    },
    methods: {
        upcEntered: function (e) {
            if (this.upcCode.length > 0){
                $.ajax({
                    url: "/Component/GetByUpc",
                    type: "GET",
                    data: {
                        upc: this.upcCode
                    }
                }).done(function (response) {
                    if (response.exists) {
                        $("#ComponentInformation").toggleClass("hidden");
                        this.component = response.component;
                    } else {
                        alert("No component found.");
                    }
                });
            }
        }
    }
});

Here is my HTML:

            UPC Code

                <input id="ComponentUPC" class="form-control" placeholder="Scan or enter UPC Code" v-on:blur="upcEntered" v-model="upcCode" />

            <input type="text" class="form-control" readonly v-model="component.Name" />

Now the issue is that even when I enter a valid UPC code and I assign the component to my ViewModel, the input that is bound to component.Name does not update with the component name. And when I enter into the console viewModel.component.Name I can see that it returns "".

But if I put an alert in my ajax.done function after I've assigned the component and it looks like this alert(this.component.Name) it alerts the name of the component.

Any ideas of where I'm going wrong here?

Body:
in order for vue to work you need to define the parent container with id InventoryContainer

<div id="InventoryContainer" class="form-horizontal row">
    <div class="col-sm-12">
        <div class="form-group">
 ....

here is the updated code: https://jsfiddle.net/hdqdmscv/
here is the updated fiddle based on your comment

https://jsfiddle.net/hdqdmscv/2/

(replace this with name of vue variable in ajax)


答:
You need the following regex:

```<code>(?<!\[)foo(?!])
</code>```

it has negative lookbehind for [ and negative lookahead for ].

Title: regexp to match sequence if not starting and ending with a specific character

Body:
When it comes to regexps, I'm not very good at finding one that works and suits my needs.I need to match a word say foo if it is not included between a character say [ and another character say ]

 "[foo] foo" // I need to replace foo with bar
 // expected result : "[foo] bar" but not "[bar] bar"

I know how to match it if it is not followed by ]

 "foo] foo".replace(/foo(!?\])/g,"bar")

And I also know how to match it if it is not preceded by [

 " [foo foo".replace(/(\[)?foo/g,function(_0,_1) {
      return _1:_0?"bar"
 })

But I don't know how to put them together.Thank you!

Body:
You need the following regex:

(?<!\[)foo(?!])

it has negative lookbehind for [ and negative lookahead for ].