问:
C# Cannot access child value on Newtonsoft.Json.Linq.JValue
How would i access the "leaguePoints"?

```<code>    using (var http = new HttpClient())
    {
        var result = JObject.Parse(await http.GetStringAsync($"https://euw.api.riotgames.com/api/lol/EUW/v2.5/league/by-summoner/12345678/entry?api_key=" + apikey).ConfigureAwait(false));
        var something = (Uri.EscapeUriString(result["12345678"][0]["tier"]["leaguePoints"].ToString()));
    }
</code>```

I also tried adding an [0] after ["tier"], but in both scenarios it gives me the error

Cannot access child value on Newtonsoft.Json.Linq.JValue.

Json example response below:

```<code>{
    "12345678": [
        {
            "tier": "PLATINUM",
            "queue": "RANKED_SOLO_5x5",
            "name": "Taric's Templars",
            "entries": [
                {
                    "isFreshBlood": false,
                    "division": "III",
                    "isVeteran": false,
                    "wins": 9,
                    "losses": 1,
                    "playerOrTeamId": "12345678",
                    "playerOrTeamName": "noname123",
                    "isInactive": false,
                    "isHotStreak": false,
                    "leaguePoints": 0
                }
            ]
        }
    ]
}
</code>```

答:
"leaguePoints" seems to be in "entries" rather than in "tier":</p>

```<code> result["12345678"][0]["entries"][0]["leaguePoints"]
</code>```

Body:
How would i access the "leaguePoints"?

    using (var http = new HttpClient())
    {
        var result = JObject.Parse(await http.GetStringAsync($"https://euw.api.riotgames.com/api/lol/EUW/v2.5/league/by-summoner/12345678/entry?api_key=" + apikey).ConfigureAwait(false));
        var something = (Uri.EscapeUriString(result["12345678"][0]["tier"]["leaguePoints"].ToString()));
    }

I also tried adding an [0] after ["tier"], but in both scenarios it gives me the error

Cannot access child value on Newtonsoft.Json.Linq.JValue.

Json example response below:

{
    "12345678": [
        {
            "tier": "PLATINUM",
            "queue": "RANKED_SOLO_5x5",
            "name": "Taric's Templars",
            "entries": [
                {
                    "isFreshBlood": false,
                    "division": "III",
                    "isVeteran": false,
                    "wins": 9,
                    "losses": 1,
                    "playerOrTeamId": "12345678",
                    "playerOrTeamName": "noname123",
                    "isInactive": false,
                    "isHotStreak": false,
                    "leaguePoints": 0
                }
            ]
        }
    ]
}

Body:
"leaguePoints" seems to be in "entries" rather than in "tier":

 result["12345678"][0]["entries"][0]["leaguePoints"]


来源: stackexchange

问:
what is the JCR role in the AEM technology stack.?
I can see in AEM technology stack there are multiple frameworks like OSGi, JCR, CRX, Granite. but am unclear about the usage and the involvement of JCR vs CRX. Can anybody explain me whats the role of JCR & CRX in AEM?</p>

答: JCR is the Java Content Repository standard, Apache JackRabbit implements the standard and CRX is a Repository based on JackRabbit.</p>

ContentLicense: CC BY-SA 3.0


问:
NullException on my dynamic slider
I would like to ask how will I be able to handle the NullException every time that I reach the last object in my int[] array.

Here is my InformationTab

```<code>package com.example.aldrinjohn.milktracktest;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

/**
 * Created by Aldrin John on 3/20/2017.
 */

public class InformationTab extends Fragment{
    ViewPager viewPager;
    CustomSwipeAdapter adapter;
    Button btnTrivia,btnBenefitB,btnBenefitM,btnPump,btnStoring,btnInfo;
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.informationtab, container, false);
        viewPager = (ViewPager)rootView.findViewById(R.id.view_pager);

        btnTrivia = (Button)rootView.findViewById(R.id.trivia);
        btnTrivia.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                GlobalVariables.buttonClick = "trivia";
                adapter = new CustomSwipeAdapter(getActivity());
                viewPager.setAdapter(adapter);
            }
        });
        btnBenefitB = (Button)rootView.findViewById(R.id.benefit_babies);
        btnBenefitB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                GlobalVariables.buttonClick = "benefitb";
                adapter = new CustomSwipeAdapter(getActivity());
                viewPager.setAdapter(adapter);
            }
        });
        btnBenefitM = (Button)rootView.findViewById(R.id.benefit_mother);
        btnBenefitM.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                GlobalVariables.buttonClick = "benefitm";
                adapter = new CustomSwipeAdapter(getActivity());
                viewPager.setAdapter(adapter);
            }
        });
        btnPump = (Button)rootView.findViewById(R.id.pump);
        btnPump.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                GlobalVariables.buttonClick = "pump";
                adapter = new CustomSwipeAdapter(getActivity());
                viewPager.setAdapter(adapter);
            }
        });
        btnStoring = (Button)rootView.findViewById(R.id.storing);
        btnStoring.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                GlobalVariables.buttonClick = "storing";
                adapter = new CustomSwipeAdapter(getActivity());
                viewPager.setAdapter(adapter);
            }
        });
        btnInfo = (Button)rootView.findViewById(R.id.tips);
        btnInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                GlobalVariables.buttonClick = "tips";
                adapter = new CustomSwipeAdapter(getActivity());
                viewPager.setAdapter(adapter);
            }
        });

        return rootView;

    }

}
</code>```

and this is my

```<code>package com.example.aldrinjohn.milktracktest;

import android.content.Context;
import android.provider.ContactsContract;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.google.android.gms.ads.formats.NativeAd;
import com.google.android.gms.tagmanager.Container;

/**
 * Created by Aldrin John on 3/26/2017.
 */

public class CustomSwipeAdapter extends PagerAdapter{
    private int[] trivia = {R.drawable.c1,R.drawable.c2,R.drawable.c3,R.drawable.c4, R.drawable.c5,R.drawable.c6};
    private int[] benefitBaby = {R.drawable.c7,R.drawable.c8,R.drawable.c9};
    private int[] benefitMother = {R.drawable.c91,R.drawable.c92};
    private int[] info = {R.drawable.a1,R.drawable.a2,R.drawable.a3,R.drawable.a4,R.drawable.a5,R.drawable.a6,R.drawable.a7,
                            R.drawable.a8,R.drawable.a9,R.drawable.a91,R.drawable.a92};
    private int[] storing = {R.drawable.b1,R.drawable.b2,R.drawable.b3,R.drawable.b4};
    private int[] pump = {R.drawable.a21,R.drawable.a22,R.drawable.a23,R.drawable.a24,R.drawable.a25,R.drawable.a31,R.drawable.a32,
            R.drawable.a33,R.drawable.a34,R.drawable.a35,R.drawable.pic1,R.drawable.pic2,R.drawable.pic3,R.drawable.pic4,R.drawable.pic5};

    private Context ctx;
    private LayoutInflater layoutInflater;

    public CustomSwipeAdapter(Context ctx)
    {
        this.ctx = ctx;
    }

    @Override
    public int getCount() {
        return pump.length;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return (view==(LinearLayout)object);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position){

        layoutInflater = (LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        final View item_view = layoutInflater.inflate(R.layout.swipe_layout,container,false);
        ImageView imgTrivia = (ImageView)item_view.findViewById(R.id.image_view);

        if(GlobalVariables.buttonClick.equals("trivia"))
        {
            imgTrivia.setImageResource(trivia[position]);
        }
        else if (GlobalVariables.buttonClick.equals("benefitb"))
        {
            imgTrivia.setImageResource(benefitBaby[position]);
        }
        else if (GlobalVariables.buttonClick.equals("benefitm"))
        {
            imgTrivia.setImageResource(benefitMother[position]);
        }
        else if (GlobalVariables.buttonClick.equals("storing"))
        {
            imgTrivia.setImageResource(storing[position]);
        }
        else if (GlobalVariables.buttonClick.equals("tips"))
        {
            imgTrivia.setImageResource(info[position]);
        }
        else if (GlobalVariables.buttonClick.equals("pump"))
        {
            imgTrivia.setImageResource(pump[position]);
        }

        container.addView(item_view);

        return item_view;
    }
@Override
    public void destroyItem(ViewGroup container, int position, Object object){
        container.removeView((LinearLayout)object);
    }

}
</code>```

答: SOLVED! I just used a global variable class that contains the number of slides that is clicked. and return it to getCount function. </p>

Title: NullException on my dynamic slider

Body:
I would like to ask how will I be able to handle the NullException every time that I reach the last object in my int[] array.

Here is my InformationTab

package com.example.aldrinjohn.milktracktest;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

/**
 * Created by Aldrin John on 3/20/2017.
 */

public class InformationTab extends Fragment{
    ViewPager viewPager;
    CustomSwipeAdapter adapter;
    Button btnTrivia,btnBenefitB,btnBenefitM,btnPump,btnStoring,btnInfo;
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.informationtab, container, false);
        viewPager = (ViewPager)rootView.findViewById(R.id.view_pager);

        btnTrivia = (Button)rootView.findViewById(R.id.trivia);
        btnTrivia.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                GlobalVariables.buttonClick = "trivia";
                adapter = new CustomSwipeAdapter(getActivity());
                viewPager.setAdapter(adapter);
            }
        });
        btnBenefitB = (Button)rootView.findViewById(R.id.benefit_babies);
        btnBenefitB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                GlobalVariables.buttonClick = "benefitb";
                adapter = new CustomSwipeAdapter(getActivity());
                viewPager.setAdapter(adapter);
            }
        });
        btnBenefitM = (Button)rootView.findViewById(R.id.benefit_mother);
        btnBenefitM.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                GlobalVariables.buttonClick = "benefitm";
                adapter = new CustomSwipeAdapter(getActivity());
                viewPager.setAdapter(adapter);
            }
        });
        btnPump = (Button)rootView.findViewById(R.id.pump);
        btnPump.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                GlobalVariables.buttonClick = "pump";
                adapter = new CustomSwipeAdapter(getActivity());
                viewPager.setAdapter(adapter);
            }
        });
        btnStoring = (Button)rootView.findViewById(R.id.storing);
        btnStoring.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                GlobalVariables.buttonClick = "storing";
                adapter = new CustomSwipeAdapter(getActivity());
                viewPager.setAdapter(adapter);
            }
        });
        btnInfo = (Button)rootView.findViewById(R.id.tips);
        btnInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                GlobalVariables.buttonClick = "tips";
                adapter = new CustomSwipeAdapter(getActivity());
                viewPager.setAdapter(adapter);
            }
        });

        return rootView;

    }

}

