问:
sql- exceeding variable size in a exec?
I inherited some partially complete sql code that I can't get to work.

it accesses multiple databases, so it first searches for proper database using a userID number, then inserts that database name into a query. the part i'm having a problem with (extremely abbreviated) is...

```<code>DECLARE @sql AS VARCHAR(8000)
    SET @sql = 'INSERT INTO ['+@DatabaseName+'].dbo.[customer]
                  ( -- containing about 200 columns. )
                VALUES(...)'
PRINT @sql
EXEC(@sql)
</code>```

i would get errors in the middle of a column name, sometimes saying it's expecting a parenthesis or quote. i started deleting white space so that, ie, [first name],[last name] were on the same line and not two different lines and that would get me a little further down the query. i don't have much more white spaces i can delete and i'm only just getting into the Values(...) portion of it. the weird thing is. i copy and pasted just the columns portion and put it into Word and it comes up as being only about 3,000 characters, including white space.

am i missing something?

if it means anything, i'm running microsoft sql server 2005, and using the sql server management studio for editing

thanks!

答: Use an nvarchar(max) datatype for @sql.</p>

Title: sql- exceeding variable size in a exec?

Body:
I inherited some partially complete sql code that I can't get to work.

it accesses multiple databases, so it first searches for proper database using a userID number, then inserts that database name into a query. the part i'm having a problem with (extremely abbreviated) is...

DECLARE @sql AS VARCHAR(8000)
    SET @sql = 'INSERT INTO ['+@DatabaseName+'].dbo.[customer]
                  ( -- containing about 200 columns. )
                VALUES(...)'
PRINT @sql
EXEC(@sql)

i would get errors in the middle of a column name, sometimes saying it's expecting a parenthesis or quote. i started deleting white space so that, ie, [first name],[last name] were on the same line and not two different lines and that would get me a little further down the query. i don't have much more white spaces i can delete and i'm only just getting into the Values(...) portion of it. the weird thing is. i copy and pasted just the columns portion and put it into Word and it comes up as being only about 3,000 characters, including white space.

am i missing something?

if it means anything, i'm running microsoft sql server 2005, and using the sql server management studio for editing

thanks!

Body: Use an nvarchar(max) datatype for @sql.


来源: stackexchange

问:
How to create a loop inside a loop in R
I am new to R and I need some help in relation loops. I need to produce a huge amount to tables from one data set and I think that a loop inside a loop will solve the problem, but I am having problems getting the right result.

Lets say I have the following data set:

```<code>var1 <- c("A","A","A","A","B","B","B","B")
var2 <- c(1,2,1,2,1,2,1,2)
df <- data.frame(var1,var2)
</code>```

And I want to extract the data in 4 tables:

Result of "A" & 1

Result of "A" & 2

Result of "B" & 1

Result of "B" & 2

I have this loop, but I cannot get the 4 tables. Can anyone help!

```<code>for (i in df$var1) {

    dummy<- df%>%filter(var1 == i)

    for (j in dummy$var2) {

       nTab <- paste0("tab_", j, sep ="")
       assign(nTab, dummy%>%filter (var2 == j))

   }
}
</code>```

答:
We can split the data frame into several data frames based on two columns and store them in a list.

```<code>df_list <- split(df, f = list(df$var1, df$var2))

df_list
# $A.1
#   var1 var2
# 1    A    1
# 3    A    1
#
# $B.1
#   var1 var2
# 5    B    1
# 7    B    1
#
# $A.2
#   var1 var2
# 2    A    2
# 4    A    2
#
# $B.2
#   var1 var2
# 6    B    2
# 8    B    2
</code>```

To save the data frames in the list, we can further use the lapply function.

```<code>lapply(names(df_list), function(x) write.csv(df_list[[x]], paste0(x, ".csv"), row.names = FALSE))
</code>```

Where df_list[[x]] is the way to access individual data frames based on the name. paste0(x, ".csv") is to construct file directory.

ContentLicense: CC BY-SA 3.0

Title: How to create a loop inside a loop in R

Body:
I am new to R and I need some help in relation loops. I need to produce a huge amount to tables from one data set and I think that a loop inside a loop will solve the problem, but I am having problems getting the right result.

Lets say I have the following data set:

var1 <- c("A","A","A","A","B","B","B","B")
var2 <- c(1,2,1,2,1,2,1,2)
df <- data.frame(var1,var2)

And I want to extract the data in 4 tables:

Result of "A" & 1

Result of "A" & 2

Result of "B" & 1

Result of "B" & 2

I have this loop, but I cannot get the 4 tables. Can anyone help!

for (i in df$var1) {

    dummy<- df%>%filter(var1 == i)

    for (j in dummy$var2) {

       nTab <- paste0("tab_", j, sep ="")
       assign(nTab, dummy%>%filter (var2 == j))

   }
}

Body:
We can split the data frame into several data frames based on two columns and store them in a list.

df_list <- split(df, f = list(df$var1, df$var2))

df_list
# $A.1
#   var1 var2
# 1    A    1
# 3    A    1
#
# $B.1
#   var1 var2
# 5    B    1
# 7    B    1
#
# $A.2
#   var1 var2
# 2    A    2
# 4    A    2
#
# $B.2
#   var1 var2
# 6    B    2
# 8    B    2

To save the data frames in the list, we can further use the lapply function.

lapply(names(df_list), function(x) write.csv(df_list[[x]], paste0(x, ".csv"), row.names = FALSE))

Where df_list[[x]] is the way to access individual data frames based on the name. paste0(x, ".csv") is to construct file directory.


问:
Symlinks not recognized when pulled from git
I have a project in git, which when I symlinks down from git the first time, the symlinks do not work. From all I can see they are properly made symlinks. If I remove the symlinks and recreate them myself, git also sees them as Identical to the ones it has.

Is there a setting in Linux or Git that would prevent symlinks from working if they came form git?

The command used to create the symlinks:

```<code>ln -s /absolute/path/to/dest symlink-name
</code>```

Some additional information

Symlinks were originally created on a MacBook, but since git sees my newly created symlinks (on linux) as identical, I doubt this is the issue.

When getting the symlinks for the first time, they do not work on linux, but on other Mac machines they do.

After fixing the symlinks by deleting and recreating them, git sees them as identical and hench they are not overridden in future pulls.

All symlinks are to .phar files.

The linux machines are running Ubuntu 16.04 or Centos 7

Using ls -lah lists the symlinks as regular files:

```<code>-rw-rw-r--.  1 vagrant vagrant   28 Nov 13 09:01 dep
-rw-rw-r--.  1 vagrant vagrant   28 Nov 13 09:01 drupal
-rw-rw-r--.  1 vagrant vagrant   20 Nov 13 09:01 drush
-rw-rw-r--.  1 vagrant vagrant   32 Nov 13 09:01 drush.complete.sh
-rw-rw-r--.  1 vagrant vagrant   29 Nov 13 09:01 drush.launcher
-rw-rw-r--.  1 vagrant vagrant   24 Nov 13 09:01 drush.php
-rw-rw-r--.  1 vagrant vagrant   33 Nov 13 09:01 php-parse
-rw-rw-r--.  1 vagrant vagrant   26 Nov 13 09:01 phpunit
-rw-rw-r--.  1 vagrant vagrant   22 Nov 13 09:01 psysh
</code>```

Whereas, if I manually remove and recreate the dep symlink, it shows up correctly. Git still sees this as identical and no changes were made.

```<code>lrwxrwxrwx.  1 vagrant vagrant   28 Nov 13 09:33 dep -> ../deployer/deployer/bin/dep
</code>```

Changing the permissions form  -rw-rw-r-- to lrwxrwxrwx on the broken symlinks, does not fix them either.

Any help is greatly appreciated.

答:
One of your configuration files has turned off the core.symlinks setting.  To find out where this was set, run:

```<code>for location in global system local; do
    git config -l --$location |& grep -q symlinks && echo $location
done
</code>```

This will output whether it is set in the global, system or local location.

The global location is typically $HOME/.gitconfig, the system location is typically /etc/gitconfig, and the local location is typically .git/config in the current repository.

Remove that line and Git should be able to create symlinks properly.

Body:
I have a project in git, which when I symlinks down from git the first time, the symlinks do not work. From all I can see they are properly made symlinks. If I remove the symlinks and recreate them myself, git also sees them as Identical to the ones it has.

Is there a setting in Linux or Git that would prevent symlinks from working if they came form git?

The command used to create the symlinks:

ln -s /absolute/path/to/dest symlink-name

Some additional information

Symlinks were originally created on a MacBook, but since git sees my newly created symlinks (on linux) as identical, I doubt this is the issue.

When getting the symlinks for the first time, they do not work on linux, but on other Mac machines they do.

After fixing the symlinks by deleting and recreating them, git sees them as identical and hench they are not overridden in future pulls.

All symlinks are to .phar files.

The linux machines are running Ubuntu 16.04 or Centos 7

Using ls -lah lists the symlinks as regular files:

-rw-rw-r--.  1 vagrant vagrant   28 Nov 13 09:01 dep
-rw-rw-r--.  1 vagrant vagrant   28 Nov 13 09:01 drupal
-rw-rw-r--.  1 vagrant vagrant   20 Nov 13 09:01 drush
-rw-rw-r--.  1 vagrant vagrant   32 Nov 13 09:01 drush.complete.sh
-rw-rw-r--.  1 vagrant vagrant   29 Nov 13 09:01 drush.launcher
-rw-rw-r--.  1 vagrant vagrant   24 Nov 13 09:01 drush.php
-rw-rw-r--.  1 vagrant vagrant   33 Nov 13 09:01 php-parse
-rw-rw-r--.  1 vagrant vagrant   26 Nov 13 09:01 phpunit
-rw-rw-r--.  1 vagrant vagrant   22 Nov 13 09:01 psysh

Whereas, if I manually remove and recreate the dep symlink, it shows up correctly. Git still sees this as identical and no changes were made.

lrwxrwxrwx.  1 vagrant vagrant   28 Nov 13 09:33 dep -> ../deployer/deployer/bin/dep

Changing the permissions form  -rw-rw-r-- to lrwxrwxrwx on the broken symlinks, does not fix them either.

Any help is greatly appreciated.

Body:
One of your configuration files has turned off the core.symlinks setting.  To find out where this was set, run:

for location in global system local; do
    git config -l --$location |& grep -q symlinks && echo $location
done

This will output whether it is set in the global, system or local location.

The global location is typically $HOME/.gitconfig, the system location is typically /etc/gitconfig, and the local location is typically .git/config in the current repository.

Remove that line and Git should be able to create symlinks properly.


问:
Javascript ES5: How to extend the Function object in order to set a property value on itself, every time the function is executed?
I currently have the following working code:

```<code>Function.prototype.GetLastCallerName = function () {
  if (!this.arguments || !this.arguments.callee || !this.arguments.callee.caller) return null;
  var result = /^function\s+([\w\$]+)\s*\(/.exec(this.arguments.callee.caller.toString());
  this.LastCaller = result ? result[1] : 'Anonymous';
  return this.LastCaller;
};
</code>```

