问:
Bootstrap grid columns overlapping
I'm trying to make a connect 4 board with bootstrap, but when i add a circle to a new column it overlaps with the circle to its left.

This is my html code (it's an example, there should be 7 columns):

```<code><div class="container">

  <div class="row">
    <div class="col-md-offset-2 col-md-1">
      <a href="#"><div></div></a>
      <a href="#"><div></div></a>
    </div>
    <div class="col-md-1">
      <a href="#"><div></div></a>
      <a href="#"><div></div></a>
    </div>

</div>
</code>```

And this is my css:

```<code>.container{
text-align: center;
}
a div{
  width: 100px;
  height: 100px;
  background-color: #858585;
  border: 4px solid black;
  border-radius: 100%;
  margin-bottom: 2px;
}
</code>```

This is the output:

circles overlapping

Is it because of the size of the circles?

答:
Your circles are overlapping because you're not giving them mkore with than their Bootstrap container. You've got a hard-coded with of 100px, but very narrow column declarations (at col-md-1).

Bootstrap columns always add up to 12. You have a total of four -- two md declarations, plus 2 from offset. The remaining 8 columns are unoccupied. This means that your content will be squished to the left.

Assuming you want seven columns (with the first one offset), you're probably looking for a structure similar to this:

```<code><div class="row">
    <div class="col-md-offset-2 col-md-1"></div>
    <div class="col-md-1"></div>
    <div class="col-md-2"></div>
    <div class="col-md-2"></div>
    <div class="col-md-2"></div>
    <div class="col-md-1"></div>
    <div class="col-md-1"></div>
</div>
</code>```

The above col-md-- declarations all add to 12, and thus occupy the fully width. Note that you can use any combination of widths to sum up to 12 columns -- 3 fours, 4 threes, 6 twos, etc.

To ensure that your circles never esacpe their bounds (and thus overlap), you need to set a max-width of 100%:

```<code>a div{
  max-width: 100%;
}
</code>```

Alternatively, if you only want two columns (as illustrated in your image), you can give them a wider column width. Simply divide (12 - [offset]) by the number of columns you would like, and that's the specification that you should use.

In this case, that's 5, as we subtract the offset of 2 from 12, and then divide the 10 by 2, giving us 5:

```<code><div class="row">
    <div class="col-md-offset-2 col-md-5"></div>
    <div class="col-md-5"></div>
</div>
</code>```

Also, note that you missed the closing
 for
 :)

Hope this helps! :)

Title: Bootstrap grid columns overlapping

Body:
I'm trying to make a connect 4 board with bootstrap, but when i add a circle to a new column it overlaps with the circle to its left.

This is my html code (it's an example, there should be 7 columns):

And this is my css:

.container{
text-align: center;
}
a div{
  width: 100px;
  height: 100px;
  background-color: #858585;
  border: 4px solid black;
  border-radius: 100%;
  margin-bottom: 2px;
}

This is the output:

circles overlapping

Is it because of the size of the circles?

Body:
Your circles are overlapping because you're not giving them mkore with than their Bootstrap container. You've got a hard-coded with of 100px, but very narrow column declarations (at col-md-1).

Bootstrap columns always add up to 12. You have a total of four -- two md declarations, plus 2 from offset. The remaining 8 columns are unoccupied. This means that your content will be squished to the left.

Assuming you want seven columns (with the first one offset), you're probably looking for a structure similar to this:

<div class="row">
    <div class="col-md-offset-2 col-md-1"></div>
    <div class="col-md-1"></div>
    <div class="col-md-2"></div>
    <div class="col-md-2"></div>
    <div class="col-md-2"></div>
    <div class="col-md-1"></div>
    <div class="col-md-1"></div>
</div>

The above col-md-- declarations all add to 12, and thus occupy the fully width. Note that you can use any combination of widths to sum up to 12 columns -- 3 fours, 4 threes, 6 twos, etc.

To ensure that your circles never esacpe their bounds (and thus overlap), you need to set a max-width of 100%:

a div{
  max-width: 100%;
}

Alternatively, if you only want two columns (as illustrated in your image), you can give them a wider column width. Simply divide (12 - [offset]) by the number of columns you would like, and that's the specification that you should use.

In this case, that's 5, as we subtract the offset of 2 from 12, and then divide the 10 by 2, giving us 5:

<div class="row">
    <div class="col-md-offset-2 col-md-5"></div>
    <div class="col-md-5"></div>
</div>

Also, note that you missed the closing </div> for <div class="row"> :)

Hope this helps! :)


来源: stackexchange

问:
I can't transform numeric numbers into time
Here's the structure of the data

What I want to do is to change the form of Time into POSIXct.

Here's what I have tried.

```<code>a <- as.POSIXct(power_consumption$Time, "%H:%M:%S")
Error in as.POSIXlt.character(as.character(x), ...) :
  字符串的格式不够标准明确(The format of the string is not standard enough)

a <- as.POSIXlt(power_consumption$Time, "%H:%M:%S")
Error in as.POSIXlt.character(as.character(x), ...) :
  字符串的格式不够标准明确(The format of the string is not standard enough)

a <- strptime(power_consumption$Time, "%H:%M:%S")
head(a)
[1] NA                        "2017-07-07 17:24:00 CST" "2017-07-07 17:25:00 CST" "2017-07-07 17:26:00 CST" "2017-07-07 17:27:00 CST"
[6] "2017-07-07 17:28:00 CST"
</code>```

I don't think the result is right, for the struction of Time has time only.

What should I do to transform Time into %H:%M:%S? Thanks

答:
By definition POSIX time formats must have a date associated with them. If the date doesn't matter, you can proceed as is, and specify an origin date if you care which will set everything to an arbitrary date you provide.

You can follow @HubertL's advice and construct the full POSIX object, which seems like the most logical option.

Alternatively you can use chron::times() to simply store everything in an HH:MM:SS object. There's also hms::as.hms()

Unless you have a specific reason why you need to keep date and time separate, just construct the full POSIX date/time object.

