问:
Make one div slide over another using only CSS
I am attempting to have 2 divs of the same size, one is initially visible while the other (below?) is initially hidden.

I desire that when you hover over the first div, the other will animate and slide upward to fully cover the first. This one should remain in place until you stop hovering over the area.

I can get a second div to move upward on hover, but it has many unwanted effects - such as a jumpy/jittery behaviour when the second div is in place - and in this fiddle, the lower one begins visible.

http://jsfiddle.net/cc28samh/1/

the HTML

```<code><div>
    <div id="stay-in-place">
        <h1>hello world</h1>
        <p>ipsum dolorum caveat emptor veni vidi vici</p>
    </div>
    <div id="move-in-to-place">
        <h2>I'm on top</h2>
    </div>
</div>
</code>```

the style

```<code><style type="text/css"> #stay-in-place {
    position:relative;
    height : 200px;
    width : 200px;
    background: red;
    -webkit-transition: height 1s, -webkit-transform 1s;
    transition: height 1s, transform 1s;
}
#stay-in-place:hover {
    height : 0px;
}
#move-in-to-place {
    position:absolute;
    height : 200px;
    width : 200px;
    background: blue;
}
</style>
</code>```

答:
I made a improved version of http://jsfiddle.net/sdL1vead/ here http://jsfiddle.net/tongadall/trqj1qgo

html

```<code><div class="box">
<div class="stay-in-place">
    <h1>hello world</h1>
    <p>ipsum dolorum caveat emptor veni vidi vici</p>
</div>
<div class="move-in-to-place">
    <span>I'm on top</span>
</div>
</div>
</code>```

CSS

```<code>.stay-in-place {
    height: 100%;
    width: 100%;
    background: red;
    position: absolute;
}
.move-in-to-place {
    position: absolute;
    bottom: -100%;
    height : 100%;
    width : 100%;
    padding: 8px;
    background: rgba(255, 255, 255, 0.7);
    opacity: 0;
    font-size: 12px;
    line-height: 1.2;
}
.box {
    margin: 2px;
    float: left;
    position: relative;
    width: 200px;
    height: 200px;
    overflow: hidden;
}
.box:hover .move-in-to-place {
    bottom: 0;
    -webkit-transition: all 0.4s, -webkit-transform 0.4s;
    transition: all 0.4s, transform 0.4s;
    width: 100%;
    height: auto;
    opacity: 1;
}
.box:not(hover) .move-in-to-place {
    bottom: -100%;
    -webkit-transition: all 2s, -webkit-transform 2s;
    transition: all 2s, transform 2s;
    width: 100%;
    height: 0;
    opacity: 0;
}
</code>```

Body:
I am attempting to have 2 divs of the same size, one is initially visible while the other (below?) is initially hidden.

I desire that when you hover over the first div, the other will animate and slide upward to fully cover the first. This one should remain in place until you stop hovering over the area.

I can get a second div to move upward on hover, but it has many unwanted effects - such as a jumpy/jittery behaviour when the second div is in place - and in this fiddle, the lower one begins visible.

http://jsfiddle.net/cc28samh/1/

the HTML

hello world

ipsum dolorum caveat emptor veni vidi vici

I'm on top

the style

Body:
I made a improved version of http://jsfiddle.net/sdL1vead/ here http://jsfiddle.net/tongadall/trqj1qgo

html

<div class="box">
<div class="stay-in-place">
    <h1>hello world</h1>
    <p>ipsum dolorum caveat emptor veni vidi vici</p>
</div>
<div class="move-in-to-place">
    <span>I'm on top</span>
</div>
</div>

CSS

.stay-in-place {
    height: 100%;
    width: 100%;
    background: red;
    position: absolute;
}
.move-in-to-place {
    position: absolute;
    bottom: -100%;
    height : 100%;
    width : 100%;
    padding: 8px;
    background: rgba(255, 255, 255, 0.7);
    opacity: 0;
    font-size: 12px;
    line-height: 1.2;
}
.box {
    margin: 2px;
    float: left;
    position: relative;
    width: 200px;
    height: 200px;
    overflow: hidden;
}
.box:hover .move-in-to-place {
    bottom: 0;
    -webkit-transition: all 0.4s, -webkit-transform 0.4s;
    transition: all 0.4s, transform 0.4s;
    width: 100%;
    height: auto;
    opacity: 1;
}
.box:not(hover) .move-in-to-place {
    bottom: -100%;
    -webkit-transition: all 2s, -webkit-transform 2s;
    transition: all 2s, transform 2s;
    width: 100%;
    height: 0;
    opacity: 0;
}


来源: stackexchange

问:
How to decode AAC compressed frames to PCM using AudioConverterFillComplexBuffer iOS
I want to implement SIP calls in my application, and first problem, that I need to solve, is converting audio from compressed AAC format with ADTS header to linear PCM.

My input data is an NSArray of ADTS frames with different framesize. Each frame is typeof NSMutableData. Each frame is of the same format and sample rate, only difference is framesize.

I tried to implement sample code, suggested by Igor Rotaru for this issue, but can't make it work.

Now my code looks like this. First of all, I configure the AudioConverter:

```<code>- (void)configureAudioConverter {
    AudioStreamBasicDescription inFormat;
    memset(&inFormat, 0, sizeof(inFormat));
    inputFormat.mBitsPerChannel = 0;
    inputFormat.mBytesPerFrame = 0;
    inputFormat.mBytesPerPacket = 0;
    inputFormat.mChannelsPerFrame = 1;
    inputFormat.mFormatFlags = kMPEG4Object_AAC_LC;
    inputFormat.mFormatID = kAudioFormatMPEG4AAC;
    inputFormat.mFramesPerPacket = 1024;
    inputFormat.mReserved = 0;
    inputFormat.mSampleRate = 22050;

    AudioStreamBasicDescription outputFormat;
    memset(&outputFormat, 0, sizeof(outputFormat));
    outputFormat.mSampleRate       = inputFormat.mSampleRate;
    outputFormat.mFormatID         = kAudioFormatLinearPCM;
    outputFormat.mFormatFlags      = kLinearPCMFormatFlagIsSignedInteger;
    outputFormat.mBytesPerPacket   = 2;
    outputFormat.mFramesPerPacket  = 1;
    outputFormat.mBytesPerFrame    = 2;
    outputFormat.mChannelsPerFrame = 1;
    outputFormat.mBitsPerChannel   = 16;
    outputFormat.mReserved         = 0;

    AudioClassDescription *description = [self
                                      getAudioClassDescriptionWithType:kAudioFormatMPEG4AAC
                                      fromManufacturer:kAppleSoftwareAudioCodecManufacturer];

    OSStatus status =  AudioConverterNewSpecific(&inputFormat, &outputFormat, 1, description, &_audioConverter);

    if (status != 0) {
        printf("setup converter error, status: %i\n", (int)status);
    }
}
</code>```

After that I wrote the callback function:

```<code>struct MyUserData {
    UInt32 mChannels;
    UInt32 mDataSize;
    const void* mData;
    AudioStreamPacketDescription mPacket;
};

OSStatus inInputDataProc(AudioConverterRef inAudioConverter,
                         UInt32 *ioNumberDataPackets,
                         AudioBufferList *ioData,
                         AudioStreamPacketDescription **outDataPacketDescription,
                         void *inUserData)
{
    struct MyUserData* userData = (struct MyUserData*)(inUserData);

    if (!userData->mDataSize) {
        *ioNumberDataPackets = 0;
        return kNoMoreDataError;
    }

    if (outDataPacketDescription) {
        userData->mPacket.mStartOffset = 0;
        userData->mPacket.mVariableFramesInPacket = 0;
        userData->mPacket.mDataByteSize = userData->mDataSize;
        *outDataPacketDescription = &userData->mPacket;
    }

    ioData->mBuffers[0].mNumberChannels = userData->mChannels;
    ioData->mBuffers[0].mDataByteSize = userData->mDataSize;
    ioData->mBuffers[0].mData = (void *)userData->mData;

    // No more data to provide following this run.
    userData->mDataSize = 0;

    return noErr;
}
</code>```

And my function for decoding frames looks like this:

```<code>- (void)startDecodingAudio {
    if (!_converterConfigured){
        return;
    }

    while (true){
        if ([self hasFramesToDecode]){
            struct MyUserData userData = {1, (UInt32)_decoderBuffer[_currPosInDecoderBuf].length, _decoderBuffer[_currPosInDecoderBuf].bytes};

            uint8_t *buffer = (uint8_t *)malloc(128 * sizeof(short int));
            AudioBufferList decBuffer;
            decBuffer.mNumberBuffers = 1;
            decBuffer.mBuffers[0].mNumberChannels = 1;
            decBuffer.mBuffers[0].mDataByteSize = 128 * sizeof(short int);
            decBuffer.mBuffers[0].mData = buffer;

            UInt32 numFrames = 128;

            AudioStreamPacketDescription outPacketDescription;
            memset(&outPacketDescription, 0, sizeof(AudioStreamPacketDescription));
            outPacketDescription.mDataByteSize = 128;
            outPacketDescription.mStartOffset = 0;
            outPacketDescription.mVariableFramesInPacket = 0;

            OSStatus status = AudioConverterFillComplexBuffer(_audioConverter,
                                                              inInputDataProc,
                                                              &userData,
                                                              &numFrames,
                                                              &decBuffer,
                                                              &outPacketDescription);

            NSError *error = nil;

            if (status == kNoMoreDataError) {
                NSLog(@"%u bytes decoded", (unsigned int)decBuffer.mBuffers[0].mDataByteSize);
                [_decodedData appendData:[NSData dataWithBytes:decBuffer.mBuffers[0].mData length:decBuffer.mBuffers[0].mDataByteSize]];
                _currPosInDecoderBuf += 1;
            } else {
                error = [NSError errorWithDomain:NSOSStatusErrorDomain code:status userInfo:nil];
            }
        } else {
            break;
        }
    }
}
</code>```

Each time, AudioConverterFillComplexBuffer returns status 1852797029 which is, according to Apple API, kAudioCodecIllegalOperationError. If somebody succeded in converting with such formats, please, share some examples, or advice.

答: Finally, I decoded my bytes with StreamingKit library (original reposiory can be found here).</p>

ContentLicense: CC BY-SA 3.0

Body:
I want to implement SIP calls in my application, and first problem, that I need to solve, is converting audio from compressed AAC format with ADTS header to linear PCM.

My input data is an NSArray of ADTS frames with different framesize. Each frame is typeof NSMutableData. Each frame is of the same format and sample rate, only difference is framesize.

I tried to implement sample code, suggested by Igor Rotaru for this issue, but can't make it work.

Now my code looks like this. First of all, I configure the AudioConverter:

- (void)configureAudioConverter {
    AudioStreamBasicDescription inFormat;
    memset(&inFormat, 0, sizeof(inFormat));
    inputFormat.mBitsPerChannel = 0;
    inputFormat.mBytesPerFrame = 0;
    inputFormat.mBytesPerPacket = 0;
    inputFormat.mChannelsPerFrame = 1;
    inputFormat.mFormatFlags = kMPEG4Object_AAC_LC;
    inputFormat.mFormatID = kAudioFormatMPEG4AAC;
    inputFormat.mFramesPerPacket = 1024;
    inputFormat.mReserved = 0;
    inputFormat.mSampleRate = 22050;

    AudioStreamBasicDescription outputFormat;
    memset(&outputFormat, 0, sizeof(outputFormat));
    outputFormat.mSampleRate       = inputFormat.mSampleRate;
    outputFormat.mFormatID         = kAudioFormatLinearPCM;
    outputFormat.mFormatFlags      = kLinearPCMFormatFlagIsSignedInteger;
    outputFormat.mBytesPerPacket   = 2;
    outputFormat.mFramesPerPacket  = 1;
    outputFormat.mBytesPerFrame    = 2;
    outputFormat.mChannelsPerFrame = 1;
    outputFormat.mBitsPerChannel   = 16;
    outputFormat.mReserved         = 0;

    AudioClassDescription *description = [self
                                      getAudioClassDescriptionWithType:kAudioFormatMPEG4AAC
                                      fromManufacturer:kAppleSoftwareAudioCodecManufacturer];

    OSStatus status =  AudioConverterNewSpecific(&inputFormat, &outputFormat, 1, description, &_audioConverter);

    if (status != 0) {
        printf("setup converter error, status: %i\n", (int)status);
    }
}

