问:
iOS Swift: Setting minute to 0 for my date object
First my date is in string format as : "06-04-2017 06:28:17 PM"

And then i converted to Date() using:

```<code>let formatter = DateFormatter()
formatter.dateFormat = "dd-MM-yyyy hh:mm:ss a"
formatter.timeZone = TimeZone(abbreviation: "GMT")
let startdate = formatter.date(from: sdate!)
print(startdate)
</code>```

This is the output Date from above:

 startdate = 2017-04-06 18:28:17 +0000

But when I try to set my minute to value 0 with the following code .
I get my day changed .

```<code>let calender = Calendar.current
calendar.timeZone = TimeZone(abbreviation: "UTC")!
let date =  calender.date(bySettingHour: Int(hour)!, minute: 00, second: 00, of: startdate!)
print(date)
</code>```

OUTPUT: 2017-04-07 12:15:00 +0000

My timezone is +5:45 , after I am setting that timezone . I am getting the same bug .

Any help .
Highly appreciated.

With the following code I get the date same :

```<code>let formatter = DateFormatter()
formatter.dateFormat = "dd-MM-yyyy hh:mm:ss a"
formatter.timeZone = TimeZone(abbreviation: "GMT")
let startdate = formatter.date(from: sdate!)
print(startdate)
</code>```

**But I can't set it's minute to 0 here. **

答:
Sorry I'm writing from the mobile so the code could be not the exact one but you will find the functions easily.

Before you print the date, convert it to date components using calendar; then set the dateComponents.minute value to 0 and reconvert it into a date:

```<code>let dateComponents = Calendar.current.dateComponents(fromDate: yourDate)
dateComponents.minute = 0
let finishedDate = Calendar.current.date(fromComponents: dateComponents)
print(finishedDate)
</code>```

Oh yeah and I recommend to set the time zone to TimeZone.current unless you want to use a specific time zone only!

Body:
First my date is in string format as : "06-04-2017 06:28:17 PM"

And then i converted to Date() using:

let formatter = DateFormatter()
formatter.dateFormat = "dd-MM-yyyy hh:mm:ss a"
formatter.timeZone = TimeZone(abbreviation: "GMT")
let startdate = formatter.date(from: sdate!)
print(startdate)

This is the output Date from above:

 startdate = 2017-04-06 18:28:17 +0000

But when I try to set my minute to value 0 with the following code .
I get my day changed .

let calender = Calendar.current
calendar.timeZone = TimeZone(abbreviation: "UTC")!
let date =  calender.date(bySettingHour: Int(hour)!, minute: 00, second: 00, of: startdate!)
print(date)

OUTPUT: 2017-04-07 12:15:00 +0000

My timezone is +5:45 , after I am setting that timezone . I am getting the same bug .

Any help .
Highly appreciated.

With the following code I get the date same :

let formatter = DateFormatter()
formatter.dateFormat = "dd-MM-yyyy hh:mm:ss a"
formatter.timeZone = TimeZone(abbreviation: "GMT")
let startdate = formatter.date(from: sdate!)
print(startdate)

**But I can't set it's minute to 0 here. **

Body:
Sorry I'm writing from the mobile so the code could be not the exact one but you will find the functions easily.

Before you print the date, convert it to date components using calendar; then set the dateComponents.minute value to 0 and reconvert it into a date:

let dateComponents = Calendar.current.dateComponents(fromDate: yourDate)
dateComponents.minute = 0
let finishedDate = Calendar.current.date(fromComponents: dateComponents)
print(finishedDate)

Oh yeah and I recommend to set the time zone to TimeZone.current unless you want to use a specific time zone only!


来源: stackexchange

问:
Can't provision authorized_keys file into VM using Vagrant
I am trying to use my own pair of RSA SSH-2 keys with Vagrant 1.9.5 on VirtualBox 5.1.22 with Windows 7 SP1 host and a CentOS 7.3 guest.

When I execute vagrant up I get :

```<code>Waiting for machine to boot. This may take a few minutes...
SSH address: 127.0.0.1:2222
SSH username: vagrant
SSH auth method: private key
Warning: Connection aborted. Retrying...
Warning: Connection reset. Retrying...
Warning: Connection aborted. Retrying...
Warning: Connection reset. Retrying...
Warning: Connection aborted. Retrying...
Warning: Connection reset. Retrying...
Warning: Connection aborted. Retrying...
...
</code>```

I have found that the cause is failing to connect to the guest because the required key is not being added to ~/.ssh/authorized_keys but it contains Vagrant's default insecure_private_key.

This is my Vagrantfile

```<code># -*- mode: ruby -*-
# vi: set ft=ruby :

VAGRANTFILE_API_VERSION = "2"

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|

  config.vm.boot_timeout = 120
  config.ssh.insert_key = false
  config.ssh.private_key_path = ["vagrant-setup/keys/my_openssh.key"]
  # This is not copying authorized_keys to the guest
  config.vm.provision "file", source: "vagrant-setup/.ssh/authorized_keys", destination: "~/.ssh/autorized_keys"
  # Setting forward_agent to true and adding the key to Pageant doesn't make any difference
  config.ssh.forward_agent = false

  config.vm.define "MyMachineName" do |vs|

    vs.vm.box = "vagrant-centos-73-x86_64-puppet"
    vs.vm.box_url = "https://github.com/CommanderK5/packer-centos-template/releases/download/0.7.3/vagrant-centos-7.3.box"

    # The shell script that will execute once just after the VM is created
    vs.vm.provision "shell", path: "vagrant-setup/setup.sh"

    # Create a private network, which allows host-only access to the machine using a specific IP.
    config.vm.network "private_network", ip: "192.168.101.110"

    vs.vm.provider "virtualbox" do |vb|
      # Enable the GUI of VirtualBox and see whether the VM is waiting for input on startup
      vb.gui = false
    end
  end

end
</code>```

I have tried copying autorized_keys using vm.provision "shell" and cp from the guest. I have tried to change the permissions of autorized_keys on the guest before copying but nothing seems to work because it does not connect. And I have tried to perform the copy inside MyMachineName like vs.vm.provision "file", ...

If I login in once using vagrant ssh with user+password and I write authorized_keys by hand then afterwards I am able to log in with the SSH key and no password.

vagrant ssh-config reports

```<code>Host MyMachineName
  HostName 127.0.0.1
  User vagrant
  Port 2222
  UserKnownHostsFile /dev/null
  StrictHostKeyChecking no
  PasswordAuthentication no
  IdentityFile C:/MyMachineName/vagrant-setup/keys/my_openssh.key
  IdentitiesOnly yes
  LogLevel FATAL
</code>```

Putting the private key into C:\Users\My User Name\.ssh\id_rsa seems to make some difference, like if Vagrant was still looking for something there despite I explicitly set my own private key, but does not make it work. And it also seems to have a problem with C:\Users\My User Name\ having spaces but since it should not be used then that should not matter.

So the question is How do I make Vagrant work with my own pair of SSH keys without having to tweak the guest VM by hand?

There are plenty of replies at this other question, but most of them come down to put the key in authorized_keys by hand, which is exactly what I am trying to avoid.

答:
Based on Frédéric Henri comment, this is what worked for me in order to login only with my own key and not insecure key nor user+password :</p>

