问:
SQL Server DSN-Less ODBC Specify 32 bit Driver
I'm working with an older application that I recently updated to .NET 4.5. The application has been using DSN ODBC connections. However, in the case of the application, it is accessed from a single location on a network drive, so it doesn't make sense to require a DSN, and it will ease deployment and updates to use a DSN-less connection string in place. I'm doing a basic string as such:

```<code>Driver={SQL Server}; Server=; Database=; UID=; PWD=
</code>```

The issue I have is that the application is compiled as 32 bit, but may be used on a 32 bit or 64 bit machine. On 64 bit machines I get this error:

The specified DSN contains an architecture mismatch between the Driver
  and Application

Which essentially means it's trying to use the 64 bit driver for the 32 bit application. That's easy enough to deal with except the driver name for SQL Server appears to be the same for 32 and 64 bit. So how can I specify only the 32 bit driver in the connection string?

答:
"To manage a data source that connects to a 32-bit driver under 64-bit platform, use c:\windows\sysWOW64\odbcad32.exe. To manage a data source that connects to a 64-bit driver, use c:\windows\system32\odbcad32.exe. In Administrative Tools on a 64-bit Windows 8 operating system, there are icons for both the 32-bit and 64-bit ODBC Data Source Administrator dialog box. Read more"

If you use the 64-bit odbcad32.exe to configure or remove a DSN that connects to a 32-bit driver, you will receive the following error message:

The specified DSN contains an architecture mismatch between the Driver and Application

To resolve this error, use the 32-bit odbcad32.exe to configure or remove the DSN.

References

The specified DSN contains an architecture mismatch between the Driver and Application

Managing Data Sources

Side Note: make sure that all references Copy Local property is set to True, even the System assemblies. I think that the issue may be from the assemblies location saved in GAC, so when copying the assemblies locally it may fix that

Body:
I'm working with an older application that I recently updated to .NET 4.5. The application has been using DSN ODBC connections. However, in the case of the application, it is accessed from a single location on a network drive, so it doesn't make sense to require a DSN, and it will ease deployment and updates to use a DSN-less connection string in place. I'm doing a basic string as such:

Driver={SQL Server}; Server=; Database=; UID=; PWD=

The issue I have is that the application is compiled as 32 bit, but may be used on a 32 bit or 64 bit machine. On 64 bit machines I get this error:

The specified DSN contains an architecture mismatch between the Driver
  and Application

Which essentially means it's trying to use the 64 bit driver for the 32 bit application. That's easy enough to deal with except the driver name for SQL Server appears to be the same for 32 and 64 bit. So how can I specify only the 32 bit driver in the connection string?


来源: stackexchange

问:
Case insensitive Predicate in WHERE clause without Changing Collation
Say I want to get all the people with the surname Smith

```<code>SELECT *
FROM   Person
WHERE  LastName = 'Smith'
</code>```

The above is fine. However, as my Database Collation is CS, a LastName value like SmItH, smith or SMITH will not be included in the results above.

I could do

```<code>SELECT *
FROM   Person
WHERE  UPPER(LastName) = 'SMITH'
</code>```

Which would work, however the query isn't then SARGable. However, the rub is that this will cause a table / index scan rather than a seek.

I know I can change the column or database collation but is there a way I can make the query SARGable without making any database changes?

答:
Maybe T-SQL pattern matching would be helpful:
https://technet.microsoft.com/en-us/library/ms187489(v=sql.105).aspx

It's not pretty but this should work:

```<code>SELECT *
FROM Person
WHERE LastName LIKE '[Ss][Mm][Ii][Tt][Hh]'
</code>```

I'm not 100% sure if SQL Server is able to use indexes with this sort of query.

Maybe something like this would be better for the indexes:

```<code>SELECT *
FROM Person
WHERE LastName LIKE 'S[Mm][Ii][Tt][Hh]'
OR LastName LIKE 's[Mm][Ii][Tt][Hh]'
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Say I want to get all the people with the surname Smith

SELECT *
FROM   Person
WHERE  LastName = 'Smith'

The above is fine. However, as my Database Collation is CS, a LastName value like SmItH, smith or SMITH will not be included in the results above.

I could do

SELECT *
FROM   Person
WHERE  UPPER(LastName) = 'SMITH'

Which would work, however the query isn't then SARGable. However, the rub is that this will cause a table / index scan rather than a seek.

I know I can change the column or database collation but is there a way I can make the query SARGable without making any database changes?

Body:
Maybe T-SQL pattern matching would be helpful:
https://technet.microsoft.com/en-us/library/ms187489(v=sql.105).aspx

It's not pretty but this should work:

SELECT *
FROM Person
WHERE LastName LIKE '[Ss][Mm][Ii][Tt][Hh]'

I'm not 100% sure if SQL Server is able to use indexes with this sort of query.

Maybe something like this would be better for the indexes:

SELECT *
FROM Person
WHERE LastName LIKE 'S[Mm][Ii][Tt][Hh]'
OR LastName LIKE 's[Mm][Ii][Tt][Hh]'


问:
Replacing part of a string in pandas column with `and` condition
I have a pandas dataframe that looks like this:

```<code>    Size    Measure     Location    Messages
    Small     1         Washington  TXT0123 TXT0875 TXT874 TXT0867 TXT0875 TXT0874
    Medium    2         California  TXT020 TXT017 TXT120 TXT012
    Large     3         Texas       TXT0123 TXT0123 TXT0123 TXT0123 TXT0217 TXT0206
    Small     4         California  TXT020 TXT0217 TXT006
    Tiny      5         Nevada      TXT0206 TXT0217 TXT0206
</code>```

I am trying to remove the 0 from the individual words in the Messages column if the length equals 7 and the fourth character is 0.

I've tried for loop, but it's removing all 0's:

```<code>for line in df.Messages:
    for message in line.split():
        if len(message) == 7 and message[3] == '0':
            print(message.replace('0', ''))
</code>```

I also tried .map which gave me some errors:

```<code>df.Messages = df.Messages.map(lambda x: x.replace('0', '') for message in line.split() for line in df.Messages if (len(message) == 7 and message[3] == '0'))

TypeError: 'generator' object is not callable
</code>```

Is there a way to do this with .map that includes the if and and conditionals?

答:
```<code>df.Messages.str.split().apply(pd.Series).fillna('').\
    applymap(lambda x : x[:2]+x[4:] if len(x)==7 and x[3]=='0' else x).\
       apply(' '.join,1)