After that I wrote the callback function:

struct MyUserData {
    UInt32 mChannels;
    UInt32 mDataSize;
    const void* mData;
    AudioStreamPacketDescription mPacket;
};

OSStatus inInputDataProc(AudioConverterRef inAudioConverter,
                         UInt32 *ioNumberDataPackets,
                         AudioBufferList *ioData,
                         AudioStreamPacketDescription **outDataPacketDescription,
                         void *inUserData)
{
    struct MyUserData* userData = (struct MyUserData*)(inUserData);

    if (!userData->mDataSize) {
        *ioNumberDataPackets = 0;
        return kNoMoreDataError;
    }

    if (outDataPacketDescription) {
        userData->mPacket.mStartOffset = 0;
        userData->mPacket.mVariableFramesInPacket = 0;
        userData->mPacket.mDataByteSize = userData->mDataSize;
        *outDataPacketDescription = &userData->mPacket;
    }

    ioData->mBuffers[0].mNumberChannels = userData->mChannels;
    ioData->mBuffers[0].mDataByteSize = userData->mDataSize;
    ioData->mBuffers[0].mData = (void *)userData->mData;

    // No more data to provide following this run.
    userData->mDataSize = 0;

    return noErr;
}

And my function for decoding frames looks like this:

- (void)startDecodingAudio {
    if (!_converterConfigured){
        return;
    }

    while (true){
        if ([self hasFramesToDecode]){
            struct MyUserData userData = {1, (UInt32)_decoderBuffer[_currPosInDecoderBuf].length, _decoderBuffer[_currPosInDecoderBuf].bytes};

            uint8_t *buffer = (uint8_t *)malloc(128 * sizeof(short int));
            AudioBufferList decBuffer;
            decBuffer.mNumberBuffers = 1;
            decBuffer.mBuffers[0].mNumberChannels = 1;
            decBuffer.mBuffers[0].mDataByteSize = 128 * sizeof(short int);
            decBuffer.mBuffers[0].mData = buffer;

            UInt32 numFrames = 128;

            AudioStreamPacketDescription outPacketDescription;
            memset(&outPacketDescription, 0, sizeof(AudioStreamPacketDescription));
            outPacketDescription.mDataByteSize = 128;
            outPacketDescription.mStartOffset = 0;
            outPacketDescription.mVariableFramesInPacket = 0;

            OSStatus status = AudioConverterFillComplexBuffer(_audioConverter,
                                                              inInputDataProc,
                                                              &userData,
                                                              &numFrames,
                                                              &decBuffer,
                                                              &outPacketDescription);

            NSError *error = nil;

            if (status == kNoMoreDataError) {
                NSLog(@"%u bytes decoded", (unsigned int)decBuffer.mBuffers[0].mDataByteSize);
                [_decodedData appendData:[NSData dataWithBytes:decBuffer.mBuffers[0].mData length:decBuffer.mBuffers[0].mDataByteSize]];
                _currPosInDecoderBuf += 1;
            } else {
                error = [NSError errorWithDomain:NSOSStatusErrorDomain code:status userInfo:nil];
            }
        } else {
            break;
        }
    }
}

Each time, AudioConverterFillComplexBuffer returns status 1852797029 which is, according to Apple API, kAudioCodecIllegalOperationError. If somebody succeded in converting with such formats, please, share some examples, or advice.


问:
How to download Microsoft Academic Graph?
Is it possible to download the entire Microsoft Academic Graph? On this page they give a link but there are no download options there.

I know I can use API and I like it, but I am still curious about a download option.

答:
https://academicgraph.blob.core.windows.net/graph/index.html

it's apparently not possible anymore via single dump, you'll need an Azure subscription and go through the Cognitive Services API


问:
How to increment letters in javascript to next letter?
I want a function that I can go from A to B, B to C, Z to A.

My function is currently like so:

```<code>function nextChar(c) {
    return String.fromCharCode(c.charCodeAt(0) + 1);
}
nextChar('a');
</code>```

