问:
Using Database from SQL Server in Visual Studio
I am doing a C# project in Visual Studio. For the purposes of the project, I need to include a database from SQL Server.

Here is what I have written in SQL Server:

```<code>create table user1 (
    id int primary key identity,
    username varchar(50),
    password varchar(50));
</code>```

Then, in the Visual Studio, I want to make a form that will insert values in the database (reading from the database works good!). Here is my code:

```<code>string sql = "INSERT INTO user1(username, password) VALUES ('"+textBox1.Text + "'+" + textBox2.Text+")";
</code>```

But I get an error message:

System.Data.SqlClient.SqlException: There are more columns in the INSERT statement than values specified in the VALUES clause. The number of values in the VALUES clause must match the number of columns specified in the INSERT statement.

What am I doing wrong?

答:
Steer clear of constructing SQL statements with input directly from the user.  this is only going to cause you trouble down the track with SQL Injection attacks.  Use parameterised SQL instead. like the following.

```<code>string sql = "INSERT INTO user1(username, password) VALUES (@username, @password)";
command.CommandText = sql;
command.Parameters.Add(new SqlParameter("@userName", textBox1.Text));
command.Parameters.Add(new SqlParameter("@password", textBox2.Text));
</code>```

Having said that I would also strongly discourage you from storing user passwords in plain text.  This will open you up to a world of hurt later on down the track.

Body:
I am doing a C# project in Visual Studio. For the purposes of the project, I need to include a database from SQL Server.

Here is what I have written in SQL Server:

create table user1 (
    id int primary key identity,
    username varchar(50),
    password varchar(50));

Then, in the Visual Studio, I want to make a form that will insert values in the database (reading from the database works good!). Here is my code:

string sql = "INSERT INTO user1(username, password) VALUES ('"+textBox1.Text + "'+" + textBox2.Text+")";

But I get an error message:

System.Data.SqlClient.SqlException: There are more columns in the INSERT statement than values specified in the VALUES clause. The number of values in the VALUES clause must match the number of columns specified in the INSERT statement.

What am I doing wrong?

Body:
Steer clear of constructing SQL statements with input directly from the user.  this is only going to cause you trouble down the track with SQL Injection attacks.  Use parameterised SQL instead. like the following.

string sql = "INSERT INTO user1(username, password) VALUES (@username, @password)";
command.CommandText = sql;
command.Parameters.Add(new SqlParameter("@userName", textBox1.Text));
command.Parameters.Add(new SqlParameter("@password", textBox2.Text));

Having said that I would also strongly discourage you from storing user passwords in plain text.  This will open you up to a world of hurt later on down the track.


来源: stackexchange

问:
Grouping records by 60 minute duration, starting the hour from the timestamp of the first record
I have a query that groups the records by the hour as shown below:

```<code>select date_trunc('hour', insert_time),
       file_type,
       avg(file_size)
from my_table
where insert_time > now()::timestamp - interval '7 days'
group by 1, 2 order by 1, 2
</code>```

This groups the records into one hour windows where each hour window starts at 0th minute.

A little background for this requirement: I have an automated test that causes the DB to be populated. The DB could have already have some records in it before my test starts. My automated test's objective is to do certain number of tasks every hour. I am looking for a way to verify my test's accuracy by generating a report in the DB for each hour, where the hour starts at the first record's timestamp (minute) matching a condition (I can define a condition to match the custom strings sent by my automation, so it picks up the first record sent by the automation)

So, the objective is to group the records by the hour, but the hour should be calculated using the minute of the first record matching the WHERE condition as the starting point.

So, if the first record inserted due to my automation has the timestamp 2017-06-06 07:47:04.012734, then the grouping should happen like this:

```<code>1st group => 2017-06-06 07:47:04.012734 to 2017-06-06 08:47:04.012734
2nd group => 2017-06-06 08:47:04.012734 to 2017-06-06 09:47:04.012734
3rd group => 2017-06-06 09:47:04.012734 to 2017-06-06 10:47:04.012734
.
.
.
</code>```

Thanks in advance!!

答:
One way is to read that first record's timestamp at first. Then subtract it from other values, truncate to one hour precision and add it back.

```<code>WITH
CTE_MinTime
AS
(
    select
        MIN(insert_time) AS MinTime
    from my_table
    where insert_time > now()::timestamp - interval '7 days'
)
select
    CTE_MinTime.MinTime + date_trunc('hour', insert_time - CTE_MinTime.MinTime),
    file_type,
    avg(file_size)
from
    my_table
    CROSS JOIN CTE_MinTime
where insert_time > now()::timestamp - interval '7 days'
group by 1, 2
order by 1, 2
;
</code>```

You can save MinTime to some variable instead of using subquery.

ContentLicense: CC BY-SA 3.0

Body:
I have a query that groups the records by the hour as shown below:

select date_trunc('hour', insert_time),
       file_type,
       avg(file_size)
from my_table
where insert_time > now()::timestamp - interval '7 days'
group by 1, 2 order by 1, 2

This groups the records into one hour windows where each hour window starts at 0th minute.

A little background for this requirement: I have an automated test that causes the DB to be populated. The DB could have already have some records in it before my test starts. My automated test's objective is to do certain number of tasks every hour. I am looking for a way to verify my test's accuracy by generating a report in the DB for each hour, where the hour starts at the first record's timestamp (minute) matching a condition (I can define a condition to match the custom strings sent by my automation, so it picks up the first record sent by the automation)

So, the objective is to group the records by the hour, but the hour should be calculated using the minute of the first record matching the WHERE condition as the starting point.

So, if the first record inserted due to my automation has the timestamp 2017-06-06 07:47:04.012734, then the grouping should happen like this:

1st group => 2017-06-06 07:47:04.012734 to 2017-06-06 08:47:04.012734
2nd group => 2017-06-06 08:47:04.012734 to 2017-06-06 09:47:04.012734
3rd group => 2017-06-06 09:47:04.012734 to 2017-06-06 10:47:04.012734
.
.
.

Thanks in advance!!

Body:
One way is to read that first record's timestamp at first. Then subtract it from other values, truncate to one hour precision and add it back.

WITH
CTE_MinTime
AS
(
    select
        MIN(insert_time) AS MinTime
    from my_table
    where insert_time > now()::timestamp - interval '7 days'
)
select
    CTE_MinTime.MinTime + date_trunc('hour', insert_time - CTE_MinTime.MinTime),
    file_type,
    avg(file_size)
from
    my_table
    CROSS JOIN CTE_MinTime
where insert_time > now()::timestamp - interval '7 days'
group by 1, 2
order by 1, 2
;

You can save MinTime to some variable instead of using subquery.


问:
member function as template parameter and c++17 equivalent
In clang 4.0, taking advantage of c++17 auto template parameter, I can now write functions like this (which turns out to be very useful in many situations):

```<code>template<auto member_function, typename OBJECT>
auto call_member_fct(OBJECT object){
    return (object.*member_function)()
}
</code>```

(G++ >= 7 offers the same possibility but I have not tested it)

The function has the useful feature that you can call it with a single template parameter, the actual member function:

```<code>call_member_fct<&action::count>(action())
</code>```

Unfortunately vs2017 does not permit this.
Is there a syntax workaround that would permit to use the same call with single template parameter in vs2017, with the function signature and object automatically deducted?

答:
Not exactly 100% the same, but should do for most situations. You can have the member function a parameter:

```<code>template <class T, class Ret>
auto yolo(auto (T::* mem) () -> Ret, T& obj)
{
    return (obj.*mem)();
}
</code>```

Call like this:

```<code>struct X { auto foo() { return 24; }};

auto test()
{
    X x;
    return yolo(&X::foo, x);
}
</code>```

Body:
In clang 4.0, taking advantage of c++17 auto template parameter, I can now write functions like this (which turns out to be very useful in many situations):

template<auto member_function, typename OBJECT>
auto call_member_fct(OBJECT object){
    return (object.*member_function)()
}

(G++ >= 7 offers the same possibility but I have not tested it)

The function has the useful feature that you can call it with a single template parameter, the actual member function:

call_member_fct<&action::count>(action())

Unfortunately vs2017 does not permit this.
Is there a syntax workaround that would permit to use the same call with single template parameter in vs2017, with the function signature and object automatically deducted?

Body:
Not exactly 100% the same, but should do for most situations. You can have the member function a parameter:

template <class T, class Ret>
auto yolo(auto (T::* mem) () -> Ret, T& obj)
{
    return (obj.*mem)();
}

Call like this:

struct X { auto foo() { return 24; }};

auto test()
{
    X x;
    return yolo(&X::foo, x);
}


问:
Get value from dictionary two levels deep
What is an elegant way of getting the value for a sub-key inside a dictionary, but only if the two levels of keys exist using python?

For example I want to get the value for 'team' from 'dad'. So if Dad doesn't exist it should return none, otherwise continue to look for subkey 'team' and if that doesn't exist return none, otherwise return the value.

Would there be an easy way to possibly write a recursive function which i just pass an array of names which it then looks through and if it hits a missing key it just returns a defined default value.

i know i can currently do

```<code>dict.get('dad', None)
</code>```

I'd like to be able to do something like this

```<code>dict.get(['dad','team'], None)
</code>```

dict

```<code>{
   "dad":{
      "team":"packers"
   },
   "mom":{
      "show":"rugrats",
      "vehicle":"buggy"
   }
}
</code>```

答:
```<code>dict.get('dad', {}).get('team', None)
</code>```

That does exactly two levels.  In the general case, you could

```<code>def recurGet(d, ks):
  head, *tail = ks
  return recurGet(d.get(head, {}), tail) if tail else d.get(head)
</code>```

The head, *tail = ks is Python 3.  In Python 2, you would have to write it explicitly as

```<code>  head = ks[0]
  tail = ks[1:]
</code>```

Body:
What is an elegant way of getting the value for a sub-key inside a dictionary, but only if the two levels of keys exist using python?

For example I want to get the value for 'team' from 'dad'. So if Dad doesn't exist it should return none, otherwise continue to look for subkey 'team' and if that doesn't exist return none, otherwise return the value.

