问:
What is the resolved node in an orderByChild query?
Firebase documentation on structuring the database mentions the following:

...when you fetch data at a location in your database, you also retrieve all of its child nodes.

I have the following basic data structure:

```<code>databaseRoot: {
    orders: {
        order1: {
            firebaseId: firebaseUid,
            ...
        }
    }
    orderItems: {
        order1: {
            firebaseId: firebaseUid,
            ...
        }
    }
}
</code>```

In my android start-up code I intend to sync the orders and orderItems that belong to the current user to handle the offline scenario.

```<code>FirebaseDatabase.getReference("orders").orderByChild("firebaseId").equalTo(firebaseUser.uid).keepSynced(true)
FirebaseDatabase.getReference("orderItems").orderByChild("firebaseId").equalTo(firebaseUser.uid).keepSynced(true)
</code>```

My Question:
Do the sync references consider the data location to be the entire Orders and OrderItems nodes, respectively?  Or does it resolve down to the specific child nodes that satisfy the firebase user id equal to the current user?

My hope is for the latter to be the result, as the client does not need any records beyond those belonging to the current user.

答:
Calling keepSynced(true) on a location is essentially the same as keeping a listener with an empty callback on that location.

So these two commands will ensure you that the orders and orderItems for the specific user are in cache.

But if that is the type of behavior you want, you might want to consider keep the data in a simpler structure: /orders/firebaseUid/order1, /orders/firebaseUid/order2, etc. With this structure you won't need a query to get the orders for a user and can just read from (and call keepSynced() on) /orders/firebaseUid.

Body:
Firebase documentation on structuring the database mentions the following:

...when you fetch data at a location in your database, you also retrieve all of its child nodes.

I have the following basic data structure:

databaseRoot: {
    orders: {
        order1: {
            firebaseId: firebaseUid,
            ...
        }
    }
    orderItems: {
        order1: {
            firebaseId: firebaseUid,
            ...
        }
    }
}

In my android start-up code I intend to sync the orders and orderItems that belong to the current user to handle the offline scenario.

FirebaseDatabase.getReference("orders").orderByChild("firebaseId").equalTo(firebaseUser.uid).keepSynced(true)
FirebaseDatabase.getReference("orderItems").orderByChild("firebaseId").equalTo(firebaseUser.uid).keepSynced(true)

My Question:
Do the sync references consider the data location to be the entire Orders and OrderItems nodes, respectively?  Or does it resolve down to the specific child nodes that satisfy the firebase user id equal to the current user?

My hope is for the latter to be the result, as the client does not need any records beyond those belonging to the current user.


来源: stackexchange

问:
Scala: change value in list inside a map
I'm facing a problem:
I want to change one element inside but the code is changing all elements.
I must be doing something wrong.
Here's what I have:

```<code>var critics: Map[String, List[(String, Double)]] = Map(
  "First" -> List(("a", 1.0), ("b", 2.0)),
  "Second" -> List(("c", 3.0), ("d", 4.0))
  )

  def setNewRating(keyMap: String, param1: String, newRating: Double) = {
    val newList = critics(keyMap).map{case (param1, _) => (param1, newRating); case x => x}
    critics = critics + (keyMap -> newList)
    }

    println(critics)

    setNewRating("First", "b", 5.0)

    println(critics)
</code>```

so, I'm looking for the key "First" and getting the List I want to change the "b" from 2.0 to 5.0 but the result I'm getting is:

```<code>critics: Map[String,List[(String, Double)]] = Map(First -> List((a,1.0), (b,2.0)), Second -> List((c,3.0), (d,4.0)))
setNewRating: (keyMap: String, param1: String, newRating: Double)Unit
Map(First -> List((a,1.0), (b,2.0)), Second -> List((c,3.0), (d,4.0)))
Map(First -> List((a,5.0), (b,5.0)), Second -> List((c,3.0), (d,4.0)))
</code>```

The code changed all the values!

thanks in advance,

答:
You need to put param1 in backticks:

```<code>  def setNewRating(keyMap: String, param1: String, newRating: Double) = {
    val newList = critics(keyMap)
     .map {
       case (`param1`, _) => param1 -> newRating
       case x => x
     }
     critics = critics + (keyMap -> newList)
  }
</code>```

The problem is that case (param1, _) means "match anything, and store the value into new local variable param1". That's not what you want.

```<code> case (`param1`, _) =>
</code>```

On the other hand, means "match the value that is the same as the outer variable param1".

Alternatively, if you renamed param1 to Param1, it would work too (apparently, scala matching assumes that everything starting with a capital letter is constant). I am not suggesting you do that, only mentioning it for completeness. Just use backticks.

