问:
Keep dropdown visible while input boxes are focused
My navbar has dropdown "fieldsets" for login and search like this:

```<code><div class="nav-button" id="nav-box">
        <a class="inside-link">
            <span id="inside-text">Sign in</span>
        </a>
        <fieldset id="menu-box" class="menu-box">
            <form method="post" id="forms" class="forms" action="checklogin.php">
                <label for="username">Username or email</label>
                <input type="text" id="username" name="username" value="" title="username" tabindex="4">

                <label for="password">Password</label>
                <input type="password" id="password" name="password" value="" title="password" tabindex="5">

                <input type="submit" id="small-btn" value="Sign in" tabindex="6">
                <input type="checkbox" id="remember" name="remember_me" value="1" tabindex="7">
                <label for="remember">Remember me</label>
                <br />
                <a href="#"id="resend_password_link">Forgot your password?</a>
                <a id='forgot_username_link' title="If you remember your password, try logging in with your email" href="#">Forgot your username?</a>
            </form>
        </fieldset>
    </div>
</code>```

I have a fiddle here: http://jsfiddle.net/WBrns/5/

While input boxes like "search" "username" and "password" are focused, I'd like the associated dropdown to not disappear so users don't have to keep their mouse within the dropdown while typing.

Line 288 in the CSS was our first attempt which obviously doesn't work. My site already includes jQuery so any js/jquery solution is acceptable (since I think it's not possible with pure css)

Thanks!

答:
To improve upon Shaz's answer, you can name the blur event to prevent multiple blur events from being attached to the same input. I also recommend using a class name and CSS to show and hide the drop down so that you can take advantage of CSS transitions.

JS

```<code>$('input').focus(function () {
  var $this = $(this);
  var $drop = $this.parents('.drop');

  $drop.addClass('open');
  $this.bind('blur.closeDrop', function () {
    $drop.removeClass('open');
    $this.unbind('blur.closeDrop');
  });
});
</code>```

CSS

```<code>.drop {
  opacity: 0;
  pointer-events: none;
  transition: opacity 0.2s ease;
}
.drop.open {
  opacity: 1;
  pointer-events: auto;
}
</code>```

Body:
My navbar has dropdown "fieldsets" for login and search like this:

            Sign in

        <fieldset id="menu-box" class="menu-box">
            <form method="post" id="forms" class="forms" action="checklogin.php">
                Username or email
                <input type="text" id="username" name="username" value="" title="username" tabindex="4">

                Password
                <input type="password" id="password" name="password" value="" title="password" tabindex="5">

                <input type="submit" id="small-btn" value="Sign in" tabindex="6">
                <input type="checkbox" id="remember" name="remember_me" value="1" tabindex="7">
                Remember me

                Forgot your password?
                Forgot your username?
            </form>
        </fieldset>

I have a fiddle here: http://jsfiddle.net/WBrns/5/

While input boxes like "search" "username" and "password" are focused, I'd like the associated dropdown to not disappear so users don't have to keep their mouse within the dropdown while typing.

Line 288 in the CSS was our first attempt which obviously doesn't work. My site already includes jQuery so any js/jquery solution is acceptable (since I think it's not possible with pure css)

Thanks!

Body:
To improve upon Shaz's answer, you can name the blur event to prevent multiple blur events from being attached to the same input. I also recommend using a class name and CSS to show and hide the drop down so that you can take advantage of CSS transitions.

JS

$('input').focus(function () {
  var $this = $(this);
  var $drop = $this.parents('.drop');

  $drop.addClass('open');
  $this.bind('blur.closeDrop', function () {
    $drop.removeClass('open');
    $this.unbind('blur.closeDrop');
  });
});

CSS

.drop {
  opacity: 0;
  pointer-events: none;
  transition: opacity 0.2s ease;
}
.drop.open {
  opacity: 1;
  pointer-events: auto;
}


来源: stackexchange

问:
How do I return the success value of chaining multiple Results if no errors occur or another value if any error happens?
I'm trying to play with chaining multiple Results. I want to write a function which receives a &[u8] and returns a Tm. If any of the steps give a error, I just want to return time::now().

I wrote:

```<code>extern crate time;

use time::{strptime, Tm};
use std::str;

pub fn buf_to_tm(buffer: &[u8]) -> Tm {
    str::from_utf8(buffer)
        .and_then(|val| strptime(val, "%d %b %y%H:%M:%S"))
        .unwrap_or(time::now())
}
</code>```

But I'm getting this error:

error[E0308]: mismatched types
 --> src/main.rs:8:25
  |
8 |         .and_then(|val| strptime(val, "%d %b %y%H:%M:%S"))
  |                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected struct `std::str::Utf8Error`, found enum `time::ParseError`
  |
  = note: expected type `std::result::Result<_, std::str::Utf8Error>`
             found type `std::result::Result<time::Tm, time::ParseError>`
  = help: here are some functions which might fulfill your needs:
          - .unwrap()
          - .unwrap_err()
```

How do I tell Rust I don't really care what type of error this code gives, I just want to return the parsed Tm if no errors occur or time::now() if any error happens.

答:
You cannot just implicitly "ignore" the error type; that's just not how statically types languages work.

The straightforward change you can make is to explicitly change each potential failure to the same type using Result::map_err. Since you don't care about the type, you can use ():

```<code>fn buf_to_tm(buffer: &[u8]) -> Tm {
    str::from_utf8(buffer)
        .map_err(|_| ())
        .and_then(|val| strptime(val, "%d %b %y%H:%M:%S").map_err(|_| ()))
        .unwrap_or_else(|_| time::now())
}
</code>```

Even better, you can convert to an Option using Result::ok instead:

```<code>fn buf_to_tm(buffer: &[u8]) -> Tm {
    str::from_utf8(buffer).ok()
        .and_then(|val| strptime(val, "%d %b %y%H:%M:%S").ok())
        .unwrap_or_else(time::now)
}
</code>```

As an additional note, you probably should use unwrap_or_else as I've done above. This only gets the current time in failure case; unwrap_or will always execute its argument. This could save some work and makes sure that the time is as "up-to-date" as it can be.

The "enterprise" solution would be to define a custom error type. This allows you to use ? (the try operator):

```<code>#[macro_use]
extern crate quick_error;
extern crate time;

use time::{strptime, Tm};
use std::str;

quick_error! {
    #[derive(Debug)]
    enum Error {
        Utf8(err: str::Utf8Error) {
            from()
        }
        Time(err: time::ParseError) {
            from()
        }
    }
}

fn buf_to_tm_inner(buffer: &[u8]) -> Result<Tm, Error> {
    let s = str::from_utf8(buffer)?;
    let t = strptime(s, "%d %b %y%H:%M:%S")?;
    Ok(t)
}

fn buf_to_tm(buffer: &[u8]) -> Tm {
    buf_to_tm_inner(buffer)
        .unwrap_or_else(|_| time::now())
}

fn main() {}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to play with chaining multiple Results. I want to write a function which receives a &[u8] and returns a Tm. If any of the steps give a error, I just want to return time::now().

I wrote:

extern crate time;

use time::{strptime, Tm};
use std::str;

pub fn buf_to_tm(buffer: &[u8]) -> Tm {
    str::from_utf8(buffer)
        .and_then(|val| strptime(val, "%d %b %y%H:%M:%S"))
        .unwrap_or(time::now())
}

But I'm getting this error:

error[E0308]: mismatched types
 --> src/main.rs:8:25
  |
8 |         .and_then(|val| strptime(val, "%d %b %y%H:%M:%S"))
  |                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected struct `std::str::Utf8Error`, found enum `time::ParseError`
  |
  = note: expected type `std::result::Result<_, std::str::Utf8Error>`
             found type `std::result::Result<time::Tm, time::ParseError>`
  = help: here are some functions which might fulfill your needs:
          - .unwrap()
          - .unwrap_err()

How do I tell Rust I don't really care what type of error this code gives, I just want to return the parsed Tm if no errors occur or time::now() if any error happens.

Body:
You cannot just implicitly "ignore" the error type; that's just not how statically types languages work.

The straightforward change you can make is to explicitly change each potential failure to the same type using Result::map_err. Since you don't care about the type, you can use ():

fn buf_to_tm(buffer: &[u8]) -> Tm {
    str::from_utf8(buffer)
        .map_err(|_| ())
        .and_then(|val| strptime(val, "%d %b %y%H:%M:%S").map_err(|_| ()))
        .unwrap_or_else(|_| time::now())
}

Even better, you can convert to an Option using Result::ok instead:

fn buf_to_tm(buffer: &[u8]) -> Tm {
    str::from_utf8(buffer).ok()
        .and_then(|val| strptime(val, "%d %b %y%H:%M:%S").ok())
        .unwrap_or_else(time::now)
}

As an additional note, you probably should use unwrap_or_else as I've done above. This only gets the current time in failure case; unwrap_or will always execute its argument. This could save some work and makes sure that the time is as "up-to-date" as it can be.

The "enterprise" solution would be to define a custom error type. This allows you to use ? (the try operator):

#[macro_use]
extern crate quick_error;
extern crate time;

use time::{strptime, Tm};
use std::str;

quick_error! {
    #[derive(Debug)]
    enum Error {
        Utf8(err: str::Utf8Error) {
            from()
        }
        Time(err: time::ParseError) {
            from()
        }
    }
}

fn buf_to_tm_inner(buffer: &[u8]) -> Result<Tm, Error> {
    let s = str::from_utf8(buffer)?;
    let t = strptime(s, "%d %b %y%H:%M:%S")?;
    Ok(t)
}

fn buf_to_tm(buffer: &[u8]) -> Tm {
    buf_to_tm_inner(buffer)
        .unwrap_or_else(|_| time::now())
}

fn main() {}


问:
Why was material design lite(MDL) deprecated with MDC?
which of the 3 high-level goals did MDL fail:

Production-ready components consumable in an a-la-carte fashion

Best-in-class performance and adherence to the Material Design guidelines

Seamless integration with other JS frameworks and libraries

Or were there some other reasons behind deprecating MDL?

答:
One of the core team members for MDC Web here. We have a migration guide if you're curious about switching from MDL to MDC Web.

One thing we accomplished by moving to MDC Web was a new architecture for JavaScript components. MDC Web is built in a way that is completely framework agnostic, so the same code base can be used in idiomatic JS, React, Angular etc... We also publish the components in a way where they can be installed in an ala carte fashion, though if you want to grab everything it is 164K.

Essentially we accomplish this by splitting up concerns into two concepts: Components and Foundations. A Component is a ready-to-use JavaScript component, while a Foundation contains all of the shared UI code. The Foundation is useful for low-level usage by frameworks like React/Angular/Vue etc..., and more complex rendering logic.