```<code># -*- mode: ruby -*-
# vi: set ft=ruby :

VAGRANTFILE_API_VERSION = "2"

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
  config.ssh.insert_key = false
  rsakey = File.read("vagrant-setup/keys/authorized_keys")
  config.vm.provision "shell", inline: <<-EOC
    echo '#{rsakey}' >> /home/vagrant/.ssh/authorized_keys
    sed --in-place=.bak -r 's/^#?(PermitRootLogin|PermitEmptyPasswords|PasswordAuthentication|X11Forwarding) yes/\1 no/' /etc/ssh/sshd_config
    sed --in-place=.bak '/== vagrant insecure public key$/d' /home/vagrant/.ssh/authorized_keys
  EOC

  config.vm.define "MyMachine" do |vs|
    vs.vm.box = "vagrant-centos-73-x86_64-puppet"
    vs.vm.box_url = "https://github.com/CommanderK5/packer-centos-template/releases/download/0.7.3/vagrant-centos-7.3.box"

    # SSH settings
    vs.ssh.private_key_path = ['~/.vagrant.d/insecure_private_key', "vagrant-setup/keys/my_openssh.key"]

    # The shell script that will execute once just after the VM is created
    vs.vm.provision "shell", path: "vagrant-setup/my_own_custom_setup_stuff.sh"

    # Create a private network, which allows host-only access to the machine using a specific IP.
    config.vm.network "private_network", ip: "192.168.101.110"
  end

end
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to use my own pair of RSA SSH-2 keys with Vagrant 1.9.5 on VirtualBox 5.1.22 with Windows 7 SP1 host and a CentOS 7.3 guest.

When I execute vagrant up I get :

Waiting for machine to boot. This may take a few minutes...
SSH address: 127.0.0.1:2222
SSH username: vagrant
SSH auth method: private key
Warning: Connection aborted. Retrying...
Warning: Connection reset. Retrying...
Warning: Connection aborted. Retrying...
Warning: Connection reset. Retrying...
Warning: Connection aborted. Retrying...
Warning: Connection reset. Retrying...
Warning: Connection aborted. Retrying...
...

I have found that the cause is failing to connect to the guest because the required key is not being added to ~/.ssh/authorized_keys but it contains Vagrant's default insecure_private_key.

This is my Vagrantfile

# -*- mode: ruby -*-
# vi: set ft=ruby :

VAGRANTFILE_API_VERSION = "2"

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|

  config.vm.boot_timeout = 120
  config.ssh.insert_key = false
  config.ssh.private_key_path = ["vagrant-setup/keys/my_openssh.key"]
  # This is not copying authorized_keys to the guest
  config.vm.provision "file", source: "vagrant-setup/.ssh/authorized_keys", destination: "~/.ssh/autorized_keys"
  # Setting forward_agent to true and adding the key to Pageant doesn't make any difference
  config.ssh.forward_agent = false

  config.vm.define "MyMachineName" do |vs|

    vs.vm.box = "vagrant-centos-73-x86_64-puppet"
    vs.vm.box_url = "https://github.com/CommanderK5/packer-centos-template/releases/download/0.7.3/vagrant-centos-7.3.box"

    # The shell script that will execute once just after the VM is created
    vs.vm.provision "shell", path: "vagrant-setup/setup.sh"

    # Create a private network, which allows host-only access to the machine using a specific IP.
    config.vm.network "private_network", ip: "192.168.101.110"

    vs.vm.provider "virtualbox" do |vb|
      # Enable the GUI of VirtualBox and see whether the VM is waiting for input on startup
      vb.gui = false
    end
  end

end

I have tried copying autorized_keys using vm.provision "shell" and cp from the guest. I have tried to change the permissions of autorized_keys on the guest before copying but nothing seems to work because it does not connect. And I have tried to perform the copy inside MyMachineName like vs.vm.provision "file", ...

If I login in once using vagrant ssh with user+password and I write authorized_keys by hand then afterwards I am able to log in with the SSH key and no password.

vagrant ssh-config reports

Host MyMachineName
  HostName 127.0.0.1
  User vagrant
  Port 2222
  UserKnownHostsFile /dev/null
  StrictHostKeyChecking no
  PasswordAuthentication no
  IdentityFile C:/MyMachineName/vagrant-setup/keys/my_openssh.key
  IdentitiesOnly yes
  LogLevel FATAL

Putting the private key into C:\Users\My User Name\.ssh\id_rsa seems to make some difference, like if Vagrant was still looking for something there despite I explicitly set my own private key, but does not make it work. And it also seems to have a problem with C:\Users\My User Name\ having spaces but since it should not be used then that should not matter.

So the question is How do I make Vagrant work with my own pair of SSH keys without having to tweak the guest VM by hand?

There are plenty of replies at this other question, but most of them come down to put the key in authorized_keys by hand, which is exactly what I am trying to avoid.

Body:
Based on Frédéric Henri comment, this is what worked for me in order to login only with my own key and not insecure key nor user+password :

# -*- mode: ruby -*-
# vi: set ft=ruby :

VAGRANTFILE_API_VERSION = "2"

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
  config.ssh.insert_key = false
  rsakey = File.read("vagrant-setup/keys/authorized_keys")
  config.vm.provision "shell", inline: <<-EOC
    echo '#{rsakey}' >> /home/vagrant/.ssh/authorized_keys
    sed --in-place=.bak -r 's/^#?(PermitRootLogin|PermitEmptyPasswords|PasswordAuthentication|X11Forwarding) yes/\1 no/' /etc/ssh/sshd_config
    sed --in-place=.bak '/== vagrant insecure public key$/d' /home/vagrant/.ssh/authorized_keys
  EOC

  config.vm.define "MyMachine" do |vs|
    vs.vm.box = "vagrant-centos-73-x86_64-puppet"
    vs.vm.box_url = "https://github.com/CommanderK5/packer-centos-template/releases/download/0.7.3/vagrant-centos-7.3.box"

    # SSH settings
    vs.ssh.private_key_path = ['~/.vagrant.d/insecure_private_key', "vagrant-setup/keys/my_openssh.key"]

    # The shell script that will execute once just after the VM is created
    vs.vm.provision "shell", path: "vagrant-setup/my_own_custom_setup_stuff.sh"

    # Create a private network, which allows host-only access to the machine using a specific IP.
    config.vm.network "private_network", ip: "192.168.101.110"
  end

end


问:
.NET code to send ZPL to Zebra printers
Is there a way to send ZPL (Zebra Programming Language) to a printer in .NET?

I have the code to do this in Delphi, but it is not pretty and I would rather not try to recreate it in .NET as it is.

答: Figured since this is still showing up high in search results for C# and ZPL I should mention SharpZebra. It's only EPL2, but I've submitted an update that adds ZPL support along with printing via sockets, the Windows Spool Service and direct USB.</p>

Title: .NET code to send ZPL to Zebra printers

ContentLicense: CC BY-SA 4.0


问:
replace chars only in specific position
How can I tell R to replace string only in given position? The example below does it in any position. Trying to make it work and can't figure out syntax.</p>

```<code>z <- c("alpha 1 bravo 0 charlie_ 0 v1 whiskey 0")
z  #  replace only in pos 25,26  substr(z, 25, 26)
sink('output.txt')
gsub(" 0","**",z)   # <@>><  ??
sink()
</code>```

答:
Just make it skip 24 characters from the beginning and then test.   Also,   sub may be better than gsub here.

```<code>z <- c("alpha 1 bravo 0 charlie_ 0 v1")
sub("^(.{24}) 0", "\\1**", z)
[1] "alpha 1 bravo 0 charlie_** v1"
</code>```

Updated string

```<code>z2 <- c("alpha 1 bravo 0 charlie_ 0 v1 whiskey 0")
sub("^(.{24}) 0", "\\1**", z2)
[1] "alpha 1 bravo 0 charlie_** v1 whiskey 0"
</code>```

Just to be clear, this pattern only changes positions 25 and 26. No positions before or after.  It does so by skipping exactly 24 characters from the beginning and then testing for the pattern " 0".  Putting parentheses around .{24} cause those first 24 characters to be stored in the variable \1  which is what is used in the "sub" part to put those back.

Title: replace chars only in specific position

Body:
How can I tell R to replace string only in given position? The example below does it in any position. Trying to make it work and can't figure out syntax.

z <- c("alpha 1 bravo 0 charlie_ 0 v1 whiskey 0")
z  #  replace only in pos 25,26  substr(z, 25, 26)
sink('output.txt')
gsub(" 0","**",z)   # <@>><  ??
sink()

Body:
Just make it skip 24 characters from the beginning and then test.   Also,   sub may be better than gsub here.

z <- c("alpha 1 bravo 0 charlie_ 0 v1")
sub("^(.{24}) 0", "\\1**", z)
[1] "alpha 1 bravo 0 charlie_** v1"

Updated string

z2 <- c("alpha 1 bravo 0 charlie_ 0 v1 whiskey 0")
sub("^(.{24}) 0", "\\1**", z2)
[1] "alpha 1 bravo 0 charlie_** v1 whiskey 0"

Just to be clear, this pattern only changes positions 25 and 26. No positions before or after.  It does so by skipping exactly 24 characters from the beginning and then testing for the pattern " 0".  Putting parentheses around .{24} cause those first 24 characters to be stored in the variable \1  which is what is used in the "sub" part to put those back.


问:
Turbolinks, Rails, back button, footer from other source
I have an issue with turbolinks. When I click a 'back' button in browser there is one more footer appends.

In application.html.slim:

```<code>doctype html
html
  head
    title
      - unless content_for(:title).present?
        | Some text...
      - else
        == yield :title
    meta name='viewport' content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no'
    = csrf_meta_tags
    = stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload'
    = javascript_include_tag 'application', 'data-turbolinks-track': 'reload'
    - if admin_admin_signed_in?
      = stylesheet_link_tag    'cms/application', media: 'all', 'data-turbolinks-track': 'reload'
      = javascript_include_tag 'cms/application', 'data-turbolinks-track': 'reload'
</code>```

I load a footer from the other source (application.coffee):

```<code>$(document).on 'turbolinks:load', ->
    $('footer').get(0).innerHTML = ''
    for src in ['//other_site.com/goc/us/other_site.com/responsive.js', '//other_site.com/footer-builder.js']
      s = document.createElement('script')
      s.async = true
      s.src = src
      document.getElementsByTagName('head')[0].appendChild s
</code>```

Thanks for attention in advance!

答:
As @uzaif said you should put Turbolinks.clearCache()into your .js file for particular dom element or even page in similar situations. In my case I added the following peace of code this way:

application.coffee:

```<code>$(document).on 'turbolinks:load', ->
  $('footer').get(0).innerHTML = ''
  for src in ['//other_site.com/goc/us/other_site.com/responsive.js', '//other_site.com/footer-builder.js']
    s = document.createElement('script')
    s.async = true
    s.src = src
    document.getElementsByTagName('head')[0].appendChild s
  Turbolinks.clearCache()
</code>```

Keep in mind it can reduce speed of page loading so make application profiling to be sure

Body:
I have an issue with turbolinks. When I click a 'back' button in browser there is one more footer appends.

In application.html.slim:

doctype html
html
  head
    title
      - unless content_for(:title).present?
        | Some text...
      - else
        == yield :title
    meta name='viewport' content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no'
    = csrf_meta_tags
    = stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload'
    = javascript_include_tag 'application', 'data-turbolinks-track': 'reload'
    - if admin_admin_signed_in?
      = stylesheet_link_tag    'cms/application', media: 'all', 'data-turbolinks-track': 'reload'
      = javascript_include_tag 'cms/application', 'data-turbolinks-track': 'reload'

I load a footer from the other source (application.coffee):

$(document).on 'turbolinks:load', ->
    $('footer').get(0).innerHTML = ''
    for src in ['//other_site.com/goc/us/other_site.com/responsive.js', '//other_site.com/footer-builder.js']
      s = document.createElement('script')
      s.async = true
      s.src = src
      document.getElementsByTagName('head')[0].appendChild s

Thanks for attention in advance!

Body:
As @uzaif said you should put Turbolinks.clearCache()into your .js file for particular dom element or even page in similar situations. In my case I added the following peace of code this way:

application.coffee:

$(document).on 'turbolinks:load', ->
  $('footer').get(0).innerHTML = ''
  for src in ['//other_site.com/goc/us/other_site.com/responsive.js', '//other_site.com/footer-builder.js']
    s = document.createElement('script')
    s.async = true
    s.src = src
    document.getElementsByTagName('head')[0].appendChild s
  Turbolinks.clearCache()

Keep in mind it can reduce speed of page loading so make application profiling to be sure


问:
SQL Query continues running for a very long time if search term not found
In my Azure hosted ASP.NET Core site I have a table of users and I implemented search as follows:

```<code>    var inner = from user in db.Users
             select  new
             {
                 Name = user.Name,
                 Verified = user.Verified,
                 PhotoURL = user.PhotoURL,
                 UserID = user.Id,
                 Subdomain = user.Subdomain,
                 Deleted=user.Deleted,
                 AppearInSearch = user.AppearInSearch
             };
    return await inner.Where(u=>u.Name.Contains(name)&& !u.Deleted && u.AppearInSearch)
                                    .OrderByDescending(u => u.Verified)
                                    .Skip(page * recordsInPage)
                                    .Take(recordsInPage)
                                    .Select(u => new UserSearchResult()
                                    {
                                        Name = u.Name,
                                        Verified = u.Verified,
                                        PhotoURL = u.PhotoURL,
                                        UserID = u.UserID,
                                        Subdomain = u.Subdomain
                                    }).ToListAsync();
</code>```

This translates to a SQL statement similar to the following:

```<code>SELECT [t].[Name], [t].[Verified],
       [t].[PhotoURL], [t].[Id],
       [t].[Subdomain], [t].[Deleted],
       [t].[AppearInSearch]
FROM (
        SELECT [user0].[Name], [user0].[Verified],
               [user0].[PhotoURL], [user0].[Id],
               [user0].[Subdomain], [user0].[Deleted],
               [user0].[AppearInSearch]
        FROM [AspNetUsers] AS [user0]
        WHERE (((CHARINDEX('khaled', [user0].[Name]) > 0) OR ('khaled' = N''))
          AND ([user0].[Deleted] = 0))
          AND ([user0].[AppearInSearch] = 1)
        ORDER BY [user0].[Verified] DESC
        OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY  ) AS [t]