I picked up that code from another thread.  As you can see, it extends the Function.prototype in order to add a method called GetLastCallerName, which picks the last calling function name and (1) sets it to LastCaller on Function.LastCaller and (2) returns it.

In order to make it work:

```<code>function MyFunction1() {
  MyFunction1.GetLastCallerName();
  console.log(MyFunction.LastCaller);
}

function MyFunction2() {
  MyFunction1();
}

MyFunction2();
</code>```

What I'd like to be able to do:  Eliminate the need to use GetLastCallerName() every time and extend Function in order to perform that get every time any function is called.

答:
I'm struggling to follow what you have tried so far with your example, but I think I get the idea of what you'd like to do. Why not leverage classes, and extend on them for your use case. Check out the following example...

```<code>class Base {

  baseFn() {
    console.log('from base');
  }
}

class Thing extends Base {

  fn1() {
    this.baseFn();
  }
}

let thingee = new Thing();

thingee.fn1();
</code>```

So baseFn is now always called when fn1 is called.

JSFiddle Link - class demo

In some of your comments it looks like you are wanting to get the "last calling function's name." How about passing back the instance of the caller itself to the parent? This would surely give you even more flexibility because now you can sculpt your caller however you wish. Check out the following...

```<code>class Base {

  baseFn(caller) {
    console.log(caller.id); // 1
  }
}

class Thing extends Base {

  constructor(id) {
    super();

    this.id = id;
  }

  fn1() {
    this.baseFn(this);
  }
}

let thingee = new Thing('1');

thingee.fn1();
</code>```

Now you can add whatever you'd like to your Thing instance, in this case, an object with an id of 1 which can be inspected when fn1 propagates up to baseFn

JSFiddle Link - caller demo

Body:
I currently have the following working code:

Function.prototype.GetLastCallerName = function () {
  if (!this.arguments || !this.arguments.callee || !this.arguments.callee.caller) return null;
  var result = /^function\s+([\w\$]+)\s*\(/.exec(this.arguments.callee.caller.toString());
  this.LastCaller = result ? result[1] : 'Anonymous';
  return this.LastCaller;
};

I picked up that code from another thread.  As you can see, it extends the Function.prototype in order to add a method called GetLastCallerName, which picks the last calling function name and (1) sets it to LastCaller on Function.LastCaller and (2) returns it.

In order to make it work:

function MyFunction1() {
  MyFunction1.GetLastCallerName();
  console.log(MyFunction.LastCaller);
}

function MyFunction2() {
  MyFunction1();
}

MyFunction2();

What I'd like to be able to do:  Eliminate the need to use GetLastCallerName() every time and extend Function in order to perform that get every time any function is called.

Body:
I'm struggling to follow what you have tried so far with your example, but I think I get the idea of what you'd like to do. Why not leverage classes, and extend on them for your use case. Check out the following example...

class Base {

  baseFn() {
    console.log('from base');
  }
}

class Thing extends Base {

  fn1() {
    this.baseFn();
  }
}

let thingee = new Thing();

thingee.fn1();

So baseFn is now always called when fn1 is called.

JSFiddle Link - class demo

In some of your comments it looks like you are wanting to get the "last calling function's name." How about passing back the instance of the caller itself to the parent? This would surely give you even more flexibility because now you can sculpt your caller however you wish. Check out the following...

class Base {

  baseFn(caller) {
    console.log(caller.id); // 1
  }
}

class Thing extends Base {

  constructor(id) {
    super();

    this.id = id;
  }

  fn1() {
    this.baseFn(this);
  }
}

let thingee = new Thing('1');

thingee.fn1();

Now you can add whatever you'd like to your Thing instance, in this case, an object with an id of 1 which can be inspected when fn1 propagates up to baseFn

JSFiddle Link - caller demo


问:
How to load/unload an html to a div by clicking on a button with slideDown/Up
I am working on a big menu-list that opens/closes with jquery's toggle() function.
I would like for one of the items on the menu-list to, when clicked, slideDown and reveal load() content from another .html on the div beneath it and then, when clicked again, to slideUp and remove the load () content.

The code i have written so far seems to work, however, after clicking the second time, it seems to go "crazy" and confuse the sequence of slideDown and Up and repeat the movement in a loop.

Since it uses the load() method, the code won't work here, but I am putting the code I am using anyway so you can check the logic.

$(document).ready(function(){
    $('.show-project-01').on('click', function(){

        if ($('.project').html() == "") {
            $('.project').slideDown()
            $('.project').load('project-01.html')
        } else {
            $('.project').slideUp()
            $('.project').empty()
        }

        return false

        })
})    ```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Pure office <img src="assets/teste-01.jpg" alt="" class="image-01">

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

I am new to jquery, so I don't quite understand what I am doing wrong and any suggestion is more than welcome.

Thank you!

答:
You could use data attributes to make sure the container div is open or closed

```<code>var button = $('.show-project-01');
var container = $('.project');

// add data-open attribute of close
button.attr('data-open','close');
  // on button click
  button.on('click',function() {

    // get data-open arrtibute
    var open = $(this).data('open');

    // if data-open is open
    if(open != 'open'){
      // update data-open to open
      $(this).data('open','open');
      container.load('project-01.html', function() {
           container.slideDown();
      });
 } else {
        container.slideUp();
        // do you need to remove the html?
        //container.empty()
        // update data-open to close
        $(this).data('open','close');
    }
});
</code>```

working example - https://jsfiddle.net/Jim_Miraidev/Lp2r3yqn/

Body:
I am working on a big menu-list that opens/closes with jquery's toggle() function.
I would like for one of the items on the menu-list to, when clicked, slideDown and reveal load() content from another .html on the div beneath it and then, when clicked again, to slideUp and remove the load () content.

The code i have written so far seems to work, however, after clicking the second time, it seems to go "crazy" and confuse the sequence of slideDown and Up and repeat the movement in a loop.

Since it uses the load() method, the code won't work here, but I am putting the code I am using anyway so you can check the logic.

$(document).ready(function(){
    $('.show-project-01').on('click', function(){

        if ($('.project').html() == "") {
            $('.project').slideDown()
            $('.project').load('project-01.html')
        } else {
            $('.project').slideUp()
            $('.project').empty()
        }

        return false

        })
})

Pure office

I am new to jquery, so I don't quite understand what I am doing wrong and any suggestion is more than welcome.

Thank you!

Body:
You could use data attributes to make sure the container div is open or closed

var button = $('.show-project-01');
var container = $('.project');

// add data-open attribute of close
button.attr('data-open','close');
  // on button click
  button.on('click',function() {

    // get data-open arrtibute
    var open = $(this).data('open');

    // if data-open is open
    if(open != 'open'){
      // update data-open to open
      $(this).data('open','open');
      container.load('project-01.html', function() {
           container.slideDown();
      });
 } else {
        container.slideUp();
        // do you need to remove the html?
        //container.empty()
        // update data-open to close
        $(this).data('open','close');
    }
});

working example - https://jsfiddle.net/Jim_Miraidev/Lp2r3yqn/


问:
How to blink KmlLayer file with polyline data on google map?
How to blink KmlLayer file with polyline data on google map?
My KmlLayer file has more than 100 polylines, and i want all the lines blinking.
Is there anyway to adjust var ctaLayer = new google.maps.KmlLayer to blink.

答:
Use setInterval to alternate the map property:

```<code>setInterval(function() {
  ctaLayer.setOptions({preserveViewport: true});
  ctaLayer.getMap() == null ? ctaLayer.setMap(map) : ctaLayer.setMap(null);
}, 1000);
</code>```

proof of concept fiddle

code snippet:

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 11,
    center: {
      lat: 41.876,
      lng: -87.624
    }
  });

  var ctaLayer = new google.maps.KmlLayer({
    url: 'http://googlemaps.github.io/js-v2-samples/ggeoxml/cta.kml',
    map: map
  });

  setInterval(function() {
    ctaLayer.setOptions({
      preserveViewport: true
    });
    ctaLayer.getMap() == null ? ctaLayer.setMap(map) : ctaLayer.setMap(null);
  }, 1000);
}
google.maps.event.addDomListener(window, "load", initMap);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}</code>```

```

Body:
Use setInterval to alternate the map property:

setInterval(function() {
  ctaLayer.setOptions({preserveViewport: true});
  ctaLayer.getMap() == null ? ctaLayer.setMap(map) : ctaLayer.setMap(null);
}, 1000);

proof of concept fiddle

code snippet:

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 11,
    center: {
      lat: 41.876,
      lng: -87.624
    }
  });

  var ctaLayer = new google.maps.KmlLayer({
    url: 'http://googlemaps.github.io/js-v2-samples/ggeoxml/cta.kml',
    map: map
  });

  setInterval(function() {
    ctaLayer.setOptions({
      preserveViewport: true
    });
    ctaLayer.getMap() == null ? ctaLayer.setMap(map) : ctaLayer.setMap(null);
  }, 1000);
}
google.maps.event.addDomListener(window, "load", initMap);

html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}

<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>


问:
Sum a field in a jsonb column with an Ecto query
Say I have a jsonb type column in a Postgres DB, called info. One of the fields is bytes, which is stored as an integer in the info field.

If I try and sum the values of the info => bytes field in an Ecto Query, as below:

```<code>total_bytes = Repo.one(from job in FilesTable,
  select: sum(fragment("info->>'bytes'")))
</code>```

I get the error function sum(text) does not exist.

Is there a way to write the query above so that info => bytes can be summed, or would I have to just select that field from each row in the database, and then use Elixir to add up the values?

答:
The error message says that it can't sum a text field. You need to explicitly cast the field to an integer so that sum works.

Also, it's incorrect to hardcode a column name in a fragment. It only works in this case because you're selecting from only one table. If you had some join statements in there with other tables with the same column name, the query won't work. You can use ? in the string and then pass the column as argument.

Here's the final thing that should work:

```<code>sum(fragment("(?->>'bytes')::integer", job.info)))
</code>```

Body:
Say I have a jsonb type column in a Postgres DB, called info. One of the fields is bytes, which is stored as an integer in the info field.

If I try and sum the values of the info => bytes field in an Ecto Query, as below:

total_bytes = Repo.one(from job in FilesTable,
  select: sum(fragment("info->>'bytes'")))

I get the error function sum(text) does not exist.

Is there a way to write the query above so that info => bytes can be summed, or would I have to just select that field from each row in the database, and then use Elixir to add up the values?

Body:
The error message says that it can't sum a text field. You need to explicitly cast the field to an integer so that sum works.

Also, it's incorrect to hardcode a column name in a fragment. It only works in this case because you're selecting from only one table. If you had some join statements in there with other tables with the same column name, the query won't work. You can use ? in the string and then pass the column as argument.

Here's the final thing that should work:

sum(fragment("(?->>'bytes')::integer", job.info)))


问:
'Suite' of Programs?
I'm currently developing multiple node.js programs that all fall under the same project. These programs will share common code for things like connecting to a server, inserting to a database, and even logging to console. Ideally, I'd like to package all of these under one parent program, like how git does it - users execute 'git [command]' to run the program 'git-[command]'.

The problem is that there are programs to be run on the server, and programs to be run on the client - I'd like to keep these separate. There are also multiple programs that every server and client will need, but I'd like to keep these separate as well instead of just having 'server' and 'client' packages.

Is there any documentation for what I'm trying to do? Or, if what I'm trying to do is not recommended, what would you guys suggest instead?

Thanks!

答:
My suggestion is to create node packages of your common code and then use npm to install and handle dependencies, updates and so on.

You are probably used to installing npm packages from the official npm registry. They can also be installed using local folders as source:

From the documentation.

```<code>{
  "name": "mainproject",
  "dependencies": {
    "serverstuff": "file:../foo/bar"
  }
}
</code>```

You can also install from GitHub:

```<code>{
  "name": "mainproject",
  "dependencies": {
    "serverstuff": "https://github.com/user-xyz/baz/tarball/master"
  }
}
</code>```

The common code packages can also have their own dependencies:

```<code>{
  "name": "serverstuff",
  "dependencies": {
    "connect": "file:../foo/bar2"
  }
}
</code>```

Title: 'Suite' of Programs?

Body:
My suggestion is to create node packages of your common code and then use npm to install and handle dependencies, updates and so on.

You are probably used to installing npm packages from the official npm registry. They can also be installed using local folders as source:

From the documentation.

{
  "name": "mainproject",
  "dependencies": {
    "serverstuff": "file:../foo/bar"
  }
}

You can also install from GitHub:

{
  "name": "mainproject",
  "dependencies": {
    "serverstuff": "https://github.com/user-xyz/baz/tarball/master"
  }
}

The common code packages can also have their own dependencies:

{
  "name": "serverstuff",
  "dependencies": {
    "connect": "file:../foo/bar2"
  }
}


问:
Visual Basic: Save in same folder as Excel Sheet
I'm very new to VB, so this is probably a very easy one.  I'm creating a Word document from an Excel spreadsheet, and would like the Word doc to save in the same folder location as the spreadsheet.

I'm using the code:
.SaveAs Filename:=ThisWorkbook.Path & Range("C8").Text & ".docx"
Which I though would work, but it saves it in teh directory up from the location.

I.e. the spreadsheet is in C:/User/Documents/MySpreadsheet.  But the Word doc would be saved in C:/User/Documents.

I also made a message popup to display ThisWorkbook.Path which comes up with the Spreadsheet path, so I know that's right!

I also don't think I've done the naming right, as I would like it to be named the text in cell C8.  But it's actually the 'Documents' folder name with the text in C8 added on.

Thanks in advance.

答:
Activate Immediate Window (Ctrl+G) and and add this line to your code: </p>

```<code>debug.print ThisWorkbook.Path & Range("C8").Text & ".docx"
</code>```

<p>You will see if your path is correct. In particular, if you have "\" between folder path and filename. </p>

Body:
Activate Immediate Window (Ctrl+G) and and add this line to your code:

debug.print ThisWorkbook.Path & Range("C8").Text & ".docx"

You will see if your path is correct. In particular, if you have "\" between folder path and filename.


问:
How can we secure our data from DBA?
I have very confidential data in my database. I am trying to secure my data from dba.

I am a member of development team. We develop our software and delpoy in a server which has its own dba. We have limited control over the server.

In this scenario how can i deny dba of the server to lookup my data and deny making changes to them.

Is it possible?

答: In Oracle, you can use database vault option.</p>

ContentLicense: CC BY-SA 2.5

Title: How can we secure our data from DBA?


问:
MySQL query for WP bundles products
I would like to extract the productnumbers and quantities from the following string:

```<code> {"25628":{"quantity":"1","tax_included":"yes","thumbnail":"yes","title":"product 1","desc":""},"25629":{"quantity":"1","tax_included":"yes","thumbnail":"yes","title":"Product 2","desc":""}}
</code>```

I would like to end up with (in this case 4 columns, but if more products are in the string more columns) with:

column_1_alias: product_1

value : 25628

column_2_alias: qty_pr_1
value: 1

column_3_alias: product_2

value : 25628

column_4_alias: qty_pr_2

value: 1

etc.

I tried with Substring but product title can differ so not all characters are always at the same position. Is there any way to split this string in usable data?

Any help would be very much appreciated..

Michel

答: Use json_decode - http://php.net/manual/en/function.json-decode.php - this will return the json to php readable format like object or array that you can easily manipulate. Please let me know if you need further information.</p>

Title: MySQL query for WP bundles products

Body:
I would like to extract the productnumbers and quantities from the following string:

 {"25628":{"quantity":"1","tax_included":"yes","thumbnail":"yes","title":"product 1","desc":""},"25629":{"quantity":"1","tax_included":"yes","thumbnail":"yes","title":"Product 2","desc":""}}

I would like to end up with (in this case 4 columns, but if more products are in the string more columns) with:

column_1_alias: product_1

value : 25628

column_2_alias: qty_pr_1
value: 1

column_3_alias: product_2

value : 25628

column_4_alias: qty_pr_2

value: 1

etc.

I tried with Substring but product title can differ so not all characters are always at the same position. Is there any way to split this string in usable data?

Any help would be very much appreciated..

Michel


问:
Determining Multiple of the Closest Pairs in Plane
When determining the closest pair of vertices in a plane with the sweep algorithm outlined below, is it possible to determine multiple pairs without additional runs?

Sort points according to their x-coordinates.

Split the set of points into two equal-sized subsets by a vertical line x=xmid.
Solve the problem recursively in the left and right subsets. This yields the left-side and right-side minimum distances dLmin and dRmin, respectively.

Find the minimal distance dLRmin among the set of pairs of points in which one point lies on the left of the dividing vertical and the other point lies to the right.

The final answer is the minimum among dLmin, dRmin, and dLRmin.

答:
It seems to me that when you are finding the minimum distance of a pair of points in a half, you can record the pair with minimum distance. If you find other pairs with the same distance, you could remember all of them by pushing them into some sort of collection. Do this for the left and right halves, and for the sliver you check in the middle, and you should be able to print out all the recorded elements of any list(s) corresponding to minimum distances. Something like:

```<code>AllPairsMinDist(points[1...n])
    sort points according to x coordinate
    return AllPairsMinDistInternal(points[1...n])