</code>```

<p>Out[597]: </p>

```<code>0    TX123 TX875 TXT874 TX867 TX875 TX874
1           TXT020 TXT017 TXT120 TXT012
2     TX123 TX123 TX123 TX123 TX217 TX206
3                  TXT020 TX217 TXT006
4                    TX206 TX217 TX206
dtype: object
</code>```

Body:
I have a pandas dataframe that looks like this:

    Size    Measure     Location    Messages
    Small     1         Washington  TXT0123 TXT0875 TXT874 TXT0867 TXT0875 TXT0874
    Medium    2         California  TXT020 TXT017 TXT120 TXT012
    Large     3         Texas       TXT0123 TXT0123 TXT0123 TXT0123 TXT0217 TXT0206
    Small     4         California  TXT020 TXT0217 TXT006
    Tiny      5         Nevada      TXT0206 TXT0217 TXT0206

I am trying to remove the 0 from the individual words in the Messages column if the length equals 7 and the fourth character is 0.

I've tried for loop, but it's removing all 0's:

for line in df.Messages:
    for message in line.split():
        if len(message) == 7 and message[3] == '0':
            print(message.replace('0', ''))

I also tried .map which gave me some errors:

df.Messages = df.Messages.map(lambda x: x.replace('0', '') for message in line.split() for line in df.Messages if (len(message) == 7 and message[3] == '0'))

TypeError: 'generator' object is not callable

Is there a way to do this with .map that includes the if and and conditionals?

Body:
df.Messages.str.split().apply(pd.Series).fillna('').\
    applymap(lambda x : x[:2]+x[4:] if len(x)==7 and x[3]=='0' else x).\
       apply(' '.join,1)

Out[597]:

0    TX123 TX875 TXT874 TX867 TX875 TX874
1           TXT020 TXT017 TXT120 TXT012
2     TX123 TX123 TX123 TX123 TX217 TX206
3                  TXT020 TX217 TXT006
4                    TX206 TX217 TX206
dtype: object


问:
Firebase Hosting: Change default SSL to Norton SSL?
Is it possible to change the default SSL Certificate on Firebase Hosting to use Norton SSL Certificate?</p>

答: The SSL certificates used by Firebase Hosting are not user-configurable, so this is not possible at present. I'd encourage you to file a feature request so we can track the desired use case.</p>


问:
Superpowered: real time pitch shift with timestretcher not working
I am using Superpowered for various real-time FX and they all work very straightforward. However the pitch shifting is a whole other story, I think in fact because it's based on the time-stretching algorithm that of course has to deal with output that changes in time which is a lot more complex than applying FX like EQ or reverb. However I'm only interested in change the pitch of my mic input.

I looked at the only example I could find on GitHub and I slightly adapted it to fit my work:

```<code>static bool audioProcessing(void *clientdata,
                            float **buffers,
                            unsigned int inputChannels,
                            unsigned int outputChannels,
                            unsigned int numberOfSamples,
                            unsigned int samplerate,
                            uint64_t hostTime) {
    __unsafe_unretained Superpowered *self = (__bridge Superpowered *)clientdata;

    SuperpoweredAudiobufferlistElement inputBuffer;

    inputBuffer.startSample = 0;
    inputBuffer.samplesUsed = 0;
    inputBuffer.endSample = self->timeStretcher->numberOfInputSamplesNeeded;
    inputBuffer.buffers[0] = SuperpoweredAudiobufferPool::getBuffer(self->timeStretcher->numberOfInputSamplesNeeded * 8 + 64);
    inputBuffer.buffers[1] = inputBuffer.buffers[2] = inputBuffer.buffers[3] = NULL;

    self->outputBuffers->clear();
    self->timeStretcher->process(&inputBuffer, self->outputBuffers);
    int samples = self->timeStretcher->numberOfInputSamplesNeeded;
    float *timeStretchedAudio = (float *)self->outputBuffers->nextSliceItem(&samples);
    if (timeStretchedAudio != 0) {
        SuperpoweredDeInterleave(timeStretchedAudio, buffers[0], buffers[1], numberOfSamples);
    }

    //self->outputBuffers->rewindSlice();

    return true;
}
</code>```

I have removed most of the code that I thought wasn't necessary. For example there was a while loop that seemed to deal with time-stretch scenarios, I'm just outputting the same time as I input.

Some observations:

If I don't clear the outputBuffers my memory usage goes through the roof

If I use self->outputBuffers->rewindSlice(); the app becomes silent, probably meaning the buffers are getting overwritten with silence

If I do not use self->outputBuffers->rewindSlice(); I can hear my own voice coming back, but timeStretchedAudio is always 0 except  the very first time

答:
I finally got it working:

```<code>static bool audioProcessing(void *clientdata,
                                float **buffers,
                                unsigned int inputChannels,
                                unsigned int outputChannels,
                                unsigned int numberOfSamples,
                                unsigned int samplerate,
                                uint64_t hostTime) {
    __unsafe_unretained Superpowered *self = (__bridge Superpowered *)clientdata;

    //timeStretching->setRateAndPitchShift(realTimeRate, realTimePitch);
    SuperpoweredAudiobufferlistElement inputBuffer;
    inputBuffer.startSample = 0;
    inputBuffer.samplesUsed = 0;
    inputBuffer.endSample = numberOfSamples;
    inputBuffer.buffers[0] = SuperpoweredAudiobufferPool::getBuffer((unsigned int) (numberOfSamples * 8 + 64));
    inputBuffer.buffers[1] = inputBuffer.buffers[2] = inputBuffer.buffers[3] = NULL;

    // Converting the 16-bit integer samples to 32-bit floating point.
    SuperpoweredInterleave(buffers[0], buffers[1], (float *)inputBuffer.buffers[0], numberOfSamples);
    //SuperpoweredShortIntToFloat(audioInputOutput, (float *)inputBuffer.buffers[0], (unsigned int) numberOfSamples);

    self->timeStretcher->process(&inputBuffer, self->outputBuffers);

    // Do we have some output?
    if (self->outputBuffers->makeSlice(0, self->outputBuffers->sampleLength)) {
        while (true) { // Iterate on every output slice.
            // Get pointer to the output samples.
            int numSamples = 0;
            float *timeStretchedAudio = (float *)self->outputBuffers->nextSliceItem(&numSamples);
            if (!timeStretchedAudio || *timeStretchedAudio == 0) {
                break;
            }

            // Convert the time stretched PCM samples from 32-bit floating point to 16-bit integer.
            //SuperpoweredFloatToShortInt(timeStretchedAudio, audioInputOutput,
            //                            (unsigned int) numSamples);
            SuperpoweredDeInterleave(timeStretchedAudio, buffers[0], buffers[1], numSamples);
            self->recorder->process(timeStretchedAudio, numSamples);

            // Write the audio to disk.
            //fwrite(audioInputOutput, 1, numSamples * 4, fd);
        }
        // Clear the output buffer list.
        self->outputBuffers->clear();
        // If we have enough samples in the fifo output buffer, pass them to the audio output.
        //SuperpoweredFloatToShortInt((float *)inputBuffer.buffers[0], audioInputOutput, (unsigned int) numberOfSamples);
    }

    return true;
}
</code>```

I am not sure if changing the rate also works, but I don't care for this application. YMMV.

Body:
I am using Superpowered for various real-time FX and they all work very straightforward. However the pitch shifting is a whole other story, I think in fact because it's based on the time-stretching algorithm that of course has to deal with output that changes in time which is a lot more complex than applying FX like EQ or reverb. However I'm only interested in change the pitch of my mic input.

I looked at the only example I could find on GitHub and I slightly adapted it to fit my work:

static bool audioProcessing(void *clientdata,
                            float **buffers,
                            unsigned int inputChannels,
                            unsigned int outputChannels,
                            unsigned int numberOfSamples,
                            unsigned int samplerate,
                            uint64_t hostTime) {
    __unsafe_unretained Superpowered *self = (__bridge Superpowered *)clientdata;

    SuperpoweredAudiobufferlistElement inputBuffer;

    inputBuffer.startSample = 0;
    inputBuffer.samplesUsed = 0;
    inputBuffer.endSample = self->timeStretcher->numberOfInputSamplesNeeded;
    inputBuffer.buffers[0] = SuperpoweredAudiobufferPool::getBuffer(self->timeStretcher->numberOfInputSamplesNeeded * 8 + 64);
    inputBuffer.buffers[1] = inputBuffer.buffers[2] = inputBuffer.buffers[3] = NULL;

    self->outputBuffers->clear();
    self->timeStretcher->process(&inputBuffer, self->outputBuffers);
    int samples = self->timeStretcher->numberOfInputSamplesNeeded;
    float *timeStretchedAudio = (float *)self->outputBuffers->nextSliceItem(&samples);
    if (timeStretchedAudio != 0) {
        SuperpoweredDeInterleave(timeStretchedAudio, buffers[0], buffers[1], numberOfSamples);
    }

    //self->outputBuffers->rewindSlice();

    return true;
}

I have removed most of the code that I thought wasn't necessary. For example there was a while loop that seemed to deal with time-stretch scenarios, I'm just outputting the same time as I input.

Some observations:

If I don't clear the outputBuffers my memory usage goes through the roof

If I use self->outputBuffers->rewindSlice(); the app becomes silent, probably meaning the buffers are getting overwritten with silence

If I do not use self->outputBuffers->rewindSlice(); I can hear my own voice coming back, but timeStretchedAudio is always 0 except  the very first time

Body:
I finally got it working:

static bool audioProcessing(void *clientdata,
                                float **buffers,
                                unsigned int inputChannels,
                                unsigned int outputChannels,
                                unsigned int numberOfSamples,
                                unsigned int samplerate,
                                uint64_t hostTime) {
    __unsafe_unretained Superpowered *self = (__bridge Superpowered *)clientdata;

    //timeStretching->setRateAndPitchShift(realTimeRate, realTimePitch);
    SuperpoweredAudiobufferlistElement inputBuffer;
    inputBuffer.startSample = 0;
    inputBuffer.samplesUsed = 0;
    inputBuffer.endSample = numberOfSamples;
    inputBuffer.buffers[0] = SuperpoweredAudiobufferPool::getBuffer((unsigned int) (numberOfSamples * 8 + 64));
    inputBuffer.buffers[1] = inputBuffer.buffers[2] = inputBuffer.buffers[3] = NULL;

    // Converting the 16-bit integer samples to 32-bit floating point.
    SuperpoweredInterleave(buffers[0], buffers[1], (float *)inputBuffer.buffers[0], numberOfSamples);
    //SuperpoweredShortIntToFloat(audioInputOutput, (float *)inputBuffer.buffers[0], (unsigned int) numberOfSamples);

    self->timeStretcher->process(&inputBuffer, self->outputBuffers);

    // Do we have some output?
    if (self->outputBuffers->makeSlice(0, self->outputBuffers->sampleLength)) {
        while (true) { // Iterate on every output slice.
            // Get pointer to the output samples.
            int numSamples = 0;
            float *timeStretchedAudio = (float *)self->outputBuffers->nextSliceItem(&numSamples);
            if (!timeStretchedAudio || *timeStretchedAudio == 0) {
                break;
            }

            // Convert the time stretched PCM samples from 32-bit floating point to 16-bit integer.
            //SuperpoweredFloatToShortInt(timeStretchedAudio, audioInputOutput,
            //                            (unsigned int) numSamples);
            SuperpoweredDeInterleave(timeStretchedAudio, buffers[0], buffers[1], numSamples);
            self->recorder->process(timeStretchedAudio, numSamples);

            // Write the audio to disk.
            //fwrite(audioInputOutput, 1, numSamples * 4, fd);
        }
        // Clear the output buffer list.
        self->outputBuffers->clear();
        // If we have enough samples in the fifo output buffer, pass them to the audio output.
        //SuperpoweredFloatToShortInt((float *)inputBuffer.buffers[0], audioInputOutput, (unsigned int) numberOfSamples);
    }

    return true;
}

I am not sure if changing the rate also works, but I don't care for this application. YMMV.


问:
I'm in a beginner's Python course, and my assignment is to print variable 'N' backwards using a 'while' statement
Here are my instructions:

We will pass you a value, N. You should output every positive value from N down to and including 0.

And here is my assignment:

```<code>    # Get N from the command line
    import sys
    N = int(sys.argv[1])

    # Your code goes here
    counter = 0
    while counter <= N:
     print(counter-N)
     counter = counter + 1
</code>```

My solution prints this:

```<code>Program Output

Program Failed for Input: 3
Expected Output: 3
2
1
0
Your Program Output: -3
-2
-1
0
</code>```

As you can see, I got the output to show -3, -2, -1, 0, but it should be 3, 2, 1, 0. Please be mindful that I am a beginner, and my code must pass using a 'while' statement, and my code must be inputted in Codio. Thank you in advance for any assistance rendered.

答:
Since we are expecting N's value to be higher than counter's value, counter-N will be negative.

Try the following:

```<code> import sys
    N = int(sys.argv[1])

    # Your code goes here
    counter = 0
    while counter <= N:
     print(N-counter)
     counter = counter + 1