Also, I should add that by default, POSIXct/lt will assign a date (in this case today's) if you don't provide one, hence all of yours saying 2017-07-07.

ContentLicense: CC BY-SA 3.0

Body:
Here's the structure of the data

What I want to do is to change the form of Time into POSIXct.

Here's what I have tried.

a <- as.POSIXct(power_consumption$Time, "%H:%M:%S")
Error in as.POSIXlt.character(as.character(x), ...) :
  字符串的格式不够标准明确(The format of the string is not standard enough)

a <- as.POSIXlt(power_consumption$Time, "%H:%M:%S")
Error in as.POSIXlt.character(as.character(x), ...) :
  字符串的格式不够标准明确(The format of the string is not standard enough)

a <- strptime(power_consumption$Time, "%H:%M:%S")
head(a)
[1] NA                        "2017-07-07 17:24:00 CST" "2017-07-07 17:25:00 CST" "2017-07-07 17:26:00 CST" "2017-07-07 17:27:00 CST"
[6] "2017-07-07 17:28:00 CST"

I don't think the result is right, for the struction of Time has time only.

What should I do to transform Time into %H:%M:%S? Thanks


问:
Writing outputs to log file and console
In Unix shell, I have a env file (env file defines the parameters required for running the user script like log file name and path, redirect outputs and errors to log file, database connection details, etc) which redirects all the outputs (echo messages) and errors to the log file from the executed script using the following code:

```<code>exec 1>>${LOG_FILE}
exec 2>>${LOG_FILE}
</code>```

The env file is executed at the beginning of each script. Due to the above code in env file all the console outputs that might be user outputs or errors are directly output to the log file which is what I actually needed.

But there are some selective user outputs which I want to be displayed in both the console and the log file. But because of the above code I am not able to do so.

I know that if I remove the above code I can get the desired result for this case, but I will have to manually write all other outputs to the log file which is not an easy task.

Is there a way to get the output in both the console and the log file without removing the above codes?

答:
Try this, it will do the work:</p>

```<code>log_file=$curr_dir/log_file.txt
exec > >(tee -a ${log_file} )
exec 2> >(tee -a ${log_file} >&2)
</code>```

Title: Writing outputs to log file and console

Body:
In Unix shell, I have a env file (env file defines the parameters required for running the user script like log file name and path, redirect outputs and errors to log file, database connection details, etc) which redirects all the outputs (echo messages) and errors to the log file from the executed script using the following code:

exec 1>>${LOG_FILE}
exec 2>>${LOG_FILE}

The env file is executed at the beginning of each script. Due to the above code in env file all the console outputs that might be user outputs or errors are directly output to the log file which is what I actually needed.

But there are some selective user outputs which I want to be displayed in both the console and the log file. But because of the above code I am not able to do so.

I know that if I remove the above code I can get the desired result for this case, but I will have to manually write all other outputs to the log file which is not an easy task.

Is there a way to get the output in both the console and the log file without removing the above codes?

Body:
Try this, it will do the work:

log_file=$curr_dir/log_file.txt
exec > >(tee -a ${log_file} )
exec 2> >(tee -a ${log_file} >&2)


问:
which version of firefox do we need for Selenium 3.3.1?
which version of firefox do we need for Selenium 3.3.1?? I'm trying to use firefox 51 with selenium 3.3.1 and I'm not able to launch the application please let me know which browser do we need to use for selenium 3.3.1</p>

答:
I have a Windows 32 bit machine.

Selenium WebDriver - 3.4.0, Selenium.Support - 3.4.0

Firefox - 54.0 (32 bit)

GeckoDriver (32 bit) downloaded and stored locally - https://github.com/mozilla/geckodriver/releases

Firefox installed and it's 'firefox.exe' path is provided.

Code to launch Firefox Browser below:

```<code>FirefoxDriverService service = FirefoxDriverService.CreateDefaultService(@"C:\GeckoDriver");
service.FirefoxBinaryPath = @"C:\Program Files\Mozilla Firefox\firefox.exe";
driverInstance = new FirefoxDriver(service);
</code>```

Body:
I have a Windows 32 bit machine.

Selenium WebDriver - 3.4.0, Selenium.Support - 3.4.0

Firefox - 54.0 (32 bit)

GeckoDriver (32 bit) downloaded and stored locally - https://github.com/mozilla/geckodriver/releases

Firefox installed and it's 'firefox.exe' path is provided.

Code to launch Firefox Browser below:

FirefoxDriverService service = FirefoxDriverService.CreateDefaultService(@"C:\GeckoDriver");
service.FirefoxBinaryPath = @"C:\Program Files\Mozilla Firefox\firefox.exe";
driverInstance = new FirefoxDriver(service);


问:
How do stateless servers work?
I try to understand this.  Normally each time user login system, server side will create a session, while user client side there is cookie. When people talk about stateless serverside, stateful client side, what do they mean? server side no need use session keep track user? only use cookies on client side to check user? mean if I change server, user will not notice it and still can resume using the service?

How to configure spring-security to to do this?

答:
Tracking a user across servers is tricky for true stateless server side. Most of the time things are sorta stateless server where logins are the exception.  However, the big deal with stateless servers is that it makes clustering very simple so you can scale horizontally.

In Java you can make it stateless using either cookies to store credentials, or using distributed hashes.  Generally, people accept using something like memcache and say they are stateless because the state is stored outside the webserver.  That allows the user to use any webserver in the farm and still be safely authenticated.  In Java we have plenty of distributed hash implementations that you can use with spring so you don't have to use memcache to do this.

The other option is to use cookies to store a cryptographic secure hashed ticket called an HMAC.  Using cookies avoids using the Session so the webserver is stateless.  With HMAC you can sign a block of data that cannot be forged or created by a 3rd party and is guaranteed to be originated from you.  This doesn't require outside server resources (the cache) to authenticate the user so it can scale better, but there are some security concerns you have to be aware of.  FYI Google uses this technique to scale horizontally.  One HMAC's aren't like SHA1 or other cyrpto-hashes.  They require a secret key that has to be on each server in the farm.  That also has to be protected with symmetric encryption key to make sure it's stored securely on the server should someone get ahold of the file.  Also HMACs information is stored in the clear so while you can put the username or email in the cookie the actual crypto hash is available to anyone.  If someone were to get ahold of that cookie they could masquerade as that user.  That's why HMACs are typically valid for only a certain amount of time.  After that they expire so if someone does get ahold of them they can't access that account forever.

So HMACs have this weakness and you should be careful about what applications you use them in.  It would be a really bad idea for Paypal to use this scheme because all I have to do is get your secure cookie then transfer all your funds to me.  The big upside is everything is your app is truly stateless.

The final option is to store your java sessions in a distributed hash.  Php and other platforms will dump their sessions in the database, the poor mans distributed cache, or dump them into memcache.  With Java you can do the same thing.  You can put your session objects into the distributed cache too.  This option has fallen out of favor because people think "cool now I can dump whatever I want into my session and it will be stateless."  However, as with all distributed caches there are limits on transfer speed, replication time, and payload size are linked.  This is true for Java or Memcache.  Keep your sessions small, and this works well.  Throw everything into the session and you go right back to scaling issues you have with a single server.  And really it's probably worse than if you had just made your server stateful because sometimes grid computing is worse than single server.

Update: Here are a list of Java distributed caching libraries you can use to do this:

http://www.manageability.org/blog/stuff/distributed-cache-java

ContentLicense: CC BY-SA 2.5

Title: How do stateless servers work?


问:
Sql Custom Pivot - Is this possible?
I am using sql server 2014

I have a set of data rows like this in #TEMP_TABLE:

```<code>SCORE_ID     DAY_ID      DAY     OPEN    CLOSED     DATE       STATUS
   1          1          Mon     1pm      4pm     1/1/17     green
   2          1          Mon     2pm      4pm     1/1/17     green
   3          1          Mon     3pm      5pm     1/1/17     red
   4          1          Mon     4pm      6pm     1/2/17     yellow
   5          1          Mon     5pm      7pm     1/2/17     yellow

   6          2          Tues    1pm      4pm     1/1/17     green
   7          2          Tues    2pm      4pm     1/1/17     green
   8          2          Tues    3pm      5pm     1/1/17     red
   9          2          Tues    4pm      6pm     1/2/17     yellow
   10         2          Tues    5pm      7pm     1/2/17     yellow

   11         5          Fri     12am     12am    1/1/17     green
</code>```

I want to try and pivot my data table so it can look like this. The column names will always be constant, but the values will vary. We can ignore SCORE_ID and DAY_ID.:

```<code> DATE       STATUS      Mon        Tues      Wed      Thurs       Fri
 1/1/17     green       1-4pm      1-4pm      -         -         12am-12am
 1/1/17     green       2-4pm      2-4pm      -         -         -
 1/1/17     red         3-5pm      3-5pm      -         -         -
 1/2/17     yellow      4-6pm      4-6pm      -         -         -
 1/2/17     yellow      5-7pm      5-7pm      -         -         -
</code>```

I tried to google how to use PIVOT, but I feel like the ones I did find don't really apply to how I want my data to be structured.

```<code>select DATE, STATUS, 'Mon', 'Tues', 'Wed, 'Thurs', Fri'
from (
    select DATE, STATUS
    from #TEMP_TABLE
) d

...
</code>```

Is the way I want to structure it possible?

答:
So generally, no, and here's why... you don't have a distinct way to identify the data set that you're looking for.  You can massage the data a little at a time using common table expressions to get the number of hours like so:

```<code>with CTE as
(select
    DATE,
    STATUS,
    RTRIM([OPEN]) + '-' + CLOSED As 'Hours',
    CAST(DATE AS varchar) + STATUS As 'GroupID',
    DAY
from StackQuestion),
CTE2 as
(select
    DATE,
    STATUS,
    CASE DAY WHEN 'Mon' THEN Hours ELSE '-' END as 'Mon',
    CASE DAY WHEN 'Tues' THEN Hours ELSE '-' END as 'Tues',
    CASE DAY WHEN 'Wed' THEN Hours ELSE '-' END as 'Wed',
    CASE DAY WHEN 'Thurs' THEN Hours ELSE '-' END as 'Thurs',
    CASE DAY WHEN 'Fri' THEN Hours ELSE '-' END as 'Fri',
    HOURS
from CTE)
select * from CTE2
</code>```

And that looks like this:

But that doesn't solve your problem.  So what if we put a pivot table on the first CTE and used that as the basis for the pivot -- I'm going to use CTE here with the same expression it as above (to save space).

```<code>select * from CTE
PIVOT ( MAX(HOURS) for DAY in ([Mon],[Tues],[Wed],[Thurs],[Fri])) as pvt
</code>```

And that result looks like this:

We can get a similar result out of CTE2 with the following:

```<code>select
    DATE,
    STATUS,
    MAX(Mon) as 'Mon',
    MAX(Tues) as 'Tues',
    MAX(Wed) as 'Wed',
    MAX(Thurs) as 'Thurs',
    MAX(Fri) as 'Fri'
from CTE2 group by DATE, STATUS, GroupID
</code>```

But the underlying issue will stay the same -- in that there's no way to identify a 'Status' for a 'Date' that has the same open/closed times.  Even if you were to key it based on those times, the 12am-12pm would be in a different row, and so would subsequent days if they didn't happen to line up with the first days' data.  What you need is some sort of ID that is unique to what you're looking at that will allow you to describe it in the query in such a way that it doesn't trip up the aggregate functions.

Hope this helps...

Title: Sql Custom Pivot - Is this possible?

Body:
I am using sql server 2014

I have a set of data rows like this in #TEMP_TABLE:

SCORE_ID     DAY_ID      DAY     OPEN    CLOSED     DATE       STATUS
   1          1          Mon     1pm      4pm     1/1/17     green
   2          1          Mon     2pm      4pm     1/1/17     green
   3          1          Mon     3pm      5pm     1/1/17     red
   4          1          Mon     4pm      6pm     1/2/17     yellow
   5          1          Mon     5pm      7pm     1/2/17     yellow

   6          2          Tues    1pm      4pm     1/1/17     green
   7          2          Tues    2pm      4pm     1/1/17     green
   8          2          Tues    3pm      5pm     1/1/17     red
   9          2          Tues    4pm      6pm     1/2/17     yellow
   10         2          Tues    5pm      7pm     1/2/17     yellow

   11         5          Fri     12am     12am    1/1/17     green

I want to try and pivot my data table so it can look like this. The column names will always be constant, but the values will vary. We can ignore SCORE_ID and DAY_ID.:

 DATE       STATUS      Mon        Tues      Wed      Thurs       Fri
 1/1/17     green       1-4pm      1-4pm      -         -         12am-12am
 1/1/17     green       2-4pm      2-4pm      -         -         -
 1/1/17     red         3-5pm      3-5pm      -         -         -
 1/2/17     yellow      4-6pm      4-6pm      -         -         -
 1/2/17     yellow      5-7pm      5-7pm      -         -         -

I tried to google how to use PIVOT, but I feel like the ones I did find don't really apply to how I want my data to be structured.

select DATE, STATUS, 'Mon', 'Tues', 'Wed, 'Thurs', Fri'
from (
    select DATE, STATUS
    from #TEMP_TABLE
) d

...

Is the way I want to structure it possible?

Body:
So generally, no, and here's why... you don't have a distinct way to identify the data set that you're looking for.  You can massage the data a little at a time using common table expressions to get the number of hours like so:

with CTE as
(select
    DATE,
    STATUS,
    RTRIM([OPEN]) + '-' + CLOSED As 'Hours',
    CAST(DATE AS varchar) + STATUS As 'GroupID',
    DAY
from StackQuestion),
CTE2 as
(select
    DATE,
    STATUS,
    CASE DAY WHEN 'Mon' THEN Hours ELSE '-' END as 'Mon',
    CASE DAY WHEN 'Tues' THEN Hours ELSE '-' END as 'Tues',
    CASE DAY WHEN 'Wed' THEN Hours ELSE '-' END as 'Wed',
    CASE DAY WHEN 'Thurs' THEN Hours ELSE '-' END as 'Thurs',
    CASE DAY WHEN 'Fri' THEN Hours ELSE '-' END as 'Fri',
    HOURS
from CTE)
select * from CTE2

And that looks like this:

But that doesn't solve your problem.  So what if we put a pivot table on the first CTE and used that as the basis for the pivot -- I'm going to use CTE here with the same expression it as above (to save space).

select * from CTE
PIVOT ( MAX(HOURS) for DAY in ([Mon],[Tues],[Wed],[Thurs],[Fri])) as pvt

And that result looks like this:

We can get a similar result out of CTE2 with the following:

select
    DATE,
    STATUS,
    MAX(Mon) as 'Mon',
    MAX(Tues) as 'Tues',
    MAX(Wed) as 'Wed',
    MAX(Thurs) as 'Thurs',
    MAX(Fri) as 'Fri'
from CTE2 group by DATE, STATUS, GroupID

But the underlying issue will stay the same -- in that there's no way to identify a 'Status' for a 'Date' that has the same open/closed times.  Even if you were to key it based on those times, the 12am-12pm would be in a different row, and so would subsequent days if they didn't happen to line up with the first days' data.  What you need is some sort of ID that is unique to what you're looking at that will allow you to describe it in the query in such a way that it doesn't trip up the aggregate functions.

Hope this helps...


问:
Prevent user to check check box randomly using javascript
I have following test checkboxes. A user can select any checkbox in any order.
My question is how I can use javascript/jquery to prevent user to select checkbox randomly.
I would like user to click first checkbox, than second and so on.

```<code>1 <input type="checkbox" name="sports" value="1"  /><br />

2 <input type="checkbox" name="sports" value="2"  /><br />

3 <input type="checkbox" name="sports" value="3"  /><br />

 4 <input type="checkbox" name="sports" value="4"  />
</code>```

I need help writing script that would only allows to check each of the chckboxx in order  - left to right.

Many Thanks in advance

Re- Edited Question:

```<code>   <div class="siblings">
     <ul>
       <table class="table table-bordered">
      <?php
       $count = 1;

      for($x=0; $x < 5; $x++){
       ?>
      <td>
     <div class="thumb">
      <label for="image <?php echo $count;?>"><img class="img"
     src="http://s5.tinypic.com/30v0ncn_th.jpg"/></label>
     <input type="checkbox" class="chk " id="image <?php echo $count;?>"
      name="tick" value="0" />
      </div>
      </td>

     <?php
     $count++;

     }

      ?>
     </table>
    </ul>
    </div>
    </table>
</code>```

答:
num8er was faster than me, but along the same lines.

window.addEventListener('DOMContentLoaded', () => {
    let checkboxes = document.querySelectorAll('[type="checkbox"]');

    for (let ix = 0; ix < checkboxes.length; ix++) {
        checkboxes[ix].addEventListener('change', toggle);
    }

    function toggle() {
        if (this.checked) {
            let el = this.nextElementSibling;
            while (el && el.tagName !== 'INPUT') {
                el = el.nextElementSibling;
            }
            if(el) el.disabled = false;
        } else {
            let el = this.nextElementSibling;
            while (el) {
                if (el.tagName === 'INPUT') {
                    el.disabled = true;
                    el.checked = false;
                }
                el = el.nextElementSibling;
            }
        }
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="checkbox" name="sports" value="1"  /><br />
<input type="checkbox" name="sports" value="2" disabled /><br />
<input type="checkbox" name="sports" value="3" disabled /><br />
<input type="checkbox" name="sports" value="4" disabled /></code>```

Body:
I have following test checkboxes. A user can select any checkbox in any order.
My question is how I can use javascript/jquery to prevent user to select checkbox randomly.
I would like user to click first checkbox, than second and so on.

1 <input type="checkbox" name="sports" value="1"  />

2 <input type="checkbox" name="sports" value="2"  />

3 <input type="checkbox" name="sports" value="3"  />

 4 <input type="checkbox" name="sports" value="4"  />

I need help writing script that would only allows to check each of the chckboxx in order  - left to right.

Many Thanks in advance

Re- Edited Question:

      <?php
       $count = 1;

      for($x=0; $x < 5; $x++){
       ?>

      <label for="image <?php echo $count;?>">
     <input type="checkbox" class="chk " id="image <?php echo $count;?>"
      name="tick" value="0" />

     <?php
     $count++;

     }

      ?>

Body:
num8er was faster than me, but along the same lines.

window.addEventListener('DOMContentLoaded', () => {
    let checkboxes = document.querySelectorAll('[type="checkbox"]');

    for (let ix = 0; ix < checkboxes.length; ix++) {
        checkboxes[ix].addEventListener('change', toggle);
    }

    function toggle() {
        if (this.checked) {
            let el = this.nextElementSibling;
            while (el && el.tagName !== 'INPUT') {
                el = el.nextElementSibling;
            }
            if(el) el.disabled = false;
        } else {
            let el = this.nextElementSibling;
            while (el) {
                if (el.tagName === 'INPUT') {
                    el.disabled = true;
                    el.checked = false;
                }
                el = el.nextElementSibling;
            }
        }
    }
});

<input type="checkbox" name="sports" value="1"  /><br />
<input type="checkbox" name="sports" value="2" disabled /><br />
<input type="checkbox" name="sports" value="3" disabled /><br />
<input type="checkbox" name="sports" value="4" disabled />


问:
Merge duplicate value in JSON array (underscore or lodash preferable)
I want to merge JSON arrays' some object which have duplicate values of specific key.

I have json Array Like this:

```<code>var data=[
    { type:"XO",
      logID:"213323",
      user:"34324234"
    },
    { type:"YO",
      logID:"2323323",
      user:"1212234"
    },
    { type:"XO",
      logID:"676323323",
      user:"45465412234"
    },
    ,
    { type:"ZO",
      logID:"1231434323",
      user:"35739434"
    }
]
</code>```

Here I want to merge JSON Objects based on key 'type'. so same type will look like this with new key:

```<code>var expectedOutput:[
     {
        type:XO,
        text: [
            {
              logID:"213323",
              user:"34324234"
            },
            {
              logID:"676323323",
              user:"45465412234"
            }
        ]
     },
     { type:"YO",
       text:[
         {
         logID:"2323323",
         user:"1212234"
        }
      ]
     },
     {
       type:"ZO",
       text:[
           {
             logID:"1231434323",
             user:"35739434"
           }
        ]
     }
]
</code>```

答:
You can use lodash#groupBy to group the collection by type, use lodash#map to transform each group object format into a group array format. To remove the type property from the array of text, we'll use a partailly applied lodash#omit function using lodash#partial.

```<code>var result = _(data)
  .groupBy('type')
  .map(function(group, type) {
    return {
      type: type,
      text: _.map(group, _.partial(_.omit, _, 'type'))
    };
  })
  .value();
</code>```

var data = [{
    type: "XO",
    logID: "213323",
    user: "34324234"
  },
  {
    type: "YO",
    logID: "2323323",
    user: "1212234"
  },
  {
    type: "XO",
    logID: "676323323",
    user: "45465412234"
  },
  {
    type: "ZO",
    logID: "1231434323",
    user: "35739434"
  }
];

var result = _(data)
  .groupBy('type')
  .map(function(group, type) {
    return {
      type: type,
      text: _.map(group, _.partial(_.omit, _, 'type'))
    };
  })
  .value();

console.log(result);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script></code>```

Body:
I want to merge JSON arrays' some object which have duplicate values of specific key.

I have json Array Like this:

var data=[
    { type:"XO",
      logID:"213323",
      user:"34324234"
    },
    { type:"YO",
      logID:"2323323",
      user:"1212234"
    },
    { type:"XO",
      logID:"676323323",
      user:"45465412234"
    },
    ,
    { type:"ZO",
      logID:"1231434323",
      user:"35739434"
    }
]

Here I want to merge JSON Objects based on key 'type'. so same type will look like this with new key:

var expectedOutput:[
     {
        type:XO,
        text: [
            {
              logID:"213323",
              user:"34324234"
            },
            {
              logID:"676323323",
              user:"45465412234"
            }
        ]
     },
     { type:"YO",
       text:[
         {
         logID:"2323323",
         user:"1212234"
        }
      ]
     },
     {
       type:"ZO",
       text:[
           {
             logID:"1231434323",
             user:"35739434"
           }
        ]
     }
]

Body:
You can use lodash#groupBy to group the collection by type, use lodash#map to transform each group object format into a group array format. To remove the type property from the array of text, we'll use a partailly applied lodash#omit function using lodash#partial.

var result = _(data)
  .groupBy('type')
  .map(function(group, type) {
    return {
      type: type,
      text: _.map(group, _.partial(_.omit, _, 'type'))
    };
  })
  .value();

var data = [{
    type: "XO",
    logID: "213323",
    user: "34324234"
  },
  {
    type: "YO",
    logID: "2323323",
    user: "1212234"
  },
  {
    type: "XO",
    logID: "676323323",
    user: "45465412234"
  },
  {
    type: "ZO",
    logID: "1231434323",
    user: "35739434"
  }
];

var result = _(data)
  .groupBy('type')
  .map(function(group, type) {
    return {
      type: type,
      text: _.map(group, _.partial(_.omit, _, 'type'))
    };
  })
  .value();

console.log(result);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>


问:
How can I modify this SQL SELECT statement to change non-numeric values?
The dataset I am using can be found here.

I am using SSIS to upload the dataset into MS SQL Server.

I uploaded everything as text, and am trying to create a working table with proper data types by inserting values from the raw table.

```<code>CREATE TABLE [WRK_demographics]
(
        [RowNumber]         INT IDENTITY(1,1)
        ,[DBN]              VARCHAR(10)
        ,[Name]             VARCHAR(1000)
        ,[schoolyear]       VARCHAR(100)
        ,[fl_percent]       FLOAT
        ,[frl_percent]      FLOAT
        ,[total_enrollment] INT
        ,[grade9]           INT
        ,[grade10]          INT
        ,[grade11]          INT
        ,[grade12]          INT
        ,[ell_num]          INT
        ,[ell_percent]      FLOAT
        ,[sped_num]         INT
        ,[sped_percent]     FLOAT
        ,[ctt_num]          INT
        ,[selfcontained_num] INT
        ,[asian_num]        INT
        ,[asian_per]        FLOAT
        ,[black_num]        INT
        ,[black_per]        FLOAT
        ,[hispanic_num]     INT
        ,[hispanic_per]     FLOAT
        ,[white_num]        INT
        ,[white_per]        FLOAT
        ,[male_num]         INT
        ,[male_per]         FLOAT
        ,[female_num]       INT
        ,[female_per]       FLOAT
)

INSERT INTO [WRK_demographics]
(
        [DBN]
        ,[Name]
        ,[schoolyear]
        ,[fl_percent]
        ,[frl_percent]
        ,[total_enrollment]
        ,[grade9]
        ,[grade10]
        ,[grade11]
        ,[grade12]
        ,[ell_num]
        ,[ell_percent]
        ,[sped_num]
        ,[sped_percent]
        ,[ctt_num]
        ,[selfcontained_num]
        ,[asian_num]
        ,[asian_per]
        ,[black_num]
        ,[black_per]
        ,[hispanic_num]
        ,[hispanic_per]
        ,[white_num]
        ,[white_per]
        ,[male_num]
        ,[male_per]
        ,[female_num]
        ,[female_per]
)
SELECT
        [DBN]
        ,[Name]
        ,[schoolyear]
        ,[fl_percent]
        ,[frl_percent]
        ,[total_enrollment]
        ,[grade9]
        ,[grade10]
        ,[grade11]
        ,[grade12]
        ,[ell_num]
        ,[ell_percent]
        ,[sped_num]
        ,[sped_percent]
        ,[ctt_num]
        ,[selfcontained_num]
        ,[asian_num]
        ,[asian_per]
        ,[black_num]
        ,[black_per]
        ,[hispanic_num]
        ,[hispanic_per]
        ,[white_num]
        ,[white_per]
        ,[male_num]
        ,[male_per]
        ,[female_num]
        ,[female_per]
FROM [RAW_demographics_20170706]
</code>```

However, the issue I am having is that for cells where there is no value, there is text instead of a null cell. So, implicit conversion cannot convert the data to int/float. Is there a way I can modify the SELECT statement to update the values of non-numeric cells to NULL? If I didn't have so many columns I would update each one in the raw table like this before inserting into the working table:

```<code>UPDATE [RAW_demographics_20170706]
SET [fl_percent] = NULL
WHERE ISNUMERIC([fl_percent]) <> 1
</code>```

I'm wondering if there is a more efficient path to take.

答: That's what TRY_CAST is for: "Returns a value cast to the specified data type if the cast succeeds; otherwise, returns null."</p>

Body:
The dataset I am using can be found here.

I am using SSIS to upload the dataset into MS SQL Server.

I uploaded everything as text, and am trying to create a working table with proper data types by inserting values from the raw table.

CREATE TABLE [WRK_demographics]
(
        [RowNumber]         INT IDENTITY(1,1)
        ,[DBN]              VARCHAR(10)
        ,[Name]             VARCHAR(1000)
        ,[schoolyear]       VARCHAR(100)
        ,[fl_percent]       FLOAT
        ,[frl_percent]      FLOAT
        ,[total_enrollment] INT
        ,[grade9]           INT
        ,[grade10]          INT
        ,[grade11]          INT
        ,[grade12]          INT
        ,[ell_num]          INT
        ,[ell_percent]      FLOAT
        ,[sped_num]         INT
        ,[sped_percent]     FLOAT
        ,[ctt_num]          INT
        ,[selfcontained_num] INT
        ,[asian_num]        INT
        ,[asian_per]        FLOAT
        ,[black_num]        INT
        ,[black_per]        FLOAT
        ,[hispanic_num]     INT
        ,[hispanic_per]     FLOAT
        ,[white_num]        INT
        ,[white_per]        FLOAT
        ,[male_num]         INT
        ,[male_per]         FLOAT
        ,[female_num]       INT
        ,[female_per]       FLOAT
)

INSERT INTO [WRK_demographics]
(
        [DBN]
        ,[Name]
        ,[schoolyear]
        ,[fl_percent]
        ,[frl_percent]
        ,[total_enrollment]
        ,[grade9]
        ,[grade10]
        ,[grade11]
        ,[grade12]
        ,[ell_num]
        ,[ell_percent]
        ,[sped_num]
        ,[sped_percent]
        ,[ctt_num]
        ,[selfcontained_num]
        ,[asian_num]
        ,[asian_per]
        ,[black_num]
        ,[black_per]
        ,[hispanic_num]
        ,[hispanic_per]
        ,[white_num]
        ,[white_per]
        ,[male_num]
        ,[male_per]
        ,[female_num]
        ,[female_per]
)
SELECT
        [DBN]
        ,[Name]
        ,[schoolyear]
        ,[fl_percent]
        ,[frl_percent]
        ,[total_enrollment]
        ,[grade9]
        ,[grade10]
        ,[grade11]
        ,[grade12]
        ,[ell_num]
        ,[ell_percent]
        ,[sped_num]
        ,[sped_percent]
        ,[ctt_num]
        ,[selfcontained_num]
        ,[asian_num]
        ,[asian_per]
        ,[black_num]
        ,[black_per]
        ,[hispanic_num]
        ,[hispanic_per]
        ,[white_num]
        ,[white_per]
        ,[male_num]
        ,[male_per]
        ,[female_num]
        ,[female_per]
FROM [RAW_demographics_20170706]

However, the issue I am having is that for cells where there is no value, there is text instead of a null cell. So, implicit conversion cannot convert the data to int/float. Is there a way I can modify the SELECT statement to update the values of non-numeric cells to NULL? If I didn't have so many columns I would update each one in the raw table like this before inserting into the working table:

UPDATE [RAW_demographics_20170706]
SET [fl_percent] = NULL
WHERE ISNUMERIC([fl_percent]) <> 1

I'm wondering if there is a more efficient path to take.


问:
DateTime Format Day of Year
Is there a format value for DateTime.ToString("") that will specify the day of the year in three digits?

For example:

Jan 1, 2012 would be 001

Feb 1, 2012 would be 032

Dec 31, 2012 would be 366 (leap year)

Dec 31, 2011 would be 365

答:
I know this is a bit old, but if you absolutely, positively, have to do it in one line of code without access to the DateTime.DayOfYear function (like I had to do today):

```<code>int myDay = floor(Now() - Date(parseInt(Now().ToString("yyyy")), 1, 1)) + 1;
</code>```

Title: DateTime Format Day of Year

Body:
I know this is a bit old, but if you absolutely, positively, have to do it in one line of code without access to the DateTime.DayOfYear function (like I had to do today):

int myDay = floor(Now() - Date(parseInt(Now().ToString("yyyy")), 1, 1)) + 1;


问:
Error while compiling clojurescript with om-tools.dom
Trying this Om & React tutorial https://www.codementor.io/reactjs/tutorial/build-single-page-app-with-react-om-clojurescript . When compiling clojurescript I get an error clojure.lang.ExceptionInfo: Don't know how to create ISeq from: clojure.lang.Symbol at line 1  {:tag :cljs/analysis-error, :file nil, :line 1, :column 1}.

Apparently the reason is in om-tools.dom. Can someone explain what I'm doing wrong?

core.cljs:

```<code>(ns spa-tutorial.core

  (:require [om.core :as om :include-macros true]
            [om-tools.dom :as dom :include-macros true]
            [om-tools.core :refer-macros [defcomponent]]
            [secretary.core :as sec :include-macros true]
            [goog.events :as events]
            [goog.history.EventType :as EventType]))

(enable-console-print!)

(def app-state (atom {:text "Hello world!"}))

(om/root
  (fn [app owner]
    (reify om/IRender
      (render [_]
        (dom/h1 nil (:text app)))))
  app-state
  {:target (. js/document (getElementById "app"))})
</code>```

project.clj:

```<code>(defproject spa-tutorial "0.1.0-SNAPSHOT"
  :description "FIXME: write this!"
  :url "http://example.com/FIXME"
  :dependencies [[org.clojure/clojure "1.6.0"]
                 [org.clojure/clojurescript "0.0-2755"]
                 [org.clojure/core.async "0.1.346.0-17112a-alpha"]
                 [org.omcljs/om "0.8.8"]
                 [prismatic/om-tools "0.4.0"]
                 [http-kit "2.1.19"]
                 [secretary "1.2.3"]]
  :plugins [[lein-cljsbuild "1.0.5"]]
  :source-paths ["src" "target/classes"]
  :clean-targets ["out/spa_tutorial" "out/spa_tutorial.js"]
  :cljsbuild {
    :builds [{:id "spa-tutorial"
              :source-paths ["src"]
              :compiler {
                :main spa-tutorial.core
                :output-to "out/spa_tutorial.js"
                :output-dir "out"
                :optimizations :none
                :verbose true}}]})
</code>```

stacktrace:

```<code>clojure.lang.ExceptionInfo: failed compiling file:out/om_tools/dom.cljs {:file #<File out/om_tools/dom.cljs>}
at clojure.core$ex_info.invoke(core.clj:4403)
at cljs.compiler$compile_file.invoke(compiler.clj:1050)
at cljs.closure$compile_file.invoke(closure.clj:343)
at cljs.closure$eval3178$fn__3179.invoke(closure.clj:394)
at cljs.closure$eval3114$fn__3115$G__3105__3122.invoke(closure.clj:301)
at cljs.closure$compile_from_jar.invoke(closure.clj:386)
at cljs.closure$eval3173$fn__3174.invoke(closure.clj:400)
at cljs.closure$eval3114$fn__3115$G__3105__3122.invoke(closure.clj:301)
at cljs.closure$get_compiled_cljs.invoke(closure.clj:463)
at cljs.closure$cljs_dependencies.invoke(closure.clj:507)
at cljs.closure$add_dependencies.doInvoke(closure.clj:529)
at clojure.lang.RestFn.applyTo(RestFn.java:139)
at clojure.core$apply.invoke(core.clj:626)
at cljs.closure$build.invoke(closure.clj:1081)
at cljs.closure$build.invoke(closure.clj:1020)
at cljsbuild.compiler$compile_cljs$fn__3416.invoke(compiler.clj:81)
at cljsbuild.compiler$compile_cljs.invoke(compiler.clj:80)
at cljsbuild.compiler$run_compiler.invoke(compiler.clj:180)
at user$eval3548$iter__3584__3588$fn__3589$fn__3607.invoke(form-init1935966926108010861.clj:1)
at user$eval3548$iter__3584__3588$fn__3589.invoke(form-init1935966926108010861.clj:1)
at clojure.lang.LazySeq.sval(LazySeq.java:40)
at clojure.lang.LazySeq.seq(LazySeq.java:49)
at clojure.lang.RT.seq(RT.java:484)
at clojure.core$seq.invoke(core.clj:133)
at clojure.core$dorun.invoke(core.clj:2855)
at clojure.core$doall.invoke(core.clj:2871)
at user$eval3548.invoke(form-init1935966926108010861.clj:1)
at clojure.lang.Compiler.eval(Compiler.java:6703)
at clojure.lang.Compiler.eval(Compiler.java:6693)
at clojure.lang.Compiler.load(Compiler.java:7130)
at clojure.lang.Compiler.loadFile(Compiler.java:7086)
at clojure.main$load_script.invoke(main.clj:274)
at clojure.main$init_opt.invoke(main.clj:279)
at clojure.main$initialize.invoke(main.clj:307)
at clojure.main$null_opt.invoke(main.clj:342)
at clojure.main$main.doInvoke(main.clj:420)
at clojure.lang.RestFn.invoke(RestFn.java:421)
at clojure.lang.Var.invoke(Var.java:383)
at clojure.lang.AFn.applyToHelper(AFn.java:156)
at clojure.lang.Var.applyTo(Var.java:700)
at clojure.main.main(main.java:37)
Caused by: clojure.lang.ExceptionInfo: Don't know how to create ISeq
from: clojure.lang.Symbol at line 1  {:tag :cljs/analysis-error, :file
nil, :line 1, :column 1}
at clojure.core$ex_info.invoke(core.clj:4403)
at cljs.analyzer$error.invoke(analyzer.clj:299)
at cljs.analyzer$analyze_seq.invoke(analyzer.clj:1634)
at cljs.analyzer$analyze$fn__1802.invoke(analyzer.clj:1723)
at cljs.analyzer$analyze.invoke(analyzer.clj:1716)
at cljs.analyzer$parse_ns$fn__1819$fn__1824.invoke(analyzer.clj:1801)
at cljs.analyzer$parse_ns$fn__1819.invoke(analyzer.clj:1801)
at cljs.analyzer$parse_ns.invoke(analyzer.clj:1789)
at cljs.compiler$compile_file.invoke(compiler.clj:1032)
... 39 more
Caused by: java.lang.IllegalArgumentException: Don't know how to create
ISeq from: clojure.lang.Symbol
</code>```

答:
Clojure error messages (without clojure.spec) are an acquired taste. The message Don't know how to create ISeq from: clojure.lang.Symbol means that ClojureScript is expecting a sequence (the ISeq interface), but it gets a symbol.

This is because the syntax of :refer-macros true is invalid for the compiler. You are using a newer version of Clojure to compile an old tutorial.

Nowadays ClojureScript expects a sequence of imported macros (e.g., :refer-macros [first-macro second-macro]), and not a boolean symbol (e.g., :refer-macros true). Although the latter syntax was valid in old versions of ClojureScript.

When you update your dependencies to newer version and you remove the :refer-macros the code compiles. I.e.,

project.clj:

```<code>(defproject spa-tutorial "0.1.0-SNAPSHOT"
  :description "FIXME: write this!"
  :url "http://example.com/FIXME"
  :dependencies [[org.clojure/clojure "1.8.0"]
                 [org.clojure/clojurescript "1.9.473"]
                 [org.clojure/core.async "0.3.443"]
                 [org.omcljs/om "1.0.0-beta1"]
                 [prismatic/om-tools "0.4.0"]]
  :plugins [[lein-cljsbuild "1.1.6"]]
  :source-paths ["src" "target/classes"]
  :clean-targets ["out/spa_tutorial" "out/spa_tutorial.js"]
  :cljsbuild {:builds [{:id "spa-tutorial"
                        :source-paths ["src"]
                        :compiler {:main spa-tutorial.core
                                   :output-to "out/spa_tutorial.js"
                                   :output-dir "out"
                                   :optimizations :none
                                   :verbose true}}]})
</code>```

core.cljs:

```<code>(ns spa-tutorial.core
  (:require [om.core :as om]
            [om-tools.dom :as dom]
            [om-tools.core :refer-macros [defcomponent]]
            [goog.events :as events]
            [goog.history.EventType :as EventType]))

(enable-console-print!)

(def app-state (atom {:text "Hello world!"}))

(om/root
 (fn [app owner]
   (reify om/IRender
     (render [_]
       (dom/h1 nil (:text app)))))
 app-state
 {:target (. js/document (getElementById "app"))})
</code>```

I would recommend switching to a newer tutorial that also uses Figwheel (an awesome library that does hot code reloading in the browser). For example the Basic Tutorial of the Om wiki.

Body:
Trying this Om & React tutorial https://www.codementor.io/reactjs/tutorial/build-single-page-app-with-react-om-clojurescript . When compiling clojurescript I get an error clojure.lang.ExceptionInfo: Don't know how to create ISeq from: clojure.lang.Symbol at line 1  {:tag :cljs/analysis-error, :file nil, :line 1, :column 1}.

Apparently the reason is in om-tools.dom. Can someone explain what I'm doing wrong?

core.cljs:

(ns spa-tutorial.core

  (:require [om.core :as om :include-macros true]
            [om-tools.dom :as dom :include-macros true]
            [om-tools.core :refer-macros [defcomponent]]
            [secretary.core :as sec :include-macros true]
            [goog.events :as events]
            [goog.history.EventType :as EventType]))

(enable-console-print!)

(def app-state (atom {:text "Hello world!"}))

(om/root
  (fn [app owner]
    (reify om/IRender
      (render [_]
        (dom/h1 nil (:text app)))))
  app-state
  {:target (. js/document (getElementById "app"))})

project.clj:

(defproject spa-tutorial "0.1.0-SNAPSHOT"
  :description "FIXME: write this!"
  :url "http://example.com/FIXME"
  :dependencies [[org.clojure/clojure "1.6.0"]
                 [org.clojure/clojurescript "0.0-2755"]
                 [org.clojure/core.async "0.1.346.0-17112a-alpha"]
                 [org.omcljs/om "0.8.8"]
                 [prismatic/om-tools "0.4.0"]
                 [http-kit "2.1.19"]
                 [secretary "1.2.3"]]
  :plugins [[lein-cljsbuild "1.0.5"]]
  :source-paths ["src" "target/classes"]
  :clean-targets ["out/spa_tutorial" "out/spa_tutorial.js"]
  :cljsbuild {
    :builds [{:id "spa-tutorial"
              :source-paths ["src"]
              :compiler {
                :main spa-tutorial.core
                :output-to "out/spa_tutorial.js"
                :output-dir "out"
                :optimizations :none
                :verbose true}}]})

stacktrace:

clojure.lang.ExceptionInfo: failed compiling file:out/om_tools/dom.cljs {:file #<File out/om_tools/dom.cljs>}
at clojure.core$ex_info.invoke(core.clj:4403)
at cljs.compiler$compile_file.invoke(compiler.clj:1050)
at cljs.closure$compile_file.invoke(closure.clj:343)
at cljs.closure$eval3178$fn__3179.invoke(closure.clj:394)
at cljs.closure$eval3114$fn__3115$G__3105__3122.invoke(closure.clj:301)
at cljs.closure$compile_from_jar.invoke(closure.clj:386)
at cljs.closure$eval3173$fn__3174.invoke(closure.clj:400)
at cljs.closure$eval3114$fn__3115$G__3105__3122.invoke(closure.clj:301)
at cljs.closure$get_compiled_cljs.invoke(closure.clj:463)
at cljs.closure$cljs_dependencies.invoke(closure.clj:507)
at cljs.closure$add_dependencies.doInvoke(closure.clj:529)
at clojure.lang.RestFn.applyTo(RestFn.java:139)
at clojure.core$apply.invoke(core.clj:626)
at cljs.closure$build.invoke(closure.clj:1081)
at cljs.closure$build.invoke(closure.clj:1020)
at cljsbuild.compiler$compile_cljs$fn__3416.invoke(compiler.clj:81)
at cljsbuild.compiler$compile_cljs.invoke(compiler.clj:80)
at cljsbuild.compiler$run_compiler.invoke(compiler.clj:180)
at user$eval3548$iter__3584__3588$fn__3589$fn__3607.invoke(form-init1935966926108010861.clj:1)
at user$eval3548$iter__3584__3588$fn__3589.invoke(form-init1935966926108010861.clj:1)
at clojure.lang.LazySeq.sval(LazySeq.java:40)
at clojure.lang.LazySeq.seq(LazySeq.java:49)
at clojure.lang.RT.seq(RT.java:484)
at clojure.core$seq.invoke(core.clj:133)
at clojure.core$dorun.invoke(core.clj:2855)
at clojure.core$doall.invoke(core.clj:2871)
at user$eval3548.invoke(form-init1935966926108010861.clj:1)
at clojure.lang.Compiler.eval(Compiler.java:6703)
at clojure.lang.Compiler.eval(Compiler.java:6693)
at clojure.lang.Compiler.load(Compiler.java:7130)
at clojure.lang.Compiler.loadFile(Compiler.java:7086)
at clojure.main$load_script.invoke(main.clj:274)
at clojure.main$init_opt.invoke(main.clj:279)
at clojure.main$initialize.invoke(main.clj:307)
at clojure.main$null_opt.invoke(main.clj:342)
at clojure.main$main.doInvoke(main.clj:420)
at clojure.lang.RestFn.invoke(RestFn.java:421)
at clojure.lang.Var.invoke(Var.java:383)
at clojure.lang.AFn.applyToHelper(AFn.java:156)
at clojure.lang.Var.applyTo(Var.java:700)
at clojure.main.main(main.java:37)
Caused by: clojure.lang.ExceptionInfo: Don't know how to create ISeq
from: clojure.lang.Symbol at line 1  {:tag :cljs/analysis-error, :file
nil, :line 1, :column 1}
at clojure.core$ex_info.invoke(core.clj:4403)
at cljs.analyzer$error.invoke(analyzer.clj:299)
at cljs.analyzer$analyze_seq.invoke(analyzer.clj:1634)
at cljs.analyzer$analyze$fn__1802.invoke(analyzer.clj:1723)
at cljs.analyzer$analyze.invoke(analyzer.clj:1716)
at cljs.analyzer$parse_ns$fn__1819$fn__1824.invoke(analyzer.clj:1801)
at cljs.analyzer$parse_ns$fn__1819.invoke(analyzer.clj:1801)
at cljs.analyzer$parse_ns.invoke(analyzer.clj:1789)
at cljs.compiler$compile_file.invoke(compiler.clj:1032)
... 39 more
Caused by: java.lang.IllegalArgumentException: Don't know how to create
ISeq from: clojure.lang.Symbol

Body:
Clojure error messages (without clojure.spec) are an acquired taste. The message Don't know how to create ISeq from: clojure.lang.Symbol means that ClojureScript is expecting a sequence (the ISeq interface), but it gets a symbol.

This is because the syntax of :refer-macros true is invalid for the compiler. You are using a newer version of Clojure to compile an old tutorial.

Nowadays ClojureScript expects a sequence of imported macros (e.g., :refer-macros [first-macro second-macro]), and not a boolean symbol (e.g., :refer-macros true). Although the latter syntax was valid in old versions of ClojureScript.

When you update your dependencies to newer version and you remove the :refer-macros the code compiles. I.e.,

project.clj:

(defproject spa-tutorial "0.1.0-SNAPSHOT"
  :description "FIXME: write this!"
  :url "http://example.com/FIXME"
  :dependencies [[org.clojure/clojure "1.8.0"]
                 [org.clojure/clojurescript "1.9.473"]
                 [org.clojure/core.async "0.3.443"]
                 [org.omcljs/om "1.0.0-beta1"]
                 [prismatic/om-tools "0.4.0"]]
  :plugins [[lein-cljsbuild "1.1.6"]]
  :source-paths ["src" "target/classes"]
  :clean-targets ["out/spa_tutorial" "out/spa_tutorial.js"]
  :cljsbuild {:builds [{:id "spa-tutorial"
                        :source-paths ["src"]
                        :compiler {:main spa-tutorial.core
                                   :output-to "out/spa_tutorial.js"
                                   :output-dir "out"
                                   :optimizations :none
                                   :verbose true}}]})

core.cljs:

(ns spa-tutorial.core
  (:require [om.core :as om]
            [om-tools.dom :as dom]
            [om-tools.core :refer-macros [defcomponent]]
            [goog.events :as events]
            [goog.history.EventType :as EventType]))

(enable-console-print!)

(def app-state (atom {:text "Hello world!"}))

(om/root
 (fn [app owner]
   (reify om/IRender
     (render [_]
       (dom/h1 nil (:text app)))))
 app-state
 {:target (. js/document (getElementById "app"))})

I would recommend switching to a newer tutorial that also uses Figwheel (an awesome library that does hot code reloading in the browser). For example the Basic Tutorial of the Om wiki.


问:
Can the vsphere apis be used on esx server without connectiong to the vsphere client
Using the vSphere Web Services SDK can the hard disks be added to the VM on a esx server without using any vsphere client.

Any links for the sample code to add the hard disks to VM would be very helpful.

答:
You don't need the vSphere Client SDK - you need the standard vSphere APIs. An easy way to start is using the vSphere management SDK -
 https://code.vmware.com/web/sdk/65/vsphere-management.</p>


问:
Split and sort string array swift 3
I'm looking for the most efficient way to go about this. Say there's an array of objects, mapped out in alphabetical order by names:

```<code>let objectArray = [AnyObject]()
let abcNameObjectArray = ["Amy", "Bernadette", "Brian", "Chris", "Candice"]
</code>```

How would I access all the values in this array that have "A" , "B", or "C" based on the first character of each String value in abcNameObject array, in alphabetical order? I'm trying to unload data and return a specific number of rows in the UITableView's cellForRowAt method and numberOfRowsInSection method based on the number of friends one might have in alphabetical order.
The goal is to split the array into a SET of arrays to populate a table view like the Contacts app and ALSO ACCESS the values for a given section. Perhaps utilizing a dictionary might be better to solve this?

答:
Solution 1:

Posting my comment as answer with code. Check if this will work for you. You can use sections from first array printed below(store dict.keys.sorted() into some array) and use that as key for displaying cells in that section.

```<code>let abcNameObjectArray = ["Amy", "Bernadette", "Brian", "Chris", "Candice", ""]

let dict = abcNameObjectArray.reduce([String: [String]]()) { (key, value) -> [String: [String]] in
    var key = key
    if let first = value.characters.first {
        let prefix = String(describing: first).lowercased()
        var array = key[prefix]

        if array == nil {
            array = []
        }
        array!.append(value)
        key[prefix] = array!.sorted()
    }
    return key
}

print(dict.keys.sorted())
print(dict)
</code>```

Output:

["a", "b", "c"]

["b": ["Bernadette", "Brian"], "a": ["Amy"], "c": ["Candice", "Chris"]]

Solution 2:

Here is one more solution using array of arrays as suggested by rmaddy

```<code>let abcNameObjectArray = ["Amy", "Bernadette", "Brian", "Chris", "Candice", ""]
let unicodeScalarA = UnicodeScalar("a")!

var arrayOfArrays = abcNameObjectArray.reduce([[String]]()) { (output, value) -> [[String]] in
    var output = output

    if output.count < 26 {
        output = (1..<27).map{ _ in return []}
    }

    if let first = value.characters.first {
        let prefix = String(describing: first).lowercased()
        let prefixIndex = Int(UnicodeScalar(prefix)!.value - unicodeScalarA.value)
        var array = output[prefixIndex]
        array.append(value)
        output[prefixIndex] = array.sorted()
    }
    return output
}

arrayOfArrays = arrayOfArrays.filter { $0.count > 0}
print(arrayOfArrays)
</code>```

Output:

[["Amy"], ["Bernadette", "Brian"], ["Chris", "Candice"]]

You can have number of sections as count of this array and each member will give number of cells required in that section.

Title: Split and sort string array swift 3

Body:
I'm looking for the most efficient way to go about this. Say there's an array of objects, mapped out in alphabetical order by names:

let objectArray = [AnyObject]()
let abcNameObjectArray = ["Amy", "Bernadette", "Brian", "Chris", "Candice"]

How would I access all the values in this array that have "A" , "B", or "C" based on the first character of each String value in abcNameObject array, in alphabetical order? I'm trying to unload data and return a specific number of rows in the UITableView's cellForRowAt method and numberOfRowsInSection method based on the number of friends one might have in alphabetical order.
The goal is to split the array into a SET of arrays to populate a table view like the Contacts app and ALSO ACCESS the values for a given section. Perhaps utilizing a dictionary might be better to solve this?

Body:
Solution 1:

Posting my comment as answer with code. Check if this will work for you. You can use sections from first array printed below(store dict.keys.sorted() into some array) and use that as key for displaying cells in that section.

let abcNameObjectArray = ["Amy", "Bernadette", "Brian", "Chris", "Candice", ""]

let dict = abcNameObjectArray.reduce([String: [String]]()) { (key, value) -> [String: [String]] in
    var key = key
    if let first = value.characters.first {
        let prefix = String(describing: first).lowercased()
        var array = key[prefix]

        if array == nil {
            array = []
        }
        array!.append(value)
        key[prefix] = array!.sorted()
    }
    return key
}

print(dict.keys.sorted())
print(dict)

Output:

["a", "b", "c"]

["b": ["Bernadette", "Brian"], "a": ["Amy"], "c": ["Candice", "Chris"]]

Solution 2:

Here is one more solution using array of arrays as suggested by rmaddy

let abcNameObjectArray = ["Amy", "Bernadette", "Brian", "Chris", "Candice", ""]
let unicodeScalarA = UnicodeScalar("a")!

var arrayOfArrays = abcNameObjectArray.reduce([[String]]()) { (output, value) -> [[String]] in
    var output = output

    if output.count < 26 {
        output = (1..<27).map{ _ in return []}
    }

    if let first = value.characters.first {
        let prefix = String(describing: first).lowercased()
        let prefixIndex = Int(UnicodeScalar(prefix)!.value - unicodeScalarA.value)
        var array = output[prefixIndex]
        array.append(value)
        output[prefixIndex] = array.sorted()
    }
    return output
}

arrayOfArrays = arrayOfArrays.filter { $0.count > 0}
print(arrayOfArrays)

Output:

[["Amy"], ["Bernadette", "Brian"], ["Chris", "Candice"]]

You can have number of sections as count of this array and each member will give number of cells required in that section.


问:
Limit number of connections to instances with AWS ELB
We are using AWS classic ELB for our service and our service can only serve x number of requests at a time. If the number of requests are greater than x then we do not want to route those requests to the instance and neither do we want to lose those requests. We would like to limit the number of connections to the instances registered with the ELB. Is there some ELB setting to configure max connections to instances?

Another solution I could find was to use ELB connection draining but based on the ELB doc [1] , using connection draining will mark the instance as OutofService after serving in-flight requests. Does that mean the instance will be terminated and de-registered from ELB after in-flight requests are served? We do not want to terminate and de-register the instances, we just want to limit the number of connections to the instances. Any solutions?

[1] http://docs.aws.amazon.com/elasticloadbalancing/latest/classic/config-conn-drain.html

答:
It appears your situation is:

Users are sending API requests to your Load Balancer

You have several instances associated with your Load Balancer to process those requests

You do not appear to be using Auto Scaling

You do not always have sufficient capacity to respond to incoming requests, but you do not want to lose any of the requests

In situations where requests come at a higher rate than you can process them, you basically have three choices:

You could put the messages into a queue and consume them when capacity is available. You could either put everything in a queue (simple), or only use a queue when things are too busy (more complex).

You could scale to handle the load, either by using Auto Scaling to add additional Amazon EC2 instances or by using AWS Lambda to process the requests (Lambda automatically scales).

You could drop requests that you are unable to process. Unless you have implemented a queue, this is going to happen at some point if requests rise above your capacity to process them.

The best solution is to use AWS Lambda functions rather than requiring Amazon EC2 instances. Lambda can tie directly to AWS API Gateway, which can front-end the API requests and provide security, throttling and caching.

The simplest method is to use Auto Scaling to increase the number of instances to try to handle the volume of requests you have arriving. This is best when there are predictable usage patterns, such as high loads during the day and less load at night. It is less useful when spikes occur in short, unpredictable periods.

To fully guarantee no loss of requests, you would need to use a queue. Rather than requests going directly to your application, you would need an initial layer that receives the request and pushes it into a queue. A backend process would then process the message and return a result that is somehow passed back as a response. (It's more difficult providing responses to messages passed via a queue because there is a disconnect between the request and the response.)


问:
Facing issue while creating an attachment in JIRA with webMethods client
We're facing an issue (http response 415 trying to create an attachment in JIRA). Can you please help resolve our issue? Steps we followed in webMethods

1) getFile load as stream
2) pub.mime:createMimeData
3) pub.mime:addBodyPart (pass the stream from step1 as input, and not setting the content type; we've tried setting application/octet-stream with same results ).
4) pub.mime:getEnvelopeStream.
5) pub.io:streamToString (to verify the Mime created in step 4)
6) pub.client:http (passing envStream creted from step4 to data/mimeStream and loadAs "stream"

Step5 output

Message-ID: <508725916.27.1498892350039.JavaMail.webmethods@bisawswmindv01>
MIME-Version: 1.0
Content-Type: multipart/form-data;boundary="------defined------";name=file;filename=sample.txt
X-Atlassian-Token: nocheck
Authorization: Basic d2AiobWV0aG9kczpBMTJzcjcxYmI=

------=_Part_26_16733932.1498892350039
Message-ID: <1774613176.25.1498892350038.JavaMail.webmethods@bisawswmindv01>
MIME-Version: 1.0
content-type: text/plain
content-transfer-encoding: 7bit
this is a test file: this is a test file

------=_Part_26_16733932.1498892350039--

答:
415 error code is for Unsupported Media Type means,
The request entity has a media type which the server or resource does not support. For example, the client uploads an image as image/svg+xml, but the server requires that images use a different format.

Looks like media type of the attachment you are uploading is not supported by JIRA.


问:
Iframe doesn't stop from reloading in Angular loop
I'm working on a comments section of a forums page where I've used tinyMCE to supply the content. The content or the comment is being added asynchronously in a loop (*ngFor) of pre-existing comments object after being added to the database. The content is being rendered by the innerHTML property that calls a method that returns a decoded html content.

html code:

```<code><div [innerHTML]="trustContent(comment)">
</code>```

the method return:

```<code>this.sanitizer.bypassSecurityTrustHtml(content);
</code>```

The issue however is that every time I add or embed a media (iframes), e.g. youtube video using the editor, all the videos/iframes flickers and reloads endlessly. Any ideas, suggestion and solution are welcomed and appreciated! Thanks :)

答:
after so long you must have found a solution, but I'll write the way I solved mine.

I encountered the same problem that you described and, in my case, the way that i solved it was to save the value of the url in a string instead of using a function.

So instead of having

```<code><div [innerHTML]="trustContent(comment)">
</code>```

i used

```<code><div [innerHTML]="safeContent">
</code>```

and in the component.ts

```<code>safeContent =  this.sanitizer.bypassSecurityTrustHtml(content);
</code>```

This stopped the infinite loop for me

Body:
I'm working on a comments section of a forums page where I've used tinyMCE to supply the content. The content or the comment is being added asynchronously in a loop (*ngFor) of pre-existing comments object after being added to the database. The content is being rendered by the innerHTML property that calls a method that returns a decoded html content.

html code:

the method return:

this.sanitizer.bypassSecurityTrustHtml(content);

The issue however is that every time I add or embed a media (iframes), e.g. youtube video using the editor, all the videos/iframes flickers and reloads endlessly. Any ideas, suggestion and solution are welcomed and appreciated! Thanks :)