Would there be an easy way to possibly write a recursive function which i just pass an array of names which it then looks through and if it hits a missing key it just returns a defined default value.

i know i can currently do

dict.get('dad', None)

I'd like to be able to do something like this

dict.get(['dad','team'], None)

dict

{
   "dad":{
      "team":"packers"
   },
   "mom":{
      "show":"rugrats",
      "vehicle":"buggy"
   }
}

Body:
dict.get('dad', {}).get('team', None)

That does exactly two levels.  In the general case, you could

def recurGet(d, ks):
  head, *tail = ks
  return recurGet(d.get(head, {}), tail) if tail else d.get(head)

The head, *tail = ks is Python 3.  In Python 2, you would have to write it explicitly as

  head = ks[0]
  tail = ks[1:]


问:
TFS GIT - How to commit only certain files?
I am new to using Git in TFS.

Say I have 10 files that I modified, however I would only like to commit 2 of those files.

Previously with TFS I could include/exclude what file(s) I wanted to check in.

What would the equivalent be in Git?

Would I Stage my 2 files I want to commit and check those in?  Or would I stage the 8 files and commit my 2 changes?

答:
You do not need to state all files:
You can git add command to stage the files you want to commit, like:

```<code>git add [file1] [file2]
</code>```

Then use git commit command to commit your change, like:

```<code>git commit -m 'commit message'
</code>```

Body:
You do not need to state all files:
You can git add command to stage the files you want to commit, like:

git add [file1] [file2]

Then use git commit command to commit your change, like:

git commit -m 'commit message'


问:
Calculate MD5 Checksum Efficiently
I'm using following code to get the Checksum of a file. It uses 50% of CPU during calculations.

```<code>MessageDigest md = MessageDigest.getInstance("MD5");
InputStream is = new FileInputStream("C:\\Temp\\Small\\Movie.mp4"); // Size 700 MB

byte [] buffer = new byte [blockSize];
int numRead;
do
{
 numRead = is.read(buffer);
 if (numRead > 0)
 {
  md.update(buffer, 0, numRead);
 }
} while (numRead != -1);

byte[] digest = md.digest();
</code>```

What can be done to reduce the code from using maximum CPU other than Thread.sleep(ms)

regards,
Kingsley Reuben J

答:
I'd rather dedicate priority management to os, for windows you could start your app with</p>

```<code>start /low your_executable
</code>```

ContentLicense: CC BY-SA 2.5

Title: Calculate MD5 Checksum Efficiently

Body:
I'm using following code to get the Checksum of a file. It uses 50% of CPU during calculations.

MessageDigest md = MessageDigest.getInstance("MD5");
InputStream is = new FileInputStream("C:\\Temp\\Small\\Movie.mp4"); // Size 700 MB

byte [] buffer = new byte [blockSize];
int numRead;
do
{
 numRead = is.read(buffer);
 if (numRead > 0)
 {
  md.update(buffer, 0, numRead);
 }
} while (numRead != -1);

byte[] digest = md.digest();

What can be done to reduce the code from using maximum CPU other than Thread.sleep(ms)

regards,
Kingsley Reuben J

Body:
I'd rather dedicate priority management to os, for windows you could start your app with

start /low your_executable


问:
Libgdx Detect horizontal scrolling
I'm working on a desktop only project using the libgdx game library, and I'm looking to implement a way for when the user scrolls horizontally to pan the camera. I'd like to avoid using libgdx's scene2d if possible. However, I can't see to find a way to capture horizontal scrolls. Is there anyway to detect a horizontal mouse scroll in Libgdx? I'd like to avoid using libgdx's scene2d if possible. And if there is not, is there a way to do it using plain java, without using awt, swing, or javafx?</p>

答:
Horizontal mouse scrolls? There is no such thing unless you are using a mouse with multiple scroll wheels. Usually the mouse has one scroll wheel.

However, if you mean moving the mouse horizontally, you should be able to capture that using getDeltaX(). Note that it's a raw input, so you will want to divide it by the screen's width in order to make movement the same on any monitor you use. You may also want to include a sensitivity multiplier so that the user may choose how fast panning is.

It's often helpful to allow rotation of the camera using the same input by checking whether a key is held down. Consider this pseudocode:

```<code>void updateCamera() {
    if (LeftShiftPressed()) {
        RotateCamera(getNormalizedX());
    } else {
        PanCamera(getNormalizedX());
    }
}

float getNormalizedX() {
    return float(getDeltaX()) / float(getScreenWidth())
}

void PanCamera(float x_movement) {
    // pan by x_movement * pan_multiplier
}

void RotateCamera(float x_movement) {
    // rotate by x_movement * rotation_multiplier
}
</code>```

Title: Libgdx Detect horizontal scrolling

Body:
Horizontal mouse scrolls? There is no such thing unless you are using a mouse with multiple scroll wheels. Usually the mouse has one scroll wheel.

However, if you mean moving the mouse horizontally, you should be able to capture that using getDeltaX(). Note that it's a raw input, so you will want to divide it by the screen's width in order to make movement the same on any monitor you use. You may also want to include a sensitivity multiplier so that the user may choose how fast panning is.

It's often helpful to allow rotation of the camera using the same input by checking whether a key is held down. Consider this pseudocode:

void updateCamera() {
    if (LeftShiftPressed()) {
        RotateCamera(getNormalizedX());
    } else {
        PanCamera(getNormalizedX());
    }
}

float getNormalizedX() {
    return float(getDeltaX()) / float(getScreenWidth())
}

void PanCamera(float x_movement) {
    // pan by x_movement * pan_multiplier
}

void RotateCamera(float x_movement) {
    // rotate by x_movement * rotation_multiplier
}


问:
Java: Why are wrapper classes needed?
On the very high level, I know that we need to "wrap" the primitive data types, such as int and char, by using their respective wrapper classes to use them within Java collections.I would like to understand how Java collections work at the low level by asking:"why do we need to wrap primitive data types as objects to be able to use them in collections?"I thank you in advance for your help.</p>

答:
Read all of the answers, but none of them really explains it simply in layman terms.

A wrapper class wraps(encloses) around a data type (can be any primitive data type such as int, char, byte, long) and makes it an object.

Here are a few reasons why wrapper classes are needed:

Allows null values.

Can be used in collection such as List, Map, etc.

Can be used in methods which accepts arguments of Object type.

Can be created like Objects using new ClassName() like other objects:

```<code>Integer wrapperInt = new Integer("10");
</code>```

Makes available all the functions that Object class has such as clone(), equals(), hashCode(), toString() etc.

Wrapper classes can be created in two ways:

Using constructor:

```<code>Integer i = new Integer("1"); //new object is created
</code>```

Using valueOf() static method:

```<code> Integer i  = Integer.valueOf("100"); //100 is stored in variable
</code>```

It is advised to use the second way of creating wrapper classes as it takes less memory as a new object is not created.

Title: Java: Why are wrapper classes needed?

Body:
Read all of the answers, but none of them really explains it simply in layman terms.

A wrapper class wraps(encloses) around a data type (can be any primitive data type such as int, char, byte, long) and makes it an object.

Here are a few reasons why wrapper classes are needed:

Allows null values.

Can be used in collection such as List, Map, etc.

Can be used in methods which accepts arguments of Object type.

Can be created like Objects using new ClassName() like other objects:

Integer wrapperInt = new Integer("10");

Makes available all the functions that Object class has such as clone(), equals(), hashCode(), toString() etc.

Wrapper classes can be created in two ways:

Using constructor:

Integer i = new Integer("1"); //new object is created

Using valueOf() static method:

 Integer i  = Integer.valueOf("100"); //100 is stored in variable

It is advised to use the second way of creating wrapper classes as it takes less memory as a new object is not created.

ContentLicense: CC BY-SA 4.0


问:
How do I set a checkbox to unchecked based on php var - previous posts don't fix my issue
I have a php var ($testx) set to 0.

Html code looks like this:

```<code><input type='checkbox' name='test_cb' id='test_cb' checked=<?= $testx == true ? 'checked' : '0' ?>></input>
</code>```

The checkbox is always checked even though the php var being checked is false.  I must be missing something obvious.

答:
First: Don't include the checked attribute unless you want it checked.  (Your original code includes checked= always, even if it should not be checked)

Second: Personally, I find that style of code to be less readable.

Here is how I would propose you do it:

```<code><?php $checked = ( $testx ) ? ' checked' : ''; ?>
<input type='checkbox' name='test_cb' id='test_cb'<?php echo $checked; ?>>
</code>```

NOTE: This assumes that $textx is either truthy or falsey - since you wrote $textx == true, I'm guessing it's either NULL or FALSE if it's not set.  Clearly you could check more strictly, if required:

```<code><?php $checked = ( TRUE === $testx ) ? ' checked' : ''; ?>
</code>```

FINALLY:
Better yet - since this would be something I presume you do often - would be to create an is_checked function, like so:

```<code>function is_checked( $var ) {
    if ( $var ) {
        echo ' checked';
    }
}
</code>```

Then you could use it repeatedly, like so:

```<code><input type='checkbox' name='test_cb' id='test_cb'<?php is_checked( $testx ); ?>>
<input type='checkbox' name='test_again' id='test_again'<?php is_checked( $testy ); ?>>
// etc...
</code>```

Body:
I have a php var ($testx) set to 0.

Html code looks like this:

<input type='checkbox' name='test_cb' id='test_cb' checked=<?= $testx == true ? 'checked' : '0' ?>></input>

The checkbox is always checked even though the php var being checked is false.  I must be missing something obvious.

Body:
First: Don't include the checked attribute unless you want it checked.  (Your original code includes checked= always, even if it should not be checked)

Second: Personally, I find that style of code to be less readable.

Here is how I would propose you do it:

<?php $checked = ( $testx ) ? ' checked' : ''; ?>
<input type='checkbox' name='test_cb' id='test_cb'<?php echo $checked; ?>>

NOTE: This assumes that $textx is either truthy or falsey - since you wrote $textx == true, I'm guessing it's either NULL or FALSE if it's not set.  Clearly you could check more strictly, if required:

<?php $checked = ( TRUE === $testx ) ? ' checked' : ''; ?>