It works for A to X, but when I use Z... it goes to [ instead of A.

答:
Simple condition.

function nextChar(c) {
    var res = c == 'z' ? 'a' : c == 'Z' ? 'A' : String.fromCharCode(c.charCodeAt(0) + 1);
    console.log(res);
}
nextChar('Z');
nextChar('z');
nextChar('a');```

Body:
I want a function that I can go from A to B, B to C, Z to A.

My function is currently like so:

function nextChar(c) {
    return String.fromCharCode(c.charCodeAt(0) + 1);
}
nextChar('a');

It works for A to X, but when I use Z... it goes to [ instead of A.


问:
How can I convert OsStr to &[u8]/Vec<u8> on Windows?
I'm trying to persistent raw OS file names to storage, so I need to get the raw bytes of an OsStr.

It seems possible to call as_bytes() on *nix platforms, but that isn't defined on MS Windows.

Is there a portable way to convert OsStr to bytes?

答:
The point of OsStr is that its very representation is OS-specific. The implementation is somewhat convoluted for technical reasons (@Shepmaster's answer provides more details), but you can think of it like this:

on POSIX systems, OsStr boils down to &[u8], because POSIX functions accept and return byte strings;

on Windows, OsStr can be thought of as an &[u16], because Win32 Unicode functions accept and return strings as arrays of 16-bit units.

Since native Windows APIs accept sequences of 16-bit "wide characters"1, that is what OsStr is designed to store. While an OsStr could be converted to bytes inasmuch anything can be converted to bytes, such representation is not useful because those bytes would be neither meaningful to the user nor to the system. This is why OsStr does not provide a method to retrieve the contents as bytes on Windows. However, it does provide OsStr::encode_wide() that iterates over the underlying u16 values which is useful in Win32. In the other direction, OsString::from_wide() can be used to create an OsString from a slice of u16 values.

It is up to you to decide how your persistence layer will deal with this difference between platforms. What Rust's OsStr provides are the necessary tools to implement the round-trip, but the code will necessarily differ between platforms. For example, serde resolves the difference by effectively treating as enum OsString { Unix(Vec<u8>), Windows(Vec<u16>) }.

1 Windows wide character strings are sometimes described as UTF-16 because that is how they are interpreted at a higher level, but this is not correct for all OS strings. A Windows file name can contain pairs of u16 values that are not valid UTF-16, and still be usable. This is why it's not possible to represent Windows strings as bytes by e.g. converting them to UTF-8.


问:
Nested loops with conditions in javascript
I am working on a project where I want to create an array named full_day[] to be have an exactly equal length with an array time_plan[] after passing through my day_schedule().

Here is  my code:

function day_schedule(){

var time_plan = [{"lesson_start":"08:00","lesson_end":"09:00"},{"lesson_start":"09:00","lesson_end":"10:00"},{"lesson_start":"10:00","lesson_end":"11:00"},{"lesson_start":"11:00","lesson_end":"12:00"},{"lesson_start":"12:00","lesson_end":"13:00"},{"lesson_start":"13:00","lesson_end":"13:30"},{"lesson_start":"13:30","lesson_end":"14:30"}];

var day = [{"subject_name":"Math-1","lesson_start":"08:00","lesson_end":"09:00"},{"subject_name":"Phy","lesson_start":"11:00","lesson_end":"12:00"},{"subject_name":"Engl","lesson_start":"12:00","lesson_end":"13:00"}];

var key1 = 'lesson_start';
var key2 = 'lesson_end';
var full_day = [];

for (var d = 0; d < day.length; d++) {
                var start_time = day[d].lesson_start;
                var end_time = day[d].lesson_end;

                for (var i = 0; i < time_plan.length; i++) {
                        var search_key = time_plan[i][key1] == start_time && time_plan[i][key2] == end_time;
                        if (search_key == true) {
                            document.writeln('day matched == ' + day[d],'
');
                            full_day.push(day[d]);
                        } else {
                            full_day.push({
                                lesson_start: ' ',
                                lesson_end: ' ',
                                subject_name: ' '
                            });
                        }

                    }

                console.log('full day',full_day.length, full_day);

            }
}

day_schedule();```
</div>
</div>
</p>

<p>i'm expecting a result of</p>

```full day 7 [
  {
    "subject_name": "Math-1",
    "lesson_start": "08:00",
    "lesson_end": "09:00"
  },
  {
    "lesson_start": " ",
    "lesson_end": " ",
    "subject_name": " "
  },
  {
    "lesson_start": " ",
    "lesson_end": " ",
    "subject_name": " "
  },
  {
    "subject_name": "Phy",
    "lesson_start": "11:00",
    "lesson_end": "12:00"
  },
  {
    "subject_name": "Engl",
    "lesson_start": "12:00",
    "lesson_end": "13:00"
  },
  {
    "lesson_start": " ",
    "lesson_end": " ",
    "subject_name": " "
  },
  {
    "lesson_start": " ",
    "lesson_end": " ",
    "subject_name": " "
  }
];
```

but i cant figure how to do it.

答:
You got the iterations all wrong if you want full_day size to match time_plan.
What you're doing in your code is iterate each element in day (3 elements) and for each one of these elements add an object to full_day for each element in time_plan (7 elements).
So what you get is:

First element in day you add 7 objects to full_day (7 elements)

Secon element in day you add another 7 objects to full_day (14 elements)

Third element in day you add again 7 objects to full_day (21 elements)

If you want to keep the logic you used, I'd suggest you turn your loops the other way around like this:

function day_schedule(){
    var time_plan = [{"lesson_start":"08:00","lesson_end":"09:00"},
                     {"lesson_start":"09:00","lesson_end":"10:00"},
                     {"lesson_start":"10:00","lesson_end":"11:00"},
                     {"lesson_start":"11:00","lesson_end":"12:00"},
                     {"lesson_start":"12:00","lesson_end":"13:00"},
                     {"lesson_start":"13:00","lesson_end":"13:30"},
                     {"lesson_start":"13:30","lesson_end":"14:30"}];

    var day =[{
                  "subject_name":"Math1",
                  "lesson_start":"08:00",
                  "lesson_end":"09:00"
              },
              {
                  "subject_name":"Phy",
                  "lesson_start":"11:00",
                  "lesson_end":"12:00"
              },
              {
                  "subject_name":"Engl",
                  "lesson_start":"12:00",
                  "lesson_end":"13:00"
    }];

    var key1 = 'lesson_start';
    var key2 = 'lesson_end';
    var full_day = [];

    for (var tp = 0; tp < time_plan.length; tp++) {
        var start_time = time_plan[tp].lesson_start;
        var end_time = time_plan[tp].lesson_end;
        var lesson = {
            lesson_start: ' ',
            lesson_end: ' ',
            subject_name: ' '
        };
        for (var i = 0; i < day.length; i++) {
            var search_key = day[i][key1] == start_time && day[i][key2] == end_time;
            if (search_key == true) {
                lesson = day[i]
            }
        }
        full_day.push(lesson)
    }
    console.log('full day',full_day.length, full_day);
}

day_schedule();```
</div>
</div>
</p>

<p>As you see, this gives the desired output.
Now, we could also fix the code a bit to make it prettier and use some useful JavaScript <code>Array</code> function like <code>find()</code></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function day_schedule(){
    var time_plan = [{"lesson_start":"08:00","lesson_end":"09:00"},
                     {"lesson_start":"09:00","lesson_end":"10:00"},
                     {"lesson_start":"10:00","lesson_end":"11:00"},
                     {"lesson_start":"11:00","lesson_end":"12:00"},
                     {"lesson_start":"12:00","lesson_end":"13:00"},
                     {"lesson_start":"13:00","lesson_end":"13:30"},
                     {"lesson_start":"13:30","lesson_end":"14:30"}
        ];
    var day =[{
                  "subject_name":"Math1",
                  "lesson_start":"08:00",
                  "lesson_end":"09:00"
              },
              {
                  "subject_name":"Phy",
                  "lesson_start":"11:00",
                  "lesson_end":"12:00"
              },
              {
                  "subject_name":"Engl",
                  "lesson_start":"12:00",
                  "lesson_end":"13:00"
        }];
    var full_day = [];

    // Use foreach instead of regular for when you iterate arrays
    for (tp in time_plan) {
        var plan = time_plan[tp]
        var start_time = plan.lesson_start;
        var end_time = plan.lesson_end;
        // Use this function to find a suitable lesson given start and end times
        var lesson = day.find(function(d) {
            var start_matches = d.lesson_start == start_time;
            var end_matches = d.lesson_end == end_time;
            var matches = start_matches && end_matches;
            return start_matches && end_matches;
        }) || { // ... or assing a default empty value
            lesson_start: ' ',
            lesson_end: ' ',
            subject_name: ' '
        };
        full_day.push(lesson)
    }
    console.log('full day',full_day.length, full_day);
}

day_schedule();</code>```

Hope this helps.

Body:
I am working on a project where I want to create an array named full_day[] to be have an exactly equal length with an array time_plan[] after passing through my day_schedule().

Here is  my code:

function day_schedule(){

var time_plan = [{"lesson_start":"08:00","lesson_end":"09:00"},{"lesson_start":"09:00","lesson_end":"10:00"},{"lesson_start":"10:00","lesson_end":"11:00"},{"lesson_start":"11:00","lesson_end":"12:00"},{"lesson_start":"12:00","lesson_end":"13:00"},{"lesson_start":"13:00","lesson_end":"13:30"},{"lesson_start":"13:30","lesson_end":"14:30"}];

var day = [{"subject_name":"Math-1","lesson_start":"08:00","lesson_end":"09:00"},{"subject_name":"Phy","lesson_start":"11:00","lesson_end":"12:00"},{"subject_name":"Engl","lesson_start":"12:00","lesson_end":"13:00"}];

var key1 = 'lesson_start';
var key2 = 'lesson_end';
var full_day = [];

for (var d = 0; d < day.length; d++) {
                var start_time = day[d].lesson_start;
                var end_time = day[d].lesson_end;

                for (var i = 0; i < time_plan.length; i++) {
                        var search_key = time_plan[i][key1] == start_time && time_plan[i][key2] == end_time;
                        if (search_key == true) {
                            document.writeln('day matched == ' + day[d],'
');
                            full_day.push(day[d]);
                        } else {
                            full_day.push({
                                lesson_start: ' ',
                                lesson_end: ' ',
                                subject_name: ' '
                            });
                        }

                    }

                console.log('full day',full_day.length, full_day);

            }
}

day_schedule();

i'm expecting a result of

full day 7 [
  {
    "subject_name": "Math-1",
    "lesson_start": "08:00",
    "lesson_end": "09:00"
  },
  {
    "lesson_start": " ",
    "lesson_end": " ",
    "subject_name": " "
  },
  {
    "lesson_start": " ",
    "lesson_end": " ",
    "subject_name": " "
  },
  {
    "subject_name": "Phy",
    "lesson_start": "11:00",
    "lesson_end": "12:00"
  },
  {
    "subject_name": "Engl",
    "lesson_start": "12:00",
    "lesson_end": "13:00"
  },
  {
    "lesson_start": " ",
    "lesson_end": " ",
    "subject_name": " "
  },
  {
    "lesson_start": " ",
    "lesson_end": " ",
    "subject_name": " "
  }
];

but i cant figure how to do it.

Body:
You got the iterations all wrong if you want full_day size to match time_plan.
What you're doing in your code is iterate each element in day (3 elements) and for each one of these elements add an object to full_day for each element in time_plan (7 elements).
So what you get is:

First element in day you add 7 objects to full_day (7 elements)

Secon element in day you add another 7 objects to full_day (14 elements)

Third element in day you add again 7 objects to full_day (21 elements)

If you want to keep the logic you used, I'd suggest you turn your loops the other way around like this:

function day_schedule(){
    var time_plan = [{"lesson_start":"08:00","lesson_end":"09:00"},
                     {"lesson_start":"09:00","lesson_end":"10:00"},
                     {"lesson_start":"10:00","lesson_end":"11:00"},
                     {"lesson_start":"11:00","lesson_end":"12:00"},
                     {"lesson_start":"12:00","lesson_end":"13:00"},
                     {"lesson_start":"13:00","lesson_end":"13:30"},
                     {"lesson_start":"13:30","lesson_end":"14:30"}];

    var day =[{
                  "subject_name":"Math1",
                  "lesson_start":"08:00",
                  "lesson_end":"09:00"
              },
              {
                  "subject_name":"Phy",
                  "lesson_start":"11:00",
                  "lesson_end":"12:00"
              },
              {
                  "subject_name":"Engl",
                  "lesson_start":"12:00",
                  "lesson_end":"13:00"
    }];

    var key1 = 'lesson_start';
    var key2 = 'lesson_end';
    var full_day = [];

    for (var tp = 0; tp < time_plan.length; tp++) {
        var start_time = time_plan[tp].lesson_start;
        var end_time = time_plan[tp].lesson_end;
        var lesson = {
            lesson_start: ' ',
            lesson_end: ' ',
            subject_name: ' '
        };
        for (var i = 0; i < day.length; i++) {
            var search_key = day[i][key1] == start_time && day[i][key2] == end_time;
            if (search_key == true) {
                lesson = day[i]
            }
        }
        full_day.push(lesson)
    }
    console.log('full day',full_day.length, full_day);
}

day_schedule();

As you see, this gives the desired output.
Now, we could also fix the code a bit to make it prettier and use some useful JavaScript Array function like find()

function day_schedule(){
    var time_plan = [{"lesson_start":"08:00","lesson_end":"09:00"},
                     {"lesson_start":"09:00","lesson_end":"10:00"},
                     {"lesson_start":"10:00","lesson_end":"11:00"},
                     {"lesson_start":"11:00","lesson_end":"12:00"},
                     {"lesson_start":"12:00","lesson_end":"13:00"},
                     {"lesson_start":"13:00","lesson_end":"13:30"},
                     {"lesson_start":"13:30","lesson_end":"14:30"}
        ];
    var day =[{
                  "subject_name":"Math1",
                  "lesson_start":"08:00",
                  "lesson_end":"09:00"
              },
              {
                  "subject_name":"Phy",
                  "lesson_start":"11:00",
                  "lesson_end":"12:00"
              },
              {
                  "subject_name":"Engl",
                  "lesson_start":"12:00",
                  "lesson_end":"13:00"
        }];
    var full_day = [];

    // Use foreach instead of regular for when you iterate arrays
    for (tp in time_plan) {
        var plan = time_plan[tp]
        var start_time = plan.lesson_start;
        var end_time = plan.lesson_end;
        // Use this function to find a suitable lesson given start and end times
        var lesson = day.find(function(d) {
            var start_matches = d.lesson_start == start_time;
            var end_matches = d.lesson_end == end_time;
            var matches = start_matches && end_matches;
            return start_matches && end_matches;
        }) || { // ... or assing a default empty value
            lesson_start: ' ',
            lesson_end: ' ',
            subject_name: ' '
        };
        full_day.push(lesson)
    }
    console.log('full day',full_day.length, full_day);
}

day_schedule();

Hope this helps.


问:
Cartesian product data frame
I have three or more independent variables represented as R vectors, like so:

```<code>A <- c(1,2,3)
B <- factor(c('x','y'))
C <- c(0.1,0.5)
</code>```

and I want to take the Cartesian product of all of them and put the result into a data frame, like this:

```<code>A B C
1 x 0.1
1 x 0.5
1 y 0.1
1 y 0.5
2 x 0.1
2 x 0.5
2 y 0.1
2 y 0.5
3 x 0.1
3 x 0.5
3 y 0.1
3 y 0.5
</code>```

I can do this by manually writing out calls to rep:

```<code>d <- data.frame(A = rep(A, times=length(B)*length(C)),
                B = rep(B, times=length(A), each=length(C)),
                C = rep(C, each=length(A)*length(B))
</code>```

but there must be a more elegant way to do it, yes?  product in itertools does part of the job, but I can't find any way to absorb the output of an iterator and put it into a data frame.  Any suggestions?

p.s. The next step in this calculation looks like

```<code>d$D <- f(d$A, d$B, d$C)
</code>```

so if you know a way to do both steps at once, that would also be helpful.

答:
Here's a way to do both, using Ramnath's suggestion of expand.grid:

```<code>f <- function(x,y,z) paste(x,y,z,sep="+")
d <- expand.grid(x=A, y=B, z=C)
d$D <- do.call(f, d)
</code>```

Note that do.call works on d "as-is" because a data.frame is a list.  But do.call expects the column names of d to match the argument names of f.

ContentLicense: CC BY-SA 4.0

Title: Cartesian product data frame

Body:
I have three or more independent variables represented as R vectors, like so:

A <- c(1,2,3)
B <- factor(c('x','y'))
C <- c(0.1,0.5)

and I want to take the Cartesian product of all of them and put the result into a data frame, like this:

A B C
1 x 0.1
1 x 0.5
1 y 0.1
1 y 0.5
2 x 0.1
2 x 0.5
2 y 0.1
2 y 0.5
3 x 0.1
3 x 0.5
3 y 0.1
3 y 0.5

I can do this by manually writing out calls to rep:

d <- data.frame(A = rep(A, times=length(B)*length(C)),
                B = rep(B, times=length(A), each=length(C)),
                C = rep(C, each=length(A)*length(B))

but there must be a more elegant way to do it, yes?  product in itertools does part of the job, but I can't find any way to absorb the output of an iterator and put it into a data frame.  Any suggestions?

p.s. The next step in this calculation looks like

d$D <- f(d$A, d$B, d$C)

so if you know a way to do both steps at once, that would also be helpful.

Body:
Here's a way to do both, using Ramnath's suggestion of expand.grid:

f <- function(x,y,z) paste(x,y,z,sep="+")
d <- expand.grid(x=A, y=B, z=C)
d$D <- do.call(f, d)

Note that do.call works on d "as-is" because a data.frame is a list.  But do.call expects the column names of d to match the argument names of f.

ContentLicense: CC BY-SA 2.5


问:
jQuery how to dynamically add a textbox with increment ID?
I am building a form solely with JavaScript and jQuery. I am unable to connect to any servers, so I am unable to use any PHP script at all.

How to add more and remove textboxes with an "add more"and "x" (for remove) buttons that also increments the ID's so I can capture the individual values associated with each ID and use them later in a variable.

I have seen and tested several working examples of dynamically adding more textboxes but they don't have an incrementing ID

Any suggestions would be very helpful.

答:
function addMore(){
  var inps = $('#wrapper > div:last').data('count')+1 || 0;
  $('#wrapper').append('
<input type=text id="count'+inps+'" class="inp"/> X
');
}

$('#wrapper').on('click' , 'a.remove' ,function(){
  $(this).closest('div').remove();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id=wrapper>
  </div>
<button id=add onclick="addMore()">Add More</button></code>```

function addMore(){
  var inps = $('#wrapper > div:last').data('count')+1 || 0;
  $('#wrapper').append('
<input type=text id="count'+inps+'" class="inp"/> X
');
}

$('#wrapper').on('click' , 'a.remove' ,function(){
  $(this).closest('div').remove();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id=wrapper>
  </div>
<button id=add onclick="addMore()">Add More</button></code>```

function addMore(){
  var inps = $('#wrapper > div:last').data('count')+1 || 0;
  $('#wrapper').append('
<input type=text id="count'+inps+'" class="inp"/> X
');
}

$('#wrapper').on('click' , 'a.remove' ,function(){
  $(this).closest('div').remove();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id=wrapper>
  </div>
<button id=add onclick="addMore()">Add More</button></code>```

Body:
function addMore(){
  var inps = $('#wrapper > div:last').data('count')+1 || 0;
  $('#wrapper').append('<div data-count="'+inps+'"><input type=text id="count'+inps+'" class="inp"/> <a class=remove>X</a></div>');
}

$('#wrapper').on('click' , 'a.remove' ,function(){
  $(this).closest('div').remove();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id=wrapper>
  </div>
<button id=add onclick="addMore()">Add More</button>

function addMore(){
  var inps = $('#wrapper > div:last').data('count')+1 || 0;
  $('#wrapper').append('<div data-count="'+inps+'"><input type=text id="count'+inps+'" class="inp"/> <a class=remove>X</a></div>');
}

$('#wrapper').on('click' , 'a.remove' ,function(){
  $(this).closest('div').remove();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id=wrapper>
  </div>
<button id=add onclick="addMore()">Add More</button>

function addMore(){
  var inps = $('#wrapper > div:last').data('count')+1 || 0;
  $('#wrapper').append('<div data-count="'+inps+'"><input type=text id="count'+inps+'" class="inp"/> <a class=remove>X</a></div>');
}

$('#wrapper').on('click' , 'a.remove' ,function(){
  $(this).closest('div').remove();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id=wrapper>
  </div>
<button id=add onclick="addMore()">Add More</button>


问:
Executing data validation rules from a table using a procedure with runtime values
I have a table that is filled with many data validation queries. For example a row:

```<code>SELECT end_time - start_time
FROM mt_process_status
WHERE process_id = <PROCESS_ID> AND ref_date = <REF_DATE>
</code>```

I have to execute all these SQL statements filling the values within '<>' with run time values and check if the performance of the process has not changed.

Can this be done with a stored procedure? I want to understand what the solution would look like.  Any links to documentation of this sort of thing, anything to guide me in the right direction.

答:
```<code>CREATE OR REPLACE PROCEDURE MY_PROC(g_id)
AS
l_query varchar2(1000);
l_duration number;

BEGIN
-- Get the query from the table
select query into l_query from my_table where id=g_id;

-- l_query contains "select end_time - start_time from mt_process_status where process_id = <PROCESS_ID> and ref_date = <REF_DATE>"

-- Put value to replace the tags (take care of code injection...)
l_query := REPLACE(l_query,'<PROCESS_ID>', something);
l_query := REPLACE(l_query,'<REF_DATE>', something_else);

EXECUTE IMMEDIATE lquery RETURN INTO l_duration;

-- Do what you have to do...
-- If you do a function, then you can:
-- RETURN l_duration;

END;
/
</code>```

Your question is not clear. This is the answer to your question. Use variables in a procedure.

regards.

Body:
I have a table that is filled with many data validation queries. For example a row:

SELECT end_time - start_time
FROM mt_process_status
WHERE process_id = <PROCESS_ID> AND ref_date = <REF_DATE>

I have to execute all these SQL statements filling the values within '<>' with run time values and check if the performance of the process has not changed.

Can this be done with a stored procedure? I want to understand what the solution would look like.  Any links to documentation of this sort of thing, anything to guide me in the right direction.

Body:
CREATE OR REPLACE PROCEDURE MY_PROC(g_id)
AS
l_query varchar2(1000);
l_duration number;

BEGIN
-- Get the query from the table
select query into l_query from my_table where id=g_id;

-- l_query contains "select end_time - start_time from mt_process_status where process_id = <PROCESS_ID> and ref_date = <REF_DATE>"

-- Put value to replace the tags (take care of code injection...)
l_query := REPLACE(l_query,'<PROCESS_ID>', something);
l_query := REPLACE(l_query,'<REF_DATE>', something_else);

EXECUTE IMMEDIATE lquery RETURN INTO l_duration;

-- Do what you have to do...
-- If you do a function, then you can:
-- RETURN l_duration;

END;
/

Your question is not clear. This is the answer to your question. Use variables in a procedure.

regards.


问:
Crash for second view object's name assign
I am new to Xamarin and MVVMCross. So I have created 2 views. Login and Register. I have a button on Login to goto Register view and I am going there by this code in the Login's ViewModel:

```<code>// method when user tap register button
public IMvxCommand NavigateRegister
{
    get { return new MvxCommand(() => ShowViewModel<RegisterViewModel>()); }
}
</code>```

It works ok the Register Page opens well. But once I assign Name for a single object on Register view (a textEdit), the app crash when I tap on the Register button.

Below is the error msg:

Xamarin.iOS: Received unhandled ObjectiveC exception:
  NSUnknownKeyException [
  setValue:forUndefinedKey:]: this class is not key value
  coding-compliant for the key regNameEdit.

EDIT:
More details: I already assigned the name (see pic below), but still crash:

And the view also been assigned to its Class "CreateAccount". But I am noticing the class declaration has "partial" darkened out in the "public partial class CreateAccount : MvxViewController" line. That's the only noticeable difference btw this class and the first one.

```<code>using MvvmCross.Binding.BindingContext;
using MvvmCross.iOS.Views;

namespace MyApp.iOS.Views
{
    public partial class CreateAccount : MvxViewController
    {
        public CreateAccount() : base("CreateAccount", null)
        {
        }

        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            // Perform any additional setup after loading the view, typically from a nib.

            Title = "Register";

            var set = this.CreateBindingSet<CreateAccount, Core.ViewModels.CreateAccountModel>();
            set.Bind(regNameEdit).To(vm => vm.NameStr);
        }

        public override void DidReceiveMemoryWarning()
        {
            base.DidReceiveMemoryWarning();
            // Release any cached data, images, etc that aren't in use.
        }
    }
}
</code>```

The Bind(regNameEdit) also is an error (not detecting the textedit still)

答:
This usually means that the a control is not defined in the View/ViewController class in your case the regNameEdit.

Make sure you created the back Property for this Edit and that the class assigned to the XIB is the one containing this property.

If you are using Xamarin Studio Designer you create the back property selecting the UIControl in the XIB/StoryBoard and setting a name, then enter.

This will create a property with the name you specified accessible in the ViewController.

```<code>public override void ViewDidLoad()
{
    base.ViewDidLoad();

    this.MyUITextField.Text = string.Empty;
}
</code>```

UPDATE

When using Storyboard:

Try this: Remove the name from the TextField and also remove the name from the ViewController class, then clean your project and rebuild. Re-add the class to the ViewController but when doing it click over the yellow icon in the bottom, there put the name and hit enter. Continue with the TextField, select it put the name and hit enter.

UPDATE # 2

When using XIBs
When you create the ViewController from the menu, Xamarin Studio will create both the ViewController class and the XIB file and will associate one with the other so here you don't have to do anything else to link them.

For the TextField you will need to do it adding the name as previously indicated.

Try this: Remove the name of the UITextField and save and clean/rebuild the project then add the name and hit enter.

Something you can do to verify if there's any problem, double click on the button in the XIB and this should take you to the ViewController class to create a method.

Hope this helps.

Body:
I am new to Xamarin and MVVMCross. So I have created 2 views. Login and Register. I have a button on Login to goto Register view and I am going there by this code in the Login's ViewModel:

// method when user tap register button
public IMvxCommand NavigateRegister
{
    get { return new MvxCommand(() => ShowViewModel<RegisterViewModel>()); }
}

It works ok the Register Page opens well. But once I assign Name for a single object on Register view (a textEdit), the app crash when I tap on the Register button.

Below is the error msg:

Xamarin.iOS: Received unhandled ObjectiveC exception:
  NSUnknownKeyException [
  setValue:forUndefinedKey:]: this class is not key value
  coding-compliant for the key regNameEdit.

EDIT:
More details: I already assigned the name (see pic below), but still crash:

And the view also been assigned to its Class "CreateAccount". But I am noticing the class declaration has "partial" darkened out in the "public partial class CreateAccount : MvxViewController" line. That's the only noticeable difference btw this class and the first one.

using MvvmCross.Binding.BindingContext;
using MvvmCross.iOS.Views;

namespace MyApp.iOS.Views
{
    public partial class CreateAccount : MvxViewController
    {
        public CreateAccount() : base("CreateAccount", null)
        {
        }

        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            // Perform any additional setup after loading the view, typically from a nib.

            Title = "Register";

            var set = this.CreateBindingSet<CreateAccount, Core.ViewModels.CreateAccountModel>();
            set.Bind(regNameEdit).To(vm => vm.NameStr);
        }

        public override void DidReceiveMemoryWarning()
        {
            base.DidReceiveMemoryWarning();
            // Release any cached data, images, etc that aren't in use.
        }
    }
}

The Bind(regNameEdit) also is an error (not detecting the textedit still)

Body:
This usually means that the a control is not defined in the View/ViewController class in your case the regNameEdit.

Make sure you created the back Property for this Edit and that the class assigned to the XIB is the one containing this property.

If you are using Xamarin Studio Designer you create the back property selecting the UIControl in the XIB/StoryBoard and setting a name, then enter.

This will create a property with the name you specified accessible in the ViewController.

public override void ViewDidLoad()
{
    base.ViewDidLoad();

    this.MyUITextField.Text = string.Empty;
}

UPDATE

When using Storyboard:

Try this: Remove the name from the TextField and also remove the name from the ViewController class, then clean your project and rebuild. Re-add the class to the ViewController but when doing it click over the yellow icon in the bottom, there put the name and hit enter. Continue with the TextField, select it put the name and hit enter.

UPDATE # 2

When using XIBs
When you create the ViewController from the menu, Xamarin Studio will create both the ViewController class and the XIB file and will associate one with the other so here you don't have to do anything else to link them.

For the TextField you will need to do it adding the name as previously indicated.

Try this: Remove the name of the UITextField and save and clean/rebuild the project then add the name and hit enter.

Something you can do to verify if there's any problem, double click on the button in the XIB and this should take you to the ViewController class to create a method.

Hope this helps.


问:
Turn off email notification - iTunes Connect
Anyone know a way to disable email notification when app status changes? I have 10+ internal testers and don't want them to be spammed by email whenever app status is changed.

Edit: All users have no territories in for all options Notification Tab.

答:
This can be done by setting iTunesConnect -> Users And Roles -> User name -> Notifications -> App Status Reports to "No Territories"

Hope this helps.

Kind regards,

Mukund


问:
looping and iteration in logstash
I have a list data in Logstash that has been parsed as that looks like:

```<code>"Attribute": [

"<Book><Name>N1</Name><Value>Clement</Value></Book>",

"<Book><Name>N2</Name><Value>Bundle Name</Value></Book>"

],
</code>```

I want to loop over that list to generate the following data in ouput:

```<code>"book1":{

"key": "N1",

"value":"Clement"

},

"book2":{

"key": "N2",

"value":"Bundle Name"
}
</code>```

Is it possible to do that?
Thanks for any help. I really appreciate it.

答:
This can likely be done with the split {} filter.

```<code>filter {
  split {
    field => "Attribute"
    target => "book_bundle"
    add_tags => [ "split_out" ]
  }
}
</code>```

Which will take your source event, clone it into N new events, where N is the number of members of the Attribute array. The array member will be put into the book_bundle field, and the tag split_out added so you can tell it's already been split later down the filter stack.

Title: looping and iteration in logstash

Body:
I have a list data in Logstash that has been parsed as that looks like:

"Attribute": [

"<Book><Name>N1</Name><Value>Clement</Value></Book>",

"<Book><Name>N2</Name><Value>Bundle Name</Value></Book>"

],

I want to loop over that list to generate the following data in ouput:

"book1":{

"key": "N1",

"value":"Clement"

},

"book2":{

"key": "N2",

"value":"Bundle Name"
}

Is it possible to do that?
Thanks for any help. I really appreciate it.

Body:
This can likely be done with the split {} filter.

filter {
  split {
    field => "Attribute"
    target => "book_bundle"
    add_tags => [ "split_out" ]
  }
}

Which will take your source event, clone it into N new events, where N is the number of members of the Attribute array. The array member will be put into the book_bundle field, and the tag split_out added so you can tell it's already been split later down the filter stack.


问:
divide vector containing sequences with increment 1
I have a vector that contains several sequences with an increment of one, e.g.

```<code>in = [1:5 8:14 16:20 23:40]
</code>```

For each of this sequences I would like to extract the start- and the endpoint of the sequence, i.e for above example I would get

```<code>out = [1 5; 8 14; 16 20; 23 40]
</code>```

Of course, this can be done with a combination of for-loops and if-conditions, but that would not be very efficient and readable. Is there any more matlab-ish way to achieve this?

答:
You can use diff to find where the runs stop and start and then use the resulting logical array (and a circularly shifted version of the logical array) to index into in to yield out

```<code>% Create a logical array that is TRUE at the beginning of each new run
starts = [true, diff(in) ~= 1];
%  1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

% Use that array to index into IN and shift it to index into IN again
out = [in(starts); in(circshift(starts, [0 -1]))].';

%     1     5
%     8    14
%    16    20
%    23    40
</code>```

Body:
I have a vector that contains several sequences with an increment of one, e.g.

in = [1:5 8:14 16:20 23:40]

For each of this sequences I would like to extract the start- and the endpoint of the sequence, i.e for above example I would get

out = [1 5; 8 14; 16 20; 23 40]

Of course, this can be done with a combination of for-loops and if-conditions, but that would not be very efficient and readable. Is there any more matlab-ish way to achieve this?

Body:
You can use diff to find where the runs stop and start and then use the resulting logical array (and a circularly shifted version of the logical array) to index into in to yield out

% Create a logical array that is TRUE at the beginning of each new run
starts = [true, diff(in) ~= 1];
%  1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

% Use that array to index into IN and shift it to index into IN again
out = [in(starts); in(circshift(starts, [0 -1]))].';

%     1     5
%     8    14
%    16    20
%    23    40


问:
how C_CreateObject , C_GenerateKey and C_GenerateKeyPair are different ?
Our PKCS#11 library miss the implementation of C_CreateObject. Before jumping into its implementation, i want to know the instances where C_CreateObject should be used instead of C_GenerateKey/C_GenerateKeyPair .</p>

答:
The PKCS#11 treats the Key Pairs (Public Key and Private Key), Certificates and Secret Keys as objects on the token. And there is also a Data Object which just holds some data.

The C_GenerateKey would create a Secret Key Object.

The C_GenerateKeyPair would create a Public Key and a Private Key Object (both the public key and private key combined would constitute the key pair).

When you say C_GenerateKey the PKCS#11 knows that it has to generate a Secret Key Object and expects a Secret Key Object Template. And similarly the C_GenerateKeyPair, it knows that it has to create a Public Key Object and a Private Key Object and expects their respective object templates.

But when you sayC_CreateObject, you have to specify which type of object you want to create, and pass in the right Object Template as well. Consider this like an abstract version of the C_GenerateXXX method.


问:
Connect to informix with python's ibm_db
I'm pretty new to python. I'm trying to connect to an informix server using python and ibm_db.connect(). However I can't seem to succeed and the error messages don't help.

Using java and jdbc I can connect successfully with the following connection url:

jdbc:informix-sqli://10.20.30.40:1234/mydb:INFORMIXSERVER=foo_bar;USER=user;PASSWORD=pass;

My attempt at using ibm_db is:

```<code>ibm_db.connect('HOSTNAME=10.20.30.40;PORT=1234;DATABASE=mydb;PROTOCOL=ONSOCTCP;UID=user;PASSWORD=pass;', '', '')
</code>```

But it gives an error (Exception: [IBM][CLI Driver] SQL0902C  A system error occurred. Subsequent SQL statements cannot be processed. IBM software support reason code: "".  SQLSTATE=58005)

I would like if possible an equivalent string I can put in as the first argument to

```<code>ibm_db.connect('', '', '')
</code>```

So I can connect with python.

答:
Protocol onsoctcp is not supported by ibm_db.

Please check https://www.ibm.com/support/knowledgecenter/SSGU8G_11.50.0/com.ibm.admin.doc/ids_admin_0207.htm, This can help you to configure a DDRA (tcpip) access to your database.

Body:
I'm pretty new to python. I'm trying to connect to an informix server using python and ibm_db.connect(). However I can't seem to succeed and the error messages don't help.

Using java and jdbc I can connect successfully with the following connection url:

jdbc:informix-sqli://10.20.30.40:1234/mydb:INFORMIXSERVER=foo_bar;USER=user;PASSWORD=pass;

My attempt at using ibm_db is:

ibm_db.connect('HOSTNAME=10.20.30.40;PORT=1234;DATABASE=mydb;PROTOCOL=ONSOCTCP;UID=user;PASSWORD=pass;', '', '')

But it gives an error (Exception: [IBM][CLI Driver] SQL0902C  A system error occurred. Subsequent SQL statements cannot be processed. IBM software support reason code: "".  SQLSTATE=58005)

I would like if possible an equivalent string I can put in as the first argument to

ibm_db.connect('', '', '')

So I can connect with python.


答:
function nextLetter(s){
    return s.replace(/([a-zA-Z])[^a-zA-Z]*$/, function(a){
        var c= a.charCodeAt(0);
        switch(c){
            case 90: return 'A';
            case 122: return 'a';
            default: return String.fromCharCode(++c);
        }
    });
}

console.log("nextLetter('z'): ", nextLetter('z'));

console.log("nextLetter('Z'): ", nextLetter('Z'));

console.log("nextLetter('x'): ", nextLetter('x'));```

Reference

Title: How to increment letters in javascript to next letter?

Body:
function nextLetter(s){
    return s.replace(/([a-zA-Z])[^a-zA-Z]*$/, function(a){
        var c= a.charCodeAt(0);
        switch(c){
            case 90: return 'A';
            case 122: return 'a';
            default: return String.fromCharCode(++c);
        }
    });
}

console.log("nextLetter('z'): ", nextLetter('z'));

console.log("nextLetter('Z'): ", nextLetter('Z'));

console.log("nextLetter('x'): ", nextLetter('x'));

Reference


问:
What is the difference between YAML and JSON?
What are the differences between YAML and JSON, specifically considering the following things?

Performance (encode/decode time)

Memory consumption

Expression clarity

Library availability, ease of use (I prefer C)

I was planning to use one of these two in our embedded system to store configure files.

Related:

Should I use YAML or JSON to store my Perl data?

答:
Sometimes you don't have to decide for one over the other.

In Go, for example, you can have both at the same time:

```<code>type Person struct {
    Name string `json:"name" yaml:"name"`
    Age int `json:"age" yaml:"age"`
}
</code>```

Body:
Sometimes you don't have to decide for one over the other.

In Go, for example, you can have both at the same time:

type Person struct {
    Name string `json:"name" yaml:"name"`
    Age int `json:"age" yaml:"age"`
}


问:
Get result from promise resolve in another async function
I'm trying to get the promise resolve result when it ends the Promise in the first function (topromise). Therefore as you'll see below I'm creating another Promise.resolve(pageData) with the value from the last then to try to get the value in my getpromise function.

This is my code:

function topromise(param){
  let pageData;
  new Promise((resolve, reject)=>{
  resolve(param)
})

.then((value)=>{
  console.log(value)
  return "hola"
})

.then((value)=>{
  console.log(value)
  pageData= "bon jour"
  return getpromise(Promise.resolve(pageData))
})

}

topromise("hello")

function getpromise(value){
  .then(value=> console.log(value))
  //I want to get the pageData result from resolve
}```

答:
Your topromise() function is missing a return, and your getpromise function seems to begin in the middle of a method call.

It's very unclear what you're trying to do, but maybe you're going for something like this. This is working code:

function topromise(param){
  let pageData;

  return Promise.resolve(param)
  .then((value)=>{
    console.log(value)
    return "hola"
  })
  .then((value)=>{
    console.log(value)
    pageData = "bon jour"
    return pageData;
  })
}

getpromise(topromise("hello"))

function getpromise(value){
  value
  .then(result => console.log(result))
}```


问:
Is it possible to find a list of all hijacked files in a view in CCRC?
In the ClearCase Remote Client is it possible to find a list of all hijacked files in a given view?</p>

答: Right-click on your view and select Show Pending Changes. All of your hijacked files will be displayed at the top of the list under the heading Hijacked Resources.


问:
liferay 7 - Mismatched anonymous define()
I'm trying to include sockjs (v1.1.2) in my liferay 7 portlet, but I'm receiving this warning:

```<code>Mismatched anonymous define() module: function ()...
</code>```

and then the library isn't loaded.

I directly included the .js file in my liferay-portlet.xml like this:

```<code><header-portlet-javascript>/common/js/sockjs.js</header-portlet-javascript>
</code>```

I don't have any idea to make it work

答:
Looks like you are running into an issue that's been fixed by LPS-68298. If you are using Liferay 7.0 DXP SP2+ or Liferay 7.0 CE GA4+ you can simply open the administration sidebar and select Control Panel > Configuration > System Settings > Foundation > JavaScript Loader > Uncheck Expose Global. If you aren't using one of the above Liferay versions, you need to follow the advice of this answer and disable the AMD loader before loading your script, then re-enable the AMD loader. Alternatively, you can fix this by manually editing your JS file. Change any text in /common/js/sockjs.js like:

```<code>typeof define == 'function'
</code>```

To:

```<code>false && typeof define == 'function'
</code>```

This will stop the file from being loaded by Liferay's AMD loader.

Body:
I'm trying to include sockjs (v1.1.2) in my liferay 7 portlet, but I'm receiving this warning:

Mismatched anonymous define() module: function ()...

and then the library isn't loaded.

I directly included the .js file in my liferay-portlet.xml like this:

/common/js/sockjs.js

I don't have any idea to make it work

Body:
Looks like you are running into an issue that's been fixed by LPS-68298. If you are using Liferay 7.0 DXP SP2+ or Liferay 7.0 CE GA4+ you can simply open the administration sidebar and select Control Panel > Configuration > System Settings > Foundation > JavaScript Loader > Uncheck Expose Global. If you aren't using one of the above Liferay versions, you need to follow the advice of this answer and disable the AMD loader before loading your script, then re-enable the AMD loader. Alternatively, you can fix this by manually editing your JS file. Change any text in /common/js/sockjs.js like:

typeof define == 'function'

To:

false && typeof define == 'function'

This will stop the file from being loaded by Liferay's AMD loader.


问:
How do you fetch a remote branch without "checking it out"
I am working on a branch "branch-A" and using the command git branch I can see that its the only branch locally.

If I use git branch -a I can see the remote copy of "remotes/origin/branch-B"

What I want to do is bring branch-B locally, but I don't want to actually check it out... I mean I could do that and then checkout my other branch to go back, but its slightly more painful since I am doing this to lots of repos.

I was thinking some sort of fetch? but I can't figure out how to phrase the command. Is it possible?

So I have:

```<code>user@pc> git branch
* branch-A
  master
</code>```

and

```<code>user@pc> git branch -a
* branch-A
  remotes/origin/branch-B
  remotes/origin/branch-A
  remotes/origin/master
</code>```

I want to be able to get:

```<code>user@pc> git branch
* branch-A
  branch-B
  master
</code>```

答:
You can run a script to create new local branches with the name of all remote branches.

```<code>$ git fetch
$ for branch in `git branch -r | sed 's@origin/@ @'`;do `git branch  $branch origin/$branch`;done
</code>```

git branch -r shows all the remote branches

sed 's@origin/@ @' split the origin/ from the begining of branch name

git branch  $branch origin/$branch create a new branch with the history of origin/branch

Now see all local branches

```<code>$ git branch
</code>```

Body:
I am working on a branch "branch-A" and using the command git branch I can see that its the only branch locally.

If I use git branch -a I can see the remote copy of "remotes/origin/branch-B"

What I want to do is bring branch-B locally, but I don't want to actually check it out... I mean I could do that and then checkout my other branch to go back, but its slightly more painful since I am doing this to lots of repos.

I was thinking some sort of fetch? but I can't figure out how to phrase the command. Is it possible?

So I have:

user@pc> git branch
* branch-A
  master

and

user@pc> git branch -a
* branch-A
  remotes/origin/branch-B
  remotes/origin/branch-A
  remotes/origin/master

I want to be able to get:

user@pc> git branch
* branch-A
  branch-B
  master

Body:
You can run a script to create new local branches with the name of all remote branches.

$ git fetch
$ for branch in `git branch -r | sed 's@origin/@ @'`;do `git branch  $branch origin/$branch`;done

git branch -r shows all the remote branches

sed 's@origin/@ @' split the origin/ from the begining of branch name

git branch  $branch origin/$branch create a new branch with the history of origin/branch

Now see all local branches

$ git branch


问:
ui-grid 'renderComplete' event after rendering rows in DOM
I'm using ui-grid 3.2.1.
Trying for a long time now to find an event that notifies me when rows are rendered in the DOM.
I looked a lot in SO, and in their issues in Github.
My test to see if rows are rendered is basically $('.ui-grid-row').length > 0.

I tried rowsRendered event, modifyRows(data), all sorts of $timeout(0) in almost every spot I could, nothing worked, all callbacks are called when the above jQuery still doesn't have results.

As a last resort I found a very inefficient solution - I $watch the .html() changes of .ui-grid-contents-wrapper, which contains the .ui-grid-row elements, and when I find one, I turn off the watcher and call the callback. It's bad but it works.

Note - The rows/columns somtimes contain inner directives which may take some time to render. I don't think it should influence rowsRendered() event.

Please, can anybody help with this?
No support from ui-grid team sadly.

EDIT:
plunkr that show there are no .ui-grid-row in DOM when rowsRendered() is called:
https://plnkr.co/edit/8clwC5hkwhAEjvoLZ6vO?p=preview

答:
Try

```<code>var rows= gridApi.core.getAllVisibleRows(gridApi.grid);
</code>```

inside rowsRendered function.

Body:
Try

var rows= gridApi.core.getAllVisibleRows(gridApi.grid);

inside rowsRendered function.


问:
Angular 2 How do I call a service method when an observable changes/when a services returns new results?
I have a simple app component with a search input and an observable resultItems: Observable<Array<string>>; powered by a search service that returns results to the UI via *ngFor.  There is also a leaflet map that should render the locations of the results.  The search service works well and I can render the location of one result in the map onclick.   My question is:  What is the recommended way to call the map service mapResults every time the search service returns new results or the observable changes?  I can imagine how I could create a custom pipe that would iterate over the parks in the service results and call mapservice.mapResult but that seems odd since the pipe wouldn't return anything to the UI and I'm a little concerned with performance, understanding little about pure and impure pipes.  I have also seen mention of a process by which you subscribe to changes of an observable, but I'm lost with the semantics and changes among API versions.

I apologize if this is a problem of poor design. I only have a few weeks of Angular learning and I admittedly haven't read the documentation thoroughly. Please point any and all issues you see.

simple Search Service

```<code>import { Injectable } from '@angular/core';
import { URLSearchParams, Jsonp } from '@angular/http';

@Injectable()
export default class ParkSearchService {

    constructor(private jsonp: Jsonp) { }

    search(parkSearchterm: string) {
        var search = new URLSearchParams()
        search.set('q', 'PARK_NAME:*' + parkSearchterm+'*');
        search.set('wt', 'json');

        search.set('json.wrf','JSONP_CALLBACK')

        var test = this.jsonp
            .get('http://parksearch/parks_full/select?', { search })
            .map((response) => response.json()['response']['docs']);

        return test

    }
}
</code>```

exert from app.component.html

```<code>  <md-card *ngFor="let item of resultItems | async; let i = index"
                 class="search-result"
                 [ngClass]="{ 'selected-result': selectedIndex === i }">
            <md-card-header class="clickable"
                            (click)="showBoundary(item)"
                            md-tooltip="Zoom to park">
                <md-card-title>{{item.PARK_NAME}}</md-card-title>
            </md-card-header>
            <md-card-content style="height: 75px; overflow-y: auto">
                <button md-button
                        color="primary"
                        md-tooltip="more info"
                        (click)="openDtl(item.PARK_HOME_PAGE_URL)">
                    <md-icon>info</md-icon>
                    <span>Details...</span>
                </button>
                <button md-button
                        color="primary"
                        md-tooltip="open park website"
                        (click)="openParkURL(item.PARK_HOME_PAGE_URL)">
                    <md-icon>web</md-icon>
                    <span>WebSite</span>
                </button>
                Amenties: {{ item.AMEN_LIST }}
            </md-card-content>
        </md-card>
</code>```

app.component.ts  (forgot to include)

```<code> export class AppComponent {
    private selectedIndex: number;
    public events: any[] = [];
    //park search items
    resultItems: Observable<Array<string>>;
    parkSearchterm = new FormControl();

    //setup resultitems
    ngOnInit() {
            this.mapService.initialize();
            this.resultItems = this.parkSearchterm.valueChanges
                .debounceTime(400)
                .distinctUntilChanged()
                .switchMap(parkSearchterm => this.parkSearchService.search(parkSearchterm));
</code>```

map service:

```<code>//Thanks for the help getting started https://github.com/haoliangyu
import { Injectable } from '@angular/core';
import { Map, GeoJSON } from 'leaflet';

@Injectable()
export default class MapService {
    public map: Map;
    private currentLayer: GeoJSON;
    private resultsLayer: any;
    private resultfeatureCollection: any;

    constructor() {

    }

    initialize() {
        if (this.map) {
            return;
        }

        this.map = L.map('map', {
            zoomControl: true,
            zoom: 6,
            minZoom: 3,
            maxZoom: 19
        });

        L.tileLayer('http://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png', {
            attribution: '© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>, Tiles courtesy of <a href="http://hot.openstreetmap.org/" target="_blank">Humanitarian OpenStreetMap Team</a>'
        }).addTo(this.map);

        L.control.scale().addTo(this.map);

        //Add the results layer
        this.resultsLayer = L.geoJSON(this.resultfeatureCollection, {
            style: () => {
                return {
                    color: '#ff00005',
                    fillColor: '#3F51B5'
                };
            }
        }).addTo(this.map);
    }
    mapResults(park) {
        //update the restults layer
        let resultfeatureCollection: GeoJSON.FeatureCollection<any> = {
            type: 'FeatureCollection',
            features: [
                {
                    type: 'Feature',
                    geometry: {
                        type: "Polygon",
                        coordinates: JSON.parse(park.BBOX[0])
                    },
                    properties: {
                        name: 'test'
                    }
                }
            ]
        };

        this.resultsLayer.addData(resultfeatureCollection);
        this.map.fitBounds(this.resultsLayer.getBounds());
    }

}
</code>```

答:
Subscribe on observer and call then search is changed. https://angular.io/docs/ts/latest/guide/router.html#!#reuse

After get result from server, put it to array. Angular will update the data in the template itself, this is the fastest way.

Body:
I have a simple app component with a search input and an observable resultItems: Observable<Array<string>>; powered by a search service that returns results to the UI via *ngFor.  There is also a leaflet map that should render the locations of the results.  The search service works well and I can render the location of one result in the map onclick.   My question is:  What is the recommended way to call the map service mapResults every time the search service returns new results or the observable changes?  I can imagine how I could create a custom pipe that would iterate over the parks in the service results and call mapservice.mapResult but that seems odd since the pipe wouldn't return anything to the UI and I'm a little concerned with performance, understanding little about pure and impure pipes.  I have also seen mention of a process by which you subscribe to changes of an observable, but I'm lost with the semantics and changes among API versions.

I apologize if this is a problem of poor design. I only have a few weeks of Angular learning and I admittedly haven't read the documentation thoroughly. Please point any and all issues you see.

simple Search Service

import { Injectable } from '@angular/core';
import { URLSearchParams, Jsonp } from '@angular/http';

@Injectable()
export default class ParkSearchService {

    constructor(private jsonp: Jsonp) { }

    search(parkSearchterm: string) {
        var search = new URLSearchParams()
        search.set('q', 'PARK_NAME:*' + parkSearchterm+'*');
        search.set('wt', 'json');

        search.set('json.wrf','JSONP_CALLBACK')

        var test = this.jsonp
            .get('http://parksearch/parks_full/select?', { search })
            .map((response) => response.json()['response']['docs']);

        return test

    }
}

exert from app.component.html

  <md-card *ngFor="let item of resultItems | async; let i = index"
                 class="search-result"
                 [ngClass]="{ 'selected-result': selectedIndex === i }">
            <md-card-header class="clickable"
                            (click)="showBoundary(item)"
                            md-tooltip="Zoom to park">
                <md-card-title>{{item.PARK_NAME}}</md-card-title>
            </md-card-header>
            <md-card-content style="height: 75px; overflow-y: auto">
                <button md-button
                        color="primary"
                        md-tooltip="more info"
                        (click)="openDtl(item.PARK_HOME_PAGE_URL)">
                    <md-icon>info</md-icon>
                    Details...
                </button>
                <button md-button
                        color="primary"
                        md-tooltip="open park website"
                        (click)="openParkURL(item.PARK_HOME_PAGE_URL)">
                    <md-icon>web</md-icon>
                    WebSite
                </button>
                Amenties: {{ item.AMEN_LIST }}
            </md-card-content>
        </md-card>

app.component.ts  (forgot to include)

 export class AppComponent {
    private selectedIndex: number;
    public events: any[] = [];
    //park search items
    resultItems: Observable<Array<string>>;
    parkSearchterm = new FormControl();

    //setup resultitems
    ngOnInit() {
            this.mapService.initialize();
            this.resultItems = this.parkSearchterm.valueChanges
                .debounceTime(400)
                .distinctUntilChanged()
                .switchMap(parkSearchterm => this.parkSearchService.search(parkSearchterm));

map service:

//Thanks for the help getting started https://github.com/haoliangyu
import { Injectable } from '@angular/core';
import { Map, GeoJSON } from 'leaflet';

@Injectable()
export default class MapService {
    public map: Map;
    private currentLayer: GeoJSON;
    private resultsLayer: any;
    private resultfeatureCollection: any;

    constructor() {

    }

    initialize() {
        if (this.map) {
            return;
        }

        this.map = L.map('map', {
            zoomControl: true,
            zoom: 6,
            minZoom: 3,
            maxZoom: 19
        });

        L.tileLayer('http://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png', {
            attribution: '© OpenStreetMap, Tiles courtesy of Humanitarian OpenStreetMap Team'
        }).addTo(this.map);

        L.control.scale().addTo(this.map);

        //Add the results layer
        this.resultsLayer = L.geoJSON(this.resultfeatureCollection, {
            style: () => {
                return {
                    color: '#ff00005',
                    fillColor: '#3F51B5'
                };
            }
        }).addTo(this.map);
    }
    mapResults(park) {
        //update the restults layer
        let resultfeatureCollection: GeoJSON.FeatureCollection<any> = {
            type: 'FeatureCollection',
            features: [
                {
                    type: 'Feature',
                    geometry: {
                        type: "Polygon",
                        coordinates: JSON.parse(park.BBOX[0])
                    },
                    properties: {
                        name: 'test'
                    }
                }
            ]
        };

        this.resultsLayer.addData(resultfeatureCollection);
        this.map.fitBounds(this.resultsLayer.getBounds());
    }

}


问:
Remove special chars from Retrofit2 response
I am trying to use Retrofit2 with GsonConverterFactory the problem is this is the response i am get from okhttp:

```<code>"{\r\n  \"Template\": {\r\n    \"id\": 11,\r\n    \"name\": \"Zoo London\"\r\n  },\r\n  \"Screens\":...
</code>```

Because of this i get the following exception:

java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 2

How do i remove the special chars and carriage returns with retrofit2?

答: The problem was fixed by making sure the api was returning a valid JSON</p>

Body:
I am trying to use Retrofit2 with GsonConverterFactory the problem is this is the response i am get from okhttp:

"{\r\n  \"Template\": {\r\n    \"id\": 11,\r\n    \"name\": \"Zoo London\"\r\n  },\r\n  \"Screens\":...

Because of this i get the following exception:

java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 2

How do i remove the special chars and carriage returns with retrofit2?


问:
typescript: define the type of a classes collection
i don't know how to define the type of class's collection in typescript:

When i compile the following code, i've got an error:

```<code>    class Wall{
        brick: string;

        constructor(){
            this.brick = "jolies briques oranges";
        }

        // Wall methods ...
    }

class Critter {
    CritterProperty1: string[];
    CritterProperty2: string;

    constructor() {
        this.CritterProperty1 = "n ne e se s so o no".split(" ");
    }

    // Critter methods ...
}

type legendObjectType = Critter | Wall;

interface Ilegend {
    [k: string]: legendObjectType;
}

// i've got an issue to define the type of 'theLegend' Object
let theLegend: Ilegend = {
    "X": Wall,
    "o": Critter
}
</code>```

error TS2322: Type '{ "X": typeof Wall; "o": typeof Critter; }' is not
  assignable to type 'Ilegend'.

while i can compile it, if the "Class Wall" is empty.

does anyone know how to define the type of such a class's collection?

let theLegend = {
      "X": Wall,
      "o": Critter }

(this is an exemple from the chapter 7 of eloquent javascript, than i try to transcribe in typescript)

EDIT

i complete the Rico Kahler's answer, with an abstract Class to avoid using the union type

```<code>abstract class MapItem {
    originChar: string;

    constructor(){}
}

class Wall extends MapItem {
    brick: string;

    constructor(){
        super();
        this.brick = "jolies briques oranges";
    }

    // Wall methods ...
}

class Critter extends MapItem {
    CritterProperty1: string[];
    CritterProperty2: string;

    constructor() {
        super();
        this.CritterProperty1 = "n ne e se s so o no".split(" ");
    }

    // Critter methods ...
}

interface Ilegend {
    [k: string]: new () => MapItem;
}

let theLegend: Ilegend = {
    "X": Wall,
    "o": Critter
}
</code>```

thank's.

答:
Your issue lies your object theLegend.

Typescript is expect an instance of Wall or Critter but instead you're providing it with a type.

```<code>let theLegend: Ilegend = {
    "X": Wall, // `Wall` is a type not an instance, it is `typeof Wall` or the Wall type
    "o": Critter // `Criter` is a type not an instance
}
</code>```

Something like the following will work:

```<code>let theLegend: Ilegend = {
    X: new Wall(), // now it's an instance!
    o: new Critter()
}
</code>```

Edit:

Now reading the javascript pages you linked, it seems like I missed your intent. If you want to create an interface that takes a constructor, then I would type Ilegend as follows:

```<code>interface Legend {
    [k: string]: new () => (Critter | Wall)
}

// now you can define an object with this type

let legend: Legend = {
    // here `Critter` actually refers to the class constructor
    // that conforms to the type `new () => (Critter | Wall)` instead of just a type
    something: Critter,
    somethingElse: Wall
}

const critter = new legend.something() // creates a `Critter`
const wall = new legend.somethingElse() // creates a `Wall`

// however, the type of `critter` and `wall` are both `Critter | Wall`. You'd have to use type assertion (i.e. casting) because typescript can't tell if its either a Critter or a Wall
</code>```

Now the interfaces allows any string to be a key and it expects every value to be a function that you can call new on to get either a Critter or a Wall

Body:
i don't know how to define the type of class's collection in typescript:

When i compile the following code, i've got an error:

    class Wall{
        brick: string;

        constructor(){
            this.brick = "jolies briques oranges";
        }

        // Wall methods ...
    }

class Critter {
    CritterProperty1: string[];
    CritterProperty2: string;

    constructor() {
        this.CritterProperty1 = "n ne e se s so o no".split(" ");
    }

    // Critter methods ...
}

type legendObjectType = Critter | Wall;

interface Ilegend {
    [k: string]: legendObjectType;
}

// i've got an issue to define the type of 'theLegend' Object
let theLegend: Ilegend = {
    "X": Wall,
    "o": Critter
}

error TS2322: Type '{ "X": typeof Wall; "o": typeof Critter; }' is not
  assignable to type 'Ilegend'.

while i can compile it, if the "Class Wall" is empty.

does anyone know how to define the type of such a class's collection?

let theLegend = {
      "X": Wall,
      "o": Critter }

(this is an exemple from the chapter 7 of eloquent javascript, than i try to transcribe in typescript)

EDIT

i complete the Rico Kahler's answer, with an abstract Class to avoid using the union type

abstract class MapItem {
    originChar: string;

    constructor(){}
}

class Wall extends MapItem {
    brick: string;

    constructor(){
        super();
        this.brick = "jolies briques oranges";
    }

    // Wall methods ...
}

class Critter extends MapItem {
    CritterProperty1: string[];
    CritterProperty2: string;

    constructor() {
        super();
        this.CritterProperty1 = "n ne e se s so o no".split(" ");
    }

    // Critter methods ...
}

interface Ilegend {
    [k: string]: new () => MapItem;
}

let theLegend: Ilegend = {
    "X": Wall,
    "o": Critter
}

thank's.

Body:
Your issue lies your object theLegend.

Typescript is expect an instance of Wall or Critter but instead you're providing it with a type.

let theLegend: Ilegend = {
    "X": Wall, // `Wall` is a type not an instance, it is `typeof Wall` or the Wall type
    "o": Critter // `Criter` is a type not an instance
}

Something like the following will work:

let theLegend: Ilegend = {
    X: new Wall(), // now it's an instance!
    o: new Critter()
}

Edit:

Now reading the javascript pages you linked, it seems like I missed your intent. If you want to create an interface that takes a constructor, then I would type Ilegend as follows:

interface Legend {
    [k: string]: new () => (Critter | Wall)
}

// now you can define an object with this type

let legend: Legend = {
    // here `Critter` actually refers to the class constructor
    // that conforms to the type `new () => (Critter | Wall)` instead of just a type
    something: Critter,
    somethingElse: Wall
}

const critter = new legend.something() // creates a `Critter`
const wall = new legend.somethingElse() // creates a `Wall`

// however, the type of `critter` and `wall` are both `Critter | Wall`. You'd have to use type assertion (i.e. casting) because typescript can't tell if its either a Critter or a Wall

Now the interfaces allows any string to be a key and it expects every value to be a function that you can call new on to get either a Critter or a Wall


问:
Integrating Docker with Xdebug and Sublime Text on PHP environment
I'm setting up a Docker development environment for my team. In this environment we want to integrate Xdebug with Docker to allow for debugging. It seems the easiest way to do this is to connect Sublime Text to the Docker instance and then install Xdebug ontop on Sublime Text. I found the following guide for integrating Sublime Text with Docker (http://domeide.github.io/) and this guide for integrating Xdebug with Sublime Text (https://www.sitepoint.com/debugging-xdebug-sublime-text-3/). What I am wondering is if anyone has any experience setting up similar environments? Is there an easier way to do this? Does this seem like the correct way to debug PHP code inside Docker?</p>

答:
This solution may also work for Sublime Text - For Visual Studio Code, I have just recently got this working. I found these remote_host and other Xdebug settings work for me on both Windows 10 Pro and OS X using the latest versions of Docker Community Edition.

In the Xdebug extension configuration, I set these along with the Xdebug extension installation in the Dockerfile of the image package from docker hub that contains php. There is a link to a post at the bottom of this answer on how this was done in the Dockerfile and how the image was built and then added to the docker-compose file.

The xdebug.remote_connect_back setting needs to be off: xdebug.remote_connect_back=0

Autostart xdebug.remote_autostart=1 it just works.

xdebug.remote_host=127.0.0.1 needs to be changed depending on Windows or OS X as follows:

Windows 10 Professional running Docker Version 17.03.0-ce-win1, open a command prompt and enter ipconfig. The address is listed under DockerNAT. For example:

```<code>ipconfig

Ethernet adapter vEthernet (DockerNAT):

    IPv4 Address. . . . . . . . . . . : 10.0.75.1
</code>```

OS X El Capitan running Docker Version 17.03.0-ce-mac2, create an alias of IP 10.254.254.254 to your existing subnet mask.

```<code>sudo ifconfig en0 alias 10.254.254.254 255.255.255.0
</code>```

Then use the IP for the xdebug.remote_host setting for your host as follows based on the examples above:

Windows 10.0.75.1

OS X: 10.254.254.254

Note, if you run into a conflict in OS X, you can remove the alias like so.

```<code>sudo ifconfig en0 -alias 10.254.254.254
</code>```

I use Visual Studio Code with the vscode-php-debug PHP Debug Adapter to Listen for Xdebug and step through my code. Note the following needs to be included in the project launch.json file in order for VS Code to map the remote server files to the local machine. This is from my project and its typical volume locations, your serverSourceRoot looks to be the same.

```<code>"serverSourceRoot": "/var/www/html",
"localSourceRoot": "${workspaceRoot}"
</code>```

The entire setup for docker-compose, nginx-proxy including how to build the image with Xdebug and more at Docker WordPress Dev Environment - Remote Debugging with Xdebug and VS Code

Body:
This solution may also work for Sublime Text - For Visual Studio Code, I have just recently got this working. I found these remote_host and other Xdebug settings work for me on both Windows 10 Pro and OS X using the latest versions of Docker Community Edition.

In the Xdebug extension configuration, I set these along with the Xdebug extension installation in the Dockerfile of the image package from docker hub that contains php. There is a link to a post at the bottom of this answer on how this was done in the Dockerfile and how the image was built and then added to the docker-compose file.

The xdebug.remote_connect_back setting needs to be off: xdebug.remote_connect_back=0

Autostart xdebug.remote_autostart=1 it just works.

xdebug.remote_host=127.0.0.1 needs to be changed depending on Windows or OS X as follows:

Windows 10 Professional running Docker Version 17.03.0-ce-win1, open a command prompt and enter ipconfig. The address is listed under DockerNAT. For example:

ipconfig

Ethernet adapter vEthernet (DockerNAT):

    IPv4 Address. . . . . . . . . . . : 10.0.75.1

OS X El Capitan running Docker Version 17.03.0-ce-mac2, create an alias of IP 10.254.254.254 to your existing subnet mask.

sudo ifconfig en0 alias 10.254.254.254 255.255.255.0

Then use the IP for the xdebug.remote_host setting for your host as follows based on the examples above:

Windows 10.0.75.1

OS X: 10.254.254.254

Note, if you run into a conflict in OS X, you can remove the alias like so.

sudo ifconfig en0 -alias 10.254.254.254

I use Visual Studio Code with the vscode-php-debug PHP Debug Adapter to Listen for Xdebug and step through my code. Note the following needs to be included in the project launch.json file in order for VS Code to map the remote server files to the local machine. This is from my project and its typical volume locations, your serverSourceRoot looks to be the same.

"serverSourceRoot": "/var/www/html",
"localSourceRoot": "${workspaceRoot}"

The entire setup for docker-compose, nginx-proxy including how to build the image with Xdebug and more at Docker WordPress Dev Environment - Remote Debugging with Xdebug and VS Code


问:
SQL Server join and insert data
My name is Thorsten and I'm new to SQL Server. Now I am facing a problem after setting a join... I joined two tables, and it worked so far, but I don't have enough knowledge to proceed.

Here is table1:

```<code>| Item | validDate  | Price |
| ---- | ---------  | ----- |
| A    | 01.01.2017 | 100   |
| A    | 31.03.2017 | 100   |
| A    | 01.04.2017 | 120   |
| A    | 31.07.2017 | 120   |
</code>```

Now I want to create a table that includes a dataset for the gap in table1:

```<code>| Item | validDate  | Price |
| ---- | ---------  | ----- |
| A    | 01.01.2017 | 100   |
| A    | 28.02.2017 | 100   |
| A    | 31.03.2017 | 120   |
</code>```

... and so on.

My idea was to set a join from table1 to a date table, were every month end is included. But I have to insert the gap as well by creating a new dataset. With what code I'll be able to solve this issue?

As mentioned - I'm a beginner, so I hope I was able to describe my problem.

Thanks in advance for help!

答:
Try to make use of below Query :

```<code>DECLARE @Table TABLE (Item VARCHAR(2), validDate DATE, Price INT)
INSERT INTO @Table VALUES
('A','2017-01-01',100),
('A','2017-03-31',100),
('A','2017-04-01',120),
('A','2017-07-31',120)

SELECT Item,DATEADD(DD,-1,validDate) AS Date,Price FROM @Table
</code>```

OUTPUT

```<code>Item     Date         Price
  A      2016-12-31   100
  A      2017-03-30   100
  A      2017-03-31   120
  A      2017-07-30   120
</code>```

Title: SQL Server join and insert data

Body:
My name is Thorsten and I'm new to SQL Server. Now I am facing a problem after setting a join... I joined two tables, and it worked so far, but I don't have enough knowledge to proceed.

Here is table1:

| Item | validDate  | Price |
| ---- | ---------  | ----- |
| A    | 01.01.2017 | 100   |
| A    | 31.03.2017 | 100   |
| A    | 01.04.2017 | 120   |
| A    | 31.07.2017 | 120   |

Now I want to create a table that includes a dataset for the gap in table1:

| Item | validDate  | Price |
| ---- | ---------  | ----- |
| A    | 01.01.2017 | 100   |
| A    | 28.02.2017 | 100   |
| A    | 31.03.2017 | 120   |

... and so on.

My idea was to set a join from table1 to a date table, were every month end is included. But I have to insert the gap as well by creating a new dataset. With what code I'll be able to solve this issue?

As mentioned - I'm a beginner, so I hope I was able to describe my problem.

Thanks in advance for help!

Body:
Try to make use of below Query :

DECLARE @Table TABLE (Item VARCHAR(2), validDate DATE, Price INT)
INSERT INTO @Table VALUES
('A','2017-01-01',100),
('A','2017-03-31',100),
('A','2017-04-01',120),
('A','2017-07-31',120)

SELECT Item,DATEADD(DD,-1,validDate) AS Date,Price FROM @Table

OUTPUT

Item     Date         Price
  A      2016-12-31   100
  A      2017-03-30   100
  A      2017-03-31   120
  A      2017-07-30   120


问:
How to copy existing xlsx column into new column using openpyxl
I have an xlsx file and I need add 1 column within openpyxl.
Can you help me pls?

Something like this:

```<code>wb = load_workbook('wb.xlsx')
ws = wb.active

wb2 = workbook()
ws2 = wb2.active

row = 0

while row < nrows:
        newVal = ws.cell_value(row, 2)
    ws2.write(row, 3, newVal)
    row = row + 1
write_book.save('wb_with_new_column')
</code>```

答:
You appear to be trying to copy the contents of one column into another column. This can be done easily as follows:

```<code>import openpyxl

wb = openpyxl.load_workbook('file1.xlsx')
ws = wb.active

for src, dst in zip(ws['B:B'], ws['C:C']):
    dst.value = src.value

wb.save('file1.xlsx')
</code>```

openpyxl allows you to iterate over cells. Here we create a source and a destination range of cells to iterate over. zip() is used to pair them up, then all that is needed is a simple value copy.

Body:
I have an xlsx file and I need add 1 column within openpyxl.
Can you help me pls?

Something like this:

wb = load_workbook('wb.xlsx')
ws = wb.active

wb2 = workbook()
ws2 = wb2.active

row = 0

while row < nrows:
        newVal = ws.cell_value(row, 2)
    ws2.write(row, 3, newVal)
    row = row + 1
write_book.save('wb_with_new_column')

Body:
You appear to be trying to copy the contents of one column into another column. This can be done easily as follows:

import openpyxl

wb = openpyxl.load_workbook('file1.xlsx')
ws = wb.active

for src, dst in zip(ws['B:B'], ws['C:C']):
    dst.value = src.value

wb.save('file1.xlsx')

openpyxl allows you to iterate over cells. Here we create a source and a destination range of cells to iterate over. zip() is used to pair them up, then all that is needed is a simple value copy.


问:
How to increment letters in javascript to next letter?
I want a function that I can go from A to B, B to C, Z to A.

My function is currently like so:

```<code>function nextChar(c) {
    return String.fromCharCode(c.charCodeAt(0) + 1);
}
nextChar('a');
</code>```

It works for A to X, but when I use Z... it goes to [ instead of A.

答:
You could use parseInt with radix 36 and the opposite method Number#toString with the same radix, and a correction for the value.

function nextChar(c) {
    var i = (parseInt(c, 36) + 1 ) % 36;
    return (!i * 10 + i).toString(36);
}

console.log(nextChar('a'));
console.log(nextChar('z'));```

Body:
I want a function that I can go from A to B, B to C, Z to A.

My function is currently like so:

function nextChar(c) {
    return String.fromCharCode(c.charCodeAt(0) + 1);
}
nextChar('a');

It works for A to X, but when I use Z... it goes to [ instead of A.


问:
Prevent click for Chocolat.js while dragging using slick.js
Right  now I have a draggable images container using slick and I want to preview full size when a single click happens using Chocolat.js,

The problem is that when I release the mouse (after dragg), still fires the full screen,

I tried to destroy the chocolat when the Dragg event begins, but it persists..

```<code>var $chocolat = $('.chocolat').Chocolat({
    imageSize: 'contain',
    loop: true
}).data('chocolat');

$('#bx-pager_builder').slick({
    dots: true,
    infinite: true,
    speed: 300,
    slidesToShow: 1,
    centerMode: true,
    variableWidth: true,
    beforeChange: function() {
        $chocolat.api().destroy();
    },
    afterChange: function() {
        $chocolat = $('.chocolat').Chocolat({
            imageSize: 'contain',
            loop: true
        }).data('chocolat');
    }
});
</code>```

The problem is that the Chocolat documentation doesn't provide examples..

Any idea if what i'm trying to do is posible? ( and how? ^^ )

答:
```<code>var chocolat_images = [];
$('.chocolat .chocolat-image').each(function(i){
    chocolat_images[chocolat_images.length] = { src: $(this).find('img').attr('src')};
});
var $chocolat = $('.slick-slider.chocolat').Chocolat(
{
    imageSize: 'contain',
    loop: true,
    images: chocolat_images,
    imageSelector: ''
}).data('chocolat');

$('.chocolat').on('click', '.chocolat-image', function(e) {
    e.preventDefault();
    $chocolat.api().open($(this).index())
});
</code>```

I was able to fix it like this. Handling 'manually' the event and the indexes

Body:
Right  now I have a draggable images container using slick and I want to preview full size when a single click happens using Chocolat.js,

The problem is that when I release the mouse (after dragg), still fires the full screen,

I tried to destroy the chocolat when the Dragg event begins, but it persists..

var $chocolat = $('.chocolat').Chocolat({
    imageSize: 'contain',
    loop: true
}).data('chocolat');

$('#bx-pager_builder').slick({
    dots: true,
    infinite: true,
    speed: 300,
    slidesToShow: 1,
    centerMode: true,
    variableWidth: true,
    beforeChange: function() {
        $chocolat.api().destroy();
    },
    afterChange: function() {
        $chocolat = $('.chocolat').Chocolat({
            imageSize: 'contain',
            loop: true
        }).data('chocolat');
    }
});

The problem is that the Chocolat documentation doesn't provide examples..

Any idea if what i'm trying to do is posible? ( and how? ^^ )

Body:
var chocolat_images = [];
$('.chocolat .chocolat-image').each(function(i){
    chocolat_images[chocolat_images.length] = { src: $(this).find('img').attr('src')};
});
var $chocolat = $('.slick-slider.chocolat').Chocolat(
{
    imageSize: 'contain',
    loop: true,
    images: chocolat_images,
    imageSelector: ''
}).data('chocolat');

$('.chocolat').on('click', '.chocolat-image', function(e) {
    e.preventDefault();
    $chocolat.api().open($(this).index())
});

I was able to fix it like this. Handling 'manually' the event and the indexes


问:
Printing in icefaces
I would like to print reports in icefaces, but could got find any proper method for it. Please guide me for implementation of the same in my project.</p>

答: I've used the ice:outputResource tag to let the user download a PDF report file.  The resource attribute of that tag should point a managed bean property that implements com.icesoft.faces.context.Resource.  </p>

Title: Printing in icefaces