AllPairsMinDistInternal(points[1...n])
    if n = 1 then
        return (+infinity, [])
    else if n = 2 then
        d = distance(points[1], points[2])
        c = (points[1], points[2])
        return (d, c)
    else then
        (dL, cL) = AllPairsMinDistInternal(points[1...floor(n/2)])
        (dR, cR) = AllPairsMinDistInternal(points[floor(n/2)+1...n])
        (dM, cM) = PairsMinDistMiddle(points[1...n], dL, dR)
        dMin = min(dL, dR, dM)
        cMin = []
        if dL = dMin then cMin = cMin union cL
        if dR = dMin then cMin = cMin union cR
        if dM = dMin then cMin = cMin union cM
        return (dMin, cMin)

AllPairsMinDistMiddle(points[1...n], dL, dR)
    if n = 1 then
        return (+infinity, [])
    else if n = 2 then
        d = distance(points[1], points[2])
        c = (points[1], points[2])
        return (d, c)
    else then
        xV = (points[floor(n/2)].x + points[floor(n/2)+1].x) / 2

        minD = min(dL, dR)
        minC = []

        ll = binary search for index of point with smallest
             x coordinate satisfying xV - x <= minD

        rr = binary search for index of point with largest
             x coordinate satisfying x - xV <= minD

        for i = ll to floor(n/2) do
            for j = floor(n/2) + 1 to rr do
                d = distance(points[i], points[j])
                if d = minD then
                    minC = minC union [(points[i], points[j])]
                else if d < minD then
                    minD = d
                    minC = [(points[i], points[j])]

        alternative to for loop:
            (dMin, cMin) = AllPairsMinDistInternal(points[ll...rr])

        return (dMin, cMin)
</code>```

There are probably some issues with the above - I just sort of typed it out ad-hoc and without really understanding the algorithm that's being used - but from your high-level description this sounds doable.

Body:
It seems to me that when you are finding the minimum distance of a pair of points in a half, you can record the pair with minimum distance. If you find other pairs with the same distance, you could remember all of them by pushing them into some sort of collection. Do this for the left and right halves, and for the sliver you check in the middle, and you should be able to print out all the recorded elements of any list(s) corresponding to minimum distances. Something like:

AllPairsMinDist(points[1...n])
    sort points according to x coordinate
    return AllPairsMinDistInternal(points[1...n])

AllPairsMinDistInternal(points[1...n])
    if n = 1 then
        return (+infinity, [])
    else if n = 2 then
        d = distance(points[1], points[2])
        c = (points[1], points[2])
        return (d, c)
    else then
        (dL, cL) = AllPairsMinDistInternal(points[1...floor(n/2)])
        (dR, cR) = AllPairsMinDistInternal(points[floor(n/2)+1...n])
        (dM, cM) = PairsMinDistMiddle(points[1...n], dL, dR)
        dMin = min(dL, dR, dM)
        cMin = []
        if dL = dMin then cMin = cMin union cL
        if dR = dMin then cMin = cMin union cR
        if dM = dMin then cMin = cMin union cM
        return (dMin, cMin)

AllPairsMinDistMiddle(points[1...n], dL, dR)
    if n = 1 then
        return (+infinity, [])
    else if n = 2 then
        d = distance(points[1], points[2])
        c = (points[1], points[2])
        return (d, c)
    else then
        xV = (points[floor(n/2)].x + points[floor(n/2)+1].x) / 2

        minD = min(dL, dR)
        minC = []

        ll = binary search for index of point with smallest
             x coordinate satisfying xV - x <= minD

        rr = binary search for index of point with largest
             x coordinate satisfying x - xV <= minD

        for i = ll to floor(n/2) do
            for j = floor(n/2) + 1 to rr do
                d = distance(points[i], points[j])
                if d = minD then
                    minC = minC union [(points[i], points[j])]
                else if d < minD then
                    minD = d
                    minC = [(points[i], points[j])]

        alternative to for loop:
            (dMin, cMin) = AllPairsMinDistInternal(points[ll...rr])

        return (dMin, cMin)

There are probably some issues with the above - I just sort of typed it out ad-hoc and without really understanding the algorithm that's being used - but from your high-level description this sounds doable.


问:
replace values in pandas based on other two column
I have problem with replacement values in a column conditional other two columns.

For example we have three columns. A, B, and C
Columns A and B are both booleans, containing True and False, and column C contains three values: "Payroll", "Social", and "Other".

When in columns A and B are True in column C we have value "Payroll".
I want to change values in column C where both column A and B are True.

I tried following code: but gives me this error "'NoneType' object has no attribute 'where'":

```<code>data1.replace({'C' : { 'Payroll', 'Social'}},inplace=True).where((data1['A'] == True) & (data1['B'] == True))
</code>```

but gives me this error "'NoneType' object has no attribute 'where'":

What can be done to this problem?

答:
Well you can use apply function to do this

```<code>def change_value(dataframe):
   for index, row in df.iterrows():
      if row['A'] == row['B'] == True:
           row['C'] = # Change to whatever value you want
      else:
           row ['C'] = # Change how ever you want