Body:
after so long you must have found a solution, but I'll write the way I solved mine.

I encountered the same problem that you described and, in my case, the way that i solved it was to save the value of the url in a string instead of using a function.

So instead of having

<div [innerHTML]="trustContent(comment)">

i used

<div [innerHTML]="safeContent">

and in the component.ts

safeContent =  this.sanitizer.bypassSecurityTrustHtml(content);

This stopped the infinite loop for me


问:
r calling dataframe variable by column number
New to R, how do you perform a regression in R without listing the variable name, but instead the column number?  I have many regression I want to estimate on a loop, I'm trying to do this,

```<code>stepreg<-with(newdata, lm(OutputChg~Furrow))
</code>```

And I want to call Furrow by its column # instead of title.  Is this possible?  As always, any help is greatly appreciated, thank you!

答:
You could construct a formula inside each loop and use it in the regression, something along the lines of</p>

```<code>allnames <- names(iris)[-5] # find names to which you wish to regress

for (name in allnames) {
  myformula <- formula(sprintf("%s ~ Species", name))
  print(summary(lm(myformula, data = iris)))
}
</code>```

Body:
New to R, how do you perform a regression in R without listing the variable name, but instead the column number?  I have many regression I want to estimate on a loop, I'm trying to do this,

stepreg<-with(newdata, lm(OutputChg~Furrow))

