问:
Use Master dataframe to aggregate regression loop using rbind
All, I'm very new to R, and can't find anything in the existing questions database that fits my exact issue. I'm running a loop of several regressions (200), and am trying to bind the results/coefficients into a single dataframe that I can export to Excel, with one set of headers.  All variables in each regression are identical.  The regression part of my loop looks like,

```<code>getreg<-OutChg~USInput
stepreg<-lm(getreg,data=mydata)
</code>```

I'm trying use a "master" dataframe to bind everything together, such as,

```<code>master<-data.frame()
master<-rbind(master,stepreg$coefficients)
</code>```

But I get the response Error in stepreg$coefficients : $ operator is invalid for atomic vectors.  Ideally, I'd like to have something where I don't even have to define master<-data.frame().

Any advice is much appreciated.  Thank you!

答:
Using data.table

```<code>datandfit <- function(x) {

  USInput <- rnorm(100, 0, 5)
  OutChg <- USInput*5 + 10 + rnorm(100, 0, 5)
  mydata <- data.table(USInput, OutChg)
  stepreg <- lm(OutChg ~ USInput, data = mydata)
  data.table(t(stepreg$coefficients))

}
</code>```

This will generate some random data, fit a model to it, and return a data.table of the results. You would skip the first three lines of the function, since you would already have data. Then, you can lapply over the function, which will return a list of 200 data.tables, and use rbindlist to combine them all into one data.table.

```<code>rbindlist(lapply(1:200, datandfit))

     (Intercept)  USInput
  1:    9.979968 4.909842
  2:   10.086159 5.083225
  3:   10.285307 4.873432
  4:   10.457751 4.905266
  5:    9.108176 5.005555
 ---
196:   10.715356 4.846002
197:    9.938905 4.966180
198:    9.968473 5.073163
199:   10.098703 5.065169
200:    9.538539 4.946085
</code>```

Body:
All, I'm very new to R, and can't find anything in the existing questions database that fits my exact issue. I'm running a loop of several regressions (200), and am trying to bind the results/coefficients into a single dataframe that I can export to Excel, with one set of headers.  All variables in each regression are identical.  The regression part of my loop looks like,

getreg<-OutChg~USInput
stepreg<-lm(getreg,data=mydata)

I'm trying use a "master" dataframe to bind everything together, such as,

master<-data.frame()
master<-rbind(master,stepreg$coefficients)

But I get the response Error in stepreg$coefficients : $ operator is invalid for atomic vectors.  Ideally, I'd like to have something where I don't even have to define master<-data.frame().

Any advice is much appreciated.  Thank you!

Body:
Using data.table

datandfit <- function(x) {

  USInput <- rnorm(100, 0, 5)
  OutChg <- USInput*5 + 10 + rnorm(100, 0, 5)
  mydata <- data.table(USInput, OutChg)
  stepreg <- lm(OutChg ~ USInput, data = mydata)
  data.table(t(stepreg$coefficients))

}

This will generate some random data, fit a model to it, and return a data.table of the results. You would skip the first three lines of the function, since you would already have data. Then, you can lapply over the function, which will return a list of 200 data.tables, and use rbindlist to combine them all into one data.table.

rbindlist(lapply(1:200, datandfit))

     (Intercept)  USInput
  1:    9.979968 4.909842
  2:   10.086159 5.083225
  3:   10.285307 4.873432
  4:   10.457751 4.905266
  5:    9.108176 5.005555
 ---
196:   10.715356 4.846002
197:    9.938905 4.966180
198:    9.968473 5.073163
199:   10.098703 5.065169
200:    9.538539 4.946085


来源: stackexchange

问:
What are some example javascript frameworks that people use?
I am really big fan of jQuery, but I don't see it as a framework for a site, more like a library.  I am looking for some sort of framework that will give me the tools to build really structured applications in javaScript.  I have found backbone.js, but find it somewhat confusing.  Is that a good one, and are there others similar to it?  an MVC pattern would be really cool, but I havent found anything.</p>

答:
If you like dynamic OOP languages like Ruby/Python, you should really check RightJS. It is very compact, fast and simple. RightJS is built fully on OOP paradigm and allows you to implement serious stuff in a serious but not boring way.

As for the dom part, it doesn't exactly uses MVC as is, but RightJS has OOP dom-wrappers, with inheritance and so one. That provides basically the same result, but with much less headache.

And if you're particularly interested in patterns, check this out https://github.com/rightjs/rightjs-patterns :)

ContentLicense: CC BY-SA 2.5


问:
Split up Bootstrap Carousel Images into separate Slides
Currently have a bootstrap Carousel that loads three images per slide. I want to split this up (eventually on mobile only) to be one image per slide dynamically. So that way desktop has three images per slide, and mobile has one image per slide.

HTML

```<code><section>
    <div class="container">
        <div class="row">
            <div class="col-md-12">
                <div class="carousel slide" data-ride="carousel" id="myCarousel">
                    <!-- Indicators -->
                    <ol class="carousel-indicators">
                        <li class="active" data-lightbox="1" data-slide-to="0" data-target="#myCarousel"></li>
                    </ol>
                    <div class="carousel slide" data-interval="false" data-ride="carousel" id="lightboxImageCarousel">
                        <ol class="carousel-indicators" style="display: none;">
                            <li class="active" data-slide-to="0" data-target="#lightboxImageCarousel"></li>
                        </ol>
                        <div class="carousel-inner">
                            <div class="item active">
                                <div class="col-xs-4 col-sm-4">
                                    <a class="example-image-link" data-lightbox="example-set-7" data-title="" href="#"><img class="img-responsive example-image" src="blank1.jpg"></a>
                                </div>
                                <div class="col-xs-4 col-sm-4">
                                    <a class="example-image-link" data-lightbox="example-set-7" data-title="" href="#"><img class="img-responsive example-image" src="blank2.jpg"></a>
                                </div>
                                <div class="col-xs-4 col-sm-4">
                                    <a class="example-image-link" data-lightbox="example-set-7" data-title="" href="#"><img class="img-responsive example-image" src="blank3.jpg"></a>
                                </div>
                            </div>
                        </div><a class="left carousel-control" data-slide="prev" href="#lightboxImageCarousel" role="button"><span aria-hidden="true" class="rslides1_nav prev"></span> <span class="sr-only">Previous</span></a> <a class="right carousel-control" data-slide="next" href="#lightboxImageCarousel" role="button"><span aria-hidden="true" class="rslides1_nav next"></span> <span class="sr-only">Next</span></a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>
</code>```

jQuery

```<code>if ($('.item').has('.active')) {
  var $itemActive = $('.item');
  var countDivs = $itemActive[0].childElementCount;
  console.log(countDivs);

  // Remove classes and convert to XS 12, And hide the rest
  $('.item').children().removeClass().addClass('col-xs-12').next().hide();

  $('.item').each(function() {
    console.log($('.item:nth-child(' + countDivs + ')'));
  });

  // Create a new Item and loop it to total number of col-xs-12 that exist inside of item
  $('.carousel-inner').append("<div class='item'></div>")

  // Add nth-child 1 of for Loop 1, and nth-child 2 for loop 2
  // Where it breaks
  $('.item.active').children().next().appendTo(".item").next().show();
}

(function() {
  $('#myCarousel').carousel({
    interval: 3200
  });
}());
</code>```

答:
Why not use Bootstrap grid options ?

By using col-xs-12, the content should use 100% of the parent container for the xs media query.

Remember that you can also hide certain tags with the Responsive Utilities Classes

Edit I made a CodePen to illustrate my point, regarding the second technique (using two containers targeting mobile and desktop environment). I think it solves the OP original problem.

As a side note, one can also add tags with the target grid size (i.e. visible-xs-*) to the body tag of the document, then make JS functions to check if they are visible, and use these functions in a debounced $(window).resize(fn) event listener to raise specific events depending on the media query currently being used. This would allow the OP to switch between JS behaviors depending on the current media query, using for example the strategy pattern. It is a bit more complicated for this use case though...

HTML (original answer)

```<code><section>
  <div class="container">
    <div class="row">
      <div class="col-md-12">
        <div class="carousel slide" data-ride="carousel" id="myCarousel">
          <!-- Indicators -->
          <ol class="carousel-indicators">
              <li class="active" data-lightbox="1" data-slide-to="0" data-target="#myCarousel"></li>
          </ol>
          <div class="carousel slide" data-interval="false" data-ride="carousel" id="lightboxImageCarousel">
            <ol class="carousel-indicators" style="display: none;">
                <li class="active" data-slide-to="0" data-target="#lightboxImageCarousel"></li>
            </ol>
            <div class="carousel-inner">
              <div class="item active">
                <div class="col-xs-12 col-sm-4">
                  <a class="example-image-link" data-lightbox="example-set-7" data-title="" href="#"><img class="img-responsive example-image" src="blank1.jpg"></a>
                </div>
                <div class="col-xs-12 col-sm-4">
                  <a class="example-image-link" data-lightbox="example-set-7" data-title="" href="#"><img class="img-responsive example-image" src="blank2.jpg"></a>
                </div>
                <div class="col-xs-12 col-sm-4">
                  <a class="example-image-link" data-lightbox="example-set-7" data-title="" href="#"><img class="img-responsive example-image" src="blank3.jpg"></a>
                </div>
              </div>
            </div><a class="left carousel-control" data-slide="prev" href="#lightboxImageCarousel" role="button"><span aria-hidden="true" class="rslides1_nav prev"></span> <span class="sr-only">Previous</span></a> <a class="right carousel-control" data-slide="next" href="#lightboxImageCarousel" role="button"><span aria-hidden="true" class="rslides1_nav next"></span> <span class="sr-only">Next</span></a>
          </div>
        </div>
      </div>
    </div>
  </div>
</section>
</code>```

Edit: second technique

