问:
How to Insert Session Array into MySQL DB using PHP
I have a multi page form and am trying to capture an array as a session to insert into mysql. Page two of the form is the  "Address" section. Here I ask for Address information. The user can hit a "enter another address" button which expands another box.

The user hits next to go to the next page (phone.php) where I ask for phone info. On this page I think I am  registering the session data correctly like so:

```<code>if(!isset($_SESSION))
{
@session_start();
}
header("Cache-control: private");
ob_start();

include('header.php');

//now, let's register our session variables from address.php
session_register('addressLineOne');
session_register('addressLineTwo');

//finally, let's store our posted values in the session variables
$_SESSION['addressLineOne'] = $_POST['addressLineOne'];
$_SESSION['addressLineTwo'] = $_POST['addressLineTwo'];
</code>```

Eventually we hit the submit.php . If I disable the code to add an additional address, this is the insert I am using which works fine.

```<code> $insertAddress="INSERT INTO address (idperson, addressLineOne, addressLineTwo)
 VALUES ( '$id','$_SESSION[addressLineOne]','$_SESSION[addressLineTwo]')";
 if (!mysql_query($insertAddress,$con))
   {die('Error: ' . mysql_error());}
 echo "";
</code>```

When I enable the "add additional address" code, the insert above will insert "ARRAY" into every DB field. I have been trying out the following:

```<code> foreach($_SESSION['idperson'] as $row=>$id)
{
    $idperson=$id;
    $addressLineOne=$_SESSION['addressLineOne'][$row];
    $addressLineTwo=$_SESSION['addressLineTwo'][$row];
}
 //enter rows into database
 foreach($_SESSION['idperson'] as $row=>$id)
{
    $idperson=mysql_real_escape_string($id);
    $addressLineOne=mysql_real_escape_string($_SESSION['addressLineOne'][$row]);
    $addressLineTwo=mysql_real_escape_string($_SESSION['addressLineTwo'][$row]);
}

 $insertAddress="INSERT INTO address (idperson, addressLineOne, addressLineTwo)
 VALUES ('.$id.','.$addressLineOne.','.$addressLineTwo.')";

 if (!mysql_query($insertAddress,$con))
 {
 die('Error: ' . mysql_error());
 }
 echo "$row record added";
</code>```

Instead of working, however, the above just inserts a couple of dots like "..." into the database. I don't know what else to do. Am I not grabbing the session data correctly? Is my foreach code way off? Thanks for any help.

Here is the code i'm using to add another table on address.php:

```<code> <?php for($i=1; $i<6; $i++):?>
 <div id='hidden<?php echo $i; ?>' style='display: none'>
<tr class="odd">
    <td width="33%">Street/Number</td>
    <td><input type="text" name="addressLineOne[]" id="addressLineOne<?php echo $i; ?>"/></td>
</tr>
<tr>
    <td>Address 2</td>
    <td><input type="text" name="addressLineTwo[]" id="addressLineTwo<?php echo $i; ?>"/></td>
</tr>
 <?php endfor; ?>
</code>```

Submit.php doesn't have anything besides connecting to the db and the above insert.

答:
So just going through and doing some cleanup:

Your first block:

No need to condition calling session_start, it's safe to just call it at the top of your script. Also, don't suppress warnings there, if you're getting warnings, find the root cause and eliminate them.

```<code>session_start();
header("Cache-control: private");
ob_start();
include('header.php');
</code>```

No need to register session variables with session_register, it's deprecated now and the manual says don't use it -- especially don't use it mixing with use of $_SESSION sets.

```<code>$_SESSION['addressLineOne'] = $_POST['addressLineOne'];
$_SESSION['addressLineTwo'] = $_POST['addressLineTwo'];
</code>```

So $_SESSION now contains at least two keys corresponding to what's just been set.

The rest of your problem stems from likely iterating through your array structure incorrectly (show us some more of your code).

Some cleanup on your second block:

There's no need to iterate through your list twice -- assuming you're iterating correctly, you just need to go through once and run the insert every time (rather than at the end).  This does assume you want one row per address indexed by the id.

Also, you might reconsider your use of die as an error control mechanism, it'll simply terminate the entire script execution -- is that really what you want?

```<code>// enter rows into database
foreach($_SESSION['addressLineOne'] as $row => $id){
    $idperson = mysql_real_escape_string($_SESSION['idperson']);
    $addressLineOne = mysql_real_escape_string($_SESSION['addressLineOne'][$row]);
    $addressLineTwo = mysql_real_escape_string($_SESSION['addressLineTwo'][$row]);
    $insertAddress="INSERT INTO address (idperson, addressLineOne, addressLineTwo)
                    VALUES ('.$id.','.$addressLineOne.','.$addressLineTwo.')";
    if(!mysql_query($insertAddress,$con)){
        // maybe not the best use of `die` here?
        die('Error: ' . mysql_error());
    }
    echo "$row record added";
}
</code>```

Body:
I have a multi page form and am trying to capture an array as a session to insert into mysql. Page two of the form is the  "Address" section. Here I ask for Address information. The user can hit a "enter another address" button which expands another box.

The user hits next to go to the next page (phone.php) where I ask for phone info. On this page I think I am  registering the session data correctly like so:

if(!isset($_SESSION))
{
@session_start();
}
header("Cache-control: private");
ob_start();

include('header.php');

//now, let's register our session variables from address.php
session_register('addressLineOne');
session_register('addressLineTwo');

//finally, let's store our posted values in the session variables
$_SESSION['addressLineOne'] = $_POST['addressLineOne'];
$_SESSION['addressLineTwo'] = $_POST['addressLineTwo'];

Eventually we hit the submit.php . If I disable the code to add an additional address, this is the insert I am using which works fine.

 $insertAddress="INSERT INTO address (idperson, addressLineOne, addressLineTwo)
 VALUES ( '$id','$_SESSION[addressLineOne]','$_SESSION[addressLineTwo]')";
 if (!mysql_query($insertAddress,$con))
   {die('Error: ' . mysql_error());}
 echo "";

When I enable the "add additional address" code, the insert above will insert "ARRAY" into every DB field. I have been trying out the following:

 foreach($_SESSION['idperson'] as $row=>$id)
{
    $idperson=$id;
    $addressLineOne=$_SESSION['addressLineOne'][$row];
    $addressLineTwo=$_SESSION['addressLineTwo'][$row];
}
 //enter rows into database
 foreach($_SESSION['idperson'] as $row=>$id)
{
    $idperson=mysql_real_escape_string($id);
    $addressLineOne=mysql_real_escape_string($_SESSION['addressLineOne'][$row]);
    $addressLineTwo=mysql_real_escape_string($_SESSION['addressLineTwo'][$row]);
}

 $insertAddress="INSERT INTO address (idperson, addressLineOne, addressLineTwo)
 VALUES ('.$id.','.$addressLineOne.','.$addressLineTwo.')";

 if (!mysql_query($insertAddress,$con))
 {
 die('Error: ' . mysql_error());
 }
 echo "$row record added";

Instead of working, however, the above just inserts a couple of dots like "..." into the database. I don't know what else to do. Am I not grabbing the session data correctly? Is my foreach code way off? Thanks for any help.

Here is the code i'm using to add another table on address.php:

 <?php for($i=1; $i<6; $i++):?>
 <div id='hidden<?php echo $i; ?>' style='display: none'>

    Street/Number
    <input type="text" name="addressLineOne[]" id="addressLineOne<?php echo $i; ?>"/>

    Address 2
    <input type="text" name="addressLineTwo[]" id="addressLineTwo<?php echo $i; ?>"/>

 <?php endfor; ?>

Submit.php doesn't have anything besides connecting to the db and the above insert.

Body:
So just going through and doing some cleanup:

Your first block:

No need to condition calling session_start, it's safe to just call it at the top of your script. Also, don't suppress warnings there, if you're getting warnings, find the root cause and eliminate them.

session_start();
header("Cache-control: private");
ob_start();
include('header.php');

No need to register session variables with session_register, it's deprecated now and the manual says don't use it -- especially don't use it mixing with use of $_SESSION sets.

$_SESSION['addressLineOne'] = $_POST['addressLineOne'];
$_SESSION['addressLineTwo'] = $_POST['addressLineTwo'];

So $_SESSION now contains at least two keys corresponding to what's just been set.

The rest of your problem stems from likely iterating through your array structure incorrectly (show us some more of your code).

Some cleanup on your second block:

There's no need to iterate through your list twice -- assuming you're iterating correctly, you just need to go through once and run the insert every time (rather than at the end).  This does assume you want one row per address indexed by the id.

Also, you might reconsider your use of die as an error control mechanism, it'll simply terminate the entire script execution -- is that really what you want?

// enter rows into database
foreach($_SESSION['addressLineOne'] as $row => $id){
    $idperson = mysql_real_escape_string($_SESSION['idperson']);
    $addressLineOne = mysql_real_escape_string($_SESSION['addressLineOne'][$row]);
    $addressLineTwo = mysql_real_escape_string($_SESSION['addressLineTwo'][$row]);
    $insertAddress="INSERT INTO address (idperson, addressLineOne, addressLineTwo)
                    VALUES ('.$id.','.$addressLineOne.','.$addressLineTwo.')";
    if(!mysql_query($insertAddress,$con)){
        // maybe not the best use of `die` here?
        die('Error: ' . mysql_error());
    }
    echo "$row record added";
}


来源: stackexchange

问:
Pygame - Smooth Transform of Image/Surface
Is there a way to create a smooth transition between one image and another?

Say I have Image X and Image Y

```<code>ImageX = pygame.image.load('foo.png')
ImageY = pygame.image.load('oof.png')
</code>```

Image X transforms into image Y when W = 5
Normally, I would just do this in the draw code:

```<code>if w == 5:
    screen.blit(ImageY, (100, 100))
else:
    screen.blit(ImageX, (100, 100))
</code>```

But that just makes image X become replaced with ImageY, one frame its imageX, another frame its imageY

How would I make ImageX transition into ImageY smoothly? Like the transition attribute in css.

答:
To set the alpha/transparency of images with per-pixel alpha, you need to use a little trick. You can create an intermediate surface, fill it with white and the desired alpha value and then blit it onto the other surface with the pygame.BLEND_RGBA_MULT flag. That will leave fully transparent pixels untouched and just change the transparency of the visible parts.