</code>```

If the search term is available in the database, the result is obtained in less than a second.
However, If it's not found the query runs for a very long time (I have seen it once reaching 48 seconds).

This greatly affects performance when we publish this feature to the internet.

Can you kindly suggest a way to solve this issue?

Thank you

Update: this issue is continued here: Empty Login Name When Showing sys.processes

答:
SQL Server has to use a scan to find rows matching the .Contains clause.  There is no way around this.

However, if we reduce the amount of data that SQL server has to scan, we will speed up the query.

Covering filtered index

An index is "covering" if it contains all the data needed to be returned in a query.

```<code>CREATE INDEX IX_User_Name_filtered ON USER ([Verified], [Name])
INCLUDE ( [PhotoURL], [Id], [Subdomain], [Deleted], [AppearInSearch]  )
WHERE [AppearInSearch]=1 AND [Deleted]=0
</code>```

This index is likely substantially smaller than the original table, so even if a scan is required, it will be quicker.

Depending on the plan that is generated, this index may be a better choice.  it doesn't include the extra columns and will be smaller still.  Testing will be required to determine the best choice.

```<code>CREATE INDEX IX_User_Name_filtered ON USER ([Verified], [Name])
WHERE [AppearInSearch]=1 AND [Deleted]=0
</code>```

Body:
In my Azure hosted ASP.NET Core site I have a table of users and I implemented search as follows:

    var inner = from user in db.Users
             select  new
             {
                 Name = user.Name,
                 Verified = user.Verified,
                 PhotoURL = user.PhotoURL,
                 UserID = user.Id,
                 Subdomain = user.Subdomain,
                 Deleted=user.Deleted,
                 AppearInSearch = user.AppearInSearch
             };
    return await inner.Where(u=>u.Name.Contains(name)&& !u.Deleted && u.AppearInSearch)
                                    .OrderByDescending(u => u.Verified)
                                    .Skip(page * recordsInPage)
                                    .Take(recordsInPage)
                                    .Select(u => new UserSearchResult()
                                    {
                                        Name = u.Name,
                                        Verified = u.Verified,
                                        PhotoURL = u.PhotoURL,
                                        UserID = u.UserID,
                                        Subdomain = u.Subdomain
                                    }).ToListAsync();

This translates to a SQL statement similar to the following:

SELECT [t].[Name], [t].[Verified],
       [t].[PhotoURL], [t].[Id],
       [t].[Subdomain], [t].[Deleted],
       [t].[AppearInSearch]
FROM (
        SELECT [user0].[Name], [user0].[Verified],
               [user0].[PhotoURL], [user0].[Id],
               [user0].[Subdomain], [user0].[Deleted],
               [user0].[AppearInSearch]
        FROM [AspNetUsers] AS [user0]
        WHERE (((CHARINDEX('khaled', [user0].[Name]) > 0) OR ('khaled' = N''))
          AND ([user0].[Deleted] = 0))
          AND ([user0].[AppearInSearch] = 1)
        ORDER BY [user0].[Verified] DESC
        OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY  ) AS [t]

If the search term is available in the database, the result is obtained in less than a second.
However, If it's not found the query runs for a very long time (I have seen it once reaching 48 seconds).

This greatly affects performance when we publish this feature to the internet.

Can you kindly suggest a way to solve this issue?

Thank you

Update: this issue is continued here: Empty Login Name When Showing sys.processes

Body:
SQL Server has to use a scan to find rows matching the .Contains clause.  There is no way around this.

However, if we reduce the amount of data that SQL server has to scan, we will speed up the query.

Covering filtered index

An index is "covering" if it contains all the data needed to be returned in a query.

CREATE INDEX IX_User_Name_filtered ON USER ([Verified], [Name])
INCLUDE ( [PhotoURL], [Id], [Subdomain], [Deleted], [AppearInSearch]  )
WHERE [AppearInSearch]=1 AND [Deleted]=0

This index is likely substantially smaller than the original table, so even if a scan is required, it will be quicker.

Depending on the plan that is generated, this index may be a better choice.  it doesn't include the extra columns and will be smaller still.  Testing will be required to determine the best choice.

CREATE INDEX IX_User_Name_filtered ON USER ([Verified], [Name])
WHERE [AppearInSearch]=1 AND [Deleted]=0


问:
I have text file with a 2D matrix in it. How do turn this into a grey scale image in python?
I'm fairly new with python so I'm not really sure where to start. All I have done is I imported the text file to python. I was suggested to use matshow.py but I don't know how I would use the text file to create the actual image.</p>

答:
Try

```<code>Matrix = loadtxt(filename)
imshow(Matrix)
</code>```

These functions come from the numpy and matplotlib libraries, respectivelly.

Body:
Try

Matrix = loadtxt(filename)
imshow(Matrix)

These functions come from the numpy and matplotlib libraries, respectivelly.


问:
Getting msbuild.exe without installing Visual Studio
How do you get msbuild.exe without installing those crazy Visual Studio programs?

I need it for an npm install to finish working. I'm on Windows 7  and can't get on older version of Visual Studio 2013 Express online.

答:
The latest (as of Jan 2019) stand-alone MSBuild installers can be found here: https://www.visualstudio.com/downloads/

Scroll down to "Tools for Visual Studio 2019" and choose "Build Tools for Visual Studio 2019" (despite the name, it's for users who don't want the full IDE)

See this question for additional information.


问:
IntelliSense: a value of type "PVOID" cannot be used to initialize an entity of type "_NtQuerySystemInformation"
I want know all handles of files that is opened by a determinated process and i have this following code that was found here, but when is passed to VS comes a error saying:

IntelliSense: a value of type "PVOID" cannot be used to initialize an entity of type "_NtQuerySystemInformation"

```<code>#ifndef UNICODE
#define UNICODE
#endif

#include <windows.h>
#include <stdio.h>

#define NT_SUCCESS(x) ((x) >= 0)
#define STATUS_INFO_LENGTH_MISMATCH 0xc0000004

#define SystemHandleInformation 16
#define ObjectBasicInformation 0
#define ObjectNameInformation 1
#define ObjectTypeInformation 2

typedef NTSTATUS (NTAPI *_NtQuerySystemInformation)(
    ULONG SystemInformationClass,
    PVOID SystemInformation,
    ULONG SystemInformationLength,
    PULONG ReturnLength
    );
typedef NTSTATUS (NTAPI *_NtDuplicateObject)(
    HANDLE SourceProcessHandle,
    HANDLE SourceHandle,
    HANDLE TargetProcessHandle,
    PHANDLE TargetHandle,
    ACCESS_MASK DesiredAccess,
    ULONG Attributes,
    ULONG Options
    );
typedef NTSTATUS (NTAPI *_NtQueryObject)(
    HANDLE ObjectHandle,
    ULONG ObjectInformationClass,
    PVOID ObjectInformation,
    ULONG ObjectInformationLength,
    PULONG ReturnLength
    );

typedef struct _UNICODE_STRING
{
    USHORT Length;
    USHORT MaximumLength;
    PWSTR Buffer;
} UNICODE_STRING, *PUNICODE_STRING;

typedef struct _SYSTEM_HANDLE
{
    ULONG ProcessId;
    BYTE ObjectTypeNumber;
    BYTE Flags;
    USHORT Handle;
    PVOID Object;
    ACCESS_MASK GrantedAccess;
} SYSTEM_HANDLE, *PSYSTEM_HANDLE;

typedef struct _SYSTEM_HANDLE_INFORMATION
{
    ULONG HandleCount;
    SYSTEM_HANDLE Handles[1];
} SYSTEM_HANDLE_INFORMATION, *PSYSTEM_HANDLE_INFORMATION;

typedef enum _POOL_TYPE
{
    NonPagedPool,
    PagedPool,
    NonPagedPoolMustSucceed,
    DontUseThisType,
    NonPagedPoolCacheAligned,
    PagedPoolCacheAligned,
    NonPagedPoolCacheAlignedMustS
} POOL_TYPE, *PPOOL_TYPE;

typedef struct _OBJECT_TYPE_INFORMATION
{
    UNICODE_STRING Name;
    ULONG TotalNumberOfObjects;
    ULONG TotalNumberOfHandles;
    ULONG TotalPagedPoolUsage;
    ULONG TotalNonPagedPoolUsage;
    ULONG TotalNamePoolUsage;
    ULONG TotalHandleTableUsage;
    ULONG HighWaterNumberOfObjects;
    ULONG HighWaterNumberOfHandles;
    ULONG HighWaterPagedPoolUsage;
    ULONG HighWaterNonPagedPoolUsage;
    ULONG HighWaterNamePoolUsage;
    ULONG HighWaterHandleTableUsage;
    ULONG InvalidAttributes;
    GENERIC_MAPPING GenericMapping;
    ULONG ValidAccess;
    BOOLEAN SecurityRequired;
    BOOLEAN MaintainHandleCount;
    USHORT MaintainTypeList;
    POOL_TYPE PoolType;
    ULONG PagedPoolUsage;
    ULONG NonPagedPoolUsage;
} OBJECT_TYPE_INFORMATION, *POBJECT_TYPE_INFORMATION;

PVOID GetLibraryProcAddress(PSTR LibraryName, PSTR ProcName)
{
    return GetProcAddress(GetModuleHandleA(LibraryName), ProcName);
}

int wmain(int argc, WCHAR *argv[])
{
    _NtQuerySystemInformation NtQuerySystemInformation =
        GetLibraryProcAddress("ntdll.dll", "NtQuerySystemInformation");
    _NtDuplicateObject NtDuplicateObject =
        GetLibraryProcAddress("ntdll.dll", "NtDuplicateObject");
    _NtQueryObject NtQueryObject =
        GetLibraryProcAddress("ntdll.dll", "NtQueryObject");
    NTSTATUS status;
    PSYSTEM_HANDLE_INFORMATION handleInfo;
    ULONG handleInfoSize = 0x10000;
    ULONG pid;
    HANDLE processHandle;
    ULONG i;

    if (argc < 2)
    {
        printf("Usage: handles [pid]\n");
        return 1;
    }

    pid = _wtoi(argv[1]);

    if (!(processHandle = OpenProcess(PROCESS_DUP_HANDLE, FALSE, pid)))
    {
        printf("Could not open PID %d! (Don't try to open a system process.)\n", pid);
        return 1;
    }

    handleInfo = (PSYSTEM_HANDLE_INFORMATION)malloc(handleInfoSize);

    /* NtQuerySystemInformation won't give us the correct buffer size,
       so we guess by doubling the buffer size. */
    while ((status = NtQuerySystemInformation(
        SystemHandleInformation,
        handleInfo,
        handleInfoSize,
        NULL
        )) == STATUS_INFO_LENGTH_MISMATCH)
        handleInfo = (PSYSTEM_HANDLE_INFORMATION)realloc(handleInfo, handleInfoSize *= 2);

    /* NtQuerySystemInformation stopped giving us STATUS_INFO_LENGTH_MISMATCH. */
    if (!NT_SUCCESS(status))
    {
        printf("NtQuerySystemInformation failed!\n");
        return 1;
    }

    for (i = 0; i < handleInfo->HandleCount; i++)
    {
        SYSTEM_HANDLE handle = handleInfo->Handles[i];
        HANDLE dupHandle = NULL;
        POBJECT_TYPE_INFORMATION objectTypeInfo;
        PVOID objectNameInfo;
        UNICODE_STRING objectName;
        ULONG returnLength;

        /* Check if this handle belongs to the PID the user specified. */
        if (handle.ProcessId != pid)
            continue;

        /* Duplicate the handle so we can query it. */
        if (!NT_SUCCESS(NtDuplicateObject(
            processHandle,
            handle.Handle,
            GetCurrentProcess(),
            &dupHandle,
            0,
            0,
            0
            )))
        {
            printf("[%#x] Error!\n", handle.Handle);
            continue;
        }

        /* Query the object type. */
        objectTypeInfo = (POBJECT_TYPE_INFORMATION)malloc(0x1000);
        if (!NT_SUCCESS(NtQueryObject(
            dupHandle,
            ObjectTypeInformation,
            objectTypeInfo,
            0x1000,
            NULL
            )))
        {
            printf("[%#x] Error!\n", handle.Handle);
            CloseHandle(dupHandle);
            continue;
        }

        /* Query the object name (unless it has an access of
           0x0012019f, on which NtQueryObject could hang. */
        if (handle.GrantedAccess == 0x0012019f)
        {
            /* We have the type, so display that. */
            printf(
                "[%#x] %.*S: (did not get name)\n",
                handle.Handle,
                objectTypeInfo->Name.Length / 2,
                objectTypeInfo->Name.Buffer
                );
            free(objectTypeInfo);
            CloseHandle(dupHandle);
            continue;
        }

        objectNameInfo = malloc(0x1000);
        if (!NT_SUCCESS(NtQueryObject(
            dupHandle,
            ObjectNameInformation,
            objectNameInfo,
            0x1000,
            &returnLength
            )))
        {
            /* Reallocate the buffer and try again. */
            objectNameInfo = realloc(objectNameInfo, returnLength);
            if (!NT_SUCCESS(NtQueryObject(
                dupHandle,
                ObjectNameInformation,
                objectNameInfo,
                returnLength,
                NULL
                )))
            {
                /* We have the type name, so just display that. */
                printf(
                    "[%#x] %.*S: (could not get name)\n",
                    handle.Handle,
                    objectTypeInfo->Name.Length / 2,
                    objectTypeInfo->Name.Buffer
                    );
                free(objectTypeInfo);
                free(objectNameInfo);
                CloseHandle(dupHandle);
                continue;
            }
        }

        /* Cast our buffer into an UNICODE_STRING. */
        objectName = *(PUNICODE_STRING)objectNameInfo;

        /* Print the information! */
        if (objectName.Length)
        {
            /* The object has a name. */
            printf(
                "[%#x] %.*S: %.*S\n",
                handle.Handle,
                objectTypeInfo->Name.Length / 2,
                objectTypeInfo->Name.Buffer,
                objectName.Length / 2,
                objectName.Buffer
                );
        }
        else
        {
            /* Print something else. */
            printf(
                "[%#x] %.*S: (unnamed)\n",
                handle.Handle,
                objectTypeInfo->Name.Length / 2,
                objectTypeInfo->Name.Buffer
                );
        }

        free(objectTypeInfo);
        free(objectNameInfo);
        CloseHandle(dupHandle);
    }

    free(handleInfo);
    CloseHandle(processHandle);

    return 0;
}
</code>```

How solve this problem?

Thank in advance.

答:
You need to cast pointer to void to pointer to function. Note that in general case size of pointer to function and size of pointer to data may be not the same.

```<code>_NtQuerySystemInformation NtQuerySystemInformation{};
{
    auto const p_proc{GetLibraryProcAddress("ntdll.dll", "NtQuerySystemInformation")};
    assert(p_proc); // TODO handle error...
    static_assert(sizeof(_NtQuerySystemInformation) == sizeof(p_proc), "pointer size mismatch");
    memcpy(&NtQuerySystemInformation, &p_proc, sizeof(NtQuerySystemInformation)); // deep copy
}
</code>```

in case of C (because code in your question actually seems to be written in C):

```<code>_NtQuerySystemInformation NtQuerySystemInformation = NULL;