The last piece of the puzzle is the concept of an Adapter. In MDC Web, an Adapter is a configuration object that gets passed to the Foundation. This will include any logic surrounding data-binding, templating, key/input handling, etc... What this all boils down to is a logical set of defaults which can be overridden if you're using a framework like React or SSR where those things diverge from how they are done in vanilla javascript in the browser.

Finally, we have a public Discord server if anyone is interested in chatting with us. We are happy to answer any implementation questions or work through any issues.


问:
Validating macOS apps that pass codesign, spctl, and check-signature but fail to run "because the identity of the developer cannot be confirmed"
My macOS app is codesigned and runs on some computers but on another it fails to run since Gatekeeper pops up "{App} can't be opened because the identity of the developer cannot be confirmed."

I want to detect this issue on the build machine before distributing a faulty .dmg, so I looked into Apple's docs on Checking Gatekeeper Conformance and Examining a Code Signature, which discuss codesign, spctl, and check-signature. What's confusing is that all of these tools report that the .app is signed by my developer account.

```<code>$ codesign -v --strict --deep --verbose=2 App.app
App.app: valid on disk
App.app: satisfies its Designated Requirement

$ codesign -d --deep --verbose=2 -r- App.app
Executable=/Applications/App.app/Contents/MacOS/App
Identifier=com.example.app
Format=app bundle with Mach-O thin (x86_64)
CodeDirectory v=20200 size=196 flags=0x0(none) hashes=3+3 location=embedded
Signature size=8539
Authority=Developer ID Application: Company, Inc. (XXXXXXXXXX)
Authority=Developer ID Certification Authority
Authority=Apple Root CA
Timestamp=Sep 22, 2016, 7:32:19 PM
Info.plist entries=21
TeamIdentifier=XXXXXXXXXX
Sealed Resources version=2 rules=12 files=10708
Nested=Frameworks/Squirrel.framework
Nested=Frameworks/App Helper NP.app
Nested=Frameworks/App Helper.app
Nested=Frameworks/App Helper EH.app
Nested=Frameworks/Mantle.framework
Nested=Frameworks/ReactiveCocoa.framework
Nested=Frameworks/Electron Framework.framework
Internal requirements count=1 size=172
designated => identifier "com.example.app" and anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] /* exists */ and certificate leaf[field.1.2.840.113635.100.6.1.13] /* exists */ and certificate leaf[subject.OU] = XXXXXXXXXX

$ spctl --assess -vv App.app
App.app: accepted
source=Developer ID
origin=Developer ID Application: Company, Inc. (XXXXXXXXXX)

$ check-signature App.app
(c) 2014 Apple Inc.  All rights reserved.
YES
</code>```

The Certificates, Identifiers & Profiles website shows unexpired "Developer ID Application" and "Developer ID Installer" certificates under my account. I've never revoked any Mac signing certificates. I've also checked that CFBundlePackageType in the app's Info.plist is set to APPL.

What is going on here?

Update: Upgrading the Mac from El Capitan to Sierra resolved the issue. I'd still be interested to learn what the issue could have been in case there are users out there encountering it.

答:
In my case this message came up, when an embedded third party framework had a bad run path setting: LD_RUNPATH_SEARCH_PATHS in build settings did reference something that it was not allowed to.

Apple documents this here https://developer.apple.com/library/content/technotes/tn2206/_index.html#//apple_ref/doc/uid/DTS40007919-CH1-TNTAG207

If an app uses @rpath or an absolute path to link to a dynamic library
  outside of the app, the app will be rejected by Gatekeeper.

And they even state:

Neither the codesign nor the spctl tool will show the error. The error
  will only appear in the system log.

The solution was to modify the third party framework to something standard like this:

$(inherited) @executable_path/../Frameworks @loader_path/Frameworks

Body:
My macOS app is codesigned and runs on some computers but on another it fails to run since Gatekeeper pops up "{App} can't be opened because the identity of the developer cannot be confirmed."

I want to detect this issue on the build machine before distributing a faulty .dmg, so I looked into Apple's docs on Checking Gatekeeper Conformance and Examining a Code Signature, which discuss codesign, spctl, and check-signature. What's confusing is that all of these tools report that the .app is signed by my developer account.

$ codesign -v --strict --deep --verbose=2 App.app
App.app: valid on disk
App.app: satisfies its Designated Requirement

$ codesign -d --deep --verbose=2 -r- App.app
Executable=/Applications/App.app/Contents/MacOS/App
Identifier=com.example.app
Format=app bundle with Mach-O thin (x86_64)
CodeDirectory v=20200 size=196 flags=0x0(none) hashes=3+3 location=embedded
Signature size=8539
Authority=Developer ID Application: Company, Inc. (XXXXXXXXXX)
Authority=Developer ID Certification Authority
Authority=Apple Root CA
Timestamp=Sep 22, 2016, 7:32:19 PM
Info.plist entries=21
TeamIdentifier=XXXXXXXXXX
Sealed Resources version=2 rules=12 files=10708
Nested=Frameworks/Squirrel.framework
Nested=Frameworks/App Helper NP.app
Nested=Frameworks/App Helper.app
Nested=Frameworks/App Helper EH.app
Nested=Frameworks/Mantle.framework
Nested=Frameworks/ReactiveCocoa.framework
Nested=Frameworks/Electron Framework.framework
Internal requirements count=1 size=172
designated => identifier "com.example.app" and anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] /* exists */ and certificate leaf[field.1.2.840.113635.100.6.1.13] /* exists */ and certificate leaf[subject.OU] = XXXXXXXXXX

$ spctl --assess -vv App.app
App.app: accepted
source=Developer ID
origin=Developer ID Application: Company, Inc. (XXXXXXXXXX)

$ check-signature App.app
(c) 2014 Apple Inc.  All rights reserved.
YES

The Certificates, Identifiers & Profiles website shows unexpired "Developer ID Application" and "Developer ID Installer" certificates under my account. I've never revoked any Mac signing certificates. I've also checked that CFBundlePackageType in the app's Info.plist is set to APPL.

What is going on here?

Update: Upgrading the Mac from El Capitan to Sierra resolved the issue. I'd still be interested to learn what the issue could have been in case there are users out there encountering it.


问:
sorting csv data according to occurrences of common words
I have a large data coming from a csv file which looks something like below.

```<code>url1, comment1
url2, comment2
</code>```

I need to find the common words between the comments and sort the rows accordingly based on the occurrence of the common words on each row.

At the moment I am able to get the common words but I'm lost as to how to sort the rows per common word without exhausting the memory.

Below is my very inefficient code.

```<code>$data = array();
while (($row = fgetcsv($fh, 1024, ',')) !== false) {
  $data[] = $row[1];
}

$str = preg_replace('/\s\s+/', ' ', trim(str_replace(array('!', '?', '.', ','), ' ', implode('', $data))));

$words = explode(" ", $str);
var_dump(array_count_values($words));
</code>```

答:
Load the exploded data/words into database sounds like a good idea,

OR you can try this:

```<code>$summary = array();
$data = array();
while (($row = fgetcsv($fh, 1024, ',')) !== false)
{
  $data[] = $row[1];
  $str    = preg_replace('/\s\s+/', ' ', trim(str_replace(array('!', '?', '.', ','), ' ', $row[1])));
  $words  = explode(" ", $str);
  foreach ($words as $word)
  {
    $word = strtolower($word); // lowercase to reduce variations
    $summary[$word]++;
  }
}
/* variable $summary will contains all your count */
/* take note on the size of $summary, could growth quite big */
</code>```

Body:
I have a large data coming from a csv file which looks something like below.

url1, comment1
url2, comment2

I need to find the common words between the comments and sort the rows accordingly based on the occurrence of the common words on each row.

At the moment I am able to get the common words but I'm lost as to how to sort the rows per common word without exhausting the memory.

Below is my very inefficient code.

$data = array();
while (($row = fgetcsv($fh, 1024, ',')) !== false) {
  $data[] = $row[1];
}

$str = preg_replace('/\s\s+/', ' ', trim(str_replace(array('!', '?', '.', ','), ' ', implode('', $data))));

$words = explode(" ", $str);
var_dump(array_count_values($words));

Body:
Load the exploded data/words into database sounds like a good idea,

OR you can try this:

$summary = array();
$data = array();
while (($row = fgetcsv($fh, 1024, ',')) !== false)
{
  $data[] = $row[1];
  $str    = preg_replace('/\s\s+/', ' ', trim(str_replace(array('!', '?', '.', ','), ' ', $row[1])));
  $words  = explode(" ", $str);
  foreach ($words as $word)
  {
    $word = strtolower($word); // lowercase to reduce variations
    $summary[$word]++;
  }
}
/* variable $summary will contains all your count */
/* take note on the size of $summary, could growth quite big */

ContentLicense: CC BY-SA 2.5


问:
C# using DataflowBlock.Completion to cancel consumer tasks instead of CancellationToken
I'm wondering if there is a neat way for IDataflowBlock.Completion to replace needing to use a cancellation token for ReceiveAsync or a similar method which consumes from BufferBlock or another IDataflowBlock.

```<code>IDataflowBlock.ReceiveAsync<T>(TimeSpan, CancellationToken)
</code>```

If InputQueue is a BufferBlock:

```<code>BufferBlock<String> InputQueue

for (int i = 0; i < 26; i++)
{
    await InputQueue.SendAsync(((char)(97 + i)).ToString());
}
</code>```

If InputQueue.Complete(); has been called, then when the queue is emptied and IDataflowBlock.Completion will change to status RanToCompletion,
which can be checked with IDataflowBlock.Completion.IsCompleted.

If multiple threads are taking from the queue this could happen during InputQueue.ReceiveAsync, is there a neater alternative to handle InputQueue completing than:

```<code>try
{
    String parcel = await InputQueue.ReceiveAsync(timeSpan);
}
catch(InvalidOperationException x)
{

}
</code>```

答:
The simplest way to cancel a Dataflow Block is to provide the token to block's constructor, like this:

```<code>new ExecutionDataflowBlockOptions
{
    CancellationToken = cancellationSource.Token
});
</code>```

CancellationToken is defined in DataflowBlockOptions class, so even BufferBlock could be canceled.

Why are you implementing the Receive logic by yourself? Is there some restriction no to use the PropagateCompletion with linking your blocks? For example, if your code looks like this:

```<code>internal void HandleMessage()
{
    try
    {
        var parcel = await InputQueue.ReceiveAsync(timeSpan);
        // handle parsel
    }
    catch(InvalidOperationException x)
    {
    }
}
</code>```