So if you want to fade one surface in and the other out, you just have to store their alpha values, change them every frame and then call the change_alpha function to get new surfaces with the right transparency. (I'm using text surfaces in this example, but it works with other surfaces/loaded images as well).

```<code>import pygame as pg

def change_alpha(orig_surf, alpha):
    """Create a copy of orig_surf with the desired alpha value.

    This function creates another surface with the desired alpha
    value and then blits it onto the copy of the original surface
    with the `BLEND_RGBA_MULT` flag to change the transparency."""
    surf = orig_surf.copy()
    # This surface is used to adjust the alpha of the txt_surf.
    alpha_surf = pg.Surface(surf.get_size(), pg.SRCALPHA)
    alpha_surf.fill((255, 255, 255, alpha))  # Set the alpha value.
    surf.blit(alpha_surf, (0, 0), special_flags=pg.BLEND_RGBA_MULT)
    return surf

def main():
    clock = pg.time.Clock()
    screen = pg.display.set_mode((640, 480))
    font = pg.font.Font(None, 64)

    # The original surface which will never be modified.
    orig_surf = font.render('Enter your text', True, pg.Color('dodgerblue'))
    alpha = 255  # The current alpha value of the surface.

    # Surface 2
    orig_surf2 = font.render('Another text surface', True, pg.Color('sienna1'))
    alpha2 = 0

    done = False
    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True

        if alpha > 0:
            # Reduce alpha each frame.
            alpha -= 4
            alpha = max(0, alpha)  # Make sure it doesn't go below 0.
            surf = change_alpha(orig_surf, alpha)
        if alpha2 < 255:
            alpha2 += 4
            alpha2 = min(255, alpha2)
            surf2 = change_alpha(orig_surf2, alpha2)

        screen.fill((30, 30, 30))
        screen.blit(surf, (30, 60))
        screen.blit(surf2, (30, 60))
        pg.display.flip()
        clock.tick(30)

if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Is there a way to create a smooth transition between one image and another?

Say I have Image X and Image Y

ImageX = pygame.image.load('foo.png')
ImageY = pygame.image.load('oof.png')

Image X transforms into image Y when W = 5
Normally, I would just do this in the draw code:

if w == 5:
    screen.blit(ImageY, (100, 100))
else:
    screen.blit(ImageX, (100, 100))

But that just makes image X become replaced with ImageY, one frame its imageX, another frame its imageY

How would I make ImageX transition into ImageY smoothly? Like the transition attribute in css.

Body:
To set the alpha/transparency of images with per-pixel alpha, you need to use a little trick. You can create an intermediate surface, fill it with white and the desired alpha value and then blit it onto the other surface with the pygame.BLEND_RGBA_MULT flag. That will leave fully transparent pixels untouched and just change the transparency of the visible parts.

So if you want to fade one surface in and the other out, you just have to store their alpha values, change them every frame and then call the change_alpha function to get new surfaces with the right transparency. (I'm using text surfaces in this example, but it works with other surfaces/loaded images as well).

import pygame as pg

def change_alpha(orig_surf, alpha):
    """Create a copy of orig_surf with the desired alpha value.

    This function creates another surface with the desired alpha
    value and then blits it onto the copy of the original surface
    with the `BLEND_RGBA_MULT` flag to change the transparency."""
    surf = orig_surf.copy()
    # This surface is used to adjust the alpha of the txt_surf.
    alpha_surf = pg.Surface(surf.get_size(), pg.SRCALPHA)
    alpha_surf.fill((255, 255, 255, alpha))  # Set the alpha value.
    surf.blit(alpha_surf, (0, 0), special_flags=pg.BLEND_RGBA_MULT)
    return surf

def main():
    clock = pg.time.Clock()
    screen = pg.display.set_mode((640, 480))
    font = pg.font.Font(None, 64)

    # The original surface which will never be modified.
    orig_surf = font.render('Enter your text', True, pg.Color('dodgerblue'))
    alpha = 255  # The current alpha value of the surface.

    # Surface 2
    orig_surf2 = font.render('Another text surface', True, pg.Color('sienna1'))
    alpha2 = 0

    done = False
    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True

        if alpha > 0:
            # Reduce alpha each frame.
            alpha -= 4
            alpha = max(0, alpha)  # Make sure it doesn't go below 0.
            surf = change_alpha(orig_surf, alpha)
        if alpha2 < 255:
            alpha2 += 4
            alpha2 = min(255, alpha2)
            surf2 = change_alpha(orig_surf2, alpha2)

        screen.fill((30, 30, 30))
        screen.blit(surf, (30, 60))
        screen.blit(surf2, (30, 60))
        pg.display.flip()
        clock.tick(30)

if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()


问:
Upgrading Gitlab 7.3.2 to current Release
We are running an old Gitlab Instance with 7.3.2 Omnibus Installation as I see. The Server was setup by someone who is not longer reachable. I tried to upgrade directly through omnibus from 7 to 10 but that did not work. When executing gitlab-ctl reconfigure I get the following Error

```<code>Recipe: gitlab::database_migrations
  * bash[migrate gitlab-rails database] action run
    [execute] rake aborted!
              PG::ConnectionBad: could not connect to server: No such file or directory
                Is the server running locally and accepting
                connections on Unix domain socket "/var/opt/gitlab/postgresql/.s.PGSQL.5432"?
              /opt/gitlab/embedded/service/gitlab-rails/lib/tasks/gitlab/db.rake:49:in `block (3 levels) in <top (required)>'
              /opt/gitlab/embedded/bin/bundle:23:in `load'
              /opt/gitlab/embedded/bin/bundle:23:in `<main>'
              Tasks: TOP => gitlab:db:configure
              (See full trace by running task with --trace)

    ================================================================================
    Error executing action `run` on resource 'bash[migrate gitlab-rails database]'
    ================================================================================

    Mixlib::ShellOut::ShellCommandFailed
    ------------------------------------
    Expected process to exit with [0], but received '1'
    ---- Begin output of "bash"  "/tmp/chef-script20171203-14483-19wea60" ----
    STDOUT: rake aborted!
    PG::ConnectionBad: could not connect to server: No such file or directory
        Is the server running locally and accepting
        connections on Unix domain socket "/var/opt/gitlab/postgresql/.s.PGSQL.5432"?
    /opt/gitlab/embedded/service/gitlab-rails/lib/tasks/gitlab/db.rake:49:in `block (3 levels) in <top (required)>'
    /opt/gitlab/embedded/bin/bundle:23:in `load'
    /opt/gitlab/embedded/bin/bundle:23:in `<main>'
    Tasks: TOP => gitlab:db:configure
    (See full trace by running task with --trace)
    STDERR:
    ---- End output of "bash"  "/tmp/chef-script20171203-14483-19wea60" ----
    Ran "bash"  "/tmp/chef-script20171203-14483-19wea60" returned 1

     Resource Declaration:
    ---------------------
    # In /opt/gitlab/embedded/cookbooks/cache/cookbooks/gitlab/recipes/database_migrations.rb

     51: bash "migrate gitlab-rails database" do
     52:   code <<-EOH
     53:     set -e
     54:     log_file="#{node['gitlab']['gitlab-rails']['log_directory']}/gitlab-rails-db-migrate-$(date +%Y-%m-%d-%H-%M-%S).log"
     55:     umask 077
     56:     /opt/gitlab/bin/gitlab-rake gitlab:db:configure 2>& 1 | tee ${log_file}
     57:     STATUS=${PIPESTATUS[0]}
     58:     echo $STATUS > #{db_migrate_status_file}
     59:     exit $STATUS
     60:   EOH
     61:   environment env_variables unless env_variables.empty?
     62:   notifies :run, "execute[clear the gitlab-rails cache]", :immediately
     63:   dependent_services.each do |svc|
     64:     notifies :restart, svc, :immediately
     65:   end
     66:   not_if "(test -f #{db_migrate_status_file}) && (cat #{db_migrate_status_file} | grep -Fx 0)"
     67:   only_if { node['gitlab']['gitlab-rails']['auto_migrate'] }
     68: end

    Compiled Resource:
    ------------------
    # Declared in /opt/gitlab/embedded/cookbooks/cache/cookbooks/gitlab/recipes/database_migrations.rb:51:in `from_file'

    bash("migrate gitlab-rails database") do
      action [:run]
      retries 0
      retry_delay 2
      default_guard_interpreter :default
      command "migrate gitlab-rails database"
      backup 5
      returns 0
      code "    set -e\n    log_file=\"/var/log/gitlab/gitlab-rails/gitlab-rails-db-migrate-$(date +%Y-%m-%d-%H-%M-%S).log\"\n    umask 077\n    /opt/gitlab/bin/gitlab-rake gitlab:db:configure 2>& 1 | tee ${log_file}\n    STATUS=${PIPESTATUS[0]}\n    echo $STATUS > /var/opt/gitlab/gitlab-rails/upgrade-status/db-migrate-873248b1f0d3a7a5535771a3a1635803-da70bc4\n    exit $STATUS\n"
      interpreter "bash"
      declared_type :bash
      cookbook_name "gitlab"
      recipe_name "database_migrations"
      not_if "(test -f /var/opt/gitlab/gitlab-rails/upgrade-status/db-migrate-873248b1f0d3a7a5535771a3a1635803-da70bc4) && (cat /var/opt/gitlab/gitlab-rails/upgrade-status/db-migrate-873248b1f0d3a7a5535771a3a1635803-da70bc4 | grep -Fx 0)"
      only_if { #code block }
    end

    Platform:
    ---------
    x86_64-linux

Running handlers:
Running handlers complete
Chef Client failed. 3 resources updated in 36 seconds
</code>```

I read a lot in the docs, but there are so much information, that I cannot get the update working.
So what are the required steps to get the installation to a current release and what are the critical steps to take?

答:
In general you should not jump across multiple major versions (i.e. 7.x, 8.x, 9.x and 10.x are major versions. They contain breaking changes.

From your current version of 7.3, I recommend trying to upgrade to 7.14.x, then to 8.0.x, 8.17.x, 9.0, 9.5.x, 10.0, 10.latext (whatever is latest at the time. After each step, verify that the web UI works and you can clone/push. Also follow the logs to check for obvious errors - sudo gitlab-ctl tail.

If you're using the GitLab package repository to upgrade (via yum/apt) you can find the specific version/install command you need to use at https://packages.gitlab.com/gitlab/gitlab-ce. Search for a version string such as 10.1.. Click on the RPM or Deb package for your OS version, then you will see an install command such as apt-get install gitlab-ce=10.1.5-ce.0 (Ubuntu Trusty) or yum install gitlab-ce-10.1.5-ce.0.el7.x86_64 (CentOS/RHEL 7). No need to repeat the curl | bash bit each time.

Body:
We are running an old Gitlab Instance with 7.3.2 Omnibus Installation as I see. The Server was setup by someone who is not longer reachable. I tried to upgrade directly through omnibus from 7 to 10 but that did not work. When executing gitlab-ctl reconfigure I get the following Error

Recipe: gitlab::database_migrations
  * bash[migrate gitlab-rails database] action run
    [execute] rake aborted!
              PG::ConnectionBad: could not connect to server: No such file or directory
                Is the server running locally and accepting
                connections on Unix domain socket "/var/opt/gitlab/postgresql/.s.PGSQL.5432"?
              /opt/gitlab/embedded/service/gitlab-rails/lib/tasks/gitlab/db.rake:49:in `block (3 levels) in <top (required)>'
              /opt/gitlab/embedded/bin/bundle:23:in `load'
              /opt/gitlab/embedded/bin/bundle:23:in `'
              Tasks: TOP => gitlab:db:configure
              (See full trace by running task with --trace)

    ================================================================================
    Error executing action `run` on resource 'bash[migrate gitlab-rails database]'
    ================================================================================

    Mixlib::ShellOut::ShellCommandFailed
    ------------------------------------
    Expected process to exit with [0], but received '1'
    ---- Begin output of "bash"  "/tmp/chef-script20171203-14483-19wea60" ----
    STDOUT: rake aborted!
    PG::ConnectionBad: could not connect to server: No such file or directory
        Is the server running locally and accepting
        connections on Unix domain socket "/var/opt/gitlab/postgresql/.s.PGSQL.5432"?
    /opt/gitlab/embedded/service/gitlab-rails/lib/tasks/gitlab/db.rake:49:in `block (3 levels) in <top (required)>'
    /opt/gitlab/embedded/bin/bundle:23:in `load'
    /opt/gitlab/embedded/bin/bundle:23:in `'
    Tasks: TOP => gitlab:db:configure
    (See full trace by running task with --trace)
    STDERR:
    ---- End output of "bash"  "/tmp/chef-script20171203-14483-19wea60" ----
    Ran "bash"  "/tmp/chef-script20171203-14483-19wea60" returned 1

     Resource Declaration:
    ---------------------
    # In /opt/gitlab/embedded/cookbooks/cache/cookbooks/gitlab/recipes/database_migrations.rb

     51: bash "migrate gitlab-rails database" do
     52:   code <<-EOH
     53:     set -e
     54:     log_file="#{node['gitlab']['gitlab-rails']['log_directory']}/gitlab-rails-db-migrate-$(date +%Y-%m-%d-%H-%M-%S).log"
     55:     umask 077
     56:     /opt/gitlab/bin/gitlab-rake gitlab:db:configure 2>& 1 | tee ${log_file}
     57:     STATUS=${PIPESTATUS[0]}
     58:     echo $STATUS > #{db_migrate_status_file}
     59:     exit $STATUS
     60:   EOH
     61:   environment env_variables unless env_variables.empty?
     62:   notifies :run, "execute[clear the gitlab-rails cache]", :immediately
     63:   dependent_services.each do |svc|
     64:     notifies :restart, svc, :immediately
     65:   end
     66:   not_if "(test -f #{db_migrate_status_file}) && (cat #{db_migrate_status_file} | grep -Fx 0)"
     67:   only_if { node['gitlab']['gitlab-rails']['auto_migrate'] }
     68: end

    Compiled Resource:
    ------------------
    # Declared in /opt/gitlab/embedded/cookbooks/cache/cookbooks/gitlab/recipes/database_migrations.rb:51:in `from_file'

    bash("migrate gitlab-rails database") do
      action [:run]
      retries 0
      retry_delay 2
      default_guard_interpreter :default
      command "migrate gitlab-rails database"
      backup 5
      returns 0
      code "    set -e\n    log_file=\"/var/log/gitlab/gitlab-rails/gitlab-rails-db-migrate-$(date +%Y-%m-%d-%H-%M-%S).log\"\n    umask 077\n    /opt/gitlab/bin/gitlab-rake gitlab:db:configure 2>& 1 | tee ${log_file}\n    STATUS=${PIPESTATUS[0]}\n    echo $STATUS > /var/opt/gitlab/gitlab-rails/upgrade-status/db-migrate-873248b1f0d3a7a5535771a3a1635803-da70bc4\n    exit $STATUS\n"
      interpreter "bash"
      declared_type :bash
      cookbook_name "gitlab"
      recipe_name "database_migrations"
      not_if "(test -f /var/opt/gitlab/gitlab-rails/upgrade-status/db-migrate-873248b1f0d3a7a5535771a3a1635803-da70bc4) && (cat /var/opt/gitlab/gitlab-rails/upgrade-status/db-migrate-873248b1f0d3a7a5535771a3a1635803-da70bc4 | grep -Fx 0)"
      only_if { #code block }
    end

    Platform:
    ---------
    x86_64-linux

Running handlers:
Running handlers complete
Chef Client failed. 3 resources updated in 36 seconds

I read a lot in the docs, but there are so much information, that I cannot get the update working.
So what are the required steps to get the installation to a current release and what are the critical steps to take?


问:
Automatically update id variable in two controllers using $broadcast in AngularJS
```<code>$ctrl.clicker = function(id)
{
   $rootScope.$broadcast('idBull', id);
}
</code>```

When I mouseenter an image the above function gets called. I want to share the id in another controller and broadcast whatever changes where made to this id.

```<code>$scope.$on('idBull', function (event, data) {
  console.log(data); // 'Data to send'
});
</code>```

In the other controller I used the code to do a console loge of my id but got no results.

答:
http://jsfiddle.net/87rLob9x/
Check this fiddle hope it helps
html

```<code><html ng-app="myApp">
<div ng-controller='ControllerA'>

    <button ng-click='add()'>Add</button
</div>
<div ng-controller='ControllerB'>
    {{ increment }}

</div>

</html>
</code>```

js:

```<code>var app = angular.module('myApp', [])
.controller('ControllerA', function($scope) {
    $scope.increment = 0;
    $scope.add = function() {
        $scope.$broadcast('hasIncremented');
    }

}).
controller('ControllerB', function($scope) {
    $scope.$on('hasIncremented', function(event) {
        $scope.increment++;
    });
})
</code>```

Body:
$ctrl.clicker = function(id)
{
   $rootScope.$broadcast('idBull', id);
}

When I mouseenter an image the above function gets called. I want to share the id in another controller and broadcast whatever changes where made to this id.

$scope.$on('idBull', function (event, data) {
  console.log(data); // 'Data to send'
});

In the other controller I used the code to do a console loge of my id but got no results.

Body:
http://jsfiddle.net/87rLob9x/
Check this fiddle hope it helps
html

<html ng-app="myApp">
<div ng-controller='ControllerA'>

    <button ng-click='add()'>Add</button
</div>
<div ng-controller='ControllerB'>
    {{ increment }}

</div>

</html>

js:

var app = angular.module('myApp', [])
.controller('ControllerA', function($scope) {
    $scope.increment = 0;
    $scope.add = function() {
        $scope.$broadcast('hasIncremented');
    }

}).
controller('ControllerB', function($scope) {
    $scope.$on('hasIncremented', function(event) {
        $scope.increment++;
    });
})


问:
Django: logging template errors
When I make an error in a django template {{placeholder}}, I get no error, just blank space in the output where I was expecting content. Is there a way to see something in my logs when this occurs, preferably using logging.warning or logging.error?

答:
Yes, there is. Just add in your development settings.py:

```<code>LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
        },
    },
    'loggers': {
        'django.template': {
            'handlers': ['console'],
            'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'),
        },
    },
}
</code>```

As roboslone stated, Django 1.9 did introduce it. The snippet is very similar to the second of Configuring logging examples in Django docs.

ContentLicense: CC BY-SA 2.5

Title: Django: logging template errors

Body:
Yes, there is. Just add in your development settings.py:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
        },
    },
    'loggers': {
        'django.template': {
            'handlers': ['console'],
            'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'),
        },
    },
}