</code>```

Body:
I have problem with replacement values in a column conditional other two columns.

For example we have three columns. A, B, and C
Columns A and B are both booleans, containing True and False, and column C contains three values: "Payroll", "Social", and "Other".

When in columns A and B are True in column C we have value "Payroll".
I want to change values in column C where both column A and B are True.

I tried following code: but gives me this error "'NoneType' object has no attribute 'where'":

data1.replace({'C' : { 'Payroll', 'Social'}},inplace=True).where((data1['A'] == True) & (data1['B'] == True))

but gives me this error "'NoneType' object has no attribute 'where'":

What can be done to this problem?

Body:
Well you can use apply function to do this

def change_value(dataframe):
   for index, row in df.iterrows():
      if row['A'] == row['B'] == True:
           row['C'] = # Change to whatever value you want
      else:
           row ['C'] = # Change how ever you want


问:
Pass @EventListener to Component via Vuejs Router
Before I used vuejs-router, I've loaded component in app this way:

```<code><my-component @done="doneForm"
              @cancel="cancelForm"></my-component>
</code>```

Well, I want to use vuejs-router to load my-component. So, how can I pass @done and @cancel to my-component via vuejs-router?

答:
You need to define a route to which your my-component will be instantiated. This component will contain the done and cancel callbacks, so:

```<code>var router = new VueRouter({
  routes: [
    { path: '/someRoute', component: SomeComponent }
  ]
]
</code>```

SomeComponent would be something like:

```<code><template>
    <my-component @done="doneForm" @cancel="cancelForm"></my-component>
</template>
<script>
    import MyComponent from '/some/path/components/MyComponent'

    export default {
        components: {
            myComponent: MyComponent
        },
        methods: {
            doneForm () {
                console.log('Form Done')
            },
            cancelForm () {
                console.log('Cancel Form')
            }
        }
    }
</script>
</code>```

As you've not shown any code and how you're calling your <my-component> but the whole point is that the <my-component> needs to be instantiated somewhere within another component that can have hold the cancelForm and doneForm methods. If you didn't want these callbacks then you could set a route up to go straight to that component.

Another option is to make thing stateful using Vuex. You could remove the callbacks from the component and when the form is done within <my-component> set something in the state that you can react to somewhere else in your app. You could also do the same with events and raise an event to listen for and do something.

Body:
Before I used vuejs-router, I've loaded component in app this way:

<my-component @done="doneForm"
              @cancel="cancelForm"></my-component>

Well, I want to use vuejs-router to load my-component. So, how can I pass @done and @cancel to my-component via vuejs-router?

Body:
You need to define a route to which your my-component will be instantiated. This component will contain the done and cancel callbacks, so:

var router = new VueRouter({
  routes: [
    { path: '/someRoute', component: SomeComponent }
  ]
]

SomeComponent would be something like:

<template>
    <my-component @done="doneForm" @cancel="cancelForm"></my-component>
</template>
<script>
    import MyComponent from '/some/path/components/MyComponent'

    export default {
        components: {
            myComponent: MyComponent
        },
        methods: {
            doneForm () {
                console.log('Form Done')
            },
            cancelForm () {
                console.log('Cancel Form')
            }
        }
    }
</script>

As you've not shown any code and how you're calling your <my-component> but the whole point is that the <my-component> needs to be instantiated somewhere within another component that can have hold the cancelForm and doneForm methods. If you didn't want these callbacks then you could set a route up to go straight to that component.

Another option is to make thing stateful using Vuex. You could remove the callbacks from the component and when the form is done within <my-component> set something in the state that you can react to somewhere else in your app. You could also do the same with events and raise an event to listen for and do something.


问:
In-solution references not working with .NET Standard 2.0
I am currently porting a project from .NET Framework 4.6.2 to .NET Standard 2.0 but it appears that in-solution references (e.g. referencing a .NET Standard 2.0 library from a .NET Framework 4.6.2 Unit Tests project) is broken. Downgrading the library to .NET Standard 1.X fixes it but it is not a solution as .NET Standard 2.0 becomes unusable. I obtained similar results when referencing a .NET Standard 2.0 library from a .NET Core 2.0 project.

If we leave the solution and reference the same .NET Standard 2.0 project from an external project it works flawlessly, and to be sure I also tested referencing a .NET Framework library from a .NET Framework Unit Tests project and it works just as well.

If it can be useful, I am using the latest Visual Studio 15.3.3.

答:
I had the same behavior two weeks ago. If you have ReSharper, I'm almost certain that you don't have the latest version. My suggestion is, instead of disabling ReSharper, you go and update it. It worked pretty well for me.

In case you wanted to know what is new in this version, you can click here.


问:
java subclass or field, good semantics
Please help me to decide which approach is reasonable in the following case. Object:

```<code>public class FunctionCall {
  private String functionName;
  private List<Exp> args;
  ...
}
</code>```

In one very particular case/check the object need to be identified somehow.
Possible approaches:

FunctionCall class becomes an attribute, but there is a doubt that this would pollute overall semantics, as the attribute should not be visible "globally".

SpecialFunctionCall inherits the FunctionCall and with instanceof can be identified in the very special case. This would be ideal, the only doubt that it would misuse purpose of inheritance?

Any other suggestions are very welcome.

Thanks in advance.

答:
What you actually need is to use two of the main three principles of Java,polymorphism and 'inheritance' combined together. Polymorphism is one of the OOPs feature that allows us to perform a single action in different ways. This means that the behavior of an object could be changed depending on particular circumstances or cases.

In your case you could create two classes, a FunctionCall and a SpecialFunctionCall. Latter should extends the first one with its one spexial behavior.

Then when your special case comes up you would use the second class which would have a different behavior than the first.

By this way you guarantee that there is a per-case functionality of the parent class FunctionCall.

See below an example of use:

```<code>public class SpecialFunctionCall extends FunctionCall{
  //your special logic goes here
  ...
}
</code>```

Title: java subclass or field, good semantics

Body:
Please help me to decide which approach is reasonable in the following case. Object:

public class FunctionCall {
  private String functionName;
  private List<Exp> args;
  ...
}

In one very particular case/check the object need to be identified somehow.
Possible approaches:

FunctionCall class becomes an attribute, but there is a doubt that this would pollute overall semantics, as the attribute should not be visible "globally".

SpecialFunctionCall inherits the FunctionCall and with instanceof can be identified in the very special case. This would be ideal, the only doubt that it would misuse purpose of inheritance?

Any other suggestions are very welcome.

Thanks in advance.

Body:
What you actually need is to use two of the main three principles of Java,polymorphism and 'inheritance' combined together. Polymorphism is one of the OOPs feature that allows us to perform a single action in different ways. This means that the behavior of an object could be changed depending on particular circumstances or cases.

In your case you could create two classes, a FunctionCall and a SpecialFunctionCall. Latter should extends the first one with its one spexial behavior.

Then when your special case comes up you would use the second class which would have a different behavior than the first.

By this way you guarantee that there is a per-case functionality of the parent class FunctionCall.

See below an example of use:

public class SpecialFunctionCall extends FunctionCall{
  //your special logic goes here
  ...
}


问:
How to make a class automatically prompt itself when setting a value
I guess the best way to explain this is with an example:

When setting to DockStyle of a Control, VS automatically prompts DockStyle,
so basically my class has a private constructor and predefined 'styles' as static instances of itself and I want that class to act like DockStyle, other examples that come to mind are AutoSizeModeor Cursors.

Here's the class in question;

```<code>public class FormDesign
{
    public static FormDesign Dark = new FormDesign(0)
    {
        // Set Values
    };

    public static FormDesign Grey = new FormDesign(1)
    {
        // Set Values
    };

    public static FormDesign Light = new FormDesign(2)
    {
        // Set Values
    };

    private FormDesign(int i) { ID = i; }

    public FormDesign Switch()
    {
        if(this == Dark) return Grey;
        if (this == Grey) return Light;
        if (this == Light) return Dark;
        return Grey;
    }

    public int ID { get; private set; }
    public Color BackColor { get; private set; }
    public Color TitleColor { get; private set; }
    public Color TitleForeColor { get; private set; }
    public Color ForeColor { get; private set; }
    public Color LightColor { get; private set; }
    public Color DarkColor { get; private set; }
    public Color MenuColor { get; private set; }
    public Color LabelColor { get; private set; }
    public Color InfoColor { get; private set; }
    public Color ActiveColor { get; private set; }
}
</code>```

答:
In order proper a property to give the implementor a list  of options use an enum.

```<code>Public Enum Theme
{
  Dark,
  Gray,
  Light
}

Public Theme ActiveTheme { get; set; }
</code>```

The default value will be the first item in the Enum.

There is the option of using enum classes however this is more complicated. See https://lostechies.com/jimmybogard/2008/08/12/enumeration-classes/ for details

Body:
I guess the best way to explain this is with an example:

When setting to DockStyle of a Control, VS automatically prompts DockStyle,
so basically my class has a private constructor and predefined 'styles' as static instances of itself and I want that class to act like DockStyle, other examples that come to mind are AutoSizeModeor Cursors.

Here's the class in question;

public class FormDesign
{
    public static FormDesign Dark = new FormDesign(0)
    {
        // Set Values
    };

    public static FormDesign Grey = new FormDesign(1)
    {
        // Set Values
    };

    public static FormDesign Light = new FormDesign(2)
    {
        // Set Values
    };

    private FormDesign(int i) { ID = i; }

    public FormDesign Switch()
    {
        if(this == Dark) return Grey;
        if (this == Grey) return Light;
        if (this == Light) return Dark;
        return Grey;
    }

    public int ID { get; private set; }
    public Color BackColor { get; private set; }
    public Color TitleColor { get; private set; }
    public Color TitleForeColor { get; private set; }
    public Color ForeColor { get; private set; }
    public Color LightColor { get; private set; }
    public Color DarkColor { get; private set; }
    public Color MenuColor { get; private set; }
    public Color LabelColor { get; private set; }
    public Color InfoColor { get; private set; }
    public Color ActiveColor { get; private set; }
}

Body:
In order proper a property to give the implementor a list  of options use an enum.

Public Enum Theme
{
  Dark,
  Gray,
  Light
}

Public Theme ActiveTheme { get; set; }

The default value will be the first item in the Enum.

There is the option of using enum classes however this is more complicated. See https://lostechies.com/jimmybogard/2008/08/12/enumeration-classes/ for details


问:
How to merge thousands of json documents in Bash?
I created more than 500 000 JSON documents through a script connecting to some API. I wanted to import these documents into RethinkDB, but it seems that RethinkDB cannot import files massively, so I thought about merging all these files into a big JSON file (say bigfile.json). Here is their structure :

file 1.json:

```<code>{
  "key_1": "value_1.1",
  "key_2": "value_1.2",
  "key_3": "value_1.3",
    ...
  "key_n": "value_1.n"
}
</code>```

file 2.json:

```<code>{
  "key_1": "value_2.1",
  "key_2": "value_2.2",
  "key_3": "value_2.3",
    ...
  "key_n": "value_2.n"
}
...
</code>```

file n.json:

```<code>{
  "key_1": "value_n.1",
  "key_2": "value_n.2",
  "key_3": "value_n.3",
    ...
  "key_n": "value_n.n"
}
</code>```

I was wondering which would be the best structure to create a big JSON file (to be complete, each file has a specific name composed by 3 variables, the first one being a timestamp (YYYYMMDDHHMMSS)), and which command or script (until now I only wrote scripts for bash...) would allow me to produce the merging.

答:
If you ever need to read a bunch of JSON files into memory as a single object with the filenames as keys and the contents as the corresponding values, consider using jq:</p>

```<code>jq -n '[inputs|{(input_filename):.}]|add' FILE...
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I created more than 500 000 JSON documents through a script connecting to some API. I wanted to import these documents into RethinkDB, but it seems that RethinkDB cannot import files massively, so I thought about merging all these files into a big JSON file (say bigfile.json). Here is their structure :

file 1.json:

{
  "key_1": "value_1.1",
  "key_2": "value_1.2",
  "key_3": "value_1.3",
    ...
  "key_n": "value_1.n"
}

file 2.json:

{
  "key_1": "value_2.1",
  "key_2": "value_2.2",
  "key_3": "value_2.3",
    ...
  "key_n": "value_2.n"
}
...

file n.json:

{
  "key_1": "value_n.1",
  "key_2": "value_n.2",
  "key_3": "value_n.3",
    ...
  "key_n": "value_n.n"
}

I was wondering which would be the best structure to create a big JSON file (to be complete, each file has a specific name composed by 3 variables, the first one being a timestamp (YYYYMMDDHHMMSS)), and which command or script (until now I only wrote scripts for bash...) would allow me to produce the merging.

Body:
If you ever need to read a bunch of JSON files into memory as a single object with the filenames as keys and the contents as the corresponding values, consider using jq:

jq -n '[inputs|{(input_filename):.}]|add' FILE...


问:
Submitting AJAX request using Vanilla JS
Here is my current code, I want to push an object (recipe) into an array at the server side, but I haven't even gotten that far yet. Right now I'm just trying to console.log(recipe) on server and getting undefined.

HTML:

```<code><button type='button' class='btn btn-warning add-recipe'><i class="fa fa-book" aria-hidden="true" onclick='addRecipe(<%= JSON.stringify(recipe.author.id) %>)'></i></button>
</code>```

JavaScript (client):

```<code>function addRecipe(recipe){
   var xml = new XMLHttpRequest();
   var recipe = recipe;
   xml.open("POST", "/add-recipe", true);
   xml.send({recipe: recipe});
}
</code>```

JavaScript (server):

```<code>router.post('/add-recipe', function(req, res) {
   var recipe = req.body.recipe;
   console.log(recipe);
})
</code>```

答:
Some changes are required in both frontend and back-end
Front-end changes

```<code>function addRecipe(recipe){
   var xml = new XMLHttpRequest();
   var recipe = recipe;
   xml.open("POST", "/add-recipe", true);
   xml.setRequestHeader("Content-type", "application/json; charset=utf-8");
   xml.send(JSON.stringify({recipe: recipe}));
}
</code>```

For the backend to consume json in express you will have to use the body parser

```<code>var bodyParser = require('body-parser');
// I am assuming router the name of your express app
router.use(bodyParser.json());

router.post('/add-recipe', function(req, res) {
   var recipe = req.body.recipe;
   console.log(recipe);
})
</code>```

Body:
Here is my current code, I want to push an object (recipe) into an array at the server side, but I haven't even gotten that far yet. Right now I'm just trying to console.log(recipe) on server and getting undefined.

HTML:

<button type='button' class='btn btn-warning add-recipe'><i class="fa fa-book" aria-hidden="true" onclick='addRecipe(<%= JSON.stringify(recipe.author.id) %>)'></button>

JavaScript (client):

function addRecipe(recipe){
   var xml = new XMLHttpRequest();
   var recipe = recipe;
   xml.open("POST", "/add-recipe", true);
   xml.send({recipe: recipe});
}

JavaScript (server):

router.post('/add-recipe', function(req, res) {
   var recipe = req.body.recipe;
   console.log(recipe);
})

Body:
Some changes are required in both frontend and back-end
Front-end changes

function addRecipe(recipe){
   var xml = new XMLHttpRequest();
   var recipe = recipe;
   xml.open("POST", "/add-recipe", true);
   xml.setRequestHeader("Content-type", "application/json; charset=utf-8");
   xml.send(JSON.stringify({recipe: recipe}));
}

For the backend to consume json in express you will have to use the body parser

var bodyParser = require('body-parser');
// I am assuming router the name of your express app
router.use(bodyParser.json());

router.post('/add-recipe', function(req, res) {
   var recipe = req.body.recipe;
   console.log(recipe);
})


问:
How do I generate a png file w/ selenium/phantomjs from a string?
I am using selenium/phantomjs to create png files of html in python. Is there a way to generate the png from an html string or filehandle (instead of a website)? I've searched through the selenium docs and googled but couldn't find an answer. I have:</p>

```<code>htmlString = '<html><body><div style="background-color:red;height:500px;width:500px;">This is a png</div></body></html>'
myFile = 'tmp.html'
f = open(myFile,'w')
f.write(htmlString)

from selenium import webdriver

driver = webdriver.PhantomJS()
driver.set_window_size(1024, 768)
#driver.get('https://google.com/') # this works fine
driver.get(myFile) # passing the file name or htmlString doesn't work...creates a blank png with nothing
driver.save_screenshot('screen.png')
driver.quit()

print "png file created"
</code>```

答:
It seems the lines

```<code>f = open(myFile,'w')
f.write(htmlString)
</code>```

Are problematic, as the generated file is empty.

I fixed this issue with

```<code>with open(myFile,'wt') as f:
    f.write(htmlString)
</code>```

or you might have to add a

```<code>f.close() to your code
</code>```

Body:
I am using selenium/phantomjs to create png files of html in python. Is there a way to generate the png from an html string or filehandle (instead of a website)? I've searched through the selenium docs and googled but couldn't find an answer. I have:

htmlString = '
This is a png
'
myFile = 'tmp.html'
f = open(myFile,'w')
f.write(htmlString)

from selenium import webdriver

driver = webdriver.PhantomJS()
driver.set_window_size(1024, 768)
#driver.get('https://google.com/') # this works fine
driver.get(myFile) # passing the file name or htmlString doesn't work...creates a blank png with nothing
driver.save_screenshot('screen.png')
driver.quit()

print "png file created"

Body:
It seems the lines

f = open(myFile,'w')
f.write(htmlString)

Are problematic, as the generated file is empty.

I fixed this issue with

with open(myFile,'wt') as f:
    f.write(htmlString)

or you might have to add a

f.close() to your code


问:
Publish to facebook stream in PHP
I've been trying to accomplish stream publishing with this JS method:

```<code>function streamPublish(name, description, hrefTitle, hrefLink, userPrompt){
    FB.ui(
    {
        method: 'stream.publish',
        message: '',
        attachment: {
            name: name,
            caption: '',
            description: (description),
            href: hrefLink
        },
        action_links: [
            { text: hrefTitle, href: hrefLink }
        ],
        user_prompt_message: userPrompt
    },
    function(response) {

    });
}
</code>```

but it never works on Internet Explorer. How can I achieve this same result (or whatever result would be considered "standard" for a facebook application posting to a user's stream) in PHP? The facebook API documentation is poor and doesn't include many code examples.

答:
Use the api function from the Facebook PHP SDK like this:

```<code>$facebook->api('/$USER_ID/feed', 'POST', $attachment);
</code>```

Where $attachment is an object built this way:

```<code>$attachment = array(
'message' => MESSAGE,
            'name' => TITLE,
            'link' => URL,
            'description' => DESC,
'picture'=> IMAGE,
    );
</code>```

You can check other kind of params to pass with the attachment on the facebook developers website

Title: Publish to facebook stream in PHP

Body:
I've been trying to accomplish stream publishing with this JS method:

function streamPublish(name, description, hrefTitle, hrefLink, userPrompt){
    FB.ui(
    {
        method: 'stream.publish',
        message: '',
        attachment: {
            name: name,
            caption: '',
            description: (description),
            href: hrefLink
        },
        action_links: [
            { text: hrefTitle, href: hrefLink }
        ],
        user_prompt_message: userPrompt
    },
    function(response) {

    });
}

but it never works on Internet Explorer. How can I achieve this same result (or whatever result would be considered "standard" for a facebook application posting to a user's stream) in PHP? The facebook API documentation is poor and doesn't include many code examples.

Body:
Use the api function from the Facebook PHP SDK like this:

$facebook->api('/$USER_ID/feed', 'POST', $attachment);

Where $attachment is an object built this way:

$attachment = array(
'message' => MESSAGE,
            'name' => TITLE,
            'link' => URL,
            'description' => DESC,
'picture'=> IMAGE,
    );

You can check other kind of params to pass with the attachment on the facebook developers website


问:
When do I need to do "git pull", before or after "git add, git commit"?
What is the right way?

```<code>git add foo.js
git commit foo.js -m "commit"
git pull
git push
</code>```

Or

```<code>git pull
git add foo.js
git commit foo.js -m "commit"
git push
</code>```

Or

```<code>git add foo.js
git pull
git commit foo.js -m "commit"
git push
</code>```

UPD:

I forgot to mention that in this case I use git add to stage a tracked and modified file. Not to include a brand new file to repository. Does this changes an order of commands?

答:
I think git pull --rebase is the cleanest way to set your local recent commits on top of the remote commits which you don't have at a certain point.

So this way you don't have to pull every time you want to start making changes.

Body:
What is the right way?

git add foo.js
git commit foo.js -m "commit"
git pull
git push

Or

git pull
git add foo.js
git commit foo.js -m "commit"
git push

Or

git add foo.js
git pull
git commit foo.js -m "commit"
git push

UPD:

I forgot to mention that in this case I use git add to stage a tracked and modified file. Not to include a brand new file to repository. Does this changes an order of commands?


问:
OneNote "My Add-ins" is disabled
I'm trying to add a new Office.js based Add-in to OneNote 2016. Unfortunately the "My Add-ins" button is grayed out:

I have confirmed that all the different options inside the Trust Center are configured correctly and "My Add-ins" is working property in both Word and Excel.

Anyone have an idea what may be the problem?

答:
Currently only the OneNote Online supports Office.js Add-ins. From the documentation:

OneNote introduces a JavaScript API for OneNote Online add-ins. You can create task pane add-ins, content add-ins, and add-in commands that interact with OneNote objects and connect to web services or other web-based resources.

You can see support by app and platform at Office Add-in Availability.

If you would like to see OneNote add-ins supported on more platforms, I strongly suggest adding this to the Office UserVoice.

Title: OneNote "My Add-ins" is disabled


问:
Finding elements by class in Selenium
Okay, so I'm trying to find the 179 in:

```<code><span class="totalcount">179</span>
</code>```

However, for some reason:

```<code>maxpage = driver.find_element_by_class_name('totalcount')
</code>```

results in maxpage being set equal to:

```<code><selenium.webdriver.firefox.webelement.FirefoxWebElement (session="2c241847-ac56-4ed5-bb0e-73b473833ce4", element="9f837b6e-e78f-4fca-87b8-4efcb463e5a3")>
</code>```

But I want to get value equal to 179. Do you have any advice?

答: You can also use maxpage.get_attribute("value").

Title: Finding elements by class in Selenium

Body:
Okay, so I'm trying to find the 179 in:

179

However, for some reason:

maxpage = driver.find_element_by_class_name('totalcount')

results in maxpage being set equal to:

<selenium.webdriver.firefox.webelement.FirefoxWebElement (session="2c241847-ac56-4ed5-bb0e-73b473833ce4", element="9f837b6e-e78f-4fca-87b8-4efcb463e5a3")>

But I want to get value equal to 179. Do you have any advice?


问:
How do you compare user input to values inside an array?
I am wanting to create a very simple script that checks user's input to a pre-existing array. However, it doesn't seem to work and I'm not sure why. Please, keep in mind I'm new to this and trying to learn.</p>

```<code><script>
    var usernumber = prompt('What is your number?');
    var numbers = ['1', '2', '3'];
    if (usernumber == 'numbers') //If the user number matches one of preset numbers
    {
        alert('Match');
    } else {
        alert('No match found.');
    }
</script>
</code>```

答:
You can use Array.indexOf prototype function here:

```<code>if(numbers.indexOf(usernumber) >= 0){
    alert('Match');
}
</code>```

Reference: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

Body:
You can use Array.indexOf prototype function here:

if(numbers.indexOf(usernumber) >= 0){
    alert('Match');
}

Reference: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf


问:
How to use generic in Scala from circe?
I want to use automatic generic marshaller to Json from circle:

```<code>def printTest[T<: Product](resourse: ResourcePartTest[T]): Unit = {
    import io.circe.generic.auto._
    import io.circe.syntax._

    println(resourse.asJson)
  }
</code>```

But I can Exeption:

```<code>Error:(29, 22) could not find implicit value for parameter encoder: io.circe.Encoder[com.moex.regulatory.standards.intermediate.v23.ResourcePartTest[T]]
    println(resourse.asJson)

Error:(29, 22) not enough arguments for method asJson: (implicit encoder: io.circe.Encoder[com.moex.regulatory.standards.intermediate.v23.ResourcePartTest[T]])io.circe.Json.
Unspecified value parameter encoder.
    println(resourse.asJson)
</code>```

Can I use automatic marshaller for Generic?

答:
I'm not sure how ResourceParTest is defined, but this should work by moving the generic derivation import outside the method and requiring an Encoder[ResourcePartTest[T]] as evidence:

```<code>import io.circe.Encoder
import io.circe.generic.auto._
import io.circe.syntax._

sealed trait ResourcePartTest[T]
case class Foo() extends ResourcePartTest[(Int, Int)]

def printTest[T <: Product](resourse:
                            ResourcePartTest[T])(implicit ev: Encoder[ResourcePartTest[T]]): Unit = {
  println(resourse.asJson)
}
</code>```

Title: How to use generic in Scala from circe?

Body:
I want to use automatic generic marshaller to Json from circle:

def printTest[T<: Product](resourse: ResourcePartTest[T]): Unit = {
    import io.circe.generic.auto._
    import io.circe.syntax._

    println(resourse.asJson)
  }

But I can Exeption:

Error:(29, 22) could not find implicit value for parameter encoder: io.circe.Encoder[com.moex.regulatory.standards.intermediate.v23.ResourcePartTest[T]]
    println(resourse.asJson)

Error:(29, 22) not enough arguments for method asJson: (implicit encoder: io.circe.Encoder[com.moex.regulatory.standards.intermediate.v23.ResourcePartTest[T]])io.circe.Json.
Unspecified value parameter encoder.
    println(resourse.asJson)

Can I use automatic marshaller for Generic?

Body:
I'm not sure how ResourceParTest is defined, but this should work by moving the generic derivation import outside the method and requiring an Encoder[ResourcePartTest[T]] as evidence:

import io.circe.Encoder
import io.circe.generic.auto._
import io.circe.syntax._

sealed trait ResourcePartTest[T]
case class Foo() extends ResourcePartTest[(Int, Int)]

def printTest[T <: Product](resourse:
                            ResourcePartTest[T])(implicit ev: Encoder[ResourcePartTest[T]]): Unit = {
  println(resourse.asJson)
}


问:
WebRTC vs Websockets: If WebRTC can do Video, Audio, and Data, why do I need Websockets?
So I'm looking to build a chat app that will allow video, audio, and text. I spent some time researching into Websockets and WebRTC to decide which to use. Since there are plenty of video and audio apps with WebRTC, this sounds like a reasonable choice, but are there other things I should consider?
Feel free to share your thoughts.

Things like:

Due to being new WebRTC is available only on some browsers, while WebSockets seems to be in more browsers.

Scalability - Websockets uses a server for session and WebRTC seems to be p2p.

Multiplexing/multiple chatrooms - Used in Google+ Hangouts, and I'm still viewing demo apps on how to implement.

Server - Websockets needs RedisSessionStore or RabbitMQ to scale across multiple machines.

答:
Webrtc is a part of peer to peer connection.
We all know that before creating peer to peer connection, it requires handshaking process to establish peer to peer connection.
And websockets play the role of handshaking process.</p>


问:
CSS resize images to fit in div and be reponsive
I am using bootstrap3 on a site that allows users to upload images of their own. These images are later displayed in a given page. Problem is, some users upload photos that are either bigger or smaller in respect to the div that'll hold them. I wish to resize all these images using CSS (or even JavaScript if need be) in order for them to fit in the div whilst maintaining their aspect ratio. At the same time, I want them to be responsive.</p>

答:
Try this: https://jsfiddle.net/murkle/10jd0khz/1/</p>

```<code>function openImageInLightBox(imageBase64) {

div = document.createElement("div");
div.id = "myLightboxDiv";
div.style.width = "80%";
div.style.height = "80%";
div.style.position = "fixed";
div.style.top = "10%";
div.style.left= "10%";
div.style.border = "7px solid rgba(0, 0, 0, 0.5)";
div.style.background = "#000";
div.style["background-image"] = "url('" + imageBase64 + "')";
div.style["background-size"] = "contain";
div.style["background-repeat"] = "no-repeat";
div.style["background-position"] = "center";
div.onclick = function() {document.body.removeChild(div);};

document.body.appendChild(div);

// now add transparent image over it
// so that "Save image as..." works
// remove this if you don't need it
var elem = document.createElement("img");
elem.src = imageBase64;
elem.style.height = "100%";
elem.style.width = "100%";
elem.style.opacity = 0;
div.appendChild(elem);

}
</code>```

Body:
Try this: https://jsfiddle.net/murkle/10jd0khz/1/

function openImageInLightBox(imageBase64) {

div = document.createElement("div");
div.id = "myLightboxDiv";
div.style.width = "80%";
div.style.height = "80%";
div.style.position = "fixed";
div.style.top = "10%";
div.style.left= "10%";
div.style.border = "7px solid rgba(0, 0, 0, 0.5)";
div.style.background = "#000";
div.style["background-image"] = "url('" + imageBase64 + "')";
div.style["background-size"] = "contain";
div.style["background-repeat"] = "no-repeat";
div.style["background-position"] = "center";
div.onclick = function() {document.body.removeChild(div);};

document.body.appendChild(div);

// now add transparent image over it
// so that "Save image as..." works
// remove this if you don't need it
var elem = document.createElement("img");
elem.src = imageBase64;
elem.style.height = "100%";
elem.style.width = "100%";
elem.style.opacity = 0;
div.appendChild(elem);

}


问:
How to put an image in the center of navigationBar of a UIViewController?
I have this snippet of code used in viewDidLoad of a UIViewController. I'va no errors. Images exists. I get the background but not the image. Image is a sort of logo.</p>

```<code>if ([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)] ) {

    /* Background of navigationBar. */
    UIImage * navigationBarImage = [UIImage imageNamed:@"01_navbar_portrait.png"];
    [self.navigationController.navigationBar setBackgroundImage:navigationBarImage forBarMetrics:UIBarMetricsDefault];

    /* Image in navigationBar */
    UIImage * logoInNavigationBar = [UIImage imageNamed:@"01_logo.png"];
    UIImageView * logoView = [[UIImageView alloc] init];
    [logoView setImage:logoInNavigationBar];
    self.navigationController.navigationItem.titleView = logoView;

}
</code>```

答:
```<code>extension UINavigationController {
func addLogoImage(image: UIImage, navItem: UINavigationItem) {
    let imageView = UIImageView(image: image)
    imageView.contentMode = .scaleAspectFit
    imageView.translatesAutoresizingMaskIntoConstraints = false

    let view = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 44))
    view.addSubview(imageView)

    navItem.titleView = view
    imageView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
    imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    imageView.heightAnchor.constraint(equalTo: view.heightAnchor).isActive = true
    imageView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true

    view.heightAnchor.constraint(equalTo: navigationBar.heightAnchor).isActive = true
    view.centerXAnchor.constraint(equalTo: navigationBar.centerXAnchor).isActive = true
    view.centerYAnchor.constraint(equalTo: navigationBar.centerYAnchor).isActive = true
}
}
</code>```

Here's what I'm using.

Of course, you might need a bit more constraints, so as to not clash with the right and left bar button items.

Body:
I have this snippet of code used in viewDidLoad of a UIViewController. I'va no errors. Images exists. I get the background but not the image. Image is a sort of logo.

if ([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)] ) {

    /* Background of navigationBar. */
    UIImage * navigationBarImage = [UIImage imageNamed:@"01_navbar_portrait.png"];
    [self.navigationController.navigationBar setBackgroundImage:navigationBarImage forBarMetrics:UIBarMetricsDefault];

    /* Image in navigationBar */
    UIImage * logoInNavigationBar = [UIImage imageNamed:@"01_logo.png"];
    UIImageView * logoView = [[UIImageView alloc] init];
    [logoView setImage:logoInNavigationBar];
    self.navigationController.navigationItem.titleView = logoView;

}

Body:
extension UINavigationController {
func addLogoImage(image: UIImage, navItem: UINavigationItem) {
    let imageView = UIImageView(image: image)
    imageView.contentMode = .scaleAspectFit
    imageView.translatesAutoresizingMaskIntoConstraints = false

    let view = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 44))
    view.addSubview(imageView)

    navItem.titleView = view
    imageView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
    imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    imageView.heightAnchor.constraint(equalTo: view.heightAnchor).isActive = true
    imageView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true

    view.heightAnchor.constraint(equalTo: navigationBar.heightAnchor).isActive = true
    view.centerXAnchor.constraint(equalTo: navigationBar.centerXAnchor).isActive = true
    view.centerYAnchor.constraint(equalTo: navigationBar.centerYAnchor).isActive = true
}
}

