问:
react-sortable-hoc reactJS library sorting issue
I'm trying out a sample using react-sortable-hoc. Sortables are failed to keep the state on sorting. Have a look at the GIF.

Below is my sample code..

```<code>import React, {Component} from 'react';
import {SortableContainer, SortableElement, arrayMove} from 'react-sortable-
hoc';
// Css
import './object_library.css'

const SortableItem = SortableElement(({value}) =>
<div className="Showcase_test_horizontalItem" >
    <div>{value}</div>
    <br />
    <TestSortable />
</div>
);

const SortableList = SortableContainer(({items}) => {
return (
    <div>
        {items.map((value, index) => (
            <SortableItem key={`item-${index}`} index={index} value={value}
/>
        ))}
    </div>
  );
});

class TestSortable extends Component {
constructor(props) {
    super(props);
    this.state = {
        sum: 0
    }
    this.onAddChild = this.onAddChild.bind(this)
}
onAddChild () {
    let prevSum = this.state.sum + 1;
    this.setState({
        sum: prevSum
    });
}
render() {
    return (
        <div>
            <div> {this.state.sum} </div>
            <button className="my_plus_buttons" onClick={this.onAddChild}>+
            </button>
        </div>
    );
   }
 }

 class SortableComponent extends Component {
 state = {
    items: ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5', 'Item 6'],
 };
 onSortEnd = ({oldIndex, newIndex}) => {
    this.setState({
        items: arrayMove(this.state.items, oldIndex, newIndex),
    });
};
render() {
    return <SortableList items={this.state.items} onSortEnd={this.onSortEnd}
    axis="x"/>;
  }
 }

 export default SortableComponent;
</code>```

Not sure why this library is not maintaining states ?

Thanks

答:
In your SortableList,  you're setting a key based on the current index, which is a normal thing to do but it seems to be what causes the problem.  Make the key match the value instead and it seems to work as expected.

I'd guess the key needs to move with the underlying component.

```<code>const SortableList = SortableContainer(({ items }) => {
  return (
    <div>
      {items.map((value, index) => (
        <SortableItem key={`item-${value}`} index={index} value={value} />
      ))}
    </div>
  );
});
</code>```

Body:
I'm trying out a sample using react-sortable-hoc. Sortables are failed to keep the state on sorting. Have a look at the GIF.

Below is my sample code..

import React, {Component} from 'react';
import {SortableContainer, SortableElement, arrayMove} from 'react-sortable-
hoc';
// Css
import './object_library.css'

const SortableItem = SortableElement(({value}) =>

{value}

    <TestSortable />

);

const SortableList = SortableContainer(({items}) => {
return (

        {items.map((value, index) => (
            <SortableItem key={`item-${index}`} index={index} value={value}
/>
        ))}

  );
});

class TestSortable extends Component {
constructor(props) {
    super(props);
    this.state = {
        sum: 0
    }
    this.onAddChild = this.onAddChild.bind(this)
}
onAddChild () {
    let prevSum = this.state.sum + 1;
    this.setState({
        sum: prevSum
    });
}
render() {
    return (

 {this.state.sum}

            <button className="my_plus_buttons" onClick={this.onAddChild}>+
            </button>

    );
   }
 }

 class SortableComponent extends Component {
 state = {
    items: ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5', 'Item 6'],
 };
 onSortEnd = ({oldIndex, newIndex}) => {
    this.setState({
        items: arrayMove(this.state.items, oldIndex, newIndex),
    });
};
render() {
    return <SortableList items={this.state.items} onSortEnd={this.onSortEnd}
    axis="x"/>;
  }
 }

 export default SortableComponent;

Not sure why this library is not maintaining states ?

Thanks

Body:
In your SortableList,  you're setting a key based on the current index, which is a normal thing to do but it seems to be what causes the problem.  Make the key match the value instead and it seems to work as expected.

I'd guess the key needs to move with the underlying component.

const SortableList = SortableContainer(({ items }) => {
  return (
    <div>
      {items.map((value, index) => (
        <SortableItem key={`item-${value}`} index={index} value={value} />
      ))}
    </div>
  );
});


来源: stackexchange

问:
Generalize function to fold both elements with one higher-kinded type and with two nested types?
I have next two elements:

```<code>x :: Maybe t
y :: [(String, t)]
</code>```

And I have a function:

```<code>foo :: t -> a
</code>```

How can I implement polymorphic function that can work both on x and y with foo to collect results in list? More specifically, I need to put something instead of ??? here:

```<code>mapToList :: ??? => (t -> a) -> ??? t -> [a]
</code>```

And I want to call with less boilerplate possible, most closest option to this is preferable:

```<code>mapToList foo x
mapToList foo y
</code>```

Something naive like this doesn't work :(

```<code>mapToList :: Foldable f => (t -> a) -> f t -> [a]
mapToList extractor = map extractor . toList

mapToList @Maybe             foo x
mapToList @([] ((,) String)) foo y
</code>```

I was looking at Compose but didn't manage to figure out how to apply it to my problem in nice simple way. I can use Compose to generalize somehow but my solution is not satisfactory. I can always use map for lists and just maybe [] foo on Maybe's. But I wonder, is there nice way to generalize both use cases?

答:
Not sure this helps at all since it's just shifting the boilerplate away from the call site, but:</p>

```<code>{-# LANGUAGE FlexibleInstances,FunctionalDependencies,RankNTypes #-}

import Data.Functor.Compose (Compose(Compose))
import Data.Foldable

class AsFoldable x a | x -> a where
  withFoldable :: (forall f. (Foldable f) => f a -> b) -> x -> b

instance AsFoldable [(String,a)] a where
  withFoldable f = f . Compose

instance AsFoldable (Maybe a) a where
  withFoldable = id

x :: Maybe Int
x = Just 3

y :: [(String,Int)]
y = [("A",5),("B",6)]

mapToList :: (AsFoldable x t) => (t -> a) -> x -> [a]
mapToList f = withFoldable (map f . toList)

main = do
  print $ mapToList (+1) x
  print $ mapToList (+1) y
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have next two elements:

x :: Maybe t
y :: [(String, t)]

And I have a function:

foo :: t -> a

How can I implement polymorphic function that can work both on x and y with foo to collect results in list? More specifically, I need to put something instead of ??? here:

mapToList :: ??? => (t -> a) -> ??? t -> [a]

And I want to call with less boilerplate possible, most closest option to this is preferable:

mapToList foo x
mapToList foo y

Something naive like this doesn't work :(

mapToList :: Foldable f => (t -> a) -> f t -> [a]
mapToList extractor = map extractor . toList

mapToList @Maybe             foo x
mapToList @([] ((,) String)) foo y

I was looking at Compose but didn't manage to figure out how to apply it to my problem in nice simple way. I can use Compose to generalize somehow but my solution is not satisfactory. I can always use map for lists and just maybe [] foo on Maybe's. But I wonder, is there nice way to generalize both use cases?

Body:
Not sure this helps at all since it's just shifting the boilerplate away from the call site, but:

{-# LANGUAGE FlexibleInstances,FunctionalDependencies,RankNTypes #-}

import Data.Functor.Compose (Compose(Compose))
import Data.Foldable

class AsFoldable x a | x -> a where
  withFoldable :: (forall f. (Foldable f) => f a -> b) -> x -> b

instance AsFoldable [(String,a)] a where
  withFoldable f = f . Compose

instance AsFoldable (Maybe a) a where
  withFoldable = id

x :: Maybe Int
x = Just 3

y :: [(String,Int)]
y = [("A",5),("B",6)]

mapToList :: (AsFoldable x t) => (t -> a) -> x -> [a]
mapToList f = withFoldable (map f . toList)

main = do
  print $ mapToList (+1) x
  print $ mapToList (+1) y


问:
SQL Server Bulk Insert failing when called from .NET SqlCommand
I have a stored procedure which does bulk insert on a SQL server 2005 database.
When I call this stored procedure from some SQL (passing in the name of a local format file and data file) it works fine. Every time.

However, when this same stored procedure gets called from C# .NET 3.5 code using SqlCommand.ExecuteNonQuery it works intermittently.

When it fails a SqlException is generated stating:

Cannot bulk load. Invalid column number in the format file "c:\bulkinsert\MyFile.fmt"

I don't think this error message is correct.

Has anyone experienced similar problems with calling bulk insert from code?

Thanks.

答:
How are you doing the bulk insert? Usually, the problem (in this scenario) is whether "c:\" is the server's "c:\", or the client's "c:\".

However. from C# code, the simplest approach is to use SqlBulkCopy. This class provides direct access to bulk-insert functionality from managed code, including mappings (although I never bother with them).

If the file is something like csv / tsv / similar, then CsvReader is highly recommended. This provides the IDataReader interface that WriteToServer uses most efficiently.

OwnerDisplayName: Nick Wright

LastEditorDisplayName: Cade Roux

OwnerDisplayName: Marc Gravell

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Marc Gravell


问:
Problem with Tail Recursion in g++
I'm was messing around with tail-recursive functions in C++, and I've run into a bit of  a snag with the g++ compiler.

The following code results in a stack overflow when numbers[] is over a couple hundred integers in size. Examining the assembly code generated by g++ for the following reveals that twoSum_Helper is executing a recursive call instruction to itself.

The question is which of the following is causing this?

A mistake in the following that I am overlooking which prevents tail-recursion.

A mistake with my usage of g++.

A flaw in the detection of tail-recursive functions within the g++ compiler.

I am compiling with g++ -O3 -Wall -fno-stack-protector test.c on Windows Vista x64 via MinGW with g++ 4.5.0.

```<code>struct result
{
    int i;
    int j;
    bool found;
};

struct result gen_Result(int i, int j, bool found)
{
    struct result r;
    r.i = i;
    r.j = j;
    r.found = found;
    return r;
}