```<code><section>
  <div class="container desktop-view hidden-xs">
    <div class="row">
      <div class="col-md-12">
        <div class="carousel slide" data-ride="carousel" id="myCarousel">
          <!-- Indicators -->
          <ol class="carousel-indicators">
              <li class="active" data-lightbox="1" data-slide-to="0" data-target="#myCarousel"></li>
          </ol>
          <div class="carousel slide" data-interval="false" data-ride="carousel" id="lightboxImageCarousel">
            <ol class="carousel-indicators" style="display: none;">
                <li class="active" data-slide-to="0" data-target="#lightboxImageCarousel"></li>
            </ol>
            <div class="carousel-inner">
              <div class="item active">
                <div class="col-sm-4">
                  <a class="example-image-link" data-lightbox="example-set-7" data-title="" href="#"><img class="img-responsive example-image" src="blank1.jpg"></a>
                </div>
                <div class="col-sm-4">
                  <a class="example-image-link" data-lightbox="example-set-7" data-title="" href="#"><img class="img-responsive example-image" src="blank2.jpg"></a>
                </div>
                <div class="col-sm-4">
                  <a class="example-image-link" data-lightbox="example-set-7" data-title="" href="#"><img class="img-responsive example-image" src="blank3.jpg"></a>
                </div>
              </div>
            </div><a class="left carousel-control" data-slide="prev" href="#lightboxImageCarousel" role="button"><span aria-hidden="true" class="rslides1_nav prev"></span> <span class="sr-only">Previous</span></a> <a class="right carousel-control" data-slide="next" href="#lightboxImageCarousel" role="button"><span aria-hidden="true" class="rslides1_nav next"></span> <span class="sr-only">Next</span></a>
          </div>
        </div>
      </div>
    </div>
  </div>

  <div class="container mobile-view hidden-sm hidden-md hidden-lg">
    <div class="row">
      <div class="col-md-12">
        <div class="carousel slide" data-ride="carousel" id="myCarousel">
          <!-- Indicators -->
          <ol class="carousel-indicators">
              <li class="active" data-lightbox="1" data-slide-to="0" data-target="#myCarousel"></li>
          </ol>
          <div class="carousel slide" data-interval="false" data-ride="carousel" id="lightboxImageCarousel">
            <ol class="carousel-indicators" style="display: none;">
                <li class="active" data-slide-to="0" data-target="#lightboxImageCarousel"></li>
            </ol>
            <div class="carousel-inner">
              <div class="item active">
                <div class="col-xs-12">
                  <a class="example-image-link" data-lightbox="example-set-7" data-title="" href="#"><img class="img-responsive example-image" src="blank1.jpg"></a>
                </div>
              </div>
              <div class="item">
                <div class="col-xs-12">
                  <a class="example-image-link" data-lightbox="example-set-7" data-title="" href="#"><img class="img-responsive example-image" src="blank2.jpg"></a>
                </div>
              </div>
              <div class="item">
                <div class="col-xs-12">
                  <a class="example-image-link" data-lightbox="example-set-7" data-title="" href="#"><img class="img-responsive example-image" src="blank3.jpg"></a>
                </div>
              </div>
            </div><a class="left carousel-control" data-slide="prev" href="#lightboxImageCarousel" role="button"><span aria-hidden="true" class="rslides1_nav prev"></span> <span class="sr-only">Previous</span></a> <a class="right carousel-control" data-slide="next" href="#lightboxImageCarousel" role="button"><span aria-hidden="true" class="rslides1_nav next"></span> <span class="sr-only">Next</span></a>
          </div>
        </div>
      </div>
    </div>
  </div>
</section>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Currently have a bootstrap Carousel that loads three images per slide. I want to split this up (eventually on mobile only) to be one image per slide dynamically. So that way desktop has three images per slide, and mobile has one image per slide.

HTML

 Previous  Next

jQuery

if ($('.item').has('.active')) {
  var $itemActive = $('.item');
  var countDivs = $itemActive[0].childElementCount;
  console.log(countDivs);

  // Remove classes and convert to XS 12, And hide the rest
  $('.item').children().removeClass().addClass('col-xs-12').next().hide();

  $('.item').each(function() {
    console.log($('.item:nth-child(' + countDivs + ')'));
  });

  // Create a new Item and loop it to total number of col-xs-12 that exist inside of item
  $('.carousel-inner').append("

")

  // Add nth-child 1 of for Loop 1, and nth-child 2 for loop 2
  // Where it breaks
  $('.item.active').children().next().appendTo(".item").next().show();
}

(function() {
  $('#myCarousel').carousel({
    interval: 3200
  });
}());

Body:
Why not use Bootstrap grid options ?

By using col-xs-12, the content should use 100% of the parent container for the xs media query.

Remember that you can also hide certain tags with the Responsive Utilities Classes

Edit I made a CodePen to illustrate my point, regarding the second technique (using two containers targeting mobile and desktop environment). I think it solves the OP original problem.

As a side note, one can also add tags with the target grid size (i.e. visible-xs-*) to the body tag of the document, then make JS functions to check if they are visible, and use these functions in a debounced $(window).resize(fn) event listener to raise specific events depending on the media query currently being used. This would allow the OP to switch between JS behaviors depending on the current media query, using for example the strategy pattern. It is a bit more complicated for this use case though...

HTML (original answer)

<section>
  <div class="container">
    <div class="row">
      <div class="col-md-12">
        <div class="carousel slide" data-ride="carousel" id="myCarousel">
          <!-- Indicators -->
          <ol class="carousel-indicators">
              <li class="active" data-lightbox="1" data-slide-to="0" data-target="#myCarousel"></li>
          </ol>
          <div class="carousel slide" data-interval="false" data-ride="carousel" id="lightboxImageCarousel">
            <ol class="carousel-indicators" style="display: none;">
                <li class="active" data-slide-to="0" data-target="#lightboxImageCarousel"></li>
            </ol>
            <div class="carousel-inner">
              <div class="item active">
                <div class="col-xs-12 col-sm-4">
                  <a class="example-image-link" data-lightbox="example-set-7" data-title="" href="#"><img class="img-responsive example-image" src="blank1.jpg"></a>
                </div>
                <div class="col-xs-12 col-sm-4">
                  <a class="example-image-link" data-lightbox="example-set-7" data-title="" href="#"><img class="img-responsive example-image" src="blank2.jpg"></a>
                </div>
                <div class="col-xs-12 col-sm-4">
                  <a class="example-image-link" data-lightbox="example-set-7" data-title="" href="#"><img class="img-responsive example-image" src="blank3.jpg"></a>
                </div>
              </div>
            </div><a class="left carousel-control" data-slide="prev" href="#lightboxImageCarousel" role="button"><span aria-hidden="true" class="rslides1_nav prev"></span> <span class="sr-only">Previous</span></a> <a class="right carousel-control" data-slide="next" href="#lightboxImageCarousel" role="button"><span aria-hidden="true" class="rslides1_nav next"></span> <span class="sr-only">Next</span></a>
          </div>
        </div>
      </div>
    </div>
  </div>
</section>

Edit: second technique

<section>
  <div class="container desktop-view hidden-xs">
    <div class="row">
      <div class="col-md-12">
        <div class="carousel slide" data-ride="carousel" id="myCarousel">
          <!-- Indicators -->
          <ol class="carousel-indicators">
              <li class="active" data-lightbox="1" data-slide-to="0" data-target="#myCarousel"></li>
          </ol>
          <div class="carousel slide" data-interval="false" data-ride="carousel" id="lightboxImageCarousel">
            <ol class="carousel-indicators" style="display: none;">
                <li class="active" data-slide-to="0" data-target="#lightboxImageCarousel"></li>
            </ol>
            <div class="carousel-inner">
              <div class="item active">
                <div class="col-sm-4">
                  <a class="example-image-link" data-lightbox="example-set-7" data-title="" href="#"><img class="img-responsive example-image" src="blank1.jpg"></a>
                </div>
                <div class="col-sm-4">
                  <a class="example-image-link" data-lightbox="example-set-7" data-title="" href="#"><img class="img-responsive example-image" src="blank2.jpg"></a>
                </div>
                <div class="col-sm-4">
                  <a class="example-image-link" data-lightbox="example-set-7" data-title="" href="#"><img class="img-responsive example-image" src="blank3.jpg"></a>
                </div>
              </div>
            </div><a class="left carousel-control" data-slide="prev" href="#lightboxImageCarousel" role="button"><span aria-hidden="true" class="rslides1_nav prev"></span> <span class="sr-only">Previous</span></a> <a class="right carousel-control" data-slide="next" href="#lightboxImageCarousel" role="button"><span aria-hidden="true" class="rslides1_nav next"></span> <span class="sr-only">Next</span></a>
          </div>
        </div>
      </div>
    </div>
  </div>

  <div class="container mobile-view hidden-sm hidden-md hidden-lg">
    <div class="row">
      <div class="col-md-12">
        <div class="carousel slide" data-ride="carousel" id="myCarousel">
          <!-- Indicators -->
          <ol class="carousel-indicators">
              <li class="active" data-lightbox="1" data-slide-to="0" data-target="#myCarousel"></li>
          </ol>
          <div class="carousel slide" data-interval="false" data-ride="carousel" id="lightboxImageCarousel">
            <ol class="carousel-indicators" style="display: none;">
                <li class="active" data-slide-to="0" data-target="#lightboxImageCarousel"></li>
            </ol>
            <div class="carousel-inner">
              <div class="item active">
                <div class="col-xs-12">
                  <a class="example-image-link" data-lightbox="example-set-7" data-title="" href="#"><img class="img-responsive example-image" src="blank1.jpg"></a>
                </div>
              </div>
              <div class="item">
                <div class="col-xs-12">
                  <a class="example-image-link" data-lightbox="example-set-7" data-title="" href="#"><img class="img-responsive example-image" src="blank2.jpg"></a>
                </div>
              </div>
              <div class="item">
                <div class="col-xs-12">
                  <a class="example-image-link" data-lightbox="example-set-7" data-title="" href="#"><img class="img-responsive example-image" src="blank3.jpg"></a>
                </div>
              </div>
            </div><a class="left carousel-control" data-slide="prev" href="#lightboxImageCarousel" role="button"><span aria-hidden="true" class="rslides1_nav prev"></span> <span class="sr-only">Previous</span></a> <a class="right carousel-control" data-slide="next" href="#lightboxImageCarousel" role="button"><span aria-hidden="true" class="rslides1_nav next"></span> <span class="sr-only">Next</span></a>
          </div>
        </div>
      </div>
    </div>
  </div>
</section>


问:
Can you install drivers in a VM which will be used when the WIM is captured?
I am using Hyper-v and have configured my VM (installed company specific software etc) and I am now ready to create a WIM from it.

What I noticed after creating the WIM file and deploying it was that the drivers were not available for the hardware I was deploying the WIM on. For example the windows resolution was wrong and when I check device manager, the intel graphics driver was missing.

So, is it possible to install drivers for the hardware I will be deploying to on the VM and then capture the image? That way I do not have to do a windows update to get the drivers (they are already on the VM and in my WIM).

答:
There is a way to stage drivers, include them in the Windows driver store, which should make them available to hardware, nonexistent on your VM but present on a different machine you want to apply them WIM to. I have used this prev. and it worked w/o a hitch. No VM was involved but the injected driver survived Sysprep with Generalization and was available afterwards on different hardware.

https://technet.microsoft.com/en-us/library/cc772036(v=ws.11).aspx


问:
Datepart Calculation in Where clause
I am having problem with the datepart calculation in the Where clause of a query. The query returns result without the calculation but nothing if i add the condition.</p>

```<code>DECLARE @StatusId INT;
SELECT @StatusId = Id FROM company.Status WHERE Name = 'Signed' AND CompanyId = 1;

SELECT FORMAT(CAST(cont.CreatedDate AS DATE), 'MM/dd') AS newDate,
    SUM(CASE WHEN cont.UpdatedDate IS NOT NULL THEN 1 ELSE 0 END) AS TotalSignedLeads
FROM client.testw cont
WHERE cont.CompanyId = 1
    AND cont.AffiliateId = 1
    AND cont.CreatedDate BETWEEN '7-01-2017' AND '7-09-2017'
    AND DATEPART(dw, cont.CreatedDate) NOT IN (1, 7) //This causes problem.
    AND cont.StatusId = @StatusId