{
    PVOID const p_proc = GetLibraryProcAddress("ntdll.dll", "NtQuerySystemInformation");
    assert(p_proc); // TODO handle error...
    assert(sizeof(_NtQuerySystemInformation) == sizeof(p_proc));
    memcpy(&NtQuerySystemInformation, &p_proc, sizeof(NtQuerySystemInformation)); // deep copy
}
</code>```

Body:
I want know all handles of files that is opened by a determinated process and i have this following code that was found here, but when is passed to VS comes a error saying:

IntelliSense: a value of type "PVOID" cannot be used to initialize an entity of type "_NtQuerySystemInformation"

#ifndef UNICODE
#define UNICODE
#endif

#include <windows.h>
#include <stdio.h>

#define NT_SUCCESS(x) ((x) >= 0)
#define STATUS_INFO_LENGTH_MISMATCH 0xc0000004

#define SystemHandleInformation 16
#define ObjectBasicInformation 0
#define ObjectNameInformation 1
#define ObjectTypeInformation 2

typedef NTSTATUS (NTAPI *_NtQuerySystemInformation)(
    ULONG SystemInformationClass,
    PVOID SystemInformation,
    ULONG SystemInformationLength,
    PULONG ReturnLength
    );
typedef NTSTATUS (NTAPI *_NtDuplicateObject)(
    HANDLE SourceProcessHandle,
    HANDLE SourceHandle,
    HANDLE TargetProcessHandle,
    PHANDLE TargetHandle,
    ACCESS_MASK DesiredAccess,
    ULONG Attributes,
    ULONG Options
    );
typedef NTSTATUS (NTAPI *_NtQueryObject)(
    HANDLE ObjectHandle,
    ULONG ObjectInformationClass,
    PVOID ObjectInformation,
    ULONG ObjectInformationLength,
    PULONG ReturnLength
    );

typedef struct _UNICODE_STRING
{
    USHORT Length;
    USHORT MaximumLength;
    PWSTR Buffer;
} UNICODE_STRING, *PUNICODE_STRING;

typedef struct _SYSTEM_HANDLE
{
    ULONG ProcessId;
    BYTE ObjectTypeNumber;
    BYTE Flags;
    USHORT Handle;
    PVOID Object;
    ACCESS_MASK GrantedAccess;
} SYSTEM_HANDLE, *PSYSTEM_HANDLE;

typedef struct _SYSTEM_HANDLE_INFORMATION
{
    ULONG HandleCount;
    SYSTEM_HANDLE Handles[1];
} SYSTEM_HANDLE_INFORMATION, *PSYSTEM_HANDLE_INFORMATION;

typedef enum _POOL_TYPE
{
    NonPagedPool,
    PagedPool,
    NonPagedPoolMustSucceed,
    DontUseThisType,
    NonPagedPoolCacheAligned,
    PagedPoolCacheAligned,
    NonPagedPoolCacheAlignedMustS
} POOL_TYPE, *PPOOL_TYPE;

typedef struct _OBJECT_TYPE_INFORMATION
{
    UNICODE_STRING Name;
    ULONG TotalNumberOfObjects;
    ULONG TotalNumberOfHandles;
    ULONG TotalPagedPoolUsage;
    ULONG TotalNonPagedPoolUsage;
    ULONG TotalNamePoolUsage;
    ULONG TotalHandleTableUsage;
    ULONG HighWaterNumberOfObjects;
    ULONG HighWaterNumberOfHandles;
    ULONG HighWaterPagedPoolUsage;
    ULONG HighWaterNonPagedPoolUsage;
    ULONG HighWaterNamePoolUsage;
    ULONG HighWaterHandleTableUsage;
    ULONG InvalidAttributes;
    GENERIC_MAPPING GenericMapping;
    ULONG ValidAccess;
    BOOLEAN SecurityRequired;
    BOOLEAN MaintainHandleCount;
    USHORT MaintainTypeList;
    POOL_TYPE PoolType;
    ULONG PagedPoolUsage;
    ULONG NonPagedPoolUsage;
} OBJECT_TYPE_INFORMATION, *POBJECT_TYPE_INFORMATION;

PVOID GetLibraryProcAddress(PSTR LibraryName, PSTR ProcName)
{
    return GetProcAddress(GetModuleHandleA(LibraryName), ProcName);
}

int wmain(int argc, WCHAR *argv[])
{
    _NtQuerySystemInformation NtQuerySystemInformation =
        GetLibraryProcAddress("ntdll.dll", "NtQuerySystemInformation");
    _NtDuplicateObject NtDuplicateObject =
        GetLibraryProcAddress("ntdll.dll", "NtDuplicateObject");
    _NtQueryObject NtQueryObject =
        GetLibraryProcAddress("ntdll.dll", "NtQueryObject");
    NTSTATUS status;
    PSYSTEM_HANDLE_INFORMATION handleInfo;
    ULONG handleInfoSize = 0x10000;
    ULONG pid;
    HANDLE processHandle;
    ULONG i;

    if (argc < 2)
    {
        printf("Usage: handles [pid]\n");
        return 1;
    }

    pid = _wtoi(argv[1]);

    if (!(processHandle = OpenProcess(PROCESS_DUP_HANDLE, FALSE, pid)))
    {
        printf("Could not open PID %d! (Don't try to open a system process.)\n", pid);
        return 1;
    }

    handleInfo = (PSYSTEM_HANDLE_INFORMATION)malloc(handleInfoSize);

    /* NtQuerySystemInformation won't give us the correct buffer size,
       so we guess by doubling the buffer size. */
    while ((status = NtQuerySystemInformation(
        SystemHandleInformation,
        handleInfo,
        handleInfoSize,
        NULL
        )) == STATUS_INFO_LENGTH_MISMATCH)
        handleInfo = (PSYSTEM_HANDLE_INFORMATION)realloc(handleInfo, handleInfoSize *= 2);

    /* NtQuerySystemInformation stopped giving us STATUS_INFO_LENGTH_MISMATCH. */
    if (!NT_SUCCESS(status))
    {
        printf("NtQuerySystemInformation failed!\n");
        return 1;
    }

    for (i = 0; i < handleInfo->HandleCount; i++)
    {
        SYSTEM_HANDLE handle = handleInfo->Handles[i];
        HANDLE dupHandle = NULL;
        POBJECT_TYPE_INFORMATION objectTypeInfo;
        PVOID objectNameInfo;
        UNICODE_STRING objectName;
        ULONG returnLength;

        /* Check if this handle belongs to the PID the user specified. */
        if (handle.ProcessId != pid)
            continue;

        /* Duplicate the handle so we can query it. */
        if (!NT_SUCCESS(NtDuplicateObject(
            processHandle,
            handle.Handle,
            GetCurrentProcess(),
            &dupHandle,
            0,
            0,
            0
            )))
        {
            printf("[%#x] Error!\n", handle.Handle);
            continue;
        }

        /* Query the object type. */
        objectTypeInfo = (POBJECT_TYPE_INFORMATION)malloc(0x1000);
        if (!NT_SUCCESS(NtQueryObject(
            dupHandle,
            ObjectTypeInformation,
            objectTypeInfo,
            0x1000,
            NULL
            )))
        {
            printf("[%#x] Error!\n", handle.Handle);
            CloseHandle(dupHandle);
            continue;
        }

        /* Query the object name (unless it has an access of
           0x0012019f, on which NtQueryObject could hang. */
        if (handle.GrantedAccess == 0x0012019f)
        {
            /* We have the type, so display that. */
            printf(
                "[%#x] %.*S: (did not get name)\n",
                handle.Handle,
                objectTypeInfo->Name.Length / 2,
                objectTypeInfo->Name.Buffer
                );
            free(objectTypeInfo);
            CloseHandle(dupHandle);
            continue;
        }

        objectNameInfo = malloc(0x1000);
        if (!NT_SUCCESS(NtQueryObject(
            dupHandle,
            ObjectNameInformation,
            objectNameInfo,
            0x1000,
            &returnLength
            )))
        {
            /* Reallocate the buffer and try again. */
            objectNameInfo = realloc(objectNameInfo, returnLength);
            if (!NT_SUCCESS(NtQueryObject(
                dupHandle,
                ObjectNameInformation,
                objectNameInfo,
                returnLength,
                NULL
                )))
            {
                /* We have the type name, so just display that. */
                printf(
                    "[%#x] %.*S: (could not get name)\n",
                    handle.Handle,
                    objectTypeInfo->Name.Length / 2,
                    objectTypeInfo->Name.Buffer
                    );
                free(objectTypeInfo);
                free(objectNameInfo);
                CloseHandle(dupHandle);
                continue;
            }
        }

        /* Cast our buffer into an UNICODE_STRING. */
        objectName = *(PUNICODE_STRING)objectNameInfo;

        /* Print the information! */
        if (objectName.Length)
        {
            /* The object has a name. */
            printf(
                "[%#x] %.*S: %.*S\n",
                handle.Handle,
                objectTypeInfo->Name.Length / 2,
                objectTypeInfo->Name.Buffer,
                objectName.Length / 2,
                objectName.Buffer
                );
        }
        else
        {
            /* Print something else. */
            printf(
                "[%#x] %.*S: (unnamed)\n",
                handle.Handle,
                objectTypeInfo->Name.Length / 2,
                objectTypeInfo->Name.Buffer
                );
        }

        free(objectTypeInfo);
        free(objectNameInfo);
        CloseHandle(dupHandle);
    }

    free(handleInfo);
    CloseHandle(processHandle);

    return 0;
}

How solve this problem?

Thank in advance.

Body:
You need to cast pointer to void to pointer to function. Note that in general case size of pointer to function and size of pointer to data may be not the same.

_NtQuerySystemInformation NtQuerySystemInformation{};
{
    auto const p_proc{GetLibraryProcAddress("ntdll.dll", "NtQuerySystemInformation")};
    assert(p_proc); // TODO handle error...
    static_assert(sizeof(_NtQuerySystemInformation) == sizeof(p_proc), "pointer size mismatch");
    memcpy(&NtQuerySystemInformation, &p_proc, sizeof(NtQuerySystemInformation)); // deep copy
}

in case of C (because code in your question actually seems to be written in C):

_NtQuerySystemInformation NtQuerySystemInformation = NULL;

{
    PVOID const p_proc = GetLibraryProcAddress("ntdll.dll", "NtQuerySystemInformation");
    assert(p_proc); // TODO handle error...
    assert(sizeof(_NtQuerySystemInformation) == sizeof(p_proc));
    memcpy(&NtQuerySystemInformation, &p_proc, sizeof(NtQuerySystemInformation)); // deep copy
}


问:
Handling C++ arrays in Cython (with numpy and pytorch)
I am trying to use cython to wrap a C++ library (fastText, if its relevant). The C++ library classes load a very large array from disk. My wrapper instantiates a class from the C++ library to load the array, then uses cython memory views and numpy.asarray to turn the array into a numpy array, then calls torch.from_numpy to create a tensor.

The problem arising is how to handle deallocating the memory for the array.

Right now, I get pointer being freed was not allocated when the program exits. This is, I expect, because both the C++ code and numpy/pytorch are trying to manage the same chunk of RAM.

I could simply comment out the destructor in the C++ library, but that feels like its going to cause me a different problem down the road.

How should I approach the issue?  Is there any kind of best practices documentation somewhere on how to handle memory sharing with C++ and cython?

If I modify the C++ library to wrap the array in a shared_ptr, will cython (and numpy, pytorch, etc.) share the shared_ptr properly?

I apologize if the question is naive; Python garbage collection is very mysterious to me.

Any advice is appreciated.

答:
I can think of three sensible ways of doing it. I'll outline them below (i.e. none of the code will be complete but hopefully it will be clear how to finish it).

1. C++ owns the memory; Cython/Python holds a shared pointer to the C++ class

(This is looks to be the lines you're already thinking along).

Start by creating a Cython class that holds a shared pointer

```<code>from libcpp.memory cimport shared_ptr