// Return 2 indexes from numbers that sum up to target.
struct result twoSum_Helper(int numbers[], int size, int target, int i, int j)
{
    if (numbers[i] + numbers[j] == target)
        return gen_Result(i, j, true);
    if (i >= (size - 1))
        return gen_Result(i, j, false);
    if (j >= size)
        return twoSum_Helper(numbers, size, target, i + 1, i + 2);
    else
        return twoSum_Helper(numbers, size, target, i, j + 1);
}
</code>```

答:
Try compilling with -O2 instead of -O3.

How do I check if gcc is performing tail-recursion optimization?

well, it doesn't work with O2 anyway. The only thing that seems to work is returning the result object into a reference that is given as a parameter.

but really, it's much easier to just remove the Tail call and use a loop instead. TCO is here to optimize tail call that are found when inlining or when performing agressive unrolling, but you shouldn't attempt to use recursion when handling large values anyway.

Title: Problem with Tail Recursion in g++

Body:
I'm was messing around with tail-recursive functions in C++, and I've run into a bit of  a snag with the g++ compiler.

The following code results in a stack overflow when numbers[] is over a couple hundred integers in size. Examining the assembly code generated by g++ for the following reveals that twoSum_Helper is executing a recursive call instruction to itself.

The question is which of the following is causing this?

A mistake in the following that I am overlooking which prevents tail-recursion.

A mistake with my usage of g++.

A flaw in the detection of tail-recursive functions within the g++ compiler.

I am compiling with g++ -O3 -Wall -fno-stack-protector test.c on Windows Vista x64 via MinGW with g++ 4.5.0.

struct result
{
    int i;
    int j;
    bool found;
};

struct result gen_Result(int i, int j, bool found)
{
    struct result r;
    r.i = i;
    r.j = j;
    r.found = found;
    return r;
}

// Return 2 indexes from numbers that sum up to target.
struct result twoSum_Helper(int numbers[], int size, int target, int i, int j)
{
    if (numbers[i] + numbers[j] == target)
        return gen_Result(i, j, true);
    if (i >= (size - 1))
        return gen_Result(i, j, false);
    if (j >= size)
        return twoSum_Helper(numbers, size, target, i + 1, i + 2);
    else
        return twoSum_Helper(numbers, size, target, i, j + 1);
}


问:
twisted (17.5.0) SSHConnection using previously closed channel (ssh_CHANNEL_OPEN_CONFIRMATION)
I use an SSHChannel over a "persistent" SSHConnection. Occasionally a previously closed localChannel will attempt to be used and results in a KeyError because the localChannel is not in the SSHConnection.channels[].

Here are some log snippets:

```<code>2017-07-05 07:54:50-0500 [-] openChannel localChannelID=2
2017-07-05 07:54:50-0500 [-] opening channel 2 with 65536 32768
2017-07-05 07:54:50-0500 [SSHChannel session (2) on SSHService 'ssh-connection' on ClientTransport,client] sending close 2
2017-07-05 07:54:50-0500 [SSHService 'ssh-connection' on ClientTransport,client] channelClosed id=2
</code>```

So now channel 2 is closed. Later (after several new channels), I see this:

```<code>2017-07-05 08:54:55-0500 [-] openChannel localChannelID=2
2017-07-05 08:54:55-0500 [-] opening channel 2 with 65536 32768
2017-07-05 08:54:55-0500 [SSHService 'ssh-connection' on ClientTransport,client] Unhandled Error Traceback (most recent call last):
<snipped irrelevant>
File "/usr/local/lib/python2.7/dist-packages/twisted/conch/ssh/connection.py", line 180, in ssh_CHANNEL_OPEN_CONFIRMATION channel = self.channels[localChannel]
exceptions.KeyError: 2
</code>```

Note that I have timers on the connections but I reset these before using.

I'm lost and can't determine why it works "most of the time" but then randomly fails. How can I test to prevent since it seems to open without any noticeable error.

答:
After talking to the twisted guys who offered to look at my code, I made a minimal single-file.py app to perform test runs and never had the issue. Observer altered reality?

Then I realized there are a couple of threads in the application which were there before moving to twisted a long time ago. They never manifested themselves in any other way.

I removed the python threads and now it's running without the channel problem. (As a side note, I had overcome the channel problem by sending deferreds to a point where I could re-start the channel open and it would work but I'm glad to have that work-around out of the code)

Body:
I use an SSHChannel over a "persistent" SSHConnection. Occasionally a previously closed localChannel will attempt to be used and results in a KeyError because the localChannel is not in the SSHConnection.channels[].

Here are some log snippets:

2017-07-05 07:54:50-0500 [-] openChannel localChannelID=2
2017-07-05 07:54:50-0500 [-] opening channel 2 with 65536 32768
2017-07-05 07:54:50-0500 [SSHChannel session (2) on SSHService 'ssh-connection' on ClientTransport,client] sending close 2
2017-07-05 07:54:50-0500 [SSHService 'ssh-connection' on ClientTransport,client] channelClosed id=2

So now channel 2 is closed. Later (after several new channels), I see this:

2017-07-05 08:54:55-0500 [-] openChannel localChannelID=2
2017-07-05 08:54:55-0500 [-] opening channel 2 with 65536 32768
2017-07-05 08:54:55-0500 [SSHService 'ssh-connection' on ClientTransport,client] Unhandled Error Traceback (most recent call last):
<snipped irrelevant>
File "/usr/local/lib/python2.7/dist-packages/twisted/conch/ssh/connection.py", line 180, in ssh_CHANNEL_OPEN_CONFIRMATION channel = self.channels[localChannel]
exceptions.KeyError: 2

Note that I have timers on the connections but I reset these before using.

I'm lost and can't determine why it works "most of the time" but then randomly fails. How can I test to prevent since it seems to open without any noticeable error.


问:
CSS - positioning images centrally within a container
I'm trying to line up some images within a container and can't seem to move them to make them central. This is how they currently look

I need to sit completely centrally and as is evident they are too far over to the right. I've tried lots of different things but can't get it right. I don't think I'm identifying the correct element.

Here's my code for the section on the photo

body {
  margin: 0 auto 0 auto;
}

.container {
  margin: auto;
  max-width: 100%;
  padding-left: 10px;
  padding-right: 10px;
}

section#welcome {
  height: 500px;
  max-width: 100%;
}

section#welcome div.row {
  height: 250px;
  text-align: center;
  position: relative;
}

#welcome h4 {
  color: #000000;
  font-size: 20px;
  padding-top: 50px;
  line-height: 5px;
}

section#welcome p {
  font-size: 10px;
  color: #bdc3c7;
  position: absolute;
  top: 50%;
  left: 50%;
  margin-right: -50%;
  transform: translate(-50%, -50%)
}

/* centering an image within a column */

section#welcome .four {
  position: relative;
  display: inline-block;
  bottom: 50px;
}

.four h3 {
  position: absolute;
  color: #FFF;
  font-size: 20px;
  margin: 0;
  top: 50%;
  left: 55%;
  transform: translate(-50%, -50%);
}

section#welcome img {
  display: block;
  margin-bottom: 30px;
}

.images,
.four {
  margin-right: 100px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section id="welcome">
  <div class="container">
    <div class="row">
      <div class="twelve columns">
        <h4>WELCOME TO FEATURE MEDIA</h4>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vel ex nisl. Vestibulum vitae ultricies nisl. Praesent sodales, leo at pellentesque pellentesque, nunc erat dapibus nunc, ut congue libero lorem in orci. Suspendisse potenti. Quisque
          facilisis mauris in vestibulum tempor. Suspendisse nec venenatis nisi. Phasellus sodales viverra ante quis efficitur. Pellentesque quis orci mi. Phasellus tempus, sapien ut luctus pellentesque, lacus risus accumsan lorem, in porta urna tellus
          ac nibh. Nunc varius elit non diam vehicula aliquet. In eget urna id orci molestie pulvinar. Integer quis risus eu erat iaculis aliquet ut at eros. Etiam feugiat, ante vel molestie finibus, lacus urna pharetra leo, ut lobortis massa lectus quis
          lorem. Vestibulum rhoncus turpis sagittis sapien vulputate sagittis. Nunc ac velit sollicitudin, consequat arcu ac, tincidunt risus.</p>
      </div>
    </div>
    <hr class="hrindeximages">
    <div class="images row">
      <div class="four columns">
        <div id="video">
          <h3>VIDEO</h3>
          <img src="images/VIDEO.jpg" alt="Video" style="width:300px;height:150px;">
        </div>
      </div>
      <div class="four columns">
        <div id="blog">
          <h3>BLOG</h3>
          <img src="images/blog.jpg" alt="blog" style="width:300px;height:150px;">
        </div>
      </div>
      <div class="four columns">
        <div id="faq">
          <h3>FAQ</h3>
          <img src="images/faq.jpg" alt="FAQ" style="width:300px;height:150px;">
        </div>
      </div>
    </div>
  </div>
</section></code>```

答: Use the padding attribute to manually center the images.</p>

Body:
I'm trying to line up some images within a container and can't seem to move them to make them central. This is how they currently look

I need to sit completely centrally and as is evident they are too far over to the right. I've tried lots of different things but can't get it right. I don't think I'm identifying the correct element.

Here's my code for the section on the photo

body {
  margin: 0 auto 0 auto;
}

.container {
  margin: auto;
  max-width: 100%;
  padding-left: 10px;
  padding-right: 10px;
}

section#welcome {
  height: 500px;
  max-width: 100%;
}

section#welcome div.row {
  height: 250px;
  text-align: center;
  position: relative;
}

#welcome h4 {
  color: #000000;
  font-size: 20px;
  padding-top: 50px;
  line-height: 5px;
}

section#welcome p {
  font-size: 10px;
  color: #bdc3c7;
  position: absolute;
  top: 50%;
  left: 50%;
  margin-right: -50%;
  transform: translate(-50%, -50%)
}

/* centering an image within a column */

section#welcome .four {
  position: relative;
  display: inline-block;
  bottom: 50px;
}

.four h3 {
  position: absolute;
  color: #FFF;
  font-size: 20px;
  margin: 0;
  top: 50%;
  left: 55%;
  transform: translate(-50%, -50%);
}

section#welcome img {
  display: block;
  margin-bottom: 30px;
}

.images,
.four {
  margin-right: 100px;
}

WELCOME TO FEATURE MEDIA

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vel ex nisl. Vestibulum vitae ultricies nisl. Praesent sodales, leo at pellentesque pellentesque, nunc erat dapibus nunc, ut congue libero lorem in orci. Suspendisse potenti. Quisque
          facilisis mauris in vestibulum tempor. Suspendisse nec venenatis nisi. Phasellus sodales viverra ante quis efficitur. Pellentesque quis orci mi. Phasellus tempus, sapien ut luctus pellentesque, lacus risus accumsan lorem, in porta urna tellus
          ac nibh. Nunc varius elit non diam vehicula aliquet. In eget urna id orci molestie pulvinar. Integer quis risus eu erat iaculis aliquet ut at eros. Etiam feugiat, ante vel molestie finibus, lacus urna pharetra leo, ut lobortis massa lectus quis
          lorem. Vestibulum rhoncus turpis sagittis sapien vulputate sagittis. Nunc ac velit sollicitudin, consequat arcu ac, tincidunt risus.

VIDEO

BLOG

FAQ


问:
How to count results passing a subquery in Knex?
I have a big query that selects multiple columns from multiple tables, and I would like to know how many records there are (doing a count).

I cannot get the length of the results because I also add .offset and .limit to the query.

Is there a way I can generate the following

```<code>SELECT COUNT(*) FROM (
  knex query
) as count
</code>```

with knex? How?

(version: 0.11.10)

答:
Got this from the documentation on the current site.

```<code>knex('users').count('active as a')
Outputs:
select count(`active`) as `a` from `users`
</code>```

Knex documentation v 0.13.0

searching for "select count" will give you a few more examples.

Body:
I have a big query that selects multiple columns from multiple tables, and I would like to know how many records there are (doing a count).