Here's what I'm using.

Of course, you might need a bit more constraints, so as to not clash with the right and left bar button items.


问:
Convert QString date (RFC 822 format) to another QString format based on culture
I've a database with multiple strings, I get this records from query, and i receive this format data in QString:

"Mon, 13 Nov 2017 09:48:45 +0000"

So, I need to convert this based on culture, for example if I want convert in italian culture?

So the result will be:

"Lun, 13 Nov 2017 09:48:45"

Exist in qt this type of conversion or I have to proceed manually ?

Thanks to all

答:
Qt provides the QLocale class to handle language/country specifics. It has overloads of QLocale::toString() that accept QDateTime.

It also has a function QLocale::toDateTime() to do the reverse operation. But in your case the non local aware QDateTime::fromString() should work.

Int the end you should have something like this (+ or - some parameters for the exact format you want).

```<code>QString source = "Mon, 13 Nov 2017 09:48:45 +0000";
QDateTime dt  = QDateTime::fromString(source, Qt::RFC2822Date);
QString result = QLocale().toString(dt, Qt::RFC2822Date);
</code>```

Note that QLocale() constructs an instance based on the current user setting in the underlying OS. You can also force a specific language/country, for instance: QLocale(QLocale::Italian).

Body:
Qt provides the QLocale class to handle language/country specifics. It has overloads of QLocale::toString() that accept QDateTime.