cdef class Holder:
    cdef shared_ptr[cpp_class] ptr

    @staticmethod
    cdef make_holder(shared_ptr[cpp_class] ptr):
       cdef holder = Holder() # empty class
       holder.ptr = ptr
       return holder
</code>```

You then need to define the buffer protocol for Holder. This allows direct access to the memory allocated by cpp_class in a way that both numpy arrays and Cython memoryviews can understand. Thus they hold a reference to a Holder instance, which in turn keeps a cpp_class alive. (Use np.asarray(holder_instance) to create a numpy array that uses the instance's memory)

The buffer protocol is a little involved but Cython has fairly extensive documentation and you should largely be able to copy and paste their examples. The two methods you need to add to Holder are __getbuffer__ and __releasebuffer__.

2. Python owns the memory; Your C++ class holds a pointer to the Python object

In this version you allocate the memory as a numpy array (using the Python C API interface). When your C++ class is destructed in decrements the reference count of the array, however if Python holds references to that array then the array can outlive the C++ class.

```<code>#include <numpy/arrayobject.h>
#include <Python.h>

class cpp_class {
   private:
     PyObject* arr;
     double* data;
   public:
     cpp_class() {
       arr = PyArray_SimpleNew(...); // details left to be filled in
       data = PyArray_DATA(reinterpret_cast<PyArrayObject*>(arr));
       # fill in the data
     }

     ~cpp_class() {
         Py_DECREF(arr); // release our reference to it
     }

     PyObject* get_np_array() {
         Py_INCREF(arr); // Cython expects this to be done before it receives a PyObject
         return arr;
     }
};
</code>```

See the numpy documentation for details of the how to allocate numpy arrays from C/C++. Be careful of reference counting if you define copy/move constructors.

The Cython wrapper then looks like:

```<code>cdef extern from "some_header.hpp":
    cdef cppclass cpp_class:
       # whatever constructors you want to allow
       object get_np_array()
</code>```

3. C++ transfers ownership of the data to Python/Cython

In this scheme C++ allocates the array, but Cython/Python is responsible for deallocating it. Once ownership is transferred C++ no longer has access to the data.

```<code>class cpp_class {
   public:
     double* data; // for simplicity this is public - you may want to use accessors
     cpp_class() :
     data(new double[50])
     {/* fill the array as needed */}

     ~cpp_class() {
       delete [] data;
     }
};

// helper function for Cython
inline void del_cpp_array(double* a) {
   delete [] a;
}
</code>```

You then use the cython.view.array class to capture the allocated memory. This has a callback function which is used on destruction:

```<code>from cython cimport view

cdef extern from "some_header.hpp":
   cdef cppclass cpp_class:
      double* data
      # whatever constructors and other functions
   void del_cpp_array(double*)

# later
cdef cpp_class cpp_instance # create this however you like
# ...
# modify line below to match your data
arr = view.array(shape=(10, 2), itemsize=sizeof(double), format="d",
                 mode="C", allocate_buffer=False)
arr.data = <char*>cpp_instance.data
cpp_instance.data = None # reset to NULL pointer
arr.callback_free_data = del_cpp_array
</code>```

arr can then be used with a memoryview or a numpy array.

You may have to mess about a bit with casting from void* or char* with del_cpp_array - I'm not sure exactly what types the Cython interface requires.

The first option is probably most work to implement but requires few changes to the C++ code. The second option may require changes to your C++ code that you don't want to make. The third option is simple but means that C++ no longer has access to the data, which might be a disadvantage.

Body:
I can think of three sensible ways of doing it. I'll outline them below (i.e. none of the code will be complete but hopefully it will be clear how to finish it).

1. C++ owns the memory; Cython/Python holds a shared pointer to the C++ class

(This is looks to be the lines you're already thinking along).

Start by creating a Cython class that holds a shared pointer

from libcpp.memory cimport shared_ptr

cdef class Holder:
    cdef shared_ptr[cpp_class] ptr

    @staticmethod
    cdef make_holder(shared_ptr[cpp_class] ptr):
       cdef holder = Holder() # empty class
       holder.ptr = ptr
       return holder

You then need to define the buffer protocol for Holder. This allows direct access to the memory allocated by cpp_class in a way that both numpy arrays and Cython memoryviews can understand. Thus they hold a reference to a Holder instance, which in turn keeps a cpp_class alive. (Use np.asarray(holder_instance) to create a numpy array that uses the instance's memory)

The buffer protocol is a little involved but Cython has fairly extensive documentation and you should largely be able to copy and paste their examples. The two methods you need to add to Holder are __getbuffer__ and __releasebuffer__.

2. Python owns the memory; Your C++ class holds a pointer to the Python object

In this version you allocate the memory as a numpy array (using the Python C API interface). When your C++ class is destructed in decrements the reference count of the array, however if Python holds references to that array then the array can outlive the C++ class.

#include <numpy/arrayobject.h>
#include <Python.h>

class cpp_class {
   private:
     PyObject* arr;
     double* data;
   public:
     cpp_class() {
       arr = PyArray_SimpleNew(...); // details left to be filled in
       data = PyArray_DATA(reinterpret_cast<PyArrayObject*>(arr));
       # fill in the data
     }

     ~cpp_class() {
         Py_DECREF(arr); // release our reference to it
     }

     PyObject* get_np_array() {
         Py_INCREF(arr); // Cython expects this to be done before it receives a PyObject
         return arr;
     }
};

See the numpy documentation for details of the how to allocate numpy arrays from C/C++. Be careful of reference counting if you define copy/move constructors.

The Cython wrapper then looks like:

cdef extern from "some_header.hpp":
    cdef cppclass cpp_class:
       # whatever constructors you want to allow
       object get_np_array()

3. C++ transfers ownership of the data to Python/Cython

In this scheme C++ allocates the array, but Cython/Python is responsible for deallocating it. Once ownership is transferred C++ no longer has access to the data.

class cpp_class {
   public:
     double* data; // for simplicity this is public - you may want to use accessors
     cpp_class() :
     data(new double[50])
     {/* fill the array as needed */}

     ~cpp_class() {
       delete [] data;
     }
};

// helper function for Cython
inline void del_cpp_array(double* a) {
   delete [] a;
}

You then use the cython.view.array class to capture the allocated memory. This has a callback function which is used on destruction:

from cython cimport view

cdef extern from "some_header.hpp":
   cdef cppclass cpp_class:
      double* data
      # whatever constructors and other functions
   void del_cpp_array(double*)

# later
cdef cpp_class cpp_instance # create this however you like
# ...
# modify line below to match your data
arr = view.array(shape=(10, 2), itemsize=sizeof(double), format="d",
                 mode="C", allocate_buffer=False)
arr.data = <char*>cpp_instance.data
cpp_instance.data = None # reset to NULL pointer
arr.callback_free_data = del_cpp_array

arr can then be used with a memoryview or a numpy array.

You may have to mess about a bit with casting from void* or char* with del_cpp_array - I'm not sure exactly what types the Cython interface requires.

The first option is probably most work to implement but requires few changes to the C++ code. The second option may require changes to your C++ code that you don't want to make. The third option is simple but means that C++ no longer has access to the data, which might be a disadvantage.


问:
Developer Console, github
How do i check in code in Git Hub from Developer console.
I have been trying to browse, i saw we have to sync code to eclipse and then drop files to Git Hub.

Can anyone suggest me a standard way to do this please

答:
The Salesforce Developer Console based out the UI cannot integrate with Git Hub to check in/out code.  You'll have to do it with files stored locally either using your IDE or terminal.  This is the same as working with any Git repo and really is unrelated to Salesforce.
There is a new feature called Salesforce DX that has a tighter integration with git repos, it's going beta in Summer 17.</p>

Title: Developer Console, github


问:
Cannot read property 'getLineAndCharacterOfPosition' of undefined
I got stuck with this error, can someone help me out?
I just upgraded to Angular2.4.3

```<code>$ ng serve                                                                                [19:46:01]
** NG Live Development Server is running on http://localhost:4200. **
Hash: ed77e2590987da94e9d9
Time: 4165ms
chunk    {0} scripts.bundle.js, scripts.bundle.map (scripts) 1.42 MB {4} [initial] [rendered]
chunk    {1} styles.bundle.js, styles.bundle.map (styles) 203 kB {4} [initial] [rendered]
chunk    {2} main.bundle.js, main.bundle.map (main) 576 bytes {3} [initial] [rendered]
chunk    {3} vendor.bundle.js, vendor.bundle.map (vendor) 234 kB [initial] [rendered]
chunk    {4} inline.bundle.js, inline.bundle.map (inline) 0 bytes [entry] [rendered]

ERROR in Cannot read property 'getLineAndCharacterOfPosition' of undefined

ERROR in ./src/main.ts
Module build failed: Error: /Users/johntostring/Documents/web-workspace/ng2-qyweb/src/main.ts (3,40): Cannot find module '@angular/platform-browser-dynamic'.)
/Users/johntostring/Documents/web-workspace/ng2-qyweb/src/main.ts (4,32): Cannot find module '@angular/core'.)
    at _checkDiagnostics (/Users/johntostring/Documents/web-workspace/ng2-qyweb/node_modules/@ngtools/webpack/src/loader.js:145:15)
    at /Users/johntostring/Documents/web-workspace/ng2-qyweb/node_modules/@ngtools/webpack/src/loader.js:172:17
 @ multi main