Then you simply may use the ActionBlock like this:

```<code>var InputQueue = new BufferBlock<string>();
var Handler = new ActionBlock<string>(parcel =>
{
    // handle parsel
});
var linkOptions = new DataflowLinkOptions { PropagateCompletion = true };
InputQueue.LinkTo(Handler, linkOptions);

// now after you call Complete method for InputQueue the completion will be propagated to your Handler block:
for (int i = 0; i < 26; i++)
{
    await InputQueue.SendAsync(((char)(97 + i)).ToString());
}
InputQueue.Complete();
await Handler.Completion;
</code>```

Also note that if you need some interaction with UI, you may use your last block as IObservable with Rx.Net library.

Body:
I'm wondering if there is a neat way for IDataflowBlock.Completion to replace needing to use a cancellation token for ReceiveAsync or a similar method which consumes from BufferBlock or another IDataflowBlock.

IDataflowBlock.ReceiveAsync<T>(TimeSpan, CancellationToken)

If InputQueue is a BufferBlock:

BufferBlock<String> InputQueue

for (int i = 0; i < 26; i++)
{
    await InputQueue.SendAsync(((char)(97 + i)).ToString());
}

If InputQueue.Complete(); has been called, then when the queue is emptied and IDataflowBlock.Completion will change to status RanToCompletion,
which can be checked with IDataflowBlock.Completion.IsCompleted.

If multiple threads are taking from the queue this could happen during InputQueue.ReceiveAsync, is there a neater alternative to handle InputQueue completing than:

try
{
    String parcel = await InputQueue.ReceiveAsync(timeSpan);
}
catch(InvalidOperationException x)
{

}

Body:
The simplest way to cancel a Dataflow Block is to provide the token to block's constructor, like this:

new ExecutionDataflowBlockOptions
{
    CancellationToken = cancellationSource.Token
});

CancellationToken is defined in DataflowBlockOptions class, so even BufferBlock could be canceled.

Why are you implementing the Receive logic by yourself? Is there some restriction no to use the PropagateCompletion with linking your blocks? For example, if your code looks like this:

internal void HandleMessage()
{
    try
    {
        var parcel = await InputQueue.ReceiveAsync(timeSpan);
        // handle parsel
    }
    catch(InvalidOperationException x)
    {
    }
}

Then you simply may use the ActionBlock like this:

var InputQueue = new BufferBlock<string>();
var Handler = new ActionBlock<string>(parcel =>
{
    // handle parsel
});
var linkOptions = new DataflowLinkOptions { PropagateCompletion = true };
InputQueue.LinkTo(Handler, linkOptions);

// now after you call Complete method for InputQueue the completion will be propagated to your Handler block:
for (int i = 0; i < 26; i++)
{
    await InputQueue.SendAsync(((char)(97 + i)).ToString());
}
InputQueue.Complete();
await Handler.Completion;

Also note that if you need some interaction with UI, you may use your last block as IObservable with Rx.Net library.


问:
How do I generate specific JSON output from VB.Net?
Being a VB.Net programmer using VB.Net 2015 community, I come across items in C# that I need to convert to VB, but this time I don't understand what I'm working with.  The website service I'm consuming returns and expects JSON / JOBJECTS structures like:

var token = new {
    iss = PARTNERID,
    product = "twpemp",
    sub = "partner",
    siteInfo = new {
        type = "id",
        id = SITEID
    },
    exp = (Int32)DateTime.UtcNow.Add(new TimeSpan(0, 4, 30)).Subtract(new DateTime(1970, 1, 1)).TotalSeconds
};
```

<p>An online converter converted this into:</p>

<pre class="lang-vb prettyprint-override"><code>Dim EPochTime = DateTime.UtcNow.Add(New TimeSpan(0, 4, 0)).Subtract(New DateTime(1970, 1, 1)).TotalSeconds
Dim Token = New With {
    Key .iss = AccNumber,
    Key .product = "twppartner",
    Key .sub = "partner",
    Key .siteInfo = New With {
        Key .type = "id",
        Key .id = Site},
    Key .exp = EPochTime
}
</code>```

I need to dynamically create this type of structures because the "key name" and values change depending on what was returned and needs to be sent back.  For example, depending on the siteid from above, the returning structure might have stuff like:

```<code>"Results": [
{
  "RecordNumber": 000001,
  "EmployeeCode": "0001",
  "FirstName": "John",
  "MiddleName": "A",
  "LastName": "Dow",
  "Designation": "Worker",
  "Home1": "Press",
},
{
  "RecordNumber": 000002,
  "EmployeeCode": "0002",
  "FirstName": "Jane",
  "MiddleName": "b",
  "LastName": "Dow",
  "Designation": "Helper",
  "Home1": "Office",
}
}
</code>```

For the next client I submit a query for, and eventually need to update with might have:

```<code>"Results": [
{
  "RecordNumber": 12345,
  "EmployeeCode": "231",
  "FirstName": "Erick",
  "MiddleName": "G",
  "LastName": "Smith",
  "Department": "Electrial",
},
{
  "RecordNumber": 732456,
  "EmployeeCode": "853",
  "FirstName": "Fred",
  "MiddleName": "W",
  "LastName": "Kerber",
  "Department": "Electrial",
}
}
</code>```

The difference between the two is one has "Department" and the other doesn't.  This structure changes based on the siteID from the first call.

My main question is how do I create something like this dynamically in VB.NET, and secondarily, exactly what is this type of thing called?  I'm calling it a structure for lack of better words.

答:
If you want a little more flexibility with outputting this stuff in JSON, there are two approaches:

1) You can use Dictionary<string,object> instead of dynamic types.  With the dictionary approach, you can add (or exclude) properties at run-time.  The JSON serializer will output in the same fashion as if you were serializing a dynamic type.

```<code> var dict = new Dictionary<string, object>() { { "key1", "value1"} };
 dict["key2"] = DateTime.Now();
 dict["key3"] = 1234567;
 if (someCondition){
       dict["key4"] = new Dictionary<string, object>() { { "key5", "value5"}, { "key6", "value6"}};
 }
</code>```

2) You can create a class that has ALL the available properties that the JSON structure might include.  For optional properties which are numeric types, make them nullable:

```<code>public class Qwijibo
{
    public int? RecordNumber {get;set;}
    public string EmployeeCode  {get;set;}
    public string FirstName {get;set;}
    public string MiddleName {get;set;}
    public string LastName {get;set;}
    public string Designation {get;set;}
    public string Home1 {get;set;}
    public string Department {get;set;
}
</code>```

The above class may work in both the scenarios you presented.  Properties you don't assign a value to will serialize as null in JSON.  As long as whatever you're transmitting to doesn't get hung up on null values, you're good to go.

Body:
Being a VB.Net programmer using VB.Net 2015 community, I come across items in C# that I need to convert to VB, but this time I don't understand what I'm working with.  The website service I'm consuming returns and expects JSON / JOBJECTS structures like:

var token = new {
    iss = PARTNERID,
    product = "twpemp",
    sub = "partner",
    siteInfo = new {
        type = "id",
        id = SITEID
    },
    exp = (Int32)DateTime.UtcNow.Add(new TimeSpan(0, 4, 30)).Subtract(new DateTime(1970, 1, 1)).TotalSeconds
};

An online converter converted this into:

Dim EPochTime = DateTime.UtcNow.Add(New TimeSpan(0, 4, 0)).Subtract(New DateTime(1970, 1, 1)).TotalSeconds
Dim Token = New With {
    Key .iss = AccNumber,
    Key .product = "twppartner",
    Key .sub = "partner",
    Key .siteInfo = New With {
        Key .type = "id",
        Key .id = Site},
    Key .exp = EPochTime
}

I need to dynamically create this type of structures because the "key name" and values change depending on what was returned and needs to be sent back.  For example, depending on the siteid from above, the returning structure might have stuff like:

"Results": [
{
  "RecordNumber": 000001,
  "EmployeeCode": "0001",
  "FirstName": "John",
  "MiddleName": "A",
  "LastName": "Dow",
  "Designation": "Worker",
  "Home1": "Press",
},
{
  "RecordNumber": 000002,
  "EmployeeCode": "0002",
  "FirstName": "Jane",
  "MiddleName": "b",
  "LastName": "Dow",
  "Designation": "Helper",
  "Home1": "Office",
}
}

For the next client I submit a query for, and eventually need to update with might have:

"Results": [
{
  "RecordNumber": 12345,
  "EmployeeCode": "231",
  "FirstName": "Erick",
  "MiddleName": "G",
  "LastName": "Smith",
  "Department": "Electrial",
},
{
  "RecordNumber": 732456,
  "EmployeeCode": "853",
  "FirstName": "Fred",
  "MiddleName": "W",
  "LastName": "Kerber",
  "Department": "Electrial",
}
}

The difference between the two is one has "Department" and the other doesn't.  This structure changes based on the siteID from the first call.

My main question is how do I create something like this dynamically in VB.NET, and secondarily, exactly what is this type of thing called?  I'm calling it a structure for lack of better words.

Body:
If you want a little more flexibility with outputting this stuff in JSON, there are two approaches:

1) You can use Dictionary<string,object> instead of dynamic types.  With the dictionary approach, you can add (or exclude) properties at run-time.  The JSON serializer will output in the same fashion as if you were serializing a dynamic type.

 var dict = new Dictionary<string, object>() { { "key1", "value1"} };
 dict["key2"] = DateTime.Now();
 dict["key3"] = 1234567;
 if (someCondition){
       dict["key4"] = new Dictionary<string, object>() { { "key5", "value5"}, { "key6", "value6"}};
 }

2) You can create a class that has ALL the available properties that the JSON structure might include.  For optional properties which are numeric types, make them nullable:

public class Qwijibo
{
    public int? RecordNumber {get;set;}
    public string EmployeeCode  {get;set;}
    public string FirstName {get;set;}
    public string MiddleName {get;set;}
    public string LastName {get;set;}
    public string Designation {get;set;}
    public string Home1 {get;set;}
    public string Department {get;set;
}

The above class may work in both the scenarios you presented.  Properties you don't assign a value to will serialize as null in JSON.  As long as whatever you're transmitting to doesn't get hung up on null values, you're good to go.


问:
Is there a way to place images with different height into 3 columns in HTML/CSS?
I have many images given from a source (from a data base, for example). The number and the sizes of the images are arbitrary. I want to place them on a page into 3 columns like this:

But I got this as the result:

My HTML code is (I use a django template):

```<code>{% for photo in object_list %}
    <div class="photos-item"><img src="{{ photo.upload.url }}"></div>
{% endfor %}
</code>```

And CSS is:

```<code>.photos-item {
    float: left;
    padding: 0.3em;
}

.photos-item img {
    width: 300px;
    box-shadow: 2px 2px 3px #888;
    cursor: pointer;
}
</code>```

What's wrong with my code?

答:
Maybe something like this could help?

It's full of examples in the web; all you have to do is use css3 columns layouts, which won't work in Explorer (obviously)

```<code><div id="columns">
    {% for photo in object_list %}
      <figure><img src="{{ photo.upload.url }}"></figure>
    {% endfor %}
</div>
</code>```

CSS

```<code>#columns {
    column-width: 320px;
    column-gap: 15px;
    width: 90%;
    max-width: 1100px;
    margin: 50px auto;
}

div#columns figure {
    background: #fefefe;
    border: 2px solid #fcfcfc;
    box-shadow: 0 1px 2px rgba(34, 25, 25, 0.4);
    margin: 0 2px 15px;
    padding: 15px;
    padding-bottom: 10px;
    transition: opacity .4s ease-in-out;
    display: inline-block;
    column-break-inside: avoid;
}

div#columns figure img {
    width: 100%; height: auto;
    border-bottom: 1px solid #ccc;
    padding-bottom: 15px;
    margin-bottom: 5px;
}
</code>```

Body:
I have many images given from a source (from a data base, for example). The number and the sizes of the images are arbitrary. I want to place them on a page into 3 columns like this:

But I got this as the result:

My HTML code is (I use a django template):

{% for photo in object_list %}

{% endfor %}

And CSS is:

.photos-item {
    float: left;
    padding: 0.3em;
}

.photos-item img {
    width: 300px;
    box-shadow: 2px 2px 3px #888;
    cursor: pointer;
}

What's wrong with my code?

Body:
Maybe something like this could help?

It's full of examples in the web; all you have to do is use css3 columns layouts, which won't work in Explorer (obviously)

<div id="columns">
    {% for photo in object_list %}
      <figure><img src="{{ photo.upload.url }}"></figure>
    {% endfor %}
</div>

CSS

#columns {
    column-width: 320px;
    column-gap: 15px;
    width: 90%;
    max-width: 1100px;
    margin: 50px auto;
}

div#columns figure {
    background: #fefefe;
    border: 2px solid #fcfcfc;
    box-shadow: 0 1px 2px rgba(34, 25, 25, 0.4);
    margin: 0 2px 15px;
    padding: 15px;
    padding-bottom: 10px;
    transition: opacity .4s ease-in-out;
    display: inline-block;
    column-break-inside: avoid;
}

div#columns figure img {
    width: 100%; height: auto;
    border-bottom: 1px solid #ccc;
    padding-bottom: 15px;
    margin-bottom: 5px;
}


问:
Fetch API cannot load file:///android_asset/www/xx/xxx.json. URL scheme "file" is not supported
Using cordova build Android app, and add cordova hot code push plugin to make app update automatically, and using Fetch API to load JSON files which located in current project directory, the problem is when update the app, any JSON files cannot be reload,and throw the error

Fetch API cannot load file:///android_asset/www/xx/xxx.json. URL
  scheme "file" is not supported.

How to solve this Fecth error in Android app? Or is there any plugin that need add to my cordova project?

答:
https://github.com/github/fetch/pull/92#issuecomment-140665932

You may use XMLHttpRequest for loading local assets.


问:
Emacs, C macro backslash stop
I am trying to figure out how to indent backslash in C define macro to certain columns.  The default value is to indent to 72 column max, but i need to indent to 76 and 80 column as well.

Which variable is that?

Title: Emacs, C macro backslash stop

Body: c-backslash-column and c-backslash-max-column.


问:
python pandas read_csv taking forever
I'm trying to load a 128MB file using panda (after googling I found that it's faster than open or np.loadtxt). The file has 1000 lines, each one containing 65K values that are either 0 or 1 separated by a single space.

For some reason it's taking ages and I can't figure out why. 128MB sounds fairly small for me and Matlab loads it in a about a minute.

Here is my (simple) code:

```<code>import os
import numpy as np
import pandas as pd
import time

DATA_DIR='D:\BinaryDescriptors3\ORBLearningIntermediatResults2'
TEST_DIR='yosemite_harris'
OUT_DIR='D:\BinaryDescriptors3\ORBLearningTripletsFinalResults'
PATCH_NUM=1000

data_filename=TEST_DIR+'_' + str(PATCH_NUM) + '_ORBresfile.txt'

data_filepath = os.path.join(DATA_DIR,data_filename)

s=time.time()
print "START"
data =  pd.read_csv(data_filepath,delimiter=' ')

e=time.time()

print e-s
</code>```

It never reached the last line (I gave it 30 minutes before terminating it). Why is reading a small, 128MB file taking so long?

EDIT:

When trying to read only one line using the following command:

data =  pd.read_csv(data_filepath,delimiter=' ', nrows=1)

I get the following error:

```<code>Traceback (most recent call last):
  File "C:\eclipse\plugins\org.python.pydev_3.7.1.201409021729\pysrc\pydevd.py", line 2090, in <module>
    debugger.run(setup['file'], None, None)
  File "C:\eclipse\plugins\org.python.pydev_3.7.1.201409021729\pysrc\pydevd.py", line 1547, in run
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "D:\BinaryDescriptors3\Python\LearnTripletsOrb\LearnTripletsOrb.py", line 18, in <module>
    data =  pd.read_csv(data_filepath,delimiter=' ', nrows=1)
  File "C:\Users\GilLevi\Anaconda\lib\site-packages\pandas\io\parsers.py", line 443, in parser_f
    return _read(filepath_or_buffer, kwds)
  File "C:\Users\GilLevi\Anaconda\lib\site-packages\pandas\io\parsers.py", line 231, in _read
    return parser.read(nrows)
  File "C:\Users\GilLevi\Anaconda\lib\site-packages\pandas\io\parsers.py", line 686, in read
    ret = self._engine.read(nrows)
  File "C:\Users\GilLevi\Anaconda\lib\site-packages\pandas\io\parsers.py", line 1130, in read
    data = self._reader.read(nrows)
  File "parser.pyx", line 727, in pandas.parser.TextReader.read (pandas\parser.c:7146)
  File "parser.pyx", line 774, in pandas.parser.TextReader._read_low_memory (pandas\parser.c:7707)
StopIteration
</code>```

When trying to read a similar file that contains only one line of 65K characters, I also get the following error:

Traceback (most recent call last):
File "C:\eclipse\plugins\org.python.pydev_3.7.1.201409021729\pysrc\pydevd.py", line 2090, in
    debugger.run(setup['file'], None, None)
File "C:\eclipse\plugins\org.python.pydev_3.7.1.201409021729\pysrc\pydevd.py", line 1547, in run
    pydev_imports.execfile(file, globals, locals)  # execute the script
File "D:\BinaryDescriptors3\Python\LearnTripletsOrb\LearnTripletsOrb.py", line 20, in
    data =  pd.read_csv(data_filepath,delimiter=' ', nrows=1)
File "C:\Users\GilLevi\Anaconda\lib\site-packages\pandas\io\parsers.py", line 443, in parser_f
    return _read(filepath_or_buffer, kwds)

File "C:\Users\GilLevi\Anaconda\lib\site-packages\pandas\io\parsers.py", line 231, in _read
    return parser.read(nrows)
  File "C:\Users\GilLevi\Anaconda\lib\site-packages\pandas\io\parsers.py", line 686, in read
    ret = self._engine.read(nrows)
  File "C:\Users\GilLevi\Anaconda\lib\site-packages\pandas\io\parsers.py", line 1130, in read
    data = self._reader.read(nrows)
  File "parser.pyx", line 727, in pandas.parser.TextReader.read (pandas\parser.c:7146)
  File "parser.pyx", line 774, in pandas.parser.TextReader._read_low_memory (pandas\parser.c:7707)
StopIteration

I also trying to produce a similar file that contains 2 lines of 65K but uses "," as a delimiter, and got the same error as in 1 and 2.

If load_csv is not the correct approach, can you please recommend a suitable alternative?

答:
The question is old but I hope others might find the answer useful.
Pandas (less so NumPy) is optimized (and very good) at working with data that has plenty of rows and a limited number of columns (say, a few dozen tops). Your case seems to be the opposite so it is not the right tool for the task.

I would preprocess the data before loading it into a DataFrame and I would swap columns and rows in the DataFrame for further processing. So it goes something like this:

```<code>df = pd.DataFrame(columns=[i for i in range(len(txt))])
txt = open(data_filepath).readlines()
for i, ln in enumerate(txt):
  row_items = ln.split()
  df[i] = row_items
...
</code>```

I believe this is going to be quite fast...

ContentLicense: CC BY-SA 4.0

Title: python pandas read_csv taking forever

Body:
I'm trying to load a 128MB file using panda (after googling I found that it's faster than open or np.loadtxt). The file has 1000 lines, each one containing 65K values that are either 0 or 1 separated by a single space.

For some reason it's taking ages and I can't figure out why. 128MB sounds fairly small for me and Matlab loads it in a about a minute.

Here is my (simple) code:

import os
import numpy as np
import pandas as pd
import time

DATA_DIR='D:\BinaryDescriptors3\ORBLearningIntermediatResults2'
TEST_DIR='yosemite_harris'
OUT_DIR='D:\BinaryDescriptors3\ORBLearningTripletsFinalResults'
PATCH_NUM=1000

data_filename=TEST_DIR+'_' + str(PATCH_NUM) + '_ORBresfile.txt'

data_filepath = os.path.join(DATA_DIR,data_filename)

s=time.time()
print "START"
data =  pd.read_csv(data_filepath,delimiter=' ')

e=time.time()

print e-s

It never reached the last line (I gave it 30 minutes before terminating it). Why is reading a small, 128MB file taking so long?

EDIT:

When trying to read only one line using the following command:

data =  pd.read_csv(data_filepath,delimiter=' ', nrows=1)

I get the following error:

Traceback (most recent call last):
  File "C:\eclipse\plugins\org.python.pydev_3.7.1.201409021729\pysrc\pydevd.py", line 2090, in <module>
    debugger.run(setup['file'], None, None)
  File "C:\eclipse\plugins\org.python.pydev_3.7.1.201409021729\pysrc\pydevd.py", line 1547, in run
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "D:\BinaryDescriptors3\Python\LearnTripletsOrb\LearnTripletsOrb.py", line 18, in <module>
    data =  pd.read_csv(data_filepath,delimiter=' ', nrows=1)
  File "C:\Users\GilLevi\Anaconda\lib\site-packages\pandas\io\parsers.py", line 443, in parser_f
    return _read(filepath_or_buffer, kwds)
  File "C:\Users\GilLevi\Anaconda\lib\site-packages\pandas\io\parsers.py", line 231, in _read
    return parser.read(nrows)
  File "C:\Users\GilLevi\Anaconda\lib\site-packages\pandas\io\parsers.py", line 686, in read
    ret = self._engine.read(nrows)
  File "C:\Users\GilLevi\Anaconda\lib\site-packages\pandas\io\parsers.py", line 1130, in read
    data = self._reader.read(nrows)
  File "parser.pyx", line 727, in pandas.parser.TextReader.read (pandas\parser.c:7146)
  File "parser.pyx", line 774, in pandas.parser.TextReader._read_low_memory (pandas\parser.c:7707)
StopIteration

When trying to read a similar file that contains only one line of 65K characters, I also get the following error:

Traceback (most recent call last):
File "C:\eclipse\plugins\org.python.pydev_3.7.1.201409021729\pysrc\pydevd.py", line 2090, in
    debugger.run(setup['file'], None, None)
File "C:\eclipse\plugins\org.python.pydev_3.7.1.201409021729\pysrc\pydevd.py", line 1547, in run
    pydev_imports.execfile(file, globals, locals)  # execute the script
File "D:\BinaryDescriptors3\Python\LearnTripletsOrb\LearnTripletsOrb.py", line 20, in
    data =  pd.read_csv(data_filepath,delimiter=' ', nrows=1)
File "C:\Users\GilLevi\Anaconda\lib\site-packages\pandas\io\parsers.py", line 443, in parser_f
    return _read(filepath_or_buffer, kwds)

File "C:\Users\GilLevi\Anaconda\lib\site-packages\pandas\io\parsers.py", line 231, in _read
    return parser.read(nrows)
  File "C:\Users\GilLevi\Anaconda\lib\site-packages\pandas\io\parsers.py", line 686, in read
    ret = self._engine.read(nrows)
  File "C:\Users\GilLevi\Anaconda\lib\site-packages\pandas\io\parsers.py", line 1130, in read
    data = self._reader.read(nrows)
  File "parser.pyx", line 727, in pandas.parser.TextReader.read (pandas\parser.c:7146)
  File "parser.pyx", line 774, in pandas.parser.TextReader._read_low_memory (pandas\parser.c:7707)
StopIteration

I also trying to produce a similar file that contains 2 lines of 65K but uses "," as a delimiter, and got the same error as in 1 and 2.

If load_csv is not the correct approach, can you please recommend a suitable alternative?

Body:
The question is old but I hope others might find the answer useful.
Pandas (less so NumPy) is optimized (and very good) at working with data that has plenty of rows and a limited number of columns (say, a few dozen tops). Your case seems to be the opposite so it is not the right tool for the task.

I would preprocess the data before loading it into a DataFrame and I would swap columns and rows in the DataFrame for further processing. So it goes something like this:

df = pd.DataFrame(columns=[i for i in range(len(txt))])
txt = open(data_filepath).readlines()
for i, ln in enumerate(txt):
  row_items = ln.split()
  df[i] = row_items
...

I believe this is going to be quite fast...


问:
:first-child not returning any elements
I must be missing some nuance on the :first-child pseudo-selector. I have the following in my code (where je is a jQuery object corresponding to a node in the DOM):

```<code>const errors = je.find('div.error');
console.log(errors.length + ' errors found');
const firstError = je.find('div.error:first-child');
console.log(firstError.length + ' first errors found ');
</code>```

The above logs:

```<code>1 errors found
0 first errors found
</code>```

If some elements were found, shouldn't I expect the :first-child pseudo-selector to return the first of them?

jFiddle SSCCE here

答:
If some elements were found, shouldn't I expect the :first-child pseudo-selector to return the first of them?

Why would you? If you have a set of elements that may or may not be related by parent, how would :first-child among those elements be meaningful? Even if they did all have the same parent, :first-child would still only match an element if it really is the first child of its parent, as the name implies. If all of the elements in the set are the first child of their respective parents, then :first-child would match all of them.

The first element in a set of matches is represented by :first, not :first-child.

Title: :first-child not returning any elements

Body:
I must be missing some nuance on the :first-child pseudo-selector. I have the following in my code (where je is a jQuery object corresponding to a node in the DOM):

const errors = je.find('div.error');
console.log(errors.length + ' errors found');
const firstError = je.find('div.error:first-child');
console.log(firstError.length + ' first errors found ');

The above logs:

1 errors found
0 first errors found

If some elements were found, shouldn't I expect the :first-child pseudo-selector to return the first of them?

jFiddle SSCCE here


问:
In JavaScript, what is the best way to convert a NodeList to an array?
The DOM method document.querySelectorAll() (and a few others) return a NodeList.

To operate on the list, e.g. using forEach(), the NodeList must first be converted to an Array.

What's the best way to convert the NodeList to an Array?

答:
With ES6 you can simply do:</p>

```<code>const spanList = [...document.querySelectorAll("span")];
</code>```

Body:
With ES6 you can simply do:

const spanList = [...document.querySelectorAll("span")];


问:
Finding isotopes of find corresponding string with two differences exactly predifined
I have a vector of names (sum formulas) e.g.

```<code>"C 4 H 15 O 7"
"C 13 H 17 O 7"
"C 3 Cxiv 1 H 15 O 7"
"C 12 Cxiv 1 H 17 O 7"
"C 24 H 15 O 4"
"C 32 H 13 O 10"
"C 12 Cxiv 1 H 24 N 1"
</code>```

In my data the vector is much longer. So how can I find a universal solution to find matches that differ in the following: Instead of one C there is one Cxiv in the string. All other compounds (H x,O x,N x...) should be the same. In other words I want to find the same sum formulas where one C is substituted by a C14 isotope. As result I want to create a vector that becomes one at the place of a string containing Cxiv if there is a match found and in all other cases becomes 0.
so for the example above the vector would look like this:

```<code>vec
0 0 1 1 0 0 0
</code>```

Is there an easy way to do this?
Many thanks!

答:
Using:

```<code># split each string by space into separate elements in a list
l <- strsplit(x, ' ')

# check which list parts contain 'Cxiv'
i <- sapply(l, function(v) any(v == 'Cxiv'))

# for those that contain 'Cxiv' increase the second number with 1
# and remove the 'Cxiv 1' part
l[i] <- lapply(l[i], function(v) {
  v[2] <- as.character(as.numeric(v[2]) + 1);
  v[-c(which(v == 'Cxiv') + 0:1)]
})

# check which are duplicates
as.integer(duplicated(l))
</code>```

gives:

```<code>[1] 0 0 1 1 0 0 0
</code>```

If you want to meet the requirement as stated in the comment (when the chemical formula with Cxiv comes first), you need to change the last step to:

```<code>as.integer((duplicated(l) | duplicated(l, fromLast = TRUE)) & grepl('Cxiv',x))
</code>```

Tested on new example data (x2) you will get:

```<code>[1] 0 0 1 1 0 1 0 0
</code>```

Used data:

```<code>x <- c("C 4 H 15 O 7","C 13 H 17 O 7","C 3 Cxiv 1 H 15 O 7","C 12 Cxiv 1 H 17 O 7",
       "C 24 H 15 O 4","C 32 H 13 O 10","C 12 Cxiv 1 H 24 N 1")
</code>```

New data:

```<code>x2 <- c("C 4 H 15 O 7","C 13 H 17 O 7","C 3 Cxiv 1 H 15 O 7","C 12 Cxiv 1 H 17 O 7",
        "C 24 H 15 O 4","C 12 Cxiv 1 H 24 N 1","C 32 H 13 O 10","C 13 H 24 N 1")
</code>```

Body:
I have a vector of names (sum formulas) e.g.

"C 4 H 15 O 7"
"C 13 H 17 O 7"
"C 3 Cxiv 1 H 15 O 7"
"C 12 Cxiv 1 H 17 O 7"
"C 24 H 15 O 4"
"C 32 H 13 O 10"
"C 12 Cxiv 1 H 24 N 1"

In my data the vector is much longer. So how can I find a universal solution to find matches that differ in the following: Instead of one C there is one Cxiv in the string. All other compounds (H x,O x,N x...) should be the same. In other words I want to find the same sum formulas where one C is substituted by a C14 isotope. As result I want to create a vector that becomes one at the place of a string containing Cxiv if there is a match found and in all other cases becomes 0.
so for the example above the vector would look like this:

vec
0 0 1 1 0 0 0

Is there an easy way to do this?
Many thanks!

Body:
Using:

# split each string by space into separate elements in a list
l <- strsplit(x, ' ')

# check which list parts contain 'Cxiv'
i <- sapply(l, function(v) any(v == 'Cxiv'))

# for those that contain 'Cxiv' increase the second number with 1
# and remove the 'Cxiv 1' part
l[i] <- lapply(l[i], function(v) {
  v[2] <- as.character(as.numeric(v[2]) + 1);
  v[-c(which(v == 'Cxiv') + 0:1)]
})

# check which are duplicates
as.integer(duplicated(l))

gives:

[1] 0 0 1 1 0 0 0

If you want to meet the requirement as stated in the comment (when the chemical formula with Cxiv comes first), you need to change the last step to:

as.integer((duplicated(l) | duplicated(l, fromLast = TRUE)) & grepl('Cxiv',x))

Tested on new example data (x2) you will get:

[1] 0 0 1 1 0 1 0 0

Used data:

x <- c("C 4 H 15 O 7","C 13 H 17 O 7","C 3 Cxiv 1 H 15 O 7","C 12 Cxiv 1 H 17 O 7",
       "C 24 H 15 O 4","C 32 H 13 O 10","C 12 Cxiv 1 H 24 N 1")

New data:

x2 <- c("C 4 H 15 O 7","C 13 H 17 O 7","C 3 Cxiv 1 H 15 O 7","C 12 Cxiv 1 H 17 O 7",
        "C 24 H 15 O 4","C 12 Cxiv 1 H 24 N 1","C 32 H 13 O 10","C 13 H 24 N 1")


问:
How do I encode URI parameter values?
I want to send a URI as the value of a query/matrix parameter. Before I can append it to an existing URI, I need to encode it according to RFC 2396. For example, given the input:

http://google.com/resource?key=value1 & value2

I expect the output:

http%3a%2f%2fgoogle.com%2fresource%3fkey%3dvalue1%2520%26%2520value2

Neither java.net.URLEncoder nor java.net.URI will generate the right output. URLEncoder is meant for HTML form encoding which is not the same as RFC 2396. URI has no mechanism for encoding a single value at a time so it has no way of knowing that value1 and value2 are part of the same key.