It also has a function QLocale::toDateTime() to do the reverse operation. But in your case the non local aware QDateTime::fromString() should work.

Int the end you should have something like this (+ or - some parameters for the exact format you want).

QString source = "Mon, 13 Nov 2017 09:48:45 +0000";
QDateTime dt  = QDateTime::fromString(source, Qt::RFC2822Date);
QString result = QLocale().toString(dt, Qt::RFC2822Date);

Note that QLocale() constructs an instance based on the current user setting in the underlying OS. You can also force a specific language/country, for instance: QLocale(QLocale::Italian).


问:
Efficient map plotting in python
Using plotly, I've learned to plot maps that represent stuff like 'salary per country' or 'number of XX per country' etc .

Now I'd like to plot the following : say I'm interested in three quantities A,B and C, I would like to plot, for each country, little circles with a size that gets bigger when the value gets bigger, for example :

USA : A=10, B=12,C=3 , I would have 3 circles in the US zone, circle(B)>circle(A)>circle(C).

My dataframe has 4 columns :columns=['Country','quantity_A','quantity_B','quantity_C']

How can I plot a map that looks like what I described. I'm willing to use any library that allows that (the simpler the better of course).

Thanks !

答:
Using matplotlib you can draw a scatter plot as follows, where the size of the scatter point is given by the quantity in the respective column.