webpack: bundle is now VALID.
</code>```

main.ts

app.module.ts

答: This happens when you modify tsconfig.app.json or tsconfig.json with invalid values.

Body:
I got stuck with this error, can someone help me out?
I just upgraded to Angular2.4.3

$ ng serve                                                                                [19:46:01]
** NG Live Development Server is running on http://localhost:4200. **
Hash: ed77e2590987da94e9d9
Time: 4165ms
chunk    {0} scripts.bundle.js, scripts.bundle.map (scripts) 1.42 MB {4} [initial] [rendered]
chunk    {1} styles.bundle.js, styles.bundle.map (styles) 203 kB {4} [initial] [rendered]
chunk    {2} main.bundle.js, main.bundle.map (main) 576 bytes {3} [initial] [rendered]
chunk    {3} vendor.bundle.js, vendor.bundle.map (vendor) 234 kB [initial] [rendered]
chunk    {4} inline.bundle.js, inline.bundle.map (inline) 0 bytes [entry] [rendered]

ERROR in Cannot read property 'getLineAndCharacterOfPosition' of undefined

ERROR in ./src/main.ts
Module build failed: Error: /Users/johntostring/Documents/web-workspace/ng2-qyweb/src/main.ts (3,40): Cannot find module '@angular/platform-browser-dynamic'.)
/Users/johntostring/Documents/web-workspace/ng2-qyweb/src/main.ts (4,32): Cannot find module '@angular/core'.)
    at _checkDiagnostics (/Users/johntostring/Documents/web-workspace/ng2-qyweb/node_modules/@ngtools/webpack/src/loader.js:145:15)
    at /Users/johntostring/Documents/web-workspace/ng2-qyweb/node_modules/@ngtools/webpack/src/loader.js:172:17
 @ multi main
webpack: bundle is now VALID.

main.ts

app.module.ts


问:
Javascript for loop with condition

I'm reading through the khan academy course on algorithms. I'm at https://www.khanacademy.org/computing/computer-science/algorithms/insertion-sort/p/challenge-implement-insert .

After calling the insert function:
  * value and the elements that were previously in array[0] to array[rightIndex], should be sorted in ascending order and stored in the elements from array[0] to array[rightIndex+1]. In order to do this, the insert function will need to make room for value by moving items that are greater than value to the right. It should start at rightIndex, and stop when it finds an item that is less than or equal to value, or when it reaches the beginning of the array. Once the function has made room for value, it can write value to the array.

My attempt is:

```<code>var insert = function(array, rightIndex, value) {

var i = rightIndex;
    for( array[i]> key ; 0; i-- ) {

        array[i + 1] = array[i];
   }
   array[i]= value;

};

var array = [3, 5, 7, 11, 13, 2, 9, 6];

insert(array, 4, 2);
println("Array after inserting 2:  " + array);
</code>```

They specifically say they want a condition within the for loop, but I don't know how to do that.

答:
```<code> var insert = function(array, rightIndex, value) {
    // for( initial_value; condition; change the value for next iteration)
    // && - returns true only when both are true.
     for(var j = rightIndex; j >= 0 && array[j] > value; j--) {
        array[j + 1] = array[j];
    }
    array[j + 1] = value;

};
</code>```

Title: Javascript for loop with condition

Body:
I'm reading through the khan academy course on algorithms. I'm at https://www.khanacademy.org/computing/computer-science/algorithms/insertion-sort/p/challenge-implement-insert .

After calling the insert function:
  * value and the elements that were previously in array[0] to array[rightIndex], should be sorted in ascending order and stored in the elements from array[0] to array[rightIndex+1]. In order to do this, the insert function will need to make room for value by moving items that are greater than value to the right. It should start at rightIndex, and stop when it finds an item that is less than or equal to value, or when it reaches the beginning of the array. Once the function has made room for value, it can write value to the array.

My attempt is:

var insert = function(array, rightIndex, value) {

var i = rightIndex;
    for( array[i]> key ; 0; i-- ) {

        array[i + 1] = array[i];
   }
   array[i]= value;

};

var array = [3, 5, 7, 11, 13, 2, 9, 6];

insert(array, 4, 2);
println("Array after inserting 2:  " + array);

They specifically say they want a condition within the for loop, but I don't know how to do that.


问:
How do I hide each head and body sections of an SSRS subreport, if the subreport body dataset contains zero rows
I have an SSRS report which passes one of it's parameters and a generated dataset of ids to a sub report.

There are two queries in the sub report, both of which require the passed parent parameter and the dataset of ids. These produce a head dataset and a body dataset to populate the subreport.

As the subreport accepts a list of multiple ids, the sub report renders multiple head sections with multiple rows of results in the body section below each head section.

For EACH id passed to the subreport, how do I hide EACH head AND body sections of the subreport, if the subreport body dataset contains zero rows?

The end result being no head section rendered in the subreport with empty rows beneath it.

I have too many failed attempts to list as prior research here.

答: I would try an expression in the visibility setting of the section you want hidden.  So something like =Iif(CountRows("MyDataset") = 0, true, false).</p>


问:
Running multiple build agents under specific user
I currently have one of my build agents in TeamCity running under a specific user due to one of the build steps.  The build agent supports a couple different projects, so I want to add an additional build agent. I have successfully done so, but upon doing so the new build agent starts working, but my older build agent gets disconnected and states "Agent has unregistered." Now I am using the same user to try and run both build agents, so not sure if that is whats causing the issue or not.  Both build agents are on the same machine and do have distinct names.  I have tried to restart the agents in hope that it would fix itself, but have not been successful.

答:
There are several resources covering setup of multiple build agents on the same machine, you can examine them if you wish.

Here are requirements from official documentation:

The agents are installed in separate directories.

The agents have the distinctive workDir and tempDir directories in the buildAgent.properties file.

Values for the name and ownPort properties of buildAgent.properties are unique.

No builds running on the agents have the absolute checkout directory specified.

Please, make sure that port number is changed, as this is most obvious reason why build agent could be terminated. Also, check that each build agent has its own unique name.
Otherwise, please check each build agent logs and - if it won't be clear -, share error here.


问:
How to programatically process the image to black and white and separate out the polygon
I have an image that represents a polygon.

I want to process it in matlab and generate the image below.

Basically i am asking to separate the polygon from the rest of the image out.  This question got inspired here.

答:
I think function contourc will get the ploygon:

```<code>C = contourc(img, [1 1]); % img is 2-D double in range [0 1]
</code>```

The format of output C is a little tricky. But for one level contour, it should be easy. You can read the documentation for contourc to construct the polygon.

Body:
I think function contourc will get the ploygon:

C = contourc(img, [1 1]); % img is 2-D double in range [0 1]

The format of output C is a little tricky. But for one level contour, it should be easy. You can read the documentation for contourc to construct the polygon.


问:
Django : How to import a python module such as pytube into a static template/webpage?
I am very new to Django. Recently I was developing a site just for getting aquainted with the framework and I came to a point where I needed to import a python module such as request,pytube etc into a static webpage so that i can use their functions . So two questions arose -
1. Is it possible to have python code embedded in static content.
2. How can I import a python module into a static webpage.</p>

答:
Python code cannot be executed by the browser within the page. If you wish to execute code within the browser you will need to use JavaScript, which would be a completely different process. If you wish to manipulate values from a webpage using Django and other Python libraries, you will need to set up a form, take the input, wash it through a views.py file with the classes or functions you need, and then return those values as context variables that are rendered through template tags in your static page upon load.

If you are new to Django, I would highly recommend looking through the Django Project's main tutorial, found here.


问:
Quotation marks in VBA
In my current VBA code, I have a query in which I am using Chr(34) to put quotation marks between some of my variables.

I was wondering what alternatives exist to this. This is a simple question, i know, but I haven't had any success with repeating quotation marks like this

" & variable string here & "

My code is messy for one and not understandable for people who are not familiar with VBA:

```<code>comboService = Chr(34) & Me.Combo8.Value & Chr(34)
</code>```

Also, this hasn't worked:

```<code>comboService = """" & Me.Combo8.Value & """"
</code>```

Can you perhaps tell me why?

Thanks in advance.

答:
I have found the same behavior if I output to a file using the Write command. Any double quotes get repeated.

However, if you construct the string and then output to file using the Print command, this does not happen and all works as expected.

Title: Quotation marks in VBA

Body:
In my current VBA code, I have a query in which I am using Chr(34) to put quotation marks between some of my variables.

I was wondering what alternatives exist to this. This is a simple question, i know, but I haven't had any success with repeating quotation marks like this

" & variable string here & "

My code is messy for one and not understandable for people who are not familiar with VBA:

comboService = Chr(34) & Me.Combo8.Value & Chr(34)

Also, this hasn't worked:

comboService = """" & Me.Combo8.Value & """"

Can you perhaps tell me why?

Thanks in advance.


问:
Change color of disabled toolbar button
I need to change the color of a disabled toolbar button. I have tried multiple methods.

1.

```<code>button.isEnabled = false
button.tintColor = UIColor.blue
</code>```

2.

```<code>button.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.blue], for: .disabled)
</code>```

Neither of them seems to work. Is there a way to change the color of a disabled toolbar item?

note: this item was created in the storyboard and I am loading it from an outlet
edit: I should have explained this earlier but the buttons have pictures and the tint color seems to be the only thing that works for changing the color of the image.

答:
It's Xcode bug. Use UIButton instead. You can just drag and drop it into the tabbar in storyboard.

And then just use title color:

```<code> button.setTitleColor(.blue, for: .disabled)
</code>```

Title: Change color of disabled toolbar button

Body:
I need to change the color of a disabled toolbar button. I have tried multiple methods.

1.

button.isEnabled = false
button.tintColor = UIColor.blue

2.

button.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.blue], for: .disabled)

Neither of them seems to work. Is there a way to change the color of a disabled toolbar item?

note: this item was created in the storyboard and I am loading it from an outlet
edit: I should have explained this earlier but the buttons have pictures and the tint color seems to be the only thing that works for changing the color of the image.

Body:
It's Xcode bug. Use UIButton instead. You can just drag and drop it into the tabbar in storyboard.

And then just use title color:

 button.setTitleColor(.blue, for: .disabled)


问:
Having a single default argument in a controller action expecting multiple
My controller action expects several arguments, but only one can be nullable on POST. It is of type decimal. Based on the research I've done for default routing, it looks limited to setting a default value for an action expecting a single parameter.

This is the response message I get due to this:

MVC : The parameters dictionary contains a null entry for parameter 'z' of non-nullable type 'System.Decimal'

Here is the method signature in BarController.cs:

```<code>[HttpPost]
public PartialViewResult Bar(int x, string y, decimal z) {*/Etc*/}
</code>```

Here is the route I attempted but was not successful (RouteConfig.cs):

```<code>routes.MapRoute(name: "Bar", url: "Foo/Bar/z",
defaults: new {controller = "Foo", action = "Bar", z= 0 });
</code>```

My request body has values for x and z, but y can be nullable.

How do I refactor so that z can be nullable? Apart from literally making it a nullable decimal type. I already have algorithms that subscribe to the Decimal type, not the nullable variant.

答: Use a nullable parameter like decimal? or int? in your action.</p>

Body:
My controller action expects several arguments, but only one can be nullable on POST. It is of type decimal. Based on the research I've done for default routing, it looks limited to setting a default value for an action expecting a single parameter.

This is the response message I get due to this:

MVC : The parameters dictionary contains a null entry for parameter 'z' of non-nullable type 'System.Decimal'

Here is the method signature in BarController.cs:

[HttpPost]
public PartialViewResult Bar(int x, string y, decimal z) {*/Etc*/}

Here is the route I attempted but was not successful (RouteConfig.cs):

routes.MapRoute(name: "Bar", url: "Foo/Bar/z",
defaults: new {controller = "Foo", action = "Bar", z= 0 });

My request body has values for x and z, but y can be nullable.

How do I refactor so that z can be nullable? Apart from literally making it a nullable decimal type. I already have algorithms that subscribe to the Decimal type, not the nullable variant.


问:
SSRS Report - Removing right side white space
I'm developing an SSRS report in Visual Studio 2012. The report is set up to use landscape orientation. There is a 0.25in margin on the left and no margin on the right. The report is 10.5 inches wide. ConsumeContainerWhitespace is set to True. There are no hidden objects outside of the normal report area.

When I look at the report in print view or actually print it out there is a huge amount of white space on the right side of the report. It's almost like the report is being shrunk and then left justified when printing.

I would love to get this fixed so the report prints the same as it looks in the designer. If anyone has an opinion or some input it would be most welcome. Thank you!

答:
This problem appears when a Windows 10 user has their DPI set to a value that is higher than %100. If DPI is set to %100 then the issue does not occur and no white space is seen when doing a print view or actually printing the report.

This is a common issue with Windows 10 and certain applications including ClickOnce apps like the one I'm using to run the reports. There does not seem to be a way to fix this from within Visual Studio as you can't make an application DPI aware that uses the ClickOnce deployment model.

The following steps will fix a Report temporarily until it is updated and the .exe is overwritten. This fix will also work for other Windows 10 apps, including Chrome, that appear blurry from using a custom DPI over %100. Be aware though that while this fix will fix blurry fonts in a ClickOnce app and white space in an SSRS report it can also disturb control positioning and form size.

Navigate to C:\Users\\AppData\Local\Apps\2.0

Under the 2.0 directory you will see one or more folders that are named with a random set of letters and numbers. Within these directories you must find the folder for the desired application. The folders will usually start with the first 3 or four letters of the application but there can be more than one folder that exists for your application.

Locate the .exe for your application. There may be more than one .exe for your app so apply this fix fix to all of them just to be sure.

Rightclick on the .exe and select properties and click the Compatibility tab.

Check the Disable display scaling on high DPI settings checkbox and click OK

Rerun your application and create a report that opens the report viewer.

Click the Print Layout button. The report should now be displayed with no white space on the right.

Print the report. There should be no extra white space on the right side of the report.

You can also work around the issue by temporarily setting your DPI back to %100 but I think that is a poor solution.


问:
jquery how to fill select option in my form
enter image description here
The json (data) looks like this
guys! I have a little form. Like this:

```<code><form method="post" action="" id="ajaxform">
<input type="text" size="32" maxlength="36" name="name" placeholder="Вaшe имя" val="">
        <select id="activity_2" name="activity_2">
        <option value="">Exmaple</option>
        </select>