GROUP BY CAST(cont.CreatedDate AS DATE)
ORDER BY newDate ;

This is the data above query gives without the datepart condition.
newDate  TotalSignedLeads
07/08    7
</code>```

答:
Well since you are casting cont.CreatedDate as a date in the top of the query, I suspect it's actually a varchar... thus you need

```<code>...
and datepart(weekday, cast(cont.CreatedDate as date)) not in (1,7)
...
</code>```

bad-habits-to-kick-using-shorthand-with-date-time-operations

If you aren't getting an error, then you don't have any rows which meet that condition. Perhaps your DATEFIRST setting isn't what you think it is.

Also, not sure what GROUP BY CAST(@StatusId.CreatedDate AS DATE) is meant to be...

Title: Datepart Calculation in Where clause

Body:
I am having problem with the datepart calculation in the Where clause of a query. The query returns result without the calculation but nothing if i add the condition.

DECLARE @StatusId INT;
SELECT @StatusId = Id FROM company.Status WHERE Name = 'Signed' AND CompanyId = 1;

SELECT FORMAT(CAST(cont.CreatedDate AS DATE), 'MM/dd') AS newDate,
    SUM(CASE WHEN cont.UpdatedDate IS NOT NULL THEN 1 ELSE 0 END) AS TotalSignedLeads
FROM client.testw cont
WHERE cont.CompanyId = 1
    AND cont.AffiliateId = 1
    AND cont.CreatedDate BETWEEN '7-01-2017' AND '7-09-2017'
    AND DATEPART(dw, cont.CreatedDate) NOT IN (1, 7) //This causes problem.
    AND cont.StatusId = @StatusId
GROUP BY CAST(cont.CreatedDate AS DATE)
ORDER BY newDate ;

This is the data above query gives without the datepart condition.
newDate  TotalSignedLeads
07/08    7

Body:
Well since you are casting cont.CreatedDate as a date in the top of the query, I suspect it's actually a varchar... thus you need

...
and datepart(weekday, cast(cont.CreatedDate as date)) not in (1,7)
...

bad-habits-to-kick-using-shorthand-with-date-time-operations

If you aren't getting an error, then you don't have any rows which meet that condition. Perhaps your DATEFIRST setting isn't what you think it is.

Also, not sure what GROUP BY CAST(@StatusId.CreatedDate AS DATE) is meant to be...

ContentLicense: CC BY-SA 4.0


问:
Dynamic SQL output of a query to a variable
I would like to output the result of the dynamic SQL into a variable called @Count but not sure what the syntax or even the code should like to accomplish this.

The code looks as follows:

```<code>declare @tab nvarchar(255) = 'Person.person'

declare @Count int
declare @SQL nvarchar(max) = 'select  count(*) from '+ @tab

exec(@SQl)

select @Count
</code>```

thank you

答:
You can utilize sp_executesql to execute your count() query, and output it @Count.

Try this:

```<code>-- Set the table to count from
declare @tab nvarchar(255) = 'Person.person'

-- Assign the SQL query
declare @SQL nvarchar(255) = N'SELECT count(*) FROM ' + @tab

-- Pepare for sp_executesql
declare @Count int
declare @Params nvarchar(100) = N'@Count int output'

-- Set the count to @Count
exec sp_executesql @SQL, @Params, @Count=@Count output

-- Output @Count
select @Count
</code>```

One last thing: Person.person looks like you might be trying to reference a person column from a Person table. But the above query is a literal representation of what it looks like you're trying to achieve in your question.

Body:
I would like to output the result of the dynamic SQL into a variable called @Count but not sure what the syntax or even the code should like to accomplish this.

The code looks as follows:

declare @tab nvarchar(255) = 'Person.person'

declare @Count int
declare @SQL nvarchar(max) = 'select  count(*) from '+ @tab

exec(@SQl)

select @Count

thank you

Body:
You can utilize sp_executesql to execute your count() query, and output it @Count.

Try this:

-- Set the table to count from
declare @tab nvarchar(255) = 'Person.person'

-- Assign the SQL query
declare @SQL nvarchar(255) = N'SELECT count(*) FROM ' + @tab

-- Pepare for sp_executesql
declare @Count int
declare @Params nvarchar(100) = N'@Count int output'

-- Set the count to @Count
exec sp_executesql @SQL, @Params, @Count=@Count output

-- Output @Count
select @Count

One last thing: Person.person looks like you might be trying to reference a person column from a Person table. But the above query is a literal representation of what it looks like you're trying to achieve in your question.


问:
connect points during multiple Matlab plot calls
I would like to connect two or multiple data points during multiple Matlab plot calls. Below is some dummy code that shows what I am trying to accomplish,

```<code>function main()
close all

t = 0;

while t<10
    x = rand(1,1);
    y = rand(1,1);
    t = t+1;
    calculateErrorAndPlot(1,x,y,t)
end
return

function calculateErrorAndPlot(figureNumber,x,y,time)

    figure(figureNumber);
    if ~ishold
        hold on
    end

    error = x-y;
    plot(time,error,'.b');
return
</code>```

Right now, I have to use '.b' to at least see the data points being plotted. Note that plot is being called with scalars.

答:
You could update the XData and YData properties of a line already plotted to add a new point. For example:</p>

```<code>function main
   fig = figure;
   ax = axes( 'Parent', fig );
   line = plot( NaN, NaN, 'Parent', ax );
   for t = 0:9
      x = rand( 1, 1 );
      y = rand( 1, 1 );
      calculateErrorAndPlot( line, x, y, t )
   end
end

function calculateErrorAndPlot( line, x, y, t )
   xData = get( line, 'XData' );
   yData = get( line, 'YData' );
   xData(end+1) = t;
   yData(end+1) = x - y;
   set( line, 'XData', xData, 'YData', yData );
end
</code>```

Body:
I would like to connect two or multiple data points during multiple Matlab plot calls. Below is some dummy code that shows what I am trying to accomplish,

function main()
close all

t = 0;

while t<10
    x = rand(1,1);
    y = rand(1,1);
    t = t+1;
    calculateErrorAndPlot(1,x,y,t)
end
return

function calculateErrorAndPlot(figureNumber,x,y,time)

    figure(figureNumber);
    if ~ishold
        hold on
    end

    error = x-y;
    plot(time,error,'.b');
return

Right now, I have to use '.b' to at least see the data points being plotted. Note that plot is being called with scalars.

Body:
You could update the XData and YData properties of a line already plotted to add a new point. For example:

function main
   fig = figure;
   ax = axes( 'Parent', fig );
   line = plot( NaN, NaN, 'Parent', ax );
   for t = 0:9
      x = rand( 1, 1 );
      y = rand( 1, 1 );
      calculateErrorAndPlot( line, x, y, t )
   end
end

function calculateErrorAndPlot( line, x, y, t )
   xData = get( line, 'XData' );
   yData = get( line, 'YData' );
   xData(end+1) = t;
   yData(end+1) = x - y;
   set( line, 'XData', xData, 'YData', yData );
end


问:
Wpf binding problem
I have in my window a rectangle with a tooltip,
Clicking the button suppose to change the tooltip text but it doesn't.

XAML:

```<code> <Grid>
    <Grid.RowDefinitions>
        <RowDefinition />
        <RowDefinition />
    </Grid.RowDefinitions>

    <Grid.Resources>
        <ToolTip x:Key="@tooltip">
            <TextBlock Text="{Binding Name}" />
        </ToolTip>
    </Grid.Resources>

    <Rectangle Width="200" Height="200" Fill="LightBlue" VerticalAlignment="Center" HorizontalAlignment="Center"
            ToolTip="{DynamicResource @tooltip}" />
    <Button Click="Button_Click" Grid.Row="1" Margin="20">Click Me</Button>
</Grid>
</code>```

code behind:

```<code>public partial class Window1 : Window
{

    public Window1()
    {
        DataContext = new Person { Name = "A" };
        InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        DataContext = new Person { Name = "B" };
    }
}
</code>```

答:
Change binding to:

Example:

```<code><ToolTip x:Key="@tooltip">
    <TextBlock Text="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Parent.PlacementTarget.DataContext.Name}" />