I cannot get the length of the results because I also add .offset and .limit to the query.

Is there a way I can generate the following

SELECT COUNT(*) FROM (
  knex query
) as count

with knex? How?

(version: 0.11.10)

Body:
Got this from the documentation on the current site.

knex('users').count('active as a')
Outputs:
select count(`active`) as `a` from `users`

Knex documentation v 0.13.0

searching for "select count" will give you a few more examples.


问:
How to declare a generic type Multi-Dimensional array in java
I want to store an array of 100 int elements in rows ie 1 row of 100 int datatypes.And every single element contains an array of 100 objects.How to do this in java or android. </p>

答:
Here is how you can initialize and fill a two-dimensional Object array:

```<code>    Object value = 42;
    int rows = 100;
    int columns = 100;
    Object[][] myData = new Object[rows][columns];
    for (int r = 0; r < rows; r++) {
        for (int c = 0; c < columns; c++) {
            myData[r][c] = value;
        }
    }
</code>```

Note that the primitive int value 42 is autoboxed when it is stored in the Object[][]. If you don't want this you could use an int[][] instead.

Body:
Here is how you can initialize and fill a two-dimensional Object array:

    Object value = 42;
    int rows = 100;
    int columns = 100;
    Object[][] myData = new Object[rows][columns];
    for (int r = 0; r < rows; r++) {
        for (int c = 0; c < columns; c++) {
            myData[r][c] = value;
        }
    }

Note that the primitive int value 42 is autoboxed when it is stored in the Object[][]. If you don't want this you could use an int[][] instead.


问:
Properly using environment.ts in my angular4 application with angular-cli
I use Intellij Ultimate to code my angular 4 application.

I created a new Angular 4 project, it contains environment.ts and environment.prod.ts and the environments are properly configured in angular-cli.json.

how do I import it in my code? Since actually when I build it I state which environment to use. How does it work? Do I need to compile something with Intellij?

I tried googling and found many examples when people actually imported a specific environment.ts file. but that's not good, right? Since it will use the same environment.ts file even if I build for a different environment.

What do I do?

答:
I had this same question, and found the same article that @Ahmed posted.  However, that didn't fix my problem: I just got:

```<code>ERROR in XXX/src/app/app.component.ts (19,29): Cannot find module './environment'.
</code>```

I'm working with a build created via ng new, so if you are working with the latest angular client you will likely have the same problem I had.  As @Ahmed states in his comment on his answer, it is important that you get the relative path correct.  The (current) version of the ng cli puts your main application component here:

```<code>projectFolder/app/src/app.component.ts
</code>```

And it places the environment file here:

```<code>projectFolder/app/environments/environment.ts
</code>```

Therefore, the correct line to include the environment from inside your app.component is this:

```<code>import { environment } from '../environments/environment';
</code>```

Small "feature": environment.ts is actually the environment configuration file for the development environment.  However, at run time (either due to the ng build command or ng serve command), this file will be replaced by whatever the actual environment states.  So even though you are explicitly including the development environment file, at run time you will get the environment variables for whatever your environment is.  It seems strange to me, but it works, and it seems like that is how it is designed to work.

ContentLicense: CC BY-SA 4.0

Body:
I had this same question, and found the same article that @Ahmed posted.  However, that didn't fix my problem: I just got:

ERROR in XXX/src/app/app.component.ts (19,29): Cannot find module './environment'.

I'm working with a build created via ng new, so if you are working with the latest angular client you will likely have the same problem I had.  As @Ahmed states in his comment on his answer, it is important that you get the relative path correct.  The (current) version of the ng cli puts your main application component here:

projectFolder/app/src/app.component.ts

And it places the environment file here:

projectFolder/app/environments/environment.ts

Therefore, the correct line to include the environment from inside your app.component is this:

import { environment } from '../environments/environment';

Small "feature": environment.ts is actually the environment configuration file for the development environment.  However, at run time (either due to the ng build command or ng serve command), this file will be replaced by whatever the actual environment states.  So even though you are explicitly including the development environment file, at run time you will get the environment variables for whatever your environment is.  It seems strange to me, but it works, and it seems like that is how it is designed to work.


问:
How to add metadata to PDF document using PDFbox?
I have an input stream of a PDF document available to me. I would like to add subject metadata to the document and then save it. I'm not sure how to do this.

I came across a sample recipe here: https://pdfbox.apache.org/1.8/cookbook/workingwithmetadata.html

However, it is still fuzzy. Below is what I'm trying and places where I have questions

```<code>PDDocument doc = PDDocument.load(myInputStream);
PDDocumentCatalog catalog = doc.getDocumentCatalog();
InputStream newXMPData = ...; //what goes here? How can I add subject tag?
PDMetadata newMetadata = new PDMetadata(doc, newXMLData, false );
catalog.setMetadata( newMetadata );
//does anything else need to happen to save the document??
//I would like an outputstream of the document (with metadata) so that I can save it to an S3 bucket
</code>```

答:
The following code sets the title of a PDF document, but it should be adaptable to work with other properties as well:

```<code>public static byte[] insertTitlePdf(byte[] documentBytes, String title) {
    try {
        PDDocument document = PDDocument.load(documentBytes);
        PDDocumentInformation info = document.getDocumentInformation();
        info.setTitle(title);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        document.save(baos);
        return baos.toByteArray();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}
</code>```

Apache PDFBox is needed, so import it to e.g. Maven with:

```<code><dependency>
    <groupId>org.apache.pdfbox</groupId>
    <artifactId>pdfbox</artifactId>
    <version>2.0.6</version>
</dependency>
</code>```

Add a title with:

```<code>byte[] documentBytesWithTitle = insertTitlePdf(documentBytes, "Some fancy title");
</code>```

Display it in the browser with (JSF example):

```<code><object class="pdf" data="data:application/pdf;base64,#{myBean.getDocumentBytesWithTitleAsBase64()}" type="application/pdf">Document could not be loaded</object>
</code>```

Result (Chrome):

Body:
I have an input stream of a PDF document available to me. I would like to add subject metadata to the document and then save it. I'm not sure how to do this.

I came across a sample recipe here: https://pdfbox.apache.org/1.8/cookbook/workingwithmetadata.html

However, it is still fuzzy. Below is what I'm trying and places where I have questions

PDDocument doc = PDDocument.load(myInputStream);
PDDocumentCatalog catalog = doc.getDocumentCatalog();
InputStream newXMPData = ...; //what goes here? How can I add subject tag?
PDMetadata newMetadata = new PDMetadata(doc, newXMLData, false );
catalog.setMetadata( newMetadata );
//does anything else need to happen to save the document??
//I would like an outputstream of the document (with metadata) so that I can save it to an S3 bucket

Body:
The following code sets the title of a PDF document, but it should be adaptable to work with other properties as well:

public static byte[] insertTitlePdf(byte[] documentBytes, String title) {
    try {
        PDDocument document = PDDocument.load(documentBytes);
        PDDocumentInformation info = document.getDocumentInformation();
        info.setTitle(title);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        document.save(baos);
        return baos.toByteArray();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}

Apache PDFBox is needed, so import it to e.g. Maven with:

<dependency>
    <groupId>org.apache.pdfbox</groupId>
    <artifactId>pdfbox</artifactId>
    <version>2.0.6</version>
</dependency>

Add a title with:

byte[] documentBytesWithTitle = insertTitlePdf(documentBytes, "Some fancy title");

Display it in the browser with (JSF example):

<object class="pdf" data="data:application/pdf;base64,#{myBean.getDocumentBytesWithTitleAsBase64()}" type="application/pdf">Document could not be loaded</object>

Result (Chrome):


问:
Testing Chef search queries in recipes using Test Kitchen
In a related post I asked about creating a comma separated list of hosts from a Chef query.  The problem though is that I'm using test-kitchen which doesn't use the Chef server so that was why my query was not returning any hosts.

My question is then, how do you test recipes that rely on Chef queries in test kitchen? Preloading data into a file or something along those lines won't expose any bugs in the knife query itself.  Is there a busser that would allow me to run queries against the Chef Server?

Update: Below is the code to support the strange results I'm getting from the Chef query.

Recipe:

```<code># Create output conf file
indexers = search("node", "role:#{node['forwarder']['indexer_role']}")

template '/opt/splunkforwarder/etc/system/local/outputs.conf' do
  source "system_local_outputs.erb"
  owner 'nobody'
  group 'nobody'
  mode 0600
  action :create
variables(
  :indexers  => indexers
)
end
</code>```

Template ERB

```<code>[tcpout]
defaultGroup = default-autolb-group

[tcpout:default-autolb-group]
disabled = false
server = <%= @indexers.map {|n| "#{n}:5501" }.join(",") %>
</code>```

attributes/default.rb

```<code>default['forwarder']['indexer_role'] = 'splunk_indexer'
</code>```

Command line query inside Docker instance to test if forwarders are configured correctly

```<code>sudo /opt/splunkforwarder/bin/splunk list forward-server -auth admin:<password>

Active forwards:
None
Configured but inactive forwards:
node[splunk-001-indexer.example.com]:5501
node[splunk-002-indexer.example.com]:5501
node[splunk-003-indexer.example.com]:5501
node[splunk-004-indexer.example.com]:5501
node[splunk-005-indexer.example.com]:5501
node[splunk-006-indexer.example.com]:5501
node[splunk-007-indexer.example.com]:5501
node[splunk-008-indexer.example.com]:5501
node[splunk-009-indexer.example.com]:5501
node[splunk-010-indexer.example.com]:5501
node[splunk-011-indexer.example.com]:5501
node[splunk-012-indexer.example.com]:5501
</code>```

Finally, the contents of outputs.conf file

```<code>sudo cat /opt/splunkforwarder/etc/system/local/outputs.conf
[tcpout]
defaultGroup = default-autolb-group

[tcpout:default-autolb-group]
disabled = false
server = node[dspe-splunk-001-indexer.pbp.gq1.yahoo.com]:5501,node[dspe-splunk-002.pbp.gq1.yahoo.com]:5501,node[dspe-splunk-003-indexer.pbp.gq1.yahoo.com]:5501,node[dspe-splunk-004-indexer.pbp.gq1.yahoo.com]:5501,node[dspe-splunk-005-indexer.pbp.gq1.yahoo.com]:5501,node[dspe-splunk-006-indexer.pbp.gq1.yahoo.com]:5501,node[dspe-splunk-007-indexer.pbp.gq1.yahoo.com]:5501,node[dspe-splunk-008.pbp.gq1.yahoo.com]:5501,node[dspe-splunk-009-indexer.pbp.gq1.yahoo.com]:5501,node[dspe-splunk-010-indexer.pbp.gq1.yahoo.com]:5501,node[dspe-splunk-011-indexer.pbp.gq1.yahoo.com]:5501,node[dspe-splunk-012-indexer.pbp.gq1.yahoo.com]:5501
</code>```

答:
You can mock search data (for nodes) by putting JSON files below test/integration/nodes/:

An example file looks as follows:

```<code>{
  "id":       "testhost",
  "name":     "testhost.example.com",
  "chef_type": "node",
  "json_class": "Chef::Node",
  "run_list": [],
  "chef_environment": "production",
  "automatic": {
    "fqdn": "testhost.example.com",
    "ip": "127.0.0.1"
  }
}
</code>```

Body:
In a related post I asked about creating a comma separated list of hosts from a Chef query.  The problem though is that I'm using test-kitchen which doesn't use the Chef server so that was why my query was not returning any hosts.

My question is then, how do you test recipes that rely on Chef queries in test kitchen? Preloading data into a file or something along those lines won't expose any bugs in the knife query itself.  Is there a busser that would allow me to run queries against the Chef Server?

Update: Below is the code to support the strange results I'm getting from the Chef query.

Recipe:

# Create output conf file
indexers = search("node", "role:#{node['forwarder']['indexer_role']}")

template '/opt/splunkforwarder/etc/system/local/outputs.conf' do
  source "system_local_outputs.erb"
  owner 'nobody'
  group 'nobody'
  mode 0600
  action :create
variables(
  :indexers  => indexers
)
end

Template ERB

[tcpout]
defaultGroup = default-autolb-group

[tcpout:default-autolb-group]
disabled = false
server = <%= @indexers.map {|n| "#{n}:5501" }.join(",") %>

attributes/default.rb

default['forwarder']['indexer_role'] = 'splunk_indexer'

Command line query inside Docker instance to test if forwarders are configured correctly

sudo /opt/splunkforwarder/bin/splunk list forward-server -auth admin:<password>

Active forwards:
None
Configured but inactive forwards:
node[splunk-001-indexer.example.com]:5501
node[splunk-002-indexer.example.com]:5501
node[splunk-003-indexer.example.com]:5501
node[splunk-004-indexer.example.com]:5501
node[splunk-005-indexer.example.com]:5501
node[splunk-006-indexer.example.com]:5501
node[splunk-007-indexer.example.com]:5501
node[splunk-008-indexer.example.com]:5501
node[splunk-009-indexer.example.com]:5501
node[splunk-010-indexer.example.com]:5501
node[splunk-011-indexer.example.com]:5501
node[splunk-012-indexer.example.com]:5501

Finally, the contents of outputs.conf file

sudo cat /opt/splunkforwarder/etc/system/local/outputs.conf
[tcpout]
defaultGroup = default-autolb-group

[tcpout:default-autolb-group]
disabled = false
server = node[dspe-splunk-001-indexer.pbp.gq1.yahoo.com]:5501,node[dspe-splunk-002.pbp.gq1.yahoo.com]:5501,node[dspe-splunk-003-indexer.pbp.gq1.yahoo.com]:5501,node[dspe-splunk-004-indexer.pbp.gq1.yahoo.com]:5501,node[dspe-splunk-005-indexer.pbp.gq1.yahoo.com]:5501,node[dspe-splunk-006-indexer.pbp.gq1.yahoo.com]:5501,node[dspe-splunk-007-indexer.pbp.gq1.yahoo.com]:5501,node[dspe-splunk-008.pbp.gq1.yahoo.com]:5501,node[dspe-splunk-009-indexer.pbp.gq1.yahoo.com]:5501,node[dspe-splunk-010-indexer.pbp.gq1.yahoo.com]:5501,node[dspe-splunk-011-indexer.pbp.gq1.yahoo.com]:5501,node[dspe-splunk-012-indexer.pbp.gq1.yahoo.com]:5501

Body:
You can mock search data (for nodes) by putting JSON files below test/integration/nodes/:

An example file looks as follows:

{
  "id":       "testhost",
  "name":     "testhost.example.com",
  "chef_type": "node",
  "json_class": "Chef::Node",
  "run_list": [],
  "chef_environment": "production",
  "automatic": {
    "fqdn": "testhost.example.com",
    "ip": "127.0.0.1"
  }
}


问:
png icons have jagged edges when sized with CSS
I'm having trouble (pulling my hair out!) figuring out how to smooth the edges of my png icons. They are sized via CSS and are saved as PNG at 263px.

I've tried resaving as GIF's and also a variety of CSS hacks:
-webkit-backface-visibility: hidden;

Ideally I need a solution that smooths out the edges of the image (not the square borders) across all major browsers, as they all seem to be suffering and creating jaggy edges.

Thanks in advance

CSS:

width: 20px;
height: 20px;

Here's an image taken from my site:

答: #logo {-webkit-transform: initial;}

Body: #logo {-webkit-transform: initial;}


问:
Is there a better way to set a gcloud project in a directory?
I work on multiple appengine projects in any given week. i.e. assume multiple clients. Earlier I could set application in app.yaml. So whenever I did appcfg.py update.... it would ensure deployment to the right project.

When deploying, the application variable throws an error with gcloud deploy. I had to use
gcloud app deploy --project [YOUR_PROJECT_ID]. So what used to be a directory level setting for a project, is now going into our build tooling. And missing out that simple detail can push a project code to the wrong customer.
i.e. if I did gcloud config set project proj1 and then somehow did a gcloud app deploy in proj2, it would deploy to proj1. Production deployments are done after detailed verification on the build tools and hence it is less of an issue there because we still use the --project flag.

But its hard to do similar stuff on the development environment. dev_appserver.py doesn't have a --project flag.
When starting dev_appserver.py I've to do gcloud config set project <project-id> before I start the server. This is important when I using stuff like PubSub or GCS (in dev topics or dev buckets).

Unfortunately, missing out a simple configuration like setting a project ID in a dev environment can result into uploading blobs/messages/etc into the wrong dev gcs bucket or wrong dev pubsub topic (not using emulators). And this has happened quite a few times especially when starting new projects.

I find the above solutions as hackish-workarounds. Is there a good way to ensure that we do not deploy or develop in a wrong project when working from a certain directory?

答:
These are exactly the reasons for which I highly dislike gcloud. Making command line argument mandatory and dropping configuration files support, much too error prone for my taste.

So far I'm still able to use the GAE SDK instead of Google Cloud SDK (see What is the relationship between Google's App Engine SDK and Cloud SDK?), which could be one option - basically keep doing stuff "the old way". Please note that it's no longer the recommended method.

You can find the still compatible GAE SDKs here.

For whenever the above will no longer be an option and I'll be forced to switch to the Cloud SDK my plan is to have version-controlled cheat-sheet text files in each app directory containing the exact cmds to use for running the devserver, deploy, etc for that particular project which I can just copy-paste into the terminal without fear of making mistakes. You carefully set these up once and then you just copy-paste them. As a bonus you can have different branch versions for different environments (staging/production, for example).

Actually I'm using this approach even for the GAE SDK - to prevent accidental deployment of the app-level config files to the wrong GAE app (such deployments must use cmdline arguments to specify the app in multi-service apps).

Or do the same but with environment config files and wrapper scripts instead of cheat-sheet files, if that's your preference.


问:
Nested each do loops printing unexpectedly in Ruby
I have two arrays containing strings. I'm trying to iterate through both arrays with nested .each do loops to see if any elements in the first array have a substring of any of the elements in the second array. I'm using .include? within the nested loops to check this. I want the result to be the string printed the number of times it matches an element in partials.

This is the method that isn't working

```<code>def orphanCheck(partials, partials1, duplicatesArray)
  partials1.each do |i|
    partials.each do |j|
      if i.include?(j)
        duplicatesArray.push(i)
      end
    end
  end
end
</code>```

I'm using this as a helper method to define partials and partials1

```<code>def manipulate(monthEmails, todayEmails, partials, partials1)
  monthEmails.each do |i|
    email = EmailAddress.new(i.to_s)
    partials.push(email.host_name.to_s)
  end
  todayEmails.each do |j|
    todaySignup = j.to_s.slice(11, 100)
    partials1.push(todaySignup)
  end
end
</code>```

And then I'm calling the two with the following

```<code>manipulate(allUnique, todayEmails, partials, partials1)

orphanCheck(partials, partials1, duplicatesArray)
#puts duplicatesArray
</code>```

duplicatesArray is printing some strings that shouldn't be matches and it's printing some strings more times than I want. For example, gmail.com isn't in partials at all but me@gmail.com, which is in partials1 once, is being pushed to duplicatesArray three times. If yahoo.com is in partials three times, then I would want me@yahoo.com (from partials1) to be pushed to duplicatesArray three times, for example.

答:
A better solution that should give you a correct duplicatesArray would be:</p>

```<code>partials1.each do |email_address|
  email_host = email_address.split("@").last
  duplicatesArray.push(email_address) if partials.include?(email_host)
end
</code>```

Body:
I have two arrays containing strings. I'm trying to iterate through both arrays with nested .each do loops to see if any elements in the first array have a substring of any of the elements in the second array. I'm using .include? within the nested loops to check this. I want the result to be the string printed the number of times it matches an element in partials.

This is the method that isn't working

def orphanCheck(partials, partials1, duplicatesArray)
  partials1.each do |i|
    partials.each do |j|
      if i.include?(j)
        duplicatesArray.push(i)
      end
    end
  end
end

I'm using this as a helper method to define partials and partials1

def manipulate(monthEmails, todayEmails, partials, partials1)
  monthEmails.each do |i|
    email = EmailAddress.new(i.to_s)
    partials.push(email.host_name.to_s)
  end
  todayEmails.each do |j|
    todaySignup = j.to_s.slice(11, 100)
    partials1.push(todaySignup)
  end
end

And then I'm calling the two with the following

manipulate(allUnique, todayEmails, partials, partials1)

orphanCheck(partials, partials1, duplicatesArray)
#puts duplicatesArray

duplicatesArray is printing some strings that shouldn't be matches and it's printing some strings more times than I want. For example, gmail.com isn't in partials at all but me@gmail.com, which is in partials1 once, is being pushed to duplicatesArray three times. If yahoo.com is in partials three times, then I would want me@yahoo.com (from partials1) to be pushed to duplicatesArray three times, for example.

Body:
A better solution that should give you a correct duplicatesArray would be:

partials1.each do |email_address|
  email_host = email_address.split("@").last
  duplicatesArray.push(email_address) if partials.include?(email_host)
end


问:
Haskell shying away from probabilistic data structures?
If you search for skips lists implemented in Haskell, you won't find many. It is a probabilistic data structure needing a random number generator, meaning that any of these structures would need to run in the IO monad.

Are Haskell folks staying away from these data structures because it's not possible to implement them purely? How can Haskell deal with them?

答: There is a new skip list implementation based on STM for haskell, see tskiplist on hackage.</p>


问:
Why does START TRANSACTION doesn't affect on autocommit implicitly as it should
So this is from the docs:

To disable autocommit mode implicitly for a single series of
  statements, use the START TRANSACTION statement:

```<code>START TRANSACTION;
SELECT @A:=SUM(salary) FROM table1 WHERE type=1;
UPDATE table2 SET summary=@A WHERE type=1;
COMMIT;
</code>```

So from my understanding, unlike using BEGIN; command which shouldn't set autocommit to 0, START TRANSACTION should set it to 0.

Now if I do this (after I start a transaction):

```<code>select @@autocommit;
</code>```

I get the value of 1.

Why autocommit is still enabled even if I use START TRANSACTION command? I thought that the autocommit variable is local to a single session. Or maybe even if it says 1, it is actually set to 0 within a transaction but just can't get that info by running a SELECT @@autocommit; query?

答:
I suggest that @@autocommit is irrelevant.  The engine knows that it is in a transaction (START or BEGIN), so it ignores the setting of autocommit.  Instead it hangs onto changes until COMMIT (or ROLLBACK).

Or do you have some reason to believe that the value of autocommit is relevant?  (Aside from SELECT @@autocommit.)

Body:
So this is from the docs:

To disable autocommit mode implicitly for a single series of
  statements, use the START TRANSACTION statement:

START TRANSACTION;
SELECT @A:=SUM(salary) FROM table1 WHERE type=1;
UPDATE table2 SET summary=@A WHERE type=1;
COMMIT;

So from my understanding, unlike using BEGIN; command which shouldn't set autocommit to 0, START TRANSACTION should set it to 0.

Now if I do this (after I start a transaction):

select @@autocommit;

I get the value of 1.

Why autocommit is still enabled even if I use START TRANSACTION command? I thought that the autocommit variable is local to a single session. Or maybe even if it says 1, it is actually set to 0 within a transaction but just can't get that info by running a SELECT @@autocommit; query?


问:
AngularJS: Import text
I am not a javascript person so please apologize if this question doesn't make sense:

In my angular project/app.js I have a an array articles which are dictionaries of article elements (description, author, etc...)

```<code>var articles = [
    {   title : "Article 1",
        date : date.toDateString(),
        shortDesc : "Short description...",
        ...
    },...
]
</code>```

This variable is then assigned to an instance variable of the controller

```<code>app.controller('BlogController', function () {
    this.articles = articles;
});
</code>```

Now, instead of typing my actual short description into the article dictionary I would like import that text from another file. How do I do that?

Thanks so much in advance!

答: You can have json file and make call to it by $http.get('data.json'). But then again you're unable to post data to it (client side difficult to write data to file). Else you can install json-server npm module & serve your json file on it, then you can do all CRUD operation through angular's $http service. This's just for mocking purpose or faking REST API, for real project purpose you should have real web services handled by server side technologies (e.g. Java, NodeJS) or create on cloud backend-as-a-service like Firebase, AWS (dynamoDB).

Title: AngularJS: Import text

Body:
I am not a javascript person so please apologize if this question doesn't make sense:

In my angular project/app.js I have a an array articles which are dictionaries of article elements (description, author, etc...)

var articles = [
    {   title : "Article 1",
        date : date.toDateString(),
        shortDesc : "Short description...",
        ...
    },...
]

This variable is then assigned to an instance variable of the controller

app.controller('BlogController', function () {
    this.articles = articles;
});

Now, instead of typing my actual short description into the article dictionary I would like import that text from another file. How do I do that?

Thanks so much in advance!


问:
Save curl download statistics / log
I'm reading a stream with curl and grep some highlights.

```<code>curl url | grep desired_key_word
</code>```

I've noticed that curl is providing me some nice download statistics such as:

```<code>  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 10.9M    0 10.9M    0     0  1008k      0 --:--:--  0:00:11 --:--:-- 1092k
</code>```

How can I save those statistics e.g. every second in a file?

I found this: http://curl.haxx.se/mail/archive-2002-11/0115.html however it was not able to abstract it to my problem.

```<code>curl -n agent.mtconnect.org/sample\?interval=0 -o xml_stream.log 2>> dl.log
</code>```

The dl.log should have the statistics included, however is does not work.

答:
Here is the unabstracted version.

curl -s -S -n http://speedtest.fremont.linode.com/100MB-fremont.bin -o /dev/null -w "%{time_total},%{size_download},%{speed_download}\n" >> stats.log

Title: Save curl download statistics / log

Body:
I'm reading a stream with curl and grep some highlights.

curl url | grep desired_key_word

I've noticed that curl is providing me some nice download statistics such as:

  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 10.9M    0 10.9M    0     0  1008k      0 --:--:--  0:00:11 --:--:-- 1092k

How can I save those statistics e.g. every second in a file?

I found this: http://curl.haxx.se/mail/archive-2002-11/0115.html however it was not able to abstract it to my problem.

curl -n agent.mtconnect.org/sample\?interval=0 -o xml_stream.log 2>> dl.log

The dl.log should have the statistics included, however is does not work.


问:
Entity Framework: association between two edmx models
I have a bigger project that uses multiple edmx files to manage the data model for an asp.net application. What I want to achieve is to link two entities accross two edmx models.

So basically, just a foreign key like this: EntityA.ForeignEntityId --> EntityB.Id

However, since the enitites are not in the same model, I cannot add this foreign key in the model designer. I know that I could do it manually by either modifying the auto-generated SQL-file or by adding the relation in the SQL Server Manager. Both these approaches have the massive downside that they are not easily maintainable because if I do "Create database from model" and run the resulting SQL script, my manual modifications are dropped (I thnink?).

So is there a way of referencing a foreign entity from another edmx model in the model designer?

答: I know this is old but i found myself with the same problem. If you create the reference in SQL and update your model from the database it will pull in the table that is referenced. I don't think this really solves the problem we have but it will at least allow for you to go back and forth without losing any FKs.</p>


问:
How I can pass opts/flags which I pass to npm install command to postinstall scripts?
How I can pass opts/flags which I pass to npm install command to postinstall scripts?

I write npm install X --some-param=some-value command. X package has postinstall script: ./scripts/postinstall.js. How I can pass some-param to postinstall script?

I try process.argv but it does not contain anything which I use as npm install params.

答:
I don't think there's a way to do that, since npm install assumes all arguments it doesn't recognize are package names. What works, and is a common solution, is to use environment variables instead. When you do this:

```<code>$ SOME_PARAM=some-value npm install
</code>```

...you can then access the value of SOME_PARAM with process.env.SOME_PARAM in your postinstall.js script.

Body:
I don't think there's a way to do that, since npm install assumes all arguments it doesn't recognize are package names. What works, and is a common solution, is to use environment variables instead. When you do this:

$ SOME_PARAM=some-value npm install

...you can then access the value of SOME_PARAM with process.env.SOME_PARAM in your postinstall.js script.


问:
REGEX to get all numbers in a string, even if other characters are in between
I have a Google Spreadsheet populated with information from a real estate website.

The phone numbers came across in a single cell like this *Cell #* (602) 695-2036 or *Cell #* 602-575-1008. I had an REGEXEXTRACT() function using \d-\d-\d which worked for numbers formatted like the second, but I need something that works on all cell number strings, regardless of formatting or characters between. So I want (602) 695-2036 to return 6026952036 and 602-575-1008 to return 6025751008.

Spreadsheet. Numbers are in row 5 and one is in row 6.

答:
You can match all numbers with the regular expression \d. Then just append your list of matches together.

Here is an example of this in JavaScript:

// INIT
var text = '(602) 695-2036';
var result = '';

// PRINT START
console.log("START: "+text);

// GET MATCHES
var matches = text.match(/\d/g);

// LOOP MATCHES
for(var index = 0; index < matches.length; index++){

 // APPEND TO RESULT
 result += matches[index];

}

// PRINT RESULT
console.log("RESULT: "+result);```


问:
jplayer.org save playlist in cookies
I have a working Jplayer and I'm proud to share it here for everyone's convenience.

It memorizes the playlist in a cookie as I add single tracks inside it. Here's the working code:

```<code>// PLAY SINGLE SONG
// el delegation is needed because songs are dynamically loaded via ajax datatables
$(document).on("click", '.playable', function(el) {
    var title = $(this).data("title");
    var artist = $(this).data("artist");
    var mp3 = $(this).data("mp3");
    var poster = $(this).data("poster");
    myPlaylist.add({
        title: title,
        artist: artist,
        mp3: mp3,
        poster: poster
    }, true ); /* true makes it play on load */
});
</code>```

The cookie storage is triggered here, using a standard jplayer function:

```<code>$("#jquery_jplayer").bind($.jPlayer.event.play, function(el) {
    Cookies.remove('jp_playlist');
    Cookies.set('jp_playlist', JSON.stringify(myPlaylist) );
});
</code>```

But I also have a button ADD ALL, which maps each song and adds it to the playlist:

```<code>// PLAY ALL
$(document).on("click", '#play_all', function(el) {

    // play all
    $.map($('.playable'), function(el) {
        var title = $(el).data("title");
        var artist = $(el).data("artist");
        var mp3 = $(el).data("mp3");
        var poster = $(el).data("poster");
        myPlaylist.add({
            title: title,
            artist: artist,
            mp3: mp3,
            poster: poster
        });
    });

    var current = myPlaylist.current;
    myPlaylist.play(current); /* if I would have put "true" like above it would have started the last song instead of the first */

    Cookies.remove('jp_playlist');
    Cookies.set('jp_playlist', JSON.stringify(myPlaylist) );
});
</code>```

The cookie is not set and the playlist isn't retained upon page reload.
I alert( JSON.stringify(myPlaylist) ) and everything shows fine. It seems that either myPlaylist.play(current) doesn't trigger the bind($.jPlayer.event.play) and my last 2 lines which force the cookie storage don't work. I also tried to remove that lines and put the "true", to test if it triggers the bind.event.play but it doesn't work.

Thank you in advance for your time and any hint.

答:
It was a cookies storage limit. I simply bypassed the limit using localstorage, e.g.:

```<code>localStorage.setItem('jp_playlist', JSON.stringify(myPlaylist) );
localStorage.removeItem('jp_playlist');
</code>```

instead of

```<code>Cookies.set('jp_playlist', JSON.stringify(myPlaylist) );
Cookies.remove('jp_playlist');
</code>```

Title: jplayer.org save playlist in cookies

Body:
I have a working Jplayer and I'm proud to share it here for everyone's convenience.

It memorizes the playlist in a cookie as I add single tracks inside it. Here's the working code:

// PLAY SINGLE SONG
// el delegation is needed because songs are dynamically loaded via ajax datatables
$(document).on("click", '.playable', function(el) {
    var title = $(this).data("title");
    var artist = $(this).data("artist");
    var mp3 = $(this).data("mp3");
    var poster = $(this).data("poster");
    myPlaylist.add({
        title: title,
        artist: artist,
        mp3: mp3,
        poster: poster
    }, true ); /* true makes it play on load */
});

The cookie storage is triggered here, using a standard jplayer function:

$("#jquery_jplayer").bind($.jPlayer.event.play, function(el) {
    Cookies.remove('jp_playlist');
    Cookies.set('jp_playlist', JSON.stringify(myPlaylist) );
});

But I also have a button ADD ALL, which maps each song and adds it to the playlist:

// PLAY ALL
$(document).on("click", '#play_all', function(el) {

    // play all
    $.map($('.playable'), function(el) {
        var title = $(el).data("title");
        var artist = $(el).data("artist");
        var mp3 = $(el).data("mp3");
        var poster = $(el).data("poster");
        myPlaylist.add({
            title: title,
            artist: artist,
            mp3: mp3,
            poster: poster
        });
    });

    var current = myPlaylist.current;
    myPlaylist.play(current); /* if I would have put "true" like above it would have started the last song instead of the first */

    Cookies.remove('jp_playlist');
    Cookies.set('jp_playlist', JSON.stringify(myPlaylist) );
});

The cookie is not set and the playlist isn't retained upon page reload.
I alert( JSON.stringify(myPlaylist) ) and everything shows fine. It seems that either myPlaylist.play(current) doesn't trigger the bind($.jPlayer.event.play) and my last 2 lines which force the cookie storage don't work. I also tried to remove that lines and put the "true", to test if it triggers the bind.event.play but it doesn't work.

Thank you in advance for your time and any hint.

Body:
It was a cookies storage limit. I simply bypassed the limit using localstorage, e.g.:

localStorage.setItem('jp_playlist', JSON.stringify(myPlaylist) );
localStorage.removeItem('jp_playlist');

instead of

Cookies.set('jp_playlist', JSON.stringify(myPlaylist) );
Cookies.remove('jp_playlist');


问:
how to reference the Tab Bar Controller from a UICollectionView Cell
I have a tab bar controller application and in one of the tabs a UI Collection View Controller with an action assigned to a button. This button does its magic and then should change the tab bar view to another one. However, I'm not able to reference it right to the tab controller.

tabBarController is the class name assigned to the controller. So, I tried:

```<code>tabBarController.selectedIndex = 3
</code>```

and also creating a method directly in the tabBarController class

```<code>tabBarController.goToIndex(3)
</code>```

The error says: Instance member of 'goToIndex' cannot be used on type tabBarController

Any ideia?

Thank you,

答:
Im having a little trouble understanding what you mean by referencing it right, but hopefully this will help. Assuming tabBarController is a subclass of UITabBarController:

```<code>class MyTabBarController: UITabBarController {

    /// ...

    func goToIndex(index: Int) {

    }
}
</code>```

In one of your tab controllers (UIViewController) you can reference your UITabBarController with self.tabBarController. Note that self.tabBarController is optional.

```<code>    self.tabBarController?.selectedIndex = 3
</code>```

If your tab UIViewController is a UIViewController inside a UINavigationController, then you will need to reference your tab bar like this:

```<code>self.navigationController?.tabBarController
</code>```

To call a function on your subclass you would need to cast the tab bar controller to your custom subclass.

```<code>    if let myTabBarController = self.tabBarController as? MyTabBarController {
        myTabBarController.goToIndex(3)
    }
