问:
Get Primary Key column name from table in sqlalchemy (Core)
I am using the core of Sqlalchemy so I am not using a declarative base class like in other similar questions.
How to get the primary key of a table using the engine?</p>

答:
So, I just ran into the same problem. You need to create a Table object that reflects the table for which you are looking to find the primary key.

```<code>from sqlalchemy import create_engine, Table, MetaData

dbUrl = 'postgres://localhost:5432/databaseName'   #will be different for different db's

engine = create_engine(dbUrl)
meta = MetaData()

table = Table('tableName', meta, autoload=True, autoload_with=engine)

primaryKeyColName = table.primary_key.columns.values()[0].name
</code>```

The Table construct above is useful for a number of different functions. I use it quite a bit for managing geospatial tables since I do not really like any of the current packages out there.

In your comment you mention that you are not defining a table...I think that means that you aren't creating a sqlalchemy model of the the table. With the approach above, you don't need to do that and can gather all sorts of information from a table in a more dynamic fashion. Especially useful if you are be handed someone else's messy database!

Hope that helps.

Body:
So, I just ran into the same problem. You need to create a Table object that reflects the table for which you are looking to find the primary key.

from sqlalchemy import create_engine, Table, MetaData

dbUrl = 'postgres://localhost:5432/databaseName'   #will be different for different db's

engine = create_engine(dbUrl)
meta = MetaData()

table = Table('tableName', meta, autoload=True, autoload_with=engine)

primaryKeyColName = table.primary_key.columns.values()[0].name

The Table construct above is useful for a number of different functions. I use it quite a bit for managing geospatial tables since I do not really like any of the current packages out there.

In your comment you mention that you are not defining a table...I think that means that you aren't creating a sqlalchemy model of the the table. With the approach above, you don't need to do that and can gather all sorts of information from a table in a more dynamic fashion. Especially useful if you are be handed someone else's messy database!

Hope that helps.


来源: stackexchange

问:
In java, how can I get an Amazon EC2 Instance to see its own tags?
So I have a java program running within an Amazon EC2 instance. Is there a way to programatically get its own tags? I have tried instantiating a new AmazonEC2Client to us the describeTags() function but it only gives me null. Any help would be appreciated thank you.

Edit: To make things clearer, the instances are going to be unmanned worker machines spun up to solely do some computations

答:
This should help you get started...</p>

```<code>String instanceId = EC2MetadataUtils.getInstanceId();
AmazonEC2 client = AmazonEC2ClientBuilder.standard()
    .withCredentials(new DefaultAWSCredentialsProviderChain())
    .build();
DescribeTagsRequest req = new DescribeTagsRequest()
    .withFilters(new Filter("resource-id", Collections.singletonList(instanceId)));
DescribeTagsResult describeTagsResult = client.describeTags(req);
List<TagDescription> tags = describeTagsResult.getTags()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This should help you get started...

String instanceId = EC2MetadataUtils.getInstanceId();
AmazonEC2 client = AmazonEC2ClientBuilder.standard()
    .withCredentials(new DefaultAWSCredentialsProviderChain())
    .build();
DescribeTagsRequest req = new DescribeTagsRequest()
    .withFilters(new Filter("resource-id", Collections.singletonList(instanceId)));
DescribeTagsResult describeTagsResult = client.describeTags(req);
List<TagDescription> tags = describeTagsResult.getTags()


问:
IE8 - Form within a hidden div, return key no longer works
I have a login form that resides within a div with display: none; I then fade in the form using jquery but the Enter/Return key no longer submits the form. If I change the display to block, it works fine. This problem is IE only.

Any ideas?

Here's an example code that doesn't work;

```<code><div id='formdiv' style='display: none;'>
<form id='loginForm' name='createLoginForm' method='post' action='' >
    <input type='text' name='username' id='username' />
    <input type='password' name='password' id='password' />
    <input type='submit' name='submit' id='login_submit'  />
</form>
</div>
</code>```

And I stuck this in the  to test the hiding/showing;

```<code><script type="text/javascript" src="jquery.tools.min.js"></script>

<script type='text/javascript'>
setTimeout('$("#formdiv").show()',1000);
</script>
</code>```

答:
I've been bitten by this before. Basically, if the form was hidden when the page is rendered, then return-submit won't work for that form.

Here's a work around:
http://www.thefutureoftheweb.com/blog/submit-a-form-in-ie-with-enter

ContentLicense: CC BY-SA 2.5

Body:
I have a login form that resides within a div with display: none; I then fade in the form using jquery but the Enter/Return key no longer submits the form. If I change the display to block, it works fine. This problem is IE only.

Any ideas?

Here's an example code that doesn't work;

<form id='loginForm' name='createLoginForm' method='post' action='' >
    <input type='text' name='username' id='username' />
    <input type='password' name='password' id='password' />
    <input type='submit' name='submit' id='login_submit'  />
</form>

And I stuck this in the  to test the hiding/showing;


问:
How can one configure Angular2 with a custom index.html location?
I've created an Angular2 application integrated with ASP.NET and served by IIS. This application is to be used by multiple clients and they would like the ability to customize the look and feel of the application to fit their branding. I'm using some aspects of ASP.NET MVC5's framework to make this possible.

The application is working as expected for most things, but I have two big stumbling blocks utilizing the cli that I can't seem to figure out.

Here is the basic folder structure of the application(there are other files and directories, but I'm excluding them as I don't believe they are relevant to the question):

```<code>Solution.sln
Web
  Controllers
  dist
  Models
  src
  Views
    Shared
      _Layout.cshtml
  .angular-cli.json
  package.json
  Web.config
  Global.asax