and this is my

package com.example.aldrinjohn.milktracktest;

import android.content.Context;
import android.provider.ContactsContract;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.google.android.gms.ads.formats.NativeAd;
import com.google.android.gms.tagmanager.Container;

/**
 * Created by Aldrin John on 3/26/2017.
 */

public class CustomSwipeAdapter extends PagerAdapter{
    private int[] trivia = {R.drawable.c1,R.drawable.c2,R.drawable.c3,R.drawable.c4, R.drawable.c5,R.drawable.c6};
    private int[] benefitBaby = {R.drawable.c7,R.drawable.c8,R.drawable.c9};
    private int[] benefitMother = {R.drawable.c91,R.drawable.c92};
    private int[] info = {R.drawable.a1,R.drawable.a2,R.drawable.a3,R.drawable.a4,R.drawable.a5,R.drawable.a6,R.drawable.a7,
                            R.drawable.a8,R.drawable.a9,R.drawable.a91,R.drawable.a92};
    private int[] storing = {R.drawable.b1,R.drawable.b2,R.drawable.b3,R.drawable.b4};
    private int[] pump = {R.drawable.a21,R.drawable.a22,R.drawable.a23,R.drawable.a24,R.drawable.a25,R.drawable.a31,R.drawable.a32,
            R.drawable.a33,R.drawable.a34,R.drawable.a35,R.drawable.pic1,R.drawable.pic2,R.drawable.pic3,R.drawable.pic4,R.drawable.pic5};

    private Context ctx;
    private LayoutInflater layoutInflater;

    public CustomSwipeAdapter(Context ctx)
    {
        this.ctx = ctx;
    }