</code>```

Update based on comments:

You're correct that you cant access the tabBarController inside the cell unless you made it a property on either the cell itself (not recommended) or the app delegate. Alternatively, you could use target action on your UIViewController to call a function on the view controller every time a button is tapped inside a cell.

```<code>class CustomCell: UITableViewCell {
    @IBOutlet weak var myButton: UIButton!
}

class MyTableViewController: UITableViewController {

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "ReuseIdentifier", for: indexPath) as! CustomCell

        /// Add the indexpath or other data as a tag that we
        /// might need later on.

        cell.myButton.tag = indexPath.row

        /// Add A Target so that we can call `changeIndex(sender:)` every time a user tapps on the
        /// button inside a cell.

        cell.myButton.addTarget(self,
                                action: #selector(MyTableViewController.changeIndex(sender:)),
                                for: .touchUpInside)

        return cell
    }

    /// This will be called every time `myButton` is tapped on any tableViewCell. If you need
    /// to know which cell was tapped, it was passed in via the tag property.
    ///
    /// - Parameter sender: UIButton on a UITableViewCell subclass.

    func changeIndex(sender: UIButton) {

        /// now tag is the indexpath row if you need it.
        let tag = sender.tag

        self.tabBarController?.selectedIndex = 3
    }
}
</code>```

Body:
I have a tab bar controller application and in one of the tabs a UI Collection View Controller with an action assigned to a button. This button does its magic and then should change the tab bar view to another one. However, I'm not able to reference it right to the tab controller.

tabBarController is the class name assigned to the controller. So, I tried:

tabBarController.selectedIndex = 3

and also creating a method directly in the tabBarController class

tabBarController.goToIndex(3)

The error says: Instance member of 'goToIndex' cannot be used on type tabBarController

Any ideia?

Thank you,

Body:
Im having a little trouble understanding what you mean by referencing it right, but hopefully this will help. Assuming tabBarController is a subclass of UITabBarController:

class MyTabBarController: UITabBarController {

    /// ...

    func goToIndex(index: Int) {

    }
}

In one of your tab controllers (UIViewController) you can reference your UITabBarController with self.tabBarController. Note that self.tabBarController is optional.

    self.tabBarController?.selectedIndex = 3

If your tab UIViewController is a UIViewController inside a UINavigationController, then you will need to reference your tab bar like this:

self.navigationController?.tabBarController

To call a function on your subclass you would need to cast the tab bar controller to your custom subclass.

    if let myTabBarController = self.tabBarController as? MyTabBarController {
        myTabBarController.goToIndex(3)
    }

Update based on comments:

You're correct that you cant access the tabBarController inside the cell unless you made it a property on either the cell itself (not recommended) or the app delegate. Alternatively, you could use target action on your UIViewController to call a function on the view controller every time a button is tapped inside a cell.

class CustomCell: UITableViewCell {
    @IBOutlet weak var myButton: UIButton!
}

class MyTableViewController: UITableViewController {

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "ReuseIdentifier", for: indexPath) as! CustomCell

        /// Add the indexpath or other data as a tag that we
        /// might need later on.

        cell.myButton.tag = indexPath.row

        /// Add A Target so that we can call `changeIndex(sender:)` every time a user tapps on the
        /// button inside a cell.

        cell.myButton.addTarget(self,
                                action: #selector(MyTableViewController.changeIndex(sender:)),
                                for: .touchUpInside)

        return cell
    }

    /// This will be called every time `myButton` is tapped on any tableViewCell. If you need
    /// to know which cell was tapped, it was passed in via the tag property.
    ///
    /// - Parameter sender: UIButton on a UITableViewCell subclass.

    func changeIndex(sender: UIButton) {

        /// now tag is the indexpath row if you need it.
        let tag = sender.tag

        self.tabBarController?.selectedIndex = 3
    }
}


问:
Rails | nested routes if nil
I have used friendly_id and globalize gem. So I can generate routes as;

```<code>/search/france/weekly/toyota-95
</code>```

Here is my routes;

```<code>namespace :search do
  resources :car_countries, path: '', only: [] do
    resources :rental_types, path: '', only: [] do
      resources :car_types, path: '', only: [:show] do
      end
    end
  end
end
</code>```

But the thing is now I would like to also get city either;

```<code>/search/nice/weekly/toyota-95
</code>```

or

```<code>/search/france/nice/weekly/toyota-95
</code>```

The problem is I want to have both with city name and without city name (only country). They should go to same controller which is at the end car_types.

So if I add car_cities to routes, I get error when there is no city but only country.

```<code>namespace :search do
 resources :car_countries, path: '', only: [] do
    resources :car_cities, path: '', only: [] do
       resources :rental_types, path: '', only: [] do
         resources :car_types, path: '', only: [:show] do
         end
       end
     end
  end

  resources :car_countries, path: '', only: [] do
    resources :rental_types, path: '', only: [] do
      resources :car_types, path: '', only: [:show] do
      end
    end
  end
end
</code>```

How can I do that?

答:
As Gerry says, take a look at route globbing http://guides.rubyonrails.org/routing.html#route-globbing-and-wildcard-segments. I'd suggest to send everything to a single controller action and either do stuff there or delegate it to a search model/service object (depends on your taste).

Example:

```<code># in config/routes.rb
get 'search/*q' => 'searches#show'

# in app/controllers/searches_controller.rb
class SearchesController < ApplicationController
  def search
    # This should work for your simple use case but it will become pretty confusing if you add more filters.

    search_params = params[:search].split('/')
    if search_params.count == 4
      country, city, rental_type, car_type = search_params
    else
      country, rental_type, car_type = search_params
    end

    # Do whatever with these variables, e.g. Car.for_country(country)...
  end
end
</code>```

A more stable solution would be to make use of the fact that rental types are probably a closed set (daily, weekly, ...) and use segment constraints for this part in the routes:

```<code># config/routes.rb
scope to: 'searches#show', constraints: { rental_type: /(daily|weekly|monthly)/ } do
  get '/search/:country/:rental_type/:car_type'
  get '/search/:country/:city/:rental_type/:car_type'
end
</code>```

This should differentiate the two URLs based on the fact that :city can never match the rental type constraint.

Yet another option would be to use a full blown constraints object (http://guides.rubyonrails.org/routing.html#advanced-constraints):

```<code># config/routes.rb
class SearchConstraint
  def initialize
    # assuming that all your objects have the friendly_id on the name field
    @country_names = %w[austria germany]
    @rental_type_names = %w[daily weekly monthly]
    @car_type_names = %w[toyota-prius vw-golf]
    @city_names = %w[innsbruck munich berlin]
  end

  def matches?(request)
    checks = []

    # only check for parts if they're actually there
    checks << @country_names.include?(request.parameters[:country]) if request.parameters[:country].present?
    checks << @rental_type_names.include?(request.parameters[:rental_type]) if request.parameters[:rental_type].present?
    checks << @car_type_names.include?(request.parameters[:car_type]) if request.parameters[:car_type].present?
    checks << @city_names.include?(request.parameters[:city]) if request.parameters[:city].present?

    checks.all? # or, if you want it more explicit: checks.all? { |result| result == true }
  end
end

scope to: 'searches#show', constraints: SearchConstraint.new do
  get '/search/:country/:rental_type/:car_type'
  get '/search/:country/:city/:rental_type/:car_type'