As roboslone stated, Django 1.9 did introduce it. The snippet is very similar to the second of Configuring logging examples in Django docs.

ContentLicense: CC BY-SA 4.0


问:
Adwords API Modify class in order to pass a variable and get response in variable
I'm trying to modify a class given from a PHP script example from the Adwords API.

I'm pretty new to playing with Objects in PHP so I can't figure out how to make it work.

I would like to modify this script below in order to pass on a keyword array as a variable, therefore replacing the keywords contained in:

```<code>$relatedToQuerySearchParameter->setQueries([
        'bakery', 'pastries', 'birthday cake'
    ]);
</code>```

Maybe to use it as a function will normally do :

```<code>function GetKeywordIdeas($array_keywords){...}
</code>```

And then get the results in a variable

Here's the code from the example:

```<code><?php
/**
 * Copyright 2017 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
namespace Google\AdsApi\Examples\AdWords\v201710\Optimization;

require __DIR__ . '/../../../../vendor/autoload.php';

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201710\cm\Language;
use Google\AdsApi\AdWords\v201710\cm\NetworkSetting;
use Google\AdsApi\AdWords\v201710\cm\Paging;
use Google\AdsApi\AdWords\v201710\o\AttributeType;
use Google\AdsApi\AdWords\v201710\o\IdeaType;
use Google\AdsApi\AdWords\v201710\o\LanguageSearchParameter;
use Google\AdsApi\AdWords\v201710\o\NetworkSearchParameter;
use Google\AdsApi\AdWords\v201710\o\RelatedToQuerySearchParameter;
use Google\AdsApi\AdWords\v201710\o\RequestType;
use Google\AdsApi\AdWords\v201710\o\SeedAdGroupIdSearchParameter;
use Google\AdsApi\AdWords\v201710\o\TargetingIdeaSelector;
use Google\AdsApi\AdWords\v201710\o\TargetingIdeaService;
use Google\AdsApi\Common\OAuth2TokenBuilder;
use Google\AdsApi\Common\Util\MapEntries;

/**
 * This example gets keyword ideas related to a seed keyword.
 */
class GetKeywordIdeas {

  // If you do not want to use an existing ad group to seed your request, you
  // can set this to null.
  const AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE';
  const PAGE_LIMIT = 500;

  public static function runExample(AdWordsServices $adWordsServices,
      AdWordsSession $session, $adGroupId) {
    $targetingIdeaService =
        $adWordsServices->get($session, TargetingIdeaService::class);

    // Create selector.
    $selector = new TargetingIdeaSelector();
    $selector->setRequestType(RequestType::IDEAS);
    $selector->setIdeaType(IdeaType::KEYWORD);
    $selector->setRequestedAttributeTypes([
        AttributeType::KEYWORD_TEXT,
        AttributeType::SEARCH_VOLUME,
        AttributeType::AVERAGE_CPC,
        AttributeType::COMPETITION,
        AttributeType::CATEGORY_PRODUCTS_AND_SERVICES
    ]);

    $paging = new Paging();
    $paging->setStartIndex(0);
    $paging->setNumberResults(10);
    $selector->setPaging($paging);

    $searchParameters = [];
    // Create related to query search parameter.
    $relatedToQuerySearchParameter = new RelatedToQuerySearchParameter();
    $relatedToQuerySearchParameter->setQueries([
        'bakery', 'pastries', 'birthday cake'
    ]);
    $searchParameters[] = $relatedToQuerySearchParameter;

    // Create language search parameter (optional).
    // The ID can be found in the documentation:
    // https://developers.google.com/adwords/api/docs/appendix/languagecodes
    $languageParameter = new LanguageSearchParameter();
    $english = new Language();
    $english->setId(1000);
    $languageParameter->setLanguages([$english]);
    $searchParameters[] = $languageParameter;

    // Create network search parameter (optional).
    $networkSetting = new NetworkSetting();
    $networkSetting->setTargetGoogleSearch(true);
    $networkSetting->setTargetSearchNetwork(false);
    $networkSetting->setTargetContentNetwork(false);
    $networkSetting->setTargetPartnerSearchNetwork(false);

    $networkSearchParameter = new NetworkSearchParameter();
    $networkSearchParameter->setNetworkSetting($networkSetting);
    $searchParameters[] = $networkSearchParameter;

    // Optional: Use an existing ad group to generate ideas.
    if (!empty($adGroupId)) {
      $seedAdGroupIdSearchParameter = new SeedAdGroupIdSearchParameter();
      $seedAdGroupIdSearchParameter->setAdGroupId($adGroupId);
      $searchParameters[] = $seedAdGroupIdSearchParameter;
    }
    $selector->setSearchParameters($searchParameters);
    $selector->setPaging(new Paging(0, self::PAGE_LIMIT));

    // Get keyword ideas.
    $page = $targetingIdeaService->get($selector);

    // Print out some information for each targeting idea.
    $entries = $page->getEntries();
    if ($entries !== null) {
      foreach ($entries as $targetingIdea) {
        $data = MapEntries::toAssociativeArray($targetingIdea->getData());
        $keyword = $data[AttributeType::KEYWORD_TEXT]->getValue();
        $searchVolume =
            ($data[AttributeType::SEARCH_VOLUME]->getValue() !== null)
            ? $data[AttributeType::SEARCH_VOLUME]->getValue() : 0;
        $averageCpc = $data[AttributeType::AVERAGE_CPC]->getValue();
        $competition = $data[AttributeType::COMPETITION]->getValue();
        $categoryIds =
            ($data[AttributeType::CATEGORY_PRODUCTS_AND_SERVICES]->getValue()
                === null)
            ? $categoryIds = '' : implode(
                ', ',
                $data[AttributeType::CATEGORY_PRODUCTS_AND_SERVICES]->getValue()
            );
        printf(
            "Keyword with text '%s', average monthly search volume %d, "
                . "average CPC %d, and competition %.2f "
                . "was found with categories: %s\n",
            $keyword,
            $searchVolume,
            ($averageCpc === null) ? 0 : $averageCpc->getMicroAmount(),
            $competition,
            $categoryIds
        );
      }
    }

    if (empty($entries)) {
      print "No related keywords were found.\n";
    }
  }

  public static function main() {
    // Generate a refreshable OAuth2 credential for authentication.
    $oAuth2Credential = (new OAuth2TokenBuilder())
        ->fromFile()
        ->build();

    // Construct an API session configured from a properties file and the OAuth2
    // credentials above.
    $session = (new AdWordsSessionBuilder())
        ->fromFile()
        ->withOAuth2Credential($oAuth2Credential)
        ->build();
    self::runExample(new AdWordsServices(), $session, self::AD_GROUP_ID);
  }
}

GetKeywordIdeas::main();
</code>```