答:
Mmhh I know you've already discarded URLEncoder, but despite of what the docs say, I decided to give it a try.

You said:

For example, given an input:

http://google.com/resource?key=value

I expect the output:

http%3a%2f%2fgoogle.com%2fresource%3fkey%3dvalue

So:

```<code>C:\oreyes\samples\java\URL>type URLEncodeSample.java
import java.net.*;

public class URLEncodeSample {
    public static void main( String [] args ) throws Throwable {
        System.out.println( URLEncoder.encode( args[0], "UTF-8" ));
    }
}

C:\oreyes\samples\java\URL>javac URLEncodeSample.java

C:\oreyes\samples\java\URL>java URLEncodeSample "http://google.com/resource?key=value"
http%3A%2F%2Fgoogle.com%2Fresource%3Fkey%3Dvalue
</code>```

As expected.

What would be the problem with this?

OwnerDisplayName: Gili

Title: How do I encode URI parameter values?

LastEditorDisplayName: Gili

Body:
Mmhh I know you've already discarded URLEncoder, but despite of what the docs say, I decided to give it a try.

You said:

For example, given an input:

http://google.com/resource?key=value

I expect the output:

http%3a%2f%2fgoogle.com%2fresource%3fkey%3dvalue

So:

C:\oreyes\samples\java\URL>type URLEncodeSample.java
import java.net.*;

public class URLEncodeSample {
    public static void main( String [] args ) throws Throwable {
        System.out.println( URLEncoder.encode( args[0], "UTF-8" ));
    }
}

C:\oreyes\samples\java\URL>javac URLEncodeSample.java

C:\oreyes\samples\java\URL>java URLEncodeSample "http://google.com/resource?key=value"
http%3A%2F%2Fgoogle.com%2Fresource%3Fkey%3Dvalue

As expected.

What would be the problem with this?

OwnerDisplayName: Oscar Reyes