</ToolTip>
</code>```

Reason:

The reason this works and yours doesn't is because the TextBlock element never gets notified of a change in a property named Name that you bind to in your code.

To fix that, in this example, TextBlock is bound to Parent (ToolTip) > PlacementTarget (Button) > DataContext (Person) > Name property. Here TextBlock has reference to PlacementTarget which in your case is a Button. Button notifies TextBlock of a change in it's DataContext property value on which notification, TextBlock updates itself.

Title: Wpf binding problem

Body:
I have in my window a rectangle with a tooltip,
Clicking the button suppose to change the tooltip text but it doesn't.

XAML:

 <Grid>
    <Grid.RowDefinitions>
        <RowDefinition />
        <RowDefinition />
    </Grid.RowDefinitions>

    <Grid.Resources>
        <ToolTip x:Key="@tooltip">
            <TextBlock Text="{Binding Name}" />
        </ToolTip>
    </Grid.Resources>

    <Rectangle Width="200" Height="200" Fill="LightBlue" VerticalAlignment="Center" HorizontalAlignment="Center"
            ToolTip="{DynamicResource @tooltip}" />
    <Button Click="Button_Click" Grid.Row="1" Margin="20">Click Me</Button>
</Grid>

code behind:

public partial class Window1 : Window
{

    public Window1()
    {
        DataContext = new Person { Name = "A" };
        InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        DataContext = new Person { Name = "B" };
    }
}

Body:
Change binding to:

Example:

<ToolTip x:Key="@tooltip">
    <TextBlock Text="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Parent.PlacementTarget.DataContext.Name}" />
</ToolTip>

Reason:

The reason this works and yours doesn't is because the TextBlock element never gets notified of a change in a property named Name that you bind to in your code.

To fix that, in this example, TextBlock is bound to Parent (ToolTip) > PlacementTarget (Button) > DataContext (Person) > Name property. Here TextBlock has reference to PlacementTarget which in your case is a Button. Button notifies TextBlock of a change in it's DataContext property value on which notification, TextBlock updates itself.


问:
TSQL insert into table with bulkcolumn -- needing two bulkcolumn inserts into same row
TSQL insert into table with bulkcolumn -- needing two bulkcolumn inserts into same row

I need to run a query with two bulkcolumn inserts into the same row.

I am trying:

However, I get the error:   Invalid object name 'BulkColumn'
Is this just a syntax problem, or is this a more fundamental rule (such as one can only insert one bulkcolumn per statement)?

Example:
in the SSMS edit-window.

```<code>INSERT INTO [table1] ([id1], [bulk1],[bulk2]
SELECT '123',
 BulkColumn
FROM Openrowset( Bulk 'C:\bulkDir1\a1.jpg', Single_Blob) as a1,
BulkColumn
FROM Openrowset( Bulk 'C:\bulkDir2\b1.jpg', Single_Blob) as a2
</code>```

It says (in the 'squiggly error' in the SSMS edit-window.):

Invalid object name 'BulkColumn'

答:
You can do it this way, your syntax is just a little off to get both columns:</p>
```<code>CREATE TABLE table1(id1 nvarchar(60),
  [bulk1] varbinary(max), [bulk2] varbinary(max));
GO

INSERT INTO table1([id1], [bulk1],[bulk2])
   SELECT
    '123' AS FileName,
     pic1.BulkColumn ,
     pic2.BulkColumn
  FROM OPENROWSET(BULK N'C:\test\a1.jpg', SINGLE_BLOB) AS pic1
  inner join OPENROWSET(BULK N'C:\test\b1.jpg', SINGLE_BLOB) AS pic2
    on 1=1
</code>```

Body:
TSQL insert into table with bulkcolumn -- needing two bulkcolumn inserts into same row

I need to run a query with two bulkcolumn inserts into the same row.

I am trying:

However, I get the error:   Invalid object name 'BulkColumn'
Is this just a syntax problem, or is this a more fundamental rule (such as one can only insert one bulkcolumn per statement)?

Example:
in the SSMS edit-window.

INSERT INTO [table1] ([id1], [bulk1],[bulk2]
SELECT '123',
 BulkColumn
FROM Openrowset( Bulk 'C:\bulkDir1\a1.jpg', Single_Blob) as a1,
BulkColumn
FROM Openrowset( Bulk 'C:\bulkDir2\b1.jpg', Single_Blob) as a2

It says (in the 'squiggly error' in the SSMS edit-window.):

Invalid object name 'BulkColumn'

Body:
You can do it this way, your syntax is just a little off to get both columns:

CREATE TABLE table1(id1 nvarchar(60),
  [bulk1] varbinary(max), [bulk2] varbinary(max));
GO

INSERT INTO table1([id1], [bulk1],[bulk2])
   SELECT
    '123' AS FileName,
     pic1.BulkColumn ,
     pic2.BulkColumn
  FROM OPENROWSET(BULK N'C:\test\a1.jpg', SINGLE_BLOB) AS pic1
  inner join OPENROWSET(BULK N'C:\test\b1.jpg', SINGLE_BLOB) AS pic2
    on 1=1


问:
MongoDB $push ObjectId
I have tried to do this a number of ways from updateOne, findOneAndUpdate to insert and even tried bulkWrite with no success.

What I have done is I have two collections the users collection and the image_upload collection. I store the users profile image inside image_upload along side all the other images that the user uploads.

What I then store in the users collection is the ObjectID of the image_upload collection that matched the image the user uploaded while creating their account (they can upload a new profile image anytime via edit profile).

So what I would like is the ability to update a ObjectId as I get.

The field personal.profile_id must be an array but is of type objectId in document. Here is the code. I ideally want it to have the ObjectID and not just a string.

```<code>$db = static::db()->image_upload;
                    try {
                        $newdata = [
                                    "data"=>
                                            [
                                            "url" => $publlic_url,
                                            "type"=> $mimetype,
                                            "date"=>new MongoDB\BSON\UTCDateTime(),
                                            "profile_pic" => true
                                            ],
                                    "uid"=>New MongoDB\BSON\ObjectId($uid)
                                    ];

                        $oauth_update = $db->insertOne($newdata);

                        $view['newdata'] = $newdata;
                        } catch(MongoResultException $e) {
                            return $response->withStatus(200)
                                ->withHeader('Content-Type', 'application/json')
                                ->write($e->getDocument());

                        }

                        $ids = $oauth_update->getInsertedId();

                        $latest = $db->findOne(array("uid"=>New MongoDB\BSON\ObjectId($uid)));

                        // Check first, last and other personal details.
                        $db = static::db()->users;
                        try {
                        $newdata = ['$set' =>["personal.profile_id"=>New MongoDB\BSON\ObjectId($ids)]];

                        $member_profile = $db->findOneAndUpdate(
                            ['kst'=>New MongoDB\BSON\ObjectId($uid)],
                            ['$push' =>["personal.profile_id"=>['$oid'=>New MongoDB\BSON\ObjectId($ids)]]],
                            [
                                'projection' =>
                                    [ 'personal' => 1 ],
                                "returnDocument" => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER
                            ]);

                        } catch(MongoResultException $e) {
                                echo $e->getCode(), " : ", $e->getMessage(), "\n";
                                var_dump($e->getDocument());
                                return $response->withStatus(200)
                                ->withHeader('Content-Type', 'application/json')
                                ->write(array('code'=>$e->getCode(), 'message'=>$e->getMessage));
                        }

                        return $response->withStatus(200)
                        ->withHeader('Content-Type', 'application/json')
                        ->write(json_encode($member_profile));
</code>```

答:
There is no work-around for the $push operator requiring an array type. Unfortunately, this is going to require migrating documents in the users collection. Some approaches for doing so are discussed in the following threads:

Converting some fields in Mongo from String to Array

mongodb type change to array

Alternatively, if you'd rather not migrate all documents in users at once, you can have the code execute two findOneAndUpdate() operations in sequence. The first operation could use $type to only match a document with { "personal.profile_id": { $type: "string" }} and then use $set to assign the most recent image ID. A second operation could then match a document with an array type and use the $push strategy (note that $type cannot be used for detecting an array field). The calling code would then expect exactly one of these operations to actually find and update a document (consider logging an error if that is not the case). This approach would then allow you to start collecting old image IDs for migrated documents, but continue overwriting the field for non-migrated documents.

One other observation based on the code you provided:

```<code>['$push' =>["personal.profile_id"=>['$oid'=>New MongoDB\BSON\ObjectId($ids)]]]
</code>```

$oid looks like extended JSON syntax for an ObjectID. That is neither an update operator nor a valid key to use in a BSON document. Attempting to execute this update via the mongo shell yields the following server-side error:

The dollar ($) prefixed field '$oid' 'personal.profile_id..$oid' is not valid for storage."

If you are only looking to push the ObjectID onto the array, the following should be sufficient:

```<code>['$push' => ['personal.profile_id' => new MongoDB\BSON\ObjectId($ids)]]
</code>```

Title: MongoDB $push ObjectId

Body:
I have tried to do this a number of ways from updateOne, findOneAndUpdate to insert and even tried bulkWrite with no success.

What I have done is I have two collections the users collection and the image_upload collection. I store the users profile image inside image_upload along side all the other images that the user uploads.

What I then store in the users collection is the ObjectID of the image_upload collection that matched the image the user uploaded while creating their account (they can upload a new profile image anytime via edit profile).

So what I would like is the ability to update a ObjectId as I get.

The field personal.profile_id must be an array but is of type objectId in document. Here is the code. I ideally want it to have the ObjectID and not just a string.

$db = static::db()->image_upload;
                    try {
                        $newdata = [
                                    "data"=>
                                            [
                                            "url" => $publlic_url,
                                            "type"=> $mimetype,
                                            "date"=>new MongoDB\BSON\UTCDateTime(),
                                            "profile_pic" => true
                                            ],
                                    "uid"=>New MongoDB\BSON\ObjectId($uid)
                                    ];

                        $oauth_update = $db->insertOne($newdata);

                        $view['newdata'] = $newdata;
                        } catch(MongoResultException $e) {
                            return $response->withStatus(200)
                                ->withHeader('Content-Type', 'application/json')
                                ->write($e->getDocument());

                        }

                        $ids = $oauth_update->getInsertedId();

                        $latest = $db->findOne(array("uid"=>New MongoDB\BSON\ObjectId($uid)));

                        // Check first, last and other personal details.
                        $db = static::db()->users;
                        try {
                        $newdata = ['$set' =>["personal.profile_id"=>New MongoDB\BSON\ObjectId($ids)]];

                        $member_profile = $db->findOneAndUpdate(
                            ['kst'=>New MongoDB\BSON\ObjectId($uid)],
                            ['$push' =>["personal.profile_id"=>['$oid'=>New MongoDB\BSON\ObjectId($ids)]]],
                            [
                                'projection' =>
                                    [ 'personal' => 1 ],
                                "returnDocument" => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER
                            ]);

                        } catch(MongoResultException $e) {
                                echo $e->getCode(), " : ", $e->getMessage(), "\n";
                                var_dump($e->getDocument());
                                return $response->withStatus(200)
                                ->withHeader('Content-Type', 'application/json')
                                ->write(array('code'=>$e->getCode(), 'message'=>$e->getMessage));
                        }

                        return $response->withStatus(200)
                        ->withHeader('Content-Type', 'application/json')
                        ->write(json_encode($member_profile));

Body:
There is no work-around for the $push operator requiring an array type. Unfortunately, this is going to require migrating documents in the users collection. Some approaches for doing so are discussed in the following threads:

Converting some fields in Mongo from String to Array

mongodb type change to array

Alternatively, if you'd rather not migrate all documents in users at once, you can have the code execute two findOneAndUpdate() operations in sequence. The first operation could use $type to only match a document with { "personal.profile_id": { $type: "string" }} and then use $set to assign the most recent image ID. A second operation could then match a document with an array type and use the $push strategy (note that $type cannot be used for detecting an array field). The calling code would then expect exactly one of these operations to actually find and update a document (consider logging an error if that is not the case). This approach would then allow you to start collecting old image IDs for migrated documents, but continue overwriting the field for non-migrated documents.

One other observation based on the code you provided:

['$push' =>["personal.profile_id"=>['$oid'=>New MongoDB\BSON\ObjectId($ids)]]]

$oid looks like extended JSON syntax for an ObjectID. That is neither an update operator nor a valid key to use in a BSON document. Attempting to execute this update via the mongo shell yields the following server-side error:

The dollar ($) prefixed field '$oid' 'personal.profile_id..$oid' is not valid for storage."

If you are only looking to push the ObjectID onto the array, the following should be sufficient:

['$push' => ['personal.profile_id' => new MongoDB\BSON\ObjectId($ids)]]


问:
Linking OpenBLAS with Qt Creator project
I am using Qt Creator for development. I want to use Armadillo linear algebra library. Therefore I used following code in my pro file:

```<code>INCLUDEPATH += C:\armadillo-7.950.1\include

LIBS += \
    -LC:\armadillo-7.950.1\examples\lib_win64 \
    -llapack_win64_MT \
    -lblas_win64_MT
</code>```

It was all good and the project compiled and linked properly. Next task was to replace LAPACK and BLAS with OpenBLAS. So the pro file was changed as following:

```<code>INCLUDEPATH += C:\armadillo-7.950.1\include \
           C:\OpenBLAS-v0.2.19-Win64-int32\include

LIBS += \
    -LC:\OpenBLAS-v0.2.19-Win64-int32\lib \
    -llibopenblas
</code>```

Now I receive the error: LNK1104: cannot open file 'libopenblas.lib'. I have downloaded windows binary of OpenBLAS. The installed folder structure is as given in the image: installed OpenBLAS folder

Please let me know what is going wrong?

Thanks.

答:
There are two reasons for this problem:

Weird naming of .lib file as libopenblas.dll.a even though package is called windows binary.

Incomplete binary package---- It doesn't contain all required dlls

Solution:

Choose a binary----win 64 or win32 and download it.

rename libopenblas.dll.a as libopenblas.lib as Yuriy has suggested

download from https://sourceforge.net/projects/openblas/files/v0.2.14/ required missing DLLs are bundled again under weirdly named zip files "mingw64_dll" or "mingw32_dll" depending upon the binary type which you have downloaded in step 1.  These zip file contain "libgcc_s_seh-1.dll", "libgfortran-3.dll" and "libquadmath-0.dll"

Add include and lib as I have done to your project and build with correct target depending upon your downloaded binary i.e win64 or X86

Copy libopenblas.dll from bin folder of OpenBLAS binary and "libgcc_s_seh-1.dll", "libgfortran-3.dll", "libquadmath-0.dll" from "mingw64_dll" or "mingw32_dll" depending upon the binary type to build debug or release directory where the exe reside.

Run your program and you are good to go.

If you want to escape copying again and again set a required system environment variable for the path containing these DLLs

Body:
I am using Qt Creator for development. I want to use Armadillo linear algebra library. Therefore I used following code in my pro file:

INCLUDEPATH += C:\armadillo-7.950.1\include

LIBS += \
    -LC:\armadillo-7.950.1\examples\lib_win64 \
    -llapack_win64_MT \
    -lblas_win64_MT

It was all good and the project compiled and linked properly. Next task was to replace LAPACK and BLAS with OpenBLAS. So the pro file was changed as following:

INCLUDEPATH += C:\armadillo-7.950.1\include \
           C:\OpenBLAS-v0.2.19-Win64-int32\include

LIBS += \
    -LC:\OpenBLAS-v0.2.19-Win64-int32\lib \
    -llibopenblas

Now I receive the error: LNK1104: cannot open file 'libopenblas.lib'. I have downloaded windows binary of OpenBLAS. The installed folder structure is as given in the image: installed OpenBLAS folder

Please let me know what is going wrong?

Thanks.


问:
GoogleApiClient Vs LocationClient to get accurate location in Android
I am trying to get an accurate location for my emergency alert app. I am already using the locationManager to get the location but fetching location with this technique takes about 30seconds I am looking for faster & accurate way.

The main goal here is to get faster/accurate location (Indoor or outdoor).

I have decided to use GooglePlayservices API for this purpose. I figured out there are two options LocationClient and GoogleApiClient?

I am not sure what is best here? Can somebody tell me what is the difference with both or is there a better option?

Let me know!

Thanks!

答:
Do not use GoogleApiClient. It is old and problematic. Use the new API. Please read the following Android newsletter link for the details :
https://android-developers.googleblog.com/2017/06/reduce-friction-with-new-location-apis.html</p>


问:
Launch an URL in Blackberry App
How do I open, or launch, a URL from a BlackBerry application?  I am not interested in doing this through a browser, such as Opera.  I think there is a Java class called BrowserContentManager or similar, but I can't figure out how to use it.</p>

答:
Check the demo code BrowserContentManagerDemo.java from the Blackberry JDE installation sample folder:

BlackBerry JDE 4.5.0\samples\com\rim\samples\device\blackberry\browser\

or from the Eclipse plugins folder:

eclipse/plugins/net.rim.ejde.componentpack6.0.0_6.0.0.29/components/samples/com/rim/samples/device/browser/browsercontentmanagerdemo/

Title: Launch an URL in Blackberry App


问:
Lodash update element values from another array Chain / Map
How I can update an array element values with another array elements data values, using Lodash

```<code>var Master_Array [
{ Name: "Jon", Region: "North America & Caribbean" },
{ Name: "Ruan", Region: "Asia Pacific" }
]

var Regions_Map = [
{ Region: 'Europe', NewRegion: 'EMEA' },
{ Region: 'North America & Caribbean', NewRegion: 'NAC' },
{ Region: 'Asia Pacific', NewRegion: 'APAC' }
]
</code>```

I think that can be did with:

```<code>_.chain()
.mapValues( ...blá blá... )
.values()
.value();
</code>```

Expected result:

```<code>var Master_Array [
{ Name: "Jon", Region: "NAC" },
{ Name: "Ruan", Region: "APAC" }
]
</code>```

答:
A solution with map and find:

var Master_Array = [
{ Name: "Jon", Region: "North America & Caribbean" },
{ Name: "Ruan", Region: "Asia Pacific" }
];

var Regions_Map = [
{ Region: 'Europe', NewRegion: 'EMEA' },
{ Region: 'North America & Caribbean', NewRegion: 'NAC' },
{ Region: 'Asia Pacific', NewRegion: 'APAC' }
];

Master_Array = Master_Array.map((person) => ({
  Name: person.Name,
  Region: Regions_Map.find((region) => region.Region === person.Region).NewRegion
}));

console.log(Master_Array);```

Body:
How I can update an array element values with another array elements data values, using Lodash

var Master_Array [
{ Name: "Jon", Region: "North America & Caribbean" },
{ Name: "Ruan", Region: "Asia Pacific" }
]

var Regions_Map = [
{ Region: 'Europe', NewRegion: 'EMEA' },
{ Region: 'North America & Caribbean', NewRegion: 'NAC' },
{ Region: 'Asia Pacific', NewRegion: 'APAC' }
]

I think that can be did with:

_.chain()
.mapValues( ...blá blá... )
.values()
.value();

Expected result:

var Master_Array [
{ Name: "Jon", Region: "NAC" },
{ Name: "Ruan", Region: "APAC" }
]


问:
How to debug why my Python program is not working?
```<code>def solve(numLegs,numHeads):
for numChicks in range(0, numHeads + 1):
numPigs = numHeads - numChicks
totLegs = 4*numPigs + 2*numChicks
if totLegs == numLegs:
return(numPigs,numChicks)
return(None,None)

def barnYard():
heads = input('Enter a Number of heads')
legs  = input('Enter a Number of legs')
pigs,chickens = solve(legs,heads)
if pigs == None:
    print ('There is no solution')
else:
    print ('number of Pigs',pigs)
    print ('number of chickens',chickens)

print (barnYard())
</code>```

I am getting error in 3 places in this code; can someone help me figure out why it is giving errors?

答:
The main error is that Whitespace is essential in Python. You must maintain correct indentation.

Your function definitions need to be indented, as do for loops and if statements.

returns are statements that need to be followed by whitespace before the item they are to return. (doing a return(x) would try to call a defined return function instead of running the correct return statement)

Another error is that when you accept a variable from input, it comes in as a string. If you want to use it for math as an integer, you need to cast it with int(input("your prompt"))

Another error is that you are using commas to join a string to another variable, and on top of that it's not a string. Make them strings, then use the + operator to contact them in the print statement.

```<code>def solve(numLegs,numHeads):
    for numChicks in range(0, numHeads + 1):
        numPigs = numHeads - numChicks
        totLegs = 4*numPigs + 2*numChicks
        if totLegs == numLegs:
            return (numPigs,numChicks)
        return (None,None)

def barnYard():
    heads = int(input('Enter a Number of heads'))
    legs  = int(input('Enter a Number of legs'))
    pigs,chickens = solve(legs,heads)
    if pigs == None:
        print ('There is no solution')
    else:
        print ('number of Pigs ' + str(pigs))
        print ('number of chickens ' + str(chickens))

print (barnYard())
</code>```

Body:
def solve(numLegs,numHeads):
for numChicks in range(0, numHeads + 1):
numPigs = numHeads - numChicks
totLegs = 4*numPigs + 2*numChicks
if totLegs == numLegs:
return(numPigs,numChicks)
return(None,None)

def barnYard():
heads = input('Enter a Number of heads')
legs  = input('Enter a Number of legs')
pigs,chickens = solve(legs,heads)
if pigs == None:
    print ('There is no solution')
else:
    print ('number of Pigs',pigs)
    print ('number of chickens',chickens)

print (barnYard())

I am getting error in 3 places in this code; can someone help me figure out why it is giving errors?

Body:
The main error is that Whitespace is essential in Python. You must maintain correct indentation.

Your function definitions need to be indented, as do for loops and if statements.

returns are statements that need to be followed by whitespace before the item they are to return. (doing a return(x) would try to call a defined return function instead of running the correct return statement)

Another error is that when you accept a variable from input, it comes in as a string. If you want to use it for math as an integer, you need to cast it with int(input("your prompt"))

Another error is that you are using commas to join a string to another variable, and on top of that it's not a string. Make them strings, then use the + operator to contact them in the print statement.

def solve(numLegs,numHeads):
    for numChicks in range(0, numHeads + 1):
        numPigs = numHeads - numChicks
        totLegs = 4*numPigs + 2*numChicks
        if totLegs == numLegs:
            return (numPigs,numChicks)
        return (None,None)

def barnYard():
    heads = int(input('Enter a Number of heads'))
    legs  = int(input('Enter a Number of legs'))
    pigs,chickens = solve(legs,heads)
    if pigs == None:
        print ('There is no solution')
    else:
        print ('number of Pigs ' + str(pigs))
        print ('number of chickens ' + str(chickens))

print (barnYard())


问:
How to automatically add user account AND password with a Bash script?
I need to have the ability to create user accounts on my Linux (Fedora 10) and automatically assign a password via a bash script(or otherwise, if need be).

It's easy to create the user via Bash e.g.:

```<code>[whoever@server ]#  /usr/sbin/useradd newuser
</code>```

Is it possible to assign a password in Bash, something functionally similar to this, but automatically:

```<code>[whoever@server ]# passwd newuser
Changing password for user testpass.
New UNIX password:
Retype new UNIX password:
passwd: all authentication tokens updated successfully.
[whoever@server ]#
</code>```

答:
I liked Tralemonkey's approach of echo thePassword | passwd theUsername --stdin though it didn't quite work for me as written. This however worked for me.

```<code>echo -e "$password\n$password\n" | sudo passwd $user
</code>```

-e is to recognize \n as new line.

sudo is root access for Ubuntu.

The double quotes are to recognize $ and expand the variables.

The above command passes the password and a new line, two times, to passwd, which is what passwd requires.

If not using variables, I think this probably works.

```<code>echo -e 'password\npassword\n' | sudo passwd username
</code>```

Single quotes should suffice here.

Body:
I need to have the ability to create user accounts on my Linux (Fedora 10) and automatically assign a password via a bash script(or otherwise, if need be).

It's easy to create the user via Bash e.g.:

[whoever@server ]#  /usr/sbin/useradd newuser

Is it possible to assign a password in Bash, something functionally similar to this, but automatically:

[whoever@server ]# passwd newuser
Changing password for user testpass.
New UNIX password:
Retype new UNIX password:
passwd: all authentication tokens updated successfully.
[whoever@server ]#

Body:
I liked Tralemonkey's approach of echo thePassword | passwd theUsername --stdin though it didn't quite work for me as written. This however worked for me.

echo -e "$password\n$password\n" | sudo passwd $user

-e is to recognize \n as new line.

sudo is root access for Ubuntu.

The double quotes are to recognize $ and expand the variables.

The above command passes the password and a new line, two times, to passwd, which is what passwd requires.

If not using variables, I think this probably works.

echo -e 'password\npassword\n' | sudo passwd username

Single quotes should suffice here.


问:
Finding just one or more comma in a string with ColdFusion
How can I detect if a string value only consists of one or more commas and nothing else. The correct value should be something like: ABC,BVC,BNM but sometimes I get value like: , or ,,, or ,, and this is not allowed. How can I detect that a string only have one or more commas and then I can create a warning to the user and stop the process.

Thank you

答:
Assuming any non-commas are either letters or numbers, you can do use a regular expression:</p>

```<code>patternAlphaNumeric = "[0-9a-zA-Z]";
testString = ",,,";

if (reFind(",", testString) > 0 && refind(patternAlphaNumeric, testString) == 0)
code for all commas
else
code for other characters
</code>```

Body:
Assuming any non-commas are either letters or numbers, you can do use a regular expression:

patternAlphaNumeric = "[0-9a-zA-Z]";
testString = ",,,";

if (reFind(",", testString) > 0 && refind(patternAlphaNumeric, testString) == 0)
code for all commas
else
code for other characters


问:
Flask-SQLAlchemy One to Many relationship failed to locate a name
I have a Flask app with Flask-SQLAlchemy. I'm trying to make a one to many relationship from a user to a trip. I saw that, if I use the declarative_base of SQLAlchemy it works but when I use the db.Model from Flask-SQLAlchemy it dosen't work.

I'm getting the following error:

```<code>sqlalchemy.exc.InvalidRequestError: When initializing mapper Mapper|User|User, expression 'Trip' failed to locate a name ("name 'Trip' is not defined"). If this is a class name, consider adding this relationship() to the <class 'models.user.User'> class after both dependent classes have been defined.
</code>```

Here are the models:

database.py

```<code>from flask import abort
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import exc

db = SQLAlchemy()

class Mixin(db.Model):
    __abstract__ = True
    id = db.Column(db.Integer, primary_key=True)
    date = db.Column(db.DateTime, default=db.func.now())
    date_changed = db.Column(
        db.DateTime, nullable=True, onupdate=db.func.now())
    date_to = db.Column(db.DateTime, nullable=True)
</code>```

user.py

```<code>from database import Mixin, db

class User(Mixin, db.Model):
    __tablename__ = 'User'
    trips = db.relationship(
        'Trip',
        backref=db.backref('user', lazy='joined'),
        lazy='dynamic'
    )
</code>```

trip.py

```<code>from database import Mixin, db

class Trip(Mixin, db.Model):
    __tablename__ = 'Trip'
    title = db.Column(db.String(100), nullable=False)
    description = db.Column(db.String(250), nullable=False)
    user_id = db.Column(
        db.Integer,
        db.ForeignKey('User.id'),
        nullable=False
    )
</code>```

答: I fixed it by using one file for my models. I didn't have enough models to need multiple model files anyway.</p>

Body:
I have a Flask app with Flask-SQLAlchemy. I'm trying to make a one to many relationship from a user to a trip. I saw that, if I use the declarative_base of SQLAlchemy it works but when I use the db.Model from Flask-SQLAlchemy it dosen't work.

I'm getting the following error:

sqlalchemy.exc.InvalidRequestError: When initializing mapper Mapper|User|User, expression 'Trip' failed to locate a name ("name 'Trip' is not defined"). If this is a class name, consider adding this relationship() to the <class 'models.user.User'> class after both dependent classes have been defined.

Here are the models:

database.py

from flask import abort
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import exc

db = SQLAlchemy()

class Mixin(db.Model):
    __abstract__ = True
    id = db.Column(db.Integer, primary_key=True)
    date = db.Column(db.DateTime, default=db.func.now())
    date_changed = db.Column(
        db.DateTime, nullable=True, onupdate=db.func.now())
    date_to = db.Column(db.DateTime, nullable=True)

user.py

from database import Mixin, db

class User(Mixin, db.Model):
    __tablename__ = 'User'
    trips = db.relationship(
        'Trip',
        backref=db.backref('user', lazy='joined'),
        lazy='dynamic'
    )

trip.py

from database import Mixin, db

class Trip(Mixin, db.Model):
    __tablename__ = 'Trip'
    title = db.Column(db.String(100), nullable=False)
    description = db.Column(db.String(250), nullable=False)
    user_id = db.Column(
        db.Integer,
        db.ForeignKey('User.id'),
        nullable=False
    )


问:
Rename files, using text-file as source
In a folder, i've 600 files, numbered from 001 to 600. It looks like foo_001.bar. In a text file, i've the number & titles of this folder. Now i want to rename foo_001.bar with the corresponding 001 title foobar from the text file.

But i don't have a clue how to do this properly on Linux Mint. Can someone help me or give me a tip?

Content of the titles.txt looks like this. With a tab (can be altered easy off course) between the number and the title.

```<code>001 title of 1
002 this is 2
003 and here goes 3
004 number four
005 hi this is five
etc
</code>```

Content of the folder looks like this. No exceptions.

```<code>file_001.ext
file_002.ext
file_003.ext
file_004.ext
file_005.ext
etc
</code>```

答:
Just loop through your file with read, get the seperated columns with awk cut (Thank you, @Jack) and mv your file accordingly. In this very simple implementation I assume that your text file containing the new names is located at ./filenames and your script is called from the directory containing your files.

```<code>#!/bin/bash
while IFS='' read -r line || [[ -n "$line" ]]; do
        NR=$(echo "$line" | cut -f 1)
        NAME=$(echo "$line" | cut -f 2)
        if [ -f "foo_${NR}.ext" ] ; then
                mv "foo_${NR}.ext" "$NAME"
        fi
done < filenames
</code>```

Title: Rename files, using text-file as source

Body:
In a folder, i've 600 files, numbered from 001 to 600. It looks like foo_001.bar. In a text file, i've the number & titles of this folder. Now i want to rename foo_001.bar with the corresponding 001 title foobar from the text file.

But i don't have a clue how to do this properly on Linux Mint. Can someone help me or give me a tip?

Content of the titles.txt looks like this. With a tab (can be altered easy off course) between the number and the title.

001 title of 1
002 this is 2
003 and here goes 3
004 number four
005 hi this is five
etc

Content of the folder looks like this. No exceptions.

file_001.ext
file_002.ext
file_003.ext
file_004.ext
file_005.ext
etc

Body:
Just loop through your file with read, get the seperated columns with awk cut (Thank you, @Jack) and mv your file accordingly. In this very simple implementation I assume that your text file containing the new names is located at ./filenames and your script is called from the directory containing your files.

#!/bin/bash
while IFS='' read -r line || [[ -n "$line" ]]; do
        NR=$(echo "$line" | cut -f 1)
        NAME=$(echo "$line" | cut -f 2)
        if [ -f "foo_${NR}.ext" ] ; then
                mv "foo_${NR}.ext" "$NAME"
        fi
done < filenames


问:
In JPA Query, can I pass the order by property and DESC/ASC order as parameters in the method signature?
I am using spring framework and working repository level implementations.

I have a class:

@Repository
public interface MyClassReadRepository extends ReadRepository<MyClass, Integer>

In this class there is a method that looks like this:

@Query("SELECT a FROM MyClass a WHERE a.type IN :myType ORDER BY :someProperty :someOrder")
Page<MyClass> findByTypeAndOrder(@Param("myType") List<MyType> myType, @Param("someProperty")String someProperty, @Param("someOrder")String someOrder, Pageable pageable)

But apparently the Query structure is wrong: ":someProperty" should be an identifier...

My question is: how to pass order and sort parameters in the example above?

Thanks in advance!

答:
You are already passing a Pageable object. You can pass your params as follows</p>

```<code>new PageRequest(1, 10, Sort.Direction.ASC, "yourProperty");
</code>```

Body:
You are already passing a Pageable object. You can pass your params as follows

new PageRequest(1, 10, Sort.Direction.ASC, "yourProperty");


问:
How to configure __main__.py, __init__.py, and setup.py for a basic package setup?

Background:

I have a directory structure like so:

```<code>Package/
    setup.py
    src/
        __init__.py
        __main__.py
        code.py
</code>```

I want to be able to run the code in a lot of different ways.

pip install Package and then python and then from Package import *

python -m Package which should do the thing in __main__.py

python __main__.py which should also do the thing in __main__.py but this time, we assume you've downloaded source rather than pip installing.

Now I've gotten the first two to work, but with a messy setup:

setup.py:

```<code>setup(
    name='Package',
    packages=['Package'],
    package_dir={'Package': 'src'},
    ...
    entry_points={ 'console_scripts': ['Package = src.__main__:main' ] }
</code>```

__init__.py:

```<code>from Package.code import .......
</code>```

__main__.py:

```<code>from . import .......
</code>```

What would make more sense to me would be in both cases to write

```<code>from code import ........
</code>```

but that gives me import errors.

Question:

Is the way I have it really the only way?

And most importantly, how do I support the third use case? Right now, python __main__.py throws

```<code>File "__main__.py", line 10, in <module>
    from . import code
ImportError: cannot import name 'class defined in code.py'
</code>```

Notes:

I have read

https://chriswarrick.com/blog/2014/09/15/python-apps-the-right-way-entry_points-and-scripts/

http://setuptools.readthedocs.io/en/latest/setuptools.html

The many questions here that look like this one but don't answer my question above.

答:
from code import ......... fails because there is no Python package installed on your system named code. There is a Python module on your system named code, but in your import statement you don't specify the package that your code module can be found in.

The purpose of the __init__.py file that you have in src/ tells Python that the src/ directory should be treated a Python package, with its contents as the modules within the package. Since code.py is located in src/ along with your __init__.py file, your code module is located in your src package.

Now that you know which package your code module can be found in, you can import stuff from it with:

```<code>from src.code import .........
</code>```

Also, as a side note: The __init__.py does its job just by being present in your src/ directory, so it doesn't even need to contain any code. For that reason it's generally a good idea to leave the __init__.py file blank.

Body:
Background:

I have a directory structure like so:

Package/
    setup.py
    src/
        __init__.py
        __main__.py
        code.py

I want to be able to run the code in a lot of different ways.

pip install Package and then python and then from Package import *

python -m Package which should do the thing in __main__.py

python __main__.py which should also do the thing in __main__.py but this time, we assume you've downloaded source rather than pip installing.

Now I've gotten the first two to work, but with a messy setup:

setup.py:

setup(
    name='Package',
    packages=['Package'],
    package_dir={'Package': 'src'},
    ...
    entry_points={ 'console_scripts': ['Package = src.__main__:main' ] }

__init__.py:

from Package.code import .......

__main__.py:

from . import .......

What would make more sense to me would be in both cases to write

from code import ........

but that gives me import errors.

Question:

Is the way I have it really the only way?

And most importantly, how do I support the third use case? Right now, python __main__.py throws

File "__main__.py", line 10, in <module>
    from . import code
ImportError: cannot import name 'class defined in code.py'

Notes:

I have read

https://chriswarrick.com/blog/2014/09/15/python-apps-the-right-way-entry_points-and-scripts/

http://setuptools.readthedocs.io/en/latest/setuptools.html

The many questions here that look like this one but don't answer my question above.

Body:
from code import ......... fails because there is no Python package installed on your system named code. There is a Python module on your system named code, but in your import statement you don't specify the package that your code module can be found in.

The purpose of the __init__.py file that you have in src/ tells Python that the src/ directory should be treated a Python package, with its contents as the modules within the package. Since code.py is located in src/ along with your __init__.py file, your code module is located in your src package.

Now that you know which package your code module can be found in, you can import stuff from it with:

from src.code import .........

Also, as a side note: The __init__.py does its job just by being present in your src/ directory, so it doesn't even need to contain any code. For that reason it's generally a good idea to leave the __init__.py file blank.


问:
On a webpage html,css consisting only of an image, fit image to viewport and center horizontally and vertically
This is for a very simple throwaway webpage, so inline CSS is if anything preferred over proper/pretty CSS. The use case is pretty simple: Take a large image (the images are 2100 px wide by 3000 px high), and ensure it always resizes to 90% viewport size, and that the image is always centered vertically and horizontally regardless of viewport size. Needs to be a pure HTML/CSS solution (no javascript/jquery). The page contains no other content except these images (which are wrapped in href> tags and link to another page).

I've been hacking around with all sorts of variations on position:absolute, tables, divs, etc but can't seem to put something together that matches my use case.

答:
Just position them absolute with 0 for all sides and set margin to auto. You might need to set this on the surrounding link (or generally the outmost inline element). No problem inlining this, if really necessary, though wouldn't recommend.

img {
  max-width: 90vw;
  max-height: 90vh;

  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;

  margin: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img src="http://via.placeholder.com/2100x3000"></code>```

Body:
This is for a very simple throwaway webpage, so inline CSS is if anything preferred over proper/pretty CSS. The use case is pretty simple: Take a large image (the images are 2100 px wide by 3000 px high), and ensure it always resizes to 90% viewport size, and that the image is always centered vertically and horizontally regardless of viewport size. Needs to be a pure HTML/CSS solution (no javascript/jquery). The page contains no other content except these images (which are wrapped in  tags and link to another page).

I've been hacking around with all sorts of variations on position:absolute, tables, divs, etc but can't seem to put something together that matches my use case.

Body:
Just position them absolute with 0 for all sides and set margin to auto. You might need to set this on the surrounding link (or generally the outmost inline element). No problem inlining this, if really necessary, though wouldn't recommend.

img {
  max-width: 90vw;
  max-height: 90vh;

  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;

  margin: auto;
}

<img src="http://via.placeholder.com/2100x3000">


问:
Devexpress Get gridview cell as hyperlink
I want to loop and edit the hyperlinks in my devexpress's gridview

```<code>    protected void ASPxGridView1_DataBound(object sender, EventArgs e)
    {
        for (int i = 0; i < ASPxGridView1.VisibleRowCount; i++)
        {
            DataRow row = ASPxGridView1.GetDataRow(i);
            ASPxHyperLink hl = row["MyColumnName"] as ASPxHyperLink;
            hl.Text = "something";
        }
    }
</code>```

Object reference not set to an instance of an object. error points to hl.text = "something";

How do I convert the row into a hyperlink properly? row["MyColumnName"].ToString() returns the text of the cell

答:
Refer these:

Find controls in the DataItem template of ASPxGridView column

The general technique of using the Init/Load event handler

Finding controls within Devexpress ASPxGridView

Either you can use the HtmlRowCreated event then you can fine control with various method provided by ASPxGridView API. There is another way that you can use the Init event of the Hyperlink control and at this event you can customize the control and  also review the "How to access controls used as my Grid templates" article for details.

```<code>protected void ASPxHyperLink1_Init(object sender, EventArgs e) {
ASPxHyperLink myLink =(ASPxHyperLink)sender;
int key = Convert.ToInt32(ASPxGridView.GetDetailRowKeyValue(myLink.NamingContainer));
}
</code>```

References:

ASPxGridView Hyperlink NavigateUrl at Runtime

Body:
I want to loop and edit the hyperlinks in my devexpress's gridview

    protected void ASPxGridView1_DataBound(object sender, EventArgs e)
    {
        for (int i = 0; i < ASPxGridView1.VisibleRowCount; i++)
        {
            DataRow row = ASPxGridView1.GetDataRow(i);
            ASPxHyperLink hl = row["MyColumnName"] as ASPxHyperLink;
            hl.Text = "something";
        }
    }

Object reference not set to an instance of an object. error points to hl.text = "something";

How do I convert the row into a hyperlink properly? row["MyColumnName"].ToString() returns the text of the cell

Body:
Refer these:

Find controls in the DataItem template of ASPxGridView column

The general technique of using the Init/Load event handler

Finding controls within Devexpress ASPxGridView

Either you can use the HtmlRowCreated event then you can fine control with various method provided by ASPxGridView API. There is another way that you can use the Init event of the Hyperlink control and at this event you can customize the control and  also review the "How to access controls used as my Grid templates" article for details.

protected void ASPxHyperLink1_Init(object sender, EventArgs e) {
ASPxHyperLink myLink =(ASPxHyperLink)sender;
int key = Convert.ToInt32(ASPxGridView.GetDetailRowKeyValue(myLink.NamingContainer));
}

References:

ASPxGridView Hyperlink NavigateUrl at Runtime


问:
Classic ASP Page that uses JavaScript crashing on new ActiveXObject
I have a asp classic page but the language is set on javascript. like this

<%@ Language=JavaScript %>

if I try to create a http request like this

```<code>   var xmlhttp = new ActiveXObject("MSXML2.ServerXMLHTTP.4.0");
</code>```

or

```<code>   var xmlhttp = new XMLHttpRequest();
</code>```

the page just crashes with a generic error saying like an internal server error occurred. Does anyone know how I can investigate and fix this?

Thanks

答: That code is not meant to execute on the server. It's meant to execute client-side. The server does not have an XHR component installed on it.</p>

Body:
I have a asp classic page but the language is set on javascript. like this

<%@ Language=JavaScript %>

if I try to create a http request like this

   var xmlhttp = new ActiveXObject("MSXML2.ServerXMLHTTP.4.0");

or

   var xmlhttp = new XMLHttpRequest();

the page just crashes with a generic error saying like an internal server error occurred. Does anyone know how I can investigate and fix this?

Thanks


问:
Good pattern for multiphase algorithm?
Is there a pattern (refactoring) to improve this piece of code?

```<code>    int phase = 0;
    foreach (var some in arrayOfSome)
    {
        if (phase == 0)
        {
            bool result = DoSomething_0(some);
            if (result) phase = 1;
        }
        else if (phase == 1)
        {
            bool result = DoSomething_1(some);
            if (result) phase = 0;

            result = DoSomething_1_0(some);
            if (result) phase = 2;
        }
        else if (phase == 2)
        {
            bool result = DoSomething_2(some);
            if (result) break;
        }
    }
</code>```

First of all, I want to reduce the number of conditional operators and make the code more readable.

答:
An elegant approach is to eliminate the if/then logic altogether. You can do this by creating an array of delegates indexed by state (phase). Each delegate slot in the array points at a function (or lambda) that does whatever and returns the new state (phase).

In these kinds of designs, you often end up with a loop that contains a single statement like this:

```<code>foreach (var x in data)
{
    state = handler[state](x);
}
</code>```

I've coded this kind of FSM many times and they are very generic when done correctly and very reliable. Bugs almost always boil down to small errors in handlers or incorrect handlers being defined for a given state/input combination.

A more general and powerful design has this pattern:

```<code>foreach (var x in data)
{
    state = handler[state,x](x);
}
</code>```

Where both the state and datum are used to select the handler delegate. There are huge benefits when using this pattern in that the temptation to add extra flags and conditions within the loop as the code or functionality grows over time.

The code you posted is OK but if - after time - one ends up with ten different states and umpteen conditions and many handlers then very subtle hard to fix bugs will creep in that are almost impossible sometimes to fix.

Title: Good pattern for multiphase algorithm?

Body:
Is there a pattern (refactoring) to improve this piece of code?

    int phase = 0;
    foreach (var some in arrayOfSome)
    {
        if (phase == 0)
        {
            bool result = DoSomething_0(some);
            if (result) phase = 1;
        }
        else if (phase == 1)
        {
            bool result = DoSomething_1(some);
            if (result) phase = 0;

            result = DoSomething_1_0(some);
            if (result) phase = 2;
        }
        else if (phase == 2)
        {
            bool result = DoSomething_2(some);
            if (result) break;
        }
    }

First of all, I want to reduce the number of conditional operators and make the code more readable.

Body:
An elegant approach is to eliminate the if/then logic altogether. You can do this by creating an array of delegates indexed by state (phase). Each delegate slot in the array points at a function (or lambda) that does whatever and returns the new state (phase).

In these kinds of designs, you often end up with a loop that contains a single statement like this:

foreach (var x in data)
{
    state = handler[state](x);
}

I've coded this kind of FSM many times and they are very generic when done correctly and very reliable. Bugs almost always boil down to small errors in handlers or incorrect handlers being defined for a given state/input combination.

A more general and powerful design has this pattern:

foreach (var x in data)
{
    state = handler[state,x](x);
}

Where both the state and datum are used to select the handler delegate. There are huge benefits when using this pattern in that the temptation to add extra flags and conditions within the loop as the code or functionality grows over time.

The code you posted is OK but if - after time - one ends up with ten different states and umpteen conditions and many handlers then very subtle hard to fix bugs will creep in that are almost impossible sometimes to fix.


问:
How to save image
I want to save image with userdefaults and use it in another view with this code but it shows an error .

```<code>UserDefaults.standard.set(img , forKey : "simg")
</code>```

please help me

答:
This is how I would do it. You have multiple places to save it to, the user's Documents folder is usually best:

```<code>func cacheImageAsPNG(image: UIImage, localID: String) {
    let userDocumentsURL = URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0])
    if let imageData = UIImagePNGRepresentation(image) {
        let filename = userDocumentsURL.appendingPathComponent("\(localID).png")

        if  FileManager.default.createFile(atPath: filename.path, contents: imageData, attributes: nil) {
            print("wrote file:\n\(filename.path)")
        } else {
            print("couldn't write the file:\n\(filename.path)")
        }
    }
}
</code>```

if you want it erased by the system during times of peak memory usage, the cache directory is a better place:

```<code> let cachesPath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).last!
</code>```

Edit: Retrieving the Image

```<code>func cachedImage(localID: String) -> UIImage? {
    let userDocumentsURL = URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0])
    let cachePath = userDocumentsURL.appendingPathComponent("\(localID).png")

    return UIImage(named: cachePath.path)
}
</code>```

Title: How to save image

Body:
I want to save image with userdefaults and use it in another view with this code but it shows an error .

UserDefaults.standard.set(img , forKey : "simg")

please help me

Body:
This is how I would do it. You have multiple places to save it to, the user's Documents folder is usually best:

func cacheImageAsPNG(image: UIImage, localID: String) {
    let userDocumentsURL = URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0])
    if let imageData = UIImagePNGRepresentation(image) {
        let filename = userDocumentsURL.appendingPathComponent("\(localID).png")

        if  FileManager.default.createFile(atPath: filename.path, contents: imageData, attributes: nil) {
            print("wrote file:\n\(filename.path)")
        } else {
            print("couldn't write the file:\n\(filename.path)")
        }
    }
}

if you want it erased by the system during times of peak memory usage, the cache directory is a better place:

 let cachesPath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).last!

Edit: Retrieving the Image

func cachedImage(localID: String) -> UIImage? {
    let userDocumentsURL = URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0])
    let cachePath = userDocumentsURL.appendingPathComponent("\(localID).png")

    return UIImage(named: cachePath.path)
}


问:
jqgrid: editData not being sent to server
I'm using guriddo jqGrid 5.2.1

I've followed the answers provided to these questions:

jqGrid: sending edit data

Add additional param to post data using jqGrid when adding new row with modal form

How to post variable data with editData or onclickSubmit in jqgrid

But the editData I've defined is not getting sent to the endpoint.

Here is the code in my jqgrid pager definition:

```<code>$('#jqGrid').navGrid('#jqGridPager',
            // the buttons to appear on the toolbar of the grid
            { edit: true,
                add: true,
                del: true,
                search: false,
                refresh: false,
                view: false,
                position: "left",
                cloneToTop: false,
                mtype: 'POST',
                editData: {
                    mediaPlanId : function() { return mpId; }
                }},
            // options for the Edit Dialog
            {
                editCaption: "Edit Item",
                recreateForm: true,
                checkOnUpdate : true,
                checkOnSubmit : true,
                closeAfterEdit: true,
                errorTextFormat: function (data) {
                    return 'Error: ' + data.responseText;
                }
            },
            // options for the Add Dialog
            {
                closeAfterAdd: true,
                recreateForm: true,
                errorTextFormat: function (data) {
                    return 'Error: ' + data.responseText;
                }
            },
            // options for the Delete Dailog
            {
                errorTextFormat: function (data) {
                    return 'Error: ' + data.responseText;
                }
            }

    );
