问:
How to evaluate a mathematical expression saved in nvarchar variable in SQL Server
i want to evaluate a mathematical expression saved in a variable in sql server

i google this a lot and found 3 solution but not applicable in my scenario

1- this solution cannot be executed inside a function but i need it inside a function

```<code>declare @expression nvarchar(max)
set @expression = '2*3*100'

declare @sql nvarchar(max)
set @sql = 'select @result = ' + @expression

declare @result int
exec sp_executesql @sql, N'@result int output', @result = @result out

select @result
</code>```

2- this cannot be saved into a variable but i need to store the result into a variable

```<code>DECLARE @LocalVariable VARCHAR(32);
SET @LocalVariable = '2*3*100';
EXEC('SELECT ' + @LocalVariable);
</code>```

3- the last solution i found gives me a error

```<code>DECLARE @x xml
DECLARE @v decimal(20,4)
SET @x = ''
DECLARE @calculatedDataString nvarchar(1000) = '(1 div 100)*((118 div 100)*300.000000)'
SET @v= @x.value('sql:variable("@calculatedDataString")', 'decimal(20,4)')
SELECT @v
</code>```

the error is

```<code>Msg 8114, Level 16, State 5, Line 5
Error converting data type nvarchar to numeric.
</code>```

please advice

答:
The last your solution fails because SET @v= @x.value('sql:variable("@calculatedDataString")', 'decimal(20,4)') does not evaluate the expression, it tries to cast @calculatedDataString to decimal which definitely must fail in most cases.

The only solution I know is CLR function. You may wish to look at this project https://github.com/zzzprojects/Eval-SQL.NET

It creates SQLNET UDT with methods you can use, kind of

```<code>SELECT  SQLNET::New(@calculatedDataString).EvalInt()
</code>```

See https://learn.microsoft.com/en-us/sql/relational-databases/clr-integration-database-objects-user-defined-types/registering-user-defined-types-in-sql-server for how to register UDT in sql-server.

Body:
i want to evaluate a mathematical expression saved in a variable in sql server

i google this a lot and found 3 solution but not applicable in my scenario

1- this solution cannot be executed inside a function but i need it inside a function

declare @expression nvarchar(max)
set @expression = '2*3*100'

declare @sql nvarchar(max)
set @sql = 'select @result = ' + @expression

declare @result int
exec sp_executesql @sql, N'@result int output', @result = @result out

select @result

2- this cannot be saved into a variable but i need to store the result into a variable

DECLARE @LocalVariable VARCHAR(32);
SET @LocalVariable = '2*3*100';
EXEC('SELECT ' + @LocalVariable);

3- the last solution i found gives me a error

DECLARE @x xml
DECLARE @v decimal(20,4)
SET @x = ''
DECLARE @calculatedDataString nvarchar(1000) = '(1 div 100)*((118 div 100)*300.000000)'
SET @v= @x.value('sql:variable("@calculatedDataString")', 'decimal(20,4)')
SELECT @v

the error is

Msg 8114, Level 16, State 5, Line 5
Error converting data type nvarchar to numeric.

please advice

Body:
The last your solution fails because SET @v= @x.value('sql:variable("@calculatedDataString")', 'decimal(20,4)') does not evaluate the expression, it tries to cast @calculatedDataString to decimal which definitely must fail in most cases.

The only solution I know is CLR function. You may wish to look at this project https://github.com/zzzprojects/Eval-SQL.NET

It creates SQLNET UDT with methods you can use, kind of

SELECT  SQLNET::New(@calculatedDataString).EvalInt()

See https://learn.microsoft.com/en-us/sql/relational-databases/clr-integration-database-objects-user-defined-types/registering-user-defined-types-in-sql-server for how to register UDT in sql-server.


来源: stackexchange

问:
Modal with overlaying anchor
Although I am quickly learning JS I have a problem i can't figure out. I have a modal which is in a
 and a
 that contains an image and product name, when I hover over this
 I get a hover icon which is an . When I click on the
 with the image in it a modal pops up - this works brilliantly. But When I click the  the modal pops up and then you are taken to the link. I don't want the modal to appear when you click the overlaying .

Here's my HTML for the Modal:

```<code><div class="modal myModal">

<!-- Modal content -->
<div class="modal-content">
    <span class="close">×</span>

    <?php echo $this->stripTags($_product->getName(), null, true) ?>
    <div class="popup-image-container">

    <img id="popup-image" src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->keepFrame($_imageKeepFrame)->resize($_gridImageSize); ?>" srcset="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->keepFrame($_imageKeepFrame)->resize($_gridImageSize); ?> 1x, <?php echo $this->helper('catalog/image')->init($_product, 'small_image')->keepFrame($_imageKeepFrame)->resize($_gridImageSize * 2); ?> 2x"
                            width="75%" height="75%"
                            alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>"
                        /></div>
    <div class="popup-buttons ">
<button type="button" title="<?php echo $this->__('View Detail') ?>" class="ui-btn ui-corner-all ui-shadow ui-btn-b ui-btn-icon-left ui-icon-check" onclick="setLocation('<?php echo $_product->getProductUrl() ?>')"><span><span><?php echo $this->__('More Detail') ?></span></span></button>

<button type="button" title="<?php echo $this->__('Visit Store') ?>" class="ui-btn ui-corner-all ui-shadow ui-btn-b ui-btn-icon-left ui-icon-check"onclick="window.open('<?php echo $_helper->productAttribute($_product, $_product->getAdvertiserBuyLink(), 'advertiser_buy_link') ?>', '_blank');"<span><span><?php echo $this->__('Goto Store') ?></span></span></button></p>
  </div>
  </div>
  </div>
</code>```

and for the Product

```<code>            <div class="prolabel-wrapper">
                <?php echo Mage::helper('prolabels')->getLabel($_product, 'category'); ?>
                <img id="product-collection-image-<?php echo $_product->getId(); ?>"
                    src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->keepFrame($_imageKeepFrame)->resize($_gridImageSize); ?>"
                    srcset="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->keepFrame($_imageKeepFrame)->resize($_gridImageSize); ?> 1x, <?php echo $this->helper('catalog/image')->init($_product, 'small_image')->keepFrame($_imageKeepFrame)->resize($_gridImageSize * 2); ?> 2x"
                    width="<?php echo $_gridImageSize ?>" height="<?php echo $_gridImageSize ?>"
                    alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>"
                />
                <ul class="add-to-links">
                    <?php if ($this->helper('wishlist')->isAllow()) : ?>
                        <li class="li-wishlist"><a rel="nofollow" id="wishlist" href="<?php echo $this->helper('wishlist')->getAddUrl($_product) ?>" class="link-wishlist" title="<?php echo $this->__('Add to Wishlist') ?>" onclick="return false;"><i class="fa fa-heart" aria-hidden="true"></i></a></li>
                    <?php endif; ?>
                    <?php if($_compareUrl=$this->getAddToCompareUrl($_product)): ?>
                        <li class="li-compare"><a rel="nofollow" href="<?php echo $_compareUrl ?>" class="link-compare" title="<?php echo $this->__('Add to Compare') ?>"><i class="fa fa-plus" aria-hidden="true"></i></a></li>
                    <?php endif; ?>
                </ul>
            </div>
</code>```

Here is the JS that I created:

```<code>var modals = document.getElementsByClassName("modal");
// Get the button that opens the modal
var btns = document.getElementsByClassName("prolabel-wrapper");

var spans=document.getElementsByClassName("close");

var wishlist=document.getElementsByClassName("link-wishlist");

var showPopup = true;
// Get the modal
window.onload = function(){

for(let i=0;i<wishlist.length;i++) {
   wishlist[i].onclick = function() {
      var showPopup = false;
      alert("Here - showPopup is " + showPopup);
      modals[i].style.display = "none";
      return false;
   }
}

alert("Here2 - showPopup is " + showPopup);

    if (showPopup){

        alert ("Still getting called" + showPopup);
for(let i=0;i<btns.length && showPopup;i++) {

        btns[i].onclick = function() {
        modals[i].style.display = "block";
        }

}

for(let i=0;i<spans.length && showPopup;i++){

        spans[i].onclick = function() {
        modals[i].style.display = "none";
        }

}
}}
</code>```

I can get the alert("Here - showPopup is " + showPopup); to popup and then the return false cancels out the link, but the modal still show, please can anyone point me in the right direction?

Thanks
Chris

答:
Inside the first for loop you are trying to set the global variable showPopup to false but, instead, you are declaring a new one.

Try replacing:

```<code>var showPopup = false;
</code>```

by:

```<code>showPopup = false;
</code>```

ContentLicense: CC BY-SA 3.0

Title: Modal with overlaying anchor

Body:
Although I am quickly learning JS I have a problem i can't figure out. I have a modal which is in a
 and a
 that contains an image and product name, when I hover over this
 I get a hover icon which is an . When I click on the
 with the image in it a modal pops up - this works brilliantly. But When I click the  the modal pops up and then you are taken to the link. I don't want the modal to appear when you click the overlaying .

Here's my HTML for the Modal:

    ×

    <?php echo $this->stripTags($_product->getName(), null, true) ?>

    <img id="popup-image" src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->keepFrame($_imageKeepFrame)->resize($_gridImageSize); ?>" srcset="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->keepFrame($_imageKeepFrame)->resize($_gridImageSize); ?> 1x, <?php echo $this->helper('catalog/image')->init($_product, 'small_image')->keepFrame($_imageKeepFrame)->resize($_gridImageSize * 2); ?> 2x"
                            width="75%" height="75%"
                            alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>"
                        />

<button type="button" title="<?php echo $this->__('View Detail') ?>" class="ui-btn ui-corner-all ui-shadow ui-btn-b ui-btn-icon-left ui-icon-check" onclick="setLocation('<?php echo $_product->getProductUrl() ?>')"><?php echo $this->__('More Detail') ?></button>

<button type="button" title="<?php echo $this->__('Visit Store') ?>" class="ui-btn ui-corner-all ui-shadow ui-btn-b ui-btn-icon-left ui-icon-check"onclick="window.open('<?php echo $_helper->productAttribute($_product, $_product->getAdvertiserBuyLink(), 'advertiser_buy_link') ?>', '_blank');"<?php echo $this->__('Goto Store') ?></button>

and for the Product

                <?php echo Mage::helper('prolabels')->getLabel($_product, 'category'); ?>
                <img id="product-collection-image-<?php echo $_product->getId(); ?>"
                    src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->keepFrame($_imageKeepFrame)->resize($_gridImageSize); ?>"
                    srcset="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->keepFrame($_imageKeepFrame)->resize($_gridImageSize); ?> 1x, <?php echo $this->helper('catalog/image')->init($_product, 'small_image')->keepFrame($_imageKeepFrame)->resize($_gridImageSize * 2); ?> 2x"
                    width="<?php echo $_gridImageSize ?>" height="<?php echo $_gridImageSize ?>"
                    alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>"
                />

                    <?php if ($this->helper('wishlist')->isAllow()) : ?>