</code>```

Body:
Here are my instructions:

We will pass you a value, N. You should output every positive value from N down to and including 0.

And here is my assignment:

    # Get N from the command line
    import sys
    N = int(sys.argv[1])

    # Your code goes here
    counter = 0
    while counter <= N:
     print(counter-N)
     counter = counter + 1

My solution prints this:

Program Output

Program Failed for Input: 3
Expected Output: 3
2
1
0
Your Program Output: -3
-2
-1
0

As you can see, I got the output to show -3, -2, -1, 0, but it should be 3, 2, 1, 0. Please be mindful that I am a beginner, and my code must pass using a 'while' statement, and my code must be inputted in Codio. Thank you in advance for any assistance rendered.

Body:
Since we are expecting N's value to be higher than counter's value, counter-N will be negative.

Try the following:

 import sys
    N = int(sys.argv[1])

    # Your code goes here
    counter = 0
    while counter <= N:
     print(N-counter)
     counter = counter + 1


问:
Nested React list not working
I am trying to recursively render JSON data to nested list using React. Right now I am using simple data object like this:

```<code>[{"id": "1",
 "name": "Luke"
},
{"id": "2",
 "name": "Jim",
  "childNodes":[{
    "id": "3",
    "name": "Lola"
   }]
}]
</code>```

using this class:

```<code>export default class NestedList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: true
    };
  }

  toggle = () => {
    this.setState({ visible: !this.state.visible });
  };

  renderChild = (child) => {
    if (child.childNodes) {
      return (
        <ul>
          {child.myData.map(item => {
            return this.renderChild(item);
          })}
        </ul>
      );
    }
    else if (child.name) {
      return <input type="checkbox"><Child name={child.name}/></input>;
    }
    return null;
  }

  render() {
    return (
      <aside>
        <div>
          <h4>Data Sets</h4>
          <ul>
            {this.renderChild(this.props.myData)}
          </ul>
        </div>
      </aside>
    );
  }
}
</code>```

which calls a Child class that creates list element:

```<code>export default class Child extends Component {
  render() {
    let {name}=this.props;
    return (
      <li>{name}</li>
    );
  }
}
</code>```

but it doesn't print anything. I have tried removing attribute childNodes altogether and tried to print the list but it doesn't work still. I don't understand where I am doing wrong. I would appreciate some help regarding how to fix this.

答:
there were couple of issues here:

You passed myData to renderChild which doesn't hold childNodes
property nor name property. Hence none of the conditions were met
(null was returned).

So maybe you should loop through myData and
pass each member of the array to renderChild.

Even if we will pass a valid "child" to the renderChild method,
inside this condition:

```<code>if (child.childNodes) {
</code>```

Again you are using a wrong property:

```<code><ul>
  {child.myData.map(item => {
  return this.renderChild(item);
  })}
</ul>
</code>```

this should be:

```<code>{child.childNodes.map(item => {...
</code>```

Last thing, You can't nest child elements inside an input element.
so change the layout, maybe like this? :

```<code>  <input type="checkbox"/>
  <Child name={child.name} />
</code>```

Here is a running example with your code:

const data = [
  {
    id: "1",
    name: "Luke"
  },
  {
    id: "2",
    name: "Jim",
    childNodes: [
      {
        id: "3",
        name: "Lola"
      }
    ]
  }
];

class NestedList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: true
    };
  }

  toggle = () => {
    this.setState({ visible: !this.state.visible });
  };

  renderChild = child => {
    if (child.childNodes) {
      return (

          {child.childNodes.map(item => {
            return this.renderChild(item);
          })}

      );
    } else if (child.name) {
      return (

          <input type="checkbox"/>
          <Child name={child.name} />

      );
    }
    return null;
  };

  render() {
    return (

Data Sets

{this.props.myData.map(item => this.renderChild(item))}

    );
  }
}

class Child extends React.Component {
  render() {
    let { name } = this.props;
    return
{name}
;
  }
}

ReactDOM.render(<NestedList myData={data} />, document.getElementById("root"));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div></code>```

Title: Nested React list not working

Body:
I am trying to recursively render JSON data to nested list using React. Right now I am using simple data object like this:

[{"id": "1",
 "name": "Luke"
},
{"id": "2",
 "name": "Jim",
  "childNodes":[{
    "id": "3",
    "name": "Lola"
   }]
}]

using this class:

export default class NestedList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: true
    };
  }

  toggle = () => {
    this.setState({ visible: !this.state.visible });
  };

  renderChild = (child) => {
    if (child.childNodes) {
      return (

          {child.myData.map(item => {
            return this.renderChild(item);
          })}

      );
    }
    else if (child.name) {
      return <input type="checkbox"><Child name={child.name}/></input>;
    }
    return null;
  }

  render() {
    return (

Data Sets

            {this.renderChild(this.props.myData)}

    );
  }
}

which calls a Child class that creates list element:

export default class Child extends Component {
  render() {
    let {name}=this.props;
    return (

{name}

    );
  }
}

but it doesn't print anything. I have tried removing attribute childNodes altogether and tried to print the list but it doesn't work still. I don't understand where I am doing wrong. I would appreciate some help regarding how to fix this.

Body:
there were couple of issues here:

You passed myData to renderChild which doesn't hold childNodes
property nor name property. Hence none of the conditions were met
(null was returned).

So maybe you should loop through myData and
pass each member of the array to renderChild.

Even if we will pass a valid "child" to the renderChild method,
inside this condition:

if (child.childNodes) {

Again you are using a wrong property:

<ul>
  {child.myData.map(item => {
  return this.renderChild(item);
  })}
</ul>

this should be:

{child.childNodes.map(item => {...

Last thing, You can't nest child elements inside an input element.
so change the layout, maybe like this? :

  <input type="checkbox"/>
  <Child name={child.name} />

Here is a running example with your code:

const data = [
  {
    id: "1",
    name: "Luke"
  },
  {
    id: "2",
    name: "Jim",
    childNodes: [
      {
        id: "3",
        name: "Lola"
      }
    ]
  }
];

class NestedList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: true
    };
  }

  toggle = () => {
    this.setState({ visible: !this.state.visible });
  };

  renderChild = child => {
    if (child.childNodes) {
      return (
        <ul>
          {child.childNodes.map(item => {
            return this.renderChild(item);
          })}
        </ul>
      );
    } else if (child.name) {
      return (
        <div>
          <input type="checkbox"/>
          <Child name={child.name} />
        </div>
      );
    }
    return null;
  };

  render() {
    return (
      <aside>
        <div>
          <h4>Data Sets</h4>
          <ul>{this.props.myData.map(item => this.renderChild(item))}</ul>
        </div>
      </aside>
    );
  }
}

class Child extends React.Component {
  render() {
    let { name } = this.props;
    return <li>{name}</li>;
  }
}

ReactDOM.render(<NestedList myData={data} />, document.getElementById("root"));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>


问:
How to access remote MySQL server using Qt5 on Linux?
I need some help in updating remote MySQL database using QT5.I am working on Linux Ubuntu 12.04.I want my app to connect to remote server and write some data to it.Any help will be greatly appreciated.</p>

答:
Here is an example:</p>

```<code>#include <QCoreApplication>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlQuery>
#include <QDebug>

int main(int argc, char *argv[])
{
   QCoreApplication a(argc, argv);

    //use mysql driver
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");

    //set hostname
    db.setHostName("localhost");

    //set db name
    db.setDatabaseName("test");

    //set username and password
    db.setUserName("user");
    db.setPassword("pass");

    //open db
    bool ok = db.open();

    qDebug() << "Db is open: " << ok;

    //define a query
    QSqlQuery query;
    //set query
    query.exec("SELECT * FROM `Persons`");

    //get values from query
    while (query.next()) {
            QString LastName = query.value(1).toString();
            QString  FirstName = query.value(2).toString();
            int age = query.value(3).toInt();
            qDebug() << LastName << " " << FirstName << " " << age;
        }

    //close db
    db.close();

  return a.exec();
 }
</code>```

Body:
Here is an example:

#include <QCoreApplication>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlQuery>
#include <QDebug>

int main(int argc, char *argv[])
{
   QCoreApplication a(argc, argv);

    //use mysql driver
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");

    //set hostname
    db.setHostName("localhost");

    //set db name
    db.setDatabaseName("test");

    //set username and password
    db.setUserName("user");
    db.setPassword("pass");

    //open db
    bool ok = db.open();

    qDebug() << "Db is open: " << ok;

    //define a query
    QSqlQuery query;
    //set query
    query.exec("SELECT * FROM `Persons`");

    //get values from query
    while (query.next()) {
            QString LastName = query.value(1).toString();
            QString  FirstName = query.value(2).toString();
            int age = query.value(3).toInt();
            qDebug() << LastName << " " << FirstName << " " << age;
        }

    //close db
    db.close();

  return a.exec();
 }


问:
Confluent Maven repository not working?
I need to use the Confluent kafka-avro-serializer Maven artifact. From the official guide I should add this repository to my Maven pom

```<code><repository>
  <id>confluent</id>
  <url>http://packages.confluent.io/maven/</url>
</repository>
</code>```

The problem is that the URL http://packages.confluent.io/maven/ seems to not work at the moment as I get the response below

```<code><Error>
  <Code>NoSuchKey</Code>
  <Message>The specified key does not exist.</Message>
  <Key>maven/</Key>
  <RequestId>15E287D11E5D4DFA</RequestId>
  <HostId>
    QVr9lCF0y3SrQoa1Z0jDWtmxD3eJz1gAEdivauojVJ+Bexb2gB6JsMpnXc+JjF95i082hgSLJSM=
  </HostId>
</Error>
</code>```

In fact Maven does not find the artifact

```<code><dependency>
  <groupId>io.confluent</groupId>
  <artifactId>kafka-avro-serializer</artifactId>
  <version>3.1.1</version>
</dependency>
</code>```

Do you know what the problem could be?
Thank you

答:
You can add a mirror in you maven settings file to fetch the jars from confluent repo along with repository config .
Changes needed are
Add a mirror in settings.xml

```<code>   <mirror>
      <id>confluent</id>
      <mirrorOf>confluent</mirrorOf>
      <name>Nexus public mirror</name>
      <url>http://packages.confluent.io/maven/</url>
</mirror>
</code>```

In repository section of maven settings add this

```<code><repository>
          <id>confluent</id>
          <url>http://packages.confluent.io/maven/</url>
          <releases>
            <enabled>true</enabled>
          </releases>
          <snapshots>
            <enabled>true</enabled>
          </snapshots>
</repository>
</code>```

Title: Confluent Maven repository not working?

Body:
I need to use the Confluent kafka-avro-serializer Maven artifact. From the official guide I should add this repository to my Maven pom

<repository>
  <id>confluent</id>
  <url>http://packages.confluent.io/maven/</url>
</repository>

The problem is that the URL http://packages.confluent.io/maven/ seems to not work at the moment as I get the response below

<Error>
  NoSuchKey
  <Message>The specified key does not exist.</Message>
  <Key>maven/</Key>
  <RequestId>15E287D11E5D4DFA</RequestId>
  <HostId>
    QVr9lCF0y3SrQoa1Z0jDWtmxD3eJz1gAEdivauojVJ+Bexb2gB6JsMpnXc+JjF95i082hgSLJSM=
  </HostId>
</Error>

In fact Maven does not find the artifact

<dependency>
  <groupId>io.confluent</groupId>
  <artifactId>kafka-avro-serializer</artifactId>
  <version>3.1.1</version>
</dependency>

Do you know what the problem could be?
Thank you

Body:
You can add a mirror in you maven settings file to fetch the jars from confluent repo along with repository config .
Changes needed are
Add a mirror in settings.xml

   <mirror>
      <id>confluent</id>
      <mirrorOf>confluent</mirrorOf>
      <name>Nexus public mirror</name>
      <url>http://packages.confluent.io/maven/</url>
</mirror>

In repository section of maven settings add this

<repository>
          <id>confluent</id>
          <url>http://packages.confluent.io/maven/</url>
          <releases>
            <enabled>true</enabled>
          </releases>
          <snapshots>
            <enabled>true</enabled>
          </snapshots>
</repository>


问:
Set column default value in Google Sheets
I have a finance tracking worksheet that has a number of formulas for each row. What I'd like to add is have these formulas replicate whenever a new row is inserted (fill it with a "default value").

Sheet before adding the row:

Sheet after adding the row:

I'd like some of these cells (B28 in this case) to contain a formula. for this row the formula is:

```<code>=IF(ISBLANK(C27), "", CONCATENATE(YEAR(C27), "-", MONTH(C27)))
</code>```

答:
Because the formula is the same for all rows, I added a function that just does the following:

```<code>function addRow() {
  SpreadsheetApp.getActiveSheet().getRange('B7:B').setValue('=IF(ISBLANK(C7), "", CONCATENATE(YEAR(C7), "-", MONTH(C7)))');
}
</code>```

I set this function to run on a trigger whenever the sheet is edited. The row numbers increment themselves so not problem there either.

Used this SO question for help: Default cell values when Inserting new row in Google Sheets

ContentLicense: CC BY-SA 4.0

Body:
I have a finance tracking worksheet that has a number of formulas for each row. What I'd like to add is have these formulas replicate whenever a new row is inserted (fill it with a "default value").

Sheet before adding the row:

Sheet after adding the row:

I'd like some of these cells (B28 in this case) to contain a formula. for this row the formula is:

=IF(ISBLANK(C27), "", CONCATENATE(YEAR(C27), "-", MONTH(C27)))

Body:
Because the formula is the same for all rows, I added a function that just does the following:

function addRow() {
  SpreadsheetApp.getActiveSheet().getRange('B7:B').setValue('=IF(ISBLANK(C7), "", CONCATENATE(YEAR(C7), "-", MONTH(C7)))');
}

I set this function to run on a trigger whenever the sheet is edited. The row numbers increment themselves so not problem there either.

Used this SO question for help: Default cell values when Inserting new row in Google Sheets


问:
How to not print everything inside a loop but make it based on decisions
so I have a question to Java. I want to print everything from the method once and not every time.
The method is called refrigeratorInformation.
So my question is, how do I just run the methode once and then get asked again, what I want to do next. Here is the code:

```<code>System.out.println("State what you would like to do with the refrigerator:");
USER_INPUT = input.nextLine();
while(true){
     if (USER_INPUT.equalsIgnoreCase("I want to close the refrigerator")){
         TimeUnit.SECONDS.sleep(1);
         System.out.println("Shutting down!");
         TimeUnit.SECONDS.sleep(3);
         System.exit(0);
     } else if (USER_INPUT.equalsIgnoreCase("What is the current temperature inside the refrigerator")){
         refrigeratorTemperature();
     } else if (USER_INPUT.equalsIgnoreCase("Show me some info about the refrigerator")){
         refrigeratorInformation();
     }
}
</code>```

And here is the methods code:

```<code>public void refrigeratorInformation(){
    dimension= "Width is 178cm, Height 66,8cm & length is 59,5cm";
    usage = 157;
    volume = 707.5; // in liter
    name = "Build Your Body Fat";
    weight = 63;
    try{
        System.out.println(name);
        System.out.println(weight);
        System.out.println(volume +" Liter");
        System.out.println("The refrigerator has a usage of " + usage + "kWh");
        System.out.println(dimension);
        TimeUnit.SECONDS.sleep(5);
    }
...
</code>```

I would be pretty thankful, if you could help me out

答:
If you want to stop executing the method you put the return statement in the end of this method, if you want to skip an iteration you put continue in your loop skipping one iteration. And if you put break your loop stops and not the method.
I believe you're looking for break

Read the docs while loop

Body:
so I have a question to Java. I want to print everything from the method once and not every time.
The method is called refrigeratorInformation.
So my question is, how do I just run the methode once and then get asked again, what I want to do next. Here is the code:

System.out.println("State what you would like to do with the refrigerator:");
USER_INPUT = input.nextLine();
while(true){
     if (USER_INPUT.equalsIgnoreCase("I want to close the refrigerator")){
         TimeUnit.SECONDS.sleep(1);
         System.out.println("Shutting down!");
         TimeUnit.SECONDS.sleep(3);
         System.exit(0);
     } else if (USER_INPUT.equalsIgnoreCase("What is the current temperature inside the refrigerator")){
         refrigeratorTemperature();
     } else if (USER_INPUT.equalsIgnoreCase("Show me some info about the refrigerator")){
         refrigeratorInformation();
     }
}

And here is the methods code:

public void refrigeratorInformation(){
    dimension= "Width is 178cm, Height 66,8cm & length is 59,5cm";
    usage = 157;
    volume = 707.5; // in liter
    name = "Build Your Body Fat";
    weight = 63;
    try{
        System.out.println(name);
        System.out.println(weight);
        System.out.println(volume +" Liter");
        System.out.println("The refrigerator has a usage of " + usage + "kWh");
        System.out.println(dimension);
        TimeUnit.SECONDS.sleep(5);
    }
...

I would be pretty thankful, if you could help me out


问:
Celery and Rabbit MQ Django
I installed Celery and RabbitMQ with the commands:
pip install celery and sudo apt-get install rabbitmq.
Celery doesn't work; I get this error:

```<code>Traceback (most recent call last):
  File "/home/morilon/dj/shop/lib/python3.5/site-
packages/celery/app/utils.py", line 361, in find_app
    found = sym.app
AttributeError: module 'myshop' has no attribute 'app'
</code>```

During handling of the above exception, another exception occurred:

```<code>Traceback (most recent call last):
  File "/home/morilon/dj/shop/bin/celery", line 11, in <module>
    sys.exit(main())
 File "/home/morilon/dj/shop/lib/python3.5/site-packages/celery/__main__.py", line 14, in main
    _main()
  File "/home/morilon/dj/shop/lib/python3.5/site-packages/celery/bin/celery.py", line 326, in main
    cmd.execute_from_commandline(argv)
  File "/home/morilon/dj/shop/lib/python3.5/site-packages/celery/bin/celery.py", line 488, in execute_from_commandline
    super(CeleryCommand, self).execute_from_commandline(argv)))
  File "/home/morilon/dj/shop/lib/python3.5/site-packages/celery/bin/base.py", line 279, in execute_from_commandline
    argv = self.setup_app_from_commandline(argv)
  File "/home/morilon/dj/shop/lib/python3.5/site-packages/celery/bin/base.py", line 481, in setup_app_from_commandline
    self.app = self.find_app(app)
  File "/home/morilon/dj/shop/lib/python3.5/site-packages/celery/bin/base.py", line 503, in find_app
    return find_app(app, symbol_by_name=self.symbol_by_name)
  File "/home/morilon/dj/shop/lib/python3.5/site-packages/celery/app/utils.py", line 366, in find_app
    found = sym.celery
AttributeError: module 'myshop' has no attribute 'celery'
</code>```

I don't understand what to do with this?

tasks.py

```<code>from celery import task
from django.core.mail import send_mail
from .models import Order

@task
def order_created(order_id):
    """
    Task to send an e-mail notification when an order is successfully created.
    """
    order = Order.objects.get(id=order_id)
    subject = 'Order nr. {}'.format(order.id)
    message = 'Dear {},\n\nYou have successfully placed an order. Your order id is {}.'.format(order.first_name,
                                                                             order.id)
    mail_sent = send_mail(subject, message, 'admin@myshop.com', [order.email])
    return mail_sent
</code>```

celery.py

```<code>import os
from celery import Celery
from django.conf import settings

# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myshop.settings')

app = Celery('myshop')

app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
</code>```

init.py

from .celery import app as celery_app

This project on GitHub https://github.com/Loctarogar/Django-by-Example

答: Where's your __init__.py file which is importing the celery app? Is it in shop/myshop/ directory? So it needs to be inside myshop app in order for celery app to be loaded at startup.

Title: Celery and Rabbit MQ Django

Body:
I installed Celery and RabbitMQ with the commands:
pip install celery and sudo apt-get install rabbitmq.
Celery doesn't work; I get this error:

Traceback (most recent call last):
  File "/home/morilon/dj/shop/lib/python3.5/site-
packages/celery/app/utils.py", line 361, in find_app
    found = sym.app
AttributeError: module 'myshop' has no attribute 'app'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/morilon/dj/shop/bin/celery", line 11, in <module>
    sys.exit(main())
 File "/home/morilon/dj/shop/lib/python3.5/site-packages/celery/__main__.py", line 14, in main
    _main()
  File "/home/morilon/dj/shop/lib/python3.5/site-packages/celery/bin/celery.py", line 326, in main
    cmd.execute_from_commandline(argv)
  File "/home/morilon/dj/shop/lib/python3.5/site-packages/celery/bin/celery.py", line 488, in execute_from_commandline
    super(CeleryCommand, self).execute_from_commandline(argv)))
  File "/home/morilon/dj/shop/lib/python3.5/site-packages/celery/bin/base.py", line 279, in execute_from_commandline
    argv = self.setup_app_from_commandline(argv)
  File "/home/morilon/dj/shop/lib/python3.5/site-packages/celery/bin/base.py", line 481, in setup_app_from_commandline
    self.app = self.find_app(app)
  File "/home/morilon/dj/shop/lib/python3.5/site-packages/celery/bin/base.py", line 503, in find_app
    return find_app(app, symbol_by_name=self.symbol_by_name)
  File "/home/morilon/dj/shop/lib/python3.5/site-packages/celery/app/utils.py", line 366, in find_app
    found = sym.celery
AttributeError: module 'myshop' has no attribute 'celery'

I don't understand what to do with this?

tasks.py

from celery import task
from django.core.mail import send_mail
from .models import Order

@task
def order_created(order_id):
    """
    Task to send an e-mail notification when an order is successfully created.
    """
    order = Order.objects.get(id=order_id)
    subject = 'Order nr. {}'.format(order.id)
    message = 'Dear {},\n\nYou have successfully placed an order. Your order id is {}.'.format(order.first_name,
                                                                             order.id)
    mail_sent = send_mail(subject, message, 'admin@myshop.com', [order.email])
    return mail_sent

celery.py

import os
from celery import Celery
from django.conf import settings

# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myshop.settings')

app = Celery('myshop')

app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)