    @Override
    public int getCount() {
        return pump.length;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return (view==(LinearLayout)object);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position){

        layoutInflater = (LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        final View item_view = layoutInflater.inflate(R.layout.swipe_layout,container,false);
        ImageView imgTrivia = (ImageView)item_view.findViewById(R.id.image_view);

        if(GlobalVariables.buttonClick.equals("trivia"))
        {
            imgTrivia.setImageResource(trivia[position]);
        }
        else if (GlobalVariables.buttonClick.equals("benefitb"))
        {
            imgTrivia.setImageResource(benefitBaby[position]);
        }
        else if (GlobalVariables.buttonClick.equals("benefitm"))
        {
            imgTrivia.setImageResource(benefitMother[position]);
        }
        else if (GlobalVariables.buttonClick.equals("storing"))
        {
            imgTrivia.setImageResource(storing[position]);
        }
        else if (GlobalVariables.buttonClick.equals("tips"))
        {
            imgTrivia.setImageResource(info[position]);
        }
        else if (GlobalVariables.buttonClick.equals("pump"))
        {
            imgTrivia.setImageResource(pump[position]);
        }

        container.addView(item_view);

        return item_view;
    }
@Override
    public void destroyItem(ViewGroup container, int position, Object object){
        container.removeView((LinearLayout)object);
    }

}


问:
Make div appear next to other
I have started a huge revision on my css knowledge.
I am trying to do the following:
I want to create a wrapper div that contains to divs with some text and some content.I want each div with class item-2 inside that div to have a width:50%
and appear next to another item-2.
Here is a snippet of my code:

body{
  background:rgba(10,10,10,.8);
}
.wrapper{
  position:relative;
  width:100%;
  margin:auto;
}
.item-2{
    text-align:center;
    display:inline-block;
    width:50%;
    border:2px solid blue;
 }
.demo{
  margin:auto;
  height:5em;
  width:5em;
  background:yellow;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='wrapper'>
  <div class='item-2'>
    <h1>Title 1</h1>
    <div class='demo'>
    </div>
  </div>
  <div class='item-2'>
    <h1>Title 1</h1>
    <div class='demo'>
    </div>
  </div>

</div>  </code>```

As you can see it's div appears below its previous div.However I want them to be next to each other.How can I achieve this? I would like an explanation to your solution sa as to improve my knowledge

答:
```<code>.wrapper display: flex;
.item-2 flex: 1;
</code>```

Title: Make div appear next to other

Body:
I have started a huge revision on my css knowledge.
I am trying to do the following:
I want to create a wrapper div that contains to divs with some text and some content.I want each div with class item-2 inside that div to have a width:50%
and appear next to another item-2.
Here is a snippet of my code:

body{
  background:rgba(10,10,10,.8);
}
.wrapper{
  position:relative;
  width:100%;
  margin:auto;
}
.item-2{
    text-align:center;
    display:inline-block;
    width:50%;
    border:2px solid blue;
 }
.demo{
  margin:auto;
  height:5em;
  width:5em;
  background:yellow;
}

Title 1

Title 1

As you can see it's div appears below its previous div.However I want them to be next to each other.How can I achieve this? I would like an explanation to your solution sa as to improve my knowledge


问:
unable to get flot graph to display
I'm trying to create a plot of temperature change over a period of time, so to start off, I'm trying to get a graph up with some test data plotted on it, but none of the data seems to want to show. I'm a bit new to JavaScript and flot, so I tried piecing together the needed code based off of seeing how other people created graphs in flot.

The data for the time on the x-axis, I created in the code just to have something to plot the temperature against, whilst I retrieved the temperature data from a .json file with test data in it. Getting the data points into a set to pass into the plot function seems to be coming together okay, but I just can't get a display. Instead, all I get is what is shown in the image that I will display after my code. Could anyone please let me know what I did wrong or what I'm missing? I'm honestly stumped here.

Source code (made by editing a flot example page):

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 <title>Flot Examples: Resizing</title>
 <link href="../examples.css" rel="stylesheet" type="text/css">
 <link href="../shared/jquery-ui/jquery-ui.min.css" rel="stylesheet" type="text/css">

```

This is what results from the code:
http://imgur.com/a/1lTvj

Any insights as to what I can do to fix this would be much appreciated. Thanks!

答:
As it turns out, the problem was that the plot function was outside of the .getJSON function. As someone whose main programming knowledge is based on C, I assumed that having the plotdata variable outside of the .getJSON function tied it to that scope, but after the end of .getJSON, the plotdata variable showed to have a size of 0, instead of the 10 points of test data that I set into it in the .getJSON function.

To fix this, I just moved the plot function into the .getJSON function, and now it keeps the changes made to plotdata and displays the proper graph.

Title: unable to get flot graph to display

Body:
I'm trying to create a plot of temperature change over a period of time, so to start off, I'm trying to get a graph up with some test data plotted on it, but none of the data seems to want to show. I'm a bit new to JavaScript and flot, so I tried piecing together the needed code based off of seeing how other people created graphs in flot.

The data for the time on the x-axis, I created in the code just to have something to plot the temperature against, whilst I retrieved the temperature data from a .json file with test data in it. Getting the data points into a set to pass into the plot function seems to be coming together okay, but I just can't get a display. Instead, all I get is what is shown in the image that I will display after my code. Could anyone please let me know what I did wrong or what I'm missing? I'm honestly stumped here.

Source code (made by editing a flot example page):

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 <title>Flot Examples: Resizing</title>
 <link href="../examples.css" rel="stylesheet" type="text/css">
 <link href="../shared/jquery-ui/jquery-ui.min.css" rel="stylesheet" type="text/css">

This is what results from the code:
http://imgur.com/a/1lTvj

Any insights as to what I can do to fix this would be much appreciated. Thanks!


问:
library and include paths, ~/lib and ~/include?
What is the canonical path for a custom library and include files? I thought of either /usr/local/lib + /usr/local/include or ~/lib ~/include. To me the latter looks a better option, since the former are managed by the distribution's package manager and it is best not to interfere.. Though I can not find any reference to people actually using ~/lib.

Thanks

答:
Is this something that you've created yourself, or a third party installation?

Normally /usr/local/ is a good place to install packages not part of the original OS. I do this myself for anything I've built and installed from source. Another place to put things is /opt which is often used by commercial third party software.

If you're going to writing something of your own then using your home directory "~" sounds fine. This is also good if you don't have root access or don't want it to mixed in with the other OS packages.

When compiling and linking you will need to configure things to use those directories. Also if you're using dynamic shared libraries the LD_LIBRARY_PATH must be set as well.


问:
Laravel Storage facade not returning good path
I'm trying to upload some files to a specific "disk" in Laravel and then to retrieve the URL from these files.

Here is my config/filesystem.php file:

'disks' => [
    ...
    'thumbnails' => [
        'driver' => 'local',
        'root' => storage_path('app/public/pictures/thumbnails'),
        'visibility' => 'public',
    ],
    ...
],
```

<p>Here is the way I handle an uploaded file (very basic, just for testing purposes):</p>

<pre class="lang-php prettyprint-override"><code>Route::post('upload', function(Request $request) {
    $file = $request->file('file');
    $path = $file->storeAs('/', 'myFile.'.$file->getClientOriginalExtension(), 'thumbnails');
    return dd($path);
});
</code>```

The file /storage/app/public/pictures/thumbnails/myFile.jpg is created, which is fine, but $path equals "myFile.jpg" instead of the full path. First strange thing.

Then if I use:

$url = Storage::disk('thumbnails')->url('myFile.jpg');
```

$url equals "/storage/myFile.jpg" instead of "/storage/app/public/pictures/thumbnails/myFile.jpg".

Am I missing something ?

答:
By default the disk url method just prepends /storage as stated in the docs.

To customize the url add a url to your config:

```<code>'thumbnails' => [
    'driver' => 'local',
    'root' => storage_path('app/public/pictures/thumbnails'),
    'visibility' => 'public',
    'url' => 'the url',
],
</code>```

Body:
I'm trying to upload some files to a specific "disk" in Laravel and then to retrieve the URL from these files.

Here is my config/filesystem.php file:

'disks' => [
    ...
    'thumbnails' => [
        'driver' => 'local',
        'root' => storage_path('app/public/pictures/thumbnails'),
        'visibility' => 'public',
    ],
    ...
],

Here is the way I handle an uploaded file (very basic, just for testing purposes):

Route::post('upload', function(Request $request) {
    $file = $request->file('file');
    $path = $file->storeAs('/', 'myFile.'.$file->getClientOriginalExtension(), 'thumbnails');
    return dd($path);
});

The file /storage/app/public/pictures/thumbnails/myFile.jpg is created, which is fine, but $path equals "myFile.jpg" instead of the full path. First strange thing.

Then if I use:

$url = Storage::disk('thumbnails')->url('myFile.jpg');

$url equals "/storage/myFile.jpg" instead of "/storage/app/public/pictures/thumbnails/myFile.jpg".

Am I missing something ?

Body:
By default the disk url method just prepends /storage as stated in the docs.

To customize the url add a url to your config:

'thumbnails' => [
    'driver' => 'local',
    'root' => storage_path('app/public/pictures/thumbnails'),
    'visibility' => 'public',
    'url' => 'the url',
],


问:
How to display one row at a time ,when i click next display next row in php?
I created a page (exam.php) where I want to show questions one by one.

When a student clicks next after submitting an answer I want it to display the next question.

```<code> <?php
    if(!isset($_SESSION['qno']))
        $_SESSION['qno'] = 1;
    else{

        if(isset($_POST['next']))
        {
                $_SESSION['qno'] += 1;
        }

    }

    $sql ="select  * from question where question_id= ' ".$_SESSION['qno']." '  ";
    $query=mysql_query($sql);
    while($row = mysql_fetch_assoc($query))
    {
        $question =$row['question'];
        $op1 = $row['option1'];
        $op2 = $row['option2'];
        $op3 = $row['option3'];
        $op4 = $row['option4'];

    }

    ?>
</code>```

It works, but in this code I am using question_id to display data. The problem comes after, when admin deletes some questions it is not working due to question_id gap.

I initialize question_id =1; so what is best solution for this problem?

答:
First of all you must transfer the current id from each page to the next one. you did it by $_SESSION["qno"].

Now you must change your query and run this program:

```<code>$sql ="select top 1 * from question where question_id>{$_SESSION['qno']} order by question_id";
$query=mysql_query($sql);
while($row = mysql_fetch_assoc($query))
  {
  $_SESSION['qno']=$row["question_id"];
  $question =$row['question'];
  $op1 = $row['option1'];
  $op2 = $row['option2'];
  $op3 = $row['option3'];
  $op4 = $row['option4'];
  }
</code>```

Body:
I created a page (exam.php) where I want to show questions one by one.

When a student clicks next after submitting an answer I want it to display the next question.

 <?php
    if(!isset($_SESSION['qno']))
        $_SESSION['qno'] = 1;
    else{

        if(isset($_POST['next']))
        {
                $_SESSION['qno'] += 1;
        }

    }

    $sql ="select  * from question where question_id= ' ".$_SESSION['qno']." '  ";
    $query=mysql_query($sql);
    while($row = mysql_fetch_assoc($query))
    {
        $question =$row['question'];
        $op1 = $row['option1'];
        $op2 = $row['option2'];
        $op3 = $row['option3'];
        $op4 = $row['option4'];

    }

    ?>

It works, but in this code I am using question_id to display data. The problem comes after, when admin deletes some questions it is not working due to question_id gap.

I initialize question_id =1; so what is best solution for this problem?

Body:
First of all you must transfer the current id from each page to the next one. you did it by $_SESSION["qno"].

Now you must change your query and run this program:

$sql ="select top 1 * from question where question_id>{$_SESSION['qno']} order by question_id";
$query=mysql_query($sql);
while($row = mysql_fetch_assoc($query))
  {
  $_SESSION['qno']=$row["question_id"];
  $question =$row['question'];
  $op1 = $row['option1'];
  $op2 = $row['option2'];
  $op3 = $row['option3'];
  $op4 = $row['option4'];
  }


问:
DragDrop button text in C# (WinForm)
My goal is to have multiple buttons whose text can be switched on the screen through dragging the text from one button to another (it's not necessary that the buttons themselves be switched, only the text on them, although if it's easier to switch the buttons themselves, that's fine). I have tried to follow this MSDN article but as soon as I actually begin to drag, I get a "no" symbol (an O with a / through it). Am I missing something? (Code below)

Thanks in advance!

```<code>public partial class Form1 : Form
{
    Button button1 = new Button();
    Button button2 = new Button();

    public Form1()
    {
        InitializeComponent();

        button1.Text = "Button 1";
        button2.Text = "Button 2";

        button2.Location = new Point(100, 0);

        this.Controls.Add(button1);
        this.Controls.Add(button2);

        button1.MouseDown += new MouseEventHandler(button_MouseDown);
        button2.MouseDown += new MouseEventHandler(button_MouseDown);

        button1.DragEnter += new DragEventHandler(button_DragEnter);
        button2.DragEnter += new DragEventHandler(button_DragEnter);

        button1.DragDrop += new DragEventHandler(button_DragDrop);
    }

    private void button_MouseDown(object sender, MouseEventArgs e)
    {
        ((Button)sender).DoDragDrop(((Button)sender).Text, DragDropEffects.Move);
    }

    private void button_DragEnter(object sender, DragEventArgs e)
    {
        e.Effect = DragDropEffects.Move;
    }

    private void button_DragDrop(object sender, DragEventArgs e)
    {
        //I'm not sure what goes here, but I can figure that out through experimentation
    }
}
</code>```

答: So it turns out I just had to do some more research. Adding button.AllowDrop = true for both buttons solved the issue

Title: DragDrop button text in C# (WinForm)

Body:
My goal is to have multiple buttons whose text can be switched on the screen through dragging the text from one button to another (it's not necessary that the buttons themselves be switched, only the text on them, although if it's easier to switch the buttons themselves, that's fine). I have tried to follow this MSDN article but as soon as I actually begin to drag, I get a "no" symbol (an O with a / through it). Am I missing something? (Code below)

Thanks in advance!

public partial class Form1 : Form
{
    Button button1 = new Button();
    Button button2 = new Button();

    public Form1()
    {
        InitializeComponent();

        button1.Text = "Button 1";
        button2.Text = "Button 2";

        button2.Location = new Point(100, 0);

        this.Controls.Add(button1);
        this.Controls.Add(button2);

        button1.MouseDown += new MouseEventHandler(button_MouseDown);
        button2.MouseDown += new MouseEventHandler(button_MouseDown);

        button1.DragEnter += new DragEventHandler(button_DragEnter);
        button2.DragEnter += new DragEventHandler(button_DragEnter);

        button1.DragDrop += new DragEventHandler(button_DragDrop);
    }

    private void button_MouseDown(object sender, MouseEventArgs e)
    {
        ((Button)sender).DoDragDrop(((Button)sender).Text, DragDropEffects.Move);
    }

    private void button_DragEnter(object sender, DragEventArgs e)
    {
        e.Effect = DragDropEffects.Move;
    }

    private void button_DragDrop(object sender, DragEventArgs e)
    {
        //I'm not sure what goes here, but I can figure that out through experimentation
    }
}


问:
lwip FreeRTOS tcp window
I am using lwip ontop of FreeRTOS to send data to a server. I am trying to maximize the data flow.
I tune several paramerters in "lwipopts.h" but I am always receiving ACK after emitting two packets.
Thanks for helping

NB: simple echo servers (on linux & windows) gived the same result with high advertised TCP_Window size

答: Did you try the TCP_NODELAY option in your sending socket?</p>

Title: lwip FreeRTOS tcp window


问:
Redirecting stdout from multiple processes to python Logging module
I have a python script that launches a number of user processes using subprocess.Popen. Each process stdout is redirected to a unique file. For example the I launch each process as follows

```<code>proc = my_proc
for p in range(1, max_p, 1):
    log_file = proc + "_" + str(p) + ".log"
    log = open(log_file, "w+")
    subprocess.Popen([my_proc, p], shell = False, stdout = log)
</code>```

I would like to rotate these files when they become too big. What would the best way of doing this? I would like to use the logging module but I dont think this is its intended use

Thanks

ContentLicense: CC BY-SA 2.5

Body:
I have a python script that launches a number of user processes using subprocess.Popen. Each process stdout is redirected to a unique file. For example the I launch each process as follows

proc = my_proc
for p in range(1, max_p, 1):
    log_file = proc + "_" + str(p) + ".log"
    log = open(log_file, "w+")
    subprocess.Popen([my_proc, p], shell = False, stdout = log)

I would like to rotate these files when they become too big. What would the best way of doing this? I would like to use the logging module but I dont think this is its intended use

Thanks

Body: How about logging.handlers.RotatingFileHandler?


问:
Fixing "You have included the Google Maps API multiple times on this page. This may cause unexpected errors."
I've included two below scripts in my header and I get the error "You have included the Google Maps API multiple times on this page. This may cause unexpected errors."

```<code><script type="text/javascript" src="https://maps.googleapis.com/maps/api/js key=************"></script>

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
</code>```

When I remove either script, I get additional js errors. How can I properly refactor these two scripts in my rails app?

Body:
I've included two below scripts in my header and I get the error "You have included the Google Maps API multiple times on this page. This may cause unexpected errors."

When I remove either script, I get additional js errors. How can I properly refactor these two scripts in my rails app?

Body:
I know that in my case it's not a Rails app but might help to someone else ... I'm working with React and I was getting the same error when I was switching between views/pages.

And like wLc said window.google = {} worked like a charm and was deleting the error in the console but the <script> tag was remaining in the html and was added every time I was revisiting the page that has the map.

On componentWillUnmount I've added some code to remove the tag.

const allScripts = document.getElementsByTagName( 'script' );
[].filter.call(
  allScripts,
  ( scpt ) => scpt.src.indexOf( 'key=googleAPIKEY' ) >= 0
 )[ 0 ].remove();

 window.google = {};


问:
Joining two tables using LINQ
I have two tables:

PlanMaster (PlanName, Product_ID)

and

ProductPoints (Entity_ID, Product_ID, Comm1, Comm2)

Now I am storing Entity_ID into a Session which is stored into an 'int':

```<code>int getEntity = Int16.Parse(Session["EntitySelected"].ToString());
</code>```

I want to show in my LINQ query all of the items from above tables which has

Entity_ID = getEntity

Here is my LINQ query:

```<code>var td = from s in cv.Entity_Product_Points join r in dt.PlanMasters on s.Product_ID equals r.Product_ID
         where s.Entity_ID = getEntity
         select s;
</code>```

Now its giving me an error which says:

Cannot implicitly convert type 'int?' to 'bool'

What is going wrong here? Thank you for your comments in advance!

答:
I think this will do,

where s.Entity_ID == getEntity

Title: Joining two tables using LINQ

Body:
I have two tables:

PlanMaster (PlanName, Product_ID)

and

ProductPoints (Entity_ID, Product_ID, Comm1, Comm2)

Now I am storing Entity_ID into a Session which is stored into an 'int':

int getEntity = Int16.Parse(Session["EntitySelected"].ToString());

I want to show in my LINQ query all of the items from above tables which has

Entity_ID = getEntity

Here is my LINQ query:

var td = from s in cv.Entity_Product_Points join r in dt.PlanMasters on s.Product_ID equals r.Product_ID
         where s.Entity_ID = getEntity
         select s;

Now its giving me an error which says:

Cannot implicitly convert type 'int?' to 'bool'

What is going wrong here? Thank you for your comments in advance!


问:
Exception Handling in Morphia (Java)
I wanted to know how to gracefully handle all exceptions that can possibly arise due to db CRUD operations.
In case of any exception, MongoException can be caught and analyzed what went wrong, it may be due to db server/ network/ time out issues . In the most recent version of Morphia, there is a way to catch these exceptions.
   But I needed info about expected exceptions that can arise for each of the below operations i.e best way to know if operation succeeded or failed.

   - get/find

   - merge

   - update

   - delete

   - save.

Can someone suggest the best possible way to handle this? I seem to be lil stuck on this as docs dint help.

Thanks :)

答:
There are a lot of different ways that things can "break" when a client application is communicating with a database. Trying to sort out exactly what the problem is complicated, and how you want to handle these errors will really depend on the nature of your application and how robust your application needs to be.

In simple cases, if you get an error you can just try again. But it's not that easy with every operation. If you insert a document and get an error back, there's no way to tell for sure exactly what went wrong. So a simple solution is to try the insert again with the same key (_id).

There's a great blog post describing this in much better detail: How To Write Resilient MongoDB Applications.

Title: Exception Handling in Morphia (Java)


问:
How can I detect service variable change when updated from another component?
I'm trying to get the updated value from a service variable (isSidebarVisible) which is keeps on updated by another component (header) with a click event (toggleSidebar).

sidebar.service.ts

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';

@Injectable()
export class SidebarService {
    isSidebarVisible: boolean;

    sidebarVisibilityChange: Subject<boolean> = new Subject<boolean>();

    constructor()  {
        this.isSidebarVisible = false;
    }

    toggleSidebarVisibilty() {
        this.isSidebarVisible = !this.isSidebarVisible
        this.sidebarVisibilityChange.next(this.isSidebarVisible);
    }
}
```
<p><strong>sidebar.component.ts</strong></p>
<pre class="lang-js prettyprint-override"><code>export class SidebarComponent implements OnInit {
    asideVisible: boolean;
    _asideSubscription: any;

    constructor(private sidebarService: SidebarService) {
        this.asideVisible = sidebarService.isSidebarVisible
        this._asideSubscription = sidebarService.sidebarVisibilityChange.subscribe((value) => {
            this.asideVisible = value
        })
    }

    ngOnInit() {
    }
}
</code>```

header.component.ts (Where service variable is updated)

export class HeaderComponent implements OnInit {
    isSidebarVisible: boolean;
    _subscription: any;

    constructor(private sidebarService: SidebarService) {
        this._subscription = sidebarService.sidebarVisibilityChange.subscribe((value) => {
            this.isSidebarVisible = value
        })
    }

    toggleSidebar() {
        this.sidebarService.toggleSidebarVisibilty()
    }

    ngOnInit() {

    }
}
```

I can see the service variable value change in header.component.html when {{ isSidebarVisible }} but In sidebar.component.html it always prints the default value and never listened to the changes.

Please help me fix this.

答:
Move subscription to the service, and both components can access this value. If you need value only once, you can use it directly (like I did in sidebar.component); If you need to update something with this value it you can use getter (example in header.component).

sidebar.service.ts:

@Injectable()
export class SidebarService {
    isSidebarVisible: boolean;

    sidebarVisibilityChange: Subject<boolean> = new Subject<boolean>();

    constructor()  {
        this.sidebarVisibilityChange.subscribe((value) => {
            this.isSidebarVisible = value
        });
    }

    toggleSidebarVisibility() {
        this.sidebarVisibilityChange.next(!this.isSidebarVisible);
    }
}
```

<h3>sidebar.component.ts</h3>

<pre class="lang-ts prettyprint-override"><code>export class SidebarComponent {
    asideVisible: boolean;

    constructor(private sidebarService: SidebarService) {
        this.asideVisible = sidebarService.isSidebarVisible;
    }
}
</code>```

header.component.ts

export class HeaderComponent {
    constructor(private sidebarService: SidebarService) { }

    get isSidebarVisible(): boolean {
        return this.sidebarService.isSidebarVisible;
    }

    toggleSidebar() {
        this.sidebarService.toggleSidebarVisibility()
    }
}
```

<p>You can also subscribe to the subject in either/both components and get the value there: </p>

```this.sidebarService.sidebarVisibilityChange.subscribe(value => {...});
```

If you want to know more about Subjects take a look here.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to get the updated value from a service variable (isSidebarVisible) which is keeps on updated by another component (header) with a click event (toggleSidebar).

sidebar.service.ts

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';

@Injectable()
export class SidebarService {
    isSidebarVisible: boolean;

    sidebarVisibilityChange: Subject<boolean> = new Subject<boolean>();

    constructor()  {
        this.isSidebarVisible = false;
    }

    toggleSidebarVisibilty() {
        this.isSidebarVisible = !this.isSidebarVisible
        this.sidebarVisibilityChange.next(this.isSidebarVisible);
    }
}

sidebar.component.ts

export class SidebarComponent implements OnInit {
    asideVisible: boolean;
    _asideSubscription: any;

    constructor(private sidebarService: SidebarService) {
        this.asideVisible = sidebarService.isSidebarVisible
        this._asideSubscription = sidebarService.sidebarVisibilityChange.subscribe((value) => {
            this.asideVisible = value
        })
    }

    ngOnInit() {
    }
}

header.component.ts (Where service variable is updated)

export class HeaderComponent implements OnInit {
    isSidebarVisible: boolean;
    _subscription: any;

    constructor(private sidebarService: SidebarService) {
        this._subscription = sidebarService.sidebarVisibilityChange.subscribe((value) => {
            this.isSidebarVisible = value
        })
    }

    toggleSidebar() {
        this.sidebarService.toggleSidebarVisibilty()
    }

    ngOnInit() {

    }
}

I can see the service variable value change in header.component.html when {{ isSidebarVisible }} but In sidebar.component.html it always prints the default value and never listened to the changes.

Please help me fix this.

Body:
Move subscription to the service, and both components can access this value. If you need value only once, you can use it directly (like I did in sidebar.component); If you need to update something with this value it you can use getter (example in header.component).

sidebar.service.ts:

@Injectable()
export class SidebarService {
    isSidebarVisible: boolean;

    sidebarVisibilityChange: Subject<boolean> = new Subject<boolean>();

    constructor()  {
        this.sidebarVisibilityChange.subscribe((value) => {
            this.isSidebarVisible = value
        });
    }

    toggleSidebarVisibility() {
        this.sidebarVisibilityChange.next(!this.isSidebarVisible);
    }
}

sidebar.component.ts

export class SidebarComponent {
    asideVisible: boolean;

    constructor(private sidebarService: SidebarService) {
        this.asideVisible = sidebarService.isSidebarVisible;
    }
}

header.component.ts

export class HeaderComponent {
    constructor(private sidebarService: SidebarService) { }

    get isSidebarVisible(): boolean {
        return this.sidebarService.isSidebarVisible;
    }

    toggleSidebar() {
        this.sidebarService.toggleSidebarVisibility()
    }
}

You can also subscribe to the subject in either/both components and get the value there:

this.sidebarService.sidebarVisibilityChange.subscribe(value => {...});

If you want to know more about Subjects take a look here.


问:
how can I add mark every two index in String
```<code>def Change(_text):
    L = len(_text)
    _i = 2
    _text[_i] = "*"
    _i += 2
    print(_text)
</code>```

How can I add a mark e.g:* every two Index In String

答:
Why are you using _ in your variables? If it is for any of these reasons then you are OK, if it is a made up syntax, try not to use it as it might cause unnecessary confusion.

As for your code, try:

```<code>def change_text(text):
    for i in range(len(text)):
        if i % 2 == 0: # check if i = even (not odd)
            print(text[:i] + "*" + text[i+1:])
</code>```

When you run change_text("tryout string") the output will look like:

```<code>*ryout string
tr*out string
tryo*t string
tryout*string
tryout s*ring
tryout str*ng
tryout strin*
</code>```

If you meant something else, name a example input and wished for output.

See How to create a Minimal, Complete, and Verifiable example

PS: Please realize that strings are immutable in Python, so you cannot actually change a string, only create new ones from it.. if you want to actually change it you might be better of saving it as a list for example. Like they have done here.

Body:
def Change(_text):
    L = len(_text)
    _i = 2
    _text[_i] = "*"
    _i += 2
    print(_text)

How can I add a mark e.g:* every two Index In String

Body:
Why are you using _ in your variables? If it is for any of these reasons then you are OK, if it is a made up syntax, try not to use it as it might cause unnecessary confusion.

As for your code, try:

def change_text(text):
    for i in range(len(text)):
        if i % 2 == 0: # check if i = even (not odd)
            print(text[:i] + "*" + text[i+1:])

When you run change_text("tryout string") the output will look like:

*ryout string
tr*out string
tryo*t string
tryout*string
tryout s*ring
tryout str*ng
tryout strin*

If you meant something else, name a example input and wished for output.

See How to create a Minimal, Complete, and Verifiable example

PS: Please realize that strings are immutable in Python, so you cannot actually change a string, only create new ones from it.. if you want to actually change it you might be better of saving it as a list for example. Like they have done here.


问:
Can I add a custom attribute to an HTML tag?
Can I add a custom attribute to an HTML tag like the following?</p>

```<code><tag myAttri="myVal" />
</code>```

答:
In HTML5: yes: use the data- attribute.</p>

```<code> <ul>
  <li data-animal-type="bird">Owl</li>
  <li data-animal-type="fish">Salmon</li>
  <li data-animal-type="spider">Tarantula</li>
</ul>
</code>```

Body:
Can I add a custom attribute to an HTML tag like the following?

<tag myAttri="myVal" />

Body:
In HTML5: yes: use the data- attribute.

 <ul>
  <li data-animal-type="bird">Owl</li>
  <li data-animal-type="fish">Salmon</li>
  <li data-animal-type="spider">Tarantula</li>
</ul>


问:
DPL DynamicPageList MediaWiki Errors - Showing HTML Instead of Links
Just did a fresh install of MediaWiki and DynamicPageList (DPL) but something is not quite configured right and I am having a hard time figuring out what is off exactly.

Instead of showing links to the pages, it is showing some oddly formatted HTML code like this:

Bird Dog Daily Checklist

If I view source, it actually looks like this:

Bird Dog Daily Checklist

Any ideas on why it is doing that and how to fix it so that it works right?

答:
This seems to be caused by a change in MediaWiki 1.16. See http://semeb.com/dpldemo/index.php?title=Issue:DPL_incompatible_with_MW_1.16_alpha. </p>

<p>I tried adding $wgRawHtml=true to my LocalSettings.php. It causes the wiki to break (servor error 500). </p>

Body:
This seems to be caused by a change in MediaWiki 1.16. See http://semeb.com/dpldemo/index.php?title=Issue:DPL_incompatible_with_MW_1.16_alpha.

I tried adding $wgRawHtml=true to my LocalSettings.php. It causes the wiki to break (servor error 500).


问:
Presto fails to recognize AWS credentials (both IAM and keys)?
I am trying to set up Presto on an AWS EC2 instance, so that I can run queries on files stored in S3. I know you can/should use EMR, but I am restricted to EC2. I have created a Derby DB for my metastore, set up HDFS on the bucket, and am able to query data files in S3 using Hive. In the Hive CLI, I can run SELECT * FROM testpresto; (testpresto is my table name) and it correctly displays all the contents of my S3 txt file. I connected Presto to the Hive metastore, so my table displays in the presto CLI via SHOW TABLES; and DESCRIBE testpresto;.

However, when I run SELECT * FROM testpresto; the query times out with the below error.

Query 20170109_165917_00007_7pyam failed: Unable to execute HTTP
  request: Connect to ${MY_BUCKET}.s3-us-west-1.amazonaws.com:443
  [${MY_BUCKET}.s3-us-west-1.amazonaws.com/54.231.237.24] failed:
  connect timed out

When I try to instantiate a new schema via Presto CLI, I get a more descriptive error.

Query 20170109_175329_00016_7pyam failed:
  java.lang.IllegalArgumentException: AWS Access Key ID and Secret
  Access Key must be specified as the username or password
  (respectively) of a s3 URL, or by setting the fs.s3.awsAccessKeyId or
  fs.s3.awsSecretAccessKey properties (respectively).

Unfortunately, nothing that I do resolves this error. From what I've read online, it seems that adding a resource reference to my Presto config (catalog/hive.properties) through

```<code>hive.config.resources=/usr/local/hadoop/etc/hadoop/core-site.xml,/usr/local/hadoop/etc/hadoop/hdfs-site.xml
</code>```

or adding the keys directly via hive.s3.aws-access-key and hive.s3.aws-secret-key should enable Presto to read from S3. I've also tried using hive.s3.use-instance-credentials=true (both with and without setting the key configs) to use the IAM role, but it all produces this same error. Is there some other setting that I am missing? I don't understand why Hive is able to query but Presto is not.

答:
I tested Presto with S3 and Hive metastore using s3a:// schema for accessing S3. Since you have Hive talking to S3, the rest should be easy:

you can assign an IAM Role that allows your EC2 instance to talk to S3. In Presto 0.157 this works out-of-the-box since hive.s3.use-instance-credentials config property of the hive connector defaults to true

alternatively you can set the following in the configuration file of the hive connector (usually catalog/hive.properties):

hive.s3.use-instance-credentials = false

hive.s3.aws-access-key = ...

hive.s3.aws-secret-key = ...

Since I understand you tested these options and they didn't work for you, you might still try:

re-try

try with s3a schema, if you haven't already

upgrade if you're well behind latest release, or try exact same version that worked for me (0.157.1-t.1)

make sure there is no network-level configuration blocking S3 access from Presto machine

make sure IAM Roles really grant you S3 access (or use explicit keys as a temporary workaround)

Body:
I am trying to set up Presto on an AWS EC2 instance, so that I can run queries on files stored in S3. I know you can/should use EMR, but I am restricted to EC2. I have created a Derby DB for my metastore, set up HDFS on the bucket, and am able to query data files in S3 using Hive. In the Hive CLI, I can run SELECT * FROM testpresto; (testpresto is my table name) and it correctly displays all the contents of my S3 txt file. I connected Presto to the Hive metastore, so my table displays in the presto CLI via SHOW TABLES; and DESCRIBE testpresto;.

However, when I run SELECT * FROM testpresto; the query times out with the below error.

Query 20170109_165917_00007_7pyam failed: Unable to execute HTTP
  request: Connect to ${MY_BUCKET}.s3-us-west-1.amazonaws.com:443
  [${MY_BUCKET}.s3-us-west-1.amazonaws.com/54.231.237.24] failed:
  connect timed out

When I try to instantiate a new schema via Presto CLI, I get a more descriptive error.

Query 20170109_175329_00016_7pyam failed:
  java.lang.IllegalArgumentException: AWS Access Key ID and Secret
  Access Key must be specified as the username or password
  (respectively) of a s3 URL, or by setting the fs.s3.awsAccessKeyId or
  fs.s3.awsSecretAccessKey properties (respectively).

Unfortunately, nothing that I do resolves this error. From what I've read online, it seems that adding a resource reference to my Presto config (catalog/hive.properties) through

hive.config.resources=/usr/local/hadoop/etc/hadoop/core-site.xml,/usr/local/hadoop/etc/hadoop/hdfs-site.xml

or adding the keys directly via hive.s3.aws-access-key and hive.s3.aws-secret-key should enable Presto to read from S3. I've also tried using hive.s3.use-instance-credentials=true (both with and without setting the key configs) to use the IAM role, but it all produces this same error. Is there some other setting that I am missing? I don't understand why Hive is able to query but Presto is not.


问:
No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Colored
When I try to start my app in Android Studio, it creates 3 errors like these:

Error:(3) Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Borderless.Colored'.

Error:(4) Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Colored'.

Error:Execution failed for task ':app:processDebugResources'.

com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Games\AndroidSDK\build-tools\25.0.2\aapt.exe'' finished with non-zero exit value 1
  Here is an image of what I see when I try to start the App

答: Set your compileSdkVersion to 24 or higher. Right now, it would appear that your compileSdkVersion is below 24, but you are using some resources (e.g., from the Android Support Library) that require a compileSdkVersion of 24 or higher.


问:
Creating a Partial Class for a Form
I would like to create a partial class for my form. I have a lot of events, and it  gets messy, so I would like to break up sections into their own files.

The problem: When I create a partial class of my form, say:

```<code>Partial Public Class Form1

End Class
</code>```

Visual Studio decides I need another form for this partial class.

Questions:

1. How do I create a partial class for a form?

2. If I cant do that, how can I break up all the events in my form into different files?

答:
Not sure what you mean be "Visual Studio decides you need another form", however, are you sure the new Form1 partial class is declared in the corresponding original namespace?

All partial classes for a given .NET type must be declared in the same namespace of course (whatever files they're stored on).

Title: Creating a Partial Class for a Form

Body:
I would like to create a partial class for my form. I have a lot of events, and it  gets messy, so I would like to break up sections into their own files.

The problem: When I create a partial class of my form, say:

Partial Public Class Form1

End Class

Visual Studio decides I need another form for this partial class.

Questions:

1. How do I create a partial class for a form?

2. If I cant do that, how can I break up all the events in my form into different files?


问:
The property is of an interface type ('IFormFile') MVC Core
I'm trying to make a form that i could save a file(image) , but it shows me an error:

InvalidOperationException: The property 'Product.Image' is of an interface type ('IFormFile'). If it is a navigation property manually configure the relationship for this property by casting it to a mapped entity type, otherwise ignore the property from the model.
Apply

I dont know how to fix it , here's the code:

Product.cs

```<code>public class Product
    {
        public Product()
        {
            OrderDetails = new HashSet<OrderDetails>();
        }

        public int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public int? CategoryId { get; set; }
        public decimal? Price { get; set; }
        public int? Quantity { get; set; }
        public string ImagePath { get; set; }

        public virtual ICollection<OrderDetails> OrderDetails { get; set; }
        public virtual Category Category { get; set; }
    }
</code>```

ProductFormViewModel.cs

```<code>public class ProductFormViewModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public int? CategoryId { get; set; }
        public decimal? Price { get; set; }
        public int? Quantity { get; set; }
        public IFormFile Image { get; set; }
    }
</code>```

Create Action

```<code>  [HttpGet]
            public IActionResult Create()
            {
                var categories = _repository.GetCategories().ToList();
                var categoriesModel = categories.Select(p => new
                {
                    p.Id,
                    p.Name
                });

                ViewBag.Categories = new SelectList(categoriesModel, "Id", "Name");

                return View();
            }

[HttpPost]
        public IActionResult Create(ProductFormViewModel product)
        {

            var file = product.Image; // **it returns NULL**
            var upload = Path.Combine(_environment.ContentRootPath, "wwwroot\\uploads", product.Name);

            if (!Directory.Exists(upload))
                Directory.CreateDirectory(upload);

            var filePath = Path.Combine(upload, file.FileName);

            if (file.Length > 0)
            {
                using (var fileStream = new FileStream(filePath, FileMode.Create))
                {
                    file.CopyTo(fileStream);
                }
            }

            var producti = new Product();
            producti.CategoryId = product.CategoryId;
            producti.Description = product.Description;
            producti.Name = product.Name;
            producti.Price = product.Price;
            producti.Quantity = product.Quantity;
            producti.ImagePath = filePath;
            _repository.AddProduct(producti);
            _repository.SaveChanges();

            return RedirectToAction("Index","Products");
        }
</code>```

Create.cshtml

```<code>@model ProductFormViewModel
<br />
<br />
<div class="container">
    <div class="panel panel-default">
        <div class="panel-heading">
        </div>
        <div class="panel-body">
            <form class="form-group" asp-action="Create" asp-controller="Products" method="post">
                <input type="hidden" asp-for="Id"/>
                <div class="col-md-12">
                    <div class="form-group col-md-6">
                        <label asp-for="Name" class="control-label col-md-3"></label>
                        <input asp-for="Name" type="text" class="form-control col-md-3"/>
                    </div>
                    <div class="form-group col-md-6">
                        <label asp-for="CategoryId" class="control-label col-md-3"></label>
                        <select asp-for="CategoryId" asp-items="@ViewBag.Categories" class="form-control col-md-3">
                            <option  hidden disabled selected >Select One</option>
                        </select>
                    </div>
                    <div class="form-group col-md-6">
                        <label asp-for="Description" class="control-label col-md-3"></label>
                        <textarea asp-for="Description" class="form-control" rows="4"></textarea>