<a rel="nofollow" id="wishlist" href="<?php echo $this->helper('wishlist')->getAddUrl($_product) ?>" class="link-wishlist" title="<?php echo $this->__('Add to Wishlist') ?>" onclick="return false;">

                    <?php endif; ?>
                    <?php if($_compareUrl=$this->getAddToCompareUrl($_product)): ?>

<a rel="nofollow" href="<?php echo $_compareUrl ?>" class="link-compare" title="<?php echo $this->__('Add to Compare') ?>">

                    <?php endif; ?>

Here is the JS that I created:

var modals = document.getElementsByClassName("modal");
// Get the button that opens the modal
var btns = document.getElementsByClassName("prolabel-wrapper");

var spans=document.getElementsByClassName("close");

var wishlist=document.getElementsByClassName("link-wishlist");

var showPopup = true;
// Get the modal
window.onload = function(){

for(let i=0;i<wishlist.length;i++) {
   wishlist[i].onclick = function() {
      var showPopup = false;
      alert("Here - showPopup is " + showPopup);
      modals[i].style.display = "none";
      return false;
   }
}

alert("Here2 - showPopup is " + showPopup);

    if (showPopup){

        alert ("Still getting called" + showPopup);
for(let i=0;i<btns.length && showPopup;i++) {

        btns[i].onclick = function() {
        modals[i].style.display = "block";
        }

}

for(let i=0;i<spans.length && showPopup;i++){

        spans[i].onclick = function() {
        modals[i].style.display = "none";
        }

}
}}

I can get the alert("Here - showPopup is " + showPopup); to popup and then the return false cancels out the link, but the modal still show, please can anyone point me in the right direction?

Thanks
Chris

Body:
Inside the first for loop you are trying to set the global variable showPopup to false but, instead, you are declaring a new one.

Try replacing:

var showPopup = false;

by:

showPopup = false;


问:
Security problem while trying to load image from server disk in Actionscript 3.0
I encountered error #2148(which is security) when i was trying to load an image file.

1.If i load the swf file in local, the image s retrieved and displayed properly.

2.But if i publish the swf file into my web project and run it in localhost, it gives me #2148 security error

3.If I use http://xx.xx/ticketstub.png in loadImage() function, it works in both 1 and 2;
The problem now is when i use C:/jbdevstudio/uploads/ticketdesign/ticketstub.png it isnt working in web server.

Any idea how can i solve this or Flash simply doesnt support this. I had googled this issue for few days and try out any solutions i found but no luck still.

Thanks!

ActionScript codes:

```<code>//http://xx.xx/ticketstub.png works in both 1 and 2
loadImage("C:/jbdevstudio/uploads/ticketdesign/ticketstub.png");

function loadImage(url:String):void {
try{
 // Set properties on my Loader object
 imageLoader = new Loader();
 imageLoader.load(new URLRequest(url));
 imageLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, imageLoading);
 imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, imageLoaded);
}catch(error:Error){
    ExternalInterface.call("er", error.toString());
}
}

function imageLoaded(e:Event):void {
try{
 // Load Image
 imageHolder.addChild(imageLoader);
 imageHolder.width = imageHolder.width / 3.5;
 imageHolder.height = imageHolder.height / 3.5;
}catch(error:Error){
    ExternalInterface.call("er", error.toString());
}
</code>```

答:
You cannot load an image from your local file system in Flash like this.

Images can be loaded from a web URL. If they come from a different domain to the SWF, you can only display them, not process them. However, with additional security support (proxy or crossdomain.xml) you can load images from another domain, and process them as you need.

The third option is to upload an image provided by the user through the FileReference class, however, the user selects the file, the SWF cannot select it directly. These files can be processed in any way you like.

ContentLicense: CC BY-SA 2.5

Body:
I encountered error #2148(which is security) when i was trying to load an image file.

1.If i load the swf file in local, the image s retrieved and displayed properly.

2.But if i publish the swf file into my web project and run it in localhost, it gives me #2148 security error

3.If I use http://xx.xx/ticketstub.png in loadImage() function, it works in both 1 and 2;
The problem now is when i use C:/jbdevstudio/uploads/ticketdesign/ticketstub.png it isnt working in web server.

Any idea how can i solve this or Flash simply doesnt support this. I had googled this issue for few days and try out any solutions i found but no luck still.

Thanks!

ActionScript codes:

//http://xx.xx/ticketstub.png works in both 1 and 2
loadImage("C:/jbdevstudio/uploads/ticketdesign/ticketstub.png");

function loadImage(url:String):void {
try{
 // Set properties on my Loader object
 imageLoader = new Loader();
 imageLoader.load(new URLRequest(url));
 imageLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, imageLoading);
 imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, imageLoaded);
}catch(error:Error){
    ExternalInterface.call("er", error.toString());
}
}

function imageLoaded(e:Event):void {
try{
 // Load Image
 imageHolder.addChild(imageLoader);
 imageHolder.width = imageHolder.width / 3.5;
 imageHolder.height = imageHolder.height / 3.5;
}catch(error:Error){
    ExternalInterface.call("er", error.toString());
}


问:
Eclipse LogCat shows only the first letter from each message
I installed android SDK and plugin on eclipse 4.4, and LogCat shows only the first letter from each message.

an screenshot:

The problem is probably in eclipse as I can see the LogCat well while running 'adb logcat'.

I tried to restart eclipse, adb, and changing LogCat fonts.

答:
1) exit eclipse

2) open up the file

~/workspace/.metadata/.plugins/org.eclipse.core.runtime/.settings/com.android.ide.eclipse.ddms.prefs

3) Input false vlaue for your arbitrarily parameters

ContentLicense: CC BY-SA 4.0


问:
Change text button action of picker
My question is simple but I do not know if it is possible to do

how i change text button (Done)?

My picture of Picker

it is for Xamarin Forms.

答:
I'm not too familiar with Xamarin, but you can use UIAppearance to style some of the UIBarButtonItems you don't have direct access to (such as a picker displayed from an embedded web view). Just do something like so at launch:</p>

```<code>let appearance = UIBarButtonItem.appearance()
appearance.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.red], for: .normal)
</code>```

Title: Change text button action of picker

Body:
I'm not too familiar with Xamarin, but you can use UIAppearance to style some of the UIBarButtonItems you don't have direct access to (such as a picker displayed from an embedded web view). Just do something like so at launch:

let appearance = UIBarButtonItem.appearance()
appearance.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.red], for: .normal)


问:
I think my code is all correct but it does not work
I coded this to show me this:

1  + (1/2!) + (1/3!) + … + (1/n!)

  if ( n < 10 )

```<code>#include <iostream>
using namespace std;
int main() {
int n;
float factn=1,m,sum;
cout<<"enter n\n";
cin>>n;
if(n<10&&n>=0){
do{
        factn=factn*n;
        m=1/factn;
        sum=sum+m;
        n--;
    }while(n>=1);
        cout<<sum;
}
else{
    cout<<"error!\n";
}
return 0;

}
</code>```

This code must show this:

( n < 10 )      1  + (1/2!) + (1/3!) + … + (1/n!)

What is the problem?