end
</code>```

Note that this last approach is probably the cleanest and least hacky approach (and it's quite easy to test) but it also comes at the cost if involving the database in every request to these particular URLs and the URLs fail hard if there's an issue with the database connection.

Hope that helps.

Title: Rails | nested routes if nil

Body:
I have used friendly_id and globalize gem. So I can generate routes as;

/search/france/weekly/toyota-95

Here is my routes;

namespace :search do
  resources :car_countries, path: '', only: [] do
    resources :rental_types, path: '', only: [] do
      resources :car_types, path: '', only: [:show] do
      end
    end
  end
end

But the thing is now I would like to also get city either;

/search/nice/weekly/toyota-95

or

/search/france/nice/weekly/toyota-95

The problem is I want to have both with city name and without city name (only country). They should go to same controller which is at the end car_types.

So if I add car_cities to routes, I get error when there is no city but only country.

namespace :search do
 resources :car_countries, path: '', only: [] do
    resources :car_cities, path: '', only: [] do
       resources :rental_types, path: '', only: [] do
         resources :car_types, path: '', only: [:show] do
         end
       end
     end
  end

  resources :car_countries, path: '', only: [] do
    resources :rental_types, path: '', only: [] do
      resources :car_types, path: '', only: [:show] do
      end
    end
  end
end

How can I do that?

Body:
As Gerry says, take a look at route globbing http://guides.rubyonrails.org/routing.html#route-globbing-and-wildcard-segments. I'd suggest to send everything to a single controller action and either do stuff there or delegate it to a search model/service object (depends on your taste).

Example:

# in config/routes.rb
get 'search/*q' => 'searches#show'

# in app/controllers/searches_controller.rb
class SearchesController < ApplicationController
  def search
    # This should work for your simple use case but it will become pretty confusing if you add more filters.

    search_params = params[:search].split('/')
    if search_params.count == 4
      country, city, rental_type, car_type = search_params
    else
      country, rental_type, car_type = search_params
    end

    # Do whatever with these variables, e.g. Car.for_country(country)...
  end
end

A more stable solution would be to make use of the fact that rental types are probably a closed set (daily, weekly, ...) and use segment constraints for this part in the routes:

# config/routes.rb
scope to: 'searches#show', constraints: { rental_type: /(daily|weekly|monthly)/ } do
  get '/search/:country/:rental_type/:car_type'
  get '/search/:country/:city/:rental_type/:car_type'
end

This should differentiate the two URLs based on the fact that :city can never match the rental type constraint.

Yet another option would be to use a full blown constraints object (http://guides.rubyonrails.org/routing.html#advanced-constraints):

# config/routes.rb
class SearchConstraint
  def initialize
    # assuming that all your objects have the friendly_id on the name field
    @country_names = %w[austria germany]
    @rental_type_names = %w[daily weekly monthly]
    @car_type_names = %w[toyota-prius vw-golf]
    @city_names = %w[innsbruck munich berlin]
  end

  def matches?(request)
    checks = []

    # only check for parts if they're actually there
    checks << @country_names.include?(request.parameters[:country]) if request.parameters[:country].present?
    checks << @rental_type_names.include?(request.parameters[:rental_type]) if request.parameters[:rental_type].present?
    checks << @car_type_names.include?(request.parameters[:car_type]) if request.parameters[:car_type].present?
    checks << @city_names.include?(request.parameters[:city]) if request.parameters[:city].present?

    checks.all? # or, if you want it more explicit: checks.all? { |result| result == true }
  end
end

scope to: 'searches#show', constraints: SearchConstraint.new do
  get '/search/:country/:rental_type/:car_type'
  get '/search/:country/:city/:rental_type/:car_type'
end

Note that this last approach is probably the cleanest and least hacky approach (and it's quite easy to test) but it also comes at the cost if involving the database in every request to these particular URLs and the URLs fail hard if there's an issue with the database connection.

Hope that helps.


问:
How to mass upload PDF files and save into MySQL using Servlet?
How do I mass upload PDF files or a folder with PDF files and save it into my MySQL database using Servlet?</p>

答:
The best you do is to ask user to specify the files using several <input type="file"...> elements on the page. And on submit check if all the files are PDF or not, perform desired action in either case. Or you can check for the PDF extension right away using JavaScript. You can also validate using AJAX, just send an AJAX request to the server on a onBlur event of the input field.

Otherwise, a privileged applet might be able to help a little more than this. For example asking a directory and scanning for all PDF's etc.


问:
Bootstrap navbar is displaying vertically instead of horizontally
I'm working on a project using CodePen and I'm using bootstrap to make a navbar. But for some reason it's displaying vertically instead of horizontally. Even when I copy and paste code from the W3Schools examples and the Bootstrap website. I don't know what else to do. Please help.

This is the W3Schools example code:

```<code>    <nav class="navbar navbar-default">
      <div class="container-fluid">
        <div class="navbar-header">
          <a class="navbar-brand" href="#">WebSiteName</a>
        </div>
        <ul class="nav navbar-nav">
          <li class="active"><a href="#">Home</a></li>
          <li><a href="#">Page 1</a></li>
          <li><a href="#">Page 2</a></li>
          <li><a href="#">Page 3</a></li>
        </ul>
      </div>
</code>```

This is example code from the Bootstrap website:

```<code>    <nav class="navbar navbar-default">
      <div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
  <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
    <span class="sr-only">Toggle navigation</span>
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
  </button>
  <a class="navbar-brand" href="#">Brand</a>
</div>

<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
  <ul class="nav navbar-nav">
    <li class="active"><a href="#">Link <span class="sr-only">(current)</span></a></li>
    <li><a href="#">Link</a></li>
    <li class="dropdown">
      <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
      <ul class="dropdown-menu">
        <li><a href="#">Action</a></li>
        <li><a href="#">Another action</a></li>
        <li><a href="#">Something else here</a></li>
        <li role="separator" class="divider"></li>
        <li><a href="#">Separated link</a></li>
        <li role="separator" class="divider"></li>
        <li><a href="#">One more separated link</a></li>
      </ul>
    </li>
  </ul>
  <form class="navbar-form navbar-left">
    <div class="form-group">
      <input type="text" class="form-control" placeholder="Search">
    </div>
    <button type="submit" class="btn btn-default">Submit</button>
  </form>
  <ul class="nav navbar-nav navbar-right">
    <li><a href="#">Link</a></li>
    <li class="dropdown">
      <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
      <ul class="dropdown-menu">
        <li><a href="#">Action</a></li>
        <li><a href="#">Another action</a></li>
        <li><a href="#">Something else here</a></li>
        <li role="separator" class="divider"></li>
        <li><a href="#">Separated link</a></li>
      </ul>
    </li>
  </ul>
</div><!-- /.navbar-collapse -->
</code>```

Both do not work. And  yes, I've triple checked my <link> and

答: As someone said - remove bootstrap 4 from loaded CSS files and it will work</p>

Body:
I'm working on a project using CodePen and I'm using bootstrap to make a navbar. But for some reason it's displaying vertically instead of horizontally. Even when I copy and paste code from the W3Schools examples and the Bootstrap website. I don't know what else to do. Please help.

This is the W3Schools example code:

          WebSiteName

Home

Page 1

Page 2

Page 3

This is example code from the Bootstrap website:

  <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
    Toggle navigation

  </button>
  Brand

Link (current)

Link

      Dropdown

Action

Another action

Something else here

Separated link

One more separated link

  <form class="navbar-form navbar-left">

      <input type="text" class="form-control" placeholder="Search">

    <button type="submit" class="btn btn-default">Submit</button>
  </form>

Link

      Dropdown

Action

Another action

Something else here

Separated link

Both do not work. And  yes, I've triple checked my <link> and


问:
React redux redirect after success post
I normally work as a Java programmer and I love the fact that with Java alot of the code design is standardized. For example you read Java example about Spring or Hibernate the code structurally looks the same for the whole world.

I am now working on ReactJS with redux and I just can't seem to understand it. Every example I have seen does everything completely different and it seams as if the entire JavaScript community just can't make up there minds on how to do something the same so I am hoping someone here can explain how ReactJS / redux works.

I have a login page and when I click on a button a http post must be done to a oauth2 auth server and on success a redirect must be done.

My Component works. It is LoginPage and I can confirm that when I click on the login button an action is called.

```<code>class LoginPage extends React.Component {
  render() {
    return (
      <div id="login-container">
        <LoginForm {...this.props} />
      </div>
    );
  }
}

const mapStateToProps = (state, ownProps) => {
  return {
  };
}