init.py

from .celery import app as celery_app

This project on GitHub https://github.com/Loctarogar/Django-by-Example


问:
convert a string to a list of object using Java 8
I have a string

```<code>"Red apple, blue banana, orange".
</code>```

How could I split it by ", " first then add "_" between two words (such as Red_apple but not orange) and capitalize all letters. I read a few posts and found a solution but it only has the split part and how could I also add "_" and capitalize all letters? :

```<code>   Pattern pattern = Pattern.compile(", ");
   List<Fruit> f = pattern.splitAsStream(fruitString)
  .map(Fruit::valueOf)
  .collect(Collectors.toList());
</code>```

Fruit is a enum object. So basically if I am able to convert a string to a certain format and I am able get a Enum object based on a Enum name.

答:
```<code>String yourString = "Red apple, blue banana, orange";
stringArray = yourString.split(", ");
List<string> result;
//stringArray will contain 3 strings
//Red apple
//blue banana
//orange
for(string s : stringArray) {
    //Replace all spaces with underscores
    result.add(s.replace(" ", "_").toUpperCase());
}
</code>```

Body:
I have a string

"Red apple, blue banana, orange".

How could I split it by ", " first then add "_" between two words (such as Red_apple but not orange) and capitalize all letters. I read a few posts and found a solution but it only has the split part and how could I also add "_" and capitalize all letters? :

   Pattern pattern = Pattern.compile(", ");
   List<Fruit> f = pattern.splitAsStream(fruitString)
  .map(Fruit::valueOf)
  .collect(Collectors.toList());