(Also, using var like this makes me cringe, you really should find a way to avoid it, but that wasn't your question ...)

ContentLicense: CC BY-SA 3.0

Body:
I'm facing a problem:
I want to change one element inside but the code is changing all elements.
I must be doing something wrong.
Here's what I have:

var critics: Map[String, List[(String, Double)]] = Map(
  "First" -> List(("a", 1.0), ("b", 2.0)),
  "Second" -> List(("c", 3.0), ("d", 4.0))
  )

  def setNewRating(keyMap: String, param1: String, newRating: Double) = {
    val newList = critics(keyMap).map{case (param1, _) => (param1, newRating); case x => x}
    critics = critics + (keyMap -> newList)
    }

    println(critics)

    setNewRating("First", "b", 5.0)

    println(critics)

so, I'm looking for the key "First" and getting the List I want to change the "b" from 2.0 to 5.0 but the result I'm getting is:

critics: Map[String,List[(String, Double)]] = Map(First -> List((a,1.0), (b,2.0)), Second -> List((c,3.0), (d,4.0)))
setNewRating: (keyMap: String, param1: String, newRating: Double)Unit
Map(First -> List((a,1.0), (b,2.0)), Second -> List((c,3.0), (d,4.0)))
Map(First -> List((a,5.0), (b,5.0)), Second -> List((c,3.0), (d,4.0)))

The code changed all the values!

thanks in advance,

Body:
You need to put param1 in backticks:

  def setNewRating(keyMap: String, param1: String, newRating: Double) = {
    val newList = critics(keyMap)
     .map {
       case (`param1`, _) => param1 -> newRating
       case x => x
     }
     critics = critics + (keyMap -> newList)
  }

The problem is that case (param1, _) means "match anything, and store the value into new local variable param1". That's not what you want.

 case (`param1`, _) =>

On the other hand, means "match the value that is the same as the outer variable param1".

Alternatively, if you renamed param1 to Param1, it would work too (apparently, scala matching assumes that everything starting with a capital letter is constant). I am not suggesting you do that, only mentioning it for completeness. Just use backticks.

(Also, using var like this makes me cringe, you really should find a way to avoid it, but that wasn't your question ...)


问:
SVG / HTML 5 canvas - circles pattern displacement, stripe.com approach
While browsing stripe.com website [please see this page, example image bellow], one thing that caught my attention was their approach on svg pattern drawing using HTML 5 canvas.

I've noticed the circles pattern (orange color) are kind of displaced and doesn't seem to be tiled within its canvas as we usually see. There's a certain freedom in this pattern arrangement (not the css transform such as the skewed appearance, but the individual circles that compose the pattern itself), in a way the circles seem to be positioned randomly within the canvas but never reaches its limits.

By trying out texture.js, a similar pattern model can accomplished, but despite the nice effect, it results in the common "tiled" style.

I've made an example Pen. Could such effect be achieved with texture.js and additional css transformation or js function?

```<code><div class="pattern">
    <div id="myCanvas" class="pattern-circles"></div>
</div>

<script type="text/javascript">
var w = '100%',
  h = '100%';

// The svg element
var svg = d3.select("#myCanvas")
  .append("svg")
  .attr("width", w)
  .attr("height", h);

// the texture
var t = textures.circles()
    //.thinner()
    .radius(4)
    .stroke("Orange")
    .fill("transparent")
    .strokeWidth(2);

svg.call(t);

// Creat the shape to add fill
svg.append("rect")
  .attr({
    "x": 0,
    "y": 0,
    "width": "1200",
    "height": "1200",
    "rx": 0,
    "ry": 0
  })
  .style({
    "fill": t.url(),
  });
</script>
</code>```

答:
Not sure if this is what you are after, but creating a pattern like this isn't overly difficult.  Here's quick swing at it, you can adjust radius and space to adjust the "density" of the pattern:

<!DOCTYPE html>

```

Body:
Not sure if this is what you are after, but creating a pattern like this isn't overly difficult.  Here's quick swing at it, you can adjust radius and space to adjust the "density" of the pattern:

<!DOCTYPE html>
<html>

  <head>
    <script data-require="d3@4.0.0" data-semver="4.0.0" src="https://d3js.org/d3.v4.min.js"></script>
  </head>

  <body>
    <script>

      var w = 500,
          h = 500;

      var svg = d3.select('body')
        .append('svg')
        .attr('width', w)
        .attr('height', h);

      var p = svg.append('defs')
        .append('pattern')
        .attr('id', 'chaos')
        .attr('patternUnits', 'userSpaceOnUse')
        .attr('width', w)
        .attr('height', h);

      var space = 20,
          radius = 5,
          col = 1,
          row = 1;

      for (var i = 0; i < 1000; i++){

        var cx = (col * space) + (Math.random() * radius + space),
            cy = (row * space) + (Math.random() * radius + space);

        col += 1;

        if (cy > (h - space)) {
          break;
        }

        if (cx > (w - space)) {

          col = 1;
          row += 1

        } else {

          p.append('circle')
            .style('stroke', 'orange')
            .style('fill', 'none')
            .attr('r', radius)
            .attr('cx', cx)
            .attr('cy', cy);
        }
      }

      svg.append('rect')
        .attr('width', w)
        .attr('height', h)
        .style('fill', 'url(#chaos)')
        .style('stroke', 'steelblue');

    </script>
  </body>

</html>


问:
Cordova iOS - can't record a media even though the file is created
I am trying to record a sound file using cordova-plugin-media, but I am always getting this error:

{message: "Failed to initialize AVAudioRecorder: (null)↵", code: 1}

I am first creating the file, like this

```<code>iOSCreateFile(fileName, callback) {
    window.requestFileSystem(LocalFileSystem.TEMPORARY, 0, (fs) => {
        fs.root.getFile(fileName, {
            create: true,
            exclusive: false
        }, (fileEntry) => {
            console.log("fileEntry is file?" + fileEntry.isFile.toString());
            // here I am getting true, so the file is obviously created
            callback(fileEntry.nativeURL);
        }, (error) => {
            console.log('error create file: ' + error);
        });
    }, (error) => {
        console.log('error loading file system: ' + error);
    });
},
</code>```

The fileEntry.nativeURL I am sending back looks like this

```<code>file:///var/mobile/Containers/Data/Application/0EE019AA-EFBA-4FB9-97EC-1F16FFDDA36B/tmp/1496663387924.wav
</code>```

then, when this calls back, I am doing the following

```<code>// that long file path string is passed here
let soundRecord = new Media(filePath, () => {
    // success
    // more code
}, (error) => {
    console.log(error);
});
</code>```

And once it tries to execute the new statement, it gives me the Failed to initialize AVAudioRecorder error...

What am I doing wrong please?

EDIT: I also tried not creating a file, but only passing a file name string to the new Media object, like "1240215251.wav", and it's supposed to create it for me, but I am still getting the same error.

UPDATE: I have tried to catch the error in the native code, but I don't understand it very well, when I am debugging I can only see where the error is generated, but nothing else, please check the below code, I have commented where needed

```<code>- (void)startRecordingAudio:(CDVInvokedUrlCommand*)command {
    NSString* callbackId = command.callbackId;

#pragma unused(callbackId)

    NSString* mediaId = [command argumentAtIndex:0];
    CDVAudioFile* audioFile = [self audioFileForResource:[command argumentAtIndex:1] withId:mediaId doValidation:YES forRecording:YES];
    __block NSString* jsString = nil;
    __block NSString* errorMsg = @"";

    if ((audioFile != nil) && (audioFile.resourceURL != nil)) {
        __weak CDVSound* weakSelf = self;
        void (^startRecording)(void) = ^{
            NSError* __autoreleasing error = nil;
            if (audioFile.recorder != nil) {
                [audioFile.recorder stop];
                audioFile.recorder = nil;
            }
            if ([weakSelf hasAudioSession]) {
                if (![weakSelf.avSession.category isEqualToString:AVAudioSessionCategoryPlayAndRecord]) {
                    [weakSelf.avSession setCategory:AVAudioSessionCategoryRecord error:nil];
                }

                if (![weakSelf.avSession setActive:YES error:&error]) {
                    // other audio with higher priority that does not allow mixing could cause this to fail
                    errorMsg = [NSString stringWithFormat:@"Unable to record audio: %@", [error localizedFailureReason]];
                    // jsString = [NSString stringWithFormat: @"%@(\"%@\",%d,%d);", @"cordova.require('cordova-plugin-media.Media').onStatus", mediaId, MEDIA_ERROR, MEDIA_ERR_ABORTED];
                    jsString = [NSString stringWithFormat:@"%@(\"%@\",%d,%@);", @"cordova.require('cordova-plugin-media.Media').onStatus", mediaId, MEDIA_ERROR, [weakSelf createMediaErrorWithCode:MEDIA_ERR_ABORTED message:errorMsg]];
                    [weakSelf.commandDelegate evalJs:jsString];
                    return;
                }
            }
            NSDictionary *audioSettings = @{AVFormatIDKey: @(kAudioFormatMPEG4AAC),
                                             AVSampleRateKey: @(44100),
                                             AVNumberOfChannelsKey: @(1),
                                             AVEncoderAudioQualityKey: @(AVAudioQualityMedium)
                                             };
            audioFile.recorder = [[CDVAudioRecorder alloc] initWithURL:audioFile.resourceURL settings:audioSettings error:&error];
            // HERE ^
            // Just after this audioFile.recorder declaration, the error variable below gets a value -  NSError *   domain:
            // @"NSOSStatusErrorDomain" - code: 1718449215  0x0000000170247e90

            bool recordingSuccess = NO;
            if (error == nil) {
                audioFile.recorder.delegate = weakSelf;
                audioFile.recorder.mediaId = mediaId;
                audioFile.recorder.meteringEnabled = YES;
                recordingSuccess = [audioFile.recorder record];
                if (recordingSuccess) {
                    NSLog(@"Started recording audio sample '%@'", audioFile.resourcePath);
                    jsString = [NSString stringWithFormat:@"%@(\"%@\",%d,%d);", @"cordova.require('cordova-plugin-media.Media').onStatus", mediaId, MEDIA_STATE, MEDIA_RUNNING];
                    [weakSelf.commandDelegate evalJs:jsString];
                }
            }

            if ((error != nil) || (recordingSuccess == NO)) {
                // It then enters in one of below cases
                if (error != nil) {
                    errorMsg = [NSString stringWithFormat:@"Failed to initialize AVAudioRecorder: %@\n", [error localizedFailureReason]];
                } else {
                    errorMsg = @"Failed to start recording using AVAudioRecorder";
                }
                audioFile.recorder = nil;
                if (weakSelf.avSession) {
                    [weakSelf.avSession setActive:NO error:nil];
                }
                jsString = [NSString stringWithFormat:@"%@(\"%@\",%d,%@);", @"cordova.require('cordova-plugin-media.Media').onStatus", mediaId, MEDIA_ERROR, [weakSelf createMediaErrorWithCode:MEDIA_ERR_ABORTED message:errorMsg]];
                [weakSelf.commandDelegate evalJs:jsString];
            }
        };
        ...
        // More irrelevant code of the method
        ...
}
</code>```

答: I think the plugin is unable to create a AVAudioRecorder because you are passing a nativeURL, I don't know if this is supported. Did you try one of the quick-examples? Without manually creating the file beforehand via iOSCreateFile.</p>

Body:
I am trying to record a sound file using cordova-plugin-media, but I am always getting this error:

{message: "Failed to initialize AVAudioRecorder: (null)↵", code: 1}

I am first creating the file, like this

iOSCreateFile(fileName, callback) {
    window.requestFileSystem(LocalFileSystem.TEMPORARY, 0, (fs) => {
        fs.root.getFile(fileName, {
            create: true,
            exclusive: false
        }, (fileEntry) => {
            console.log("fileEntry is file?" + fileEntry.isFile.toString());
            // here I am getting true, so the file is obviously created
            callback(fileEntry.nativeURL);
        }, (error) => {
            console.log('error create file: ' + error);
        });
    }, (error) => {
        console.log('error loading file system: ' + error);
    });
},

The fileEntry.nativeURL I am sending back looks like this

file:///var/mobile/Containers/Data/Application/0EE019AA-EFBA-4FB9-97EC-1F16FFDDA36B/tmp/1496663387924.wav

then, when this calls back, I am doing the following

// that long file path string is passed here
let soundRecord = new Media(filePath, () => {
    // success
    // more code
}, (error) => {
    console.log(error);
});

And once it tries to execute the new statement, it gives me the Failed to initialize AVAudioRecorder error...

What am I doing wrong please?

EDIT: I also tried not creating a file, but only passing a file name string to the new Media object, like "1240215251.wav", and it's supposed to create it for me, but I am still getting the same error.

UPDATE: I have tried to catch the error in the native code, but I don't understand it very well, when I am debugging I can only see where the error is generated, but nothing else, please check the below code, I have commented where needed

- (void)startRecordingAudio:(CDVInvokedUrlCommand*)command {
    NSString* callbackId = command.callbackId;

#pragma unused(callbackId)

    NSString* mediaId = [command argumentAtIndex:0];
    CDVAudioFile* audioFile = [self audioFileForResource:[command argumentAtIndex:1] withId:mediaId doValidation:YES forRecording:YES];
    __block NSString* jsString = nil;
    __block NSString* errorMsg = @"";

    if ((audioFile != nil) && (audioFile.resourceURL != nil)) {
        __weak CDVSound* weakSelf = self;
        void (^startRecording)(void) = ^{
            NSError* __autoreleasing error = nil;
            if (audioFile.recorder != nil) {
                [audioFile.recorder stop];
                audioFile.recorder = nil;
            }
            if ([weakSelf hasAudioSession]) {
                if (![weakSelf.avSession.category isEqualToString:AVAudioSessionCategoryPlayAndRecord]) {
                    [weakSelf.avSession setCategory:AVAudioSessionCategoryRecord error:nil];
                }

                if (![weakSelf.avSession setActive:YES error:&error]) {
                    // other audio with higher priority that does not allow mixing could cause this to fail
                    errorMsg = [NSString stringWithFormat:@"Unable to record audio: %@", [error localizedFailureReason]];
                    // jsString = [NSString stringWithFormat: @"%@(\"%@\",%d,%d);", @"cordova.require('cordova-plugin-media.Media').onStatus", mediaId, MEDIA_ERROR, MEDIA_ERR_ABORTED];
                    jsString = [NSString stringWithFormat:@"%@(\"%@\",%d,%@);", @"cordova.require('cordova-plugin-media.Media').onStatus", mediaId, MEDIA_ERROR, [weakSelf createMediaErrorWithCode:MEDIA_ERR_ABORTED message:errorMsg]];
                    [weakSelf.commandDelegate evalJs:jsString];
                    return;
                }
            }
            NSDictionary *audioSettings = @{AVFormatIDKey: @(kAudioFormatMPEG4AAC),
                                             AVSampleRateKey: @(44100),
                                             AVNumberOfChannelsKey: @(1),
                                             AVEncoderAudioQualityKey: @(AVAudioQualityMedium)
                                             };
            audioFile.recorder = [[CDVAudioRecorder alloc] initWithURL:audioFile.resourceURL settings:audioSettings error:&error];
            // HERE ^
            // Just after this audioFile.recorder declaration, the error variable below gets a value -  NSError *   domain:
            // @"NSOSStatusErrorDomain" - code: 1718449215  0x0000000170247e90

            bool recordingSuccess = NO;
            if (error == nil) {
                audioFile.recorder.delegate = weakSelf;
                audioFile.recorder.mediaId = mediaId;
                audioFile.recorder.meteringEnabled = YES;
                recordingSuccess = [audioFile.recorder record];
                if (recordingSuccess) {
                    NSLog(@"Started recording audio sample '%@'", audioFile.resourcePath);
                    jsString = [NSString stringWithFormat:@"%@(\"%@\",%d,%d);", @"cordova.require('cordova-plugin-media.Media').onStatus", mediaId, MEDIA_STATE, MEDIA_RUNNING];
                    [weakSelf.commandDelegate evalJs:jsString];
                }
            }

            if ((error != nil) || (recordingSuccess == NO)) {
                // It then enters in one of below cases
                if (error != nil) {
                    errorMsg = [NSString stringWithFormat:@"Failed to initialize AVAudioRecorder: %@\n", [error localizedFailureReason]];
                } else {
                    errorMsg = @"Failed to start recording using AVAudioRecorder";
                }
                audioFile.recorder = nil;
                if (weakSelf.avSession) {
                    [weakSelf.avSession setActive:NO error:nil];
                }
                jsString = [NSString stringWithFormat:@"%@(\"%@\",%d,%@);", @"cordova.require('cordova-plugin-media.Media').onStatus", mediaId, MEDIA_ERROR, [weakSelf createMediaErrorWithCode:MEDIA_ERR_ABORTED message:errorMsg]];
                [weakSelf.commandDelegate evalJs:jsString];
            }
        };
        ...
        // More irrelevant code of the method
        ...
}


问:
How to use QTextStream with PythonQT?
I am writing a plugin for a Qt desktop app using PythonQT.
I wonder how to use << operator in python.

```<code>QTextStream stream(&file);
stream << doc.toString();
</code>```

Any hints?
How may I ask Python to list all methods for a given class like QTextStream?
Or is there another way in Python to write a QDomDocument to a QFile?

答:
Found a solution already...</p>

```<code>doc = QDomDocument()
root = doc.createElement("Animation")
doc.appendChild(root)
stream = QTextStream(xmlfile)
doc.save(stream, 0)
</code>```

Title: How to use QTextStream with PythonQT?

Body:
I am writing a plugin for a Qt desktop app using PythonQT.
I wonder how to use << operator in python.

QTextStream stream(&file);
stream << doc.toString();

Any hints?
How may I ask Python to list all methods for a given class like QTextStream?
Or is there another way in Python to write a QDomDocument to a QFile?

Body:
Found a solution already...

doc = QDomDocument()
root = doc.createElement("Animation")
doc.appendChild(root)
stream = QTextStream(xmlfile)
doc.save(stream, 0)


问:
Scatter plotting pandas DataFrame with categorically labeled rows/columns
I would like to produce a scatter plot of pandas DataFrame with categorical row and column labels using matplotlib. A sample DataFrame looks like this:

```<code>import pandas as pd
df = pd.DataFrame({"a": [1,2], "b": [3,4]}, index=["c","d"])
#   a  b
#c  1  2
#d  3  4
</code>```

The marker size is the function of the respective DataFrame values. So far, I came up with an awkward solution that essentially enumerates the rows and columns, plots the data, and then reconstructs the labels:

```<code>flat = df.reset_index(drop=True).T.reset_index(drop=True).T.stack().reset_index()
#   level_0  level_1  0
#0        0        0  1
#1        0        1  2
#2        1        0  3
#3        1        1  4

flat.plot(kind='scatter', x='level_0', y='level_1', s=100*flat[0])
plt.xticks(range(df.shape[1]), df.columns)
plt.yticks(range(df.shape[0]), df.index)
plt.show()
</code>```

Which kind of works.

Now, question: Is there a more intuitive, more integrated way to produce this scatter plot, ideally without splitting the data and the metadata?

答:
Maybe you can use numpy array and pd.melt to create the scatter plot as shown below:

```<code>arr = np.array([[i,j] for i in range(df.shape[1]) for j in range(df.shape[0])])
plt.scatter(arr[:,0],arr[:,1],s=100*pd.melt(df)['value'],marker='o')
plt.xlabel('level_0')
plt.ylabel('level_1')
plt.xticks(range(df.shape[1]), df.columns)
plt.yticks(range(df.shape[0]), df.index)
plt.show()
</code>```

Body:
I would like to produce a scatter plot of pandas DataFrame with categorical row and column labels using matplotlib. A sample DataFrame looks like this:

import pandas as pd
df = pd.DataFrame({"a": [1,2], "b": [3,4]}, index=["c","d"])
#   a  b
#c  1  2
#d  3  4

The marker size is the function of the respective DataFrame values. So far, I came up with an awkward solution that essentially enumerates the rows and columns, plots the data, and then reconstructs the labels:

flat = df.reset_index(drop=True).T.reset_index(drop=True).T.stack().reset_index()
#   level_0  level_1  0
#0        0        0  1
#1        0        1  2
#2        1        0  3
#3        1        1  4

flat.plot(kind='scatter', x='level_0', y='level_1', s=100*flat[0])
plt.xticks(range(df.shape[1]), df.columns)
plt.yticks(range(df.shape[0]), df.index)
plt.show()

Which kind of works.

Now, question: Is there a more intuitive, more integrated way to produce this scatter plot, ideally without splitting the data and the metadata?

Body:
Maybe you can use numpy array and pd.melt to create the scatter plot as shown below:

arr = np.array([[i,j] for i in range(df.shape[1]) for j in range(df.shape[0])])
plt.scatter(arr[:,0],arr[:,1],s=100*pd.melt(df)['value'],marker='o')
plt.xlabel('level_0')
plt.ylabel('level_1')
plt.xticks(range(df.shape[1]), df.columns)
plt.yticks(range(df.shape[0]), df.index)
plt.show()


问:
Angular 2 and calendar script
I am writing small website using Angular 2 and I would like to implement simple calendar inside one component. Nothing big with schedules, just small calendar window with higlighted current day.
I have found some nice js script for that but later I have discovered that I cannot use  inside component in Angular2.
Is there any other way I can do this or maybe some other library?</p>

答:
I'm not entirely sure if this is what you are looking for, but Angular Material includes a good Angular 2 ready calendar/datepicker.

```<code><md-input-container>
  <input mdInput [mdDatepicker]="picker" placeholder="Choose a date">
  <button mdSuffix [mdDatepickerToggle]="picker"></button>
</md-input-container>
<md-datepicker #picker></md-datepicker>
</code>```

Full Code: https://plnkr.co/edit/4SIRfrDOubZxuTcvxiCP

Docs: https://material.angular.io/components/component/datepicker

Title: Angular 2 and calendar script

Body:
I'm not entirely sure if this is what you are looking for, but Angular Material includes a good Angular 2 ready calendar/datepicker.

<md-input-container>
  <input mdInput [mdDatepicker]="picker" placeholder="Choose a date">
  <button mdSuffix [mdDatepickerToggle]="picker"></button>
</md-input-container>
<md-datepicker #picker></md-datepicker>

Full Code: https://plnkr.co/edit/4SIRfrDOubZxuTcvxiCP

Docs: https://material.angular.io/components/component/datepicker


问:
Create file path variable without opening file
I'm trying to implement some simple error logging in a PowerShell script that installs stuff.

The structure is as follows:

```<code>New-Item C:\Test\LogFile.txt -ItemType file
$Path = C:\Test\LogFile.txt

try
{
    #Install stuff
}
catch
{
    Add-Content $Path "error description"
}

try
{
    #Install more stuff
}
catch
{
    Add-Content $Path "error description"
}
</code>```

The problem is with the $Path = C:\Test\LogFile.txt line. It's causing the file to open up. Can I create the path variable without opening the file? I really want to use a variable here in case I decide to change the error log file location.

答:
It's auto-opening the file because you're calling the path like you would from the shell.  If you want to see it in action, open powershell and just type the path to your error file and hit enter, it'll probably open in notepad.

To avoid this, you need to wrap the $path variable in quotes:  $path = 'c:\blah.txt'

Body:
I'm trying to implement some simple error logging in a PowerShell script that installs stuff.

The structure is as follows:

New-Item C:\Test\LogFile.txt -ItemType file
$Path = C:\Test\LogFile.txt

try
{
    #Install stuff
}
catch
{
    Add-Content $Path "error description"
}

try
{
    #Install more stuff
}
catch
{
    Add-Content $Path "error description"
}

The problem is with the $Path = C:\Test\LogFile.txt line. It's causing the file to open up. Can I create the path variable without opening the file? I really want to use a variable here in case I decide to change the error log file location.


问:
xml parsing with no browser use
I have read the example for Rss Parsing from the ibm site.(http://www.ibm.com/developerworks/opensource/library/x-android/).

In this example,the rss are shown in a listview and then,if you press one announcement you can see it in the web browser of the device.How could i see them in the app,with no use of the device browser?

Thanks a lot

答: Create a layout with a WebView then load the URL from each "announcement" using WebView.loadUrl.

ContentLicense: CC BY-SA 2.5

Title: xml parsing with no browser use


问:
Symfony cannot connect to mysql DB on docker ECS container
I'm using amazon-ecs to launch docker containers that I have. Everything works fine locally, but when I'm running the containers on ECS I'm getting the following error:

"NOTICE: PHP message: Unable to open PDO connection [wrapped: SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known]"

I'm linking the containers in the docker-compose file, and I'm able to ping the the mysql container from the nginx container, so I know their linked.

docker-compose

```<code>version: '2'

services:
  nginx:
    image: "xxxx.dkr.ecr.us-east-2.amazonaws.com/nginx:latest"
    ports:
      - "8086:80"
    links:
      - fpm
      - mysql

  fpm:
    image: "xxxx.dkr.ecr.us-east-2.amazonaws.com/php-fpm:latest"
    links:
      - redis

  mysql:
    image: "xxxx.dkr.ecr.us-east-2.amazonaws.com/mysql:latest"
    environment:
      MYSQL_DATABASE: strix
      MYSQL_USER: strix
      MYSQL_PASSWORD: rRCd29b3fG76ypM3
      MYSQL_ROOT_PASSWORD: root
  redis:
    image: redis:latest
</code>```

My symfony database.yml has the following:

```<code>dev:
  propel:
    param:
      classname: DebugPDO
      debug: { realmemoryusage: true, details: { time: { enabled: true }, slow: { enabled: true, threshold: 0.1 }, mem: { enabled: true }, mempeak: { enabled: true }, memdelta: { enabled: true } } }

task:
  propel:
    param:
      profiler: false

test:
  propel:
    param:
      classname: DebugPDO
all:
  propel:
    class: sfPropelDatabase
    param:
      classname: PropelPDO
      dsn: 'mysql:host=mysql;dbname=strix'
      username: strix
      password: xxxx
      encoding: utf8
      persistent: true
      pooling: true
</code>```

I'm not sure if there's some network config that I have wrong on ECS or if I'm pointing to the wrong hostname. Any help would be appreciated. I am not familiar with symfony and am trying to raise an old application from the dead.

答:
Turns out when I was running docker on my local machine, all the containers could talk to each other even though I hadn't explicitly linked them. In this case the fpm container needed to connect to the mysql container (and was doing so locally) but I didn't know this. When it was up on ECS, because it was not explicitly linked, it was throwing the connection error.

I simply fixed it by adding mysql to the fpm links

```<code>fpm:
  image: "xxxx.dkr.ecr.us-east-2.amazonaws.com/php-fpm:latest"
  links:
    - redis
    - mysql
</code>```

Body:
I'm using amazon-ecs to launch docker containers that I have. Everything works fine locally, but when I'm running the containers on ECS I'm getting the following error:

"NOTICE: PHP message: Unable to open PDO connection [wrapped: SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known]"

I'm linking the containers in the docker-compose file, and I'm able to ping the the mysql container from the nginx container, so I know their linked.

docker-compose

version: '2'

services:
  nginx:
    image: "xxxx.dkr.ecr.us-east-2.amazonaws.com/nginx:latest"
    ports:
      - "8086:80"
    links:
      - fpm
      - mysql

  fpm:
    image: "xxxx.dkr.ecr.us-east-2.amazonaws.com/php-fpm:latest"
    links:
      - redis

  mysql:
    image: "xxxx.dkr.ecr.us-east-2.amazonaws.com/mysql:latest"
    environment:
      MYSQL_DATABASE: strix
      MYSQL_USER: strix
      MYSQL_PASSWORD: rRCd29b3fG76ypM3
      MYSQL_ROOT_PASSWORD: root
  redis:
    image: redis:latest

My symfony database.yml has the following:

dev:
  propel:
    param:
      classname: DebugPDO
      debug: { realmemoryusage: true, details: { time: { enabled: true }, slow: { enabled: true, threshold: 0.1 }, mem: { enabled: true }, mempeak: { enabled: true }, memdelta: { enabled: true } } }

task:
  propel:
    param:
      profiler: false

test:
  propel:
    param:
      classname: DebugPDO
all:
  propel:
    class: sfPropelDatabase
    param:
      classname: PropelPDO
      dsn: 'mysql:host=mysql;dbname=strix'
      username: strix
      password: xxxx
      encoding: utf8
      persistent: true
      pooling: true

I'm not sure if there's some network config that I have wrong on ECS or if I'm pointing to the wrong hostname. Any help would be appreciated. I am not familiar with symfony and am trying to raise an old application from the dead.

Body:
Turns out when I was running docker on my local machine, all the containers could talk to each other even though I hadn't explicitly linked them. In this case the fpm container needed to connect to the mysql container (and was doing so locally) but I didn't know this. When it was up on ECS, because it was not explicitly linked, it was throwing the connection error.

I simply fixed it by adding mysql to the fpm links

fpm:
  image: "xxxx.dkr.ecr.us-east-2.amazonaws.com/php-fpm:latest"
  links:
    - redis
    - mysql


问:
How to parse JSON having different keys in each array element using POJO classes in android
I have this response coming from server. I want to parse that using pojo classes. I have created pojo classes having setter and getter methods which holds values.But the logic which I am using is not working properly.While I'm printing values it was not returning values exactly.

Response:

```<code>{
        "code":200,
        "status":"ok",
        "message":"Promotions feed.",
        "data":{
        "feed":[
        {
        "id":0,
        "businessId":0,
      "photoUrl":"https:\/\/d1e6yi6s3cx2ur.cloudfront.net\/videos\/0\/8b84c9c1-50ed-4e93-9785-797bbf2be667.png",
        "videoUrl":"https:\/\/d1e6yi6s3cx2ur.cloudfront.net\/videos\/0\/_464b2fb6-ede6-403f-b6ae-1666c9504337.mov",
        "isNew":true,
        "type":"news"
        },
        {
        "id":198,
        "specialType":"limited",
        "name":"Big Data Shoes!",
        "description":"Get them now while you can. They're dangerous!",
        "start":"2017-06-04 14:59:01Z",
        "end":"2018-01-26 19:00:00Z",
        "limitedAmount":30,
        "countInfo":{
        "views":70,
        "likes":0,
        "liked":false,
        "type":"count_info"
        },
        "type":"special"
        },
        {
        "id":"1616636",
        "partnerId":3,
        "uuid":"57dacc36-abac-4bb3-89a4-f1981130b206",
        "type":"partner_offer"
        }
     ]
   }
}
</code>```

FeedPojo.java

```<code>public class FeedPojo {

    private static String id;
    private static String businessId;
    private static String photoUrl;
    private static String videoUrl;
    public static String getId() {
        return id;
    }
    public static void setId(String id) {
        FeedPojo.id = id;
    }

    public static String getPartnerId() {
        return partnerId;
    }

    public static void setPartnerId(String partnerId) {
        FeedPojo.partnerId = partnerId;
    }
   }
</code>```

MainActivity.java

```<code>FeedPojo.setType(promoJsonObject.getString("type"));

Log.d(TAG, "TypeFeed:" + FeedPojo.getType());
Log.e(TAG, "Type:" + promoJsonObject.getString("type"));
             if (promoJsonObject.getString("type") == "news") {

                                        FeedPojo.setId(promoJsonObject.getString("id"));
                                        FeedPojo.setBusinessName(promoJsonObject.getString("businessName"));
                                        FeedPojo.setBusinessLogoUrl(promoJsonObject.getString("businessLogoUrl"));
                                        FeedPojo.setText(promoJsonObject.getString("text"));

 Log.d(TAG,"Id"+FeedPojo.getId());
                                        Log.d(TAG,"Businessname"+FeedPojo.getBusinessName());

                                    }
                                    if (FeedPojo.getType() == "special") {

                                        FeedPojo.setId(promoJsonObject.getString("id"));
                                        FeedPojo.setType(promoJsonObject.getString("type"));
                                        FeedPojo.setName(promoJsonObject.getString("name"));
                                        FeedPojo.setDescription(promoJsonObject.getString("description"));
                                        FeedPojo.setStart(promoJsonObject.getString("start"));
                                        FeedPojo.setEnd(promoJsonObject.getString("end"));
                }
</code>```

答:
Try with Gson.

Gradle import:

```<code>compile 'com.google.code.gson:gson:2.2.4'
</code>```

Code to parse our pojo with gson:

```<code>JSONObject object = new JSONObject(response);
Gson gson = new Gson();
FeedPojo feedPojo = gson.fromJson(object.toString(), FeedPojo.class);
</code>```

Your FeedPojo must implement Serializable:

```<code>public class FeedPojo implements Serializable {
    ...
}
</code>```

Body:
I have this response coming from server. I want to parse that using pojo classes. I have created pojo classes having setter and getter methods which holds values.But the logic which I am using is not working properly.While I'm printing values it was not returning values exactly.

Response:

{
        "code":200,
        "status":"ok",
        "message":"Promotions feed.",
        "data":{
        "feed":[
        {
        "id":0,
        "businessId":0,
      "photoUrl":"https:\/\/d1e6yi6s3cx2ur.cloudfront.net\/videos\/0\/8b84c9c1-50ed-4e93-9785-797bbf2be667.png",
        "videoUrl":"https:\/\/d1e6yi6s3cx2ur.cloudfront.net\/videos\/0\/_464b2fb6-ede6-403f-b6ae-1666c9504337.mov",
        "isNew":true,
        "type":"news"
        },
        {
        "id":198,
        "specialType":"limited",
        "name":"Big Data Shoes!",
        "description":"Get them now while you can. They're dangerous!",
        "start":"2017-06-04 14:59:01Z",
        "end":"2018-01-26 19:00:00Z",
        "limitedAmount":30,
        "countInfo":{
        "views":70,
        "likes":0,
        "liked":false,
        "type":"count_info"
        },
        "type":"special"
        },
        {
        "id":"1616636",
        "partnerId":3,
        "uuid":"57dacc36-abac-4bb3-89a4-f1981130b206",
        "type":"partner_offer"
        }
     ]
   }
}

FeedPojo.java

public class FeedPojo {

    private static String id;
    private static String businessId;
    private static String photoUrl;
    private static String videoUrl;
    public static String getId() {
        return id;
    }
    public static void setId(String id) {
        FeedPojo.id = id;
    }

    public static String getPartnerId() {
        return partnerId;
    }

    public static void setPartnerId(String partnerId) {
        FeedPojo.partnerId = partnerId;
    }
   }

MainActivity.java

FeedPojo.setType(promoJsonObject.getString("type"));

Log.d(TAG, "TypeFeed:" + FeedPojo.getType());
Log.e(TAG, "Type:" + promoJsonObject.getString("type"));
             if (promoJsonObject.getString("type") == "news") {

                                        FeedPojo.setId(promoJsonObject.getString("id"));
                                        FeedPojo.setBusinessName(promoJsonObject.getString("businessName"));
                                        FeedPojo.setBusinessLogoUrl(promoJsonObject.getString("businessLogoUrl"));
                                        FeedPojo.setText(promoJsonObject.getString("text"));

 Log.d(TAG,"Id"+FeedPojo.getId());
                                        Log.d(TAG,"Businessname"+FeedPojo.getBusinessName());

                                    }
                                    if (FeedPojo.getType() == "special") {

                                        FeedPojo.setId(promoJsonObject.getString("id"));
                                        FeedPojo.setType(promoJsonObject.getString("type"));
                                        FeedPojo.setName(promoJsonObject.getString("name"));
                                        FeedPojo.setDescription(promoJsonObject.getString("description"));
                                        FeedPojo.setStart(promoJsonObject.getString("start"));
                                        FeedPojo.setEnd(promoJsonObject.getString("end"));
                }

Body:
Try with Gson.

Gradle import:

compile 'com.google.code.gson:gson:2.2.4'

Code to parse our pojo with gson:

JSONObject object = new JSONObject(response);
Gson gson = new Gson();
FeedPojo feedPojo = gson.fromJson(object.toString(), FeedPojo.class);

Your FeedPojo must implement Serializable:

public class FeedPojo implements Serializable {
    ...
}


问:
Using lengthOf.at.least in Chaijs Assertions
I'm using Chai.js. I have the following assertion

```<code>it('Expects subjects in the response body', () => {
  expect(response.body).to.be.an('object').that.includes.key("subjects");
 expect(response.body.subjects).to.be.an('array').that.has.lengthOf.at.least(1);
});
</code>```

This doesn't pass I get an error message saying Cannot read property 'least' of undefined

But the following works fine.

```<code>it('Expects subjects in the response body', () => {
    expect(response.body).to.be.an('object').that.includes.key("subjects");
    expect(response.body.subjects).to.be.an('array').that.has.lengthOf(10);
});
</code>```

So how am I using .at.least() incorrectly?

答:
It seems that you're using an old (3.x) version of Chai. Upgrade to the newest version (4.0.2) to solve this problem.</p>

```<code>npm i -D chai@latest
</code>```

Body:
I'm using Chai.js. I have the following assertion

it('Expects subjects in the response body', () => {
  expect(response.body).to.be.an('object').that.includes.key("subjects");
 expect(response.body.subjects).to.be.an('array').that.has.lengthOf.at.least(1);
});

This doesn't pass I get an error message saying Cannot read property 'least' of undefined

But the following works fine.

it('Expects subjects in the response body', () => {
    expect(response.body).to.be.an('object').that.includes.key("subjects");
    expect(response.body.subjects).to.be.an('array').that.has.lengthOf(10);
});

So how am I using .at.least() incorrectly?

Body:
It seems that you're using an old (3.x) version of Chai. Upgrade to the newest version (4.0.2) to solve this problem.

npm i -D chai@latest


问:
locking only when modifying vs entire method
When should locks be used? Only when modifying data or when accessing it as well?

```<code>public class Test {
    static Dictionary<string, object> someList = new Dictionary<string, object>();

    static object syncLock = new object();

    public static object GetValue(string name) {
        if (someList.ContainsKey(name)) {
            return someList[name];
        } else {
            lock(syncLock) {
                object someValue = GetValueFromSomeWhere(name);
                someList.Add(name, someValue);
            }
        }
    }
}
</code>```

Should there be a lock around the the entire block or is it ok to just add it to the actual modification? My understanding is that there still could be some race condition where one call might not have found it and started to add it while another call right after might have also run into the same situation - but I'm not sure. Locking is still so confusing. I haven't run into any issues with the above similar code but I could just be lucky so far. Any help above would be appriciated as well as any good resources for how/when to lock objects.

答:
ReaderWriterLock or the slim version if you under 4.0.

You will aquire the reader lock for the reads (will allow for concurrent reads) and upgrade the lock to the writer lock when something is to write (will allow only one write at the time and will block all the reads until is done, as well as the concurrent write-threads).

Make sure to release your locks with the pattern to avoid deadlocking:

```<code>            void Write(object[] args)
            {

                   this.ReaderWriterLock.AquireWriteLock(TimeOut.Infinite);

                    try
                    {
                      this.myData.Write(args);

                    }
                    catch(Exception ex)
                    {

                    }
                    finally
                    {

                        this.ReaderWriterLock.RelaseWriterLock();
                    }

            }
</code>```

Body:
When should locks be used? Only when modifying data or when accessing it as well?

public class Test {
    static Dictionary<string, object> someList = new Dictionary<string, object>();

    static object syncLock = new object();

    public static object GetValue(string name) {
        if (someList.ContainsKey(name)) {
            return someList[name];
        } else {
            lock(syncLock) {
                object someValue = GetValueFromSomeWhere(name);
                someList.Add(name, someValue);
            }
        }
    }
}

Should there be a lock around the the entire block or is it ok to just add it to the actual modification? My understanding is that there still could be some race condition where one call might not have found it and started to add it while another call right after might have also run into the same situation - but I'm not sure. Locking is still so confusing. I haven't run into any issues with the above similar code but I could just be lucky so far. Any help above would be appriciated as well as any good resources for how/when to lock objects.

Body:
ReaderWriterLock or the slim version if you under 4.0.

You will aquire the reader lock for the reads (will allow for concurrent reads) and upgrade the lock to the writer lock when something is to write (will allow only one write at the time and will block all the reads until is done, as well as the concurrent write-threads).

Make sure to release your locks with the pattern to avoid deadlocking:

            void Write(object[] args)
            {

                   this.ReaderWriterLock.AquireWriteLock(TimeOut.Infinite);

                    try
                    {
                      this.myData.Write(args);

                    }
                    catch(Exception ex)
                    {

                    }
                    finally
                    {

                        this.ReaderWriterLock.RelaseWriterLock();
                    }

            }


问:
How I find numbers with repeating digits within a range
I'm trying to find all numbers within the range 000000000..999999999 that have at least 3 or more similar digits grouped together.

Here are examples of integers that pass: 112333678, 111234567, 122111876

Here are examples of integers that fail: 123456789, 122334455, 123123123

I ran this line in Ruby, and then my Macbook Pro with 16 GB of RAM ran out of memory: (000000000..999999999).to_a.select{|e| e.to_s =~ /(\d)\1+/}

答:
Why not extract each digit in an array and check if any digit has 3 consecutive occurrences?

```<code>int number = 666455477;

int counter = 0;
//l = number of digits
int l = (int)(Math.Log10(number) + 1);
int[] array = new int[l];

//Numbers get inserted in reverse order, but doesnt matter
while (number > 0)
{
    array[counter] = number % 10;

    if(counter > 1)
    {
        if (array[counter] == array[counter - 1] && array[counter] == array[counter - 2])
            Console.WriteLine("Number contains 3 consecutive: {0}'s", array[counter]);
    }
    number /= 10;
    counter++;
}
</code>```

This way you can also store large numbers as string, read in each character and parse it as int into the array. If you don't want to use an array, you can simply have 3 variables storing the current and previous 2 values as well.

Not sure in which language you would like to solve, but most languages would support loops and arrays I presume.

Body:
Why not extract each digit in an array and check if any digit has 3 consecutive occurrences?

int number = 666455477;

int counter = 0;
//l = number of digits
int l = (int)(Math.Log10(number) + 1);
int[] array = new int[l];

//Numbers get inserted in reverse order, but doesnt matter
while (number > 0)
{
    array[counter] = number % 10;

    if(counter > 1)
    {
        if (array[counter] == array[counter - 1] && array[counter] == array[counter - 2])
            Console.WriteLine("Number contains 3 consecutive: {0}'s", array[counter]);
    }
    number /= 10;
    counter++;
}

This way you can also store large numbers as string, read in each character and parse it as int into the array. If you don't want to use an array, you can simply have 3 variables storing the current and previous 2 values as well.

Not sure in which language you would like to solve, but most languages would support loops and arrays I presume.


问:
Getting duplicates on JOINs in SQL Server 2014
My Tables:

Account A

Plate P

FinTransMaster F

TollTrans T

Relationships:

```<code>A.AccountId = P.AccountId
A.AccountId = F.AccountId
A.AccountId = P.AccountId = F.AccountId
P.LicPlateNo = T.LicPlateNo

T.AccountId != A.AccountId
T.AccountId != P.AccountId
T.AccountId != F.AccountId
</code>```

I need all records where:

```<code>     T.AccountId = '123456'
 AND EXISTS F.TransCode = 'TOLL'
 AND NOT EXISTS F.TransCode = 'PYMT'
 AND A.CurrentBalance > 0
</code>```

My code so far:

```<code>SELECT A.*

FROM Account A
INNER JOIN Plate P ON P.AccountId = A.AccountId
INNER JOIN TollTrans T ON T.LicPlateNo = P.LicPlateNo

WHERE EXISTS     (SELECT 1
                  FROM FinTransMaster F
                  WHERE F.AcctID = A.AccountID AND F.TransCode = 'TOLL'
                  )
  AND NOT EXISTS (SELECT 1
                  FROM FinTransMaster F
                  WHERE F.AcctID = A.AccountID AND F.TransCode = 'PYMT'
                  )
  AND T.AccountId = '123456'
  AND A.CurrentBalance > 0

ORDER BY BalanceDT DESC
</code>```

Each Account has a Licence Plate. Some Accounts have multiple Licence Plates. Maybe, that's the reason I'm getting duplicates.

How can I refine this code?

答:
If you're only interested in the Account table, just move the other tables to EXISTS subqueries:

```<code>SELECT *
FROM Account A
WHERE EXISTS     (SELECT 1
                  FROM FinTransMaster F
                  WHERE F.AcctID = A.AccountID AND F.TransCode = 'TOLL'
                  )
  AND NOT EXISTS (SELECT 1
                  FROM FinTransMaster F
                  WHERE F.AcctID = A.AccountID AND F.TransCode = 'PYMT'
                  )
  AND EXISTS      (SELECT 1
                  FROM Plate P
                  INNER JOIN TollTrans T ON T.LicPlateNo = P.LicPlateNo
                  WHERE P.AccountId = A.AccountId
                    AND T.AccountId = '123456'
                  )
  AND A.CurrentBalance > 0
ORDER BY BalanceDT DESC
</code>```

If BalanceDT isn't in the Account table, then you can't do that, but, well, you didn't qualify that column.

Body:
My Tables:

Account A

Plate P

FinTransMaster F

TollTrans T

Relationships:

A.AccountId = P.AccountId
A.AccountId = F.AccountId
A.AccountId = P.AccountId = F.AccountId
P.LicPlateNo = T.LicPlateNo

T.AccountId != A.AccountId
T.AccountId != P.AccountId
T.AccountId != F.AccountId

I need all records where:

     T.AccountId = '123456'
 AND EXISTS F.TransCode = 'TOLL'
 AND NOT EXISTS F.TransCode = 'PYMT'
 AND A.CurrentBalance > 0

My code so far:

SELECT A.*

FROM Account A
INNER JOIN Plate P ON P.AccountId = A.AccountId
INNER JOIN TollTrans T ON T.LicPlateNo = P.LicPlateNo

WHERE EXISTS     (SELECT 1
                  FROM FinTransMaster F
                  WHERE F.AcctID = A.AccountID AND F.TransCode = 'TOLL'
                  )
  AND NOT EXISTS (SELECT 1
                  FROM FinTransMaster F
                  WHERE F.AcctID = A.AccountID AND F.TransCode = 'PYMT'
                  )
  AND T.AccountId = '123456'
  AND A.CurrentBalance > 0

ORDER BY BalanceDT DESC

Each Account has a Licence Plate. Some Accounts have multiple Licence Plates. Maybe, that's the reason I'm getting duplicates.

How can I refine this code?

Body:
If you're only interested in the Account table, just move the other tables to EXISTS subqueries:

SELECT *
FROM Account A
WHERE EXISTS     (SELECT 1
                  FROM FinTransMaster F
                  WHERE F.AcctID = A.AccountID AND F.TransCode = 'TOLL'
                  )
  AND NOT EXISTS (SELECT 1
                  FROM FinTransMaster F
                  WHERE F.AcctID = A.AccountID AND F.TransCode = 'PYMT'
                  )
  AND EXISTS      (SELECT 1
                  FROM Plate P
                  INNER JOIN TollTrans T ON T.LicPlateNo = P.LicPlateNo
                  WHERE P.AccountId = A.AccountId
                    AND T.AccountId = '123456'
                  )
  AND A.CurrentBalance > 0
ORDER BY BalanceDT DESC

If BalanceDT isn't in the Account table, then you can't do that, but, well, you didn't qualify that column.


问:
MVC Razor view Intellisense broken in VS 2013/2015/2017
I have an existing project written in VS2010 which when loaded in VS2010 works perfectly.

When I load this same project in VS2013 the MVC Razor views contain lots of errors as if the config file is missing from the views folder.

It appears to have not loaded the Razor editor correctly using the config files from both the root and the views folder and instead gives me errors like ...

```<code>The name 'model' does not exist in the current context
</code>```

and ...

```<code>'System.Web.WebPages.Html.HtmlHelper' does not contain a definition for 'LabelFor'
and no extension method 'LabelFor' accepting a first argument of type
'System.Web.WebPages.Html.HtmlHelper' could be found
(are you missing a using directive or an assembly reference?)
</code>```

...

Any idea what would cause this?

Edit:
Config files as requested ....

From main web.config file (not all of it as it's way too big to post)

```<code><runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
        <dependentAssembly>
            <assemblyIdentity name="Ninject" culture="neutral" publicKeyToken="c7192dc5380945e7" />
            <bindingRedirect newVersion="3.0.0.0" oldVersion="0.0.0.0-3.0.0.0" />
        </dependentAssembly>
        <dependentAssembly>
            <assemblyIdentity name="Microsoft.Practices.EnterpriseLibrary.Validation" culture="neutral" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect newVersion="5.0.505.0" oldVersion="0.0.0.0-5.0.505.0" />
        </dependentAssembly>
        <dependentAssembly>
            <assemblyIdentity name="System.Web" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
            <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
        </dependentAssembly>
        <dependentAssembly>
            <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
        </dependentAssembly>
        <dependentAssembly>
            <assemblyIdentity name="Microsoft.Practices.ServiceLocation" publicKeyToken="31bf3856ad364e35" culture="neutral" />
            <bindingRedirect oldVersion="0.0.0.0-1.2.0.0" newVersion="1.2.0.0" />
        </dependentAssembly>
    </assemblyBinding>
</runtime>
</code>```

Config file in "~/Views/" ...

```<code><?xml version="1.0"?>
<configuration>
    <configSections>
        <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
            <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
            <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
        </sectionGroup>
    </configSections>

    <system.web.webPages.razor>
        <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <pages pageBaseType="System.Web.Mvc.WebViewPage">
            <namespaces>
                <add namespace="System.Web.Mvc" />
                <add namespace="System.Web.Mvc.Ajax" />
                <add namespace="System.Web.Mvc.Html" />
                <add namespace="System.Web.Routing" />
                <add namespace="Emedia.Common.Mvc.Views.Helpers"/>
                <add namespace="Emedia.Common.Mvc.Views.Extensions"/>
        <add namespace="Emedia.Common.Utilities"/>
        <add namespace="Emedia.Common.Utilities.Extensions"/>
        <add namespace="Emedia.Common.Mvc.Controllers.Helpers"/>
                <add namespace="Emedia.Resources.Service"/>
        <add namespace="Emedia.Subscriber.Controllers"/>
        <add namespace="Emedia.Subscriber.Controllers.ViewModels"/>
            </namespaces>
        </pages>
    </system.web.webPages.razor>

    <appSettings>
        <add key="webpages:Enabled" value="false" />
    </appSettings>

    <system.web>
        <httpHandlers>
            <add path="*" verb="*" type="System.Web.HttpNotFoundHandler"/>
        </httpHandlers>
        <pages
            validateRequest="false"
            pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
            pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
            userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
            <controls>
                <add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" namespace="System.Web.Mvc" tagPrefix="mvc" />
        </controls>
    </pages>
</system.web>

<system.webServer>
    <validation validateIntegratedModeConfiguration="false" />

    <handlers>
        <remove name="BlockViewHandler"/>
        <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
    </handlers>
</system.webServer>
</code>```

答:
Update the NuGet Packages using Package Manager console in Tool, Library package Manager..

In command line..
PM> Update-Package
This will update NuGet packages and verify the current version of System.web.MVC and update this version in web.config file under Views folder.

```<code><system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Optimization"/>
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.Webpages"/>
      </namespaces>
    </pages>
  </system.web.webPages.razor>
</code>```

Close the solution and Reopen.

Hope this works !!!

Body:
I have an existing project written in VS2010 which when loaded in VS2010 works perfectly.

When I load this same project in VS2013 the MVC Razor views contain lots of errors as if the config file is missing from the views folder.

It appears to have not loaded the Razor editor correctly using the config files from both the root and the views folder and instead gives me errors like ...

The name 'model' does not exist in the current context

and ...

'System.Web.WebPages.Html.HtmlHelper' does not contain a definition for 'LabelFor'
and no extension method 'LabelFor' accepting a first argument of type
'System.Web.WebPages.Html.HtmlHelper' could be found
(are you missing a using directive or an assembly reference?)

...

Any idea what would cause this?

Edit:
Config files as requested ....

From main web.config file (not all of it as it's way too big to post)

<runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
        <dependentAssembly>
            <assemblyIdentity name="Ninject" culture="neutral" publicKeyToken="c7192dc5380945e7" />
            <bindingRedirect newVersion="3.0.0.0" oldVersion="0.0.0.0-3.0.0.0" />
        </dependentAssembly>
        <dependentAssembly>
            <assemblyIdentity name="Microsoft.Practices.EnterpriseLibrary.Validation" culture="neutral" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect newVersion="5.0.505.0" oldVersion="0.0.0.0-5.0.505.0" />
        </dependentAssembly>
        <dependentAssembly>
            <assemblyIdentity name="System.Web" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
            <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
        </dependentAssembly>
        <dependentAssembly>
            <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
        </dependentAssembly>
        <dependentAssembly>
            <assemblyIdentity name="Microsoft.Practices.ServiceLocation" publicKeyToken="31bf3856ad364e35" culture="neutral" />
            <bindingRedirect oldVersion="0.0.0.0-1.2.0.0" newVersion="1.2.0.0" />
        </dependentAssembly>
    </assemblyBinding>
</runtime>

Config file in "~/Views/" ...

<?xml version="1.0"?>
<configuration>
    <configSections>
        <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">

        </sectionGroup>
    </configSections>

    <system.web.webPages.razor>
        <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <pages pageBaseType="System.Web.Mvc.WebViewPage">
            <namespaces>
                <add namespace="System.Web.Mvc" />
                <add namespace="System.Web.Mvc.Ajax" />
                <add namespace="System.Web.Mvc.Html" />
                <add namespace="System.Web.Routing" />
                <add namespace="Emedia.Common.Mvc.Views.Helpers"/>
                <add namespace="Emedia.Common.Mvc.Views.Extensions"/>
        <add namespace="Emedia.Common.Utilities"/>
        <add namespace="Emedia.Common.Utilities.Extensions"/>
        <add namespace="Emedia.Common.Mvc.Controllers.Helpers"/>
                <add namespace="Emedia.Resources.Service"/>
        <add namespace="Emedia.Subscriber.Controllers"/>
        <add namespace="Emedia.Subscriber.Controllers.ViewModels"/>
            </namespaces>
        </pages>
    </system.web.webPages.razor>

    <appSettings>
        <add key="webpages:Enabled" value="false" />
    </appSettings>

    <system.web>
        <httpHandlers>
            <add path="*" verb="*" type="System.Web.HttpNotFoundHandler"/>
        </httpHandlers>
        <pages
            validateRequest="false"
            pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
            pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
            userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
            <controls>
                <add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" namespace="System.Web.Mvc" tagPrefix="mvc" />
        </controls>
    </pages>
</system.web>

<system.webServer>
    <validation validateIntegratedModeConfiguration="false" />

    <handlers>
        <remove name="BlockViewHandler"/>
        <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
    </handlers>
</system.webServer>

Body:
Update the NuGet Packages using Package Manager console in Tool, Library package Manager..

In command line..
PM> Update-Package
This will update NuGet packages and verify the current version of System.web.MVC and update this version in web.config file under Views folder.

<system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Optimization"/>
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.Webpages"/>
      </namespaces>
    </pages>
  </system.web.webPages.razor>

Close the solution and Reopen.

Hope this works !!!


问:
Access to redefined variables inside a nested block
Consider the program below:

```<code>#include <iostream>
using std::cout;
int i = 10;

int main() {
     int i = 9;
     {
          int i = 8;
          {
                int i = 7;
                cout << i << "\n";   // i = 7
                cout << ::i << "\n"; // i = 10 (global i)

                // How could we access to other i declarations here?
          }
     }
     return 0;
}
</code>```

using i inside the nested block referes to the last declarations of i, because the latter hides the other declarations. In order to use the global i (the declarations outside the function main), we could use ::i

I would like to know if there is a way to use the other decalarations of i inside the nested block.

答:
Declare a new variable name, something like 'j' instead of 'i'. </p>

```<code>#include <iostream>
using std::cout;
int i = 10;

int main() {
     int i = 9;
     {
          int j = 8;
          {
                int j = 7;
                cout << j << "\n";   // j = 7
                cout << ::i << "\n"; // i = 10 (global i)

                // How could we access to other
       i declarations here?
          }
     }
     return 0;
    }
</code>```

Body:
Consider the program below:

#include <iostream>
using std::cout;
int i = 10;

int main() {
     int i = 9;
     {
          int i = 8;
          {
                int i = 7;
                cout << i << "\n";   // i = 7
                cout << ::i << "\n"; // i = 10 (global i)

                // How could we access to other i declarations here?
          }
     }
     return 0;
}

using i inside the nested block referes to the last declarations of i, because the latter hides the other declarations. In order to use the global i (the declarations outside the function main), we could use ::i

I would like to know if there is a way to use the other decalarations of i inside the nested block.

Body:
Declare a new variable name, something like 'j' instead of 'i'.

#include <iostream>
using std::cout;
int i = 10;

int main() {
     int i = 9;
     {
          int j = 8;
          {
                int j = 7;
                cout << j << "\n";   // j = 7
                cout << ::i << "\n"; // i = 10 (global i)

                // How could we access to other
       i declarations here?
          }
     }
     return 0;
    }


问:
Nodejs req.body shows empty from Android Volley
Android Code:

```<code>private void registerUser(){
        final String username = "subrata";
        final String password = "banerjee";
        final String email = "test_email";

        StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Toast.makeText(LoginActivity.this,response,Toast.LENGTH_LONG).show();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(LoginActivity.this,error.toString(),Toast.LENGTH_LONG).show();
                    }
                }){
            @Override
            protected Map<String,String> getParams(){
                Map<String,String> params = new HashMap<String, String>();
                params.put(KEY_USERNAME,username);
                params.put(KEY_PASSWORD,password);
                params.put(KEY_EMAIL, email);
                return params;
            }

        };

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }
</code>```

I'm trying to send http request using Android Volley to my node.js server (expressjs). Its hitting the server and getting the response but when I'm printing the req.body in node.js its shows {} (empty). I'm new to Android and unable to figure out the reason. Please someone guide me.

答:
Call this method in OnResponse GetResponse(response);
And the method will be

```<code>private void GetResponse(String res){
    JSONObject jsonObject = null;

    try {
        jsonObject = new JSONObject(res);
        JSONArray result = jsonObject.getJSONArray("result");

        for (int i = 0; i < result.length(); i++) {
            JSONObject jo = result.getJSONObject(i);
            String temp = jo.getString("what_ever");
            String temp1 = jo.getString("what_ever_1");
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }
}
</code>```

This will get you the response in String format fetched from json.

Body:
Android Code:

private void registerUser(){
        final String username = "subrata";
        final String password = "banerjee";
        final String email = "test_email";

        StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Toast.makeText(LoginActivity.this,response,Toast.LENGTH_LONG).show();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(LoginActivity.this,error.toString(),Toast.LENGTH_LONG).show();
                    }
                }){
            @Override
            protected Map<String,String> getParams(){
                Map<String,String> params = new HashMap<String, String>();
                params.put(KEY_USERNAME,username);
                params.put(KEY_PASSWORD,password);
                params.put(KEY_EMAIL, email);
                return params;
            }

        };

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }

I'm trying to send http request using Android Volley to my node.js server (expressjs). Its hitting the server and getting the response but when I'm printing the req.body in node.js its shows {} (empty). I'm new to Android and unable to figure out the reason. Please someone guide me.

Body:
Call this method in OnResponse GetResponse(response);
And the method will be

private void GetResponse(String res){
    JSONObject jsonObject = null;

    try {
        jsonObject = new JSONObject(res);
        JSONArray result = jsonObject.getJSONArray("result");

        for (int i = 0; i < result.length(); i++) {
            JSONObject jo = result.getJSONObject(i);
            String temp = jo.getString("what_ever");
            String temp1 = jo.getString("what_ever_1");
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }
}

This will get you the response in String format fetched from json.


问:
Ansible Host/Group Structure
I need help figuring out how I should structure my hosts and groups for my use case.

Let me set the scene a little. My current setup is as follows:

hosts

```<code>[windows]
client_1 ansible_host=172.0.0.1
[linux]
client_2 ansible_host=172.0.0.2
client_3 ansible_host=172.0.0.3
</code>```

Let's take a look at just the windows setup.

group_vars/windows

```<code>jboss_service_name: JBOSSAS7SVC
app_service_name: APPSRVC
...
</code>```

host_vars/client_1

```<code>ansible_user: username
ansible_password: pasword
ansible_port: 5986
ansible_connection: winrm
ansible_winrm_server_cert_validation: ignore
</code>```

Then my playbook looks as follows:

```<code>- hosts: '{{ target }}'
  name: Stop JBoss and App Services.
  remote_user: '{{ ansible_user }}'
  tasks:
  - name: Stopping JBoss Service.
    win_service:
      name: '{{ jboss_service_name }}'
      start_mode: manual
      state: stopped

  - name: Stopping App Service.
    win_service:
      name: '{{ app_service_name }}'
      start_mode: manual
      state: stopped
</code>```

So I can run my play as follows:

```<code>ansible-playbook my-playbook.yml --extra-var "target=client_1"
</code>```

Or for all windows machines:

```<code>ansible-playbook my-playbook.yml --extra-var "target=windows"
</code>```

This works fine, I have this working as listed above. However, this solution is for a single server setup for my clients. Meaning jboss, the app, web and db server are all on the same physical server - in this case 172.0.0.1.

However this is not always the case. For any given client, it might be a shared or distributed setup. Meaning the jboss, app, web, db services may be on a single server, or each be on their own server.

So I've been trying to adapt this setup but I'm not sure exactly how to run my plays such that I'm executing the showdown service commands on a particular client server. I need to still be able to execute a playbook on a single client or a group - windows.

This is what I've come up with so far.

hosts (removed the ansible_host=...)

```<code>[windows]
client_1
[linux]
client_2
client_3
</code>```

group_vars/windows (No changes here)

```<code>jboss_service_name: JBOSSAS7SVC
app_service_name: APPSRVC
...
</code>```

host_vars/client_1 (moved ip addresses down to the client host_var level)

```<code>ansible_user: username
ansible_password: pasword
ansible_port: 5986
ansible_connection: winrm
ansible_winrm_server_cert_validation: ignore

app_server: 172.0.0.1
jboss_server: app_server: 172.0.0.2
web_server: app_server: 172.0.0.3
...
</code>```

In the above host_var file, if it was a shared setup I would just set **_server* variables to all use the same IP address.

I've created a test playbook that debug prints variables in the host_var file and group_var file, meaning it has access to all of that data.

I execute it as follows:

```<code>ansible-playbook -i client_1 test-playbook.yml
</code>```

I could then pass in the group windows instead of a client host.

But what I don't understand is how to edit my old playbook to make use of these new variables, eg the call to win_service to shutdown jboss for that client should only be executed on server host_vars/client_1.app_server, likewise shutting down my app service should only be ran on server app_server for that client.

I know this is a long piece of text, so thank you for taking the time to read it.

My question is then, do I have this completely wrong? How should I structure my hosts such that I can distinguish between windows and linux hosts, can set this up by client, and be able to support a shared or distributed server setup for any given client?

Many thanks.

答:
Name your hosts something different, but use the same IP addresses:

```<code>[windows_app]
wa01 ansible_host=111.111.111.1

[windows_jboss]
wj01 ansible_host=111.111.111.1

[windows:children]
windows_app
windows_jboss
</code>```

Define service_name in group_vars/windows_app and group_vars/windows_jboss.

Your playbooks should define the hosts for the specific plays:

```<code>- hosts: windows
  name: Stop JBoss and App Services on Windows servers
  remote_user: '{{ ansible_user }}'
  tasks:
  - name: Stopping Service.
    win_service:
      name: '{{ service_name }}'
      start_mode: manual
      state: stopped
</code>```

Don't use --extra-vars, but -l or --limit= to stop one service but not the other:

```<code>ansible-playbook test-playbook.yml -l windows_app
</code>```

Title: Ansible Host/Group Structure

Body:
I need help figuring out how I should structure my hosts and groups for my use case.

Let me set the scene a little. My current setup is as follows:

hosts

[windows]
client_1 ansible_host=172.0.0.1
[linux]
client_2 ansible_host=172.0.0.2
client_3 ansible_host=172.0.0.3

Let's take a look at just the windows setup.

group_vars/windows

jboss_service_name: JBOSSAS7SVC
app_service_name: APPSRVC
...

host_vars/client_1

ansible_user: username
ansible_password: pasword
ansible_port: 5986
ansible_connection: winrm
ansible_winrm_server_cert_validation: ignore

Then my playbook looks as follows:

- hosts: '{{ target }}'
  name: Stop JBoss and App Services.
  remote_user: '{{ ansible_user }}'
  tasks:
  - name: Stopping JBoss Service.
    win_service:
      name: '{{ jboss_service_name }}'
      start_mode: manual
      state: stopped

  - name: Stopping App Service.
    win_service:
      name: '{{ app_service_name }}'
      start_mode: manual
      state: stopped

So I can run my play as follows:

ansible-playbook my-playbook.yml --extra-var "target=client_1"

Or for all windows machines:

ansible-playbook my-playbook.yml --extra-var "target=windows"

This works fine, I have this working as listed above. However, this solution is for a single server setup for my clients. Meaning jboss, the app, web and db server are all on the same physical server - in this case 172.0.0.1.

However this is not always the case. For any given client, it might be a shared or distributed setup. Meaning the jboss, app, web, db services may be on a single server, or each be on their own server.

So I've been trying to adapt this setup but I'm not sure exactly how to run my plays such that I'm executing the showdown service commands on a particular client server. I need to still be able to execute a playbook on a single client or a group - windows.

This is what I've come up with so far.

hosts (removed the ansible_host=...)

[windows]
client_1
[linux]
client_2
client_3

group_vars/windows (No changes here)

jboss_service_name: JBOSSAS7SVC
app_service_name: APPSRVC
...

host_vars/client_1 (moved ip addresses down to the client host_var level)

ansible_user: username
ansible_password: pasword
ansible_port: 5986
ansible_connection: winrm
ansible_winrm_server_cert_validation: ignore

app_server: 172.0.0.1
jboss_server: app_server: 172.0.0.2
web_server: app_server: 172.0.0.3
...

In the above host_var file, if it was a shared setup I would just set **_server* variables to all use the same IP address.

I've created a test playbook that debug prints variables in the host_var file and group_var file, meaning it has access to all of that data.

I execute it as follows:

ansible-playbook -i client_1 test-playbook.yml

I could then pass in the group windows instead of a client host.

But what I don't understand is how to edit my old playbook to make use of these new variables, eg the call to win_service to shutdown jboss for that client should only be executed on server host_vars/client_1.app_server, likewise shutting down my app service should only be ran on server app_server for that client.

I know this is a long piece of text, so thank you for taking the time to read it.

My question is then, do I have this completely wrong? How should I structure my hosts such that I can distinguish between windows and linux hosts, can set this up by client, and be able to support a shared or distributed server setup for any given client?

Many thanks.

Body:
Name your hosts something different, but use the same IP addresses:

[windows_app]
wa01 ansible_host=111.111.111.1

[windows_jboss]
wj01 ansible_host=111.111.111.1

[windows:children]
windows_app
windows_jboss

Define service_name in group_vars/windows_app and group_vars/windows_jboss.

Your playbooks should define the hosts for the specific plays:

- hosts: windows
  name: Stop JBoss and App Services on Windows servers
  remote_user: '{{ ansible_user }}'
  tasks:
  - name: Stopping Service.
    win_service:
      name: '{{ service_name }}'
      start_mode: manual
      state: stopped

Don't use --extra-vars, but -l or --limit= to stop one service but not the other:

ansible-playbook test-playbook.yml -l windows_app


问:
Java Regex to extract any characters between two tokens
I am trying to parse the following text

```<code>### __Description of the report__
Lorem ipsum dolor sit amet,  & mauris elit, blandit a turpis vel nibh,
consectetuer aliquam. Nec sem. Venenatis quam etiam donec consequat
sagittis, luctus porttitor odit sollicitudin <> vestibulum ultrices erat,
sed eleifend
* amet, sollicitudin sit egestas
* quis eros nulla. Sed donec

### __Notable filters__
* Lorem ipsum dolor sit amet, mauris elit, blandit a turpis vel
* consectetuer aliquam. Nec sem. Venenatis quam etiam donec consequat
* sagittis, luctus porttitor odit sollicitudin vestibulum ultrices
</code>```

I want to capture all text between the ### __Description of the report__ and ### __Notable filters__ which could be numbers letters, or any combination of special characters.

I thought using ### __Description of the report__(.*?)### __Notable filters__ would work, but it doesn't return any results. How can i extract the text between the two headings?

答:
You can use the String's split function and use both headers as the regex, concatenating with the '|' operator.

In this way, the content of the first section will be placed in the first element of the array and the content of the second section will be placed in the second element of the array.

Please check this code:

```<code>public class Test {
    private String testString = "### __Description of the report__\n" +
"Lorem ipsum dolor sit amet,  & mauris elit, blandit a turpis vel nibh, \n" +
"consectetuer aliquam. Nec sem. Venenatis quam etiam donec consequat \n" +
"sagittis, luctus porttitor odit sollicitudin <> vestibulum ultrices erat,\n" +
"sed eleifend \n" +
"* amet, sollicitudin sit egestas \n" +
"* quis eros nulla. Sed donec\n" +
"\n" +
"### __Notable filters__\n" +
"* Lorem ipsum dolor sit amet, mauris elit, blandit a turpis vel\n" +
"* consectetuer aliquam. Nec sem. Venenatis quam etiam donec consequat \n" +
"* sagittis, luctus porttitor odit sollicitudin vestibulum ultrices ";

    public static void main (String[] args)
    {
        Test t = new Test();
        String[] parts = t.testString.split("### __Description of the report__\n|### __Notable filters__\n");
    }
}
</code>```

Body:
I am trying to parse the following text

### __Description of the report__
Lorem ipsum dolor sit amet,  & mauris elit, blandit a turpis vel nibh,
consectetuer aliquam. Nec sem. Venenatis quam etiam donec consequat
sagittis, luctus porttitor odit sollicitudin <> vestibulum ultrices erat,
sed eleifend
* amet, sollicitudin sit egestas
* quis eros nulla. Sed donec

### __Notable filters__
* Lorem ipsum dolor sit amet, mauris elit, blandit a turpis vel
* consectetuer aliquam. Nec sem. Venenatis quam etiam donec consequat
* sagittis, luctus porttitor odit sollicitudin vestibulum ultrices

I want to capture all text between the ### __Description of the report__ and ### __Notable filters__ which could be numbers letters, or any combination of special characters.

I thought using ### __Description of the report__(.*?)### __Notable filters__ would work, but it doesn't return any results. How can i extract the text between the two headings?

Body:
You can use the String's split function and use both headers as the regex, concatenating with the '|' operator.

In this way, the content of the first section will be placed in the first element of the array and the content of the second section will be placed in the second element of the array.

Please check this code:

public class Test {
    private String testString = "### __Description of the report__\n" +
"Lorem ipsum dolor sit amet,  & mauris elit, blandit a turpis vel nibh, \n" +
"consectetuer aliquam. Nec sem. Venenatis quam etiam donec consequat \n" +
"sagittis, luctus porttitor odit sollicitudin <> vestibulum ultrices erat,\n" +
"sed eleifend \n" +
"* amet, sollicitudin sit egestas \n" +
"* quis eros nulla. Sed donec\n" +
"\n" +
"### __Notable filters__\n" +
"* Lorem ipsum dolor sit amet, mauris elit, blandit a turpis vel\n" +
"* consectetuer aliquam. Nec sem. Venenatis quam etiam donec consequat \n" +
"* sagittis, luctus porttitor odit sollicitudin vestibulum ultrices ";

    public static void main (String[] args)
    {
        Test t = new Test();
        String[] parts = t.testString.split("### __Description of the report__\n|### __Notable filters__\n");
    }
}


问:
Calculate rolling correlation with pandas
I have a list of 10 stocks differentiated by PERMNO. I would like to group those stocks by PERMNO and calculate the rolling correlation between the stock return (RET) for each PERMNO with the market return (vwretd). The code I am trying is below.

```<code>CRSP['rollingcorr'] = CRSP.groupby('PERMNO').rolling_corr(CRSP['RET'],CRSP['vwretd'],10)
</code>```

The error I am getting is below.

```<code>---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-32-c18e1ce01302> in <module>()
      1 #CRSP['rollingcorr'] = CRSP.rolling_corr(CRSP['vwretd'],CRSP['RET'],120)
----> 2 CRSP['rollingmean'] = CRSP.groupby('PERMNO').rolling_corr(CRSP['vwretd'],10)
      3 CRSP.head(20)

C:\Users\rebortz\Anaconda\lib\site-packages\pandas\core\groupby.pyc in __getattr__(self, attr)
    296
    297         raise AttributeError("%r object has no attribute %r" %
--> 298                              (type(self).__name__, attr))
    299
    300     def __getitem__(self, key):

AttributeError: 'DataFrameGroupBy' object has no attribute 'rolling_corr'
</code>```

please help!

Thanks

答:
Running rolling.corr() on Python 3.5 generates a warning the function is deprecated and may stop working in future. Using Series.rolling(window=<period>).corr(other=series) instead is recommended.
E.g.

```<code>data['scrip1DailyReturn'].rolling(window=90).corr(other=data['scrip2DailyReturn'])
</code>```

Body:
I have a list of 10 stocks differentiated by PERMNO. I would like to group those stocks by PERMNO and calculate the rolling correlation between the stock return (RET) for each PERMNO with the market return (vwretd). The code I am trying is below.

CRSP['rollingcorr'] = CRSP.groupby('PERMNO').rolling_corr(CRSP['RET'],CRSP['vwretd'],10)

The error I am getting is below.

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-32-c18e1ce01302> in <module>()
      1 #CRSP['rollingcorr'] = CRSP.rolling_corr(CRSP['vwretd'],CRSP['RET'],120)
----> 2 CRSP['rollingmean'] = CRSP.groupby('PERMNO').rolling_corr(CRSP['vwretd'],10)
      3 CRSP.head(20)

C:\Users\rebortz\Anaconda\lib\site-packages\pandas\core\groupby.pyc in __getattr__(self, attr)
    296
    297         raise AttributeError("%r object has no attribute %r" %
--> 298                              (type(self).__name__, attr))
    299
    300     def __getitem__(self, key):

AttributeError: 'DataFrameGroupBy' object has no attribute 'rolling_corr'

please help!

Thanks

Body:
Running rolling.corr() on Python 3.5 generates a warning the function is deprecated and may stop working in future. Using Series.rolling(window=<period>).corr(other=series) instead is recommended.
E.g.

data['scrip1DailyReturn'].rolling(window=90).corr(other=data['scrip2DailyReturn'])

ContentLicense: CC BY-SA 4.0


问:
Server-side highscores for a Javascript-written game
I'm implementing a simple game in Javascript, and am interested in having an online highscores table for it, so that players can compete against one another. I've two concerns about this:

What is the simplest server-side program I need for this purpose? I don't need a full-fledged "web application", just something simple that gets POST requests with highscores, updates a database and sends back lists of scores. I'm familiar with Django. What are your suggestions?

How can I make the highscores table reasonably secure? I'm aware that making it bulletproof against competent and dedicated hackers is difficult, but I wouldn't want anyone with access to the Javascript sourcecode to be able to submit fictitious scores too simply. Any tools for this purpose?

答:
To submit score securely, sign it (you'd also need to ensure that the score isn't faked before it's signed and sent, but that's another problem).

Hide a secret in JS code, and send highscore + hash(highscore + secret) to the server. The hash could be MD5/SHA1 — there are easy to find JS implementations.

Of course it won't stand anyone carefully analysing the JS code, but at least someone won't be able to submit fake highscore just by tampering with HTTP traffic.

On hiding stuff in JS:

You can't really hide it (it's ultimately futile like DRM), but you can try hard to obfuscate it and make debugging painful.

Don't put the secret as a literal in the source code - compute it at run time combining results of several functions, local and global-ish variables.

Minify all code, remove sourcemaps.

Add bits of code that don't do anything, but seem to be important, to make debugging more confusing.

Don't put anything in global scope, but do rely on shared mutable state by passing closures and arrays around.

Rely on Date and timers to cause race conditions to make your code produce wrong results if it's paused in the debugger (just don't make it too tight to allow it to run on slow machines).

If the game is deterministic (like a puzzle game), then users could submit highscore in form of a log of steps taken to win (user's input) that you'd replay on the server to calculate the score.

This would change attack from finding/emulating score-submitting function to witing AI or hacking the game itself to make it easier to play (but still within its basic rules).


问:
"Please provide a valid cache path" error in laravel
I duplicated a working laravel app and renamed it to use for another app.  I deleted the vendor folder and run the following commands again:

```<code>composer self-update

composer-update

npm install

bower install
</code>```

I configured my routes and everything properly however now when I try to run my app in my browser I get the following errors:

InvalidArgumentException in Compiler.php line 36: Please provide a
  valid cache path.

ErrorException in Filesystem.php line 111:
  file_put_contents(F:\www\example\app\storage\framework/sessions/edf262ee7a2084a923bb967b938f54cb19f6b37d):
  failed to open stream: No such file or directory

I have never had this issue before, I do not know what is causing it neither do I know how to fix it, I have googled online for a solution but have found none so far.

答:
You can edit your readme.md with instructions to install your laravel app in other environment like this:

```<code>## Create folders

```
#!terminal

cp .env.example .env && mkdir bootstrap/cache storage storage/framework && cd storage/framework && mkdir sessions views cache

```

## Folder permissions

```
#!terminal

sudo chown :www-data app storage bootstrap -R
sudo chmod 775 app storage bootstrap -R

```

## Install dependencies

```
#!terminal

composer install

```
</code>```

Body:
I duplicated a working laravel app and renamed it to use for another app.  I deleted the vendor folder and run the following commands again:

composer self-update

composer-update

npm install

bower install

I configured my routes and everything properly however now when I try to run my app in my browser I get the following errors:

InvalidArgumentException in Compiler.php line 36: Please provide a
  valid cache path.

ErrorException in Filesystem.php line 111:
  file_put_contents(F:\www\example\app\storage\framework/sessions/edf262ee7a2084a923bb967b938f54cb19f6b37d):
  failed to open stream: No such file or directory

I have never had this issue before, I do not know what is causing it neither do I know how to fix it, I have googled online for a solution but have found none so far.

Body:
You can edit your readme.md with instructions to install your laravel app in other environment like this:

## Create folders

```
#!terminal

cp .env.example .env && mkdir bootstrap/cache storage storage/framework && cd storage/framework && mkdir sessions views cache

```

## Folder permissions

```
#!terminal

sudo chown :www-data app storage bootstrap -R
sudo chmod 775 app storage bootstrap -R

```

## Install dependencies

```
#!terminal

composer install

```