</code>```

mpId is defined outside of the jqGrid and jqGridPager functions, at the page level.  I tried sending a value of 1, but that doesn't work either.  I suspect I've missed something simple, but I can't figure out what.

答:
You place the editData parameter on the wrong place. The options of navGrid are very bad and one can made easy errors. I described the problem in detailed in the wiki article of free jqGrid fork, which I develop.

Currently you placed editData in the options of navGrid instead of placing it in the options of Edit/Add, which are the options of editGridRow. The problem is solved in free jqGrid, but if you do prefer to use commercial version of Guriddo jqGrid JS then I would recommend you to rewrite your code in the following way:

```<code>var myErrorFunc = function (data) {
        return 'Error: ' + data.responseText;
    },
    addEditFormOptions = {
        editCaption: "Edit Item",
        recreateForm: true,
        checkOnUpdate : true,
        checkOnSubmit : true,
        closeAfterEdit: true,
        closeAfterAdd: true,
        editData: {
            mediaPlanId : function() { return mpId; }
        },
        errorTextFormat: myErrorFunc
    },
    delOptions = {
        errorTextFormat: myErrorFunc
    };

$('#jqGrid').navGrid('#jqGridPager', { search: false, refresh: false },
    addEditFormOptions, addEditFormOptions, delOptions);