Thanks for your help or explanations.

答:
answer to a comment, returning the keywords as an array:

you will need to insert and change several lines:

before this line:

```<code>foreach ($entries as $targetingIdea) {
</code>```

insert

```<code>$keywords = [];
</code>```

after $keyword = $data[AttributeType::KEYWORD_TEXT]->getValue();
insert $keywords[] = $keyword;

before these lines

```<code>    }
if (empty($entries)) {
</code>```

insert return $keywords;

change self::runExample(new AdWordsServices(), $session, self::AD_GROUP_ID, $array_keywords);

to return self::runExample(new AdWordsServices(), $session, self::AD_GROUP_ID, $array_keywords);

then call it like this $keywords = GetKeywordIdeas::main($array_keywords);

Body:
I'm trying to modify a class given from a PHP script example from the Adwords API.

I'm pretty new to playing with Objects in PHP so I can't figure out how to make it work.

I would like to modify this script below in order to pass on a keyword array as a variable, therefore replacing the keywords contained in:

$relatedToQuerySearchParameter->setQueries([
        'bakery', 'pastries', 'birthday cake'
    ]);

Maybe to use it as a function will normally do :

function GetKeywordIdeas($array_keywords){...}

And then get the results in a variable

Here's the code from the example:

<?php
/**
 * Copyright 2017 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
namespace Google\AdsApi\Examples\AdWords\v201710\Optimization;

require __DIR__ . '/../../../../vendor/autoload.php';

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201710\cm\Language;
use Google\AdsApi\AdWords\v201710\cm\NetworkSetting;
use Google\AdsApi\AdWords\v201710\cm\Paging;
use Google\AdsApi\AdWords\v201710\o\AttributeType;
use Google\AdsApi\AdWords\v201710\o\IdeaType;
use Google\AdsApi\AdWords\v201710\o\LanguageSearchParameter;
use Google\AdsApi\AdWords\v201710\o\NetworkSearchParameter;
use Google\AdsApi\AdWords\v201710\o\RelatedToQuerySearchParameter;
use Google\AdsApi\AdWords\v201710\o\RequestType;
use Google\AdsApi\AdWords\v201710\o\SeedAdGroupIdSearchParameter;
use Google\AdsApi\AdWords\v201710\o\TargetingIdeaSelector;
use Google\AdsApi\AdWords\v201710\o\TargetingIdeaService;
use Google\AdsApi\Common\OAuth2TokenBuilder;
use Google\AdsApi\Common\Util\MapEntries;

/**
 * This example gets keyword ideas related to a seed keyword.
 */
class GetKeywordIdeas {

  // If you do not want to use an existing ad group to seed your request, you
  // can set this to null.
  const AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE';
  const PAGE_LIMIT = 500;

  public static function runExample(AdWordsServices $adWordsServices,
      AdWordsSession $session, $adGroupId) {
    $targetingIdeaService =
        $adWordsServices->get($session, TargetingIdeaService::class);

    // Create selector.
    $selector = new TargetingIdeaSelector();
    $selector->setRequestType(RequestType::IDEAS);
    $selector->setIdeaType(IdeaType::KEYWORD);
    $selector->setRequestedAttributeTypes([
        AttributeType::KEYWORD_TEXT,
        AttributeType::SEARCH_VOLUME,
        AttributeType::AVERAGE_CPC,
        AttributeType::COMPETITION,
        AttributeType::CATEGORY_PRODUCTS_AND_SERVICES
    ]);

    $paging = new Paging();
    $paging->setStartIndex(0);
    $paging->setNumberResults(10);
    $selector->setPaging($paging);

    $searchParameters = [];
    // Create related to query search parameter.
    $relatedToQuerySearchParameter = new RelatedToQuerySearchParameter();
    $relatedToQuerySearchParameter->setQueries([
        'bakery', 'pastries', 'birthday cake'
    ]);
    $searchParameters[] = $relatedToQuerySearchParameter;

    // Create language search parameter (optional).
    // The ID can be found in the documentation:
    // https://developers.google.com/adwords/api/docs/appendix/languagecodes
    $languageParameter = new LanguageSearchParameter();
    $english = new Language();
    $english->setId(1000);
    $languageParameter->setLanguages([$english]);
    $searchParameters[] = $languageParameter;

    // Create network search parameter (optional).
    $networkSetting = new NetworkSetting();
    $networkSetting->setTargetGoogleSearch(true);
    $networkSetting->setTargetSearchNetwork(false);
    $networkSetting->setTargetContentNetwork(false);
    $networkSetting->setTargetPartnerSearchNetwork(false);

    $networkSearchParameter = new NetworkSearchParameter();
    $networkSearchParameter->setNetworkSetting($networkSetting);
    $searchParameters[] = $networkSearchParameter;

    // Optional: Use an existing ad group to generate ideas.
    if (!empty($adGroupId)) {
      $seedAdGroupIdSearchParameter = new SeedAdGroupIdSearchParameter();
      $seedAdGroupIdSearchParameter->setAdGroupId($adGroupId);
      $searchParameters[] = $seedAdGroupIdSearchParameter;
    }
    $selector->setSearchParameters($searchParameters);
    $selector->setPaging(new Paging(0, self::PAGE_LIMIT));

    // Get keyword ideas.
    $page = $targetingIdeaService->get($selector);

    // Print out some information for each targeting idea.
    $entries = $page->getEntries();
    if ($entries !== null) {
      foreach ($entries as $targetingIdea) {
        $data = MapEntries::toAssociativeArray($targetingIdea->getData());
        $keyword = $data[AttributeType::KEYWORD_TEXT]->getValue();
        $searchVolume =
            ($data[AttributeType::SEARCH_VOLUME]->getValue() !== null)
            ? $data[AttributeType::SEARCH_VOLUME]->getValue() : 0;
        $averageCpc = $data[AttributeType::AVERAGE_CPC]->getValue();
        $competition = $data[AttributeType::COMPETITION]->getValue();
        $categoryIds =
            ($data[AttributeType::CATEGORY_PRODUCTS_AND_SERVICES]->getValue()
                === null)
            ? $categoryIds = '' : implode(
                ', ',
                $data[AttributeType::CATEGORY_PRODUCTS_AND_SERVICES]->getValue()
            );
        printf(
            "Keyword with text '%s', average monthly search volume %d, "
                . "average CPC %d, and competition %.2f "
                . "was found with categories: %s\n",
            $keyword,
            $searchVolume,
            ($averageCpc === null) ? 0 : $averageCpc->getMicroAmount(),
            $competition,
            $categoryIds
        );
      }
    }

    if (empty($entries)) {
      print "No related keywords were found.\n";
    }
  }

  public static function main() {
    // Generate a refreshable OAuth2 credential for authentication.
    $oAuth2Credential = (new OAuth2TokenBuilder())
        ->fromFile()
        ->build();

    // Construct an API session configured from a properties file and the OAuth2
    // credentials above.
    $session = (new AdWordsSessionBuilder())
        ->fromFile()
        ->withOAuth2Credential($oAuth2Credential)
        ->build();
    self::runExample(new AdWordsServices(), $session, self::AD_GROUP_ID);
  }
}

GetKeywordIdeas::main();

Thanks for your help or explanations.

Body:
answer to a comment, returning the keywords as an array:

you will need to insert and change several lines:

before this line:

foreach ($entries as $targetingIdea) {

insert

$keywords = [];

after $keyword = $data[AttributeType::KEYWORD_TEXT]->getValue();
insert $keywords[] = $keyword;

before these lines

    }