And I want to call Furrow by its column # instead of title.  Is this possible?  As always, any help is greatly appreciated, thank you!

Body:
You could construct a formula inside each loop and use it in the regression, something along the lines of

allnames <- names(iris)[-5] # find names to which you wish to regress

for (name in allnames) {
  myformula <- formula(sprintf("%s ~ Species", name))
  print(summary(lm(myformula, data = iris)))
}


问:
Updating a data attribute of a TR with jQuery
I have read many of the answers and I am still not quite sure how to update an attribute of a TR.  The idea of my code is to combine similar rows into one while updating the first row's data-auditidentity attribute.

What in the blue blazes am I missing??  The end result should be one table row for procedure and the data-auditidentity property should have all four comma separated keys.  Trying to update using attr to have all four values comma separated fails.

var uniqueKeys = [];
var resultsTable = $('#results');
$(resultsTable).find('tbody > tr').each(function() {

  var tableName = $(this).find('td:eq(0)').text();
  var tableAction = $(this).find('td:eq(1)').text();
  var uniqueKey = tableName + '#' + tableAction;

  if (uniqueKeys.indexOf(uniqueKey) < 0) {
    uniqueKeys.push(uniqueKey);
  } else {

    var initValue = '',
      newCombinedValues = '',
      auditidentity = '';
    initValue = $(resultsTable).find(" tr td:first-child:contains(" + tableName + ")").parent().attr('data-auditidentity');

    var activityLogId = $(this).data('activitylogid');
    auditidentity = $(this).data('auditidentity');

    newCombinedValues = initValue + "," + auditidentity;

    $(resultsTable).find("tbody tr td:first:contains(" + tableName + ")").parent().attr('data-auditidentity', newCombinedValues);

    // After we have what we need, remove the combined row as we are combining the keys into one row
    //$(this).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>
<table id="results">
<tbody role="alert" aria-live="polite" aria-relevant="all" data-auditidentity="18487179,18487183">
  <tr class="subRow odd" data-activitylogid="6459056" data-auditidentity="18487186" data-auditid="f831583e-d1a9-4e35-ac92-82a5cb48c62e">
    <td class="  sorting_1">Selection</td>
    <td class=" ">Update</td>
  </tr>
  <tr class="subRow even" data-activitylogid="6459056" data-auditidentity="18487179" data-auditid="88506880-632f-4e17-bceb-ebd4e20e435a">
    <td class="  sorting_1">Procedure</td>
    <td class=" ">Update</td>
  </tr>
  <tr class="subRow odd" data-activitylogid="6459056" data-auditidentity="18487181" data-auditid="a2768380-8c4a-4070-9834-900f95db77a2">
    <td class="  sorting_1">Procedure</td>
    <td class=" ">Update</td>
  </tr>
  <tr class="subRow even" data-activitylogid="6459056" data-auditidentity="18487182" data-auditid="cb54deca-2bc4-4b71-ba5a-0e6d075b7b26">
    <td class="  sorting_1">Procedure</td>
    <td class=" ">Update</td>
  </tr>
  <tr class="subRow odd" data-activitylogid="6459056" data-auditidentity="18487183" data-auditid="05803858-aaba-4f9b-9128-fc0c265cfaf6">
    <td class="  sorting_1">Procedure</td>
    <td class=" ">Update</td>
  </tr>
</tbody></table></code>```

The END RESULT SHOULD BE THIS

```<code><table id="results">
<tbody role="alert" aria-live="polite" aria-relevant="all" data-auditidentity="18487179,18487183">
  <tr class="subRow odd" data-activitylogid="6459056" data-auditidentity="18487186" data-auditid="f831583e-d1a9-4e35-ac92-82a5cb48c62e">
    <td class="  sorting_1">Selection</td>
    <td class=" "><a class="auditaction">Update</a></td>
  </tr>
  <tr class="subRow even" data-activitylogid="6459056" data-auditidentity="18487179,18487181,18487182,18487183" data-auditid="88506880-632f-4e17-bceb-ebd4e20e435a">
    <td class="  sorting_1">Procedure</td>
    <td class=" "><a class="auditaction">Update</a></td>
  </tr>
</tbody></table>
</code>```

答:
You can try this piece of jQuery code,

```<code>var uniqueRows = {};
 $('table tr').each(function(){
    var tdValue = $(this).find('td').eq(0).html();
    if(!uniqueRows[tdValue]){
        uniqueRows[tdValue] = $(this);
    } else {
        uniqueRows[tdValue].data('auditidentity',
            uniqueRows[tdValue].data('auditidentity')+','+$(this).data('auditidentity'));
        $(this).remove();
    }
 });
</code>```

Please make sure you select correct table in your code.
Hope it helps

Body:
I have read many of the answers and I am still not quite sure how to update an attribute of a TR.  The idea of my code is to combine similar rows into one while updating the first row's data-auditidentity attribute.

What in the blue blazes am I missing??  The end result should be one table row for procedure and the data-auditidentity property should have all four comma separated keys.  Trying to update using attr to have all four values comma separated fails.

var uniqueKeys = [];
var resultsTable = $('#results');
$(resultsTable).find('tbody > tr').each(function() {

  var tableName = $(this).find('td:eq(0)').text();
  var tableAction = $(this).find('td:eq(1)').text();
  var uniqueKey = tableName + '#' + tableAction;

  if (uniqueKeys.indexOf(uniqueKey) < 0) {
    uniqueKeys.push(uniqueKey);
  } else {

    var initValue = '',
      newCombinedValues = '',
      auditidentity = '';
    initValue = $(resultsTable).find(" tr td:first-child:contains(" + tableName + ")").parent().attr('data-auditidentity');

    var activityLogId = $(this).data('activitylogid');
    auditidentity = $(this).data('auditidentity');

    newCombinedValues = initValue + "," + auditidentity;

    $(resultsTable).find("tbody tr td:first:contains(" + tableName + ")").parent().attr('data-auditidentity', newCombinedValues);

    // After we have what we need, remove the combined row as we are combining the keys into one row
    //$(this).remove();
  }
});

    Selection
    Update

    Procedure
    Update

    Procedure
    Update

    Procedure
    Update

    Procedure
    Update

The END RESULT SHOULD BE THIS

    Selection
    Update

    Procedure
    Update

Body:
You can try this piece of jQuery code,

var uniqueRows = {};
 $('table tr').each(function(){
    var tdValue = $(this).find('td').eq(0).html();
    if(!uniqueRows[tdValue]){
        uniqueRows[tdValue] = $(this);
    } else {
        uniqueRows[tdValue].data('auditidentity',
            uniqueRows[tdValue].data('auditidentity')+','+$(this).data('auditidentity'));
        $(this).remove();
    }
 });

Please make sure you select correct table in your code.
Hope it helps


问:
How can I Sort a List<int> using another List<int>?
I need to Sort a List using another List.
I am trying to use :

```<code>var docsIds = new List<int>() { 1, 7, 4 };
var tileSizes = new List<int>();
tileSizes = tileSizes.OrderBy(x => docsIds.IndexOf());
</code>```

Input : 1,2,3,4,5,6,7

Expected Output: 1,7,4,2,3,5,6

Any help is appreciated.

答:
If tileSizes are distinct and always contain all docsIds, Union can be used for an O(n) complexity:

```<code>tileSizes = docsIds.Union(tileSizes).ToList();        // { 1, 7, 4, 2, 3, 5, 6 }
</code>```

Body:
I need to Sort a List using another List.
I am trying to use :

var docsIds = new List<int>() { 1, 7, 4 };
var tileSizes = new List<int>();
tileSizes = tileSizes.OrderBy(x => docsIds.IndexOf());

Input : 1,2,3,4,5,6,7

Expected Output: 1,7,4,2,3,5,6

Any help is appreciated.

Body:
If tileSizes are distinct and always contain all docsIds, Union can be used for an O(n) complexity:

tileSizes = docsIds.Union(tileSizes).ToList();        // { 1, 7, 4, 2, 3, 5, 6 }


问:
Sql Alchemy can't cast jsonb to boolean
I have the following value I'm pulling from a model, and trying to cast to a boolean. However, when I run the program I get an error stating `can't cast jsonb type to boolean. The value for the jsonb value here is a boolean, so why can't it cast it? What do I need to change?

The data value that I'm trying to get is the boolean out of {"unsubscribe" : "True"}

Here is the line that causes the error.

args.append(Customer.data['unsubscribed'].cast(sqlalchemy.Boolean) == "{}".format(True))

Here is the customer model

```<code>class Customer(Base):
    __tablename__ = 'customers'
    id = Column(UUID, primary_key=True, server_default='uuid_generate_v4()')
    phone_number = Column(String)
    data = Column(JSONB)
    created_at = Column(DateTime, server_default='NOW()')
    updated_at = Column(DateTime, server_default='NOW()')

    @property
    def agent_number(self):
        return self.data["agent"]["phoneNumber"]

    def __repr__(self):
        return '<Customer(id={}, phone_number={}, data={}, created_at={}, updated_at={})>'.format(
            self.id,
            self.phone_number,
            self.data,
            self.created_at,
            self.updated_at
        )
</code>```

答:
As far as PostgreSQL is concerned, the true is a jsonb type, not a SQL boolean type. You can't do

```<code>SELECT 'true'::jsonb::boolean;
</code>```

You also can't do

```<code>SELECT '123'::jsonb::int;
</code>```

You'll need to do some sort of conversion. One way is to convert to varchar using ->>:

```<code>SELECT (('{"unsubscribed": true}'::jsonb)->>'unsubscribed')::boolean;
</code>```

Or, you can use jsonb_to_record:

```<code>SELECT unsubscribed FROM jsonb_to_record('{"unsubscribed": true}'::jsonb) AS o(unsubscribed boolean);
</code>```

As far as SQLAlchemy is concerned, you can do

```<code>Customer.data['unsubscribed'].astext.cast(sqlalchemy.Boolean).is_(True)
</code>```

Or, go the other way

```<code>Customer.data['unsubscribed'] == cast('true', JSONB)
</code>```

Title: Sql Alchemy can't cast jsonb to boolean

Body:
I have the following value I'm pulling from a model, and trying to cast to a boolean. However, when I run the program I get an error stating `can't cast jsonb type to boolean. The value for the jsonb value here is a boolean, so why can't it cast it? What do I need to change?

The data value that I'm trying to get is the boolean out of {"unsubscribe" : "True"}

Here is the line that causes the error.

args.append(Customer.data['unsubscribed'].cast(sqlalchemy.Boolean) == "{}".format(True))

Here is the customer model

class Customer(Base):
    __tablename__ = 'customers'
    id = Column(UUID, primary_key=True, server_default='uuid_generate_v4()')
    phone_number = Column(String)
    data = Column(JSONB)
    created_at = Column(DateTime, server_default='NOW()')
    updated_at = Column(DateTime, server_default='NOW()')

    @property
    def agent_number(self):
        return self.data["agent"]["phoneNumber"]

    def __repr__(self):
        return '<Customer(id={}, phone_number={}, data={}, created_at={}, updated_at={})>'.format(
            self.id,
            self.phone_number,
            self.data,
            self.created_at,
            self.updated_at
        )

Body:
As far as PostgreSQL is concerned, the true is a jsonb type, not a SQL boolean type. You can't do

SELECT 'true'::jsonb::boolean;

You also can't do

SELECT '123'::jsonb::int;

You'll need to do some sort of conversion. One way is to convert to varchar using ->>:

SELECT (('{"unsubscribed": true}'::jsonb)->>'unsubscribed')::boolean;

Or, you can use jsonb_to_record:

SELECT unsubscribed FROM jsonb_to_record('{"unsubscribed": true}'::jsonb) AS o(unsubscribed boolean);

As far as SQLAlchemy is concerned, you can do

Customer.data['unsubscribed'].astext.cast(sqlalchemy.Boolean).is_(True)

Or, go the other way

Customer.data['unsubscribed'] == cast('true', JSONB)


问:
Ignite loading similar data to particular instance
So i'm really new to apache ignite here. What i'm trying to do is load data having similar properties to a single rather than it being loaded to random instances. For example, say that some data of this form:

```<code>ROLL_NO
34569
12349
34439
45329
32359
43549
53259
34229
</code>```

As u can see, the above data is all ending with 9. Say that i have two ignite instances A and B currently running. Is there any way i can load these data ending with 9 to either of the instance A or B and NOT BOTH.

Please let me know if this is possible and if so how to accomplish this. Thanks in advance.

答: First of all, Ignite is a key-value storage, so you need to define what is a key and what is a value. The key should contain some ID that will uniquely identify an entry, and an affinity key that can be the same for multiple entries. All entries with the same affinity key will reside in same partition. Please refer to this page for more details: https://apacheignite.readme.io/docs/affinity-collocation</p>

Body:
So i'm really new to apache ignite here. What i'm trying to do is load data having similar properties to a single rather than it being loaded to random instances. For example, say that some data of this form:

ROLL_NO
34569
12349
34439
45329
32359
43549
53259
34229

As u can see, the above data is all ending with 9. Say that i have two ignite instances A and B currently running. Is there any way i can load these data ending with 9 to either of the instance A or B and NOT BOTH.

Please let me know if this is possible and if so how to accomplish this. Thanks in advance.


问:
Bootstrap grid columns overlapping
I'm trying to make a connect 4 board with bootstrap, but when i add a circle to a new column it overlaps with the circle to its left.

This is my html code (it's an example, there should be 7 columns):

```<code><div class="container">

  <div class="row">
    <div class="col-md-offset-2 col-md-1">
      <a href="#"><div></div></a>
      <a href="#"><div></div></a>
    </div>
    <div class="col-md-1">
      <a href="#"><div></div></a>
      <a href="#"><div></div></a>
    </div>

</div>
</code>```

And this is my css:

```<code>.container{
text-align: center;
}
a div{
  width: 100px;
  height: 100px;
  background-color: #858585;
  border: 4px solid black;
  border-radius: 100%;
  margin-bottom: 2px;
}
</code>```

This is the output:

circles overlapping

Is it because of the size of the circles?

答:
Since bootstrap columns are flexible (in % and not in px) you should set a maximum value in percentage. </p>

```<code>a div{
  width: 200px;
  height: 200px;
  max-width: 100%;
  background-color: #858585;
  border: 4px solid black;
  border-radius: 100%;
  margin-bottom: 2px;
}
</code>```

Title: Bootstrap grid columns overlapping

Body:
I'm trying to make a connect 4 board with bootstrap, but when i add a circle to a new column it overlaps with the circle to its left.

This is my html code (it's an example, there should be 7 columns):

And this is my css:

.container{
text-align: center;
}
a div{
  width: 100px;
  height: 100px;
  background-color: #858585;
  border: 4px solid black;
  border-radius: 100%;
  margin-bottom: 2px;
}

This is the output:

circles overlapping

Is it because of the size of the circles?

Body:
Since bootstrap columns are flexible (in % and not in px) you should set a maximum value in percentage.

a div{
  width: 200px;
  height: 200px;
  max-width: 100%;
  background-color: #858585;
  border: 4px solid black;
  border-radius: 100%;
  margin-bottom: 2px;
}


问:
Has 'find' similar capability as 'ls -visible pname'
I can use "ls -visible pname" to find visible elements under 'pname'.
But through 'find', I can NOT find a way to find just visible elements. That is, 'find' will always list hidden elements by the Config Spec also.

Does anyone know if 'find' can find just 'visible' elements under a specific 'pname'??

Thanks

答:
cleartool man find

http://publib.boulder.ibm.com/infocenter/cchelp/v7r0m1/index.jsp?topic=/com.ibm.rational.clearcase.cc_ref.doc/topics/ct_find.htm

Note: The find command is similar to
  the UNIX and Linux find(1) command.
  Only a limited set of the standard
  find options are supported; the way
  that commands are invoked on selected
  objects (–exec and –ok options)
  differs from find(1).

To answer your question to VonC, no, you are wrong. -visible does not need to work with -all, and you can use -visible to achieve exactly what you want to do.


问:
Trying to understand power function, C Programming Language, 2e, 27
I'm working my way through The C Programming Language, K&R, 2nd edition, page 26, about the power() function, and I'm confused by something:

```<code>int power(int base, int n)
{
    int p;

    for (p = 1; n > 0; --n)
        p = p * base;
    return p;
}
</code>```

How does p get incremented? If the for loop "runs backwards until it becomes zero", why is it n > 0 and not n = 0?

答:
```<code>for (p = 1; n > 0; --n)
</code>```

I don't like this full of tricks style of programming as it makes code more difficult to understand for humans. In such a trivial example it is not the big issue, but in the large & complex code making it even more complex and heavy to read is a horrible programming manner

```<code>int power(int base, int n)
{
    int p = 1;
    int x;

    for (x = 0; x < n; x++)
        p = p * base;
    return p;
}
</code>```

Isn't it easier to read? If you are worried about the additional x variable - do not. It will be optimized out by the compiler. In the K&R era such micro optimisations were necessary buy nowadays, thanks God, we can focus on effective algorithms, leaving the micro optimisations to the compilers - and as practice shows they are much better than 99.99% of the coders

Body:
I'm working my way through The C Programming Language, K&R, 2nd edition, page 26, about the power() function, and I'm confused by something:

int power(int base, int n)
{
    int p;

    for (p = 1; n > 0; --n)
        p = p * base;
    return p;
}

How does p get incremented? If the for loop "runs backwards until it becomes zero", why is it n > 0 and not n = 0?

Body:
for (p = 1; n > 0; --n)

I don't like this full of tricks style of programming as it makes code more difficult to understand for humans. In such a trivial example it is not the big issue, but in the large & complex code making it even more complex and heavy to read is a horrible programming manner

int power(int base, int n)
{
    int p = 1;
    int x;

    for (x = 0; x < n; x++)
        p = p * base;
    return p;
}

Isn't it easier to read? If you are worried about the additional x variable - do not. It will be optimized out by the compiler. In the K&R era such micro optimisations were necessary buy nowadays, thanks God, we can focus on effective algorithms, leaving the micro optimisations to the compilers - and as practice shows they are much better than 99.99% of the coders


问:
Google Drive API - 502 Bad Gateway
As of 7pm Eastern on 7/6/2017 all of my requests to the Google Drive API are returning 502 Bad Gateway error.  I even tried using Google API's Explorer in the browser and am getting the same error.

Here's an example:

Request:

```<code>GET https://www.googleapis.com/drive/v3/files?key={YOUR_API_KEY}
</code>```

Response:

```<code>502

content-length:  1613
content-type:  text/html; charset=UTF-8
date:  Thu, 06 Jul 2017 23:02:40 GMT

<!DOCTYPE html>
<html lang=en>
  <meta charset=utf-8>
  <meta name=viewport content="initial-scale=1, minimum-scale=1,
width=device-width">
  <title>Error 502 (Server Error)!!1</title>
  <style>
    ...
  </style>
  <a href=//www.google.com/><span id=logo aria-label=Google></span></a>
  <p><b>502.</b> <ins>That’s an error.</ins>
  <p>The server encountered a temporary error and could not complete your request.<p>Please try again in 30 seconds.  <ins>That’s all we know.</ins>
</code>```

Are others experiencing this problem?

答: I guess it was just an intermittent problem.  It's fixed now.</p>

Title: Google Drive API - 502 Bad Gateway

Body:
As of 7pm Eastern on 7/6/2017 all of my requests to the Google Drive API are returning 502 Bad Gateway error.  I even tried using Google API's Explorer in the browser and am getting the same error.

Here's an example:

Request:

GET https://www.googleapis.com/drive/v3/files?key={YOUR_API_KEY}

Response:

502

content-length:  1613
content-type:  text/html; charset=UTF-8
date:  Thu, 06 Jul 2017 23:02:40 GMT

<!DOCTYPE html>

  <meta charset=utf-8>
  <meta name=viewport content="initial-scale=1, minimum-scale=1,
width=device-width">
  <title>Error 502 (Server Error)!!1</title>

502. That’s an error.

The server encountered a temporary error and could not complete your request.
Please try again in 30 seconds.  That’s all we know.

Are others experiencing this problem?


问:
Fix absolutely positioned element to top of viewport on scroll
I'm trying to combine the best of both worlds and accomplish what fixed positioning does when you set top: 0 (appends to top of viewport) while keeping the element absolutely positioned so it scrolls horizontally with its parent element (doing this with fixed is problematic).

The catch is this is a table header so trying to hack my way through this with nested divs set to different positioning methods won't work here.

What I currently tried was keeping the table header with a position of absolute while calculating the distance of the top of the table from the top of the viewport within a scroll event listener:

```<code>const distanceToTop = this.headerElement.getBoundingClientRect().top;
this.stickyHeaderElement.style.top = `${Math.abs(distanceToTop)}px`;
</code>```

this.headerElement is the original table header that you can scroll past (does nothing) while the stickyHeader instance is where the smoke & mirrors occurs.

This current method is doing what I want it to... however, it's incredibly hacky because as you scroll past the original table header and the sticky instance appends, the sticky header shakes due to all the DOM manipulation happening every time the event listener fires.

Since it's recalculating with the logic above.

Question: Can I have an absolutely positioned table header element also append to the top of the viewport like fixed positioning allows? Is there a more efficient solution out there?

答:
Sticky Headers are simple when using Position:fixed.

#header_container {
  background: green;
  height: 60px;
  left: 0;
  position: fixed;
  width: 100%;
  top: 0;
}

#header {
  line-height: 60px;
  margin: 0 auto;
  width: 100%;
  text-align: center;
}

#container {
  margin: 0 auto;
  overflow: auto;
  padding: 80px 0;
  width: 100%;
}

#content {
  height: 500px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="header_container">
  <div id="header">
    Header Content
  </div>
</div>

<div id="container">
  <div id="content">
    Content Here
  </div>
</div></code>```

Body:
I'm trying to combine the best of both worlds and accomplish what fixed positioning does when you set top: 0 (appends to top of viewport) while keeping the element absolutely positioned so it scrolls horizontally with its parent element (doing this with fixed is problematic).

The catch is this is a table header so trying to hack my way through this with nested divs set to different positioning methods won't work here.

What I currently tried was keeping the table header with a position of absolute while calculating the distance of the top of the table from the top of the viewport within a scroll event listener:

const distanceToTop = this.headerElement.getBoundingClientRect().top;
this.stickyHeaderElement.style.top = `${Math.abs(distanceToTop)}px`;

this.headerElement is the original table header that you can scroll past (does nothing) while the stickyHeader instance is where the smoke & mirrors occurs.

This current method is doing what I want it to... however, it's incredibly hacky because as you scroll past the original table header and the sticky instance appends, the sticky header shakes due to all the DOM manipulation happening every time the event listener fires.

Since it's recalculating with the logic above.

Question: Can I have an absolutely positioned table header element also append to the top of the viewport like fixed positioning allows? Is there a more efficient solution out there?

Body:
Sticky Headers are simple when using Position:fixed.

#header_container {
  background: green;
  height: 60px;
  left: 0;
  position: fixed;
  width: 100%;
  top: 0;
}

#header {
  line-height: 60px;
  margin: 0 auto;
  width: 100%;
  text-align: center;
}

#container {
  margin: 0 auto;
  overflow: auto;
  padding: 80px 0;
  width: 100%;
}

#content {
  height: 500px;
}

<div id="header_container">
  <div id="header">
    Header Content
  </div>
</div>

<div id="container">
  <div id="content">
    Content Here
  </div>
</div>


问:
Clojurescript macros: Using the node api at compile time
I'm writing a cli script with lumo and I want the following macro, but using readFileSync from nodejs.

```<code>(defmacro compile-time-slurp [path]
  ;; slurp is not defined in self hosted cljs
  (slurp path))
</code>```

Is this possible?

EDIT: To be more clear, this is in self-hosted clojurescript, where the slurp function is not available at macro-expansion-time.

答:
ClojureScript macros are written in the Clojure language and have roughly this lifecycle:

jvm loads Clojure runtime, gets ready and a bunch of other stuff.

macro is compiled

macro runs and produces a new ClojureScript expression

if that expression is a macro loop again.

This omits all the parts done in the rest of the ClojureScript compiler (which is most of it) so we can focus on the fact that ClojureScript macros only have access to the parts of Clojure that are available from the JVM and not node while they are running the form returned by that macro which will become part of the finished ClojureScript program has access to the node APIs such as readFileSync.

In short, your macro should return a call to readFileSync rather than do the file reading while the macro is running. If your code really needs to read some files while evaluating the macro, because for instance they contain the code to output or something, then you would need to use the Clojure form to read those files such as the call to slurp you have above.

Body:
I'm writing a cli script with lumo and I want the following macro, but using readFileSync from nodejs.

(defmacro compile-time-slurp [path]
  ;; slurp is not defined in self hosted cljs
  (slurp path))

Is this possible?

EDIT: To be more clear, this is in self-hosted clojurescript, where the slurp function is not available at macro-expansion-time.


问:
Rails don't show validation error messages on associated model
I have simple but frustrating problem with showing validation errors for comments of posts. Error partial shows errors for posts but despite validation works on comments, errors don't render.

comment form partial is inserted into post view:

```<code><%= form_for([@post, @post.comments.build]) do |f| %>
  <%= render 'shared/error_messages', object: f.object %>
  <p>
    <%= f.label :commenter %><br>
    <%= f.text_field :commenter %>
  </p>
  <p>
    <%= f.label :body %><br>
    <%= f.text_area :body %>
  </p>
  <p>
    <%= f.submit %>
  </p>
<% end %>
</code>```

errors partial

```<code><% if object.errors.any? %>
<h2>Errors:</h2>
<ul>
  <% object.errors.full_messages.each do |msg| %>
    <li><%= msg %></li>
  <% end %>
</ul>
</code>```

models:

```<code> class Post < ActiveRecord::Base
  has_many :comments, dependent: :destroy

  validates :title, :content, :presence => true
  validates :title, length: { minimum: 3 }
  validates :title, :uniqueness => true

end

class Comment < ActiveRecord::Base
  belongs_to :post

  validates :body,      presence: true
  validates :commenter, presence: true, length: { minimum: 3 }

end
</code>```

I have been looking for answer for some time but can't get it working.

答:
Add this line to the Post model

validates_associated :comments

Body:
I have simple but frustrating problem with showing validation errors for comments of posts. Error partial shows errors for posts but despite validation works on comments, errors don't render.

comment form partial is inserted into post view:

<%= form_for([@post, @post.comments.build]) do |f| %>
  <%= render 'shared/error_messages', object: f.object %>

    <%= f.label :commenter %>

    <%= f.text_field :commenter %>

    <%= f.label :body %>

    <%= f.text_area :body %>

    <%= f.submit %>

<% end %>

errors partial

<% if object.errors.any? %>

Errors:

  <% object.errors.full_messages.each do |msg| %>

<%= msg %>

  <% end %>

models:

 class Post < ActiveRecord::Base
  has_many :comments, dependent: :destroy

  validates :title, :content, :presence => true
  validates :title, length: { minimum: 3 }
  validates :title, :uniqueness => true

end

class Comment < ActiveRecord::Base
  belongs_to :post

  validates :body,      presence: true
  validates :commenter, presence: true, length: { minimum: 3 }

end

I have been looking for answer for some time but can't get it working.


问:
How to specify multiple result path values in AWS Step Functions
I have a AWS Step Function State formatted as follows:

```<code>"MyState": {
  "Type": "Task",
  "Resource": "<MyLambdaARN>",
  "ResultPath": "$.value1"
  "Next": "NextState"
}
</code>```

I want to add a second value but can't find out how anywhere. None of the AWS examples display multiple ResultPath values being added to the output.

Would I just add a comma between them?

```<code>"MyState": {
  "Type": "Task",
  "Resource": "<MyLambdaARN>",
  "ResultPath": "$.value1, $.value2"
  "Next": "NextState"
}
</code>```

Or is there a better way to format these?

答:
I think it would be like the following, but I haven't actually done this so I can't say for sure.

```<code>"ResultPath": {

                 "var1" : "$.value1",
                 "var2" : "$.value2"
 },
</code>```

=====

After looking further into this, I am convinced that there is no direct way to do what you want to do.  Here is a way that could give you the results that you want.

1) You would omit the InputPath, OutputPath, and ResultPath from your step.  This would mean that all of $. would be passed in as an input to your step function and that all of the output from the lambda function would be stored as $.  In the lambda function you could set the results fields to be whatever you want them to be.  The lambda function must return the modified input as it output.

Body:
I have a AWS Step Function State formatted as follows:

"MyState": {
  "Type": "Task",
  "Resource": "<MyLambdaARN>",
  "ResultPath": "$.value1"
  "Next": "NextState"
}

I want to add a second value but can't find out how anywhere. None of the AWS examples display multiple ResultPath values being added to the output.

Would I just add a comma between them?

"MyState": {
  "Type": "Task",
  "Resource": "<MyLambdaARN>",
  "ResultPath": "$.value1, $.value2"
  "Next": "NextState"
}

Or is there a better way to format these?

Body:
I think it would be like the following, but I haven't actually done this so I can't say for sure.

"ResultPath": {

                 "var1" : "$.value1",
                 "var2" : "$.value2"
 },

=====

After looking further into this, I am convinced that there is no direct way to do what you want to do.  Here is a way that could give you the results that you want.

1) You would omit the InputPath, OutputPath, and ResultPath from your step.  This would mean that all of $. would be passed in as an input to your step function and that all of the output from the lambda function would be stored as $.  In the lambda function you could set the results fields to be whatever you want them to be.  The lambda function must return the modified input as it output.