<input type="submit" value="GO GO GO"/>
</form>
<script src="/add-information/aa.js"></script>
</code>```

In this little code i receive a json with data from my database:

```<code>        var data = JSON.parse(response);
        console.log(data);
</code>```

in data there is id and name of the rubric. How can i load all this array in my option list?
I was told to do something like this:

```<code>var select = document.getelementById('activity_2'); // id of the select
select.options[i] = new Option(data.id, data.od); // add data?
</code>```

help me please, how i can fill select with data from 'data'?

THE SOLUTION BY ADEON IS:

var data = JSON.parse(response);
        console.log(data);

```<code>    var select = document.getElementById('activity_2');

    for (var i = 0; i < data.data.length; i++) {
    select.options[select.length] = new Option(data.data[i].name_rus, data.data[i].id);
        }
</code>```

答:
You need to do these:

1) Your call getelementById should be changed to getElementById otherwise you would receive error.

2) You need to create options string first and then append that string to DOM rather than touching DOM every time you add options. Touching DOM as less as possible is a good idea from performance point of view.

3) To simplify the syntax you can use string interpolation syntax like below:

var select = document.getElementById('activity_2');
//$(select).html('');
var data = [{id:1, name_rom:'a', name_rus:'abc'},{id:2, name_rom:'x', name_rus:'xyz'}];
var options = "";
for (var i = 0; i < data.length; i++) {
  options += `<option value=${data[i].id}>${data[i].name_rus}</option>`;//<--string
                                                             //interpolation
}
$(select).append(options);
//OR below, so you don't need to call document.getElementById
//$('#activity_2').append(options);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" action="" id="ajaxform">
  <input type="text" size="32" maxlength="36" name="name" placeholder="Вaшe имя" val="">
  <select id="activity_2" name="activity_2">
        <option value="">Exmaple</option>
  </select></code>```

Body:
enter image description here
The json (data) looks like this
guys! I have a little form. Like this:

<form method="post" action="" id="ajaxform">
<input type="text" size="32" maxlength="36" name="name" placeholder="Вaшe имя" val="">
        <select id="activity_2" name="activity_2">
        <option value="">Exmaple</option>
        </select>
<input type="submit" value="GO GO GO"/>
</form>

In this little code i receive a json with data from my database:

        var data = JSON.parse(response);
        console.log(data);

in data there is id and name of the rubric. How can i load all this array in my option list?
I was told to do something like this:

var select = document.getelementById('activity_2'); // id of the select
select.options[i] = new Option(data.id, data.od); // add data?

help me please, how i can fill select with data from 'data'?

THE SOLUTION BY ADEON IS:

var data = JSON.parse(response);
        console.log(data);

    var select = document.getElementById('activity_2');

    for (var i = 0; i < data.data.length; i++) {
    select.options[select.length] = new Option(data.data[i].name_rus, data.data[i].id);
        }

Body:
You need to do these:

1) Your call getelementById should be changed to getElementById otherwise you would receive error.

2) You need to create options string first and then append that string to DOM rather than touching DOM every time you add options. Touching DOM as less as possible is a good idea from performance point of view.

3) To simplify the syntax you can use string interpolation syntax like below:

var select = document.getElementById('activity_2');
//$(select).html('');
var data = [{id:1, name_rom:'a', name_rus:'abc'},{id:2, name_rom:'x', name_rus:'xyz'}];
var options = "";
for (var i = 0; i < data.length; i++) {
  options += `<option value=${data[i].id}>${data[i].name_rus}</option>`;//<--string
                                                             //interpolation
}
$(select).append(options);
//OR below, so you don't need to call document.getElementById
//$('#activity_2').append(options);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" action="" id="ajaxform">
  <input type="text" size="32" maxlength="36" name="name" placeholder="Вaшe имя" val="">
  <select id="activity_2" name="activity_2">
        <option value="">Exmaple</option>
  </select>


问:
HTTP Authentication equivalent for cURL username:password
Is there a way to convert the following curl into an normal http request?

curl --user <username>:<password> https://{username}.fred.sensetecnic.com/api/{custom_endpoint_name}

Into something like this (using Postman for the http requests)

```<code>GET https://{username}.fred.sensetecnic.com/api/{custom_endpoint_name}

Headers: Username: username, Password: password
</code>```

答:
Use Basic Auth provided in postman.

Goto Authorization tab.

Select Basic Auth from Type dropdown list.

Add username and password.

Click Update request(if applicable).

Note: For this to work, server must accept json encoded credentials.

Click on Headers.

Select Content type

Add key-value pairs, Username and Password

Body:
Is there a way to convert the following curl into an normal http request?

curl --user <username>:<password> https://{username}.fred.sensetecnic.com/api/{custom_endpoint_name}

Into something like this (using Postman for the http requests)

GET https://{username}.fred.sensetecnic.com/api/{custom_endpoint_name}

Headers: Username: username, Password: password


问:
How to use background-image: with php
How can I use background-image: url() in conjunction with php in order to obtain the directory of the image I would like to display.

CSS

```<code>.imageGallery {
width: 960px;
position: relative;
background-image: url('<?php bloginfo("template_directory");?>/images/visitus.png');
}
</code>```

Currently, this css does not work. No background image is displayed.

HTML

```<code><div class="imageGallery">
</div>
</code>```

For example:

this works fine

```<code><img src='<?php bloginfo("template_directory");?>/images/home.png' class="headImage" />
</code>```

but this doesn't

```<code>    background-image: url('<?php bloginfo("template_directory");?>/images/visitus.png');
</code>```

答:
It depenteds to where is your css file , put your css file and image file into same place, and try below

```<code>background-image: url("frame.jpg");
</code>```

Or you can use / to start from root folder.

```<code>background-image: url("/frame.jpg");
</code>```

Read this.

Title: How to use background-image: with php

Body:
How can I use background-image: url() in conjunction with php in order to obtain the directory of the image I would like to display.

CSS

.imageGallery {
width: 960px;
position: relative;
background-image: url('<?php bloginfo("template_directory");?>/images/visitus.png');
}

Currently, this css does not work. No background image is displayed.

HTML

For example:

this works fine

<img src='<?php bloginfo("template_directory");?>/images/home.png' class="headImage" />

but this doesn't

    background-image: url('<?php bloginfo("template_directory");?>/images/visitus.png');

Body:
It depenteds to where is your css file , put your css file and image file into same place, and try below

background-image: url("frame.jpg");

Or you can use / to start from root folder.

background-image: url("/frame.jpg");

Read this.


问:
How to limit a container's width to X when it contains a wider (>X) image?
I need my div element to be as wide as the screen even when its child image element is wider than that. Is that possible? I tried overflow: hidden on the div to no avail.

```<code><div>
    <img src="image.jpg">
</div>
</code>```

答:
You can use the following:

div {
  width: 100%;
  height: 100px;
}