Fruit is a enum object. So basically if I am able to convert a string to a certain format and I am able get a Enum object based on a Enum name.


问:
Template Tag if statement having issues with arguments given
I made a template tag to show the current user if they have any unread notifications in the base template. I think that I need to pass in two arguments - one to establish that we are only showing notifications for the current user (using filter to do this), and the second to return if there are any unread notifications (also using filter for this). However, I am getting an error saying that I can only pass through one argument even though I need two.

Here if my template tag:

```<code>@register.simple_tag(name='notseen')
def notseen():
    if UserNotification.objects.filter(toUser=User) and UserNotification.objects.filter(read=False).exists():
        print("True")
        return True
    else:
        print("False")
        return False
</code>```

Here is the Traceback:

```<code>Traceback (most recent call last):
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/core/handlers/base.py", line 217, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/core/handlers/base.py", line 215, in _get_response
    response = response.render()
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/template/response.py", line 107, in render
    self.content = self.rendered_content
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/template/response.py", line 84, in rendered_content
    content = template.render(context, self._request)
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/template/backends/django.py", line 66, in render
    return self.template.render(context)
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/template/base.py", line 207, in render
    return self._render(context)
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/template/base.py", line 199, in _render
    return self.nodelist.render(context)
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/template/base.py", line 990, in render
    bit = node.render_annotated(context)
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/template/base.py", line 957, in render_annotated
    return self.render(context)
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/template/loader_tags.py", line 177, in render
    return compiled_parent._render(context)
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/template/base.py", line 199, in _render
    return self.nodelist.render(context)
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/template/base.py", line 990, in render
    bit = node.render_annotated(context)
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/template/base.py", line 957, in render_annotated
    return self.render(context)
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/template/defaulttags.py", line 322, in render
    return nodelist.render(context)
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/template/base.py", line 990, in render
    bit = node.render_annotated(context)
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/template/base.py", line 957, in render_annotated
    return self.render(context)
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/template/library.py", line 203, in render
    output = self.func(*resolved_args, **resolved_kwargs)
  File "/Users/garrettlove/Desktop/evverest/notify/templatetags/notify_extras.py", line 11, in notseen
    if UserNotification.objects.filter(toUser=User) and UserNotification.objects.filter(read=False).exists():
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/db/models/query.py", line 784, in filter
    return self._filter_or_exclude(False, *args, **kwargs)
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/db/models/query.py", line 802, in _filter_or_exclude
    clone.query.add_q(Q(*args, **kwargs))
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1250, in add_q
    clause, _ = self._add_q(q_object, self.used_aliases)
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1276, in _add_q
    allow_joins=allow_joins, split_subq=split_subq,
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1210, in build_filter
    condition = self.build_lookup(lookups, col, value)
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1104, in build_lookup
    return final_lookup(lhs, rhs)
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/db/models/lookups.py", line 24, in __init__
    self.rhs = self.get_prep_lookup()
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/db/models/lookups.py", line 72, in get_prep_lookup
    return self.rhs._prepare(self.lhs.output_field)
TypeError: _prepare() takes 1 positional argument but 2 were given
</code>```

Edit:
I added print(myUser.__dict__) to the if statement and this is the output

```<code>{'__module__': 'django.contrib.auth.models', '__doc__': '\n    Users within the Django authentication system are represented by this\n    model.\n\n    Username, password and email are required. Other fields are optional.\n    ', '_meta': <Options for User>, 'DoesNotExist': <class 'django.contrib.auth.models.DoesNotExist'>, 'MultipleObjectsReturned': <class 'django.contrib.auth.models.MultipleObjectsReturned'>, 'get_next_by_date_joined': <function curry.<locals>._curried at 0x1024c3598>, 'get_previous_by_date_joined': <function curry.<locals>._curried at 0x1024c3620>, 'groups': <django.db.models.fields.related_descriptors.ManyToManyDescriptor object at 0x1024c7f98>, 'user_permissions': <django.db.models.fields.related_descriptors.ManyToManyDescriptor object at 0x1024d0630>, 'id': <django.db.models.query_utils.DeferredAttribute object at 0x1024d0748>, 'logentry_set': <django.db.models.fields.related_descriptors.ReverseManyToOneDescriptor object at 0x1024d0828>, 'userprofile': <django.db.models.fields.related_descriptors.ReverseOneToOneDescriptor object at 0x1024ee358>, 'userpost': <django.db.models.fields.related_descriptors.ReverseManyToOneDescriptor object at 0x1024f65c0>, 'post_likes': <django.db.models.fields.related_descriptors.ManyToManyDescriptor object at 0x1024f6630>, 'usercomment': <django.db.models.fields.related_descriptors.ReverseManyToOneDescriptor object at 0x1024eeeb8>, 'blogpost': <django.db.models.fields.related_descriptors.ReverseManyToOneDescriptor object at 0x1025065c0>, 'blogcomment': <django.db.models.fields.related_descriptors.ReverseManyToOneDescriptor object at 0x102506c50>, 'user': <django.db.models.fields.related_descriptors.ReverseManyToOneDescriptor object at 0x10250e6a0>, 'emailaddress_set': <django.db.models.fields.related_descriptors.ReverseManyToOneDescriptor object at 0x102548240>, 'socialaccount_set': <django.db.models.fields.related_descriptors.ReverseManyToOneDescriptor object at 0x10256a128>}
</code>```

答:
Check Python Scope here </p>

```<code>@register.simple_tag(name='notseen')
def notseen():
    # Add User varaible here
    myUser = get_user_model()
    if UserNotification.objects.filter(toUser=myUser) and UserNotification.objects.filter(read=False).exists():
        print("True")
        return True
    else:
        print("False")
        return False
</code>```

Body:
I made a template tag to show the current user if they have any unread notifications in the base template. I think that I need to pass in two arguments - one to establish that we are only showing notifications for the current user (using filter to do this), and the second to return if there are any unread notifications (also using filter for this). However, I am getting an error saying that I can only pass through one argument even though I need two.

Here if my template tag:

@register.simple_tag(name='notseen')
def notseen():
    if UserNotification.objects.filter(toUser=User) and UserNotification.objects.filter(read=False).exists():
        print("True")
        return True
    else:
        print("False")
        return False

Here is the Traceback:

Traceback (most recent call last):
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/core/handlers/base.py", line 217, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/core/handlers/base.py", line 215, in _get_response
    response = response.render()
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/template/response.py", line 107, in render
    self.content = self.rendered_content
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/template/response.py", line 84, in rendered_content
    content = template.render(context, self._request)
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/template/backends/django.py", line 66, in render
    return self.template.render(context)
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/template/base.py", line 207, in render
    return self._render(context)
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/template/base.py", line 199, in _render
    return self.nodelist.render(context)
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/template/base.py", line 990, in render
    bit = node.render_annotated(context)
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/template/base.py", line 957, in render_annotated
    return self.render(context)
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/template/loader_tags.py", line 177, in render
    return compiled_parent._render(context)
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/template/base.py", line 199, in _render
    return self.nodelist.render(context)
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/template/base.py", line 990, in render
    bit = node.render_annotated(context)
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/template/base.py", line 957, in render_annotated
    return self.render(context)
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/template/defaulttags.py", line 322, in render
    return nodelist.render(context)
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/template/base.py", line 990, in render
    bit = node.render_annotated(context)
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/template/base.py", line 957, in render_annotated
    return self.render(context)
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/template/library.py", line 203, in render
    output = self.func(*resolved_args, **resolved_kwargs)
  File "/Users/garrettlove/Desktop/evverest/notify/templatetags/notify_extras.py", line 11, in notseen
    if UserNotification.objects.filter(toUser=User) and UserNotification.objects.filter(read=False).exists():
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/db/models/query.py", line 784, in filter
    return self._filter_or_exclude(False, *args, **kwargs)
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/db/models/query.py", line 802, in _filter_or_exclude
    clone.query.add_q(Q(*args, **kwargs))
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1250, in add_q
    clause, _ = self._add_q(q_object, self.used_aliases)
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1276, in _add_q
    allow_joins=allow_joins, split_subq=split_subq,
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1210, in build_filter
    condition = self.build_lookup(lookups, col, value)
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1104, in build_lookup
    return final_lookup(lhs, rhs)
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/db/models/lookups.py", line 24, in __init__
    self.rhs = self.get_prep_lookup()
  File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/db/models/lookups.py", line 72, in get_prep_lookup
    return self.rhs._prepare(self.lhs.output_field)
TypeError: _prepare() takes 1 positional argument but 2 were given

Edit:
I added print(myUser.__dict__) to the if statement and this is the output

{'__module__': 'django.contrib.auth.models', '__doc__': '\n    Users within the Django authentication system are represented by this\n    model.\n\n    Username, password and email are required. Other fields are optional.\n    ', '_meta': <Options for User>, 'DoesNotExist': <class 'django.contrib.auth.models.DoesNotExist'>, 'MultipleObjectsReturned': <class 'django.contrib.auth.models.MultipleObjectsReturned'>, 'get_next_by_date_joined': <function curry.<locals>._curried at 0x1024c3598>, 'get_previous_by_date_joined': <function curry.<locals>._curried at 0x1024c3620>, 'groups': <django.db.models.fields.related_descriptors.ManyToManyDescriptor object at 0x1024c7f98>, 'user_permissions': <django.db.models.fields.related_descriptors.ManyToManyDescriptor object at 0x1024d0630>, 'id': <django.db.models.query_utils.DeferredAttribute object at 0x1024d0748>, 'logentry_set': <django.db.models.fields.related_descriptors.ReverseManyToOneDescriptor object at 0x1024d0828>, 'userprofile': <django.db.models.fields.related_descriptors.ReverseOneToOneDescriptor object at 0x1024ee358>, 'userpost': <django.db.models.fields.related_descriptors.ReverseManyToOneDescriptor object at 0x1024f65c0>, 'post_likes': <django.db.models.fields.related_descriptors.ManyToManyDescriptor object at 0x1024f6630>, 'usercomment': <django.db.models.fields.related_descriptors.ReverseManyToOneDescriptor object at 0x1024eeeb8>, 'blogpost': <django.db.models.fields.related_descriptors.ReverseManyToOneDescriptor object at 0x1025065c0>, 'blogcomment': <django.db.models.fields.related_descriptors.ReverseManyToOneDescriptor object at 0x102506c50>, 'user': <django.db.models.fields.related_descriptors.ReverseManyToOneDescriptor object at 0x10250e6a0>, 'emailaddress_set': <django.db.models.fields.related_descriptors.ReverseManyToOneDescriptor object at 0x102548240>, 'socialaccount_set': <django.db.models.fields.related_descriptors.ReverseManyToOneDescriptor object at 0x10256a128>}

Body:
Check Python Scope here

@register.simple_tag(name='notseen')
def notseen():
    # Add User varaible here
    myUser = get_user_model()
    if UserNotification.objects.filter(toUser=myUser) and UserNotification.objects.filter(read=False).exists():
        print("True")
        return True
    else:
        print("False")
        return False


问:
c++ shared_ptr & memcpy errors
I have decided to move to modern c++ practices, and I'v tried to adapt my old code to make use of smart pointers. I have a packet class that holds the packet data, along side some other variables.

```<code>class Packet
{
public:
    Packet(int connId, std::shared_ptr<char[]> buff, size_t pLen)
        : connID(connId), packetLen(pLen)
    {
        buffer = buff;
    }

    Packet(){}

    int connID;
    size_t packetLen;
    std::shared_ptr<char[]> buffer;
};
</code>```

And I have a test function that creates and inserts data into the new allocated buffer.

```<code>std::vector<Packet> packetV;

void createPacket()
{
    std::shared_ptr<char[]> data = std::make_shared<char[]>(10);

    for (int i = 0; i < 5; ++i)
    {
        uint8_t byte = 5;
        memcpy(*data.get() + i, &byte, sizeof(uint8_t));
    }

    packetV.push_back(Packet(1, data, 5*sizeof(uint8_t)));
}

//(Main function)
void main()
{
    std::string input;
    do
    {
        std::cin >> input;
        if (input == "packet") createPacket();
        else if (input == "exit") input.clear();
        else if (input == "empty") packetV.clear();
        else if (input == "show") std::cout << packetV.size() << std::endl;

    } while (input.size() > 0);
}
</code>```

When I try compiling the code I get the fallowing errors:

```<code>1>c:\program files (x86)\microsoft visual studio\2017\professional\vc\tools\msvc\14.11.25503\include\type_traits(1192): error C2070: 'char []': illegal sizeof operand
1>c:\program files (x86)\microsoft visual studio\2017\professional\vc\tools\msvc\14.11.25503\include\type_traits(1199): note: see reference to class template instantiation 'std::aligned_union<1,_Ty>' being compiled
1>        with
1>        [
1>            _Ty=char []
1>        ]
1>c:\program files (x86)\microsoft visual studio\2017\professional\vc\tools\msvc\14.11.25503\include\memory(1731): note: see reference to alias template instantiation 'aligned_union_t<1,char[]>' being compiled
1>c:\program files (x86)\microsoft visual studio\2017\professional\vc\tools\msvc\14.11.25503\include\memory(1778): note: see reference to class template instantiation 'std::_Ref_count_obj<_Ty>' being compiled
1>        with
1>        [
1>            _Ty=char []
1>        ]
1>c:\users\...\documents\visual studio 2017\projects\..\...\source.cpp(29): note: see reference to function template instantiation 'std::shared_ptr<char []> std::make_shared<char[],int>(int &&)' being compiled
</code>```

Could someone help me to understand the error and advice me on how to design the insertion and extraction of the data into the char * array by using smart pointers !?

答:
std::shared_ptr is NOT specialized for use with arrays in the current standard version of C++. Support is expected to arrive in C++20.

In the meantime, you have a couple of options:

Use std::string, which automatically manages dynamically-sized strings, and really should be your go-to default response when someone says "Save a bunch of characters in memory!"

Use std::unique_ptr<char[]>. Unlike shared_ptr, unique_ptr IS specialized for arrays, which means the constructs you're trying to use will work with it.

Use std::vector<uint8_t>. This is (nearly) equivalent to std::string in terms of the data it stores, but here, the usage is more verbose: the data isn't merely a string of characters, but specifically, it's raw binary data.

Title: c++ shared_ptr & memcpy errors

Body:
I have decided to move to modern c++ practices, and I'v tried to adapt my old code to make use of smart pointers. I have a packet class that holds the packet data, along side some other variables.

class Packet
{
public:
    Packet(int connId, std::shared_ptr<char[]> buff, size_t pLen)
        : connID(connId), packetLen(pLen)
    {
        buffer = buff;
    }

    Packet(){}

    int connID;
    size_t packetLen;
    std::shared_ptr<char[]> buffer;
};

And I have a test function that creates and inserts data into the new allocated buffer.

std::vector<Packet> packetV;

void createPacket()
{
    std::shared_ptr<char[]> data = std::make_shared<char[]>(10);

    for (int i = 0; i < 5; ++i)
    {
        uint8_t byte = 5;
        memcpy(*data.get() + i, &byte, sizeof(uint8_t));
    }

    packetV.push_back(Packet(1, data, 5*sizeof(uint8_t)));
}

//(Main function)
void main()
{
    std::string input;
    do
    {
        std::cin >> input;
        if (input == "packet") createPacket();
        else if (input == "exit") input.clear();
        else if (input == "empty") packetV.clear();
        else if (input == "show") std::cout << packetV.size() << std::endl;

    } while (input.size() > 0);
}

When I try compiling the code I get the fallowing errors:

1>c:\program files (x86)\microsoft visual studio\2017\professional\vc\tools\msvc\14.11.25503\include\type_traits(1192): error C2070: 'char []': illegal sizeof operand
1>c:\program files (x86)\microsoft visual studio\2017\professional\vc\tools\msvc\14.11.25503\include\type_traits(1199): note: see reference to class template instantiation 'std::aligned_union<1,_Ty>' being compiled
1>        with
1>        [
1>            _Ty=char []
1>        ]
1>c:\program files (x86)\microsoft visual studio\2017\professional\vc\tools\msvc\14.11.25503\include\memory(1731): note: see reference to alias template instantiation 'aligned_union_t<1,char[]>' being compiled
1>c:\program files (x86)\microsoft visual studio\2017\professional\vc\tools\msvc\14.11.25503\include\memory(1778): note: see reference to class template instantiation 'std::_Ref_count_obj<_Ty>' being compiled
1>        with
1>        [
1>            _Ty=char []
1>        ]
1>c:\users\...\documents\visual studio 2017\projects\..\...\source.cpp(29): note: see reference to function template instantiation 'std::shared_ptr<char []> std::make_shared<char[],int>(int &&)' being compiled