</code>```

Body:
I'm using guriddo jqGrid 5.2.1

I've followed the answers provided to these questions:

jqGrid: sending edit data

Add additional param to post data using jqGrid when adding new row with modal form

How to post variable data with editData or onclickSubmit in jqgrid

But the editData I've defined is not getting sent to the endpoint.

Here is the code in my jqgrid pager definition:

$('#jqGrid').navGrid('#jqGridPager',
            // the buttons to appear on the toolbar of the grid
            { edit: true,
                add: true,
                del: true,
                search: false,
                refresh: false,
                view: false,
                position: "left",
                cloneToTop: false,
                mtype: 'POST',
                editData: {
                    mediaPlanId : function() { return mpId; }
                }},
            // options for the Edit Dialog
            {
                editCaption: "Edit Item",
                recreateForm: true,
                checkOnUpdate : true,
                checkOnSubmit : true,
                closeAfterEdit: true,
                errorTextFormat: function (data) {
                    return 'Error: ' + data.responseText;
                }
            },
            // options for the Add Dialog
            {
                closeAfterAdd: true,
                recreateForm: true,
                errorTextFormat: function (data) {
                    return 'Error: ' + data.responseText;
                }
            },
            // options for the Delete Dailog
            {
                errorTextFormat: function (data) {
                    return 'Error: ' + data.responseText;
                }
            }

    );

mpId is defined outside of the jqGrid and jqGridPager functions, at the page level.  I tried sending a value of 1, but that doesn't work either.  I suspect I've missed something simple, but I can't figure out what.

Body:
You place the editData parameter on the wrong place. The options of navGrid are very bad and one can made easy errors. I described the problem in detailed in the wiki article of free jqGrid fork, which I develop.

Currently you placed editData in the options of navGrid instead of placing it in the options of Edit/Add, which are the options of editGridRow. The problem is solved in free jqGrid, but if you do prefer to use commercial version of Guriddo jqGrid JS then I would recommend you to rewrite your code in the following way:

var myErrorFunc = function (data) {
        return 'Error: ' + data.responseText;
    },
    addEditFormOptions = {
        editCaption: "Edit Item",
        recreateForm: true,
        checkOnUpdate : true,
        checkOnSubmit : true,
        closeAfterEdit: true,
        closeAfterAdd: true,
        editData: {
            mediaPlanId : function() { return mpId; }
        },
        errorTextFormat: myErrorFunc
    },
    delOptions = {
        errorTextFormat: myErrorFunc
    };

$('#jqGrid').navGrid('#jqGridPager', { search: false, refresh: false },
    addEditFormOptions, addEditFormOptions, delOptions);


问:
Javascript XMLHttpRequest: Ignore invalid SSL Certificate
so I have been having trouble with grabbing information from a device that is interfaced with via https due to the fact that it has an invalid security certificate.  I know the device is to be trusted and I don't have access to the server-side so I can't change it.  I was wondering if there was any way to set up an XMLHttpRequest object in Javascript to just ignore an invalid SSL certificate and just grab the information anyway.  As it is now it seems to just reject the certificate and stop.  Thanks.</p>

答:
I know the device is to be trusted

Yes but you don't know whether you are really connected to the device.

That is the purpose of the certificate. That's why it has to be valid.


问:
Click anchor element using javascript function
I know this has been covered elsewhere on this site, as well as many others, but I just can't seem to figure it out.

I have an anchor tag that I use to show a lightbox form:

```<code><a id="aNoData" href="#divNoData" class="fancybox">No Data</a>
</code>```

I want to click it using a javascript function:

```<code>function fnNoData()
{
    //  This line works
    alert("this line works");
    //  Neither of these lines work
    $('#aNoData').click();
     document.getElementById('aNoData').click();
}
</code>```

I'm calling the function from my code behind, like this:

```<code>ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "fnNoData()", true);
</code>```

When I do this, the first line (the alert box) shows fine. However, the other two lines (to click the anchor tag) do not. The non-working lines work great if I put them in my $(document).ready block (the anchor clicks on page load). So it seems that the lines to click my anchor work fine, just not in my function.

Can anyone see what I'm doing wrong?

答:
If you want to do click directly than you can use trigger

Check this hope this will helps you.

```<code>function fnNoData()
{
    //  This line works
    alert("this line works");
    //trigger
    $('#aNoData').trigger('click');
    //document.getElementById('aNoData').click();
}
</code>```

Body:
I know this has been covered elsewhere on this site, as well as many others, but I just can't seem to figure it out.

I have an anchor tag that I use to show a lightbox form:

No Data

I want to click it using a javascript function:

function fnNoData()
{
    //  This line works
    alert("this line works");
    //  Neither of these lines work
    $('#aNoData').click();
     document.getElementById('aNoData').click();
}

I'm calling the function from my code behind, like this:

ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "fnNoData()", true);

When I do this, the first line (the alert box) shows fine. However, the other two lines (to click the anchor tag) do not. The non-working lines work great if I put them in my $(document).ready block (the anchor clicks on page load). So it seems that the lines to click my anchor work fine, just not in my function.

Can anyone see what I'm doing wrong?

Body:
If you want to do click directly than you can use trigger

Check this hope this will helps you.

function fnNoData()
{
    //  This line works
    alert("this line works");
    //trigger
    $('#aNoData').trigger('click');
    //document.getElementById('aNoData').click();
}


问:
clear() methods in Java
Many of the container type data structures in Java come with a clear() method. For example, we can call clear() on a Vector we want to clear out all the contents in the Vector. My question is after applying the clear() method, does the content in the vector get nulled out or are they still being referenced? Thanks.

答:
```<code>while(!stack.isEmpty()){
    System.out.println(stack.pop());
    System.out.println(stack);
}
</code>```

Title: clear() methods in Java


问:
NameError: uninitialized constant ActiveRecord::Migrator::Zlib
I'm new to Ruby and Active Record. I'm trying to run my first migration with the command:

```<code>rake db:migrate
</code>```

I keep getting this error:

NameError: uninitialized constant ActiveRecord::Migrator::Zlib.

I've tried with different projects and all migrations are getting this error.

答:
Add the following to Rakefile:

require 'zlib'

Body:
I'm new to Ruby and Active Record. I'm trying to run my first migration with the command:

rake db:migrate

I keep getting this error:

NameError: uninitialized constant ActiveRecord::Migrator::Zlib.

I've tried with different projects and all migrations are getting this error.


问:
Angular 2 - Call other component function
i'm trying to call another component function from a component. This is my constructor :

```<code>    constructor(
        private http: Http,
        private appComponent: AppComponent
        ) {
        this.setUrl();
    }

    setUrl() {
        if (this.appComponent) {
            this.Url = this.appComponent.getEnvironnement();
        } else {
            setInterval(this.setUrl, 1000);
        }
    }
</code>```

However, when I'm trying to property/function from my appComponent, I get an error saying : appComponent is undefined

Why my component is undefined, even if I initialize it on the beginning ?

答:
You can use the @Output for other component event binding.

Do use @Input and @Output instead of the inputs and outputs properties of the @Directive and @Component decorators

For more information you can visit following URl:
https://www.sitepoint.com/angular-2-components-inputs-outputs/

Body:
i'm trying to call another component function from a component. This is my constructor :

    constructor(
        private http: Http,
        private appComponent: AppComponent
        ) {
        this.setUrl();
    }

    setUrl() {
        if (this.appComponent) {
            this.Url = this.appComponent.getEnvironnement();
        } else {
            setInterval(this.setUrl, 1000);
        }
    }

However, when I'm trying to property/function from my appComponent, I get an error saying : appComponent is undefined

Why my component is undefined, even if I initialize it on the beginning ?