FINALLY:
Better yet - since this would be something I presume you do often - would be to create an is_checked function, like so:

function is_checked( $var ) {
    if ( $var ) {
        echo ' checked';
    }
}

Then you could use it repeatedly, like so:

<input type='checkbox' name='test_cb' id='test_cb'<?php is_checked( $testx ); ?>>
<input type='checkbox' name='test_again' id='test_again'<?php is_checked( $testy ); ?>>
// etc...


问:
Undefined reference ... But all is linked
I have a link problem with CodeBlocks IDE. But I think everything should be fine.

I want to work with laslib library. They provide a .lib file which I've linked in CodeBlocks IDE (such i usually did ...). Then I've included the "inc" folder which containing .hpp includes.

Atm, I did the minimal requirement to include an external library.

Then, in my "main" function, I've included the necessary files, the CodeBlocks intellisense provide me the prototypes of functions (so links are good I guess).

Here is my code :

```<code>#include <iostream>
#include <vector>

#include "lasreader.hpp"
#include "laswriter.hpp"
#include "lasdefinitions.hpp"

#define FILENAME "D:\\las.las"
#define FILEOUT "D:\\out"

int main(int argc, char** argv)
{
// Assume that's correct for simplicity @TODO : check argv
std::string filename = FILENAME;//argv[1];
std::string file_out = FILEOUT; //argv[2];

LASreadOpener lasreadopener;
LASwriteOpener laswriteopener;
lasreadopener.set_file_name(filename.c_str());
laswriteopener.set_file_name(file_out.c_str());

lasreadopener.parse(0, NULL); // parse without args

// Declare lasreader
LASreader* lasreader;

// Open the file
lasreader = lasreadopener.open();

//  Create and open the writer
LASwriter* laswriter = laswriteopener.open(&lasreader->header);

// Loop through the points (note they will already be filtered)
while (lasreader->read_point())
{
    // Show coordinates
    std::cout << lasreader->point.get_x() << ", " << lasreader->point.get_y() << ", " << lasreader->point.get_z() << std::endl;

    // Write point
    laswriter->write_point(&lasreader->point);

    // Add it to the inventory (keeps track of min/max values for the header)
    laswriter->update_inventory(&lasreader->point);
}

laswriter->update_header(&lasreader->header, TRUE);

laswriter->close();
lasreader->close();

delete laswriter;
delete lasreader;
}
</code>```

And errors are :

```<code>main.cpp|17|undefined reference to `LASreadOpener::LASreadOpener()'|
main.cpp|18|undefined reference to `LASwriteOpener::LASwriteOpener()'|
</code>```

etc ...

I didnt see what I've did wrong ... I've already tried the "hard" method with copying .hpp and .lib in mingw corresponding folders ...

Any ideas?

答:
Make sure that you are building your code for the same architecture as the library. By default, LASlib is built for 32-bit, but your compiler may default to 64-bit, so the compiler won't link them due to different method signatures.

You could try to either rebuild LASlib for 64-bit, or compile your own software for 32-bit.

Unfortunately your linker is hiding the problem somewhat, as it is demangling the method names. If you can set the compiler to output mangled names, this may help as it can highlight differences between 32-bit and 64-bit binaries. For example, decoding a mangled name (e.g. using https://demangler.com) can indicate where the linker is expecting a method returning a 64-bit pointer, but where the library has defined a method with the same name but which returns a 32-bit pointer.

Body:
I have a link problem with CodeBlocks IDE. But I think everything should be fine.

I want to work with laslib library. They provide a .lib file which I've linked in CodeBlocks IDE (such i usually did ...). Then I've included the "inc" folder which containing .hpp includes.

Atm, I did the minimal requirement to include an external library.

Then, in my "main" function, I've included the necessary files, the CodeBlocks intellisense provide me the prototypes of functions (so links are good I guess).

Here is my code :

#include <iostream>
#include <vector>

#include "lasreader.hpp"
#include "laswriter.hpp"
#include "lasdefinitions.hpp"

#define FILENAME "D:\\las.las"
#define FILEOUT "D:\\out"

int main(int argc, char** argv)
{
// Assume that's correct for simplicity @TODO : check argv
std::string filename = FILENAME;//argv[1];
std::string file_out = FILEOUT; //argv[2];

LASreadOpener lasreadopener;
LASwriteOpener laswriteopener;
lasreadopener.set_file_name(filename.c_str());
laswriteopener.set_file_name(file_out.c_str());

lasreadopener.parse(0, NULL); // parse without args

// Declare lasreader
LASreader* lasreader;

// Open the file
lasreader = lasreadopener.open();

//  Create and open the writer
LASwriter* laswriter = laswriteopener.open(&lasreader->header);

// Loop through the points (note they will already be filtered)
while (lasreader->read_point())
{
    // Show coordinates
    std::cout << lasreader->point.get_x() << ", " << lasreader->point.get_y() << ", " << lasreader->point.get_z() << std::endl;

    // Write point
    laswriter->write_point(&lasreader->point);

    // Add it to the inventory (keeps track of min/max values for the header)
    laswriter->update_inventory(&lasreader->point);
}

laswriter->update_header(&lasreader->header, TRUE);

laswriter->close();
lasreader->close();

delete laswriter;
delete lasreader;
}

And errors are :

main.cpp|17|undefined reference to `LASreadOpener::LASreadOpener()'|
main.cpp|18|undefined reference to `LASwriteOpener::LASwriteOpener()'|

etc ...

I didnt see what I've did wrong ... I've already tried the "hard" method with copying .hpp and .lib in mingw corresponding folders ...

Any ideas?


问:
HTML and CSS radio tabs issue
okay, i made a website for my work. It's just for his ebay site seeing as ebay will no longer support javascript. I made a set of (seven) tabs composed entirely of html and css. they work fine but the problem im having is none of the tabs actually are open and display upon the inital opening of the webpage. He'd like tab-1 open when the webpage opens to display item information without the user having to open it manually. here's an example of my html for it. </p>

```<code><div class="tabs">
<div class="tab">
<input type="radio" id="tab-1" name="tab-group-1">
<label for="tab-1"><span style="cursor:pointer" class=:"tab-switch">tab-1 name</span></label>

<div class="content">
<p>tab-1 info</p>
</div>
</div>

<div class="tab">
<input type="radio" id="tab-2" name="tab-group-1">
<label for="tab-2"><span style="cursor:pointer">tab-2 name</span></label>

<div class="content">
<p>tab-2 info</p>
</div>
</div>
</code>```

<p>this is the basic format that i created my radio tabs with. I'm just curious now on what i can do to make tab-1 open by default. i assume maybe a pseudo-class or something of the sort. Keep in mind I am avoiding the use of javascript in any form. </p>

答:
Set the checked attribute on the input you want to be selected by default.

input:checked ~ .content {
  display: block;
}
.content, input {
  display: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="tabs">
  <div class="tab">
    <input type="radio" id="tab-1" name="tab-group-1" checked>
    <label for="tab-1"><span style="cursor:pointer" class=:"tab-switch">tab-1 name</span></label>

    <div class="content">
      <p>tab-1 info</p>
    </div>
  </div>

  <div class="tab">
    <input type="radio" id="tab-2" name="tab-group-1">
    <label for="tab-2"><span style="cursor:pointer">tab-2 name</span></label>

    <div class="content">
      <p>tab-2 info</p>
    </div>
  </div></code>```

Title: HTML and CSS radio tabs issue

Body:
okay, i made a website for my work. It's just for his ebay site seeing as ebay will no longer support javascript. I made a set of (seven) tabs composed entirely of html and css. they work fine but the problem im having is none of the tabs actually are open and display upon the inital opening of the webpage. He'd like tab-1 open when the webpage opens to display item information without the user having to open it manually. here's an example of my html for it.

<input type="radio" id="tab-1" name="tab-group-1">
tab-1 name

tab-1 info

<input type="radio" id="tab-2" name="tab-group-1">
tab-2 name

tab-2 info

this is the basic format that i created my radio tabs with. I'm just curious now on what i can do to make tab-1 open by default. i assume maybe a pseudo-class or something of the sort. Keep in mind I am avoiding the use of javascript in any form.

Body:
Set the checked attribute on the input you want to be selected by default.

input:checked ~ .content {
  display: block;
}
.content, input {
  display: none;
}

<div class="tabs">
  <div class="tab">
    <input type="radio" id="tab-1" name="tab-group-1" checked>
    <label for="tab-1"><span style="cursor:pointer" class=:"tab-switch">tab-1 name</span></label>

    <div class="content">
      <p>tab-1 info</p>
    </div>
  </div>

  <div class="tab">
    <input type="radio" id="tab-2" name="tab-group-1">
    <label for="tab-2"><span style="cursor:pointer">tab-2 name</span></label>

    <div class="content">
      <p>tab-2 info</p>
    </div>
  </div>


问:
JS Not showing wrong result UPDATED
Instead of 39500 output i get 500. Could someone help me, i want IF gw reaches 0, there should be no more -500 on wall.

I used my code but it is not working.
HTML

```<code><li><b>Infantry: </b><span id="gw">40000</span></li>
<p class="fort"><b>Fort: </b><span id="wall">1000</span></p>
<button class="troops" onclick="send()">SEND TROOPS</button>
</code>```

JS

```<code>function send(){
    var a = document.getElementById('gw').innerHTML;
    var b = 500;
    var c = a-b;

    var label = document.getElementById('wall');
    label.innerHTML = parseInt(label.innerHTML) - b;
    var label = document.getElementById('gw');
    label.innerHTML = parseInt(label.innerHTML) - c;

}
</code>```

答:
Your code works fine, it's just that you have a mistake here

```<code><span class= id="wall">1000</span></p>
</code>```

Remove the class= if you don't need it or add a class.

Regarding your inquiry about value checkers. I created a code snippet to help you out.

```<code>function send(){
    var labelWall = document.getElementById('wall');
    var labelGW = document.getElementById('gw');
    var wallValue = parseInt(labelWall.innerHTML, 10);
    var GWValue = parseInt(labelGW.innerHTML, 10);
    var b = 500;

    if(wallValue > 0 && GWValue > 0) {
        labelGW.innerHTML = GWValue - b;
        labelWall.innerHTML = wallValue - b;
    }
}
</code>```

Here's the pen

Title: JS Not showing wrong result UPDATED

Body:
Instead of 39500 output i get 500. Could someone help me, i want IF gw reaches 0, there should be no more -500 on wall.

I used my code but it is not working.
HTML

Infantry: 40000

Fort: 1000

<button class="troops" onclick="send()">SEND TROOPS</button>

JS

function send(){
    var a = document.getElementById('gw').innerHTML;
    var b = 500;
    var c = a-b;

    var label = document.getElementById('wall');
    label.innerHTML = parseInt(label.innerHTML) - b;
    var label = document.getElementById('gw');
    label.innerHTML = parseInt(label.innerHTML) - c;

}

Body:
Your code works fine, it's just that you have a mistake here

<span class= id="wall">1000</span></p>

Remove the class= if you don't need it or add a class.

Regarding your inquiry about value checkers. I created a code snippet to help you out.

function send(){
    var labelWall = document.getElementById('wall');
    var labelGW = document.getElementById('gw');
    var wallValue = parseInt(labelWall.innerHTML, 10);
    var GWValue = parseInt(labelGW.innerHTML, 10);
    var b = 500;

    if(wallValue > 0 && GWValue > 0) {
        labelGW.innerHTML = GWValue - b;
        labelWall.innerHTML = wallValue - b;
    }
}

Here's the pen


问:
How do I add a button to the footer of a section of a table view?
I would like to add a button to the footer of my table view (or at least make the whole thing clickable). How would I go about doing this? Thanks in advance!</p>

答:
Per Apple's Docs you must implement the heightForFooterInSection method, otherwise your viewForFooterInSection wouldn't do anything.

Swift 3

```<code>override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 100
}

func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {

guard section == 0 else { return nil } // Can remove if want button for all sections

let footerView = UIView(frame: CGRect(0, 0, 320, 40))
        let myButton = UIButton(type: .custom)

        myButton.setTitle("My Button", for: .normal)
        myButton.addTarget(self, action: #selector(myAction(_:)), for: .touchUpInside)

        myButton.setTitleColor(UIColor.black, for: .normal) //set the color this is may be different for iOS 7
        myButton.frame = CGRect(0, 0, 130, 30) //set some large width to ur title
        footerView.addSubview(myButton)
        return footerView;

}

func myAction(_ sender : AnyObject) {

}
</code>```

Objective-C

```<code>- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
      return 100.0f;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if(section == 0) //Decide which footer according to your logic
    {
       UIView *footerView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 40)];
       UIButton *myButton=[UIButton buttonWithType:UIButtonTypeCustom];
       [myButton setTitle:@"Add to other" forState:UIControlStateNormal];
       [myButton addTarget:self action:@selector(myAction:) forControlEvents:UIControlEventTouchUpInside];
       [myButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];//set the color this is may be different for iOS 7
       myButton.frame=CGRectMake(0, 0, 130, 30); //set some large width to ur title
       [footerView addSubview: myButton];
       return footerView;
    }
}