It returns wrong values :(

答:
Take time to fix your formatting. Aside from making code pretty and readable, it often got that effect on  focusing your thoughts on the  structure and logic of program. Probably you could  spot the problem with formula implementation in that case.

cin can give you status if entered value is correct. There is more, if you want repeat  input,  i.e. the status should be cleared.
Your formula can be implemented with for() loop, using local variables. It doesn't really matter which type of loop you use, you can use a direct declaration and use  while if you want,  just for()  allows some declarations and statements included into its "header":

```<code>#include <iostream>
using  std::cin;
using  std::cout;
int main()
{
    int n;

    cout << "enter n\n";
    bool res = cin >> n;  // false if input was incorrectly parsed
    if (res)
        res = (n<10) && (n>=0);

    if( res )
    {
        float sum = 1; // starting value for sum
        for( int k = 1, j = 1; k < n; k++)
        {
            j = j * (j + 1);  // j accumulates factorial
            sum = sum + 1.f / j;
        }
        cout<< sum << "\n";
    }
    else
    {
        cout<<"error!\n";
    }
    return 0;
}
</code>```

Actually there is way to calculate factorial without cycle at all, by using exponential functions.

Body:
I coded this to show me this:

1  + (1/2!) + (1/3!) + … + (1/n!)

  if ( n < 10 )

#include <iostream>
using namespace std;
int main() {
int n;
float factn=1,m,sum;
cout<<"enter n\n";
cin>>n;
if(n<10&&n>=0){
do{
        factn=factn*n;
        m=1/factn;
        sum=sum+m;
        n--;
    }while(n>=1);
        cout<<sum;
}
else{
    cout<<"error!\n";
}
return 0;

}

This code must show this:

( n < 10 )      1  + (1/2!) + (1/3!) + … + (1/n!)

What is the problem?

It returns wrong values :(

Body:
Take time to fix your formatting. Aside from making code pretty and readable, it often got that effect on  focusing your thoughts on the  structure and logic of program. Probably you could  spot the problem with formula implementation in that case.

cin can give you status if entered value is correct. There is more, if you want repeat  input,  i.e. the status should be cleared.
Your formula can be implemented with for() loop, using local variables. It doesn't really matter which type of loop you use, you can use a direct declaration and use  while if you want,  just for()  allows some declarations and statements included into its "header":

#include <iostream>
using  std::cin;
using  std::cout;
int main()
{
    int n;

    cout << "enter n\n";
    bool res = cin >> n;  // false if input was incorrectly parsed
    if (res)
        res = (n<10) && (n>=0);

    if( res )
    {
        float sum = 1; // starting value for sum
        for( int k = 1, j = 1; k < n; k++)
        {
            j = j * (j + 1);  // j accumulates factorial
            sum = sum + 1.f / j;
        }
        cout<< sum << "\n";
    }
    else
    {
        cout<<"error!\n";
    }
    return 0;
}

Actually there is way to calculate factorial without cycle at all, by using exponential functions.


问:
NodeJS Mongo - Mongoose - Dynamic collection name
So, I want to create a client side based paritioning schema, where I set the collection name as function(), my pseudo code is something like that:

```<code>var mongoose = require('mongoose'),
  Schema = mongoose.Schema,

var ConvForUserSchema = new Schema({
  user_id: Number,
  conv_hash: String,
  archived: Boolean,
  unread: Boolean
}, function CollectionName() {
  return (this.user_id % 10000);
});
</code>```

Is this in any way possible through moongose such that both read and writes will work as expected?

答:
Gomosoft's solution works. It needs some amends but the idea works nicely.
The above solution works only the first time. If you are trying to send a second request to the same collection, it will throw an error for trying to overwrite the model that is already defined. So I had to tweak it as follows:

```<code>var Rating      = require('./app/models/rating');
var myRating;

router.route('/ratings/:user_id')
.post(function(req,res){

    var user_id         = req.params.user_id;
    if(myRating == undefined){
        myRating        = Rating(user_id);
    }

    ...

    rating.save(...);
});
</code>```

Because I'm checking if myRating is undefined, it will create this reference only once. So no errors will occur.
Hope this helps.

Body:
So, I want to create a client side based paritioning schema, where I set the collection name as function(), my pseudo code is something like that:

var mongoose = require('mongoose'),
  Schema = mongoose.Schema,

var ConvForUserSchema = new Schema({
  user_id: Number,
  conv_hash: String,
  archived: Boolean,
  unread: Boolean
}, function CollectionName() {
  return (this.user_id % 10000);
});

Is this in any way possible through moongose such that both read and writes will work as expected?

Body:
Gomosoft's solution works. It needs some amends but the idea works nicely.
The above solution works only the first time. If you are trying to send a second request to the same collection, it will throw an error for trying to overwrite the model that is already defined. So I had to tweak it as follows:

var Rating      = require('./app/models/rating');
var myRating;

router.route('/ratings/:user_id')
.post(function(req,res){

    var user_id         = req.params.user_id;
    if(myRating == undefined){
        myRating        = Rating(user_id);
    }

    ...

    rating.save(...);
});

Because I'm checking if myRating is undefined, it will create this reference only once. So no errors will occur.
Hope this helps.


问:
imageButton in RecyclerView not displaying
I've been a lurker on your forums for some time now, and they have helped me enormously on a variety of issues I've had, so thanks! :D

I'm trying to create my first app for android and it's a card game named shithead that my friends and I used to play often.

I've decided to use a RecyclerView to display your hand. I need to be able to dynamically add buttons (with card images) to the display at runtime. From what I can tell, I need an adapter for this.

Using the handy guide at "https:// guides.codepath.com/android/using-the-recyclerview" and attempting to modify it for my own purposes I've come very close to a test run of making this work. When I run the program on an emulator in Android Studio, it gives me the following display:
images displayed as grey rectangles

I feel like I've got to be really close, and I'm simply missing some crucial syntax for working with android or android studio.

In my Card object I build a String idText that correlates to the card images I have saved in my project's mipmap-hdpi, mipmap-xhdpi etc. folders (mipmap-hdpi shown below)
mipmap-hdpi folder in Android Studio

```<code>public Card(int suitInput, int rankInput)
{
    suit = suitInput;
    rank = rankInput;
    faceUp = false;
    text = RankString[rank] + " of " + SuitString[suit];
    idText = "i_" + RankString[rank] + "_of_" + SuitString[suit];
}
</code>```

I also have a function getImageId in my Card Class:

```<code>public static int getImageId(Context context) {
    return context.getResources().getIdentifier("drawable/@+id/" + idText, null, context.getPackageName());
}
</code>```

my onBindViewHolder method in my CardAdapter is below:

```<code>@Override
public void onBindViewHolder(CardAdapter.ViewHolder viewHolder, int position)
{
    //get the data model based on position
    Card card = mCards.get(position);

    //Set item views baased on views and data model
    ImageButton imageButton = viewHolder.cardButton;
    imageButton.setImageResource(card.getImageId(mContext));
    TextView textView = viewHolder.cardText;
    textView.setText(card.text);
}
</code>```

my MainActivity class does very little as of yet. It initializes one player, me, and a Deck of Card objects. It then gives me 6 cards off the top of the unshuffled deck, AKA 2 - 7 of diamonds. It then initializes the CardAdapter.

```<code>public class MainActivity extends AppCompatActivity {

Player me;
Deck deck;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.testdisplay);

    //lookup the recyclerview in activity layout
    RecyclerView rvCards = (RecyclerView) findViewById(R.id.rvCards);

    me = new Player("Dr_StrangeKill");
    deck = new Deck();

    me.hand.add(deck.getCards().remove(0));
    me.hand.add(deck.getCards().remove(0));
    me.hand.add(deck.getCards().remove(0));
    me.hand.add(deck.getCards().remove(0));
    me.hand.add(deck.getCards().remove(0));
    me.hand.add(deck.getCards().remove(0));

    //create adapter passing in sample user data
    CardAdapter adapter = new CardAdapter(this, me.hand);
    //Attach the adapter to the recyclerView to populate items
    rvCards.setAdapter(adapter);
    //Set layout manager to position the items
    rvCards.setLayoutManager(new LinearLayoutManager(this));
}
</code>```

The Deck, Player, and Card objects all appear to be working as intended insofar as the values of the code are concerned, as the resultant display correctly shows that 'Dr_StrangeKill' has received 2 - 7 of Diamonds, but doesn't show the card images themselves! This is my first time working with images in any IDE (eclipse, visual studio, android studio), and I feel like i'm very close but off in some small but crucial way. Any help would be greatly appreciated!

答:
I suggest you put your images in a drawable folder because mipmap folder is for launcher icons, if you want to support different screen densities, here's a link that shows you how to create a drawable folder for each screen density, after that you should get your image identifier like this:</p>

```<code>context.getResources().getIdentifier(idText, "drawable", context.getPackageName());
</code>```

Body:
I've been a lurker on your forums for some time now, and they have helped me enormously on a variety of issues I've had, so thanks! :D

I'm trying to create my first app for android and it's a card game named shithead that my friends and I used to play often.

I've decided to use a RecyclerView to display your hand. I need to be able to dynamically add buttons (with card images) to the display at runtime. From what I can tell, I need an adapter for this.

Using the handy guide at "https:// guides.codepath.com/android/using-the-recyclerview" and attempting to modify it for my own purposes I've come very close to a test run of making this work. When I run the program on an emulator in Android Studio, it gives me the following display:
images displayed as grey rectangles

I feel like I've got to be really close, and I'm simply missing some crucial syntax for working with android or android studio.

In my Card object I build a String idText that correlates to the card images I have saved in my project's mipmap-hdpi, mipmap-xhdpi etc. folders (mipmap-hdpi shown below)
mipmap-hdpi folder in Android Studio

public Card(int suitInput, int rankInput)
{
    suit = suitInput;
    rank = rankInput;
    faceUp = false;
    text = RankString[rank] + " of " + SuitString[suit];
    idText = "i_" + RankString[rank] + "_of_" + SuitString[suit];
}

I also have a function getImageId in my Card Class:

public static int getImageId(Context context) {
    return context.getResources().getIdentifier("drawable/@+id/" + idText, null, context.getPackageName());
}

my onBindViewHolder method in my CardAdapter is below:

@Override
public void onBindViewHolder(CardAdapter.ViewHolder viewHolder, int position)
{
    //get the data model based on position
    Card card = mCards.get(position);

    //Set item views baased on views and data model
    ImageButton imageButton = viewHolder.cardButton;
    imageButton.setImageResource(card.getImageId(mContext));
    TextView textView = viewHolder.cardText;
    textView.setText(card.text);
}

my MainActivity class does very little as of yet. It initializes one player, me, and a Deck of Card objects. It then gives me 6 cards off the top of the unshuffled deck, AKA 2 - 7 of diamonds. It then initializes the CardAdapter.

public class MainActivity extends AppCompatActivity {

Player me;
Deck deck;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.testdisplay);

    //lookup the recyclerview in activity layout
    RecyclerView rvCards = (RecyclerView) findViewById(R.id.rvCards);

    me = new Player("Dr_StrangeKill");
    deck = new Deck();

    me.hand.add(deck.getCards().remove(0));
    me.hand.add(deck.getCards().remove(0));
    me.hand.add(deck.getCards().remove(0));
    me.hand.add(deck.getCards().remove(0));
    me.hand.add(deck.getCards().remove(0));
    me.hand.add(deck.getCards().remove(0));

    //create adapter passing in sample user data
    CardAdapter adapter = new CardAdapter(this, me.hand);
    //Attach the adapter to the recyclerView to populate items
    rvCards.setAdapter(adapter);
    //Set layout manager to position the items
    rvCards.setLayoutManager(new LinearLayoutManager(this));
}

The Deck, Player, and Card objects all appear to be working as intended insofar as the values of the code are concerned, as the resultant display correctly shows that 'Dr_StrangeKill' has received 2 - 7 of Diamonds, but doesn't show the card images themselves! This is my first time working with images in any IDE (eclipse, visual studio, android studio), and I feel like i'm very close but off in some small but crucial way. Any help would be greatly appreciated!

Body:
I suggest you put your images in a drawable folder because mipmap folder is for launcher icons, if you want to support different screen densities, here's a link that shows you how to create a drawable folder for each screen density, after that you should get your image identifier like this:

context.getResources().getIdentifier(idText, "drawable", context.getPackageName());


问:
JqGrid with Google Fusion Tables
Trying to get jqGrid to work with Google fusion tables.

Can't seem to find the event in jqGrid that allows you to control where it gets data from.

Would accept an equivalent javascript table engine that does this job better.

If you could link to an example or provide one in your answer, thanks.

Edit: OK here is how far I've gotten

I know how to get jqGrid to request the Google fusion tables but I can't get it to parse the JSON.
I can't seem to find any decent documentation for the jsonreader part of jqGrid that explains what each variable does.

http://cablegate.politicswiki.ie/test.html is where I'm currently at.

答:
It is not event but property.
See example here: http://www.trirand.com/jqgridwiki/doku.php?id=wiki:retrieving_data
You can define data source as JSON, function, xml, etc.</p>

OwnerDisplayName: Stephen Lacy

Title: JqGrid with Google Fusion Tables


问:
How do I remedy "The breakpoint will not currently be hit. No symbols have been loaded for this document." warning?
A C# desktop application (on the Visual Studio Express edition) worked, but then it didn't work 5 seconds later.

I tried the following:

Ensure debug configuration, debug flag, and full debug information are set on all assemblies.

Delete all bin and obj folders and all DLL files related to the project from my entire machine.

Recreate projects causing the problem from scratch.

Reboot.

I have two Windows Forms projects in the solution. One of them loads the debug information, one doesn't. They both refer to the assembly I'm trying to get debug information on in exactly the same way in the project file. Any ideas?

I want to add here, mostly for myself when I come back to review this question, that symbols are not loaded until the assembly is loaded, and the assembly is not loaded until it is needed. If the breakpoint is in a library that is only used in one function in your main assembly, the symbols will not be loaded (and it will show the breakpoint as not being hit) until that function is called.

答:
Using Dependency Injection, Autofac in my case, to automatically resolve by scanning assemblies. One of the referenced assemblies was not getting resolved.

My fix was to directly reference a class from the assembly to force Visual Studio to load the assembly. Just having the assembly as a reference will not load the assembly when the application runs.


问:
Using reflection to create instance when using xmlbeans
I've got a xsd file with over 100 types defined in it. I generated java code with xmlbeans binding, and then I can use

```<code>MyType.Factory.newInstance();
</code>```

to get the class instance. But since there are too many types I've decide to use reflection to get create instances for each type.

I can now get the class(interface) of MyType using

```<code>Class clz = Class.forName("com.foo.MyType");
</code>```

But have no idea of how to get the Factory class defined in the MyType interface and then get the new instance.

Any comment or hint is appreciated. Thanks in advance.

答: you have to use the binary name to refer to inner classes: com.foo.MyType$Factory</p>

Body:
I've got a xsd file with over 100 types defined in it. I generated java code with xmlbeans binding, and then I can use

MyType.Factory.newInstance();

to get the class instance. But since there are too many types I've decide to use reflection to get create instances for each type.

I can now get the class(interface) of MyType using

Class clz = Class.forName("com.foo.MyType");

But have no idea of how to get the Factory class defined in the MyType interface and then get the new instance.

Any comment or hint is appreciated. Thanks in advance.


问:
How do I create a pub package that works with Flutter?
pub is Dart's package manager. Flutter is a mobile app SDK that uses Dart. How can I create a package that depends on, or targets, Flutter?</p>

答:
A trick I also use is to just flutter create foo (which creates a full-fledged Flutter app, more than you need) and then rm -rf foo/ios foo/android and edit/remove foo/lib/main.dart, etc.

The stagehand solution from @sethladd is more elegant, but requires having installed stagehand.


问:
"RCTBundleURLProvider.h" file not found - AppDelegate.m
I am trying to run my React Native app in XCode and I keep getting this error. I cannot figure out how to resolve the issue. Any suggestions?

Screen Shot of Error in XCode:

答: I found that my fix to this issue after upgrading React was to change the declaration of #import "RCTBundleURLProvider.h" to #import <React/RCTBundleURLProvider.h>


问:
jQuery reset star-rating.js
I am using this plugin https://danielupshaw.com/jquery-star-rating/

I want to reset my form. But how can I reset these stars??

```<code> $("#btn-reset").on('click', function() {
  //some other inputs reset
  $('#starrating').star_rating.remove();
  $('#starrating').star_rating.reload();
 }
</code>```

Please help on how to reset these stars to zero or null.

Here is the full code.

```<code> $("#btn-reset").on('click', function() {
   $('#starrating').star_rating.reload();
});
  jQuery(function($) {
    $('#starrating').star_rating({
        click: function(clicked_rating, event) {
            event.preventDefault();
            $('input[name=\'rating\']').val(clicked_rating);
            this.rating(clicked_rating);
        }
    });
});
</code>```

答:
A bit another approach by re-rendering your rating stars from scratch using custom renderRating function.

HTML:

<button class="reset-rating">Reset rating</button>
```

<p><strong>JS:</strong></p>

<pre class="lang-js prettyprint-override"><code>var defaultRating = "0/5";

renderRating("3/5");

function renderRating(rating) {
  var ratingEl = $('<span />').addClass('rating');
  var ratingStr = rating || defaultRating;

  ratingEl.text(ratingStr);
  $('.rating-stars').html(ratingEl);
  ratingEl.star_rating();
}

$('.reset-rating').on('click', function() {
  renderRating();
})
</code>```

Preview on JSFiddle

Title: jQuery reset star-rating.js

Body:
I am using this plugin https://danielupshaw.com/jquery-star-rating/

I want to reset my form. But how can I reset these stars??

 $("#btn-reset").on('click', function() {
  //some other inputs reset
  $('#starrating').star_rating.remove();
  $('#starrating').star_rating.reload();
 }

Please help on how to reset these stars to zero or null.

Here is the full code.

 $("#btn-reset").on('click', function() {
   $('#starrating').star_rating.reload();
});
  jQuery(function($) {
    $('#starrating').star_rating({
        click: function(clicked_rating, event) {
            event.preventDefault();
            $('input[name=\'rating\']').val(clicked_rating);
            this.rating(clicked_rating);
        }
    });
});

Body:
A bit another approach by re-rendering your rating stars from scratch using custom renderRating function.

HTML:

<div class="rating-stars"></div>
<button class="reset-rating">Reset rating</button>

JS:

var defaultRating = "0/5";

renderRating("3/5");

function renderRating(rating) {
  var ratingEl = $('<span />').addClass('rating');
  var ratingStr = rating || defaultRating;

  ratingEl.text(ratingStr);
  $('.rating-stars').html(ratingEl);
  ratingEl.star_rating();
}

$('.reset-rating').on('click', function() {
  renderRating();
})

Preview on JSFiddle


问:
New to C#, can anyone explain to me how enums and setting variables for enums works?
I'm sure this is a very simple question, but I'm learning how to program in C# and the "flow" of this text adventure program makes perfect sense to me, but I'm confused how  the third line "private States myState;" works.

As you can see, the program starts by setting the variable myState to States.cell, which calls a void method (not shown below) that waits for a key that changes the variable "myState" thus updating the update function.

My question is, how does the "enum" class work? It seems as though it's possible to make a variable from the "enum States" line, but I don't understand why that is. Sorry if this is a really stupid question.

Here's the code:

```<code>        public Text text;
private enum States {cell, sheets_0, mirror, lock_0, sheets_1, cell_mirror, lock_1, freedom};
private States myState;

// Use this for initialization
void Start () {
    myState = States.cell;
}

// Update is called once per frame
void Update () {
    print (myState);
        if      (myState == States.cell){           state_cell();}
        else if (myState == States.sheets_0){       state_sheets_0();}
        else if (myState == States.mirror){         state_mirror();}
        else if (myState == States.lock_0){         state_lock_0();}
        else if (myState == States.sheets_1){       state_sheets_1();}
        else if (myState == States.cell_mirror){    state_cell_mirror();}
        else if (myState == States.lock_1){         state_lock_1();}
        else if (myState == States.freedom){        state_freedom();}
}
</code>```

答:
by default enum are int value but can also be casted as other type

```<code>public enum MyEnum : byte
{
    One = 1,
    Two = 2
}
</code>```

If you intend to use the associated value as it's underlying type you'll need to cast it

```<code>var myByte = (byte)MyEnum.Two;
</code>```

As per you example you should use a switch statement instead of multiple if statement it's more readeable:

```<code>var enumValue = MyEnum.One;
switch (enumValue)
{
    case MyEnum.One:
        //Do Something here.
        break;
    case MyEnum.Two:
        //Do something else here.
        break;
    default:
        throw new ArgumentOutOfRangeException();
}
</code>```

Body:
I'm sure this is a very simple question, but I'm learning how to program in C# and the "flow" of this text adventure program makes perfect sense to me, but I'm confused how  the third line "private States myState;" works.

As you can see, the program starts by setting the variable myState to States.cell, which calls a void method (not shown below) that waits for a key that changes the variable "myState" thus updating the update function.

My question is, how does the "enum" class work? It seems as though it's possible to make a variable from the "enum States" line, but I don't understand why that is. Sorry if this is a really stupid question.

Here's the code:

        public Text text;
private enum States {cell, sheets_0, mirror, lock_0, sheets_1, cell_mirror, lock_1, freedom};
private States myState;

// Use this for initialization
void Start () {
    myState = States.cell;
}

// Update is called once per frame
void Update () {
    print (myState);
        if      (myState == States.cell){           state_cell();}
        else if (myState == States.sheets_0){       state_sheets_0();}
        else if (myState == States.mirror){         state_mirror();}
        else if (myState == States.lock_0){         state_lock_0();}
        else if (myState == States.sheets_1){       state_sheets_1();}
        else if (myState == States.cell_mirror){    state_cell_mirror();}
        else if (myState == States.lock_1){         state_lock_1();}
        else if (myState == States.freedom){        state_freedom();}
}

Body:
by default enum are int value but can also be casted as other type

public enum MyEnum : byte
{
    One = 1,
    Two = 2
}

If you intend to use the associated value as it's underlying type you'll need to cast it

var myByte = (byte)MyEnum.Two;

As per you example you should use a switch statement instead of multiple if statement it's more readeable:

var enumValue = MyEnum.One;
switch (enumValue)
{
    case MyEnum.One:
        //Do Something here.
        break;
    case MyEnum.Two:
        //Do something else here.
        break;
    default:
        throw new ArgumentOutOfRangeException();
}


问:
How to show my answer after few wrong attempt in HTML JavaScripts

Please help me to add a "Button" called "See your answer".

This "See your answer" button appear only after when user clicks "Check your answer" button 3 times, and 3 answers are wrong.

After click "See your answer" button, correct answer appear.

the correct answer is "100".

Thank you!!!

<title> </title>

How much is your profit?

<input id="id1" name = "id1" required>
  <button  type = "button" onclick="myFunction()">Check Your Answer</button>

```

答:
Basically what you need is a little application state. You'll need a variable in your JavaScript along the lines of numberOfSubmissions. On your click handler for Check Your Answer increment numberOfIncorrectSubmissions if the answer is incorrect. After you increment, check if the value is 3 or higher. If it is, then show your See the Answer button.

Let me know if any of that is unclear or if you have trouble implementing.


问:
How to add crypto to a nodejs build?
"It is possible for Node.js to be built without including support for the crypto module."

How can I add crypto to Node.js or choose how to build with ?

I know there is a npm package with the name "crypto" but there are packages who needs the crypto built-in.

答: Alternative of crypto is bcrypt and grunt-openssl </p>

Title: How to add crypto to a nodejs build?


答:
This is the idea. Try this out. Change the variable names and what not.

You need a global variable that will store the number of "attempts" in this case Y.

Every time you fail, Y is increased by 1.

There is an additional if statement on the function that if the fail equals to the about of "attempts", it will do something. You can make it do anything you want including resetting the attempt counter.

Cheers!

```<code><head>
<title> </title>
</head>

<body>

<p>How much is your profit?

<input id="id1" name = "id1" required>
  <button  type = "button" onclick="myFunction()">Check Your Answer</button> </p>

<p id="Q1"></p>
<p id="Q2"></p>

<script>

    var y=0;
function myFunction() {
    var x, text, text2;

    x = document.getElementById("id1").value;

    if (isNaN(x) || x != 100) {
      text = "Incorrect";
      document.getElementById("Q1").style.color = "red";
      y=y+1;
    }
    else {
        text = "Correct";
        document.getElementById("Q1").style.color = "green";
    }

    if (y==3){
      text2 = "DONE";
      document.getElementById("Q2").style.color = "orange";
    }

    document.getElementById("Q1").innerHTML = text;
    document.getElementById("Q2").innerHTML = y;
}
</script>

</body>
</html>
</code>```

Title: How to show my answer after few wrong attempt in HTML JavaScripts

Body:
Please help me to add a "Button" called "See your answer".

This "See your answer" button appear only after when user clicks "Check your answer" button 3 times, and 3 answers are wrong.

After click "See your answer" button, correct answer appear.

the correct answer is "100".

Thank you!!!

<title> </title>

How much is your profit?

<input id="id1" name = "id1" required>
  <button  type = "button" onclick="myFunction()">Check Your Answer</button>

Body:
This is the idea. Try this out. Change the variable names and what not.

You need a global variable that will store the number of "attempts" in this case Y.

Every time you fail, Y is increased by 1.

There is an additional if statement on the function that if the fail equals to the about of "attempts", it will do something. You can make it do anything you want including resetting the attempt counter.

Cheers!

<head>
<title> </title>
</head>

<body>

<p>How much is your profit?

<input id="id1" name = "id1" required>
  <button  type = "button" onclick="myFunction()">Check Your Answer</button> </p>

<p id="Q1"></p>
<p id="Q2"></p>

<script>

    var y=0;
function myFunction() {
    var x, text, text2;

    x = document.getElementById("id1").value;

    if (isNaN(x) || x != 100) {
      text = "Incorrect";
      document.getElementById("Q1").style.color = "red";
      y=y+1;
    }
    else {
        text = "Correct";
        document.getElementById("Q1").style.color = "green";
    }

    if (y==3){
      text2 = "DONE";
      document.getElementById("Q2").style.color = "orange";
    }

    document.getElementById("Q1").innerHTML = text;
    document.getElementById("Q2").innerHTML = y;
}
</script>

</body>
</html>


问:
AH01215: ImportError: No module named PIL: - python script unable to recognize PIL when running from apache2 config
What did you do?

I have configured in apache httpd.conf - enabling of mod_cgi.so and httpd-vhosts.conf.

In httpd-vhosts have following conifguration. Basically am trying to capture all /images/ pattern, read have that process using a index.py script and return back as image/jpeg content.

```<code><VirtualHost *:80>
ServerAdmin abc.xyz@gmail.com
ServerName www.groc-example.com
ServerAlias groc-example.com
Alias "/images/" "/var/www/images/"
DirectoryIndex index.py
ErrorLog "/private/var/log/apache2/groc-example-images-error_log"
CustomLog "/private/var/log/apache2/groc-access-log" common
<Directory "/var/www/images/">
Options +ExecCGI
Allow from all
Require all granted
ForceType text/html
AddHandler cgi-script .py
</code>```

In the index.py am just trying to start the script by trying to import the image. It doenst work i.e. recognize at all. The same import of PIL works from python2/python3 interface in spyder or pycharm or commandlines.

If I remove PIL import statement, the html works or prints out to browser.

```<code>#! /usr/bin/env python
from PIL import Image

print ""
print "hello world"
print "--"
print ""
</code>```

What did you expect to happen?

python script to recognize PIL but it doesnt recognize. I have uninstalled PIL-SIMD multiple times and reinstalled but it isnt working.
Though I have both python2 and python3, default am using python2 and so is apache CGI interface.

What actually happened?

I capture following error in apache logs.

```<code>AH01215: from PIL import Image: /var/www/images/index.py
AH01215: ImportError: No module named PIL: /var/www/images/index.py
</code>```

What versions of Pillow and Python are you using?

Python 2.7.12
Pillow-SIMD
Pillow-SIMD (4.0.0.post0)

Please help if this wont resolve, I have to completely move away from python.

答:
All - i have tried the links provided by Dan-Dev & others as well. James, am using this only to resize image and send back and intercept calls for only images. All other requests will go to other Appservers through Apache2.

I just printed a sys.path to get following. I am unable to get anything on PYTHONPATH. Note that even here if i comment out and just output the image from os namespace, it works. Issue happens when i try pillow. I uninstalled /reinstalled both python & pillow-simd but still this issue persist.

I also have tried #!/usr/bin/python option as well which doesnt work. I am on mac 10.5.*

['/private/var/www/images', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload', '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC', '/Library/Python/2.7/site-packages']

Body:
What did you do?

I have configured in apache httpd.conf - enabling of mod_cgi.so and httpd-vhosts.conf.

In httpd-vhosts have following conifguration. Basically am trying to capture all /images/ pattern, read have that process using a index.py script and return back as image/jpeg content.

<VirtualHost *:80>
ServerAdmin abc.xyz@gmail.com
ServerName www.groc-example.com
ServerAlias groc-example.com
Alias "/images/" "/var/www/images/"
DirectoryIndex index.py
ErrorLog "/private/var/log/apache2/groc-example-images-error_log"
CustomLog "/private/var/log/apache2/groc-access-log" common
<Directory "/var/www/images/">
Options +ExecCGI
Allow from all
Require all granted
ForceType text/html
AddHandler cgi-script .py

In the index.py am just trying to start the script by trying to import the image. It doenst work i.e. recognize at all. The same import of PIL works from python2/python3 interface in spyder or pycharm or commandlines.

If I remove PIL import statement, the html works or prints out to browser.

#! /usr/bin/env python
from PIL import Image

print ""
print "hello world"
print "--"
print ""

What did you expect to happen?

python script to recognize PIL but it doesnt recognize. I have uninstalled PIL-SIMD multiple times and reinstalled but it isnt working.
Though I have both python2 and python3, default am using python2 and so is apache CGI interface.

What actually happened?

I capture following error in apache logs.

AH01215: from PIL import Image: /var/www/images/index.py
AH01215: ImportError: No module named PIL: /var/www/images/index.py

What versions of Pillow and Python are you using?

Python 2.7.12
Pillow-SIMD
Pillow-SIMD (4.0.0.post0)

Please help if this wont resolve, I have to completely move away from python.


问:
Reading from a data sheet using Java or C#
I would consider myself an amateur programmer.  I've taken Java classes and i'm in the process of self-teaching myself C#.

When it comes to Reading Data (say for example an Excel file)  I've noticed a trend, It always begins with Open...ImportData/ManipulateData/ExportData....Export

My question:

Is there some other way to read data other than the "OpenStream" "CloseStream" that I know of already?

I know that there are a ton of different languages out there, but maybe a built in function that I don't know of already for Java or C#?

答:
I/O operations are essentially streaming operations. Your main logic stored and executed inside the memory. After that you can dump the result, temporary calculations or the application state down to the disk. The traditional way to achive this is using streams (filestream, networkstream...) because the data is layed down one after another. Usually these streams are not random access streams, thats why there is easy to work with them.

In C# if you dont want to open or close disposable objects manually you can use the using statement.


问:
Symfony rendering templates from ajax
I have the following ajax I call:

```<code>$('.checkbox').click(function () {
            $.ajax({
                type:'POST',
                url: '/loadProducts',
                data: {},
                success: function(response) {
                    $('.js-products').html(response);
                }});
            return false;
        });
</code>```

Now when I call my endpoint loadProducts, I wants to get products, render a product template(s) and return all of them.

In my endpoint I could do this:

```<code>/**
 * @Route("/loadProducts", name="loadProducts")
 */
public function loadProducts() {
    /* @var \AppBundle\Service\ProductService $productService */
    $productService = $this->get('app.product');

    $products = $productService->getProducts();

    $productItems = [];
    foreach ($products as $product) {
        $productItems = $this->render('home/productItem.html.twig', [
            'product' => $product
        ]);
    }

    $response = new Response();
    $response->headers->set('Content-Type', 'application/json');
    $response->setContent(json_encode($productItems));
    return $response;
}
</code>```

But that only renders one product. How could I return rendering multiple product.html.twig files? (apart from creating a new template that renders all)

答:
You will get something like this. Your action will start to render products.html.twig which have a loop that renders multiple times product.html.twig

products.html.twig

```<code>{% extends base_template %}

{% block body %}
<div class="container">
    <div class="row">
        {% for product in products %}
            <div class="col-md-3">
                {% include 'shop/product.html.twig' %}
            </div>
        {% endfor %}
    </div>
</div>
{% endblock %}
</code>```

product.html.twig

```<code><div class="product">
    <img src="somesource.jpg">
    <div class="description">
        <h3>{{ product.name }}</h3>
        <p>{{ product.description }}</p>
    </div>
</div>
</code>```

Title: Symfony rendering templates from ajax

Body:
I have the following ajax I call:

$('.checkbox').click(function () {
            $.ajax({
                type:'POST',
                url: '/loadProducts',
                data: {},
                success: function(response) {
                    $('.js-products').html(response);
                }});
            return false;
        });

Now when I call my endpoint loadProducts, I wants to get products, render a product template(s) and return all of them.

In my endpoint I could do this:

/**
 * @Route("/loadProducts", name="loadProducts")
 */
public function loadProducts() {
    /* @var \AppBundle\Service\ProductService $productService */
    $productService = $this->get('app.product');

    $products = $productService->getProducts();

    $productItems = [];
    foreach ($products as $product) {
        $productItems = $this->render('home/productItem.html.twig', [
            'product' => $product
        ]);
    }

    $response = new Response();
    $response->headers->set('Content-Type', 'application/json');
    $response->setContent(json_encode($productItems));
    return $response;
}

But that only renders one product. How could I return rendering multiple product.html.twig files? (apart from creating a new template that renders all)

Body:
You will get something like this. Your action will start to render products.html.twig which have a loop that renders multiple times product.html.twig

products.html.twig

{% extends base_template %}

{% block body %}
<div class="container">
    <div class="row">
        {% for product in products %}
            <div class="col-md-3">
                {% include 'shop/product.html.twig' %}
            </div>
        {% endfor %}
    </div>
</div>
{% endblock %}

product.html.twig

<div class="product">
    <img src="somesource.jpg">
    <div class="description">
        <h3>{{ product.name }}</h3>
        <p>{{ product.description }}</p>
    </div>
</div>


问:
iOS: deliver NSLocalNotification or Push Notification only when user is idle
I want to send a notification to the user of my iOS application, preferably using NSLocalNotificaiton.

However, if the user is on a call I don't want them to recieve the notification until after the call (I don't want to interrupt their call). Is there any way to schedule the notification to occur after the call has ended?

答: A notification will no more interrupt a call than a calendar or SMS alert does—the alert view will appear on their screen, and if the ringer isn't silenced then the alert sound will play, but the user won't get disconnected or anything in the process. The only way you have of detecting that the user may have finished a call is the -applicationDidBecomeActive: method on your app delegate, but if your app's going to be in the foreground (which is the only point at which it'll receive that message) then you don't need to bother with a UILocalNotification. In short: no, you can't schedule things around the user's phone activity, but nor should you worry about your notifications interrupting them mid-call.


问:
Docker vs. Rocket in development
Why should I consider using Rocket instead of Docker in our development pipeline. We would like to use docker to create testable containers, but now there is Rocket which pretends to know the same. If we would like to start containerization should we seriously consider Rocket as it seems it is still pretty new?

There is not much information about Rocket, so I'm no clear where it stays now in 2015.

UPDATE: from https://coreos.com/blog/app-container-and-the-open-container-project/

As we participate in OCP, our primary goals are as follows:

Users should be able to package their application once and have it work with any container runtime (like Docker, rkt, Kurma, or Jetpack)

The standard should fulfill the requirements of the most rigorous security and production environments

The standard should be vendor neutral and developed in the open

答:
As with most competitors both have their advantage and disandvantages.

Docker hub offers a public registry where docker images can be pushed and pulled with ease.

There is also now a free registry offered by GitLab! Its really good.

A core issue at the moment is security. Docker now scan their images for security flaws and report on the security status of each image.

With rocket image signatures are cross checked with the signature of the publisher to see if they have been tampered with. This affords a degree of confidence.

For a fuller discussion on security see https://bobcares.com/blog/docker-vs-rkt-rocket/

With regards standards, it seems that OCI (Open Container Initiative) has been adopted by the big players and will pave the way forward for containerisation standatisation.

Title: Docker vs. Rocket in development


问:
How to use stackdriver client from GAE standard environment?
Execution of this this line:

```<code>logging = LoggingOptions.getDefaultInstance().getService()
</code>```

On Google App Engine standard environment instance results with:

```<code>com.google.api.server.spi.SystemService invokeServiceMethod: exception occurred while calling backend method (SystemService.java:398)
java.lang.NoClassDefFoundError: java.nio.channels.spi.SelectorProvider is a restricted class. Please see the Google App Engine developer's guide for more details.
    at java.nio.channels.spi.SelectorProvider.<clinit>(SelectorProvider.java)
    at io.netty.channel.nio.NioEventLoopGroup.<init>(NioEventLoopGroup.java:59)
    at io.grpc.netty.Utils$DefaultEventLoopGroupResource.create(Utils.java:187)
    at io.grpc.netty.Utils$DefaultEventLoopGroupResource.create(Utils.java:171)
    at io.grpc.internal.SharedResourceHolder.getInternal(SharedResourceHolder.java:121)
    at io.grpc.internal.SharedResourceHolder.get(SharedResourceHolder.java:91)
    at io.grpc.netty.NettyChannelBuilder$NettyTransportFactory.<init>(NettyChannelBuilder.java:311)
    at io.grpc.netty.NettyChannelBuilder$NettyTransportFactory.<init>(NettyChannelBuilder.java:280)
    at io.grpc.netty.NettyChannelBuilder.buildTransportFactory(NettyChannelBuilder.java:230)
    at io.grpc.internal.AbstractManagedChannelImplBuilder.build(AbstractManagedChannelImplBuilder.java:239)
    at com.google.api.gax.grpc.InstantiatingChannelProvider.createChannel(InstantiatingChannelProvider.java:123)
    at com.google.api.gax.grpc.InstantiatingChannelProvider.getChannel(InstantiatingChannelProvider.java:110)
    at com.google.api.gax.grpc.ProviderManager.getChannel(ProviderManager.java:105)
    at com.google.api.gax.grpc.ChannelAndExecutor.create(ChannelAndExecutor.java:67)
    at com.google.api.gax.grpc.ClientSettings.getChannelAndExecutor(ClientSettings.java:81)
    at com.google.cloud.logging.spi.v2.ConfigServiceV2Client.<init>(ConfigServiceV2Client.java:131)
    at com.google.cloud.logging.spi.v2.ConfigServiceV2Client.create(ConfigServiceV2Client.java:122)
    at com.google.cloud.logging.spi.DefaultLoggingRpc.<init>(DefaultLoggingRpc.java:141)
    at com.google.cloud.logging.LoggingOptions$DefaultLoggingRpcFactory.create(LoggingOptions.java:68)
    at com.google.cloud.logging.LoggingOptions$DefaultLoggingRpcFactory.create(LoggingOptions.java:62)
    at com.google.cloud.ServiceOptions.getRpc(ServiceOptions.java:503)
    at com.google.cloud.logging.LoggingImpl.<init>(LoggingImpl.java:96)
    at com.google.cloud.logging.LoggingOptions$DefaultLoggingFactory.create(LoggingOptions.java:43)
    at com.google.cloud.logging.LoggingOptions$DefaultLoggingFactory.create(LoggingOptions.java:38)
    at com.google.cloud.ServiceOptions.getService(ServiceOptions.java:490)
</code>```

Is there any way to get it to work?

答:
You will have to use the v2 api of google-api-services. Explanation:

Google provides two sets of supported libraries for interfacing with their cloud services.

Google API Client Libraries[1] (google-api-services): older libraries that provide a programmatic overlay on top of each API's REST interface

Google Cloud Libraries[2] (google-cloud): alpha/beta libraries that are based on gRPC. They are allegedly much more performant, but are NOT supported in Standard Appengine (found this little note in their github page.. [3]) because of network security limitations on gRPC.

Each set of libraries now has a v1 and v2 set of apis for both sets of libraries (v1 is discontinued).

google-api-services v2 documentation[4]

google-cloud v2 documentation[5]

Sources:

Main docs page: https://cloud.google.com/apis/docs/client-libraries-explained

[1]: https://developers.google.com/api-client-library/

[2]: http://googlecloudplatform.github.io/google-cloud-java/0.10.0/index.html

[3]: https://github.com/GoogleCloudPlatform/google-cloud-java

[4]: http://googlecloudplatform.github.io/google-cloud-java/0.10.0/apidocs/index.html

[5]: https://developers.google.com/resources/api-libraries/documentation/logging/v2beta1/java/latest/com/google/api/services/logging/v2beta1/package-summary.html

Body:
Execution of this this line:

logging = LoggingOptions.getDefaultInstance().getService()

On Google App Engine standard environment instance results with:

com.google.api.server.spi.SystemService invokeServiceMethod: exception occurred while calling backend method (SystemService.java:398)
java.lang.NoClassDefFoundError: java.nio.channels.spi.SelectorProvider is a restricted class. Please see the Google App Engine developer's guide for more details.
    at java.nio.channels.spi.SelectorProvider.<clinit>(SelectorProvider.java)
    at io.netty.channel.nio.NioEventLoopGroup.<init>(NioEventLoopGroup.java:59)
    at io.grpc.netty.Utils$DefaultEventLoopGroupResource.create(Utils.java:187)
    at io.grpc.netty.Utils$DefaultEventLoopGroupResource.create(Utils.java:171)
    at io.grpc.internal.SharedResourceHolder.getInternal(SharedResourceHolder.java:121)
    at io.grpc.internal.SharedResourceHolder.get(SharedResourceHolder.java:91)
    at io.grpc.netty.NettyChannelBuilder$NettyTransportFactory.<init>(NettyChannelBuilder.java:311)
    at io.grpc.netty.NettyChannelBuilder$NettyTransportFactory.<init>(NettyChannelBuilder.java:280)
    at io.grpc.netty.NettyChannelBuilder.buildTransportFactory(NettyChannelBuilder.java:230)
    at io.grpc.internal.AbstractManagedChannelImplBuilder.build(AbstractManagedChannelImplBuilder.java:239)
    at com.google.api.gax.grpc.InstantiatingChannelProvider.createChannel(InstantiatingChannelProvider.java:123)
    at com.google.api.gax.grpc.InstantiatingChannelProvider.getChannel(InstantiatingChannelProvider.java:110)
    at com.google.api.gax.grpc.ProviderManager.getChannel(ProviderManager.java:105)
    at com.google.api.gax.grpc.ChannelAndExecutor.create(ChannelAndExecutor.java:67)
    at com.google.api.gax.grpc.ClientSettings.getChannelAndExecutor(ClientSettings.java:81)
    at com.google.cloud.logging.spi.v2.ConfigServiceV2Client.<init>(ConfigServiceV2Client.java:131)
    at com.google.cloud.logging.spi.v2.ConfigServiceV2Client.create(ConfigServiceV2Client.java:122)
    at com.google.cloud.logging.spi.DefaultLoggingRpc.<init>(DefaultLoggingRpc.java:141)
    at com.google.cloud.logging.LoggingOptions$DefaultLoggingRpcFactory.create(LoggingOptions.java:68)
    at com.google.cloud.logging.LoggingOptions$DefaultLoggingRpcFactory.create(LoggingOptions.java:62)
    at com.google.cloud.ServiceOptions.getRpc(ServiceOptions.java:503)
    at com.google.cloud.logging.LoggingImpl.<init>(LoggingImpl.java:96)
    at com.google.cloud.logging.LoggingOptions$DefaultLoggingFactory.create(LoggingOptions.java:43)
    at com.google.cloud.logging.LoggingOptions$DefaultLoggingFactory.create(LoggingOptions.java:38)
    at com.google.cloud.ServiceOptions.getService(ServiceOptions.java:490)

Is there any way to get it to work?


问:
Body vertical swipe to scroll with hammerjs
I would like to mimic touch device scroll behaviour with hammerjs
I can listen to swipe events and stuff and make calculations to animate to position based on velocity but it wont be like it work on touch device exactly.

Maybe someone already did that and know where I can find it or how I can do it as close as possible to the origin?

I would appreciate your help

答:
Maybe it will help you, that Hammer.Pan(i am sure of) and Hammer.Swipe(i did not investigate) are set to Horizontal only! To enable vertical panning and i guess swiping as well is to set All directions explicitly.

I am referring to latest version 2.0.8 (which was actually never updated on github. Still looks like 2.0.7 code) :(

mc.get('pan').set({ direction: Hammer.DIRECTION_ALL });
```


问:
How to use iOS 10.3 devices with Xcode 8.2.1
This iPad mini 2 (Model A1490) is running iOS 10.3 (14E277), which may not be supported by this version of Xcode.

my xcode version 8.2.1
my Device ios version 10.2

答: Just solved it. Get new Xcode here: https://itunes.apple.com/us/app/xcode/id497799835?ls=1&mt=12</p>


问:
Update a column with different data based on the Primary key
I would like to update a table but the problem I have is the following: I have a table with more than 60K primary keys in a column called TerminalID. This table has like 10 more columns, but I would like to update a column called SerialNumber, but the problem is that the serial number is not the same for every primary key.

The problem is that the update SQL code below will apply the same serial number to all the terminalID's I have and not a different to each PK.

Any idea?

```<code>Use [testserver]

update [testtable]
set SerialNumber =''
from [testtable]
where [TerminalID] in ( ... )

terminalID    Serial Number
463328        215728108
168734        213808561
160879        214621937
451991       215523741
</code>```

This is the only way I can think now , do it one by one

```<code>Update [terminalsetting] SET [SerialNumber] ='766' WHERE [TerminalID] ='63872'
Update [terminalsetting] SET [SerialNumber] ='215728108' WHERE [TerminalID] ='463328'
Update [terminalsetting] SET [SerialNumber] ='213808561' WHERE [TerminalID] ='168734'
</code>```

答:
I would say use rownumber column and CTE. This will give you a unique number for each row.
Then using this number and update your table.

Read this
https://learn.microsoft.com/en-us/sql/t-sql/functions/row-number-transact-sql

Body:
I would like to update a table but the problem I have is the following: I have a table with more than 60K primary keys in a column called TerminalID. This table has like 10 more columns, but I would like to update a column called SerialNumber, but the problem is that the serial number is not the same for every primary key.

The problem is that the update SQL code below will apply the same serial number to all the terminalID's I have and not a different to each PK.

Any idea?

Use [testserver]

update [testtable]
set SerialNumber =''
from [testtable]
where [TerminalID] in ( ... )

terminalID    Serial Number
463328        215728108
168734        213808561
160879        214621937
451991       215523741

This is the only way I can think now , do it one by one

Update [terminalsetting] SET [SerialNumber] ='766' WHERE [TerminalID] ='63872'
Update [terminalsetting] SET [SerialNumber] ='215728108' WHERE [TerminalID] ='463328'
Update [terminalsetting] SET [SerialNumber] ='213808561' WHERE [TerminalID] ='168734'


问:
Exception handling in java for checked and unchecked exception
If we want to make a checked exception, we can extend the Exception class, and for unchecked exceptions we can extend the RuntimeException class.

But the Exception class is a super for RuntimeException, so why can't I make a runtime exception class using the Exception class?

Extending Exception/RunTimeException in java?

答: That is just a feature of the language. Keep in mind that there are other Throwable classes, most notably Error and its children, none of which you are required to check for. Exception and RuntimeException are just markers in the inheritance tree that the compiler uses to check if a Throwable needs to be checked or not, pretty much because the authors of the language decided that those would be the names of those markers.


问:
When does int++ get incremented?
I've got a line of code,

```<code>list[index++] = recursiveFunction();
</code>```

Does index get incremented before or after the call to recursiveFunction?

答:
Under Visual Studio 2008/.NET Framework 3.5 on Windows, index is incremented before recursiveFunction is called.  This sample app prints "index = 1" to the console.

```<code>class Program
{
    private int index = 0;

    private static void Main()
    {
        new Program().TryMe();
    }

    private void TryMe()
    {
        var list = new List<int>();
        list.Add(1);
        list.Add(2);

        list[index++] = ReturnZero();
    }

    private int ReturnZero()
    {
        Console.WriteLine(string.Format("index = {0}", index));
        return 0;
    }
}
</code>```

Title: When does int++ get incremented?

Body:
I've got a line of code,

list[index++] = recursiveFunction();

Does index get incremented before or after the call to recursiveFunction?

Body:
Under Visual Studio 2008/.NET Framework 3.5 on Windows, index is incremented before recursiveFunction is called.  This sample app prints "index = 1" to the console.

class Program
{
    private int index = 0;

    private static void Main()
    {
        new Program().TryMe();
    }

    private void TryMe()
    {
        var list = new List<int>();
        list.Add(1);
        list.Add(2);

        list[index++] = ReturnZero();
    }

    private int ReturnZero()
    {
        Console.WriteLine(string.Format("index = {0}", index));
        return 0;
    }
}


问:
.NET Core and Classic ASP in the same solution?
My company is exploring using the new .NET Core for a small internal project, however, there are a couple of very complex (and old) classic ASP pages we don't want to have to rewrite at the moment.

Is it possible within a .NET Core solution to run some classic ASP pages? So far we've not managed, but perhaps there is some Program.cs or appsettings.json configuration we are missing.

答:
Side by side? Yes. Same solution? No. There are significant differences between ASP.NET and ASP.NET Core, and the difference is even more extreme when comparing classic ASP.

ASP.NET Core is designed to run outside of IIS, and .NET Core is designed to run outside of Windows. Classic ASP is incompatible with both of these things at an architectural level.


问:
What is the correct sql for Update a row in a table?
I am able to Insert data into MySQL using C# fine. However, it doesn't like my Update sql below. key is an autoincrement Primary Key.

This is the code i am using. What is the correct Update sql and the corresponding C# statement to execute it?

```<code>public int UpdatetData(int key, System.DateTime ts, string user)
    {
                string sql = @"update parameters (DateTime, User)
                              values (@timestamp, @user) where Key = @key";

                try
                {
                    using (MySqlCommand cmd = new MySqlCommand(sql, connection))
                    {
                        cmd.Parameters.AddWithValue("@key", key);
                        cmd.Parameters.AddWithValue("@timestamp", ts);
                        cmd.Parameters.AddWithValue("@user", user);
                        ...
                        return cmd.ExecuteNonQuery();
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                    return -1;
                }
        }
</code>```

答:
The correct syntax for an UPDATE statement is this:

Update  `Parameters`
Set     `DateTime` = @TimeStamp,
        `User` = @User
Where   `Key` = @Key
```

<p>The only change you need to make to the C# is your <code>sql</code> variable declaration:</p>

<pre class="lang-cs prettyprint-override"><code>string sql =
@"
    Update  `Parameters`
    Set     `DateTime` = @TimeStamp,
            `User` = @User
    Where   `Key` = @Key
";
</code>```

Body:
I am able to Insert data into MySQL using C# fine. However, it doesn't like my Update sql below. key is an autoincrement Primary Key.

This is the code i am using. What is the correct Update sql and the corresponding C# statement to execute it?

public int UpdatetData(int key, System.DateTime ts, string user)
    {
                string sql = @"update parameters (DateTime, User)
                              values (@timestamp, @user) where Key = @key";

                try
                {
                    using (MySqlCommand cmd = new MySqlCommand(sql, connection))
                    {
                        cmd.Parameters.AddWithValue("@key", key);
                        cmd.Parameters.AddWithValue("@timestamp", ts);
                        cmd.Parameters.AddWithValue("@user", user);
                        ...
                        return cmd.ExecuteNonQuery();
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                    return -1;
                }
        }

Body:
The correct syntax for an UPDATE statement is this:

Update  `Parameters`
Set     `DateTime` = @TimeStamp,
        `User` = @User
Where   `Key` = @Key

The only change you need to make to the C# is your sql variable declaration:

string sql =
@"
    Update  `Parameters`
    Set     `DateTime` = @TimeStamp,
            `User` = @User
    Where   `Key` = @Key
";


问:
Button's Text Cycle Through String-Array
I have a button that when clicked, the text inside changes. I'm trying to accomplish this with an array in my strings.xml, thinking that the onClick will do a for loop through the string-array

```<code><string-array name="RG_answers">
     <item>text 1</item><!--Of course this is example text-->
     <item>text 2</item>
     <item>text 3</item>
</string-array>
</code>```

I don't know if I'm just not Googling correctly, or what. Inside my onCreate() my button is basic

```<code> mTrueButton = (Button) findViewById(R.id.true_button);
        mTrueButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
</code>```

So basic that it's only helpful (if that) by providing the names I called it. Is it possible/feasible? From what I've found I haven't seen anyone ask a question like this.

答:
You need three steps:</p>

```<code>//1 Declare an index outside onClick:
int currentIndex=0;

//2- Read the answers:
Resources res = getResources();
myStrings = res.getStringArray(R.array.RG_answers);

//3- iterate thru them inside onClick:
mTrueButton.setText(myStrings[(currentIndex++)%(myStrings.length)]);
</code>```

Body:
I have a button that when clicked, the text inside changes. I'm trying to accomplish this with an array in my strings.xml, thinking that the onClick will do a for loop through the string-array

<string-array name="RG_answers">
     <item>text 1</item>
     <item>text 2</item>
     <item>text 3</item>
</string-array>

I don't know if I'm just not Googling correctly, or what. Inside my onCreate() my button is basic

 mTrueButton = (Button) findViewById(R.id.true_button);
        mTrueButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

So basic that it's only helpful (if that) by providing the names I called it. Is it possible/feasible? From what I've found I haven't seen anyone ask a question like this.

Body:
You need three steps:

//1 Declare an index outside onClick:
int currentIndex=0;

//2- Read the answers:
Resources res = getResources();
myStrings = res.getStringArray(R.array.RG_answers);

//3- iterate thru them inside onClick:
mTrueButton.setText(myStrings[(currentIndex++)%(myStrings.length)]);


问:
Linq group by and get count of occurence
I need to get topic name and number of times (count) a given topic occurs.

Example:

```<code>Name: John
Topic: X, Y, Z => these are List<string>

Name: Bob
Topic: Y

Name: Suzy
Topic: Y, Z

Should generate output:
X: 1
Y: 3
Z: 2
</code>```

I've tried this but it doesn't return correct result:

```<code>var result = from r in items
                         orderby r.Topic
                         group r by r.Topic
                into grp
                         select new { key = grp.Key, cnt = grp.Count() };
</code>```

答:
I like to do this using SelectMany( to flatten the inner collection)
Just another way to do this</p>

```<code>var result = items.SelectMany((w) => w.Topic)
                    .GroupBy((q) => q)
                    .Select((p) => new { Grp = p.Key, Cnt = p.Count() })
                    .OrderBy((g) => g.Cnt);
</code>```

Body:
I need to get topic name and number of times (count) a given topic occurs.

Example:

Name: John
Topic: X, Y, Z => these are List<string>

Name: Bob
Topic: Y

Name: Suzy
Topic: Y, Z

Should generate output:
X: 1
Y: 3
Z: 2

I've tried this but it doesn't return correct result:

var result = from r in items
                         orderby r.Topic
                         group r by r.Topic
                into grp
                         select new { key = grp.Key, cnt = grp.Count() };

Body:
I like to do this using SelectMany( to flatten the inner collection)
Just another way to do this

var result = items.SelectMany((w) => w.Topic)
                    .GroupBy((q) => q)
                    .Select((p) => new { Grp = p.Key, Cnt = p.Count() })
                    .OrderBy((g) => g.Cnt);


问:
How to show my answer after few wrong attempt in HTML JavaScripts

Please help me to add a "Button" called "See your answer".

This "See your answer" button appear only after when user clicks "Check your answer" button 3 times, and 3 answers are wrong.

After click "See your answer" button, correct answer appear.

the correct answer is "100".

Thank you!!!

<title> </title>

How much is your profit?

<input id="id1" name = "id1" required>
  <button  type = "button" onclick="myFunction()">Check Your Answer</button>

```

答:
You can add a global variable that tracks the number of incorrect answers. I can't recite all of the reasons global variables are frowned upon, but basically they clutter the global namespace and could lead to conflicts, things like that. I hope this helps though.</p>

```<code><html>

<head>
<title> </title>
</head>

<body>

<p>How much is your profit?

<input id="id1" name = "id1" required>
  <button  type = "button" onclick="myFunction()">Check Your Answer</button> </p>

<p id="Q1"></p>

<script>
var failedAttempts = 0;
function myFunction() {
    var x, text;
    x = document.getElementById("id1").value;

    if (failedAttempts === 3){
         // Show the answer
    }else if(isNaN(x) || x != 100) {
        text = "Incorrect"; document.getElementById("Q1").style.color = "red";
        failedAttempts++;
    } else {
        text = "Correct"; document.getElementById("Q1").style.color = "green";
    }
    document.getElementById("Q1").innerHTML = text;
}
</script>

</body>
</html>
</code>```

Body:
You can add a global variable that tracks the number of incorrect answers. I can't recite all of the reasons global variables are frowned upon, but basically they clutter the global namespace and could lead to conflicts, things like that. I hope this helps though.

<html>

<head>
<title> </title>
</head>

<body>

<p>How much is your profit?

<input id="id1" name = "id1" required>
  <button  type = "button" onclick="myFunction()">Check Your Answer</button> </p>

<p id="Q1"></p>

<script>
var failedAttempts = 0;
function myFunction() {
    var x, text;
    x = document.getElementById("id1").value;

    if (failedAttempts === 3){
         // Show the answer
    }else if(isNaN(x) || x != 100) {
        text = "Incorrect"; document.getElementById("Q1").style.color = "red";
        failedAttempts++;
    } else {
        text = "Correct"; document.getElementById("Q1").style.color = "green";
    }
    document.getElementById("Q1").innerHTML = text;
}
</script>

</body>
</html>


问:
Build Linear Regression with dynamic inputs in R Shiny
I am trying to build a simple shiny app using a linear regression that allows the user to select both the independent and dependent variables that are used in the lm() function and eventually plot out a few charts as well. I am currently stuck on passing the inputs to the lm() function on the server side of shiny and being able to print out the summary of the regression. Can anyone assist me in where my logic/code is going wrong. Below is the code

```<code>library(shiny)
library(data.table)

RegData <- as.data.table(read.table("/home/r2uphp/ShinyApps/IRViews/RegData.tsv", header = TRUE, stringsAsFactors = FALSE))

ui <- fluidPage(
  headerPanel("Regression and Time Series Analysis"),
  sidebarPanel(
    p("Select the inputs for the Dependent Variable"),
    selectInput(inputId = "DepVar", label = "Dependent Variables", multiple = FALSE, choices = list("AvgIR", "YYYYMM", "SumCount", "AvgLTV", "AvgGFEE", "AvgRTC", "Date")),
    p("Select the inputs for the Independent Variable"),
    selectInput(inputId = "IndVar", label = "Independent Variables", multiple = FALSE, choices = list( "SumCount", "AvgIR", "YYYYMM", "AvgLTV", "AvgGFEE", "AvgRTC", "Date"))
  ),
  mainPanel(
    verbatimTextOutput(outputId = "RegSum"),
    verbatimTextOutput(outputId = "IndPrint"),
    verbatimTextOutput(outputId = "DepPrint")
    #plotOutput("hist")
  )
)

server <- function(input, output) {

    lm1 <- reactive({lm(paste0(input$DepVar) ~ paste0(input$IndVar), data = RegData)})

    output$DepPrint <- renderPrint({input$DepVar})
    output$IndPrint <- renderPrint({input$IndVar})
    output$RegSum <- renderPrint({summary(lm1())})

}

shinyApp(ui = ui, server = server)
</code>```

This is the result of the shinyapp

Here is a sample dataset that I am using:

```<code>     YYYYMM      AvgIR SumCount    AvgLTV     AvgGFEE   AvgRTC       Date
 1: 2015-10 0.04106781   180029 0.7531805 0.002424778 319.6837 2015-10-01
 2: 2015-11 0.04036154   160061 0.7380383 0.002722529 312.6314 2015-11-01
 3: 2015-12 0.04001407   145560 0.7392874 0.002425912 313.0351 2015-12-01
 4: 2016-01 0.04034078   147693 0.7396932 0.002600640 315.0238 2016-01-01
 5: 2016-02 0.04055688   142545 0.7345160 0.002449523 310.3950 2016-02-01
</code>```

Thanks in advance!

答:
You just need to build your formula correctly. I'm not sure what you think paste0 does, but here's a better way

```<code>lm1 <- reactive({lm(reformulate(input$IndVar, input$DepVar), data = RegData)})
</code>```

The reformulate() command will build the correct formula for you (note that the independent variables come first in the function.

Body:
I am trying to build a simple shiny app using a linear regression that allows the user to select both the independent and dependent variables that are used in the lm() function and eventually plot out a few charts as well. I am currently stuck on passing the inputs to the lm() function on the server side of shiny and being able to print out the summary of the regression. Can anyone assist me in where my logic/code is going wrong. Below is the code

library(shiny)
library(data.table)

RegData <- as.data.table(read.table("/home/r2uphp/ShinyApps/IRViews/RegData.tsv", header = TRUE, stringsAsFactors = FALSE))

ui <- fluidPage(
  headerPanel("Regression and Time Series Analysis"),
  sidebarPanel(
    p("Select the inputs for the Dependent Variable"),
    selectInput(inputId = "DepVar", label = "Dependent Variables", multiple = FALSE, choices = list("AvgIR", "YYYYMM", "SumCount", "AvgLTV", "AvgGFEE", "AvgRTC", "Date")),
    p("Select the inputs for the Independent Variable"),
    selectInput(inputId = "IndVar", label = "Independent Variables", multiple = FALSE, choices = list( "SumCount", "AvgIR", "YYYYMM", "AvgLTV", "AvgGFEE", "AvgRTC", "Date"))
  ),
  mainPanel(
    verbatimTextOutput(outputId = "RegSum"),
    verbatimTextOutput(outputId = "IndPrint"),
    verbatimTextOutput(outputId = "DepPrint")
    #plotOutput("hist")
  )
)

server <- function(input, output) {

    lm1 <- reactive({lm(paste0(input$DepVar) ~ paste0(input$IndVar), data = RegData)})

    output$DepPrint <- renderPrint({input$DepVar})
    output$IndPrint <- renderPrint({input$IndVar})
    output$RegSum <- renderPrint({summary(lm1())})

}

shinyApp(ui = ui, server = server)

This is the result of the shinyapp

Here is a sample dataset that I am using:

     YYYYMM      AvgIR SumCount    AvgLTV     AvgGFEE   AvgRTC       Date
 1: 2015-10 0.04106781   180029 0.7531805 0.002424778 319.6837 2015-10-01
 2: 2015-11 0.04036154   160061 0.7380383 0.002722529 312.6314 2015-11-01
 3: 2015-12 0.04001407   145560 0.7392874 0.002425912 313.0351 2015-12-01
 4: 2016-01 0.04034078   147693 0.7396932 0.002600640 315.0238 2016-01-01
 5: 2016-02 0.04055688   142545 0.7345160 0.002449523 310.3950 2016-02-01

Thanks in advance!

Body:
You just need to build your formula correctly. I'm not sure what you think paste0 does, but here's a better way

lm1 <- reactive({lm(reformulate(input$IndVar, input$DepVar), data = RegData)})

The reformulate() command will build the correct formula for you (note that the independent variables come first in the function.


问:
Problem with NSRange
I'm having a problem with NSRange. Here is my code:

```<code>NSRange range = [[[NSHTTPCookie requestHeaderFieldsWithCookies:[[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:cookie]]] objectForKey:@"Cookie"] rangeOfString:@"x"];
NSLog(@"%f", range.length);
if (range.length >= 1) {
    NSLog(@"Do Something");
} else {
    NSLog(@"AUTHING");
}
</code>```

Console output:

```<code>0.000000
Do something
</code>```

And then the second time I run through the code:

```<code>0.000000
AUTHING
</code>```

What the hell is going on? NSNotFound I think it was does not work and I'm not the only person finding this problem so using it is not a solution.

Thanks for any help.

Cheers

Edit: I tried using NSLog(@"%d", range.length) but it gives incorrect output the first time it runs through, the second time it runs through it is correct. I've tried using NSNotFound thinking that the strange output is due to it being NSNotFound but it didn't trigger

答:
As a general comment, debugging is much easier if you split up the nested method calls and do a quick NSLog to see what's going on. (i'm not that good at adhering to that so it's not meant as criticism).

One thing i first noted was the use of "%f" to display the length, try using %i (integer) and you should be able to get the correct length. %f will always display 0.00000.

what url are you using? given that you are pulling the data from the headers, the string "x" may or may not be present in the field. i would suggest NSLog-ing the NSString* object that you pull out of the dictionary and checking to see what's going on. E.g.:NSString *cookie = @"http://www.google.com/";

```<code>NSHTTPCookieStorage *store = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSURL *url = [NSURL URLWithString:cookie];
NSDictionary *header = [NSHTTPCookie requestHeaderFieldsWithCookies: [store cookiesForURL:url]];
NSString *cookieParameter = [header objectForKey:@"Cookie"];

NSLog(@"Cookie param is %@", cookieParameter);

// Test range of "x"
NSRange range = [cookieParameter rangeOfString:@"x"];
NSLog(@"%f", range.length); // will print out 0.00000
NSLog(@"%i", range.length); // will print out correct length (always 1 for "x")
NSLog(@"%i", range.location); // will print out the location of the first instance of "x"
if (range.length >= 1) {
    NSLog(@"Do Something");
} else {
    NSLog(@"AUTHING");
}
</code>```

It seems like the code just detects the index of the string "x" from what I can tell, is this the intended result?

Title: Problem with NSRange

Body:
I'm having a problem with NSRange. Here is my code:

NSRange range = [[[NSHTTPCookie requestHeaderFieldsWithCookies:[[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:cookie]]] objectForKey:@"Cookie"] rangeOfString:@"x"];
NSLog(@"%f", range.length);
if (range.length >= 1) {
    NSLog(@"Do Something");
} else {
    NSLog(@"AUTHING");
}

Console output:

0.000000
Do something

And then the second time I run through the code:

0.000000
AUTHING

What the hell is going on? NSNotFound I think it was does not work and I'm not the only person finding this problem so using it is not a solution.

Thanks for any help.

Cheers

Edit: I tried using NSLog(@"%d", range.length) but it gives incorrect output the first time it runs through, the second time it runs through it is correct. I've tried using NSNotFound thinking that the strange output is due to it being NSNotFound but it didn't trigger

Body:
As a general comment, debugging is much easier if you split up the nested method calls and do a quick NSLog to see what's going on. (i'm not that good at adhering to that so it's not meant as criticism).

One thing i first noted was the use of "%f" to display the length, try using %i (integer) and you should be able to get the correct length. %f will always display 0.00000.

what url are you using? given that you are pulling the data from the headers, the string "x" may or may not be present in the field. i would suggest NSLog-ing the NSString* object that you pull out of the dictionary and checking to see what's going on. E.g.:NSString *cookie = @"http://www.google.com/";

NSHTTPCookieStorage *store = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSURL *url = [NSURL URLWithString:cookie];
NSDictionary *header = [NSHTTPCookie requestHeaderFieldsWithCookies: [store cookiesForURL:url]];
NSString *cookieParameter = [header objectForKey:@"Cookie"];

NSLog(@"Cookie param is %@", cookieParameter);

// Test range of "x"
NSRange range = [cookieParameter rangeOfString:@"x"];
NSLog(@"%f", range.length); // will print out 0.00000
NSLog(@"%i", range.length); // will print out correct length (always 1 for "x")
NSLog(@"%i", range.location); // will print out the location of the first instance of "x"
if (range.length >= 1) {
    NSLog(@"Do Something");
} else {
    NSLog(@"AUTHING");
}

It seems like the code just detects the index of the string "x" from what I can tell, is this the intended result?