Could someone help me to understand the error and advice me on how to design the insertion and extraction of the data into the char * array by using smart pointers !?


问:
Secure Wiping of files in Compact Framework
Given the path of a string i want to wipe out the contents of a file. The natural way I thought (which maybe incorrect) was to open a FileStream to the file and write gibberish (random data perhaps taken from a RNGCryptoServiceProvider) to it. And then perhaps do this several times and then delete the file.

My problem is that while this may look logically correct, i read up on another blog that Windows might actually choose to write the file to a different place in the hard disk.

Is that the case in Windows Mobile? Will this actually be a problem? Does this writing to a different location in the hard disk apply to even flash based (SD etc) cards ?

答:
I've not personally done this, but you will probably need to use the low-level FLASH driver IOCTLs to do this correctly.

http://msdn.microsoft.com/en-us/library/aa927166.aspx

I think IOCTL_FMD_RAW_WRITE_BLOCKS looks particularly useful.

-PaulH

Another possibility that may work would be to erase the file normally, then use the defragment APIs to wipe ALL of the freespace on your flash. Since you're wiping everything, it won't be necessary to know exactly where on the disk your file was. But, this will wear out your flash drive more quickly. The C# method is detailed in this blog post: http://blogs.msdn.com/b/jeffrey_wall/archive/2004/09/13/229137.aspx

ContentLicense: CC BY-SA 2.5


问:
C++ : How to ensure that a class member variable is modifiable only within a certain method
I am using C++ 14 with clang on MacOS Sierra. I want to enforce a rule by design. Following is the rule.

I have a member variable in my class say:

```<code>unsigned int m_important_num;
</code>```

There are 4 methods in my class.

```<code>fun1();
fun2();
fun3();
fun4();
</code>```

Objective:

I want only fun2() to be able to change the value of m_important_num.

Question:

Is it possible to make it compiler error if any method other than fun2() changes the variable?
One possible way is to declare it const somehow empower fun2() to change const variables? Is this a good solution? Or are their any better solutions?

Secondary question:

Is it a wrong design to try do such a thing?

答:
I little variant (if I understand correctly) of the Jeffrey solution: put the variable in an inner class and make it private; create a public getter and make func2() friend to the inner class.

I mean

```<code>struct foo
 {
   int f1 () { return b0.getVal(); }; // you can read `val` everywhere
   void f2 () { b0.val = 42; }; // you can write `val` in f2()
   void f3 () { /* b0.val = 42; ERROR ! */ }; // but only in f2()

   class bar
    {
      private:
         int val = 24;

      public:
         int getVal () { return val; }

      friend void foo::f2 ();
    };

   bar b0;
 };
</code>```

In other words: friend is your friend.

Body:
I am using C++ 14 with clang on MacOS Sierra. I want to enforce a rule by design. Following is the rule.

I have a member variable in my class say:

unsigned int m_important_num;

There are 4 methods in my class.

fun1();
fun2();
fun3();
fun4();

Objective:

I want only fun2() to be able to change the value of m_important_num.

Question:

Is it possible to make it compiler error if any method other than fun2() changes the variable?
One possible way is to declare it const somehow empower fun2() to change const variables? Is this a good solution? Or are their any better solutions?

Secondary question:

Is it a wrong design to try do such a thing?

Body:
I little variant (if I understand correctly) of the Jeffrey solution: put the variable in an inner class and make it private; create a public getter and make func2() friend to the inner class.

I mean

struct foo
 {
   int f1 () { return b0.getVal(); }; // you can read `val` everywhere
   void f2 () { b0.val = 42; }; // you can write `val` in f2()
   void f3 () { /* b0.val = 42; ERROR ! */ }; // but only in f2()

   class bar
    {
      private:
         int val = 24;

      public:
         int getVal () { return val; }

      friend void foo::f2 ();
    };

   bar b0;
 };

In other words: friend is your friend.


问:
Exposing .NET MVC Service layer as REST endpoints
I have a .NET MVC application with a service layer that we inject using Unity into the controllers to separate view logic from business logic.  Is there any way to expose the same service layer methods as REST endpoints so that other applications could use our service layer as a REST API, while still using the service layer in our monolithic application?

Are there any examples of someone doing this?

答:
In that case, you can create a separated project using ASP.Net Web Api.

Using Web Api, you should be able to inject your services into your controllers and call those Rest Services from your MVC application as well as from any other application (mobile, etc).

You can also consider, in case you are using EF, creating a separate project(layer) for your repository and inject the EF Context into your repositories, the repositories into your services layer and your services into your controllers.

In my personal projects, I call the services layer only from my WEB API project and never from my MVC application. The MVC will use the services layer only through your REST Services.


问:
xslt sort based on mutually exclusive element
I have an xml data where there are 2 date elements <STRT_DT> and <STRT_BY_DT>. These 2 elements are mutually exclusive. I need to sort the XML aggregate with these dates in ascending order by date. Sample Instance:

<EVNT>

 <LGL_EVNT>
 <STRT_DT>2017-11-01</STRT_DT>
 <EVNT_TYP_CD>10</EVNT_TYP_CD>
</LGL_EVNT>
<LGL_EVNT>
 <STRT_BY_DT>2017-11-02</STRT_BY_DT>
 <EVNT_TYP_CD>10</EVNT_TYP_CD>
</LGL_EVNT>
<LGL_EVNT>
 <STRT_DT>2017-10-02</STRT_DT>
 <EVNT_TYP_CD>10</EVNT_TYP_CD>
</LGL_EVNT>
<LGL_EVNT>
 <STRT_BY_DT>2017-10-03</STRT_BY_DT>
 <EVNT_TYP_CD>10</EVNT_TYP_CD>
</LGL_EVNT>
</EVNT>

Expected Output is to get the Legal Event aggregate in ascending order:

<EVNT>
<LGL_EVNT>
 <STRT_DT>2017-10-02</STRT_DT>
 <EVNT_TYP_CD>10</EVNT_TYP_CD>
</LGL_EVNT>
<LGL_EVNT>
 <STRT_BY_DT>2017-10-03</STRT_BY_DT>
 <EVNT_TYP_CD>10</EVNT_TYP_CD>
</LGL_EVNT>
<LGL_EVNT>
 <STRT_DT>2017-11-01</STRT_DT>
 <EVNT_TYP_CD>10</EVNT_TYP_CD>
</LGL_EVNT>
<LGL_EVNT>
 <STRT_BY_DT>2017-11-02</STRT_BY_DT>
 <EVNT_TYP_CD>10</EVNT_TYP_CD>
</LGL_EVNT>
</EVNT>

I am not able to sort based on these 2 mutually exclusive elements using xslt 2.0. Please help.

答:
Simply use an xsl:sort with a sequence of two dates constructed from the two elements, as they are mutually exclusive there will only one sort key for each element:

```<code><xsl:template match="EVNT">
    <xsl:copy>
        <xsl:apply-templates select="LGL_EVNT">
            <xsl:sort select="xs:date(STRT_DT) , xs:date(STRT_BY_DT)"/>
        </xsl:apply-templates>
    </xsl:copy>
</xsl:template>
</code>```

Add the identity transformation template to that (or use XSLT 3 and <xsl:mode on-no-match="shallow-copy"/>).

Body:
Simply use an xsl:sort with a sequence of two dates constructed from the two elements, as they are mutually exclusive there will only one sort key for each element:

<xsl:template match="EVNT">
    <xsl:copy>
        <xsl:apply-templates select="LGL_EVNT">
            <xsl:sort select="xs:date(STRT_DT) , xs:date(STRT_BY_DT)"/>
        </xsl:apply-templates>
    </xsl:copy>
</xsl:template>

Add the identity transformation template to that (or use XSLT 3 and <xsl:mode on-no-match="shallow-copy"/>).


问:
Execute cqlsh inside script
I am trying to execute cqlsh inside bash script. My script is below. When ı try to execute sh file, it returns cql command not found</p>

```<code>#!/bin/bash

set -x

PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

cqlsh -e "SELECT * FROM msg.msg_log limit 1;" > /home/yunus/sh/cqlshcontrol.txt

error1=$( more /home/yunus/sh/cqlshcontrol.txt | wc -l )

if [ $error1 -lt 1 ]; then

curl -S -X POST --data "payload={\"text\": \" Cqlsh not responding, Connection Problem   \",\"username\":\"Elevate Cassandra1\",\"icon_emoji\":\"${SLACK_ICON}\"}" https://hooks.slack.com/services/

fi
</code>```

答:
some suggestions

use [[/]] over [/].

the return value of $() is not an error value and should be named lines or something more meaningful.  The lack of another error variable in the code makes the appended number (the 1 in error1) seem even odder.

There's no reason to use more or pipe inside of that subshell.  Just run wc -l on your file.

Are you sure cqlsh is in the PATH?  Try which cqlsh to find it.

wc will never return a negative value so comparing for equality with zero would be clear and cover just as many potential cases.

otherwise

If that doesn't get you out of your confusion please show the output when you try to run it.

Title: Execute cqlsh inside script

Body:
I am trying to execute cqlsh inside bash script. My script is below. When ı try to execute sh file, it returns cql command not found

#!/bin/bash

set -x

PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

cqlsh -e "SELECT * FROM msg.msg_log limit 1;" > /home/yunus/sh/cqlshcontrol.txt

error1=$( more /home/yunus/sh/cqlshcontrol.txt | wc -l )

if [ $error1 -lt 1 ]; then

curl -S -X POST --data "payload={\"text\": \" Cqlsh not responding, Connection Problem   \",\"username\":\"Elevate Cassandra1\",\"icon_emoji\":\"${SLACK_ICON}\"}" https://hooks.slack.com/services/

fi


问:
Javascript event listener not firing

If you come across this thread with a similar event listener problem the issue may be with your CSS and not your Javascript. See my answer below for details.