- (void)myAction:(id)sender
{
      NSLog(@"add to charity");
}
</code>```

Body:
Per Apple's Docs you must implement the heightForFooterInSection method, otherwise your viewForFooterInSection wouldn't do anything.

Swift 3

override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 100
}

func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {

guard section == 0 else { return nil } // Can remove if want button for all sections

let footerView = UIView(frame: CGRect(0, 0, 320, 40))
        let myButton = UIButton(type: .custom)

        myButton.setTitle("My Button", for: .normal)
        myButton.addTarget(self, action: #selector(myAction(_:)), for: .touchUpInside)

        myButton.setTitleColor(UIColor.black, for: .normal) //set the color this is may be different for iOS 7
        myButton.frame = CGRect(0, 0, 130, 30) //set some large width to ur title
        footerView.addSubview(myButton)
        return footerView;

}

func myAction(_ sender : AnyObject) {

}

Objective-C

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
      return 100.0f;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if(section == 0) //Decide which footer according to your logic
    {
       UIView *footerView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 40)];
       UIButton *myButton=[UIButton buttonWithType:UIButtonTypeCustom];
       [myButton setTitle:@"Add to other" forState:UIControlStateNormal];
       [myButton addTarget:self action:@selector(myAction:) forControlEvents:UIControlEventTouchUpInside];
       [myButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];//set the color this is may be different for iOS 7
       myButton.frame=CGRectMake(0, 0, 130, 30); //set some large width to ur title
       [footerView addSubview: myButton];
       return footerView;
    }
}

- (void)myAction:(id)sender
{
      NSLog(@"add to charity");
}


问:
Capture API works bad in dark especially in night time or in previewing dark corners through camera
I was using this library which is https://github.com/CosmicMind/Material. Everything is already working well aside from one which requires a bit of optimization,

I've tried this one which works pretty well with improved lighting in the dark, it is pretty much useful for devices that don't have flash such as iPads.

https://github.com/ooper-shlab/AVCamManual-Swift

I can't seem to get where the lighting optimization happens in the code. I would've help if I have figured out.

The preview really would look a lot darker using the Capture API of material.

Screenshots of each can be seen below:
The demo for Material's Capture Api:

The demo for AVFoundation:

答:
So after trying to do some trial and error on the code of AVFoundation.
Commenting codes until I could see which block of code is responsible for the lighting.
I was able to find out that it was the AVCaptureSession.sessionPreset which was originally set to  = AVCaptureSessionPresetHigh, after setting it to

AVCaptureSession.sessionPreset = AVCaptureSessionPresetPhoto

Now it's better and looks like the default on ios camera app.


问:
Unable to setup NServiceBus v5 multi-tenant saga example as a hosted service
I've looked over the NServiceBus documentation and have run the sample for setting up multiple tenants to keep the saga data in individual databases for each tenant.

https://docs.particular.net/samples/outbox/multi-tenant/?version=core_5

I currently have an NServiceBus application using the NServiceBus.Host package and is running as a Windows Service. It is sharing a single saga data table among several tenants so thought it would be simple to convert the sample to be hosted so I could see how I need to proceed to convert my existing project to multi-tenant SQL connections. However, the example uses a console application and a manually created bus.

If I add the NServiceBus.Host NuGet package to the sample application an EndpointConfig.cs file is added as I expect but I can't figure out how to work with the Pipeline Executor.

In the Receiver project in Program.cs there is this:

```<code>internal static PipelineExecutor PipelineExecutor;