```<code>import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)
import pandas as pd

countries = ["USA", "Israel", "Tibet"]
columns=['quantity_A','quantity_B','quantity_C']

df = pd.DataFrame(np.random.rand(len(countries),len(columns))+.2,
                  columns=columns, index=countries)

fig, ax=plt.subplots()

for i,c in enumerate(df.columns):
    ax.scatter(df.index, np.ones(len(df))*i, s = df[c]*200, c=range(len(df)), cmap="tab10")

ax.set_yticks(range(len(df.columns)))
ax.set_yticklabels(df.columns)
ax.margins(0.5)
plt.show()
</code>```

Title: Efficient map plotting in python

Body:
Using matplotlib you can draw a scatter plot as follows, where the size of the scatter point is given by the quantity in the respective column.

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)
import pandas as pd

countries = ["USA", "Israel", "Tibet"]
columns=['quantity_A','quantity_B','quantity_C']

df = pd.DataFrame(np.random.rand(len(countries),len(columns))+.2,
                  columns=columns, index=countries)

fig, ax=plt.subplots()

for i,c in enumerate(df.columns):
    ax.scatter(df.index, np.ones(len(df))*i, s = df[c]*200, c=range(len(df)), cmap="tab10")

ax.set_yticks(range(len(df.columns)))
ax.set_yticklabels(df.columns)
ax.margins(0.5)
plt.show()


问:
Fatal error: Call to a member function bind_param() on a non-object using Update Query
I have just gotten into using premade statements to help with SQL protections.
My script checks to see if the User exists in the Users table and if it does already exist it runs:

```<code>$stmt = $Con->prepare("UPDATE `HA00`.`Users` SET `Unix` = ?,`4690` = ?,`LastIP` = ?,`LastLogin` = CURRENT_TIME( ) WHERE `Users`.`User` = ?;");

$stmt->bind_param('ssss',$PUnix,$P46,$IP,$PAD);
$PAD = $AD;
$PUnix = $Unix;
$IP = $_SERVER['REMOTE_ADDR'];
$P46 = $CTR;
$stmt->execute();
</code>```

If the user doesn't exist theirs is a nearly identical Insert SQL Query that works fine. I am positive I am missing something simple. I have checked the other pages but I am not finding the issue.

Edit:

"var_dump($stmt);" shows bool(false)

答: Try use $stmt->bindValue instead. It should work.</p>

Body:
I have just gotten into using premade statements to help with SQL protections.
My script checks to see if the User exists in the Users table and if it does already exist it runs:

$stmt = $Con->prepare("UPDATE `HA00`.`Users` SET `Unix` = ?,`4690` = ?,`LastIP` = ?,`LastLogin` = CURRENT_TIME( ) WHERE `Users`.`User` = ?;");

$stmt->bind_param('ssss',$PUnix,$P46,$IP,$PAD);
$PAD = $AD;
$PUnix = $Unix;
$IP = $_SERVER['REMOTE_ADDR'];
$P46 = $CTR;
$stmt->execute();

If the user doesn't exist theirs is a nearly identical Insert SQL Query that works fine. I am positive I am missing something simple. I have checked the other pages but I am not finding the issue.

Edit:

"var_dump($stmt);" shows bool(false)


问:
Passing a derived type from Fortran to C++
I have an old Fortran77 program that calls a C++ function and passes several arrays of values to it (~ 100 individual values total). I'd like to convert the arrays to derived types, to make the code more readable and give names to the individual members of the arrays.

Is it possible to pass a derived type from Fortran to a C++ function?

How does C++ know how the structure looks like? Do I have to define the structure twice (once in Fortran and once in C++), and if yes, is there any automatic way to check that both structures are in sync?

I'm using GCC; I'd obviously have to switch the Fortran code to Fortran95 or higher.

答:
Look into ISO_C_BINDING, the C-Fortran binding that is part of F2003. You can create a derived type with a BIND(C) attribute, which will be compatible with a C struct of the "companion C processor" (in the case of gfortran, gcc).

See chapter 7 in the gfortran manual: http://gcc.gnu.org/onlinedocs/gfortran/Mixed-Language-Programming.html


问:
Excel VBA - Highlighting pairs of positive and negative numbers
Suppose I have a column of numbers, for example:

1; -1; 5; 4; 3; -3; -3; 3; -4; 7.

I want to make a macro that can highlight all pairs of positive and negative numbers (ex. 1 and -1) while also taking in consideration the fact that multiple pairs can appear (ex. 3 and -3 both appear twice). Also, I want to be able to input the range that I want to work with.

For the above example, all numbers should be highlighted except 5 and 7.

Here's what I came up with so far

```<code>Sub HighlightExercise()

Set myRange = Application.InputBox(prompt:="Sample", Type:=8)

myRange.Interior.ColorIndex = 2

For Each cell In myRange

If cell.Interior.ColorIndex = 30 Then Next

Set CValue = Cell.Value

myRange.Select

Set CFind = Selection.Find(What:=CValue.Value * -1, After:=ActiveCell, LookIn:= _
    xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:= _
    xlNext, MatchCase:=False, SearchFormat:=False)

If CFind.Value = Null Then Next

If CFind.Interior.ColorIndex = 30 Then Next

CFind.Interior.ColorIndex = 30

CValue.Interior.ColorIndex = 30

Next

End Sub
</code>```

In the above example, it says "Compile error, Next without For" yet the For condition is there. I tried with "Next Cell" and "Next iteration" but still nothing. What am I not getting?

答:
Instead of:

If cell.Interior.ColorIndex = 30 Then Next

You need to test for the opposite and allow it to run the code if true:

```<code>If cell.Interior.ColorIndex <> 30 Then
</code>```

Also you use .Value in many places that does not allow it:

Set CValue = Cell.Value

Should be:

```<code>Set CValue = Cell
</code>```

But really that is not needed as Cell is already a range.

Don't forget to declare your variables:

```<code>Dim myRange As Range
Dim cell As Range
Dim cfind As Range
</code>```

Also in the Find, we want to search from the current cell down so change:

After:=ActiveCell

To

```<code>After:=cell
</code>```

Avoid using .Select just do what you want with the range:

```<code>Set cfind = myRange.Find...
</code>```

try:

```<code>Sub HighlightExercise()
Dim myRange As Range
Dim cell As Range
Dim cfind As Range
Set myRange = Application.InputBox(prompt:="Sample", Type:=8)

myRange.Interior.ColorIndex = 2

For Each cell In myRange

    If cell.Interior.ColorIndex <> 30 Then

        Set cfind = myRange.Find(What:=cell.Value * -1, After:=cell, LookIn:= _
            xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:= _
            xlNext, MatchCase:=False, SearchFormat:=False)
        If Not cfind Is Nothing Then
            If cfind.Interior.ColorIndex <> 30 Then
                cfind.Interior.ColorIndex = 30
                cell.Interior.ColorIndex = 30
            End If
        End If
    End If
Next
</code>```

Body:
Suppose I have a column of numbers, for example:

1; -1; 5; 4; 3; -3; -3; 3; -4; 7.

I want to make a macro that can highlight all pairs of positive and negative numbers (ex. 1 and -1) while also taking in consideration the fact that multiple pairs can appear (ex. 3 and -3 both appear twice). Also, I want to be able to input the range that I want to work with.

For the above example, all numbers should be highlighted except 5 and 7.

Here's what I came up with so far

Sub HighlightExercise()

Set myRange = Application.InputBox(prompt:="Sample", Type:=8)

myRange.Interior.ColorIndex = 2

For Each cell In myRange

If cell.Interior.ColorIndex = 30 Then Next

Set CValue = Cell.Value

myRange.Select

Set CFind = Selection.Find(What:=CValue.Value * -1, After:=ActiveCell, LookIn:= _
    xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:= _
    xlNext, MatchCase:=False, SearchFormat:=False)

If CFind.Value = Null Then Next

If CFind.Interior.ColorIndex = 30 Then Next

CFind.Interior.ColorIndex = 30

CValue.Interior.ColorIndex = 30

Next

End Sub

In the above example, it says "Compile error, Next without For" yet the For condition is there. I tried with "Next Cell" and "Next iteration" but still nothing. What am I not getting?

Body:
Instead of:

If cell.Interior.ColorIndex = 30 Then Next