if (empty($entries)) {

insert return $keywords;

change self::runExample(new AdWordsServices(), $session, self::AD_GROUP_ID, $array_keywords);

to return self::runExample(new AdWordsServices(), $session, self::AD_GROUP_ID, $array_keywords);

then call it like this $keywords = GetKeywordIdeas::main($array_keywords);


问:
How to check on multiple conditions in PHP
I want to check the security input of a form.
People should answer the security question with the words "allow", "Allow" or 'ALLOW'. These 3 answers are all accepted.

I tried code below but it doesn't pass the if loop if I type one of these 3 answers. What I am doing wrong?

```<code>if( ! isset($_POST['security']) || empty($_POST['security']) || $_POST['security'] != 'allow' || $_POST['security'] != 'Allow' || $_POST['security'] != 'ALLOW') {
      $error .= "<p class=\"message-error\">" . $messages['security_invalid'] . "</p>";
}
</code>```

答:
Try this:

```<code>if( empty($_POST['security']) or strtolower($_POST['security']) != 'allow') {
    $error .= "yaddayadaa";
}
</code>```

Using empty() is good enough for checking if its not set, or empty, or zero, or null. Then, just lowercase the post and check once for not being allow.

Body:
I want to check the security input of a form.
People should answer the security question with the words "allow", "Allow" or 'ALLOW'. These 3 answers are all accepted.

I tried code below but it doesn't pass the if loop if I type one of these 3 answers. What I am doing wrong?

if( ! isset($_POST['security']) || empty($_POST['security']) || $_POST['security'] != 'allow' || $_POST['security'] != 'Allow' || $_POST['security'] != 'ALLOW') {
      $error .= "
" . $messages['security_invalid'] . "
";
}

Body:
Try this:

if( empty($_POST['security']) or strtolower($_POST['security']) != 'allow') {
    $error .= "yaddayadaa";
}

Using empty() is good enough for checking if its not set, or empty, or zero, or null. Then, just lowercase the post and check once for not being allow.


问:
Counting rows in multiple partitions using Oracle SQL
For a partitioned table I can count the rows in a partition quickly with a query like this:

```<code>select count(*)
from db.table Partition (P)
where column value is Null
</code>```

Is there a way to do this for multiple partitions?

My desired result is the following-

```<code>Partition name         Count of Null Rows
P1                         20000
P2                         12000
P3                          30000
</code>```

答:
It won't be as efficient as using FROM TABLE PARTITION (p), but you could do this:

```<code>select o.object_name, o.subobject_name partition, count(*)
from sh.sales s
inner join all_objects o on o.object_id = dbms_rowid.rowid_object(s.rowid)
where o.subobject_name in ('SALES_Q1_2000','SALES_Q2_2000')
-- for performance, you can add conditions to restrict to the partitions of interest, if you know them
-- e.g., and s.sale_date between to_date('01-JAN-2000','DD-MON-YYYY') and to_date('30-JUN-2000','DD-MON-YYYY')
group by o.object_name, o.subobject_name;
</code>```

Basically, it uses the rowid to determine the partition for each row and counts them.

Body:
For a partitioned table I can count the rows in a partition quickly with a query like this:

select count(*)
from db.table Partition (P)
where column value is Null

Is there a way to do this for multiple partitions?

My desired result is the following-

Partition name         Count of Null Rows
P1                         20000
P2                         12000
P3                          30000

Body:
It won't be as efficient as using FROM TABLE PARTITION (p), but you could do this:

select o.object_name, o.subobject_name partition, count(*)
from sh.sales s
inner join all_objects o on o.object_id = dbms_rowid.rowid_object(s.rowid)
where o.subobject_name in ('SALES_Q1_2000','SALES_Q2_2000')
-- for performance, you can add conditions to restrict to the partitions of interest, if you know them
-- e.g., and s.sale_date between to_date('01-JAN-2000','DD-MON-YYYY') and to_date('30-JUN-2000','DD-MON-YYYY')
group by o.object_name, o.subobject_name;

Basically, it uses the rowid to determine the partition for each row and counts them.


问:
Is there a intersection function for vectors?
Very often one finds statements that lists have a performance disadvantage compared to vectors because of consing and additional gc steps and some function work on generic sequences accepting lists and vectors.

But some functions like intersection expect two lists. Is there a library providing an alternative for vectors?

I started with something like this, but have the feeling that there should be a more mature solution.

```<code>(defun vec-intersec (vec-1 vec-2 &aux (result (make-array 0 :adjustable t :fill-pointer 0)))
  "A simple implementation of intersection for vectors instead of lists."
  (loop :for v1 :across vec-1
        :if (find v1 vec-2 :test #'equal)
          :do (vector-push-extend v1 result))
  result)
</code>```

答:
It always depends on the size of your collection and what you want to do with it.

Below about 20 to 50 elements, lists are often perfectly OK even for random access (if you're not in a tight inner loop, or consing a lot).

If you already have vectors, it might be most convenient to sort one of them so that you can do a binary search instead of a naïve linear one.  If that is not enough, and your collections bigger, putting the elements into a hash-table (as keys, with an appropriate :test) gives you faster (amortized) lookup.

This should take you quite far.  If you identify an issue that cannot be solved in such a simple way, you might want to look into FSet or CL-Containers, which support more advanced data structures.

Body:
Very often one finds statements that lists have a performance disadvantage compared to vectors because of consing and additional gc steps and some function work on generic sequences accepting lists and vectors.

But some functions like intersection expect two lists. Is there a library providing an alternative for vectors?

I started with something like this, but have the feeling that there should be a more mature solution.

(defun vec-intersec (vec-1 vec-2 &aux (result (make-array 0 :adjustable t :fill-pointer 0)))
  "A simple implementation of intersection for vectors instead of lists."
  (loop :for v1 :across vec-1
        :if (find v1 vec-2 :test #'equal)
          :do (vector-push-extend v1 result))
  result)


问:
How to do a Docker healthcheck with wget instead of curl?
Docker healthcheck document shows this for curl:

```<code>HEALTHCHECK --interval=5m --timeout=3s \
  CMD curl -f http://localhost/ || exit 1
</code>```

I want a one-line equivalent in wget that would exit 1 when HTTP 200 is not returned.

答:
The following seems to be the equivalent:</p>
```<code>HEALTHCHECK  --interval=5m --timeout=3s \
  CMD wget --no-verbose --tries=1 --spider http://localhost/ || exit 1
</code>```

Body:
Docker healthcheck document shows this for curl:

HEALTHCHECK --interval=5m --timeout=3s \
  CMD curl -f http://localhost/ || exit 1

I want a one-line equivalent in wget that would exit 1 when HTTP 200 is not returned.

Body:
The following seems to be the equivalent:

HEALTHCHECK  --interval=5m --timeout=3s \
  CMD wget --no-verbose --tries=1 --spider http://localhost/ || exit 1


问:
SQL Joins vs Single Table : Performance Difference?
I am trying to stick to the practice of keeping the database normalized, but that leads to the need to run multiple join queries. Is there a performance degradation if many queries use joins vs having a call to a single table that might contain redundant data?</p>

答:
Keep the Database normalised UNTIL you have discovered a bottleneck. Then only after careful profiling should you denormalise.

In most instances, having a good covering set of indexes and up to date statistics will solve most performance and blocking issues without any denormalisation.

Using a single table could lead to worse performance if there are writes as well as reads against it.

OwnerDisplayName: zsharp

LastEditorDisplayName: mwigdahl

OwnerDisplayName: Mitch Wheat


问:
64/32-bit division on a processor with 32/16-bit division
My processor, a small 16-bit microcontroller with no FPU and integer math only has 16/16 division and 32/16 division which both take 18 cycles. At the moment I'm using a very slow software routine (~7,500 cycles) to do 64/32 division. Is there any way to use these division engines to calculate a 64/32 division? Similar to how I'm already using the 16x16 multiplier and adder to calculate 32x32 multiplies? I'm using C but can work with any general explanation on how it can be done... I'm hoping to target <200 cycles (if it's at all possible.)</p>

答:
You may want to look at Booth's Algorithm (http://www.scribd.com/doc/3132888/Booths-Algorithm-Multiplication-Division).

The part you want is about 1/2 way down the page.

I haven't looked at this since my VLSI class, but, this may be your best bet, if possible you may want to do this in assembly, to optimize it as much as possible, if you will be calling this often.

Basically involves shifting and adding or subtracting.


问:
Angular Async Form Validation with Injected Providers
I have a custom async validator in a reactive form that needs to call out to a service to validate whether a name is unique.

Since validators are pure functions, there doesn't seem to be a good way to inject a provider such as HTTP to make these calls.

The code I currently have is returning a function that passes the service but this feels a tad hacky...

```<code>export function nameValidator(platformService: PlatformService): ValidatorFn {
    return (control: FormControl): { [key: string]: any } => {
        return userService.getUnique(control.value)
    };
}
</code>```

my question is there a better way?

答:
Validators can be injectable directive classes when being used as directives in templates.

They are expected to be functions when they are specified directly in FormControl or FormBuilder

In order to make use of DI they should be useFactory or useClass providers and injected into a component:

```<code>@Injectable()
class NameValidator implements AsyncValidator {
  constructor(private userService: UserService) {}

  validate = (control: FormControl) => this.userService.getUnique(control.value);
}

...

new FormControl('', nameValidator.validate);
</code>```

Notice that validate method is passed as a callback and should be either an arrow or be bound to class instance with bind.

Body:
I have a custom async validator in a reactive form that needs to call out to a service to validate whether a name is unique.

Since validators are pure functions, there doesn't seem to be a good way to inject a provider such as HTTP to make these calls.

The code I currently have is returning a function that passes the service but this feels a tad hacky...

export function nameValidator(platformService: PlatformService): ValidatorFn {
    return (control: FormControl): { [key: string]: any } => {
        return userService.getUnique(control.value)
    };
}

my question is there a better way?

Body:
Validators can be injectable directive classes when being used as directives in templates.

They are expected to be functions when they are specified directly in FormControl or FormBuilder

In order to make use of DI they should be useFactory or useClass providers and injected into a component:

@Injectable()
class NameValidator implements AsyncValidator {
  constructor(private userService: UserService) {}

  validate = (control: FormControl) => this.userService.getUnique(control.value);
}

...

new FormControl('', nameValidator.validate);

Notice that validate method is passed as a callback and should be either an arrow or be bound to class instance with bind.


问:
Wrapping method call with PostSharp
Is there any way to wrap a method call with PostSharp? I have to add code around/outside a specific call.

The OnMethodBound add the code inside the specified method and the MethodInterception aspect redirects the call to the aspect, but I have to to add code outside the call.

Example:
Without aspect:

```<code>...
call();
...
</code>```

With aspect:

```<code>beforePart();
call();
afterPart();
</code>```

答:
I had similar requirement and I wrote a logging aspect for all database calls I make with external library which is Dapper. I created an aspect:

```<code>[MulticastAttributeUsage(MulticastTargets.Method)]
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public sealed class SqlLogger : MethodInterceptionAspect
{
    public override void OnInvoke(MethodInterceptionArgs args)
    {
        // logging code goes here

        base.OnInvoke(args);
    }
}
</code>```

And then I registered it on assembly level:

```<code>[assembly: SqlLogger(AttributeTargetAssemblies = "Dapper", AttributePriority = 1)]
</code>```

Title: Wrapping method call with PostSharp

Body:
Is there any way to wrap a method call with PostSharp? I have to add code around/outside a specific call.

The OnMethodBound add the code inside the specified method and the MethodInterception aspect redirects the call to the aspect, but I have to to add code outside the call.

Example:
Without aspect:

...
call();
...

With aspect:

beforePart();
call();
afterPart();

Body:
I had similar requirement and I wrote a logging aspect for all database calls I make with external library which is Dapper. I created an aspect:

[MulticastAttributeUsage(MulticastTargets.Method)]
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public sealed class SqlLogger : MethodInterceptionAspect
{
    public override void OnInvoke(MethodInterceptionArgs args)
    {
        // logging code goes here

        base.OnInvoke(args);
    }
}

And then I registered it on assembly level:

[assembly: SqlLogger(AttributeTargetAssemblies = "Dapper", AttributePriority = 1)]


问:
Generate 5 million + unique rows of data
Alright so I've looked around and haven't quite found something like this online

I have to write a script to generate minimum of 5 million unique rows of test data for a table, and these are the columns it needs:
•   First Name
•   Last Name
•   City
•   State

(can't be gibberish data)

suggestions on how to do this at all? If possible, I would appreciate some code examples to help me get going. The lecture notes and slides are completely useless and I have no idea how it's supposed to be done.

I found this, and the top answer looks like the closest thing to what I'm doing, just not sure how to change/adjust the columns and attributes in the create table statement to match mine: How to generate 1000000 rows with random data?

答:
Make 4 tables, 1 for each column and do a cross join that you select into your random data table.  In each table put your values, e.g., the first_name table has 100 names, last_name has 100 names, city as 100 names, and state as 50.  100 * 100 * 100 * 50 = 50 million combinations.

Just make sure each table has no duplicates.

Edit:
In the end @Jaluvshuskies and I had this discussion in chat.  For anyone who comes across this and wonders what we did:  we made the insert statements in Excel from a copy-paste list of googled first and last names, cities, and 50 USA states.

Each entry was 1 insert statement, e.g.,

```<code>INSERT INTO first_name (firstname) VALUES ('Sophia');
INSERT INTO first_name (firstname) VALUES ('Olivia');
INSERT INTO first_name (firstname) VALUES ('Emma');
INSERT INTO first_name (firstname) VALUES ('Ava');
INSERT INTO first_name (firstname) VALUES ('Isabella');
</code>```

The then an insert from a cross join subquery and all done.

Body:
Make 4 tables, 1 for each column and do a cross join that you select into your random data table.  In each table put your values, e.g., the first_name table has 100 names, last_name has 100 names, city as 100 names, and state as 50.  100 * 100 * 100 * 50 = 50 million combinations.

Just make sure each table has no duplicates.

Edit:
In the end @Jaluvshuskies and I had this discussion in chat.  For anyone who comes across this and wonders what we did:  we made the insert statements in Excel from a copy-paste list of googled first and last names, cities, and 50 USA states.

Each entry was 1 insert statement, e.g.,

INSERT INTO first_name (firstname) VALUES ('Sophia');
INSERT INTO first_name (firstname) VALUES ('Olivia');
INSERT INTO first_name (firstname) VALUES ('Emma');
INSERT INTO first_name (firstname) VALUES ('Ava');
INSERT INTO first_name (firstname) VALUES ('Isabella');

The then an insert from a cross join subquery and all done.


问:
Simple file legend in Xmgrace
I am using xmgrace to plot several graphs on a shared axed, from a two-column data file like so:

```<code>@    title "RMSD"
@    xaxis  label "Time (ns)"
@    yaxis  label "RMSD (nm)"
@TYPE xy
@ subtitle "C-alpha after lsq fit to C-alpha"
   1.7125001    0.0005074
   1.7225001    0.0635904
   1.7325001    0.0747008
   1.7425001    0.0707590
   1.7525001    0.0821623
   1.7625000    0.0842335
   1.7725000    0.0929994
   1.7825000    0.0938834
   1.7925001    0.1014052
   1.8025001    0.1107717
   1.8125001    0.1106072
   1.8225001    0.1032858
   1.8325001    0.0967231
   1.8425001    0.1072746
</code>```

So, I call the command to show me all graphs on the GUI

```<code>xmgrace 1.xvg rmsd_amber_2.xvg rmsd_3.xvg
</code>```

Is it possible to automatically use the filenames as the labels for the legend, using an option found within the GUI of xmgrace?  So far xmgrace automatically uses different line colors for each data series, but does not show the filename as the data label.

If this is not possible, please suggest me another GUI software for Linux which is able to open xvg files from the terminal for its visualization "on the fly".

Thanks !

答:
Xmgrace does not do what you want

The xmgrace help (shown by calling xmgrace --help at the terminal) shows that there is no command line flag to specify data set legend titles. If that were the case you could probably come up with some bash commands to parse the title from your data files.

But there is another way

As an alternative, you can load a parameters file containing the correct titles. If you save any parameters file from within the xmgrace GUI and load it in a text editor, you will see that almost every aspect of Plot, Graph and Set appearance properties can be controlled.

However, it is not all needed; we can delete almost all of that information and just keep the lines related to our data set legend titles (everything else will just take the default values).

Solution

A minimal parameter file "template.par" might contain just the following four lines:

```<code>with g0
  s0 legend "title0"
  s1 legend "title1"
  s2 legend "title2"
</code>```

where in your case "title1" would be "RMSD".

You can then use xmgrace -param template.par 1.xvg rmsd_amber_2.xvg rmsd_3.xvg to create the plot.

Automating it

So far so good, but you want to create template.par automatically by parsing your chosen bunch of .xvg files. You could probably achieve this in any number of different ways using a bash script or even a bash one-liner.

Title: Simple file legend in Xmgrace

Body:
I am using xmgrace to plot several graphs on a shared axed, from a two-column data file like so:

@    title "RMSD"
@    xaxis  label "Time (ns)"
@    yaxis  label "RMSD (nm)"
@TYPE xy
@ subtitle "C-alpha after lsq fit to C-alpha"
   1.7125001    0.0005074
   1.7225001    0.0635904
   1.7325001    0.0747008
   1.7425001    0.0707590
   1.7525001    0.0821623
   1.7625000    0.0842335
   1.7725000    0.0929994
   1.7825000    0.0938834
   1.7925001    0.1014052
   1.8025001    0.1107717
   1.8125001    0.1106072
   1.8225001    0.1032858
   1.8325001    0.0967231
   1.8425001    0.1072746

So, I call the command to show me all graphs on the GUI

xmgrace 1.xvg rmsd_amber_2.xvg rmsd_3.xvg

Is it possible to automatically use the filenames as the labels for the legend, using an option found within the GUI of xmgrace?  So far xmgrace automatically uses different line colors for each data series, but does not show the filename as the data label.

If this is not possible, please suggest me another GUI software for Linux which is able to open xvg files from the terminal for its visualization "on the fly".

Thanks !

Body:
Xmgrace does not do what you want

The xmgrace help (shown by calling xmgrace --help at the terminal) shows that there is no command line flag to specify data set legend titles. If that were the case you could probably come up with some bash commands to parse the title from your data files.

But there is another way

As an alternative, you can load a parameters file containing the correct titles. If you save any parameters file from within the xmgrace GUI and load it in a text editor, you will see that almost every aspect of Plot, Graph and Set appearance properties can be controlled.

However, it is not all needed; we can delete almost all of that information and just keep the lines related to our data set legend titles (everything else will just take the default values).

Solution

A minimal parameter file "template.par" might contain just the following four lines:

with g0
  s0 legend "title0"
  s1 legend "title1"
  s2 legend "title2"

where in your case "title1" would be "RMSD".

You can then use xmgrace -param template.par 1.xvg rmsd_amber_2.xvg rmsd_3.xvg to create the plot.

Automating it

So far so good, but you want to create template.par automatically by parsing your chosen bunch of .xvg files. You could probably achieve this in any number of different ways using a bash script or even a bash one-liner.


答: Found the issue .. The second AddGeometryColumn call doesn't add the validation triggers to the table, which is why it appears to work.  The real fix is to include the SRID as the second parameter to GeomFromText.

Title: "[geom-type or SRID not allowed]" only after first call to `AddGeometryColumn`

Body:
I'm getting an error that "[geom-type or SRID not allowed]" for a geometry column, but I'm confident that the value I'm inserting is valid for the type and SR.  I noticed that if I drop the table and recreate it again with the same value SQL, I no longer get the error.  For example, in the query below, I get the error with the second DROP/CREATE/AddGeometryColumn commented out, but not if I uncomment it.

DROP TABLE IF EXISTS test;
CREATE TABLE test (Value double);
SELECT AddGeometryColumn('test', 'SHAPE', 32615, 'LINESTRING');
--DROP TABLE IF EXISTS test;
--CREATE TABLE test (Value double);
--SELECT AddGeometryColumn('test', 'SHAPE', 32615, 'LINESTRING');
INSERT INTO test VALUES (46.71864700317383, GeomFromText('LINESTRING (701268.032645698 3675362.29477,701268.032645698 3675364.29728502,701265.122816664 3675368.30231507,701264.28479163 3675368.86824025,701261.045560283 3675372.30734512,701260.272152777 3675372.78885241,701256.259513924 3675375.65843502,701255.162166084 3675376.31237516,701252.246875071 3675377.76809262,701248.234236219 3675378.84164383,701244.221597366 3675378.58692897,701240.208958513 3675376.3929278,701240.119712612 3675376.31237516,701236.663233482 3675372.30734512,701236.19631966 3675371.17638664,701234.972864821 3675368.30231507,701234.36868546 3675364.29728502,701234.36868546 3675362.29477)'))

https://www.screencast.com/t/1aP4rXEdhap

Is this expected behavior?


问:
Immutable .toArray() wont render data - ReactJS
I am mapping over some data and I am trying to use some of the data as the options for the semantic-ui-react Dropdown component, but the data wont load in even if I add .toArray() to the end of it, however if I change the data structure to not use Immutable, it works fine. I mainly wanted to understand why so I could get a better understanding of things.

Here is the mapping of the data with immutable:

          {
            labelingData.map((item, i) => {
              return (

                  {
                    item.get('categories').map((category, c) => {
                      return (

                          {
                            category.get('subcategories').map((subcategory, sc) => {
                              return (

                                  {
                                    subcategory.get('name') === 'Labels'
                                    ? <Dropdown
                                        defaultValue={'Bananas'}
                                        options={subcategory.get('childItems').toArray()}
                                      />
                                    : null
                                  }

                              );
                            })
                          }

                      );
                    })
                  }

              );
            })
          }```

I do get an error in the console about unknown props but I am not adding these props in my code:

Unknown props `_root`, `__ownerID`, `__hash`, `__altered` on
 tag. Remove these props from the element

答:
The api of semantic-ui-react Dropdown options is to pass in an array of objects that look like:

```<code>{ text: '', value: '' }
</code>```

However, when you call .toArray() on a Immutable.List containing some Immutable.Map it will not .toJS() the Maps.

eg.

```<code>var list = Immutable.fromJS({ value: 1 }, 2]);
console.log(list.toArray()); // prints [Immutable.Map, 2]
</code>```

So you are actually giving Dropdown an array of Maps and the Dropdown doesn't use .get to get the values from the object.

Another thing is that React prefers to receive arrays rather than immutable.Lists.

So you could use a reduce function rather than a map function to create a normal array of react components:

```<code>item.get('categories').reduce((result, category, c) => {
  result.push(<Category key={c} category={category} />);
  return result;
}, []);
</code>```

Body:
I am mapping over some data and I am trying to use some of the data as the options for the semantic-ui-react Dropdown component, but the data wont load in even if I add .toArray() to the end of it, however if I change the data structure to not use Immutable, it works fine. I mainly wanted to understand why so I could get a better understanding of things.

Here is the mapping of the data with immutable:

          {
            labelingData.map((item, i) => {
              return (

                  {
                    item.get('categories').map((category, c) => {
                      return (

                          {
                            category.get('subcategories').map((subcategory, sc) => {
                              return (

                                  {
                                    subcategory.get('name') === 'Labels'
                                    ? <Dropdown
                                        defaultValue={'Bananas'}
                                        options={subcategory.get('childItems').toArray()}
                                      />
                                    : null
                                  }

                              );
                            })
                          }

                      );
                    })
                  }

              );
            })
          }

I do get an error in the console about unknown props but I am not adding these props in my code:

Unknown props `_root`, `__ownerID`, `__hash`, `__altered` on
 tag. Remove these props from the element

Body:
The api of semantic-ui-react Dropdown options is to pass in an array of objects that look like:

{ text: '', value: '' }

However, when you call .toArray() on a Immutable.List containing some Immutable.Map it will not .toJS() the Maps.

eg.

var list = Immutable.fromJS({ value: 1 }, 2]);
console.log(list.toArray()); // prints [Immutable.Map, 2]

So you are actually giving Dropdown an array of Maps and the Dropdown doesn't use .get to get the values from the object.

Another thing is that React prefers to receive arrays rather than immutable.Lists.

So you could use a reduce function rather than a map function to create a normal array of react components:

item.get('categories').reduce((result, category, c) => {
  result.push(<Category key={c} category={category} />);
  return result;
}, []);


问:
Python3 NZEC Error
This piece of code is supposed to find account balance after withdraw from bank(fee=0.5).

```<code>wd,ac=raw_input().split(" ")
wd=int(wd)
ac=float(ac)
if(ac<wd):
    print(ac)
elif(wd%5==0):
    if(ac>wd+0.50):
        print(ac-wd-0.50)
    else:
        print(ac)
else:
    print(ac)
</code>```

I got a Runtime NZEC Error while submitting on codechef. I am newbie and had searched for resolve and had used split(" ") in place of int(input()), which I had tried previously, but the problem still occurs.

Geeksforgeeks says:

"In python, generally multiple inputs are separated by commas and we read them using input() or int(input()), but most of the online coding platforms while testing gives input separated by space and in those cases int(input()) is not able to read the input properly and shows error like NZEC"

Given that I've tried to account for that... What is wrong with my code?

答: It looks like an error with your raw_input statement. Remember that, in python 3, raw_input doesn't exist any more. If you changed it from raw_input to input, then the code works just fine.

Title: Python3 NZEC Error

Body:
This piece of code is supposed to find account balance after withdraw from bank(fee=0.5).

wd,ac=raw_input().split(" ")
wd=int(wd)
ac=float(ac)
if(ac<wd):
    print(ac)
elif(wd%5==0):
    if(ac>wd+0.50):
        print(ac-wd-0.50)
    else:
        print(ac)
else:
    print(ac)

I got a Runtime NZEC Error while submitting on codechef. I am newbie and had searched for resolve and had used split(" ") in place of int(input()), which I had tried previously, but the problem still occurs.

Geeksforgeeks says:

"In python, generally multiple inputs are separated by commas and we read them using input() or int(input()), but most of the online coding platforms while testing gives input separated by space and in those cases int(input()) is not able to read the input properly and shows error like NZEC"

Given that I've tried to account for that... What is wrong with my code?


问:
SQL Server group by ID & dynamic Pivot/Transpose attributes
I have seen a Dynamic SQL answer that was VERY similar to my problem here, but I couldn't wrap my head around the small change that would get me to the finish line.

I am trying to illustrate all of the stores you will need to travel to in order to complete a recipe, given a table that has a list of suppliers for each ingredient.

Current Ingredient Table:

```<code>RecipeId    Supplier
1           Store A
1           Store B
2           Store A
3           Store B
3           Store C
3           Store D
</code>```

Desired Ingredient Table (after group & pivot):

```<code>RecipeId    Supplier 1      Supplier 2      Supplier 3
1           Store A         Store B         NULL
2           Store A         NULL            NULL
3           Store B         Store C         Store D
</code>```

Any one recipe can have zero to infinite suppliers (I can cap it at 10 if I absolutely need to)
This is part of a larger query where I hope to ULTIMATELY join the ingredient table back to the recipe table yielding something like:

```<code>RecipeId    Recipe Name     Supplier 1      Supplier 2      Supplier 3      Supplier N
1           Cookies         Store A         Store B         NULL            NULL
2           Cake            Store A         NULL            NULL            NULL
3           Pie             Store B         Store C         Store D         NULL
</code>```

答:
Simple query for N recipes is below:

See working demo

```<code> declare @q varchar(max), @cols varchar(max)
set @cols
     = STUFF((
          SELECT distinct ',' +
               QUOTENAME('Supplier '+
                         cast(row_number()  over (partition by recipeid order by supplier ) as varchar(max))
                        )
            FROM Ingredient
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'')

set @q=
'select
  recipeid,'+ @cols +
' from
(
    select
       recipeid,
       Supplier,
       ''Supplier ''+
         cast(row_number()  over (partition by recipeid order by supplier ) as varchar(max))  as r
    from
       Ingredient
)I
pivot
(
    max(Supplier)
    for r in ('+@cols+')
 )piv'

 exec(@q)
</code>```

Body:
I have seen a Dynamic SQL answer that was VERY similar to my problem here, but I couldn't wrap my head around the small change that would get me to the finish line.

I am trying to illustrate all of the stores you will need to travel to in order to complete a recipe, given a table that has a list of suppliers for each ingredient.

Current Ingredient Table:

RecipeId    Supplier
1           Store A
1           Store B
2           Store A
3           Store B
3           Store C
3           Store D

Desired Ingredient Table (after group & pivot):

RecipeId    Supplier 1      Supplier 2      Supplier 3
1           Store A         Store B         NULL
2           Store A         NULL            NULL
3           Store B         Store C         Store D

Any one recipe can have zero to infinite suppliers (I can cap it at 10 if I absolutely need to)
This is part of a larger query where I hope to ULTIMATELY join the ingredient table back to the recipe table yielding something like:

RecipeId    Recipe Name     Supplier 1      Supplier 2      Supplier 3      Supplier N
1           Cookies         Store A         Store B         NULL            NULL
2           Cake            Store A         NULL            NULL            NULL
3           Pie             Store B         Store C         Store D         NULL

Body:
Simple query for N recipes is below:

See working demo

 declare @q varchar(max), @cols varchar(max)
set @cols
     = STUFF((
          SELECT distinct ',' +
               QUOTENAME('Supplier '+
                         cast(row_number()  over (partition by recipeid order by supplier ) as varchar(max))
                        )
            FROM Ingredient
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'')

set @q=
'select
  recipeid,'+ @cols +
' from
(
    select
       recipeid,
       Supplier,
       ''Supplier ''+
         cast(row_number()  over (partition by recipeid order by supplier ) as varchar(max))  as r
    from
       Ingredient
)I
pivot
(
    max(Supplier)
    for r in ('+@cols+')
 )piv'

 exec(@q)


问:
Print linq query (select *l)
i need to print all rows from one table.
avoid placing: s.Adress+s.EmployeeID, etc</p>

```<code>var query = from x
            in bd.Employees
            where x.City == "London" && x.TitleOfCourtesy == "Mr."
            select x;

foreach(var s in query)
{
  Console.WriteLine(s.Address+"---"+s.EmployeeID);
}
</code>```

答:
Console.WriteLine takes params so you can do this:

```<code>Console.WriteLine("{0}---{1}", s.Address, s.EmployeeID.ToString());
</code>```

Or you can use C# 6.0 string interpolation (Note the dollar sign):

```<code>Console.WriteLine($"{s.Address}---{s.EmployeeID}");
</code>```

EDIT

Since you mentioned in the comments:

I want to print all rows from each column from table Employees (Northwind db), without writing each of the columns names

You can do this, imagine you have a class:

```<code>public class One
{
    public int Id { get; set; }
    public string Name { get; set; }
}
</code>```

You can:

```<code>// using System.Web.Script.Serialization;
var ser = new JavaScriptSerializer();
var one = ser.Serialize(new One() { Id = 1, Name = "George" });

Console.WriteLine(one);
</code>```

Title: Print linq query (select *l)

Body:
i need to print all rows from one table.
avoid placing: s.Adress+s.EmployeeID, etc

var query = from x
            in bd.Employees
            where x.City == "London" && x.TitleOfCourtesy == "Mr."
            select x;

foreach(var s in query)
{
  Console.WriteLine(s.Address+"---"+s.EmployeeID);
}

Body:
Console.WriteLine takes params so you can do this:

Console.WriteLine("{0}---{1}", s.Address, s.EmployeeID.ToString());

Or you can use C# 6.0 string interpolation (Note the dollar sign):

Console.WriteLine($"{s.Address}---{s.EmployeeID}");

EDIT

Since you mentioned in the comments:

I want to print all rows from each column from table Employees (Northwind db), without writing each of the columns names

You can do this, imagine you have a class:

public class One
{
    public int Id { get; set; }
    public string Name { get; set; }
}

You can:

// using System.Web.Script.Serialization;
var ser = new JavaScriptSerializer();
var one = ser.Serialize(new One() { Id = 1, Name = "George" });

Console.WriteLine(one);


问:
Azure Functions and Caching
We are planning to develop an Azure function for which the input trigger is a service bus message and the output will be blob storage. The service bus message will contain a image url and the function will resize the image to a predefined resolution and will upload to azure blob storage.

The resolution to which the image should be resized is stored in the database and the Azure function needs to make a call to database to get to know the resolution that is supposed to be used for the image in the input message. The resolution would actually be a master data configured based on the source of the input message.

Making a database call would be a expensive call as it would have to go to the database for each call. Is there any way to cache the data and use it without calling the database. Like in memory caching?

答: You can use Azure Cache service (https://azure.microsoft.com/en-us/services/cache/) to cache your data. Basically, In your Azure Function instead of calling database all the time, call Azure cache and use if it is not expired and if it is expired or not set then call database to get the value and populate the cache with appropriate expiry logic (timeout after fixed time or some other custom logic).</p>

Title: Azure Functions and Caching


问:
GetgeneratedKeys not working although row inserted
I use HSQLDB - Tried version 2.3.4 and 2.4.

I have this Java code:

```<code>            String sqlquery = "MERGE INTO bewertung pu USING "
            .concat("(VALUES ?,?,?) ")
            .concat("temp (tid,jurorid,runde) ")
            .concat("ON temp.tid = pu.tid and temp.jurorid=pu.jurorid and temp.runde=pu.runde ")
            .concat("WHEN NOT MATCHED THEN ")
            .concat("INSERT (tid,jurorid,runde) ")
            .concat("VALUES (temp.tid,temp.jurorid,temp.runde)");

        PreparedStatement preparedStatement = sql.getConnection().prepareStatement(sqlquery,
                                      Statement.RETURN_GENERATED_KEYS);

        preparedStatement.setInt(1, eineBewertung.getTanzID()); //TID
        preparedStatement.setInt(2, eineBewertung.getJurorID()); //JURORID
        preparedStatement.setInt(3, eineBewertung.getRunde()); //RUNDE

        int rowsAffected = preparedStatement.executeUpdate();

        if (rowsAffected == 0) {
            //UPDATE
            //DO SOMETHING
        }else{
            //INSERT
            try (ResultSet rs = preparedStatement.getGeneratedKeys()) {
               if (rs.next()) {
                   eineBewertung.setBewertungsid(rs.getInt(1));
               }
            }catch (SQLException ex) {
                this.controller.error_ausgeben(ex);
            }
        }
</code>```

It works. If I insert a new row I get rowsAffected = 1. I check the database and the insert worked.

But, I do not get anything back in the resultset getGeneratedKeys()
It is every time empty.

I have found some tips to replace Statement.RETURN_GENERATED_KEYS with the primary key. But this didn`t work for me.

```<code>    PreparedStatement preparedStatement = sql.getConnection().prepareStatement(sqlquery,
                                  new String[]{"BEWERTUNGSID"});
</code>```

This is how I create the table:

```<code>            statement.execute("create table PUBLIC.BEWERTUNG"
                .concat("(BEWERTUNGSID INTEGER IDENTITY,")
                .concat("TID INTEGER FOREIGN KEY REFERENCES Tanz(Tanzid),")
                .concat("JURORID INTEGER not null FOREIGN KEY References JUROR(JURORID),")
                .concat("RUNDE INTEGER not null,")
                .concat("primary key(BEWERTUNGSID)")
                .concat(")"));
</code>```

Why do I not get any generated keys back? Thank you

//EDIT
If I replace my sqlquery with an insert statement it is working.

```<code>            sqlquery = "INSERT INTO BEWERTUNG(TID, JURORID, RUNDE) VALUES(22, 2, 2)";
</code>```

Why is merge not working in the sqlquery?

答: With versions of HSQLDB up to 2.4.0, generated keys are not available when inserting data using a MERGE statement. Code has been committed to allow this in the next version.</p>

Body:
I use HSQLDB - Tried version 2.3.4 and 2.4.

I have this Java code:

            String sqlquery = "MERGE INTO bewertung pu USING "
            .concat("(VALUES ?,?,?) ")
            .concat("temp (tid,jurorid,runde) ")
            .concat("ON temp.tid = pu.tid and temp.jurorid=pu.jurorid and temp.runde=pu.runde ")
            .concat("WHEN NOT MATCHED THEN ")
            .concat("INSERT (tid,jurorid,runde) ")
            .concat("VALUES (temp.tid,temp.jurorid,temp.runde)");

        PreparedStatement preparedStatement = sql.getConnection().prepareStatement(sqlquery,
                                      Statement.RETURN_GENERATED_KEYS);

        preparedStatement.setInt(1, eineBewertung.getTanzID()); //TID
        preparedStatement.setInt(2, eineBewertung.getJurorID()); //JURORID
        preparedStatement.setInt(3, eineBewertung.getRunde()); //RUNDE

        int rowsAffected = preparedStatement.executeUpdate();

        if (rowsAffected == 0) {
            //UPDATE
            //DO SOMETHING
        }else{
            //INSERT
            try (ResultSet rs = preparedStatement.getGeneratedKeys()) {
               if (rs.next()) {
                   eineBewertung.setBewertungsid(rs.getInt(1));
               }
            }catch (SQLException ex) {
                this.controller.error_ausgeben(ex);
            }
        }

It works. If I insert a new row I get rowsAffected = 1. I check the database and the insert worked.

But, I do not get anything back in the resultset getGeneratedKeys()
It is every time empty.

I have found some tips to replace Statement.RETURN_GENERATED_KEYS with the primary key. But this didn`t work for me.

    PreparedStatement preparedStatement = sql.getConnection().prepareStatement(sqlquery,
                                  new String[]{"BEWERTUNGSID"});

This is how I create the table:

            statement.execute("create table PUBLIC.BEWERTUNG"
                .concat("(BEWERTUNGSID INTEGER IDENTITY,")
                .concat("TID INTEGER FOREIGN KEY REFERENCES Tanz(Tanzid),")
                .concat("JURORID INTEGER not null FOREIGN KEY References JUROR(JURORID),")
                .concat("RUNDE INTEGER not null,")
                .concat("primary key(BEWERTUNGSID)")
                .concat(")"));

Why do I not get any generated keys back? Thank you

//EDIT
If I replace my sqlquery with an insert statement it is working.

            sqlquery = "INSERT INTO BEWERTUNG(TID, JURORID, RUNDE) VALUES(22, 2, 2)";

Why is merge not working in the sqlquery?


问:
VBA: Code review - Skip 1st line of a sheet
I was trying to understand how to skip the 1st row (A) of my sheet when i use below code which check whether any value available on my excel sheet.

```<code>Sub IsActiveSheetEmpty()
    If WorksheetFunction.CountA(Cells) = 0 Then
       MsgBox ActiveSheet.Name & " is empty"
    Else
      MsgBox ActiveSheet.Name & " is not empty"
    End If
End Sub
</code>```

Thanks in Advance

答:
Try the following (does implicitly reference active sheet so you may want to explicitly state the worksheet name.) It will use the last row and column for which ever version of Excel you are using:</p>

```<code>Sub IsActiveSheetEmpty()

    If WorksheetFunction.CountA(Range(Cells(2, "A"), Cells(Cells.Rows.Count, Cells.Columns.Count))) = 0 Then
       MsgBox ActiveSheet.Name & " is empty"
    Else
      MsgBox ActiveSheet.Name & " is not empty"
    End If

End Sub
</code>```

Body:
I was trying to understand how to skip the 1st row (A) of my sheet when i use below code which check whether any value available on my excel sheet.

Sub IsActiveSheetEmpty()
    If WorksheetFunction.CountA(Cells) = 0 Then
       MsgBox ActiveSheet.Name & " is empty"
    Else
      MsgBox ActiveSheet.Name & " is not empty"
    End If
End Sub

Thanks in Advance

Body:
Try the following (does implicitly reference active sheet so you may want to explicitly state the worksheet name.) It will use the last row and column for which ever version of Excel you are using:

Sub IsActiveSheetEmpty()

    If WorksheetFunction.CountA(Range(Cells(2, "A"), Cells(Cells.Rows.Count, Cells.Columns.Count))) = 0 Then
       MsgBox ActiveSheet.Name & " is empty"
    Else
      MsgBox ActiveSheet.Name & " is not empty"
    End If

End Sub


问:
PHP Regular expression tag matching
Been beating my head against a wall trying to get this to work - help from any regex gurus would be greatly appreciated!

The text that has to be matched

```<code>[template option="whatever"]

<p>any amount of html would go here</p>

[/template]
</code>```

I need to pull the 'option' value (i.e. 'whatever') and the html between the template tags.

So far I have:

```<code>> /\[template\s*option=["\']([^"\']+)["\']\]((?!\[\/template\]))/
</code>```

Which gets me everything except the html between the template tags.

Any ideas?

Thanks, Chris

答:
edit: [\s\S] will match anything that is space or not space.

you may have a problem when there are consecutive blocks in a large string. in that case you will need to make a more specific quantifier - either non greedy (+?) or specify range {1,200} or make the [\s\S] more specific

```<code>/\[template\s*option=["\']([^"\']+)["\']\]([\s\S]+)\[\/template\]/
</code>```

Title: PHP Regular expression tag matching

Body:
Been beating my head against a wall trying to get this to work - help from any regex gurus would be greatly appreciated!

The text that has to be matched

[template option="whatever"]

any amount of html would go here

[/template]

I need to pull the 'option' value (i.e. 'whatever') and the html between the template tags.

So far I have:

> /\[template\s*option=["\']([^"\']+)["\']\]((?!\[\/template\]))/

Which gets me everything except the html between the template tags.

Any ideas?

Thanks, Chris

Body:
edit: [\s\S] will match anything that is space or not space.

you may have a problem when there are consecutive blocks in a large string. in that case you will need to make a more specific quantifier - either non greedy (+?) or specify range {1,200} or make the [\s\S] more specific

/\[template\s*option=["\']([^"\']+)["\']\]([\s\S]+)\[\/template\]/


答:
You are free to use the usual approaches that you would use in other .NET applications:

You can cache it in memory. The easiest way is just to declare a static dictionary and put database values inside (use concurrent dictionary if needed). The cached values will be reused for all subsequent Function executions which run on the same instance. If an instance gets idle for 5 minutes, or if App scales out to an extra instance, you will have to read the database again;

You can use distributed cache, e.g. Redis, by using its SDK from Function code. Might be a bit nicer, since you keep the stateless nature of Functions, but might cost a bit more. Table Storage is a viable alternative to Redis, but with more limited API.

There's no "caching" feature of Azure Functions themselves, that would be ready to use without any extra code.

Title: Azure Functions and Caching

Body:
We are planning to develop an Azure function for which the input trigger is a service bus message and the output will be blob storage. The service bus message will contain a image url and the function will resize the image to a predefined resolution and will upload to azure blob storage.

The resolution to which the image should be resized is stored in the database and the Azure function needs to make a call to database to get to know the resolution that is supposed to be used for the image in the input message. The resolution would actually be a master data configured based on the source of the input message.

Making a database call would be a expensive call as it would have to go to the database for each call. Is there any way to cache the data and use it without calling the database. Like in memory caching?


问:
How to pass variables from javascript to python in Jupyter?
As I understand it, I should be able to print the variable foo in the snippet below.

```<code>from IPython.display import HTML
HTML('''
    <script type="text/javascript">
        IPython.notebook.kernel.execute("foo=97")
    </script>
     ''')
print(foo)
</code>```

Instead, I see this error message:

```<code>NameErrorTraceback (most recent call last)
<ipython-input-2-91b73ee49ec6> in <module>()
      5     </script>
      6      ''')
----> 7 print(foo)

NameError: name 'foo' is not defined
</code>```

I'm trying to use this answer but struggling to make it work.

FWIW, this is the latest Jupyter code (according to pip) running on Fedora 23. What are the prerequisites to make this work?

答:
```<code>from IPython.display import HTML
HTML('''
<script type="text/javascript">
    IPython.notebook.kernel.execute("foo=11")
</script>
 ''')
from time import sleep
sleep(3)
print(foo)
</code>```

The reason this works is the HTML takes some time to work and you print it even before the value is set. With sleep, the wait time of 3s seems to be enough and the variable gets assigned.

Body:
As I understand it, I should be able to print the variable foo in the snippet below.

from IPython.display import HTML
HTML('''

     ''')
print(foo)

Instead, I see this error message:

NameErrorTraceback (most recent call last)
<ipython-input-2-91b73ee49ec6> in <module>()
      5     </script>
      6      ''')
----> 7 print(foo)

NameError: name 'foo' is not defined

I'm trying to use this answer but struggling to make it work.

FWIW, this is the latest Jupyter code (according to pip) running on Fedora 23. What are the prerequisites to make this work?

Body:
from IPython.display import HTML
HTML('''
<script type="text/javascript">
    IPython.notebook.kernel.execute("foo=11")
</script>
 ''')
from time import sleep
sleep(3)
print(foo)

The reason this works is the HTML takes some time to work and you print it even before the value is set. With sleep, the wait time of 3s seems to be enough and the variable gets assigned.