</code>```

The only relevant update that I've made to my .angular-cli.json file is that I changed the { apps: { index: '' } } value to be "../Views/Shared/_Layout.cshtml" instead of the default "index.html".

When I run ng build from within the Web directory, the application compiles and the correct script tags are placed in the _Layout.cshtml file right before the closing body tag as expected.

I'm not sure if these problems stem from the same root cause. I assume they do which is why I've put both here, but if they seem to be separate questions, I can break them apart.

Issue 1
If I run ng build multiple times, it doesn't remove and replace the script tags it creates in the _Layout.cshtml file as expected, but instead continues to append new script tags before the closing body tag. So if I run ng build twice in development mode, I'll get the same set of script tags in the file twice.

Any ideas as to what I would need to change to get the expected functionality back from ng build?

Issue 2
Now when I run ng build --watch, the build seems to end up in an endless loop. It continues packaging the assets over and over.

Any ideas as to what might be causing the infinite loop and how I can get ng build --watch to work properly with this setup?

I didn't have either of these issues with the index.html file, but unfortunately, I need to use the _Layout.cshtml file as my index file. I can create a custom prebuild npm task to clean up the script tags, but it doesn't seem like I should have to. I have not figured out a work around for the watch task issue.

UPDATE
As I suspected, this has nothing to do with the fact that it is an *.cshtml file, but rather due to the fact that the apps/index location is outside of the src folder.

Steps to reproduce:

npm install @angular/cli

node_modules/.bin/ng new test-custom-index

Movetest-custom-index/src/index.html to test-custom-index/index.html

Update the .angular-cli.json so index property is "index": "../index.html" instead of "index": "index.html"

From the test-custom-index directory run node_modules/.bin/ng build two times consecutively and you will see the duplicate script entries in the index.html file.
OR run node_modules/.bin/ng build --watch and watch it get caught in an infinite loop.

Any help would be greatly appreciated!!!

答:
I solved this by making the angular index page a partial and loading into the razor layout.

In the cli config:

"index": "index.cshtml",

but that file is actually blank. Then, in a razor file that uses the layout you want:

```<code>@section scripts
{
    <base href="~/">
    @Html.Partial("~/js/dist/index.cshtml")
}
</code>```

You could also just put that partial directly into the layout. The only gotcha with this is that if the index.cshtml lies outside your View folder you need to make it inherit from MvcWebPage, and the easiest way to do this is to copy the web.config file from your View folder into a folder one up from the index.cshtml file.

Body:
I've created an Angular2 application integrated with ASP.NET and served by IIS. This application is to be used by multiple clients and they would like the ability to customize the look and feel of the application to fit their branding. I'm using some aspects of ASP.NET MVC5's framework to make this possible.

The application is working as expected for most things, but I have two big stumbling blocks utilizing the cli that I can't seem to figure out.

Here is the basic folder structure of the application(there are other files and directories, but I'm excluding them as I don't believe they are relevant to the question):

Solution.sln
Web
  Controllers
  dist
  Models
  src
  Views
    Shared
      _Layout.cshtml
  .angular-cli.json
  package.json
  Web.config
  Global.asax

The only relevant update that I've made to my .angular-cli.json file is that I changed the { apps: { index: '' } } value to be "../Views/Shared/_Layout.cshtml" instead of the default "index.html".

When I run ng build from within the Web directory, the application compiles and the correct script tags are placed in the _Layout.cshtml file right before the closing body tag as expected.

I'm not sure if these problems stem from the same root cause. I assume they do which is why I've put both here, but if they seem to be separate questions, I can break them apart.

Issue 1
If I run ng build multiple times, it doesn't remove and replace the script tags it creates in the _Layout.cshtml file as expected, but instead continues to append new script tags before the closing body tag. So if I run ng build twice in development mode, I'll get the same set of script tags in the file twice.

Any ideas as to what I would need to change to get the expected functionality back from ng build?

Issue 2
Now when I run ng build --watch, the build seems to end up in an endless loop. It continues packaging the assets over and over.

Any ideas as to what might be causing the infinite loop and how I can get ng build --watch to work properly with this setup?

I didn't have either of these issues with the index.html file, but unfortunately, I need to use the _Layout.cshtml file as my index file. I can create a custom prebuild npm task to clean up the script tags, but it doesn't seem like I should have to. I have not figured out a work around for the watch task issue.

UPDATE
As I suspected, this has nothing to do with the fact that it is an *.cshtml file, but rather due to the fact that the apps/index location is outside of the src folder.

Steps to reproduce:

npm install @angular/cli

node_modules/.bin/ng new test-custom-index

Movetest-custom-index/src/index.html to test-custom-index/index.html

Update the .angular-cli.json so index property is "index": "../index.html" instead of "index": "index.html"

From the test-custom-index directory run node_modules/.bin/ng build two times consecutively and you will see the duplicate script entries in the index.html file.
OR run node_modules/.bin/ng build --watch and watch it get caught in an infinite loop.

Any help would be greatly appreciated!!!

Body:
I solved this by making the angular index page a partial and loading into the razor layout.

In the cli config:

"index": "index.cshtml",

but that file is actually blank. Then, in a razor file that uses the layout you want:

@section scripts
{
    <base href="~/">
    @Html.Partial("~/js/dist/index.cshtml")
}

You could also just put that partial directly into the layout. The only gotcha with this is that if the index.cshtml lies outside your View folder you need to make it inherit from MvcWebPage, and the easiest way to do this is to copy the web.config file from your View folder into a folder one up from the index.cshtml file.


问:
Is it possible to use multiple keys with lrange?
I would like to list two different groups of messages on the same web page, but I have been failing to do so.

It is easy if I want to list only one group of messages like the follows.

```<code>router.get("/index", function(req, res) {
  redisClient.lrange('chat:messages', 0, -1, function(err, messages) {
    if (err) {
      console.log(err);
    } else {
      var message_list = [];
      messages.forEach(function(message, i) {
        message_list.push(message);
      });
      res.render("index", { messages: message_list });
    }
  });
});
</code>```

But, I want to list two groups of messages, so what I really want to do is like the follows.

```<code>router.get("/index", function(req, res) {
  redisClient.lrange(['chat:messages1', 'chat:messages2'], 0, -1, function(err, messages) {
    if (err) {
      console.log(err);
    } else {
      var message_list1 = [];
      var message_list2 = [];
      messages[0].forEach(function(message, i) {
        message_list1.push(message);
      });
      messages[1].forEach(function(message, i) {
        message_list2.push(message);
      });
      res.render("index", { messages1: message_list1, messages2: message_list2 });
    }
  });
});
</code>```

This code doesn't work, but I hope I was able to give you an idea of what I want to do.

Is it possible to list two groups of messages on the same page?

If so, how should I tweak my code to make it work?

答:
The lrange command only takes a single key plus indexes. Is it reasonable to rewrite your logic using a multi-block:

```<code> redisClient.multi()
     .lrange('chat:messages1', 0, -1)
     .lrange('chat:messages2', 0, -1)
     .exec(function (err, replies) {
         replies.forEach(function (reply, index) {
            // do your computation
     });
</code>```

Body:
I would like to list two different groups of messages on the same web page, but I have been failing to do so.

It is easy if I want to list only one group of messages like the follows.

router.get("/index", function(req, res) {
  redisClient.lrange('chat:messages', 0, -1, function(err, messages) {
    if (err) {
      console.log(err);
    } else {
      var message_list = [];
      messages.forEach(function(message, i) {
        message_list.push(message);
      });
      res.render("index", { messages: message_list });
    }
  });
});

But, I want to list two groups of messages, so what I really want to do is like the follows.

router.get("/index", function(req, res) {
  redisClient.lrange(['chat:messages1', 'chat:messages2'], 0, -1, function(err, messages) {
    if (err) {
      console.log(err);
    } else {
      var message_list1 = [];
      var message_list2 = [];
      messages[0].forEach(function(message, i) {
        message_list1.push(message);
      });
      messages[1].forEach(function(message, i) {
        message_list2.push(message);
      });
      res.render("index", { messages1: message_list1, messages2: message_list2 });
    }
  });
});

This code doesn't work, but I hope I was able to give you an idea of what I want to do.

Is it possible to list two groups of messages on the same page?

If so, how should I tweak my code to make it work?

Body:
The lrange command only takes a single key plus indexes. Is it reasonable to rewrite your logic using a multi-block:

 redisClient.multi()
     .lrange('chat:messages1', 0, -1)
     .lrange('chat:messages2', 0, -1)
     .exec(function (err, replies) {
         replies.forEach(function (reply, index) {
            // do your computation
     });


问:
Adding custom geometry to the viewer
I have a model that I wish to subdivide, by drawing semi-transparent boxes over different parts.

Following the example https://forge.autodesk.com/cloud_and_mobile/2016/02/custom-transparent-meshes-with-view-data-api.html I have drawn the boxes and added them to the sceneAfter object.  So they draw semi-transparently, and the model appears within them as expected.

I have used a bufferGeometry, which avoids the missing attributes error.

However, I cannot either select the boxes, or ignore the boxes and select the components inside them.  The example states "Another option would be to create the custom geometry the same way the viewer does, so it could participate in the selection".  Is there any documentation on how the viewer creates the geometry?

Searching through the source, I can see dbId and fragId being assigned to a Mesh in addSingleMesh, but as part of the model consolidation.

I am not yet sure if I want to select the boxes or the items within them, but as the viewer knows to ignore components that are ghosted out, I hope this is a relatively simple thing to toggle?

答:
When you add a custom mesh to the scene it will not take part to the viewer selection mechanism. As far as I know we don't have a sample that illustrates how to achieve that, so I'm asking to the development team if they can provide some directions...

In the meantime you can add some logic to handle the selection of the meshes that you added separately. This is what I did in the sample referenced by that blog post: Boolean Operations in the Forge Viewer. Custom selection is performed there:

```<code>onClick (event) {

  const pointer = event.pointers
    ? event.pointers[0]
    : event

  const rayCaster = this.pointerToRaycaster(
    this.viewer.impl.canvas,
    this.viewer.impl.camera,
    pointer)

  const intersectResults = rayCaster.intersectObjects(
    this.intersectMeshes, true)

  if (intersectResults.length) {

    const mesh = intersectResults[0].object

    this.panel.setVisible(false)

    this.panel.setNodeProperties(mesh.dbId)

    this.panel.setVisible(true)
  }
}
</code>```

You may also be interested in that article which deals with filtering the viewer native selection: Controlling components selection in the Viewer.

Hope that helps

Title: Adding custom geometry to the viewer

Body:
When you add a custom mesh to the scene it will not take part to the viewer selection mechanism. As far as I know we don't have a sample that illustrates how to achieve that, so I'm asking to the development team if they can provide some directions...

In the meantime you can add some logic to handle the selection of the meshes that you added separately. This is what I did in the sample referenced by that blog post: Boolean Operations in the Forge Viewer. Custom selection is performed there:

onClick (event) {

  const pointer = event.pointers
    ? event.pointers[0]
    : event

  const rayCaster = this.pointerToRaycaster(
    this.viewer.impl.canvas,
    this.viewer.impl.camera,
    pointer)

  const intersectResults = rayCaster.intersectObjects(
    this.intersectMeshes, true)

  if (intersectResults.length) {

    const mesh = intersectResults[0].object

    this.panel.setVisible(false)

    this.panel.setNodeProperties(mesh.dbId)

    this.panel.setVisible(true)
  }
}

You may also be interested in that article which deals with filtering the viewer native selection: Controlling components selection in the Viewer.

Hope that helps


问:
Autorreconf and "error: possibly undefined macro: AM_NLS"
I'm trying to produce a configure script for systemd.

```<code>$ git clone https://github.com/systemd/systemd.git
$ cd systemd

$ autoreconf -i
configure.ac:74: warning: macro 'AM_NLS' not found in library
configure.ac:74: error: possibly undefined macro: AM_NLS
      If this token and others are legitimate, please use m4_pattern_allow.
      See the Autoconf documentation.
autoreconf: /usr/bin/autoconf failed with exit status: 1
</code>```

I'm on a fairly modern machine that's fully patched. Its Fedora 25, x86_64:

```<code>$ lsb_release -a
LSB Version:    :core-4.1-amd64:core-4.1-noarch
Distributor ID: Fedora
Description:    Fedora release 25 (Twenty Five)
Release:        25
Codename:       TwentyFive
</code>```

I'm not an Autotools expert, and searching for "error: possibly undefined macro: AM_NLS" is not returning useful hits for me. I found Linphone configuration results in multiple undefined Autotools macros, but its not exactly clear what I should do. Unix & Linux Stack Exchange has Some M4 macros don't seem to be defined, but its still not clear what I should do for this issue.

What is the problem and how do I fix it?

答:
What is the problem and how do I fix it?

The problem is it's expecting GNU gettext, specifically on Fedora 25 gettext-devel.  It's in /usr/share/aclocal/nls.m4 contained in that package.  You should be able to install that package and build.

Body:
I'm trying to produce a configure script for systemd.

$ git clone https://github.com/systemd/systemd.git
$ cd systemd

$ autoreconf -i
configure.ac:74: warning: macro 'AM_NLS' not found in library
configure.ac:74: error: possibly undefined macro: AM_NLS
      If this token and others are legitimate, please use m4_pattern_allow.
      See the Autoconf documentation.
autoreconf: /usr/bin/autoconf failed with exit status: 1

I'm on a fairly modern machine that's fully patched. Its Fedora 25, x86_64:

$ lsb_release -a
LSB Version:    :core-4.1-amd64:core-4.1-noarch
Distributor ID: Fedora
Description:    Fedora release 25 (Twenty Five)
Release:        25
Codename:       TwentyFive

I'm not an Autotools expert, and searching for "error: possibly undefined macro: AM_NLS" is not returning useful hits for me. I found Linphone configuration results in multiple undefined Autotools macros, but its not exactly clear what I should do. Unix & Linux Stack Exchange has Some M4 macros don't seem to be defined, but its still not clear what I should do for this issue.

What is the problem and how do I fix it?


问:
What's the fastest way to acces a Pandas DataFrame?
I have a DataFrame df with 541 columns, and I need to save all unique pairs of its column names into the rows of a separate DataFrame, repeated 8 times each.

I thought I would create an empty DataFrame fp, double loop through df's column names, insert into every 8th row, and fill in the blanks with the last available value.

When I tried to do this though I was baffled by how long it's taking. With 541 columns I only have to write 146,611 times yet it's taking well over 20 minutes. This seems egregious for just data access. Where is the problem and how can I solve it? It takes less time than that for Pandas to produce a correlation matrix with the columns so I must me doing something wrong.

Here's a reproducible example of what I mean:

```<code>fp = np.empty(shape = (146611, 10))
fp.fill(np.nan)

fp = pd.DataFrame(fp)

%timeit for idx in range(0, len(fp)): fp.iloc[idx, 0] = idx

# 1 loop, best of 3: 22.3 s per loop
</code>```

答:
Don't do iloc/loc/chained-indexing. Using the NumPy interface alone increases speed by ~180x. If you further remove element access, we can bump this to 180,000x.

```<code>fp = np.empty(shape = (146611, 10))
fp.fill(np.nan)

fp = pd.DataFrame(fp)

# this confirms how slow data access is on my computer
%timeit for idx in range(0, len(fp)): fp.iloc[idx, 0] = idx

1 loops, best of 3: 3min 9s per loop

# this accesses the underlying NumPy array, so you can directly set the data
%timeit for idx in range(0, len(fp)): fp.values[idx, 0] = idx

1 loops, best of 3: 1.19 s per loop
</code>```

This is because there's extensive code that goes in the Python layer for this fancing indexing, taking ~10µs per loop. Using Pandas indexing should be done to retrieve entire subsets of data, which you then use to do vectorized operations on the entire dataframe. Individual element access is glacial: using Python dictionaries will give you a > 180 fold increase in performance.

Things get a lot better when you access columns or rows instead of individual elements: 3 orders of magnitude better.

```<code># set all items in 1 go.
%timeit fp[0] = np.arange(146611)
1000 loops, best of 3: 814 µs per loop
</code>```

Moral

Don't try to access individual elements via chained indexing, loc, or iloc. Generate a NumPy array in a single allocation, from a Python list (or a C-interface if performance is absolutely critical), and then perform operations on entire columns or dataframes.

Using NumPy arrays and performing operations directly on columns rather than individual elements, we got a whopping 180,000+ fold increase in performance. Not too shabby.

Edit

Comments from @kushy suggest Pandas may have optimized indexing in certain cases since I originally wrote this answer. Always profile your own code, and your mileage may vary.

Body:
I have a DataFrame df with 541 columns, and I need to save all unique pairs of its column names into the rows of a separate DataFrame, repeated 8 times each.

I thought I would create an empty DataFrame fp, double loop through df's column names, insert into every 8th row, and fill in the blanks with the last available value.

When I tried to do this though I was baffled by how long it's taking. With 541 columns I only have to write 146,611 times yet it's taking well over 20 minutes. This seems egregious for just data access. Where is the problem and how can I solve it? It takes less time than that for Pandas to produce a correlation matrix with the columns so I must me doing something wrong.

Here's a reproducible example of what I mean:

fp = np.empty(shape = (146611, 10))
fp.fill(np.nan)

fp = pd.DataFrame(fp)

%timeit for idx in range(0, len(fp)): fp.iloc[idx, 0] = idx

# 1 loop, best of 3: 22.3 s per loop

Body:
Don't do iloc/loc/chained-indexing. Using the NumPy interface alone increases speed by ~180x. If you further remove element access, we can bump this to 180,000x.

fp = np.empty(shape = (146611, 10))
fp.fill(np.nan)

fp = pd.DataFrame(fp)

# this confirms how slow data access is on my computer
%timeit for idx in range(0, len(fp)): fp.iloc[idx, 0] = idx

1 loops, best of 3: 3min 9s per loop

# this accesses the underlying NumPy array, so you can directly set the data
%timeit for idx in range(0, len(fp)): fp.values[idx, 0] = idx

1 loops, best of 3: 1.19 s per loop

This is because there's extensive code that goes in the Python layer for this fancing indexing, taking ~10µs per loop. Using Pandas indexing should be done to retrieve entire subsets of data, which you then use to do vectorized operations on the entire dataframe. Individual element access is glacial: using Python dictionaries will give you a > 180 fold increase in performance.

Things get a lot better when you access columns or rows instead of individual elements: 3 orders of magnitude better.

# set all items in 1 go.
%timeit fp[0] = np.arange(146611)
1000 loops, best of 3: 814 µs per loop

Moral

Don't try to access individual elements via chained indexing, loc, or iloc. Generate a NumPy array in a single allocation, from a Python list (or a C-interface if performance is absolutely critical), and then perform operations on entire columns or dataframes.

Using NumPy arrays and performing operations directly on columns rather than individual elements, we got a whopping 180,000+ fold increase in performance. Not too shabby.

Edit

Comments from @kushy suggest Pandas may have optimized indexing in certain cases since I originally wrote this answer. Always profile your own code, and your mileage may vary.

ContentLicense: CC BY-SA 4.0


问:
How to do some thing to all class on js
every body.

I try to make function as each function on jquery i make this code

```<code>var $ = function (e){
    var d = document
    if(e){
        if ("#" == e.substring(0, 1)) {
            return d.querySelectorAll(e);
        } else if ("." == e.substring(0, 1)) {
            return d.querySelectorAll(e);
        } else if ("." != e.substring(0, 1) && "#" != e.substring(0, 1)){
            return d.querySelectorAll(e)
        }
    }
}
</code>```

i want it if i write $(".example").style.background = "red";

答:
If you want create each function, this code is work

```<code>function each(a,b) {
  var c = document.querySelectorAll(a);
  for(var i = c.length - 1; i >= 0; i--) {
    return b.call(i, c[i]);
  }
}

//use

each(".class", function(e) {
  e.style.background = "red";
});
</code>```

You need selector engine like sizzle if you want write $(".class").style.background = "red";

Title: How to do some thing to all class on js

Body:
every body.

I try to make function as each function on jquery i make this code

var $ = function (e){
    var d = document
    if(e){
        if ("#" == e.substring(0, 1)) {
            return d.querySelectorAll(e);
        } else if ("." == e.substring(0, 1)) {
            return d.querySelectorAll(e);
        } else if ("." != e.substring(0, 1) && "#" != e.substring(0, 1)){
            return d.querySelectorAll(e)
        }
    }
}

i want it if i write $(".example").style.background = "red";

Body:
If you want create each function, this code is work

function each(a,b) {
  var c = document.querySelectorAll(a);
  for(var i = c.length - 1; i >= 0; i--) {
    return b.call(i, c[i]);
  }
}

//use

each(".class", function(e) {
  e.style.background = "red";
});

You need selector engine like sizzle if you want write $(".class").style.background = "red";


问:
S3 policy to allow a user to enable / disable versioning on a specific bucket AND enable / disable static website hosting
For a specific IAM user I can restrict access to a specific bucket (i.e. list, get, put, delete).

However, is there an S3 policy to allow a user to do some of the meta stuff like enable / disable versioning on a specific bucket AND enable / disable static website hosting on the same bucket?

答:
To control versioning, users must use the s3:putBucketVersioning API call.

To control static website hosting, users must use the s3:putBucketWebsite API call.

You will need to assign these permissions to a user to allow them to control Versioning and Static Hosting Website settings.


问:
Javascript Modularized Promise Chain Out of Order
I am trying to figure out the reason why my promise chain is executing out of order despite writing a non-nested then chain. My functions have been modularized to reduce the code bloat that will happen in my chain (I expect to have five then methods) and I'm not sure if something within those modules are causing the jump in the order or if it is due to my overall promise structure.

Here is the terminal output:

```<code>Executing (a6bf615e-5497-47b2-8aea-3f7d70927cba): START TRANSACTION;
Executing (a6bf615e-5497-47b2-8aea-3f7d70927cba): SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
Step 1: Document Find
Step 3: Cancel Stripe Subscription
string //console.log(typeof subscriptionId);
sub_jsdfjsdfjdsfjsdfj //console.log(subscriptionId)
Executing (a6bf615e-5497-47b2-8aea-3f7d70927cba): SELECT ....
Step 2: Set Array
[ 13, 14 ] //console.log(documentArr);
undefined //console.log(canceledStripeAccount);
undefined //console.log(canceledAt)
</code>```

Here is my promise structure:

```<code>var sequelize = require('sequelize');
var models = require('../../../models/db-index');
var deleteAccount = require('./delete-account');

//DELETE /settings/account
exports.delete = function(req, res){
    var documents;
    var documentArr;
    var canceledStripeAccount;
    var canceledAt;

    return models.sequelize.transaction().then(function(t){

        return deleteAccount.queryAllDocuments(req.session.organizationId, t)
        .then(function(_document){
                console.log("Step 2: Set Array");
                documentArr = _document;
                console.log(documentArr);
        })
        .then(deleteAccount.cancelStripeAccount(req.session.subscriptionId, canceledStripeAccount, canceledAt))
        .then(function(canceledStripeAccount){
            console.log(canceledStripeAccount);
            console.log(canceledAt)
        });
    });
};
</code>```

Modules File:

```<code>var models = require('../../../models/db-index');
var components = require('./components');
var stripe = require('stripe')(process.env.STRIPE_API_KEY);

module.exports = {

    queryAllDocuments: function(organization, t){
        console.log("Step 1: Document Find");
        return models.Document.findAll({
            include: [{
                model: models.User,
                include: [{
                    model: models.Organization,
                    where: {
                        organizationId: organization
                    }
                }]
            }],
            transaction: t
        })
    },

    cancelStripeAccount: function(subscriptionId, canceledStripeAccount, canceledAt){
        console.log("Step 3: Cancel Stripe Subscription");
        console.log(typeof subscriptionId);
        console.log(subscriptionId)
        return stripe.subscriptions.del(subscriptionId).then(function(_canceledStripeAccount){
            return canceledStripeAccount = _canceledStripeAccount;
            //canceledAt = canceledStripeAccount.canceled_at;
        })
    }

}
</code>```

答:
You are calling the function directly before .then() even calls its callback (and passing the return value from that to .then()):

```<code>.then(deleteAccount.cancelStripeAccount(req.session.subscriptionId,
        canceledStripeAccount, canceledAt))
</code>```

Instead, .then() should be passed a function reference so it can call the function sometime later:

```<code>.then(() => deleteAccount.cancelStripeAccount(req.session.subscriptionId,
              canceledStripeAccount, canceledAt))
</code>```

Body:
I am trying to figure out the reason why my promise chain is executing out of order despite writing a non-nested then chain. My functions have been modularized to reduce the code bloat that will happen in my chain (I expect to have five then methods) and I'm not sure if something within those modules are causing the jump in the order or if it is due to my overall promise structure.

Here is the terminal output:

Executing (a6bf615e-5497-47b2-8aea-3f7d70927cba): START TRANSACTION;
Executing (a6bf615e-5497-47b2-8aea-3f7d70927cba): SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
Step 1: Document Find
Step 3: Cancel Stripe Subscription
string //console.log(typeof subscriptionId);
sub_jsdfjsdfjdsfjsdfj //console.log(subscriptionId)
Executing (a6bf615e-5497-47b2-8aea-3f7d70927cba): SELECT ....
Step 2: Set Array
[ 13, 14 ] //console.log(documentArr);
undefined //console.log(canceledStripeAccount);
undefined //console.log(canceledAt)

Here is my promise structure:

var sequelize = require('sequelize');
var models = require('../../../models/db-index');
var deleteAccount = require('./delete-account');

//DELETE /settings/account
exports.delete = function(req, res){
    var documents;
    var documentArr;
    var canceledStripeAccount;
    var canceledAt;

    return models.sequelize.transaction().then(function(t){

        return deleteAccount.queryAllDocuments(req.session.organizationId, t)
        .then(function(_document){
                console.log("Step 2: Set Array");
                documentArr = _document;
                console.log(documentArr);
        })
        .then(deleteAccount.cancelStripeAccount(req.session.subscriptionId, canceledStripeAccount, canceledAt))
        .then(function(canceledStripeAccount){
            console.log(canceledStripeAccount);
            console.log(canceledAt)
        });
    });
};

Modules File:

var models = require('../../../models/db-index');
var components = require('./components');
var stripe = require('stripe')(process.env.STRIPE_API_KEY);

module.exports = {

    queryAllDocuments: function(organization, t){
        console.log("Step 1: Document Find");
        return models.Document.findAll({
            include: [{
                model: models.User,
                include: [{
                    model: models.Organization,
                    where: {
                        organizationId: organization
                    }
                }]
            }],
            transaction: t
        })
    },

    cancelStripeAccount: function(subscriptionId, canceledStripeAccount, canceledAt){
        console.log("Step 3: Cancel Stripe Subscription");
        console.log(typeof subscriptionId);
        console.log(subscriptionId)
        return stripe.subscriptions.del(subscriptionId).then(function(_canceledStripeAccount){
            return canceledStripeAccount = _canceledStripeAccount;
            //canceledAt = canceledStripeAccount.canceled_at;
        })
    }

}

Body:
You are calling the function directly before .then() even calls its callback (and passing the return value from that to .then()):

.then(deleteAccount.cancelStripeAccount(req.session.subscriptionId,
        canceledStripeAccount, canceledAt))

Instead, .then() should be passed a function reference so it can call the function sometime later:

.then(() => deleteAccount.cancelStripeAccount(req.session.subscriptionId,
              canceledStripeAccount, canceledAt))


问:
How to format many values in a database?
I have a database (in SQLite) in which some entries (or possibly all) are strings whose first character is a space.

The database may be small enough for me to export it as a CSV file and do a regular-expression search-and-replace which will delete the leading space. Is there an SQL statement which can achieve the same result?

(The database has over 60 columns---listing each one might get tedious.)

答:
You can strip the unneeded spaces right in select query:

```<code>SELECT TRIM(field)
</code>```

or do it once on all rows

```<code>UPDATE table SET field = TRIM(field)
</code>```

Body:
You can strip the unneeded spaces right in select query:

SELECT TRIM(field)

or do it once on all rows

UPDATE table SET field = TRIM(field)


问:
Python - Issue Scraping with BeautifulSoup
I'm trying to scrape the Stack Overflow jobs page using Beautiful Soup 4 and URLLIB as a personal project. I'm facing an issue where I'm trying to scrape all the links to the 50 jobs listed on each page. I'm using a regex to identify these links. Even though I reference the tag properly, I am facing these two specific issues:

Instead of the 50 links clearly visible in the source code, I get only 25 results each time as my output(after accounting for an removing an initial irrelevant link)

There's a difference between how the links are ordered in the source code and my output.

Here's my code. Any help on this will be greatly appreciated:

```<code>import bs4
import urllib.request
import re

#Obtaining source code to parse

sauce = urllib.request.urlopen('https://stackoverflow.com/jobs?med=site-ui&ref=jobs-tab&sort=p&pg=0').read()

soup = bs4.BeautifulSoup(sauce, 'html.parser')

snippet = soup.find_all("script",type="application/ld+json")
strsnippet = str(snippet)

print(strsnippet)

joburls = re.findall('https://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', strsnippet)

print("Urls: ",joburls)
print(len(joburls))
</code>```

答:
Disclaimer: I did some asking of my own for a part of this answer.

```<code>from bs4 import BeautifulSoup
import requests
import json

# note: link is slightly different; yours just redirects here
link = 'https://stackoverflow.com/jobs?med=site-ui&ref=jobs-tab&sort=p'
r = requests.get(link)
soup = BeautifulSoup(r.text, 'html.parser')

s = soup.find('script', type='application/ld+json')
urls = [el['url'] for el in json.loads(s.text)['itemListElement']]

print(len(urls))
50
</code>```

Process:

Use soup.find rather than soup.find_all.  This will give a JSON bs4.element.Tag

json.loads(s.text) is a nested dict.  Access the values for itemListElement key to get a dict of urls, and convert to list.

Body:
I'm trying to scrape the Stack Overflow jobs page using Beautiful Soup 4 and URLLIB as a personal project. I'm facing an issue where I'm trying to scrape all the links to the 50 jobs listed on each page. I'm using a regex to identify these links. Even though I reference the tag properly, I am facing these two specific issues:

Instead of the 50 links clearly visible in the source code, I get only 25 results each time as my output(after accounting for an removing an initial irrelevant link)

There's a difference between how the links are ordered in the source code and my output.

Here's my code. Any help on this will be greatly appreciated:

import bs4
import urllib.request
import re

#Obtaining source code to parse

sauce = urllib.request.urlopen('https://stackoverflow.com/jobs?med=site-ui&ref=jobs-tab&sort=p&pg=0').read()

soup = bs4.BeautifulSoup(sauce, 'html.parser')

snippet = soup.find_all("script",type="application/ld+json")
strsnippet = str(snippet)

print(strsnippet)

joburls = re.findall('https://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', strsnippet)

print("Urls: ",joburls)
print(len(joburls))

Body:
Disclaimer: I did some asking of my own for a part of this answer.

from bs4 import BeautifulSoup
import requests
import json

# note: link is slightly different; yours just redirects here
link = 'https://stackoverflow.com/jobs?med=site-ui&ref=jobs-tab&sort=p'
r = requests.get(link)
soup = BeautifulSoup(r.text, 'html.parser')

s = soup.find('script', type='application/ld+json')
urls = [el['url'] for el in json.loads(s.text)['itemListElement']]

print(len(urls))
50

Process:

Use soup.find rather than soup.find_all.  This will give a JSON bs4.element.Tag

json.loads(s.text) is a nested dict.  Access the values for itemListElement key to get a dict of urls, and convert to list.


问:
EF 6.1.3 how to seed on-to-many relationship
I am trying to seed my EF code first database in the Configuration file of the migrations folder, but somehow I have no idea how as I do not want to add a new entry to the related database.

I have the following database structure.

```<code>public class ClassSchedule
    {
        public int Id { get; set; }
        public DateTime StartTime { get; set; }
        public DateTime EndTime { get; set; }

        public virtual Class Classes { get; set; }
        public virtual Classroom Classrooms { get; set; }
    }

public class Class
    {
        public Class()
        {
            this.Students = new HashSet<Student>();
            this.ClassSchedules = new HashSet<ClassSchedule>();
        }

        public int Id { get; set; }
        public int LevelId { get; set; }

        [StringLength(50)]
        public string ClassName { get; set; }
        public int MaxStudents { get; set; }

        public virtual Level Levels { get; set; }
        public ICollection<Student> Students { get; set; }
        public ICollection<ClassSchedule> ClassSchedules { get; set; }
    }

  public class Classroom
    {
        public Classroom()
        {
            this.ClassSchedules = new HashSet<ClassSchedule>();
        }

        public int Id { get; set; }
        public string ClassRoomName { get; set; }
        public int MaxStudents { get; set; }

        public ICollection<ClassSchedule> ClassSchedules { get; set; }
    }
</code>```

And have got the following Code in my migration configuration file:

```<code>// all classrooms
  context.Classrooms.Add(new Classroom() { ClassRoomName = "Cherry", MaxStudents = 20 });
  context.Classrooms.Add(new Classroom() { ClassRoomName = "Pear", MaxStudents = 12 });
  context.Classrooms.Add(new Classroom() { ClassRoomName = "Apple", MaxStudents = 12 });

  // classes
  context.Classes.Add(new Class() { ClassName = "YR1", MaxStudents = 12, LevelId = 1 });
  context.Classes.Add(new Class() { ClassName = "YB1", MaxStudents = 6, LevelId = 3 });
  context.Classes.Add(new Class() { ClassName = "IELTS L1", MaxStudents = 40, LevelId = 14 });
</code>```

Now what i want to do is something like this:

```<code>// ClassRoom schedules, links the class and classroom on a certain time
            context.ClassSchedules.Add(new ClassSchedule() { StartTime = DateTime.Parse("2017-09-17T18:00:00"), EndTime = DateTime.Parse("2017-09-17T20:00:00"), Classes = 1, Classrooms = 1 });
</code>```

Another thing I tried was:

```<code>   context.ClassSchedules.Add(new ClassSchedule() { StartTime = DateTime.Parse("2017-09-17T18:00:00"), EndTime = DateTime.Parse("2017-09-17T20:00:00"), Classes = { Id = 1 }, Classrooms = { Id = 2 } });
</code>```

However that does't work, also note that I cannot use new Classes() { Id = 1 }  as this will create a new entity.

Any help will be appreciated, Cheers!

答:
I couldn't get it to work with the method  @gertArnold suggested, but after looking around for some time I found that it is possible to do it via the AddOrUpdate method and it will also check whether the value already exists or not. In that case it will be written as follows:

```<code> context.ClassSchedules.AddOrUpdate(cs => cs.ScheduleName,
        new ClassSchedule
        {
            ScheduleName = "Yippie red class",
            StartTime = DateTime.Parse("2017-09-17T18:00:00"),
            EndTime = DateTime.Parse("2017-09-17T20:00:00"),
            Classes = new Class()
            {
                ClassName = "YR1",
                MaxStudents = 12,
                LevelId = 1
            },
            Classrooms = new Classroom()
            {
                ClassRoomName = "Cherry",
                MaxStudents = 20
            }

        });
</code>```

Hope it will help anyone.

Body:
I am trying to seed my EF code first database in the Configuration file of the migrations folder, but somehow I have no idea how as I do not want to add a new entry to the related database.

I have the following database structure.

public class ClassSchedule
    {
        public int Id { get; set; }
        public DateTime StartTime { get; set; }
        public DateTime EndTime { get; set; }

        public virtual Class Classes { get; set; }
        public virtual Classroom Classrooms { get; set; }
    }

public class Class
    {
        public Class()
        {
            this.Students = new HashSet<Student>();
            this.ClassSchedules = new HashSet<ClassSchedule>();
        }

        public int Id { get; set; }
        public int LevelId { get; set; }

        [StringLength(50)]
        public string ClassName { get; set; }
        public int MaxStudents { get; set; }

        public virtual Level Levels { get; set; }
        public ICollection<Student> Students { get; set; }
        public ICollection<ClassSchedule> ClassSchedules { get; set; }
    }

  public class Classroom
    {
        public Classroom()
        {
            this.ClassSchedules = new HashSet<ClassSchedule>();
        }

        public int Id { get; set; }
        public string ClassRoomName { get; set; }
        public int MaxStudents { get; set; }

        public ICollection<ClassSchedule> ClassSchedules { get; set; }
    }

And have got the following Code in my migration configuration file:

// all classrooms
  context.Classrooms.Add(new Classroom() { ClassRoomName = "Cherry", MaxStudents = 20 });
  context.Classrooms.Add(new Classroom() { ClassRoomName = "Pear", MaxStudents = 12 });
  context.Classrooms.Add(new Classroom() { ClassRoomName = "Apple", MaxStudents = 12 });

  // classes
  context.Classes.Add(new Class() { ClassName = "YR1", MaxStudents = 12, LevelId = 1 });
  context.Classes.Add(new Class() { ClassName = "YB1", MaxStudents = 6, LevelId = 3 });
  context.Classes.Add(new Class() { ClassName = "IELTS L1", MaxStudents = 40, LevelId = 14 });

Now what i want to do is something like this:

// ClassRoom schedules, links the class and classroom on a certain time
            context.ClassSchedules.Add(new ClassSchedule() { StartTime = DateTime.Parse("2017-09-17T18:00:00"), EndTime = DateTime.Parse("2017-09-17T20:00:00"), Classes = 1, Classrooms = 1 });

Another thing I tried was:

   context.ClassSchedules.Add(new ClassSchedule() { StartTime = DateTime.Parse("2017-09-17T18:00:00"), EndTime = DateTime.Parse("2017-09-17T20:00:00"), Classes = { Id = 1 }, Classrooms = { Id = 2 } });

However that does't work, also note that I cannot use new Classes() { Id = 1 }  as this will create a new entity.

Any help will be appreciated, Cheers!

Body:
I couldn't get it to work with the method  @gertArnold suggested, but after looking around for some time I found that it is possible to do it via the AddOrUpdate method and it will also check whether the value already exists or not. In that case it will be written as follows:

 context.ClassSchedules.AddOrUpdate(cs => cs.ScheduleName,
        new ClassSchedule
        {
            ScheduleName = "Yippie red class",
            StartTime = DateTime.Parse("2017-09-17T18:00:00"),
            EndTime = DateTime.Parse("2017-09-17T20:00:00"),
            Classes = new Class()
            {
                ClassName = "YR1",
                MaxStudents = 12,
                LevelId = 1
            },
            Classrooms = new Classroom()
            {
                ClassRoomName = "Cherry",
                MaxStudents = 20
            }

        });

Hope it will help anyone.


问:
Apache Mod Expires, how to Debug?
My objective: Have the javascript on my server ALWAYS pull from my server, and not allow caching.

My OS: Ubuntu

My Methods: (following https://www.digitalocean.com/community/tutorials/how-to-configure-apache-content-caching-on-ubuntu-14-04#setting-expires-and-caching-headers-on-content)

sudo a2enmod expires

sudo a2enmod headers

add the following to my (already proven to be working) .htaccess file:

ExpiresActive On
ExpiresByType text/javascript "access plus 1 seconds"

My results: No change at all in the HTTP headers. Users still complain that their cache files are out of date.

My .htaccess file, in it's entirety is:

```<code>    RewriteEngine On
RewriteCond %{REMOTE_ADDR} !^123\.456\.789\.000
RewriteCond %{DOCUMENT_ROOT}/maintenance.html -f
RewriteCond %{DOCUMENT_ROOT}/maintenance.enable -f
RewriteCond %{SCRIPT_FILENAME} !maintenance.html
RewriteRule ^.*$ /maintenance.html [R=503,L]
ErrorDocument 503 /maintenance.html
ExpiresActive On
ExpiresByType text/javascript "access plus 1 seconds"
#ExpiresByType  text/js “access plus 1 seconds”
</code>```

I know it's reading the .htaccess code because my maintenance mode code still works. I further know it's reading it because I fought with 500 Internal Server errors until I got my ExpiresByTypes syntax right.

How do I even BEGIN to debug this problem?

答:
No HTTP response headers shown in the question, but Apache's default mime.types maps *.js to application/javascript not the text/javascript you're matching.

```<code>application/javascript              js
</code>```

At the very least, duplicate your config for application/javascript!

Title: Apache Mod Expires, how to Debug?

Body:
My objective: Have the javascript on my server ALWAYS pull from my server, and not allow caching.

My OS: Ubuntu

My Methods: (following https://www.digitalocean.com/community/tutorials/how-to-configure-apache-content-caching-on-ubuntu-14-04#setting-expires-and-caching-headers-on-content)

sudo a2enmod expires

sudo a2enmod headers

add the following to my (already proven to be working) .htaccess file:

ExpiresActive On
ExpiresByType text/javascript "access plus 1 seconds"

My results: No change at all in the HTTP headers. Users still complain that their cache files are out of date.

My .htaccess file, in it's entirety is:

    RewriteEngine On
RewriteCond %{REMOTE_ADDR} !^123\.456\.789\.000
RewriteCond %{DOCUMENT_ROOT}/maintenance.html -f
RewriteCond %{DOCUMENT_ROOT}/maintenance.enable -f
RewriteCond %{SCRIPT_FILENAME} !maintenance.html
RewriteRule ^.*$ /maintenance.html [R=503,L]
ErrorDocument 503 /maintenance.html
ExpiresActive On
ExpiresByType text/javascript "access plus 1 seconds"
#ExpiresByType  text/js “access plus 1 seconds”

I know it's reading the .htaccess code because my maintenance mode code still works. I further know it's reading it because I fought with 500 Internal Server errors until I got my ExpiresByTypes syntax right.

How do I even BEGIN to debug this problem?

Body:
No HTTP response headers shown in the question, but Apache's default mime.types maps *.js to application/javascript not the text/javascript you're matching.

application/javascript              js

At the very least, duplicate your config for application/javascript!


问:
terraform conditionally create resource based on external data?
As part of a setup, I create TLS certs and store them in S3. Creating the certs is done via external data source that runs the command to generate the certs. I then use those outputs to create S3 bucket object resources.

This works very well the first time I run terraform apply. However, if I change any other (non-cert) variable, resource, etc. and rerun, it reruns the external command, which generates a new key/cert pair, uploads them to S3, and breaks everything that already works.

Is there any way to create the resource conditionally? What pattern could I use to make the certs created only if they don't exist?

I did look at storing the generated keys/certs locally, but this is sensitive key material; I do not want it stored in local disk (and there are keys per environment).

Key/cert generation and storage:

```<code>data "external" "ca" {
  program = ["sh","-c","jq '.root|fromjson' | cfssl gencert -initca -"]
  #
  query = {root = "${ data.template_file.etcd-ca-csr.rendered }"}
  # the result will be saved in
  # data.external.etcd-ca.result.key
  # data.external.etcd-ca.result.csr
  # data.external.etcd-ca.result.cert
}

resource "aws_s3_bucket_object" "ca_cert" {
  bucket = "${aws_s3_bucket.my_bucket.id}"
  key = "ca.pem"
  content = "${data.external.ca.result.cert}"
}
resource "aws_s3_bucket_object" "ca_key" {
  bucket = "${aws_s3_bucket.my_bucket.id}"
  key = "ca-key.pem"
  content = "${data.external.ca.result.key}"
}
</code>```

Happy to look at using some form of conditional or entirely different generation pattern.

答:
The reason for this behavior is that external is a data source, and thus Terraform expects that it is is read-only and side-effect-free. It re-runs data sources for every plan.

In order to do this via an external script, it would be necessary to use a resource provisioner to run the script and upload it to S3, since there is currently no external equivalent for resources, which are allowed to have side-effects, and provisioners are side-effect-only (that is, they can't produce results to use elsewhere in config.)

Another approach, though, would be to use Terraform's built-in TLS provider, which allows creation of certificates within Terraform itself. In this case it looks like you're trying to create a new CA cert and key, which could be done with tls_self_signed_cert like this:

```<code>resource "tls_private_key" "ca" {
  algorithm = "RSA"
  rsa_bits = 2048
}

resource "tls_self_signed_cert" "ca" {
  key_algorithm   = "RSA"
  private_key_pem = "${tls_private_key.ca.private_key_pem}"

  # ... subject and validity settings, as appropriate

  is_ca_certificate = true

  allowed_uses = ["cert_signing"]
}

resource "aws_s3_bucket_object" "ca_cert" {
  bucket  = "${aws_s3_bucket.my_bucket.id}"
  key     = "ca.pem"
  content = "${resource.tls_self_signed_cert.ca.cert_pem}"
}

resource "aws_s3_bucket_object" "ca_key" {
  bucket  = "${aws_s3_bucket.my_bucket.id}"
  key     = "ca-key.pem"
  content = "${resource.tls_self_signed_cert.ca.private_key_pem}"
}
</code>```

The generated private key will be included in the state for use on future runs, so it's important to ensure that the state is stored securely. Note that this would also be true using the external data source, since data source results are also stored in state. Thus this approach is equivalent from the standpoint of where the secrets get stored.

I wrote more details about using Terraform for TLS certificate management in an article on my website. Its scope is broader than your requirements here, but may be of some interest.

Body:
As part of a setup, I create TLS certs and store them in S3. Creating the certs is done via external data source that runs the command to generate the certs. I then use those outputs to create S3 bucket object resources.

This works very well the first time I run terraform apply. However, if I change any other (non-cert) variable, resource, etc. and rerun, it reruns the external command, which generates a new key/cert pair, uploads them to S3, and breaks everything that already works.

Is there any way to create the resource conditionally? What pattern could I use to make the certs created only if they don't exist?

I did look at storing the generated keys/certs locally, but this is sensitive key material; I do not want it stored in local disk (and there are keys per environment).

Key/cert generation and storage:

data "external" "ca" {
  program = ["sh","-c","jq '.root|fromjson' | cfssl gencert -initca -"]
  #
  query = {root = "${ data.template_file.etcd-ca-csr.rendered }"}
  # the result will be saved in
  # data.external.etcd-ca.result.key
  # data.external.etcd-ca.result.csr
  # data.external.etcd-ca.result.cert
}

resource "aws_s3_bucket_object" "ca_cert" {
  bucket = "${aws_s3_bucket.my_bucket.id}"
  key = "ca.pem"
  content = "${data.external.ca.result.cert}"
}
resource "aws_s3_bucket_object" "ca_key" {
  bucket = "${aws_s3_bucket.my_bucket.id}"
  key = "ca-key.pem"
  content = "${data.external.ca.result.key}"
}

Happy to look at using some form of conditional or entirely different generation pattern.

Body:
The reason for this behavior is that external is a data source, and thus Terraform expects that it is is read-only and side-effect-free. It re-runs data sources for every plan.

In order to do this via an external script, it would be necessary to use a resource provisioner to run the script and upload it to S3, since there is currently no external equivalent for resources, which are allowed to have side-effects, and provisioners are side-effect-only (that is, they can't produce results to use elsewhere in config.)

Another approach, though, would be to use Terraform's built-in TLS provider, which allows creation of certificates within Terraform itself. In this case it looks like you're trying to create a new CA cert and key, which could be done with tls_self_signed_cert like this:

resource "tls_private_key" "ca" {
  algorithm = "RSA"
  rsa_bits = 2048
}

resource "tls_self_signed_cert" "ca" {
  key_algorithm   = "RSA"
  private_key_pem = "${tls_private_key.ca.private_key_pem}"

  # ... subject and validity settings, as appropriate

  is_ca_certificate = true

  allowed_uses = ["cert_signing"]
}

resource "aws_s3_bucket_object" "ca_cert" {
  bucket  = "${aws_s3_bucket.my_bucket.id}"
  key     = "ca.pem"
  content = "${resource.tls_self_signed_cert.ca.cert_pem}"
}

resource "aws_s3_bucket_object" "ca_key" {
  bucket  = "${aws_s3_bucket.my_bucket.id}"
  key     = "ca-key.pem"
  content = "${resource.tls_self_signed_cert.ca.private_key_pem}"
}

The generated private key will be included in the state for use on future runs, so it's important to ensure that the state is stored securely. Note that this would also be true using the external data source, since data source results are also stored in state. Thus this approach is equivalent from the standpoint of where the secrets get stored.

I wrote more details about using Terraform for TLS certificate management in an article on my website. Its scope is broader than your requirements here, but may be of some interest.


问:
Python tkinter creating two windows
I am currently trying to create two windows with a tkinter program but it doesn't seem to be working. It was only recently that i just moved over my game to tkinter and it is the first time working with tkinter. Due to that I have no clue why this isn't working.

This is my first window and its working fine

```<code>class Application(tk.Frame):
        def __init__(self, master=None):
            super().__init__(master)
            self.pack()
            self.create_widgets()
            self.crafting_listbox
</code>```

My second window though isn't working

```<code>class Application_2(tk.Frame):
        def __init__(self, master=None):
            super().__init__(master)
            self.pack()
            self.crafting_listbox()
</code>```

Then the finishing bit

```<code> root = tk.Tk()
    app = Application(master=root)
    app.mainloop()
</code>```

I am unsure why this isn't working, whats going wrong?

答:
You never call your second Frame.

To make a second window use the Toplevel class.

```<code>root = tk.Tk()
app = Application(master=root)

second_win = tk.Toplevel(root)
app2 = Application_2(second_win)

root.mainloop()
</code>```

Title: Python tkinter creating two windows

Body:
I am currently trying to create two windows with a tkinter program but it doesn't seem to be working. It was only recently that i just moved over my game to tkinter and it is the first time working with tkinter. Due to that I have no clue why this isn't working.

This is my first window and its working fine

class Application(tk.Frame):
        def __init__(self, master=None):
            super().__init__(master)
            self.pack()
            self.create_widgets()
            self.crafting_listbox

My second window though isn't working

class Application_2(tk.Frame):
        def __init__(self, master=None):
            super().__init__(master)
            self.pack()
            self.crafting_listbox()

Then the finishing bit

 root = tk.Tk()
    app = Application(master=root)
    app.mainloop()

I am unsure why this isn't working, whats going wrong?

Body:
You never call your second Frame.

To make a second window use the Toplevel class.

root = tk.Tk()
app = Application(master=root)

second_win = tk.Toplevel(root)
app2 = Application_2(second_win)

root.mainloop()


问:
Making a custom launcher
Followed this tutorial.

FROM TUTPLUS

Tut seems very simple and logical, the annoying part is, it just don't work(although everything seems to make sense).

when i click the home button my app wont run, neither i get any option to select among the default launcher app and my app, i can see the app among launcher app when i go to settings>home.

I did provide filters as given in tutorial.

```<code><activity
android:name=".HomeActivity"
android:label="Bawa launcher"
android:theme="@style/apptheme"
android:launchMode="singleTask"
android:stateNotNeeded="true"
>
<intent-filter>
  <action android:name="android.intent.action.MAIN" />
  <category android:name="android.intent.category.HOME" />
  <category android:name="android.intent.category.DEFAULT" />
  <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</code>```

答: Though a bit late, may help others. In phone's settings, selecting the default launcher to your launcher will solve the problem. In my case, above code worked by this method. </p>

Title: Making a custom launcher

Body:
Followed this tutorial.

FROM TUTPLUS

Tut seems very simple and logical, the annoying part is, it just don't work(although everything seems to make sense).

when i click the home button my app wont run, neither i get any option to select among the default launcher app and my app, i can see the app among launcher app when i go to settings>home.

I did provide filters as given in tutorial.

<activity
android:name=".HomeActivity"
android:label="Bawa launcher"
android:theme="@style/apptheme"
android:launchMode="singleTask"
android:stateNotNeeded="true"
>
<intent-filter>
  <action android:name="android.intent.action.MAIN" />
  <category android:name="android.intent.category.HOME" />
  <category android:name="android.intent.category.DEFAULT" />
  <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>


问:
recursion- find the biggest worm in matrix
i have the following question:
for a nXn matrix, we will define a "worm" at the size of k which is a series of adjacent cells with consecutive numbers. adjacent cell is the cell from the right\left\up\down of the current cell ( not diagonal).
i need to write a recursive function which return the longest worm in array
for instance: in matrix:

```<code>{{3,4,5,6},
 {5,6,2,7},
 {12,13,14,15},
 {19,18,17,16}};
</code>```

the longest worm is 8 cells. starting from [2][0] and ends at [3][0].

so far i have written the following code:

```<code>public static int longestWarm(int[][] arr, int row, int col) {
    if (row < 0 || row >= arr.length || col < 0 || col >= arr.length) return 0;
    if (col >= arr.length || row >= arr.length) return 0;

    int sum1 = 1, sum2 = 1, sum3 = 1, sum4 = 1;

    if (row > 0 && arr[row][col] == arr[row - 1][col] - 1)
            sum1 = 1 + longestWarm(arr, row - 1,col);
    else if (row < arr[0].length - 1 && arr[row][col] == arr[row + 1][col] - 1)
            sum2 = 1 + longestWarm(arr, row + 1, col);
    else if (col > 0 && arr[row][col] == arr[row][col - 1] - 1)
            sum3 = 1 + longestWarm(arr, row, col - 1);
    else if (col < arr[0].length - 1 && arr[row][col] == arr[row][col + 1] - 1)
            sum4 = 1 + longestWarm(arr, row, col + 1);

    int max1 = Math.max(sum1, sum2);
    int max2 = Math.max(sum3, sum4);

    return Math.max(max1, max2);
}
</code>```

the problem is that i get the first worm that i find in matrix and not the biggest one. my output is 5 and not 8.
please help finding what i am doing wrong.

答:
Your program works fine.
Add this.

```<code>public static int longestWarm(int[][] arr) {
    int len = arr.length;
    int max = 0;
    for (int row = 0; row < len; ++row) {
        for (int col = 0; col < len; ++col) {
            int length = longestWarm(arr, row, col);
            if (length > max)
                max = length;
        }
    }
    return max;
}
</code>```

And try this

```<code>int[][] arr = {
    {3, 4, 5, 6},
    {5, 6, 2, 7},
    {12, 13, 14, 15},
    {19, 18, 17, 16}};
System.out.println("lngest warm=" + longestWarm(arr));
</code>```

Body:
i have the following question:
for a nXn matrix, we will define a "worm" at the size of k which is a series of adjacent cells with consecutive numbers. adjacent cell is the cell from the right\left\up\down of the current cell ( not diagonal).
i need to write a recursive function which return the longest worm in array
for instance: in matrix:

{{3,4,5,6},
 {5,6,2,7},
 {12,13,14,15},
 {19,18,17,16}};

the longest worm is 8 cells. starting from [2][0] and ends at [3][0].

so far i have written the following code:

public static int longestWarm(int[][] arr, int row, int col) {
    if (row < 0 || row >= arr.length || col < 0 || col >= arr.length) return 0;
    if (col >= arr.length || row >= arr.length) return 0;

    int sum1 = 1, sum2 = 1, sum3 = 1, sum4 = 1;

    if (row > 0 && arr[row][col] == arr[row - 1][col] - 1)
            sum1 = 1 + longestWarm(arr, row - 1,col);
    else if (row < arr[0].length - 1 && arr[row][col] == arr[row + 1][col] - 1)
            sum2 = 1 + longestWarm(arr, row + 1, col);
    else if (col > 0 && arr[row][col] == arr[row][col - 1] - 1)
            sum3 = 1 + longestWarm(arr, row, col - 1);
    else if (col < arr[0].length - 1 && arr[row][col] == arr[row][col + 1] - 1)
            sum4 = 1 + longestWarm(arr, row, col + 1);

    int max1 = Math.max(sum1, sum2);
    int max2 = Math.max(sum3, sum4);

    return Math.max(max1, max2);
}

the problem is that i get the first worm that i find in matrix and not the biggest one. my output is 5 and not 8.
please help finding what i am doing wrong.

Body:
Your program works fine.
Add this.

public static int longestWarm(int[][] arr) {
    int len = arr.length;
    int max = 0;
    for (int row = 0; row < len; ++row) {
        for (int col = 0; col < len; ++col) {
            int length = longestWarm(arr, row, col);
            if (length > max)
                max = length;
        }
    }
    return max;
}

And try this

int[][] arr = {
    {3, 4, 5, 6},
    {5, 6, 2, 7},
    {12, 13, 14, 15},
    {19, 18, 17, 16}};
System.out.println("lngest warm=" + longestWarm(arr));


问:
Why can't I make an int array using 'const int*' same as 'const char*'?
Why can I create a string or array of chars in this way:

```<code>#include <iostream>
int main() {
  const char *string = "Hello, World!";
  std::cout << string[1] << std::endl;
}
</code>```

? and it outputs the second element correctly, while I can't make an array of integer type without the array's subscript notation [ ]? What's the difference between the char's one and this one: const int* intArray={3,54,12,53};.

答:
The strings litterals come from the C language. Any string declared with double quotes in the code is automatically converted as a const char[].

So this:

```<code>const char str[6] = "hello";
</code>```

Is exactly the same as:

```<code>const char str[6] = { 'h', 'e', 'l', 'l', 'o', '\0' };
</code>```

Body:
Why can I create a string or array of chars in this way:

#include <iostream>
int main() {
  const char *string = "Hello, World!";
  std::cout << string[1] << std::endl;
}

? and it outputs the second element correctly, while I can't make an array of integer type without the array's subscript notation [ ]? What's the difference between the char's one and this one: const int* intArray={3,54,12,53};.

Body:
The strings litterals come from the C language. Any string declared with double quotes in the code is automatically converted as a const char[].

So this:

const char str[6] = "hello";

Is exactly the same as:

const char str[6] = { 'h', 'e', 'l', 'l', 'o', '\0' };


问:
Avoiding SQL injections with complex dynamic SQL targeting OLEDB Linked Server
In SQL Server 2016, I'm running a complex dynamic SQL query on an OLE-DB Linked Server, inside a stored procedure.

I'm currently building the dynamic SQL as a string, concatenating parameters in many places. So, I'm concerned about SQL injection.

The linked server is actually connecting to the OLE-DB provider interface to OSISoft PI, which is a specialised historian database. I can't define stored procedures within PI, so I think dynamic SQL is the only way to get the flexibility I need.

I do use the QUOTENAME(input, '''') function to wrap the user-supplied parameters in quote marks, which should also escape any quote marks found in the input. But I'm not certain if this constitutes an EFFECTIVE defense against SQL injections. I mostly did it because it makes the literals simpler in the string concatenation.

The stored procedure currently looks something like this:

```<code>-- Wrap user-supplied parameters in quotes to simplify SQL string building
DECLARE @Tag1   NVARCHAR(30) = QUOTENAME(@Tag1Input, '''')
DECLARE @Tag2   NVARCHAR(30) = QUOTENAME(@Tag2Input, '''')
DECLARE @Tag3   NVARCHAR(30) = QUOTENAME(@Tag3Input, '''')
DECLARE @Tag4   NVARCHAR(30) = QUOTENAME(@Tag4Input, '''')
DECLARE @Tag5   NVARCHAR(30) = QUOTENAME(@Tag5Input, '''')
DECLARE @Tag6   NVARCHAR(30) = QUOTENAME(@Tag6Input, '''')
DECLARE @Tag7   NVARCHAR(30) = QUOTENAME(@Tag7Input, '''')
DECLARE @Tag8   NVARCHAR(30) = QUOTENAME(@Tag8Input, '''')
DECLARE @Tag9   NVARCHAR(30) = QUOTENAME(@Tag9Input, '''')
DECLARE @Tag10  NVARCHAR(30) = QUOTENAME(@Tag10Input, '''')
DECLARE @starttimeq NVARCHAR(10) = QUOTENAME(@starttime, '''')
DECLARE @endtimeq   NVARCHAR(10) = QUOTENAME(@endtime, '''')
DECLARE @timestepq  NVARCHAR(10) = QUOTENAME(@timestep, '''')
DECLARE @calcbasisq NVARCHAR(30) = QUOTENAME(@calcbasis, '''')

-- Build SQL statement
DECLARE @sql NVARCHAR(2000) = 'SELECT tag, time, value
FROM piarchive..piavg
WHERE
    tag IN (' + @Tag1 + ', ' + @Tag2 + ', ' +@Tag3 + ', ' + @Tag4 + ', ' + @Tag5 + ', ' + @Tag6 + ', ' + @Tag7+ ', ' + @Tag8 + ', ' + @Tag9 + ', ' + @Tag10 + ')
    AND time BETWEEN ' + @starttimeq + ' AND ' + @endtimeq + '
    AND timestep = ' + @timestepq + '
    AND calcbasis = ' + @calcbasisq + '
UNION
SELECT ''calculatedValue'' AS tag, time, value
FROM piarchive..piavg
WHERE
    expr = ''(''' + @Tag2 + ''' * (''' + @Tag3 + '''-''' + @Tag4 + ''') / (''' + @Tag2 + '''-''' + @Tag4 + ''') * 100.0 + ''' + @Tag5 + ''' * (''' + @Tag4 + '''-''' + @Tag1 + ''') / (''' + @Tag5 + '''-''' + @Tag1 + ''') * (''' +@Tag3 + '''-''' + @Tag2 + ''') / (''' + @Tag4 + '''-''' + @Tag2 + ''') * 100.0) / ((''' +@Tag3 + '''-''' + @Tag4 + ''') / (''' + @Tag2 + '''-''' + @Tag4 + ''') * 100.0 + (''' + @Tag4 + '''-''' + @Tag1 + ''') / (''' + @Tag5 + '''-''' + @Tag1 + ''') * (''' +@Tag3 + '''-''' + @Tag2 + ''') / (''' + @Tag4 + '''-''' + @Tag2 + ''') * 100.0)''
    AND time BETWEEN ' + @starttimeq + ' AND ' + @endtimeq + '
    AND timestep = ' + @timestepq + '
    AND calcbasis = ' + @calcbasisq + '
ORDER BY time ASC, tag ASC'

-- Invoke dynamic SQL on PI OLEDB linked server
EXEC (@sql) AT PI
</code>```

As far as I can tell, I can't use sp_executesql to run a query on an OLE-DB Linked Server. (Please correct me if I'm wrong).

And it seems like the EXEC(@sql, <params>) AT LinkedServer syntax only supports positional ? parameters due to OLE-DB limitations. Because of the hideous expr filter clause, I really want to use named parameters instead of positional parameters.

How can I safely prepare this SQL string, to guard against SQL injection attacks, when I can't use sp_executesql or named parameters? Is there an elegant approach or do I just have to brute-force it with 46 positional parameters including many repeats?

答:
In the end, I worked with the administrators of the PI system to enable the PI DATE and TIME function views within the pifunction catalog. These function views convert the PI-specific time literals into formats that SQL Server can handle, within the SQL Server execution context. (When I tried to set up these function views myself I got an error dialog which said Error creating TIME - View creation failed. [PI SDK] Item not found in collection: %OSI. It turns out this error was caused by my account not having sufficient security permissions within PI.)

After the function views were set up, I could replace the dynamic SQL with a conventional SQL query running inside the SQL Server context, using standard parameter substitutions. This eliminates the SQL injection risk, as well as significantly improving the readability of the code.

Body:
In SQL Server 2016, I'm running a complex dynamic SQL query on an OLE-DB Linked Server, inside a stored procedure.

I'm currently building the dynamic SQL as a string, concatenating parameters in many places. So, I'm concerned about SQL injection.

The linked server is actually connecting to the OLE-DB provider interface to OSISoft PI, which is a specialised historian database. I can't define stored procedures within PI, so I think dynamic SQL is the only way to get the flexibility I need.

I do use the QUOTENAME(input, '''') function to wrap the user-supplied parameters in quote marks, which should also escape any quote marks found in the input. But I'm not certain if this constitutes an EFFECTIVE defense against SQL injections. I mostly did it because it makes the literals simpler in the string concatenation.

The stored procedure currently looks something like this:

-- Wrap user-supplied parameters in quotes to simplify SQL string building
DECLARE @Tag1   NVARCHAR(30) = QUOTENAME(@Tag1Input, '''')
DECLARE @Tag2   NVARCHAR(30) = QUOTENAME(@Tag2Input, '''')
DECLARE @Tag3   NVARCHAR(30) = QUOTENAME(@Tag3Input, '''')
DECLARE @Tag4   NVARCHAR(30) = QUOTENAME(@Tag4Input, '''')
DECLARE @Tag5   NVARCHAR(30) = QUOTENAME(@Tag5Input, '''')
DECLARE @Tag6   NVARCHAR(30) = QUOTENAME(@Tag6Input, '''')
DECLARE @Tag7   NVARCHAR(30) = QUOTENAME(@Tag7Input, '''')
DECLARE @Tag8   NVARCHAR(30) = QUOTENAME(@Tag8Input, '''')
DECLARE @Tag9   NVARCHAR(30) = QUOTENAME(@Tag9Input, '''')
DECLARE @Tag10  NVARCHAR(30) = QUOTENAME(@Tag10Input, '''')
DECLARE @starttimeq NVARCHAR(10) = QUOTENAME(@starttime, '''')
DECLARE @endtimeq   NVARCHAR(10) = QUOTENAME(@endtime, '''')
DECLARE @timestepq  NVARCHAR(10) = QUOTENAME(@timestep, '''')
DECLARE @calcbasisq NVARCHAR(30) = QUOTENAME(@calcbasis, '''')

-- Build SQL statement
DECLARE @sql NVARCHAR(2000) = 'SELECT tag, time, value
FROM piarchive..piavg
WHERE
    tag IN (' + @Tag1 + ', ' + @Tag2 + ', ' +@Tag3 + ', ' + @Tag4 + ', ' + @Tag5 + ', ' + @Tag6 + ', ' + @Tag7+ ', ' + @Tag8 + ', ' + @Tag9 + ', ' + @Tag10 + ')
    AND time BETWEEN ' + @starttimeq + ' AND ' + @endtimeq + '
    AND timestep = ' + @timestepq + '
    AND calcbasis = ' + @calcbasisq + '
UNION
SELECT ''calculatedValue'' AS tag, time, value
FROM piarchive..piavg
WHERE
    expr = ''(''' + @Tag2 + ''' * (''' + @Tag3 + '''-''' + @Tag4 + ''') / (''' + @Tag2 + '''-''' + @Tag4 + ''') * 100.0 + ''' + @Tag5 + ''' * (''' + @Tag4 + '''-''' + @Tag1 + ''') / (''' + @Tag5 + '''-''' + @Tag1 + ''') * (''' +@Tag3 + '''-''' + @Tag2 + ''') / (''' + @Tag4 + '''-''' + @Tag2 + ''') * 100.0) / ((''' +@Tag3 + '''-''' + @Tag4 + ''') / (''' + @Tag2 + '''-''' + @Tag4 + ''') * 100.0 + (''' + @Tag4 + '''-''' + @Tag1 + ''') / (''' + @Tag5 + '''-''' + @Tag1 + ''') * (''' +@Tag3 + '''-''' + @Tag2 + ''') / (''' + @Tag4 + '''-''' + @Tag2 + ''') * 100.0)''
    AND time BETWEEN ' + @starttimeq + ' AND ' + @endtimeq + '
    AND timestep = ' + @timestepq + '
    AND calcbasis = ' + @calcbasisq + '
ORDER BY time ASC, tag ASC'

-- Invoke dynamic SQL on PI OLEDB linked server
EXEC (@sql) AT PI

As far as I can tell, I can't use sp_executesql to run a query on an OLE-DB Linked Server. (Please correct me if I'm wrong).

And it seems like the EXEC(@sql, <params>) AT LinkedServer syntax only supports positional ? parameters due to OLE-DB limitations. Because of the hideous expr filter clause, I really want to use named parameters instead of positional parameters.

How can I safely prepare this SQL string, to guard against SQL injection attacks, when I can't use sp_executesql or named parameters? Is there an elegant approach or do I just have to brute-force it with 46 positional parameters including many repeats?


问:
Execute .jar file from a Java program
How could I run a local jar file from a java program?

The jar file is not in the class-path of the Java caller program.

答:
Add jar library to your project

Import main class (see manifest in jar file)

Invoke static method main with arguments

```<code>String args[] = {"-emaple","value"};
PortMapperStarter.main(args);
</code>```

Title: Execute .jar file from a Java program

Body:
Add jar library to your project

Import main class (see manifest in jar file)

Invoke static method main with arguments

String args[] = {"-emaple","value"};
PortMapperStarter.main(args);


问:
zfcuser - whitelist routes and all childroutes
I'am using ZfcUser module in my application to protect access to /admin route. As I want to block all childroutes of /admin, except for /login, /register etc.

In order to do so, I've added a code from accepted answer here - Zend Framework 2 - Global check for authentication with ZFCUser

```<code>protected $whitelist = array('zfcuser/login', 'default');

  public function onBootstrap($e)
  {
      $app = $e->getApplication();
      $em  = $app->getEventManager();
      $sm  = $app->getServiceManager();

      $list = $this->whitelist;
      $auth = $sm->get('zfcuser_auth_service');

      $em->attach(MvcEvent::EVENT_ROUTE, function($e) use ($list, $auth) {
          $match = $e->getRouteMatch();

          // No route match, this is a 404
          if (!$match instanceof RouteMatch) {
              return;
          }

          // Route is whitelisted
          $name = $match->getMatchedRouteName();
          if (in_array($name, $list)) {
              return;
          }

          // User is authenticated
          if ($auth->hasIdentity()) {
              return;
          }

          // Redirect to the user login page, as an example
          $router   = $e->getRouter();
          $url      = $router->assemble(array(), array(
              'name' => 'zfcuser/login'
          ));

          $response = $e->getResponse();
          $response->getHeaders()->addHeaderLine('Location', $url);
          $response->setStatusCode(302);

          return $response;
      }, -100);
  }
</code>```

It works, however it also block access to root routes - and as there is plenty of them, I do not really want to add every single route to whitelist. Is there any way to restrict access only to /admin routes?

答:
I suggest taking a look at ZfcRbac.  It has a "guards" functionality that I think is exactly what you're looking for:

```<code>return [
    'zfc_rbac' => [
        'guards' => [
            'ZfcRbac\Guard\RouteGuard' => [
                'admin*' => ['admin']
            ]
        ]
    ]
];
</code>```

This would restrict any route starting with admin to users in the admin role.  Since the default operation mode is blacklist-based ("protection mode" is "allow"), you only need to specify rules for the routes you want to restrict access to.  Any route not matching a RouteGuard will be publicly-accessible.

Body:
I'am using ZfcUser module in my application to protect access to /admin route. As I want to block all childroutes of /admin, except for /login, /register etc.

In order to do so, I've added a code from accepted answer here - Zend Framework 2 - Global check for authentication with ZFCUser

protected $whitelist = array('zfcuser/login', 'default');

  public function onBootstrap($e)
  {
      $app = $e->getApplication();
      $em  = $app->getEventManager();
      $sm  = $app->getServiceManager();

      $list = $this->whitelist;
      $auth = $sm->get('zfcuser_auth_service');

      $em->attach(MvcEvent::EVENT_ROUTE, function($e) use ($list, $auth) {
          $match = $e->getRouteMatch();

          // No route match, this is a 404
          if (!$match instanceof RouteMatch) {
              return;
          }

          // Route is whitelisted
          $name = $match->getMatchedRouteName();
          if (in_array($name, $list)) {
              return;
          }

          // User is authenticated
          if ($auth->hasIdentity()) {
              return;
          }

          // Redirect to the user login page, as an example
          $router   = $e->getRouter();
          $url      = $router->assemble(array(), array(
              'name' => 'zfcuser/login'
          ));

          $response = $e->getResponse();
          $response->getHeaders()->addHeaderLine('Location', $url);
          $response->setStatusCode(302);

          return $response;
      }, -100);
  }

It works, however it also block access to root routes - and as there is plenty of them, I do not really want to add every single route to whitelist. Is there any way to restrict access only to /admin routes?

Body:
I suggest taking a look at ZfcRbac.  It has a "guards" functionality that I think is exactly what you're looking for:

return [
    'zfc_rbac' => [
        'guards' => [
            'ZfcRbac\Guard\RouteGuard' => [
                'admin*' => ['admin']
            ]
        ]
    ]
];

This would restrict any route starting with admin to users in the admin role.  Since the default operation mode is blacklist-based ("protection mode" is "allow"), you only need to specify rules for the routes you want to restrict access to.  Any route not matching a RouteGuard will be publicly-accessible.


问:
Spring-boot unwanted SQL UPDATE at the end of transaction
I'm using spring-boot 1.5.4 with hibernate-core 5.2.10.

I have a controller that invokes a service method (lets name it pService) to save an entity after some logic

pService.save is something like this:

```<code>@Transactional(readOnly = false, rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
public <S extends SomeEntity> S save(S entity) throws ServiceException {
    //some logic

    entity.setAttrX("original text");
    S justSavedEntity = someEntityRepository.save(entity); // POINT 1

   //we termporarily change one attribute just to get a legible representation calling another service method (lets name it eService)
   eService.process(justSavedEntity);

   return justSavedEntity; //POINT 2

}
</code>```

eService.process is something like this:

```<code>@Transactional(readOnly = false, propagation = Propagation.MANDATORY)
public void process(SomeEntity entity) {

    //some logic
    entity.setAttrX("someText");
    //method ends here
}
</code>```

Because there's no other call to save apart of the one at POINT 1, I expect the text "original text" to be saved in database, but the text I'm getting saved is the text changed at POINT 2.

So, why I'm getting saved "someText" instead of "original text"?

I can see in the database log that after POINT 1 an SQL INSERT command is runned  and when pService returns, and unwanted SQL UPDATE command is runned changing "original text" to "someText" causing the error.

why is this "extra" UPDATE command issued?

Thanks in advance!

答:
This is the expected behaviour as described by the JPA specification. You changed a managed entity, which is intended logically to be the same thing as changing the stored data, so before the transaction completes the state of the entity is synced with the database. The idea is that you don't have to call save at the end of the method -- it's redundant.

Arnold Galovics has written a pretty good blog post about this with pretty diagrams.

Given this it becomes obvious that you shouldn't be mutating the entity this way. It suggests that the 'process' you're calling isn't treating the object it is passed as an entity. It's a common mistake to think that just because your current object seems to provide everything you need in a different context that it's a good idea to use it in that context, rather than checking that the object represents the same concept. In this case, your process doesn't want an entity.

You should be creating a value object of some kind to pass to the process method. Creating a value object could be as easy as detaching the entity from it's persistence context: Spring JpaRepository - Detach and Attach entity

Or, you could just calculate the value of the field and pass it as a second param to your process method on eService. Your final option is to send the entity as is and have the receiving service calculate the 'legible' representation.

However, you have other problems. You'd probably realise what they are if you transitioned to spring-data-jpa rather than writing your own repository classes. In simple terms, the repository class is intended to store and retrieve an entity in a persistent store of some kind, it is not intended to invoke other services. That would be the responsibility of whatever code was using the repo in the first place. In a spring-mvc app this would typically be a controller, which exists to orchestrate your applications services.

To put it plainly, you shouldn't be calling a service from within a repo class. It should do nothing but CRUD on an entity -- absolutely nothing else, ever. If you need it to do something else, then you've probably done something else wrong or you've picked the wrong architecture for your app.

You should take a look at spring-data-jpa. It's configured by default to auto-generate the repo's implementation at run time. This would probably reduce your code base, save you a load of time and defects, and would not easily allow you to make this class of architectural mistake. And, to top it off, it's a lot easier than what you're doing now.

Body:
I'm using spring-boot 1.5.4 with hibernate-core 5.2.10.

I have a controller that invokes a service method (lets name it pService) to save an entity after some logic

pService.save is something like this:

@Transactional(readOnly = false, rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
public <S extends SomeEntity> S save(S entity) throws ServiceException {
    //some logic

    entity.setAttrX("original text");
    S justSavedEntity = someEntityRepository.save(entity); // POINT 1

   //we termporarily change one attribute just to get a legible representation calling another service method (lets name it eService)
   eService.process(justSavedEntity);

   return justSavedEntity; //POINT 2

}

eService.process is something like this:

@Transactional(readOnly = false, propagation = Propagation.MANDATORY)
public void process(SomeEntity entity) {

    //some logic
    entity.setAttrX("someText");
    //method ends here
}

Because there's no other call to save apart of the one at POINT 1, I expect the text "original text" to be saved in database, but the text I'm getting saved is the text changed at POINT 2.

So, why I'm getting saved "someText" instead of "original text"?

I can see in the database log that after POINT 1 an SQL INSERT command is runned  and when pService returns, and unwanted SQL UPDATE command is runned changing "original text" to "someText" causing the error.

why is this "extra" UPDATE command issued?

Thanks in advance!


问:
Change UIAlertController Background Tint
Yes, I know. You can't change the appearance of a UIAlertController. I don't want to change the background of the UIAlertController itself, I want to change the tint of the view's background. You know how it's like a transparent black color? I want to change that color to clear. How would I do this?

答:
You can change the background colour as follows:</p>

```<code>let alert = UIAlertController(title: "TITLE", message: "My message", preferredStyle: .alert)
if let subview = alert.view.subviews.first?.subviews.first?.subviews.first {
    subview.backgroundColor = .red
}
alert.view.tintColor = UIColor.black
</code>```

Body:
You can change the background colour as follows:

let alert = UIAlertController(title: "TITLE", message: "My message", preferredStyle: .alert)
if let subview = alert.view.subviews.first?.subviews.first?.subviews.first {
    subview.backgroundColor = .red
}
alert.view.tintColor = UIColor.black


问:
ES6-style Export-from in Typescript Module Definition (module.d.ts)
To be honest, I have very little idea what is actually happening. I am trying to create a declaration file based on the one shown here - something I have never done before.

I have these files (renamed and edited due to work rules):

project_one

some_interface.ts

```<code>import SomeOtherInterface from "some_other_file";

interface ThisInterface
{
  aMethodRequiring(aThing: SomeOtherInterface): void;
}

export default ThisInterface;
</code>```

index.d.ts

```<code>export { default as ThisInterface } from "some_interface";
</code>```

tsconfig.json

```<code>{
  "compilerOptions": {
    "baseUrl": "src",
    "noImplicitAny": true,
    "target": "es2015"
  },
  "exclude": [
    "src/**/*.type.ts"
  ],
  "include": [
    "src/**/*.ts"
  ]
}
</code>```

project_two

some_class.ts

```<code>/// <reference types="project_one" />
     /* ^ This seems to be fine ^ */

import SomethingInThisProject from "a_file_in_this_project";
import { ThisInterface }      from "project_one"; // <=== This is the line that fails.

class ThatClass
{
  private instanceOfThisInterface : ThisInterface;

  constructor(saidInstance: ThisInterface)
  {
    this.instanceOfThisInterface = saidInstance;
  }

  // The useful stuff
}

export default ThatClass;
</code>```

tsconfig.json

```<code>{
  "compilerOptions": {
    "baseUrl": "src",
    "noImplicitAny": true,
    "target": "es2015"
  },
  "exclude": [
    "src/**/*.type.ts"
  ],
  "include": [
    "src/**/*.ts"
  ]
}
</code>```

package.json

```<code>{
  "name": "project_two",
  "version": "0.1.0",
  "description": "A Second Project",
  "main": "index.js",
  "repository": "https://github.com/project/two",
  "author": "Cyle Ven Dawson",
  "license": "MIT",
  "devDependencies": {
    ...
  },
  "dependencies": {
    ...
    "project_one": "^0.5.0"
  }
}
</code>```

TypeScript finds the project_one declaration file just fine. However, it yells at me about the importing from it, saying [ts] cannot find module 'project_one'. I imagine there is more wrong with this code than simply how I try to import things from the declaration file, but for now I am looking to get the import line to work.

What have I misunderstood?

答:
The location of the custom typing should be referenced in the tsconfig.json

```<code>{
    "compilerOptions": {
        "typeRoots": [
            "./custom_typings",
            "./node_modules/@types"
        ]
    }
}
</code>```

See tsconfig documentation for more detailed information.

Body:
To be honest, I have very little idea what is actually happening. I am trying to create a declaration file based on the one shown here - something I have never done before.

I have these files (renamed and edited due to work rules):

project_one

some_interface.ts

import SomeOtherInterface from "some_other_file";

interface ThisInterface
{
  aMethodRequiring(aThing: SomeOtherInterface): void;
}

export default ThisInterface;

index.d.ts

export { default as ThisInterface } from "some_interface";

tsconfig.json

{
  "compilerOptions": {
    "baseUrl": "src",
    "noImplicitAny": true,
    "target": "es2015"
  },
  "exclude": [
    "src/**/*.type.ts"
  ],
  "include": [
    "src/**/*.ts"
  ]
}

project_two

some_class.ts

/// <reference types="project_one" />
     /* ^ This seems to be fine ^ */

import SomethingInThisProject from "a_file_in_this_project";
import { ThisInterface }      from "project_one"; // <=== This is the line that fails.

class ThatClass
{
  private instanceOfThisInterface : ThisInterface;

  constructor(saidInstance: ThisInterface)
  {
    this.instanceOfThisInterface = saidInstance;
  }

  // The useful stuff
}

export default ThatClass;

tsconfig.json

{
  "compilerOptions": {
    "baseUrl": "src",
    "noImplicitAny": true,
    "target": "es2015"
  },
  "exclude": [
    "src/**/*.type.ts"
  ],
  "include": [
    "src/**/*.ts"
  ]
}

package.json

{
  "name": "project_two",
  "version": "0.1.0",
  "description": "A Second Project",
  "main": "index.js",
  "repository": "https://github.com/project/two",
  "author": "Cyle Ven Dawson",
  "license": "MIT",
  "devDependencies": {
    ...
  },
  "dependencies": {
    ...
    "project_one": "^0.5.0"
  }
}

TypeScript finds the project_one declaration file just fine. However, it yells at me about the importing from it, saying [ts] cannot find module 'project_one'. I imagine there is more wrong with this code than simply how I try to import things from the declaration file, but for now I am looking to get the import line to work.

What have I misunderstood?

Body:
The location of the custom typing should be referenced in the tsconfig.json

{
    "compilerOptions": {
        "typeRoots": [
            "./custom_typings",
            "./node_modules/@types"
        ]
    }
}

See tsconfig documentation for more detailed information.


问:
IconToolbarItem with Iconize not click event
I am currently developing a Xamarin.Forms application.  I am using IconizePlugin.  The app is tabbedPage based and on toolbar I'm trying to include icons for some actions.

This is whay I'm getting:

Icons are showing well and in Xamarin.iOS gets the click event, while it is not working in Xamarin.Droid.

I included the corresponding nugets and followed every steps told in documentation and can't archive this.  Other iconize controls in Droid are working fine except the IconToolbarItem.

Please help!

答:
The workaround I found was to declare de IconToolbarItem in the c# code instead of xaml.  Although I don't know why it wasn't working while on xaml.

Declaring the item li

```<code>ToolbarItems.Add(new IconToolbarItem
{
       Icon = "fa-plus",
       IconColor = Color.White,
       Command = new Command(this.addBono)
});
</code>```

Body:
The workaround I found was to declare de IconToolbarItem in the c# code instead of xaml.  Although I don't know why it wasn't working while on xaml.

Declaring the item li

ToolbarItems.Add(new IconToolbarItem
{
       Icon = "fa-plus",
       IconColor = Color.White,
       Command = new Command(this.addBono)
});


答:
Such a feature exists in C and is named compound literal.

For example

```<code>#include <stdio.h>

int main(void)
{
    const int *intArray = ( int[] ){ 3, 54, 12, 53 };

    printf( "%d\n", intArray[1] );

    return 0;
}
</code>```

However C++ does not support this feature from C.

There is a difference compared with string literals. String literals have static storage duration independent on where they appear while compound literals have either static storage duration or automatic storage duration dependent on where they are appear.

In C++ something that is close to this feature is std::initializer_list . For example

```<code>#include <iostream>
#include <initializer_list>

int main()
{
    const auto &myArray = { 3, 54, 12, 53 };

    std::cout << myArray.begin()[1] << std::endl;

    return 0;
}
</code>```

Title: Why can't I make an int array using 'const int*' same as 'const char*'?

Body:
Such a feature exists in C and is named compound literal.

For example

#include <stdio.h>

int main(void)
{
    const int *intArray = ( int[] ){ 3, 54, 12, 53 };

    printf( "%d\n", intArray[1] );

    return 0;
}

However C++ does not support this feature from C.

There is a difference compared with string literals. String literals have static storage duration independent on where they appear while compound literals have either static storage duration or automatic storage duration dependent on where they are appear.

In C++ something that is close to this feature is std::initializer_list . For example

#include <iostream>
#include <initializer_list>

int main()
{
    const auto &myArray = { 3, 54, 12, 53 };

    std::cout << myArray.begin()[1] << std::endl;

    return 0;
}