You need to test for the opposite and allow it to run the code if true:

If cell.Interior.ColorIndex <> 30 Then

Also you use .Value in many places that does not allow it:

Set CValue = Cell.Value

Should be:

Set CValue = Cell

But really that is not needed as Cell is already a range.

Don't forget to declare your variables:

Dim myRange As Range
Dim cell As Range
Dim cfind As Range

Also in the Find, we want to search from the current cell down so change:

After:=ActiveCell

To

After:=cell

Avoid using .Select just do what you want with the range:

Set cfind = myRange.Find...

try:

Sub HighlightExercise()
Dim myRange As Range
Dim cell As Range
Dim cfind As Range
Set myRange = Application.InputBox(prompt:="Sample", Type:=8)

myRange.Interior.ColorIndex = 2

For Each cell In myRange

    If cell.Interior.ColorIndex <> 30 Then

        Set cfind = myRange.Find(What:=cell.Value * -1, After:=cell, LookIn:= _
            xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:= _
            xlNext, MatchCase:=False, SearchFormat:=False)
        If Not cfind Is Nothing Then
            If cfind.Interior.ColorIndex <> 30 Then
                cfind.Interior.ColorIndex = 30
                cell.Interior.ColorIndex = 30
            End If
        End If
    End If
Next


问:
Classification tree with timestamp
I'm working with a simple classification tree with only one predictor. The predictor is the timestamp i.e. the number of seconds between the origin and the timestamp. Well, the problem isn't estimate the tree, but how can I change the labels split? I want in the plot the right format of the timestamp and not the number of seconds. Anyone can help me??enter image description here

答: The object tree is a list of 6 elements. If you write nametree$frame$splits you will find a matrix that contains the labels of the splits. I create a function that converts the labels in the right format. The function as.POSIXct played an important role.</p>

Title: Classification tree with timestamp


问:
ActiveRecord finder method #where not filtering query results
TL;DR: Why am I receiving a list of all resident's when I'm using class methods to scope between active & inactive residents?

My application uses the 'acts_as_tenant' gem. The tenant model is called Account, which has many employees who manage residents.

```<code>class Account < ActiveRecord::Base
  before_create :set_subdomain

  has_one  :admin, class_name: 'Employee', foreign_key: :account_id,
    dependent: :destroy, inverse_of: :account

  has_many :employees, class_name: 'Employee', foreign_key: :account_id,
    dependent: :destroy, inverse_of: :account

  has_many :residents
  has_many :invites
  has_many :daily_summaries
  has_one  :subscription
  .
  .
  .
end
</code>```

In my resident's schema there is a flag attribute named is_active, it's purpose being to differentiate between active and soft-deleted residents. You can also see the db constraints added.

```<code>create_table :residents do |t|
  t.integer    :account_id, null: false
  t.integer    :employee_id, null: false
  t.boolean    :is_active, default: true, null: false
  .
  .
  .
end
</code>```

I allow employees to view soft-deleted residents & offer a tabbed index-view of both active/inactive residents.

In my Resident class I have the following class methods to scope based on active/inactive state.

```<code>  class Resident < ActiveRecord::Base
    acts_as_tenant(:account)
    .
    .
    .
    def self.inactive_count(current_account)
      where({ account_id: current_account.id, is_active: false }).count
    end

    def self.default(current_account)
      where({ account_id: current_account.id, is_active: true })
    end

    def self.inactive(current_account)
      # where({ account_id: current_account.id, is_active: false })
      where("account_id = ? AND is_active = ?", current_account.id, false).first
    end

    def archive
      update_attribute(:is_active, false)
    end
    .
    .
    .
  end
</code>```

My problem is that I am receiving a list of all residents in both the active and inactive tabs in my index-view. Note the last name is the same in both images of this view page.

I would prefer for the class method to only return active or inactive residents respectively.

I'm wanting to find out why I'm not receiving only active or only inactive residents based on my query class methods.

The class methods for active/inactive count appear to be working as expected, here is a peak.

```<code>  def index
   @inactive_residents = Resident.inactive(current_account)
   @inactive_resident_count = Resident.inactive_count(current_account)
   @active_residents = Resident.default(current_account)
   @active_resident_count = Resident.active_count(current_account)
  end
</code>```

My reading so far to solve:

Rails Guides - ActiveRecord querying

Rails scope returns all instead of nil

ActiveRecord::Relation

Server logs included to show SQL

View templates

index.html.erb

```<code>  <li class="active">
    <a href="#" data-toggle="tab">
      Active Residents
      <span class="badge badge-purple">
        <%= @active_resident_count %>
      </span>
    </a>
   </li>
   <li>
     <a href="#" data-toggle="tab">
       Inactive Residents
       <span class="badge badge-dark">
         <%= @inactive_resident_count %>
       </span>
     </a>
   </li>
</code>```

_active_residents.html.erb

```<code><% if @active_residents.any? %>
  <tbody>
    <% @active_residents.reverse_each do |resident| %>
      .
      .
      .
    <% end %>
  </tbody>
<% end %>
</code>```

_inactive_residents.html.erb

```<code><% unless @inactive_residents.nil? %>
  <% @inactive_residents.reverse_each do |resident| %>
    .
    .
    .
  <% end %>
<% end %>
</code>```

Update after comment

My logs are below, nothing changes in the log when I select the 'inactive' tab in the browser. I also don't see any output from js console in dev tools unless I set an option for verbose output. I will include an image of this also.

答:
This worked for me

Second comment in Yan Foto's answer to this SO post

To sum up the link above:

if you are using the data-attribute method you have to have the href attribute set to the ID of the tab you want to open. In JS version you have to have something like $('#myTab a[href="#profile"]').tab('show') in order to open a tab with href value set to #profile

My example

in both partial files I added

and in index.html.erb which houses the partials I changed the href value from # to my_tab_id

```<code><ul class="nav nav-tabs tabs-right">
  <li class="active">
    <a href="#my_tab1_id" data-toggle="tab">
      Active Residents
      <span class="badge badge-purple">
        <%= @active_resident_count %>
      </span>
    </a>
   </li>
   <li>
     <a href="#my_tab2_id" data-toggle="tab">
       Inactive Residents
       <span class="badge badge-dark">
         <%= @inactive_resident_count %>
       </span>
      </a>
    </li>
  </ul>
</code>```

Body:
TL;DR: Why am I receiving a list of all resident's when I'm using class methods to scope between active & inactive residents?

My application uses the 'acts_as_tenant' gem. The tenant model is called Account, which has many employees who manage residents.

class Account < ActiveRecord::Base
  before_create :set_subdomain

  has_one  :admin, class_name: 'Employee', foreign_key: :account_id,
    dependent: :destroy, inverse_of: :account

  has_many :employees, class_name: 'Employee', foreign_key: :account_id,
    dependent: :destroy, inverse_of: :account

  has_many :residents
  has_many :invites
  has_many :daily_summaries
  has_one  :subscription
  .
  .
  .
end

In my resident's schema there is a flag attribute named is_active, it's purpose being to differentiate between active and soft-deleted residents. You can also see the db constraints added.

create_table :residents do |t|
  t.integer    :account_id, null: false
  t.integer    :employee_id, null: false
  t.boolean    :is_active, default: true, null: false
  .
  .
  .
end

I allow employees to view soft-deleted residents & offer a tabbed index-view of both active/inactive residents.

In my Resident class I have the following class methods to scope based on active/inactive state.

  class Resident < ActiveRecord::Base
    acts_as_tenant(:account)
    .
    .
    .
    def self.inactive_count(current_account)
      where({ account_id: current_account.id, is_active: false }).count
    end

    def self.default(current_account)
      where({ account_id: current_account.id, is_active: true })
    end

    def self.inactive(current_account)
      # where({ account_id: current_account.id, is_active: false })
      where("account_id = ? AND is_active = ?", current_account.id, false).first
    end

    def archive
      update_attribute(:is_active, false)
    end
    .
    .
    .
  end

My problem is that I am receiving a list of all residents in both the active and inactive tabs in my index-view. Note the last name is the same in both images of this view page.

I would prefer for the class method to only return active or inactive residents respectively.

I'm wanting to find out why I'm not receiving only active or only inactive residents based on my query class methods.

The class methods for active/inactive count appear to be working as expected, here is a peak.

  def index
   @inactive_residents = Resident.inactive(current_account)
   @inactive_resident_count = Resident.inactive_count(current_account)
   @active_residents = Resident.default(current_account)
   @active_resident_count = Resident.active_count(current_account)
  end

My reading so far to solve:

Rails Guides - ActiveRecord querying

Rails scope returns all instead of nil

ActiveRecord::Relation

Server logs included to show SQL

View templates

index.html.erb

      Active Residents

        <%= @active_resident_count %>

       Inactive Residents

         <%= @inactive_resident_count %>

_active_residents.html.erb

<% if @active_residents.any? %>

    <% @active_residents.reverse_each do |resident| %>
      .
      .
      .
    <% end %>

<% end %>

_inactive_residents.html.erb

<% unless @inactive_residents.nil? %>
  <% @inactive_residents.reverse_each do |resident| %>
    .
    .
    .
  <% end %>
<% end %>

Update after comment

My logs are below, nothing changes in the log when I select the 'inactive' tab in the browser. I also don't see any output from js console in dev tools unless I set an option for verbose output. I will include an image of this also.

Body:
This worked for me

Second comment in Yan Foto's answer to this SO post

To sum up the link above:

if you are using the data-attribute method you have to have the href attribute set to the ID of the tab you want to open. In JS version you have to have something like $('#myTab a[href="#profile"]').tab('show') in order to open a tab with href value set to #profile

My example

in both partial files I added

<div class="tab-pane fade in active" id="my_tab1_id">

and in index.html.erb which houses the partials I changed the href value from # to my_tab_id

<ul class="nav nav-tabs tabs-right">
  <li class="active">
    <a href="#my_tab1_id" data-toggle="tab">
      Active Residents&nbsp;&nbsp;
      <span class="badge badge-purple">
        <%= @active_resident_count %>
      </span>
    </a>
   </li>
   <li>
     <a href="#my_tab2_id" data-toggle="tab">
       Inactive Residents&nbsp;&nbsp;
       <span class="badge badge-dark">
         <%= @inactive_resident_count %>
       </span>
      </a>
    </li>
  </ul>


问:
How to Debug Variables in Smarty like in PHP var_dump()
I have some variables inside a template and I don't know where I assigned them. I need to know what is inside a particular variable; for instance, say I have a variable in smarty called member. I tried with {debug} but it didn't work, and no popup was shown.

How can I output/debug smarty variables using something like var_dump() inside the templates?

答:
If you want something prettier I would advise

```<code>{"<?php\n\$data =\n"|@cat:{$yourvariable|@var_export:true|@cat:";\n?>"}|@highlight_string:true}
</code>```

just replace yourvariable by your variable

Body:
If you want something prettier I would advise

{"<?php\n\$data =\n"|@cat:{$yourvariable|@var_export:true|@cat:";\n?>"}|@highlight_string:true}

just replace yourvariable by your variable