var busConfiguration = new BusConfiguration();
PipelineExecutor = ((UnicastBus) startableBus).Builder.Build<PipelineExecutor>();
</code>```

However, you obviously can't do that inside EnpointConfig.cs of a hosted application.

Next if you view MultiTenantOpenSqlConnectionBehavior.cs in the Invoke method you have access to the context IncomingContext context where the individual client connections are stuffed into the context with their corresponding keys and the next pipeline step is executed via next();

```<code>class MultiTenantOpenSqlConnectionBehavior :
    IBehavior<IncomingContext>
{

    public void Invoke(IncomingContext context, Action next)
    {
        var defaultConnectionString = ConfigurationManager.ConnectionStrings["NServiceBus/Persistence"]
            .ConnectionString;
        #region OpenTenantDatabaseConnection

        string tenant;
        if (!context.PhysicalMessage.Headers.TryGetValue("TenantId", out tenant))
        {
            throw new InvalidOperationException("No tenant id");
        }
        var connectionString = ConfigurationManager.ConnectionStrings[tenant]
            .ConnectionString;
        var lazyConnection = new Lazy<IDbConnection>(() =>
        {
            var connection = new SqlConnection(connectionString);
            connection.Open();
            return connection;
        });
        var key = $"LazySqlConnection-{defaultConnectionString}";
        context.Set(key, lazyConnection);
        try
        {
            next();
        }
        finally
        {
            if (lazyConnection.IsValueCreated)
            {
                lazyConnection.Value.Dispose();
            }
            context.Remove(key);
        }

        #endregion
    }
}
</code>```

Then in MultiTenantConnectionProvider.cs, the static PipelineExecutor declared above is referenced and with that context the connection can be retrieved with the same key that was set in the above class.

```<code>class MultiTenantConnectionProvider :
    DriverConnectionProvider
{

    public override IDbConnection GetConnection()
    {
        var defaultConnectionString = ConfigurationManager.ConnectionStrings["NServiceBus/Persistence"]
            .ConnectionString;

        #region GetConnectionFromContext

        Lazy<IDbConnection> lazy;

        //
        // This line is the problem. The static Program.PipelineExecutor is accessed
        //
        var pipelineExecutor = Program.PipelineExecutor;

        var key = $"LazySqlConnection-{defaultConnectionString}";
        if (
            pipelineExecutor != null &&
            pipelineExecutor.CurrentContext.TryGet(key, out lazy))
        {
            var connection = Driver.CreateConnection();
            connection.ConnectionString = lazy.Value.ConnectionString;
            connection.Open();
            return connection;
        }
        return base.GetConnection();

        #endregion
    }
}
</code>```

Surely there has to be a way to do this in a hosted application but I can't find any information on how to do this.

答:
Unfortunately the NServiceBus Host does not support multi tenant scenarios. Instead you can take that sample use a self hosted service https://docs.particular.net/nservicebus/hosting/windows-service

The code is fairly trivial

Body:
I've looked over the NServiceBus documentation and have run the sample for setting up multiple tenants to keep the saga data in individual databases for each tenant.

https://docs.particular.net/samples/outbox/multi-tenant/?version=core_5

I currently have an NServiceBus application using the NServiceBus.Host package and is running as a Windows Service. It is sharing a single saga data table among several tenants so thought it would be simple to convert the sample to be hosted so I could see how I need to proceed to convert my existing project to multi-tenant SQL connections. However, the example uses a console application and a manually created bus.

If I add the NServiceBus.Host NuGet package to the sample application an EndpointConfig.cs file is added as I expect but I can't figure out how to work with the Pipeline Executor.

In the Receiver project in Program.cs there is this:

internal static PipelineExecutor PipelineExecutor;

var busConfiguration = new BusConfiguration();
PipelineExecutor = ((UnicastBus) startableBus).Builder.Build<PipelineExecutor>();

However, you obviously can't do that inside EnpointConfig.cs of a hosted application.

Next if you view MultiTenantOpenSqlConnectionBehavior.cs in the Invoke method you have access to the context IncomingContext context where the individual client connections are stuffed into the context with their corresponding keys and the next pipeline step is executed via next();

class MultiTenantOpenSqlConnectionBehavior :
    IBehavior<IncomingContext>
{

    public void Invoke(IncomingContext context, Action next)
    {
        var defaultConnectionString = ConfigurationManager.ConnectionStrings["NServiceBus/Persistence"]
            .ConnectionString;
        #region OpenTenantDatabaseConnection

        string tenant;
        if (!context.PhysicalMessage.Headers.TryGetValue("TenantId", out tenant))
        {
            throw new InvalidOperationException("No tenant id");
        }
        var connectionString = ConfigurationManager.ConnectionStrings[tenant]
            .ConnectionString;
        var lazyConnection = new Lazy<IDbConnection>(() =>
        {
            var connection = new SqlConnection(connectionString);
            connection.Open();
            return connection;
        });
        var key = $"LazySqlConnection-{defaultConnectionString}";
        context.Set(key, lazyConnection);
        try
        {
            next();
        }
        finally
        {
            if (lazyConnection.IsValueCreated)
            {
                lazyConnection.Value.Dispose();
            }
            context.Remove(key);
        }

        #endregion
    }
}

Then in MultiTenantConnectionProvider.cs, the static PipelineExecutor declared above is referenced and with that context the connection can be retrieved with the same key that was set in the above class.

class MultiTenantConnectionProvider :
    DriverConnectionProvider
{

    public override IDbConnection GetConnection()
    {
        var defaultConnectionString = ConfigurationManager.ConnectionStrings["NServiceBus/Persistence"]
            .ConnectionString;

        #region GetConnectionFromContext

        Lazy<IDbConnection> lazy;

        //
        // This line is the problem. The static Program.PipelineExecutor is accessed
        //
        var pipelineExecutor = Program.PipelineExecutor;

        var key = $"LazySqlConnection-{defaultConnectionString}";
        if (
            pipelineExecutor != null &&
            pipelineExecutor.CurrentContext.TryGet(key, out lazy))
        {
            var connection = Driver.CreateConnection();
            connection.ConnectionString = lazy.Value.ConnectionString;
            connection.Open();
            return connection;
        }
        return base.GetConnection();

        #endregion
    }
}

Surely there has to be a way to do this in a hosted application but I can't find any information on how to do this.


问:
R postgres connection to remote survey error in RS-DBI driver
i cannot for the life of me get postgres connection a remote postgres db.

```<code>"Error in postgresqlNewConnection(drv, ...) :
  RS-DBI driver: (could not connect"
</code>```

I have RPostgreSQL installed, i have postgres running in the background, my macbook is up to date 10.12.5 macOS sierra.

and still cannot connect

```<code>  drv <- dbDriver("RPostgreSQL")
 > con <- dbConnect(drv, host=hostName,
 +                  port=portName,
+                  dbname=databaseName,
+                  user=userName,
+                  password=passwordName)
Error in postgresqlNewConnection(drv, ...) :
  RS-DBI driver: (could not connect
</code>```

notably..i CAN connect with all the same credentials via postico app.

答:
I had the same problem. I ended up using the RPostgres package.

Disclaimer: I wan't able to install the package by following the git_hub instructions exactly;

Here is what I did to successfully install it on windows:

1) Install Rtools following the instructions here:

2) Install devtools:

```<code>install.packages("devtools")
</code>```

3) Install Rcpp and DBI as the instruction:

```<code>devtools::install_github("RcppCore/Rcpp")
devtools::install_github("rstats-db/DBI")
</code>```

4) Download the RPostgres source file on github by clicking clone and download; Extract it to a folder;

5) Install RPostgres from the source folder:

```<code>install.packages("path_to_downloads/Downloads/RPostgres-master/", repos = NULL, type="source")
</code>```

Body:
i cannot for the life of me get postgres connection a remote postgres db.

"Error in postgresqlNewConnection(drv, ...) :
  RS-DBI driver: (could not connect"

I have RPostgreSQL installed, i have postgres running in the background, my macbook is up to date 10.12.5 macOS sierra.

and still cannot connect

  drv <- dbDriver("RPostgreSQL")
 > con <- dbConnect(drv, host=hostName,
 +                  port=portName,
+                  dbname=databaseName,
+                  user=userName,
+                  password=passwordName)
Error in postgresqlNewConnection(drv, ...) :
  RS-DBI driver: (could not connect

notably..i CAN connect with all the same credentials via postico app.

Body:
I had the same problem. I ended up using the RPostgres package.

Disclaimer: I wan't able to install the package by following the git_hub instructions exactly;

Here is what I did to successfully install it on windows:

1) Install Rtools following the instructions here:

2) Install devtools:

install.packages("devtools")

3) Install Rcpp and DBI as the instruction:

devtools::install_github("RcppCore/Rcpp")
devtools::install_github("rstats-db/DBI")

4) Download the RPostgres source file on github by clicking clone and download; Extract it to a folder;

5) Install RPostgres from the source folder:

install.packages("path_to_downloads/Downloads/RPostgres-master/", repos = NULL, type="source")


问:
XCode9-beta: Implicit declaration of function 'sqlite3_key'
I am having an issue with EncryptedStore SQLCipher wrapper to encrypt core data.

I've added C-flags for this as:

```<code>Debug = -DSQLITE_HAS_CODEC -DSQLITE_TEMP_STORE=2 -DSQLITE_THREADSAFE -DSQLCIPHER_CRYPTO_CC
Release = -DSQLITE_HAS_CODEC -DNDEBUG -DSQLITE_OS_UNIX=1 -DSQLITE_TEMP_STORE=2 -DSQLITE_THREADSAFE -DSQLCIPHER_CRYPTO_CC
</code>```

And used it as:

```<code>func encryptedCoordinator() -> NSPersistentStoreCoordinator {
  var coordinator:NSPersistentStoreCoordinator?
  let ops:[String : Any] =    [NSMigratePersistentStoresAutomaticallyOption:(true),                                              NSInferMappingModelAutomaticallyOption:(true), EncryptedStorePassphraseKey:sqlCipherKey, EncryptedStoreDatabaseLocation:self.sqliteFileURL()]

  do {
      coordinator = try EncryptedStore.make(options: ops, managedObjectModel: self.managedObjectModel, error: ())
    }catch {
      fatalError("Error opening encrypted DB: \(error)")
    }
    return coordinator!
  }
</code>```

It is working fine in XCode8, but it's giving error in XCode9-beta.

Error line:

```<code>- (BOOL)changeDatabasePassphrase:(NSString *)passphrase error:(NSError *__autoreleasing*)error {
  BOOL result;
  int status;
  if ([passphrase length] > 0) {
    // Password provided, use it to key the DB
    const char *string = [passphrase UTF8String];
    status = sqlite3_rekey(database, string, (int)strlen(string));//ERROR line
    string = NULL;
    passphrase = nil;
  } else {
    // No password
    status = SQLITE_OK;
  }
  result = status == SQLITE_OK;
  if (result) {
    result = [self checkDatabaseStatusWithError:error];
  }
return result && (*error == nil);
}
</code>```

Function is declared in EncryptedStroe/sqlite3.h as:

```<code>SQLITE_API int sqlite3_rekey(
sqlite3 *db,                   /* Database to be rekeyed */
  const void *pKey, int nKey     /* The new key */
);
SQLITE_API int sqlite3_rekey_v2(
  sqlite3 *db,                   /* Database to be rekeyed */
  const char *zDbName,           /* Name of the database */
  const void *pKey, int nKey     /* The new key */
);
</code>```

答:
I think the problem is the import EncryptedStore.m file does:

 #import <sqlite3.h>

It uses <> so the system sqlite library is imported, which doesn't include these functions. By changing <> with "" everything compiles fine.

Body:
I am having an issue with EncryptedStore SQLCipher wrapper to encrypt core data.

I've added C-flags for this as:

Debug = -DSQLITE_HAS_CODEC -DSQLITE_TEMP_STORE=2 -DSQLITE_THREADSAFE -DSQLCIPHER_CRYPTO_CC
Release = -DSQLITE_HAS_CODEC -DNDEBUG -DSQLITE_OS_UNIX=1 -DSQLITE_TEMP_STORE=2 -DSQLITE_THREADSAFE -DSQLCIPHER_CRYPTO_CC

And used it as:

func encryptedCoordinator() -> NSPersistentStoreCoordinator {
  var coordinator:NSPersistentStoreCoordinator?
  let ops:[String : Any] =    [NSMigratePersistentStoresAutomaticallyOption:(true),                                              NSInferMappingModelAutomaticallyOption:(true), EncryptedStorePassphraseKey:sqlCipherKey, EncryptedStoreDatabaseLocation:self.sqliteFileURL()]

  do {
      coordinator = try EncryptedStore.make(options: ops, managedObjectModel: self.managedObjectModel, error: ())
    }catch {
      fatalError("Error opening encrypted DB: \(error)")
    }
    return coordinator!
  }

It is working fine in XCode8, but it's giving error in XCode9-beta.

Error line:

- (BOOL)changeDatabasePassphrase:(NSString *)passphrase error:(NSError *__autoreleasing*)error {
  BOOL result;
  int status;
  if ([passphrase length] > 0) {
    // Password provided, use it to key the DB
    const char *string = [passphrase UTF8String];
    status = sqlite3_rekey(database, string, (int)strlen(string));//ERROR line
    string = NULL;
    passphrase = nil;
  } else {
    // No password
    status = SQLITE_OK;
  }
  result = status == SQLITE_OK;
  if (result) {
    result = [self checkDatabaseStatusWithError:error];
  }
return result && (*error == nil);
}

Function is declared in EncryptedStroe/sqlite3.h as:

SQLITE_API int sqlite3_rekey(
sqlite3 *db,                   /* Database to be rekeyed */
  const void *pKey, int nKey     /* The new key */
);
SQLITE_API int sqlite3_rekey_v2(
  sqlite3 *db,                   /* Database to be rekeyed */
  const char *zDbName,           /* Name of the database */
  const void *pKey, int nKey     /* The new key */
);


问:
Configuring ActiveMQ: How to Send a Message to an Apache ActiveMQ Queue with Node.js
I have a JAVA api which needs to consume data from ActiveMQ.

Client has provided me the host,Port and API key details.

Im a newby in this ActiveMQ and need suggestion on how to establish the initial queue connection since the queue works on tcp protocol.

I was suggested to use one of the client libraries supported by activeMQ in various languages

Currently i am referring :  http://activemq.apache.org/cross-language-clients.html

Need suggestion on how to configure or execute (if i use "How to Send a Message to an Apache ActiveMQ Queue with Node.js" from the above link) on the below code.

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

stompit.connect({ host: 'localhost', port: 61613 }, (err, client) => {
const frame = client.send({ destination: 'SampleQueue' });

frame.write('Simples Assim');

frame.end();

client.disconnect();
 });
</code>```

Assuming i don't have any Node environment setup in my machine.

答:
You can listen to or send messages to ActiveMQ using the STOMP protocol. Just use the example from https://github.com/gdaws/node-stomp
 (and you definitely need to install Nodejs on the machine that will be running that script).

I'm not sure of how your workflow is with the Java API, but if that API sends some message to ActiveMQ and you need to deal with that message, you can use stompit. All you need to do is subscribe to the queue in which the message is stored. If you need to send a reply message, you can do so as well to any queue you wish.

Body:
I have a JAVA api which needs to consume data from ActiveMQ.

Client has provided me the host,Port and API key details.

Im a newby in this ActiveMQ and need suggestion on how to establish the initial queue connection since the queue works on tcp protocol.

I was suggested to use one of the client libraries supported by activeMQ in various languages

Currently i am referring :  http://activemq.apache.org/cross-language-clients.html

Need suggestion on how to configure or execute (if i use "How to Send a Message to an Apache ActiveMQ Queue with Node.js" from the above link) on the below code.

const stompit = require('stompit');

stompit.connect({ host: 'localhost', port: 61613 }, (err, client) => {
const frame = client.send({ destination: 'SampleQueue' });

frame.write('Simples Assim');

frame.end();

client.disconnect();
 });

Assuming i don't have any Node environment setup in my machine.


问:
Write a loop for my function in r
I am currently trying to write my first loop for lagged regressions on 30 variables. Variables are labeled as rx1, rx2.... rx3, and the data frame is called my_num_data.

I have created a loop that looks like this:

```<code>z <- zoo(my_num_data)

for (i in 1:30)
{dyn$lm(my_num_data$rx[i] ~ lag(my_num_data$rx[i], 1)
        + lag(my_num_data$rx[i], 2))
}
</code>```

But I received an error message:

Error in model.frame.default(formula = dyn(my_num_data$rx[i] ~ lag(my_num_data$rx[i],  :
        invalid type (NULL) for variable 'my_num_data$rx[i]'

Can anyone tell me what the problem is with the loop?

Thanks!

答:
This produces a list, L, whose ith component has the name of the ith column of z and whose content is the regression of the ith column of z on its first two lags.  Lag is same as lag except for a reversal of argument k's sign.

```<code>library(dyn)
z <- zoo(anscombe) # test input using builtin data.frame anscombe

Lag <- function(x, k) lag(x, -k)
L <- lapply(as.list(z), function(x) dyn$lm(x ~ Lag(x, 1:2)))
</code>```

Title: Write a loop for my function in r

Body:
I am currently trying to write my first loop for lagged regressions on 30 variables. Variables are labeled as rx1, rx2.... rx3, and the data frame is called my_num_data.

I have created a loop that looks like this:

z <- zoo(my_num_data)

for (i in 1:30)
{dyn$lm(my_num_data$rx[i] ~ lag(my_num_data$rx[i], 1)
        + lag(my_num_data$rx[i], 2))
}

But I received an error message:

Error in model.frame.default(formula = dyn(my_num_data$rx[i] ~ lag(my_num_data$rx[i],  :
        invalid type (NULL) for variable 'my_num_data$rx[i]'

Can anyone tell me what the problem is with the loop?

Thanks!

Body:
This produces a list, L, whose ith component has the name of the ith column of z and whose content is the regression of the ith column of z on its first two lags.  Lag is same as lag except for a reversal of argument k's sign.

library(dyn)
z <- zoo(anscombe) # test input using builtin data.frame anscombe

Lag <- function(x, k) lag(x, -k)
L <- lapply(as.list(z), function(x) dyn$lm(x ~ Lag(x, 1:2)))


问:
Azure Bot Service set node.js version not working
Specifying a Node.js version in Azure Bot Service doesn't seem to work.

In Azure portal, navigate to the bot service instance, then in application settings set the environment variable WEBSITE_NODE_DEFAULT_VERSION to 7.7.4, which is the highest version available as of 22/05/2017. However it turns out the node.js runtime is still v6.5.0!

In Kudu -> Environment it shows:

```<code>WEBSITE_NODE_DEFAULT_VERSION = 7.7.4
</code>```

and

```<code>Path = D:\home\site\deployments\tools;... D:\Program Files (x86)\nodejs\7.7.4;...
</code>```

Couldn't find where this v6.5.0 node.js version was set. Maybe in IIS settings? It would be good if azure bot service allows to use customized node.js version rather than the system provided lag version. So is there a fix or work-around? Thanks.

答:
For other people who want to customize their node.js version for their bots, I've found a way: use Azure App Service instead of Azure Bot Service. Here is how:

Create your Azure app from the Azure portal, and choose the node.js template

(optional) Configure Continuous Delivery

Register your app in Bot Framework portal

start Kudu Cmd console

cd D:\home\site\wwwroot

md bin

cd bin

then download the node.js version you like, e.g.

```<code>curl -O http://nodejs.org/dist/latest/win-x64/node.exe
</code>```

Using Kudu, modify D:\home\site\wwwroot\web.config to point to your entry .js file (default is server.js) and add the following line:

<iisnode watchedFiles="web.config;*.js"
    nodeProcessCommandLine=""D:\home\site\wwwroot\bin\node.exe""
/>```

Following the steps above, you are no longer restricted by the locked node v6.5, and use the latest node.js feature as you wish.

Body:
Specifying a Node.js version in Azure Bot Service doesn't seem to work.

In Azure portal, navigate to the bot service instance, then in application settings set the environment variable WEBSITE_NODE_DEFAULT_VERSION to 7.7.4, which is the highest version available as of 22/05/2017. However it turns out the node.js runtime is still v6.5.0!

In Kudu -> Environment it shows:

WEBSITE_NODE_DEFAULT_VERSION = 7.7.4

and

Path = D:\home\site\deployments\tools;... D:\Program Files (x86)\nodejs\7.7.4;...

Couldn't find where this v6.5.0 node.js version was set. Maybe in IIS settings? It would be good if azure bot service allows to use customized node.js version rather than the system provided lag version. So is there a fix or work-around? Thanks.

Body:
For other people who want to customize their node.js version for their bots, I've found a way: use Azure App Service instead of Azure Bot Service. Here is how:

Create your Azure app from the Azure portal, and choose the node.js template

(optional) Configure Continuous Delivery

Register your app in Bot Framework portal

start Kudu Cmd console

cd D:\home\site\wwwroot

md bin

cd bin

then download the node.js version you like, e.g.

curl -O http://nodejs.org/dist/latest/win-x64/node.exe

Using Kudu, modify D:\home\site\wwwroot\web.config to point to your entry .js file (default is server.js) and add the following line:

<iisnode watchedFiles="web.config;*.js"
    nodeProcessCommandLine="&quot;D:\home\site\wwwroot\bin\node.exe&quot;"
/>

Following the steps above, you are no longer restricted by the locked node v6.5, and use the latest node.js feature as you wish.


问:
Using jQuery I need to replace spaces inside href with hyphens
I have a list of links that direct to a page which corresponds to each of the 50 states in the US.

I am looping through each states in an array and adding it the href for each but for states that contain two words I need to replaces the space (' ') between them with a hyphen('-').

example: New York must be replaced with New-York.

href="http://www.projectknow.com/find/New York/" class="spaces">

MUST BE REPLACED WITH

href="http://www.projectknow.com/find/New-York/" class="spaces">

This is what I got so far but it does NOT work. Still new to jQuery and any help would be greatly appreciated.

```<code>var option = '';
for (var i = 0; i < states.length;i++){
    option += '<li><a href="http://www.states.com/find/'+ states[i] +'/"
    class="spaces">'+ states[i] +'</a></li>';
}

$('.menu').append(option);

$("a.spaces").each(function (){
    $(this).attr('href', $(this).attr("href").replace("","-"));
});
</code>```

答:
Maybe you can replace it before add it to a link tag then you don't need to handle it after added, like this way:

var option = '';
for (var i = 0; i < states.length;i++){
   var state = states[i].replace(/ /g, '-');
   option += '
'+ states[i] +'
';
}```

Body:
I have a list of links that direct to a page which corresponds to each of the 50 states in the US.

I am looping through each states in an array and adding it the href for each but for states that contain two words I need to replaces the space (' ') between them with a hyphen('-').

example: New York must be replaced with New-York.

MUST BE REPLACED WITH

This is what I got so far but it does NOT work. Still new to jQuery and any help would be greatly appreciated.

var option = '';
for (var i = 0; i < states.length;i++){
    option += '
'+ states[i] +'
';
}

$('.menu').append(option);

$("a.spaces").each(function (){
    $(this).attr('href', $(this).attr("href").replace("","-"));
});

Body:
Maybe you can replace it before add it to a link tag then you don't need to handle it after added, like this way:

var option = '';
for (var i = 0; i < states.length;i++){
   var state = states[i].replace(/ /g, '-');
   option += '<li><a href="http://www.states.com/find/'+ state +'/" class="spaces">'+ states[i] +'</a></li>';
}


问:
Issue parsing variable from HTML with bs4
Im trying to parse the "value" of variable ( __VIEWSTATEGENERATOR ), here's the HTML code ::

```<code><div>
<input id="__VIEWSTATEGENERATOR" name="__VIEWSTATEGENERATOR" type="hidden" value="1434571F"/>
</div>
</code>```

Here's the code I am attempting to do that with ::

```<code>viewstategenerator = soup.findAll("input", {"type": "hidden", "name": "__VIEWSTATEGENERATOR"})
</code>```

I then execute:: print(viewstategenerator), and I get the following string for my variable:

```<code>>>> print(viewstategenerator)
[<input id="__VIEWSTATEGENERATOR" name="__VIEWSTATEGENERATOR" type="hidden" value="1434571F"/>]
</code>```

I was expecting to grab just the value of "1434571F", not sure why that is... Any help would be highly appreciated!!

答:
It looks like you're close but just a tad confused about the BeautifulSoup API.

soup.findAll returns a list of all of the DOM elements that match the query you gave it. Seeing as only one element on the page can match your query, you should use soup.find instead. To get the value of the value attribute of your input element, use ['value'].

```<code>from bs4 import BeautifulSoup as Soup

html = """
<div>
<input id="__VIEWSTATEGENERATOR" name="__VIEWSTATEGENERATOR" type="hidden" value="1434571F"/>
</div>
"""

soup = Soup(html, 'lxml') # Use whatever parser you're already using.

viewstategenerator = soup.find("input", {"type": "hidden", "name": "__VIEWSTATEGENERATOR"})
print(viewstategenerator['value'])
# Prints 1434571F
</code>```

Body:
Im trying to parse the "value" of variable ( __VIEWSTATEGENERATOR ), here's the HTML code ::

<input id="__VIEWSTATEGENERATOR" name="__VIEWSTATEGENERATOR" type="hidden" value="1434571F"/>

Here's the code I am attempting to do that with ::

viewstategenerator = soup.findAll("input", {"type": "hidden", "name": "__VIEWSTATEGENERATOR"})

I then execute:: print(viewstategenerator), and I get the following string for my variable:

>>> print(viewstategenerator)
[<input id="__VIEWSTATEGENERATOR" name="__VIEWSTATEGENERATOR" type="hidden" value="1434571F"/>]

I was expecting to grab just the value of "1434571F", not sure why that is... Any help would be highly appreciated!!

Body:
It looks like you're close but just a tad confused about the BeautifulSoup API.

soup.findAll returns a list of all of the DOM elements that match the query you gave it. Seeing as only one element on the page can match your query, you should use soup.find instead. To get the value of the value attribute of your input element, use ['value'].

from bs4 import BeautifulSoup as Soup

html = """
<div>
<input id="__VIEWSTATEGENERATOR" name="__VIEWSTATEGENERATOR" type="hidden" value="1434571F"/>
</div>
"""

soup = Soup(html, 'lxml') # Use whatever parser you're already using.

viewstategenerator = soup.find("input", {"type": "hidden", "name": "__VIEWSTATEGENERATOR"})
print(viewstategenerator['value'])
# Prints 1434571F


问:
How to use cv2.findHomography() with Squeezed Images
I am using the python bindings for opencv. I am using keypoint detection and description (ie SURF, SIFT,...) to find a template image contained within a target image, but there is a catch: the template can be "squeezed" in the target image, so that the aspect ratio is different than the target image.

This does not work with findHomography(), since it assumes a simple perspective transform, which cannot have this sort of stretching.

Are there any ways to do this? I have thought about incrementally stretching the target image different amounts to change the aspect ratio, and using findHomography at each iteration, but as far as I can tell there is no way of comparing the quality of a fit (since I'm using RANSAC to find the best fit), so I can't tell at which squeeze level it fits best.

Perhaps counting the number of points that matched correctly from the RANSAC by looking at the length of the returned mask? This seems sorta gross.

答:
This does not work with findHomography(), since it assumes a simple perspective transform, which cannot have this sort of stretching.

This is not true; even an affine warp includes stretching the aspect ratios and even shear distortion, and homographies expand this by even non-uniform distortions. For example, the affine transformation given by the matrix

```<code>2 0 0
0 1 0
</code>```

will stretch an image horizontally by a factor of two, as seen with this short program:

```<code>import cv2
import numpy as np

img = cv2.imread('lena.png')
affine_warp = np.array([[2, 0, 0], [0, 1, 0]], dtype=np.float32)
dsize = (img.shape[1]*2, img.shape[0])
warped_img = cv2.warpAffine(img, affine_warp, dsize)

cv2.imshow("2x Horizontal Stretching", warped_img)
cv2.waitKey(0)
</code>```

Producing the output:

So that is not your issue. Homographies allow even stronger warping. Are you running RANSAC yourself or letting the findHomography() function decide your points via RANSAC? Please post your expected output and your current code, possibly in a new question that reflects the problems you're facing.

Body:
This does not work with findHomography(), since it assumes a simple perspective transform, which cannot have this sort of stretching.

This is not true; even an affine warp includes stretching the aspect ratios and even shear distortion, and homographies expand this by even non-uniform distortions. For example, the affine transformation given by the matrix

2 0 0
0 1 0

will stretch an image horizontally by a factor of two, as seen with this short program:

import cv2
import numpy as np

img = cv2.imread('lena.png')
affine_warp = np.array([[2, 0, 0], [0, 1, 0]], dtype=np.float32)
dsize = (img.shape[1]*2, img.shape[0])
warped_img = cv2.warpAffine(img, affine_warp, dsize)

cv2.imshow("2x Horizontal Stretching", warped_img)
cv2.waitKey(0)

Producing the output:

So that is not your issue. Homographies allow even stronger warping. Are you running RANSAC yourself or letting the findHomography() function decide your points via RANSAC? Please post your expected output and your current code, possibly in a new question that reflects the problems you're facing.


问:
How to prevent content jumping up when resizing browser?
The image caption and content is held in place by the image. When window is resized or image is loading the page content jumps up and is then jumps back down again.

Is it possible to prevent the content from moving in this way?

```<code><div class="profile">
    <img src="http://lorempixel.com/g/720/720/nature" alt="" />
</div>
</code>```

See https://codepen.io/atoms/pen/bRdLVe

Built on Chris Ferdinandi's Kraken CSS framework.

This seems to do the trick:

```<code>.profile {
    position: relative;
    width: 100%;
    padding-bottom: 100%;
    float: left;
    height: 0;
    }
.profile img {
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
    }
</code>```

and the result:
https://codepen.io/atoms/pen/jwbOYe

Now when you reload the page the text stays in place even when the image has not yet loaded. And you can resize the browser window to reflow the contents with the same result.

Not sure if the CSS is entirely correct but it seems to work.

答:
This depends on if you are going to have consistent image sizes or not. If your images will always be the same size in that spot, you can set a CSS height of the image size on the image (or even your profile div) and that will create the space on the page before the image loads, preventing the jump.

```<code>.profile img { height:250px }
</code>```

If your images will vary in size and you need to avoid distortion, a JS approach like also mentioned here might be a better approach.

Body:
The image caption and content is held in place by the image. When window is resized or image is loading the page content jumps up and is then jumps back down again.

Is it possible to prevent the content from moving in this way?

See https://codepen.io/atoms/pen/bRdLVe

Built on Chris Ferdinandi's Kraken CSS framework.

This seems to do the trick:

.profile {
    position: relative;
    width: 100%;
    padding-bottom: 100%;
    float: left;
    height: 0;
    }
.profile img {
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
    }

and the result:
https://codepen.io/atoms/pen/jwbOYe

Now when you reload the page the text stays in place even when the image has not yet loaded. And you can resize the browser window to reflow the contents with the same result.

Not sure if the CSS is entirely correct but it seems to work.

Body:
This depends on if you are going to have consistent image sizes or not. If your images will always be the same size in that spot, you can set a CSS height of the image size on the image (or even your profile div) and that will create the space on the page before the image loads, preventing the jump.

.profile img { height:250px }

If your images will vary in size and you need to avoid distortion, a JS approach like also mentioned here might be a better approach.


问:
Unity resolution problem when configuring through xml with named registered dependency
I have an interface which takes a generic type

```<code>interface IIFace<T>
</code>```

Then i have several implementations

```<code>public class IFaceImp1 : IIFace<MyObj> {}
public class IFaceImp2 : IIFace<MyObj> {}
</code>```

I defined a viewmodel which gets injected into it an object of this interface for a specific type...

```<code>public MainViewModel(IIFace<MyObj> scrapper) { }
</code>```

And then i configure Unity to populate it

```<code><containers>
    <container>
        <register type="IIFace[MyObj]" mapTo="IFaceImp1">
            <constructor>
                <param name="loc" value="i am just a mock">
                </param>
            </constructor>
        </register>
    </container>
</containers>
</code>```

This works fine
The problem is, now i wanted to create named registrations, so that later i can resolve them by name... So I named it, and created another one first, bu t that didn't work. I reduced the problem to this :

```<code><containers>
    <container>
        <register type="IIFace[MyObj]" mapTo="IFaceImp1" name="FirstImplementation">
            <constructor>
                <param name="loc" value="i am just a mock">
                </param>
            </constructor>
        </register>
    </container>
</containers>
</code>```

Which also doesn't work... wh en trying to Resolve<>("FirstImplementation"). However, if I remove the name attribute and use the Resolve<>() overload, it works fine..
Any ideas about what could be happening, that having a name this doesn't work??

答:
Ok, i found out what was the problem
I needed to use the  tag, building my object model in the xml
the end result is something similar to this :

```<code><containers>
    <container>

        <register type="ViewModelBase" mapTo="MainViewModel" name="MockMainViewModel">
          <constructor>
            <param name="imp">
              <dependency name="FirstImplementation" />
            </param>
          </constructor>
        </register>

        <register type="IIFace[MyObj]" mapTo="IFaceImp1" name="FirstImplementation">
            <constructor>
                <param name="loc" value="i am just a mock">
                </param>
            </constructor>
        </register>
    </container>
</containers>
</code>```

This way, this configuration is telling Unity to, when called with Resolve("MockMainViewModel"), instantiate it, and resolve (through dependency too) the parameter that needs in its constructor, with the specified name ("FirstImplementation")
I was basically unaware of the  tag, but anyway this may be useful to someone that comes up with the same problem and doesn't know why the resolution fails to work automatically, and what's the right approach.

Body:
I have an interface which takes a generic type

interface IIFace<T>

Then i have several implementations

public class IFaceImp1 : IIFace<MyObj> {}
public class IFaceImp2 : IIFace<MyObj> {}

I defined a viewmodel which gets injected into it an object of this interface for a specific type...

public MainViewModel(IIFace<MyObj> scrapper) { }

And then i configure Unity to populate it

<containers>
    <container>
        <register type="IIFace[MyObj]" mapTo="IFaceImp1">
            <constructor>
                <param name="loc" value="i am just a mock">
                </param>
            </constructor>
        </register>
    </container>
</containers>

This works fine
The problem is, now i wanted to create named registrations, so that later i can resolve them by name... So I named it, and created another one first, bu t that didn't work. I reduced the problem to this :

<containers>
    <container>
        <register type="IIFace[MyObj]" mapTo="IFaceImp1" name="FirstImplementation">
            <constructor>
                <param name="loc" value="i am just a mock">
                </param>
            </constructor>
        </register>
    </container>
</containers>

Which also doesn't work... wh en trying to Resolve<>("FirstImplementation"). However, if I remove the name attribute and use the Resolve<>() overload, it works fine..
Any ideas about what could be happening, that having a name this doesn't work??

Body:
Ok, i found out what was the problem
I needed to use the  tag, building my object model in the xml
the end result is something similar to this :

<containers>
    <container>

        <register type="ViewModelBase" mapTo="MainViewModel" name="MockMainViewModel">
          <constructor>
            <param name="imp">
              <dependency name="FirstImplementation" />
            </param>
          </constructor>
        </register>

        <register type="IIFace[MyObj]" mapTo="IFaceImp1" name="FirstImplementation">
            <constructor>
                <param name="loc" value="i am just a mock">
                </param>
            </constructor>
        </register>
    </container>
</containers>

This way, this configuration is telling Unity to, when called with Resolve("MockMainViewModel"), instantiate it, and resolve (through dependency too) the parameter that needs in its constructor, with the specified name ("FirstImplementation")
I was basically unaware of the  tag, but anyway this may be useful to someone that comes up with the same problem and doesn't know why the resolution fails to work automatically, and what's the right approach.


问:
BigQuery is picking the wrong sheet when linking to Google sheet for table loading. What other options to use while loading?
Even if I give link to the second/third sheet in a group of Google sheets, it always picks the first sheet for loading.</p>

答: BigQuery only supports reading from the first sheet/tab for now. There are ongoing work to read from any sheet.</p>


问:
Trying to use filter function on strings
i have the following function and I am trying to make a list containing the 'tweet numbers' of tweets done by DanClark . I am splitting the strings and trying to use the filter function to produce it. I am trying to avoid explicit recursion. i keep getting the following error " 'str' object is not callable" when i try to run "search_tweets(tweets, "DanClark")"</p>

```<code>tweet1 = "#1::@DanClark::The party was amazing"
tweet19 = "#19::@NatalyS::Avoid 401 Toronto area at this time"
tweet50 = "#50::@CBCNews::How Canadian captain gave her team a speech"
tweet14 = "#14::@DanClark::The food was good"
tweet15 = "#15::@DaveLin::Lucky you DanClark"
tweets =   [tweet1, tweet19, tweet50, tweet14, tweet15]

def separator(tweets, item1, item2, tweeter):

part1 = (tweets[item1].split('::'))
part2 = part1[item2]
part3 = part2[1:]

  if part3 == tweeter:
      return (part1[0])[1:]
  else:
      return []

def search_tweets(tweets, tweeter):
  return list(filter((separator(tweets, 0, 1, tweeter)), tweets))
</code>```

答:
Given:

```<code>>>> tweet1 = "#1::@DanClark::The party was amazing"
>>> tweet19 = "#19::@NatalyS::Avoid 401 Toronto area at this time"
>>> tweet50 = "#50::@CBCNews::How Canadian captain gave her team a speech"
>>> tweet14 = "#14::@DanClark::The food was good"
>>> tweet15 = "#15::@DaveLin::Lucky you DanClark"
>>> tweets =   [tweet1, tweet19, tweet50, tweet14, tweet15]
</code>```

You can use filter to search the list tweets for tweets by the first element like so:

```<code>>>> tweeter = '#50'
>>> list(filter(lambda s: s.partition('::')[0]==tweeter, tweets))
['#50::@CBCNews::How Canadian captain gave her team a speech']
</code>```

Or the second element:

```<code>>>> tweeter = '@DanClark'
>>> list(filter(lambda s: s.split('::')[1]==tweeter, tweets))
['#1::@DanClark::The party was amazing', '#14::@DanClark::The food was good']
</code>```

Then if you just want the numbers corresponding to Dan's tweets:

```<code>>>> [e.partition('::')[0] for e in filter(lambda s: s.split('::')[1]==tweeter, tweets)]
['#1', '#14']
</code>```

Body:
i have the following function and I am trying to make a list containing the 'tweet numbers' of tweets done by DanClark . I am splitting the strings and trying to use the filter function to produce it. I am trying to avoid explicit recursion. i keep getting the following error " 'str' object is not callable" when i try to run "search_tweets(tweets, "DanClark")"

tweet1 = "#1::@DanClark::The party was amazing"
tweet19 = "#19::@NatalyS::Avoid 401 Toronto area at this time"
tweet50 = "#50::@CBCNews::How Canadian captain gave her team a speech"
tweet14 = "#14::@DanClark::The food was good"
tweet15 = "#15::@DaveLin::Lucky you DanClark"
tweets =   [tweet1, tweet19, tweet50, tweet14, tweet15]

def separator(tweets, item1, item2, tweeter):

part1 = (tweets[item1].split('::'))
part2 = part1[item2]
part3 = part2[1:]

  if part3 == tweeter:
      return (part1[0])[1:]
  else:
      return []

def search_tweets(tweets, tweeter):
  return list(filter((separator(tweets, 0, 1, tweeter)), tweets))

Body:
Given:

>>> tweet1 = "#1::@DanClark::The party was amazing"
>>> tweet19 = "#19::@NatalyS::Avoid 401 Toronto area at this time"
>>> tweet50 = "#50::@CBCNews::How Canadian captain gave her team a speech"
>>> tweet14 = "#14::@DanClark::The food was good"
>>> tweet15 = "#15::@DaveLin::Lucky you DanClark"
>>> tweets =   [tweet1, tweet19, tweet50, tweet14, tweet15]

You can use filter to search the list tweets for tweets by the first element like so:

>>> tweeter = '#50'
>>> list(filter(lambda s: s.partition('::')[0]==tweeter, tweets))
['#50::@CBCNews::How Canadian captain gave her team a speech']

Or the second element:

>>> tweeter = '@DanClark'
>>> list(filter(lambda s: s.split('::')[1]==tweeter, tweets))
['#1::@DanClark::The party was amazing', '#14::@DanClark::The food was good']

Then if you just want the numbers corresponding to Dan's tweets:

>>> [e.partition('::')[0] for e in filter(lambda s: s.split('::')[1]==tweeter, tweets)]
['#1', '#14']


问:
How do I find the index for the minimum, second to minimum, etc. in a multi-dimensional list in Python?
I currently have the following code that creates an n x n x n list of values. I am using the following code to find the index of the minimum value of the whole list, but I am also interested in finding the second to minimum, third to minimum and so on. Here is the code I am using right now: You can ignore the for loops and such as they all seem to be working properly.

```<code>    ind = np.unravel_index(C.argmin(), C.shape)
</code>```

C is the list that contains the data. Is there a simple way to modify this line of code to find what I am looking for?

答:
You could use np.argsort instead of argmin:

```<code>>>> import numpy as np
>>> arr = np.random.random((20, 20, 20))
>>> nsmallest = 3
>>> np.unravel_index(np.argsort(arr, axis=None)[:nsmallest], arr.shape)
(array([ 3, 16, 12], dtype=int64),
 array([ 2, 15, 15], dtype=int64),
 array([16, 11, 19], dtype=int64))
</code>```

This is however transposed so the first column contains the index for the smallest item: (3, 2, 16), the second the index for the second-to-smallest: (16, 15, 11), ...

Or simply use a loop over the argsort result:

```<code>>>> argsorted = np.argsort(arr, axis=None)
>>> for i in range(nsmallest):
...     print(np.unravel_index(argsorted[i], arr.shape))
(3, 2, 16)
(16, 15, 11)
(12, 15, 19)
</code>```

Body:
I currently have the following code that creates an n x n x n list of values. I am using the following code to find the index of the minimum value of the whole list, but I am also interested in finding the second to minimum, third to minimum and so on. Here is the code I am using right now: You can ignore the for loops and such as they all seem to be working properly.

    ind = np.unravel_index(C.argmin(), C.shape)

C is the list that contains the data. Is there a simple way to modify this line of code to find what I am looking for?

Body:
You could use np.argsort instead of argmin:

>>> import numpy as np
>>> arr = np.random.random((20, 20, 20))
>>> nsmallest = 3
>>> np.unravel_index(np.argsort(arr, axis=None)[:nsmallest], arr.shape)
(array([ 3, 16, 12], dtype=int64),
 array([ 2, 15, 15], dtype=int64),
 array([16, 11, 19], dtype=int64))

This is however transposed so the first column contains the index for the smallest item: (3, 2, 16), the second the index for the second-to-smallest: (16, 15, 11), ...

Or simply use a loop over the argsort result:

>>> argsorted = np.argsort(arr, axis=None)
>>> for i in range(nsmallest):
...     print(np.unravel_index(argsorted[i], arr.shape))
(3, 2, 16)
(16, 15, 11)
(12, 15, 19)