const mapDispatchToProps = (dispatch) => {
  return {
    handleSubmit: (evt) => {
      evt.preventDefault();

      performLogin(dispatch, evt.target.username.value, evt.target.password.value );
    }
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(LoginPage);
</code>```

The performLogin method is an action and my actions.js looks like this:

```<code>export function performLogin( dispatch, username, password ) {
    login(username, password).then(function (response) {
        dispatch({
            type: LOGIN_SUCCESS
        });
    })
    .catch(function (error) {
        dispatch({
            type: LOGIN_FAILURE
        });
    });
}
</code>```

The reducer looks like this:

```<code>const loginReducer = (state = initialState, action) => {
    switch (action.type) {
        case LOGIN_SUCCESS:
            return [
                ...state, {
                    auth: {
                        'login': true
                    }
                }
            ]
        case LOGIN_FAILURE:
            return [
                ...state, {
                    auth: {
                        'login': false
                    }
                }
            ]
        default:
            return state;
    }
};
</code>```

I have tried doing a axios post in the action but I got the error something like the action needs to be a plain object or something like that.

My question is where do you perform ajax calls and redirects in ReactJS/redux? In the action or the reducer?

This is a part of my packages.json:

```<code>"react": "^15.1.0",
"react-addons-test-utils": "^15.1.0",
"react-dom": "^15.1.0",
"react-redux": "^5.0.4",
"react-router": "^3.0.2",
"react-router-dom": "^4.1.1",
"react-router-redux": "^4.0.8",
"react-tap-event-plugin": "^2.0.1",
"redux": "^3.5.2",
"redux-form": "^6.8.0",
"redux-logger": "^2.6.1",
"redux-promise": "^0.5.3",
"redux-thunk": "^2.1.0",
</code>```

答:
For the error "action needs to be a plain object or something like that" I believe your Redux-thunk is set up incorrectly. dispatch(performLogin(username, password))

export function performLogin( username, password ) {
   return function (dispatch) {
     return login(username, password)
       .then(function (response) {
         dispatch({
           type: LOGIN_SUCCESS
         });
       })
   }
 }

See example makeASandwichWithSecretSauce https://github.com/gaearon/redux-thunk

Title: React redux redirect after success post

Body:
I normally work as a Java programmer and I love the fact that with Java alot of the code design is standardized. For example you read Java example about Spring or Hibernate the code structurally looks the same for the whole world.

I am now working on ReactJS with redux and I just can't seem to understand it. Every example I have seen does everything completely different and it seams as if the entire JavaScript community just can't make up there minds on how to do something the same so I am hoping someone here can explain how ReactJS / redux works.

I have a login page and when I click on a button a http post must be done to a oauth2 auth server and on success a redirect must be done.

My Component works. It is LoginPage and I can confirm that when I click on the login button an action is called.

class LoginPage extends React.Component {
  render() {
    return (

        <LoginForm {...this.props} />

    );
  }
}

const mapStateToProps = (state, ownProps) => {
  return {
  };
}

const mapDispatchToProps = (dispatch) => {
  return {
    handleSubmit: (evt) => {
      evt.preventDefault();

      performLogin(dispatch, evt.target.username.value, evt.target.password.value );
    }
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(LoginPage);

The performLogin method is an action and my actions.js looks like this:

export function performLogin( dispatch, username, password ) {
    login(username, password).then(function (response) {
        dispatch({
            type: LOGIN_SUCCESS
        });
    })
    .catch(function (error) {
        dispatch({
            type: LOGIN_FAILURE
        });
    });
}

The reducer looks like this:

const loginReducer = (state = initialState, action) => {
    switch (action.type) {
        case LOGIN_SUCCESS:
            return [
                ...state, {
                    auth: {
                        'login': true
                    }
                }
            ]
        case LOGIN_FAILURE:
            return [
                ...state, {
                    auth: {
                        'login': false
                    }
                }
            ]
        default:
            return state;
    }
};

I have tried doing a axios post in the action but I got the error something like the action needs to be a plain object or something like that.

My question is where do you perform ajax calls and redirects in ReactJS/redux? In the action or the reducer?

This is a part of my packages.json:

"react": "^15.1.0",
"react-addons-test-utils": "^15.1.0",
"react-dom": "^15.1.0",
"react-redux": "^5.0.4",
"react-router": "^3.0.2",
"react-router-dom": "^4.1.1",
"react-router-redux": "^4.0.8",
"react-tap-event-plugin": "^2.0.1",
"redux": "^3.5.2",
"redux-form": "^6.8.0",
"redux-logger": "^2.6.1",
"redux-promise": "^0.5.3",
"redux-thunk": "^2.1.0",


问:
SQL Compare 27 fields as 1 field
I'm looking for duplicate records in a file there are 27 fields that I need to compare they are all in a row is there a way to compare they with out having each typed out (a way to substring out the record format data)

I'm using

```<code>Select RRN(a),
       RRN(b)
From   fileX a
Inner Join fileX b
    On RRN(a) < RRN(b)
       And a.FLD1 = b.FLD1
       And a.FLD2 = b.FLD2
       And a.FLD3 = b.FLD3
       And a.FLD5 = b.FLD5
       And a.FLD6 = b.FLD6
       And a.FLD7 = b.FLD7
       And a.FLD8 = b.FLD8
       And a.FLD9 = b.FLD9
       And a.FLD10 = b.FLD10
       And a.FLD11 = b.FLD11
       And a.FLD12 = b.FLD12
       And a.FLD13 = b.FLD13
       And a.FLD14 = b.FLD14
       And a.FLD15 = b.FLD15
       And a.FLD16 = b.FLD16
       And a.FLD17 = b.FLD17
       And a.FLD18 = b.FLD18
       And a.FLD19 = b.FLD19
       And a.FLD21 = b.FLD21
       And a.FLD22 = b.FLD22
       And a.FLD23 = b.FLD23
       And a.FLD24 = b.FLD24
       And a.FLD25 = b.FLD25
       And a.FLD26 = b.FLD26
       And a.FLD27 = b.FLD27
</code>```

I would like to use

```<code>Select RRN(a),
       RRN(b)
From   fileX a
Inner Join fileX b
    On RRN(a) < RRN(b)
       And substr(A.RCDFMT, 100, 54) = substr(B.RCDFMT, 100, 54)
</code>```

I know I could concatenate them all together, but that still means typing out all the field names, I just want a shorter cleaner looking selection.

答:
Create a view with the 27 fields concatenated into one field.

Create a logical file with the 27 fields concatenated into one field.

```<code>create view mylib/myview as
select a.fld1 || a.fld2 || a.fld3
...
 as allfld
from mylib/myfile.
</code>```

Title: SQL Compare 27 fields as 1 field

Body:
I'm looking for duplicate records in a file there are 27 fields that I need to compare they are all in a row is there a way to compare they with out having each typed out (a way to substring out the record format data)

I'm using

Select RRN(a),
       RRN(b)
From   fileX a
Inner Join fileX b
    On RRN(a) < RRN(b)
       And a.FLD1 = b.FLD1
       And a.FLD2 = b.FLD2
       And a.FLD3 = b.FLD3
       And a.FLD5 = b.FLD5
       And a.FLD6 = b.FLD6
       And a.FLD7 = b.FLD7
       And a.FLD8 = b.FLD8
       And a.FLD9 = b.FLD9
       And a.FLD10 = b.FLD10
       And a.FLD11 = b.FLD11
       And a.FLD12 = b.FLD12
       And a.FLD13 = b.FLD13
       And a.FLD14 = b.FLD14
       And a.FLD15 = b.FLD15
       And a.FLD16 = b.FLD16
       And a.FLD17 = b.FLD17
       And a.FLD18 = b.FLD18
       And a.FLD19 = b.FLD19
       And a.FLD21 = b.FLD21
       And a.FLD22 = b.FLD22
       And a.FLD23 = b.FLD23
       And a.FLD24 = b.FLD24
       And a.FLD25 = b.FLD25
       And a.FLD26 = b.FLD26
       And a.FLD27 = b.FLD27

I would like to use

Select RRN(a),
       RRN(b)
From   fileX a
Inner Join fileX b
    On RRN(a) < RRN(b)
       And substr(A.RCDFMT, 100, 54) = substr(B.RCDFMT, 100, 54)

I know I could concatenate them all together, but that still means typing out all the field names, I just want a shorter cleaner looking selection.

Body:
Create a view with the 27 fields concatenated into one field.

Create a logical file with the 27 fields concatenated into one field.

create view mylib/myview as
select a.fld1 || a.fld2 || a.fld3
...
 as allfld
from mylib/myfile.


问:
Adding Image into Webpage using AngularJS
Why does my image show up as a file logo? link below

This is how my image shows up when I add it

This is my JS for the image (AngularJS)

{
    name: 'Screw',
    price: 1,
    description: 'A small item drilled into objects',
    specs: '1 centimeter',
    images: [
                {
                    full: "1024px-Phillips_screw.jpg"
                }
            ]
}
```

<p>This is my HTML for adding the image</p>

<pre class="lang-html prettyprint-override"><code><img ng-src="{{product.images[0].full}}"/>
</code>```

答:
Check the console for the error, but it's probably because the path is incorrect.

If they're in your images folder you'd want to put that path:

```<code><img src="/images/{{product.images[0].full}}"/>
</code>```

Body:
Why does my image show up as a file logo? link below

This is how my image shows up when I add it

This is my JS for the image (AngularJS)

{
    name: 'Screw',
    price: 1,
    description: 'A small item drilled into objects',
    specs: '1 centimeter',
    images: [
                {
                    full: "1024px-Phillips_screw.jpg"
                }
            ]
}

This is my HTML for adding the image

Body:
Check the console for the error, but it's probably because the path is incorrect.

If they're in your images folder you'd want to put that path:

<img src="/images/{{product.images[0].full}}"/>


问:
Can only import win32com.client with IDLE. What extra work do i need to set up pywin32?
I have a Tkinter program that i use for time management.  I decided to have it scan my inbox in outlook to check emails for tags, and then based on the tag, add it to my list of tasks to do for the night.

The code i wrote works just fine, but i'm getting an error when I import win32com.client.  I can import it in IDLE, but it is having problems importing when i try to run the code with a .bat file, or double clicking the .py file.

I have found several people with similar problems, but from what i can tell, it's having problems with win32api module, or pywin32

```<code>Traceback (most recent call last):
    File "my_program_filename.py", line 1, in <module>
import win32com.client
    File "c:/Python27/lib/site-packages/win32com/__init__.py", line 5, in <module>
import win32api, sys, os
ImportError:  DLL load failed: The specified module could not be found
</code>```

I'm really confused.  When i get the sys.path it's the same with IDLE as it is running from the .py file with the exception of an added "c:/users/username/desktop/timer" for my .py file.

I'm really lost and haven't had to mess with the system path, but I'm not able to figure out what i need to do to fix this.

What do I need to do to get pywin32 working so I can use win32com.client?

Any help is greatly appreciated.  Thanks!

答: I found this link to be the solution rather than the win32com/client as indicated above:  win32com import error python 3.4</p>

Body:
I have a Tkinter program that i use for time management.  I decided to have it scan my inbox in outlook to check emails for tags, and then based on the tag, add it to my list of tasks to do for the night.

The code i wrote works just fine, but i'm getting an error when I import win32com.client.  I can import it in IDLE, but it is having problems importing when i try to run the code with a .bat file, or double clicking the .py file.

I have found several people with similar problems, but from what i can tell, it's having problems with win32api module, or pywin32

Traceback (most recent call last):
    File "my_program_filename.py", line 1, in <module>
import win32com.client
    File "c:/Python27/lib/site-packages/win32com/__init__.py", line 5, in <module>
import win32api, sys, os
ImportError:  DLL load failed: The specified module could not be found

I'm really confused.  When i get the sys.path it's the same with IDLE as it is running from the .py file with the exception of an added "c:/users/username/desktop/timer" for my .py file.

I'm really lost and haven't had to mess with the system path, but I'm not able to figure out what i need to do to fix this.

What do I need to do to get pywin32 working so I can use win32com.client?

Any help is greatly appreciated.  Thanks!


问:
Imageresizer watermark - changing the image
I have watermarks working fine using asp.net imageresizer but I want to be able to set the watermark image via an admin function.

The image path is set in the web.config, but if I overwrite this image the watermark does not change - it always shows the old image unless I change the web.config. So obviously it is being cached - how can get it to return the image with the new watermark file?

I have tried touching the file that has the watermark applied, touching the watermark file itself - nothing works unless I change the web.config which is not feasible for a live site.

答: Watermark overlays are memory-cached for best performance - thus no disk check. The Watermark plugin can be reconfigured via C# - so if you need to dynamically change watermark data, I'd suggest doing it that way, rather than overwriting the file. It's a new image, so change the filename. That will also ensure that cached results with outdated overlays/watermarks are updated immediately.</p>


问:
Html table to csv table with image
How to export this html table  in to  CSV
example table:

i want this table to be exported to  csv  .so how to achieve using JQUERY?

```<code><html>
<body bgcolor="cyan">

<table border="1" align="center" >
 <br><a href="imp2.csv">Click Here To View In CSV format</a><img src="up.jpg"  align="middle" width="39" height="32" />
  <tr>
    <th>ID</th>
    <th>Name</th>
    <th>Month</th>

    <th>Savings</th>

  </tr>
</table>

</body>
</html>
</code>```

Thanks
Joseph

答:
Excel files support embedded images, CSV files do not. So the short answer is: You can't.

Theoretically, you could set location to a data: scheme URI that you generate on the fly. Actually generating an Excel file would be distinctly non-trivial and I wouldn't be surprised if you rapidly ran into length limits.

Title: Html table to csv table with image

Body:
How to export this html table  in to  CSV
example table:

i want this table to be exported to  csv  .so how to achieve using JQUERY?

Click Here To View In CSV format

    ID
    Name
    Month

    Savings

Thanks
Joseph