div img {
  width: inherit;
  height: inherit;
  background-size: cover;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <img src="http://placehold.it/1600" />
</div></code>```

Body:
You can use the following:

div {
  width: 100%;
  height: 100px;
}

div img {
  width: inherit;
  height: inherit;
  background-size: cover;
}

<div>
  <img src="http://placehold.it/1600" />
</div>


问:
Ajax - Notice : Undefined index when using $_GET in PHP
I'm creating for a school assignment a sort of social media platform. I've created a simple chat tool. Each friend relation has a single conversation.

The problem is that when I reload all the chat messages using Ajax, I can't use the $_GET method to get the conversation id which I saved in the url. Without this id I can't use the function in my Chat class.
I'm sorry if some code is written in Dutch.

The url looks like this chat.php?gesprek_id=1. Gesprek or Conversation Id is like I said saved in the url. After the Ajax request I receive the notice:

'Notice: Undefined index: gesprek_id in ...'

It refers to the $_GET method in php.

My code:

Chat Class:

```<code>public function getNewMessages($gesprekId){
    $conn = Db::getInstance();
    $stm = $conn->prepare("SELECT * from chat WHERE gesprek_id = :gesprek_id AND tijd > :tijd");
    $stm->bindValue(":gesprek_id", $gesprekId, PDO::PARAM_STR);
    $stm->bindValue(":tijd", $_SERVER['REQUEST_TIME'], PDO::PARAM_STR);
    $stm->execute();
    $res = $stm->fetchAll();
    return $res;
}
</code>```

Php for Ajax

```<code><?php
header('Content-Type: application/json');

include_once('../classes/Db.php');
include_once('../classes/Chat.php');

session_start();

$gesprekId = $_GET['gesprek_id'];

$chat = new \Kvm\Chat();
$newMessages = $chat->getNewMessages($gesprekId);
?>

<?php foreach ($newMessages as $message): ?>
    <?php $profile = $chat->getUserMessage($message['user_id']); ?>
        <?php if ($message['user_id'] == $_SESSION['user_id']): ?>
            <div id="messageBlock" class="blockRed">
                <div class="profile-chat">
                    <img class="profileSmall" src="<?php echo $profile['avatar']; ?>"/>
                <div>
                    <h4 class="username"><?php echo $profile['firstname'] . ' ' . $profile['lastname']; ?></h4>
                </div>
            </div>
            <p class="message"><?php echo $message['message'] ?></p>
        </div>
    <?php else: ?>
        <div id="messageBlock" class="blockYellow">
            <div class="profile-chat">
                <img class="profileSmall src="<?php echo $profile['avatar']; ?>"/>
                <div>
                    <h4 class="username"><?php echo $profile['firstname'] . ' ' . $profile['lastname']; ?></h4>
                </div>
            </div>
            <p class="message"><?php echo $message['message'] ?></p>
        </div>
    <?php endif; ?>
<?php endforeach; ?>
</code>```

Edit in Ajax (added a few lines to find the correct 'gesprek_id' with the solution of the $_GET issue)
Ajax/Jquery:

```<code>$(document).ready(function () {

function loadchat() {
    var messageList = $('#allMessages');
    var gesprekId = $('.message').attr('data-gesprekId');
    $(messageList).load('ajax/newChat.php?gesprek_id='+gesprekId);
}
setInterval(loadchat, 50000);
loadchat();
});
</code>```

I hope that my question is clear.

It's also my first question asked in Stackoverflow so I'm sorry if something is not well described. (and sorry if I made some errors in English ;) )
Thank you by advance.

答:
Change your call to

```<code>$(messageList).load('ajax/newChat.php?gesprek_id=abc');
</code>```

It should start working.

Basically, you're trying to make a GET request to newChat.php . You're trying to access the same parameter in PHP. Since, there are no GET parameters, GET is throwing a warning.

But, in this load function. you're not sending any GET parameters. Hence, the change to gesprek_id=abc.

About doing a polling repeatedly, You need to rewrite the setInterval function better.

```<code>setInterval(function() {
      // Do something every 5 seconds
      loadchat();
}, 5000);
</code>```

I'm not sure if this is the ideal way. Something feels a little odd here. But, I would think, there will be better ways of doing this. Anyhow, I've rewritten the setInterval call for you.

Body:
I'm creating for a school assignment a sort of social media platform. I've created a simple chat tool. Each friend relation has a single conversation.

The problem is that when I reload all the chat messages using Ajax, I can't use the $_GET method to get the conversation id which I saved in the url. Without this id I can't use the function in my Chat class.
I'm sorry if some code is written in Dutch.

The url looks like this chat.php?gesprek_id=1. Gesprek or Conversation Id is like I said saved in the url. After the Ajax request I receive the notice:

'Notice: Undefined index: gesprek_id in ...'

It refers to the $_GET method in php.

My code:

Chat Class:

public function getNewMessages($gesprekId){
    $conn = Db::getInstance();
    $stm = $conn->prepare("SELECT * from chat WHERE gesprek_id = :gesprek_id AND tijd > :tijd");
    $stm->bindValue(":gesprek_id", $gesprekId, PDO::PARAM_STR);
    $stm->bindValue(":tijd", $_SERVER['REQUEST_TIME'], PDO::PARAM_STR);
    $stm->execute();
    $res = $stm->fetchAll();
    return $res;
}

Php for Ajax

<?php
header('Content-Type: application/json');

include_once('../classes/Db.php');
include_once('../classes/Chat.php');

session_start();

$gesprekId = $_GET['gesprek_id'];

$chat = new \Kvm\Chat();
$newMessages = $chat->getNewMessages($gesprekId);
?>

<?php foreach ($newMessages as $message): ?>
    <?php $profile = $chat->getUserMessage($message['user_id']); ?>
        <?php if ($message['user_id'] == $_SESSION['user_id']): ?>

                    <img class="profileSmall" src="<?php echo $profile['avatar']; ?>"/>

<?php echo $profile['firstname'] . ' ' . $profile['lastname']; ?>

<?php echo $message['message'] ?>

    <?php else: ?>

                <img class="profileSmall src="<?php echo $profile['avatar']; ?>"/>

<?php echo $profile['firstname'] . ' ' . $profile['lastname']; ?>

<?php echo $message['message'] ?>

    <?php endif; ?>
<?php endforeach; ?>

Edit in Ajax (added a few lines to find the correct 'gesprek_id' with the solution of the $_GET issue)
Ajax/Jquery:

$(document).ready(function () {

function loadchat() {
    var messageList = $('#allMessages');
    var gesprekId = $('.message').attr('data-gesprekId');
    $(messageList).load('ajax/newChat.php?gesprek_id='+gesprekId);
}
setInterval(loadchat, 50000);
loadchat();
});

I hope that my question is clear.

It's also my first question asked in Stackoverflow so I'm sorry if something is not well described. (and sorry if I made some errors in English ;) )
Thank you by advance.

Body:
Change your call to

$(messageList).load('ajax/newChat.php?gesprek_id=abc');

It should start working.

Basically, you're trying to make a GET request to newChat.php . You're trying to access the same parameter in PHP. Since, there are no GET parameters, GET is throwing a warning.

But, in this load function. you're not sending any GET parameters. Hence, the change to gesprek_id=abc.

About doing a polling repeatedly, You need to rewrite the setInterval function better.

setInterval(function() {
      // Do something every 5 seconds
      loadchat();
}, 5000);

I'm not sure if this is the ideal way. Something feels a little odd here. But, I would think, there will be better ways of doing this. Anyhow, I've rewritten the setInterval call for you.


问:
How can I programmatically modify an embedded bar/column chart with VBA?
I'm creating a ProcessBook display that populates an embedded Microsoft Office 11.0 Spreadsheet object (Office 2003) with a set of entries. I'm then calculating aggregate data about them; this aggregate data should not be visible in spreadsheet form onscreen, but does need to be used to generate a bar chart. The data is currently being used to populate a separate Microsoft Office 11.0 Spreadsheet object. It's organized such that the title of each bar chart is in column A and the corresponding value is in column B.

Since this is ProcessBook, I've had some difficulty even gaining access to embedded objects, but I've managed to embed and gain access to a ChartSpace object, as well as a child ChChart object. Unfortunately, I can't figure out how to either manually set the values of the bars or how to use the .SetData or .SetSpreadsheetData methods to point it to an object that I've populated.

Accessing the ChartSpace object is pretty straightforward: ThisDisplay.ChartSpace1

I can then add a Chart and access it fairly easily:

Dim objChart as ChChart

Set objChart = ThisDisplay.ChartSpace1.Charts.Add(0)

I can access my spreadsheet values pretty easily as well:

strBarName = ThisDisplay.sstChartData.Range("A2").Value

intBarVal = ThisDisplay.sstChartData.Range("B2").Value

How do I actually set the data source or manually set the values of the bars in the ChChart object? Alternatively, how do I use a different object to accomplish the same goal?

答:
Apparently persistence is the key here. I managed to determine how to both add values manually and how to refer to the existing spreadsheet object. Both examples take heavily from the online ChChart documentation; I guess I was just tired when I attempted it in the first place and must have mistyped something somewhere.

```<code>Public Sub AddValuesToChartManually()
Dim objChart As ChChart
With ThisDisplay.ChartSpace1
    Do While .Charts.Count > 0
        ThisDisplay.ChartSpace1.Charts.Delete (0)
    Loop

    Set objChart = .Charts.Add
    objChart.HasTitle = True
    objChart.Title.Caption = "Chart Title"
    objChart.Axes.Item(0).HasTitle = True
    objChart.Axes.Item(1).HasTitle = True
    objChart.Axes.Item(0).Title.Caption = "Axis 0"
    objChart.Axes.Item(1).Title.Caption = "Axis 1"
    objChart.HasLegend = False

    Dim astrHeaders(0 To 4) As String
    Dim aintValues1(0 To 4) As String
    Dim aintValues2(0 To 4) As String
    Dim astrSeries1(0) As String
    Dim astrSeries2(0) As String

    astrHeaders(0) = "AL1"
    astrHeaders(1) = "AL2"
    astrHeaders(2) = "AL3"
    astrHeaders(3) = "AL4"
    astrHeaders(4) = "AL5"

    astrSeries(0) = "Series Name"

    aintValues(0) = 1
    aintValues(1) = 3
    aintValues(2) = 17
    aintValues(3) = 1
    aintValues(4) = 7

    objChart.Type = .Constants.chChartTypeColumnClustered

    Call objChart.SetData(chDimSeriesName, .Constants.chDataLiteral, astrSeries)
    Call objChart.SetData(chDimCategories, .Constants.chDataLiteral, astrHeaders)
    Call objChart.SeriesCollection(0).SetData(.Constants.chDimValues, .Constants.chDataLiteral, aintValues)

End With
End Sub

Public Sub AddValuesFromSpreadsheet()
Dim objChart1 As ChChart

With ThisDisplay.ChartSpace1
    Do While .Charts.Count > 0
        ThisDisplay.ChartSpace1.Charts.Delete (0)
    Loop

    Set .DataSource = ThisDisplay.sstChartData

    Set objChart1 = .Charts.Add
    ' Set the chart type.
    objChart1.Type = .Constants.chChartTypeColumnClustered

    ' Display titles
    objChart1.HasTitle = True
    objChart1.Title.Caption = "Chart Title"

    ' Bind the series name to cell B1 in the first sheet of the spreadsheet
    objChart1.SetData chDimSeriesNames, .Constants.chDataBound, "B1"

    ' Bind the category axis to cell A2:A28 in the first sheet of the spreadsheet.
    objChart1.SetData chDimCategories, .Constants.chDataBound, "A2:A6"

    ' Bind the values of the data series to cells B2:B28 in the first sheet of the spreadsheet.
    objChart1.SeriesCollection(0).SetData chDimValues, .Constants.chDataBound, "B2:B6"

End With
End Sub
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Apparently persistence is the key here. I managed to determine how to both add values manually and how to refer to the existing spreadsheet object. Both examples take heavily from the online ChChart documentation; I guess I was just tired when I attempted it in the first place and must have mistyped something somewhere.

Public Sub AddValuesToChartManually()
Dim objChart As ChChart
With ThisDisplay.ChartSpace1
    Do While .Charts.Count > 0
        ThisDisplay.ChartSpace1.Charts.Delete (0)
    Loop

    Set objChart = .Charts.Add
    objChart.HasTitle = True
    objChart.Title.Caption = "Chart Title"
    objChart.Axes.Item(0).HasTitle = True
    objChart.Axes.Item(1).HasTitle = True
    objChart.Axes.Item(0).Title.Caption = "Axis 0"
    objChart.Axes.Item(1).Title.Caption = "Axis 1"
    objChart.HasLegend = False

    Dim astrHeaders(0 To 4) As String
    Dim aintValues1(0 To 4) As String
    Dim aintValues2(0 To 4) As String
    Dim astrSeries1(0) As String
    Dim astrSeries2(0) As String

    astrHeaders(0) = "AL1"
    astrHeaders(1) = "AL2"
    astrHeaders(2) = "AL3"
    astrHeaders(3) = "AL4"
    astrHeaders(4) = "AL5"

    astrSeries(0) = "Series Name"

    aintValues(0) = 1
    aintValues(1) = 3
    aintValues(2) = 17
    aintValues(3) = 1
    aintValues(4) = 7

    objChart.Type = .Constants.chChartTypeColumnClustered

    Call objChart.SetData(chDimSeriesName, .Constants.chDataLiteral, astrSeries)
    Call objChart.SetData(chDimCategories, .Constants.chDataLiteral, astrHeaders)
    Call objChart.SeriesCollection(0).SetData(.Constants.chDimValues, .Constants.chDataLiteral, aintValues)

End With
End Sub

Public Sub AddValuesFromSpreadsheet()
Dim objChart1 As ChChart

With ThisDisplay.ChartSpace1
    Do While .Charts.Count > 0
        ThisDisplay.ChartSpace1.Charts.Delete (0)
    Loop

    Set .DataSource = ThisDisplay.sstChartData

    Set objChart1 = .Charts.Add
    ' Set the chart type.
    objChart1.Type = .Constants.chChartTypeColumnClustered

    ' Display titles
    objChart1.HasTitle = True
    objChart1.Title.Caption = "Chart Title"

    ' Bind the series name to cell B1 in the first sheet of the spreadsheet
    objChart1.SetData chDimSeriesNames, .Constants.chDataBound, "B1"

    ' Bind the category axis to cell A2:A28 in the first sheet of the spreadsheet.
    objChart1.SetData chDimCategories, .Constants.chDataBound, "A2:A6"

    ' Bind the values of the data series to cells B2:B28 in the first sheet of the spreadsheet.
    objChart1.SeriesCollection(0).SetData chDimValues, .Constants.chDataBound, "B2:B6"

End With
End Sub