问:
Clear image resource from memory after nullifying
I have an Android Activity that needs to be held in memory for the lifetime of the app (don't ask why). The background of this Activity takes up about 12MB of memory. I want to free up this memory space when this Activity isn't being viewed. I tried adding the below code

```<code>@Override
protected void onPause() {
    setBackground(null);
    super.onPause();
}

@Override
protected void onResume() {
    super.onResume();
    setBackgroundResource(R.drawable.bg);
}
</code>```

But this results in the memory space still being allocated. The below tree was retrieved via MAT, and as you can see, there is no direct reference to my app itself.

I suspect the Bitmap is somewhere in memory, waiting to be gc'd, but for whatever reason, it never does.

FYI, I also tried the following

```<code>private Drawable background;

@Override
protected void onResume() {
    background = activity.getResources().getDrawable(R.drawable.bg);
    setBackground(background);
}

@Override
protected void onPause() {
    setBackground(null);
    background = null;
}
</code>```

but that resulted in this madness

答:
Turns out calling

```<code>((BitmapDrawable)background).getBitmap().recycle();
</code>```

clears the data from memory, while nulling the object does not!

Body:
I have an Android Activity that needs to be held in memory for the lifetime of the app (don't ask why). The background of this Activity takes up about 12MB of memory. I want to free up this memory space when this Activity isn't being viewed. I tried adding the below code

@Override
protected void onPause() {
    setBackground(null);
    super.onPause();
}

@Override
protected void onResume() {
    super.onResume();
    setBackgroundResource(R.drawable.bg);
}

But this results in the memory space still being allocated. The below tree was retrieved via MAT, and as you can see, there is no direct reference to my app itself.

I suspect the Bitmap is somewhere in memory, waiting to be gc'd, but for whatever reason, it never does.

FYI, I also tried the following

private Drawable background;

@Override
protected void onResume() {
    background = activity.getResources().getDrawable(R.drawable.bg);
    setBackground(background);
}

@Override
protected void onPause() {
    setBackground(null);
    background = null;
}

but that resulted in this madness

Body:
Turns out calling

((BitmapDrawable)background).getBitmap().recycle();

clears the data from memory, while nulling the object does not!


问:
Why is $0 different between `sh myscript` and `source myscript`?
I have a very simple shell scripts name test.sh:

```<code>[mylinux ~]$ cat test.sh
echo "a"
echo "${0}"
</code>```

However, when I source it and sh it, the results are quite different:

```<code>[mylinux ~]$ sh test.sh
a
test.sh
[mylinux ~]$ source test.sh
array : x, y
0,x
1,x
</code>```

I can't understand the results of source test.sh, and, after I changed the name of test.sh, the results changed also:

```<code>[mylinux ~]$ mv test.sh a.sh
[mylinux ~]$ source a.sh
a
-bash
</code>```

How can I understand this phenomenon?

BTW, the second strange results only exits in one of my remote linux session, in my local linux system, everything works fine. So for sure it's related to the environment, and what I can do to find the fundamental reason?

I found the real problem, that is, even if their is no such a file test.sh, I can even perform source test.sh to get the results:

```<code>[mylinux ~]$ rm test.sh
[mylinux ~]$ source test.sh
array : x, y
0,x
1,x
</code>```

This is quite strange for me...

答: source performs path lookup on its argument if the argument doesn't contain any / characters, so while sh test.sh and source ./test.sh are guaranteed to be running code from a file in the current directory, source test.sh may be running a different script entirely. source test.sh will only run ./test.sh if it doesn't find test.sh in your PATH first.

Body:
I have a very simple shell scripts name test.sh:

[mylinux ~]$ cat test.sh
echo "a"
echo "${0}"

However, when I source it and sh it, the results are quite different:

[mylinux ~]$ sh test.sh
a
test.sh
[mylinux ~]$ source test.sh
array : x, y
0,x
1,x

I can't understand the results of source test.sh, and, after I changed the name of test.sh, the results changed also:

[mylinux ~]$ mv test.sh a.sh
[mylinux ~]$ source a.sh
a
-bash

How can I understand this phenomenon?

BTW, the second strange results only exits in one of my remote linux session, in my local linux system, everything works fine. So for sure it's related to the environment, and what I can do to find the fundamental reason?

I found the real problem, that is, even if their is no such a file test.sh, I can even perform source test.sh to get the results:

[mylinux ~]$ rm test.sh
[mylinux ~]$ source test.sh
array : x, y
0,x
1,x

This is quite strange for me...


问:
To derive a table out of an existing one
```<code>Table:
A | B | C  | D
1   q   123  23
2   w   22   32
3   e   23   21

New table:
A | B | C  | D
1   q   123  C
1   q   23   D
2   w   22   C
2   w   32   D
3   e   23   C
3   e   21   D
</code>```

I want to derive a new table/view from an existing table, where I want the records in the first table to be split by a column name.

C and D are months in the original table. In the new table I want the months to be as records.

The records in the original table for the months (123,23 for 1) should match the months column and be put into another column in the new table.

Please let me know if it is not clear.

答:
Do a UNION ALL, with one select for the c's and one select for the d's.

```<code>select a, b, c, 'c' from tablename
union all
select a, b, d, 'd' from tablename
</code>```

Body:
Table:
A | B | C  | D
1   q   123  23
2   w   22   32
3   e   23   21

New table:
A | B | C  | D
1   q   123  C
1   q   23   D
2   w   22   C
2   w   32   D
3   e   23   C
3   e   21   D

I want to derive a new table/view from an existing table, where I want the records in the first table to be split by a column name.

C and D are months in the original table. In the new table I want the months to be as records.

The records in the original table for the months (123,23 for 1) should match the months column and be put into another column in the new table.

Please let me know if it is not clear.

Body:
Do a UNION ALL, with one select for the c's and one select for the d's.

select a, b, c, 'c' from tablename
union all
select a, b, d, 'd' from tablename


问:
MySQL get the latest products with distinct product_name from a particular month
I've the following product table in my database. I want to get the rows of all the products with distinct product_name added in the month of Dec in the descending order of their id.

```<code>id  product_name    qty month
1   Apple           20  Dec
2   Banana          40  Jan
3   Cherry          60  Jun
4   Apple           25  Dec
5   Banana          50  Dec
6   Papaya          20  Dec
7   Guava           34  Aug
8   Watermelon      55  Mar
9   Apple           75  Dec
10  Orange          32  Dec
</code>```

The resulting table should be as below:

```<code>id  product_name    qty month
10  Orange          32  Dec
9   Apple           75  Dec
6   Papaya          20  Dec
5   Banana          50  Dec
</code>```

So far I've come up with the following query and it doesn't get the result I need.

```<code>SELECT *
FROM product
WHERE month = "Dec"
GROUP BY product_name
ORDER BY id DESC
</code>```

The problem with this query is that it gets the first row/record of Apple rather than last one as shown in table below:

```<code>id  product_name    qty month
10  Orange          32  Dec
6   Papaya          20  Dec
5   Banana          50  Dec
1   Apple           20  Dec
</code>```

Can anyone help me write a proper mysql query for this?

答:
You can use the following query:

```<code>SELECT MAX(id), product_name
FROM product
WHERE month = "Dec"
GROUP BY product_name
</code>```

to get the biggest id per product_name:

Output:

```<code>max_id  product_name
9       Apple
5       Banana
10      Orange
6       Papaya
</code>```

Using the above query as a derived table you can join back to the original table in order to get the rest of the fields:

```<code>SELECT t1.*
FROM product AS t1
INNER JOIN (
   SELECT MAX(id) AS max_id, product_name
   FROM product
   WHERE month = "Dec"
   GROUP BY product_name
) AS t2 ON t1.id = t2.max_id and t1.product_name = t2.product_name
ORDER BY t1.id
</code>```

Demo here

Body:
I've the following product table in my database. I want to get the rows of all the products with distinct product_name added in the month of Dec in the descending order of their id.

id  product_name    qty month
1   Apple           20  Dec
2   Banana          40  Jan
3   Cherry          60  Jun
4   Apple           25  Dec
5   Banana          50  Dec
6   Papaya          20  Dec
7   Guava           34  Aug
8   Watermelon      55  Mar
9   Apple           75  Dec
10  Orange          32  Dec

The resulting table should be as below:

id  product_name    qty month
10  Orange          32  Dec
9   Apple           75  Dec
6   Papaya          20  Dec
5   Banana          50  Dec

So far I've come up with the following query and it doesn't get the result I need.

SELECT *
FROM product
WHERE month = "Dec"
GROUP BY product_name
ORDER BY id DESC

The problem with this query is that it gets the first row/record of Apple rather than last one as shown in table below:

id  product_name    qty month
10  Orange          32  Dec
6   Papaya          20  Dec
5   Banana          50  Dec
1   Apple           20  Dec

Can anyone help me write a proper mysql query for this?

Body:
You can use the following query:

SELECT MAX(id), product_name
FROM product
WHERE month = "Dec"
GROUP BY product_name

to get the biggest id per product_name:

Output:

max_id  product_name
9       Apple
5       Banana
10      Orange
6       Papaya

Using the above query as a derived table you can join back to the original table in order to get the rest of the fields:

SELECT t1.*
FROM product AS t1
INNER JOIN (
   SELECT MAX(id) AS max_id, product_name
   FROM product
   WHERE month = "Dec"
   GROUP BY product_name
) AS t2 ON t1.id = t2.max_id and t1.product_name = t2.product_name
ORDER BY t1.id

Demo here


问:
Apache POI numbered list
I am using apache-poi to write some data in a MS Word document. I've already spent several hours trying to figure out how to create a numbered list but I haven't achieved any results.

I've gone through this, that and multiple other questions. Taking into account that apache-poi has the worst kind of documentation I've ever seen (basically there's no documentation at all) and their classes and methods have absolutely mad names it's too difficult for me to understand such complex examples.

Q: Could anyone provide a concise code snippet to create such a list in MS Word document:

One

Two

Three

Thank's in advance.

答:
First I thought there is an issue with my code linked in your question, since apache poi is highly in development and sometimes code which has worked in earlier versions does not work any more in current versions. But simple copy&paste code leads to working code even in current version 3.16.

So I have removed all the table stuff, since the linked question was about a list in table cells and I got:

```<code>import java.io.FileOutputStream;

import org.apache.poi.xwpf.usermodel.*;

import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTAbstractNum;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTLvl;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STNumberFormat;

import java.util.ArrayList;
import java.util.Arrays;

import java.math.BigInteger;

public class CreateWordSimplestNumberingList {

 public static void main(String[] args) throws Exception {

  XWPFDocument document = new XWPFDocument();

  XWPFParagraph paragraph = document.createParagraph();
  XWPFRun run=paragraph.createRun();
  run.setText("The list:");

  ArrayList<String> documentList = new ArrayList<String>(
   Arrays.asList(
    new String[] {
     "One",
     "Two",
     "Three"
    }));

  CTAbstractNum cTAbstractNum = CTAbstractNum.Factory.newInstance();
  //Next we set the AbstractNumId. This requires care.
  //Since we are in a new document we can start numbering from 0.
  //But if we have an existing document, we must determine the next free number first.
  cTAbstractNum.setAbstractNumId(BigInteger.valueOf(0));

/* Bullet list
  CTLvl cTLvl = cTAbstractNum.addNewLvl();
  cTLvl.setIlvl(BigInteger.valueOf(0)); // set indent level 0
  cTLvl.addNewNumFmt().setVal(STNumberFormat.BULLET);
  cTLvl.addNewLvlText().setVal("•");
*/

///* Decimal list
  CTLvl cTLvl = cTAbstractNum.addNewLvl();
  cTLvl.setIlvl(BigInteger.valueOf(0)); // set indent level 0
  cTLvl.addNewNumFmt().setVal(STNumberFormat.DECIMAL);
  cTLvl.addNewLvlText().setVal("%1.");
  cTLvl.addNewStart().setVal(BigInteger.valueOf(1));
//*/

  XWPFAbstractNum abstractNum = new XWPFAbstractNum(cTAbstractNum);

  XWPFNumbering numbering = document.createNumbering();

  BigInteger abstractNumID = numbering.addAbstractNum(abstractNum);

  BigInteger numID = numbering.addNum(abstractNumID);

  for (String string : documentList) {
   paragraph = document.createParagraph();
   paragraph.setNumID(numID);
   run=paragraph.createRun();
   run.setText(string);
  }

  paragraph = document.createParagraph();

  FileOutputStream out = new FileOutputStream("CreateWordSimplestNumberingList.docx");
  document.write(out);
  out.close();
  document.close();

 }
}
</code>```

This results in:

What you need to know is, that a *.docx file is simply a ZIP file containing a directory structure with XMLfiles in it. So what I do if I have the requirement to create a special Word document, is to create the simplest form of that document using Word itself. Then I unzip the *.docx file and find the main story in /word/document.xml. With numberings (lists) I find there:

```<code><w:numId w:val="1"/>
</code>```

within the paragraphs. This are references to mumIds in /word/numbering.xml. Well have a look at this, I find something like:

```<code><w:numbering>
 <w:abstractNum w:abstractNumId="0">
  <w:lvl>
   <w:start w:val="1"/>
   <w:numFmt w:val="decimal"/>
   <w:lvlText w:val="%1."/>
  </w:lvl>
 </w:abstractNum>
 <w:num w:numId="1">
  <w:abstractNumId w:val="0"/>
 </w:num>
</w:numbering>
</code>```

A abstractNum having the definition for levels (lvl) of the numbering and a num having the numId and a reference to the abstractNum.

Then you need to know that apache poi XWPF bases on org.openxmlformats.schemas.wordprocessingml.x2006.main.*. So we have XWPFNumbering and XWPFAbstractNum but XWPFAbstractNum can only be created using org.openxmlformats.schemas.wordprocessingml.x2006.main.CTAbstractNum So how to find documentation about CTAbstractNum. Well Google it and find http://grepcode.com/file/repo1.maven.org/maven2/org.apache.poi/ooxml-schemas/1.1/org/openxmlformats/schemas/wordprocessingml/x2006/main/CTAbstractNum.java

Title: Apache POI numbered list

Body:
First I thought there is an issue with my code linked in your question, since apache poi is highly in development and sometimes code which has worked in earlier versions does not work any more in current versions. But simple copy&paste code leads to working code even in current version 3.16.

So I have removed all the table stuff, since the linked question was about a list in table cells and I got:

import java.io.FileOutputStream;

import org.apache.poi.xwpf.usermodel.*;

import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTAbstractNum;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTLvl;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STNumberFormat;

import java.util.ArrayList;
import java.util.Arrays;

import java.math.BigInteger;

public class CreateWordSimplestNumberingList {

 public static void main(String[] args) throws Exception {

  XWPFDocument document = new XWPFDocument();

  XWPFParagraph paragraph = document.createParagraph();
  XWPFRun run=paragraph.createRun();
  run.setText("The list:");

  ArrayList<String> documentList = new ArrayList<String>(
   Arrays.asList(
    new String[] {
     "One",
     "Two",
     "Three"
    }));

  CTAbstractNum cTAbstractNum = CTAbstractNum.Factory.newInstance();
  //Next we set the AbstractNumId. This requires care.
  //Since we are in a new document we can start numbering from 0.
  //But if we have an existing document, we must determine the next free number first.
  cTAbstractNum.setAbstractNumId(BigInteger.valueOf(0));

/* Bullet list
  CTLvl cTLvl = cTAbstractNum.addNewLvl();
  cTLvl.setIlvl(BigInteger.valueOf(0)); // set indent level 0
  cTLvl.addNewNumFmt().setVal(STNumberFormat.BULLET);
  cTLvl.addNewLvlText().setVal("•");
*/

///* Decimal list
  CTLvl cTLvl = cTAbstractNum.addNewLvl();
  cTLvl.setIlvl(BigInteger.valueOf(0)); // set indent level 0
  cTLvl.addNewNumFmt().setVal(STNumberFormat.DECIMAL);
  cTLvl.addNewLvlText().setVal("%1.");
  cTLvl.addNewStart().setVal(BigInteger.valueOf(1));
//*/

  XWPFAbstractNum abstractNum = new XWPFAbstractNum(cTAbstractNum);

  XWPFNumbering numbering = document.createNumbering();

  BigInteger abstractNumID = numbering.addAbstractNum(abstractNum);

  BigInteger numID = numbering.addNum(abstractNumID);

  for (String string : documentList) {
   paragraph = document.createParagraph();
   paragraph.setNumID(numID);
   run=paragraph.createRun();
   run.setText(string);
  }

  paragraph = document.createParagraph();

  FileOutputStream out = new FileOutputStream("CreateWordSimplestNumberingList.docx");
  document.write(out);
  out.close();
  document.close();

 }
}

This results in:

What you need to know is, that a *.docx file is simply a ZIP file containing a directory structure with XMLfiles in it. So what I do if I have the requirement to create a special Word document, is to create the simplest form of that document using Word itself. Then I unzip the *.docx file and find the main story in /word/document.xml. With numberings (lists) I find there:

<w:numId w:val="1"/>

within the paragraphs. This are references to mumIds in /word/numbering.xml. Well have a look at this, I find something like:

<w:numbering>
 <w:abstractNum w:abstractNumId="0">
  <w:lvl>
   <w:start w:val="1"/>
   <w:numFmt w:val="decimal"/>
   <w:lvlText w:val="%1."/>
  </w:lvl>
 </w:abstractNum>
 <w:num w:numId="1">
  <w:abstractNumId w:val="0"/>
 </w:num>
</w:numbering>

A abstractNum having the definition for levels (lvl) of the numbering and a num having the numId and a reference to the abstractNum.

Then you need to know that apache poi XWPF bases on org.openxmlformats.schemas.wordprocessingml.x2006.main.*. So we have XWPFNumbering and XWPFAbstractNum but XWPFAbstractNum can only be created using org.openxmlformats.schemas.wordprocessingml.x2006.main.CTAbstractNum So how to find documentation about CTAbstractNum. Well Google it and find http://grepcode.com/file/repo1.maven.org/maven2/org.apache.poi/ooxml-schemas/1.1/org/openxmlformats/schemas/wordprocessingml/x2006/main/CTAbstractNum.java


问:
NotifyDataSetChanged refreshes RecyclerView but scrolls as well.
I have a RecyclerView and one item row needs to be updated like every second (SeekBar). So I call NotifyDataSetChanged once I update the data in the list. UI gets updated but the issue is that the RecyclerView scrolls so that this particular item is either at top or bottom of the screen.
I don't want RecyclerView to scroll.</p>

```<code>// Update Data
    mData.set(mData.indexOf(cardData), cardData);
    // RefreshView
    refreshView() {
       runOnUiThread(new Runnable(){
          notifyDataSetChanged();
         }
     );
</code>```

答: You can update one item using notifyItemChanged(position); and u wont update all data in adapter, you will update only certain item

Body:
I have a RecyclerView and one item row needs to be updated like every second (SeekBar). So I call NotifyDataSetChanged once I update the data in the list. UI gets updated but the issue is that the RecyclerView scrolls so that this particular item is either at top or bottom of the screen.
I don't want RecyclerView to scroll.

// Update Data
    mData.set(mData.indexOf(cardData), cardData);
    // RefreshView
    refreshView() {
       runOnUiThread(new Runnable(){
          notifyDataSetChanged();
         }
     );


问:
Sync code for Promise All
Hi everyone I'm having troubles with my code because of promises are being done in a async way and i need them to be sync. So I have this function to return the value of the two promises inside fullfilled

```<code> ServicesController.prototype.uci = function (device, config, path, section, property, value, apply, commit) {
    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'inicio');

    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'config', config);
    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'path', path);
    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'section', section);
    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'option', property);
    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'value', value);
    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'apply', apply);
    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'commit', commit);

    var values = {};
    values[property] = value;
    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'values', values);

    return Controllers.Ubus.uciRequest('set', {"config": config, "section": section, values}, device)
            .then(function (uciData) {
                createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'uciData', uciData);
                var promises = [];

                if (uciData != null) {
                    createLog('info', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'depois do if do uciData');

                    if (commit) {
                        createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'commit');
                        var p1 = new Promise(function (resolve, reject) {
                            Controllers.Ubus.uciRequest('commit', {"config": config}, device)
                                .then(function (dataCommit) {
                                    if (dataCommit && dataCommit.hasOwnProperty('result') && dataCommit.result[0] == 0) {
                                        createLog('info', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'commit data', dataCommit);
                                        resolve(dataCommit.result[0]);
                                    } else {
                                        reject("no data");
                                    }
                                }).catch(function (err) {
                                    createLog('error', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'error promise commit', err);
                                });
                        });
                        promises.push(p1);
                    }

                    if (apply) {
                        createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'apply');
                        var p2 = new Promise(function (resolve, reject) {
                                Controllers.Ubus.fileExec(device.id, "exec", path, "restart")
                                .then(function (dataApply) {
                                    if (dataApply && dataApply.hasOwnProperty('result') && dataApply.result[0] == 0) {
                                        createLog('info', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'apply data', dataApply);
                                        resolve(dataApply.result[0]);
                                    } else {
                                        reject("no data");
                                    }
                                }).catch(function (err) {
                                    createLog('error', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'error promise apply', err);
                                });
                        });
                        promises.push(p2);
                    }
                    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'promises ', promises);
                }
            }).then(function (promises) {
                createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'promises then', promises);
                Promise.all(promises).then(function (values) {
                    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'promises all', values);
return(values);

                }).catch(function (err) {
                    createLog('error', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'error promise all', err);
                });
            }).catch(function (err) {
                createLog('error', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'error then 2', err);
            });
}
</code>```

By my logs I'm entering in the apply and commit if.

Right now i'm receiving this log:

```<code> [2017-06-08 15:37:39.621] - error: /opt/wscontroller/wscontroller-api/routes/services ServicesController NA uci error promise all {}
</code>```

Anyone can give me some help to solve this problem?

答: The issue is no Promise or other value is actually returned from .then() chained to Controllers.Ubus.uciRequest() calls.

Title: Sync code for Promise All

Body:
Hi everyone I'm having troubles with my code because of promises are being done in a async way and i need them to be sync. So I have this function to return the value of the two promises inside fullfilled

 ServicesController.prototype.uci = function (device, config, path, section, property, value, apply, commit) {
    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'inicio');

    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'config', config);
    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'path', path);
    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'section', section);
    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'option', property);
    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'value', value);
    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'apply', apply);
    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'commit', commit);

    var values = {};
    values[property] = value;
    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'values', values);

    return Controllers.Ubus.uciRequest('set', {"config": config, "section": section, values}, device)
            .then(function (uciData) {
                createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'uciData', uciData);
                var promises = [];

                if (uciData != null) {
                    createLog('info', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'depois do if do uciData');

                    if (commit) {
                        createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'commit');
                        var p1 = new Promise(function (resolve, reject) {
                            Controllers.Ubus.uciRequest('commit', {"config": config}, device)
                                .then(function (dataCommit) {
                                    if (dataCommit && dataCommit.hasOwnProperty('result') && dataCommit.result[0] == 0) {
                                        createLog('info', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'commit data', dataCommit);
                                        resolve(dataCommit.result[0]);
                                    } else {
                                        reject("no data");
                                    }
                                }).catch(function (err) {
                                    createLog('error', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'error promise commit', err);
                                });
                        });
                        promises.push(p1);
                    }

                    if (apply) {
                        createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'apply');
                        var p2 = new Promise(function (resolve, reject) {
                                Controllers.Ubus.fileExec(device.id, "exec", path, "restart")
                                .then(function (dataApply) {
                                    if (dataApply && dataApply.hasOwnProperty('result') && dataApply.result[0] == 0) {
                                        createLog('info', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'apply data', dataApply);
                                        resolve(dataApply.result[0]);
                                    } else {
                                        reject("no data");
                                    }
                                }).catch(function (err) {
                                    createLog('error', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'error promise apply', err);
                                });
                        });
                        promises.push(p2);
                    }
                    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'promises ', promises);
                }
            }).then(function (promises) {
                createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'promises then', promises);
                Promise.all(promises).then(function (values) {
                    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'promises all', values);
return(values);

                }).catch(function (err) {
                    createLog('error', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'error promise all', err);
                });
            }).catch(function (err) {
                createLog('error', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'error then 2', err);
            });
}