                    </div>
                    <div class="form-group col-md-6">

                        <label asp-for="Price" class="control-label col-md-3"></label>
                        <input type="text" asp-for="Price" class="form-control col-md-3"/>
                    </div>
                    <div class="form-group col-md-6">
                        <label asp-for="Quantity" class="control-label col-md-3"></label>
                        <input type="text" asp-for="Quantity" class="form-control col-md-3"/>
                    </div>
                    <div class="form-group col-md-12">
                        <label class="control-label">Select Image</label>
                        <input asp-for="Image" type="file" class="btn-file"/>
                    </div>
                    <div class="form-group col-md-12 text-center">
                        <input type="submit" class="btn btn-success" value="Save"/>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
</code>```

答:
IFormFile is a type used by the ASP.NET Core framework and it does not have a sql server type equivalent.

For your domain model store it as byte[] and when you work with views, is ok for you to use the IFormFile type.

ProductModel:

```<code>public class Product
{
    public Product()
    {
        OrderDetails = new HashSet<OrderDetails>();
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public int? CategoryId { get; set; }
    public decimal? Price { get; set; }
    public int? Quantity { get; set; }
    public string ImagePath { get; set; }

    public virtual ICollection<OrderDetails> OrderDetails { get; set; }
    public virtual Category Category { get; set; }
}
</code>```

ProductViewModel:

```<code>public class ProductViewModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public int? CategoryId { get; set; }
    public decimal? Price { get; set; }
    public int? Quantity { get; set; }
    public IFormFile Image { get; set; }
}
</code>```

Controller method:

```<code>[HttpGet]
public IActionResult Create()
{
    var categories = _repository.GetCategories().ToList();
    var categoriesModel = categories.Select(p => new
    {
        p.Id,
        p.Name
    });

    ViewBag.Categories = new SelectList(categoriesModel, "Id", "Name");

    return View();
}

[HttpPost]
public IActionResult Create(ProductViewModel model)
{
    // Save the image to desired location and retrieve the path
    // string ImagePath = ...

    // Add to db
    _repository.Add(new Product
    {
        Id = model.Id,
        ImagePath = ImagePath,
        // and so on
    });

    return View();
}
</code>```

Also specify to the form enctype="multipart/form-data" in your view.

Body:
I'm trying to make a form that i could save a file(image) , but it shows me an error:

InvalidOperationException: The property 'Product.Image' is of an interface type ('IFormFile'). If it is a navigation property manually configure the relationship for this property by casting it to a mapped entity type, otherwise ignore the property from the model.
Apply

I dont know how to fix it , here's the code:

Product.cs

public class Product
    {
        public Product()
        {
            OrderDetails = new HashSet<OrderDetails>();
        }

        public int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public int? CategoryId { get; set; }
        public decimal? Price { get; set; }
        public int? Quantity { get; set; }
        public string ImagePath { get; set; }

        public virtual ICollection<OrderDetails> OrderDetails { get; set; }
        public virtual Category Category { get; set; }
    }

ProductFormViewModel.cs

public class ProductFormViewModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public int? CategoryId { get; set; }
        public decimal? Price { get; set; }
        public int? Quantity { get; set; }
        public IFormFile Image { get; set; }
    }

Create Action

  [HttpGet]
            public IActionResult Create()
            {
                var categories = _repository.GetCategories().ToList();
                var categoriesModel = categories.Select(p => new
                {
                    p.Id,
                    p.Name
                });

                ViewBag.Categories = new SelectList(categoriesModel, "Id", "Name");

                return View();
            }

[HttpPost]
        public IActionResult Create(ProductFormViewModel product)
        {

            var file = product.Image; // **it returns NULL**
            var upload = Path.Combine(_environment.ContentRootPath, "wwwroot\\uploads", product.Name);

            if (!Directory.Exists(upload))
                Directory.CreateDirectory(upload);

            var filePath = Path.Combine(upload, file.FileName);

            if (file.Length > 0)
            {
                using (var fileStream = new FileStream(filePath, FileMode.Create))
                {
                    file.CopyTo(fileStream);
                }
            }

            var producti = new Product();
            producti.CategoryId = product.CategoryId;
            producti.Description = product.Description;
            producti.Name = product.Name;
            producti.Price = product.Price;
            producti.Quantity = product.Quantity;
            producti.ImagePath = filePath;
            _repository.AddProduct(producti);
            _repository.SaveChanges();

            return RedirectToAction("Index","Products");
        }

Create.cshtml

@model ProductFormViewModel

            <form class="form-group" asp-action="Create" asp-controller="Products" method="post">
                <input type="hidden" asp-for="Id"/>

                        <input asp-for="Name" type="text" class="form-control col-md-3"/>

                        <select asp-for="CategoryId" asp-items="@ViewBag.Categories" class="form-control col-md-3">
                            <option  hidden disabled selected >Select One</option>
                        </select>

                        <textarea asp-for="Description" class="form-control" rows="4"></textarea>

                        <input type="text" asp-for="Price" class="form-control col-md-3"/>

                        <input type="text" asp-for="Quantity" class="form-control col-md-3"/>

                        Select Image
                        <input asp-for="Image" type="file" class="btn-file"/>

                        <input type="submit" class="btn btn-success" value="Save"/>

            </form>

Body:
IFormFile is a type used by the ASP.NET Core framework and it does not have a sql server type equivalent.

For your domain model store it as byte[] and when you work with views, is ok for you to use the IFormFile type.

ProductModel:

public class Product
{
    public Product()
    {
        OrderDetails = new HashSet<OrderDetails>();
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public int? CategoryId { get; set; }
    public decimal? Price { get; set; }
    public int? Quantity { get; set; }
    public string ImagePath { get; set; }

    public virtual ICollection<OrderDetails> OrderDetails { get; set; }
    public virtual Category Category { get; set; }
}

ProductViewModel:

public class ProductViewModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public int? CategoryId { get; set; }
    public decimal? Price { get; set; }
    public int? Quantity { get; set; }
    public IFormFile Image { get; set; }
}

Controller method:

[HttpGet]
public IActionResult Create()
{
    var categories = _repository.GetCategories().ToList();
    var categoriesModel = categories.Select(p => new
    {
        p.Id,
        p.Name
    });

    ViewBag.Categories = new SelectList(categoriesModel, "Id", "Name");

    return View();
}

[HttpPost]
public IActionResult Create(ProductViewModel model)
{
    // Save the image to desired location and retrieve the path
    // string ImagePath = ...

    // Add to db
    _repository.Add(new Product
    {
        Id = model.Id,
        ImagePath = ImagePath,
        // and so on
    });

    return View();
}

Also specify to the form enctype="multipart/form-data" in your view.


问:
Finding probability
I am trying to find out how I would work out the odds for the results in a coin toss simulator. There is a 50% chance of heads and a 50% of tails.
How would I go about working out the odds of the result it returns happening?
Here is my code:</p>

```<code>import random
head = 0
tail = 0
length  = int(input('How many coins do you want to flip? '))
for i in range(length):
    side = random.randint(0, 1)
    if side == 1:
        head = head + 1
    else:
        tail = tail + 1
print('There where ' + str(tail) + ' tails and ' + str(head) + ' heads')
</code>```

答:
To calculate such probability you should use binomial coefficient.  - this gives you all possible combinations of h heads and t tails. Divide it with all possible combinations which are  and you get your probability.

To get the factorial function, the exclamation mark, you can write:

```<code>def fact(n):
    if n == 0:
        return 1
    return n * fact(n-1)
</code>```

This will work for all positive numbers. If you want to speed it up, you can have a dictionary that will allow you to memorise previous calls. That would be:

```<code>_d = {0:1}
def fact(n):
    if n in _d: return _d[n]
    _d[n] = n * fact(n-1)
    return _d[n]
</code>```

Title: Finding probability

Body:
I am trying to find out how I would work out the odds for the results in a coin toss simulator. There is a 50% chance of heads and a 50% of tails.
How would I go about working out the odds of the result it returns happening?
Here is my code:

import random
head = 0
tail = 0
length  = int(input('How many coins do you want to flip? '))
for i in range(length):
    side = random.randint(0, 1)
    if side == 1:
        head = head + 1
    else:
        tail = tail + 1
print('There where ' + str(tail) + ' tails and ' + str(head) + ' heads')

Body:
To calculate such probability you should use binomial coefficient.  - this gives you all possible combinations of h heads and t tails. Divide it with all possible combinations which are  and you get your probability.

To get the factorial function, the exclamation mark, you can write:

def fact(n):
    if n == 0:
        return 1
    return n * fact(n-1)

This will work for all positive numbers. If you want to speed it up, you can have a dictionary that will allow you to memorise previous calls. That would be:

_d = {0:1}
def fact(n):
    if n in _d: return _d[n]
    _d[n] = n * fact(n-1)
    return _d[n]


问:
Why we need to distribute files in Spark at all, e.g. --py-files?
As I read from many blogs and posts here in SO, for example this one (in the first a few paragraphs), quoted as follows:

Not to get into too many details, but when you run different
  transformations on a RDD (map, flatMap, filter and others), your
  transformation code (closure) is:

serialized on the driver node,

shipped to the appropriate nodes in the cluster,

deserialized,

and finally executed on the nodes

OK, here is my take at this:

I define some custom transformation/action functions in the driver, and then those custom functions will be serialized to all the executors to run the job.

Then what's the point of shipping extra py-files to all the nodes? Since all that executors need will be serialized to them, what the heck is going on here?

答: Not sure, but use spark 2.x and DataFrame API to avoid serialization and to ship scala code to your nodes without dealing with extra python container on your nodes. </p>


问:
Installing a puppet module from a manifest script
I'm using puppet to provision a vagrant (ubuntu based) virtual machine.
In my script I need to:

```<code>sudo apt-get build-dep python-lxml
</code>```

I know I can install the apt puppet module so I can use:

```<code>apt::builddep { 'python-lxml': }
</code>```

But I can't find any reference about installing a module from the script and how to include/require it. Seems to me that the puppet docs refer only to installing from the command line puppet tool

I also tried doing something like:

```<code>define build_dep($pkgname){
    exec {
    "builddepend_$pkgname":
    commmand => "sudo apt-get build-dep $pkgname";
    }
}
build_dep{
    "python-imaging":
    pkgname => "python-imaging";

    "python-lxml":
    pkgname => "python-lxml";
}
</code>```

But puppet exited with an error on this. And also:

```<code>exec{"install apt module":

    command => "puppet module install puppetlabs/apt"
}

class { 'apt':
        require => Exec["install apt module"]}
include apt

apt::builddep { 'python-imaging':
 }
</code>```

but got could not find declared class apt at..

any ideas? directions? I know I'm missing something obvious but can't figure this out.

EDIT: If I pre-install (with puppet module install from the commandline) the apt:builddep works fine. But I need puppet to handle the module downloading and installation. Some of the other work arounds also work for the basic use case but won't answer my main question.

答:
Using answers from this question I created this script:

```<code>#!/bin/bash

function install_module {
   IFS=':' read module version <<< "$1"
   if (puppet module list | grep $module ) >/dev/null; then
    echo "Module $module is already installed"
   else
        if [ -z "$version" ]; then
            puppet module install $module
        else
        puppet module install -v $version $module
    fi
    fi
}

if dpkg --compare-versions `puppet --version` "lt" 3.8.7; then
    sudo apt-get remove --purge -y puppet
    sudo apt-get -y autoremove
fi

if which puppet >/dev/null; then
    echo "Puppet is already installed"
else
    echo "Installing puppet"
    wget https://apt.puppetlabs.com/puppetlabs-release-trusty.deb
    sudo dpkg -i puppetlabs-release-trusty.deb
    sudo apt-get update
    sudo apt-get install -y puppet=3.8.7*
    mkdir -p /etc/puppet/modules
fi

for var in "$@"
do
    install_module "$var"
done
</code>```

Then you can use it from your Vagrantfile like this:

```<code>puppet_modules = [
    'puppetlabs-stdlib:4.16.0',
    'puppetlabs-apt:2.3.0',
    'puppet-nodejs:2.3.0'
    ]

config.vm.provision "shell", path: "puppet/scripts/puppet.sh", args: puppet_modules.join(" ")
</code>```

It removes puppet from vm if version is lower than 3.8.7, then installs puppet 3.8.7, and then installs all the modules.

It would probably work only on debian/ubuntu boxes.

Body:
I'm using puppet to provision a vagrant (ubuntu based) virtual machine.
In my script I need to:

sudo apt-get build-dep python-lxml

I know I can install the apt puppet module so I can use:

apt::builddep { 'python-lxml': }

But I can't find any reference about installing a module from the script and how to include/require it. Seems to me that the puppet docs refer only to installing from the command line puppet tool

I also tried doing something like:

define build_dep($pkgname){
    exec {
    "builddepend_$pkgname":
    commmand => "sudo apt-get build-dep $pkgname";
    }
}
build_dep{
    "python-imaging":
    pkgname => "python-imaging";

    "python-lxml":
    pkgname => "python-lxml";
}

But puppet exited with an error on this. And also:

exec{"install apt module":

    command => "puppet module install puppetlabs/apt"
}

class { 'apt':
        require => Exec["install apt module"]}
include apt

apt::builddep { 'python-imaging':
 }

but got could not find declared class apt at..

any ideas? directions? I know I'm missing something obvious but can't figure this out.

EDIT: If I pre-install (with puppet module install from the commandline) the apt:builddep works fine. But I need puppet to handle the module downloading and installation. Some of the other work arounds also work for the basic use case but won't answer my main question.

Body:
Using answers from this question I created this script:

#!/bin/bash

function install_module {
   IFS=':' read module version <<< "$1"
   if (puppet module list | grep $module ) >/dev/null; then
    echo "Module $module is already installed"
   else
        if [ -z "$version" ]; then
            puppet module install $module
        else
        puppet module install -v $version $module
    fi
    fi
}

if dpkg --compare-versions `puppet --version` "lt" 3.8.7; then
    sudo apt-get remove --purge -y puppet
    sudo apt-get -y autoremove
fi

if which puppet >/dev/null; then
    echo "Puppet is already installed"
else
    echo "Installing puppet"
    wget https://apt.puppetlabs.com/puppetlabs-release-trusty.deb
    sudo dpkg -i puppetlabs-release-trusty.deb
    sudo apt-get update
    sudo apt-get install -y puppet=3.8.7*
    mkdir -p /etc/puppet/modules
fi

for var in "$@"
do
    install_module "$var"
done

Then you can use it from your Vagrantfile like this:

puppet_modules = [
    'puppetlabs-stdlib:4.16.0',
    'puppetlabs-apt:2.3.0',
    'puppet-nodejs:2.3.0'
    ]

config.vm.provision "shell", path: "puppet/scripts/puppet.sh", args: puppet_modules.join(" ")

It removes puppet from vm if version is lower than 3.8.7, then installs puppet 3.8.7, and then installs all the modules.

It would probably work only on debian/ubuntu boxes.


问:
App wont run unless you update google play services error on real device
I am using Firebase Auth for my app, in some devices it throws me that error, my firebase dependencies are 9.6.1.

1:Can i do something against this?

2:The onComplete never gets called so i cant know if the user doesnt support this, how could i handle it?

3:Are there a lot of devices with version of google play services lower than that?

Thanks

答: I'd recommend lowering the Google Play Services version you use in your app: unless you specifically need something in a later version of Play Services? It shouldn't cause a problem for your app, but should solve the issue with users needing an update.</p>


问:
Visual C++ variable declarations
In my MainApp.XAML.h file within the namespace brackets, I have:

```<code>int food;
food = 0;
</code>```

When I compile the code I get a couple of errors saying:

```<code>Error C4430 missing type specifier - int assumed
</code>```

and:

```<code>Error C2086 'int MonsterFights::food': redefinition
</code>```

but when I google how to declare a variable, it shows the same way as I am doing.

Am I missing something?

--EDIT--

So if I need to put my variables in my .cpp file, where abouts in the .cpp file do I put them?

Currently I have it here:

```<code>MainPage::MainPage()
{
    InitializeComponent();
}
int food = 5;
</code>```

答:
There are two problems here:

The first is that you have a variable definition in the header file. That means the variable will be defined in every translation unit (roughly a source file with all included header files) where you include the header file.

You can only have one single definition of each variable, and should only have declarations in the header file. Move the definition to a single source file, and have a declaration instead in the header file:

```<code>extern int food;
</code>```

The second problem is that you can't have general statements in the global scope or in namespace scope, only declarations and definitions.

You solve this by changing your definition (the one you have in a source file) to initialize the variable:

```<code>int food = 0;
</code>```

Note that this initialization is not really needed for global variables. The compiler will make sure that otherwise uninitialized global variables are suitable initialized to "zero", which for int variables means they will become 0.

Title: Visual C++ variable declarations

Body:
In my MainApp.XAML.h file within the namespace brackets, I have:

int food;
food = 0;

When I compile the code I get a couple of errors saying:

Error C4430 missing type specifier - int assumed

and:

Error C2086 'int MonsterFights::food': redefinition

but when I google how to declare a variable, it shows the same way as I am doing.

Am I missing something?

--EDIT--

So if I need to put my variables in my .cpp file, where abouts in the .cpp file do I put them?

Currently I have it here:

MainPage::MainPage()
{
    InitializeComponent();
}
int food = 5;

Body:
There are two problems here:

The first is that you have a variable definition in the header file. That means the variable will be defined in every translation unit (roughly a source file with all included header files) where you include the header file.

You can only have one single definition of each variable, and should only have declarations in the header file. Move the definition to a single source file, and have a declaration instead in the header file:

extern int food;

The second problem is that you can't have general statements in the global scope or in namespace scope, only declarations and definitions.

You solve this by changing your definition (the one you have in a source file) to initialize the variable:

int food = 0;

Note that this initialization is not really needed for global variables. The compiler will make sure that otherwise uninitialized global variables are suitable initialized to "zero", which for int variables means they will become 0.


问:
Double Tap inside UIScrollView to Another View
I want to preface this question with the fact I am new to the iphone application development and many times believe I may be over my head. I am trying to find an action that will allow me to double tap anywhere within my full screen UIScrollView to return to my main menu (MainMenuViewController).

I currently have the following code running for my ScrollViewController...

```<code>ScrollViewController.h

#import <UIKit/UIKit.h>

@interface ScrollViewController : UIViewController <UIScrollViewDelegate>
{

}

@end

ScrollViewController.m

#import "ScrollViewController.h"

UIScrollView *myScrollView;
UIPageControl *myPageControl;

@implementation ScrollViewController

- (void)loadScrollViewWithPage:(UIView *)page
{
int pageCount = [[myScrollView subviews] count];

CGRect bounds = myScrollView.bounds;
bounds.origin.x = bounds.size.width * pageCount;
bounds.origin.y = 0;
page.frame = bounds;
[myScrollView addSubview:page];
}

...etc
</code>```

Any advice or sample code to implement a double tap within the ScrollView Controller to allow me to return to my MainMenuViewController would be greatly appreciated. Also please include any Interface Builder changes to the view (if necessary). I have been pouring over the forums for days and have not been able to successfully implement this action. Thanks...R.J.

答:
First of all, create a subclass of a UIScrollView:

```<code>#import <UIKit/UIKit.h>

@interface MyScrollView : UIScrollView {
}

@end
</code>```

Implement it:

```<code>#import "MyScrollView.h"

@implementation MyScrollView

- (void) touchesEnded: (NSSet *) touches withEvent: (UIEvent *) event {

    if (!self.dragging) {
        [self.nextResponder touchesEnded: touches withEvent:event];
    }
    [super touchesEnded: touches withEvent: event];
}

- (void)dealloc {
    [super dealloc];
}

@end
</code>```

Then, use this subclass instead of a normal UIScrollView in your main View Controller. This will call the touchesEnded:withEvent: method (alternatively, you can call any method you want). Then, track for double taps (if you need info on how to do that, let me know).

Body:
I want to preface this question with the fact I am new to the iphone application development and many times believe I may be over my head. I am trying to find an action that will allow me to double tap anywhere within my full screen UIScrollView to return to my main menu (MainMenuViewController).

I currently have the following code running for my ScrollViewController...

ScrollViewController.h

#import <UIKit/UIKit.h>

@interface ScrollViewController : UIViewController <UIScrollViewDelegate>
{

}

@end

ScrollViewController.m

#import "ScrollViewController.h"

UIScrollView *myScrollView;
UIPageControl *myPageControl;

@implementation ScrollViewController

- (void)loadScrollViewWithPage:(UIView *)page
{
int pageCount = [[myScrollView subviews] count];

CGRect bounds = myScrollView.bounds;
bounds.origin.x = bounds.size.width * pageCount;
bounds.origin.y = 0;
page.frame = bounds;
[myScrollView addSubview:page];
}

...etc

Any advice or sample code to implement a double tap within the ScrollView Controller to allow me to return to my MainMenuViewController would be greatly appreciated. Also please include any Interface Builder changes to the view (if necessary). I have been pouring over the forums for days and have not been able to successfully implement this action. Thanks...R.J.

Body:
First of all, create a subclass of a UIScrollView:

#import <UIKit/UIKit.h>

@interface MyScrollView : UIScrollView {
}

@end

Implement it:

#import "MyScrollView.h"

@implementation MyScrollView

- (void) touchesEnded: (NSSet *) touches withEvent: (UIEvent *) event {

    if (!self.dragging) {
        [self.nextResponder touchesEnded: touches withEvent:event];
    }
    [super touchesEnded: touches withEvent: event];
}

- (void)dealloc {
    [super dealloc];
}

@end

Then, use this subclass instead of a normal UIScrollView in your main View Controller. This will call the touchesEnded:withEvent: method (alternatively, you can call any method you want). Then, track for double taps (if you need info on how to do that, let me know).


问:
Maximum sum all prime submatrix
The problem is given in the title. My approach to this problem is like that:

Create a binary matrix B where 1s represents the prime numbers in the input let say V, which is nxn non negative integer matrix

Find all the positive submatrices including 1x1 fom B

Find the sum of them and return the greatest one with the left top corner of the submatrix and the size of it.

In this sense, section 2 of my algorithm seems a little complicated. Is there any way to find them without the brute force, which is I think, iterating via for loops and finding them. I am hoping that matlab has a function returning what I want.

Any help is appreciated.

答:
this is approximately what you planned:</p>

```<code>% generate random matrix
sz = [20 20];
imax = 200;
A = randi(imax,sz);
% binary matrix of primes
B = isprime(A);
% concat both
C = cat(3,A,B);
% compute maximum number of rows&cols in each cc in B
cc = bwconncomp(B,4);
[rows,cols] = cellfun(@(ind)ind2sub(size(B),ind),cc.PixelIdxList,'UniformOutput',false);
maxwidth = max(cellfun(@(c) max(c) - min(c),cols)) + 1;
maxheight = max(cellfun(@(c) max(c) - min(c),rows)) + 1;
% find max-sum sub matrix
valMax = 0;
idxMax = [0,0];
for ii = 1:maxheight
    for jj = 1:maxwidth
        % generate rectangle filter
        h = ones(ii,jj);
        n1 = ii*jj; % number of elements in filter
        % filter the concat matrix
        res = imfilter(C,h);
        % indexes of cc having rectangular shape
        idxs = find(res(:,:,2) == n1);
        if isempty(idxs)
            break
        end
        % find max value of all relevant rectangles
        [v,i] = max(res(idxs));
        if v > valMax
            valMax = v; % max value
            [r,c] = ind2sub(size(B),idxs(i));
            r = r - ceil(ii/2) + 1;
            c = c - ceil(jj/2) + 1;
            idxMax = [c,r,jj,ii]; % max value rect [x,y,w,h]
        end
    end
end
</code>```

Title: Maximum sum all prime submatrix

Body:
this is approximately what you planned:

% generate random matrix
sz = [20 20];
imax = 200;
A = randi(imax,sz);
% binary matrix of primes
B = isprime(A);
% concat both
C = cat(3,A,B);
% compute maximum number of rows&cols in each cc in B
cc = bwconncomp(B,4);
[rows,cols] = cellfun(@(ind)ind2sub(size(B),ind),cc.PixelIdxList,'UniformOutput',false);
maxwidth = max(cellfun(@(c) max(c) - min(c),cols)) + 1;
maxheight = max(cellfun(@(c) max(c) - min(c),rows)) + 1;
% find max-sum sub matrix
valMax = 0;
idxMax = [0,0];
for ii = 1:maxheight
    for jj = 1:maxwidth
        % generate rectangle filter
        h = ones(ii,jj);
        n1 = ii*jj; % number of elements in filter
        % filter the concat matrix
        res = imfilter(C,h);
        % indexes of cc having rectangular shape
        idxs = find(res(:,:,2) == n1);
        if isempty(idxs)
            break
        end
        % find max value of all relevant rectangles
        [v,i] = max(res(idxs));
        if v > valMax
            valMax = v; % max value
            [r,c] = ind2sub(size(B),idxs(i));
            r = r - ceil(ii/2) + 1;
            c = c - ceil(jj/2) + 1;
            idxMax = [c,r,jj,ii]; % max value rect [x,y,w,h]
        end
    end
end