I've spent a considerable amount of time searching SO and looking at others' solutions to similar problems to no avail, so I've finally had to create an account.

I'm working on a webpage that has a picture of a world map with some location pins on top of it representing office locations. The idea is that mousing over one of this pins will alter some images and text elsewhere on the page.

However, when I mouseover any of the pins, nothing happens at all. No text or image changes elsewhere, and no messages printed to the console. I don't see any errors reported. I've made sure the events are not bound until after the document's ready, so I'm at a bit of a loss as to what I'm doing wrong. The console message "document ready" does get printed indicating the listeners should be bound. I've tried swapping in "click" to no effect, and I also tried using jQuery to delegate the event to the document (which was suggested in a similar question) and also saw no improvement.

Any help very much appreciated.

EDIT: Seeing some of the comments about clarity, I've commented out all of the code in my javascript except for what's listed below. I still don't see any console messages logged when I mouse over the element. Looking in the console, once more I don't see any error messages and I can verify the event "mouseenter" is in fact bound to meridianPin.

HTML for the map looks like this:

```<code><!-- Image & Map Widgets -->
<div id="mapContainer" class="itt-contact-img-container">
  <img class="itt-full-width-image" src="./Images/mapBanner.png" alt="worldMap">
  <img id="bangalorePin" class="itt-contact-pin itt-contact-pin-bangalore" src="./Icons/svg/locationIcon.svg">
  <img id="rosevillePin" class="itt-contact-pin itt-contact-pin-roseville" src="./Icons/svg/locationIcon.svg">
  <img id="mumbaiPin" class="itt-contact-pin itt-contact-pin-mumbai" src="./Icons/svg/locationIcon.svg">
  <img id="jaipurPin" class="itt-contact-pin itt-contact-pin-jaipur" src="./Icons/svg/locationIcon.svg">
  <img id="lakeoswegoPin" class="itt-contact-pin itt-contact-pin-lakeoswego" src="./Icons/svg/locationIcon.svg">
  <img id="camasPin" class="itt-contact-pin itt-contact-pin-camas" src="./Icons/svg/locationIcon.svg">
  <img id="meridianPin" class="itt-contact-pin itt-contact-pin-meridian" src="./Icons/svg/locationIcon.svg">
</div>
</code>```

Commented out all event listener binding except for this one:

```<code>$(document).ready(function(){
  console.log("document ready");
    document.getElementById("meridianPin").addEventListener("mouseenter", meridianHighlight);
})
</code>```

Here's the highlight function in question now that everything else is commented out:

```<code>function meridianHighlight(){
  console.log("meridian highlight");

  $("#itt-contact-silhouette").attr("src","./Icons/svg/idaho.svg");

  $("#itt-contact-hdr-merdian").css("display","block");
  $("#itt-contact-info-merdian").css("display","block");
  $("#itt-contact-hdr-camas").css("display","none");
  $("#itt-contact-info-camas").css("display","none");
  $("#itt-contact-hdr-lakeoswego").css("display","none");
  $("#itt-contact-info-lakeoswego").css("display","none");
  $("#itt-contact-hdr-roseville").css("display","none");
  $("#itt-contact-info-roseville").css("display","none");
  $("#itt-contact-hdr-jaipur").css("display","none");
  $("#itt-contact-info-jaipur").css("display","none");
  $("#itt-contact-hdr-mumbai").css("display","none");
  $("#itt-contact-info-mumbai").css("display","none");
  $("#itt-contact-hdr-bangalore").css("display","none");
  $("#itt-contact-info-bangalore").css("display","none");
}
</code>```

答:
Turns out that this was somehow a CSS problem. In my html you can see "mapBanner" at the top of the image group which was large image spanning the width of viewport, while each of the location icons was 22x22px. The icons appeared on top of the world map image on the page but took no notice of their mouseover event listeners. I changed the map picture to be the background image of the containing div, and now the event listeners fire as they should.

I'm happy to know how to move forward but I still don't understand how what I did earlier was wrong (aside from it not working), should I expect page large elements to mask the event listeners of smaller elements within?

Title: Javascript event listener not firing

Body:
If you come across this thread with a similar event listener problem the issue may be with your CSS and not your Javascript. See my answer below for details.

I've spent a considerable amount of time searching SO and looking at others' solutions to similar problems to no avail, so I've finally had to create an account.

I'm working on a webpage that has a picture of a world map with some location pins on top of it representing office locations. The idea is that mousing over one of this pins will alter some images and text elsewhere on the page.

However, when I mouseover any of the pins, nothing happens at all. No text or image changes elsewhere, and no messages printed to the console. I don't see any errors reported. I've made sure the events are not bound until after the document's ready, so I'm at a bit of a loss as to what I'm doing wrong. The console message "document ready" does get printed indicating the listeners should be bound. I've tried swapping in "click" to no effect, and I also tried using jQuery to delegate the event to the document (which was suggested in a similar question) and also saw no improvement.

Any help very much appreciated.

EDIT: Seeing some of the comments about clarity, I've commented out all of the code in my javascript except for what's listed below. I still don't see any console messages logged when I mouse over the element. Looking in the console, once more I don't see any error messages and I can verify the event "mouseenter" is in fact bound to meridianPin.

HTML for the map looks like this:

Commented out all event listener binding except for this one:

$(document).ready(function(){
  console.log("document ready");
    document.getElementById("meridianPin").addEventListener("mouseenter", meridianHighlight);
})

Here's the highlight function in question now that everything else is commented out:

function meridianHighlight(){
  console.log("meridian highlight");

  $("#itt-contact-silhouette").attr("src","./Icons/svg/idaho.svg");

  $("#itt-contact-hdr-merdian").css("display","block");
  $("#itt-contact-info-merdian").css("display","block");
  $("#itt-contact-hdr-camas").css("display","none");
  $("#itt-contact-info-camas").css("display","none");
  $("#itt-contact-hdr-lakeoswego").css("display","none");
  $("#itt-contact-info-lakeoswego").css("display","none");
  $("#itt-contact-hdr-roseville").css("display","none");
  $("#itt-contact-info-roseville").css("display","none");
  $("#itt-contact-hdr-jaipur").css("display","none");
  $("#itt-contact-info-jaipur").css("display","none");
  $("#itt-contact-hdr-mumbai").css("display","none");
  $("#itt-contact-info-mumbai").css("display","none");
  $("#itt-contact-hdr-bangalore").css("display","none");
  $("#itt-contact-info-bangalore").css("display","none");
}


问:
How to create mysql table with many hasMany association in CakePHP?
I'm defining a completely new database. I have now faced a problem
which I would describe as "usual" but still could not find good
information from web. So here's the problem:

I have many tables in my database (which I would describe as guides) such as:

Skills

Places

Activities

and so on...

Now to all these guide types I'd like to add a comment feature and
other similar features like attaching images and videos. I have many guide types so I dropped the idea of having a separate comment image and video tables for each of them. I need one table for each of them.

The question is, what is the best way to achieve this? I have heard and read about 3 solutions and I'm not familiar with none of them.

I have read about using UUIDs would fix this problem but I'm not very familiar how they function. Could someone elaborate on that if that is the correct way to go? Something about UUIDs I read but not quite understood it.

Other thing I have read about is creating a hierarchial model "tree table" which would hold association links. More info at Managing Hierarchical Data in MySQL.

I have also read about creating object tables and using program like object inheritance inside MySQL in a similar way like the hierarchical model.

UUIDs sound most simple so I would appreciate help in there.

I don't know anything about how to use them. But here's how I thought it works - at least you'll get a hang of it what I'm trying to achieve here and how/what I'm misunderstanding about them:

I would create a new table: Guides which could have UUID field.

Then link all those guide types (Skills etc.) to guide table (Guide as parent and the other as child)

Parent and Child have both UUID fields and when creating a guide Parent and Child gets same UUID so they can be linked. Child also has its own Id field.

Then link comments to Guides by using UUID field that points to Guide plus separate id int field for comments.

Please tell me if this is correct way or is it total garbage and if so, how I should do it?

答: Check http://cakeapp.com, create your DB layout there and download the SQL later.</p>


问:
I'm in a beginner's Python course, and my assignment is to print variable 'N' backwards using a 'while' statement
Here are my instructions:

We will pass you a value, N. You should output every positive value from N down to and including 0.

And here is my assignment:

```<code>    # Get N from the command line
    import sys
    N = int(sys.argv[1])

    # Your code goes here
    counter = 0
    while counter <= N:
     print(counter-N)
     counter = counter + 1
</code>```

My solution prints this:

```<code>Program Output

Program Failed for Input: 3
Expected Output: 3
2
1
0
Your Program Output: -3
-2
-1
0
</code>```

As you can see, I got the output to show -3, -2, -1, 0, but it should be 3, 2, 1, 0. Please be mindful that I am a beginner, and my code must pass using a 'while' statement, and my code must be inputted in Codio. Thank you in advance for any assistance rendered.

答:
Just step down from N to 0:</p>

```<code># Get N from the command line
import sys
N = int(sys.argv[1])

# Your code goes here
counter = N
while counter >= 0:
 print(counter)
 counter -= 1
</code>```

Body:
Here are my instructions:

We will pass you a value, N. You should output every positive value from N down to and including 0.

And here is my assignment:

    # Get N from the command line
    import sys
    N = int(sys.argv[1])

    # Your code goes here
    counter = 0
    while counter <= N:
     print(counter-N)
     counter = counter + 1

My solution prints this:

Program Output

Program Failed for Input: 3
Expected Output: 3
2
1
0
Your Program Output: -3
-2
-1
0

As you can see, I got the output to show -3, -2, -1, 0, but it should be 3, 2, 1, 0. Please be mindful that I am a beginner, and my code must pass using a 'while' statement, and my code must be inputted in Codio. Thank you in advance for any assistance rendered.

Body:
Just step down from N to 0:

# Get N from the command line
import sys
N = int(sys.argv[1])

# Your code goes here
counter = N
while counter >= 0:
 print(counter)
 counter -= 1