By my logs I'm entering in the apply and commit if.

Right now i'm receiving this log:

 [2017-06-08 15:37:39.621] - error: /opt/wscontroller/wscontroller-api/routes/services ServicesController NA uci error promise all {}

Anyone can give me some help to solve this problem?


问:
scrollable segments in ionic 2 (horizontal)
I am trying to do horizontal scroll using segments in ionic2. Here is the code:

home.ts:

```<code><ion-scroll scrollX="true" style="width:100vw;height:350px" >
<ion-segment [(ngModel)]="relationship" color="primary">

      <ion-segment-button value="friends" (ionSelect)="selectedFriends()">
        Friends
      </ion-segment-button>
      <ion-segment-button value="enemies" (ionSelect)="selectedEnemies()">
        Enemies
      </ion-segment-button>
       <ion-segment-button value="enemies" (ionSelect)="selectedEnemies()">
        Enemies
      </ion-segment-button>
      <ion-segment-button value="enemies" (ionSelect)="selectedEnemies()">
        Enemies
      </ion-segment-button>
      <ion-segment-button value="enemies" (ionSelect)="selectedEnemies()">
        Enemies
      </ion-segment-button>
      <ion-segment-button value="enemies" (ionSelect)="selectedEnemies()">
        Enemies
      </ion-segment-button>
      <ion-segment-button value="enemies" (ionSelect)="selectedEnemies()">
        Enemies
      </ion-segment-button>
      <ion-segment-button value="enemies" (ionSelect)="selectedEnemies()">
        Enemies
      </ion-segment-button>
      <ion-segment-button value="enemies" (ionSelect)="selectedEnemies()">
        Enemies
      </ion-segment-button>
      <ion-segment-button value="enemies" (ionSelect)="selectedEnemies()">
        Enemies
      </ion-segment-button>

    </ion-segment>
      </ion-scroll>
</code>```

According to this document, I used the ion-scroll outside the ion-segment, so I am getting the UI like this.

How can I make my name visible depending upon the length of the name and show only 3 to 4 names. After the user scroll, it should show the next names one by one.

答:
this solution is for Ionic2, so the solution was working only for Ionic2

```<code>ion-segment {
    justify-content: space-between;
    overflow: auto;

    &::-webkit-scrollbar {
        width: 0;
        height: 0;
        display: none;
    }

    ion-segment-button.segment-button {
        flex: 1 0 100px;
    }
}
</code>```

this is if you want fixed width tabs, if you want various width you should switch from flex to block/inline-block

```<code>ion-segment {
    display: block;
    white-space: nowrap;
    font-size: 0;
    overflow: auto;

    &::-webkit-scrollbar {
        width: 0;
        height: 0;
        display: none;
    }

    ion-segment-button.segment-button {
        display: inline-block;
        min-width: 100px;
        width: auto;
    }
}
</code>```

here is for various width tabs

as mentioned in the solution by Suraj
find github discussion link here

Body:
I am trying to do horizontal scroll using segments in ionic2. Here is the code:

home.ts:

<ion-scroll scrollX="true" style="width:100vw;height:350px" >
<ion-segment [(ngModel)]="relationship" color="primary">

      <ion-segment-button value="friends" (ionSelect)="selectedFriends()">
        Friends
      </ion-segment-button>
      <ion-segment-button value="enemies" (ionSelect)="selectedEnemies()">
        Enemies
      </ion-segment-button>
       <ion-segment-button value="enemies" (ionSelect)="selectedEnemies()">
        Enemies
      </ion-segment-button>
      <ion-segment-button value="enemies" (ionSelect)="selectedEnemies()">
        Enemies
      </ion-segment-button>
      <ion-segment-button value="enemies" (ionSelect)="selectedEnemies()">
        Enemies
      </ion-segment-button>
      <ion-segment-button value="enemies" (ionSelect)="selectedEnemies()">
        Enemies
      </ion-segment-button>
      <ion-segment-button value="enemies" (ionSelect)="selectedEnemies()">
        Enemies
      </ion-segment-button>
      <ion-segment-button value="enemies" (ionSelect)="selectedEnemies()">
        Enemies
      </ion-segment-button>
      <ion-segment-button value="enemies" (ionSelect)="selectedEnemies()">
        Enemies
      </ion-segment-button>
      <ion-segment-button value="enemies" (ionSelect)="selectedEnemies()">
        Enemies
      </ion-segment-button>

    </ion-segment>
      </ion-scroll>

According to this document, I used the ion-scroll outside the ion-segment, so I am getting the UI like this.

How can I make my name visible depending upon the length of the name and show only 3 to 4 names. After the user scroll, it should show the next names one by one.

Body:
this solution is for Ionic2, so the solution was working only for Ionic2

ion-segment {
    justify-content: space-between;
    overflow: auto;

    &::-webkit-scrollbar {
        width: 0;
        height: 0;
        display: none;
    }

    ion-segment-button.segment-button {
        flex: 1 0 100px;
    }
}

this is if you want fixed width tabs, if you want various width you should switch from flex to block/inline-block

ion-segment {
    display: block;
    white-space: nowrap;
    font-size: 0;
    overflow: auto;

    &::-webkit-scrollbar {
        width: 0;
        height: 0;
        display: none;
    }

    ion-segment-button.segment-button {
        display: inline-block;
        min-width: 100px;
        width: auto;
    }
}

here is for various width tabs

as mentioned in the solution by Suraj
find github discussion link here